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: 315201 $")
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 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
02343
02344
02345 static void try_suggested_sip_codec(struct sip_pvt *p);
02346 static const char *get_sdp_iterate(int* start, struct sip_request *req, const char *name);
02347 static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value);
02348 static int find_sdp(struct sip_request *req);
02349 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action);
02350 static int process_sdp_o(const char *o, struct sip_pvt *p);
02351 static int process_sdp_c(const char *c, struct ast_hostent *hp);
02352 static int process_sdp_a_sendonly(const char *a, int *sendonly);
02353 static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp *newaudiortp, int *last_rtpmap_codec);
02354 static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp *newvideortp, int *last_rtpmap_codec);
02355 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);
02356 static int process_sdp_a_image(const char *a, struct sip_pvt *p);
02357 static void add_codec_to_sdp(const struct sip_pvt *p, int codec,
02358 struct ast_str **m_buf, struct ast_str **a_buf,
02359 int debug, int *min_packet_size);
02360 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
02361 struct ast_str **m_buf, struct ast_str **a_buf,
02362 int debug);
02363 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38);
02364 static void do_setnat(struct sip_pvt *p, int natflags);
02365 static void stop_media_flows(struct sip_pvt *p);
02366
02367
02368 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
02369 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
02370 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
02371 const char *secret, const char *md5secret, int sipmethod,
02372 char *uri, enum xmittype reliable, int ignore);
02373 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
02374 int sipmethod, char *uri, enum xmittype reliable,
02375 struct sockaddr_in *sin, struct sip_peer **authpeer);
02376 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin);
02377
02378
02379 static int check_sip_domain(const char *domain, char *context, size_t len);
02380 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
02381 static void clear_sip_domains(void);
02382
02383
02384 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, const char *configuration, int lineno);
02385 static int clear_realm_authentication(struct sip_auth *authlist);
02386 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm);
02387
02388
02389 static void check_rtp_timeout(struct sip_pvt *dialog, time_t t);
02390 static int sip_do_reload(enum channelreloadreason reason);
02391 static int reload_config(enum channelreloadreason reason);
02392 static int expire_register(const void *data);
02393 static void *do_monitor(void *data);
02394 static int restart_monitor(void);
02395 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer);
02396 static struct ast_variable *copy_vars(struct ast_variable *src);
02397
02398 static int sip_refer_allocate(struct sip_pvt *p);
02399 static void ast_quiet_chan(struct ast_channel *chan);
02400 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
02401 static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context);
02402
02403
02404
02405
02406
02407
02408
02409
02410 #define check_request_transport(peer, tmpl) ({ \
02411 int ret = 0; \
02412 if (peer->socket.type == tmpl->socket.type) \
02413 ; \
02414 else if (!(peer->transports & tmpl->socket.type)) {\
02415 ast_log(LOG_ERROR, \
02416 "'%s' is not a valid transport for '%s'. we only use '%s'! ending call.\n", \
02417 get_transport(tmpl->socket.type), peer->name, get_transport_list(peer->transports) \
02418 ); \
02419 ret = 1; \
02420 } else if (peer->socket.type & SIP_TRANSPORT_TLS) { \
02421 ast_log(LOG_WARNING, \
02422 "peer '%s' HAS NOT USED (OR SWITCHED TO) TLS in favor of '%s' (but this was allowed in sip.conf)!\n", \
02423 peer->name, get_transport(tmpl->socket.type) \
02424 ); \
02425 } else { \
02426 ast_debug(1, \
02427 "peer '%s' has contacted us over %s even though we prefer %s.\n", \
02428 peer->name, get_transport(tmpl->socket.type), get_transport(peer->socket.type) \
02429 ); \
02430 }\
02431 (ret); \
02432 })
02433
02434
02435
02436 static int cb_extensionstate(char *context, char* exten, int state, void *data);
02437 static int sip_devicestate(void *data);
02438 static int sip_poke_noanswer(const void *data);
02439 static int sip_poke_peer(struct sip_peer *peer, int force);
02440 static void sip_poke_all_peers(void);
02441 static void sip_peer_hold(struct sip_pvt *p, int hold);
02442 static void mwi_event_cb(const struct ast_event *, void *);
02443
02444
02445 static const char *sip_nat_mode(const struct sip_pvt *p);
02446 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02447 static char *transfermode2str(enum transfermodes mode) attribute_const;
02448 static const char *nat2str(int nat) attribute_const;
02449 static int peer_status(struct sip_peer *peer, char *status, int statuslen);
02450 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02451 static char * _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
02452 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02453 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02454 static void print_group(int fd, ast_group_t group, int crlf);
02455 static const char *dtmfmode2str(int mode) attribute_const;
02456 static int str2dtmfmode(const char *str) attribute_unused;
02457 static const char *insecure2str(int mode) attribute_const;
02458 static void cleanup_stale_contexts(char *new, char *old);
02459 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
02460 static const char *domain_mode_to_text(const enum domain_mode mode);
02461 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02462 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
02463 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02464 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
02465 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02466 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02467 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02468 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02469 static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02470 static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
02471 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
02472 static char *complete_sip_peer(const char *word, int state, int flags2);
02473 static char *complete_sip_registered_peer(const char *word, int state, int flags2);
02474 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state);
02475 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
02476 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state);
02477 static char *complete_sipnotify(const char *line, const char *word, int pos, int state);
02478 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02479 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02480 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02481 static char *sip_do_debug_ip(int fd, char *arg);
02482 static char *sip_do_debug_peer(int fd, char *arg);
02483 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02484 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02485 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02486 static int sip_dtmfmode(struct ast_channel *chan, void *data);
02487 static int sip_addheader(struct ast_channel *chan, void *data);
02488 static int sip_do_reload(enum channelreloadreason reason);
02489 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02490 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
02491
02492
02493
02494
02495
02496 static void sip_dump_history(struct sip_pvt *dialog);
02497 static inline int sip_debug_test_addr(const struct sockaddr_in *addr);
02498 static inline int sip_debug_test_pvt(struct sip_pvt *p);
02499
02500
02501
02502
02503 #define append_history(p, event, fmt , args... ) append_history_full(p, "%-15s " fmt, event, ## args)
02504 static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
02505 static void sip_dump_history(struct sip_pvt *dialog);
02506
02507
02508 static struct sip_peer *temp_peer(const char *name);
02509 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only);
02510 static int update_call_counter(struct sip_pvt *fup, int event);
02511 static void sip_destroy_peer(struct sip_peer *peer);
02512 static void sip_destroy_peer_fn(void *peer);
02513 static void set_peer_defaults(struct sip_peer *peer);
02514 static struct sip_peer *temp_peer(const char *name);
02515 static void register_peer_exten(struct sip_peer *peer, int onoff);
02516 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime, int forcenamematch, int devstate_only, int transport);
02517 static int sip_poke_peer_s(const void *data);
02518 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
02519 static void reg_source_db(struct sip_peer *peer);
02520 static void destroy_association(struct sip_peer *peer);
02521 static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
02522 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
02523 static void set_socket_transport(struct sip_socket *socket, int transport);
02524
02525
02526 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);
02527 static void update_peer(struct sip_peer *p, int expire);
02528 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config);
02529 static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername);
02530 static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin, int devstate_only);
02531 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02532
02533
02534 static void ast_sip_ouraddrfor(struct in_addr *them, struct sockaddr_in *us, struct sip_pvt *p);
02535 static void sip_registry_destroy(struct sip_registry *reg);
02536 static int sip_register(const char *value, int lineno);
02537 static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
02538 static int sip_reregister(const void *data);
02539 static int __sip_do_register(struct sip_registry *r);
02540 static int sip_reg_timeout(const void *data);
02541 static void sip_send_all_registers(void);
02542 static int sip_reinvite_retry(const void *data);
02543
02544
02545 static void append_date(struct sip_request *req);
02546 static int determine_firstline_parts(struct sip_request *req);
02547 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
02548 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
02549 static int find_sip_method(const char *msg);
02550 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported);
02551 static int parse_request(struct sip_request *req);
02552 static const char *get_header(const struct sip_request *req, const char *name);
02553 static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
02554 static int method_match(enum sipmethod id, const char *name);
02555 static void parse_copy(struct sip_request *dst, const struct sip_request *src);
02556 static char *get_in_brackets(char *tmp);
02557 static const char *find_alias(const char *name, const char *_default);
02558 static const char *__get_header(const struct sip_request *req, const char *name, int *start);
02559 static int lws2sws(char *msgbuf, int len);
02560 static void extract_uri(struct sip_pvt *p, struct sip_request *req);
02561 static char *remove_uri_parameters(char *uri);
02562 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
02563 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
02564 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
02565 static int set_address_from_contact(struct sip_pvt *pvt);
02566 static void check_via(struct sip_pvt *p, struct sip_request *req);
02567 static char *get_calleridname(const char *input, char *output, size_t outputsize);
02568 static int get_rpid_num(const char *input, char *output, int maxlen);
02569 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq);
02570 static int get_destination(struct sip_pvt *p, struct sip_request *oreq);
02571 static int get_msg_text(char *buf, int len, struct sip_request *req, int addnewline);
02572 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout);
02573 static struct sip_via *parse_via(const char *header);
02574 static void free_via(struct sip_via *v);
02575
02576
02577 static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session);
02578 static void *sip_tcp_worker_fn(void *);
02579
02580
02581 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
02582 static int init_req(struct sip_request *req, int sipmethod, const char *recip);
02583 static void deinit_req(struct sip_request *req);
02584 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch);
02585 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod);
02586 static int init_resp(struct sip_request *resp, const char *msg);
02587 static inline int resp_needs_contact(const char *msg, enum sipmethod method);
02588 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
02589 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p);
02590 static void build_via(struct sip_pvt *p);
02591 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
02592 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct sockaddr_in *sin, int newdialog);
02593 static char *generate_random_string(char *buf, size_t size);
02594 static void build_callid_pvt(struct sip_pvt *pvt);
02595 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain);
02596 static void make_our_tag(char *tagbuf, size_t len);
02597 static int add_header(struct sip_request *req, const char *var, const char *value);
02598 static int add_content(struct sip_request *req, const char *line);
02599 static int finalize_content(struct sip_request *req);
02600 static int add_text(struct sip_request *req, const char *text);
02601 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode);
02602 static int add_vidupdate(struct sip_request *req);
02603 static void add_route(struct sip_request *req, struct sip_route *route);
02604 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
02605 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
02606 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
02607 static void set_destination(struct sip_pvt *p, char *uri);
02608 static void append_date(struct sip_request *req);
02609 static void build_contact(struct sip_pvt *p);
02610 static void build_rpid(struct sip_pvt *p);
02611
02612
02613 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock);
02614 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);
02615 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock);
02616 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
02617 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e);
02618 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
02619 static int handle_request_message(struct sip_pvt *p, struct sip_request *req);
02620 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
02621 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
02622 static int handle_request_options(struct sip_pvt *p, struct sip_request *req);
02623 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin, int *nounlock);
02624 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
02625 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno);
02626
02627
02628 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02629 static void handle_response_notify(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02630 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02631 static void handle_response_subscribe(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02632 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02633 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02634
02635
02636 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);
02637 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
02638 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
02639 static enum ast_rtp_get_result sip_get_trtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
02640 static int sip_get_codec(struct ast_channel *chan);
02641 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect);
02642
02643
02644 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
02645 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
02646 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
02647 static void change_t38_state(struct sip_pvt *p, int state);
02648
02649
02650 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp);
02651 static int proc_session_timer(const void *vp);
02652 static void stop_session_timer(struct sip_pvt *p);
02653 static void start_session_timer(struct sip_pvt *p);
02654 static void restart_session_timer(struct sip_pvt *p);
02655 static const char *strefresher2str(enum st_refresher r);
02656 static int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref);
02657 static int parse_minse(const char *p_hdrval, int *const p_interval);
02658 static int st_get_se(struct sip_pvt *, int max);
02659 static enum st_refresher st_get_refresher(struct sip_pvt *);
02660 static enum st_mode st_get_mode(struct sip_pvt *);
02661 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p);
02662
02663
02664 static int sip_subscribe_mwi(const char *value, int lineno);
02665 static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi);
02666 static void sip_send_all_mwi_subscriptions(void);
02667 static int sip_subscribe_mwi_do(const void *data);
02668 static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi);
02669
02670
02671 static const struct ast_channel_tech sip_tech = {
02672 .type = "SIP",
02673 .description = "Session Initiation Protocol (SIP)",
02674 .capabilities = AST_FORMAT_AUDIO_MASK,
02675 .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
02676 .requester = sip_request_call,
02677 .devicestate = sip_devicestate,
02678 .call = sip_call,
02679 .send_html = sip_sendhtml,
02680 .hangup = sip_hangup,
02681 .answer = sip_answer,
02682 .read = sip_read,
02683 .write = sip_write,
02684 .write_video = sip_write,
02685 .write_text = sip_write,
02686 .indicate = sip_indicate,
02687 .transfer = sip_transfer,
02688 .fixup = sip_fixup,
02689 .send_digit_begin = sip_senddigit_begin,
02690 .send_digit_end = sip_senddigit_end,
02691 .bridge = ast_rtp_bridge,
02692 .early_bridge = ast_rtp_early_bridge,
02693 .send_text = sip_sendtext,
02694 .func_channel_read = acf_channel_read,
02695 .queryoption = sip_queryoption,
02696 .get_pvt_uniqueid = sip_get_callid,
02697 };
02698
02699
02700
02701
02702
02703
02704
02705 static struct ast_channel_tech sip_tech_info;
02706
02707
02708
02709 static struct ast_tls_config sip_tls_cfg;
02710
02711
02712 static struct ast_tls_config default_tls_cfg;
02713
02714
02715 static struct ast_tcptls_session_args sip_tcp_desc = {
02716 .accept_fd = -1,
02717 .master = AST_PTHREADT_NULL,
02718 .tls_cfg = NULL,
02719 .poll_timeout = -1,
02720 .name = "SIP TCP server",
02721 .accept_fn = ast_tcptls_server_root,
02722 .worker_fn = sip_tcp_worker_fn,
02723 };
02724
02725
02726 static struct ast_tcptls_session_args sip_tls_desc = {
02727 .accept_fd = -1,
02728 .master = AST_PTHREADT_NULL,
02729 .tls_cfg = &sip_tls_cfg,
02730 .poll_timeout = -1,
02731 .name = "SIP TLS server",
02732 .accept_fn = ast_tcptls_server_root,
02733 .worker_fn = sip_tcp_worker_fn,
02734 };
02735
02736
02737 #define IS_SIP_TECH(t) ((t) == &sip_tech || (t) == &sip_tech_info)
02738
02739
02740
02741
02742 static const char *map_x_s(const struct _map_x_s *table, int x, const char *errorstring)
02743 {
02744 const struct _map_x_s *cur;
02745
02746 for (cur = table; cur->s; cur++)
02747 if (cur->x == x)
02748 return cur->s;
02749 return errorstring;
02750 }
02751
02752
02753
02754
02755 static int map_s_x(const struct _map_x_s *table, const char *s, int errorvalue)
02756 {
02757 const struct _map_x_s *cur;
02758
02759 for (cur = table; cur->s; cur++)
02760 if (!strcasecmp(cur->s, s))
02761 return cur->x;
02762 return errorvalue;
02763 }
02764
02765
02766
02767 static struct ast_rtp_protocol sip_rtp = {
02768 .type = "SIP",
02769 .get_rtp_info = sip_get_rtp_peer,
02770 .get_vrtp_info = sip_get_vrtp_peer,
02771 .get_trtp_info = sip_get_trtp_peer,
02772 .set_rtp_peer = sip_set_rtp_peer,
02773 .get_codec = sip_get_codec,
02774 };
02775
02776
02777
02778
02779 static struct ast_variable *copy_vars(struct ast_variable *src)
02780 {
02781 struct ast_variable *res = NULL, *tmp, *v = NULL;
02782
02783 for (v = src ; v ; v = v->next) {
02784 if ((tmp = ast_variable_new(v->name, v->value, v->file))) {
02785 tmp->next = res;
02786 res = tmp;
02787 }
02788 }
02789 return res;
02790 }
02791
02792 static void tcptls_packet_destructor(void *obj)
02793 {
02794 struct tcptls_packet *packet = obj;
02795
02796 ast_free(packet->data);
02797 }
02798
02799 static void sip_tcptls_client_args_destructor(void *obj)
02800 {
02801 struct ast_tcptls_session_args *args = obj;
02802 if (args->tls_cfg) {
02803 ast_free(args->tls_cfg->certfile);
02804 ast_free(args->tls_cfg->cipher);
02805 ast_free(args->tls_cfg->cafile);
02806 ast_free(args->tls_cfg->capath);
02807 }
02808 ast_free(args->tls_cfg);
02809 ast_free((char *) args->name);
02810 }
02811
02812 static void sip_threadinfo_destructor(void *obj)
02813 {
02814 struct sip_threadinfo *th = obj;
02815 struct tcptls_packet *packet;
02816 if (th->alert_pipe[1] > -1) {
02817 close(th->alert_pipe[0]);
02818 }
02819 if (th->alert_pipe[1] > -1) {
02820 close(th->alert_pipe[1]);
02821 }
02822 th->alert_pipe[0] = th->alert_pipe[1] = -1;
02823
02824 while ((packet = AST_LIST_REMOVE_HEAD(&th->packet_q, entry))) {
02825 ao2_t_ref(packet, -1, "thread destruction, removing packet from frame queue");
02826 }
02827
02828 if (th->tcptls_session) {
02829 ao2_t_ref(th->tcptls_session, -1, "remove tcptls_session for sip_threadinfo object");
02830 }
02831 }
02832
02833
02834 static struct sip_threadinfo *sip_threadinfo_create(struct ast_tcptls_session_instance *tcptls_session, int transport)
02835 {
02836 struct sip_threadinfo *th;
02837
02838 if (!tcptls_session || !(th = ao2_alloc(sizeof(*th), sip_threadinfo_destructor))) {
02839 return NULL;
02840 }
02841
02842 th->alert_pipe[0] = th->alert_pipe[1] = -1;
02843
02844 if (pipe(th->alert_pipe) == -1) {
02845 ao2_t_ref(th, -1, "Failed to open alert pipe on sip_threadinfo");
02846 ast_log(LOG_ERROR, "Could not create sip alert pipe in tcptls thread, error %s\n", strerror(errno));
02847 return NULL;
02848 }
02849 ao2_t_ref(tcptls_session, +1, "tcptls_session ref for sip_threadinfo object");
02850 th->tcptls_session = tcptls_session;
02851 th->type = transport ? transport : (tcptls_session->ssl ? SIP_TRANSPORT_TLS: SIP_TRANSPORT_TCP);
02852 ao2_t_link(threadt, th, "Adding new tcptls helper thread");
02853 ao2_t_ref(th, -1, "Decrementing threadinfo ref from alloc, only table ref remains");
02854 return th;
02855 }
02856
02857
02858 static int sip_tcptls_write(struct ast_tcptls_session_instance *tcptls_session, const void *buf, size_t len)
02859 {
02860 int res = len;
02861 struct sip_threadinfo *th = NULL;
02862 struct tcptls_packet *packet = NULL;
02863 struct sip_threadinfo tmp = {
02864 .tcptls_session = tcptls_session,
02865 };
02866 enum sip_tcptls_alert alert = TCPTLS_ALERT_DATA;
02867
02868 if (!tcptls_session) {
02869 return XMIT_ERROR;
02870 }
02871
02872 ast_mutex_lock(&tcptls_session->lock);
02873
02874 if ((tcptls_session->fd == -1) ||
02875 !(th = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread")) ||
02876 !(packet = ao2_alloc(sizeof(*packet), tcptls_packet_destructor)) ||
02877 !(packet->data = ast_str_create(len))) {
02878 goto tcptls_write_setup_error;
02879 }
02880
02881
02882 ast_str_set(&packet->data, 0, "%s", (char *) buf);
02883 packet->len = len;
02884
02885
02886
02887
02888 ao2_lock(th);
02889 if (write(th->alert_pipe[1], &alert, sizeof(alert)) == -1) {
02890 ast_log(LOG_ERROR, "write() to alert pipe failed: %s\n", strerror(errno));
02891 ao2_t_ref(packet, -1, "could not write to alert pipe, remove packet");
02892 packet = NULL;
02893 res = XMIT_ERROR;
02894 } else {
02895 AST_LIST_INSERT_TAIL(&th->packet_q, packet, entry);
02896 }
02897 ao2_unlock(th);
02898
02899 ast_mutex_unlock(&tcptls_session->lock);
02900 ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo object after finding it");
02901 return res;
02902
02903 tcptls_write_setup_error:
02904 if (th) {
02905 ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo obj, could not create packet");
02906 }
02907 if (packet) {
02908 ao2_t_ref(packet, -1, "could not allocate packet's data");
02909 }
02910 ast_mutex_unlock(&tcptls_session->lock);
02911
02912 return XMIT_ERROR;
02913 }
02914
02915
02916 static void *sip_tcp_worker_fn(void *data)
02917 {
02918 struct ast_tcptls_session_instance *tcptls_session = data;
02919
02920 return _sip_tcp_helper_thread(NULL, tcptls_session);
02921 }
02922
02923
02924
02925
02926
02927
02928
02929
02930 static int sip_check_authtimeout(time_t start)
02931 {
02932 int timeout;
02933 time_t now;
02934 if(time(&now) == -1) {
02935 ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
02936 return -1;
02937 }
02938
02939 timeout = (authtimeout - (now - start)) * 1000;
02940 if (timeout < 0) {
02941
02942 return 0;
02943 }
02944
02945 return timeout;
02946 }
02947
02948
02949
02950
02951 static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session)
02952 {
02953 int res, cl, timeout = -1, authenticated = 0, flags;
02954 time_t start;
02955 struct sip_request req = { 0, } , reqcpy = { 0, };
02956 struct sip_threadinfo *me = NULL;
02957 char buf[1024] = "";
02958 struct pollfd fds[2] = { { 0 }, { 0 }, };
02959 struct ast_tcptls_session_args *ca = NULL;
02960
02961
02962
02963
02964
02965
02966
02967
02968
02969
02970
02971
02972 if (!tcptls_session->client) {
02973 if (ast_atomic_fetchadd_int(&unauth_sessions, +1) >= authlimit) {
02974
02975 goto cleanup;
02976 }
02977
02978 if ((flags = fcntl(tcptls_session->fd, F_GETFL)) == -1) {
02979 ast_log(LOG_ERROR, "error setting socket to non blocking mode, fcntl() failed: %s\n", strerror(errno));
02980 goto cleanup;
02981 }
02982
02983 flags |= O_NONBLOCK;
02984 if (fcntl(tcptls_session->fd, F_SETFL, flags) == -1) {
02985 ast_log(LOG_ERROR, "error setting socket to non blocking mode, fcntl() failed: %s\n", strerror(errno));
02986 goto cleanup;
02987 }
02988
02989 if (!(me = sip_threadinfo_create(tcptls_session, tcptls_session->ssl ? SIP_TRANSPORT_TLS : SIP_TRANSPORT_TCP))) {
02990 goto cleanup;
02991 }
02992 ao2_t_ref(me, +1, "Adding threadinfo ref for tcp_helper_thread");
02993 } else {
02994 struct sip_threadinfo tmp = {
02995 .tcptls_session = tcptls_session,
02996 };
02997
02998 if ((!(ca = tcptls_session->parent)) ||
02999 (!(me = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread"))) ||
03000 (!(tcptls_session = ast_tcptls_client_start(tcptls_session)))) {
03001 goto cleanup;
03002 }
03003 }
03004
03005 me->threadid = pthread_self();
03006 ast_debug(2, "Starting thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");
03007
03008
03009 fds[0].fd = tcptls_session->fd;
03010 fds[1].fd = me->alert_pipe[0];
03011 fds[0].events = fds[1].events = POLLIN | POLLPRI;
03012
03013 if (!(req.data = ast_str_create(SIP_MIN_PACKET)))
03014 goto cleanup;
03015 if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET)))
03016 goto cleanup;
03017
03018 if(time(&start) == -1) {
03019 ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
03020 goto cleanup;
03021 }
03022
03023 for (;;) {
03024 struct ast_str *str_save;
03025
03026 if (!tcptls_session->client && req.authenticated && !authenticated) {
03027 authenticated = 1;
03028 ast_atomic_fetchadd_int(&unauth_sessions, -1);
03029 }
03030
03031
03032 if (!tcptls_session->client && !authenticated ) {
03033 if ((timeout = sip_check_authtimeout(start)) < 0) {
03034 goto cleanup;
03035 }
03036
03037 if (timeout == 0) {
03038 ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
03039 goto cleanup;
03040 }
03041 } else {
03042 timeout = -1;
03043 }
03044
03045 res = ast_poll(fds, 2, timeout);
03046 if (res < 0) {
03047 ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", tcptls_session->ssl ? "SSL": "TCP", res);
03048 goto cleanup;
03049 } else if (res == 0) {
03050
03051 ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
03052 goto cleanup;
03053 }
03054
03055
03056
03057 if (fds[0].revents) {
03058
03059 fds[0].revents = 0;
03060
03061
03062 str_save = req.data;
03063 memset(&req, 0, sizeof(req));
03064 req.data = str_save;
03065 ast_str_reset(req.data);
03066
03067 str_save = reqcpy.data;
03068 memset(&reqcpy, 0, sizeof(reqcpy));
03069 reqcpy.data = str_save;
03070 ast_str_reset(reqcpy.data);
03071
03072 memset(buf, 0, sizeof(buf));
03073
03074 if (tcptls_session->ssl) {
03075 set_socket_transport(&req.socket, SIP_TRANSPORT_TLS);
03076 req.socket.port = htons(ourport_tls);
03077 } else {
03078 set_socket_transport(&req.socket, SIP_TRANSPORT_TCP);
03079 req.socket.port = htons(ourport_tcp);
03080 }
03081 req.socket.fd = tcptls_session->fd;
03082
03083
03084 while (req.len < 4 || strncmp(REQ_OFFSET_TO_STR(&req, len - 4), "\r\n\r\n", 4)) {
03085 if (!tcptls_session->client && !authenticated ) {
03086 if ((timeout = sip_check_authtimeout(start)) < 0) {
03087 goto cleanup;
03088 }
03089
03090 if (timeout == 0) {
03091 ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
03092 goto cleanup;
03093 }
03094 } else {
03095 timeout = -1;
03096 }
03097
03098 res = ast_wait_for_input(tcptls_session->fd, timeout);
03099 if (res < 0) {
03100 ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", tcptls_session->ssl ? "SSL": "TCP", res);
03101 goto cleanup;
03102 } else if (res == 0) {
03103
03104 ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
03105 goto cleanup;
03106 }
03107
03108 ast_mutex_lock(&tcptls_session->lock);
03109 if (!fgets(buf, sizeof(buf), tcptls_session->f)) {
03110 ast_mutex_unlock(&tcptls_session->lock);
03111 goto cleanup;
03112 }
03113 ast_mutex_unlock(&tcptls_session->lock);
03114 if (me->stop)
03115 goto cleanup;
03116 ast_str_append(&req.data, 0, "%s", buf);
03117 req.len = req.data->used;
03118 }
03119 copy_request(&reqcpy, &req);
03120 parse_request(&reqcpy);
03121
03122 if (sscanf(get_header(&reqcpy, "Content-Length"), "%30d", &cl)) {
03123 while (cl > 0) {
03124 size_t bytes_read;
03125 if (!tcptls_session->client && !authenticated ) {
03126 if ((timeout = sip_check_authtimeout(start)) < 0) {
03127 goto cleanup;
03128 }
03129
03130 if (timeout == 0) {
03131 ast_debug(2, "SIP %s server timed out", tcptls_session->ssl ? "SSL": "TCP");
03132 goto cleanup;
03133 }
03134 } else {
03135 timeout = -1;
03136 }
03137
03138 res = ast_wait_for_input(tcptls_session->fd, timeout);
03139 if (res < 0) {
03140 ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", tcptls_session->ssl ? "SSL": "TCP", res);
03141 goto cleanup;
03142 } else if (res == 0) {
03143
03144 ast_debug(2, "SIP %s server timed out", tcptls_session->ssl ? "SSL": "TCP");
03145 goto cleanup;
03146 }
03147
03148 ast_mutex_lock(&tcptls_session->lock);
03149 if (!(bytes_read = fread(buf, 1, MIN(sizeof(buf) - 1, cl), tcptls_session->f))) {
03150 ast_mutex_unlock(&tcptls_session->lock);
03151 goto cleanup;
03152 }
03153 buf[bytes_read] = '\0';
03154 ast_mutex_unlock(&tcptls_session->lock);
03155 if (me->stop)
03156 goto cleanup;
03157 cl -= strlen(buf);
03158 ast_str_append(&req.data, 0, "%s", buf);
03159 req.len = req.data->used;
03160 }
03161 }
03162
03163
03164
03165 req.socket.tcptls_session = tcptls_session;
03166 handle_request_do(&req, &tcptls_session->remote_address);
03167 }
03168
03169 if (fds[1].revents) {
03170 enum sip_tcptls_alert alert;
03171 struct tcptls_packet *packet;
03172
03173 fds[1].revents = 0;
03174
03175 if (read(me->alert_pipe[0], &alert, sizeof(alert)) == -1) {
03176 ast_log(LOG_ERROR, "read() failed: %s\n", strerror(errno));
03177 continue;
03178 }
03179
03180 switch (alert) {
03181 case TCPTLS_ALERT_STOP:
03182 goto cleanup;
03183 case TCPTLS_ALERT_DATA:
03184 ao2_lock(me);
03185 if (!(packet = AST_LIST_REMOVE_HEAD(&me->packet_q, entry))) {
03186 ast_log(LOG_WARNING, "TCPTLS thread alert_pipe indicated packet should be sent, but frame_q is empty");
03187 } else if (ast_tcptls_server_write(tcptls_session, ast_str_buffer(packet->data), packet->len) == -1) {
03188 ast_log(LOG_WARNING, "Failure to write to tcp/tls socket\n");
03189 }
03190
03191 if (packet) {
03192 ao2_t_ref(packet, -1, "tcptls packet sent, this is no longer needed");
03193 }
03194 ao2_unlock(me);
03195 break;
03196 default:
03197 ast_log(LOG_ERROR, "Unknown tcptls thread alert '%d'\n", alert);
03198 }
03199 }
03200 }
03201
03202 ast_debug(2, "Shutting down thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");
03203
03204 cleanup:
03205 if (!tcptls_session->client && !authenticated) {
03206 ast_atomic_fetchadd_int(&unauth_sessions, -1);
03207 }
03208
03209 if (me) {
03210 ao2_t_unlink(threadt, me, "Removing tcptls helper thread, thread is closing");
03211 ao2_t_ref(me, -1, "Removing tcp_helper_threads threadinfo ref");
03212 }
03213 deinit_req(&reqcpy);
03214 deinit_req(&req);
03215
03216
03217 if (ca) {
03218 ao2_t_ref(ca, -1, "closing tcptls thread, getting rid of client tcptls_session arguments");
03219 }
03220
03221 if (tcptls_session) {
03222 ast_mutex_lock(&tcptls_session->lock);
03223 if (tcptls_session->f) {
03224 fclose(tcptls_session->f);
03225 tcptls_session->f = NULL;
03226 }
03227 if (tcptls_session->fd != -1) {
03228 close(tcptls_session->fd);
03229 tcptls_session->fd = -1;
03230 }
03231 tcptls_session->parent = NULL;
03232 ast_mutex_unlock(&tcptls_session->lock);
03233
03234 ao2_ref(tcptls_session, -1);
03235 tcptls_session = NULL;
03236 }
03237 return NULL;
03238 }
03239
03240
03241
03242 static int peer_is_marked(void *peerobj, void *arg, int flags)
03243 {
03244 struct sip_peer *peer = peerobj;
03245 if (peer->the_mark && peer->pokeexpire != -1) {
03246 AST_SCHED_DEL(sched, peer->pokeexpire);
03247 }
03248 return peer->the_mark ? CMP_MATCH : 0;
03249 }
03250
03251
03252
03253 static void unlink_marked_peers_from_tables(void)
03254 {
03255 ao2_t_callback(peers, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, peer_is_marked, NULL,
03256 "initiating callback to remove marked peers");
03257 ao2_t_callback(peers_by_ip, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, peer_is_marked, NULL,
03258 "initiating callback to remove marked peers");
03259 }
03260
03261
03262 static void unlink_peer_from_tables(struct sip_peer *peer)
03263 {
03264 ao2_t_unlink(peers, peer, "ao2_unlink of peer from peers table");
03265 if (peer->addr.sin_addr.s_addr) {
03266 ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
03267 }
03268 }
03269
03270
03271
03272
03273
03274
03275 static void *unref_peer(struct sip_peer *peer, char *tag)
03276 {
03277 ao2_t_ref(peer, -1, tag);
03278 return NULL;
03279 }
03280
03281 static struct sip_peer *ref_peer(struct sip_peer *peer, char *tag)
03282 {
03283 ao2_t_ref(peer, 1, tag);
03284 return peer;
03285 }
03286
03287
03288
03289
03290
03291
03292
03293
03294
03295
03296
03297
03298 static void ref_proxy(struct sip_pvt *pvt, struct sip_proxy *proxy)
03299 {
03300 struct sip_proxy *old_obproxy = pvt->outboundproxy;
03301
03302
03303
03304 if (proxy && proxy != &sip_cfg.outboundproxy) {
03305 ao2_ref(proxy, +1);
03306 }
03307 pvt->outboundproxy = proxy;
03308 if (old_obproxy && old_obproxy != &sip_cfg.outboundproxy) {
03309 ao2_ref(old_obproxy, -1);
03310 }
03311 }
03312
03313
03314
03315
03316
03317
03318
03319
03320 static void *dialog_unlink_all(struct sip_pvt *dialog, int lockowner, int lockdialoglist)
03321 {
03322 struct sip_pkt *cp;
03323
03324 dialog_ref(dialog, "Let's bump the count in the unlink so it doesn't accidentally become dead before we are done");
03325
03326 ao2_t_unlink(dialogs, dialog, "unlinking dialog via ao2_unlink");
03327
03328
03329 if (dialog->owner) {
03330 if (lockowner)
03331 ast_channel_lock(dialog->owner);
03332 ast_debug(1, "Detaching from channel %s\n", dialog->owner->name);
03333 dialog->owner->tech_pvt = dialog_unref(dialog->owner->tech_pvt, "resetting channel dialog ptr in unlink_all");
03334 if (lockowner)
03335 ast_channel_unlock(dialog->owner);
03336 }
03337 if (dialog->registry) {
03338 if (dialog->registry->call == dialog)
03339 dialog->registry->call = dialog_unref(dialog->registry->call, "nulling out the registry's call dialog field in unlink_all");
03340 dialog->registry = registry_unref(dialog->registry, "delete dialog->registry");
03341 }
03342 if (dialog->stateid > -1) {
03343 ast_extension_state_del(dialog->stateid, NULL);
03344 dialog_unref(dialog, "removing extension_state, should unref the associated dialog ptr that was stored there.");
03345 dialog->stateid = -1;
03346 }
03347
03348 if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog)
03349 dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
03350 if (dialog->relatedpeer && dialog->relatedpeer->call == dialog)
03351 dialog->relatedpeer->call = dialog_unref(dialog->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
03352
03353
03354 while((cp = dialog->packets)) {
03355 dialog->packets = dialog->packets->next;
03356 AST_SCHED_DEL(sched, cp->retransid);
03357 dialog_unref(cp->owner, "remove all current packets in this dialog, and the pointer to the dialog too as part of __sip_destroy");
03358 if (cp->data) {
03359 ast_free(cp->data);
03360 }
03361 ast_free(cp);
03362 }
03363
03364 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"));
03365
03366 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"));
03367
03368 if (dialog->autokillid > -1)
03369 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"));
03370
03371 if (dialog->request_queue_sched_id > -1) {
03372 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"));
03373 }
03374
03375 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"));
03376
03377 if (dialog->t38id > -1) {
03378 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"));
03379 }
03380
03381 dialog_unref(dialog, "Let's unbump the count in the unlink so the poor pvt can disappear if it is time");
03382 return NULL;
03383 }
03384
03385 static void *registry_unref(struct sip_registry *reg, char *tag)
03386 {
03387 ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount - 1);
03388 ASTOBJ_UNREF(reg, sip_registry_destroy);
03389 return NULL;
03390 }
03391
03392
03393 static struct sip_registry *registry_addref(struct sip_registry *reg, char *tag)
03394 {
03395 ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount + 1);
03396 return ASTOBJ_REF(reg);
03397 }
03398
03399
03400 static struct ast_udptl_protocol sip_udptl = {
03401 type: "SIP",
03402 get_udptl_info: sip_get_udptl_peer,
03403 set_udptl_peer: sip_set_udptl_peer,
03404 };
03405
03406 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
03407 __attribute__((format(printf, 2, 3)));
03408
03409
03410
03411 static const char *referstatus2str(enum referstatus rstatus)
03412 {
03413 return map_x_s(referstatusstrings, rstatus, "");
03414 }
03415
03416 static inline void pvt_set_needdestroy(struct sip_pvt *pvt, const char *reason)
03417 {
03418 append_history(pvt, "NeedDestroy", "Setting needdestroy because %s", reason);
03419 pvt->needdestroy = 1;
03420 }
03421
03422
03423
03424
03425 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
03426 {
03427 if (p->initreq.headers)
03428 ast_debug(1, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
03429 else
03430 ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
03431
03432 copy_request(&p->initreq, req);
03433 parse_request(&p->initreq);
03434 if (req->debug)
03435 ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
03436 }
03437
03438
03439 static void sip_alreadygone(struct sip_pvt *dialog)
03440 {
03441 ast_debug(3, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
03442 dialog->alreadygone = 1;
03443 }
03444
03445
03446 static int proxy_update(struct sip_proxy *proxy)
03447 {
03448
03449
03450 if (!inet_aton(proxy->name, &proxy->ip.sin_addr)) {
03451
03452
03453 if (ast_get_ip_or_srv(&proxy->ip, proxy->name, sip_cfg.srvlookup ? "_sip._udp" : NULL) < 0) {
03454 ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
03455 return FALSE;
03456 }
03457 }
03458 proxy->last_dnsupdate = time(NULL);
03459 return TRUE;
03460 }
03461
03462
03463
03464
03465
03466 static int port_str2int(const char *pt, unsigned int standard)
03467 {
03468 int port = standard;
03469 if (ast_strlen_zero(pt) || (sscanf(pt, "%30d", &port) != 1) || (port < 1) || (port > 65535)) {
03470 port = standard;
03471 }
03472
03473 return port;
03474 }
03475
03476
03477 static struct sip_proxy *proxy_allocate(char *name, char *port, int force)
03478 {
03479 struct sip_proxy *proxy;
03480
03481 if (ast_strlen_zero(name)) {
03482 return NULL;
03483 }
03484
03485 proxy = ao2_alloc(sizeof(*proxy), NULL);
03486 if (!proxy)
03487 return NULL;
03488 proxy->force = force;
03489 ast_copy_string(proxy->name, name, sizeof(proxy->name));
03490 proxy->ip.sin_port = htons(port_str2int(port, STANDARD_SIP_PORT));
03491 proxy->ip.sin_family = AF_INET;
03492 proxy_update(proxy);
03493 return proxy;
03494 }
03495
03496
03497 static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
03498 {
03499 if (peer && peer->outboundproxy) {
03500 if (sipdebug)
03501 ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
03502 append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
03503 return peer->outboundproxy;
03504 }
03505 if (sip_cfg.outboundproxy.name[0]) {
03506 if (sipdebug)
03507 ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
03508 append_history(dialog, "OBproxy", "Using global obproxy %s", sip_cfg.outboundproxy.name);
03509 return &sip_cfg.outboundproxy;
03510 }
03511 if (sipdebug)
03512 ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
03513 return NULL;
03514 }
03515
03516
03517
03518
03519
03520
03521
03522 static int method_match(enum sipmethod id, const char *name)
03523 {
03524 int len = strlen(sip_methods[id].text);
03525 int l_name = name ? strlen(name) : 0;
03526
03527 return (l_name >= len && name[len] < 33 &&
03528 !strncasecmp(sip_methods[id].text, name, len));
03529 }
03530
03531
03532 static int find_sip_method(const char *msg)
03533 {
03534 int i, res = 0;
03535
03536 if (ast_strlen_zero(msg))
03537 return 0;
03538 for (i = 1; i < ARRAY_LEN(sip_methods) && !res; i++) {
03539 if (method_match(i, msg))
03540 res = sip_methods[i].id;
03541 }
03542 return res;
03543 }
03544
03545
03546 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported)
03547 {
03548 char *next, *sep;
03549 char *temp;
03550 unsigned int profile = 0;
03551 int i, found;
03552
03553 if (ast_strlen_zero(supported) )
03554 return 0;
03555 temp = ast_strdupa(supported);
03556
03557 if (sipdebug)
03558 ast_debug(3, "Begin: parsing SIP \"Supported: %s\"\n", supported);
03559
03560 for (next = temp; next; next = sep) {
03561 found = FALSE;
03562 if ( (sep = strchr(next, ',')) != NULL)
03563 *sep++ = '\0';
03564 next = ast_skip_blanks(next);
03565 if (sipdebug)
03566 ast_debug(3, "Found SIP option: -%s-\n", next);
03567 for (i = 0; i < ARRAY_LEN(sip_options); i++) {
03568 if (!strcasecmp(next, sip_options[i].text)) {
03569 profile |= sip_options[i].id;
03570 found = TRUE;
03571 if (sipdebug)
03572 ast_debug(3, "Matched SIP option: %s\n", next);
03573 break;
03574 }
03575 }
03576
03577
03578
03579
03580
03581 if (!found)
03582 profile |= SIP_OPT_UNKNOWN;
03583
03584 if (!found && sipdebug) {
03585 if (!strncasecmp(next, "x-", 2))
03586 ast_debug(3, "Found private SIP option, not supported: %s\n", next);
03587 else
03588 ast_debug(3, "Found no match for SIP option: %s (Please file bug report!)\n", next);
03589 }
03590 }
03591
03592 if (pvt)
03593 pvt->sipoptions = profile;
03594 return profile;
03595 }
03596
03597
03598 static inline int sip_debug_test_addr(const struct sockaddr_in *addr)
03599 {
03600 if (!sipdebug)
03601 return 0;
03602 if (debugaddr.sin_addr.s_addr) {
03603 if (((ntohs(debugaddr.sin_port) != 0)
03604 && (debugaddr.sin_port != addr->sin_port))
03605 || (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
03606 return 0;
03607 }
03608 return 1;
03609 }
03610
03611
03612 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p)
03613 {
03614 if (p->outboundproxy)
03615 return &p->outboundproxy->ip;
03616
03617 return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? &p->recv : &p->sa;
03618 }
03619
03620
03621 static const char *sip_nat_mode(const struct sip_pvt *p)
03622 {
03623 return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? "NAT" : "no NAT";
03624 }
03625
03626
03627 static inline int sip_debug_test_pvt(struct sip_pvt *p)
03628 {
03629 if (!sipdebug)
03630 return 0;
03631 return sip_debug_test_addr(sip_real_dst(p));
03632 }
03633
03634
03635 static int get_transport_str2enum(const char *transport)
03636 {
03637 int res = 0;
03638
03639 if (ast_strlen_zero(transport)) {
03640 return res;
03641 }
03642
03643 if (!strcasecmp(transport, "udp")) {
03644 res |= SIP_TRANSPORT_UDP;
03645 }
03646 if (!strcasecmp(transport, "tcp")) {
03647 res |= SIP_TRANSPORT_TCP;
03648 }
03649 if (!strcasecmp(transport, "tls")) {
03650 res |= SIP_TRANSPORT_TLS;
03651 }
03652
03653 return res;
03654 }
03655
03656
03657 static inline const char *get_transport_list(unsigned int transports) {
03658 switch (transports) {
03659 case SIP_TRANSPORT_UDP:
03660 return "UDP";
03661 case SIP_TRANSPORT_TCP:
03662 return "TCP";
03663 case SIP_TRANSPORT_TLS:
03664 return "TLS";
03665 case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TCP:
03666 return "TCP,UDP";
03667 case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TLS:
03668 return "TLS,UDP";
03669 case SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS:
03670 return "TLS,TCP";
03671 default:
03672 return transports ?
03673 "TLS,TCP,UDP" : "UNKNOWN";
03674 }
03675 }
03676
03677
03678 static inline const char *get_transport(enum sip_transport t)
03679 {
03680 switch (t) {
03681 case SIP_TRANSPORT_UDP:
03682 return "UDP";
03683 case SIP_TRANSPORT_TCP:
03684 return "TCP";
03685 case SIP_TRANSPORT_TLS:
03686 return "TLS";
03687 }
03688
03689 return "UNKNOWN";
03690 }
03691
03692
03693 static inline const char *get_srv_protocol(enum sip_transport t)
03694 {
03695 switch (t) {
03696 case SIP_TRANSPORT_UDP:
03697 return "udp";
03698 case SIP_TRANSPORT_TLS:
03699 case SIP_TRANSPORT_TCP:
03700 return "tcp";
03701 }
03702
03703 return "udp";
03704 }
03705
03706
03707 static inline const char *get_srv_service(enum sip_transport t)
03708 {
03709 switch (t) {
03710 case SIP_TRANSPORT_TCP:
03711 case SIP_TRANSPORT_UDP:
03712 return "sip";
03713 case SIP_TRANSPORT_TLS:
03714 return "sips";
03715 }
03716 return "sip";
03717 }
03718
03719
03720
03721
03722
03723
03724
03725 static inline const char *get_transport_pvt(struct sip_pvt *p)
03726 {
03727 if (p->outboundproxy && p->outboundproxy->transport) {
03728 set_socket_transport(&p->socket, p->outboundproxy->transport);
03729 }
03730
03731 return get_transport(p->socket.type);
03732 }
03733
03734
03735
03736
03737
03738
03739 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len)
03740 {
03741 int res = 0;
03742 const struct sockaddr_in *dst = sip_real_dst(p);
03743
03744 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));
03745
03746 if (sip_prepare_socket(p) < 0)
03747 return XMIT_ERROR;
03748
03749 if (p->socket.type == SIP_TRANSPORT_UDP) {
03750 res = sendto(p->socket.fd, data->str, len, 0, (const struct sockaddr *)dst, sizeof(struct sockaddr_in));
03751 } else if (p->socket.tcptls_session) {
03752 res = sip_tcptls_write(p->socket.tcptls_session, data->str, len);
03753 } else {
03754 ast_debug(2, "Socket type is TCP but no tcptls_session is present to write to\n");
03755 return XMIT_ERROR;
03756 }
03757
03758 if (res == -1) {
03759 switch (errno) {
03760 case EBADF:
03761 case EHOSTUNREACH:
03762 case ENETDOWN:
03763 case ENETUNREACH:
03764 case ECONNREFUSED:
03765 res = XMIT_ERROR;
03766 }
03767 }
03768 if (res != len)
03769 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));
03770
03771 return res;
03772 }
03773
03774
03775 static void build_via(struct sip_pvt *p)
03776 {
03777
03778 const char *rport = ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_RFC3581 ? ";rport" : "";
03779
03780
03781 snprintf(p->via, sizeof(p->via), "SIP/2.0/%s %s:%d;branch=z9hG4bK%08x%s",
03782 get_transport_pvt(p),
03783 ast_inet_ntoa(p->ourip.sin_addr),
03784 ntohs(p->ourip.sin_port), (int) p->branch, rport);
03785 }
03786
03787
03788
03789
03790
03791
03792
03793
03794 static void ast_sip_ouraddrfor(struct in_addr *them, struct sockaddr_in *us, struct sip_pvt *p)
03795 {
03796 struct sockaddr_in theirs;
03797
03798
03799
03800
03801
03802
03803
03804
03805
03806
03807
03808
03809 int want_remap;
03810
03811 *us = internip;
03812
03813 ast_ouraddrfor(them, &us->sin_addr);
03814 theirs.sin_addr = *them;
03815
03816 want_remap = localaddr &&
03817 (externip.sin_addr.s_addr || stunaddr.sin_addr.s_addr) &&
03818 ast_apply_ha(localaddr, &theirs) == AST_SENSE_ALLOW ;
03819
03820 if (want_remap &&
03821 (!sip_cfg.matchexterniplocally || !ast_apply_ha(localaddr, us)) ) {
03822
03823 if (externexpire && time(NULL) >= externexpire) {
03824 if (stunaddr.sin_addr.s_addr) {
03825 ast_stun_request(sipsock, &stunaddr, NULL, &externip);
03826 } else {
03827 if (ast_parse_arg(externhost, PARSE_INADDR, &externip))
03828 ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
03829 }
03830 externexpire = time(NULL) + externrefresh;
03831 }
03832 if (externip.sin_addr.s_addr)
03833 *us = externip;
03834 else
03835 ast_log(LOG_WARNING, "stun failed\n");
03836 ast_debug(1, "Target address %s is not local, substituting externip\n",
03837 ast_inet_ntoa(*(struct in_addr *)&them->s_addr));
03838 } else if (p) {
03839
03840 switch (p->socket.type) {
03841 case SIP_TRANSPORT_TCP:
03842 if (sip_tcp_desc.local_address.sin_addr.s_addr) {
03843 *us = sip_tcp_desc.local_address;
03844 } else {
03845 us->sin_port = sip_tcp_desc.local_address.sin_port;
03846 }
03847 break;
03848 case SIP_TRANSPORT_TLS:
03849 if (sip_tls_desc.local_address.sin_addr.s_addr) {
03850 *us = sip_tls_desc.local_address;
03851 } else {
03852 us->sin_port = sip_tls_desc.local_address.sin_port;
03853 }
03854 break;
03855 case SIP_TRANSPORT_UDP:
03856
03857 default:
03858 if (bindaddr.sin_addr.s_addr) {
03859 *us = bindaddr;
03860 }
03861 }
03862 } else if (bindaddr.sin_addr.s_addr) {
03863 *us = bindaddr;
03864 }
03865 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));
03866 }
03867
03868
03869 static __attribute__((format(printf, 2, 0))) void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
03870 {
03871 char buf[80], *c = buf;
03872 struct sip_history *hist;
03873 int l;
03874
03875 vsnprintf(buf, sizeof(buf), fmt, ap);
03876 strsep(&c, "\r\n");
03877 l = strlen(buf) + 1;
03878 if (!(hist = ast_calloc(1, sizeof(*hist) + l)))
03879 return;
03880 if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
03881 ast_free(hist);
03882 return;
03883 }
03884 memcpy(hist->event, buf, l);
03885 if (p->history_entries == MAX_HISTORY_ENTRIES) {
03886 struct sip_history *oldest;
03887 oldest = AST_LIST_REMOVE_HEAD(p->history, list);
03888 p->history_entries--;
03889 ast_free(oldest);
03890 }
03891 AST_LIST_INSERT_TAIL(p->history, hist, list);
03892 p->history_entries++;
03893 }
03894
03895
03896 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
03897 {
03898 va_list ap;
03899
03900 if (!p)
03901 return;
03902
03903 if (!p->do_history && !recordhistory && !dumphistory)
03904 return;
03905
03906 va_start(ap, fmt);
03907 append_history_va(p, fmt, ap);
03908 va_end(ap);
03909
03910 return;
03911 }
03912
03913
03914 static int retrans_pkt(const void *data)
03915 {
03916 struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
03917 int reschedule = DEFAULT_RETRANS;
03918 int xmitres = 0;
03919
03920
03921 sip_pvt_lock(pkt->owner);
03922
03923 if (pkt->retrans < MAX_RETRANS) {
03924 pkt->retrans++;
03925 if (!pkt->timer_t1) {
03926 if (sipdebug)
03927 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);
03928 } else {
03929 int siptimer_a;
03930
03931 if (sipdebug)
03932 ast_debug(4, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n", pkt->retransid, pkt->retrans, sip_methods[pkt->method].text, pkt->method);
03933 if (!pkt->timer_a)
03934 pkt->timer_a = 2 ;
03935 else
03936 pkt->timer_a = 2 * pkt->timer_a;
03937
03938
03939 siptimer_a = pkt->timer_t1 * pkt->timer_a;
03940 if (pkt->method != SIP_INVITE && siptimer_a > 4000)
03941 siptimer_a = 4000;
03942
03943
03944 reschedule = siptimer_a;
03945 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);
03946 }
03947
03948 if (sip_debug_test_pvt(pkt->owner)) {
03949 const struct sockaddr_in *dst = sip_real_dst(pkt->owner);
03950 ast_verbose("Retransmitting #%d (%s) to %s:%d:\n%s\n---\n",
03951 pkt->retrans, sip_nat_mode(pkt->owner),
03952 ast_inet_ntoa(dst->sin_addr),
03953 ntohs(dst->sin_port), pkt->data->str);
03954 }
03955
03956 append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data->str);
03957 xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
03958 if (xmitres == XMIT_ERROR) {
03959 ast_log(LOG_WARNING, "Network error on retransmit in dialog %s\n", pkt->owner->callid);
03960 } else {
03961 sip_pvt_unlock(pkt->owner);
03962 return reschedule;
03963 }
03964 }
03965
03966 if (pkt->owner && pkt->method != SIP_OPTIONS && xmitres == 0) {
03967 if (pkt->is_fatal || sipdebug)
03968 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",
03969 pkt->owner->callid, pkt->seqno,
03970 pkt->is_fatal ? "Critical" : "Non-critical", pkt->is_resp ? "Response" : "Request");
03971 } else if (pkt->method == SIP_OPTIONS && sipdebug) {
03972 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);
03973
03974 }
03975 if (xmitres == XMIT_ERROR) {
03976 ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission on Call ID %s\n", pkt->owner->callid);
03977 append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03978 } else {
03979 append_history(pkt->owner, "MaxRetries", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03980 }
03981 pkt->retransid = -1;
03982
03983 if (pkt->is_fatal) {
03984 while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
03985 sip_pvt_unlock(pkt->owner);
03986 usleep(1);
03987 sip_pvt_lock(pkt->owner);
03988 }
03989
03990 if (pkt->owner->owner && !pkt->owner->owner->hangupcause)
03991 pkt->owner->owner->hangupcause = AST_CAUSE_NO_USER_RESPONSE;
03992
03993 if (pkt->owner->owner) {
03994 sip_alreadygone(pkt->owner);
03995 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);
03996 ast_queue_hangup_with_cause(pkt->owner->owner, AST_CAUSE_PROTOCOL_ERROR);
03997 ast_channel_unlock(pkt->owner->owner);
03998 } else {
03999
04000
04001
04002 if (pkt->method != SIP_OPTIONS && pkt->method != SIP_REGISTER) {
04003 pvt_set_needdestroy(pkt->owner, "no response to critical packet");
04004 sip_alreadygone(pkt->owner);
04005 append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
04006 }
04007 }
04008 }
04009
04010 if (pkt->method == SIP_BYE) {
04011
04012 sip_alreadygone(pkt->owner);
04013 if (pkt->owner->owner)
04014 ast_channel_unlock(pkt->owner->owner);
04015 append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
04016 pvt_set_needdestroy(pkt->owner, "no response to BYE");
04017 }
04018
04019
04020 for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
04021 if (cur == pkt) {
04022 UNLINK(cur, pkt->owner->packets, prev);
04023 sip_pvt_unlock(pkt->owner);
04024 if (pkt->owner)
04025 pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
04026 if (pkt->data)
04027 ast_free(pkt->data);
04028 pkt->data = NULL;
04029 ast_free(pkt);
04030 return 0;
04031 }
04032 }
04033
04034 ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
04035 sip_pvt_unlock(pkt->owner);
04036 return 0;
04037 }
04038
04039
04040
04041
04042 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)
04043 {
04044 struct sip_pkt *pkt = NULL;
04045 int siptimer_a = DEFAULT_RETRANS;
04046 int xmitres = 0;
04047 int respid;
04048
04049 if (sipmethod == SIP_INVITE) {
04050
04051 p->pendinginvite = seqno;
04052 }
04053
04054
04055
04056
04057 if (!(p->socket.type & SIP_TRANSPORT_UDP)) {
04058 xmitres = __sip_xmit(p, data, len);
04059 if (xmitres == XMIT_ERROR) {
04060 append_history(p, "XmitErr", "%s", fatal ? "(Critical)" : "(Non-critical)");
04061 return AST_FAILURE;
04062 } else {
04063 return AST_SUCCESS;
04064 }
04065 }
04066
04067 if (!(pkt = ast_calloc(1, sizeof(*pkt) + len + 1)))
04068 return AST_FAILURE;
04069
04070 if (!(pkt->data = ast_str_create(len))) {
04071 ast_free(pkt);
04072 return AST_FAILURE;
04073 }
04074 ast_str_set(&pkt->data, 0, "%s%s", data->str, "\0");
04075 pkt->packetlen = len;
04076
04077 pkt->method = sipmethod;
04078 pkt->seqno = seqno;
04079 pkt->is_resp = resp;
04080 pkt->is_fatal = fatal;
04081 pkt->owner = dialog_ref(p, "__sip_reliable_xmit: setting pkt->owner");
04082 pkt->next = p->packets;
04083 p->packets = pkt;
04084 if (resp) {
04085
04086 if (sscanf(ast_str_buffer(pkt->data), "SIP/2.0 %30u", &respid) == 1) {
04087 pkt->response_code = respid;
04088 }
04089 }
04090 pkt->timer_t1 = p->timer_t1;
04091 pkt->retransid = -1;
04092 if (pkt->timer_t1)
04093 siptimer_a = pkt->timer_t1 * 2;
04094
04095
04096 AST_SCHED_REPLACE_VARIABLE(pkt->retransid, sched, siptimer_a, retrans_pkt, pkt, 1);
04097 if (sipdebug)
04098 ast_debug(4, "*** SIP TIMER: Initializing retransmit timer on packet: Id #%d\n", pkt->retransid);
04099
04100 xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
04101
04102 if (xmitres == XMIT_ERROR) {
04103 append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
04104 ast_log(LOG_ERROR, "Serious Network Trouble; __sip_xmit returns error for pkt data\n");
04105 AST_SCHED_DEL(sched, pkt->retransid);
04106 p->packets = pkt->next;
04107 pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
04108 ast_free(pkt->data);
04109 ast_free(pkt);
04110 return AST_FAILURE;
04111 } else {
04112 return AST_SUCCESS;
04113 }
04114 }
04115
04116
04117
04118
04119
04120
04121 static int __sip_autodestruct(const void *data)
04122 {
04123 struct sip_pvt *p = (struct sip_pvt *)data;
04124
04125
04126 if (p->subscribed) {
04127 transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE);
04128 p->subscribed = NONE;
04129 append_history(p, "Subscribestatus", "timeout");
04130 ast_debug(3, "Re-scheduled destruction of SIP subscription %s\n", p->callid ? p->callid : "<unknown>");
04131 return 10000;
04132 }
04133
04134
04135 if (p->packets) {
04136 if (!p->needdestroy) {
04137 char method_str[31];
04138 ast_debug(3, "Re-scheduled destruction of SIP call %s\n", p->callid ? p->callid : "<unknown>");
04139 append_history(p, "ReliableXmit", "timeout");
04140 if (sscanf(p->lastmsg, "Tx: %30s", method_str) == 1 || sscanf(p->lastmsg, "Rx: %30s", method_str) == 1) {
04141 if (method_match(SIP_CANCEL, method_str) || method_match(SIP_BYE, method_str)) {
04142 pvt_set_needdestroy(p, "autodestruct");
04143 }
04144 }
04145 return 10000;
04146 } else {
04147
04148 __sip_pretend_ack(p);
04149 }
04150 }
04151
04152
04153 p->autokillid = -1;
04154
04155
04156
04157
04158
04159 sip_pvt_lock(p);
04160 while (p->owner && ast_channel_trylock(p->owner)) {
04161 sip_pvt_unlock(p);
04162 sched_yield();
04163 sip_pvt_lock(p);
04164 }
04165
04166 if (p->owner) {
04167 ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
04168 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
04169 ast_channel_unlock(p->owner);
04170 } else if (p->refer && !p->alreadygone) {
04171 ast_debug(3, "Finally hanging up channel after transfer: %s\n", p->callid);
04172 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
04173 append_history(p, "ReferBYE", "Sending BYE on transferer call leg %s", p->callid);
04174 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
04175 } else {
04176 append_history(p, "AutoDestroy", "%s", p->callid);
04177 ast_debug(3, "Auto destroying SIP dialog '%s'\n", p->callid);
04178 dialog_unlink_all(p, TRUE, TRUE);
04179
04180
04181
04182 }
04183
04184 sip_pvt_unlock(p);
04185
04186 dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
04187
04188 return 0;
04189 }
04190
04191
04192 static void sip_scheddestroy(struct sip_pvt *p, int ms)
04193 {
04194 if (ms < 0) {
04195 if (p->timer_t1 == 0) {
04196 p->timer_t1 = global_t1;
04197 p->timer_b = global_timer_b;
04198 }
04199 ms = p->timer_t1 * 64;
04200 }
04201 if (sip_debug_test_pvt(p))
04202 ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
04203 if (sip_cancel_destroy(p))
04204 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
04205
04206 if (p->do_history)
04207 append_history(p, "SchedDestroy", "%d ms", ms);
04208 p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, dialog_ref(p, "setting ref as passing into ast_sched_add for __sip_autodestruct"));
04209
04210 if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_schedid > 0)
04211 stop_session_timer(p);
04212 }
04213
04214
04215
04216
04217
04218 static int sip_cancel_destroy(struct sip_pvt *p)
04219 {
04220 int res = 0;
04221 if (p->autokillid > -1) {
04222 int res3;
04223
04224 if (!(res3 = ast_sched_del(sched, p->autokillid))) {
04225 append_history(p, "CancelDestroy", "");
04226 p->autokillid = -1;
04227 dialog_unref(p, "dialog unrefd because autokillid is de-sched'd");
04228 }
04229 }
04230 return res;
04231 }
04232
04233
04234
04235 static int __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
04236 {
04237 struct sip_pkt *cur, *prev = NULL;
04238 const char *msg = "Not Found";
04239 int res = FALSE;
04240
04241
04242
04243
04244
04245
04246 if (p->outboundproxy && !p->outboundproxy->force){
04247 ref_proxy(p, NULL);
04248 }
04249
04250 for (cur = p->packets; cur; prev = cur, cur = cur->next) {
04251 if (cur->seqno != seqno || cur->is_resp != resp)
04252 continue;
04253 if (cur->is_resp || cur->method == sipmethod) {
04254 res = TRUE;
04255 msg = "Found";
04256 if (!resp && (seqno == p->pendinginvite)) {
04257 ast_debug(1, "Acked pending invite %d\n", p->pendinginvite);
04258 p->pendinginvite = 0;
04259 }
04260 if (cur->retransid > -1) {
04261 if (sipdebug)
04262 ast_debug(4, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
04263 }
04264
04265
04266
04267
04268
04269
04270
04271
04272
04273
04274
04275
04276
04277
04278
04279
04280 while (cur->retransid > -1 && ast_sched_del(sched, cur->retransid)) {
04281 sip_pvt_unlock(p);
04282 usleep(1);
04283 sip_pvt_lock(p);
04284 }
04285 UNLINK(cur, p->packets, prev);
04286 dialog_unref(cur->owner, "unref pkt cur->owner dialog from sip ack before freeing pkt");
04287 if (cur->data)
04288 ast_free(cur->data);
04289 ast_free(cur);
04290 break;
04291 }
04292 }
04293 ast_debug(1, "Stopping retransmission on '%s' of %s %d: Match %s\n",
04294 p->callid, resp ? "Response" : "Request", seqno, msg);
04295 return res;
04296 }
04297
04298
04299
04300 static void __sip_pretend_ack(struct sip_pvt *p)
04301 {
04302 struct sip_pkt *cur = NULL;
04303
04304 while (p->packets) {
04305 int method;
04306 if (cur == p->packets) {
04307 ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
04308 return;
04309 }
04310 cur = p->packets;
04311 method = (cur->method) ? cur->method : find_sip_method(cur->data->str);
04312 __sip_ack(p, cur->seqno, cur->is_resp, method);
04313 }
04314 }
04315
04316
04317 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
04318 {
04319 struct sip_pkt *cur;
04320 int res = FALSE;
04321
04322 for (cur = p->packets; cur; cur = cur->next) {
04323 if (cur->seqno == seqno && cur->is_resp == resp &&
04324 (cur->is_resp || method_match(sipmethod, cur->data->str))) {
04325
04326 if (cur->retransid > -1) {
04327 if (sipdebug)
04328 ast_debug(4, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
04329 }
04330 AST_SCHED_DEL(sched, cur->retransid);
04331 res = TRUE;
04332 break;
04333 }
04334 }
04335 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");
04336 return res;
04337 }
04338
04339
04340
04341 static void parse_copy(struct sip_request *dst, const struct sip_request *src)
04342 {
04343 copy_request(dst, src);
04344 parse_request(dst);
04345 }
04346
04347
04348 static void add_blank(struct sip_request *req)
04349 {
04350 if (!req->lines) {
04351
04352 ast_str_append(&req->data, 0, "\r\n");
04353 req->len = ast_str_strlen(req->data);
04354 }
04355 }
04356
04357 static int send_provisional_keepalive_full(struct sip_pvt *pvt, int with_sdp)
04358 {
04359 const char *msg = NULL;
04360
04361 if (!pvt->last_provisional || !strncasecmp(pvt->last_provisional, "100", 3)) {
04362 msg = "183 Session Progress";
04363 }
04364
04365 if (pvt->invitestate < INV_COMPLETED) {
04366 if (with_sdp) {
04367 transmit_response_with_sdp(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq, XMIT_UNRELIABLE, FALSE);
04368 } else {
04369 transmit_response(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq);
04370 }
04371 return PROVIS_KEEPALIVE_TIMEOUT;
04372 }
04373
04374 return 0;
04375 }
04376
04377 static int send_provisional_keepalive(const void *data) {
04378 struct sip_pvt *pvt = (struct sip_pvt *) data;
04379
04380 return send_provisional_keepalive_full(pvt, 0);
04381 }
04382
04383 static int send_provisional_keepalive_with_sdp(const void *data) {
04384 struct sip_pvt *pvt = (void *)data;
04385
04386 return send_provisional_keepalive_full(pvt, 1);
04387 }
04388
04389 static void update_provisional_keepalive(struct sip_pvt *pvt, int with_sdp)
04390 {
04391 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"));
04392
04393 pvt->provisional_keepalive_sched_id = ast_sched_add(sched, PROVIS_KEEPALIVE_TIMEOUT,
04394 with_sdp ? send_provisional_keepalive_with_sdp : send_provisional_keepalive, dialog_ref(pvt, "Increment refcount to pass dialog pointer to sched callback"));
04395 }
04396
04397
04398 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
04399 {
04400 int res;
04401
04402 finalize_content(req);
04403 add_blank(req);
04404 if (sip_debug_test_pvt(p)) {
04405 const struct sockaddr_in *dst = sip_real_dst(p);
04406
04407 ast_verbose("\n<--- %sTransmitting (%s) to %s:%d --->\n%s\n<------------>\n",
04408 reliable ? "Reliably " : "", sip_nat_mode(p),
04409 ast_inet_ntoa(dst->sin_addr),
04410 ntohs(dst->sin_port), req->data->str);
04411 }
04412 if (p->do_history) {
04413 struct sip_request tmp = { .rlPart1 = 0, };
04414 parse_copy(&tmp, req);
04415 append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", tmp.data->str, get_header(&tmp, "CSeq"),
04416 (tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? REQ_OFFSET_TO_STR(&tmp, rlPart2) : sip_methods[tmp.method].text);
04417 deinit_req(&tmp);
04418 }
04419
04420
04421 if (p->initreq.method == SIP_INVITE && reliable == XMIT_CRITICAL) {
04422 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"));
04423 }
04424
04425 res = (reliable) ?
04426 __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
04427 __sip_xmit(p, req->data, req->len);
04428 deinit_req(req);
04429 if (res > 0)
04430 return 0;
04431 return res;
04432 }
04433
04434
04435 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
04436 {
04437 int res;
04438
04439
04440
04441
04442 if (p->outboundproxy) {
04443 p->sa = p->outboundproxy->ip;
04444 }
04445
04446 finalize_content(req);
04447 add_blank(req);
04448 if (sip_debug_test_pvt(p)) {
04449 if (ast_test_flag(&p->flags[0], SIP_NAT_ROUTE))
04450 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);
04451 else
04452 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);
04453 }
04454 if (p->do_history) {
04455 struct sip_request tmp = { .rlPart1 = 0, };
04456 parse_copy(&tmp, req);
04457 append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", tmp.data->str, get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
04458 deinit_req(&tmp);
04459 }
04460 res = (reliable) ?
04461 __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
04462 __sip_xmit(p, req->data, req->len);
04463 deinit_req(req);
04464 return res;
04465 }
04466
04467
04468 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen)
04469 {
04470 int res = -1;
04471 enum ast_t38_state state = T38_STATE_UNAVAILABLE;
04472 struct sip_pvt *p = (struct sip_pvt *) chan->tech_pvt;
04473
04474 switch (option) {
04475 case AST_OPTION_T38_STATE:
04476
04477 if (*datalen != sizeof(enum ast_t38_state)) {
04478 ast_log(LOG_ERROR, "Invalid datalen for AST_OPTION_T38_STATE option. Expected %d, got %d\n", (int)sizeof(enum ast_t38_state), *datalen);
04479 return -1;
04480 }
04481
04482 sip_pvt_lock(p);
04483
04484
04485 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
04486 switch (p->t38.state) {
04487 case T38_LOCAL_REINVITE:
04488 case T38_PEER_REINVITE:
04489 state = T38_STATE_NEGOTIATING;
04490 break;
04491 case T38_ENABLED:
04492 state = T38_STATE_NEGOTIATED;
04493 break;
04494 default:
04495 state = T38_STATE_UNKNOWN;
04496 }
04497 }
04498
04499 sip_pvt_unlock(p);
04500
04501 *((enum ast_t38_state *) data) = state;
04502 res = 0;
04503
04504 break;
04505 default:
04506 break;
04507 }
04508
04509 return res;
04510 }
04511
04512
04513
04514
04515
04516 static const char *find_closing_quote(const char *start, const char *lim)
04517 {
04518 char last_char = '\0';
04519 const char *s;
04520 for (s = start; *s && s != lim; last_char = *s++) {
04521 if (*s == '"' && last_char != '\\')
04522 break;
04523 }
04524 return s;
04525 }
04526
04527
04528
04529
04530
04531
04532
04533
04534
04535
04536
04537
04538
04539 static char *get_in_brackets(char *tmp)
04540 {
04541 const char *parse = tmp;
04542 char *first_bracket;
04543
04544
04545
04546
04547
04548 while ( (first_bracket = strchr(parse, '<')) ) {
04549 char *first_quote = strchr(parse, '"');
04550
04551 if (!first_quote || first_quote > first_bracket)
04552 break;
04553
04554 parse = find_closing_quote(first_quote + 1, NULL);
04555 if (!*parse) {
04556
04557 ast_log(LOG_WARNING, "No closing quote found in '%s'\n", tmp);
04558 break;
04559 }
04560 parse++;
04561 }
04562 if (first_bracket) {
04563 char *second_bracket = strchr(first_bracket + 1, '>');
04564 if (second_bracket) {
04565 *second_bracket = '\0';
04566 tmp = first_bracket + 1;
04567 } else {
04568 ast_log(LOG_WARNING, "No closing bracket found in '%s'\n", tmp);
04569 }
04570 }
04571
04572 return tmp;
04573 }
04574
04575
04576
04577
04578
04579
04580
04581
04582
04583
04584
04585
04586
04587
04588
04589
04590
04591
04592
04593
04594 static int parse_uri(char *uri, const char *scheme,
04595 char **ret_name, char **pass, char **domain, char **port, char **options, char **transport)
04596 {
04597 char *name = NULL;
04598 int error = 0;
04599
04600
04601 if (pass)
04602 *pass = "";
04603 if (port)
04604 *port = "";
04605 if (scheme) {
04606 int l;
04607 char *scheme2 = ast_strdupa(scheme);
04608 char *cur = strsep(&scheme2, ",");
04609 for (; !ast_strlen_zero(cur); cur = strsep(&scheme2, ",")) {
04610 l = strlen(cur);
04611 if (!strncasecmp(uri, cur, l)) {
04612 uri += l;
04613 break;
04614 }
04615 }
04616 if (ast_strlen_zero(cur)) {
04617 ast_debug(1, "No supported scheme found in '%s' using the scheme[s] %s\n", uri, scheme);
04618 error = -1;
04619 }
04620 }
04621 if (transport) {
04622 char *t, *type = "";
04623 *transport = "";
04624 if ((t = strstr(uri, "transport="))) {
04625 strsep(&t, "=");
04626 if ((type = strsep(&t, ";"))) {
04627 *transport = type;
04628 }
04629 }
04630 }
04631
04632 if (!domain) {
04633
04634
04635
04636 } else {
04637
04638
04639
04640 char *c, *dom = "";
04641
04642 if ((c = strchr(uri, '@')) == NULL) {
04643
04644 dom = uri;
04645 name = "";
04646 } else {
04647 *c++ = '\0';
04648 dom = c;
04649 name = uri;
04650 }
04651
04652
04653 dom = strsep(&dom, ";");
04654 name = strsep(&name, ";");
04655
04656 if (port && (c = strchr(dom, ':'))) {
04657 *c++ = '\0';
04658 *port = c;
04659 }
04660 if (pass && (c = strchr(name, ':'))) {
04661 *c++ = '\0';
04662 *pass = c;
04663 }
04664 *domain = dom;
04665 }
04666 if (ret_name)
04667 *ret_name = name;
04668 if (options)
04669 *options = uri ? uri : "";
04670
04671 return error;
04672 }
04673
04674
04675 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
04676 {
04677 struct sip_pvt *p = chan->tech_pvt;
04678
04679 if (subclass != AST_HTML_URL)
04680 return -1;
04681
04682 ast_string_field_build(p, url, "<%s>;mode=active", data);
04683
04684 if (sip_debug_test_pvt(p))
04685 ast_debug(1, "Send URL %s, state = %d!\n", data, chan->_state);
04686
04687 switch (chan->_state) {
04688 case AST_STATE_RING:
04689 transmit_response(p, "100 Trying", &p->initreq);
04690 break;
04691 case AST_STATE_RINGING:
04692 transmit_response(p, "180 Ringing", &p->initreq);
04693 break;
04694 case AST_STATE_UP:
04695 if (!p->pendinginvite) {
04696 transmit_reinvite_with_sdp(p, FALSE, FALSE);
04697 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
04698 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
04699 }
04700 break;
04701 default:
04702 ast_log(LOG_WARNING, "Don't know how to send URI when state is %d!\n", chan->_state);
04703 }
04704
04705 return 0;
04706 }
04707
04708
04709 static const char *sip_get_callid(struct ast_channel *chan)
04710 {
04711 return chan->tech_pvt ? ((struct sip_pvt *) chan->tech_pvt)->callid : "";
04712 }
04713
04714
04715
04716 static int sip_sendtext(struct ast_channel *ast, const char *text)
04717 {
04718 struct sip_pvt *p = ast->tech_pvt;
04719 int debug = sip_debug_test_pvt(p);
04720
04721 if (debug)
04722 ast_verbose("Sending text %s on %s\n", text, ast->name);
04723 if (!p)
04724 return -1;
04725
04726
04727 if (!text)
04728 return 0;
04729 if (debug)
04730 ast_verbose("Really sending text %s on %s\n", text, ast->name);
04731 transmit_message_with_text(p, text);
04732 return 0;
04733 }
04734
04735
04736
04737
04738
04739
04740 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)
04741 {
04742 char port[10];
04743 char ipaddr[INET_ADDRSTRLEN];
04744 char regseconds[20];
04745 char *tablename = NULL;
04746 char str_lastms[20];
04747
04748 const char *sysname = ast_config_AST_SYSTEM_NAME;
04749 char *syslabel = NULL;
04750
04751 time_t nowtime = time(NULL) + expirey;
04752 const char *fc = fullcontact ? "fullcontact" : NULL;
04753
04754 int realtimeregs = ast_check_realtime("sipregs");
04755
04756 tablename = realtimeregs ? "sipregs" : "sippeers";
04757
04758
04759 snprintf(str_lastms, sizeof(str_lastms), "%d", lastms);
04760 snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime);
04761 ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
04762 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
04763
04764 if (ast_strlen_zero(sysname))
04765 sysname = NULL;
04766 else if (sip_cfg.rtsave_sysname)
04767 syslabel = "regserver";
04768
04769
04770
04771
04772
04773
04774
04775 if (fc) {
04776 ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
04777 "port", port, "regseconds", regseconds,
04778 deprecated_username ? "username" : "defaultuser", defaultuser,
04779 "useragent", useragent, "lastms", str_lastms,
04780 fc, fullcontact, syslabel, sysname, SENTINEL);
04781 } else {
04782 ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
04783 "port", port, "regseconds", regseconds,
04784 "useragent", useragent, "lastms", str_lastms,
04785 deprecated_username ? "username" : "defaultuser", defaultuser,
04786 syslabel, sysname, SENTINEL);
04787 }
04788 }
04789
04790
04791 static void register_peer_exten(struct sip_peer *peer, int onoff)
04792 {
04793 char multi[256];
04794 char *stringp, *ext, *context;
04795 struct pbx_find_info q = { .stacklen = 0 };
04796
04797
04798
04799
04800
04801 if (ast_strlen_zero(global_regcontext))
04802 return;
04803
04804 ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
04805 stringp = multi;
04806 while ((ext = strsep(&stringp, "&"))) {
04807 if ((context = strchr(ext, '@'))) {
04808 *context++ = '\0';
04809 if (!ast_context_find(context)) {
04810 ast_log(LOG_WARNING, "Context %s must exist in regcontext= in sip.conf!\n", context);
04811 continue;
04812 }
04813 } else {
04814 context = global_regcontext;
04815 }
04816 if (onoff) {
04817 if (!ast_exists_extension(NULL, context, ext, 1, NULL)) {
04818 ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
04819 ast_strdup(peer->name), ast_free_ptr, "SIP");
04820 }
04821 } else if (pbx_find_extension(NULL, NULL, &q, context, ext, 1, NULL, "", E_MATCH)) {
04822 ast_context_remove_extension(context, ext, 1, NULL);
04823 }
04824 }
04825 }
04826
04827
04828 static void destroy_mailbox(struct sip_mailbox *mailbox)
04829 {
04830 if (mailbox->mailbox)
04831 ast_free(mailbox->mailbox);
04832 if (mailbox->context)
04833 ast_free(mailbox->context);
04834 if (mailbox->event_sub)
04835 ast_event_unsubscribe(mailbox->event_sub);
04836 ast_free(mailbox);
04837 }
04838
04839
04840 static void clear_peer_mailboxes(struct sip_peer *peer)
04841 {
04842 struct sip_mailbox *mailbox;
04843
04844 while ((mailbox = AST_LIST_REMOVE_HEAD(&peer->mailboxes, entry)))
04845 destroy_mailbox(mailbox);
04846 }
04847
04848 static void sip_destroy_peer_fn(void *peer)
04849 {
04850 sip_destroy_peer(peer);
04851 }
04852
04853
04854 static void sip_destroy_peer(struct sip_peer *peer)
04855 {
04856 ast_debug(3, "Destroying SIP peer %s\n", peer->name);
04857 if (peer->outboundproxy)
04858 ao2_ref(peer->outboundproxy, -1);
04859 peer->outboundproxy = NULL;
04860
04861
04862 if (peer->call) {
04863 dialog_unlink_all(peer->call, TRUE, TRUE);
04864 peer->call = dialog_unref(peer->call, "peer->call is being unset");
04865 }
04866
04867
04868 if (peer->mwipvt) {
04869 dialog_unlink_all(peer->mwipvt, TRUE, TRUE);
04870 peer->mwipvt = dialog_unref(peer->mwipvt, "unreffing peer->mwipvt");
04871 }
04872
04873 if (peer->chanvars) {
04874 ast_variables_destroy(peer->chanvars);
04875 peer->chanvars = NULL;
04876 }
04877
04878 register_peer_exten(peer, FALSE);
04879 ast_free_ha(peer->ha);
04880 if (peer->selfdestruct)
04881 ast_atomic_fetchadd_int(&apeerobjs, -1);
04882 else if (peer->is_realtime) {
04883 ast_atomic_fetchadd_int(&rpeerobjs, -1);
04884 ast_debug(3, "-REALTIME- peer Destroyed. Name: %s. Realtime Peer objects: %d\n", peer->name, rpeerobjs);
04885 } else
04886 ast_atomic_fetchadd_int(&speerobjs, -1);
04887 clear_realm_authentication(peer->auth);
04888 peer->auth = NULL;
04889 if (peer->dnsmgr)
04890 ast_dnsmgr_release(peer->dnsmgr);
04891 clear_peer_mailboxes(peer);
04892
04893 if (peer->socket.tcptls_session) {
04894 ao2_ref(peer->socket.tcptls_session, -1);
04895 peer->socket.tcptls_session = NULL;
04896 }
04897
04898 ast_string_field_free_memory(peer);
04899 }
04900
04901
04902 static void update_peer(struct sip_peer *p, int expire)
04903 {
04904 int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
04905 if (sip_cfg.peer_rtupdate &&
04906 (p->is_realtime || rtcachefriends)) {
04907 realtime_update_peer(p->name, &p->addr, p->username, rtcachefriends ? p->fullcontact : NULL, p->useragent, expire, p->deprecated_username, p->lastms);
04908 }
04909 }
04910
04911 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *cfg)
04912 {
04913 struct ast_variable *var = NULL;
04914 struct ast_flags flags = {0};
04915 char *cat = NULL;
04916 const char *insecure;
04917 while ((cat = ast_category_browse(cfg, cat))) {
04918 insecure = ast_variable_retrieve(cfg, cat, "insecure");
04919 set_insecure_flags(&flags, insecure, -1);
04920 if (ast_test_flag(&flags, SIP_INSECURE_PORT)) {
04921 var = ast_category_root(cfg, cat);
04922 break;
04923 }
04924 }
04925 return var;
04926 }
04927
04928 static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername)
04929 {
04930 struct ast_variable *tmp;
04931 for (tmp = var; tmp; tmp = tmp->next) {
04932 if (!newpeername && !strcasecmp(tmp->name, "name"))
04933 newpeername = tmp->value;
04934 }
04935 return newpeername;
04936 }
04937
04938
04939
04940
04941
04942
04943
04944 static struct sip_peer *realtime_peer(const char *newpeername, struct sockaddr_in *sin, int devstate_only)
04945 {
04946 struct sip_peer *peer;
04947 struct ast_variable *var = NULL;
04948 struct ast_variable *varregs = NULL;
04949 struct ast_variable *tmp;
04950 struct ast_config *peerlist = NULL;
04951 char ipaddr[INET_ADDRSTRLEN];
04952 char portstring[6];
04953 char *cat = NULL;
04954 unsigned short portnum;
04955 int realtimeregs = ast_check_realtime("sipregs");
04956
04957
04958 if (newpeername) {
04959 if (realtimeregs)
04960 varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04961
04962 var = ast_load_realtime("sippeers", "name", newpeername, "host", "dynamic", SENTINEL);
04963 if (!var && sin)
04964 var = ast_load_realtime("sippeers", "name", newpeername, "host", ast_inet_ntoa(sin->sin_addr), SENTINEL);
04965 if (!var) {
04966 var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
04967
04968
04969
04970
04971
04972
04973 if (var && sin) {
04974 for (tmp = var; tmp; tmp = tmp->next) {
04975 if (!strcasecmp(tmp->name, "host")) {
04976 struct hostent *hp;
04977 struct ast_hostent ahp;
04978 if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || (memcmp(hp->h_addr, &sin->sin_addr, sizeof(hp->h_addr)))) {
04979
04980 ast_variables_destroy(var);
04981 var = NULL;
04982 }
04983 break;
04984 }
04985 }
04986 }
04987 }
04988 }
04989
04990 if (!var && sin) {
04991 ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
04992 portnum = ntohs(sin->sin_port);
04993 sprintf(portstring, "%u", portnum);
04994 var = ast_load_realtime("sippeers", "host", ipaddr, "port", portstring, SENTINEL);
04995 if (var) {
04996 if (realtimeregs) {
04997 newpeername = get_name_from_variable(var, newpeername);
04998 varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04999 }
05000 } else {
05001 if (realtimeregs)
05002 varregs = ast_load_realtime("sipregs", "ipaddr", ipaddr, "port", portstring, SENTINEL);
05003 else
05004 var = ast_load_realtime("sippeers", "ipaddr", ipaddr, "port", portstring, SENTINEL);
05005 if (varregs) {
05006 newpeername = get_name_from_variable(varregs, newpeername);
05007 var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
05008 }
05009 }
05010 if (!var) {
05011 peerlist = ast_load_realtime_multientry("sippeers", "host", ipaddr, SENTINEL);
05012 if (peerlist) {
05013 var = get_insecure_variable_from_config(peerlist);
05014 if(var) {
05015 if (realtimeregs) {
05016 newpeername = get_name_from_variable(var, newpeername);
05017 varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
05018 }
05019 } else {
05020 peerlist = NULL;
05021 cat = NULL;
05022 peerlist = ast_load_realtime_multientry("sippeers", "ipaddr", ipaddr, SENTINEL);
05023 if(peerlist) {
05024 var = get_insecure_variable_from_config(peerlist);
05025 if(var) {
05026 if (realtimeregs) {
05027 newpeername = get_name_from_variable(var, newpeername);
05028 varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
05029 }
05030 }
05031 }
05032 }
05033 } else {
05034 if (realtimeregs) {
05035 peerlist = ast_load_realtime_multientry("sipregs", "ipaddr", ipaddr, SENTINEL);
05036 if (peerlist) {
05037 varregs = get_insecure_variable_from_config(peerlist);
05038 if (varregs) {
05039 newpeername = get_name_from_variable(varregs, newpeername);
05040 var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
05041 }
05042 }
05043 } else {
05044 peerlist = ast_load_realtime_multientry("sippeers", "ipaddr", ipaddr, SENTINEL);
05045 if (peerlist) {
05046 var = get_insecure_variable_from_config(peerlist);
05047 if (var) {
05048 newpeername = get_name_from_variable(var, newpeername);
05049 varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
05050 }
05051 }
05052 }
05053 }
05054 }
05055 }
05056
05057 if (!var) {
05058 if (peerlist)
05059 ast_config_destroy(peerlist);
05060 return NULL;
05061 }
05062
05063 for (tmp = var; tmp; tmp = tmp->next) {
05064 if (!newpeername && !strcasecmp(tmp->name, "name")) {
05065 newpeername = tmp->value;
05066 }
05067 }
05068
05069 if (!newpeername) {
05070 ast_log(LOG_WARNING, "Cannot Determine peer name ip=%s\n", ipaddr);
05071 if(peerlist)
05072 ast_config_destroy(peerlist);
05073 else
05074 ast_variables_destroy(var);
05075 return NULL;
05076 }
05077
05078
05079
05080 peer = build_peer(newpeername, var, varregs, TRUE, devstate_only);
05081 if (!peer) {
05082 if(peerlist)
05083 ast_config_destroy(peerlist);
05084 else {
05085 ast_variables_destroy(var);
05086 ast_variables_destroy(varregs);
05087 }
05088 return NULL;
05089 }
05090
05091 ast_debug(3, "-REALTIME- loading peer from database to memory. Name: %s. Peer objects: %d\n", peer->name, rpeerobjs);
05092
05093 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && !devstate_only) {
05094
05095 ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
05096 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
05097 AST_SCHED_REPLACE_UNREF(peer->expire, sched, sip_cfg.rtautoclear * 1000, expire_register, peer,
05098 unref_peer(_data, "remove registration ref"),
05099 unref_peer(peer, "remove registration ref"),
05100 ref_peer(peer, "add registration ref"));
05101 }
05102 ao2_t_link(peers, peer, "link peer into peers table");
05103 if (peer->addr.sin_addr.s_addr) {
05104 ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
05105 }
05106 }
05107 peer->is_realtime = 1;
05108 if (peerlist)
05109 ast_config_destroy(peerlist);
05110 else {
05111 ast_variables_destroy(var);
05112 ast_variables_destroy(varregs);
05113 }
05114
05115 return peer;
05116 }
05117
05118
05119 static int find_by_name(void *obj, void *arg, void *data, int flags)
05120 {
05121 struct sip_peer *search = obj, *match = arg;
05122 int *which_objects = data;
05123
05124
05125 if (strcmp(search->name, match->name)) {
05126 return 0;
05127 }
05128
05129 switch (*which_objects) {
05130 case FINDUSERS:
05131 if (!(search->type & SIP_TYPE_USER)) {
05132 return 0;
05133 }
05134 break;
05135 case FINDPEERS:
05136 if (!(search->type & SIP_TYPE_PEER)) {
05137 return 0;
05138 }
05139 break;
05140 case FINDALLDEVICES:
05141 break;
05142 }
05143
05144 return CMP_MATCH | CMP_STOP;
05145 }
05146
05147
05148
05149
05150
05151
05152
05153
05154
05155
05156
05157
05158
05159
05160 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime, int which_objects, int devstate_only, int transport)
05161 {
05162 struct sip_peer *p = NULL;
05163 struct sip_peer tmp_peer;
05164
05165 if (peer) {
05166 ast_copy_string(tmp_peer.name, peer, sizeof(tmp_peer.name));
05167 p = ao2_t_callback_data(peers, OBJ_POINTER, find_by_name, &tmp_peer, &which_objects, "ao2_find in peers table");
05168 } else if (sin) {
05169 tmp_peer.addr.sin_addr.s_addr = sin->sin_addr.s_addr;
05170 tmp_peer.addr.sin_port = sin->sin_port;
05171 tmp_peer.flags[0].flags = 0;
05172 tmp_peer.transports = transport;
05173 p = ao2_t_find(peers_by_ip, &tmp_peer, OBJ_POINTER, "ao2_find in peers_by_ip table");
05174 if (!p) {
05175 ast_set_flag(&tmp_peer.flags[0], SIP_INSECURE_PORT);
05176 p = ao2_t_find(peers_by_ip, &tmp_peer, OBJ_POINTER, "ao2_find in peers_by_ip table 2");
05177 if (p) {
05178 return p;
05179 }
05180 }
05181 }
05182
05183 if (!p && (realtime || devstate_only)) {
05184 p = realtime_peer(peer, sin, devstate_only);
05185 if (p) {
05186 switch (which_objects) {
05187 case FINDUSERS:
05188 if (!(p->type & SIP_TYPE_USER)) {
05189 unref_peer(p, "Wrong type of realtime SIP endpoint");
05190 return NULL;
05191 }
05192 break;
05193 case FINDPEERS:
05194 if (!(p->type & SIP_TYPE_PEER)) {
05195 unref_peer(p, "Wrong type of realtime SIP endpoint");
05196 return NULL;
05197 }
05198 break;
05199 case FINDALLDEVICES:
05200 break;
05201 }
05202 }
05203 }
05204
05205 return p;
05206 }
05207
05208
05209 static void do_setnat(struct sip_pvt *p, int natflags)
05210 {
05211 const char *mode = natflags ? "On" : "Off";
05212
05213 if (p->rtp) {
05214 ast_debug(1, "Setting NAT on RTP to %s\n", mode);
05215 ast_rtp_setnat(p->rtp, natflags);
05216 }
05217 if (p->vrtp) {
05218 ast_debug(1, "Setting NAT on VRTP to %s\n", mode);
05219 ast_rtp_setnat(p->vrtp, natflags);
05220 }
05221 if (p->udptl) {
05222 ast_debug(1, "Setting NAT on UDPTL to %s\n", mode);
05223 ast_udptl_setnat(p->udptl, natflags);
05224 }
05225 if (p->trtp) {
05226 ast_debug(1, "Setting NAT on TRTP to %s\n", mode);
05227 ast_rtp_setnat(p->trtp, natflags);
05228 }
05229 }
05230
05231
05232 static void change_t38_state(struct sip_pvt *p, int state)
05233 {
05234 int old = p->t38.state;
05235 struct ast_channel *chan = p->owner;
05236 struct ast_control_t38_parameters parameters = { .request_response = 0 };
05237
05238
05239 if (old == state)
05240 return;
05241
05242 p->t38.state = state;
05243 ast_debug(2, "T38 state changed to %d on channel %s\n", p->t38.state, chan ? chan->name : "<none>");
05244
05245
05246 if (!chan)
05247 return;
05248
05249
05250 switch (state) {
05251 case T38_PEER_REINVITE:
05252 parameters = p->t38.their_parms;
05253 parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
05254 parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
05255 ast_udptl_set_tag(p->udptl, "SIP/%s", p->username);
05256 break;
05257 case T38_ENABLED:
05258 parameters = p->t38.their_parms;
05259 parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
05260 parameters.request_response = AST_T38_NEGOTIATED;
05261 ast_udptl_set_tag(p->udptl, "SIP/%s", p->username);
05262 break;
05263 case T38_DISABLED:
05264 if (old == T38_ENABLED) {
05265 parameters.request_response = AST_T38_TERMINATED;
05266 } else if (old == T38_LOCAL_REINVITE) {
05267 parameters.request_response = AST_T38_REFUSED;
05268 }
05269 break;
05270 case T38_LOCAL_REINVITE:
05271
05272 break;
05273 }
05274
05275
05276 if (parameters.request_response)
05277 ast_queue_control_data(chan, AST_CONTROL_T38_PARAMETERS, ¶meters, sizeof(parameters));
05278 }
05279
05280
05281 static void set_t38_capabilities(struct sip_pvt *p)
05282 {
05283 if (p->udptl) {
05284 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY) {
05285 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
05286 } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_FEC) {
05287 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
05288 } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL) {
05289 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
05290 }
05291 }
05292 }
05293
05294 static void copy_socket_data(struct sip_socket *to_sock, const struct sip_socket *from_sock)
05295 {
05296 if (to_sock->tcptls_session) {
05297 ao2_ref(to_sock->tcptls_session, -1);
05298 to_sock->tcptls_session = NULL;
05299 }
05300
05301 if (from_sock->tcptls_session) {
05302 ao2_ref(from_sock->tcptls_session, +1);
05303 }
05304
05305 *to_sock = *from_sock;
05306 }
05307
05308
05309
05310
05311
05312
05313
05314
05315 static int create_addr_from_peer(struct sip_pvt *dialog, struct sip_peer *peer)
05316 {
05317
05318
05319
05320
05321 if (dialog->socket.type && check_request_transport(peer, dialog))
05322 return -1;
05323 copy_socket_data(&dialog->socket, &peer->socket);
05324
05325 if ((peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr) &&
05326 (!peer->maxms || ((peer->lastms >= 0) && (peer->lastms <= peer->maxms)))) {
05327 dialog->sa = (peer->addr.sin_addr.s_addr) ? peer->addr : peer->defaddr;
05328 dialog->recv = dialog->sa;
05329 } else
05330 return -1;
05331
05332 ast_copy_flags(&dialog->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
05333 ast_copy_flags(&dialog->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
05334 dialog->capability = peer->capability;
05335 if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS) &&
05336 (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT) ||
05337 !(dialog->capability & AST_FORMAT_VIDEO_MASK)) &&
05338 dialog->vrtp) {
05339 ast_rtp_destroy(dialog->vrtp);
05340 dialog->vrtp = NULL;
05341 }
05342 if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_TEXTSUPPORT) && dialog->trtp) {
05343 ast_rtp_destroy(dialog->trtp);
05344 dialog->trtp = NULL;
05345 }
05346 dialog->prefs = peer->prefs;
05347 if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_T38SUPPORT)) {
05348
05349 if (dialog->udptl || (!dialog->udptl && (dialog->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr)))) {
05350 dialog->t38_maxdatagram = peer->t38_maxdatagram;
05351 set_t38_capabilities(dialog);
05352 } else {
05353
05354 ast_debug(1, "UDPTL creation failed on dialog.\n");
05355 ast_clear_flag(&dialog->flags[1], SIP_PAGE2_T38SUPPORT);
05356 }
05357 } else if (dialog->udptl) {
05358 ast_udptl_destroy(dialog->udptl);
05359 dialog->udptl = NULL;
05360 }
05361 do_setnat(dialog, ast_test_flag(&dialog->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
05362
05363 if (dialog->rtp) {
05364 ast_rtp_setdtmf(dialog->rtp, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
05365 ast_rtp_setdtmfcompensate(dialog->rtp, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
05366 ast_rtp_set_rtptimeout(dialog->rtp, peer->rtptimeout);
05367 ast_rtp_set_rtpholdtimeout(dialog->rtp, peer->rtpholdtimeout);
05368 ast_rtp_set_rtpkeepalive(dialog->rtp, peer->rtpkeepalive);
05369
05370 ast_rtp_codec_setpref(dialog->rtp, &dialog->prefs);
05371 dialog->autoframing = peer->autoframing;
05372 }
05373 if (dialog->vrtp) {
05374 ast_rtp_setdtmf(dialog->vrtp, 0);
05375 ast_rtp_setdtmfcompensate(dialog->vrtp, 0);
05376 ast_rtp_set_rtptimeout(dialog->vrtp, peer->rtptimeout);
05377 ast_rtp_set_rtpholdtimeout(dialog->vrtp, peer->rtpholdtimeout);
05378 ast_rtp_set_rtpkeepalive(dialog->vrtp, peer->rtpkeepalive);
05379 }
05380 if (dialog->trtp) {
05381 ast_rtp_setdtmf(dialog->trtp, 0);
05382 ast_rtp_setdtmfcompensate(dialog->trtp, 0);
05383 ast_rtp_set_rtptimeout(dialog->trtp, peer->rtptimeout);
05384 ast_rtp_set_rtpholdtimeout(dialog->trtp, peer->rtpholdtimeout);
05385 ast_rtp_set_rtpkeepalive(dialog->trtp, peer->rtpkeepalive);
05386 }
05387
05388 ast_string_field_set(dialog, peername, peer->name);
05389 ast_string_field_set(dialog, authname, peer->username);
05390 ast_string_field_set(dialog, username, peer->username);
05391 ast_string_field_set(dialog, peersecret, peer->secret);
05392 ast_string_field_set(dialog, peermd5secret, peer->md5secret);
05393 ast_string_field_set(dialog, mohsuggest, peer->mohsuggest);
05394 ast_string_field_set(dialog, mohinterpret, peer->mohinterpret);
05395 ast_string_field_set(dialog, tohost, peer->tohost);
05396 ast_string_field_set(dialog, fullcontact, peer->fullcontact);
05397 ast_string_field_set(dialog, context, peer->context);
05398 ast_string_field_set(dialog, parkinglot, peer->parkinglot);
05399 ref_proxy(dialog, obproxy_get(dialog, peer));
05400 dialog->callgroup = peer->callgroup;
05401 dialog->pickupgroup = peer->pickupgroup;
05402 dialog->allowtransfer = peer->allowtransfer;
05403 dialog->jointnoncodeccapability = dialog->noncodeccapability;
05404 dialog->rtptimeout = peer->rtptimeout;
05405 dialog->peerauth = peer->auth;
05406 dialog->maxcallbitrate = peer->maxcallbitrate;
05407 if (ast_strlen_zero(dialog->tohost))
05408 ast_string_field_set(dialog, tohost, ast_inet_ntoa(dialog->sa.sin_addr));
05409 if (!ast_strlen_zero(peer->fromdomain)) {
05410 ast_string_field_set(dialog, fromdomain, peer->fromdomain);
05411 if (!dialog->initreq.headers) {
05412 char *c;
05413 char *tmpcall = ast_strdupa(dialog->callid);
05414
05415 c = strchr(tmpcall, '@');
05416 if (c) {
05417 *c = '\0';
05418 ao2_t_unlink(dialogs, dialog, "About to change the callid -- remove the old name");
05419 ast_string_field_build(dialog, callid, "%s@%s", tmpcall, peer->fromdomain);
05420 ao2_t_link(dialogs, dialog, "New dialog callid -- inserted back into table");
05421 }
05422 }
05423 }
05424 if (!ast_strlen_zero(peer->fromuser))
05425 ast_string_field_set(dialog, fromuser, peer->fromuser);
05426 if (!ast_strlen_zero(peer->language))
05427 ast_string_field_set(dialog, language, peer->language);
05428
05429
05430
05431
05432 if (peer->maxms && peer->lastms)
05433 dialog->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
05434 else
05435 dialog->timer_t1 = peer->timer_t1;
05436
05437
05438
05439 if (peer->timer_b)
05440 dialog->timer_b = peer->timer_b;
05441 else
05442 dialog->timer_b = 64 * dialog->timer_t1;
05443
05444 if ((ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
05445 (ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
05446 dialog->noncodeccapability |= AST_RTP_DTMF;
05447 else
05448 dialog->noncodeccapability &= ~AST_RTP_DTMF;
05449 if (peer->call_limit)
05450 ast_set_flag(&dialog->flags[0], SIP_CALL_LIMIT);
05451 if (!dialog->portinuri)
05452 dialog->portinuri = peer->portinuri;
05453
05454 dialog->chanvars = copy_vars(peer->chanvars);
05455
05456 return 0;
05457 }
05458
05459
05460
05461
05462 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct sockaddr_in *sin, int newdialog)
05463 {
05464 struct hostent *hp;
05465 struct ast_hostent ahp;
05466 struct sip_peer *peer;
05467 char *port;
05468 int portno = 0;
05469 char host[MAXHOSTNAMELEN], *hostn;
05470 char peername[256];
05471 int srv_ret = 0;
05472
05473 ast_copy_string(peername, opeer, sizeof(peername));
05474 port = strchr(peername, ':');
05475 if (port) {
05476 *port++ = '\0';
05477 dialog->portinuri = 1;
05478 }
05479 dialog->sa.sin_family = AF_INET;
05480 dialog->timer_t1 = global_t1;
05481 dialog->timer_b = global_timer_b;
05482 peer = find_peer(peername, NULL, TRUE, FINDPEERS, FALSE, 0);
05483
05484 if (peer) {
05485 int res;
05486 if (newdialog) {
05487 set_socket_transport(&dialog->socket, 0);
05488 }
05489 res = create_addr_from_peer(dialog, peer);
05490 if (!ast_strlen_zero(port)) {
05491 if ((portno = atoi(port))) {
05492 dialog->sa.sin_port = dialog->recv.sin_port = htons(portno);
05493 }
05494 }
05495 unref_peer(peer, "create_addr: unref peer from find_peer hashtab lookup");
05496 return res;
05497 }
05498
05499 do_setnat(dialog, ast_test_flag(&dialog->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
05500
05501 ast_string_field_set(dialog, tohost, peername);
05502
05503
05504 ref_proxy(dialog, obproxy_get(dialog, NULL));
05505
05506 if (sin) {
05507
05508 memcpy(&dialog->sa.sin_addr, &sin->sin_addr, sizeof(dialog->sa.sin_addr));
05509 if (!sin->sin_port) {
05510 portno = port_str2int(port, (dialog->socket.type == SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT);
05511 } else {
05512 portno = ntohs(sin->sin_port);
05513 }
05514 } else {
05515
05516
05517
05518
05519
05520
05521 hostn = peername;
05522
05523
05524
05525 if (!port && sip_cfg.srvlookup) {
05526 char service[MAXHOSTNAMELEN];
05527 int tportno;
05528 snprintf(service, sizeof(service), "_%s._%s.%s",
05529 get_srv_service(dialog->socket.type),
05530 get_srv_protocol(dialog->socket.type), peername);
05531 srv_ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
05532 if (srv_ret > 0) {
05533 hostn = host;
05534 portno = tportno;
05535 }
05536 }
05537 if (!portno)
05538 portno = port_str2int(port, (dialog->socket.type == SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT);
05539 hp = ast_gethostbyname(hostn, &ahp);
05540 if (!hp) {
05541 ast_log(LOG_WARNING, "No such host: %s\n", peername);
05542 return -1;
05543 }
05544 memcpy(&dialog->sa.sin_addr, hp->h_addr, sizeof(dialog->sa.sin_addr));
05545 }
05546
05547 if (!dialog->socket.type)
05548 set_socket_transport(&dialog->socket, SIP_TRANSPORT_UDP);
05549 if (!dialog->socket.port)
05550 dialog->socket.port = bindaddr.sin_port;
05551 dialog->sa.sin_port = htons(portno);
05552 dialog->recv = dialog->sa;
05553 return 0;
05554 }
05555
05556
05557
05558
05559 static int auto_congest(const void *arg)
05560 {
05561 struct sip_pvt *p = (struct sip_pvt *)arg;
05562
05563 sip_pvt_lock(p);
05564 p->initid = -1;
05565 if (p->owner) {
05566
05567 if (!ast_channel_trylock(p->owner)) {
05568 append_history(p, "Cong", "Auto-congesting (timer)");
05569 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
05570 ast_channel_unlock(p->owner);
05571 }
05572
05573
05574 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
05575 }
05576 sip_pvt_unlock(p);
05577 dialog_unref(p, "unreffing arg passed into auto_congest callback (p->initid)");
05578 return 0;
05579 }
05580
05581
05582
05583
05584 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
05585 {
05586 int res;
05587 struct sip_pvt *p = ast->tech_pvt;
05588 struct varshead *headp;
05589 struct ast_var_t *current;
05590 const char *referer = NULL;
05591
05592 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
05593 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
05594 return -1;
05595 }
05596
05597
05598 headp=&ast->varshead;
05599 AST_LIST_TRAVERSE(headp, current, entries) {
05600
05601 if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
05602 p->options->vxml_url = ast_var_value(current);
05603 } else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
05604 p->options->uri_options = ast_var_value(current);
05605 } else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
05606
05607 p->options->addsipheaders = 1;
05608 } else if (!strcasecmp(ast_var_name(current), "SIPFROMDOMAIN")) {
05609 ast_string_field_set(p, fromdomain, ast_var_value(current));
05610 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER")) {
05611
05612 p->options->transfer = 1;
05613 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REFERER")) {
05614
05615 referer = ast_var_value(current);
05616 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REPLACES")) {
05617
05618 p->options->replaces = ast_var_value(current);
05619 }
05620 }
05621
05622 res = 0;
05623 ast_set_flag(&p->flags[0], SIP_OUTGOING);
05624
05625
05626
05627
05628 ast_clear_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_T38);
05629
05630 if (p->options->transfer) {
05631 char buf[SIPBUFSIZE/2];
05632
05633 if (referer) {
05634 if (sipdebug)
05635 ast_debug(3, "Call for %s transfered by %s\n", p->username, referer);
05636 snprintf(buf, sizeof(buf)-1, "-> %s (via %s)", p->cid_name, referer);
05637 } else
05638 snprintf(buf, sizeof(buf)-1, "-> %s", p->cid_name);
05639 ast_string_field_set(p, cid_name, buf);
05640 }
05641 ast_debug(1, "Outgoing Call for %s\n", p->username);
05642
05643 res = update_call_counter(p, INC_CALL_RINGING);
05644
05645 if (res == -1) {
05646 ast->hangupcause = AST_CAUSE_USER_BUSY;
05647 return res;
05648 }
05649 p->callingpres = ast->cid.cid_pres;
05650 p->jointcapability = ast_translate_available_formats(p->capability, p->prefcodec);
05651 p->jointnoncodeccapability = p->noncodeccapability;
05652
05653
05654 if (!(p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
05655 ast_log(LOG_WARNING, "No audio format found to offer. Cancelling call to %s\n", p->username);
05656 res = -1;
05657 } else {
05658 int xmitres;
05659
05660 xmitres = transmit_invite(p, SIP_INVITE, 1, 2);
05661 if (xmitres == XMIT_ERROR)
05662 return -1;
05663 p->invitestate = INV_CALLING;
05664
05665
05666 AST_SCHED_REPLACE_UNREF(p->initid, sched, p->timer_b, auto_congest, p,
05667 dialog_unref(_data, "dialog ptr dec when SCHED_REPLACE del op succeeded"),
05668 dialog_unref(p, "dialog ptr dec when SCHED_REPLACE add failed"),
05669 dialog_ref(p, "dialog ptr inc when SCHED_REPLACE add succeeded") );
05670 }
05671 return res;
05672 }
05673
05674
05675
05676 static void sip_registry_destroy(struct sip_registry *reg)
05677 {
05678
05679 ast_debug(3, "Destroying registry entry for %s@%s\n", reg->username, reg->hostname);
05680
05681 if (reg->call) {
05682
05683
05684 reg->call->registry = registry_unref(reg->call->registry, "destroy reg->call->registry");
05685 ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", reg->username, reg->hostname);
05686 dialog_unlink_all(reg->call, TRUE, TRUE);
05687 reg->call = dialog_unref(reg->call, "unref reg->call");
05688
05689 }
05690 AST_SCHED_DEL(sched, reg->expire);
05691 AST_SCHED_DEL(sched, reg->timeout);
05692
05693 ast_string_field_free_memory(reg);
05694 ast_atomic_fetchadd_int(®objs, -1);
05695 ast_dnsmgr_release(reg->dnsmgr);
05696 ast_free(reg);
05697 }
05698
05699
05700 static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi)
05701 {
05702 if (mwi->call) {
05703 mwi->call->mwi = NULL;
05704 sip_destroy(mwi->call);
05705 }
05706
05707 AST_SCHED_DEL(sched, mwi->resub);
05708 ast_string_field_free_memory(mwi);
05709 ast_dnsmgr_release(mwi->dnsmgr);
05710 ast_free(mwi);
05711 }
05712
05713
05714 static void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist)
05715 {
05716 struct sip_request *req;
05717
05718 if (p->stimer) {
05719 ast_free(p->stimer);
05720 p->stimer = NULL;
05721 }
05722
05723 if (sip_debug_test_pvt(p))
05724 ast_verbose("Really destroying SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
05725
05726 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
05727 update_call_counter(p, DEC_CALL_LIMIT);
05728 ast_debug(2, "This call did not properly clean up call limits. Call ID %s\n", p->callid);
05729 }
05730
05731
05732 if (p->owner) {
05733 if (lockowner)
05734 ast_channel_lock(p->owner);
05735 if (option_debug)
05736 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
05737 p->owner->tech_pvt = NULL;
05738
05739 p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
05740 if (lockowner)
05741 ast_channel_unlock(p->owner);
05742
05743 usleep(1);
05744 }
05745
05746
05747 if (p->relatedpeer && p->relatedpeer->mwipvt)
05748 p->relatedpeer->mwipvt = dialog_unref(p->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
05749 if (p->relatedpeer && p->relatedpeer->call == p)
05750 p->relatedpeer->call = dialog_unref(p->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
05751
05752 if (p->relatedpeer)
05753 p->relatedpeer = unref_peer(p->relatedpeer,"unsetting a dialog relatedpeer field in sip_destroy");
05754
05755 if (p->registry) {
05756 if (p->registry->call == p)
05757 p->registry->call = dialog_unref(p->registry->call, "nulling out the registry's call dialog field in unlink_all");
05758 p->registry = registry_unref(p->registry, "delete p->registry");
05759 }
05760
05761 if (p->mwi) {
05762 p->mwi->call = NULL;
05763 }
05764
05765 if (dumphistory)
05766 sip_dump_history(p);
05767
05768 if (p->options)
05769 ast_free(p->options);
05770
05771 if (p->notify_headers) {
05772 ast_variables_destroy(p->notify_headers);
05773 p->notify_headers = NULL;
05774 }
05775 if (p->rtp) {
05776 ast_rtp_destroy(p->rtp);
05777 }
05778 if (p->vrtp) {
05779 ast_rtp_destroy(p->vrtp);
05780 }
05781 if (p->trtp) {
05782 while (ast_rtp_get_bridged(p->trtp))
05783 usleep(1);
05784 ast_rtp_destroy(p->trtp);
05785 }
05786 if (p->udptl)
05787 ast_udptl_destroy(p->udptl);
05788 if (p->refer)
05789 ast_free(p->refer);
05790 if (p->route) {
05791 free_old_route(p->route);
05792 p->route = NULL;
05793 }
05794 deinit_req(&p->initreq);
05795
05796
05797 if (p->stimer) {
05798 p->stimer->quit_flag = 1;
05799 if (p->stimer->st_active == TRUE && p->stimer->st_schedid > -1) {
05800 AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
05801 dialog_unref(p, "removing session timer ref"));
05802 }
05803 ast_free(p->stimer);
05804 p->stimer = NULL;
05805 }
05806
05807
05808 if (p->history) {
05809 struct sip_history *hist;
05810 while ( (hist = AST_LIST_REMOVE_HEAD(p->history, list)) ) {
05811 ast_free(hist);
05812 p->history_entries--;
05813 }
05814 ast_free(p->history);
05815 p->history = NULL;
05816 }
05817
05818 while ((req = AST_LIST_REMOVE_HEAD(&p->request_queue, next))) {
05819 ast_free(req);
05820 }
05821
05822 if (p->chanvars) {
05823 ast_variables_destroy(p->chanvars);
05824 p->chanvars = NULL;
05825 }
05826
05827 ast_string_field_free_memory(p);
05828
05829 if (p->socket.tcptls_session) {
05830 ao2_ref(p->socket.tcptls_session, -1);
05831 p->socket.tcptls_session = NULL;
05832 }
05833 }
05834
05835
05836
05837
05838
05839
05840
05841
05842
05843
05844
05845
05846
05847
05848
05849 static int update_call_counter(struct sip_pvt *fup, int event)
05850 {
05851 char name[256];
05852 int *inuse = NULL, *call_limit = NULL, *inringing = NULL;
05853 int outgoing = fup->outgoing_call;
05854 struct sip_peer *p = NULL;
05855
05856 ast_debug(3, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
05857
05858
05859
05860
05861 if (!ast_test_flag(&fup->flags[0], SIP_CALL_LIMIT) && !ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD))
05862 return 0;
05863
05864 ast_copy_string(name, fup->username, sizeof(name));
05865
05866
05867 if ((p = find_peer(ast_strlen_zero(fup->peername) ? name : fup->peername, NULL, TRUE, FINDALLDEVICES, FALSE, 0))) {
05868 inuse = &p->inUse;
05869 call_limit = &p->call_limit;
05870 inringing = &p->inRinging;
05871 ast_copy_string(name, fup->peername, sizeof(name));
05872 }
05873 if (!p) {
05874 ast_debug(2, "%s is not a local device, no call limit\n", name);
05875 return 0;
05876 }
05877
05878 switch(event) {
05879
05880 case DEC_CALL_LIMIT:
05881
05882 if (inuse) {
05883 sip_pvt_lock(fup);
05884 ao2_lock(p);
05885 if (*inuse > 0) {
05886 if (ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
05887 (*inuse)--;
05888 ast_clear_flag(&fup->flags[0], SIP_INC_COUNT);
05889 }
05890 } else {
05891 *inuse = 0;
05892 }
05893 ao2_unlock(p);
05894 sip_pvt_unlock(fup);
05895 }
05896
05897
05898 if (inringing) {
05899 sip_pvt_lock(fup);
05900 ao2_lock(p);
05901 if (*inringing > 0) {
05902 if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
05903 (*inringing)--;
05904 ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
05905 }
05906 } else {
05907 *inringing = 0;
05908 }
05909 ao2_unlock(p);
05910 sip_pvt_unlock(fup);
05911 }
05912
05913
05914 sip_pvt_lock(fup);
05915 ao2_lock(p);
05916 if (ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD) && sip_cfg.notifyhold) {
05917 ast_clear_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD);
05918 ao2_unlock(p);
05919 sip_pvt_unlock(fup);
05920 sip_peer_hold(fup, FALSE);
05921 } else {
05922 ao2_unlock(p);
05923 sip_pvt_unlock(fup);
05924 }
05925 if (sipdebug)
05926 ast_debug(2, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
05927 break;
05928
05929 case INC_CALL_RINGING:
05930 case INC_CALL_LIMIT:
05931
05932 if (*call_limit > 0 ) {
05933 if (*inuse >= *call_limit) {
05934 ast_log(LOG_NOTICE, "Call %s %s '%s' rejected due to usage limit of %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
05935 unref_peer(p, "update_call_counter: unref peer p, call limit exceeded");
05936 return -1;
05937 }
05938 }
05939 if (inringing && (event == INC_CALL_RINGING)) {
05940 sip_pvt_lock(fup);
05941 ao2_lock(p);
05942 if (!ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
05943 (*inringing)++;
05944 ast_set_flag(&fup->flags[0], SIP_INC_RINGING);
05945 }
05946 ao2_unlock(p);
05947 sip_pvt_unlock(fup);
05948 }
05949 if (inuse) {
05950 sip_pvt_lock(fup);
05951 ao2_lock(p);
05952 if (!ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
05953 (*inuse)++;
05954 ast_set_flag(&fup->flags[0], SIP_INC_COUNT);
05955 }
05956 ao2_unlock(p);
05957 sip_pvt_unlock(fup);
05958 }
05959 if (sipdebug) {
05960 ast_debug(2, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", "peer", name, *inuse, *call_limit);
05961 }
05962 break;
05963
05964 case DEC_CALL_RINGING:
05965 if (inringing) {
05966 sip_pvt_lock(fup);
05967 ao2_lock(p);
05968 if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
05969 if (*inringing > 0) {
05970 (*inringing)--;
05971 }
05972 ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
05973 }
05974 ao2_unlock(p);
05975 sip_pvt_unlock(fup);
05976 }
05977 break;
05978
05979 default:
05980 ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
05981 }
05982
05983 if (p) {
05984 ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", p->name);
05985 unref_peer(p, "update_call_counter: unref_peer from call counter");
05986 }
05987 return 0;
05988 }
05989
05990
05991 static void sip_destroy_fn(void *p)
05992 {
05993 sip_destroy(p);
05994 }
05995
05996
05997
05998
05999
06000
06001 static struct sip_pvt * sip_destroy(struct sip_pvt *p)
06002 {
06003 ast_debug(3, "Destroying SIP dialog %s\n", p->callid);
06004 __sip_destroy(p, TRUE, TRUE);
06005 return NULL;
06006 }
06007
06008
06009 static int hangup_sip2cause(int cause)
06010 {
06011
06012
06013 switch(cause) {
06014 case 401:
06015 return AST_CAUSE_CALL_REJECTED;
06016 case 403:
06017 return AST_CAUSE_CALL_REJECTED;
06018 case 404:
06019 return AST_CAUSE_UNALLOCATED;
06020 case 405:
06021 return AST_CAUSE_INTERWORKING;
06022 case 407:
06023 return AST_CAUSE_CALL_REJECTED;
06024 case 408:
06025 return AST_CAUSE_NO_USER_RESPONSE;
06026 case 409:
06027 return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
06028 case 410:
06029 return AST_CAUSE_NUMBER_CHANGED;
06030 case 411:
06031 return AST_CAUSE_INTERWORKING;
06032 case 413:
06033 return AST_CAUSE_INTERWORKING;
06034 case 414:
06035 return AST_CAUSE_INTERWORKING;
06036 case 415:
06037 return AST_CAUSE_INTERWORKING;
06038 case 420:
06039 return AST_CAUSE_NO_ROUTE_DESTINATION;
06040 case 480:
06041 return AST_CAUSE_NO_ANSWER;
06042 case 481:
06043 return AST_CAUSE_INTERWORKING;
06044 case 482:
06045 return AST_CAUSE_INTERWORKING;
06046 case 483:
06047 return AST_CAUSE_NO_ANSWER;
06048 case 484:
06049 return AST_CAUSE_INVALID_NUMBER_FORMAT;
06050 case 485:
06051 return AST_CAUSE_UNALLOCATED;
06052 case 486:
06053 return AST_CAUSE_BUSY;
06054 case 487:
06055 return AST_CAUSE_INTERWORKING;
06056 case 488:
06057 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
06058 case 491:
06059 return AST_CAUSE_INTERWORKING;
06060 case 493:
06061 return AST_CAUSE_INTERWORKING;
06062 case 500:
06063 return AST_CAUSE_FAILURE;
06064 case 501:
06065 return AST_CAUSE_FACILITY_REJECTED;
06066 case 502:
06067 return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
06068 case 503:
06069 return AST_CAUSE_CONGESTION;
06070 case 504:
06071 return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
06072 case 505:
06073 return AST_CAUSE_INTERWORKING;
06074 case 600:
06075 return AST_CAUSE_USER_BUSY;
06076 case 603:
06077 return AST_CAUSE_CALL_REJECTED;
06078 case 604:
06079 return AST_CAUSE_UNALLOCATED;
06080 case 606:
06081 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
06082 default:
06083 return AST_CAUSE_NORMAL;
06084 }
06085
06086 return 0;
06087 }
06088
06089
06090
06091
06092
06093
06094
06095
06096
06097
06098
06099
06100
06101
06102
06103
06104
06105
06106
06107
06108
06109
06110
06111
06112
06113
06114
06115
06116
06117
06118
06119
06120
06121 static const char *hangup_cause2sip(int cause)
06122 {
06123 switch (cause) {
06124 case AST_CAUSE_UNALLOCATED:
06125 case AST_CAUSE_NO_ROUTE_DESTINATION:
06126 case AST_CAUSE_NO_ROUTE_TRANSIT_NET:
06127 return "404 Not Found";
06128 case AST_CAUSE_CONGESTION:
06129 case AST_CAUSE_SWITCH_CONGESTION:
06130 return "503 Service Unavailable";
06131 case AST_CAUSE_NO_USER_RESPONSE:
06132 return "408 Request Timeout";
06133 case AST_CAUSE_NO_ANSWER:
06134 case AST_CAUSE_UNREGISTERED:
06135 return "480 Temporarily unavailable";
06136 case AST_CAUSE_CALL_REJECTED:
06137 return "403 Forbidden";
06138 case AST_CAUSE_NUMBER_CHANGED:
06139 return "410 Gone";
06140 case AST_CAUSE_NORMAL_UNSPECIFIED:
06141 return "480 Temporarily unavailable";
06142 case AST_CAUSE_INVALID_NUMBER_FORMAT:
06143 return "484 Address incomplete";
06144 case AST_CAUSE_USER_BUSY:
06145 return "486 Busy here";
06146 case AST_CAUSE_FAILURE:
06147 return "500 Server internal failure";
06148 case AST_CAUSE_FACILITY_REJECTED:
06149 return "501 Not Implemented";
06150 case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
06151 return "503 Service Unavailable";
06152
06153 case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
06154 return "502 Bad Gateway";
06155 case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL:
06156 return "488 Not Acceptable Here";
06157
06158 case AST_CAUSE_NOTDEFINED:
06159 default:
06160 ast_debug(1, "AST hangup cause %d (no match found in SIP)\n", cause);
06161 return NULL;
06162 }
06163
06164
06165 return 0;
06166 }
06167
06168
06169
06170
06171 static int sip_hangup(struct ast_channel *ast)
06172 {
06173 struct sip_pvt *p = ast->tech_pvt;
06174 int needcancel = FALSE;
06175 int needdestroy = 0;
06176 struct ast_channel *oldowner = ast;
06177
06178 if (!p) {
06179 ast_debug(1, "Asked to hangup channel that was not connected\n");
06180 return 0;
06181 }
06182 if (ast_test_flag(ast, AST_FLAG_ANSWERED_ELSEWHERE) || ast->hangupcause == AST_CAUSE_ANSWERED_ELSEWHERE) {
06183 ast_debug(1, "This call was answered elsewhere");
06184 if (ast->hangupcause == AST_CAUSE_ANSWERED_ELSEWHERE) {
06185 ast_debug(1, "####### It's the cause code, buddy. The cause code!!!\n");
06186 }
06187 append_history(p, "Cancel", "Call answered elsewhere");
06188 p->answered_elsewhere = TRUE;
06189 }
06190
06191
06192 if (p->owner)
06193 p->hangupcause = p->owner->hangupcause;
06194
06195 if (ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
06196 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
06197 if (sipdebug)
06198 ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
06199 update_call_counter(p, DEC_CALL_LIMIT);
06200 }
06201 ast_debug(4, "SIP Transfer: Not hanging up right now... Rescheduling hangup for %s.\n", p->callid);
06202 if (p->autokillid > -1 && sip_cancel_destroy(p))
06203 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
06204 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06205 ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
06206 p->needdestroy = 0;
06207 p->owner->tech_pvt = dialog_unref(p->owner->tech_pvt, "unref p->owner->tech_pvt");
06208 sip_pvt_lock(p);
06209 p->owner = NULL;
06210 sip_pvt_unlock(p);
06211 ast_module_unref(ast_module_info->self);
06212 return 0;
06213 }
06214
06215 if (ast_test_flag(ast, AST_FLAG_ZOMBIE)) {
06216 if (p->refer)
06217 ast_debug(1, "SIP Transfer: Hanging up Zombie channel %s after transfer ... Call-ID: %s\n", ast->name, p->callid);
06218 else
06219 ast_debug(1, "Hanging up zombie call. Be scared.\n");
06220 } else
06221 ast_debug(1, "Hangup call %s, SIP callid %s\n", ast->name, p->callid);
06222
06223 sip_pvt_lock(p);
06224 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
06225 if (sipdebug)
06226 ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
06227 update_call_counter(p, DEC_CALL_LIMIT);
06228 }
06229
06230
06231 if (p->owner != ast) {
06232 ast_log(LOG_WARNING, "Huh? We aren't the owner? Can't hangup call.\n");
06233 sip_pvt_unlock(p);
06234 return 0;
06235 }
06236
06237
06238 if (p->invitestate < INV_COMPLETED && p->owner->_state != AST_STATE_UP) {
06239 needcancel = TRUE;
06240 ast_debug(4, "Hanging up channel in state %s (not UP)\n", ast_state2str(ast->_state));
06241 }
06242
06243 stop_media_flows(p);
06244
06245 append_history(p, needcancel ? "Cancel" : "Hangup", "Cause %s", p->owner ? ast_cause2str(p->hangupcause) : "Unknown");
06246
06247
06248 if (p->dsp)
06249 ast_dsp_free(p->dsp);
06250
06251 p->owner = NULL;
06252 ast->tech_pvt = dialog_unref(ast->tech_pvt, "unref ast->tech_pvt");
06253
06254 ast_module_unref(ast_module_info->self);
06255
06256
06257
06258
06259
06260
06261 if (p->alreadygone)
06262 needdestroy = 1;
06263 else if (p->invitestate != INV_CALLING)
06264 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06265
06266
06267 if (!p->alreadygone && p->initreq.data && !ast_strlen_zero(p->initreq.data->str)) {
06268 if (needcancel) {
06269 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06270
06271
06272 if (p->invitestate == INV_CALLING) {
06273
06274 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
06275
06276 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06277 append_history(p, "DELAY", "Not sending cancel, waiting for timeout");
06278 } else {
06279 struct sip_pkt *cur;
06280
06281 for (cur = p->packets; cur; cur = cur->next) {
06282 __sip_semi_ack(p, cur->seqno, cur->is_resp, cur->method ? cur->method : find_sip_method(cur->data->str));
06283 }
06284 p->invitestate = INV_CANCELLED;
06285
06286 transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
06287
06288
06289 needdestroy = 0;
06290 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06291 }
06292 } else {
06293 const char *res;
06294 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"));
06295 if (p->hangupcause && (res = hangup_cause2sip(p->hangupcause)))
06296 transmit_response_reliable(p, res, &p->initreq);
06297 else
06298 transmit_response_reliable(p, "603 Declined", &p->initreq);
06299 p->invitestate = INV_TERMINATED;
06300 }
06301 } else {
06302 if (p->stimer->st_active == TRUE) {
06303 stop_session_timer(p);
06304 }
06305
06306 if (!p->pendinginvite) {
06307 struct ast_channel *bridge = ast_bridged_channel(oldowner);
06308 char *audioqos = "";
06309 char *videoqos = "";
06310 char *textqos = "";
06311
06312
06313
06314
06315 while (bridge && ast_channel_trylock(bridge)) {
06316 sip_pvt_unlock(p);
06317 do {
06318
06319 CHANNEL_DEADLOCK_AVOIDANCE(oldowner);
06320 } while (sip_pvt_trylock(p));
06321 bridge = ast_bridged_channel(oldowner);
06322 }
06323
06324 if (p->rtp)
06325 ast_rtp_set_vars(oldowner, p->rtp);
06326
06327 if (bridge) {
06328 struct sip_pvt *q = bridge->tech_pvt;
06329
06330 if (IS_SIP_TECH(bridge->tech) && q && q->rtp)
06331 ast_rtp_set_vars(bridge, q->rtp);
06332 ast_channel_unlock(bridge);
06333 }
06334
06335 if (p->vrtp)
06336 videoqos = ast_rtp_get_quality(p->vrtp, NULL, RTPQOS_SUMMARY);
06337 if (p->trtp)
06338 textqos = ast_rtp_get_quality(p->trtp, NULL, RTPQOS_SUMMARY);
06339
06340 if (oldowner->_state == AST_STATE_UP) {
06341 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
06342 }
06343
06344
06345 if (p->do_history) {
06346 if (p->rtp)
06347 append_history(p, "RTCPaudio", "Quality:%s", audioqos);
06348 if (p->vrtp)
06349 append_history(p, "RTCPvideo", "Quality:%s", videoqos);
06350 if (p->trtp)
06351 append_history(p, "RTCPtext", "Quality:%s", textqos);
06352 }
06353 if (p->rtp && oldowner)
06354 pbx_builtin_setvar_helper(oldowner, "RTPAUDIOQOS", audioqos);
06355 if (p->vrtp && oldowner)
06356 pbx_builtin_setvar_helper(oldowner, "RTPVIDEOQOS", videoqos);
06357 if (p->trtp && oldowner)
06358 pbx_builtin_setvar_helper(oldowner, "RTPTEXTQOS", textqos);
06359 } else {
06360
06361
06362 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
06363 ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);
06364 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"));
06365 if (sip_cancel_destroy(p))
06366 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
06367 }
06368 }
06369 }
06370 if (needdestroy) {
06371 pvt_set_needdestroy(p, "hangup");
06372 }
06373 sip_pvt_unlock(p);
06374 return 0;
06375 }
06376
06377
06378 static void try_suggested_sip_codec(struct sip_pvt *p)
06379 {
06380 int fmt;
06381 const char *codec;
06382
06383 codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC");
06384 if (!codec)
06385 return;
06386
06387 fmt = ast_getformatbyname(codec);
06388 if (fmt) {
06389 ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC} variable\n", codec);
06390 if (p->jointcapability & fmt) {
06391 p->jointcapability &= fmt;
06392 p->capability &= fmt;
06393 } else
06394 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
06395 } else
06396 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n", codec);
06397 return;
06398 }
06399
06400
06401
06402 static int sip_answer(struct ast_channel *ast)
06403 {
06404 int res = 0;
06405 struct sip_pvt *p = ast->tech_pvt;
06406
06407 sip_pvt_lock(p);
06408 if (ast->_state != AST_STATE_UP) {
06409 try_suggested_sip_codec(p);
06410
06411 ast_setstate(ast, AST_STATE_UP);
06412 ast_debug(1, "SIP answering channel: %s\n", ast->name);
06413 ast_rtp_new_source(p->rtp);
06414 res = transmit_response_with_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL, FALSE);
06415 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
06416 }
06417 sip_pvt_unlock(p);
06418 return res;
06419 }
06420
06421
06422 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
06423 {
06424 struct sip_pvt *p = ast->tech_pvt;
06425 int res = 0;
06426
06427 switch (frame->frametype) {
06428 case AST_FRAME_VOICE:
06429 if (!(frame->subclass & ast->nativeformats)) {
06430 char s1[512], s2[512], s3[512];
06431 ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %s(%d) read/write = %s(%d)/%s(%d)\n",
06432 frame->subclass,
06433 ast_getformatname_multiple(s1, sizeof(s1) - 1, ast->nativeformats & AST_FORMAT_AUDIO_MASK),
06434 ast->nativeformats & AST_FORMAT_AUDIO_MASK,
06435 ast_getformatname_multiple(s2, sizeof(s2) - 1, ast->readformat),
06436 ast->readformat,
06437 ast_getformatname_multiple(s3, sizeof(s3) - 1, ast->writeformat),
06438 ast->writeformat);
06439 return 0;
06440 }
06441 if (p) {
06442 sip_pvt_lock(p);
06443 if (p->rtp) {
06444
06445 if ((ast->_state != AST_STATE_UP) &&
06446 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06447 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06448 ast_rtp_new_source(p->rtp);
06449 if (!global_prematuremediafilter) {
06450 p->invitestate = INV_EARLY_MEDIA;
06451 transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06452 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06453 }
06454 } else if (p->t38.state == T38_ENABLED) {
06455
06456 } else {
06457 p->lastrtptx = time(NULL);
06458 res = ast_rtp_write(p->rtp, frame);
06459 }
06460 }
06461 sip_pvt_unlock(p);
06462 }
06463 break;
06464 case AST_FRAME_VIDEO:
06465 if (p) {
06466 sip_pvt_lock(p);
06467 if (p->vrtp) {
06468
06469 if ((ast->_state != AST_STATE_UP) &&
06470 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06471 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06472 p->invitestate = INV_EARLY_MEDIA;
06473 transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06474 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06475 }
06476 p->lastrtptx = time(NULL);
06477 res = ast_rtp_write(p->vrtp, frame);
06478 }
06479 sip_pvt_unlock(p);
06480 }
06481 break;
06482 case AST_FRAME_TEXT:
06483 if (p) {
06484 sip_pvt_lock(p);
06485 if (p->red) {
06486 red_buffer_t140(p->trtp, frame);
06487 } else {
06488 if (p->trtp) {
06489
06490 if ((ast->_state != AST_STATE_UP) &&
06491 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06492 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06493 p->invitestate = INV_EARLY_MEDIA;
06494 transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06495 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06496 }
06497 p->lastrtptx = time(NULL);
06498 res = ast_rtp_write(p->trtp, frame);
06499 }
06500 }
06501 sip_pvt_unlock(p);
06502 }
06503 break;
06504 case AST_FRAME_IMAGE:
06505 return 0;
06506 break;
06507 case AST_FRAME_MODEM:
06508 if (p) {
06509 sip_pvt_lock(p);
06510
06511
06512
06513
06514 if ((ast->_state == AST_STATE_UP) &&
06515 p->udptl &&
06516 (p->t38.state == T38_ENABLED)) {
06517 res = ast_udptl_write(p->udptl, frame);
06518 }
06519 sip_pvt_unlock(p);
06520 }
06521 break;
06522 default:
06523 ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
06524 return 0;
06525 }
06526
06527 return res;
06528 }
06529
06530
06531
06532 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
06533 {
06534 int ret = -1;
06535 struct sip_pvt *p;
06536
06537 if (newchan && ast_test_flag(newchan, AST_FLAG_ZOMBIE))
06538 ast_debug(1, "New channel is zombie\n");
06539 if (oldchan && ast_test_flag(oldchan, AST_FLAG_ZOMBIE))
06540 ast_debug(1, "Old channel is zombie\n");
06541
06542 if (!newchan || !newchan->tech_pvt) {
06543 if (!newchan)
06544 ast_log(LOG_WARNING, "No new channel! Fixup of %s failed.\n", oldchan->name);
06545 else
06546 ast_log(LOG_WARNING, "No SIP tech_pvt! Fixup of %s failed.\n", oldchan->name);
06547 return -1;
06548 }
06549 p = newchan->tech_pvt;
06550
06551 sip_pvt_lock(p);
06552 append_history(p, "Masq", "Old channel: %s\n", oldchan->name);
06553 append_history(p, "Masq (cont)", "...new owner: %s\n", newchan->name);
06554 if (p->owner != oldchan)
06555 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
06556 else {
06557 p->owner = newchan;
06558
06559
06560
06561
06562
06563
06564 sip_set_rtp_peer(newchan, NULL, NULL, 0, 0, 0);
06565 ret = 0;
06566 }
06567 ast_debug(3, "SIP Fixup: New owner for dialogue %s: %s (Old parent: %s)\n", p->callid, p->owner->name, oldchan->name);
06568
06569 sip_pvt_unlock(p);
06570 return ret;
06571 }
06572
06573 static int sip_senddigit_begin(struct ast_channel *ast, char digit)
06574 {
06575 struct sip_pvt *p = ast->tech_pvt;
06576 int res = 0;
06577
06578 sip_pvt_lock(p);
06579 switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
06580 case SIP_DTMF_INBAND:
06581 res = -1;
06582 break;
06583 case SIP_DTMF_RFC2833:
06584 if (p->rtp)
06585 ast_rtp_senddigit_begin(p->rtp, digit);
06586 break;
06587 default:
06588 break;
06589 }
06590 sip_pvt_unlock(p);
06591
06592 return res;
06593 }
06594
06595
06596
06597 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration)
06598 {
06599 struct sip_pvt *p = ast->tech_pvt;
06600 int res = 0;
06601
06602 sip_pvt_lock(p);
06603 switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
06604 case SIP_DTMF_INFO:
06605 case SIP_DTMF_SHORTINFO:
06606 transmit_info_with_digit(p, digit, duration);
06607 break;
06608 case SIP_DTMF_RFC2833:
06609 if (p->rtp)
06610 ast_rtp_senddigit_end_with_duration(p->rtp, digit, duration);
06611 break;
06612 case SIP_DTMF_INBAND:
06613 res = -1;
06614 break;
06615 }
06616 sip_pvt_unlock(p);
06617
06618 return res;
06619 }
06620
06621
06622 static int sip_transfer(struct ast_channel *ast, const char *dest)
06623 {
06624 struct sip_pvt *p = ast->tech_pvt;
06625 int res;
06626
06627 if (dest == NULL)
06628 dest = "";
06629 sip_pvt_lock(p);
06630 if (ast->_state == AST_STATE_RING)
06631 res = sip_sipredirect(p, dest);
06632 else
06633 res = transmit_refer(p, dest);
06634 sip_pvt_unlock(p);
06635 return res;
06636 }
06637
06638
06639 static int interpret_t38_parameters(struct sip_pvt *p, const struct ast_control_t38_parameters *parameters)
06640 {
06641 int res = 0;
06642
06643 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) || !p->udptl) {
06644 return -1;
06645 }
06646 switch (parameters->request_response) {
06647 case AST_T38_NEGOTIATED:
06648 case AST_T38_REQUEST_NEGOTIATE:
06649
06650 if (!parameters->max_ifp) {
06651 change_t38_state(p, T38_DISABLED);
06652 if (p->t38.state == T38_PEER_REINVITE) {
06653 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"));
06654 transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
06655 }
06656 break;
06657 } else if (p->t38.state == T38_PEER_REINVITE) {
06658 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"));
06659 p->t38.our_parms = *parameters;
06660
06661
06662
06663 if (!p->t38.their_parms.fill_bit_removal) {
06664 p->t38.our_parms.fill_bit_removal = FALSE;
06665 }
06666 if (!p->t38.their_parms.transcoding_mmr) {
06667 p->t38.our_parms.transcoding_mmr = FALSE;
06668 }
06669 if (!p->t38.their_parms.transcoding_jbig) {
06670 p->t38.our_parms.transcoding_jbig = FALSE;
06671 }
06672 p->t38.our_parms.version = MIN(p->t38.our_parms.version, p->t38.their_parms.version);
06673 p->t38.our_parms.rate_management = p->t38.their_parms.rate_management;
06674 ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
06675 change_t38_state(p, T38_ENABLED);
06676 transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
06677 } else if (p->t38.state != T38_ENABLED) {
06678 p->t38.our_parms = *parameters;
06679 ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
06680 change_t38_state(p, T38_LOCAL_REINVITE);
06681 if (!p->pendinginvite) {
06682 transmit_reinvite_with_sdp(p, TRUE, FALSE);
06683 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
06684 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
06685 }
06686 }
06687 break;
06688 case AST_T38_TERMINATED:
06689 case AST_T38_REFUSED:
06690 case AST_T38_REQUEST_TERMINATE:
06691 if (p->t38.state == T38_PEER_REINVITE) {
06692 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"));
06693 change_t38_state(p, T38_DISABLED);
06694 transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
06695 } else if (p->t38.state == T38_ENABLED)
06696 transmit_reinvite_with_sdp(p, FALSE, FALSE);
06697 break;
06698 case AST_T38_REQUEST_PARMS: {
06699 struct ast_control_t38_parameters parameters = p->t38.their_parms;
06700
06701 if (p->t38.state == T38_PEER_REINVITE) {
06702 AST_SCHED_DEL(sched, p->t38id);
06703 parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
06704 parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
06705 ast_queue_control_data(p->owner, AST_CONTROL_T38_PARAMETERS, ¶meters, sizeof(parameters));
06706
06707
06708
06709
06710 res = AST_T38_REQUEST_PARMS;
06711 }
06712 break;
06713 }
06714 default:
06715 res = -1;
06716 break;
06717 }
06718
06719 return res;
06720 }
06721
06722
06723
06724
06725
06726
06727 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
06728 {
06729 struct sip_pvt *p = ast->tech_pvt;
06730 int res = 0;
06731
06732 sip_pvt_lock(p);
06733 switch(condition) {
06734 case AST_CONTROL_RINGING:
06735 if (ast->_state == AST_STATE_RING) {
06736 p->invitestate = INV_EARLY_MEDIA;
06737 if (!ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) ||
06738 (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) {
06739
06740 transmit_provisional_response(p, "180 Ringing", &p->initreq, 0);
06741 ast_set_flag(&p->flags[0], SIP_RINGING);
06742 if (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) != SIP_PROG_INBAND_YES)
06743 break;
06744 } else {
06745
06746 }
06747 }
06748 res = -1;
06749 break;
06750 case AST_CONTROL_BUSY:
06751 if (ast->_state != AST_STATE_UP) {
06752 transmit_response_reliable(p, "486 Busy Here", &p->initreq);
06753 p->invitestate = INV_COMPLETED;
06754 sip_alreadygone(p);
06755 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
06756 break;
06757 }
06758 res = -1;
06759 break;
06760 case AST_CONTROL_CONGESTION:
06761 if (ast->_state != AST_STATE_UP) {
06762 transmit_response_reliable(p, "503 Service Unavailable", &p->initreq);
06763 p->invitestate = INV_COMPLETED;
06764 sip_alreadygone(p);
06765 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
06766 break;
06767 }
06768 res = -1;
06769 break;
06770 case AST_CONTROL_PROCEEDING:
06771 if ((ast->_state != AST_STATE_UP) &&
06772 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06773 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06774 transmit_response(p, "100 Trying", &p->initreq);
06775 p->invitestate = INV_PROCEEDING;
06776 break;
06777 }
06778 res = -1;
06779 break;
06780 case AST_CONTROL_PROGRESS:
06781 if ((ast->_state != AST_STATE_UP) &&
06782 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06783 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06784 p->invitestate = INV_EARLY_MEDIA;
06785 transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06786 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06787 break;
06788 }
06789 res = -1;
06790 break;
06791 case AST_CONTROL_HOLD:
06792 ast_rtp_new_source(p->rtp);
06793 ast_moh_start(ast, data, p->mohinterpret);
06794 break;
06795 case AST_CONTROL_UNHOLD:
06796 ast_rtp_new_source(p->rtp);
06797 ast_moh_stop(ast);
06798 break;
06799 case AST_CONTROL_VIDUPDATE:
06800 if (p->vrtp && !p->novideo) {
06801 transmit_info_with_vidupdate(p);
06802
06803 } else
06804 res = -1;
06805 break;
06806 case AST_CONTROL_T38_PARAMETERS:
06807 if (datalen != sizeof(struct ast_control_t38_parameters)) {
06808 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);
06809 res = -1;
06810 } else {
06811 const struct ast_control_t38_parameters *parameters = data;
06812 res = interpret_t38_parameters(p, parameters);
06813 }
06814 break;
06815 case AST_CONTROL_SRCUPDATE:
06816 ast_rtp_new_source(p->rtp);
06817 break;
06818 case AST_CONTROL_SRCCHANGE:
06819 ast_rtp_change_source(p->rtp);
06820 break;
06821 case -1:
06822 res = -1;
06823 break;
06824 default:
06825 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
06826 res = -1;
06827 break;
06828 }
06829 sip_pvt_unlock(p);
06830 return res;
06831 }
06832
06833
06834
06835
06836
06837
06838
06839 static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title)
06840 {
06841 struct ast_channel *tmp;
06842 struct ast_variable *v = NULL;
06843 int fmt;
06844 int what;
06845 int video;
06846 int text;
06847 int needvideo = 0;
06848 int needtext = 0;
06849 char buf[SIPBUFSIZE];
06850 char *decoded_exten;
06851
06852 {
06853 const char *my_name;
06854
06855 if (title) {
06856 my_name = title;
06857 } else {
06858 char *port = NULL;
06859 my_name = ast_strdupa(i->fromdomain);
06860 if ((port = strchr(i->fromdomain, ':'))) {
06861 *port = '\0';
06862 }
06863 }
06864
06865 sip_pvt_unlock(i);
06866
06867 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));
06868
06869 }
06870 if (!tmp) {
06871 ast_log(LOG_WARNING, "Unable to allocate AST channel structure for SIP channel\n");
06872 sip_pvt_lock(i);
06873 return NULL;
06874 }
06875 sip_pvt_lock(i);
06876
06877 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;
06878
06879
06880
06881 if (i->jointcapability) {
06882 what = i->jointcapability;
06883 video = i->jointcapability & AST_FORMAT_VIDEO_MASK;
06884 text = i->jointcapability & AST_FORMAT_TEXT_MASK;
06885 } else if (i->capability) {
06886 what = i->capability;
06887 video = i->capability & AST_FORMAT_VIDEO_MASK;
06888 text = i->capability & AST_FORMAT_TEXT_MASK;
06889 } else {
06890 what = global_capability;
06891 video = global_capability & AST_FORMAT_VIDEO_MASK;
06892 text = global_capability & AST_FORMAT_TEXT_MASK;
06893 }
06894
06895
06896 tmp->nativeformats = ast_codec_choose(&i->prefs, what, 1) | video | text;
06897 ast_debug(3, "*** Our native formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, tmp->nativeformats));
06898 ast_debug(3, "*** Joint capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->jointcapability));
06899 ast_debug(3, "*** Our capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->capability));
06900 ast_debug(3, "*** AST_CODEC_CHOOSE formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, ast_codec_choose(&i->prefs, what, 1)));
06901 if (i->prefcodec)
06902 ast_debug(3, "*** Our preferred formats from the incoming channel are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->prefcodec));
06903
06904
06905 fmt = ast_best_codec(tmp->nativeformats);
06906
06907
06908
06909
06910
06911 if (i->vrtp) {
06912 if (ast_test_flag(&i->flags[1], SIP_PAGE2_VIDEOSUPPORT))
06913 needvideo = AST_FORMAT_VIDEO_MASK;
06914 else if (i->prefcodec)
06915 needvideo = i->prefcodec & AST_FORMAT_VIDEO_MASK;
06916 else
06917 needvideo = i->jointcapability & AST_FORMAT_VIDEO_MASK;
06918 }
06919
06920 if (i->trtp) {
06921 if (i->prefcodec)
06922 needtext = i->prefcodec & AST_FORMAT_TEXT_MASK;
06923 else
06924 needtext = i->jointcapability & AST_FORMAT_TEXT_MASK;
06925 }
06926
06927 if (needvideo)
06928 ast_debug(3, "This channel can handle video! HOLLYWOOD next!\n");
06929 else
06930 ast_debug(3, "This channel will not be able to handle video.\n");
06931
06932 if ((ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) || (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) ||
06933 (ast_test_flag(&i->flags[1], SIP_PAGE2_FAX_DETECT))) {
06934 int features = 0;
06935
06936 if ((ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) || (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
06937 features |= DSP_FEATURE_DIGIT_DETECT;
06938 }
06939
06940 if (ast_test_flag(&i->flags[1], SIP_PAGE2_FAX_DETECT)) {
06941 features |= DSP_FEATURE_FAX_DETECT;
06942 }
06943
06944 i->dsp = ast_dsp_new();
06945 ast_dsp_set_features(i->dsp, features);
06946 if (global_relaxdtmf)
06947 ast_dsp_set_digitmode(i->dsp, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
06948 }
06949
06950
06951 if (i->rtp) {
06952 ast_channel_set_fd(tmp, 0, ast_rtp_fd(i->rtp));
06953 ast_channel_set_fd(tmp, 1, ast_rtcp_fd(i->rtp));
06954 }
06955 if (needvideo && i->vrtp) {
06956 ast_channel_set_fd(tmp, 2, ast_rtp_fd(i->vrtp));
06957 ast_channel_set_fd(tmp, 3, ast_rtcp_fd(i->vrtp));
06958 }
06959 if (needtext && i->trtp)
06960 ast_channel_set_fd(tmp, 4, ast_rtp_fd(i->trtp));
06961 if (i->udptl)
06962 ast_channel_set_fd(tmp, 5, ast_udptl_fd(i->udptl));
06963
06964 if (state == AST_STATE_RING)
06965 tmp->rings = 1;
06966 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
06967 tmp->writeformat = fmt;
06968 tmp->rawwriteformat = fmt;
06969 tmp->readformat = fmt;
06970 tmp->rawreadformat = fmt;
06971 tmp->tech_pvt = dialog_ref(i, "sip_new: set chan->tech_pvt to i");
06972
06973 tmp->callgroup = i->callgroup;
06974 tmp->pickupgroup = i->pickupgroup;
06975 tmp->cid.cid_pres = i->callingpres;
06976 if (!ast_strlen_zero(i->parkinglot))
06977 ast_string_field_set(tmp, parkinglot, i->parkinglot);
06978 if (!ast_strlen_zero(i->accountcode))
06979 ast_string_field_set(tmp, accountcode, i->accountcode);
06980 if (i->amaflags)
06981 tmp->amaflags = i->amaflags;
06982 if (!ast_strlen_zero(i->language))
06983 ast_string_field_set(tmp, language, i->language);
06984 i->owner = tmp;
06985 ast_module_ref(ast_module_info->self);
06986 ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
06987
06988
06989
06990
06991 if (ast_exists_extension(NULL, i->context, i->exten, 1, i->cid_num)) {
06992
06993 ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));
06994 } else {
06995 decoded_exten = ast_strdupa(i->exten);
06996 ast_uri_decode(decoded_exten);
06997 ast_copy_string(tmp->exten, decoded_exten, sizeof(tmp->exten));
06998 }
06999
07000
07001
07002 tmp->cid.cid_ani = ast_strdup(i->cid_num);
07003 if (!ast_strlen_zero(i->rdnis))
07004 tmp->cid.cid_rdnis = ast_strdup(i->rdnis);
07005
07006 if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s"))
07007 tmp->cid.cid_dnid = ast_strdup(i->exten);
07008
07009 tmp->priority = 1;
07010 if (!ast_strlen_zero(i->uri))
07011 pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
07012 if (!ast_strlen_zero(i->domain))
07013 pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
07014 if (!ast_strlen_zero(i->callid))
07015 pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
07016 if (i->rtp)
07017 ast_jb_configure(tmp, &global_jbconf);
07018
07019
07020 for (v = i->chanvars ; v ; v = v->next) {
07021 char valuebuf[1024];
07022 pbx_builtin_setvar_helper(tmp, v->name, ast_get_encoded_str(v->value, valuebuf, sizeof(valuebuf)));
07023 }
07024
07025 if (state != AST_STATE_DOWN && ast_pbx_start(tmp)) {
07026 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
07027 tmp->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
07028 ast_hangup(tmp);
07029 tmp = NULL;
07030 }
07031
07032 if (i->do_history)
07033 append_history(i, "NewChan", "Channel %s - from %s", tmp->name, i->callid);
07034
07035
07036 if (sip_cfg.callevents)
07037 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
07038 "Channel: %s\r\nUniqueid: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\n",
07039 tmp->name, tmp->uniqueid, "SIP", i->callid, i->fullcontact);
07040
07041 return tmp;
07042 }
07043
07044
07045 static char *get_body_by_line(const char *line, const char *name, int nameLen, char delimiter)
07046 {
07047 if (!strncasecmp(line, name, nameLen) && line[nameLen] == delimiter)
07048 return ast_skip_blanks(line + nameLen + 1);
07049
07050 return "";
07051 }
07052
07053
07054
07055
07056
07057 static const char *get_sdp_iterate(int *start, struct sip_request *req, const char *name)
07058 {
07059 int len = strlen(name);
07060
07061 while (*start < (req->sdp_start + req->sdp_count)) {
07062 const char *r = get_body_by_line(REQ_OFFSET_TO_STR(req, line[(*start)++]), name, len, '=');
07063 if (r[0] != '\0')
07064 return r;
07065 }
07066
07067
07068 (*start)++;
07069
07070 return "";
07071 }
07072
07073
07074
07075
07076
07077
07078 static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value)
07079 {
07080 char type = '\0';
07081 const char *line = NULL;
07082
07083 if (stop > (req->sdp_start + req->sdp_count)) {
07084 stop = req->sdp_start + req->sdp_count;
07085 }
07086
07087 while (*start < stop) {
07088 line = REQ_OFFSET_TO_STR(req, line[(*start)++]);
07089 if (line[1] == '=') {
07090 type = line[0];
07091 *value = ast_skip_blanks(line + 2);
07092 break;
07093 }
07094 }
07095
07096 return type;
07097 }
07098
07099
07100 static char *get_body(struct sip_request *req, char *name, char delimiter)
07101 {
07102 int x;
07103 int len = strlen(name);
07104 char *r;
07105
07106 for (x = 0; x < req->lines; x++) {
07107 r = get_body_by_line(REQ_OFFSET_TO_STR(req, line[x]), name, len, delimiter);
07108 if (r[0] != '\0')
07109 return r;
07110 }
07111
07112 return "";
07113 }
07114
07115
07116 static const char *find_alias(const char *name, const char *_default)
07117 {
07118
07119 static const struct cfalias {
07120 char * const fullname;
07121 char * const shortname;
07122 } aliases[] = {
07123 { "Content-Type", "c" },
07124 { "Content-Encoding", "e" },
07125 { "From", "f" },
07126 { "Call-ID", "i" },
07127 { "Contact", "m" },
07128 { "Content-Length", "l" },
07129 { "Subject", "s" },
07130 { "To", "t" },
07131 { "Supported", "k" },
07132 { "Refer-To", "r" },
07133 { "Referred-By", "b" },
07134 { "Allow-Events", "u" },
07135 { "Event", "o" },
07136 { "Via", "v" },
07137 { "Accept-Contact", "a" },
07138 { "Reject-Contact", "j" },
07139 { "Request-Disposition", "d" },
07140 { "Session-Expires", "x" },
07141 { "Identity", "y" },
07142 { "Identity-Info", "n" },
07143 };
07144 int x;
07145
07146 for (x = 0; x < ARRAY_LEN(aliases); x++) {
07147 if (!strcasecmp(aliases[x].fullname, name))
07148 return aliases[x].shortname;
07149 }
07150
07151 return _default;
07152 }
07153
07154 static const char *__get_header(const struct sip_request *req, const char *name, int *start)
07155 {
07156 int pass;
07157
07158
07159
07160
07161
07162
07163
07164
07165
07166
07167 for (pass = 0; name && pass < 2;pass++) {
07168 int x, len = strlen(name);
07169 for (x = *start; x < req->headers; x++) {
07170 char *header = REQ_OFFSET_TO_STR(req, header[x]);
07171 if (!strncasecmp(header, name, len)) {
07172 char *r = header + len;
07173 if (sip_cfg.pedanticsipchecking)
07174 r = ast_skip_blanks(r);
07175
07176 if (*r == ':') {
07177 *start = x+1;
07178 return ast_skip_blanks(r+1);
07179 }
07180 }
07181 }
07182 if (pass == 0)
07183 name = find_alias(name, NULL);
07184 }
07185
07186
07187 return "";
07188 }
07189
07190
07191
07192
07193 static const char *get_header(const struct sip_request *req, const char *name)
07194 {
07195 int start = 0;
07196 return __get_header(req, name, &start);
07197 }
07198
07199
07200 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect)
07201 {
07202
07203 struct ast_frame *f;
07204
07205 if (!p->rtp) {
07206
07207 return &ast_null_frame;
07208 }
07209
07210 switch(ast->fdno) {
07211 case 0:
07212 f = ast_rtp_read(p->rtp);
07213 break;
07214 case 1:
07215 f = ast_rtcp_read(p->rtp);
07216 break;
07217 case 2:
07218 f = ast_rtp_read(p->vrtp);
07219 break;
07220 case 3:
07221 f = ast_rtcp_read(p->vrtp);
07222 break;
07223 case 4:
07224 f = ast_rtp_read(p->trtp);
07225 if (sipdebug_text) {
07226 int i;
07227 unsigned char* arr = f->data.ptr;
07228 for (i=0; i < f->datalen; i++)
07229 ast_verbose("%c", (arr[i] > ' ' && arr[i] < '}') ? arr[i] : '.');
07230 ast_verbose(" -> ");
07231 for (i=0; i < f->datalen; i++)
07232 ast_verbose("%02X ", arr[i]);
07233 ast_verbose("\n");
07234 }
07235 break;
07236 case 5:
07237 f = ast_udptl_read(p->udptl);
07238 break;
07239 default:
07240 f = &ast_null_frame;
07241 }
07242
07243 if (f && (f->frametype == AST_FRAME_DTMF_BEGIN || f->frametype == AST_FRAME_DTMF_END) &&
07244 (ast_test_flag(&p->flags[0], SIP_DTMF) != SIP_DTMF_RFC2833)) {
07245 ast_debug(1, "Ignoring DTMF (%c) RTP frame because dtmfmode is not RFC2833\n", f->subclass);
07246 return &ast_null_frame;
07247 }
07248
07249
07250 if (!p->owner || (f && f->frametype != AST_FRAME_VOICE))
07251 return f;
07252
07253 if (f && f->subclass != (p->owner->nativeformats & AST_FORMAT_AUDIO_MASK)) {
07254 if (!(f->subclass & p->jointcapability)) {
07255 ast_debug(1, "Bogus frame of format '%s' received from '%s'!\n",
07256 ast_getformatname(f->subclass), p->owner->name);
07257 return &ast_null_frame;
07258 }
07259 ast_debug(1, "Oooh, format changed to %d %s\n",
07260 f->subclass, ast_getformatname(f->subclass));
07261 p->owner->nativeformats = (p->owner->nativeformats & (AST_FORMAT_VIDEO_MASK | AST_FORMAT_TEXT_MASK)) | f->subclass;
07262 ast_set_read_format(p->owner, p->owner->readformat);
07263 ast_set_write_format(p->owner, p->owner->writeformat);
07264 }
07265
07266 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) {
07267 f = ast_dsp_process(p->owner, p->dsp, f);
07268 if (f && f->frametype == AST_FRAME_DTMF) {
07269 if (f->subclass == 'f') {
07270 if (option_debug)
07271 ast_log(LOG_DEBUG, "Fax CNG detected on %s\n", ast->name);
07272 *faxdetect = 1;
07273
07274 if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
07275 ast_dsp_set_features(p->dsp, DSP_FEATURE_DIGIT_DETECT);
07276 } else {
07277 ast_dsp_free(p->dsp);
07278 p->dsp = NULL;
07279 }
07280 } else {
07281 ast_debug(1, "* Detected inband DTMF '%c'\n", f->subclass);
07282 }
07283 }
07284 }
07285
07286 return f;
07287 }
07288
07289
07290 static struct ast_frame *sip_read(struct ast_channel *ast)
07291 {
07292 struct ast_frame *fr;
07293 struct sip_pvt *p = ast->tech_pvt;
07294 int faxdetected = FALSE;
07295
07296 sip_pvt_lock(p);
07297 fr = sip_rtp_read(ast, p, &faxdetected);
07298 p->lastrtprx = time(NULL);
07299
07300
07301 if (faxdetected && ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_CNG)) {
07302 ast_channel_lock(ast);
07303 if (strcmp(ast->exten, "fax")) {
07304 const char *target_context = S_OR(ast->macrocontext, ast->context);
07305 ast_channel_unlock(ast);
07306 if (ast_exists_extension(ast, target_context, "fax", 1, ast->cid.cid_num)) {
07307 ast_verbose(VERBOSE_PREFIX_2 "Redirecting '%s' to fax extension due to CNG detection\n", ast->name);
07308 pbx_builtin_setvar_helper(ast, "FAXEXTEN", ast->exten);
07309 if (ast_async_goto(ast, target_context, "fax", 1)) {
07310 ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", ast->name, target_context);
07311 }
07312 fr = &ast_null_frame;
07313 } else {
07314 ast_log(LOG_NOTICE, "FAX CNG detected but no fax extension\n");
07315 }
07316 } else {
07317 ast_channel_unlock(ast);
07318 }
07319 }
07320
07321
07322 if (fr && fr->frametype == AST_FRAME_VOICE && p->invitestate != INV_EARLY_MEDIA && ast->_state != AST_STATE_UP) {
07323 fr = &ast_null_frame;
07324 }
07325
07326 sip_pvt_unlock(p);
07327
07328 return fr;
07329 }
07330
07331
07332
07333 static char *generate_random_string(char *buf, size_t size)
07334 {
07335 long val[4];
07336 int x;
07337
07338 for (x=0; x<4; x++)
07339 val[x] = ast_random();
07340 snprintf(buf, size, "%08lx%08lx%08lx%08lx", val[0], val[1], val[2], val[3]);
07341
07342 return buf;
07343 }
07344
07345
07346 static void build_callid_pvt(struct sip_pvt *pvt)
07347 {
07348 char buf[33];
07349
07350 const char *host = S_OR(pvt->fromdomain, ast_inet_ntoa(pvt->ourip.sin_addr));
07351
07352 ast_string_field_build(pvt, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
07353
07354 }
07355
07356
07357 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain)
07358 {
07359 char buf[33];
07360
07361 const char *host = S_OR(fromdomain, ast_inet_ntoa(ourip));
07362
07363 ast_string_field_build(reg, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
07364 }
07365
07366
07367 static void make_our_tag(char *tagbuf, size_t len)
07368 {
07369 snprintf(tagbuf, len, "as%08lx", ast_random());
07370 }
07371
07372
07373 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p)
07374 {
07375 struct sip_st_dlg *stp;
07376
07377 if (p->stimer) {
07378 ast_log(LOG_ERROR, "Session-Timer struct already allocated\n");
07379 return p->stimer;
07380 }
07381
07382 if (!(stp = ast_calloc(1, sizeof(struct sip_st_dlg))))
07383 return NULL;
07384
07385 p->stimer = stp;
07386
07387 stp->st_schedid = -1;
07388
07389 return p->stimer;
07390 }
07391
07392
07393
07394
07395
07396 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
07397 int useglobal_nat, const int intended_method, struct sip_request *req)
07398 {
07399 struct sip_pvt *p;
07400
07401 if (!(p = ao2_t_alloc(sizeof(*p), sip_destroy_fn, "allocate a dialog(pvt) struct")))
07402 return NULL;
07403
07404 if (ast_string_field_init(p, 512)) {
07405 ao2_t_ref(p, -1, "failed to string_field_init, drop p");
07406 return NULL;
07407 }
07408
07409 if (req) {
07410 set_socket_transport(&p->socket, req->socket.type);
07411 } else {
07412 set_socket_transport(&p->socket, SIP_TRANSPORT_UDP);
07413 }
07414
07415 p->socket.fd = -1;
07416 p->method = intended_method;
07417 p->initid = -1;
07418 p->waitid = -1;
07419 p->autokillid = -1;
07420 p->request_queue_sched_id = -1;
07421 p->provisional_keepalive_sched_id = -1;
07422 p->t38id = -1;
07423 p->subscribed = NONE;
07424 p->stateid = -1;
07425 p->sessionversion_remote = -1;
07426 p->session_modify = TRUE;
07427 p->stimer = NULL;
07428 p->prefs = default_prefs;
07429
07430 if (intended_method != SIP_OPTIONS) {
07431 p->timer_t1 = global_t1;
07432 p->timer_b = global_timer_b;
07433 }
07434
07435 if (!sin)
07436 p->ourip = internip;
07437 else {
07438 p->sa = *sin;
07439 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
07440 }
07441
07442
07443 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
07444 ast_copy_flags(&p->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
07445
07446 p->do_history = recordhistory;
07447
07448 p->branch = ast_random();
07449 make_our_tag(p->tag, sizeof(p->tag));
07450 p->ocseq = INITIAL_CSEQ;
07451
07452 if (sip_methods[intended_method].need_rtp) {
07453 p->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
07454
07455 if (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) ||
07456 ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS))
07457 p->vrtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
07458 if (ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT))
07459 p->trtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
07460 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
07461 if (!(p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr))) {
07462
07463 ast_log(LOG_ERROR, "UDPTL creation failed\n");
07464 ast_clear_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT);
07465 }
07466 }
07467 if (!p->rtp|| (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) && !p->vrtp)
07468 || (ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT) && !p->trtp)) {
07469 ast_log(LOG_WARNING, "Unable to create RTP audio %s%ssession: %s\n",
07470 ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "and video " : "",
07471 ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT) ? "and text " : "", strerror(errno));
07472 if (p->chanvars) {
07473 ast_variables_destroy(p->chanvars);
07474 p->chanvars = NULL;
07475 }
07476 ao2_t_ref(p, -1, "failed to create RTP audio session, drop p");
07477 return NULL;
07478 p->t38_maxdatagram = global_t38_maxdatagram;
07479 }
07480 ast_rtp_setqos(p->rtp, global_tos_audio, global_cos_audio, "SIP RTP");
07481 ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
07482 ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
07483 ast_rtp_set_rtptimeout(p->rtp, global_rtptimeout);
07484 ast_rtp_set_rtpholdtimeout(p->rtp, global_rtpholdtimeout);
07485 ast_rtp_set_rtpkeepalive(p->rtp, global_rtpkeepalive);
07486 if (p->vrtp) {
07487 ast_rtp_setqos(p->vrtp, global_tos_video, global_cos_video, "SIP VRTP");
07488 ast_rtp_setdtmf(p->vrtp, 0);
07489 ast_rtp_setdtmfcompensate(p->vrtp, 0);
07490 ast_rtp_set_rtptimeout(p->vrtp, global_rtptimeout);
07491 ast_rtp_set_rtpholdtimeout(p->vrtp, global_rtpholdtimeout);
07492 ast_rtp_set_rtpkeepalive(p->vrtp, global_rtpkeepalive);
07493 }
07494 if (p->trtp) {
07495 ast_rtp_setqos(p->trtp, global_tos_text, global_cos_text, "SIP TRTP");
07496 ast_rtp_setdtmf(p->trtp, 0);
07497 ast_rtp_setdtmfcompensate(p->trtp, 0);
07498 }
07499 if (p->udptl)
07500 ast_udptl_setqos(p->udptl, global_tos_audio, global_cos_audio);
07501 p->maxcallbitrate = default_maxcallbitrate;
07502 p->autoframing = global_autoframing;
07503 ast_rtp_codec_setpref(p->rtp, &p->prefs);
07504 }
07505
07506 if (useglobal_nat && sin) {
07507
07508 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT);
07509 p->recv = *sin;
07510 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
07511 }
07512
07513 if (p->method != SIP_REGISTER)
07514 ast_string_field_set(p, fromdomain, default_fromdomain);
07515 build_via(p);
07516 if (!callid)
07517 build_callid_pvt(p);
07518 else
07519 ast_string_field_set(p, callid, callid);
07520
07521 ast_string_field_set(p, mohinterpret, default_mohinterpret);
07522 ast_string_field_set(p, mohsuggest, default_mohsuggest);
07523 p->capability = global_capability;
07524 p->allowtransfer = sip_cfg.allowtransfer;
07525 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
07526 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
07527 p->noncodeccapability |= AST_RTP_DTMF;
07528 if (p->udptl) {
07529 p->t38_maxdatagram = global_t38_maxdatagram;
07530 set_t38_capabilities(p);
07531 }
07532 ast_string_field_set(p, context, sip_cfg.default_context);
07533 ast_string_field_set(p, parkinglot, default_parkinglot);
07534
07535 AST_LIST_HEAD_INIT_NOLOCK(&p->request_queue);
07536
07537
07538
07539 ao2_t_link(dialogs, p, "link pvt into dialogs table");
07540
07541 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");
07542 return p;
07543 }
07544
07545 static void free_via(struct sip_via *v)
07546 {
07547 if (!v) {
07548 return;
07549 }
07550
07551 if (v->via) {
07552 ast_free(v->via);
07553 }
07554
07555 ast_free(v);
07556 }
07557
07558
07559
07560
07561
07562
07563
07564
07565
07566
07567
07568
07569
07570
07571
07572
07573
07574
07575
07576
07577
07578
07579
07580
07581
07582
07583
07584
07585
07586
07587
07588
07589
07590
07591 static struct sip_via *parse_via(const char *header)
07592 {
07593 struct sip_via *v = ast_calloc(1, sizeof(*v));
07594 char *via, *parm;
07595
07596 if (!v) {
07597 return NULL;
07598 }
07599
07600 v->via = ast_strdup(header);
07601 v->ttl = 1;
07602
07603 via = v->via;
07604
07605 if (ast_strlen_zero(via)) {
07606 ast_log(LOG_ERROR, "received request without a Via header\n");
07607 free_via(v);
07608 return NULL;
07609 }
07610
07611
07612 via = strsep(&via, ",");
07613
07614
07615 v->protocol = strsep(&via, " \t\r\n");
07616 if (ast_strlen_zero(v->protocol)) {
07617 ast_log(LOG_ERROR, "missing sent-protocol in Via header\n");
07618 free_via(v);
07619 return NULL;
07620 }
07621 v->protocol = ast_skip_blanks(v->protocol);
07622
07623 if (via) {
07624 via = ast_skip_blanks(via);
07625 }
07626
07627
07628 v->sent_by = strsep(&via, "; \t\r\n");
07629 if (ast_strlen_zero(v->sent_by)) {
07630 ast_log(LOG_ERROR, "missing sent-by in Via header\n");
07631 free_via(v);
07632 return NULL;
07633 }
07634 v->sent_by = ast_skip_blanks(v->sent_by);
07635
07636
07637 if ((parm = strchr(v->sent_by, ':'))) {
07638 char *endptr;
07639
07640 v->port = strtol(++parm, &endptr, 10);
07641 }
07642
07643
07644 while ((parm = strsep(&via, "; \t\r\n"))) {
07645 char *c;
07646 if ((c = strstr(parm, "maddr="))) {
07647 v->maddr = ast_skip_blanks(c + sizeof("maddr=") - 1);
07648 } else if ((c = strstr(parm, "branch="))) {
07649 v->branch = ast_skip_blanks(c + sizeof("branch=") - 1);
07650 } else if ((c = strstr(parm, "ttl="))) {
07651 char *endptr;
07652 c = ast_skip_blanks(c + sizeof("ttl=") - 1);
07653 v->ttl = strtol(c, &endptr, 10);
07654
07655
07656 if (c == endptr) {
07657 v->ttl = 1;
07658 }
07659 }
07660 }
07661
07662 return v;
07663 }
07664
07665
07666
07667
07668
07669
07670
07671
07672 static int addr_is_multicast(struct in_addr *addr)
07673 {
07674 return ((ntohl(addr->s_addr) & 0xf0000000) == 0xe0000000);
07675 }
07676
07677 static int process_via(struct sip_pvt *p, const struct sip_request *req)
07678 {
07679 struct sip_via *via = parse_via(get_header(req, "Via"));
07680
07681 if (!via) {
07682 ast_log(LOG_ERROR, "error processing via header\n");
07683 return -1;
07684 }
07685
07686 if (via->maddr) {
07687 struct hostent *hp;
07688 struct ast_hostent ahp;
07689
07690 hp = ast_gethostbyname(via->maddr, &ahp);
07691 if (hp == NULL) {
07692 ast_log(LOG_WARNING, "Can't find address for maddr '%s'\n", via->maddr);
07693 ast_log(LOG_ERROR, "error processing via header\n");
07694 free_via(via);
07695 return -1;
07696 }
07697
07698 p->sa.sin_family = AF_INET;
07699 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
07700
07701 if (via->port) {
07702 p->sa.sin_port = via->port;
07703 } else {
07704 p->sa.sin_port = STANDARD_SIP_PORT;
07705 }
07706
07707 if (addr_is_multicast(&p->sa.sin_addr)) {
07708 setsockopt(sipsock, IPPROTO_IP, IP_MULTICAST_TTL, &via->ttl, sizeof(via->ttl));
07709 }
07710 }
07711
07712 free_via(via);
07713 return 0;
07714 }
07715
07716
07717 struct find_call_cb_arg {
07718 enum sipmethod method;
07719 const char *callid;
07720 const char *fromtag;
07721 const char *totag;
07722 const char *tag;
07723 };
07724
07725
07726
07727
07728
07729 static int find_call_cb(void *__pvt, void *__arg, int flags)
07730 {
07731 struct sip_pvt *p = __pvt;
07732 struct find_call_cb_arg *arg = __arg;
07733
07734 int found = FALSE;
07735
07736 if (!ast_strlen_zero(p->callid)) {
07737 if (arg->method == SIP_REGISTER)
07738 found = (!strcmp(p->callid, arg->callid));
07739 else {
07740 found = !strcmp(p->callid, arg->callid);
07741 if (sip_cfg.pedanticsipchecking && found) {
07742 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);
07743 }
07744 }
07745
07746 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);
07747
07748
07749 if (sip_cfg.pedanticsipchecking && found && arg->method != SIP_RESPONSE) {
07750 if (p->tag[0] == '\0' && arg->totag[0]) {
07751
07752 found = FALSE;
07753 } else if (arg->totag[0]) {
07754 if (strcmp(arg->totag, p->tag)) {
07755 found = FALSE;
07756 }
07757 }
07758 if (!found)
07759 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);
07760 }
07761 }
07762 return found;
07763 }
07764
07765
07766
07767
07768
07769
07770 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method)
07771 {
07772 struct sip_pvt *p = NULL;
07773 char *tag = "";
07774 char totag[128];
07775 char fromtag[128];
07776 struct find_call_cb_arg arg;
07777 const char *callid = get_header(req, "Call-ID");
07778 const char *from = get_header(req, "From");
07779 const char *to = get_header(req, "To");
07780 const char *cseq = get_header(req, "Cseq");
07781 struct sip_pvt *sip_pvt_ptr;
07782
07783
07784
07785 if (ast_strlen_zero(callid) || ast_strlen_zero(to) ||
07786 ast_strlen_zero(from) || ast_strlen_zero(cseq))
07787 return NULL;
07788
07789 arg.method = req->method;
07790 arg.callid = callid;
07791 arg.fromtag = fromtag;
07792 arg.totag = totag;
07793 arg.tag = "";
07794
07795 if (sip_cfg.pedanticsipchecking) {
07796
07797
07798
07799
07800
07801
07802 if (gettag(req, "To", totag, sizeof(totag)))
07803 req->has_to_tag = 1;
07804 gettag(req, "From", fromtag, sizeof(fromtag));
07805
07806 tag = (req->method == SIP_RESPONSE) ? totag : fromtag;
07807
07808 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);
07809
07810
07811 if (ast_strlen_zero(fromtag)) {
07812 ast_debug(5, "%s request has no from tag, dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
07813 return NULL;
07814 }
07815
07816 if (ast_strlen_zero(totag) && (req->method == SIP_ACK || req->method == SIP_BYE || req->method == SIP_INFO )) {
07817 ast_debug(5, "%s must have a to tag. dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
07818 return NULL;
07819 }
07820 }
07821
07822 restartsearch:
07823 if (!sip_cfg.pedanticsipchecking) {
07824 struct sip_pvt tmp_dialog = {
07825 .callid = callid,
07826 };
07827 sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find in dialogs");
07828 if (sip_pvt_ptr) {
07829
07830 sip_pvt_lock(sip_pvt_ptr);
07831 return sip_pvt_ptr;
07832 }
07833 } else {
07834 ao2_lock(dialogs);
07835 p = ao2_t_callback(dialogs, 0 , find_call_cb, &arg, "pedantic linear search for dialog");
07836 if (p) {
07837 if (sip_pvt_trylock(p)) {
07838 ao2_unlock(dialogs);
07839 usleep(1);
07840 goto restartsearch;
07841 }
07842 ao2_unlock(dialogs);
07843 return p;
07844 }
07845 ao2_unlock(dialogs);
07846 }
07847
07848
07849 if (sip_methods[intended_method].can_create == CAN_CREATE_DIALOG) {
07850 if (intended_method == SIP_REFER) {
07851
07852 transmit_response_using_temp(callid, sin, 1, intended_method, req, "603 Declined (no dialog)");
07853 } else if (intended_method == SIP_NOTIFY) {
07854
07855
07856 transmit_response_using_temp(callid, sin, 1, intended_method, req, "481 No subscription");
07857 } else {
07858
07859 if ((p = sip_alloc(callid, sin, 1, intended_method, req))) {
07860
07861 sip_pvt_lock(p);
07862 } else {
07863
07864
07865
07866
07867
07868
07869
07870
07871 transmit_response_using_temp(callid, sin, 1, intended_method, req, "500 Server internal error");
07872 ast_debug(4, "Failed allocating SIP dialog, sending 500 Server internal error and giving up\n");
07873 }
07874 }
07875 return p;
07876 } else if( sip_methods[intended_method].can_create == CAN_CREATE_DIALOG_UNSUPPORTED_METHOD) {
07877
07878 transmit_response_using_temp(callid, sin, 1, intended_method, req, "501 Method Not Implemented");
07879 ast_debug(2, "Got a request with unsupported SIP method.\n");
07880 } else if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
07881
07882 transmit_response_using_temp(callid, sin, 1, intended_method, req, "481 Call leg/transaction does not exist");
07883 ast_debug(2, "That's odd... Got a request in unknown dialog. Callid %s\n", callid ? callid : "<unknown>");
07884 }
07885
07886
07887 if (intended_method == SIP_RESPONSE)
07888 ast_debug(2, "That's odd... Got a response on a call we don't know about. Callid %s\n", callid ? callid : "<unknown>");
07889
07890 return NULL;
07891 }
07892
07893
07894 static int sip_register(const char *value, int lineno)
07895 {
07896 struct sip_registry *reg;
07897 int portnum = 0;
07898 enum sip_transport transport = SIP_TRANSPORT_UDP;
07899 char buf[256] = "";
07900 char *userpart = NULL, *hostpart = NULL;
07901
07902 AST_DECLARE_APP_ARGS(pre1,
07903 AST_APP_ARG(peer);
07904 AST_APP_ARG(userpart);
07905 );
07906 AST_DECLARE_APP_ARGS(pre2,
07907 AST_APP_ARG(transport);
07908 AST_APP_ARG(blank);
07909 AST_APP_ARG(userpart);
07910 );
07911 AST_DECLARE_APP_ARGS(user1,
07912 AST_APP_ARG(userpart);
07913 AST_APP_ARG(secret);
07914 AST_APP_ARG(authuser);
07915 );
07916 AST_DECLARE_APP_ARGS(host1,
07917 AST_APP_ARG(hostpart);
07918 AST_APP_ARG(expiry);
07919 );
07920 AST_DECLARE_APP_ARGS(host2,
07921 AST_APP_ARG(hostpart);
07922 AST_APP_ARG(extension);
07923 );
07924 AST_DECLARE_APP_ARGS(host3,
07925 AST_APP_ARG(host);
07926 AST_APP_ARG(port);
07927 );
07928
07929 if (!value)
07930 return -1;
07931 ast_copy_string(buf, value, sizeof(buf));
07932
07933
07934
07935
07936
07937
07938 if ((hostpart = strrchr(buf, '@'))) {
07939 *hostpart++ = '\0';
07940 userpart = buf;
07941 }
07942
07943 if (ast_strlen_zero(userpart) || ast_strlen_zero(hostpart)) {
07944 ast_log(LOG_WARNING, "Format for registration is [peer?][transport://]user[@domain][:secret[:authuser]]@host[:port][/extension][~expiry] at line %d\n", lineno);
07945 return -1;
07946 }
07947
07948
07949
07950
07951
07952
07953 AST_NONSTANDARD_RAW_ARGS(pre1, userpart, '?');
07954 if (ast_strlen_zero(pre1.userpart)) {
07955 pre1.userpart = pre1.peer;
07956 pre1.peer = NULL;
07957 }
07958
07959
07960
07961
07962
07963
07964
07965 AST_NONSTANDARD_RAW_ARGS(pre2, pre1.userpart, '/');
07966 if (ast_strlen_zero(pre2.userpart)) {
07967 pre2.userpart = pre2.transport;
07968 pre2.transport = NULL;
07969 } else {
07970 pre2.transport[strlen(pre2.transport) - 1] = '\0';
07971 }
07972
07973 if (!ast_strlen_zero(pre2.blank)) {
07974 ast_log(LOG_WARNING, "Format for registration is [peer?][transport://]user[@domain][:secret[:authuser]]@host[:port][/extension][~expiry] at line %d\n", lineno);
07975 return -1;
07976 }
07977
07978
07979
07980
07981
07982
07983
07984
07985
07986 AST_NONSTANDARD_RAW_ARGS(user1, pre2.userpart, ':');
07987
07988
07989
07990
07991
07992
07993
07994
07995
07996
07997 AST_NONSTANDARD_RAW_ARGS(host1, hostpart, '~');
07998
07999
08000
08001
08002
08003
08004
08005
08006
08007
08008
08009 AST_NONSTANDARD_RAW_ARGS(host2, host1.hostpart, '/');
08010
08011
08012
08013
08014
08015
08016
08017
08018
08019
08020
08021
08022 AST_NONSTANDARD_RAW_ARGS(host3, host2.hostpart, ':');
08023
08024 if (host3.port) {
08025 if (!(portnum = port_str2int(host3.port, 0))) {
08026 ast_log(LOG_NOTICE, "'%s' is not a valid port number on line %d of sip.conf. using default.\n", host3.port, lineno);
08027 }
08028 }
08029
08030
08031 if (!pre2.transport) {
08032 transport = SIP_TRANSPORT_UDP;
08033 } else if (!strncasecmp(pre2.transport, "tcp", 3)) {
08034 transport = SIP_TRANSPORT_TCP;
08035 } else if (!strncasecmp(pre2.transport, "tls", 3)) {
08036 transport = SIP_TRANSPORT_TLS;
08037 } else if (!strncasecmp(pre2.transport, "udp", 3)) {
08038 transport = SIP_TRANSPORT_UDP;
08039 } else {
08040 transport = SIP_TRANSPORT_UDP;
08041 ast_log(LOG_NOTICE, "'%.3s' is not a valid transport type on line %d of sip.conf. defaulting to udp.\n", pre2.transport, lineno);
08042 }
08043
08044
08045 if (!portnum) {
08046 if (transport == SIP_TRANSPORT_TLS) {
08047 portnum = STANDARD_TLS_PORT;
08048 } else {
08049 portnum = STANDARD_SIP_PORT;
08050 }
08051 }
08052
08053 if (!(reg = ast_calloc(1, sizeof(*reg)))) {
08054 ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry entry\n");
08055 return -1;
08056 }
08057
08058 if (ast_string_field_init(reg, 256)) {
08059 ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry strings\n");
08060 ast_free(reg);
08061 return -1;
08062 }
08063
08064 ast_atomic_fetchadd_int(®objs, 1);
08065 ASTOBJ_INIT(reg);
08066 ast_string_field_set(reg, callback, ast_strip_quoted(S_OR(host2.extension, "s"), "\"", "\""));
08067 ast_string_field_set(reg, username, ast_strip_quoted(S_OR(user1.userpart, ""), "\"", "\""));
08068 ast_string_field_set(reg, hostname, ast_strip_quoted(S_OR(host3.host, ""), "\"", "\""));
08069 ast_string_field_set(reg, authuser, ast_strip_quoted(S_OR(user1.authuser, ""), "\"", "\""));
08070 ast_string_field_set(reg, secret, ast_strip_quoted(S_OR(user1.secret, ""), "\"", "\""));
08071 ast_string_field_set(reg, peername, ast_strip_quoted(S_OR(pre1.peer, ""), "\"", "\""));
08072
08073 reg->transport = transport;
08074 reg->timeout = reg->expire = -1;
08075 reg->refresh = reg->expiry = reg->configured_expiry = (host1.expiry ? atoi(ast_strip_quoted(host1.expiry, "\"", "\"")) : default_expiry);
08076 reg->portno = portnum;
08077 reg->callid_valid = FALSE;
08078 reg->ocseq = INITIAL_CSEQ;
08079 ASTOBJ_CONTAINER_LINK(®l, reg);
08080 registry_unref(reg, "unref the reg pointer");
08081 return 0;
08082 }
08083
08084
08085 static int sip_subscribe_mwi(const char *value, int lineno)
08086 {
08087 struct sip_subscription_mwi *mwi;
08088 int portnum = 0;
08089 enum sip_transport transport = SIP_TRANSPORT_UDP;
08090 char buf[256] = "";
08091 char *username = NULL, *hostname = NULL, *secret = NULL, *authuser = NULL, *porta = NULL, *mailbox = NULL;
08092
08093 if (!value) {
08094 return -1;
08095 }
08096
08097 ast_copy_string(buf, value, sizeof(buf));
08098
08099 sip_parse_host(buf, lineno, &username, &portnum, &transport);
08100
08101 if ((hostname = strrchr(username, '@'))) {
08102 *hostname++ = '\0';
08103 }
08104
08105 if ((secret = strchr(username, ':'))) {
08106 *secret++ = '\0';
08107 if ((authuser = strchr(secret, ':'))) {
08108 *authuser++ = '\0';
08109 }
08110 }
08111
08112 if ((mailbox = strchr(hostname, '/'))) {
08113 *mailbox++ = '\0';
08114 }
08115
08116 if (ast_strlen_zero(username) || ast_strlen_zero(hostname) || ast_strlen_zero(mailbox)) {
08117 ast_log(LOG_WARNING, "Format for MWI subscription is user[:secret[:authuser]]@host[:port][/mailbox] at line %d\n", lineno);
08118 return -1;
08119 }
08120
08121 if ((porta = strchr(hostname, ':'))) {
08122 *porta++ = '\0';
08123 if (!(portnum = atoi(porta))) {
08124 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
08125 return -1;
08126 }
08127 }
08128
08129 if (!(mwi = ast_calloc(1, sizeof(*mwi)))) {
08130 return -1;
08131 }
08132
08133 if (ast_string_field_init(mwi, 256)) {
08134 ast_free(mwi);
08135 return -1;
08136 }
08137
08138 ASTOBJ_INIT(mwi);
08139 ast_string_field_set(mwi, username, username);
08140 if (secret) {
08141 ast_string_field_set(mwi, secret, secret);
08142 }
08143 if (authuser) {
08144 ast_string_field_set(mwi, authuser, authuser);
08145 }
08146 ast_string_field_set(mwi, hostname, hostname);
08147 ast_string_field_set(mwi, mailbox, mailbox);
08148 mwi->resub = -1;
08149 mwi->portno = portnum;
08150 mwi->transport = transport;
08151
08152 ASTOBJ_CONTAINER_LINK(&submwil, mwi);
08153 ASTOBJ_UNREF(mwi, sip_subscribe_mwi_destroy);
08154
08155 return 0;
08156 }
08157
08158
08159
08160 static int lws2sws(char *msgbuf, int len)
08161 {
08162 int h = 0, t = 0;
08163 int lws = 0;
08164
08165 for (; h < len;) {
08166
08167 if (msgbuf[h] == '\r') {
08168 h++;
08169 continue;
08170 }
08171
08172 if (msgbuf[h] == '\n') {
08173
08174 if (h + 1 == len)
08175 break;
08176
08177 if (msgbuf[h + 1] == ' ' || msgbuf[h + 1] == '\t') {
08178
08179 h++;
08180 continue;
08181 }
08182
08183 msgbuf[t++] = msgbuf[h++];
08184 lws = 0;
08185 continue;
08186 }
08187 if (msgbuf[h] == ' ' || msgbuf[h] == '\t') {
08188 if (lws) {
08189 h++;
08190 continue;
08191 }
08192 msgbuf[t++] = msgbuf[h++];
08193 lws = 1;
08194 continue;
08195 }
08196 msgbuf[t++] = msgbuf[h++];
08197 if (lws)
08198 lws = 0;
08199 }
08200 msgbuf[t] = '\0';
08201 return t;
08202 }
08203
08204
08205
08206
08207 static int parse_request(struct sip_request *req)
08208 {
08209 char *c = req->data->str;
08210 ptrdiff_t *dst = req->header;
08211 int i = 0, lim = SIP_MAX_HEADERS - 1;
08212 unsigned int skipping_headers = 0;
08213 ptrdiff_t current_header_offset = 0;
08214 char *previous_header = "";
08215
08216 req->header[0] = 0;
08217 req->headers = -1;
08218 for (; *c; c++) {
08219 if (*c == '\r') {
08220 *c = '\0';
08221 } else if (*c == '\n') {
08222 *c = '\0';
08223 current_header_offset = (c + 1) - req->data->str;
08224 previous_header = req->data->str + dst[i];
08225 if (skipping_headers) {
08226
08227
08228
08229 if (ast_strlen_zero(previous_header)) {
08230 skipping_headers = 0;
08231 }
08232 dst[i] = current_header_offset;
08233 continue;
08234 }
08235 if (sipdebug) {
08236 ast_debug(4, "%7s %2d [%3d]: %s\n",
08237 req->headers < 0 ? "Header" : "Body",
08238 i, (int) strlen(previous_header), previous_header);
08239 }
08240 if (ast_strlen_zero(previous_header) && req->headers < 0) {
08241 req->headers = i;
08242 dst = req->line;
08243 i = 0;
08244 lim = SIP_MAX_LINES - 1;
08245 } else {
08246 if (i++ == lim) {
08247
08248
08249
08250 if (req->headers != -1) {
08251 break;
08252 } else {
08253 req->headers = i;
08254 dst = req->line;
08255 i = 0;
08256 lim = SIP_MAX_LINES - 1;
08257 skipping_headers = 1;
08258 }
08259 }
08260 }
08261 dst[i] = current_header_offset;
08262 }
08263 }
08264
08265
08266
08267
08268
08269
08270 previous_header = req->data->str + dst[i];
08271 if ((i < lim) && !ast_strlen_zero(previous_header)) {
08272 if (sipdebug) {
08273 ast_debug(4, "%7s %2d [%3d]: %s\n",
08274 req->headers < 0 ? "Header" : "Body",
08275 i, (int) strlen(previous_header), previous_header );
08276 }
08277 i++;
08278 }
08279
08280
08281 if (req->headers >= 0) {
08282 req->lines = i;
08283 } else {
08284 req->headers = i;
08285 req->lines = 0;
08286
08287 req->line[0] = ast_str_strlen(req->data);
08288 }
08289
08290 if (*c) {
08291 ast_log(LOG_WARNING, "Too many lines, skipping <%s>\n", c);
08292 }
08293
08294
08295 return determine_firstline_parts(req);
08296 }
08297
08298
08299
08300
08301
08302
08303
08304
08305
08306 static int find_sdp(struct sip_request *req)
08307 {
08308 const char *content_type;
08309 const char *content_length;
08310 const char *search;
08311 char *boundary;
08312 unsigned int x;
08313 int boundaryisquoted = FALSE;
08314 int found_application_sdp = FALSE;
08315 int found_end_of_headers = FALSE;
08316
08317 content_length = get_header(req, "Content-Length");
08318
08319 if (!ast_strlen_zero(content_length)) {
08320 if (sscanf(content_length, "%30u", &x) != 1) {
08321 ast_log(LOG_WARNING, "Invalid Content-Length: %s\n", content_length);
08322 return 0;
08323 }
08324
08325
08326
08327 if (x == 0)
08328 return 0;
08329 }
08330
08331 content_type = get_header(req, "Content-Type");
08332
08333
08334 if (!strncasecmp(content_type, "application/sdp", 15)) {
08335 req->sdp_start = 0;
08336 req->sdp_count = req->lines;
08337 return req->lines ? 1 : 0;
08338 }
08339
08340
08341 if (strncasecmp(content_type, "multipart/mixed", 15))
08342 return 0;
08343
08344
08345 if ((search = strcasestr(content_type, ";boundary=")))
08346 search += 10;
08347 else if ((search = strcasestr(content_type, "; boundary=")))
08348 search += 11;
08349 else
08350 return 0;
08351
08352 if (ast_strlen_zero(search))
08353 return 0;
08354
08355
08356 if (*search == '\"') {
08357 search++;
08358 boundaryisquoted = TRUE;
08359 }
08360
08361
08362
08363 boundary = ast_strdupa(search - 2);
08364 boundary[0] = boundary[1] = '-';
08365
08366 if (boundaryisquoted)
08367 boundary[strlen(boundary) - 1] = '\0';
08368
08369
08370
08371
08372 for (x = 0; x < (req->lines); x++) {
08373 char *line = REQ_OFFSET_TO_STR(req, line[x]);
08374 if (!strncasecmp(line, boundary, strlen(boundary))){
08375 if (found_application_sdp && found_end_of_headers) {
08376 req->sdp_count = (x - 1) - req->sdp_start;
08377 return 1;
08378 }
08379 found_application_sdp = FALSE;
08380 }
08381 if (!strcasecmp(line, "Content-Type: application/sdp"))
08382 found_application_sdp = TRUE;
08383
08384 if (ast_strlen_zero(line)) {
08385 if (found_application_sdp && !found_end_of_headers){
08386 req->sdp_start = x;
08387 found_end_of_headers = TRUE;
08388 }
08389 }
08390 }
08391 if (found_application_sdp && found_end_of_headers) {
08392 req->sdp_count = x - req->sdp_start;
08393 return TRUE;
08394 }
08395 return FALSE;
08396 }
08397
08398
08399 static void change_hold_state(struct sip_pvt *dialog, struct sip_request *req, int holdstate, int sendonly)
08400 {
08401 if (sip_cfg.notifyhold && (!holdstate || !ast_test_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD)))
08402 sip_peer_hold(dialog, holdstate);
08403 if (sip_cfg.callevents)
08404 manager_event(EVENT_FLAG_CALL, "Hold",
08405 "Status: %s\r\n"
08406 "Channel: %s\r\n"
08407 "Uniqueid: %s\r\n",
08408 holdstate ? "On" : "Off",
08409 dialog->owner->name,
08410 dialog->owner->uniqueid);
08411 append_history(dialog, holdstate ? "Hold" : "Unhold", "%s", req->data->str);
08412 if (!holdstate) {
08413 ast_clear_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD);
08414 return;
08415 }
08416
08417
08418 if (sendonly == 1)
08419 ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_ONEDIR);
08420 else if (sendonly == 2)
08421 ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_INACTIVE);
08422 else
08423 ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_ACTIVE);
08424 return;
08425 }
08426
08427 enum media_type {
08428 SDP_AUDIO,
08429 SDP_VIDEO,
08430 SDP_IMAGE,
08431 SDP_TEXT,
08432 };
08433
08434 static int get_ip_and_port_from_sdp(struct sip_request *req, const enum media_type media, struct sockaddr_in *sin)
08435 {
08436 const char *m;
08437 const char *c;
08438 int miterator = req->sdp_start;
08439 int citerator = req->sdp_start;
08440 int x = 0;
08441 int numberofports;
08442 int len;
08443 char host[258] = "";
08444 struct ast_hostent audiohp;
08445 struct hostent *hp;
08446
08447 c = get_sdp_iterate(&citerator, req, "c");
08448 if (sscanf(c, "IN IP4 %256s", host) != 1) {
08449 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
08450
08451 }
08452
08453 for (m = get_sdp_iterate(&miterator, req, "m"); !ast_strlen_zero(m); m = get_sdp_iterate(&miterator, req, "m")) {
08454 if ((media == SDP_AUDIO && ((sscanf(m, "audio %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08455 (sscanf(m, "audio %30u RTP/AVP %n", &x, &len) == 1 && len > 0))) ||
08456 (media == SDP_VIDEO && ((sscanf(m, "video %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08457 (sscanf(m, "video %30u RTP/AVP %n", &x, &len) == 1 && len > 0)))) {
08458
08459
08460
08461
08462 c = get_sdp_iterate(&citerator, req, "c");
08463 if (!ast_strlen_zero(c)) {
08464 sscanf(c, "IN IP4 %256s", host);
08465 }
08466 break;
08467 }
08468 }
08469
08470 if (ast_strlen_zero(host) || x == 0) {
08471 ast_log(LOG_WARNING, "Failed to read an alternate host or port in SDP. Expect %s problems\n", media == SDP_AUDIO ? "audio" : "video");
08472 return -1;
08473 }
08474
08475 hp = ast_gethostbyname(host, &audiohp);
08476 if (!hp) {
08477 ast_log(LOG_WARNING, "Could not look up IP address of alternate hostname. Expect %s problems\n", media == SDP_AUDIO? "audio" : "video");
08478 return -1;
08479 }
08480
08481 memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
08482 sin->sin_port = htons(x);
08483 return 0;
08484 }
08485
08486
08487
08488
08489
08490
08491 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action)
08492 {
08493
08494 int start = req->sdp_start;
08495 int next = start;
08496 int iterator = start;
08497
08498
08499 char type = '\0';
08500 const char *value = NULL;
08501 const char *m = NULL;
08502 const char *nextm = NULL;
08503 int len = -1;
08504
08505
08506 struct ast_hostent sessionhp;
08507 struct ast_hostent audiohp;
08508 struct ast_hostent videohp;
08509 struct ast_hostent texthp;
08510 struct ast_hostent imagehp;
08511 struct hostent *hp = NULL;
08512 struct hostent *vhp = NULL;
08513 struct hostent *thp = NULL;
08514 struct hostent *ihp = NULL;
08515 int portno = -1;
08516 int vportno = -1;
08517 int tportno = -1;
08518 int udptlportno = -1;
08519 struct sockaddr_in sin = { 0, };
08520 struct sockaddr_in vsin = { 0, };
08521 struct sockaddr_in isin = { 0, };
08522 struct sockaddr_in tsin = { 0, };
08523
08524
08525 int peercapability = 0, peernoncodeccapability = 0;
08526 int vpeercapability = 0, vpeernoncodeccapability = 0;
08527 int tpeercapability = 0, tpeernoncodeccapability = 0;
08528
08529 struct ast_rtp *newaudiortp, *newvideortp, *newtextrtp;
08530 int newjointcapability;
08531 int newpeercapability;
08532 int newnoncodeccapability;
08533
08534 const char *codecs;
08535 int codec;
08536
08537
08538 int sendonly = -1;
08539 int vsendonly = -1;
08540 int numberofports;
08541 int numberofmediastreams = 0;
08542 int last_rtpmap_codec = 0;
08543 int red_data_pt[10];
08544 int red_num_gen = 0;
08545 char red_fmtp[100] = "empty";
08546 int debug = sip_debug_test_pvt(p);
08547
08548
08549 char buf[SIPBUFSIZE];
08550
08551
08552
08553 if (!p->rtp) {
08554 ast_log(LOG_ERROR, "Got SDP but have no RTP session allocated.\n");
08555 return -1;
08556 }
08557
08558
08559 #ifdef LOW_MEMORY
08560 newaudiortp = ast_threadstorage_get(&ts_audio_rtp, ast_rtp_alloc_size());
08561 #else
08562 newaudiortp = alloca(ast_rtp_alloc_size());
08563 #endif
08564 memset(newaudiortp, 0, ast_rtp_alloc_size());
08565 ast_rtp_new_init(newaudiortp);
08566 ast_rtp_pt_clear(newaudiortp);
08567
08568 #ifdef LOW_MEMORY
08569 newvideortp = ast_threadstorage_get(&ts_video_rtp, ast_rtp_alloc_size());
08570 #else
08571 newvideortp = alloca(ast_rtp_alloc_size());
08572 #endif
08573 memset(newvideortp, 0, ast_rtp_alloc_size());
08574 ast_rtp_new_init(newvideortp);
08575 ast_rtp_pt_clear(newvideortp);
08576
08577 #ifdef LOW_MEMORY
08578 newtextrtp = ast_threadstorage_get(&ts_text_rtp, ast_rtp_alloc_size());
08579 #else
08580 newtextrtp = alloca(ast_rtp_alloc_size());
08581 #endif
08582 memset(newtextrtp, 0, ast_rtp_alloc_size());
08583 ast_rtp_new_init(newtextrtp);
08584 ast_rtp_pt_clear(newtextrtp);
08585
08586
08587 p->lastrtprx = p->lastrtptx = time(NULL);
08588
08589 memset(p->offered_media, 0, sizeof(p->offered_media));
08590
08591
08592
08593 p->novideo = TRUE;
08594 p->notext = TRUE;
08595
08596 if (p->vrtp)
08597 ast_rtp_pt_clear(newvideortp);
08598
08599 if (p->trtp)
08600 ast_rtp_pt_clear(newtextrtp);
08601
08602
08603 nextm = get_sdp_iterate(&next, req, "m");
08604 if (ast_strlen_zero(nextm)) {
08605 ast_log(LOG_WARNING, "Insufficient information for SDP (m= not found)\n");
08606 return -1;
08607 }
08608
08609
08610 while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
08611 int processed = FALSE;
08612 switch (type) {
08613 case 'o':
08614
08615
08616
08617 if (!process_sdp_o(value, p))
08618 return (p->session_modify == FALSE) ? 0 : -1;
08619 break;
08620 case 'c':
08621 if (process_sdp_c(value, &sessionhp)) {
08622 processed = TRUE;
08623 hp = &sessionhp.hp;
08624 vhp = hp;
08625 thp = hp;
08626 ihp = hp;
08627 }
08628 break;
08629 case 'a':
08630 if (process_sdp_a_sendonly(value, &sendonly)) {
08631 processed = TRUE;
08632 vsendonly = sendonly;
08633 }
08634 else if (process_sdp_a_audio(value, p, newaudiortp, &last_rtpmap_codec))
08635 processed = TRUE;
08636 else if (process_sdp_a_video(value, p, newvideortp, &last_rtpmap_codec))
08637 processed = TRUE;
08638 else if (process_sdp_a_text(value, p, newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec))
08639 processed = TRUE;
08640 else if (process_sdp_a_image(value, p))
08641 processed = TRUE;
08642 break;
08643 }
08644
08645 if (option_debug > 2)
08646 ast_log(LOG_DEBUG, "Processing session-level SDP %c=%s... %s\n", type, value, (processed == TRUE)? "OK." : "UNSUPPORTED.");
08647 }
08648
08649
08650
08651
08652 while (!ast_strlen_zero(nextm)) {
08653 int audio = FALSE;
08654 int video = FALSE;
08655 int image = FALSE;
08656 int text = FALSE;
08657 int x;
08658
08659 numberofports = 1;
08660 len = -1;
08661 start = next;
08662 m = nextm;
08663 iterator = next;
08664 nextm = get_sdp_iterate(&next, req, "m");
08665
08666
08667 if ((sscanf(m, "audio %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08668 (sscanf(m, "audio %30u RTP/AVP %n", &x, &len) == 1 && len > 0)) {
08669 audio = TRUE;
08670 p->offered_media[SDP_AUDIO].offered = TRUE;
08671 numberofmediastreams++;
08672 portno = x;
08673
08674
08675 codecs = m + len;
08676 ast_copy_string(p->offered_media[SDP_AUDIO].text, codecs, sizeof(p->offered_media[SDP_AUDIO].text));
08677 for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
08678 if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
08679 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
08680 return -1;
08681 }
08682 if (debug)
08683 ast_verbose("Found RTP audio format %d\n", codec);
08684
08685 ast_rtp_set_m_type(newaudiortp, codec);
08686 }
08687
08688 } else if ((sscanf(m, "video %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08689 (sscanf(m, "video %30u RTP/AVP %n", &x, &len) == 1 && len >= 0)) {
08690 video = TRUE;
08691 p->novideo = FALSE;
08692 p->offered_media[SDP_VIDEO].offered = TRUE;
08693 numberofmediastreams++;
08694 vportno = x;
08695
08696
08697 codecs = m + len;
08698 ast_copy_string(p->offered_media[SDP_VIDEO].text, codecs, sizeof(p->offered_media[SDP_VIDEO].text));
08699 for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
08700 if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
08701 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
08702 return -1;
08703 }
08704 if (debug)
08705 ast_verbose("Found RTP video format %d\n", codec);
08706 ast_rtp_set_m_type(newvideortp, codec);
08707 }
08708
08709 } else if ((sscanf(m, "text %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08710 (sscanf(m, "text %30u RTP/AVP %n", &x, &len) == 1 && len > 0)) {
08711 text = TRUE;
08712 p->notext = FALSE;
08713 p->offered_media[SDP_TEXT].offered = TRUE;
08714 numberofmediastreams++;
08715 tportno = x;
08716
08717
08718 codecs = m + len;
08719 ast_copy_string(p->offered_media[SDP_TEXT].text, codecs, sizeof(p->offered_media[SDP_TEXT].text));
08720 for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
08721 if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
08722 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
08723 return -1;
08724 }
08725 if (debug)
08726 ast_verbose("Found RTP text format %d\n", codec);
08727 ast_rtp_set_m_type(newtextrtp, codec);
08728 }
08729
08730 } else if (p->udptl && ((sscanf(m, "image %30u udptl t38%n", &x, &len) == 1 && len > 0) ||
08731 (sscanf(m, "image %30u UDPTL t38%n", &x, &len) == 1 && len > 0) )) {
08732 image = TRUE;
08733 if (debug)
08734 ast_verbose("Got T.38 offer in SDP in dialog %s\n", p->callid);
08735 p->offered_media[SDP_IMAGE].offered = TRUE;
08736 udptlportno = x;
08737 numberofmediastreams++;
08738
08739 if (p->t38.state != T38_ENABLED) {
08740 memset(&p->t38.their_parms, 0, sizeof(p->t38.their_parms));
08741
08742
08743
08744 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
08745 }
08746 } else {
08747 ast_log(LOG_WARNING, "Unsupported SDP media type in offer: %s\n", m);
08748 continue;
08749 }
08750
08751
08752 if (numberofports > 1)
08753 ast_log(LOG_WARNING, "SDP offered %d ports for media, not supported by Asterisk. Will try anyway...\n", numberofports);
08754
08755
08756
08757
08758 while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
08759 int processed = FALSE;
08760
08761 switch (type) {
08762 case 'c':
08763 if (audio) {
08764 if (process_sdp_c(value, &audiohp)) {
08765 processed = TRUE;
08766 hp = &audiohp.hp;
08767 }
08768 } else if (video) {
08769 if (process_sdp_c(value, &videohp)) {
08770 processed = TRUE;
08771 vhp = &videohp.hp;
08772 }
08773 } else if (text) {
08774 if (process_sdp_c(value, &texthp)) {
08775 processed = TRUE;
08776 thp = &texthp.hp;
08777 }
08778 } else if (image) {
08779 if (process_sdp_c(value, &imagehp)) {
08780 processed = TRUE;
08781 ihp = &imagehp.hp;
08782 }
08783 }
08784 break;
08785 case 'a':
08786
08787 if (audio) {
08788 if (process_sdp_a_sendonly(value, &sendonly))
08789 processed = TRUE;
08790 else if (process_sdp_a_audio(value, p, newaudiortp, &last_rtpmap_codec))
08791 processed = TRUE;
08792 }
08793
08794 else if (video) {
08795 if (process_sdp_a_sendonly(value, &vsendonly))
08796 processed = TRUE;
08797 else if (process_sdp_a_video(value, p, newvideortp, &last_rtpmap_codec))
08798 processed = TRUE;
08799 }
08800
08801 else if (text) {
08802 if (process_sdp_a_text(value, p, newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec))
08803 processed = TRUE;
08804 }
08805
08806 else if (image) {
08807 if (process_sdp_a_image(value, p))
08808 processed = TRUE;
08809 }
08810 break;
08811 }
08812
08813 if (option_debug > 2)
08814 ast_log(LOG_DEBUG, "Processing media-level (%s) SDP %c=%s... %s\n",
08815 (audio == TRUE)? "audio" : (video == TRUE)? "video" : "image",
08816 type, value,
08817 (processed == TRUE)? "OK." : "UNSUPPORTED.");
08818 }
08819 }
08820
08821
08822
08823 if (!hp && !vhp && !thp && !ihp) {
08824 ast_log(LOG_WARNING, "Insufficient information in SDP (c=)...\n");
08825 return -1;
08826 }
08827
08828 if (portno == -1 && vportno == -1 && udptlportno == -1 && tportno == -1)
08829
08830
08831 return -2;
08832
08833 if (numberofmediastreams > 3)
08834
08835 return -3;
08836
08837 if (udptlportno == -1) {
08838 change_t38_state(p, T38_DISABLED);
08839 }
08840
08841
08842
08843 ast_rtp_get_current_formats(newaudiortp, &peercapability, &peernoncodeccapability);
08844 ast_rtp_get_current_formats(newvideortp, &vpeercapability, &vpeernoncodeccapability);
08845 ast_rtp_get_current_formats(newtextrtp, &tpeercapability, &tpeernoncodeccapability);
08846
08847 newjointcapability = p->capability & (peercapability | vpeercapability | tpeercapability);
08848 newpeercapability = (peercapability | vpeercapability | tpeercapability);
08849 newnoncodeccapability = p->noncodeccapability & peernoncodeccapability;
08850
08851 if (debug) {
08852
08853 char s1[SIPBUFSIZE], s2[SIPBUFSIZE], s3[SIPBUFSIZE], s4[SIPBUFSIZE], s5[SIPBUFSIZE];
08854
08855 ast_verbose("Capabilities: us - %s, peer - audio=%s/video=%s/text=%s, combined - %s\n",
08856 ast_getformatname_multiple(s1, SIPBUFSIZE, p->capability),
08857 ast_getformatname_multiple(s2, SIPBUFSIZE, peercapability),
08858 ast_getformatname_multiple(s3, SIPBUFSIZE, vpeercapability),
08859 ast_getformatname_multiple(s4, SIPBUFSIZE, tpeercapability),
08860 ast_getformatname_multiple(s5, SIPBUFSIZE, newjointcapability));
08861
08862 ast_verbose("Non-codec capabilities (dtmf): us - %s, peer - %s, combined - %s\n",
08863 ast_rtp_lookup_mime_multiple(s1, SIPBUFSIZE, p->noncodeccapability, 0, 0),
08864 ast_rtp_lookup_mime_multiple(s2, SIPBUFSIZE, peernoncodeccapability, 0, 0),
08865 ast_rtp_lookup_mime_multiple(s3, SIPBUFSIZE, newnoncodeccapability, 0, 0));
08866 }
08867 if (!newjointcapability && (portno != -1)) {
08868 ast_log(LOG_NOTICE, "No compatible codecs, not accepting this offer!\n");
08869
08870 return -1;
08871 }
08872
08873
08874 if (p->rtp) {
08875 if (portno > 0) {
08876 sin.sin_family = AF_INET;
08877 sin.sin_port = htons(portno);
08878 memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
08879 ast_rtp_set_peer(p->rtp, &sin);
08880 if (debug)
08881 ast_verbose("Peer audio RTP is at port %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
08882
08883
08884 p->jointcapability = newjointcapability;
08885 p->peercapability = newpeercapability;
08886 p->jointnoncodeccapability = newnoncodeccapability;
08887
08888 ast_rtp_pt_copy(p->rtp, newaudiortp);
08889
08890 if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) {
08891 ast_clear_flag(&p->flags[0], SIP_DTMF);
08892 if (newnoncodeccapability & AST_RTP_DTMF) {
08893
08894 ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
08895
08896 ast_rtp_setdtmf(p->rtp, 1);
08897 ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
08898 } else {
08899 ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
08900 }
08901 }
08902 } else if (udptlportno > 0) {
08903 if (debug)
08904 ast_verbose("Got T.38 Re-invite without audio. Keeping RTP active during T.38 session.\n");
08905 } else {
08906 ast_rtp_stop(p->rtp);
08907 if (debug)
08908 ast_verbose("Peer doesn't provide audio\n");
08909 }
08910 }
08911
08912
08913 if (p->vrtp) {
08914 if (vportno > 0) {
08915 vsin.sin_family = AF_INET;
08916 vsin.sin_port = htons(vportno);
08917 memcpy(&vsin.sin_addr, vhp->h_addr, sizeof(vsin.sin_addr));
08918 ast_rtp_set_peer(p->vrtp, &vsin);
08919 if (debug)
08920 ast_verbose("Peer video RTP is at port %s:%d\n", ast_inet_ntoa(vsin.sin_addr), ntohs(vsin.sin_port));
08921 ast_rtp_pt_copy(p->vrtp, newvideortp);
08922 } else {
08923 ast_rtp_stop(p->vrtp);
08924 if (debug)
08925 ast_verbose("Peer doesn't provide video\n");
08926 }
08927 }
08928
08929
08930 if (p->trtp) {
08931 if (tportno > 0) {
08932 tsin.sin_family = AF_INET;
08933 tsin.sin_port = htons(tportno);
08934 memcpy(&tsin.sin_addr, thp->h_addr, sizeof(tsin.sin_addr));
08935 ast_rtp_set_peer(p->trtp, &tsin);
08936 if (debug)
08937 ast_verbose("Peer T.140 RTP is at port %s:%d\n", ast_inet_ntoa(tsin.sin_addr), ntohs(tsin.sin_port));
08938 if ((p->jointcapability & AST_FORMAT_T140RED)) {
08939 p->red = 1;
08940 rtp_red_init(p->trtp, 300, red_data_pt, 2);
08941 } else {
08942 p->red = 0;
08943 }
08944 ast_rtp_pt_copy(p->trtp, newtextrtp);
08945 } else {
08946 ast_rtp_stop(p->trtp);
08947 if (debug)
08948 ast_verbose("Peer doesn't provide T.140\n");
08949 }
08950 }
08951
08952 if (p->udptl) {
08953 if (udptlportno > 0) {
08954 isin.sin_family = AF_INET;
08955 isin.sin_port = htons(udptlportno);
08956 if (ast_test_flag(&p->flags[0], SIP_NAT) && ast_test_flag(&p->flags[1], SIP_PAGE2_UDPTL_DESTINATION)) {
08957 struct sockaddr_in remote_address = { 0, };
08958 ast_rtp_get_peer(p->rtp, &remote_address);
08959 if (remote_address.sin_addr.s_addr) {
08960 memcpy(&isin, &remote_address, sizeof(isin));
08961 if (debug) {
08962 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));
08963 }
08964 }
08965 } else {
08966 memcpy(&isin.sin_addr, ihp->h_addr, sizeof(isin.sin_addr));
08967 }
08968 ast_udptl_set_peer(p->udptl, &isin);
08969 if (debug)
08970 ast_debug(1,"Peer T.38 UDPTL is at port %s:%d\n", ast_inet_ntoa(isin.sin_addr), ntohs(isin.sin_port));
08971
08972
08973 if (!ast_udptl_get_far_max_datagram(p->udptl)) {
08974
08975 ast_udptl_set_far_max_datagram(p->udptl, 0);
08976 }
08977
08978
08979 if ((t38action == SDP_T38_ACCEPT) &&
08980 (p->t38.state == T38_LOCAL_REINVITE)) {
08981 change_t38_state(p, T38_ENABLED);
08982 } else if ((t38action == SDP_T38_INITIATE) &&
08983 p->owner && p->lastinvite) {
08984 change_t38_state(p, T38_PEER_REINVITE);
08985
08986 if (ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_T38)) {
08987 ast_channel_lock(p->owner);
08988 if (strcmp(p->owner->exten, "fax")) {
08989 const char *target_context = S_OR(p->owner->macrocontext, p->owner->context);
08990 ast_channel_unlock(p->owner);
08991 if (ast_exists_extension(p->owner, target_context, "fax", 1, p->owner->cid.cid_num)) {
08992 ast_verbose(VERBOSE_PREFIX_2 "Redirecting '%s' to fax extension due to peer T.38 re-INVITE\n", p->owner->name);
08993 pbx_builtin_setvar_helper(p->owner, "FAXEXTEN", p->owner->exten);
08994 if (ast_async_goto(p->owner, target_context, "fax", 1)) {
08995 ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", p->owner->name, target_context);
08996 }
08997 } else {
08998 ast_log(LOG_NOTICE, "T.38 re-INVITE detected but no fax extension\n");
08999 }
09000 } else {
09001 ast_channel_unlock(p->owner);
09002 }
09003 }
09004 }
09005 } else {
09006 ast_udptl_stop(p->udptl);
09007 if (debug)
09008 ast_debug(1, "Peer doesn't provide T.38 UDPTL\n");
09009 }
09010 }
09011
09012 if ((portno == -1) && (p->t38.state != T38_DISABLED)) {
09013 ast_debug(3, "Have T.38 but no audio, accepting offer anyway\n");
09014 return 0;
09015 }
09016
09017
09018 ast_debug(2, "We're settling with these formats: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, p->jointcapability));
09019
09020 if (!p->owner)
09021 return 0;
09022
09023 ast_debug(4, "We have an owner, now see if we need to change this call\n");
09024
09025 if (!(p->owner->nativeformats & p->jointcapability) && (p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
09026 if (debug) {
09027 char s1[SIPBUFSIZE], s2[SIPBUFSIZE];
09028 ast_debug(1, "Oooh, we need to change our audio formats since our peer supports only %s and not %s\n",
09029 ast_getformatname_multiple(s1, SIPBUFSIZE, p->jointcapability),
09030 ast_getformatname_multiple(s2, SIPBUFSIZE, p->owner->nativeformats));
09031 }
09032 p->owner->nativeformats = ast_codec_choose(&p->prefs, p->jointcapability, 1) | (p->capability & vpeercapability) | (p->capability & tpeercapability);
09033 ast_set_read_format(p->owner, p->owner->readformat);
09034 ast_set_write_format(p->owner, p->owner->writeformat);
09035 }
09036
09037 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)
09038 && (sin.sin_addr.s_addr || vsin.sin_addr.s_addr ||
09039 isin.sin_addr.s_addr || tsin.sin_addr.s_addr)
09040 && (!sendonly || sendonly == -1)) {
09041 ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
09042
09043 ast_queue_frame(p->owner, &ast_null_frame);
09044 change_hold_state(p, req, FALSE, sendonly);
09045 } else if (!(sin.sin_addr.s_addr || vsin.sin_addr.s_addr ||
09046 isin.sin_addr.s_addr || tsin.sin_addr.s_addr)
09047 || (sendonly && sendonly != -1)) {
09048 ast_queue_control_data(p->owner, AST_CONTROL_HOLD,
09049 S_OR(p->mohsuggest, NULL),
09050 !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
09051 if (sendonly)
09052 ast_rtp_stop(p->rtp);
09053
09054
09055 ast_queue_frame(p->owner, &ast_null_frame);
09056 change_hold_state(p, req, TRUE, sendonly);
09057 }
09058
09059 return 0;
09060 }
09061
09062 static int process_sdp_o(const char *o, struct sip_pvt *p)
09063 {
09064 char *o_copy;
09065 char *token;
09066 int64_t rua_version;
09067
09068
09069
09070
09071
09072
09073
09074
09075
09076
09077 p->session_modify = TRUE;
09078
09079 if (ast_strlen_zero(o)) {
09080 ast_log(LOG_WARNING, "SDP syntax error. SDP without an o= line\n");
09081 return FALSE;
09082 }
09083
09084 o_copy = ast_strdupa(o);
09085 token = strsep(&o_copy, " ");
09086 if (!o_copy) {
09087 ast_log(LOG_WARNING, "SDP syntax error in o= line username\n");
09088 return FALSE;
09089 }
09090 token = strsep(&o_copy, " ");
09091 if (!o_copy) {
09092 ast_log(LOG_WARNING, "SDP syntax error in o= line session-id\n");
09093 return FALSE;
09094 }
09095 token = strsep(&o_copy, " ");
09096 if (!o_copy) {
09097 ast_log(LOG_WARNING, "SDP syntax error in o= line\n");
09098 return FALSE;
09099 }
09100 if (!sscanf(token, "%30" SCNd64, &rua_version)) {
09101 ast_log(LOG_WARNING, "SDP syntax error in o= line version\n");
09102 return FALSE;
09103 }
09104
09105
09106
09107
09108
09109
09110
09111
09112
09113
09114
09115
09116
09117
09118
09119
09120
09121
09122
09123 if (ast_test_flag(&p->flags[1], SIP_PAGE2_IGNORESDPVERSION) ||
09124 (p->sessionversion_remote < 0) ||
09125 (p->sessionversion_remote < rua_version)) {
09126 p->sessionversion_remote = rua_version;
09127 } else {
09128 if (p->t38.state == T38_LOCAL_REINVITE) {
09129 p->sessionversion_remote = rua_version;
09130 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);
09131 } else {
09132 p->session_modify = FALSE;
09133 ast_debug(2, "Call %s responded to our reinvite without changing SDP version; ignoring SDP.\n", p->callid);
09134 return FALSE;
09135 }
09136 }
09137
09138 return TRUE;
09139 }
09140
09141 static int process_sdp_c(const char *c, struct ast_hostent *ast_hp)
09142 {
09143 char host[258];
09144 struct hostent *hp;
09145
09146
09147 if (sscanf(c, "IN IP4 %255s", host) != 1) {
09148 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
09149 return FALSE;
09150 } else {
09151 if (!(hp = ast_gethostbyname(host, ast_hp))) {
09152 ast_log(LOG_WARNING, "Unable to lookup RTP Audio host in c= line, '%s'\n", c);
09153 return FALSE;
09154 }
09155 return TRUE;
09156 }
09157 return FALSE;
09158 }
09159
09160 static int process_sdp_a_sendonly(const char *a, int *sendonly)
09161 {
09162 int found = FALSE;
09163
09164 if (!strcasecmp(a, "sendonly")) {
09165 if (*sendonly == -1)
09166 *sendonly = 1;
09167 found = TRUE;
09168 } else if (!strcasecmp(a, "inactive")) {
09169 if (*sendonly == -1)
09170 *sendonly = 2;
09171 found = TRUE;
09172 } else if (!strcasecmp(a, "sendrecv")) {
09173 if (*sendonly == -1)
09174 *sendonly = 0;
09175 found = TRUE;
09176 }
09177 return found;
09178 }
09179
09180 static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp *newaudiortp, int *last_rtpmap_codec)
09181 {
09182 int found = FALSE;
09183 int codec;
09184 char mimeSubtype[128];
09185 char fmtp_string[64];
09186 unsigned int sample_rate;
09187 int debug = sip_debug_test_pvt(p);
09188
09189 if (!strncasecmp(a, "ptime", 5)) {
09190 char *tmp = strrchr(a, ':');
09191 long int framing = 0;
09192 if (tmp) {
09193 tmp++;
09194 framing = strtol(tmp, NULL, 10);
09195 if (framing == LONG_MIN || framing == LONG_MAX) {
09196 framing = 0;
09197 ast_debug(1, "Can't read framing from SDP: %s\n", a);
09198 }
09199 }
09200 if (framing && p->autoframing) {
09201 struct ast_codec_pref *pref = ast_rtp_codec_getpref(p->rtp);
09202 int codec_n;
09203 int format = 0;
09204 for (codec_n = 0; codec_n < MAX_RTP_PT; codec_n++) {
09205 format = ast_rtp_codec_getformat(codec_n);
09206 if (!format)
09207 continue;
09208 if (option_debug)
09209 ast_log(LOG_DEBUG, "Setting framing for %d to %ld\n", format, framing);
09210 ast_codec_pref_setsize(pref, format, framing);
09211 }
09212 ast_rtp_codec_setpref(p->rtp, pref);
09213 }
09214 found = TRUE;
09215 } else if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
09216
09217 if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
09218 if (ast_rtp_set_rtpmap_type_rate(newaudiortp, codec, "audio", mimeSubtype,
09219 ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0, sample_rate) != -1) {
09220 if (debug)
09221 ast_verbose("Found audio description format %s for ID %d\n", mimeSubtype, codec);
09222
09223 (*last_rtpmap_codec)++;
09224 found = TRUE;
09225 } else {
09226 ast_rtp_unset_m_type(newaudiortp, codec);
09227 if (debug)
09228 ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
09229 }
09230 } else {
09231 if (debug)
09232 ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
09233 }
09234 } else if (sscanf(a, "fmtp: %30u %63s", &codec, fmtp_string) == 2) {
09235 struct rtpPayloadType payload;
09236
09237 payload = ast_rtp_lookup_pt(newaudiortp, codec);
09238 if (payload.code && payload.isAstFormat) {
09239 unsigned int bit_rate;
09240
09241 switch (payload.code) {
09242 case AST_FORMAT_SIREN7:
09243 if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
09244 if (bit_rate != 32000) {
09245 ast_log(LOG_WARNING, "Got Siren7 offer at %d bps, but only 32000 bps supported; ignoring.\n", bit_rate);
09246 ast_rtp_unset_m_type(newaudiortp, codec);
09247 } else {
09248 found = TRUE;
09249 }
09250 }
09251 break;
09252 case AST_FORMAT_SIREN14:
09253 if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
09254 if (bit_rate != 48000) {
09255 ast_log(LOG_WARNING, "Got Siren14 offer at %d bps, but only 48000 bps supported; ignoring.\n", bit_rate);
09256 ast_rtp_unset_m_type(newaudiortp, codec);
09257 } else {
09258 found = TRUE;
09259 }
09260 }
09261 break;
09262 }
09263 }
09264 }
09265
09266 return found;
09267 }
09268
09269 static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp *newvideortp, int *last_rtpmap_codec)
09270 {
09271 int found = FALSE;
09272 int codec;
09273 char mimeSubtype[128];
09274 unsigned int sample_rate;
09275 int debug = sip_debug_test_pvt(p);
09276
09277 if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
09278
09279 if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
09280
09281 if (!strncasecmp(mimeSubtype, "H26", 3) || !strncasecmp(mimeSubtype, "MP4", 3)) {
09282 if (ast_rtp_set_rtpmap_type_rate(newvideortp, codec, "video", mimeSubtype, 0, sample_rate) != -1) {
09283 if (debug)
09284 ast_verbose("Found video description format %s for ID %d\n", mimeSubtype, codec);
09285
09286 (*last_rtpmap_codec)++;
09287 found = TRUE;
09288 } else {
09289 ast_rtp_unset_m_type(newvideortp, codec);
09290 if (debug)
09291 ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
09292 }
09293 }
09294 } else {
09295 if (debug)
09296 ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
09297 }
09298 }
09299
09300 return found;
09301 }
09302
09303 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)
09304 {
09305 int found = FALSE;
09306 int codec;
09307 char mimeSubtype[128];
09308 unsigned int sample_rate;
09309 char *red_cp;
09310 int debug = sip_debug_test_pvt(p);
09311
09312 if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
09313
09314 if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
09315 if (!strncasecmp(mimeSubtype, "T140", 4)) {
09316 if (p->trtp) {
09317
09318 ast_rtp_set_rtpmap_type(newtextrtp, codec, "text", mimeSubtype, 0);
09319 found = TRUE;
09320 }
09321 } else if (!strncasecmp(mimeSubtype, "RED", 3)) {
09322 if (p->trtp) {
09323 ast_rtp_set_rtpmap_type(newtextrtp, codec, "text", mimeSubtype, 0);
09324 sprintf(red_fmtp, "fmtp:%d ", codec);
09325 if (debug)
09326 ast_verbose("RED submimetype has payload type: %d\n", codec);
09327 found = TRUE;
09328 }
09329 }
09330 } else {
09331 if (debug)
09332 ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
09333 }
09334 } else if (!strncmp(a, red_fmtp, strlen(red_fmtp))) {
09335
09336 red_cp = &red_fmtp[strlen(red_fmtp)];
09337 strncpy(red_fmtp, a, 100);
09338
09339 sscanf(red_cp, "%30u", &red_data_pt[*red_num_gen]);
09340 red_cp = strtok(red_cp, "/");
09341 while (red_cp && (*red_num_gen)++ < RED_MAX_GENERATION) {
09342 sscanf(red_cp, "%30u", &red_data_pt[*red_num_gen]);
09343 red_cp = strtok(NULL, "/");
09344 }
09345 red_cp = red_fmtp;
09346 found = TRUE;
09347 }
09348
09349 return found;
09350 }
09351
09352 static int process_sdp_a_image(const char *a, struct sip_pvt *p)
09353 {
09354 int found = FALSE;
09355 char s[256];
09356 unsigned int x;
09357
09358 if ((sscanf(a, "T38FaxMaxBuffer:%30u", &x) == 1)) {
09359 ast_debug(3, "MaxBufferSize:%d\n", x);
09360 found = TRUE;
09361 } else if ((sscanf(a, "T38MaxBitRate:%30u", &x) == 1) || (sscanf(a, "T38FaxMaxRate:%30u", &x) == 1)) {
09362 ast_debug(3, "T38MaxBitRate: %d\n", x);
09363 switch (x) {
09364 case 14400:
09365 p->t38.their_parms.rate = AST_T38_RATE_14400;
09366 break;
09367 case 12000:
09368 p->t38.their_parms.rate = AST_T38_RATE_12000;
09369 break;
09370 case 9600:
09371 p->t38.their_parms.rate = AST_T38_RATE_9600;
09372 break;
09373 case 7200:
09374 p->t38.their_parms.rate = AST_T38_RATE_7200;
09375 break;
09376 case 4800:
09377 p->t38.their_parms.rate = AST_T38_RATE_4800;
09378 break;
09379 case 2400:
09380 p->t38.their_parms.rate = AST_T38_RATE_2400;
09381 break;
09382 }
09383 found = TRUE;
09384 } else if ((sscanf(a, "T38FaxVersion:%30u", &x) == 1)) {
09385 ast_debug(3, "FaxVersion: %u\n", x);
09386 p->t38.their_parms.version = x;
09387 found = TRUE;
09388 } else if ((sscanf(a, "T38FaxMaxDatagram:%30u", &x) == 1) || (sscanf(a, "T38MaxDatagram:%30u", &x) == 1)) {
09389
09390 if (((signed int) p->t38_maxdatagram >= 0) && ((unsigned int) p->t38_maxdatagram > x)) {
09391 ast_debug(1, "Overriding T38FaxMaxDatagram '%d' with '%d'\n", x, p->t38_maxdatagram);
09392 x = p->t38_maxdatagram;
09393 }
09394 ast_debug(3, "FaxMaxDatagram: %u\n", x);
09395 ast_udptl_set_far_max_datagram(p->udptl, x);
09396 found = TRUE;
09397 } else if ((strncmp(a, "T38FaxFillBitRemoval", 20) == 0)) {
09398 if (sscanf(a, "T38FaxFillBitRemoval:%30u", &x) == 1) {
09399 ast_debug(3, "FillBitRemoval: %d\n", x);
09400 if (x == 1) {
09401 p->t38.their_parms.fill_bit_removal = TRUE;
09402 }
09403 } else {
09404 ast_debug(3, "FillBitRemoval\n");
09405 p->t38.their_parms.fill_bit_removal = TRUE;
09406 }
09407 found = TRUE;
09408 } else if ((strncmp(a, "T38FaxTranscodingMMR", 20) == 0)) {
09409 if (sscanf(a, "T38FaxTranscodingMMR:%30u", &x) == 1) {
09410 ast_debug(3, "Transcoding MMR: %d\n", x);
09411 if (x == 1) {
09412 p->t38.their_parms.transcoding_mmr = TRUE;
09413 }
09414 } else {
09415 ast_debug(3, "Transcoding MMR\n");
09416 p->t38.their_parms.transcoding_mmr = TRUE;
09417 }
09418 found = TRUE;
09419 } else if ((strncmp(a, "T38FaxTranscodingJBIG", 21) == 0)) {
09420 if (sscanf(a, "T38FaxTranscodingJBIG:%30u", &x) == 1) {
09421 ast_debug(3, "Transcoding JBIG: %d\n", x);
09422 if (x == 1) {
09423 p->t38.their_parms.transcoding_jbig = TRUE;
09424 }
09425 } else {
09426 ast_debug(3, "Transcoding JBIG\n");
09427 p->t38.their_parms.transcoding_jbig = TRUE;
09428 }
09429 found = TRUE;
09430 } else if ((sscanf(a, "T38FaxRateManagement:%255s", s) == 1)) {
09431 ast_debug(3, "RateManagement: %s\n", s);
09432 if (!strcasecmp(s, "localTCF"))
09433 p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_LOCAL_TCF;
09434 else if (!strcasecmp(s, "transferredTCF"))
09435 p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF;
09436 found = TRUE;
09437 } else if ((sscanf(a, "T38FaxUdpEC:%255s", s) == 1)) {
09438 ast_debug(3, "UDP EC: %s\n", s);
09439 if (!strcasecmp(s, "t38UDPRedundancy")) {
09440 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
09441 } else if (!strcasecmp(s, "t38UDPFEC")) {
09442 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
09443 } else {
09444 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
09445 }
09446 found = TRUE;
09447 }
09448
09449 return found;
09450 }
09451
09452
09453 #ifdef LOW_MEMORY
09454 static void ts_ast_rtp_destroy(void *data)
09455 {
09456 struct ast_rtp *tmp = data;
09457 ast_rtp_destroy(tmp);
09458 }
09459 #endif
09460
09461
09462
09463
09464 static int add_supported_header(struct sip_pvt *pvt, struct sip_request *req)
09465 {
09466 int res;
09467 if (st_get_mode(pvt) != SESSION_TIMER_MODE_REFUSE) {
09468 res = add_header(req, "Supported", "replaces, timer");
09469 } else {
09470 res = add_header(req, "Supported", "replaces");
09471 }
09472 return res;
09473 }
09474
09475
09476 static int add_header(struct sip_request *req, const char *var, const char *value)
09477 {
09478 if (req->headers == SIP_MAX_HEADERS) {
09479 ast_log(LOG_WARNING, "Out of SIP header space\n");
09480 return -1;
09481 }
09482
09483 if (req->lines) {
09484 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
09485 return -1;
09486 }
09487
09488 if (sip_cfg.compactheaders) {
09489 var = find_alias(var, var);
09490 }
09491
09492 ast_str_append(&req->data, 0, "%s: %s\r\n", var, value);
09493 req->header[req->headers] = req->len;
09494
09495 req->len = ast_str_strlen(req->data);
09496 req->headers++;
09497
09498 return 0;
09499 }
09500
09501
09502 static int finalize_content(struct sip_request *req)
09503 {
09504 char clen[10];
09505
09506 if (req->lines) {
09507 ast_log(LOG_WARNING, "finalize_content() called on a message that has already been finalized\n");
09508 return -1;
09509 }
09510
09511 snprintf(clen, sizeof(clen), "%zd", ast_str_strlen(req->content));
09512 add_header(req, "Content-Length", clen);
09513
09514 if (ast_str_strlen(req->content)) {
09515 ast_str_append(&req->data, 0, "\r\n%s", ast_str_buffer(req->content));
09516 req->len = ast_str_strlen(req->data);
09517 }
09518 req->lines = ast_str_strlen(req->content) ? 1 : 0;
09519 return 0;
09520 }
09521
09522
09523 static int add_content(struct sip_request *req, const char *line)
09524 {
09525 if (req->lines) {
09526 ast_log(LOG_WARNING, "Can't add more content when the content has been finalized\n");
09527 return -1;
09528 }
09529
09530 ast_str_append(&req->content, 0, "%s", line);
09531 return 0;
09532 }
09533
09534
09535 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field)
09536 {
09537 const char *tmp = get_header(orig, field);
09538
09539 if (!ast_strlen_zero(tmp))
09540 return add_header(req, field, tmp);
09541 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
09542 return -1;
09543 }
09544
09545
09546 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field)
09547 {
09548 int start = 0;
09549 int copied = 0;
09550 for (;;) {
09551 const char *tmp = __get_header(orig, field, &start);
09552
09553 if (ast_strlen_zero(tmp))
09554 break;
09555
09556 add_header(req, field, tmp);
09557 copied++;
09558 }
09559 return copied ? 0 : -1;
09560 }
09561
09562
09563
09564
09565
09566
09567
09568
09569
09570 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field)
09571 {
09572 int copied = 0;
09573 int start = 0;
09574
09575 for (;;) {
09576 char new[512];
09577 const char *oh = __get_header(orig, field, &start);
09578
09579 if (ast_strlen_zero(oh))
09580 break;
09581
09582 if (!copied) {
09583 char leftmost[512], *others, *rport;
09584
09585
09586 ast_copy_string(leftmost, oh, sizeof(leftmost));
09587 others = strchr(leftmost, ',');
09588 if (others)
09589 *others++ = '\0';
09590
09591
09592 rport = strstr(leftmost, ";rport");
09593 if (rport && *(rport+6) == '=')
09594 rport = NULL;
09595
09596
09597 if (rport && ((ast_test_flag(&p->flags[0], SIP_NAT) == SIP_NAT_ALWAYS) || (ast_test_flag(&p->flags[0], SIP_NAT) == SIP_NAT_RFC3581))) {
09598
09599 char *end;
09600
09601 rport = strstr(leftmost, ";rport");
09602
09603 if (rport) {
09604 end = strchr(rport + 1, ';');
09605 if (end)
09606 memmove(rport, end, strlen(end) + 1);
09607 else
09608 *rport = '\0';
09609 }
09610
09611
09612 snprintf(new, sizeof(new), "%s;received=%s;rport=%d%s%s",
09613 leftmost, ast_inet_ntoa(p->recv.sin_addr),
09614 ntohs(p->recv.sin_port),
09615 others ? "," : "", others ? others : "");
09616 } else {
09617
09618 snprintf(new, sizeof(new), "%s;received=%s%s%s",
09619 leftmost, ast_inet_ntoa(p->recv.sin_addr),
09620 others ? "," : "", others ? others : "");
09621 }
09622 oh = new;
09623 }
09624 add_header(req, field, oh);
09625 copied++;
09626 }
09627 if (!copied) {
09628 ast_log(LOG_NOTICE, "No header field '%s' present to copy\n", field);
09629 return -1;
09630 }
09631 return 0;
09632 }
09633
09634
09635 static void add_route(struct sip_request *req, struct sip_route *route)
09636 {
09637 char r[SIPBUFSIZE*2], *p;
09638 int n, rem = sizeof(r);
09639
09640 if (!route)
09641 return;
09642
09643 p = r;
09644 for (;route ; route = route->next) {
09645 n = strlen(route->hop);
09646 if (rem < n+3)
09647 break;
09648 if (p != r) {
09649 *p++ = ',';
09650 --rem;
09651 }
09652 *p++ = '<';
09653 ast_copy_string(p, route->hop, rem);
09654 p += n;
09655 *p++ = '>';
09656 rem -= (n+2);
09657 }
09658 *p = '\0';
09659 add_header(req, "Route", r);
09660 }
09661
09662
09663
09664
09665
09666
09667
09668
09669
09670
09671 static void set_destination(struct sip_pvt *p, char *uri)
09672 {
09673 char *h, *maddr, hostname[256];
09674 int port, hn;
09675 struct hostent *hp;
09676 struct ast_hostent ahp;
09677 int debug=sip_debug_test_pvt(p);
09678 int tls_on = FALSE;
09679 int use_dns = sip_cfg.srvlookup;
09680
09681 if (debug)
09682 ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
09683
09684
09685 h = strchr(uri, '@');
09686 if (h)
09687 ++h;
09688 else {
09689 h = uri;
09690 if (!strncasecmp(h, "sip:", 4)) {
09691 h += 4;
09692 } else if (!strncasecmp(h, "sips:", 5)) {
09693 h += 5;
09694 tls_on = TRUE;
09695 }
09696 }
09697 hn = strcspn(h, ":;>") + 1;
09698 if (hn > sizeof(hostname))
09699 hn = sizeof(hostname);
09700 ast_copy_string(hostname, h, hn);
09701
09702 h += hn - 1;
09703
09704
09705 if (*h == ':') {
09706
09707 ++h;
09708 port = strtol(h, &h, 10);
09709 use_dns = FALSE;
09710 } else
09711 port = tls_on ? STANDARD_TLS_PORT : STANDARD_SIP_PORT;
09712
09713
09714 maddr = strstr(h, "maddr=");
09715 if (maddr) {
09716 maddr += 6;
09717 hn = strspn(maddr, "0123456789.") + 1;
09718 if (hn > sizeof(hostname))
09719 hn = sizeof(hostname);
09720 ast_copy_string(hostname, maddr, hn);
09721 }
09722
09723
09724
09725 hp = ast_gethostbyname(hostname, &ahp);
09726 if (hp == NULL) {
09727 ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
09728 return;
09729 }
09730 p->sa.sin_family = AF_INET;
09731 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
09732 p->sa.sin_port = htons(port);
09733 if (debug)
09734 ast_verbose("set_destination: set destination to %s, port %d\n", ast_inet_ntoa(p->sa.sin_addr), port);
09735 }
09736
09737
09738 static int init_resp(struct sip_request *resp, const char *msg)
09739 {
09740
09741 memset(resp, 0, sizeof(*resp));
09742 resp->method = SIP_RESPONSE;
09743 if (!(resp->data = ast_str_create(SIP_MIN_PACKET)))
09744 goto e_return;
09745 if (!(resp->content = ast_str_create(SIP_MIN_PACKET)))
09746 goto e_free_data;
09747 resp->header[0] = 0;
09748 ast_str_set(&resp->data, 0, "SIP/2.0 %s\r\n", msg);
09749 resp->len = resp->data->used;
09750 resp->headers++;
09751 return 0;
09752
09753 e_free_data:
09754 ast_free(resp->data);
09755 resp->data = NULL;
09756 e_return:
09757 return -1;
09758 }
09759
09760
09761 static int init_req(struct sip_request *req, int sipmethod, const char *recip)
09762 {
09763
09764 memset(req, 0, sizeof(*req));
09765 if (!(req->data = ast_str_create(SIP_MIN_PACKET)))
09766 goto e_return;
09767 if (!(req->content = ast_str_create(SIP_MIN_PACKET)))
09768 goto e_free_data;
09769 req->method = sipmethod;
09770 req->header[0] = 0;
09771 ast_str_set(&req->data, 0, "%s %s SIP/2.0\r\n", sip_methods[sipmethod].text, recip);
09772 req->len = ast_str_strlen(req->data);
09773 req->headers++;
09774 return 0;
09775
09776 e_free_data:
09777 ast_free(req->data);
09778 req->data = NULL;
09779 e_return:
09780 return -1;
09781 }
09782
09783
09784 static void deinit_req(struct sip_request *req)
09785 {
09786 if (req->data) {
09787 ast_free(req->data);
09788 req->data = NULL;
09789 }
09790 if (req->content) {
09791 ast_free(req->content);
09792 req->content = NULL;
09793 }
09794 }
09795
09796
09797
09798 static inline int resp_needs_contact(const char *msg, enum sipmethod method) {
09799
09800
09801
09802
09803
09804
09805
09806
09807
09808
09809
09810
09811
09812
09813
09814 switch (method) {
09815
09816 case SIP_INVITE:
09817 case SIP_UPDATE:
09818 case SIP_SUBSCRIBE:
09819 case SIP_NOTIFY:
09820 if ((msg[0] >= '1' && msg[0] <= '3') || !strncmp(msg, "485", 3))
09821 return 1;
09822 break;
09823
09824
09825 case SIP_REGISTER:
09826 case SIP_OPTIONS:
09827 if (msg[0] == '2' || msg[0] == '3' || !strncmp(msg, "485", 3))
09828 return 1;
09829 break;
09830
09831
09832 case SIP_BYE:
09833 case SIP_PRACK:
09834 case SIP_MESSAGE:
09835 case SIP_PUBLISH:
09836 if (msg[0] == '3' || !strncmp(msg, "485", 3))
09837 return 1;
09838 break;
09839
09840
09841 case SIP_REFER:
09842 if (msg[0] >= '2' && msg[0] <= '6')
09843 return 1;
09844 break;
09845
09846
09847 case SIP_ACK:
09848 case SIP_CANCEL:
09849 case SIP_INFO:
09850 case SIP_PING:
09851 default:
09852 return 0;
09853 }
09854 return 0;
09855 }
09856
09857
09858 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req)
09859 {
09860 char newto[256];
09861 const char *ot;
09862
09863 init_resp(resp, msg);
09864 copy_via_headers(p, resp, req, "Via");
09865 if (msg[0] == '1' || msg[0] == '2')
09866 copy_all_header(resp, req, "Record-Route");
09867 copy_header(resp, req, "From");
09868 ot = get_header(req, "To");
09869 if (!strcasestr(ot, "tag=") && strncmp(msg, "100", 3)) {
09870
09871
09872 if (!ast_strlen_zero(p->theirtag) && ast_test_flag(&p->flags[0], SIP_OUTGOING))
09873 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
09874 else if (p->tag && !ast_test_flag(&p->flags[0], SIP_OUTGOING))
09875 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
09876 else
09877 ast_copy_string(newto, ot, sizeof(newto));
09878 ot = newto;
09879 }
09880 add_header(resp, "To", ot);
09881 copy_header(resp, req, "Call-ID");
09882 copy_header(resp, req, "CSeq");
09883 if (!ast_strlen_zero(global_useragent))
09884 add_header(resp, "Server", global_useragent);
09885 add_header(resp, "Allow", ALLOWED_METHODS);
09886 add_supported_header(p, resp);
09887
09888
09889 if (p->method == SIP_INVITE && p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE) {
09890 char se_hdr[256];
09891 snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval,
09892 strefresher2str(p->stimer->st_ref));
09893 add_header(resp, "Session-Expires", se_hdr);
09894 }
09895
09896 if (msg[0] == '2' && (p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER)) {
09897
09898
09899 char tmp[256];
09900
09901 snprintf(tmp, sizeof(tmp), "%d", p->expiry);
09902 add_header(resp, "Expires", tmp);
09903 if (p->expiry) {
09904 char contact[SIPBUFSIZE];
09905 const char *contact_uri = p->method == SIP_SUBSCRIBE ? p->our_contact : p->fullcontact;
09906 char *brackets = strchr(contact_uri, '<');
09907 snprintf(contact, sizeof(contact), "%s%s%s;expires=%d", brackets ? "" : "<", contact_uri, brackets ? "" : ">", p->expiry);
09908 add_header(resp, "Contact", contact);
09909 }
09910 } else if (!ast_strlen_zero(p->our_contact) && resp_needs_contact(msg, p->method)) {
09911 add_header(resp, "Contact", p->our_contact);
09912 }
09913
09914 if (!ast_strlen_zero(p->url)) {
09915 add_header(resp, "Access-URL", p->url);
09916 ast_string_field_set(p, url, NULL);
09917 }
09918
09919
09920
09921
09922 p->sa = p->recv;
09923
09924 if (process_via(p, req)) {
09925 ast_log(LOG_WARNING, "error processing via header, will send response to originating address\n");
09926 }
09927
09928 return 0;
09929 }
09930
09931
09932 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch)
09933 {
09934 struct sip_request *orig = &p->initreq;
09935 char stripped[80];
09936 char tmp[80];
09937 char newto[256];
09938 const char *c;
09939 const char *ot, *of;
09940 int is_strict = FALSE;
09941 int is_outbound = ast_test_flag(&p->flags[0], SIP_OUTGOING);
09942
09943 memset(req, 0, sizeof(struct sip_request));
09944
09945 snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", sip_methods[sipmethod].text);
09946
09947 if (!seqno) {
09948 p->ocseq++;
09949 seqno = p->ocseq;
09950 }
09951
09952
09953 if (sipmethod == SIP_CANCEL) {
09954 p->branch = p->invite_branch;
09955 build_via(p);
09956 } else if (newbranch && (sipmethod == SIP_INVITE)) {
09957 p->branch ^= ast_random();
09958 p->invite_branch = p->branch;
09959 build_via(p);
09960 } else if (newbranch) {
09961 p->branch ^= ast_random();
09962 build_via(p);
09963 }
09964
09965
09966 if (p->route && !ast_strlen_zero(p->route->hop) && strstr(p->route->hop, ";lr") == NULL) {
09967 is_strict = TRUE;
09968 if (sipdebug)
09969 ast_debug(1, "Strict routing enforced for session %s\n", p->callid);
09970 }
09971
09972 if (sipmethod == SIP_CANCEL)
09973 c = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
09974 else if (sipmethod == SIP_ACK) {
09975
09976
09977 if (!ast_strlen_zero(p->okcontacturi))
09978 c = is_strict ? p->route->hop : p->okcontacturi;
09979 else
09980 c = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
09981 } else if (!ast_strlen_zero(p->okcontacturi))
09982 c = is_strict ? p->route->hop : p->okcontacturi;
09983 else if (!ast_strlen_zero(p->uri))
09984 c = p->uri;
09985 else {
09986 char *n;
09987
09988 ast_copy_string(stripped, get_header(orig, is_outbound ? "To" : "From"),
09989 sizeof(stripped));
09990 n = get_in_brackets(stripped);
09991 c = remove_uri_parameters(n);
09992 }
09993 init_req(req, sipmethod, c);
09994
09995 snprintf(tmp, sizeof(tmp), "%d %s", seqno, sip_methods[sipmethod].text);
09996
09997 add_header(req, "Via", p->via);
09998 if (p->route) {
09999 set_destination(p, p->route->hop);
10000 add_route(req, is_strict ? p->route->next : p->route);
10001 }
10002 add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
10003
10004 ot = get_header(orig, "To");
10005 of = get_header(orig, "From");
10006
10007
10008
10009 if (!strcasestr(ot, "tag=") && sipmethod != SIP_CANCEL) {
10010
10011
10012 if (is_outbound && !ast_strlen_zero(p->theirtag))
10013 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
10014 else if (!is_outbound)
10015 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
10016 else
10017 snprintf(newto, sizeof(newto), "%s", ot);
10018 ot = newto;
10019 }
10020
10021 if (is_outbound) {
10022 add_header(req, "From", of);
10023 add_header(req, "To", ot);
10024 } else {
10025 add_header(req, "From", ot);
10026 add_header(req, "To", of);
10027 }
10028
10029 if (sipmethod != SIP_BYE && sipmethod != SIP_CANCEL && sipmethod != SIP_MESSAGE)
10030 add_header(req, "Contact", p->our_contact);
10031
10032 copy_header(req, orig, "Call-ID");
10033 add_header(req, "CSeq", tmp);
10034
10035 if (!ast_strlen_zero(global_useragent))
10036 add_header(req, "User-Agent", global_useragent);
10037
10038 if (!ast_strlen_zero(p->rpid))
10039 add_header(req, "Remote-Party-ID", p->rpid);
10040
10041 if (!ast_strlen_zero(p->url)) {
10042 add_header(req, "Access-URL", p->url);
10043 ast_string_field_set(p, url, NULL);
10044 }
10045
10046
10047
10048
10049
10050
10051
10052
10053 if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE
10054 && sipmethod == SIP_INVITE) {
10055 char se_hdr[256];
10056 snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval,
10057 strefresher2str(p->stimer->st_ref));
10058 add_header(req, "Require", "timer");
10059 add_header(req, "Session-Expires", se_hdr);
10060 snprintf(se_hdr, sizeof(se_hdr), "%d", st_get_se(p, FALSE));
10061 add_header(req, "Min-SE", se_hdr);
10062 }
10063
10064 return 0;
10065 }
10066
10067
10068 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
10069 {
10070 struct sip_request resp;
10071 int seqno = 0;
10072
10073 if (reliable && (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1)) {
10074 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
10075 return -1;
10076 }
10077 respprep(&resp, p, msg, req);
10078
10079
10080 if (p->method == SIP_INVITE && msg[0] != '1' && p->owner && p->owner->hangupcause) {
10081 char buf[10];
10082
10083 add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->owner->hangupcause));
10084 snprintf(buf, sizeof(buf), "%d", p->owner->hangupcause);
10085 add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
10086 }
10087 return send_response(p, &resp, reliable, seqno);
10088 }
10089
10090 static int temp_pvt_init(void *data)
10091 {
10092 struct sip_pvt *p = data;
10093
10094 p->do_history = 0;
10095 return ast_string_field_init(p, 512);
10096 }
10097
10098 static void temp_pvt_cleanup(void *data)
10099 {
10100 struct sip_pvt *p = data;
10101
10102 ast_string_field_free_memory(p);
10103
10104 ast_free(data);
10105 }
10106
10107
10108 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)
10109 {
10110 struct sip_pvt *p = NULL;
10111
10112 if (!(p = ast_threadstorage_get(&ts_temp_pvt, sizeof(*p)))) {
10113 ast_log(LOG_ERROR, "Failed to get temporary pvt\n");
10114 return -1;
10115 }
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125 p->method = intended_method;
10126
10127 if (!sin)
10128 p->ourip = internip;
10129 else {
10130 p->sa = *sin;
10131 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
10132 }
10133
10134 p->branch = ast_random();
10135 make_our_tag(p->tag, sizeof(p->tag));
10136 p->ocseq = INITIAL_CSEQ;
10137
10138 if (useglobal_nat && sin) {
10139 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT);
10140 p->recv = *sin;
10141 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
10142 }
10143
10144 ast_string_field_set(p, fromdomain, default_fromdomain);
10145 build_via(p);
10146 ast_string_field_set(p, callid, callid);
10147
10148 copy_socket_data(&p->socket, &req->socket);
10149
10150
10151 __transmit_response(p, msg, req, XMIT_UNRELIABLE);
10152
10153
10154 ast_string_field_init(p, 0);
10155
10156 return 0;
10157 }
10158
10159
10160 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req)
10161 {
10162 return __transmit_response(p, msg, req, XMIT_UNRELIABLE);
10163 }
10164
10165
10166 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported)
10167 {
10168 struct sip_request resp;
10169 respprep(&resp, p, msg, req);
10170 append_date(&resp);
10171 add_header(&resp, "Unsupported", unsupported);
10172 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
10173 }
10174
10175
10176 static int transmit_response_with_minse(struct sip_pvt *p, const char *msg, const struct sip_request *req, int minse_int)
10177 {
10178 struct sip_request resp;
10179 char minse_str[20];
10180
10181 respprep(&resp, p, msg, req);
10182 append_date(&resp);
10183
10184 snprintf(minse_str, sizeof(minse_str), "%d", minse_int);
10185 add_header(&resp, "Min-SE", minse_str);
10186 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
10187 }
10188
10189
10190
10191
10192
10193 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req)
10194 {
10195 return __transmit_response(p, msg, req, req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL);
10196 }
10197
10198
10199 static void append_date(struct sip_request *req)
10200 {
10201 char tmpdat[256];
10202 struct tm tm;
10203 time_t t = time(NULL);
10204
10205 gmtime_r(&t, &tm);
10206 strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
10207 add_header(req, "Date", tmpdat);
10208 }
10209
10210
10211 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req)
10212 {
10213 struct sip_request resp;
10214 respprep(&resp, p, msg, req);
10215 append_date(&resp);
10216 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
10217 }
10218
10219
10220 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
10221 {
10222 struct sip_request resp;
10223 respprep(&resp, p, msg, req);
10224 add_header(&resp, "Accept", "application/sdp");
10225 return send_response(p, &resp, reliable, 0);
10226 }
10227
10228
10229 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)
10230 {
10231 struct sip_request resp;
10232 char tmp[512];
10233 int seqno = 0;
10234
10235 if (reliable && (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1)) {
10236 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
10237 return -1;
10238 }
10239
10240
10241 snprintf(tmp, sizeof(tmp), "Digest algorithm=MD5, realm=\"%s\", nonce=\"%s\"%s", sip_cfg.realm, randdata, stale ? ", stale=true" : "");
10242 respprep(&resp, p, msg, req);
10243 add_header(&resp, header, tmp);
10244 append_history(p, "AuthChal", "Auth challenge sent for %s - nc %d", p->username, p->noncecount);
10245 return send_response(p, &resp, reliable, seqno);
10246 }
10247
10248
10249 static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp)
10250 {
10251 int res;
10252
10253 if (!(res = with_sdp ? transmit_response_with_sdp(p, msg, req, XMIT_UNRELIABLE, FALSE) : transmit_response(p, msg, req))) {
10254 p->last_provisional = msg;
10255 update_provisional_keepalive(p, with_sdp);
10256 }
10257
10258 return res;
10259 }
10260
10261
10262 static int add_text(struct sip_request *req, const char *text)
10263 {
10264
10265 add_header(req, "Content-Type", "text/plain;charset=UTF-8");
10266 add_content(req, text);
10267 return 0;
10268 }
10269
10270
10271
10272
10273
10274 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode)
10275 {
10276 char tmp[256];
10277 int event;
10278 if (mode) {
10279
10280 if (digit == '*')
10281 event = 10;
10282 else if (digit == '#')
10283 event = 11;
10284 else if ((digit >= 'A') && (digit <= 'D'))
10285 event = 12 + digit - 'A';
10286 else
10287 event = atoi(&digit);
10288 snprintf(tmp, sizeof(tmp), "%d\r\n", event);
10289 add_header(req, "Content-Type", "application/dtmf");
10290 add_content(req, tmp);
10291 } else {
10292
10293 snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=%u\r\n", digit, duration);
10294 add_header(req, "Content-Type", "application/dtmf-relay");
10295 add_content(req, tmp);
10296 }
10297 return 0;
10298 }
10299
10300
10301
10302 static int add_vidupdate(struct sip_request *req)
10303 {
10304 const char *xml_is_a_huge_waste_of_space =
10305 "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
10306 " <media_control>\r\n"
10307 " <vc_primitive>\r\n"
10308 " <to_encoder>\r\n"
10309 " <picture_fast_update>\r\n"
10310 " </picture_fast_update>\r\n"
10311 " </to_encoder>\r\n"
10312 " </vc_primitive>\r\n"
10313 " </media_control>\r\n";
10314 add_header(req, "Content-Type", "application/media_control+xml");
10315 add_content(req, xml_is_a_huge_waste_of_space);
10316 return 0;
10317 }
10318
10319
10320 static void add_codec_to_sdp(const struct sip_pvt *p, int codec,
10321 struct ast_str **m_buf, struct ast_str **a_buf,
10322 int debug, int *min_packet_size)
10323 {
10324 int rtp_code;
10325 struct ast_format_list fmt;
10326
10327
10328 if (debug)
10329 ast_verbose("Adding codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
10330 if ((rtp_code = ast_rtp_lookup_code(p->rtp, 1, codec)) == -1)
10331 return;
10332
10333 if (p->rtp) {
10334 struct ast_codec_pref *pref = ast_rtp_codec_getpref(p->rtp);
10335 fmt = ast_codec_pref_getsize(pref, codec);
10336 } else
10337 return;
10338 ast_str_append(m_buf, 0, " %d", rtp_code);
10339 ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
10340 ast_rtp_lookup_mime_subtype(1, codec,
10341 ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0),
10342 ast_rtp_lookup_sample_rate(1, codec));
10343
10344 switch (codec) {
10345 case AST_FORMAT_G729A:
10346
10347 ast_str_append(a_buf, 0, "a=fmtp:%d annexb=no\r\n", rtp_code);
10348 break;
10349 case AST_FORMAT_G723_1:
10350
10351 ast_str_append(a_buf, 0, "a=fmtp:%d annexa=no\r\n", rtp_code);
10352 break;
10353 case AST_FORMAT_ILBC:
10354
10355 ast_str_append(a_buf, 0, "a=fmtp:%d mode=%d\r\n", rtp_code, fmt.cur_ms);
10356 break;
10357 case AST_FORMAT_SIREN7:
10358
10359 ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=32000\r\n", rtp_code);
10360 break;
10361 case AST_FORMAT_SIREN14:
10362
10363 ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=48000\r\n", rtp_code);
10364 break;
10365 }
10366
10367 if (fmt.cur_ms && (fmt.cur_ms < *min_packet_size))
10368 *min_packet_size = fmt.cur_ms;
10369
10370
10371 if ((*min_packet_size)==0 && fmt.cur_ms)
10372 *min_packet_size = fmt.cur_ms;
10373 }
10374
10375
10376
10377 static void add_vcodec_to_sdp(const struct sip_pvt *p, int codec,
10378 struct ast_str **m_buf, struct ast_str **a_buf,
10379 int debug, int *min_packet_size)
10380 {
10381 int rtp_code;
10382
10383 if (!p->vrtp)
10384 return;
10385
10386 if (debug)
10387 ast_verbose("Adding video codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
10388
10389 if ((rtp_code = ast_rtp_lookup_code(p->vrtp, 1, codec)) == -1)
10390 return;
10391
10392 ast_str_append(m_buf, 0, " %d", rtp_code);
10393 ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
10394 ast_rtp_lookup_mime_subtype(1, codec, 0),
10395 ast_rtp_lookup_sample_rate(1, codec));
10396
10397 }
10398
10399
10400 static void add_tcodec_to_sdp(const struct sip_pvt *p, int codec,
10401 struct ast_str **m_buf, struct ast_str **a_buf,
10402 int debug, int *min_packet_size)
10403 {
10404 int rtp_code;
10405
10406 if (!p->trtp)
10407 return;
10408
10409 if (debug)
10410 ast_verbose("Adding text codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
10411
10412 if ((rtp_code = ast_rtp_lookup_code(p->trtp, 1, codec)) == -1)
10413 return;
10414
10415 ast_str_append(m_buf, 0, " %d", rtp_code);
10416 ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
10417 ast_rtp_lookup_mime_subtype(1, codec, 0),
10418 ast_rtp_lookup_sample_rate(1, codec));
10419
10420
10421 if (codec == AST_FORMAT_T140RED) {
10422 ast_str_append(a_buf, 0, "a=fmtp:%d %d/%d/%d\r\n", rtp_code,
10423 ast_rtp_lookup_code(p->trtp, 1, AST_FORMAT_T140),
10424 ast_rtp_lookup_code(p->trtp, 1, AST_FORMAT_T140),
10425 ast_rtp_lookup_code(p->trtp, 1, AST_FORMAT_T140));
10426
10427 }
10428 }
10429
10430
10431
10432 static unsigned int t38_get_rate(enum ast_control_t38_rate rate)
10433 {
10434 switch (rate) {
10435 case AST_T38_RATE_2400:
10436 return 2400;
10437 case AST_T38_RATE_4800:
10438 return 4800;
10439 case AST_T38_RATE_7200:
10440 return 7200;
10441 case AST_T38_RATE_9600:
10442 return 9600;
10443 case AST_T38_RATE_12000:
10444 return 12000;
10445 case AST_T38_RATE_14400:
10446 return 14400;
10447 default:
10448 return 0;
10449 }
10450 }
10451
10452
10453 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
10454 struct ast_str **m_buf, struct ast_str **a_buf,
10455 int debug)
10456 {
10457 int rtp_code;
10458
10459 if (debug)
10460 ast_verbose("Adding non-codec 0x%x (%s) to SDP\n", format, ast_rtp_lookup_mime_subtype(0, format, 0));
10461 if ((rtp_code = ast_rtp_lookup_code(p->rtp, 0, format)) == -1)
10462 return;
10463
10464 ast_str_append(m_buf, 0, " %d", rtp_code);
10465 ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
10466 ast_rtp_lookup_mime_subtype(0, format, 0),
10467 ast_rtp_lookup_sample_rate(0, format));
10468 if (format == AST_RTP_DTMF)
10469 ast_str_append(a_buf, 0, "a=fmtp:%d 0-16\r\n", rtp_code);
10470 }
10471
10472
10473
10474
10475 static void get_our_media_address(struct sip_pvt *p, int needvideo,
10476 struct sockaddr_in *sin, struct sockaddr_in *vsin, struct sockaddr_in *tsin,
10477 struct sockaddr_in *dest, struct sockaddr_in *vdest)
10478 {
10479
10480 ast_rtp_get_us(p->rtp, sin);
10481 if (p->vrtp)
10482 ast_rtp_get_us(p->vrtp, vsin);
10483 if (p->trtp)
10484 ast_rtp_get_us(p->trtp, tsin);
10485
10486
10487
10488 if (p->redirip.sin_addr.s_addr) {
10489 dest->sin_port = p->redirip.sin_port;
10490 dest->sin_addr = p->redirip.sin_addr;
10491 } else {
10492 dest->sin_addr = p->ourip.sin_addr;
10493 dest->sin_port = sin->sin_port;
10494 }
10495 if (needvideo) {
10496
10497 if (p->vredirip.sin_addr.s_addr) {
10498 vdest->sin_addr = p->vredirip.sin_addr;
10499 vdest->sin_port = p->vredirip.sin_port;
10500 } else {
10501 vdest->sin_addr = p->ourip.sin_addr;
10502 vdest->sin_port = vsin->sin_port;
10503 }
10504 }
10505
10506 }
10507
10508
10509
10510
10511
10512
10513
10514 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38)
10515 {
10516 int alreadysent = 0;
10517 int doing_directmedia = FALSE;
10518
10519 struct sockaddr_in sin;
10520 struct sockaddr_in vsin;
10521 struct sockaddr_in tsin;
10522 struct sockaddr_in dest;
10523 struct sockaddr_in udptlsin;
10524 struct sockaddr_in vdest = { 0, };
10525 struct sockaddr_in tdest = { 0, };
10526 struct sockaddr_in udptldest = { 0, };
10527
10528
10529 char *version = "v=0\r\n";
10530 char subject[256];
10531 char owner[256];
10532 char connection[256];
10533 char *session_time = "t=0 0\r\n";
10534 char bandwidth[256] = "";
10535 char *hold = "";
10536 struct ast_str *m_audio = ast_str_alloca(256);
10537 struct ast_str *m_video = ast_str_alloca(256);
10538 struct ast_str *m_text = ast_str_alloca(256);
10539 struct ast_str *m_modem = ast_str_alloca(256);
10540 struct ast_str *a_audio = ast_str_alloca(1024);
10541 struct ast_str *a_video = ast_str_alloca(1024);
10542 struct ast_str *a_text = ast_str_alloca(1024);
10543 struct ast_str *a_modem = ast_str_alloca(1024);
10544
10545 int x;
10546 int capability = 0;
10547 int needaudio = FALSE;
10548 int needvideo = FALSE;
10549 int needtext = FALSE;
10550 int debug = sip_debug_test_pvt(p);
10551 int min_audio_packet_size = 0;
10552 int min_video_packet_size = 0;
10553 int min_text_packet_size = 0;
10554
10555 char codecbuf[SIPBUFSIZE];
10556 char buf[SIPBUFSIZE];
10557 char dummy_answer[256];
10558
10559
10560 snprintf(subject, sizeof(subject), "s=%s\r\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
10561
10562 if (!p->rtp) {
10563 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
10564 return AST_FAILURE;
10565 }
10566
10567
10568
10569
10570 if (!p->sessionid) {
10571 p->sessionid = (int)ast_random();
10572 p->sessionversion = p->sessionid;
10573 } else {
10574 if (oldsdp == FALSE)
10575 p->sessionversion++;
10576 }
10577
10578 if (add_audio) {
10579 doing_directmedia = (p->redirip.sin_addr.s_addr && p->redircodecs) ? TRUE : FALSE;
10580
10581 if ((p->jointcapability & AST_FORMAT_VIDEO_MASK) && !p->novideo) {
10582 if (p->vrtp) {
10583 needvideo = TRUE;
10584 ast_debug(2, "This call needs video offers!\n");
10585 } else
10586 ast_debug(2, "This call needs video offers, but there's no video support enabled!\n");
10587 }
10588
10589 if ((p->jointcapability & AST_FORMAT_TEXT_MASK) && !p->notext) {
10590 if (sipdebug_text)
10591 ast_verbose("We think we can do text\n");
10592 if (p->trtp) {
10593 if (sipdebug_text) {
10594 ast_verbose("And we have a text rtp object\n");
10595 }
10596 needtext = TRUE;
10597 ast_debug(2, "This call needs text offers! \n");
10598 } else {
10599 ast_debug(2, "This call needs text offers, but there's no text support enabled ! \n");
10600 }
10601 }
10602 }
10603
10604 get_our_media_address(p, needvideo, &sin, &vsin, &tsin, &dest, &vdest);
10605
10606 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));
10607 snprintf(connection, sizeof(connection), "c=IN IP4 %s\r\n", ast_inet_ntoa(dest.sin_addr));
10608
10609 if (add_audio) {
10610 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_ONEDIR) {
10611 hold = "a=recvonly\r\n";
10612 doing_directmedia = FALSE;
10613 } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_INACTIVE) {
10614 hold = "a=inactive\r\n";
10615 doing_directmedia = FALSE;
10616 } else {
10617 hold = "a=sendrecv\r\n";
10618 }
10619
10620 capability = p->jointcapability;
10621
10622
10623 ast_debug(1, "** Our capability: %s Video flag: %s Text flag: %s\n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), capability),
10624 p->novideo ? "True" : "False", p->notext ? "True" : "False");
10625 ast_debug(1, "** Our prefcodec: %s \n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), p->prefcodec));
10626
10627 if (doing_directmedia) {
10628 capability &= p->redircodecs;
10629 ast_debug(1, "** Our native-bridge filtered capablity: %s\n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), capability));
10630 }
10631
10632
10633 if (capability & AST_FORMAT_AUDIO_MASK)
10634 needaudio = TRUE;
10635
10636 if (debug)
10637 ast_verbose("Audio is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(sin.sin_port));
10638
10639
10640
10641 if (needvideo) {
10642 ast_str_append(&m_video, 0, "m=video %d RTP/AVP", ntohs(vdest.sin_port));
10643
10644
10645 if (p->maxcallbitrate)
10646 snprintf(bandwidth, sizeof(bandwidth), "b=CT:%d\r\n", p->maxcallbitrate);
10647 if (debug)
10648 ast_verbose("Video is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(vdest.sin_port));
10649 }
10650
10651
10652
10653 if (needtext) {
10654 if (sipdebug_text)
10655 ast_verbose("Lets set up the text sdp\n");
10656
10657 if (p->tredirip.sin_addr.s_addr) {
10658 tdest.sin_addr = p->tredirip.sin_addr;
10659 tdest.sin_port = p->tredirip.sin_port;
10660 } else {
10661 tdest.sin_addr = p->ourip.sin_addr;
10662 tdest.sin_port = tsin.sin_port;
10663 }
10664 ast_str_append(&m_text, 0, "m=text %d RTP/AVP", ntohs(tdest.sin_port));
10665 if (debug)
10666 ast_verbose("Text is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(tsin.sin_port));
10667
10668 }
10669
10670
10671
10672
10673
10674
10675 ast_str_append(&m_audio, 0, "m=audio %d RTP/AVP", ntohs(dest.sin_port));
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686 if (capability & p->prefcodec) {
10687 int codec = p->prefcodec & AST_FORMAT_AUDIO_MASK;
10688
10689 add_codec_to_sdp(p, codec, &m_audio, &a_audio, debug, &min_audio_packet_size);
10690 alreadysent |= codec;
10691 }
10692
10693
10694 for (x = 0; x < 32; x++) {
10695 int codec;
10696
10697 if (!(codec = ast_codec_pref_index(&p->prefs, x)))
10698 break;
10699
10700 if (!(capability & codec))
10701 continue;
10702
10703 if (alreadysent & codec)
10704 continue;
10705
10706 add_codec_to_sdp(p, codec, &m_audio, &a_audio, debug, &min_audio_packet_size);
10707 alreadysent |= codec;
10708 }
10709
10710
10711 for (x = 1; x <= (needtext ? AST_FORMAT_TEXT_MASK : (needvideo ? AST_FORMAT_VIDEO_MASK : AST_FORMAT_AUDIO_MASK)); x <<= 1) {
10712 if (!(capability & x))
10713 continue;
10714
10715 if (alreadysent & x)
10716 continue;
10717
10718 if (x & AST_FORMAT_AUDIO_MASK)
10719 add_codec_to_sdp(p, x, &m_audio, &a_audio, debug, &min_audio_packet_size);
10720 else if (x & AST_FORMAT_VIDEO_MASK)
10721 add_vcodec_to_sdp(p, x, &m_video, &a_video, debug, &min_video_packet_size);
10722 else if (x & AST_FORMAT_TEXT_MASK)
10723 add_tcodec_to_sdp(p, x, &m_text, &a_text, debug, &min_text_packet_size);
10724 }
10725
10726
10727 for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
10728 if (!(p->jointnoncodeccapability & x))
10729 continue;
10730
10731 add_noncodec_to_sdp(p, x, &m_audio, &a_audio, debug);
10732 }
10733
10734 ast_debug(3, "-- Done with adding codecs to SDP\n");
10735
10736 if (!p->owner || !ast_internal_timing_enabled(p->owner))
10737 ast_str_append(&a_audio, 0, "a=silenceSupp:off - - - -\r\n");
10738
10739 if (min_audio_packet_size)
10740 ast_str_append(&a_audio, 0, "a=ptime:%d\r\n", min_audio_packet_size);
10741
10742
10743 if (min_video_packet_size)
10744 ast_str_append(&a_video, 0, "a=ptime:%d\r\n", min_video_packet_size);
10745
10746
10747 if (min_text_packet_size)
10748 ast_str_append(&a_text, 0, "a=ptime:%d\r\n", min_text_packet_size);
10749
10750 if (m_audio->len - m_audio->used < 2 || m_video->len - m_video->used < 2 ||
10751 m_text->len - m_text->used < 2 || a_text->len - a_text->used < 2 ||
10752 a_audio->len - a_audio->used < 2 || a_video->len - a_video->used < 2)
10753 ast_log(LOG_WARNING, "SIP SDP may be truncated due to undersized buffer!!\n");
10754 }
10755
10756 if (add_t38) {
10757
10758 ast_udptl_get_us(p->udptl, &udptlsin);
10759
10760
10761 if (p->udptlredirip.sin_addr.s_addr) {
10762 udptldest.sin_port = p->udptlredirip.sin_port;
10763 udptldest.sin_addr = p->udptlredirip.sin_addr;
10764 } else {
10765 udptldest.sin_addr = p->ourip.sin_addr;
10766 udptldest.sin_port = udptlsin.sin_port;
10767 }
10768
10769 if (debug)
10770 ast_debug(1, "T.38 UDPTL is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(udptlsin.sin_port));
10771
10772
10773
10774
10775 ast_str_append(&m_modem, 0, "m=image %d udptl t38\r\n", ntohs(udptldest.sin_port));
10776
10777 ast_str_append(&a_modem, 0, "a=T38FaxVersion:%d\r\n", p->t38.our_parms.version);
10778 ast_str_append(&a_modem, 0, "a=T38MaxBitRate:%d\r\n", t38_get_rate(p->t38.our_parms.rate));
10779 if (p->t38.our_parms.fill_bit_removal) {
10780 ast_str_append(&a_modem, 0, "a=T38FaxFillBitRemoval\r\n");
10781 }
10782 if (p->t38.our_parms.transcoding_mmr) {
10783 ast_str_append(&a_modem, 0, "a=T38FaxTranscodingMMR\r\n");
10784 }
10785 if (p->t38.our_parms.transcoding_jbig) {
10786 ast_str_append(&a_modem, 0, "a=T38FaxTranscodingJBIG\r\n");
10787 }
10788 switch (p->t38.our_parms.rate_management) {
10789 case AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF:
10790 ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:transferredTCF\r\n");
10791 break;
10792 case AST_T38_RATE_MANAGEMENT_LOCAL_TCF:
10793 ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:localTCF\r\n");
10794 break;
10795 }
10796 ast_str_append(&a_modem, 0, "a=T38FaxMaxDatagram:%u\r\n", ast_udptl_get_local_max_datagram(p->udptl));
10797 switch (ast_udptl_get_error_correction_scheme(p->udptl)) {
10798 case UDPTL_ERROR_CORRECTION_NONE:
10799 break;
10800 case UDPTL_ERROR_CORRECTION_FEC:
10801 ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPFEC\r\n");
10802 break;
10803 case UDPTL_ERROR_CORRECTION_REDUNDANCY:
10804 ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPRedundancy\r\n");
10805 break;
10806 }
10807 }
10808
10809 if (needaudio)
10810 ast_str_append(&m_audio, 0, "\r\n");
10811 if (needvideo)
10812 ast_str_append(&m_video, 0, "\r\n");
10813 if (needtext)
10814 ast_str_append(&m_text, 0, "\r\n");
10815
10816 add_header(resp, "Content-Type", "application/sdp");
10817 add_content(resp, version);
10818 add_content(resp, owner);
10819 add_content(resp, subject);
10820 add_content(resp, connection);
10821 if (needvideo)
10822 add_content(resp, bandwidth);
10823 add_content(resp, session_time);
10824 if (needaudio) {
10825 add_content(resp, m_audio->str);
10826 add_content(resp, a_audio->str);
10827 add_content(resp, hold);
10828 } else if (p->offered_media[SDP_AUDIO].offered) {
10829 snprintf(dummy_answer, sizeof(dummy_answer), "m=audio 0 RTP/AVP %s\r\n", p->offered_media[SDP_AUDIO].text);
10830 add_content(resp, dummy_answer);
10831 }
10832 if (needvideo) {
10833 add_content(resp, m_video->str);
10834 add_content(resp, a_video->str);
10835 add_content(resp, hold);
10836 } else if (p->offered_media[SDP_VIDEO].offered) {
10837 snprintf(dummy_answer, sizeof(dummy_answer), "m=video 0 RTP/AVP %s\r\n", p->offered_media[SDP_VIDEO].text);
10838 add_content(resp, dummy_answer);
10839 }
10840 if (needtext) {
10841 add_content(resp, m_text->str);
10842 add_content(resp, a_text->str);
10843 add_content(resp, hold);
10844 } else if (p->offered_media[SDP_TEXT].offered) {
10845 snprintf(dummy_answer, sizeof(dummy_answer), "m=text 0 RTP/AVP %s\r\n", p->offered_media[SDP_TEXT].text);
10846 add_content(resp, dummy_answer);
10847 }
10848 if (add_t38) {
10849 add_content(resp, m_modem->str);
10850 add_content(resp, a_modem->str);
10851 } else if (p->offered_media[SDP_IMAGE].offered) {
10852 add_content(resp, "m=image 0 udptl t38\r\n");
10853 }
10854
10855
10856 p->lastrtprx = p->lastrtptx = time(NULL);
10857
10858 ast_debug(3, "Done building SDP. Settling with this capability: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, capability));
10859
10860 return AST_SUCCESS;
10861 }
10862
10863
10864 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
10865 {
10866 struct sip_request resp;
10867 int seqno;
10868
10869 if (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1) {
10870 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
10871 return -1;
10872 }
10873 respprep(&resp, p, msg, req);
10874 if (p->udptl) {
10875 add_sdp(&resp, p, 0, 0, 1);
10876 } else
10877 ast_log(LOG_ERROR, "Can't add SDP to response, since we have no UDPTL session allocated. Call-ID %s\n", p->callid);
10878 if (retrans && !p->pendinginvite)
10879 p->pendinginvite = seqno;
10880 return send_response(p, &resp, retrans, seqno);
10881 }
10882
10883
10884 static void copy_request(struct sip_request *dst, const struct sip_request *src)
10885 {
10886
10887
10888
10889 struct ast_str *duplicate = dst->data;
10890 struct ast_str *duplicate_content = dst->content;
10891
10892
10893
10894 memcpy(dst, src, sizeof(*dst));
10895 dst->data = duplicate;
10896 dst->content = duplicate_content;
10897
10898
10899 if (!dst->data && !(dst->data = ast_str_create(ast_str_strlen(src->data) + 1)))
10900 return;
10901 ast_str_copy_string(&dst->data, src->data);
10902
10903
10904 if (src->content) {
10905 if (!dst->content && !(dst->content = ast_str_create(ast_str_strlen(src->content) + 1)))
10906 return;
10907 ast_str_copy_string(&dst->content, src->content);
10908 }
10909 }
10910
10911
10912
10913
10914 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable, int oldsdp)
10915 {
10916 struct sip_request resp;
10917 int seqno;
10918 if (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1) {
10919 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
10920 return -1;
10921 }
10922 respprep(&resp, p, msg, req);
10923 if (p->rtp) {
10924 if (!p->autoframing && !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
10925 ast_debug(1, "Setting framing from config on incoming call\n");
10926 ast_rtp_codec_setpref(p->rtp, &p->prefs);
10927 }
10928 try_suggested_sip_codec(p);
10929 if (p->t38.state == T38_ENABLED) {
10930 add_sdp(&resp, p, oldsdp, TRUE, TRUE);
10931 } else {
10932 add_sdp(&resp, p, oldsdp, TRUE, FALSE);
10933 }
10934 } else
10935 ast_log(LOG_ERROR, "Can't add SDP to response, since we have no RTP session allocated. Call-ID %s\n", p->callid);
10936 if (reliable && !p->pendinginvite)
10937 p->pendinginvite = seqno;
10938 return send_response(p, &resp, reliable, seqno);
10939 }
10940
10941
10942 static int determine_firstline_parts(struct sip_request *req)
10943 {
10944 char *e = ast_skip_blanks(req->data->str);
10945 char *local_rlPart1;
10946
10947 if (!*e)
10948 return -1;
10949 req->rlPart1 = e - req->data->str;
10950 local_rlPart1 = e;
10951 e = ast_skip_nonblanks(e);
10952 if (*e)
10953 *e++ = '\0';
10954
10955 e = ast_skip_blanks(e);
10956 if ( !*e )
10957 return -1;
10958 ast_trim_blanks(e);
10959
10960 if (!strcasecmp(local_rlPart1, "SIP/2.0") ) {
10961 if (strlen(e) < 3)
10962 return -1;
10963 req->rlPart2 = e - req->data->str;
10964 } else {
10965 if ( *e == '<' ) {
10966 ast_debug(3, "Oops. Bogus uri in <> %s\n", e);
10967 e++;
10968 if (!*e)
10969 return -1;
10970 }
10971 req->rlPart2 = e - req->data->str;
10972 e = ast_skip_nonblanks(e);
10973 if (*e)
10974 *e++ = '\0';
10975 e = ast_skip_blanks(e);
10976 if (strcasecmp(e, "SIP/2.0") ) {
10977 ast_debug(3, "Skipping packet - Bad request protocol %s\n", e);
10978 return -1;
10979 }
10980 }
10981 return 1;
10982 }
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp)
10998 {
10999 struct sip_request req;
11000
11001 reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ? SIP_UPDATE : SIP_INVITE, 0, 1);
11002
11003 add_header(&req, "Allow", ALLOWED_METHODS);
11004 add_supported_header(p, &req);
11005 if (sipdebug) {
11006 if (oldsdp == TRUE)
11007 add_header(&req, "X-asterisk-Info", "SIP re-invite (Session-Timers)");
11008 else
11009 add_header(&req, "X-asterisk-Info", "SIP re-invite (External RTP bridge)");
11010 }
11011
11012 if (p->do_history)
11013 append_history(p, "ReInv", "Re-invite sent");
11014 memset(p->offered_media, 0, sizeof(p->offered_media));
11015
11016 if (t38version)
11017 add_sdp(&req, p, oldsdp, FALSE, TRUE);
11018 else
11019 add_sdp(&req, p, oldsdp, TRUE, FALSE);
11020
11021
11022 initialize_initreq(p, &req);
11023 p->lastinvite = p->ocseq;
11024 ast_set_flag(&p->flags[0], SIP_OUTGOING);
11025
11026 return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
11027 }
11028
11029
11030 static char *remove_uri_parameters(char *uri)
11031 {
11032 char *atsign;
11033 atsign = strchr(uri, '@');
11034 if (!atsign)
11035 atsign = uri;
11036 atsign = strchr(atsign, ';');
11037 if (atsign)
11038 *atsign = '\0';
11039 return uri;
11040 }
11041
11042
11043 static void extract_uri(struct sip_pvt *p, struct sip_request *req)
11044 {
11045 char stripped[SIPBUFSIZE];
11046 char *c;
11047
11048 ast_copy_string(stripped, get_header(req, "Contact"), sizeof(stripped));
11049 c = get_in_brackets(stripped);
11050
11051 c = remove_uri_parameters(c);
11052 if (!ast_strlen_zero(c))
11053 ast_string_field_set(p, uri, c);
11054
11055 }
11056
11057
11058 static void build_contact(struct sip_pvt *p)
11059 {
11060 char tmp[SIPBUFSIZE];
11061 char *user = ast_uri_encode(p->exten, tmp, sizeof(tmp), 1);
11062 int ourport = ntohs(p->ourip.sin_port);
11063
11064
11065 if (!sip_standard_port(p->socket.type, ourport)) {
11066 if (p->socket.type == SIP_TRANSPORT_UDP)
11067 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);
11068 else
11069 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));
11070 } else {
11071 if (p->socket.type == SIP_TRANSPORT_UDP)
11072 ast_string_field_build(p, our_contact, "<sip:%s%s%s>", user, ast_strlen_zero(user) ? "" : "@", ast_inet_ntoa(p->ourip.sin_addr));
11073 else
11074 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));
11075 }
11076 }
11077
11078
11079 static void build_rpid(struct sip_pvt *p)
11080 {
11081 int send_pres_tags = TRUE;
11082 const char *privacy=NULL;
11083 const char *screen=NULL;
11084 char buf[256];
11085 const char *clid = default_callerid;
11086 const char *clin = NULL;
11087 const char *fromdomain;
11088
11089 if (!ast_strlen_zero(p->rpid) || !ast_strlen_zero(p->rpid_from))
11090 return;
11091
11092 if (p->owner && !ast_strlen_zero(p->owner->cid.cid_num))
11093 clid = p->owner->cid.cid_num;
11094 if (p->owner && p->owner->cid.cid_name)
11095 clin = p->owner->cid.cid_name;
11096 if (ast_strlen_zero(clin))
11097 clin = clid;
11098
11099 switch (p->callingpres) {
11100 case AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED:
11101 privacy = "off";
11102 screen = "no";
11103 break;
11104 case AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN:
11105 privacy = "off";
11106 screen = "yes";
11107 break;
11108 case AST_PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN:
11109 privacy = "off";
11110 screen = "no";
11111 break;
11112 case AST_PRES_ALLOWED_NETWORK_NUMBER:
11113 privacy = "off";
11114 screen = "yes";
11115 break;
11116 case AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED:
11117 privacy = "full";
11118 screen = "no";
11119 break;
11120 case AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN:
11121 privacy = "full";
11122 screen = "yes";
11123 break;
11124 case AST_PRES_PROHIB_USER_NUMBER_FAILED_SCREEN:
11125 privacy = "full";
11126 screen = "no";
11127 break;
11128 case AST_PRES_PROHIB_NETWORK_NUMBER:
11129 privacy = "full";
11130 screen = "yes";
11131 break;
11132 case AST_PRES_NUMBER_NOT_AVAILABLE:
11133 send_pres_tags = FALSE;
11134 break;
11135 default:
11136 ast_log(LOG_WARNING, "Unsupported callingpres (%d)\n", p->callingpres);
11137 if ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)
11138 privacy = "full";
11139 else
11140 privacy = "off";
11141 screen = "no";
11142 break;
11143 }
11144
11145 fromdomain = S_OR(p->fromdomain, ast_inet_ntoa(p->ourip.sin_addr));
11146
11147 snprintf(buf, sizeof(buf), "\"%s\" <sip:%s@%s>", clin, clid, fromdomain);
11148 if (send_pres_tags)
11149 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ";privacy=%s;screen=%s", privacy, screen);
11150 ast_string_field_set(p, rpid, buf);
11151
11152 ast_string_field_build(p, rpid_from, "\"%s\" <sip:%s@%s>;tag=%s", clin,
11153 S_OR(p->fromuser, clid),
11154 fromdomain, p->tag);
11155 }
11156
11157
11158 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod)
11159 {
11160 struct ast_str *invite = ast_str_alloca(256);
11161 char from[256];
11162 char to[256];
11163 char tmp_n[SIPBUFSIZE/2];
11164 char tmp_l[SIPBUFSIZE/2];
11165 const char *l = NULL;
11166 const char *n = NULL;
11167 const char *d = NULL;
11168 const char *urioptions = "";
11169 int ourport;
11170
11171 if (ast_test_flag(&p->flags[0], SIP_USEREQPHONE)) {
11172 const char *s = p->username;
11173
11174
11175
11176
11177
11178
11179 if (*s == '+')
11180 s++;
11181 for (; *s; s++) {
11182 if (!strchr(AST_DIGIT_ANYNUM, *s) )
11183 break;
11184 }
11185
11186 if (!*s)
11187 urioptions = ";user=phone";
11188 }
11189
11190
11191 snprintf(p->lastmsg, sizeof(p->lastmsg), "Init: %s", sip_methods[sipmethod].text);
11192
11193 d = S_OR(p->fromdomain, ast_inet_ntoa(p->ourip.sin_addr));
11194 if (p->owner) {
11195 l = p->owner->cid.cid_num;
11196 n = p->owner->cid.cid_name;
11197 }
11198
11199 if (!ast_test_flag(&p->flags[0], SIP_SENDRPID) &&
11200 ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)) {
11201 l = CALLERID_UNKNOWN;
11202 n = l;
11203 d = FROMDOMAIN_INVALID;
11204 }
11205 if (ast_strlen_zero(l))
11206 l = default_callerid;
11207 if (ast_strlen_zero(n))
11208 n = l;
11209
11210 if (!ast_strlen_zero(p->fromuser))
11211 l = p->fromuser;
11212 else
11213 ast_string_field_set(p, fromuser, l);
11214
11215
11216 if (!ast_strlen_zero(p->fromname))
11217 n = p->fromname;
11218 else
11219 ast_string_field_set(p, fromname, n);
11220
11221 if (sip_cfg.pedanticsipchecking) {
11222 ast_uri_encode(n, tmp_n, sizeof(tmp_n), 0);
11223 n = tmp_n;
11224 ast_uri_encode(l, tmp_l, sizeof(tmp_l), 0);
11225 l = tmp_l;
11226 }
11227
11228 ourport = ntohs(p->ourip.sin_port);
11229 if (!sip_standard_port(p->socket.type, ourport) && ast_strlen_zero(p->fromdomain))
11230 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s:%d>;tag=%s", n, l, d, ourport, p->tag);
11231 else
11232 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=%s", n, l, d, p->tag);
11233
11234
11235 if (!ast_strlen_zero(p->fullcontact)) {
11236
11237 ast_str_append(&invite, 0, "%s", p->fullcontact);
11238 } else {
11239
11240 ast_str_append(&invite, 0, "sip:");
11241 if (!ast_strlen_zero(p->username)) {
11242 n = p->username;
11243 if (sip_cfg.pedanticsipchecking) {
11244 ast_uri_encode(n, tmp_n, sizeof(tmp_n), 0);
11245 n = tmp_n;
11246 }
11247 ast_str_append(&invite, 0, "%s@", n);
11248 }
11249 ast_str_append(&invite, 0, "%s", p->tohost);
11250 if (p->portinuri)
11251 ast_str_append(&invite, 0, ":%d", ntohs(p->sa.sin_port));
11252 ast_str_append(&invite, 0, "%s", urioptions);
11253 }
11254
11255
11256 if (p->options && !ast_strlen_zero(p->options->uri_options))
11257 ast_str_append(&invite, 0, ";%s", p->options->uri_options);
11258
11259
11260
11261
11262 ast_string_field_set(p, uri, invite->str);
11263
11264 if (!ast_strlen_zero(p->todnid)) {
11265
11266 if (!strchr(p->todnid, '@')) {
11267
11268 snprintf(to, sizeof(to), "<sip:%s@%s>%s%s", p->todnid, p->tohost, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
11269 } else {
11270 snprintf(to, sizeof(to), "<sip:%s>%s%s", p->todnid, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
11271 }
11272 } else {
11273 if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->theirtag)) {
11274
11275 snprintf(to, sizeof(to), "<%s%s>;tag=%s", (strncasecmp(p->uri, "sip:", 4) ? "sip:" : ""), p->uri, p->theirtag);
11276 } else if (p->options && p->options->vxml_url) {
11277
11278 snprintf(to, sizeof(to), "<%s>;%s", p->uri, p->options->vxml_url);
11279 } else
11280 snprintf(to, sizeof(to), "<%s>", p->uri);
11281 }
11282
11283 init_req(req, sipmethod, p->uri);
11284
11285 snprintf(tmp_n, sizeof(tmp_n), "%d %s", ++p->ocseq, sip_methods[sipmethod].text);
11286
11287 add_header(req, "Via", p->via);
11288 add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
11289
11290
11291
11292
11293 add_route(req, p->route);
11294
11295
11296 if (ast_test_flag(&p->flags[0], SIP_SENDRPID) && (sipmethod == SIP_INVITE)) {
11297 build_rpid(p);
11298 add_header(req, "From", p->rpid_from);
11299 } else
11300 add_header(req, "From", from);
11301 add_header(req, "To", to);
11302 ast_string_field_set(p, exten, l);
11303 build_contact(p);
11304 add_header(req, "Contact", p->our_contact);
11305 add_header(req, "Call-ID", p->callid);
11306 add_header(req, "CSeq", tmp_n);
11307 if (!ast_strlen_zero(global_useragent))
11308 add_header(req, "User-Agent", global_useragent);
11309 if (!ast_strlen_zero(p->rpid))
11310 add_header(req, "Remote-Party-ID", p->rpid);
11311 }
11312
11313
11314
11315
11316
11317
11318
11319
11320 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init)
11321 {
11322 struct sip_request req;
11323 struct ast_variable *var;
11324
11325 req.method = sipmethod;
11326 if (init) {
11327 p->branch ^= ast_random();
11328 p->invite_branch = p->branch;
11329 build_via(p);
11330 }
11331 if (init > 1)
11332 initreqprep(&req, p, sipmethod);
11333 else
11334
11335 reqprep(&req, p, sipmethod, 0, init ? 0 : 1);
11336
11337 if (p->options && p->options->auth)
11338 add_header(&req, p->options->authheader, p->options->auth);
11339 append_date(&req);
11340 if (sipmethod == SIP_REFER) {
11341 if (p->refer) {
11342 char buf[SIPBUFSIZE];
11343 if (!ast_strlen_zero(p->refer->refer_to))
11344 add_header(&req, "Refer-To", p->refer->refer_to);
11345 if (!ast_strlen_zero(p->refer->referred_by)) {
11346 snprintf(buf, sizeof(buf), "%s <%s>", p->refer->referred_by_name, p->refer->referred_by);
11347 add_header(&req, "Referred-By", buf);
11348 }
11349 }
11350 } else if (sipmethod == SIP_SUBSCRIBE) {
11351 char buf[SIPBUFSIZE];
11352
11353 add_header(&req, "Event", "message-summary");
11354 add_header(&req, "Accept", "application/simple-message-summary");
11355 snprintf(buf, sizeof(buf), "%d", mwi_expiry);
11356 add_header(&req, "Expires", buf);
11357 }
11358
11359
11360
11361 if (p->options && !ast_strlen_zero(p->options->replaces)) {
11362 add_header(&req, "Replaces", p->options->replaces);
11363 add_header(&req, "Require", "replaces");
11364 }
11365
11366
11367 if (st_get_mode(p) == SESSION_TIMER_MODE_ORIGINATE) {
11368 char i2astr[10];
11369
11370 if (!p->stimer->st_interval)
11371 p->stimer->st_interval = st_get_se(p, TRUE);
11372
11373 p->stimer->st_active = TRUE;
11374
11375 snprintf(i2astr, sizeof(i2astr), "%d", p->stimer->st_interval);
11376 add_header(&req, "Session-Expires", i2astr);
11377 snprintf(i2astr, sizeof(i2astr), "%d", st_get_se(p, FALSE));
11378 add_header(&req, "Min-SE", i2astr);
11379 }
11380
11381 add_header(&req, "Allow", ALLOWED_METHODS);
11382 add_supported_header(p, &req);
11383
11384 if(p->notify_headers) {
11385 char buf[512];
11386 for (var = p->notify_headers; var; var = var->next) {
11387 ast_copy_string(buf, var->value, sizeof(buf));
11388 add_header(&req, var->name, ast_unescape_semicolon(buf));
11389 }
11390 }
11391 if (p->options && p->options->addsipheaders && p->owner) {
11392 struct ast_channel *chan = p->owner;
11393 struct varshead *headp;
11394
11395 ast_channel_lock(chan);
11396
11397 headp = &chan->varshead;
11398
11399 if (!headp)
11400 ast_log(LOG_WARNING, "No Headp for the channel...ooops!\n");
11401 else {
11402 const struct ast_var_t *current;
11403 AST_LIST_TRAVERSE(headp, current, entries) {
11404
11405 if (!strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
11406 char *content, *end;
11407 const char *header = ast_var_value(current);
11408 char *headdup = ast_strdupa(header);
11409
11410
11411 if (*headdup == '"')
11412 headdup++;
11413 if ((content = strchr(headdup, ':'))) {
11414 *content++ = '\0';
11415 content = ast_skip_blanks(content);
11416
11417 end = content + strlen(content) -1;
11418 if (*end == '"')
11419 *end = '\0';
11420
11421 add_header(&req, headdup, content);
11422 if (sipdebug)
11423 ast_debug(1, "Adding SIP Header \"%s\" with content :%s: \n", headdup, content);
11424 }
11425 }
11426 }
11427 }
11428
11429 ast_channel_unlock(chan);
11430 }
11431 if (sdp) {
11432 memset(p->offered_media, 0, sizeof(p->offered_media));
11433 if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
11434 ast_debug(1, "T38 is in state %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
11435 add_sdp(&req, p, FALSE, FALSE, TRUE);
11436 } else if (p->rtp)
11437 add_sdp(&req, p, FALSE, TRUE, FALSE);
11438 }
11439
11440 if (!p->initreq.headers || init > 2)
11441 initialize_initreq(p, &req);
11442 p->lastinvite = p->ocseq;
11443 return send_request(p, &req, init ? XMIT_CRITICAL : XMIT_RELIABLE, p->ocseq);
11444 }
11445
11446
11447 static int sip_subscribe_mwi_do(const void *data)
11448 {
11449 struct sip_subscription_mwi *mwi = (struct sip_subscription_mwi*)data;
11450
11451 if (!mwi) {
11452 return -1;
11453 }
11454
11455 mwi->resub = -1;
11456 __sip_subscribe_mwi_do(mwi);
11457 ASTOBJ_UNREF(mwi, sip_subscribe_mwi_destroy);
11458
11459 return 0;
11460 }
11461
11462
11463 static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi)
11464 {
11465
11466 if (!mwi->dnsmgr) {
11467 char transport[MAXHOSTNAMELEN];
11468 snprintf(transport, sizeof(transport), "_%s._%s", get_srv_service(mwi->transport), get_srv_protocol(mwi->transport));
11469 ast_dnsmgr_lookup(mwi->hostname, &mwi->us, &mwi->dnsmgr, sip_cfg.srvlookup ? transport : NULL);
11470 }
11471
11472
11473 if (mwi->call) {
11474 transmit_invite(mwi->call, SIP_SUBSCRIBE, 0, 0);
11475 return 0;
11476 }
11477
11478
11479 if (!(mwi->call = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL))) {
11480 return -1;
11481 }
11482
11483 ref_proxy(mwi->call, obproxy_get(mwi->call, NULL));
11484
11485 if (!mwi->us.sin_port && mwi->portno) {
11486 mwi->us.sin_port = htons(mwi->portno);
11487 }
11488
11489
11490 if (create_addr(mwi->call, mwi->hostname, &mwi->us, 0)) {
11491 dialog_unlink_all(mwi->call, TRUE, TRUE);
11492 mwi->call = dialog_unref(mwi->call, "unref dialog after unlink_all");
11493 return 0;
11494 }
11495
11496 if (!mwi->dnsmgr && mwi->portno) {
11497 mwi->call->sa.sin_port = htons(mwi->portno);
11498 mwi->call->recv.sin_port = htons(mwi->portno);
11499 } else {
11500 mwi->portno = ntohs(mwi->call->sa.sin_port);
11501 }
11502
11503
11504 if (!ast_strlen_zero(mwi->authuser)) {
11505 ast_string_field_set(mwi->call, peername, mwi->authuser);
11506 ast_string_field_set(mwi->call, authname, mwi->authuser);
11507 ast_string_field_set(mwi->call, fromuser, mwi->authuser);
11508 } else {
11509 ast_string_field_set(mwi->call, peername, mwi->username);
11510 ast_string_field_set(mwi->call, authname, mwi->username);
11511 ast_string_field_set(mwi->call, fromuser, mwi->username);
11512 }
11513 ast_string_field_set(mwi->call, username, mwi->username);
11514 if (!ast_strlen_zero(mwi->secret)) {
11515 ast_string_field_set(mwi->call, peersecret, mwi->secret);
11516 }
11517 set_socket_transport(&mwi->call->socket, mwi->transport);
11518 mwi->call->socket.port = htons(mwi->portno);
11519 ast_sip_ouraddrfor(&mwi->call->sa.sin_addr, &mwi->call->ourip, mwi->call);
11520 build_contact(mwi->call);
11521 build_via(mwi->call);
11522 build_callid_pvt(mwi->call);
11523 ast_set_flag(&mwi->call->flags[0], SIP_OUTGOING);
11524
11525
11526 mwi->call->mwi = ASTOBJ_REF(mwi);
11527
11528
11529 transmit_invite(mwi->call, SIP_SUBSCRIBE, 0, 2);
11530
11531 return 0;
11532 }
11533
11534 static int find_calling_channel(struct ast_channel *c, void *data) {
11535 struct sip_pvt *p = data;
11536
11537 return (c->pbx &&
11538 (!strcasecmp(c->macroexten, p->exten) || !strcasecmp(c->exten, p->exten)) &&
11539 (sip_cfg.notifycid == IGNORE_CONTEXT || !strcasecmp(c->context, p->context)));
11540 }
11541
11542
11543 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout)
11544 {
11545 struct ast_str *tmp = ast_str_alloca(4000);
11546 char from[256], to[256];
11547 char *c, *mfrom, *mto;
11548 struct sip_request req;
11549 char hint[AST_MAX_EXTENSION];
11550 char *statestring = "terminated";
11551 const struct cfsubscription_types *subscriptiontype;
11552 enum state { NOTIFY_OPEN, NOTIFY_INUSE, NOTIFY_CLOSED } local_state = NOTIFY_OPEN;
11553 char *pidfstate = "--";
11554 char *pidfnote= "Ready";
11555
11556 memset(from, 0, sizeof(from));
11557 memset(to, 0, sizeof(to));
11558
11559 switch (state) {
11560 case (AST_EXTENSION_RINGING | AST_EXTENSION_INUSE):
11561 statestring = (sip_cfg.notifyringing) ? "early" : "confirmed";
11562 local_state = NOTIFY_INUSE;
11563 pidfstate = "busy";
11564 pidfnote = "Ringing";
11565 break;
11566 case AST_EXTENSION_RINGING:
11567 statestring = "early";
11568 local_state = NOTIFY_INUSE;
11569 pidfstate = "busy";
11570 pidfnote = "Ringing";
11571 break;
11572 case AST_EXTENSION_INUSE:
11573 statestring = "confirmed";
11574 local_state = NOTIFY_INUSE;
11575 pidfstate = "busy";
11576 pidfnote = "On the phone";
11577 break;
11578 case AST_EXTENSION_BUSY:
11579 statestring = "confirmed";
11580 local_state = NOTIFY_CLOSED;
11581 pidfstate = "busy";
11582 pidfnote = "On the phone";
11583 break;
11584 case AST_EXTENSION_UNAVAILABLE:
11585 statestring = "terminated";
11586 local_state = NOTIFY_CLOSED;
11587 pidfstate = "away";
11588 pidfnote = "Unavailable";
11589 break;
11590 case AST_EXTENSION_ONHOLD:
11591 statestring = "confirmed";
11592 local_state = NOTIFY_CLOSED;
11593 pidfstate = "busy";
11594 pidfnote = "On hold";
11595 break;
11596 case AST_EXTENSION_NOT_INUSE:
11597 default:
11598
11599 break;
11600 }
11601
11602 subscriptiontype = find_subscription_type(p->subscribed);
11603
11604
11605 if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, p->exten)) {
11606 char *hint2 = hint, *individual_hint = NULL;
11607 int hint_count = 0, unavailable_count = 0;
11608
11609 while ((individual_hint = strsep(&hint2, "&"))) {
11610 hint_count++;
11611
11612 if (ast_device_state(individual_hint) == AST_DEVICE_UNAVAILABLE)
11613 unavailable_count++;
11614 }
11615
11616
11617
11618
11619 if (hint_count > 0 && hint_count == unavailable_count) {
11620 local_state = NOTIFY_CLOSED;
11621 pidfstate = "away";
11622 pidfnote = "Not online";
11623 }
11624 }
11625
11626 ast_copy_string(from, get_header(&p->initreq, "From"), sizeof(from));
11627 c = get_in_brackets(from);
11628 if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
11629 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
11630 return -1;
11631 }
11632
11633 mfrom = remove_uri_parameters(c);
11634
11635 ast_copy_string(to, get_header(&p->initreq, "To"), sizeof(to));
11636 c = get_in_brackets(to);
11637 if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
11638 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
11639 return -1;
11640 }
11641 mto = remove_uri_parameters(c);
11642
11643 reqprep(&req, p, SIP_NOTIFY, 0, 1);
11644
11645
11646 add_header(&req, "Event", subscriptiontype->event);
11647 add_header(&req, "Content-Type", subscriptiontype->mediatype);
11648 switch(state) {
11649 case AST_EXTENSION_DEACTIVATED:
11650 if (timeout)
11651 add_header(&req, "Subscription-State", "terminated;reason=timeout");
11652 else {
11653 add_header(&req, "Subscription-State", "terminated;reason=probation");
11654 add_header(&req, "Retry-After", "60");
11655 }
11656 break;
11657 case AST_EXTENSION_REMOVED:
11658 add_header(&req, "Subscription-State", "terminated;reason=noresource");
11659 break;
11660 default:
11661 if (p->expiry)
11662 add_header(&req, "Subscription-State", "active");
11663 else
11664 add_header(&req, "Subscription-State", "terminated;reason=timeout");
11665 }
11666 switch (p->subscribed) {
11667 case XPIDF_XML:
11668 case CPIM_PIDF_XML:
11669 ast_str_append(&tmp, 0,
11670 "<?xml version=\"1.0\"?>\n"
11671 "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n"
11672 "<presence>\n");
11673 ast_str_append(&tmp, 0, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
11674 ast_str_append(&tmp, 0, "<atom id=\"%s\">\n", p->exten);
11675 ast_str_append(&tmp, 0, "<address uri=\"%s;user=ip\" priority=\"0.800000\">\n", mto);
11676 ast_str_append(&tmp, 0, "<status status=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "open" : (local_state == NOTIFY_INUSE) ? "inuse" : "closed");
11677 ast_str_append(&tmp, 0, "<msnsubstatus substatus=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "online" : (local_state == NOTIFY_INUSE) ? "onthephone" : "offline");
11678 ast_str_append(&tmp, 0, "</address>\n</atom>\n</presence>\n");
11679 break;
11680 case PIDF_XML:
11681 ast_str_append(&tmp, 0,
11682 "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"
11683 "<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);
11684 ast_str_append(&tmp, 0, "<pp:person><status>\n");
11685 if (pidfstate[0] != '-')
11686 ast_str_append(&tmp, 0, "<ep:activities><ep:%s/></ep:activities>\n", pidfstate);
11687 ast_str_append(&tmp, 0, "</status></pp:person>\n");
11688 ast_str_append(&tmp, 0, "<note>%s</note>\n", pidfnote);
11689 ast_str_append(&tmp, 0, "<tuple id=\"%s\">\n", p->exten);
11690 ast_str_append(&tmp, 0, "<contact priority=\"1\">%s</contact>\n", mto);
11691 if (pidfstate[0] == 'b')
11692 ast_str_append(&tmp, 0, "<status><basic>open</basic></status>\n");
11693 else
11694 ast_str_append(&tmp, 0, "<status><basic>%s</basic></status>\n", (local_state != NOTIFY_CLOSED) ? "open" : "closed");
11695 ast_str_append(&tmp, 0, "</tuple>\n</presence>\n");
11696 break;
11697 case DIALOG_INFO_XML:
11698 ast_str_append(&tmp, 0, "<?xml version=\"1.0\"?>\n");
11699 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);
11700 if ((state & AST_EXTENSION_RINGING) && sip_cfg.notifyringing) {
11701 const char *local_display = p->exten;
11702 char *local_target = mto;
11703
11704
11705
11706
11707 if (sip_cfg.notifycid) {
11708 struct ast_channel *caller = ast_channel_search_locked(find_calling_channel, p);
11709
11710 if (caller) {
11711 int need = strlen(caller->cid.cid_num) + strlen(p->fromdomain) + sizeof("sip:@");
11712 local_target = alloca(need);
11713 snprintf(local_target, need, "sip:%s@%s", caller->cid.cid_num, p->fromdomain);
11714 if (!(ast_strlen_zero(caller->cid.cid_name))) {
11715 local_display = ast_strdupa(caller->cid.cid_name);
11716 }
11717 ast_channel_unlock(caller);
11718 caller = NULL;
11719 }
11720
11721
11722 if (sip_cfg.pedanticsipchecking) {
11723 ast_str_append(&tmp, 0, "<dialog id=\"%s\" call-id=\"pickup-%s\" local-tag=\"%s\" remote-tag=\"%s\" direction=\"recipient\">\n",
11724 p->exten, p->callid, p->theirtag, p->tag);
11725 } else {
11726 ast_str_append(&tmp, 0, "<dialog id=\"%s\" call-id=\"pickup-%s\" direction=\"recipient\">\n",
11727 p->exten, p->callid);
11728 }
11729 ast_str_append(&tmp, 0,
11730 "<remote>\n"
11731
11732
11733 "<identity display=\"%s\">%s</identity>\n"
11734 "<target uri=\"%s\"/>\n"
11735 "</remote>\n"
11736 "<local>\n"
11737 "<identity>%s</identity>\n"
11738 "<target uri=\"%s\"/>\n"
11739 "</local>\n",
11740 local_display, local_target, local_target, mto, mto);
11741 } else {
11742 ast_str_append(&tmp, 0, "<dialog id=\"%s\" direction=\"recipient\">\n", p->exten);
11743 }
11744 } else {
11745 ast_str_append(&tmp, 0, "<dialog id=\"%s\">\n", p->exten);
11746 }
11747 ast_str_append(&tmp, 0, "<state>%s</state>\n", statestring);
11748 if (state == AST_EXTENSION_ONHOLD) {
11749 ast_str_append(&tmp, 0, "<local>\n<target uri=\"%s\">\n"
11750 "<param pname=\"+sip.rendering\" pvalue=\"no\"/>\n"
11751 "</target>\n</local>\n", mto);
11752 }
11753 ast_str_append(&tmp, 0, "</dialog>\n</dialog-info>\n");
11754 break;
11755 case NONE:
11756 default:
11757 break;
11758 }
11759
11760 add_content(&req, tmp->str);
11761
11762 p->pendinginvite = p->ocseq;
11763
11764 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11765 }
11766
11767
11768
11769
11770
11771
11772
11773 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten)
11774 {
11775 struct sip_request req;
11776 struct ast_str *out = ast_str_alloca(500);
11777 int ourport = ntohs(p->ourip.sin_port);
11778 const char *exten = S_OR(vmexten, default_vmexten);
11779
11780 initreqprep(&req, p, SIP_NOTIFY);
11781 add_header(&req, "Event", "message-summary");
11782 add_header(&req, "Content-Type", default_notifymime);
11783 ast_str_append(&out, 0, "Messages-Waiting: %s\r\n", newmsgs ? "yes" : "no");
11784
11785 if (!ast_strlen_zero(p->fromdomain)) {
11786 ast_str_append(&out, 0, "Message-Account: sip:%s@%s\r\n", exten, p->fromdomain);
11787 } else if (!sip_standard_port(p->socket.type, ourport)) {
11788 if (p->socket.type == SIP_TRANSPORT_UDP) {
11789 ast_str_append(&out, 0, "Message-Account: sip:%s@%s:%d\r\n", exten, ast_inet_ntoa(p->ourip.sin_addr), ourport);
11790 } else {
11791 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));
11792 }
11793 } else {
11794 if (p->socket.type == SIP_TRANSPORT_UDP) {
11795 ast_str_append(&out, 0, "Message-Account: sip:%s@%s\r\n", exten, ast_inet_ntoa(p->ourip.sin_addr));
11796 } else {
11797 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));
11798 }
11799 }
11800
11801
11802
11803 ast_str_append(&out, 0, "Voice-Message: %d/%d%s\r\n",
11804 newmsgs, oldmsgs, (ast_test_flag(&p->flags[1], SIP_PAGE2_BUGGY_MWI) ? "" : " (0/0)"));
11805
11806 if (p->subscribed) {
11807 if (p->expiry)
11808 add_header(&req, "Subscription-State", "active");
11809 else
11810 add_header(&req, "Subscription-State", "terminated;reason=timeout");
11811 }
11812
11813 add_content(&req, out->str);
11814
11815 if (!p->initreq.headers)
11816 initialize_initreq(p, &req);
11817 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11818 }
11819
11820
11821 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate)
11822 {
11823 struct sip_request req;
11824 char tmp[SIPBUFSIZE/2];
11825
11826 reqprep(&req, p, SIP_NOTIFY, 0, 1);
11827 snprintf(tmp, sizeof(tmp), "refer;id=%d", cseq);
11828 add_header(&req, "Event", tmp);
11829 add_header(&req, "Subscription-state", terminate ? "terminated;reason=noresource" : "active");
11830 add_header(&req, "Content-Type", "message/sipfrag;version=2.0");
11831 add_header(&req, "Allow", ALLOWED_METHODS);
11832 add_supported_header(p, &req);
11833
11834 snprintf(tmp, sizeof(tmp), "SIP/2.0 %s\r\n", message);
11835 add_content(&req, tmp);
11836
11837 if (!p->initreq.headers)
11838 initialize_initreq(p, &req);
11839
11840 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11841 }
11842
11843
11844 static int transmit_notify_custom(struct sip_pvt *p, struct ast_variable *vars) {
11845 struct sip_request req;
11846 struct ast_variable *var, *newvar;
11847
11848 initreqprep(&req, p, SIP_NOTIFY);
11849
11850
11851 p->notify_headers = newvar = ast_variable_new("Subscription-State", "terminated", "");
11852 add_header(&req, newvar->name, newvar->value);
11853 for (var = vars; var; var = var->next) {
11854 char buf[512];
11855
11856 if (!strcasecmp(var->name, "Content-Length")) {
11857 ast_debug(2, "Ignoring pair %s=%s\n", var->name, var->value);
11858 continue;
11859 }
11860
11861 ast_debug(2, " Adding pair %s=%s\n", var->name, var->value);
11862 ast_copy_string(buf, var->value, sizeof(buf));
11863 add_header(&req, var->name, ast_unescape_semicolon(buf));
11864 newvar->next = ast_variable_new(var->name, var->value, "");
11865 newvar = newvar->next;
11866 }
11867
11868 if (!p->initreq.headers) {
11869 initialize_initreq(p, &req);
11870 }
11871
11872 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11873 }
11874
11875 static int manager_sipnotify(struct mansession *s, const struct message *m)
11876 {
11877 const char *channame = astman_get_header(m, "Channel");
11878 struct ast_variable *vars = astman_get_variables(m);
11879 struct sip_pvt *p;
11880
11881 if (ast_strlen_zero(channame)) {
11882 astman_send_error(s, m, "SIPNotify requires a channel name");
11883 return 0;
11884 }
11885
11886 if (!strncasecmp(channame, "sip/", 4)) {
11887 channame += 4;
11888 }
11889
11890 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
11891 astman_send_error(s, m, "Unable to build sip pvt data for notify (memory/socket error)");
11892 return 0;
11893 }
11894
11895 if (create_addr(p, channame, NULL, 0)) {
11896
11897 dialog_unlink_all(p, TRUE, TRUE);
11898 dialog_unref(p, "unref dialog inside for loop" );
11899
11900 astman_send_error(s, m, "Could not create address");
11901 return 0;
11902 }
11903
11904
11905 ast_set_flag(&p->flags[0], SIP_OUTGOING);
11906
11907
11908 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
11909 build_via(p);
11910 ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
11911 build_callid_pvt(p);
11912 ao2_t_link(dialogs, p, "Linking in new name");
11913 dialog_ref(p, "bump the count of p, which transmit_sip_request will decrement.");
11914 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
11915
11916 if (!transmit_notify_custom(p, vars)) {
11917 astman_send_ack(s, m, "Notify Sent");
11918 } else {
11919 astman_send_error(s, m, "Unable to send notify");
11920 }
11921 ast_variables_destroy(vars);
11922 return 0;
11923 }
11924
11925 static char mandescr_sipnotify[] =
11926 "Description: Sends a SIP Notify event\n"
11927 "All parameters for this event must be specified in the body of this request\n"
11928 "via multiple Variable: name=value sequences.\n"
11929 "Variables: \n"
11930 " *Channel: <peername> Peer to receive the notify. Required.\n"
11931 " *Variable: <name>=<value> At least one variable pair must be specified.\n"
11932 " ActionID: <id> Action ID for this transaction. Will be returned.\n";
11933
11934 static const struct _map_x_s regstatestrings[] = {
11935 { REG_STATE_FAILED, "Failed" },
11936 { REG_STATE_UNREGISTERED, "Unregistered"},
11937 { REG_STATE_REGSENT, "Request Sent"},
11938 { REG_STATE_AUTHSENT, "Auth. Sent"},
11939 { REG_STATE_REGISTERED, "Registered"},
11940 { REG_STATE_REJECTED, "Rejected"},
11941 { REG_STATE_TIMEOUT, "Timeout"},
11942 { REG_STATE_NOAUTH, "No Authentication"},
11943 { -1, NULL }
11944 };
11945
11946
11947 static const char *regstate2str(enum sipregistrystate regstate)
11948 {
11949 return map_x_s(regstatestrings, regstate, "Unknown");
11950 }
11951
11952
11953
11954
11955
11956
11957
11958 static int sip_reregister(const void *data)
11959 {
11960
11961 struct sip_registry *r= (struct sip_registry *) data;
11962
11963
11964 if (!r)
11965 return 0;
11966
11967 if (r->call && r->call->do_history)
11968 append_history(r->call, "RegistryRenew", "Account: %s@%s", r->username, r->hostname);
11969
11970
11971 if (sipdebug)
11972 ast_log(LOG_NOTICE, " -- Re-registration for %s@%s\n", r->username, r->hostname);
11973
11974 r->expire = -1;
11975 r->expiry = r->configured_expiry;
11976 __sip_do_register(r);
11977 registry_unref(r, "unref the re-register scheduled event");
11978 return 0;
11979 }
11980
11981
11982 static int __sip_do_register(struct sip_registry *r)
11983 {
11984 int res;
11985
11986 res = transmit_register(r, SIP_REGISTER, NULL, NULL);
11987 return res;
11988 }
11989
11990
11991
11992
11993
11994
11995
11996 static int sip_reg_timeout(const void *data)
11997 {
11998
11999
12000 struct sip_registry *r = (struct sip_registry *)data;
12001 struct sip_pvt *p;
12002 int res;
12003
12004
12005 if (!r)
12006 return 0;
12007
12008 if (r->dnsmgr) {
12009
12010 ast_dnsmgr_refresh(r->dnsmgr);
12011 }
12012
12013 ast_log(LOG_NOTICE, " -- Registration for '%s@%s' timed out, trying again (Attempt #%d)\n", r->username, r->hostname, r->regattempts);
12014
12015
12016
12017
12018 if (r->call) {
12019
12020
12021 p = r->call;
12022 sip_pvt_lock(p);
12023 pvt_set_needdestroy(p, "registration timeout");
12024
12025 __sip_pretend_ack(p);
12026 sip_pvt_unlock(p);
12027
12028
12029
12030 if (p->registry)
12031 p->registry = registry_unref(p->registry, "p->registry unreffed");
12032 r->call = dialog_unref(r->call, "unrefing r->call");
12033 }
12034
12035 r->timeout = -1;
12036 if (global_regattempts_max && r->regattempts > global_regattempts_max) {
12037
12038
12039
12040 ast_log(LOG_NOTICE, " -- Giving up forever trying to register '%s@%s'\n", r->username, r->hostname);
12041 r->regstate = REG_STATE_FAILED;
12042 } else {
12043 r->regstate = REG_STATE_UNREGISTERED;
12044 res=transmit_register(r, SIP_REGISTER, NULL, NULL);
12045 }
12046 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));
12047 registry_unref(r, "unreffing registry_unref r");
12048 return 0;
12049 }
12050
12051
12052
12053
12054 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader)
12055 {
12056 struct sip_request req;
12057 char from[256];
12058 char to[256];
12059 char tmp[80];
12060 char addr[80];
12061 struct sip_pvt *p;
12062 struct sip_peer *peer = NULL;
12063 int res;
12064 char *fromdomain;
12065 char *domainport = NULL;
12066
12067
12068 if (r == NULL || ((auth == NULL) && (r->regstate == REG_STATE_REGSENT || r->regstate == REG_STATE_AUTHSENT))) {
12069 if (r) {
12070 ast_log(LOG_NOTICE, "Strange, trying to register %s@%s when registration already pending\n", r->username, r->hostname);
12071 }
12072 return 0;
12073 }
12074
12075 if (r->dnsmgr == NULL) {
12076 char transport[MAXHOSTNAMELEN];
12077 peer = find_peer(r->hostname, NULL, TRUE, FINDPEERS, FALSE, 0);
12078 snprintf(transport, sizeof(transport), "_%s._%s",get_srv_service(r->transport), get_srv_protocol(r->transport));
12079 ast_dnsmgr_lookup(peer ? peer->tohost : r->hostname, &r->us, &r->dnsmgr, sip_cfg.srvlookup ? transport : NULL);
12080 if (peer) {
12081 peer = unref_peer(peer, "removing peer ref for dnsmgr_lookup");
12082 }
12083 }
12084
12085 if (r->call) {
12086 if (!auth) {
12087 ast_log(LOG_WARNING, "Already have a REGISTER going on to %s@%s?? \n", r->username, r->hostname);
12088 return 0;
12089 } else {
12090 p = dialog_ref(r->call, "getting a copy of the r->call dialog in transmit_register");
12091 make_our_tag(p->tag, sizeof(p->tag));
12092 ast_string_field_set(p, theirtag, NULL);
12093 }
12094 } else {
12095
12096 if (!r->callid_valid) {
12097 build_callid_registry(r, internip.sin_addr, default_fromdomain);
12098 r->callid_valid = TRUE;
12099 }
12100
12101 if (!(p = sip_alloc( r->callid, NULL, 0, SIP_REGISTER, NULL))) {
12102 ast_log(LOG_WARNING, "Unable to allocate registration transaction (memory or socket error)\n");
12103 return 0;
12104 }
12105
12106 if (p->do_history)
12107 append_history(p, "RegistryInit", "Account: %s@%s", r->username, r->hostname);
12108
12109
12110 if (!r->us.sin_port && r->portno)
12111 r->us.sin_port = htons(r->portno);
12112
12113
12114 if (create_addr(p, S_OR(r->peername, r->hostname), &r->us, 0)) {
12115
12116
12117 dialog_unlink_all(p, TRUE, TRUE);
12118 p = dialog_unref(p, "unref dialog after unlink_all");
12119 if (r->timeout > -1) {
12120 AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
12121 registry_unref(_data, "del for REPLACE of registry ptr"),
12122 registry_unref(r, "object ptr dec when SCHED_REPLACE add failed"),
12123 registry_addref(r,"add for REPLACE registry ptr"));
12124 ast_log(LOG_WARNING, "Still have a registration timeout for %s@%s (create_addr() error), %d\n", r->username, r->hostname, r->timeout);
12125 } else {
12126 r->timeout = ast_sched_add(sched, global_reg_timeout * 1000, sip_reg_timeout, registry_addref(r, "add for REPLACE registry ptr"));
12127 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);
12128 }
12129 r->regattempts++;
12130 return 0;
12131 }
12132
12133
12134 ast_string_field_set(r, callid, p->callid);
12135 if (!r->dnsmgr && r->portno) {
12136 p->sa.sin_port = htons(r->portno);
12137 p->recv.sin_port = htons(r->portno);
12138 } else {
12139 r->portno = ntohs(p->sa.sin_port);
12140 }
12141 ast_set_flag(&p->flags[0], SIP_OUTGOING);
12142 r->call = dialog_ref(p, "copying dialog into registry r->call");
12143 p->registry = registry_addref(r, "transmit_register: addref to p->registry in transmit_register");
12144 if (!ast_strlen_zero(r->secret)) {
12145 ast_string_field_set(p, peersecret, r->secret);
12146 }
12147 if (!ast_strlen_zero(r->md5secret))
12148 ast_string_field_set(p, peermd5secret, r->md5secret);
12149
12150
12151 if (!ast_strlen_zero(r->authuser)) {
12152 ast_string_field_set(p, peername, r->authuser);
12153 ast_string_field_set(p, authname, r->authuser);
12154 } else if (!ast_strlen_zero(r->username)) {
12155 ast_string_field_set(p, peername, r->username);
12156 ast_string_field_set(p, authname, r->username);
12157 ast_string_field_set(p, fromuser, r->username);
12158 }
12159 if (!ast_strlen_zero(r->username))
12160 ast_string_field_set(p, username, r->username);
12161
12162 if (!ast_strlen_zero(r->callback))
12163 ast_string_field_set(p, exten, r->callback);
12164
12165
12166 set_socket_transport(&p->socket, r->transport);
12167 if (r->transport == SIP_TRANSPORT_TLS || r->transport == SIP_TRANSPORT_TCP) {
12168 p->socket.port = sip_tcp_desc.local_address.sin_port;
12169 }
12170
12171
12172
12173
12174
12175
12176 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
12177 build_contact(p);
12178 }
12179
12180
12181 if (auth == NULL) {
12182 if (r->timeout > -1)
12183 ast_log(LOG_WARNING, "Still have a registration timeout, #%d - deleting it\n", r->timeout);
12184 AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
12185 registry_unref(_data,"reg ptr unrefed from del in SCHED_REPLACE"),
12186 registry_unref(r,"reg ptr unrefed from add failure in SCHED_REPLACE"),
12187 registry_addref(r,"reg ptr reffed from add in SCHED_REPLACE"));
12188 ast_debug(1, "Scheduled a registration timeout for %s id #%d \n", r->hostname, r->timeout);
12189 }
12190
12191 if ((fromdomain = strchr(r->username, '@'))) {
12192
12193 fromdomain++ ;
12194
12195 snprintf(from, sizeof(from), "<sip:%s>;tag=%s", r->username, p->tag);
12196 if (!ast_strlen_zero(p->theirtag))
12197 snprintf(to, sizeof(to), "<sip:%s>;tag=%s", r->username, p->theirtag);
12198 else
12199 snprintf(to, sizeof(to), "<sip:%s>", r->username);
12200
12201
12202
12203 if (ast_strlen_zero(p->fromdomain)) {
12204 ast_string_field_set(p, fromdomain, fromdomain);
12205 }
12206 } else {
12207 snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->tag);
12208 if (!ast_strlen_zero(p->theirtag))
12209 snprintf(to, sizeof(to), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->theirtag);
12210 else
12211 snprintf(to, sizeof(to), "<sip:%s@%s>", r->username, p->tohost);
12212 }
12213
12214
12215
12216 if (!ast_strlen_zero(p->fromdomain)) {
12217 domainport = strrchr(p->fromdomain, ':');
12218 if (domainport) {
12219 *domainport++ = '\0';
12220 if (ast_strlen_zero(domainport))
12221 domainport = NULL;
12222 }
12223 if (domainport) {
12224 if (atoi(domainport) != STANDARD_SIP_PORT)
12225 snprintf(addr, sizeof(addr), "sip:%s:%s", p->fromdomain, domainport);
12226 else
12227 snprintf(addr, sizeof(addr), "sip:%s", p->fromdomain);
12228 } else {
12229 if (r->portno && r->portno != STANDARD_SIP_PORT)
12230 snprintf(addr, sizeof(addr), "sip:%s:%d", p->fromdomain, r->portno);
12231 else
12232 snprintf(addr, sizeof(addr), "sip:%s", p->fromdomain);
12233 }
12234 } else {
12235 if (r->portno && r->portno != STANDARD_SIP_PORT)
12236 snprintf(addr, sizeof(addr), "sip:%s:%d", r->hostname, r->portno);
12237 else
12238 snprintf(addr, sizeof(addr), "sip:%s", r->hostname);
12239 }
12240 ast_string_field_set(p, uri, addr);
12241
12242 p->branch ^= ast_random();
12243
12244 init_req(&req, sipmethod, addr);
12245
12246
12247 snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, sip_methods[sipmethod].text);
12248 p->ocseq = r->ocseq;
12249
12250 build_via(p);
12251 add_header(&req, "Via", p->via);
12252 add_header(&req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
12253 add_header(&req, "From", from);
12254 add_header(&req, "To", to);
12255 add_header(&req, "Call-ID", p->callid);
12256 add_header(&req, "CSeq", tmp);
12257 if (!ast_strlen_zero(global_useragent))
12258 add_header(&req, "User-Agent", global_useragent);
12259
12260
12261 if (auth)
12262 add_header(&req, authheader, auth);
12263 else if (!ast_strlen_zero(r->nonce)) {
12264 char digest[1024];
12265
12266
12267
12268
12269
12270
12271 if (sipdebug)
12272 ast_debug(1, " >>> Re-using Auth data for %s@%s\n", r->username, r->hostname);
12273 ast_string_field_set(p, realm, r->realm);
12274 ast_string_field_set(p, nonce, r->nonce);
12275 ast_string_field_set(p, domain, r->domain);
12276 ast_string_field_set(p, opaque, r->opaque);
12277 ast_string_field_set(p, qop, r->qop);
12278 p->noncecount = ++r->noncecount;
12279
12280 memset(digest, 0, sizeof(digest));
12281 if(!build_reply_digest(p, sipmethod, digest, sizeof(digest)))
12282 add_header(&req, "Authorization", digest);
12283 else
12284 ast_log(LOG_NOTICE, "No authorization available for authentication of registration to %s@%s\n", r->username, r->hostname);
12285
12286 }
12287
12288 snprintf(tmp, sizeof(tmp), "%d", r->expiry);
12289 add_header(&req, "Expires", tmp);
12290 add_header(&req, "Contact", p->our_contact);
12291
12292 initialize_initreq(p, &req);
12293 if (sip_debug_test_pvt(p)) {
12294 ast_verbose("REGISTER %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
12295 }
12296 r->regstate = auth ? REG_STATE_AUTHSENT : REG_STATE_REGSENT;
12297 r->regattempts++;
12298 ast_debug(4, "REGISTER attempt %d to %s@%s\n", r->regattempts, r->username, r->hostname);
12299 res = send_request(p, &req, XMIT_CRITICAL, p->ocseq);
12300 dialog_unref(p, "p is finished here at the end of transmit_register");
12301 return res;
12302 }
12303
12304
12305 static int transmit_message_with_text(struct sip_pvt *p, const char *text)
12306 {
12307 struct sip_request req;
12308
12309 reqprep(&req, p, SIP_MESSAGE, 0, 1);
12310 add_text(&req, text);
12311 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
12312 }
12313
12314
12315 static int sip_refer_allocate(struct sip_pvt *p)
12316 {
12317 p->refer = ast_calloc(1, sizeof(struct sip_refer));
12318 return p->refer ? 1 : 0;
12319 }
12320
12321
12322
12323
12324
12325
12326 static int transmit_refer(struct sip_pvt *p, const char *dest)
12327 {
12328 struct sip_request req = {
12329 .headers = 0,
12330 };
12331 char from[256];
12332 const char *of;
12333 char *c;
12334 char referto[256];
12335 char *ttag, *ftag;
12336 char *theirtag = ast_strdupa(p->theirtag);
12337 int use_tls=FALSE;
12338
12339 if (sipdebug)
12340 ast_debug(1, "SIP transfer of %s to %s\n", p->callid, dest);
12341
12342
12343 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
12344 of = get_header(&p->initreq, "To");
12345 ttag = theirtag;
12346 ftag = p->tag;
12347 } else {
12348 of = get_header(&p->initreq, "From");
12349 ftag = theirtag;
12350 ttag = p->tag;
12351 }
12352
12353 ast_copy_string(from, of, sizeof(from));
12354 of = get_in_brackets(from);
12355 ast_string_field_set(p, from, of);
12356 if (!strncasecmp(of, "sip:", 4)) {
12357 of += 4;
12358 }else if (!strncasecmp(of, "sips:", 5)) {
12359 of += 5;
12360 use_tls = TRUE;
12361 } else {
12362 ast_log(LOG_NOTICE, "From address missing 'sip(s):', assuming sip:\n");
12363 }
12364
12365 if ((c = strchr(dest, '@')))
12366 c = NULL;
12367 else if ((c = strchr(of, '@')))
12368 *c++ = '\0';
12369 if (c)
12370 snprintf(referto, sizeof(referto), "<sip%s:%s@%s>", use_tls ? "s" : "", dest, c);
12371 else
12372 snprintf(referto, sizeof(referto), "<sip%s:%s>", use_tls ? "s" : "", dest);
12373
12374
12375 sip_refer_allocate(p);
12376 ast_copy_string(p->refer->refer_to, referto, sizeof(p->refer->refer_to));
12377 ast_copy_string(p->refer->referred_by, p->our_contact, sizeof(p->refer->referred_by));
12378 p->refer->status = REFER_SENT;
12379
12380 reqprep(&req, p, SIP_REFER, 0, 1);
12381
12382 add_header(&req, "Refer-To", referto);
12383 add_header(&req, "Allow", ALLOWED_METHODS);
12384 add_supported_header(p, &req);
12385 if (!ast_strlen_zero(p->our_contact))
12386 add_header(&req, "Referred-By", p->our_contact);
12387
12388 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398 }
12399
12400
12401
12402 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration)
12403 {
12404 struct sip_request req;
12405
12406 reqprep(&req, p, SIP_INFO, 0, 1);
12407 add_digit(&req, digit, duration, (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_SHORTINFO));
12408 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
12409 }
12410
12411
12412 static int transmit_info_with_vidupdate(struct sip_pvt *p)
12413 {
12414 struct sip_request req;
12415
12416 reqprep(&req, p, SIP_INFO, 0, 1);
12417 add_vidupdate(&req);
12418 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
12419 }
12420
12421
12422
12423
12424 static int transmit_request(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
12425 {
12426 struct sip_request resp;
12427
12428 if (sipmethod == SIP_ACK)
12429 p->invitestate = INV_CONFIRMED;
12430
12431 reqprep(&resp, p, sipmethod, seqno, newbranch);
12432 if (sipmethod == SIP_CANCEL && p->answered_elsewhere)
12433 add_header(&resp, "Reason", "SIP;cause=200;text=\"Call completed elsewhere\"");
12434
12435 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
12436 }
12437
12438
12439 static void auth_headers(enum sip_auth_type code, char **header, char **respheader)
12440 {
12441 if (code == WWW_AUTH) {
12442 *header = "WWW-Authenticate";
12443 *respheader = "Authorization";
12444 } else if (code == PROXY_AUTH) {
12445 *header = "Proxy-Authenticate";
12446 *respheader = "Proxy-Authorization";
12447 } else {
12448 ast_verbose("-- wrong response code %d\n", code);
12449 *header = *respheader = "Invalid";
12450 }
12451 }
12452
12453
12454 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
12455 {
12456 struct sip_request resp;
12457
12458 reqprep(&resp, p, sipmethod, seqno, newbranch);
12459 if (!ast_strlen_zero(p->realm)) {
12460 char digest[1024];
12461
12462 memset(digest, 0, sizeof(digest));
12463 if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
12464 char *dummy, *response;
12465 enum sip_auth_type code = p->options ? p->options->auth_type : PROXY_AUTH;
12466 auth_headers(code, &dummy, &response);
12467 add_header(&resp, response, digest);
12468 } else
12469 ast_log(LOG_WARNING, "No authentication available for call %s\n", p->callid);
12470 }
12471
12472
12473 if (sipmethod == SIP_BYE) {
12474 char buf[10];
12475
12476 add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->hangupcause));
12477 snprintf(buf, sizeof(buf), "%d", p->hangupcause);
12478 add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
12479 }
12480
12481 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
12482 }
12483
12484
12485 static void destroy_association(struct sip_peer *peer)
12486 {
12487 int realtimeregs = ast_check_realtime("sipregs");
12488 char *tablename = (realtimeregs) ? "sipregs" : "sippeers";
12489
12490 if (!sip_cfg.ignore_regexpire) {
12491 if (peer->rt_fromcontact && sip_cfg.peer_rtupdate) {
12492 ast_update_realtime(tablename, "name", peer->name, "fullcontact", "", "ipaddr", "", "port", "", "regseconds", "0", "regserver", "", "useragent", "", "lastms", "", SENTINEL);
12493 } else {
12494 ast_db_del("SIP/Registry", peer->name);
12495 }
12496 }
12497 }
12498
12499 static void set_socket_transport(struct sip_socket *socket, int transport)
12500 {
12501
12502 if (socket->type != transport) {
12503 socket->fd = -1;
12504 socket->type = transport;
12505 if (socket->tcptls_session) {
12506 ao2_ref(socket->tcptls_session, -1);
12507 socket->tcptls_session = NULL;
12508 }
12509 }
12510 }
12511
12512
12513 static int expire_register(const void *data)
12514 {
12515 struct sip_peer *peer = (struct sip_peer *)data;
12516
12517 if (!peer)
12518 return 0;
12519
12520 peer->expire = -1;
12521 peer->portinuri = 0;
12522
12523 destroy_association(peer);
12524 set_socket_transport(&peer->socket, peer->default_outbound_transport);
12525
12526 if (peer->socket.tcptls_session) {
12527 ao2_ref(peer->socket.tcptls_session, -1);
12528 peer->socket.tcptls_session = NULL;
12529 }
12530
12531 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
12532 register_peer_exten(peer, FALSE);
12533 ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
12534
12535
12536
12537
12538 if (peer->is_realtime)
12539 ast_debug(3, "-REALTIME- peer expired registration. Name: %s. Realtime peer objects now %d\n", peer->name, rpeerobjs);
12540
12541 if (peer->selfdestruct ||
12542 ast_test_flag(&peer->flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
12543 unlink_peer_from_tables(peer);
12544 }
12545
12546
12547
12548 memset(&peer->addr, 0, sizeof(peer->addr));
12549
12550 unref_peer(peer, "removing peer ref for expire_register");
12551
12552 return 0;
12553 }
12554
12555
12556 static int sip_poke_peer_s(const void *data)
12557 {
12558 struct sip_peer *peer = (struct sip_peer *)data;
12559 struct sip_peer *foundpeer;
12560
12561 peer->pokeexpire = -1;
12562
12563 foundpeer = ao2_find(peers, peer, OBJ_POINTER);
12564 if (!foundpeer) {
12565 unref_peer(peer, "removing poke peer ref");
12566 return 0;
12567 } else if (foundpeer->name != peer->name) {
12568 unref_peer(foundpeer, "removing above peer ref");
12569 unref_peer(peer, "removing poke peer ref");
12570 return 0;
12571 }
12572
12573 unref_peer(foundpeer, "removing above peer ref");
12574 sip_poke_peer(peer, 0);
12575 unref_peer(peer, "removing poke peer ref");
12576
12577 return 0;
12578 }
12579
12580
12581 static void reg_source_db(struct sip_peer *peer)
12582 {
12583 char data[256];
12584 struct in_addr in;
12585 int expire;
12586 int port;
12587 char *scan, *addr, *port_str, *expiry_str, *username, *contact;
12588
12589 if (peer->rt_fromcontact)
12590 return;
12591 if (ast_db_get("SIP/Registry", peer->name, data, sizeof(data)))
12592 return;
12593
12594 scan = data;
12595 addr = strsep(&scan, ":");
12596 port_str = strsep(&scan, ":");
12597 expiry_str = strsep(&scan, ":");
12598 username = strsep(&scan, ":");
12599 contact = scan;
12600
12601 if (!inet_aton(addr, &in))
12602 return;
12603
12604 if (port_str)
12605 port = atoi(port_str);
12606 else
12607 return;
12608
12609 if (expiry_str)
12610 expire = atoi(expiry_str);
12611 else
12612 return;
12613
12614 if (username)
12615 ast_string_field_set(peer, username, username);
12616 if (contact)
12617 ast_string_field_set(peer, fullcontact, contact);
12618
12619 ast_debug(2, "SIP Seeding peer from astdb: '%s' at %s@%s:%d for %d\n",
12620 peer->name, peer->username, ast_inet_ntoa(in), port, expire);
12621
12622 memset(&peer->addr, 0, sizeof(peer->addr));
12623 peer->addr.sin_family = AF_INET;
12624 peer->addr.sin_addr = in;
12625 peer->addr.sin_port = htons(port);
12626 if (sipsock < 0) {
12627
12628 AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, ast_random() % 5000 + 1, sip_poke_peer_s, peer,
12629 unref_peer(_data, "removing poke peer ref"),
12630 unref_peer(peer, "removing poke peer ref"),
12631 ref_peer(peer, "adding poke peer ref"));
12632 } else {
12633 sip_poke_peer(peer, 0);
12634 }
12635 AST_SCHED_REPLACE_UNREF(peer->expire, sched, (expire + 10) * 1000, expire_register, peer,
12636 unref_peer(_data, "remove registration ref"),
12637 unref_peer(peer, "remove registration ref"),
12638 ref_peer(peer, "add registration ref"));
12639 register_peer_exten(peer, TRUE);
12640 }
12641
12642
12643 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req)
12644 {
12645 char contact[SIPBUFSIZE];
12646 char *c;
12647
12648
12649 ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
12650 c = get_in_brackets(contact);
12651
12652
12653 ast_string_field_set(pvt, fullcontact, c);
12654
12655
12656 ast_string_field_set(pvt, okcontacturi, c);
12657
12658
12659
12660 return TRUE;
12661 }
12662
12663 static int __set_address_from_contact(const char *fullcontact, struct sockaddr_in *sin, int tcp)
12664 {
12665 struct hostent *hp;
12666 struct ast_hostent ahp;
12667 int port = STANDARD_SIP_PORT;
12668 char *host, *pt, *transport;
12669 char contact_buf[256];
12670 char *contact;
12671
12672
12673 ast_copy_string(contact_buf, fullcontact, sizeof(contact_buf));
12674 contact = contact_buf;
12675
12676
12677
12678
12679
12680
12681
12682
12683 if (parse_uri(contact, "sip:,sips:", &contact, NULL, &host, &pt, NULL, &transport)) {
12684 ast_log(LOG_WARNING, "Invalid contact uri %s (missing sip: or sips:), attempting to use anyway\n", fullcontact);
12685 }
12686
12687
12688 if (((get_transport_str2enum(transport) == SIP_TRANSPORT_TLS)) || !(strncasecmp(fullcontact, "sips", 4))) {
12689 port = port_str2int(pt, STANDARD_TLS_PORT);
12690 } else {
12691 port = port_str2int(pt, STANDARD_SIP_PORT);
12692 }
12693
12694
12695
12696
12697
12698
12699
12700
12701 hp = ast_gethostbyname(host, &ahp);
12702 if (!hp) {
12703 ast_log(LOG_WARNING, "Invalid host name in Contact: (can't resolve in DNS) : '%s'\n", host);
12704 return -1;
12705 }
12706 sin->sin_family = AF_INET;
12707 memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
12708 sin->sin_port = htons(port);
12709
12710 return 0;
12711 }
12712
12713
12714 static int set_address_from_contact(struct sip_pvt *pvt)
12715 {
12716 if (ast_test_flag(&pvt->flags[0], SIP_NAT_ROUTE)) {
12717
12718
12719
12720 pvt->sa = pvt->recv;
12721 return 0;
12722 }
12723
12724 return __set_address_from_contact(pvt->fullcontact, &pvt->sa, pvt->socket.type == SIP_TRANSPORT_TLS ? 1 : 0);
12725 }
12726
12727
12728 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *peer, struct sip_request *req)
12729 {
12730 char contact[SIPBUFSIZE];
12731 char data[SIPBUFSIZE];
12732 const char *expires = get_header(req, "Expires");
12733 int expire = atoi(expires);
12734 char *curi, *host, *pt, *transport;
12735 int port;
12736 int transport_type;
12737 const char *useragent;
12738 struct hostent *hp;
12739 struct ast_hostent ahp;
12740 struct sockaddr_in oldsin, testsin;
12741 char *firstcuri = NULL;
12742 int start = 0;
12743 int wildcard_found = 0;
12744 int single_binding_found;
12745
12746 ast_copy_string(contact, __get_header(req, "Contact", &start), sizeof(contact));
12747
12748 if (ast_strlen_zero(expires)) {
12749 char *s = strcasestr(contact, ";expires=");
12750 if (s) {
12751 expires = strsep(&s, ";");
12752 if (sscanf(expires + 9, "%30d", &expire) != 1)
12753 expire = default_expiry;
12754 } else {
12755
12756 expire = default_expiry;
12757 }
12758 }
12759
12760 copy_socket_data(&pvt->socket, &req->socket);
12761
12762 do {
12763
12764 curi = contact;
12765 if (strchr(contact, '<') == NULL)
12766 strsep(&curi, ";");
12767 curi = get_in_brackets(contact);
12768 if (!firstcuri) {
12769 firstcuri = ast_strdupa(curi);
12770 }
12771
12772 if (!strcasecmp(curi, "*")) {
12773 wildcard_found = 1;
12774 } else {
12775 single_binding_found = 1;
12776 }
12777
12778 if (wildcard_found && (ast_strlen_zero(expires) || expire != 0 || single_binding_found)) {
12779
12780
12781 return PARSE_REGISTER_FAILED;
12782 }
12783
12784 ast_copy_string(contact, __get_header(req, "Contact", &start), sizeof(contact));
12785 } while (!ast_strlen_zero(contact));
12786 curi = firstcuri;
12787
12788
12789
12790
12791
12792 if (ast_strlen_zero(curi) && ast_strlen_zero(expires)) {
12793
12794 if (peer->expire > -1 && !ast_strlen_zero(peer->fullcontact))
12795 pvt->expiry = ast_sched_when(sched, peer->expire);
12796 return PARSE_REGISTER_QUERY;
12797 } else if (!strcasecmp(curi, "*") || !expire) {
12798
12799 memset(&peer->addr, 0, sizeof(peer->addr));
12800 set_socket_transport(&peer->socket, peer->default_outbound_transport);
12801
12802 AST_SCHED_DEL_UNREF(sched, peer->expire,
12803 unref_peer(peer, "remove register expire ref"));
12804
12805 destroy_association(peer);
12806
12807 register_peer_exten(peer, FALSE);
12808 ast_string_field_set(peer, fullcontact, "");
12809 ast_string_field_set(peer, useragent, "");
12810 peer->sipoptions = 0;
12811 peer->lastms = 0;
12812 peer->portinuri = 0;
12813 pvt->expiry = 0;
12814
12815 ast_verb(3, "Unregistered SIP '%s'\n", peer->name);
12816
12817 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unregistered\r\n", peer->name);
12818 return PARSE_REGISTER_UPDATE;
12819 }
12820
12821
12822 ast_string_field_set(peer, fullcontact, curi);
12823
12824
12825 ast_string_field_build(pvt, our_contact, "<%s>", curi);
12826
12827
12828 if (parse_uri(curi, "sip:,sips:", &curi, NULL, &host, &pt, NULL, &transport)) {
12829 ast_log(LOG_NOTICE, "Not a valid SIP contact (missing sip:) trying to use anyway\n");
12830 }
12831
12832
12833
12834 peer->portinuri = !ast_strlen_zero(pt) ? TRUE : FALSE;
12835
12836
12837 if ((transport_type = get_transport_str2enum(transport))) {
12838
12839
12840
12841
12842 port = port_str2int(pt, (transport_type == SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT);
12843 } else {
12844 port = port_str2int(pt, STANDARD_SIP_PORT);
12845 transport_type = pvt->socket.type;
12846 }
12847
12848
12849
12850
12851 if ((peer->socket.type != transport_type) && (peer->transports & transport_type)) {
12852 set_socket_transport(&peer->socket, transport_type);
12853 }
12854
12855 oldsin = peer->addr;
12856
12857
12858 if (peer->addr.sin_addr.s_addr) {
12859 ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
12860 }
12861
12862 if (!ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE)) {
12863
12864 ast_debug(1, "Store REGISTER's Contact header for call routing.\n");
12865
12866
12867 hp = ast_gethostbyname(host, &ahp);
12868 if (!hp) {
12869 ast_log(LOG_WARNING, "Invalid host '%s'\n", host);
12870 ast_string_field_set(peer, fullcontact, "");
12871 ast_string_field_set(pvt, our_contact, "");
12872 return PARSE_REGISTER_FAILED;
12873 }
12874 peer->addr.sin_family = AF_INET;
12875 memcpy(&peer->addr.sin_addr, hp->h_addr, sizeof(peer->addr.sin_addr));
12876 peer->addr.sin_port = htons(port);
12877 } else {
12878
12879
12880 ast_debug(1, "Store REGISTER's src-IP:port for call routing.\n");
12881 peer->addr = pvt->recv;
12882 }
12883
12884
12885 memcpy(&testsin.sin_addr, &peer->addr.sin_addr, sizeof(testsin.sin_addr));
12886 if (ast_apply_ha(global_contact_ha, &testsin) != AST_SENSE_ALLOW ||
12887 ast_apply_ha(peer->contactha, &testsin) != AST_SENSE_ALLOW) {
12888 ast_log(LOG_WARNING, "Host '%s' disallowed by contact ACL (violating IP %s)\n", host, ast_inet_ntoa(testsin.sin_addr));
12889 ast_string_field_set(peer, fullcontact, "");
12890 ast_string_field_set(pvt, our_contact, "");
12891 return PARSE_REGISTER_DENIED;
12892 }
12893
12894
12895
12896
12897 if ((peer->socket.type == pvt->socket.type) &&
12898 (peer->addr.sin_addr.s_addr == pvt->recv.sin_addr.s_addr) &&
12899 (peer->addr.sin_port == pvt->recv.sin_port)){
12900
12901 copy_socket_data(&peer->socket, &pvt->socket);
12902 }
12903
12904
12905 ao2_t_link(peers_by_ip, peer, "ao2_link into peers_by_ip table");
12906
12907
12908 peer->sipoptions = pvt->sipoptions;
12909
12910 if (!ast_strlen_zero(curi) && ast_strlen_zero(peer->username))
12911 ast_string_field_set(peer, username, curi);
12912
12913 AST_SCHED_DEL_UNREF(sched, peer->expire,
12914 unref_peer(peer, "remove register expire ref"));
12915
12916 if (expire > max_expiry)
12917 expire = max_expiry;
12918 if (expire < min_expiry)
12919 expire = min_expiry;
12920 if (peer->is_realtime && !ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
12921 peer->expire = -1;
12922 } else {
12923 peer->expire = ast_sched_add(sched, (expire + 10) * 1000, expire_register,
12924 ref_peer(peer, "add registration ref"));
12925 if (peer->expire == -1) {
12926 unref_peer(peer, "remote registration ref");
12927 }
12928 }
12929 pvt->expiry = expire;
12930 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);
12931
12932
12933
12934
12935 if (!peer->rt_fromcontact && (peer->socket.type & SIP_TRANSPORT_UDP))
12936 ast_db_put("SIP/Registry", peer->name, data);
12937 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));
12938
12939
12940 if (VERBOSITY_ATLEAST(2) && inaddrcmp(&peer->addr, &oldsin)) {
12941 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));
12942 }
12943 sip_poke_peer(peer, 0);
12944 register_peer_exten(peer, 1);
12945
12946
12947 useragent = get_header(req, "User-Agent");
12948 if (strcasecmp(useragent, peer->useragent)) {
12949 ast_string_field_set(peer, useragent, useragent);
12950 ast_verb(4, "Saved useragent \"%s\" for peer %s\n", peer->useragent, peer->name);
12951 }
12952 return PARSE_REGISTER_UPDATE;
12953 }
12954
12955
12956 static void free_old_route(struct sip_route *route)
12957 {
12958 struct sip_route *next;
12959
12960 while (route) {
12961 next = route->next;
12962 ast_free(route);
12963 route = next;
12964 }
12965 }
12966
12967
12968 static void list_route(struct sip_route *route)
12969 {
12970 if (!route)
12971 ast_verbose("list_route: no route\n");
12972 else {
12973 for (;route; route = route->next)
12974 ast_verbose("list_route: hop: <%s>\n", route->hop);
12975 }
12976 }
12977
12978
12979 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards)
12980 {
12981 struct sip_route *thishop, *head, *tail;
12982 int start = 0;
12983 int len;
12984 const char *rr, *contact, *c;
12985
12986
12987 if (p->route && p->route_persistant) {
12988 ast_debug(1, "build_route: Retaining previous route: <%s>\n", p->route->hop);
12989 return;
12990 }
12991
12992 if (p->route) {
12993 free_old_route(p->route);
12994 p->route = NULL;
12995 }
12996
12997
12998 p->route_persistant = 1;
12999
13000
13001
13002
13003
13004
13005 head = NULL;
13006 tail = head;
13007
13008 for (;;) {
13009
13010 rr = __get_header(req, "Record-Route", &start);
13011 if (*rr == '\0')
13012 break;
13013 for (; (rr = strchr(rr, '<')) ; rr += len) {
13014 ++rr;
13015 len = strcspn(rr, ">") + 1;
13016
13017 if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
13018
13019 ast_copy_string(thishop->hop, rr, len);
13020 ast_debug(2, "build_route: Record-Route hop: <%s>\n", thishop->hop);
13021
13022 if (backwards) {
13023
13024 thishop->next = head;
13025 head = thishop;
13026
13027 if (!tail)
13028 tail = thishop;
13029 } else {
13030 thishop->next = NULL;
13031
13032 if (tail)
13033 tail->next = thishop;
13034 else
13035 head = thishop;
13036 tail = thishop;
13037 }
13038 }
13039 }
13040 }
13041
13042
13043 if (!head || (!ast_strlen_zero(head->hop) && strstr(head->hop, ";lr") == NULL) ) {
13044
13045
13046 contact = get_header(req, "Contact");
13047 if (!ast_strlen_zero(contact)) {
13048 ast_debug(2, "build_route: Contact hop: %s\n", contact);
13049
13050 c = strchr(contact, '<');
13051 if (c) {
13052
13053 ++c;
13054 len = strcspn(c, ">") + 1;
13055 } else {
13056
13057 c = contact;
13058 len = strlen(contact) + 1;
13059 }
13060 if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
13061
13062 ast_copy_string(thishop->hop, c, len);
13063 thishop->next = NULL;
13064
13065 if (tail)
13066 tail->next = thishop;
13067 else
13068 head = thishop;
13069 }
13070 }
13071 }
13072
13073
13074 p->route = head;
13075
13076
13077 if (sip_debug_test_pvt(p))
13078 list_route(p->route);
13079 }
13080
13081
13082
13083
13084
13085
13086
13087 static void set_nonce_randdata(struct sip_pvt *p, int forceupdate)
13088 {
13089 if (p->stalenonce || forceupdate || ast_strlen_zero(p->randdata)) {
13090 ast_string_field_build(p, randdata, "%08lx", ast_random());
13091 p->stalenonce = 0;
13092 }
13093 }
13094
13095 AST_THREADSTORAGE(check_auth_buf);
13096 #define CHECK_AUTH_BUF_INITLEN 256
13097
13098
13099
13100
13101
13102
13103 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
13104 const char *secret, const char *md5secret, int sipmethod,
13105 char *uri, enum xmittype reliable, int ignore)
13106 {
13107 const char *response;
13108 char *reqheader, *respheader;
13109 const char *authtoken;
13110 char a1_hash[256];
13111 char resp_hash[256]="";
13112 char *c;
13113 int wrongnonce = FALSE;
13114 int good_response;
13115 const char *usednonce = p->randdata;
13116 struct ast_str *buf;
13117 int res;
13118
13119
13120 enum keys { K_RESP, K_URI, K_USER, K_NONCE, K_LAST };
13121 struct x {
13122 const char *key;
13123 const char *s;
13124 } *i, keys[] = {
13125 [K_RESP] = { "response=", "" },
13126 [K_URI] = { "uri=", "" },
13127 [K_USER] = { "username=", "" },
13128 [K_NONCE] = { "nonce=", "" },
13129 [K_LAST] = { NULL, NULL}
13130 };
13131
13132
13133 if (ast_strlen_zero(secret) && ast_strlen_zero(md5secret))
13134 return AUTH_SUCCESSFUL;
13135
13136
13137
13138 response = "401 Unauthorized";
13139
13140
13141
13142
13143
13144 auth_headers(WWW_AUTH, &respheader, &reqheader);
13145
13146 authtoken = get_header(req, reqheader);
13147 if (ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
13148
13149
13150 if (!reliable) {
13151
13152
13153 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
13154
13155 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13156 }
13157 return AUTH_CHALLENGE_SENT;
13158 } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
13159
13160 set_nonce_randdata(p, 1);
13161 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
13162
13163 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13164 return AUTH_CHALLENGE_SENT;
13165 }
13166
13167
13168
13169
13170
13171
13172 if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN)))
13173 return AUTH_SECRET_FAILED;
13174
13175
13176 res = ast_str_set(&buf, 0, "%s", authtoken);
13177
13178 if (res == AST_DYNSTR_BUILD_FAILED)
13179 return AUTH_SECRET_FAILED;
13180
13181 c = buf->str;
13182
13183 while(c && *(c = ast_skip_blanks(c)) ) {
13184 for (i = keys; i->key != NULL; i++) {
13185 const char *separator = ",";
13186
13187 if (strncasecmp(c, i->key, strlen(i->key)) != 0)
13188 continue;
13189
13190 c += strlen(i->key);
13191 if (*c == '"') {
13192 c++;
13193 separator = "\"";
13194 }
13195 i->s = c;
13196 strsep(&c, separator);
13197 break;
13198 }
13199 if (i->key == NULL)
13200 strsep(&c, " ,");
13201 }
13202
13203
13204 if (strcmp(username, keys[K_USER].s)) {
13205 ast_log(LOG_WARNING, "username mismatch, have <%s>, digest has <%s>\n",
13206 username, keys[K_USER].s);
13207
13208 return AUTH_USERNAME_MISMATCH;
13209 }
13210
13211
13212
13213 if (strcasecmp(p->randdata, keys[K_NONCE].s) || p->stalenonce) {
13214 wrongnonce = TRUE;
13215 usednonce = keys[K_NONCE].s;
13216 } else {
13217 p->stalenonce = 1;
13218 }
13219
13220 if (!ast_strlen_zero(md5secret))
13221 ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
13222 else {
13223 char a1[256];
13224 snprintf(a1, sizeof(a1), "%s:%s:%s", username, sip_cfg.realm, secret);
13225 ast_md5_hash(a1_hash, a1);
13226 }
13227
13228
13229 {
13230 char a2[256];
13231 char a2_hash[256];
13232 char resp[256];
13233
13234 snprintf(a2, sizeof(a2), "%s:%s", sip_methods[sipmethod].text,
13235 S_OR(keys[K_URI].s, uri));
13236 ast_md5_hash(a2_hash, a2);
13237 snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, usednonce, a2_hash);
13238 ast_md5_hash(resp_hash, resp);
13239 }
13240
13241 good_response = keys[K_RESP].s &&
13242 !strncasecmp(keys[K_RESP].s, resp_hash, strlen(resp_hash));
13243 if (wrongnonce) {
13244 if (good_response) {
13245 if (sipdebug)
13246 ast_log(LOG_NOTICE, "Correct auth, but based on stale nonce received from '%s'\n", get_header(req, "From"));
13247
13248 set_nonce_randdata(p, 0);
13249 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, TRUE);
13250 } else {
13251
13252 if (!req->ignore) {
13253 if (sipdebug)
13254 ast_log(LOG_NOTICE, "Bad authentication received from '%s'\n", get_header(req, "To"));
13255 set_nonce_randdata(p, 1);
13256 } else {
13257 if (sipdebug)
13258 ast_log(LOG_NOTICE, "Duplicate authentication received from '%s'\n", get_header(req, "To"));
13259 }
13260 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
13261 }
13262
13263
13264 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13265 return AUTH_CHALLENGE_SENT;
13266 }
13267 if (good_response) {
13268 append_history(p, "AuthOK", "Auth challenge successful for %s", username);
13269 return AUTH_SUCCESSFUL;
13270 }
13271
13272
13273
13274
13275
13276
13277 return AUTH_SECRET_FAILED;
13278 }
13279
13280
13281 static void sip_peer_hold(struct sip_pvt *p, int hold)
13282 {
13283 struct sip_peer *peer = find_peer(p->peername, NULL, 1, FINDALLDEVICES, FALSE, 0);
13284
13285 if (!peer)
13286 return;
13287
13288
13289 ast_atomic_fetchadd_int(&peer->onHold, (hold ? +1 : -1));
13290
13291
13292 ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
13293 unref_peer(peer, "sip_peer_hold: from find_peer operation");
13294
13295 return;
13296 }
13297
13298
13299 static void mwi_event_cb(const struct ast_event *event, void *userdata)
13300 {
13301 struct sip_peer *peer = userdata;
13302
13303 ao2_lock(peer);
13304 sip_send_mwi_to_peer(peer, event, 0);
13305 ao2_unlock(peer);
13306 }
13307
13308
13309
13310
13311 static int cb_extensionstate(char *context, char* exten, int state, void *data)
13312 {
13313 struct sip_pvt *p = data;
13314
13315 sip_pvt_lock(p);
13316
13317 switch(state) {
13318 case AST_EXTENSION_DEACTIVATED:
13319 case AST_EXTENSION_REMOVED:
13320 if (p->autokillid > -1 && sip_cancel_destroy(p))
13321 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
13322 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13323 ast_verb(2, "Extension state: Watcher for hint %s %s. Notify User %s\n", exten, state == AST_EXTENSION_DEACTIVATED ? "deactivated" : "removed", p->username);
13324 p->stateid = -1;
13325 p->subscribed = NONE;
13326 append_history(p, "Subscribestatus", "%s", state == AST_EXTENSION_REMOVED ? "HintRemoved" : "Deactivated");
13327 break;
13328 default:
13329 p->laststate = state;
13330 break;
13331 }
13332 if (p->subscribed != NONE) {
13333 if (!p->pendinginvite) {
13334 transmit_state_notify(p, state, 1, FALSE);
13335 } else {
13336
13337
13338 ast_set_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
13339 }
13340 }
13341 ast_verb(2, "Extension Changed %s[%s] new state %s for Notify User %s %s\n", exten, context, ast_extension_state2str(state), p->username,
13342 ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE) ? "(queued)" : "");
13343
13344 sip_pvt_unlock(p);
13345
13346 return 0;
13347 }
13348
13349
13350
13351
13352 static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable)
13353 {
13354
13355
13356 const char *response = "407 Proxy Authentication Required";
13357 const char *reqheader = "Proxy-Authorization";
13358 const char *respheader = "Proxy-Authenticate";
13359 const char *authtoken;
13360 struct ast_str *buf;
13361 char *c;
13362
13363
13364 enum keys { K_NONCE, K_LAST };
13365 struct x {
13366 const char *key;
13367 const char *s;
13368 } *i, keys[] = {
13369 [K_NONCE] = { "nonce=", "" },
13370 [K_LAST] = { NULL, NULL}
13371 };
13372
13373 if (sipmethod == SIP_REGISTER || sipmethod == SIP_SUBSCRIBE) {
13374 response = "401 Unauthorized";
13375 reqheader = "Authorization";
13376 respheader = "WWW-Authenticate";
13377 }
13378 authtoken = get_header(req, reqheader);
13379 if (req->ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
13380
13381
13382 transmit_response_with_auth(p, response, req, p->randdata, 0, respheader, 0);
13383
13384 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13385 return;
13386 } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
13387
13388 set_nonce_randdata(p, 1);
13389 transmit_response_with_auth(p, response, req, p->randdata, 0, respheader, 0);
13390
13391 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13392 return;
13393 }
13394
13395 if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN))) {
13396 transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
13397 return;
13398 }
13399
13400
13401 if (ast_str_set(&buf, 0, "%s", authtoken) == AST_DYNSTR_BUILD_FAILED) {
13402 transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
13403 return;
13404 }
13405
13406 c = buf->str;
13407
13408 while (c && *(c = ast_skip_blanks(c))) {
13409 for (i = keys; i->key != NULL; i++) {
13410 const char *separator = ",";
13411
13412 if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
13413 continue;
13414 }
13415
13416 c += strlen(i->key);
13417 if (*c == '"') {
13418 c++;
13419 separator = "\"";
13420 }
13421 i->s = c;
13422 strsep(&c, separator);
13423 break;
13424 }
13425 if (i->key == NULL) {
13426 strsep(&c, " ,");
13427 }
13428 }
13429
13430
13431 if (strcasecmp(p->randdata, keys[K_NONCE].s)) {
13432 if (!req->ignore) {
13433 set_nonce_randdata(p, 1);
13434 }
13435 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
13436
13437
13438 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13439 } else {
13440 transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
13441 }
13442 }
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458 static char *terminate_uri(char *uri)
13459 {
13460 char *t = uri;
13461 while (*t && *t > ' ' && *t != ';')
13462 t++;
13463 *t = '\0';
13464 return uri;
13465 }
13466
13467
13468
13469
13470
13471
13472 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
13473 struct sip_request *req, char *uri)
13474 {
13475 enum check_auth_result res = AUTH_NOT_FOUND;
13476 struct sip_peer *peer;
13477 char tmp[256];
13478 char *name, *c;
13479 char *domain;
13480
13481 terminate_uri(uri);
13482
13483 ast_copy_string(tmp, get_header(req, "To"), sizeof(tmp));
13484 if (sip_cfg.pedanticsipchecking)
13485 ast_uri_decode(tmp);
13486
13487 c = get_in_brackets(tmp);
13488 c = remove_uri_parameters(c);
13489
13490 if (!strncasecmp(c, "sip:", 4)) {
13491 name = c + 4;
13492 } else if (!strncasecmp(c, "sips:", 5)) {
13493 name = c + 5;
13494 } else {
13495 name = c;
13496 ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, ast_inet_ntoa(sin->sin_addr));
13497 }
13498
13499
13500
13501
13502
13503 if ((c = strchr(name, '@'))) {
13504 *c++ = '\0';
13505 domain = c;
13506 if ((c = strchr(domain, ':')))
13507 *c = '\0';
13508 if (!AST_LIST_EMPTY(&domain_list)) {
13509 if (!check_sip_domain(domain, NULL, 0)) {
13510 transmit_response(p, "404 Not found (unknown domain)", &p->initreq);
13511 return AUTH_UNKNOWN_DOMAIN;
13512 }
13513 }
13514 }
13515 c = strchr(name, ';');
13516 if (c)
13517 *c = '\0';
13518
13519 ast_string_field_set(p, exten, name);
13520 build_contact(p);
13521 if (req->ignore) {
13522
13523 const char *expires = get_header(req, "Expires");
13524 int expire = atoi(expires);
13525
13526 if (ast_strlen_zero(expires)) {
13527 if ((expires = strcasestr(get_header(req, "Contact"), ";expires="))) {
13528 expire = atoi(expires + 9);
13529 }
13530 }
13531 if (!ast_strlen_zero(expires) && expire == 0) {
13532 transmit_response_with_date(p, "200 OK", req);
13533 return 0;
13534 }
13535 }
13536 peer = find_peer(name, NULL, TRUE, FINDPEERS, FALSE, 0);
13537 if (!(peer && ast_apply_ha(peer->ha, sin))) {
13538
13539 if (peer) {
13540 unref_peer(peer, "register_verify: unref_peer: from find_peer operation");
13541 peer = NULL;
13542 res = AUTH_ACL_FAILED;
13543 } else
13544 res = AUTH_NOT_FOUND;
13545 }
13546
13547 if (peer) {
13548
13549
13550 if (p->rtp) {
13551 ast_rtp_codec_setpref(p->rtp, &peer->prefs);
13552 p->autoframing = peer->autoframing;
13553 }
13554 if (!peer->host_dynamic) {
13555 ast_log(LOG_ERROR, "Peer '%s' is trying to register, but not configured as host=dynamic\n", peer->name);
13556 res = AUTH_PEER_NOT_DYNAMIC;
13557 } else {
13558 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_NAT);
13559 if (ast_test_flag(&p->flags[1], SIP_PAGE2_REGISTERTRYING))
13560 transmit_response(p, "100 Trying", req);
13561 if (!(res = check_auth(p, req, peer->name, peer->secret, peer->md5secret, SIP_REGISTER, uri, XMIT_UNRELIABLE, req->ignore))) {
13562 if (sip_cancel_destroy(p))
13563 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
13564
13565 if (check_request_transport(peer, req)) {
13566 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
13567 transmit_response_with_date(p, "403 Forbidden", req);
13568 res = AUTH_BAD_TRANSPORT;
13569 } else {
13570
13571
13572
13573 switch (parse_register_contact(p, peer, req)) {
13574 case PARSE_REGISTER_DENIED:
13575 ast_log(LOG_WARNING, "Registration denied because of contact ACL\n");
13576 transmit_response_with_date(p, "603 Denied", req);
13577 peer->lastmsgssent = -1;
13578 res = 0;
13579 break;
13580 case PARSE_REGISTER_FAILED:
13581 ast_log(LOG_WARNING, "Failed to parse contact info\n");
13582 transmit_response_with_date(p, "400 Bad Request", req);
13583 peer->lastmsgssent = -1;
13584 res = 0;
13585 break;
13586 case PARSE_REGISTER_QUERY:
13587 ast_string_field_set(p, fullcontact, peer->fullcontact);
13588 transmit_response_with_date(p, "200 OK", req);
13589 peer->lastmsgssent = -1;
13590 res = 0;
13591 break;
13592 case PARSE_REGISTER_UPDATE:
13593 ast_string_field_set(p, fullcontact, peer->fullcontact);
13594 update_peer(peer, p->expiry);
13595
13596 transmit_response_with_date(p, "200 OK", req);
13597 if (!ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY))
13598 peer->lastmsgssent = -1;
13599 res = 0;
13600 break;
13601 }
13602 }
13603
13604 }
13605 }
13606 }
13607 if (!peer && sip_cfg.autocreatepeer) {
13608
13609 peer = temp_peer(name);
13610 if (peer) {
13611 ao2_t_link(peers, peer, "link peer into peer table");
13612 if (peer->addr.sin_addr.s_addr) {
13613 ao2_t_link(peers_by_ip, peer, "link peer into peers-by-ip table");
13614 }
13615
13616 if (sip_cancel_destroy(p))
13617 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
13618 switch (parse_register_contact(p, peer, req)) {
13619 case PARSE_REGISTER_DENIED:
13620 ast_log(LOG_WARNING, "Registration denied because of contact ACL\n");
13621 transmit_response_with_date(p, "403 Forbidden (ACL)", req);
13622 peer->lastmsgssent = -1;
13623 res = 0;
13624 break;
13625 case PARSE_REGISTER_FAILED:
13626 ast_log(LOG_WARNING, "Failed to parse contact info\n");
13627 transmit_response_with_date(p, "400 Bad Request", req);
13628 peer->lastmsgssent = -1;
13629 res = 0;
13630 break;
13631 case PARSE_REGISTER_QUERY:
13632 ast_string_field_set(p, fullcontact, peer->fullcontact);
13633 transmit_response_with_date(p, "200 OK", req);
13634 peer->lastmsgssent = -1;
13635 res = 0;
13636 break;
13637 case PARSE_REGISTER_UPDATE:
13638 ast_string_field_set(p, fullcontact, peer->fullcontact);
13639
13640 transmit_response_with_date(p, "200 OK", req);
13641 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));
13642 peer->lastmsgssent = -1;
13643 res = 0;
13644 break;
13645 }
13646 }
13647 }
13648 if (!peer && sip_cfg.alwaysauthreject) {
13649
13650
13651
13652 transmit_response(p, "100 Trying", req);
13653
13654 sched_yield();
13655 }
13656 if (!res) {
13657 ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
13658 }
13659 if (res < 0) {
13660 switch (res) {
13661 case AUTH_SECRET_FAILED:
13662
13663 transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
13664 if (global_authfailureevents)
13665 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",
13666 name, ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
13667 break;
13668 case AUTH_USERNAME_MISMATCH:
13669
13670
13671
13672
13673 case AUTH_NOT_FOUND:
13674 case AUTH_PEER_NOT_DYNAMIC:
13675 case AUTH_ACL_FAILED:
13676 if (sip_cfg.alwaysauthreject) {
13677 transmit_fake_auth_response(p, SIP_REGISTER, &p->initreq, XMIT_UNRELIABLE);
13678 if (global_authfailureevents) {
13679 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",
13680 name, res == AUTH_PEER_NOT_DYNAMIC ? "AUTH_PEER_NOT_DYNAMIC" : "URI_NOT_FOUND",
13681 ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
13682 }
13683 } else {
13684
13685 if (res == AUTH_PEER_NOT_DYNAMIC) {
13686 transmit_response(p, "403 Forbidden", &p->initreq);
13687 if (global_authfailureevents) {
13688 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
13689 "ChannelType: SIP\r\n"
13690 "Peer: SIP/%s\r\n"
13691 "PeerStatus: Rejected\r\n"
13692 "Cause: AUTH_PEER_NOT_DYNAMIC\r\n"
13693 "Address: %s\r\n"
13694 "Port: %d\r\n",
13695 name, ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
13696 }
13697 } else {
13698 transmit_response(p, "404 Not found", &p->initreq);
13699 if (global_authfailureevents) {
13700 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
13701 "ChannelType: SIP\r\n"
13702 "Peer: SIP/%s\r\n"
13703 "PeerStatus: Rejected\r\n"
13704 "Cause: %s\r\n"
13705 "Address: %s\r\n"
13706 "Port: %d\r\n",
13707 name,
13708 (res == AUTH_USERNAME_MISMATCH) ? "AUTH_USERNAME_MISMATCH" : "URI_NOT_FOUND",
13709 ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
13710 }
13711 }
13712 }
13713 break;
13714 case AUTH_BAD_TRANSPORT:
13715 default:
13716 break;
13717 }
13718 }
13719 if (peer)
13720 unref_peer(peer, "register_verify: unref_peer: tossing stack peer pointer at end of func");
13721
13722 return res;
13723 }
13724
13725
13726 static void sip_set_redirstr(struct sip_pvt *p, char *reason) {
13727
13728 if (!strcmp(reason, "unknown")) {
13729 ast_string_field_set(p, redircause, "UNKNOWN");
13730 } else if (!strcmp(reason, "user-busy")) {
13731 ast_string_field_set(p, redircause, "BUSY");
13732 } else if (!strcmp(reason, "no-answer")) {
13733 ast_string_field_set(p, redircause, "NOANSWER");
13734 } else if (!strcmp(reason, "unavailable")) {
13735 ast_string_field_set(p, redircause, "UNREACHABLE");
13736 } else if (!strcmp(reason, "unconditional")) {
13737 ast_string_field_set(p, redircause, "UNCONDITIONAL");
13738 } else if (!strcmp(reason, "time-of-day")) {
13739 ast_string_field_set(p, redircause, "UNKNOWN");
13740 } else if (!strcmp(reason, "do-not-disturb")) {
13741 ast_string_field_set(p, redircause, "UNKNOWN");
13742 } else if (!strcmp(reason, "deflection")) {
13743 ast_string_field_set(p, redircause, "UNKNOWN");
13744 } else if (!strcmp(reason, "follow-me")) {
13745 ast_string_field_set(p, redircause, "UNKNOWN");
13746 } else if (!strcmp(reason, "out-of-service")) {
13747 ast_string_field_set(p, redircause, "UNREACHABLE");
13748 } else if (!strcmp(reason, "away")) {
13749 ast_string_field_set(p, redircause, "UNREACHABLE");
13750 } else {
13751 ast_string_field_set(p, redircause, "UNKNOWN");
13752 }
13753 }
13754
13755
13756 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq)
13757 {
13758 char tmp[256], *exten, *rexten, *rdomain;
13759 char *params, *reason = NULL;
13760 struct sip_request *req;
13761
13762 req = oreq ? oreq : &p->initreq;
13763
13764 ast_copy_string(tmp, get_header(req, "Diversion"), sizeof(tmp));
13765 if (ast_strlen_zero(tmp))
13766 return 0;
13767
13768
13769
13770
13771 params = strchr(tmp, ';');
13772
13773 exten = get_in_brackets(tmp);
13774 if (!strncasecmp(exten, "sip:", 4)) {
13775 exten += 4;
13776 } else if (!strncasecmp(exten, "sips:", 5)) {
13777 exten += 5;
13778 } else {
13779 ast_log(LOG_WARNING, "Huh? Not an RDNIS SIP header (%s)?\n", exten);
13780 return -1;
13781 }
13782
13783
13784 if (params) {
13785 *params = '\0';
13786 params++;
13787 while (*params == ';' || *params == ' ')
13788 params++;
13789
13790 if ((reason = strcasestr(params, "reason="))) {
13791 reason+=7;
13792
13793 if (*reason == '"')
13794 ast_strip_quoted(reason, "\"", "\"");
13795 if (!ast_strlen_zero(reason)) {
13796 sip_set_redirstr(p, reason);
13797 if (p->owner) {
13798 pbx_builtin_setvar_helper(p->owner, "__PRIREDIRECTREASON", p->redircause);
13799 pbx_builtin_setvar_helper(p->owner, "__SIPREDIRECTREASON", reason);
13800 }
13801 }
13802 }
13803 }
13804
13805 rdomain = exten;
13806 rexten = strsep(&rdomain, "@");
13807 if (p->owner)
13808 pbx_builtin_setvar_helper(p->owner, "__SIPRDNISDOMAIN", rdomain);
13809
13810 if (sip_debug_test_pvt(p))
13811 ast_verbose("RDNIS for this call is is %s (reason %s)\n", exten, reason ? reason : "");
13812
13813 ast_string_field_set(p, rdnis, rexten);
13814
13815 return 0;
13816 }
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830 static int get_destination(struct sip_pvt *p, struct sip_request *oreq)
13831 {
13832 char tmp[256] = "", *uri, *a;
13833 char tmpf[256] = "", *from = NULL;
13834 struct sip_request *req;
13835 char *colon;
13836 char *decoded_uri;
13837
13838 req = oreq;
13839 if (!req)
13840 req = &p->initreq;
13841
13842
13843 if (req->rlPart2)
13844 ast_copy_string(tmp, REQ_OFFSET_TO_STR(req, rlPart2), sizeof(tmp));
13845
13846 if (sip_cfg.pedanticsipchecking)
13847 ast_uri_decode(tmp);
13848
13849 uri = get_in_brackets(tmp);
13850
13851 if (!strncasecmp(uri, "sip:", 4)) {
13852 uri += 4;
13853 } else if (!strncasecmp(uri, "sips:", 5)) {
13854 uri += 5;
13855 } else {
13856 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", uri);
13857 return -1;
13858 }
13859
13860
13861
13862
13863
13864 ast_copy_string(tmpf, get_header(req, "From"), sizeof(tmpf));
13865 if (!ast_strlen_zero(tmpf)) {
13866 if (sip_cfg.pedanticsipchecking)
13867 ast_uri_decode(tmpf);
13868 from = get_in_brackets(tmpf);
13869 }
13870
13871 if (!ast_strlen_zero(from)) {
13872 if (!strncasecmp(from, "sip:", 4)) {
13873 from += 4;
13874 } else if (!strncasecmp(from, "sips:", 5)) {
13875 from += 5;
13876 } else {
13877 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", from);
13878 return -1;
13879 }
13880 if ((a = strchr(from, '@')))
13881 *a++ = '\0';
13882 else
13883 a = from;
13884 from = strsep(&from, ";");
13885 a = strsep(&a, ";");
13886 ast_string_field_set(p, fromdomain, a);
13887 }
13888
13889
13890
13891
13892 if ((a = strchr(uri, '@'))) {
13893 *a++ = '\0';
13894 } else {
13895 a = uri;
13896 uri = "s";
13897 }
13898 colon = strchr(a, ':');
13899 if (colon)
13900 *colon = '\0';
13901
13902 uri = strsep(&uri, ";");
13903 a = strsep(&a, ";");
13904
13905 ast_string_field_set(p, domain, a);
13906
13907 if (!AST_LIST_EMPTY(&domain_list)) {
13908 char domain_context[AST_MAX_EXTENSION];
13909
13910 domain_context[0] = '\0';
13911 if (!check_sip_domain(p->domain, domain_context, sizeof(domain_context))) {
13912 if (!sip_cfg.allow_external_domains && (req->method == SIP_INVITE || req->method == SIP_REFER)) {
13913 ast_debug(1, "Got SIP %s to non-local domain '%s'; refusing request.\n", sip_methods[req->method].text, p->domain);
13914 return -2;
13915 }
13916 }
13917
13918
13919 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_HAVEPEERCONTEXT) && !ast_strlen_zero(domain_context))
13920 ast_string_field_set(p, context, domain_context);
13921 }
13922
13923
13924 if (req->method == SIP_SUBSCRIBE && !ast_strlen_zero(p->subscribecontext))
13925 ast_string_field_set(p, context, p->subscribecontext);
13926
13927 if (sip_debug_test_pvt(p))
13928 ast_verbose("Looking for %s in %s (domain %s)\n", uri, p->context, p->domain);
13929
13930
13931
13932 decoded_uri = ast_strdupa(uri);
13933 ast_uri_decode(decoded_uri);
13934
13935
13936 if (req->method == SIP_SUBSCRIBE) {
13937 char hint[AST_MAX_EXTENSION];
13938 int which = 0;
13939 if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, uri) ||
13940 (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, decoded_uri) && (which = 1))) {
13941 if (!oreq) {
13942 ast_string_field_set(p, exten, which ? decoded_uri : uri);
13943 }
13944 return 0;
13945 } else {
13946 return -1;
13947 }
13948 } else {
13949 int which = 0;
13950
13951
13952
13953 if (ast_exists_extension(NULL, p->context, uri, 1, S_OR(p->cid_num, from)) ||
13954 (ast_exists_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from)) && (which = 1)) ||
13955 !strcmp(decoded_uri, ast_pickup_ext())) {
13956 if (!oreq) {
13957 ast_string_field_set(p, exten, which ? decoded_uri : uri);
13958 }
13959 return 0;
13960 }
13961 }
13962
13963
13964 if((ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP) &&
13965 ast_canmatch_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from))) ||
13966 !strncmp(decoded_uri, ast_pickup_ext(), strlen(decoded_uri))) {
13967 return 1;
13968 }
13969
13970 return -1;
13971 }
13972
13973
13974
13975
13976 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag)
13977 {
13978 struct sip_pvt *sip_pvt_ptr;
13979 struct sip_pvt tmp_dialog = {
13980 .callid = callid,
13981 };
13982
13983 if (totag)
13984 ast_debug(4, "Looking for callid %s (fromtag %s totag %s)\n", callid, fromtag ? fromtag : "<no fromtag>", totag ? totag : "<no totag>");
13985
13986
13987
13988 sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find of dialog in dialogs table");
13989 if (sip_pvt_ptr) {
13990
13991 sip_pvt_lock(sip_pvt_ptr);
13992 if (sip_cfg.pedanticsipchecking) {
13993 unsigned char frommismatch = 0, tomismatch = 0;
13994
13995 if (ast_strlen_zero(fromtag)) {
13996 sip_pvt_unlock(sip_pvt_ptr);
13997 ast_debug(4, "Matched %s call for callid=%s - no from tag specified, pedantic check fails\n",
13998 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
13999 return NULL;
14000 }
14001
14002 if (ast_strlen_zero(totag)) {
14003 sip_pvt_unlock(sip_pvt_ptr);
14004 ast_debug(4, "Matched %s call for callid=%s - no to tag specified, pedantic check fails\n",
14005 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
14006 return NULL;
14007 }
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022 frommismatch = !!strcmp(fromtag, sip_pvt_ptr->theirtag);
14023 tomismatch = !!strcmp(totag, sip_pvt_ptr->tag);
14024
14025 if (frommismatch || tomismatch) {
14026 sip_pvt_unlock(sip_pvt_ptr);
14027 if (frommismatch) {
14028 ast_debug(4, "Matched %s call for callid=%s - pedantic from tag check fails; their tag is %s our tag is %s\n",
14029 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid,
14030 fromtag, sip_pvt_ptr->theirtag);
14031 }
14032 if (tomismatch) {
14033 ast_debug(4, "Matched %s call for callid=%s - pedantic to tag check fails; their tag is %s our tag is %s\n",
14034 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid,
14035 totag, sip_pvt_ptr->tag);
14036 }
14037 return NULL;
14038 }
14039 }
14040
14041 if (totag)
14042 ast_debug(4, "Matched %s call - their tag is %s Our tag is %s\n",
14043 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING",
14044 sip_pvt_ptr->theirtag, sip_pvt_ptr->tag);
14045
14046
14047 while (sip_pvt_ptr->owner && ast_channel_trylock(sip_pvt_ptr->owner)) {
14048 sip_pvt_unlock(sip_pvt_ptr);
14049 usleep(1);
14050 sip_pvt_lock(sip_pvt_ptr);
14051 }
14052 }
14053
14054 return sip_pvt_ptr;
14055 }
14056
14057
14058
14059
14060
14061
14062
14063
14064 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req)
14065 {
14066
14067 const char *p_referred_by = NULL;
14068 char *h_refer_to = NULL;
14069 char *h_referred_by = NULL;
14070 char *refer_to;
14071 const char *p_refer_to;
14072 char *referred_by_uri = NULL;
14073 char *ptr;
14074 struct sip_request *req = NULL;
14075 const char *transfer_context = NULL;
14076 struct sip_refer *referdata;
14077
14078
14079 req = outgoing_req;
14080 referdata = transferer->refer;
14081
14082 if (!req)
14083 req = &transferer->initreq;
14084
14085 p_refer_to = get_header(req, "Refer-To");
14086 if (ast_strlen_zero(p_refer_to)) {
14087 ast_log(LOG_WARNING, "Refer-To Header missing. Skipping transfer.\n");
14088 return -2;
14089 }
14090 h_refer_to = ast_strdupa(p_refer_to);
14091 refer_to = get_in_brackets(h_refer_to);
14092 if (sip_cfg.pedanticsipchecking)
14093 ast_uri_decode(refer_to);
14094
14095 if (!strncasecmp(refer_to, "sip:", 4)) {
14096 refer_to += 4;
14097 } else if (!strncasecmp(refer_to, "sips:", 5)) {
14098 refer_to += 5;
14099 } else {
14100 ast_log(LOG_WARNING, "Can't transfer to non-sip: URI. (Refer-to: %s)?\n", refer_to);
14101 return -3;
14102 }
14103
14104
14105 p_referred_by = get_header(req, "Referred-By");
14106
14107
14108 if (transferer->owner) {
14109 struct ast_channel *peer = ast_bridged_channel(transferer->owner);
14110 if (peer) {
14111 pbx_builtin_setvar_helper(peer, "SIPREFERRINGCONTEXT", transferer->context);
14112 pbx_builtin_setvar_helper(peer, "SIPREFERREDBYHDR", p_referred_by);
14113 }
14114 }
14115
14116 if (!ast_strlen_zero(p_referred_by)) {
14117 char *lessthan;
14118 h_referred_by = ast_strdupa(p_referred_by);
14119 if (sip_cfg.pedanticsipchecking)
14120 ast_uri_decode(h_referred_by);
14121
14122
14123 ast_copy_string(referdata->referred_by_name, h_referred_by, sizeof(referdata->referred_by_name));
14124 if ((lessthan = strchr(referdata->referred_by_name, '<'))) {
14125 *(lessthan - 1) = '\0';
14126 }
14127
14128 referred_by_uri = get_in_brackets(h_referred_by);
14129 if (!strncasecmp(referred_by_uri, "sip:", 4)) {
14130 referred_by_uri += 4;
14131 } else if (!strncasecmp(referred_by_uri, "sips:", 5)) {
14132 referred_by_uri += 5;
14133 } else {
14134 ast_log(LOG_WARNING, "Huh? Not a sip: header (Referred-by: %s). Skipping.\n", referred_by_uri);
14135 referred_by_uri = NULL;
14136 }
14137 }
14138
14139
14140 if ((ptr = strcasestr(refer_to, "replaces="))) {
14141 char *to = NULL, *from = NULL;
14142
14143
14144 referdata->attendedtransfer = 1;
14145 ast_copy_string(referdata->replaces_callid, ptr+9, sizeof(referdata->replaces_callid));
14146 ast_uri_decode(referdata->replaces_callid);
14147 if ((ptr = strchr(referdata->replaces_callid, ';'))) {
14148 *ptr++ = '\0';
14149 }
14150
14151 if (ptr) {
14152
14153 to = strcasestr(ptr, "to-tag=");
14154 from = strcasestr(ptr, "from-tag=");
14155 }
14156
14157
14158 if (to) {
14159 ptr = to + 7;
14160 if ((to = strchr(ptr, '&')))
14161 *to = '\0';
14162 if ((to = strchr(ptr, ';')))
14163 *to = '\0';
14164 ast_copy_string(referdata->replaces_callid_totag, ptr, sizeof(referdata->replaces_callid_totag));
14165 }
14166
14167 if (from) {
14168 ptr = from + 9;
14169 if ((to = strchr(ptr, '&')))
14170 *to = '\0';
14171 if ((to = strchr(ptr, ';')))
14172 *to = '\0';
14173 ast_copy_string(referdata->replaces_callid_fromtag, ptr, sizeof(referdata->replaces_callid_fromtag));
14174 }
14175
14176 if (!strcmp(referdata->replaces_callid, transferer->callid) &&
14177 (!sip_cfg.pedanticsipchecking ||
14178 (!strcmp(referdata->replaces_callid_fromtag, transferer->theirtag) &&
14179 !strcmp(referdata->replaces_callid_totag, transferer->tag)))) {
14180 ast_log(LOG_WARNING, "Got an attempt to replace own Call-ID on %s\n", transferer->callid);
14181 return -4;
14182 }
14183
14184 if (!sip_cfg.pedanticsipchecking)
14185 ast_debug(2, "Attended transfer: Will use Replace-Call-ID : %s (No check of from/to tags)\n", referdata->replaces_callid );
14186 else
14187 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>" );
14188 }
14189
14190 if ((ptr = strchr(refer_to, '@'))) {
14191 char *urioption = NULL, *domain;
14192 *ptr++ = '\0';
14193
14194 if ((urioption = strchr(ptr, ';')))
14195 *urioption++ = '\0';
14196
14197 domain = ptr;
14198 if ((ptr = strchr(domain, ':')))
14199 *ptr = '\0';
14200
14201
14202 ast_copy_string(referdata->refer_to_domain, domain, sizeof(referdata->refer_to_domain));
14203 if (urioption)
14204 ast_copy_string(referdata->refer_to_urioption, urioption, sizeof(referdata->refer_to_urioption));
14205 }
14206
14207 if ((ptr = strchr(refer_to, ';')))
14208 *ptr = '\0';
14209 ast_copy_string(referdata->refer_to, refer_to, sizeof(referdata->refer_to));
14210
14211 if (referred_by_uri) {
14212 if ((ptr = strchr(referred_by_uri, ';')))
14213 *ptr = '\0';
14214 ast_copy_string(referdata->referred_by, referred_by_uri, sizeof(referdata->referred_by));
14215 } else {
14216 referdata->referred_by[0] = '\0';
14217 }
14218
14219
14220 if (transferer->owner)
14221 transfer_context = pbx_builtin_getvar_helper(transferer->owner, "TRANSFER_CONTEXT");
14222
14223
14224 if (ast_strlen_zero(transfer_context)) {
14225 transfer_context = S_OR(transferer->owner->macrocontext,
14226 S_OR(transferer->context, sip_cfg.default_context));
14227 }
14228
14229 ast_copy_string(referdata->refer_to_context, transfer_context, sizeof(referdata->refer_to_context));
14230
14231
14232 if (referdata->attendedtransfer || ast_exists_extension(NULL, transfer_context, refer_to, 1, NULL) ) {
14233 if (sip_debug_test_pvt(transferer)) {
14234 ast_verbose("SIP transfer to extension %s@%s by %s\n", refer_to, transfer_context, referred_by_uri);
14235 }
14236
14237 return 0;
14238 }
14239 if (sip_debug_test_pvt(transferer))
14240 ast_verbose("Failed SIP Transfer to non-existing extension %s in context %s\n n", refer_to, transfer_context);
14241
14242
14243 return -1;
14244 }
14245
14246
14247
14248
14249
14250 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq)
14251 {
14252 char tmp[256] = "", *c, *a;
14253 struct sip_request *req = oreq ? oreq : &p->initreq;
14254 struct sip_refer *referdata = NULL;
14255 const char *transfer_context = NULL;
14256
14257 if (!p->refer && !sip_refer_allocate(p))
14258 return -1;
14259
14260 referdata = p->refer;
14261
14262 ast_copy_string(tmp, get_header(req, "Also"), sizeof(tmp));
14263 c = get_in_brackets(tmp);
14264
14265 if (sip_cfg.pedanticsipchecking)
14266 ast_uri_decode(c);
14267
14268 if (!strncasecmp(c, "sip:", 4)) {
14269 c += 4;
14270 } else if (!strncasecmp(c, "sips:", 5)) {
14271 c += 5;
14272 } else {
14273 ast_log(LOG_WARNING, "Huh? Not a SIP header in Also: transfer (%s)?\n", c);
14274 return -1;
14275 }
14276
14277 if ((a = strchr(c, ';')))
14278 *a = '\0';
14279
14280 if ((a = strchr(c, '@'))) {
14281 *a++ = '\0';
14282 ast_copy_string(referdata->refer_to_domain, a, sizeof(referdata->refer_to_domain));
14283 }
14284
14285 if (sip_debug_test_pvt(p))
14286 ast_verbose("Looking for %s in %s\n", c, p->context);
14287
14288 if (p->owner)
14289 transfer_context = pbx_builtin_getvar_helper(p->owner, "TRANSFER_CONTEXT");
14290
14291
14292 if (ast_strlen_zero(transfer_context)) {
14293 transfer_context = S_OR(p->owner->macrocontext,
14294 S_OR(p->context, sip_cfg.default_context));
14295 }
14296 if (ast_exists_extension(NULL, transfer_context, c, 1, NULL)) {
14297
14298 ast_debug(1, "SIP Bye-also transfer to Extension %s@%s \n", c, transfer_context);
14299 ast_copy_string(referdata->refer_to, c, sizeof(referdata->refer_to));
14300 ast_copy_string(referdata->referred_by, "", sizeof(referdata->referred_by));
14301 ast_copy_string(referdata->refer_contact, "", sizeof(referdata->refer_contact));
14302 referdata->refer_call = dialog_unref(referdata->refer_call, "unreffing referdata->refer_call");
14303
14304 ast_string_field_set(p, context, transfer_context);
14305 return 0;
14306 } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
14307 return 1;
14308 }
14309
14310 return -1;
14311 }
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323 static attribute_unused void check_via_response(struct sip_pvt *p, struct sip_request *req)
14324 {
14325 char via[256];
14326 char *cur, *opts;
14327
14328 ast_copy_string(via, get_header(req, "Via"), sizeof(via));
14329
14330
14331 opts = strchr(via, ',');
14332 if (opts)
14333 *opts = '\0';
14334
14335
14336 opts = strchr(via, ';');
14337 if (!opts)
14338 return;
14339 *opts++ = '\0';
14340 while ( (cur = strsep(&opts, ";")) ) {
14341 if (!strncmp(cur, "rport=", 6)) {
14342 int port = strtol(cur+6, NULL, 10);
14343
14344 p->ourip.sin_port = ntohs(port);
14345 } else if (!strncmp(cur, "received=", 9)) {
14346 if (ast_parse_arg(cur+9, PARSE_INADDR, &p->ourip))
14347 ;
14348 }
14349 }
14350 }
14351
14352
14353 static void check_via(struct sip_pvt *p, struct sip_request *req)
14354 {
14355 char via[512];
14356 char *c, *pt, *maddr;
14357 struct hostent *hp;
14358 struct ast_hostent ahp;
14359
14360 ast_copy_string(via, get_header(req, "Via"), sizeof(via));
14361
14362
14363 c = strchr(via, ',');
14364 if (c)
14365 *c = '\0';
14366
14367
14368 c = strstr(via, ";rport");
14369 if (c && (c[6] != '='))
14370 ast_set_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT);
14371
14372
14373 maddr = strstr(via, "maddr=");
14374 if (maddr) {
14375 maddr += 6;
14376 c = maddr + strspn(maddr, "0123456789.");
14377 *c = '\0';
14378 }
14379
14380 c = strchr(via, ';');
14381 if (c)
14382 *c = '\0';
14383
14384 c = strchr(via, ' ');
14385 if (c) {
14386 *c = '\0';
14387 c = ast_skip_blanks(c+1);
14388 if (strcasecmp(via, "SIP/2.0/UDP") && strcasecmp(via, "SIP/2.0/TCP") && strcasecmp(via, "SIP/2.0/TLS")) {
14389 ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
14390 return;
14391 }
14392 pt = strchr(c, ':');
14393 if (pt)
14394 *pt++ = '\0';
14395
14396 if (maddr)
14397 c = maddr;
14398 hp = ast_gethostbyname(c, &ahp);
14399 if (!hp) {
14400 ast_log(LOG_WARNING, "'%s' is not a valid host\n", c);
14401 return;
14402 }
14403 memset(&p->sa, 0, sizeof(p->sa));
14404 p->sa.sin_family = AF_INET;
14405 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
14406 p->sa.sin_port = htons(port_str2int(pt, STANDARD_SIP_PORT));
14407
14408 if (sip_debug_test_pvt(p)) {
14409 const struct sockaddr_in *dst = sip_real_dst(p);
14410 ast_verbose("Sending to %s : %d (%s)\n", ast_inet_ntoa(dst->sin_addr), ntohs(dst->sin_port), sip_nat_mode(p));
14411 }
14412 }
14413 }
14414
14415
14416 static char *get_calleridname(const char *input, char *output, size_t outputsize)
14417 {
14418 const char *end = strchr(input, '<');
14419 const char *tmp = strchr(input, '"');
14420 int bytes = 0;
14421 int maxbytes = outputsize - 1;
14422
14423 if (!end || end == input)
14424 return NULL;
14425
14426 end--;
14427
14428 if (tmp && tmp <= end) {
14429
14430
14431
14432 end = strchr(tmp+1, '"');
14433 if (!end)
14434 return NULL;
14435 bytes = (int) (end - tmp);
14436
14437 if (bytes > maxbytes)
14438 bytes = maxbytes;
14439 ast_copy_string(output, tmp + 1, bytes);
14440 } else {
14441
14442
14443 input = ast_skip_blanks(input);
14444
14445 while(*end && *end < 33 && end > input)
14446 end--;
14447 if (end >= input) {
14448 bytes = (int) (end - input) + 2;
14449
14450 if (bytes > maxbytes)
14451 bytes = maxbytes;
14452 ast_copy_string(output, input, bytes);
14453 } else
14454 return NULL;
14455 }
14456 return output;
14457 }
14458
14459
14460
14461
14462
14463 static int get_rpid_num(const char *input, char *output, int maxlen)
14464 {
14465 char *start;
14466 char *end;
14467
14468 start = strchr(input, ':');
14469 if (!start) {
14470 output[0] = '\0';
14471 return 0;
14472 }
14473 start++;
14474
14475
14476 ast_copy_string(output, start, maxlen);
14477 output[maxlen-1] = '\0';
14478
14479 end = strchr(output, '@');
14480 if (end)
14481 *end = '\0';
14482 else
14483 output[0] = '\0';
14484 if (strstr(input, "privacy=full") || strstr(input, "privacy=uri"))
14485 return AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
14486
14487 return 0;
14488 }
14489
14490
14491
14492 static void replace_cid(struct sip_pvt *p, const char *rpid_num, const char *calleridname)
14493 {
14494
14495 if (!ast_strlen_zero(rpid_num) && ast_test_flag(&p->flags[0], SIP_TRUSTRPID)) {
14496 char *tmp = ast_strdupa(rpid_num);
14497 if (!ast_strlen_zero(calleridname))
14498 ast_string_field_set(p, cid_name, calleridname);
14499 if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
14500 ast_shrink_phone_number(tmp);
14501 ast_string_field_set(p, cid_num, tmp);
14502 }
14503 }
14504
14505
14506 static enum check_auth_result check_peer_ok(struct sip_pvt *p, char *of,
14507 struct sip_request *req, int sipmethod, struct sockaddr_in *sin,
14508 struct sip_peer **authpeer,
14509 enum xmittype reliable,
14510 char *rpid_num, char *calleridname, char *uri2)
14511 {
14512 enum check_auth_result res;
14513 int debug=sip_debug_test_addr(sin);
14514 struct sip_peer *peer;
14515
14516 if (sipmethod == SIP_SUBSCRIBE) {
14517
14518
14519
14520 peer = find_peer(of, NULL, TRUE, FINDALLDEVICES, FALSE, 0);
14521 } else {
14522
14523 peer = find_peer(of, NULL, TRUE, FINDUSERS, FALSE, 0);
14524
14525
14526 if (!peer) {
14527 peer = find_peer(NULL, &p->recv, TRUE, FINDPEERS, FALSE, p->socket.type);
14528 }
14529 }
14530
14531 if (!peer) {
14532 if (debug)
14533 ast_verbose("No matching peer for '%s' from '%s:%d'\n",
14534 of, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
14535 return AUTH_DONT_KNOW;
14536 }
14537 if (!ast_apply_ha(peer->ha, sin)) {
14538 ast_debug(2, "Found peer '%s' for '%s', but fails host access\n", peer->name, of);
14539 unref_peer(peer, "unref_peer: check_peer_ok: from find_peer call, early return of AUTH_ACL_FAILED");
14540 return AUTH_ACL_FAILED;
14541 }
14542 if (debug)
14543 ast_verbose("Found peer '%s' for '%s' from %s:%d\n",
14544 peer->name, of, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
14545
14546
14547
14548 if (p->rtp) {
14549 ast_rtp_codec_setpref(p->rtp, &peer->prefs);
14550 p->autoframing = peer->autoframing;
14551 }
14552
14553
14554 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
14555 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
14556
14557 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) && p->udptl) {
14558 p->t38_maxdatagram = peer->t38_maxdatagram;
14559 set_t38_capabilities(p);
14560 }
14561
14562
14563
14564 if (p->sipoptions)
14565 peer->sipoptions = p->sipoptions;
14566
14567 replace_cid(p, rpid_num, calleridname);
14568 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT_ROUTE));
14569
14570 ast_string_field_set(p, peersecret, peer->secret);
14571 ast_string_field_set(p, peermd5secret, peer->md5secret);
14572 ast_string_field_set(p, subscribecontext, peer->subscribecontext);
14573 ast_string_field_set(p, mohinterpret, peer->mohinterpret);
14574 ast_string_field_set(p, mohsuggest, peer->mohsuggest);
14575 ast_string_field_set(p, parkinglot, peer->parkinglot);
14576 if (peer->callingpres)
14577 p->callingpres = peer->callingpres;
14578 if (peer->maxms && peer->lastms)
14579 p->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
14580 else
14581 p->timer_t1 = peer->timer_t1;
14582
14583
14584 if (peer->timer_b)
14585 p->timer_b = peer->timer_b;
14586 else
14587 p->timer_b = 64 * p->timer_t1;
14588
14589 if (ast_test_flag(&peer->flags[0], SIP_INSECURE_INVITE)) {
14590
14591 ast_string_field_set(p, peersecret, NULL);
14592 ast_string_field_set(p, peermd5secret, NULL);
14593 }
14594 if (!(res = check_auth(p, req, peer->name, p->peersecret, p->peermd5secret, sipmethod, uri2, reliable, req->ignore))) {
14595 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
14596 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
14597
14598 if (peer->call_limit)
14599 ast_set_flag(&p->flags[0], SIP_CALL_LIMIT);
14600 ast_string_field_set(p, peername, peer->name);
14601 ast_string_field_set(p, authname, peer->name);
14602
14603 if (sipmethod == SIP_INVITE) {
14604
14605 p->chanvars = copy_vars(peer->chanvars);
14606 }
14607
14608 if (authpeer) {
14609 ao2_t_ref(peer, 1, "copy pointer into (*authpeer)");
14610 (*authpeer) = peer;
14611 }
14612
14613 if (!ast_strlen_zero(peer->username)) {
14614 ast_string_field_set(p, username, peer->username);
14615
14616
14617 ast_string_field_set(p, authname, peer->username);
14618 }
14619 if (!ast_strlen_zero(peer->cid_num)) {
14620 char *tmp = ast_strdupa(peer->cid_num);
14621 if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
14622 ast_shrink_phone_number(tmp);
14623 ast_string_field_set(p, cid_num, tmp);
14624 }
14625 if (!ast_strlen_zero(peer->cid_name))
14626 ast_string_field_set(p, cid_name, peer->cid_name);
14627 ast_string_field_set(p, fullcontact, peer->fullcontact);
14628 if (!ast_strlen_zero(peer->context))
14629 ast_string_field_set(p, context, peer->context);
14630 ast_string_field_set(p, peersecret, peer->secret);
14631 ast_string_field_set(p, peermd5secret, peer->md5secret);
14632 ast_string_field_set(p, language, peer->language);
14633 ast_string_field_set(p, accountcode, peer->accountcode);
14634 p->amaflags = peer->amaflags;
14635 p->callgroup = peer->callgroup;
14636 p->pickupgroup = peer->pickupgroup;
14637 p->capability = peer->capability;
14638 p->prefs = peer->prefs;
14639 p->jointcapability = peer->capability;
14640 if (p->peercapability)
14641 p->jointcapability &= p->peercapability;
14642 p->maxcallbitrate = peer->maxcallbitrate;
14643 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS) &&
14644 (!ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) ||
14645 !(p->capability & AST_FORMAT_VIDEO_MASK)) &&
14646 p->vrtp) {
14647 ast_rtp_destroy(p->vrtp);
14648 p->vrtp = NULL;
14649 }
14650 if ((!ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT) || !(p->capability & AST_FORMAT_TEXT_MASK)) && p->trtp) {
14651 ast_rtp_destroy(p->trtp);
14652 p->trtp = NULL;
14653 }
14654 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
14655 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
14656 p->noncodeccapability |= AST_RTP_DTMF;
14657 else
14658 p->noncodeccapability &= ~AST_RTP_DTMF;
14659 p->jointnoncodeccapability = p->noncodeccapability;
14660 }
14661 unref_peer(peer, "check_peer_ok: unref_peer: tossing temp ptr to peer from find_peer");
14662 return res;
14663 }
14664
14665
14666
14667
14668
14669
14670
14671 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
14672 int sipmethod, char *uri, enum xmittype reliable,
14673 struct sockaddr_in *sin, struct sip_peer **authpeer)
14674 {
14675 char from[256];
14676 char *dummy;
14677 char *domain;
14678 char *of;
14679 char rpid_num[50];
14680 const char *rpid;
14681 enum check_auth_result res;
14682 char calleridname[50];
14683 char *uri2 = ast_strdupa(uri);
14684
14685 terminate_uri(uri2);
14686
14687 ast_copy_string(from, get_header(req, "From"), sizeof(from));
14688 if (sip_cfg.pedanticsipchecking)
14689 ast_uri_decode(from);
14690
14691 memset(calleridname, 0, sizeof(calleridname));
14692 get_calleridname(from, calleridname, sizeof(calleridname));
14693 if (calleridname[0])
14694 ast_string_field_set(p, cid_name, calleridname);
14695
14696 rpid = get_header(req, "Remote-Party-ID");
14697 memset(rpid_num, 0, sizeof(rpid_num));
14698 if (!ast_strlen_zero(rpid))
14699 p->callingpres = get_rpid_num(rpid, rpid_num, sizeof(rpid_num));
14700
14701 of = get_in_brackets(from);
14702 if (ast_strlen_zero(p->exten)) {
14703 char *t = uri2;
14704 if (!strncasecmp(t, "sip:", 4))
14705 t+= 4;
14706 else if (!strncasecmp(t, "sips:", 5))
14707 t += 5;
14708 ast_string_field_set(p, exten, t);
14709 t = strchr(p->exten, '@');
14710 if (t)
14711 *t = '\0';
14712 if (ast_strlen_zero(p->our_contact))
14713 build_contact(p);
14714 }
14715
14716 ast_string_field_set(p, from, of);
14717
14718
14719 if (parse_uri(of, "sip:,sips:", &of, &dummy, &domain, &dummy, &dummy, NULL)) {
14720 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
14721 }
14722
14723 if (ast_strlen_zero(of)) {
14724
14725
14726
14727
14728
14729
14730 of = domain;
14731 } else {
14732 char *tmp = ast_strdupa(of);
14733
14734
14735
14736 tmp = strsep(&tmp, ";");
14737 if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
14738 ast_shrink_phone_number(tmp);
14739 ast_string_field_set(p, cid_num, tmp);
14740 }
14741
14742 if (global_match_auth_username) {
14743
14744
14745
14746
14747
14748
14749
14750
14751 const char *hdr = get_header(req, "Authorization");
14752 if (ast_strlen_zero(hdr))
14753 hdr = get_header(req, "Proxy-Authorization");
14754
14755 if ( !ast_strlen_zero(hdr) && (hdr = strstr(hdr, "username=\"")) ) {
14756 ast_copy_string(from, hdr + strlen("username=\""), sizeof(from));
14757 of = from;
14758 of = strsep(&of, "\"");
14759 }
14760 }
14761
14762 res = check_peer_ok(p, of, req, sipmethod, sin,
14763 authpeer, reliable, rpid_num, calleridname, uri2);
14764 if (res != AUTH_DONT_KNOW)
14765 return res;
14766
14767
14768 if (sip_cfg.allowguest) {
14769 replace_cid(p, rpid_num, calleridname);
14770 res = AUTH_SUCCESSFUL;
14771 } else if (sip_cfg.alwaysauthreject)
14772 res = AUTH_FAKE_AUTH;
14773 else
14774 res = AUTH_SECRET_FAILED;
14775
14776
14777 if (ast_test_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT)) {
14778 ast_set_flag(&p->flags[0], SIP_NAT_ROUTE);
14779 }
14780
14781 return res;
14782 }
14783
14784
14785
14786
14787 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin)
14788 {
14789 return check_user_full(p, req, sipmethod, uri, reliable, sin, NULL);
14790 }
14791
14792
14793 static int get_msg_text(char *buf, int len, struct sip_request *req, int addnewline)
14794 {
14795 int x;
14796 int y;
14797
14798 buf[0] = '\0';
14799
14800 y = len - strlen(buf) - 5;
14801 if (y < 0)
14802 y = 0;
14803 for (x = 0; x < req->lines; x++) {
14804 char *line = REQ_OFFSET_TO_STR(req, line[x]);
14805 strncat(buf, line, y);
14806 y -= strlen(line) + 1;
14807 if (y < 0)
14808 y = 0;
14809 if (y != 0 && addnewline)
14810 strcat(buf, "\n");
14811 }
14812 return 0;
14813 }
14814
14815
14816
14817
14818
14819 static void receive_message(struct sip_pvt *p, struct sip_request *req)
14820 {
14821 char buf[1400];
14822 struct ast_frame f;
14823 const char *content_type = get_header(req, "Content-Type");
14824
14825 if (strncmp(content_type, "text/plain", strlen("text/plain"))) {
14826 transmit_response(p, "415 Unsupported Media Type", req);
14827 if (!p->owner)
14828 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14829 return;
14830 }
14831
14832 if (get_msg_text(buf, sizeof(buf), req, FALSE)) {
14833 ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
14834 transmit_response(p, "202 Accepted", req);
14835 if (!p->owner)
14836 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14837 return;
14838 }
14839
14840 if (p->owner) {
14841 if (sip_debug_test_pvt(p))
14842 ast_verbose("SIP Text message received: '%s'\n", buf);
14843 memset(&f, 0, sizeof(f));
14844 f.frametype = AST_FRAME_TEXT;
14845 f.subclass = 0;
14846 f.offset = 0;
14847 f.data.ptr = buf;
14848 f.datalen = strlen(buf) + 1;
14849 ast_queue_frame(p->owner, &f);
14850 transmit_response(p, "202 Accepted", req);
14851 return;
14852 }
14853
14854
14855 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);
14856 transmit_response(p, "405 Method Not Allowed", req);
14857 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14858 return;
14859 }
14860
14861
14862 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14863 {
14864 #define FORMAT "%-25.25s %-15.15s %-15.15s \n"
14865 #define FORMAT2 "%-25.25s %-15.15s %-15.15s \n"
14866 char ilimits[40];
14867 char iused[40];
14868 int showall = FALSE;
14869 struct ao2_iterator i;
14870 struct sip_peer *peer;
14871
14872 switch (cmd) {
14873 case CLI_INIT:
14874 e->command = "sip show inuse";
14875 e->usage =
14876 "Usage: sip show inuse [all]\n"
14877 " List all SIP devices usage counters and limits.\n"
14878 " Add option \"all\" to show all devices, not only those with a limit.\n";
14879 return NULL;
14880 case CLI_GENERATE:
14881 return NULL;
14882 }
14883
14884 if (a->argc < 3)
14885 return CLI_SHOWUSAGE;
14886
14887 if (a->argc == 4 && !strcmp(a->argv[3], "all"))
14888 showall = TRUE;
14889
14890 ast_cli(a->fd, FORMAT, "* Peer name", "In use", "Limit");
14891
14892 i = ao2_iterator_init(peers, 0);
14893 while ((peer = ao2_t_iterator_next(&i, "iterate thru peer table"))) {
14894 ao2_lock(peer);
14895 if (peer->call_limit)
14896 snprintf(ilimits, sizeof(ilimits), "%d", peer->call_limit);
14897 else
14898 ast_copy_string(ilimits, "N/A", sizeof(ilimits));
14899 snprintf(iused, sizeof(iused), "%d/%d/%d", peer->inUse, peer->inRinging, peer->onHold);
14900 if (showall || peer->call_limit)
14901 ast_cli(a->fd, FORMAT2, peer->name, iused, ilimits);
14902 ao2_unlock(peer);
14903 unref_peer(peer, "toss iterator pointer");
14904 }
14905 ao2_iterator_destroy(&i);
14906
14907 return CLI_SUCCESS;
14908 #undef FORMAT
14909 #undef FORMAT2
14910 }
14911
14912
14913
14914 static char *transfermode2str(enum transfermodes mode)
14915 {
14916 if (mode == TRANSFER_OPENFORALL)
14917 return "open";
14918 else if (mode == TRANSFER_CLOSED)
14919 return "closed";
14920 return "strict";
14921 }
14922
14923 static struct _map_x_s natmodes[] = {
14924 { SIP_NAT_NEVER, "No"},
14925 { SIP_NAT_ROUTE, "Route"},
14926 { SIP_NAT_ALWAYS, "Always"},
14927 { SIP_NAT_RFC3581, "RFC3581"},
14928 { -1, NULL},
14929 };
14930
14931
14932 static const char *nat2str(int nat)
14933 {
14934 return map_x_s(natmodes, nat, "Unknown");
14935 }
14936
14937 #ifdef NOTUSED
14938
14939
14940
14941
14942 static struct _map_x_s natcfgmodes[] = {
14943 { SIP_NAT_NEVER, "never"},
14944 { SIP_NAT_ROUTE, "route"},
14945 { SIP_NAT_ALWAYS, "yes"},
14946 { SIP_NAT_RFC3581, "no"},
14947 { -1, NULL},
14948 };
14949
14950
14951 static const char *nat2strconfig(int nat)
14952 {
14953 return map_x_s(natcfgmodes, nat, "Unknown");
14954 }
14955 #endif
14956
14957
14958
14959
14960
14961
14962
14963 static struct _map_x_s stmodes[] = {
14964 { SESSION_TIMER_MODE_ACCEPT, "Accept"},
14965 { SESSION_TIMER_MODE_ORIGINATE, "Originate"},
14966 { SESSION_TIMER_MODE_REFUSE, "Refuse"},
14967 { -1, NULL},
14968 };
14969
14970 static const char *stmode2str(enum st_mode m)
14971 {
14972 return map_x_s(stmodes, m, "Unknown");
14973 }
14974
14975 static enum st_mode str2stmode(const char *s)
14976 {
14977 return map_s_x(stmodes, s, -1);
14978 }
14979
14980
14981 static struct _map_x_s strefreshers[] = {
14982 { SESSION_TIMER_REFRESHER_AUTO, "auto"},
14983 { SESSION_TIMER_REFRESHER_UAC, "uac"},
14984 { SESSION_TIMER_REFRESHER_UAS, "uas"},
14985 { -1, NULL},
14986 };
14987
14988 static const char *strefresher2str(enum st_refresher r)
14989 {
14990 return map_x_s(strefreshers, r, "Unknown");
14991 }
14992
14993 static enum st_refresher str2strefresher(const char *s)
14994 {
14995 return map_s_x(strefreshers, s, -1);
14996 }
14997
14998
14999 static int peer_status(struct sip_peer *peer, char *status, int statuslen)
15000 {
15001 int res = 0;
15002 if (peer->maxms) {
15003 if (peer->lastms < 0) {
15004 ast_copy_string(status, "UNREACHABLE", statuslen);
15005 } else if (peer->lastms > peer->maxms) {
15006 snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
15007 res = 1;
15008 } else if (peer->lastms) {
15009 snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
15010 res = 1;
15011 } else {
15012 ast_copy_string(status, "UNKNOWN", statuslen);
15013 }
15014 } else {
15015 ast_copy_string(status, "Unmonitored", statuslen);
15016
15017 res = -1;
15018 }
15019 return res;
15020 }
15021
15022
15023
15024
15025
15026
15027 static const char *cli_yesno(int x)
15028 {
15029 return x ? "Yes" : "No";
15030 }
15031
15032
15033 static char *sip_show_tcp(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15034 {
15035 struct sip_threadinfo *th;
15036 struct ao2_iterator i;
15037
15038 #define FORMAT2 "%-30.30s %3.6s %9.9s %6.6s\n"
15039 #define FORMAT "%-30.30s %-6d %-9.9s %-6.6s\n"
15040
15041 switch (cmd) {
15042 case CLI_INIT:
15043 e->command = "sip show tcp";
15044 e->usage =
15045 "Usage: sip show tcp\n"
15046 " Lists all active TCP/TLS sessions.\n";
15047 return NULL;
15048 case CLI_GENERATE:
15049 return NULL;
15050 }
15051
15052 if (a->argc != 3)
15053 return CLI_SHOWUSAGE;
15054
15055 ast_cli(a->fd, FORMAT2, "Host", "Port", "Transport", "Type");
15056 i = ao2_iterator_init(threadt, 0);
15057 while ((th = ao2_t_iterator_next(&i, "iterate through tcp threads for 'sip show tcp'"))) {
15058 ast_cli(a->fd, FORMAT, ast_inet_ntoa(th->tcptls_session->remote_address.sin_addr),
15059 ntohs(th->tcptls_session->remote_address.sin_port),
15060 get_transport(th->type),
15061 (th->tcptls_session->client ? "Client" : "Server"));
15062 ao2_t_ref(th, -1, "decrement ref from iterator");
15063 }
15064 ao2_iterator_destroy(&i);
15065 return CLI_SUCCESS;
15066 #undef FORMAT
15067 #undef FORMAT2
15068 }
15069
15070
15071 static char *sip_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15072 {
15073 regex_t regexbuf;
15074 int havepattern = FALSE;
15075 struct ao2_iterator user_iter;
15076 struct sip_peer *user;
15077
15078 #define FORMAT "%-25.25s %-15.15s %-15.15s %-15.15s %-5.5s%-10.10s\n"
15079
15080 switch (cmd) {
15081 case CLI_INIT:
15082 e->command = "sip show users";
15083 e->usage =
15084 "Usage: sip show users [like <pattern>]\n"
15085 " Lists all known SIP users.\n"
15086 " Optional regular expression pattern is used to filter the user list.\n";
15087 return NULL;
15088 case CLI_GENERATE:
15089 return NULL;
15090 }
15091
15092 switch (a->argc) {
15093 case 5:
15094 if (!strcasecmp(a->argv[3], "like")) {
15095 if (regcomp(®exbuf, a->argv[4], REG_EXTENDED | REG_NOSUB))
15096 return CLI_SHOWUSAGE;
15097 havepattern = TRUE;
15098 } else
15099 return CLI_SHOWUSAGE;
15100 case 3:
15101 break;
15102 default:
15103 return CLI_SHOWUSAGE;
15104 }
15105
15106 ast_cli(a->fd, FORMAT, "Username", "Secret", "Accountcode", "Def.Context", "ACL", "NAT");
15107
15108 user_iter = ao2_iterator_init(peers, 0);
15109 while ((user = ao2_iterator_next(&user_iter))) {
15110 ao2_lock(user);
15111 if (!(user->type & SIP_TYPE_USER)) {
15112 ao2_unlock(user);
15113 unref_peer(user, "sip show users");
15114 continue;
15115 }
15116
15117 if (havepattern && regexec(®exbuf, user->name, 0, NULL, 0)) {
15118 ao2_unlock(user);
15119 unref_peer(user, "sip show users");
15120 continue;
15121 }
15122
15123 ast_cli(a->fd, FORMAT, user->name,
15124 user->secret,
15125 user->accountcode,
15126 user->context,
15127 cli_yesno(user->ha != NULL),
15128 nat2str(ast_test_flag(&user->flags[0], SIP_NAT)));
15129 ao2_unlock(user);
15130 unref_peer(user, "sip show users");
15131 }
15132 ao2_iterator_destroy(&user_iter);
15133
15134 if (havepattern)
15135 regfree(®exbuf);
15136
15137 return CLI_SUCCESS;
15138 #undef FORMAT
15139 }
15140
15141
15142 static char mandescr_show_registry[] =
15143 "Description: Lists all registration requests and status\n"
15144 "Registrations will follow as separate events. followed by a final event called\n"
15145 "RegistrationsComplete.\n"
15146 "Variables: \n"
15147 " ActionID: <id> Action ID for this transaction. Will be returned.\n";
15148
15149
15150 static int manager_show_registry(struct mansession *s, const struct message *m)
15151 {
15152 const char *id = astman_get_header(m, "ActionID");
15153 char idtext[256] = "";
15154 int total = 0;
15155
15156 if (!ast_strlen_zero(id))
15157 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
15158
15159 astman_send_listack(s, m, "Registrations will follow", "start");
15160
15161 ASTOBJ_CONTAINER_TRAVERSE(®l, 1, do {
15162 ASTOBJ_RDLOCK(iterator);
15163 astman_append(s,
15164 "Event: RegistryEntry\r\n"
15165 "%s"
15166 "Host: %s\r\n"
15167 "Port: %d\r\n"
15168 "Username: %s\r\n"
15169 "Refresh: %d\r\n"
15170 "State: %s\r\n"
15171 "RegistrationTime: %ld\r\n"
15172 "\r\n", idtext, iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT,
15173 iterator->username, iterator->refresh, regstate2str(iterator->regstate), (long) iterator->regtime.tv_sec);
15174 ASTOBJ_UNLOCK(iterator);
15175 total++;
15176 } while(0));
15177
15178 astman_append(s,
15179 "Event: RegistrationsComplete\r\n"
15180 "EventList: Complete\r\n"
15181 "ListItems: %d\r\n"
15182 "%s"
15183 "\r\n", total, idtext);
15184
15185 return 0;
15186 }
15187
15188 static char mandescr_show_peers[] =
15189 "Description: Lists SIP peers in text format with details on current status.\n"
15190 "Peerlist will follow as separate events, followed by a final event called\n"
15191 "PeerlistComplete.\n"
15192 "Variables: \n"
15193 " ActionID: <id> Action ID for this transaction. Will be returned.\n";
15194
15195
15196
15197 static int manager_sip_show_peers(struct mansession *s, const struct message *m)
15198 {
15199 const char *id = astman_get_header(m, "ActionID");
15200 const char *a[] = {"sip", "show", "peers"};
15201 char idtext[256] = "";
15202 int total = 0;
15203
15204 if (!ast_strlen_zero(id))
15205 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
15206
15207 astman_send_listack(s, m, "Peer status list will follow", "start");
15208
15209 _sip_show_peers(-1, &total, s, m, 3, a);
15210
15211 astman_append(s,
15212 "Event: PeerlistComplete\r\n"
15213 "EventList: Complete\r\n"
15214 "ListItems: %d\r\n"
15215 "%s"
15216 "\r\n", total, idtext);
15217 return 0;
15218 }
15219
15220
15221 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15222 {
15223 switch (cmd) {
15224 case CLI_INIT:
15225 e->command = "sip show peers";
15226 e->usage =
15227 "Usage: sip show peers [like <pattern>]\n"
15228 " Lists all known SIP peers.\n"
15229 " Optional regular expression pattern is used to filter the peer list.\n";
15230 return NULL;
15231 case CLI_GENERATE:
15232 return NULL;
15233 }
15234
15235 return _sip_show_peers(a->fd, NULL, NULL, NULL, a->argc, (const char **) a->argv);
15236 }
15237
15238 int peercomparefunc(const void *a, const void *b);
15239
15240 int peercomparefunc(const void *a, const void *b)
15241 {
15242 struct sip_peer **ap = (struct sip_peer **)a;
15243 struct sip_peer **bp = (struct sip_peer **)b;
15244 return strcmp((*ap)->name, (*bp)->name);
15245 }
15246
15247
15248
15249 static char *_sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[])
15250 {
15251 regex_t regexbuf;
15252 int havepattern = FALSE;
15253 struct sip_peer *peer;
15254 struct ao2_iterator i;
15255
15256
15257 #define FORMAT2 "%-25.25s %-15.15s %-3.3s %-3.3s %-3.3s %-8s %-10s %s\n"
15258 #define FORMAT "%-25.25s %-15.15s %-3.3s %-3.3s %-3.3s %-8d %-10s %s\n"
15259
15260 char name[256];
15261 int total_peers = 0;
15262 int peers_mon_online = 0;
15263 int peers_mon_offline = 0;
15264 int peers_unmon_offline = 0;
15265 int peers_unmon_online = 0;
15266 const char *id;
15267 char idtext[256] = "";
15268 int realtimepeers;
15269 int objcount = ao2_container_count(peers);
15270 struct sip_peer **peerarray;
15271 int k;
15272
15273
15274 realtimepeers = ast_check_realtime("sippeers");
15275 peerarray = ast_calloc(sizeof(struct sip_peer *), objcount);
15276
15277 if (s) {
15278 id = astman_get_header(m, "ActionID");
15279 if (!ast_strlen_zero(id))
15280 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
15281 }
15282
15283 switch (argc) {
15284 case 5:
15285 if (!strcasecmp(argv[3], "like")) {
15286 if (regcomp(®exbuf, argv[4], REG_EXTENDED | REG_NOSUB))
15287 return CLI_SHOWUSAGE;
15288 havepattern = TRUE;
15289 } else
15290 return CLI_SHOWUSAGE;
15291 case 3:
15292 break;
15293 default:
15294 return CLI_SHOWUSAGE;
15295 }
15296
15297 if (!s)
15298 ast_cli(fd, FORMAT2, "Name/username", "Host", "Dyn", "Nat", "ACL", "Port", "Status", (realtimepeers ? "Realtime" : ""));
15299
15300
15301 i = ao2_iterator_init(peers, 0);
15302 while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
15303 ao2_lock(peer);
15304
15305 if (!(peer->type & SIP_TYPE_PEER)) {
15306 ao2_unlock(peer);
15307 unref_peer(peer, "unref peer because it's actually a user");
15308 continue;
15309 }
15310
15311 if (havepattern && regexec(®exbuf, peer->name, 0, NULL, 0)) {
15312 objcount--;
15313 ao2_unlock(peer);
15314 unref_peer(peer, "toss iterator peer ptr before continue");
15315 continue;
15316 }
15317
15318 peerarray[total_peers++] = peer;
15319 ao2_unlock(peer);
15320 }
15321 ao2_iterator_destroy(&i);
15322
15323 qsort(peerarray, total_peers, sizeof(struct sip_peer *), peercomparefunc);
15324
15325 for(k=0; k < total_peers; k++) {
15326 char status[20] = "";
15327 char srch[2000];
15328 char pstatus;
15329 peer = peerarray[k];
15330
15331 ao2_lock(peer);
15332 if (havepattern && regexec(®exbuf, peer->name, 0, NULL, 0)) {
15333 ao2_unlock(peer);
15334 unref_peer(peer, "toss iterator peer ptr before continue");
15335 continue;
15336 }
15337
15338 if (!ast_strlen_zero(peer->username) && !s)
15339 snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
15340 else
15341 ast_copy_string(name, peer->name, sizeof(name));
15342
15343 pstatus = peer_status(peer, status, sizeof(status));
15344 if (pstatus == 1)
15345 peers_mon_online++;
15346 else if (pstatus == 0)
15347 peers_mon_offline++;
15348 else {
15349 if (peer->addr.sin_port == 0)
15350 peers_unmon_offline++;
15351 else
15352 peers_unmon_online++;
15353 }
15354
15355 snprintf(srch, sizeof(srch), FORMAT, name,
15356 peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
15357 peer->host_dynamic ? " D " : " ",
15358 ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) ? " N " : " ",
15359 peer->ha ? " A " : " ",
15360 ntohs(peer->addr.sin_port), status,
15361 realtimepeers ? (peer->is_realtime ? "Cached RT":"") : "");
15362
15363 if (!s) {
15364 ast_cli(fd, FORMAT, name,
15365 peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
15366 peer->host_dynamic ? " D " : " ",
15367 ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) ? " N " : " ",
15368 peer->ha ? " A " : " ",
15369
15370 ntohs(peer->addr.sin_port), status,
15371 realtimepeers ? (peer->is_realtime ? "Cached RT":"") : "");
15372 } else {
15373
15374 astman_append(s,
15375 "Event: PeerEntry\r\n%s"
15376 "Channeltype: SIP\r\n"
15377 "ObjectName: %s\r\n"
15378 "ChanObjectType: peer\r\n"
15379 "IPaddress: %s\r\n"
15380 "IPport: %d\r\n"
15381 "Dynamic: %s\r\n"
15382 "Natsupport: %s\r\n"
15383 "VideoSupport: %s\r\n"
15384 "TextSupport: %s\r\n"
15385 "ACL: %s\r\n"
15386 "Status: %s\r\n"
15387 "RealtimeDevice: %s\r\n\r\n",
15388 idtext,
15389 peer->name,
15390 peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "-none-",
15391 ntohs(peer->addr.sin_port),
15392 peer->host_dynamic ? "yes" : "no",
15393 ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) ? "yes" : "no",
15394 ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "yes" : "no",
15395 ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT) ? "yes" : "no",
15396 peer->ha ? "yes" : "no",
15397 status,
15398 realtimepeers ? (peer->is_realtime ? "yes":"no") : "no");
15399 }
15400 ao2_unlock(peer);
15401 unref_peer(peer, "toss iterator peer ptr");
15402 }
15403
15404 if (!s)
15405 ast_cli(fd, "%d sip peers [Monitored: %d online, %d offline Unmonitored: %d online, %d offline]\n",
15406 total_peers, peers_mon_online, peers_mon_offline, peers_unmon_online, peers_unmon_offline);
15407
15408 if (havepattern)
15409 regfree(®exbuf);
15410
15411 if (total)
15412 *total = total_peers;
15413
15414 ast_free(peerarray);
15415
15416 return CLI_SUCCESS;
15417 #undef FORMAT
15418 #undef FORMAT2
15419 }
15420
15421 static int peer_dump_func(void *userobj, void *arg, int flags)
15422 {
15423 struct sip_peer *peer = userobj;
15424 int refc = ao2_t_ref(userobj, 0, "");
15425 int *fd = arg;
15426
15427 ast_cli(*fd, "name: %s\ntype: peer\nobjflags: %d\nrefcount: %d\n\n",
15428 peer->name, 0, refc);
15429 return 0;
15430 }
15431
15432 static int dialog_dump_func(void *userobj, void *arg, int flags)
15433 {
15434 struct sip_pvt *pvt = userobj;
15435 int refc = ao2_t_ref(userobj, 0, "");
15436 int *fd = arg;
15437
15438 ast_cli(*fd, "name: %s\ntype: dialog\nobjflags: %d\nrefcount: %d\n\n",
15439 pvt->callid, 0, refc);
15440 return 0;
15441 }
15442
15443
15444
15445 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15446 {
15447 char tmp[256];
15448
15449 switch (cmd) {
15450 case CLI_INIT:
15451 e->command = "sip show objects";
15452 e->usage =
15453 "Usage: sip show objects\n"
15454 " Lists status of known SIP objects\n";
15455 return NULL;
15456 case CLI_GENERATE:
15457 return NULL;
15458 }
15459
15460 if (a->argc != 3)
15461 return CLI_SHOWUSAGE;
15462 ast_cli(a->fd, "-= Peer objects: %d static, %d realtime, %d autocreate =-\n\n", speerobjs, rpeerobjs, apeerobjs);
15463 ao2_t_callback(peers, OBJ_NODATA, peer_dump_func, &a->fd, "initiate ao2_callback to dump peers");
15464 ast_cli(a->fd, "-= Registry objects: %d =-\n\n", regobjs);
15465 ASTOBJ_CONTAINER_DUMP(a->fd, tmp, sizeof(tmp), ®l);
15466 ast_cli(a->fd, "-= Dialog objects:\n\n");
15467 ao2_t_callback(dialogs, OBJ_NODATA, dialog_dump_func, &a->fd, "initiate ao2_callback to dump dialogs");
15468 return CLI_SUCCESS;
15469 }
15470
15471 static void print_group(int fd, ast_group_t group, int crlf)
15472 {
15473 char buf[256];
15474 ast_cli(fd, crlf ? "%s\r\n" : "%s\n", ast_print_group(buf, sizeof(buf), group) );
15475 }
15476
15477
15478 static struct _map_x_s dtmfstr[] = {
15479 { SIP_DTMF_RFC2833, "rfc2833" },
15480 { SIP_DTMF_INFO, "info" },
15481 { SIP_DTMF_SHORTINFO, "shortinfo" },
15482 { SIP_DTMF_INBAND, "inband" },
15483 { SIP_DTMF_AUTO, "auto" },
15484 { -1, NULL },
15485 };
15486
15487
15488 static const char *dtmfmode2str(int mode)
15489 {
15490 return map_x_s(dtmfstr, mode, "<error>");
15491 }
15492
15493
15494 static int str2dtmfmode(const char *str)
15495 {
15496 return map_s_x(dtmfstr, str, -1);
15497 }
15498
15499 static struct _map_x_s insecurestr[] = {
15500 { SIP_INSECURE_PORT, "port" },
15501 { SIP_INSECURE_INVITE, "invite" },
15502 { SIP_INSECURE_PORT | SIP_INSECURE_INVITE, "port,invite" },
15503 { 0, "no" },
15504 { -1, NULL },
15505 };
15506
15507
15508 static const char *insecure2str(int mode)
15509 {
15510 return map_x_s(insecurestr, mode, "<error>");
15511 }
15512
15513
15514
15515
15516 static void cleanup_stale_contexts(char *new, char *old)
15517 {
15518 char *oldcontext, *newcontext, *stalecontext, *stringp, newlist[AST_MAX_CONTEXT];
15519
15520 while ((oldcontext = strsep(&old, "&"))) {
15521 stalecontext = '\0';
15522 ast_copy_string(newlist, new, sizeof(newlist));
15523 stringp = newlist;
15524 while ((newcontext = strsep(&stringp, "&"))) {
15525 if (!strcmp(newcontext, oldcontext)) {
15526
15527 stalecontext = '\0';
15528 break;
15529 } else if (strcmp(newcontext, oldcontext)) {
15530 stalecontext = oldcontext;
15531 }
15532
15533 }
15534 if (stalecontext)
15535 ast_context_destroy(ast_context_find(stalecontext), "SIP");
15536 }
15537 }
15538
15539
15540
15541
15542
15543
15544
15545
15546
15547
15548
15549
15550
15551 static int dialog_needdestroy(void *dialogobj, void *arg, int flags)
15552 {
15553 struct sip_pvt *dialog = dialogobj;
15554 time_t *t = arg;
15555
15556 if (sip_pvt_trylock(dialog)) {
15557
15558
15559 return 0;
15560 }
15561
15562
15563 check_rtp_timeout(dialog, *t);
15564
15565
15566
15567
15568 if (dialog->needdestroy && !dialog->packets && !dialog->owner) {
15569
15570 if (dialog->rtp && ast_rtp_get_bridged(dialog->rtp)) {
15571 ast_debug(2, "Bridge still active. Delaying destruction of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
15572 sip_pvt_unlock(dialog);
15573 return 0;
15574 }
15575
15576 if (dialog->vrtp && ast_rtp_get_bridged(dialog->vrtp)) {
15577 ast_debug(2, "Bridge still active. Delaying destroy of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
15578 sip_pvt_unlock(dialog);
15579 return 0;
15580 }
15581
15582 sip_pvt_unlock(dialog);
15583
15584
15585 dialog_unlink_all(dialog, TRUE, FALSE);
15586 return 0;
15587 }
15588
15589 sip_pvt_unlock(dialog);
15590
15591 return 0;
15592 }
15593
15594
15595
15596 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15597 {
15598 struct sip_peer *peer, *pi;
15599 int prunepeer = FALSE;
15600 int multi = FALSE;
15601 char *name = NULL;
15602 regex_t regexbuf;
15603 struct ao2_iterator i;
15604 static char *choices[] = { "all", "like", NULL };
15605 char *cmplt;
15606
15607 if (cmd == CLI_INIT) {
15608 e->command = "sip prune realtime [peer|all]";
15609 e->usage =
15610 "Usage: sip prune realtime [peer [<name>|all|like <pattern>]|all]\n"
15611 " Prunes object(s) from the cache.\n"
15612 " Optional regular expression pattern is used to filter the objects.\n";
15613 return NULL;
15614 } else if (cmd == CLI_GENERATE) {
15615 if (a->pos == 4 && !strcasecmp(a->argv[3], "peer")) {
15616 cmplt = ast_cli_complete(a->word, choices, a->n);
15617 if (!cmplt)
15618 cmplt = complete_sip_peer(a->word, a->n - sizeof(choices), SIP_PAGE2_RTCACHEFRIENDS);
15619 return cmplt;
15620 }
15621 if (a->pos == 5 && !strcasecmp(a->argv[4], "like"))
15622 return complete_sip_peer(a->word, a->n, SIP_PAGE2_RTCACHEFRIENDS);
15623 return NULL;
15624 }
15625 switch (a->argc) {
15626 case 4:
15627 name = a->argv[3];
15628
15629 if (!strcasecmp(name, "peer") || !strcasecmp(name, "like"))
15630 return CLI_SHOWUSAGE;
15631 prunepeer = TRUE;
15632 if (!strcasecmp(name, "all")) {
15633 multi = TRUE;
15634 name = NULL;
15635 }
15636
15637 break;
15638 case 5:
15639
15640 name = a->argv[4];
15641 if (!strcasecmp(a->argv[3], "peer"))
15642 prunepeer = TRUE;
15643 else if (!strcasecmp(a->argv[3], "like")) {
15644 prunepeer = TRUE;
15645 multi = TRUE;
15646 } else
15647 return CLI_SHOWUSAGE;
15648 if (!strcasecmp(name, "like"))
15649 return CLI_SHOWUSAGE;
15650 if (!multi && !strcasecmp(name, "all")) {
15651 multi = TRUE;
15652 name = NULL;
15653 }
15654 break;
15655 case 6:
15656 name = a->argv[5];
15657 multi = TRUE;
15658
15659 if (strcasecmp(a->argv[4], "like"))
15660 return CLI_SHOWUSAGE;
15661 if (!strcasecmp(a->argv[3], "peer")) {
15662 prunepeer = TRUE;
15663 } else
15664 return CLI_SHOWUSAGE;
15665 break;
15666 default:
15667 return CLI_SHOWUSAGE;
15668 }
15669
15670 if (multi && name) {
15671 if (regcomp(®exbuf, name, REG_EXTENDED | REG_NOSUB))
15672 return CLI_SHOWUSAGE;
15673 }
15674
15675 if (multi) {
15676 if (prunepeer) {
15677 int pruned = 0;
15678
15679 i = ao2_iterator_init(peers, 0);
15680 while ((pi = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
15681 ao2_lock(pi);
15682 if (name && regexec(®exbuf, pi->name, 0, NULL, 0)) {
15683 unref_peer(pi, "toss iterator peer ptr before continue");
15684 ao2_unlock(pi);
15685 continue;
15686 };
15687 if (ast_test_flag(&pi->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
15688 pi->the_mark = 1;
15689 pruned++;
15690 }
15691 ao2_unlock(pi);
15692 unref_peer(pi, "toss iterator peer ptr");
15693 }
15694 ao2_iterator_destroy(&i);
15695 if (pruned) {
15696 unlink_marked_peers_from_tables();
15697 ast_cli(a->fd, "%d peers pruned.\n", pruned);
15698 } else
15699 ast_cli(a->fd, "No peers found to prune.\n");
15700 }
15701 } else {
15702 if (prunepeer) {
15703 struct sip_peer tmp;
15704 ast_copy_string(tmp.name, name, sizeof(tmp.name));
15705 if ((peer = ao2_t_find(peers, &tmp, OBJ_POINTER | OBJ_UNLINK, "finding to unlink from peers"))) {
15706 if (peer->addr.sin_addr.s_addr) {
15707 ao2_t_unlink(peers_by_ip, peer, "unlinking peer from peers_by_ip also");
15708 }
15709 if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
15710 ast_cli(a->fd, "Peer '%s' is not a Realtime peer, cannot be pruned.\n", name);
15711
15712 ao2_t_link(peers, peer, "link peer into peer table");
15713 if (peer->addr.sin_addr.s_addr) {
15714 ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
15715 }
15716
15717 } else
15718 ast_cli(a->fd, "Peer '%s' pruned.\n", name);
15719 unref_peer(peer, "sip_prune_realtime: unref_peer: tossing temp peer ptr");
15720 } else
15721 ast_cli(a->fd, "Peer '%s' not found.\n", name);
15722 }
15723 }
15724
15725 return CLI_SUCCESS;
15726 }
15727
15728
15729 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref)
15730 {
15731 int x, codec;
15732
15733 for(x = 0; x < 32 ; x++) {
15734 codec = ast_codec_pref_index(pref, x);
15735 if (!codec)
15736 break;
15737 ast_cli(fd, "%s", ast_getformatname(codec));
15738 ast_cli(fd, ":%d", pref->framing[x]);
15739 if (x < 31 && ast_codec_pref_index(pref, x + 1))
15740 ast_cli(fd, ",");
15741 }
15742 if (!x)
15743 ast_cli(fd, "none");
15744 }
15745
15746
15747 static const char *domain_mode_to_text(const enum domain_mode mode)
15748 {
15749 switch (mode) {
15750 case SIP_DOMAIN_AUTO:
15751 return "[Automatic]";
15752 case SIP_DOMAIN_CONFIG:
15753 return "[Configured]";
15754 }
15755
15756 return "";
15757 }
15758
15759
15760 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15761 {
15762 struct domain *d;
15763 #define FORMAT "%-40.40s %-20.20s %-16.16s\n"
15764
15765 switch (cmd) {
15766 case CLI_INIT:
15767 e->command = "sip show domains";
15768 e->usage =
15769 "Usage: sip show domains\n"
15770 " Lists all configured SIP local domains.\n"
15771 " Asterisk only responds to SIP messages to local domains.\n";
15772 return NULL;
15773 case CLI_GENERATE:
15774 return NULL;
15775 }
15776
15777 if (AST_LIST_EMPTY(&domain_list)) {
15778 ast_cli(a->fd, "SIP Domain support not enabled.\n\n");
15779 return CLI_SUCCESS;
15780 } else {
15781 ast_cli(a->fd, FORMAT, "Our local SIP domains:", "Context", "Set by");
15782 AST_LIST_LOCK(&domain_list);
15783 AST_LIST_TRAVERSE(&domain_list, d, list)
15784 ast_cli(a->fd, FORMAT, d->domain, S_OR(d->context, "(default)"),
15785 domain_mode_to_text(d->mode));
15786 AST_LIST_UNLOCK(&domain_list);
15787 ast_cli(a->fd, "\n");
15788 return CLI_SUCCESS;
15789 }
15790 }
15791 #undef FORMAT
15792
15793 static char mandescr_show_peer[] =
15794 "Description: Show one SIP peer with details on current status.\n"
15795 "Variables: \n"
15796 " Peer: <name> The peer name you want to check.\n"
15797 " ActionID: <id> Optional action ID for this AMI transaction.\n";
15798
15799
15800 static int manager_sip_show_peer(struct mansession *s, const struct message *m)
15801 {
15802 const char *a[4];
15803 const char *peer;
15804
15805 peer = astman_get_header(m, "Peer");
15806 if (ast_strlen_zero(peer)) {
15807 astman_send_error(s, m, "Peer: <name> missing.");
15808 return 0;
15809 }
15810 a[0] = "sip";
15811 a[1] = "show";
15812 a[2] = "peer";
15813 a[3] = peer;
15814
15815 _sip_show_peer(1, -1, s, m, 4, a);
15816 astman_append(s, "\r\n\r\n" );
15817 return 0;
15818 }
15819
15820
15821 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15822 {
15823 switch (cmd) {
15824 case CLI_INIT:
15825 e->command = "sip show peer";
15826 e->usage =
15827 "Usage: sip show peer <name> [load]\n"
15828 " Shows all details on one SIP peer and the current status.\n"
15829 " Option \"load\" forces lookup of peer in realtime storage.\n";
15830 return NULL;
15831 case CLI_GENERATE:
15832 return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
15833 }
15834 return _sip_show_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
15835 }
15836
15837
15838 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
15839 {
15840 struct sip_peer *peer;
15841 int load_realtime;
15842
15843 if (argc < 4)
15844 return CLI_SHOWUSAGE;
15845
15846 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
15847 if ((peer = find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0))) {
15848 sip_poke_peer(peer, 1);
15849 unref_peer(peer, "qualify: done with peer");
15850 } else if (type == 0) {
15851 ast_cli(fd, "Peer '%s' not found\n", argv[3]);
15852 } else {
15853 astman_send_error(s, m, "Peer not found");
15854 }
15855 return CLI_SUCCESS;
15856 }
15857
15858
15859 static int manager_sip_qualify_peer(struct mansession *s, const struct message *m)
15860 {
15861 const char *a[4];
15862 const char *peer;
15863
15864 peer = astman_get_header(m, "Peer");
15865 if (ast_strlen_zero(peer)) {
15866 astman_send_error(s, m, "Peer: <name> missing.");
15867 return 0;
15868 }
15869 a[0] = "sip";
15870 a[1] = "qualify";
15871 a[2] = "peer";
15872 a[3] = peer;
15873
15874 _sip_qualify_peer(1, -1, s, m, 4, a);
15875 astman_append(s, "\r\n\r\n" );
15876 return 0;
15877 }
15878
15879
15880 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15881 {
15882 switch (cmd) {
15883 case CLI_INIT:
15884 e->command = "sip qualify peer";
15885 e->usage =
15886 "Usage: sip qualify peer <name> [load]\n"
15887 " Requests a response from one SIP peer and the current status.\n"
15888 " Option \"load\" forces lookup of peer in realtime storage.\n";
15889 return NULL;
15890 case CLI_GENERATE:
15891 return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
15892 }
15893 return _sip_qualify_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
15894 }
15895
15896
15897 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer)
15898 {
15899 struct sip_mailbox *mailbox;
15900
15901 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
15902 ast_str_append(mailbox_str, 0, "%s%s%s%s",
15903 mailbox->mailbox,
15904 ast_strlen_zero(mailbox->context) ? "" : "@",
15905 S_OR(mailbox->context, ""),
15906 AST_LIST_NEXT(mailbox, entry) ? "," : "");
15907 }
15908 }
15909
15910 static struct _map_x_s faxecmodes[] = {
15911 { SIP_PAGE2_T38SUPPORT_UDPTL, "None"},
15912 { SIP_PAGE2_T38SUPPORT_UDPTL_FEC, "FEC"},
15913 { SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY, "Redundancy"},
15914 { -1, NULL},
15915 };
15916
15917 static const char *faxec2str(int faxec)
15918 {
15919 return map_x_s(faxecmodes, faxec, "Unknown");
15920 }
15921
15922
15923 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
15924 {
15925 char status[30] = "";
15926 char cbuf[256];
15927 struct sip_peer *peer;
15928 char codec_buf[512];
15929 struct ast_codec_pref *pref;
15930 struct ast_variable *v;
15931 struct sip_auth *auth;
15932 int x = 0, codec = 0, load_realtime;
15933 int realtimepeers;
15934
15935 realtimepeers = ast_check_realtime("sippeers");
15936
15937 if (argc < 4)
15938 return CLI_SHOWUSAGE;
15939
15940 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
15941 peer = find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0);
15942
15943 if (s) {
15944 if (peer) {
15945 const char *id = astman_get_header(m, "ActionID");
15946
15947 astman_append(s, "Response: Success\r\n");
15948 if (!ast_strlen_zero(id))
15949 astman_append(s, "ActionID: %s\r\n", id);
15950 } else {
15951 snprintf (cbuf, sizeof(cbuf), "Peer %s not found.", argv[3]);
15952 astman_send_error(s, m, cbuf);
15953 return CLI_SUCCESS;
15954 }
15955 }
15956 if (peer && type==0 ) {
15957 struct ast_str *mailbox_str = ast_str_alloca(512);
15958 ast_cli(fd, "\n\n");
15959 ast_cli(fd, " * Name : %s\n", peer->name);
15960 if (realtimepeers) {
15961 ast_cli(fd, " Realtime peer: %s\n", peer->is_realtime ? "Yes, cached" : "No");
15962 }
15963 ast_cli(fd, " Secret : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
15964 ast_cli(fd, " MD5Secret : %s\n", ast_strlen_zero(peer->md5secret)?"<Not set>":"<Set>");
15965 ast_cli(fd, " Remote Secret: %s\n", ast_strlen_zero(peer->remotesecret)?"<Not set>":"<Set>");
15966 for (auth = peer->auth; auth; auth = auth->next) {
15967 ast_cli(fd, " Realm-auth : Realm %-15.15s User %-10.20s ", auth->realm, auth->username);
15968 ast_cli(fd, "%s\n", !ast_strlen_zero(auth->secret)?"<Secret set>":(!ast_strlen_zero(auth->md5secret)?"<MD5secret set>" : "<Not set>"));
15969 }
15970 ast_cli(fd, " Context : %s\n", peer->context);
15971 ast_cli(fd, " Subscr.Cont. : %s\n", S_OR(peer->subscribecontext, "<Not set>") );
15972 ast_cli(fd, " Language : %s\n", peer->language);
15973 if (!ast_strlen_zero(peer->accountcode))
15974 ast_cli(fd, " Accountcode : %s\n", peer->accountcode);
15975 ast_cli(fd, " AMA flags : %s\n", ast_cdr_flags2str(peer->amaflags));
15976 ast_cli(fd, " Transfer mode: %s\n", transfermode2str(peer->allowtransfer));
15977 ast_cli(fd, " CallingPres : %s\n", ast_describe_caller_presentation(peer->callingpres));
15978 if (!ast_strlen_zero(peer->fromuser))
15979 ast_cli(fd, " FromUser : %s\n", peer->fromuser);
15980 if (!ast_strlen_zero(peer->fromdomain))
15981 ast_cli(fd, " FromDomain : %s\n", peer->fromdomain);
15982 ast_cli(fd, " Callgroup : ");
15983 print_group(fd, peer->callgroup, 0);
15984 ast_cli(fd, " Pickupgroup : ");
15985 print_group(fd, peer->pickupgroup, 0);
15986 peer_mailboxes_to_str(&mailbox_str, peer);
15987 ast_cli(fd, " Mailbox : %s\n", mailbox_str->str);
15988 ast_cli(fd, " VM Extension : %s\n", peer->vmexten);
15989 ast_cli(fd, " LastMsgsSent : %d/%d\n", (peer->lastmsgssent & 0x7fff0000) >> 16, peer->lastmsgssent & 0xffff);
15990 ast_cli(fd, " Call limit : %d\n", peer->call_limit);
15991 if (peer->busy_level)
15992 ast_cli(fd, " Busy level : %d\n", peer->busy_level);
15993 ast_cli(fd, " Dynamic : %s\n", cli_yesno(peer->host_dynamic));
15994 ast_cli(fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
15995 ast_cli(fd, " MaxCallBR : %d kbps\n", peer->maxcallbitrate);
15996 ast_cli(fd, " Expire : %ld\n", ast_sched_when(sched, peer->expire));
15997 ast_cli(fd, " Insecure : %s\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
15998 ast_cli(fd, " Nat : %s\n", nat2str(ast_test_flag(&peer->flags[0], SIP_NAT)));
15999 ast_cli(fd, " ACL : %s\n", cli_yesno(peer->ha != NULL));
16000 ast_cli(fd, " T.38 support : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
16001 ast_cli(fd, " T.38 EC mode : %s\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
16002 ast_cli(fd, " T.38 MaxDtgrm: %d\n", peer->t38_maxdatagram);
16003 ast_cli(fd, " DirectMedia : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)));
16004 ast_cli(fd, " PromiscRedir : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)));
16005 ast_cli(fd, " User=Phone : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)));
16006 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)));
16007 ast_cli(fd, " Text Support : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)));
16008 ast_cli(fd, " Ign SDP ver : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_IGNORESDPVERSION)));
16009 ast_cli(fd, " Trust RPID : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_TRUSTRPID)));
16010 ast_cli(fd, " Send RPID : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_SENDRPID)));
16011 ast_cli(fd, " Subscriptions: %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
16012 ast_cli(fd, " Overlap dial : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWOVERLAP)));
16013 ast_cli(fd, " Forward Loop : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_FORWARD_LOOP_DETECTED)));
16014 if (peer->outboundproxy)
16015 ast_cli(fd, " Outb. proxy : %s %s\n", ast_strlen_zero(peer->outboundproxy->name) ? "<not set>" : peer->outboundproxy->name,
16016 peer->outboundproxy->force ? "(forced)" : "");
16017
16018
16019 ast_cli(fd, " DTMFmode : %s\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
16020 ast_cli(fd, " Timer T1 : %d\n", peer->timer_t1);
16021 ast_cli(fd, " Timer B : %d\n", peer->timer_b);
16022 ast_cli(fd, " ToHost : %s\n", peer->tohost);
16023 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));
16024 ast_cli(fd, " Defaddr->IP : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
16025 ast_cli(fd, " Prim.Transp. : %s\n", get_transport(peer->socket.type));
16026 ast_cli(fd, " Allowed.Trsp : %s\n", get_transport_list(peer->transports));
16027 if (!ast_strlen_zero(global_regcontext))
16028 ast_cli(fd, " Reg. exten : %s\n", peer->regexten);
16029 ast_cli(fd, " Def. Username: %s\n", peer->username);
16030 ast_cli(fd, " SIP Options : ");
16031 if (peer->sipoptions) {
16032 int lastoption = -1;
16033 for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
16034 if (sip_options[x].id != lastoption) {
16035 if (peer->sipoptions & sip_options[x].id)
16036 ast_cli(fd, "%s ", sip_options[x].text);
16037 lastoption = x;
16038 }
16039 }
16040 } else
16041 ast_cli(fd, "(none)");
16042
16043 ast_cli(fd, "\n");
16044 ast_cli(fd, " Codecs : ");
16045 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
16046 ast_cli(fd, "%s\n", codec_buf);
16047 ast_cli(fd, " Codec Order : (");
16048 print_codec_to_cli(fd, &peer->prefs);
16049 ast_cli(fd, ")\n");
16050
16051 ast_cli(fd, " Auto-Framing : %s \n", cli_yesno(peer->autoframing));
16052 ast_cli(fd, " 100 on REG : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_REGISTERTRYING) ? "Yes" : "No");
16053 ast_cli(fd, " Status : ");
16054 peer_status(peer, status, sizeof(status));
16055 ast_cli(fd, "%s\n", status);
16056 ast_cli(fd, " Useragent : %s\n", peer->useragent);
16057 ast_cli(fd, " Reg. Contact : %s\n", peer->fullcontact);
16058 ast_cli(fd, " Qualify Freq : %d ms\n", peer->qualifyfreq);
16059 if (peer->chanvars) {
16060 ast_cli(fd, " Variables :\n");
16061 for (v = peer->chanvars ; v ; v = v->next)
16062 ast_cli(fd, " %s = %s\n", v->name, v->value);
16063 }
16064
16065 ast_cli(fd, " Sess-Timers : %s\n", stmode2str(peer->stimer.st_mode_oper));
16066 ast_cli(fd, " Sess-Refresh : %s\n", strefresher2str(peer->stimer.st_ref));
16067 ast_cli(fd, " Sess-Expires : %d secs\n", peer->stimer.st_max_se);
16068 ast_cli(fd, " Min-Sess : %d secs\n", peer->stimer.st_min_se);
16069 ast_cli(fd, " Parkinglot : %s\n", peer->parkinglot);
16070 ast_cli(fd, "\n");
16071 peer = unref_peer(peer, "sip_show_peer: unref_peer: done with peer ptr");
16072 } else if (peer && type == 1) {
16073 char buffer[256];
16074 struct ast_str *mailbox_str = ast_str_alloca(512);
16075 astman_append(s, "Channeltype: SIP\r\n");
16076 astman_append(s, "ObjectName: %s\r\n", peer->name);
16077 astman_append(s, "ChanObjectType: peer\r\n");
16078 astman_append(s, "SecretExist: %s\r\n", ast_strlen_zero(peer->secret)?"N":"Y");
16079 astman_append(s, "RemoteSecretExist: %s\r\n", ast_strlen_zero(peer->remotesecret)?"N":"Y");
16080 astman_append(s, "MD5SecretExist: %s\r\n", ast_strlen_zero(peer->md5secret)?"N":"Y");
16081 astman_append(s, "Context: %s\r\n", peer->context);
16082 astman_append(s, "Language: %s\r\n", peer->language);
16083 if (!ast_strlen_zero(peer->accountcode))
16084 astman_append(s, "Accountcode: %s\r\n", peer->accountcode);
16085 astman_append(s, "AMAflags: %s\r\n", ast_cdr_flags2str(peer->amaflags));
16086 astman_append(s, "CID-CallingPres: %s\r\n", ast_describe_caller_presentation(peer->callingpres));
16087 if (!ast_strlen_zero(peer->fromuser))
16088 astman_append(s, "SIP-FromUser: %s\r\n", peer->fromuser);
16089 if (!ast_strlen_zero(peer->fromdomain))
16090 astman_append(s, "SIP-FromDomain: %s\r\n", peer->fromdomain);
16091 astman_append(s, "Callgroup: ");
16092 astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->callgroup));
16093 astman_append(s, "Pickupgroup: ");
16094 astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->pickupgroup));
16095 peer_mailboxes_to_str(&mailbox_str, peer);
16096 astman_append(s, "VoiceMailbox: %s\r\n", mailbox_str->str);
16097 astman_append(s, "TransferMode: %s\r\n", transfermode2str(peer->allowtransfer));
16098 astman_append(s, "LastMsgsSent: %d\r\n", peer->lastmsgssent);
16099 astman_append(s, "Call-limit: %d\r\n", peer->call_limit);
16100 astman_append(s, "Busy-level: %d\r\n", peer->busy_level);
16101 astman_append(s, "MaxCallBR: %d kbps\r\n", peer->maxcallbitrate);
16102 astman_append(s, "Dynamic: %s\r\n", peer->host_dynamic?"Y":"N");
16103 astman_append(s, "Callerid: %s\r\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, ""));
16104 astman_append(s, "RegExpire: %ld seconds\r\n", ast_sched_when(sched, peer->expire));
16105 astman_append(s, "SIP-AuthInsecure: %s\r\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
16106 astman_append(s, "SIP-NatSupport: %s\r\n", nat2str(ast_test_flag(&peer->flags[0], SIP_NAT)));
16107 astman_append(s, "ACL: %s\r\n", (peer->ha?"Y":"N"));
16108 astman_append(s, "SIP-CanReinvite: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)?"Y":"N"));
16109 astman_append(s, "SIP-DirectMedia: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)?"Y":"N"));
16110 astman_append(s, "SIP-PromiscRedir: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)?"Y":"N"));
16111 astman_append(s, "SIP-UserPhone: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)?"Y":"N"));
16112 astman_append(s, "SIP-VideoSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)?"Y":"N"));
16113 astman_append(s, "SIP-TextSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)?"Y":"N"));
16114 astman_append(s, "SIP-T.38Support: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)?"Y":"N"));
16115 astman_append(s, "SIP-T.38EC: %s\r\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
16116 astman_append(s, "SIP-T.38MaxDtgrm: %d\r\n", peer->t38_maxdatagram);
16117 astman_append(s, "SIP-Sess-Timers: %s\r\n", stmode2str(peer->stimer.st_mode_oper));
16118 astman_append(s, "SIP-Sess-Refresh: %s\r\n", strefresher2str(peer->stimer.st_ref));
16119 astman_append(s, "SIP-Sess-Expires: %d\r\n", peer->stimer.st_max_se);
16120 astman_append(s, "SIP-Sess-Min: %d\r\n", peer->stimer.st_min_se);
16121
16122
16123 astman_append(s, "SIP-DTMFmode: %s\r\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
16124 astman_append(s, "ToHost: %s\r\n", peer->tohost);
16125 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));
16126 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));
16127 astman_append(s, "Default-Username: %s\r\n", peer->username);
16128 if (!ast_strlen_zero(global_regcontext))
16129 astman_append(s, "RegExtension: %s\r\n", peer->regexten);
16130 astman_append(s, "Codecs: ");
16131 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
16132 astman_append(s, "%s\r\n", codec_buf);
16133 astman_append(s, "CodecOrder: ");
16134 pref = &peer->prefs;
16135 for(x = 0; x < 32 ; x++) {
16136 codec = ast_codec_pref_index(pref, x);
16137 if (!codec)
16138 break;
16139 astman_append(s, "%s", ast_getformatname(codec));
16140 if (x < 31 && ast_codec_pref_index(pref, x+1))
16141 astman_append(s, ",");
16142 }
16143
16144 astman_append(s, "\r\n");
16145 astman_append(s, "Status: ");
16146 peer_status(peer, status, sizeof(status));
16147 astman_append(s, "%s\r\n", status);
16148 astman_append(s, "SIP-Useragent: %s\r\n", peer->useragent);
16149 astman_append(s, "Reg-Contact: %s\r\n", peer->fullcontact);
16150 astman_append(s, "QualifyFreq: %d ms\r\n", peer->qualifyfreq);
16151 astman_append(s, "Parkinglot: %s\r\n", peer->parkinglot);
16152 if (peer->chanvars) {
16153 for (v = peer->chanvars ; v ; v = v->next) {
16154 astman_append(s, "ChanVariable: %s=%s\r\n", v->name, v->value);
16155 }
16156 }
16157
16158 peer = unref_peer(peer, "sip_show_peer: unref_peer: done with peer");
16159
16160 } else {
16161 ast_cli(fd, "Peer %s not found.\n", argv[3]);
16162 ast_cli(fd, "\n");
16163 }
16164
16165 return CLI_SUCCESS;
16166 }
16167
16168
16169 static char *complete_sip_user(const char *word, int state)
16170 {
16171 char *result = NULL;
16172 int wordlen = strlen(word);
16173 int which = 0;
16174 struct ao2_iterator user_iter;
16175 struct sip_peer *user;
16176
16177 user_iter = ao2_iterator_init(peers, 0);
16178 while ((user = ao2_iterator_next(&user_iter))) {
16179 ao2_lock(user);
16180 if (!(user->type & SIP_TYPE_USER)) {
16181 ao2_unlock(user);
16182 unref_peer(user, "complete sip user");
16183 continue;
16184 }
16185
16186 if (!strncasecmp(word, user->name, wordlen) && ++which > state) {
16187 result = ast_strdup(user->name);
16188 }
16189 ao2_unlock(user);
16190 unref_peer(user, "complete sip user");
16191 if (result) {
16192 break;
16193 }
16194 }
16195 ao2_iterator_destroy(&user_iter);
16196 return result;
16197 }
16198
16199 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state)
16200 {
16201 if (pos == 3)
16202 return complete_sip_user(word, state);
16203
16204 return NULL;
16205 }
16206
16207
16208 static char *sip_show_user(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16209 {
16210 char cbuf[256];
16211 struct sip_peer *user;
16212 struct ast_variable *v;
16213 int load_realtime;
16214
16215 switch (cmd) {
16216 case CLI_INIT:
16217 e->command = "sip show user";
16218 e->usage =
16219 "Usage: sip show user <name> [load]\n"
16220 " Shows all details on one SIP user and the current status.\n"
16221 " Option \"load\" forces lookup of peer in realtime storage.\n";
16222 return NULL;
16223 case CLI_GENERATE:
16224 return complete_sip_show_user(a->line, a->word, a->pos, a->n);
16225 }
16226
16227 if (a->argc < 4)
16228 return CLI_SHOWUSAGE;
16229
16230
16231 load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? TRUE : FALSE;
16232
16233 if ((user = find_peer(a->argv[3], NULL, load_realtime, FINDUSERS, FALSE, 0))) {
16234 ao2_lock(user);
16235 ast_cli(a->fd, "\n\n");
16236 ast_cli(a->fd, " * Name : %s\n", user->name);
16237 ast_cli(a->fd, " Secret : %s\n", ast_strlen_zero(user->secret)?"<Not set>":"<Set>");
16238 ast_cli(a->fd, " MD5Secret : %s\n", ast_strlen_zero(user->md5secret)?"<Not set>":"<Set>");
16239 ast_cli(a->fd, " Context : %s\n", user->context);
16240 ast_cli(a->fd, " Language : %s\n", user->language);
16241 if (!ast_strlen_zero(user->accountcode))
16242 ast_cli(a->fd, " Accountcode : %s\n", user->accountcode);
16243 ast_cli(a->fd, " AMA flags : %s\n", ast_cdr_flags2str(user->amaflags));
16244 ast_cli(a->fd, " Transfer mode: %s\n", transfermode2str(user->allowtransfer));
16245 ast_cli(a->fd, " MaxCallBR : %d kbps\n", user->maxcallbitrate);
16246 ast_cli(a->fd, " CallingPres : %s\n", ast_describe_caller_presentation(user->callingpres));
16247 ast_cli(a->fd, " Call limit : %d\n", user->call_limit);
16248 ast_cli(a->fd, " Callgroup : ");
16249 print_group(a->fd, user->callgroup, 0);
16250 ast_cli(a->fd, " Pickupgroup : ");
16251 print_group(a->fd, user->pickupgroup, 0);
16252 ast_cli(a->fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), user->cid_name, user->cid_num, "<unspecified>"));
16253 ast_cli(a->fd, " ACL : %s\n", cli_yesno(user->ha != NULL));
16254 ast_cli(a->fd, " Sess-Timers : %s\n", stmode2str(user->stimer.st_mode_oper));
16255 ast_cli(a->fd, " Sess-Refresh : %s\n", strefresher2str(user->stimer.st_ref));
16256 ast_cli(a->fd, " Sess-Expires : %d secs\n", user->stimer.st_max_se);
16257 ast_cli(a->fd, " Sess-Min-SE : %d secs\n", user->stimer.st_min_se);
16258
16259 ast_cli(a->fd, " Codec Order : (");
16260 print_codec_to_cli(a->fd, &user->prefs);
16261 ast_cli(a->fd, ")\n");
16262
16263 ast_cli(a->fd, " Auto-Framing: %s \n", cli_yesno(user->autoframing));
16264 if (user->chanvars) {
16265 ast_cli(a->fd, " Variables :\n");
16266 for (v = user->chanvars ; v ; v = v->next)
16267 ast_cli(a->fd, " %s = %s\n", v->name, v->value);
16268 }
16269
16270 ast_cli(a->fd, "\n");
16271
16272 ao2_unlock(user);
16273 unref_peer(user, "sip show user");
16274 } else {
16275 ast_cli(a->fd, "User %s not found.\n", a->argv[3]);
16276 ast_cli(a->fd, "\n");
16277 }
16278
16279 return CLI_SUCCESS;
16280 }
16281
16282
16283 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16284 {
16285 struct ast_str *cbuf;
16286 struct ast_cb_names cbnames = {9, { "retrans_pkt",
16287 "__sip_autodestruct",
16288 "expire_register",
16289 "auto_congest",
16290 "sip_reg_timeout",
16291 "sip_poke_peer_s",
16292 "sip_poke_noanswer",
16293 "sip_reregister",
16294 "sip_reinvite_retry"},
16295 { retrans_pkt,
16296 __sip_autodestruct,
16297 expire_register,
16298 auto_congest,
16299 sip_reg_timeout,
16300 sip_poke_peer_s,
16301 sip_poke_noanswer,
16302 sip_reregister,
16303 sip_reinvite_retry}};
16304
16305 switch (cmd) {
16306 case CLI_INIT:
16307 e->command = "sip show sched";
16308 e->usage =
16309 "Usage: sip show sched\n"
16310 " Shows stats on what's in the sched queue at the moment\n";
16311 return NULL;
16312 case CLI_GENERATE:
16313 return NULL;
16314 }
16315
16316 cbuf = ast_str_alloca(2048);
16317
16318 ast_cli(a->fd, "\n");
16319 ast_sched_report(sched, &cbuf, &cbnames);
16320 ast_cli(a->fd, "%s", cbuf->str);
16321
16322 return CLI_SUCCESS;
16323 }
16324
16325
16326 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16327 {
16328 #define FORMAT2 "%-30.30s %-6.6s %-12.12s %8.8s %-20.20s %-25.25s\n"
16329 #define FORMAT "%-30.30s %-6.6s %-12.12s %8d %-20.20s %-25.25s\n"
16330 char host[80];
16331 char tmpdat[256];
16332 struct ast_tm tm;
16333 int counter = 0;
16334
16335 switch (cmd) {
16336 case CLI_INIT:
16337 e->command = "sip show registry";
16338 e->usage =
16339 "Usage: sip show registry\n"
16340 " Lists all registration requests and status.\n";
16341 return NULL;
16342 case CLI_GENERATE:
16343 return NULL;
16344 }
16345
16346 if (a->argc != 3)
16347 return CLI_SHOWUSAGE;
16348 ast_cli(a->fd, FORMAT2, "Host", "dnsmgr", "Username", "Refresh", "State", "Reg.Time");
16349
16350 ASTOBJ_CONTAINER_TRAVERSE(®l, 1, do {
16351 ASTOBJ_RDLOCK(iterator);
16352 snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
16353 if (iterator->regtime.tv_sec) {
16354 ast_localtime(&iterator->regtime, &tm, NULL);
16355 ast_strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T", &tm);
16356 } else
16357 tmpdat[0] = '\0';
16358 ast_cli(a->fd, FORMAT, host, (iterator->dnsmgr) ? "Y" : "N", iterator->username, iterator->refresh, regstate2str(iterator->regstate), tmpdat);
16359 ASTOBJ_UNLOCK(iterator);
16360 counter++;
16361 } while(0));
16362 ast_cli(a->fd, "%d SIP registrations.\n", counter);
16363 return CLI_SUCCESS;
16364 #undef FORMAT
16365 #undef FORMAT2
16366 }
16367
16368
16369
16370
16371
16372 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16373 {
16374 struct sip_peer *peer;
16375 int load_realtime = 0;
16376
16377 switch (cmd) {
16378 case CLI_INIT:
16379 e->command = "sip unregister";
16380 e->usage =
16381 "Usage: sip unregister <peer>\n"
16382 " Unregister (force expiration) a SIP peer from the registry\n";
16383 return NULL;
16384 case CLI_GENERATE:
16385 return complete_sip_unregister(a->line, a->word, a->pos, a->n);
16386 }
16387
16388 if (a->argc != 3)
16389 return CLI_SHOWUSAGE;
16390
16391 if ((peer = find_peer(a->argv[2], NULL, load_realtime, FINDPEERS, TRUE, 0))) {
16392 if (peer->expire > 0) {
16393 AST_SCHED_DEL_UNREF(sched, peer->expire,
16394 unref_peer(peer, "remove register expire ref"));
16395 expire_register(ref_peer(peer, "ref for expire_register"));
16396 ast_cli(a->fd, "Unregistered peer \'%s\'\n\n", a->argv[2]);
16397 } else {
16398 ast_cli(a->fd, "Peer %s not registered\n", a->argv[2]);
16399 }
16400 unref_peer(peer, "sip_unregister: unref_peer via sip_unregister: done with peer from find_peer call");
16401 } else {
16402 ast_cli(a->fd, "Peer unknown: \'%s\'. Not unregistered.\n", a->argv[2]);
16403 }
16404
16405 return CLI_SUCCESS;
16406 }
16407
16408
16409 static int show_chanstats_cb(void *__cur, void *__arg, int flags)
16410 {
16411 #define FORMAT2 "%-15.15s %-11.11s %-8.8s %-10.10s %-10.10s ( %%) %-6.6s %-10.10s %-10.10s ( %%) %-6.6s\n"
16412 #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"
16413 struct sip_pvt *cur = __cur;
16414 unsigned int rxcount, txcount, rxploss, txploss;
16415 char durbuf[10];
16416 int duration;
16417 int durh, durm, durs;
16418 struct ast_channel *c = cur->owner;
16419 struct __show_chan_arg *arg = __arg;
16420 int fd = arg->fd;
16421
16422
16423 if (cur->subscribed != NONE)
16424 return 0;
16425
16426 if (!cur->rtp) {
16427 if (sipdebug)
16428 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");
16429 return 0;
16430 }
16431 rxcount = ast_rtp_get_qosvalue(cur->rtp, AST_RTP_RXCOUNT);
16432 txcount = ast_rtp_get_qosvalue(cur->rtp, AST_RTP_TXCOUNT);
16433 rxploss = ast_rtp_get_qosvalue(cur->rtp, AST_RTP_RXPLOSS);
16434 txploss = ast_rtp_get_qosvalue(cur->rtp, AST_RTP_TXPLOSS);
16435
16436
16437 if (c && c->cdr && !ast_tvzero(c->cdr->start)) {
16438 duration = (int)(ast_tvdiff_ms(ast_tvnow(), c->cdr->start) / 1000);
16439 durh = duration / 3600;
16440 durm = (duration % 3600) / 60;
16441 durs = duration % 60;
16442 snprintf(durbuf, sizeof(durbuf), "%02d:%02d:%02d", durh, durm, durs);
16443 } else {
16444 durbuf[0] = '\0';
16445 }
16446
16447 ast_cli(fd, FORMAT,
16448 ast_inet_ntoa(cur->sa.sin_addr),
16449 cur->callid,
16450 durbuf,
16451 rxcount > (unsigned int) 100000 ? (unsigned int) (rxcount)/(unsigned int) 1000 : rxcount,
16452 rxcount > (unsigned int) 100000 ? "K":" ",
16453 rxploss,
16454 (rxcount + rxploss) > 0 ? (double) rxploss / (rxcount + rxploss) * 100 : 0,
16455 ast_rtp_get_qosvalue(cur->rtp, AST_RTP_RXJITTER),
16456 txcount > (unsigned int) 100000 ? (unsigned int) (txcount)/(unsigned int) 1000 : txcount,
16457 txcount > (unsigned int) 100000 ? "K":" ",
16458 txploss,
16459 txcount > 0 ? (double) txploss / txcount * 100 : 0,
16460 ast_rtp_get_qosvalue(cur->rtp, AST_RTP_TXJITTER)
16461 );
16462 arg->numchans++;
16463
16464 return 0;
16465 }
16466
16467
16468 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16469 {
16470 struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
16471
16472 switch (cmd) {
16473 case CLI_INIT:
16474 e->command = "sip show channelstats";
16475 e->usage =
16476 "Usage: sip show channelstats\n"
16477 " Lists all currently active SIP channel's RTCP statistics.\n"
16478 " Note that calls in the much optimized RTP P2P bridge mode will not show any packets here.";
16479 return NULL;
16480 case CLI_GENERATE:
16481 return NULL;
16482 }
16483
16484 if (a->argc != 3)
16485 return CLI_SHOWUSAGE;
16486
16487 ast_cli(a->fd, FORMAT2, "Peer", "Call ID", "Duration", "Recv: Pack", "Lost", "Jitter", "Send: Pack", "Lost", "Jitter");
16488
16489 ao2_t_callback(dialogs, OBJ_NODATA, show_chanstats_cb, &arg, "callback to sip show chanstats");
16490 ast_cli(a->fd, "%d active SIP channel%s\n", arg.numchans, (arg.numchans != 1) ? "s" : "");
16491 return CLI_SUCCESS;
16492 }
16493 #undef FORMAT
16494 #undef FORMAT2
16495
16496
16497 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16498 {
16499 int realtimepeers;
16500 int realtimeregs;
16501 char codec_buf[SIPBUFSIZE];
16502 const char *msg;
16503
16504 switch (cmd) {
16505 case CLI_INIT:
16506 e->command = "sip show settings";
16507 e->usage =
16508 "Usage: sip show settings\n"
16509 " Provides detailed list of the configuration of the SIP channel.\n";
16510 return NULL;
16511 case CLI_GENERATE:
16512 return NULL;
16513 }
16514
16515
16516 realtimepeers = ast_check_realtime("sippeers");
16517 realtimeregs = ast_check_realtime("sipregs");
16518
16519 if (a->argc != 3)
16520 return CLI_SHOWUSAGE;
16521 ast_cli(a->fd, "\n\nGlobal Settings:\n");
16522 ast_cli(a->fd, "----------------\n");
16523 ast_cli(a->fd, " UDP SIP Port: %d\n", ntohs(bindaddr.sin_port));
16524 ast_cli(a->fd, " UDP Bindaddress: %s\n", ast_inet_ntoa(bindaddr.sin_addr));
16525 ast_cli(a->fd, " TCP SIP Port: ");
16526 if (sip_tcp_desc.local_address.sin_family == AF_INET) {
16527 ast_cli(a->fd, "%d\n", ntohs(sip_tcp_desc.local_address.sin_port));
16528 ast_cli(a->fd, " TCP Bindaddress: %s\n", ast_inet_ntoa(sip_tcp_desc.local_address.sin_addr));
16529 } else {
16530 ast_cli(a->fd, "Disabled\n");
16531 }
16532 ast_cli(a->fd, " TLS SIP Port: ");
16533 if (default_tls_cfg.enabled != FALSE) {
16534 ast_cli(a->fd, "%d\n", ntohs(sip_tls_desc.local_address.sin_port));
16535 ast_cli(a->fd, " TLS Bindaddress: %s\n", ast_inet_ntoa(sip_tls_desc.local_address.sin_addr));
16536 } else {
16537 ast_cli(a->fd, "Disabled\n");
16538 }
16539 ast_cli(a->fd, " Videosupport: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT)));
16540 ast_cli(a->fd, " Textsupport: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT)));
16541 ast_cli(a->fd, " Ignore SDP sess. ver.: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION)));
16542 ast_cli(a->fd, " AutoCreate Peer: %s\n", cli_yesno(sip_cfg.autocreatepeer));
16543 ast_cli(a->fd, " Match Auth Username: %s\n", cli_yesno(global_match_auth_username));
16544 ast_cli(a->fd, " Allow unknown access: %s\n", cli_yesno(sip_cfg.allowguest));
16545 ast_cli(a->fd, " Allow subscriptions: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
16546 ast_cli(a->fd, " Allow overlap dialing: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP)));
16547 ast_cli(a->fd, " Allow promsic. redir: %s\n", cli_yesno(ast_test_flag(&global_flags[0], SIP_PROMISCREDIR)));
16548 ast_cli(a->fd, " Enable call counters: %s\n", cli_yesno(global_callcounter));
16549 ast_cli(a->fd, " SIP domain support: %s\n", cli_yesno(!AST_LIST_EMPTY(&domain_list)));
16550 ast_cli(a->fd, " Realm. auth: %s\n", cli_yesno(authl != NULL));
16551 ast_cli(a->fd, " Our auth realm %s\n", sip_cfg.realm);
16552 ast_cli(a->fd, " Call to non-local dom.: %s\n", cli_yesno(sip_cfg.allow_external_domains));
16553 ast_cli(a->fd, " URI user is phone no: %s\n", cli_yesno(ast_test_flag(&global_flags[0], SIP_USEREQPHONE)));
16554 ast_cli(a->fd, " Always auth rejects: %s\n", cli_yesno(sip_cfg.alwaysauthreject));
16555 ast_cli(a->fd, " Direct RTP setup: %s\n", cli_yesno(sip_cfg.directrtpsetup));
16556 ast_cli(a->fd, " User Agent: %s\n", global_useragent);
16557 ast_cli(a->fd, " SDP Session Name: %s\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
16558 ast_cli(a->fd, " SDP Owner Name: %s\n", ast_strlen_zero(global_sdpowner) ? "-" : global_sdpowner);
16559 ast_cli(a->fd, " Reg. context: %s\n", S_OR(global_regcontext, "(not set)"));
16560 ast_cli(a->fd, " Regexten on Qualify: %s\n", cli_yesno(sip_cfg.regextenonqualify));
16561 ast_cli(a->fd, " Caller ID: %s\n", default_callerid);
16562 ast_cli(a->fd, " From: Domain: %s\n", default_fromdomain);
16563 ast_cli(a->fd, " Record SIP history: %s\n", recordhistory ? "On" : "Off");
16564 ast_cli(a->fd, " Call Events: %s\n", sip_cfg.callevents ? "On" : "Off");
16565 ast_cli(a->fd, " Auth. Failure Events: %s\n", global_authfailureevents ? "On" : "Off");
16566
16567 ast_cli(a->fd, " T.38 support: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
16568 ast_cli(a->fd, " T.38 EC mode: %s\n", faxec2str(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
16569 ast_cli(a->fd, " T.38 MaxDtgrm: %d\n", global_t38_maxdatagram);
16570
16571 if (!realtimepeers && !realtimeregs)
16572 ast_cli(a->fd, " SIP realtime: Disabled\n" );
16573 else
16574 ast_cli(a->fd, " SIP realtime: Enabled\n" );
16575 ast_cli(a->fd, " Qualify Freq : %d ms\n", global_qualifyfreq);
16576 ast_cli(a->fd, "\nNetwork QoS Settings:\n");
16577 ast_cli(a->fd, "---------------------------\n");
16578 ast_cli(a->fd, " IP ToS SIP: %s\n", ast_tos2str(global_tos_sip));
16579 ast_cli(a->fd, " IP ToS RTP audio: %s\n", ast_tos2str(global_tos_audio));
16580 ast_cli(a->fd, " IP ToS RTP video: %s\n", ast_tos2str(global_tos_video));
16581 ast_cli(a->fd, " IP ToS RTP text: %s\n", ast_tos2str(global_tos_text));
16582 ast_cli(a->fd, " 802.1p CoS SIP: %d\n", global_cos_sip);
16583 ast_cli(a->fd, " 802.1p CoS RTP audio: %d\n", global_cos_audio);
16584 ast_cli(a->fd, " 802.1p CoS RTP video: %d\n", global_cos_video);
16585 ast_cli(a->fd, " 802.1p CoS RTP text: %d\n", global_cos_text);
16586 ast_cli(a->fd, " Jitterbuffer enabled: %s\n", cli_yesno(ast_test_flag(&global_jbconf, AST_JB_ENABLED)));
16587 ast_cli(a->fd, " Jitterbuffer forced: %s\n", cli_yesno(ast_test_flag(&global_jbconf, AST_JB_FORCED)));
16588 ast_cli(a->fd, " Jitterbuffer max size: %ld\n", global_jbconf.max_size);
16589 ast_cli(a->fd, " Jitterbuffer resync: %ld\n", global_jbconf.resync_threshold);
16590 ast_cli(a->fd, " Jitterbuffer impl: %s\n", global_jbconf.impl);
16591 ast_cli(a->fd, " Jitterbuffer log: %s\n", cli_yesno(ast_test_flag(&global_jbconf, AST_JB_LOG)));
16592
16593 ast_cli(a->fd, "\nNetwork Settings:\n");
16594 ast_cli(a->fd, "---------------------------\n");
16595
16596 if (localaddr == NULL)
16597 msg = "Disabled, no localnet list";
16598 else if (externip.sin_addr.s_addr == 0)
16599 msg = "Disabled, externip is 0.0.0.0";
16600 else if (stunaddr.sin_addr.s_addr != 0)
16601 msg = "Enabled using STUN";
16602 else if (!ast_strlen_zero(externhost))
16603 msg = "Enabled using externhost";
16604 else
16605 msg = "Enabled using externip";
16606 ast_cli(a->fd, " SIP address remapping: %s\n", msg);
16607 ast_cli(a->fd, " Externhost: %s\n", S_OR(externhost, "<none>"));
16608 ast_cli(a->fd, " Externip: %s:%d\n", ast_inet_ntoa(externip.sin_addr), ntohs(externip.sin_port));
16609 ast_cli(a->fd, " Externrefresh: %d\n", externrefresh);
16610 {
16611 struct ast_ha *d;
16612 const char *prefix = "Localnet:";
16613 char buf[INET_ADDRSTRLEN];
16614
16615 for (d = localaddr; d ; prefix = "", d = d->next) {
16616 ast_cli(a->fd, " %-24s%s/%s\n",
16617 prefix, ast_inet_ntoa(d->netaddr),
16618 inet_ntop(AF_INET, &d->netmask, buf, sizeof(buf)) );
16619 }
16620 }
16621 ast_cli(a->fd, " STUN server: %s:%d\n", ast_inet_ntoa(stunaddr.sin_addr), ntohs(stunaddr.sin_port));
16622
16623 ast_cli(a->fd, "\nGlobal Signalling Settings:\n");
16624 ast_cli(a->fd, "---------------------------\n");
16625 ast_cli(a->fd, " Codecs: ");
16626 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, global_capability);
16627 ast_cli(a->fd, "%s\n", codec_buf);
16628 ast_cli(a->fd, " Codec Order: ");
16629 print_codec_to_cli(a->fd, &default_prefs);
16630 ast_cli(a->fd, "\n");
16631 ast_cli(a->fd, " Relax DTMF: %s\n", cli_yesno(global_relaxdtmf));
16632 ast_cli(a->fd, " RFC2833 Compensation: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_RFC2833_COMPENSATE)));
16633 ast_cli(a->fd, " Compact SIP headers: %s\n", cli_yesno(sip_cfg.compactheaders));
16634 ast_cli(a->fd, " RTP Keepalive: %d %s\n", global_rtpkeepalive, global_rtpkeepalive ? "" : "(Disabled)" );
16635 ast_cli(a->fd, " RTP Timeout: %d %s\n", global_rtptimeout, global_rtptimeout ? "" : "(Disabled)" );
16636 ast_cli(a->fd, " RTP Hold Timeout: %d %s\n", global_rtpholdtimeout, global_rtpholdtimeout ? "" : "(Disabled)");
16637 ast_cli(a->fd, " MWI NOTIFY mime type: %s\n", default_notifymime);
16638 ast_cli(a->fd, " DNS SRV lookup: %s\n", cli_yesno(sip_cfg.srvlookup));
16639 ast_cli(a->fd, " Pedantic SIP support: %s\n", cli_yesno(sip_cfg.pedanticsipchecking));
16640 ast_cli(a->fd, " Reg. min duration %d secs\n", min_expiry);
16641 ast_cli(a->fd, " Reg. max duration: %d secs\n", max_expiry);
16642 ast_cli(a->fd, " Reg. default duration: %d secs\n", default_expiry);
16643 ast_cli(a->fd, " Outbound reg. timeout: %d secs\n", global_reg_timeout);
16644 ast_cli(a->fd, " Outbound reg. attempts: %d\n", global_regattempts_max);
16645 ast_cli(a->fd, " Notify ringing state: %s\n", cli_yesno(sip_cfg.notifyringing));
16646 if (sip_cfg.notifyringing) {
16647 ast_cli(a->fd, " Include CID: %s%s\n",
16648 cli_yesno(sip_cfg.notifycid),
16649 sip_cfg.notifycid == IGNORE_CONTEXT ? " (Ignoring context)" : "");
16650 }
16651 ast_cli(a->fd, " Notify hold state: %s\n", cli_yesno(sip_cfg.notifyhold));
16652 ast_cli(a->fd, " SIP Transfer mode: %s\n", transfermode2str(sip_cfg.allowtransfer));
16653 ast_cli(a->fd, " Max Call Bitrate: %d kbps\n", default_maxcallbitrate);
16654 ast_cli(a->fd, " Auto-Framing: %s\n", cli_yesno(global_autoframing));
16655 ast_cli(a->fd, " Outb. proxy: %s %s\n", ast_strlen_zero(sip_cfg.outboundproxy.name) ? "<not set>" : sip_cfg.outboundproxy.name,
16656 sip_cfg.outboundproxy.force ? "(forced)" : "");
16657 ast_cli(a->fd, " Session Timers: %s\n", stmode2str(global_st_mode));
16658 ast_cli(a->fd, " Session Refresher: %s\n", strefresher2str (global_st_refresher));
16659 ast_cli(a->fd, " Session Expires: %d secs\n", global_max_se);
16660 ast_cli(a->fd, " Session Min-SE: %d secs\n", global_min_se);
16661 ast_cli(a->fd, " Timer T1: %d\n", global_t1);
16662 ast_cli(a->fd, " Timer T1 minimum: %d\n", global_t1min);
16663 ast_cli(a->fd, " Timer B: %d\n", global_timer_b);
16664 ast_cli(a->fd, " No premature media: %s\n", global_prematuremediafilter ? "Yes" : "No");
16665
16666 ast_cli(a->fd, "\nDefault Settings:\n");
16667 ast_cli(a->fd, "-----------------\n");
16668 ast_cli(a->fd, " Allowed transports: %s\n", get_transport_list(default_transports));
16669 ast_cli(a->fd, " Outbound transport: %s\n", get_transport(default_primary_transport));
16670 ast_cli(a->fd, " Context: %s\n", sip_cfg.default_context);
16671 ast_cli(a->fd, " Nat: %s\n", nat2str(ast_test_flag(&global_flags[0], SIP_NAT)));
16672 ast_cli(a->fd, " DTMF: %s\n", dtmfmode2str(ast_test_flag(&global_flags[0], SIP_DTMF)));
16673 ast_cli(a->fd, " Qualify: %d\n", default_qualify);
16674 ast_cli(a->fd, " Use ClientCode: %s\n", cli_yesno(ast_test_flag(&global_flags[0], SIP_USECLIENTCODE)));
16675 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" );
16676 ast_cli(a->fd, " Language: %s\n", default_language);
16677 ast_cli(a->fd, " MOH Interpret: %s\n", default_mohinterpret);
16678 ast_cli(a->fd, " MOH Suggest: %s\n", default_mohsuggest);
16679 ast_cli(a->fd, " Voice Mail Extension: %s\n", default_vmexten);
16680 ast_cli(a->fd, " Forward Detected Loops: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_FORWARD_LOOP_DETECTED)));
16681
16682 if (realtimepeers || realtimeregs) {
16683 ast_cli(a->fd, "\nRealtime SIP Settings:\n");
16684 ast_cli(a->fd, "----------------------\n");
16685 ast_cli(a->fd, " Realtime Peers: %s\n", cli_yesno(realtimepeers));
16686 ast_cli(a->fd, " Realtime Regs: %s\n", cli_yesno(realtimeregs));
16687 ast_cli(a->fd, " Cache Friends: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)));
16688 ast_cli(a->fd, " Update: %s\n", cli_yesno(sip_cfg.peer_rtupdate));
16689 ast_cli(a->fd, " Ignore Reg. Expire: %s\n", cli_yesno(sip_cfg.ignore_regexpire));
16690 ast_cli(a->fd, " Save sys. name: %s\n", cli_yesno(sip_cfg.rtsave_sysname));
16691 ast_cli(a->fd, " Auto Clear: %d (%s)\n", sip_cfg.rtautoclear, ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR) ? "Enabled" : "Disabled");
16692 }
16693 ast_cli(a->fd, "\n----\n");
16694 return CLI_SUCCESS;
16695 }
16696
16697 static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16698 {
16699 #define FORMAT "%-30.30s %-12.12s %-10.10s %-10.10s\n"
16700 char host[80];
16701
16702 switch (cmd) {
16703 case CLI_INIT:
16704 e->command = "sip show mwi";
16705 e->usage =
16706 "Usage: sip show mwi\n"
16707 " Provides a list of MWI subscriptions and status.\n";
16708 return NULL;
16709 case CLI_GENERATE:
16710 return NULL;
16711 }
16712
16713 ast_cli(a->fd, FORMAT, "Host", "Username", "Mailbox", "Subscribed");
16714
16715 ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
16716 ASTOBJ_RDLOCK(iterator);
16717 snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
16718 ast_cli(a->fd, FORMAT, host, iterator->username, iterator->mailbox, iterator->subscribed ? "Yes" : "No");
16719 ASTOBJ_UNLOCK(iterator);
16720 } while(0));
16721
16722 return CLI_SUCCESS;
16723 #undef FORMAT
16724 }
16725
16726
16727
16728 static const char *subscription_type2str(enum subscriptiontype subtype)
16729 {
16730 int i;
16731
16732 for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
16733 if (subscription_types[i].type == subtype) {
16734 return subscription_types[i].text;
16735 }
16736 }
16737 return subscription_types[0].text;
16738 }
16739
16740
16741 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype)
16742 {
16743 int i;
16744
16745 for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
16746 if (subscription_types[i].type == subtype) {
16747 return &subscription_types[i];
16748 }
16749 }
16750 return &subscription_types[0];
16751 }
16752
16753
16754
16755
16756
16757
16758
16759
16760 #define FORMAT4 "%-15.15s %-15.15s %-15.15s %-15.15s %-13.13s %-15.15s %-10.10s %-6.6d\n"
16761 #define FORMAT3 "%-15.15s %-15.15s %-15.15s %-15.15s %-13.13s %-15.15s %-10.10s %-6.6s\n"
16762 #define FORMAT2 "%-15.15s %-15.15s %-15.15s %-15.15s %-7.7s %-15.15s %-6.6s\n"
16763 #define FORMAT "%-15.15s %-15.15s %-15.15s %-15.15s %-3.3s %-3.3s %-15.15s %-10.10s\n"
16764
16765
16766 static int show_channels_cb(void *__cur, void *__arg, int flags)
16767 {
16768 struct sip_pvt *cur = __cur;
16769 struct __show_chan_arg *arg = __arg;
16770 const struct sockaddr_in *dst = sip_real_dst(cur);
16771
16772
16773 if (cur->subscribed == NONE && !arg->subscriptions) {
16774
16775 const char *referstatus = cur->refer ? referstatus2str(cur->refer->status) : "";
16776 char formatbuf[SIPBUFSIZE/2];
16777
16778 ast_cli(arg->fd, FORMAT, ast_inet_ntoa(dst->sin_addr),
16779 S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
16780 cur->callid,
16781 ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0),
16782 cli_yesno(ast_test_flag(&cur->flags[1], SIP_PAGE2_CALL_ONHOLD)),
16783 cur->needdestroy ? "(d)" : "",
16784 cur->lastmsg ,
16785 referstatus
16786 );
16787 arg->numchans++;
16788 }
16789 if (cur->subscribed != NONE && arg->subscriptions) {
16790 struct ast_str *mailbox_str = ast_str_alloca(512);
16791 if (cur->subscribed == MWI_NOTIFICATION && cur->relatedpeer)
16792 peer_mailboxes_to_str(&mailbox_str, cur->relatedpeer);
16793 ast_cli(arg->fd, FORMAT4, ast_inet_ntoa(dst->sin_addr),
16794 S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
16795 cur->callid,
16796
16797 cur->subscribed == MWI_NOTIFICATION ? "--" : cur->subscribeuri,
16798 cur->subscribed == MWI_NOTIFICATION ? "<none>" : ast_extension_state2str(cur->laststate),
16799 subscription_type2str(cur->subscribed),
16800 cur->subscribed == MWI_NOTIFICATION ? S_OR(mailbox_str->str, "<none>") : "<none>",
16801 cur->expiry
16802 );
16803 arg->numchans++;
16804 }
16805 return 0;
16806 }
16807
16808
16809
16810
16811
16812
16813 static char *sip_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16814 {
16815 struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
16816
16817
16818 if (cmd == CLI_INIT) {
16819 e->command = "sip show {channels|subscriptions}";
16820 e->usage =
16821 "Usage: sip show channels\n"
16822 " Lists all currently active SIP calls (dialogs).\n"
16823 "Usage: sip show subscriptions\n"
16824 " Lists active SIP subscriptions.\n";
16825 return NULL;
16826 } else if (cmd == CLI_GENERATE)
16827 return NULL;
16828
16829 if (a->argc != e->args)
16830 return CLI_SHOWUSAGE;
16831 arg.subscriptions = !strcasecmp(a->argv[e->args - 1], "subscriptions");
16832 if (!arg.subscriptions)
16833 ast_cli(arg.fd, FORMAT2, "Peer", "User/ANR", "Call ID", "Format", "Hold", "Last Message", "Expiry");
16834 else
16835 ast_cli(arg.fd, FORMAT3, "Peer", "User", "Call ID", "Extension", "Last state", "Type", "Mailbox", "Expiry");
16836
16837
16838 ao2_t_callback(dialogs, OBJ_NODATA, show_channels_cb, &arg, "callback to show channels");
16839
16840
16841 ast_cli(arg.fd, "%d active SIP %s%s\n", arg.numchans,
16842 (arg.subscriptions ? "subscription" : "dialog"),
16843 ESS(arg.numchans));
16844 return CLI_SUCCESS;
16845 #undef FORMAT
16846 #undef FORMAT2
16847 #undef FORMAT3
16848 }
16849
16850
16851
16852
16853
16854
16855 static char *complete_sipch(const char *line, const char *word, int pos, int state)
16856 {
16857 int which=0;
16858 struct sip_pvt *cur;
16859 char *c = NULL;
16860 int wordlen = strlen(word);
16861 struct ao2_iterator i;
16862
16863 if (pos != 3) {
16864 return NULL;
16865 }
16866
16867 i = ao2_iterator_init(dialogs, 0);
16868 while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
16869 sip_pvt_lock(cur);
16870 if (!strncasecmp(word, cur->callid, wordlen) && ++which > state) {
16871 c = ast_strdup(cur->callid);
16872 sip_pvt_unlock(cur);
16873 dialog_unref(cur, "drop ref in iterator loop break");
16874 break;
16875 }
16876 sip_pvt_unlock(cur);
16877 dialog_unref(cur, "drop ref in iterator loop");
16878 }
16879 ao2_iterator_destroy(&i);
16880 return c;
16881 }
16882
16883
16884
16885 static char *complete_sip_peer(const char *word, int state, int flags2)
16886 {
16887 char *result = NULL;
16888 int wordlen = strlen(word);
16889 int which = 0;
16890 struct ao2_iterator i = ao2_iterator_init(peers, 0);
16891 struct sip_peer *peer;
16892
16893 while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
16894
16895 if (!strncasecmp(word, peer->name, wordlen) &&
16896 (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
16897 ++which > state)
16898 result = ast_strdup(peer->name);
16899 unref_peer(peer, "toss iterator peer ptr before break");
16900 if (result) {
16901 break;
16902 }
16903 }
16904 ao2_iterator_destroy(&i);
16905 return result;
16906 }
16907
16908
16909 static char *complete_sip_registered_peer(const char *word, int state, int flags2)
16910 {
16911 char *result = NULL;
16912 int wordlen = strlen(word);
16913 int which = 0;
16914 struct ao2_iterator i;
16915 struct sip_peer *peer;
16916
16917 i = ao2_iterator_init(peers, 0);
16918 while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
16919 if (!strncasecmp(word, peer->name, wordlen) &&
16920 (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
16921 ++which > state && peer->expire > 0)
16922 result = ast_strdup(peer->name);
16923 if (result) {
16924 unref_peer(peer, "toss iterator peer ptr before break");
16925 break;
16926 }
16927 unref_peer(peer, "toss iterator peer ptr");
16928 }
16929 ao2_iterator_destroy(&i);
16930 return result;
16931 }
16932
16933
16934 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state)
16935 {
16936 if (pos == 3)
16937 return complete_sipch(line, word, pos, state);
16938
16939 return NULL;
16940 }
16941
16942
16943 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state)
16944 {
16945 if (pos == 3) {
16946 return complete_sip_peer(word, state, 0);
16947 }
16948
16949 return NULL;
16950 }
16951
16952
16953 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state)
16954 {
16955 if (pos == 2)
16956 return complete_sip_registered_peer(word, state, 0);
16957
16958 return NULL;
16959 }
16960
16961
16962 static char *complete_sipnotify(const char *line, const char *word, int pos, int state)
16963 {
16964 char *c = NULL;
16965
16966 if (pos == 2) {
16967 int which = 0;
16968 char *cat = NULL;
16969 int wordlen = strlen(word);
16970
16971
16972
16973 if (!notify_types)
16974 return NULL;
16975
16976 while ( (cat = ast_category_browse(notify_types, cat)) ) {
16977 if (!strncasecmp(word, cat, wordlen) && ++which > state) {
16978 c = ast_strdup(cat);
16979 break;
16980 }
16981 }
16982 return c;
16983 }
16984
16985 if (pos > 2)
16986 return complete_sip_peer(word, state, 0);
16987
16988 return NULL;
16989 }
16990
16991
16992 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16993 {
16994 struct sip_pvt *cur;
16995 size_t len;
16996 int found = 0;
16997 struct ao2_iterator i;
16998
16999 switch (cmd) {
17000 case CLI_INIT:
17001 e->command = "sip show channel";
17002 e->usage =
17003 "Usage: sip show channel <call-id>\n"
17004 " Provides detailed status on a given SIP dialog (identified by SIP call-id).\n";
17005 return NULL;
17006 case CLI_GENERATE:
17007 return complete_sipch(a->line, a->word, a->pos, a->n);
17008 }
17009
17010 if (a->argc != 4)
17011 return CLI_SHOWUSAGE;
17012 len = strlen(a->argv[3]);
17013
17014 i = ao2_iterator_init(dialogs, 0);
17015 while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
17016 sip_pvt_lock(cur);
17017
17018 if (!strncasecmp(cur->callid, a->argv[3], len)) {
17019 char formatbuf[SIPBUFSIZE/2];
17020 ast_cli(a->fd, "\n");
17021 if (cur->subscribed != NONE)
17022 ast_cli(a->fd, " * Subscription (type: %s)\n", subscription_type2str(cur->subscribed));
17023 else
17024 ast_cli(a->fd, " * SIP Call\n");
17025 ast_cli(a->fd, " Curr. trans. direction: %s\n", ast_test_flag(&cur->flags[0], SIP_OUTGOING) ? "Outgoing" : "Incoming");
17026 ast_cli(a->fd, " Call-ID: %s\n", cur->callid);
17027 ast_cli(a->fd, " Owner channel ID: %s\n", cur->owner ? cur->owner->name : "<none>");
17028 ast_cli(a->fd, " Our Codec Capability: %d\n", cur->capability);
17029 ast_cli(a->fd, " Non-Codec Capability (DTMF): %d\n", cur->noncodeccapability);
17030 ast_cli(a->fd, " Their Codec Capability: %d\n", cur->peercapability);
17031 ast_cli(a->fd, " Joint Codec Capability: %d\n", cur->jointcapability);
17032 ast_cli(a->fd, " Format: %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0) );
17033 ast_cli(a->fd, " T.38 support %s\n", cli_yesno(cur->udptl != NULL));
17034 ast_cli(a->fd, " Video support %s\n", cli_yesno(cur->vrtp != NULL));
17035 ast_cli(a->fd, " MaxCallBR: %d kbps\n", cur->maxcallbitrate);
17036 ast_cli(a->fd, " Theoretical Address: %s:%d\n", ast_inet_ntoa(cur->sa.sin_addr), ntohs(cur->sa.sin_port));
17037 ast_cli(a->fd, " Received Address: %s:%d\n", ast_inet_ntoa(cur->recv.sin_addr), ntohs(cur->recv.sin_port));
17038 ast_cli(a->fd, " SIP Transfer mode: %s\n", transfermode2str(cur->allowtransfer));
17039 ast_cli(a->fd, " NAT Support: %s\n", nat2str(ast_test_flag(&cur->flags[0], SIP_NAT)));
17040 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)" );
17041 ast_cli(a->fd, " Our Tag: %s\n", cur->tag);
17042 ast_cli(a->fd, " Their Tag: %s\n", cur->theirtag);
17043 ast_cli(a->fd, " SIP User agent: %s\n", cur->useragent);
17044 if (!ast_strlen_zero(cur->username))
17045 ast_cli(a->fd, " Username: %s\n", cur->username);
17046 if (!ast_strlen_zero(cur->peername))
17047 ast_cli(a->fd, " Peername: %s\n", cur->peername);
17048 if (!ast_strlen_zero(cur->uri))
17049 ast_cli(a->fd, " Original uri: %s\n", cur->uri);
17050 if (!ast_strlen_zero(cur->cid_num))
17051 ast_cli(a->fd, " Caller-ID: %s\n", cur->cid_num);
17052 ast_cli(a->fd, " Need Destroy: %s\n", cli_yesno(cur->needdestroy));
17053 ast_cli(a->fd, " Last Message: %s\n", cur->lastmsg);
17054 ast_cli(a->fd, " Promiscuous Redir: %s\n", cli_yesno(ast_test_flag(&cur->flags[0], SIP_PROMISCREDIR)));
17055 ast_cli(a->fd, " Route: %s\n", cur->route ? cur->route->hop : "N/A");
17056 ast_cli(a->fd, " DTMF Mode: %s\n", dtmfmode2str(ast_test_flag(&cur->flags[0], SIP_DTMF)));
17057 ast_cli(a->fd, " SIP Options: ");
17058 if (cur->sipoptions) {
17059 int x;
17060 for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
17061 if (cur->sipoptions & sip_options[x].id)
17062 ast_cli(a->fd, "%s ", sip_options[x].text);
17063 }
17064 ast_cli(a->fd, "\n");
17065 } else
17066 ast_cli(a->fd, "(none)\n");
17067
17068 if (!cur->stimer)
17069 ast_cli(a->fd, " Session-Timer: Uninitiallized\n");
17070 else {
17071 ast_cli(a->fd, " Session-Timer: %s\n", cur->stimer->st_active ? "Active" : "Inactive");
17072 if (cur->stimer->st_active == TRUE) {
17073 ast_cli(a->fd, " S-Timer Interval: %d\n", cur->stimer->st_interval);
17074 ast_cli(a->fd, " S-Timer Refresher: %s\n", strefresher2str(cur->stimer->st_ref));
17075 ast_cli(a->fd, " S-Timer Expirys: %d\n", cur->stimer->st_expirys);
17076 ast_cli(a->fd, " S-Timer Sched Id: %d\n", cur->stimer->st_schedid);
17077 ast_cli(a->fd, " S-Timer Peer Sts: %s\n", cur->stimer->st_active_peer_ua ? "Active" : "Inactive");
17078 ast_cli(a->fd, " S-Timer Cached Min-SE: %d\n", cur->stimer->st_cached_min_se);
17079 ast_cli(a->fd, " S-Timer Cached SE: %d\n", cur->stimer->st_cached_max_se);
17080 ast_cli(a->fd, " S-Timer Cached Ref: %s\n", strefresher2str(cur->stimer->st_cached_ref));
17081 ast_cli(a->fd, " S-Timer Cached Mode: %s\n", stmode2str(cur->stimer->st_cached_mode));
17082 }
17083 }
17084
17085 ast_cli(a->fd, "\n\n");
17086
17087 found++;
17088 }
17089
17090 sip_pvt_unlock(cur);
17091
17092 ao2_t_ref(cur, -1, "toss dialog ptr set by iterator_next");
17093 }
17094 ao2_iterator_destroy(&i);
17095
17096 if (!found)
17097 ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
17098
17099 return CLI_SUCCESS;
17100 }
17101
17102
17103 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17104 {
17105 struct sip_pvt *cur;
17106 size_t len;
17107 int found = 0;
17108 struct ao2_iterator i;
17109
17110 switch (cmd) {
17111 case CLI_INIT:
17112 e->command = "sip show history";
17113 e->usage =
17114 "Usage: sip show history <call-id>\n"
17115 " Provides detailed dialog history on a given SIP call (specified by call-id).\n";
17116 return NULL;
17117 case CLI_GENERATE:
17118 return complete_sip_show_history(a->line, a->word, a->pos, a->n);
17119 }
17120
17121 if (a->argc != 4)
17122 return CLI_SHOWUSAGE;
17123
17124 if (!recordhistory)
17125 ast_cli(a->fd, "\n***Note: History recording is currently DISABLED. Use 'sip set history on' to ENABLE.\n");
17126
17127 len = strlen(a->argv[3]);
17128
17129 i = ao2_iterator_init(dialogs, 0);
17130 while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
17131 sip_pvt_lock(cur);
17132 if (!strncasecmp(cur->callid, a->argv[3], len)) {
17133 struct sip_history *hist;
17134 int x = 0;
17135
17136 ast_cli(a->fd, "\n");
17137 if (cur->subscribed != NONE)
17138 ast_cli(a->fd, " * Subscription\n");
17139 else
17140 ast_cli(a->fd, " * SIP Call\n");
17141 if (cur->history)
17142 AST_LIST_TRAVERSE(cur->history, hist, list)
17143 ast_cli(a->fd, "%d. %s\n", ++x, hist->event);
17144 if (x == 0)
17145 ast_cli(a->fd, "Call '%s' has no history\n", cur->callid);
17146 found++;
17147 }
17148 sip_pvt_unlock(cur);
17149 ao2_t_ref(cur, -1, "toss dialog ptr from iterator_next");
17150 }
17151 ao2_iterator_destroy(&i);
17152
17153 if (!found)
17154 ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
17155
17156 return CLI_SUCCESS;
17157 }
17158
17159
17160 static void sip_dump_history(struct sip_pvt *dialog)
17161 {
17162 int x = 0;
17163 struct sip_history *hist;
17164 static int errmsg = 0;
17165
17166 if (!dialog)
17167 return;
17168
17169 if (!option_debug && !sipdebug) {
17170 if (!errmsg) {
17171 ast_log(LOG_NOTICE, "You must have debugging enabled (SIP or Asterisk) in order to dump SIP history.\n");
17172 errmsg = 1;
17173 }
17174 return;
17175 }
17176
17177 ast_debug(1, "\n---------- SIP HISTORY for '%s' \n", dialog->callid);
17178 if (dialog->subscribed)
17179 ast_debug(1, " * Subscription\n");
17180 else
17181 ast_debug(1, " * SIP Call\n");
17182 if (dialog->history)
17183 AST_LIST_TRAVERSE(dialog->history, hist, list)
17184 ast_debug(1, " %-3.3d. %s\n", ++x, hist->event);
17185 if (!x)
17186 ast_debug(1, "Call '%s' has no history\n", dialog->callid);
17187 ast_debug(1, "\n---------- END SIP HISTORY for '%s' \n", dialog->callid);
17188 }
17189
17190
17191
17192 static void handle_request_info(struct sip_pvt *p, struct sip_request *req)
17193 {
17194 char buf[1024];
17195 unsigned int event;
17196 const char *c = get_header(req, "Content-Type");
17197
17198
17199 if (!strcasecmp(c, "application/dtmf-relay") ||
17200 !strcasecmp(c, "application/vnd.nortelnetworks.digits")) {
17201 unsigned int duration = 0;
17202
17203 if (!p->owner) {
17204 transmit_response(p, "481 Call leg/transaction does not exist", req);
17205 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17206 return;
17207 }
17208
17209
17210 if (ast_strlen_zero(c = get_body(req, "Signal", '=')) && ast_strlen_zero(c = get_body(req, "d", '='))) {
17211 ast_log(LOG_WARNING, "Unable to retrieve DTMF signal from INFO message from %s\n", p->callid);
17212 transmit_response(p, "200 OK", req);
17213 return;
17214 } else {
17215 ast_copy_string(buf, c, sizeof(buf));
17216 }
17217
17218 if (!ast_strlen_zero((c = get_body(req, "Duration", '='))))
17219 duration = atoi(c);
17220 if (!duration)
17221 duration = 100;
17222
17223
17224 if (ast_strlen_zero(buf)) {
17225 transmit_response(p, "200 OK", req);
17226 return;
17227 }
17228
17229 if (buf[0] == '*')
17230 event = 10;
17231 else if (buf[0] == '#')
17232 event = 11;
17233 else if ((buf[0] >= 'A') && (buf[0] <= 'D'))
17234 event = 12 + buf[0] - 'A';
17235 else if (buf[0] == '!')
17236 event = 16;
17237 else
17238 event = atoi(buf);
17239 if (event == 16) {
17240
17241 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_FLASH, };
17242 ast_queue_frame(p->owner, &f);
17243 if (sipdebug)
17244 ast_verbose("* DTMF-relay event received: FLASH\n");
17245 } else {
17246
17247 struct ast_frame f = { AST_FRAME_DTMF, };
17248 if (event < 10) {
17249 f.subclass = '0' + event;
17250 } else if (event < 11) {
17251 f.subclass = '*';
17252 } else if (event < 12) {
17253 f.subclass = '#';
17254 } else if (event < 16) {
17255 f.subclass = 'A' + (event - 12);
17256 }
17257 f.len = duration;
17258 ast_queue_frame(p->owner, &f);
17259 if (sipdebug)
17260 ast_verbose("* DTMF-relay event received: %c\n", f.subclass);
17261 }
17262 transmit_response(p, "200 OK", req);
17263 return;
17264 } else if (!strcasecmp(c, "application/dtmf")) {
17265
17266 unsigned int duration = 0;
17267
17268 if (!p->owner) {
17269 transmit_response(p, "481 Call leg/transaction does not exist", req);
17270 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17271 return;
17272 }
17273
17274 get_msg_text(buf, sizeof(buf), req, TRUE);
17275 duration = 100;
17276
17277 if (ast_strlen_zero(buf)) {
17278 transmit_response(p, "200 OK", req);
17279 return;
17280 }
17281 event = atoi(buf);
17282 if (event == 16) {
17283
17284 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_FLASH, };
17285 ast_queue_frame(p->owner, &f);
17286 if (sipdebug)
17287 ast_verbose("* DTMF-relay event received: FLASH\n");
17288 } else {
17289
17290 struct ast_frame f = { AST_FRAME_DTMF, };
17291 if (event < 10) {
17292 f.subclass = '0' + event;
17293 } else if (event < 11) {
17294 f.subclass = '*';
17295 } else if (event < 12) {
17296 f.subclass = '#';
17297 } else if (event < 16) {
17298 f.subclass = 'A' + (event - 12);
17299 }
17300 f.len = duration;
17301 ast_queue_frame(p->owner, &f);
17302 if (sipdebug)
17303 ast_verbose("* DTMF-relay event received: %c\n", f.subclass);
17304 }
17305 transmit_response(p, "200 OK", req);
17306 return;
17307
17308 } else if (!strcasecmp(c, "application/media_control+xml")) {
17309
17310 if (p->owner)
17311 ast_queue_control(p->owner, AST_CONTROL_VIDUPDATE);
17312 transmit_response(p, "200 OK", req);
17313 return;
17314 } else if (!ast_strlen_zero(c = get_header(req, "X-ClientCode"))) {
17315
17316 if (ast_test_flag(&p->flags[0], SIP_USECLIENTCODE)) {
17317 if (p->owner && p->owner->cdr)
17318 ast_cdr_setuserfield(p->owner, c);
17319 if (p->owner && ast_bridged_channel(p->owner) && ast_bridged_channel(p->owner)->cdr)
17320 ast_cdr_setuserfield(ast_bridged_channel(p->owner), c);
17321 transmit_response(p, "200 OK", req);
17322 } else {
17323 transmit_response(p, "403 Forbidden", req);
17324 }
17325 return;
17326 } else if (!ast_strlen_zero(c = get_header(req, "Record"))) {
17327
17328
17329
17330
17331
17332
17333
17334 struct ast_call_feature *feat;
17335 int j;
17336 struct ast_frame f = { AST_FRAME_DTMF, };
17337
17338 ast_rdlock_call_features();
17339 feat = ast_find_call_feature("automon");
17340 if (!feat || ast_strlen_zero(feat->exten)) {
17341 ast_log(LOG_WARNING, "Recording requested, but no One Touch Monitor registered. (See features.conf)\n");
17342
17343 transmit_response(p, "403 Forbidden", req);
17344 ast_unlock_call_features();
17345 return;
17346 }
17347
17348 f.len = 100;
17349 for (j=0; j < strlen(feat->exten); j++) {
17350 f.subclass = feat->exten[j];
17351 ast_queue_frame(p->owner, &f);
17352 if (sipdebug)
17353 ast_verbose("* DTMF-relay event faked: %c\n", f.subclass);
17354 }
17355 ast_unlock_call_features();
17356
17357 ast_debug(1, "Got a Request to Record the channel, state %s\n", c);
17358 transmit_response(p, "200 OK", req);
17359 return;
17360 } else if (ast_strlen_zero(c = get_header(req, "Content-Length")) || !strcasecmp(c, "0")) {
17361
17362 transmit_response(p, "200 OK", req);
17363 return;
17364 }
17365
17366
17367
17368
17369 ast_log(LOG_WARNING, "Unable to parse INFO message from %s. Content %s\n", p->callid, buf);
17370 transmit_response(p, "415 Unsupported media type", req);
17371 return;
17372 }
17373
17374
17375 static char *sip_do_debug_ip(int fd, char *arg)
17376 {
17377 struct hostent *hp;
17378 struct ast_hostent ahp;
17379 int port = 0;
17380 char *p;
17381
17382 p = arg;
17383 strsep(&p, ":");
17384 if (p)
17385 port = atoi(p);
17386 hp = ast_gethostbyname(arg, &ahp);
17387 if (hp == NULL)
17388 return CLI_SHOWUSAGE;
17389
17390 debugaddr.sin_family = AF_INET;
17391 memcpy(&debugaddr.sin_addr, hp->h_addr, sizeof(debugaddr.sin_addr));
17392 debugaddr.sin_port = htons(port);
17393 if (port == 0)
17394 ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_inet_ntoa(debugaddr.sin_addr));
17395 else
17396 ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(debugaddr.sin_addr), port);
17397
17398 sipdebug |= sip_debug_console;
17399
17400 return CLI_SUCCESS;
17401 }
17402
17403
17404 static char *sip_do_debug_peer(int fd, char *arg)
17405 {
17406 struct sip_peer *peer = find_peer(arg, NULL, TRUE, FINDPEERS, FALSE, 0);
17407 if (!peer)
17408 ast_cli(fd, "No such peer '%s'\n", arg);
17409 else if (peer->addr.sin_addr.s_addr == 0)
17410 ast_cli(fd, "Unable to get IP address of peer '%s'\n", arg);
17411 else {
17412 debugaddr.sin_family = AF_INET;
17413 debugaddr.sin_addr = peer->addr.sin_addr;
17414 debugaddr.sin_port = peer->addr.sin_port;
17415 ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n",
17416 ast_inet_ntoa(debugaddr.sin_addr), ntohs(debugaddr.sin_port));
17417 sipdebug |= sip_debug_console;
17418 }
17419 if (peer)
17420 unref_peer(peer, "sip_do_debug_peer: unref_peer, from find_peer call");
17421 return CLI_SUCCESS;
17422 }
17423
17424
17425 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17426 {
17427 int oldsipdebug = sipdebug & sip_debug_console;
17428 char *what;
17429
17430 if (cmd == CLI_INIT) {
17431 e->command = "sip set debug {on|off|ip|peer}";
17432 e->usage =
17433 "Usage: sip set debug {off|on|ip addr[:port]|peer peername}\n"
17434 " Globally disables dumping of SIP packets,\n"
17435 " or enables it either globally or for a (single)\n"
17436 " IP address or registered peer.\n";
17437 return NULL;
17438 } else if (cmd == CLI_GENERATE) {
17439 if (a->pos == 4 && !strcasecmp(a->argv[3], "peer"))
17440 return complete_sip_peer(a->word, a->n, 0);
17441 return NULL;
17442 }
17443
17444 what = a->argv[e->args-1];
17445 if (a->argc == e->args) {
17446 if (!strcasecmp(what, "on")) {
17447 sipdebug |= sip_debug_console;
17448 sipdebug_text = 1;
17449 memset(&debugaddr, 0, sizeof(debugaddr));
17450 ast_cli(a->fd, "SIP Debugging %senabled\n", oldsipdebug ? "re-" : "");
17451 return CLI_SUCCESS;
17452 } else if (!strcasecmp(what, "off")) {
17453 sipdebug &= ~sip_debug_console;
17454 sipdebug_text = 0;
17455 ast_cli(a->fd, "SIP Debugging Disabled\n");
17456 return CLI_SUCCESS;
17457 }
17458 } else if (a->argc == e->args +1) {
17459 if (!strcasecmp(what, "ip"))
17460 return sip_do_debug_ip(a->fd, a->argv[e->args]);
17461 else if (!strcasecmp(what, "peer"))
17462 return sip_do_debug_peer(a->fd, a->argv[e->args]);
17463 }
17464 return CLI_SHOWUSAGE;
17465 }
17466
17467
17468 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17469 {
17470 struct ast_variable *varlist;
17471 int i;
17472
17473 switch (cmd) {
17474 case CLI_INIT:
17475 e->command = "sip notify";
17476 e->usage =
17477 "Usage: sip notify <type> <peer> [<peer>...]\n"
17478 " Send a NOTIFY message to a SIP peer or peers\n"
17479 " Message types are defined in sip_notify.conf\n";
17480 return NULL;
17481 case CLI_GENERATE:
17482 return complete_sipnotify(a->line, a->word, a->pos, a->n);
17483 }
17484
17485 if (a->argc < 4)
17486 return CLI_SHOWUSAGE;
17487
17488 if (!notify_types) {
17489 ast_cli(a->fd, "No %s file found, or no types listed there\n", notify_config);
17490 return CLI_FAILURE;
17491 }
17492
17493 varlist = ast_variable_browse(notify_types, a->argv[2]);
17494
17495 if (!varlist) {
17496 ast_cli(a->fd, "Unable to find notify type '%s'\n", a->argv[2]);
17497 return CLI_FAILURE;
17498 }
17499
17500 for (i = 3; i < a->argc; i++) {
17501 struct sip_pvt *p;
17502
17503 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
17504 ast_log(LOG_WARNING, "Unable to build sip pvt data for notify (memory/socket error)\n");
17505 return CLI_FAILURE;
17506 }
17507
17508 if (create_addr(p, a->argv[i], NULL, 1)) {
17509
17510 dialog_unlink_all(p, TRUE, TRUE);
17511 dialog_unref(p, "unref dialog inside for loop" );
17512
17513 ast_cli(a->fd, "Could not create address for '%s'\n", a->argv[i]);
17514 continue;
17515 }
17516
17517
17518 ast_set_flag(&p->flags[0], SIP_OUTGOING);
17519
17520
17521 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
17522 build_via(p);
17523 ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
17524 build_callid_pvt(p);
17525 ao2_t_link(dialogs, p, "Linking in new name");
17526 ast_cli(a->fd, "Sending NOTIFY of type '%s' to '%s'\n", a->argv[2], a->argv[i]);
17527 dialog_ref(p, "bump the count of p, which transmit_sip_request will decrement.");
17528 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
17529 transmit_notify_custom(p, varlist);
17530 }
17531
17532 return CLI_SUCCESS;
17533 }
17534
17535
17536 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17537 {
17538 switch (cmd) {
17539 case CLI_INIT:
17540 e->command = "sip set history {on|off}";
17541 e->usage =
17542 "Usage: sip set history {on|off}\n"
17543 " Enables/Disables recording of SIP dialog history for debugging purposes.\n"
17544 " Use 'sip show history' to view the history of a call number.\n";
17545 return NULL;
17546 case CLI_GENERATE:
17547 return NULL;
17548 }
17549
17550 if (a->argc != e->args)
17551 return CLI_SHOWUSAGE;
17552
17553 if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
17554 recordhistory = TRUE;
17555 ast_cli(a->fd, "SIP History Recording Enabled (use 'sip show history')\n");
17556 } else if (!strncasecmp(a->argv[e->args - 1], "off", 3)) {
17557 recordhistory = FALSE;
17558 ast_cli(a->fd, "SIP History Recording Disabled\n");
17559 } else {
17560 return CLI_SHOWUSAGE;
17561 }
17562 return CLI_SUCCESS;
17563 }
17564
17565
17566 static int do_register_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code)
17567 {
17568 char *header, *respheader;
17569 char digest[1024];
17570
17571 p->authtries++;
17572 auth_headers(code, &header, &respheader);
17573 memset(digest, 0, sizeof(digest));
17574 if (reply_digest(p, req, header, SIP_REGISTER, digest, sizeof(digest))) {
17575
17576
17577 if (sip_debug_test_pvt(p) && p->registry)
17578 ast_verbose("No authentication challenge, sending blank registration to domain/host name %s\n", p->registry->hostname);
17579
17580 return -1;
17581 }
17582 if (p->do_history)
17583 append_history(p, "RegistryAuth", "Try: %d", p->authtries);
17584 if (sip_debug_test_pvt(p) && p->registry)
17585 ast_verbose("Responding to challenge, registration to domain/host name %s\n", p->registry->hostname);
17586 return transmit_register(p->registry, SIP_REGISTER, digest, respheader);
17587 }
17588
17589
17590 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code, int sipmethod, int init)
17591 {
17592 char *header, *respheader;
17593 char digest[1024];
17594
17595 if (!p->options && !(p->options = ast_calloc(1, sizeof(*p->options))))
17596 return -2;
17597
17598 p->authtries++;
17599 auth_headers(code, &header, &respheader);
17600 ast_debug(2, "Auth attempt %d on %s\n", p->authtries, sip_methods[sipmethod].text);
17601 memset(digest, 0, sizeof(digest));
17602 if (reply_digest(p, req, header, sipmethod, digest, sizeof(digest) )) {
17603
17604 return -1;
17605 }
17606
17607 p->options->auth = digest;
17608 p->options->authheader = respheader;
17609 return transmit_invite(p, sipmethod, sipmethod == SIP_INVITE, init);
17610 }
17611
17612
17613
17614
17615
17616 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len)
17617 {
17618 char tmp[512];
17619 char *c;
17620 char oldnonce[256];
17621
17622
17623 const struct x {
17624 const char *key;
17625 const ast_string_field *field;
17626 } *i, keys[] = {
17627 { "realm=", &p->realm },
17628 { "nonce=", &p->nonce },
17629 { "opaque=", &p->opaque },
17630 { "qop=", &p->qop },
17631 { "domain=", &p->domain },
17632 { NULL, 0 },
17633 };
17634
17635 ast_copy_string(tmp, get_header(req, header), sizeof(tmp));
17636 if (ast_strlen_zero(tmp))
17637 return -1;
17638 if (strncasecmp(tmp, "Digest ", strlen("Digest "))) {
17639 ast_log(LOG_WARNING, "missing Digest.\n");
17640 return -1;
17641 }
17642 c = tmp + strlen("Digest ");
17643 ast_copy_string(oldnonce, p->nonce, sizeof(oldnonce));
17644 while (c && *(c = ast_skip_blanks(c))) {
17645 for (i = keys; i->key != NULL; i++) {
17646 char *src, *separator;
17647 if (strncasecmp(c, i->key, strlen(i->key)) != 0)
17648 continue;
17649
17650 c += strlen(i->key);
17651 if (*c == '"') {
17652 src = ++c;
17653 separator = "\"";
17654 } else {
17655 src = c;
17656 separator = ",";
17657 }
17658 strsep(&c, separator);
17659 ast_string_field_ptr_set(p, i->field, src);
17660 break;
17661 }
17662 if (i->key == NULL)
17663 strsep(&c, ",");
17664 }
17665
17666 if (strcmp(p->nonce, oldnonce))
17667 p->noncecount = 0;
17668
17669
17670 if (p->registry) {
17671 struct sip_registry *r = p->registry;
17672
17673 if (strcmp(r->nonce, p->nonce)) {
17674 ast_string_field_set(r, realm, p->realm);
17675 ast_string_field_set(r, nonce, p->nonce);
17676 ast_string_field_set(r, domain, p->domain);
17677 ast_string_field_set(r, opaque, p->opaque);
17678 ast_string_field_set(r, qop, p->qop);
17679 r->noncecount = 0;
17680 }
17681 }
17682 return build_reply_digest(p, sipmethod, digest, digest_len);
17683 }
17684
17685
17686
17687
17688
17689
17690 static int build_reply_digest(struct sip_pvt *p, int method, char* digest, int digest_len)
17691 {
17692 char a1[256];
17693 char a2[256];
17694 char a1_hash[256];
17695 char a2_hash[256];
17696 char resp[256];
17697 char resp_hash[256];
17698 char uri[256];
17699 char opaque[256] = "";
17700 char cnonce[80];
17701 const char *username;
17702 const char *secret;
17703 const char *md5secret;
17704 struct sip_auth *auth = NULL;
17705
17706 if (!ast_strlen_zero(p->domain))
17707 ast_copy_string(uri, p->domain, sizeof(uri));
17708 else if (!ast_strlen_zero(p->uri))
17709 ast_copy_string(uri, p->uri, sizeof(uri));
17710 else
17711 snprintf(uri, sizeof(uri), "sip:%s@%s", p->username, ast_inet_ntoa(p->sa.sin_addr));
17712
17713 snprintf(cnonce, sizeof(cnonce), "%08lx", ast_random());
17714
17715
17716 if(!(auth = find_realm_authentication(p->peerauth, p->realm)))
17717 auth = find_realm_authentication(authl, p->realm);
17718
17719 if (auth) {
17720 ast_debug(3, "use realm [%s] from peer [%s][%s]\n", auth->username, p->peername, p->username);
17721 username = auth->username;
17722 secret = auth->secret;
17723 md5secret = auth->md5secret;
17724 if (sipdebug)
17725 ast_debug(1, "Using realm %s authentication for call %s\n", p->realm, p->callid);
17726 } else {
17727
17728 username = p->authname;
17729 secret = p->peersecret;
17730 md5secret = p->peermd5secret;
17731 }
17732 if (ast_strlen_zero(username))
17733 return -1;
17734
17735
17736 snprintf(a1, sizeof(a1), "%s:%s:%s", username, p->realm, secret);
17737 snprintf(a2, sizeof(a2), "%s:%s", sip_methods[method].text, uri);
17738 if (!ast_strlen_zero(md5secret))
17739 ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
17740 else
17741 ast_md5_hash(a1_hash, a1);
17742 ast_md5_hash(a2_hash, a2);
17743
17744 p->noncecount++;
17745 if (!ast_strlen_zero(p->qop))
17746 snprintf(resp, sizeof(resp), "%s:%s:%08x:%s:%s:%s", a1_hash, p->nonce, p->noncecount, cnonce, "auth", a2_hash);
17747 else
17748 snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, p->nonce, a2_hash);
17749 ast_md5_hash(resp_hash, resp);
17750
17751
17752 if (!ast_strlen_zero(p->opaque)) {
17753 snprintf(opaque, sizeof(opaque), ", opaque=\"%s\"", p->opaque);
17754 }
17755
17756
17757 if (!ast_strlen_zero(p->qop))
17758 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);
17759 else
17760 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);
17761
17762 append_history(p, "AuthResp", "Auth response sent for %s in realm %s - nc %d", username, p->realm, p->noncecount);
17763
17764 return 0;
17765 }
17766
17767
17768 static int func_header_read(struct ast_channel *chan, const char *function, char *data, char *buf, size_t len)
17769 {
17770 struct sip_pvt *p;
17771 const char *content = NULL;
17772 AST_DECLARE_APP_ARGS(args,
17773 AST_APP_ARG(header);
17774 AST_APP_ARG(number);
17775 );
17776 int i, number, start = 0;
17777
17778 if (ast_strlen_zero(data)) {
17779 ast_log(LOG_WARNING, "This function requires a header name.\n");
17780 return -1;
17781 }
17782
17783 ast_channel_lock(chan);
17784 if (!IS_SIP_TECH(chan->tech)) {
17785 ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
17786 ast_channel_unlock(chan);
17787 return -1;
17788 }
17789
17790 AST_STANDARD_APP_ARGS(args, data);
17791 if (!args.number) {
17792 number = 1;
17793 } else {
17794 sscanf(args.number, "%30d", &number);
17795 if (number < 1)
17796 number = 1;
17797 }
17798
17799 p = chan->tech_pvt;
17800
17801
17802 if (!p) {
17803 ast_channel_unlock(chan);
17804 return -1;
17805 }
17806
17807 for (i = 0; i < number; i++)
17808 content = __get_header(&p->initreq, args.header, &start);
17809
17810 if (ast_strlen_zero(content)) {
17811 ast_channel_unlock(chan);
17812 return -1;
17813 }
17814
17815 ast_copy_string(buf, content, len);
17816 ast_channel_unlock(chan);
17817
17818 return 0;
17819 }
17820
17821 static struct ast_custom_function sip_header_function = {
17822 .name = "SIP_HEADER",
17823 .read = func_header_read,
17824 };
17825
17826
17827 static int func_check_sipdomain(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
17828 {
17829 if (ast_strlen_zero(data)) {
17830 ast_log(LOG_WARNING, "CHECKSIPDOMAIN requires an argument - A domain name\n");
17831 return -1;
17832 }
17833 if (check_sip_domain(data, NULL, 0))
17834 ast_copy_string(buf, data, len);
17835 else
17836 buf[0] = '\0';
17837 return 0;
17838 }
17839
17840 static struct ast_custom_function checksipdomain_function = {
17841 .name = "CHECKSIPDOMAIN",
17842 .read = func_check_sipdomain,
17843 };
17844
17845
17846 static int function_sippeer(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
17847 {
17848 struct sip_peer *peer;
17849 char *colname;
17850
17851 if ((colname = strchr(data, ':'))) {
17852 static int deprecation_warning = 0;
17853 *colname++ = '\0';
17854 if (deprecation_warning++ % 10 == 0)
17855 ast_log(LOG_WARNING, "SIPPEER(): usage of ':' to separate arguments is deprecated. Please use ',' instead.\n");
17856 } else if ((colname = strchr(data, ',')))
17857 *colname++ = '\0';
17858 else
17859 colname = "ip";
17860
17861 if (!(peer = find_peer(data, NULL, TRUE, FINDPEERS, FALSE, 0)))
17862 return -1;
17863
17864 if (!strcasecmp(colname, "ip")) {
17865 ast_copy_string(buf, peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "", len);
17866 } else if (!strcasecmp(colname, "port")) {
17867 snprintf(buf, len, "%d", ntohs(peer->addr.sin_port));
17868 } else if (!strcasecmp(colname, "status")) {
17869 peer_status(peer, buf, len);
17870 } else if (!strcasecmp(colname, "language")) {
17871 ast_copy_string(buf, peer->language, len);
17872 } else if (!strcasecmp(colname, "regexten")) {
17873 ast_copy_string(buf, peer->regexten, len);
17874 } else if (!strcasecmp(colname, "limit")) {
17875 snprintf(buf, len, "%d", peer->call_limit);
17876 } else if (!strcasecmp(colname, "busylevel")) {
17877 snprintf(buf, len, "%d", peer->busy_level);
17878 } else if (!strcasecmp(colname, "curcalls")) {
17879 snprintf(buf, len, "%d", peer->inUse);
17880 } else if (!strcasecmp(colname, "accountcode")) {
17881 ast_copy_string(buf, peer->accountcode, len);
17882 } else if (!strcasecmp(colname, "callgroup")) {
17883 ast_print_group(buf, len, peer->callgroup);
17884 } else if (!strcasecmp(colname, "pickupgroup")) {
17885 ast_print_group(buf, len, peer->pickupgroup);
17886 } else if (!strcasecmp(colname, "useragent")) {
17887 ast_copy_string(buf, peer->useragent, len);
17888 } else if (!strcasecmp(colname, "mailbox")) {
17889 struct ast_str *mailbox_str = ast_str_alloca(512);
17890 peer_mailboxes_to_str(&mailbox_str, peer);
17891 ast_copy_string(buf, mailbox_str->str, len);
17892 } else if (!strcasecmp(colname, "context")) {
17893 ast_copy_string(buf, peer->context, len);
17894 } else if (!strcasecmp(colname, "expire")) {
17895 snprintf(buf, len, "%d", peer->expire);
17896 } else if (!strcasecmp(colname, "dynamic")) {
17897 ast_copy_string(buf, peer->host_dynamic ? "yes" : "no", len);
17898 } else if (!strcasecmp(colname, "callerid_name")) {
17899 ast_copy_string(buf, peer->cid_name, len);
17900 } else if (!strcasecmp(colname, "callerid_num")) {
17901 ast_copy_string(buf, peer->cid_num, len);
17902 } else if (!strcasecmp(colname, "codecs")) {
17903 ast_getformatname_multiple(buf, len -1, peer->capability);
17904 } else if (!strncasecmp(colname, "chanvar[", 8)) {
17905 char *chanvar=colname + 8;
17906 struct ast_variable *v;
17907
17908 chanvar = strsep(&chanvar, "]");
17909 for (v = peer->chanvars ; v ; v = v->next) {
17910 if (!strcasecmp(v->name, chanvar)) {
17911 ast_copy_string(buf, v->value, len);
17912 }
17913 }
17914 } else if (!strncasecmp(colname, "codec[", 6)) {
17915 char *codecnum;
17916 int codec = 0;
17917
17918 codecnum = colname + 6;
17919 codecnum = strsep(&codecnum, "]");
17920 if((codec = ast_codec_pref_index(&peer->prefs, atoi(codecnum)))) {
17921 ast_copy_string(buf, ast_getformatname(codec), len);
17922 } else {
17923 buf[0] = '\0';
17924 }
17925 } else {
17926 buf[0] = '\0';
17927 }
17928
17929 unref_peer(peer, "unref_peer from function_sippeer, just before return");
17930
17931 return 0;
17932 }
17933
17934
17935 static struct ast_custom_function sippeer_function = {
17936 .name = "SIPPEER",
17937 .read = function_sippeer,
17938 };
17939
17940
17941 static int function_sipchaninfo_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
17942 {
17943 struct sip_pvt *p;
17944 static int deprecated = 0;
17945
17946 *buf = 0;
17947
17948 if (!data) {
17949 ast_log(LOG_WARNING, "This function requires a parameter name.\n");
17950 return -1;
17951 }
17952
17953 ast_channel_lock(chan);
17954 if (!IS_SIP_TECH(chan->tech)) {
17955 ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
17956 ast_channel_unlock(chan);
17957 return -1;
17958 }
17959
17960 if (deprecated++ % 20 == 0) {
17961
17962 ast_log(LOG_WARNING, "SIPCHANINFO() is deprecated. Please transition to using CHANNEL().\n");
17963 }
17964
17965 p = chan->tech_pvt;
17966
17967
17968 if (!p) {
17969 ast_channel_unlock(chan);
17970 return -1;
17971 }
17972
17973 if (!strcasecmp(data, "peerip")) {
17974 ast_copy_string(buf, p->sa.sin_addr.s_addr ? ast_inet_ntoa(p->sa.sin_addr) : "", len);
17975 } else if (!strcasecmp(data, "recvip")) {
17976 ast_copy_string(buf, p->recv.sin_addr.s_addr ? ast_inet_ntoa(p->recv.sin_addr) : "", len);
17977 } else if (!strcasecmp(data, "from")) {
17978 ast_copy_string(buf, p->from, len);
17979 } else if (!strcasecmp(data, "uri")) {
17980 ast_copy_string(buf, p->uri, len);
17981 } else if (!strcasecmp(data, "useragent")) {
17982 ast_copy_string(buf, p->useragent, len);
17983 } else if (!strcasecmp(data, "peername")) {
17984 ast_copy_string(buf, p->peername, len);
17985 } else if (!strcasecmp(data, "t38passthrough")) {
17986 if (p->t38.state == T38_DISABLED) {
17987 ast_copy_string(buf, "0", len);
17988 } else {
17989 ast_copy_string(buf, "1", len);
17990 }
17991 } else {
17992 ast_channel_unlock(chan);
17993 return -1;
17994 }
17995 ast_channel_unlock(chan);
17996
17997 return 0;
17998 }
17999
18000
18001 static struct ast_custom_function sipchaninfo_function = {
18002 .name = "SIPCHANINFO",
18003 .read = function_sipchaninfo_read,
18004 };
18005
18006
18007
18008
18009
18010
18011
18012 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req)
18013 {
18014 char tmp[SIPBUFSIZE];
18015 char *s, *e, *t, *trans;
18016 char *domain;
18017 enum sip_transport transport = SIP_TRANSPORT_UDP;
18018
18019 ast_copy_string(tmp, get_header(req, "Contact"), sizeof(tmp));
18020 if ((t = strchr(tmp, ',')))
18021 *t = '\0';
18022
18023 s = get_in_brackets(tmp);
18024 if ((trans = strcasestr(s, ";transport="))) do {
18025 trans += 11;
18026
18027 if ((e = strchr(trans, ';')))
18028 *e = '\0';
18029
18030 if (!strncasecmp(trans, "tcp", 3))
18031 transport = SIP_TRANSPORT_TCP;
18032 else if (!strncasecmp(trans, "tls", 3))
18033 transport = SIP_TRANSPORT_TLS;
18034 else {
18035 if (strncasecmp(trans, "udp", 3))
18036 ast_debug(1, "received contact with an invalid transport, '%s'\n", s);
18037
18038 transport = SIP_TRANSPORT_UDP;
18039 }
18040 } while(0);
18041 s = remove_uri_parameters(s);
18042
18043 if (p->socket.tcptls_session) {
18044 ao2_ref(p->socket.tcptls_session, -1);
18045 p->socket.tcptls_session = NULL;
18046 }
18047
18048 set_socket_transport(&p->socket, transport);
18049
18050 if (ast_test_flag(&p->flags[0], SIP_PROMISCREDIR)) {
18051 char *host = NULL;
18052 if (!strncasecmp(s, "sip:", 4))
18053 s += 4;
18054 else if (!strncasecmp(s, "sips:", 5))
18055 s += 5;
18056 e = strchr(s, '/');
18057 if (e)
18058 *e = '\0';
18059 if ((host = strchr(s, '@'))) {
18060 *host++ = '\0';
18061 ast_debug(2, "Found promiscuous redirection to 'SIP/%s::::%s@%s'\n", s, get_transport(transport), host);
18062 if (p->owner)
18063 ast_string_field_build(p->owner, call_forward, "SIP/%s::::%s@%s", s, get_transport(transport), host);
18064 } else {
18065 ast_debug(2, "Found promiscuous redirection to 'SIP/::::%s@%s'\n", get_transport(transport), s);
18066 if (p->owner)
18067 ast_string_field_build(p->owner, call_forward, "SIP/::::%s@%s", get_transport(transport), s);
18068 }
18069 } else {
18070 e = strchr(tmp, '@');
18071 if (e) {
18072 *e++ = '\0';
18073 domain = e;
18074 } else {
18075
18076 domain = tmp;
18077 }
18078 e = strchr(tmp, '/');
18079 if (e)
18080 *e = '\0';
18081
18082 if (!strncasecmp(s, "sip:", 4))
18083 s += 4;
18084 else if (!strncasecmp(s, "sips:", 5))
18085 s += 5;
18086 e = strchr(s, ';');
18087 if (e)
18088 *e = '\0';
18089 ast_uri_decode(s);
18090 ast_debug(2, "Received 302 Redirect to extension '%s' (domain %s)\n", s, domain);
18091 if (p->owner) {
18092 pbx_builtin_setvar_helper(p->owner, "SIPDOMAIN", domain);
18093 ast_string_field_set(p->owner, call_forward, s);
18094 }
18095 }
18096 }
18097
18098
18099
18100
18101
18102
18103 static void check_pendings(struct sip_pvt *p)
18104 {
18105 if (ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
18106
18107 if (p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA) {
18108 p->invitestate = INV_CANCELLED;
18109 transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
18110
18111
18112 } else {
18113
18114
18115 if (p->pendinginvite)
18116 return;
18117
18118 if (p->owner) {
18119 ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
18120 }
18121
18122 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, TRUE);
18123 }
18124 ast_clear_flag(&p->flags[0], SIP_PENDINGBYE);
18125 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18126 } else if (ast_test_flag(&p->flags[0], SIP_NEEDREINVITE)) {
18127
18128 if (p->pendinginvite || p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA || p->waitid > 0) {
18129 ast_debug(2, "NOT Sending pending reinvite (yet) on '%s'\n", p->callid);
18130 } else {
18131 ast_debug(2, "Sending pending reinvite on '%s'\n", p->callid);
18132
18133 transmit_reinvite_with_sdp(p, (p->t38.state == T38_LOCAL_REINVITE ? TRUE : FALSE), FALSE);
18134 ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);
18135 }
18136 }
18137 }
18138
18139
18140
18141
18142
18143 static int sip_reinvite_retry(const void *data)
18144 {
18145 struct sip_pvt *p = (struct sip_pvt *) data;
18146 struct ast_channel *owner;
18147
18148 sip_pvt_lock(p);
18149 while ((owner = p->owner) && ast_channel_trylock(owner)) {
18150 sip_pvt_unlock(p);
18151 usleep(1);
18152 sip_pvt_lock(p);
18153 }
18154 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
18155 p->waitid = -1;
18156 check_pendings(p);
18157 sip_pvt_unlock(p);
18158 if (owner) {
18159 ast_channel_unlock(owner);
18160 }
18161 dialog_unref(p, "unref the dialog ptr from sip_reinvite_retry, because it held a dialog ptr");
18162 return 0;
18163 }
18164
18165
18166
18167 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
18168 {
18169 int outgoing = ast_test_flag(&p->flags[0], SIP_OUTGOING);
18170 int res = 0;
18171 int xmitres = 0;
18172 int reinvite = (p->owner && p->owner->_state == AST_STATE_UP);
18173 char *p_hdrval;
18174 int rtn;
18175
18176 if (reinvite)
18177 ast_debug(4, "SIP response %d to RE-invite on %s call %s\n", resp, outgoing ? "outgoing" : "incoming", p->callid);
18178 else
18179 ast_debug(4, "SIP response %d to standard invite\n", resp);
18180
18181 if (p->alreadygone) {
18182 ast_debug(1, "Got response on call that is already terminated: %s (ignoring)\n", p->callid);
18183 return;
18184 }
18185
18186
18187
18188 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"));
18189
18190
18191
18192
18193 if (resp > 100 && resp < 200 && resp!=101 && resp != 180 && resp != 182 && resp != 183)
18194 resp = 183;
18195
18196
18197 if (resp >= 100 && resp < 200 && p->invitestate == INV_CALLING)
18198 p->invitestate = INV_PROCEEDING;
18199
18200
18201 if (resp >= 300 && (p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA ))
18202 p->invitestate = INV_COMPLETED;
18203
18204
18205 if ((resp == 200 || resp >= 300) && p->pendinginvite && seqno == p->pendinginvite)
18206 p->pendinginvite = 0;
18207
18208 switch (resp) {
18209 case 100:
18210 case 101:
18211 if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p))
18212 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
18213 check_pendings(p);
18214 break;
18215
18216 case 180:
18217 case 182:
18218 if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p))
18219 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
18220 if (!req->ignore && p->owner) {
18221 ast_queue_control(p->owner, AST_CONTROL_RINGING);
18222 if (p->owner->_state != AST_STATE_UP) {
18223 ast_setstate(p->owner, AST_STATE_RINGING);
18224 }
18225 }
18226 if (find_sdp(req)) {
18227 if (p->invitestate != INV_CANCELLED)
18228 p->invitestate = INV_EARLY_MEDIA;
18229 res = process_sdp(p, req, SDP_T38_NONE);
18230 if (!req->ignore && p->owner) {
18231
18232 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
18233 }
18234 }
18235 check_pendings(p);
18236 break;
18237
18238 case 183:
18239 if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
18240 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
18241 if (find_sdp(req)) {
18242 if (p->invitestate != INV_CANCELLED)
18243 p->invitestate = INV_EARLY_MEDIA;
18244 res = process_sdp(p, req, SDP_T38_NONE);
18245 if (!req->ignore && p->owner) {
18246
18247 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
18248 }
18249 } else {
18250
18251
18252
18253
18254 if (!req->ignore && p->owner) {
18255 ast_queue_control(p->owner, AST_CONTROL_RINGING);
18256 }
18257 }
18258 check_pendings(p);
18259 break;
18260
18261 case 200:
18262 if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
18263 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
18264 p->authtries = 0;
18265 if (find_sdp(req)) {
18266 if ((res = process_sdp(p, req, SDP_T38_ACCEPT)) && !req->ignore)
18267 if (!reinvite)
18268
18269
18270 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
18271 }
18272
18273
18274
18275
18276 if (outgoing) {
18277 update_call_counter(p, DEC_CALL_RINGING);
18278 parse_ok_contact(p, req);
18279
18280 if (!reinvite)
18281 build_route(p, req, 1);
18282
18283 if(set_address_from_contact(p)) {
18284
18285
18286 if (!p->route && !req->ignore)
18287 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
18288 }
18289
18290 }
18291
18292 if (!req->ignore && p->owner) {
18293 if (!reinvite) {
18294 ast_queue_control(p->owner, AST_CONTROL_ANSWER);
18295 if (sip_cfg.callevents)
18296 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
18297 "Channel: %s\r\nChanneltype: %s\r\nUniqueid: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
18298 p->owner->name, "SIP", p->owner->uniqueid, p->callid, p->fullcontact, p->peername);
18299 } else {
18300 ast_queue_frame(p->owner, &ast_null_frame);
18301 }
18302 } else {
18303
18304
18305
18306 if (!req->ignore)
18307 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
18308 }
18309
18310
18311 if (st_get_mode(p) != SESSION_TIMER_MODE_REFUSE && p->outgoing_call == TRUE && !reinvite) {
18312 p_hdrval = (char*)get_header(req, "Session-Expires");
18313 if (!ast_strlen_zero(p_hdrval)) {
18314
18315 enum st_refresher tmp_st_ref = SESSION_TIMER_REFRESHER_AUTO;
18316 int tmp_st_interval = 0;
18317 rtn = parse_session_expires(p_hdrval, &tmp_st_interval, &tmp_st_ref);
18318 if (rtn != 0) {
18319 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
18320 }
18321 if (tmp_st_ref == SESSION_TIMER_REFRESHER_UAC ||
18322 tmp_st_ref == SESSION_TIMER_REFRESHER_UAS) {
18323 p->stimer->st_ref = tmp_st_ref;
18324 }
18325 if (tmp_st_interval) {
18326 p->stimer->st_interval = tmp_st_interval;
18327 }
18328 p->stimer->st_active = TRUE;
18329 p->stimer->st_active_peer_ua = TRUE;
18330 start_session_timer(p);
18331 } else {
18332
18333 if (st_get_mode(p) == SESSION_TIMER_MODE_ORIGINATE) {
18334 p->stimer->st_ref = SESSION_TIMER_REFRESHER_UAC;
18335 p->stimer->st_active_peer_ua = FALSE;
18336 start_session_timer(p);
18337 }
18338 }
18339 }
18340
18341
18342
18343 p->invitestate = INV_TERMINATED;
18344 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
18345 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, TRUE);
18346 check_pendings(p);
18347 break;
18348
18349 case 407:
18350 case 401:
18351
18352 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
18353 if (p->options)
18354 p->options->auth_type = resp;
18355
18356
18357 ast_string_field_set(p, theirtag, NULL);
18358 if (!req->ignore) {
18359 if (p->authtries < MAX_AUTHTRIES)
18360 p->invitestate = INV_CALLING;
18361 if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, SIP_INVITE, 1)) {
18362 ast_log(LOG_NOTICE, "Failed to authenticate on INVITE to '%s'\n", get_header(&p->initreq, "From"));
18363 pvt_set_needdestroy(p, "failed to authenticate on INVITE");
18364 sip_alreadygone(p);
18365 if (p->owner)
18366 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18367 }
18368 }
18369 break;
18370
18371 case 403:
18372
18373 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
18374 ast_log(LOG_WARNING, "Received response: \"Forbidden\" from '%s'\n", get_header(&p->initreq, "From"));
18375 if (!req->ignore && p->owner)
18376 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18377 pvt_set_needdestroy(p, "received 403 response");
18378 sip_alreadygone(p);
18379 break;
18380
18381 case 404:
18382 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
18383 if (p->owner && !req->ignore)
18384 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18385 sip_alreadygone(p);
18386 break;
18387
18388 case 408:
18389 case 481:
18390
18391 ast_log(LOG_WARNING, "Re-invite to non-existing call leg on other UA. SIP dialog '%s'. Giving up.\n", p->callid);
18392 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
18393 if (p->owner)
18394 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18395 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18396 break;
18397
18398 case 422:
18399 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
18400 ast_string_field_set(p, theirtag, NULL);
18401 proc_422_rsp(p, req);
18402 break;
18403
18404 case 428:
18405 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
18406 append_history(p, "Identity", "SIP identity is required. Not supported by Asterisk.");
18407 ast_log(LOG_WARNING, "SIP identity required by proxy. SIP dialog '%s'. Giving up.\n", p->callid);
18408 if (p->owner)
18409 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18410 break;
18411
18412
18413
18414 case 487:
18415
18416
18417
18418 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
18419 if (p->owner && !req->ignore) {
18420 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_NORMAL_CLEARING);
18421 append_history(p, "Hangup", "Got 487 on CANCEL request from us. Queued AST hangup request");
18422 } else if (!req->ignore) {
18423 update_call_counter(p, DEC_CALL_LIMIT);
18424 append_history(p, "Hangup", "Got 487 on CANCEL request from us on call without owner. Killing this dialog.");
18425 pvt_set_needdestroy(p, "received 487 response");
18426 sip_alreadygone(p);
18427 }
18428 break;
18429 case 415:
18430 case 488:
18431 case 606:
18432 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
18433 if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
18434 change_t38_state(p, T38_DISABLED);
18435
18436 ast_rtp_set_rtptimers_onhold(p->rtp);
18437
18438
18439 transmit_reinvite_with_sdp(p, FALSE, FALSE);
18440 } else {
18441
18442 if (p->owner && !req->ignore)
18443 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18444 pvt_set_needdestroy(p, "received 488 response");
18445
18446 if (!reinvite)
18447 sip_alreadygone(p);
18448 }
18449 break;
18450 case 491:
18451 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
18452 if (p->owner && !req->ignore) {
18453 if (p->owner->_state != AST_STATE_UP) {
18454 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18455 pvt_set_needdestroy(p, "received 491 response");
18456 } else {
18457
18458
18459
18460 int wait;
18461
18462
18463 if (p->outgoing_call) {
18464 wait = 2100 + ast_random() % 2000;
18465 } else {
18466 wait = ast_random() % 2000;
18467 }
18468 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."));
18469 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);
18470 ast_debug(2, "Reinvite race. Waiting %d secs before retry\n", wait);
18471 }
18472 }
18473 break;
18474
18475 case 501:
18476 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
18477 if (p->owner)
18478 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18479 break;
18480 }
18481 if (xmitres == XMIT_ERROR)
18482 ast_log(LOG_WARNING, "Could not transmit message in dialog %s\n", p->callid);
18483 }
18484
18485
18486
18487
18488 static void handle_response_notify(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
18489 {
18490 switch (resp) {
18491 case 200:
18492
18493 if (p->owner) {
18494 if (!p->refer) {
18495 ast_log(LOG_WARNING, "Notify answer on an owned channel? - %s\n", p->owner->name);
18496 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_NORMAL_UNSPECIFIED);
18497 } else {
18498 ast_debug(4, "Got OK on REFER Notify message\n");
18499 }
18500 } else {
18501 if (p->subscribed == NONE) {
18502 ast_debug(4, "Got 200 accepted on NOTIFY\n");
18503 pvt_set_needdestroy(p, "received 200 response");
18504 }
18505 if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
18506
18507 ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
18508 cb_extensionstate((char *)p->context, (char *)p->exten, p->laststate, (void *) p);
18509 }
18510 }
18511 break;
18512 case 401:
18513 case 407:
18514 if (!p->notify_headers) {
18515 break;
18516 }
18517 ast_string_field_set(p, theirtag, NULL);
18518 if (ast_strlen_zero(p->authname)) {
18519 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));
18520 pvt_set_needdestroy(p, "unable to authenticate NOTIFY");
18521 }
18522 if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_NOTIFY, 0)) {
18523 ast_log(LOG_NOTICE, "Failed to authenticate on NOTIFY to '%s'\n", get_header(&p->initreq, "From"));
18524 pvt_set_needdestroy(p, "failed to authenticate NOTIFY");
18525 }
18526 break;
18527 }
18528 }
18529
18530
18531 static void handle_response_subscribe(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
18532 {
18533 if (!p->mwi) {
18534 return;
18535 }
18536
18537 switch (resp) {
18538 case 200:
18539 ast_debug(3, "Got 200 OK on subscription for MWI\n");
18540 if (p->options) {
18541 ast_free(p->options);
18542 p->options = NULL;
18543 }
18544 p->mwi->subscribed = 1;
18545 if ((p->mwi->resub = ast_sched_add(sched, mwi_expiry * 1000, sip_subscribe_mwi_do, ASTOBJ_REF(p->mwi))) < 0) {
18546 ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18547 }
18548 break;
18549 case 401:
18550 case 407:
18551 ast_string_field_set(p, theirtag, NULL);
18552 if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_SUBSCRIBE, 0)) {
18553 ast_log(LOG_NOTICE, "Failed to authenticate on SUBSCRIBE to '%s'\n", get_header(&p->initreq, "From"));
18554 p->mwi->call = NULL;
18555 ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18556 pvt_set_needdestroy(p, "failed to authenticate SUBSCRIBE");
18557 }
18558 break;
18559 case 403:
18560 transmit_response_with_date(p, "200 OK", req);
18561 ast_log(LOG_WARNING, "Authentication failed while trying to subscribe for MWI.\n");
18562 p->mwi->call = NULL;
18563 ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18564 pvt_set_needdestroy(p, "received 403 response");
18565 sip_alreadygone(p);
18566 break;
18567 case 404:
18568 ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side said that a mailbox may not have been configured.\n");
18569 p->mwi->call = NULL;
18570 ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18571 pvt_set_needdestroy(p, "received 404 response");
18572 break;
18573 case 481:
18574 ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side said that our dialog did not exist.\n");
18575 p->mwi->call = NULL;
18576 ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18577 pvt_set_needdestroy(p, "received 481 response");
18578 break;
18579 case 500:
18580 case 501:
18581 ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side may have suffered a heart attack.\n");
18582 p->mwi->call = NULL;
18583 ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18584 pvt_set_needdestroy(p, "received 500/501 response");
18585 break;
18586 }
18587 }
18588
18589
18590
18591
18592 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
18593 {
18594
18595 if (!p->refer)
18596 return;
18597
18598 switch (resp) {
18599 case 202:
18600
18601
18602 p->refer->status = REFER_ACCEPTED;
18603
18604 ast_debug(3, "Got 202 accepted on transfer\n");
18605
18606 break;
18607
18608 case 401:
18609 case 407:
18610 if (ast_strlen_zero(p->authname)) {
18611 ast_log(LOG_WARNING, "Asked to authenticate REFER to %s:%d but we have no matching peer or realm auth!\n",
18612 ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
18613 pvt_set_needdestroy(p, "unable to authenticate REFER");
18614 }
18615 if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_REFER, 0)) {
18616 ast_log(LOG_NOTICE, "Failed to authenticate on REFER to '%s'\n", get_header(&p->initreq, "From"));
18617 p->refer->status = REFER_NOAUTH;
18618 pvt_set_needdestroy(p, "failed to authenticat REFER");
18619 }
18620 break;
18621 case 481:
18622
18623
18624
18625
18626 ast_log(LOG_WARNING, "Remote host can't match REFER request to call '%s'. Giving up.\n", p->callid);
18627 if (p->owner)
18628 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18629 pvt_set_needdestroy(p, "received 481 response");
18630 break;
18631
18632 case 500:
18633 case 501:
18634
18635
18636 ast_log(LOG_NOTICE, "SIP transfer to %s failed, call miserably fails. \n", p->refer->refer_to);
18637 pvt_set_needdestroy(p, "received 500/501 response");
18638 p->refer->status = REFER_FAILED;
18639 break;
18640 case 603:
18641 ast_log(LOG_NOTICE, "SIP transfer to %s declined, call miserably fails. \n", p->refer->refer_to);
18642 p->refer->status = REFER_FAILED;
18643 pvt_set_needdestroy(p, "received 603 response");
18644 break;
18645 }
18646 }
18647
18648
18649 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
18650 {
18651 int expires, expires_ms;
18652 struct sip_registry *r;
18653 r=p->registry;
18654
18655 switch (resp) {
18656 case 401:
18657 if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
18658 ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s@%s' (Tries %d)\n", p->registry->username, p->registry->hostname, p->authtries);
18659 pvt_set_needdestroy(p, "failed to authenticate REGISTER");
18660 }
18661 break;
18662 case 403:
18663 ast_log(LOG_WARNING, "Forbidden - wrong password on authentication for REGISTER for '%s' to '%s'\n", p->registry->username, p->registry->hostname);
18664 AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 403"));
18665 r->regstate = REG_STATE_NOAUTH;
18666 pvt_set_needdestroy(p, "received 403 response");
18667 break;
18668 case 404:
18669 ast_log(LOG_WARNING, "Got 404 Not found on SIP register to service %s@%s, giving up\n", p->registry->username, p->registry->hostname);
18670 pvt_set_needdestroy(p, "received 404 response");
18671 if (r->call)
18672 r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 404");
18673 r->regstate = REG_STATE_REJECTED;
18674 AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 404"));
18675 break;
18676 case 407:
18677 if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
18678 ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s' (tries '%d')\n", get_header(&p->initreq, "From"), p->authtries);
18679 pvt_set_needdestroy(p, "failed to authenticate REGISTER");
18680 }
18681 break;
18682 case 408:
18683
18684 if (r) {
18685 r->regattempts = 0;
18686 } else {
18687 ast_log(LOG_WARNING, "Got a 408 response to our REGISTER on call %s after we had destroyed the registry object\n", p->callid);
18688 }
18689 break;
18690 case 423:
18691 r->expiry = atoi(get_header(req, "Min-Expires"));
18692 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);
18693 AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 423"));
18694 if (r->call) {
18695 r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 423");
18696 pvt_set_needdestroy(p, "received 423 response");
18697 }
18698 if (r->expiry > max_expiry) {
18699 ast_log(LOG_WARNING, "Required expiration time from %s@%s is too high, giving up\n", p->registry->username, p->registry->hostname);
18700 r->expiry = r->configured_expiry;
18701 r->regstate = REG_STATE_REJECTED;
18702 } else {
18703 r->regstate = REG_STATE_UNREGISTERED;
18704 transmit_register(r, SIP_REGISTER, NULL, NULL);
18705 }
18706 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));
18707 break;
18708 case 479:
18709 ast_log(LOG_WARNING, "Got error 479 on register to %s@%s, giving up (check config)\n", p->registry->username, p->registry->hostname);
18710 pvt_set_needdestroy(p, "received 479 response");
18711 if (r->call)
18712 r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 479");
18713 r->regstate = REG_STATE_REJECTED;
18714 AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 479"));
18715 break;
18716 case 200:
18717 if (!r) {
18718 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));
18719 pvt_set_needdestroy(p, "received erroneous 200 response");
18720 return 0;
18721 }
18722
18723 r->regstate = REG_STATE_REGISTERED;
18724 r->regtime = ast_tvnow();
18725 manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelType: SIP\r\nDomain: %s\r\nStatus: %s\r\n", r->hostname, regstate2str(r->regstate));
18726 r->regattempts = 0;
18727 ast_debug(1, "Registration successful\n");
18728 if (r->timeout > -1) {
18729 ast_debug(1, "Cancelling timeout %d\n", r->timeout);
18730 }
18731 AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 200"));
18732 if (r->call)
18733 r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 200");
18734 p->registry = registry_unref(p->registry, "unref registry entry p->registry");
18735
18736 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18737
18738
18739
18740
18741
18742
18743 expires = 0;
18744
18745
18746 if (!ast_strlen_zero(get_header(req, "Contact"))) {
18747 const char *contact = NULL;
18748 const char *tmptmp = NULL;
18749 int start = 0;
18750 for(;;) {
18751 contact = __get_header(req, "Contact", &start);
18752
18753 if(!ast_strlen_zero(contact)) {
18754 if( (tmptmp=strstr(contact, p->our_contact))) {
18755 contact=tmptmp;
18756 break;
18757 }
18758 } else
18759 break;
18760 }
18761 tmptmp = strcasestr(contact, "expires=");
18762 if (tmptmp) {
18763 if (sscanf(tmptmp + 8, "%30d;", &expires) != 1)
18764 expires = 0;
18765 }
18766
18767 }
18768 if (!expires)
18769 expires=atoi(get_header(req, "expires"));
18770 if (!expires)
18771 expires=default_expiry;
18772
18773 expires_ms = expires * 1000;
18774 if (expires <= EXPIRY_GUARD_LIMIT)
18775 expires_ms -= MAX((expires_ms * EXPIRY_GUARD_PCT), EXPIRY_GUARD_MIN);
18776 else
18777 expires_ms -= EXPIRY_GUARD_SECS * 1000;
18778 if (sipdebug)
18779 ast_log(LOG_NOTICE, "Outbound Registration: Expiry for %s is %d sec (Scheduling reregistration in %d s)\n", r->hostname, expires, expires_ms/1000);
18780
18781 r->refresh= (int) expires_ms / 1000;
18782
18783
18784 AST_SCHED_REPLACE_UNREF(r->expire, sched, expires_ms, sip_reregister, r,
18785 registry_unref(_data,"unref in REPLACE del fail"),
18786 registry_unref(r,"unref in REPLACE add fail"),
18787 registry_addref(r,"The Addition side of REPLACE"));
18788 }
18789 return 1;
18790 }
18791
18792
18793 static void handle_response_peerpoke(struct sip_pvt *p, int resp, struct sip_request *req)
18794 {
18795 struct sip_peer *peer = p->relatedpeer ;
18796 int statechanged, is_reachable, was_reachable;
18797 int pingtime = ast_tvdiff_ms(ast_tvnow(), peer->ps);
18798
18799
18800
18801
18802
18803
18804 if (pingtime < 1)
18805 pingtime = 1;
18806
18807
18808
18809
18810
18811 was_reachable = peer->lastms > 0 && peer->lastms <= peer->maxms;
18812 is_reachable = pingtime <= peer->maxms;
18813 statechanged = peer->lastms == 0
18814 || was_reachable != is_reachable;
18815
18816 peer->lastms = pingtime;
18817 peer->call = dialog_unref(peer->call, "unref dialog peer->call");
18818 if (statechanged) {
18819 const char *s = is_reachable ? "Reachable" : "Lagged";
18820 char str_lastms[20];
18821 snprintf(str_lastms, sizeof(str_lastms), "%d", pingtime);
18822
18823 ast_log(LOG_NOTICE, "Peer '%s' is now %s. (%dms / %dms)\n",
18824 peer->name, s, pingtime, peer->maxms);
18825 ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
18826 if (sip_cfg.peer_rtupdate) {
18827 ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", str_lastms, SENTINEL);
18828 }
18829 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
18830 "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: %s\r\nTime: %d\r\n",
18831 peer->name, s, pingtime);
18832 if (is_reachable && sip_cfg.regextenonqualify)
18833 register_peer_exten(peer, TRUE);
18834 }
18835
18836 pvt_set_needdestroy(p, "got OPTIONS response");
18837
18838
18839 AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
18840 is_reachable ? peer->qualifyfreq : DEFAULT_FREQ_NOTOK,
18841 sip_poke_peer_s, peer,
18842 unref_peer(_data, "removing poke peer ref"),
18843 unref_peer(peer, "removing poke peer ref"),
18844 ref_peer(peer, "adding poke peer ref"));
18845 }
18846
18847
18848 static void stop_media_flows(struct sip_pvt *p)
18849 {
18850
18851 if (p->rtp)
18852 ast_rtp_stop(p->rtp);
18853 if (p->vrtp)
18854 ast_rtp_stop(p->vrtp);
18855 if (p->trtp)
18856 ast_rtp_stop(p->trtp);
18857 if (p->udptl)
18858 ast_udptl_stop(p->udptl);
18859 }
18860
18861
18862
18863 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
18864 {
18865 struct ast_channel *owner;
18866 int sipmethod;
18867 int res = 1;
18868 const char *c = get_header(req, "Cseq");
18869
18870 char *c_copy = ast_strdupa(c);
18871
18872 const char *msg = ast_skip_blanks(ast_skip_nonblanks(c_copy));
18873
18874 if (!msg)
18875 msg = "";
18876
18877 sipmethod = find_sip_method(msg);
18878
18879 owner = p->owner;
18880 if (owner)
18881 owner->hangupcause = hangup_sip2cause(resp);
18882
18883 if (p->socket.type == SIP_TRANSPORT_UDP) {
18884 int ack_res;
18885
18886
18887 if ((resp >= 100) && (resp <= 199)) {
18888 ack_res = __sip_semi_ack(p, seqno, 0, sipmethod);
18889 } else {
18890 ack_res = __sip_ack(p, seqno, 0, sipmethod);
18891 }
18892
18893 if (ack_res == FALSE) {
18894 append_history(p, "Ignore", "Ignoring this retransmit\n");
18895 return;
18896 }
18897 }
18898
18899
18900 if (!p->owner && sipmethod == SIP_NOTIFY && p->pendinginvite)
18901 p->pendinginvite = 0;
18902
18903
18904 if (ast_strlen_zero(p->theirtag) || (resp >= 200)) {
18905 char tag[128];
18906
18907 gettag(req, "To", tag, sizeof(tag));
18908 ast_string_field_set(p, theirtag, tag);
18909 }
18910
18911
18912
18913
18914
18915
18916
18917
18918
18919
18920
18921
18922
18923
18924
18925 if ((resp == 404 || resp == 408 || resp == 481) && sipmethod == SIP_BYE) {
18926 pvt_set_needdestroy(p, "received 4XX response to a BYE");
18927 return;
18928 }
18929
18930 if (p->relatedpeer && p->method == SIP_OPTIONS) {
18931
18932
18933
18934 if (resp != 100)
18935 handle_response_peerpoke(p, resp, req);
18936 } else if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
18937 switch(resp) {
18938 case 100:
18939 case 101:
18940 case 183:
18941 case 180:
18942 case 182:
18943 if (sipmethod == SIP_INVITE)
18944 handle_response_invite(p, resp, rest, req, seqno);
18945 break;
18946 case 200:
18947 p->authtries = 0;
18948 if (sipmethod == SIP_MESSAGE || sipmethod == SIP_INFO) {
18949
18950
18951
18952 } else if (sipmethod == SIP_INVITE) {
18953 handle_response_invite(p, resp, rest, req, seqno);
18954 } else if (sipmethod == SIP_NOTIFY) {
18955 handle_response_notify(p, resp, rest, req, seqno);
18956 } else if (sipmethod == SIP_REGISTER) {
18957 res = handle_response_register(p, resp, rest, req, seqno);
18958 } else if (sipmethod == SIP_SUBSCRIBE) {
18959 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
18960 handle_response_subscribe(p, resp, rest, req, seqno);
18961 } else if (sipmethod == SIP_BYE) {
18962 pvt_set_needdestroy(p, "received 200 response");
18963 ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
18964 }
18965 break;
18966 case 202:
18967 if (sipmethod == SIP_REFER)
18968 handle_response_refer(p, resp, rest, req, seqno);
18969 break;
18970 case 401:
18971 case 407:
18972 if (sipmethod == SIP_INVITE)
18973 handle_response_invite(p, resp, rest, req, seqno);
18974 else if (sipmethod == SIP_NOTIFY)
18975 handle_response_notify(p, resp, rest, req, seqno);
18976 else if (sipmethod == SIP_REFER)
18977 handle_response_refer(p, resp, rest, req, seqno);
18978 else if (sipmethod == SIP_SUBSCRIBE)
18979 handle_response_subscribe(p, resp, rest, req, seqno);
18980 else if (p->registry && sipmethod == SIP_REGISTER)
18981 res = handle_response_register(p, resp, rest, req, seqno);
18982 else if (sipmethod == SIP_BYE) {
18983 if (p->options)
18984 p->options->auth_type = resp;
18985 if (ast_strlen_zero(p->authname)) {
18986 ast_log(LOG_WARNING, "Asked to authenticate %s, to %s:%d but we have no matching peer!\n",
18987 msg, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
18988 pvt_set_needdestroy(p, "unable to authenticate BYE");
18989 } else if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp, sipmethod, 0)) {
18990 ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
18991 pvt_set_needdestroy(p, "failed to authenticate BYE");
18992 }
18993 } else {
18994 ast_log(LOG_WARNING, "Got authentication request (%d) on %s to '%s'\n", resp, sip_methods[sipmethod].text, get_header(req, "To"));
18995 pvt_set_needdestroy(p, "received 407 response");
18996 }
18997 break;
18998 case 403:
18999 if (sipmethod == SIP_INVITE)
19000 handle_response_invite(p, resp, rest, req, seqno);
19001 else if (sipmethod == SIP_SUBSCRIBE)
19002 handle_response_subscribe(p, resp, rest, req, seqno);
19003 else if (p->registry && sipmethod == SIP_REGISTER)
19004 res = handle_response_register(p, resp, rest, req, seqno);
19005 else {
19006 ast_log(LOG_WARNING, "Forbidden - maybe wrong password on authentication for %s\n", msg);
19007 pvt_set_needdestroy(p, "received 403 response");
19008 }
19009 break;
19010 case 404:
19011 if (p->registry && sipmethod == SIP_REGISTER)
19012 res = handle_response_register(p, resp, rest, req, seqno);
19013 else if (sipmethod == SIP_INVITE)
19014 handle_response_invite(p, resp, rest, req, seqno);
19015 else if (sipmethod == SIP_SUBSCRIBE)
19016 handle_response_subscribe(p, resp, rest, req, seqno);
19017 else if (owner)
19018 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
19019 break;
19020 case 423:
19021 if (sipmethod == SIP_REGISTER)
19022 res = handle_response_register(p, resp, rest, req, seqno);
19023 break;
19024 case 408:
19025 if (sipmethod == SIP_INVITE)
19026 handle_response_invite(p, resp, rest, req, seqno);
19027 else if (sipmethod == SIP_REGISTER)
19028 res = handle_response_register(p, resp, rest, req, seqno);
19029 else if (sipmethod == SIP_BYE) {
19030 pvt_set_needdestroy(p, "received 408 response");
19031 ast_debug(4, "Got timeout on bye. Thanks for the answer. Now, kill this call\n");
19032 } else {
19033 if (owner)
19034 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
19035 pvt_set_needdestroy(p, "received 408 response");
19036 }
19037 break;
19038
19039 case 422:
19040 if (sipmethod == SIP_INVITE) {
19041 handle_response_invite(p, resp, rest, req, seqno);
19042 }
19043 break;
19044
19045 case 481:
19046 if (sipmethod == SIP_INVITE) {
19047 handle_response_invite(p, resp, rest, req, seqno);
19048 } else if (sipmethod == SIP_REFER) {
19049 handle_response_refer(p, resp, rest, req, seqno);
19050 } else if (sipmethod == SIP_SUBSCRIBE) {
19051 handle_response_subscribe(p, resp, rest, req, seqno);
19052 } else if (sipmethod == SIP_NOTIFY) {
19053 pvt_set_needdestroy(p, "received 481 response");
19054 } else if (sipmethod == SIP_BYE) {
19055
19056
19057 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
19058 } else if (sipmethod == SIP_CANCEL) {
19059
19060
19061 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
19062 } else {
19063 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
19064
19065 }
19066 break;
19067 case 487:
19068 if (sipmethod == SIP_INVITE)
19069 handle_response_invite(p, resp, rest, req, seqno);
19070 break;
19071 case 415:
19072 case 488:
19073 case 606:
19074 if (sipmethod == SIP_INVITE)
19075 handle_response_invite(p, resp, rest, req, seqno);
19076 break;
19077 case 491:
19078 if (sipmethod == SIP_INVITE)
19079 handle_response_invite(p, resp, rest, req, seqno);
19080 else {
19081 ast_debug(1, "Got 491 on %s, unsupported. Call ID %s\n", sip_methods[sipmethod].text, p->callid);
19082 pvt_set_needdestroy(p, "received 491 response");
19083 }
19084 break;
19085 case 501:
19086 if (sipmethod == SIP_INVITE)
19087 handle_response_invite(p, resp, rest, req, seqno);
19088 else if (sipmethod == SIP_REFER)
19089 handle_response_refer(p, resp, rest, req, seqno);
19090 else
19091 ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n", ast_inet_ntoa(p->sa.sin_addr), msg);
19092 break;
19093 case 603:
19094 if (sipmethod == SIP_REFER) {
19095 handle_response_refer(p, resp, rest, req, seqno);
19096 break;
19097 }
19098
19099 default:
19100 if ((resp >= 300) && (resp < 700)) {
19101
19102 if ((resp != 487))
19103 ast_verb(3, "Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_inet_ntoa(p->sa.sin_addr));
19104
19105 if (sipmethod == SIP_INVITE)
19106 stop_media_flows(p);
19107
19108
19109 switch(resp) {
19110 case 300:
19111 case 301:
19112 case 302:
19113 case 305:
19114 parse_moved_contact(p, req);
19115
19116 case 486:
19117 case 600:
19118 case 603:
19119 if (p->owner)
19120 ast_queue_control(p->owner, AST_CONTROL_BUSY);
19121 break;
19122 case 482:
19123
19124
19125
19126
19127
19128 if (p->owner && ast_test_flag(&p->flags[1], SIP_PAGE2_FORWARD_LOOP_DETECTED)) {
19129 ast_debug(1, "Hairpin detected, setting up call forward for what it's worth\n");
19130 ast_string_field_build(p->owner, call_forward,
19131 "Local/%s@%s", p->username, p->context);
19132 }
19133
19134 case 480:
19135 case 404:
19136 case 410:
19137 case 400:
19138 case 500:
19139 if (sipmethod == SIP_REFER) {
19140 handle_response_refer(p, resp, rest, req, seqno);
19141 break;
19142 } else if (sipmethod == SIP_SUBSCRIBE) {
19143 handle_response_subscribe(p, resp, rest, req, seqno);
19144 break;
19145 }
19146
19147 case 502:
19148 case 503:
19149 case 504:
19150 if (owner)
19151 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
19152 break;
19153 default:
19154
19155 if (owner && sipmethod != SIP_MESSAGE && sipmethod != SIP_INFO && sipmethod != SIP_BYE)
19156 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
19157 break;
19158 }
19159
19160 if (sipmethod == SIP_INVITE)
19161 transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
19162 if (sipmethod != SIP_MESSAGE && sipmethod != SIP_INFO)
19163 sip_alreadygone(p);
19164 if (!p->owner) {
19165 pvt_set_needdestroy(p, "transaction completed");
19166 }
19167 } else if ((resp >= 100) && (resp < 200)) {
19168 if (sipmethod == SIP_INVITE) {
19169 if (!req->ignore && sip_cancel_destroy(p))
19170 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
19171 if (find_sdp(req))
19172 process_sdp(p, req, SDP_T38_NONE);
19173 if (p->owner) {
19174
19175 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
19176 }
19177 }
19178 } else
19179 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));
19180 }
19181 } else {
19182
19183
19184 if (req->debug)
19185 ast_verbose("SIP Response message for INCOMING dialog %s arrived\n", msg);
19186
19187 if (sipmethod == SIP_INVITE && resp == 200) {
19188
19189
19190 char tag[128];
19191
19192 gettag(req, "To", tag, sizeof(tag));
19193 ast_string_field_set(p, theirtag, tag);
19194 }
19195
19196 switch(resp) {
19197 case 200:
19198 if (sipmethod == SIP_INVITE) {
19199 handle_response_invite(p, resp, rest, req, seqno);
19200 } else if (sipmethod == SIP_CANCEL) {
19201 ast_debug(1, "Got 200 OK on CANCEL\n");
19202
19203
19204 } else if (sipmethod == SIP_NOTIFY) {
19205
19206 if (p->owner) {
19207 if (p->refer) {
19208 ast_debug(1, "Got 200 OK on NOTIFY for transfer\n");
19209 } else
19210 ast_log(LOG_WARNING, "Notify answer on an owned channel?\n");
19211
19212 } else {
19213 if (!p->subscribed && !p->refer) {
19214 pvt_set_needdestroy(p, "transaction completed");
19215 }
19216 if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
19217
19218 ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
19219 cb_extensionstate((char *)p->context, (char *)p->exten, p->laststate, (void *) p);
19220 }
19221 }
19222 } else if (sipmethod == SIP_BYE) {
19223 pvt_set_needdestroy(p, "transaction completed");
19224 } else if (sipmethod == SIP_MESSAGE || sipmethod == SIP_INFO) {
19225
19226
19227 ;
19228 }
19229 break;
19230 case 202:
19231 if (sipmethod == SIP_REFER)
19232 handle_response_refer(p, resp, rest, req, seqno);
19233 break;
19234 case 401:
19235 case 407:
19236 if (sipmethod == SIP_REFER)
19237 handle_response_refer(p, resp, rest, req, seqno);
19238 else if (sipmethod == SIP_INVITE)
19239 handle_response_invite(p, resp, rest, req, seqno);
19240 else if (sipmethod == SIP_BYE) {
19241 if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, sipmethod, 0)) {
19242 ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
19243 pvt_set_needdestroy(p, "failed to authenticate BYE");
19244 }
19245 }
19246 break;
19247 case 481:
19248 if (sipmethod == SIP_INVITE) {
19249
19250 handle_response_invite(p, resp, rest, req, seqno);
19251 } else if (sipmethod == SIP_BYE) {
19252 pvt_set_needdestroy(p, "received 481 response");
19253 } else if (sipmethod == SIP_NOTIFY) {
19254 pvt_set_needdestroy(p, "received 481 response");
19255 } else if (sipdebug) {
19256 ast_debug(1, "Remote host can't match request %s to call '%s'. Giving up\n", sip_methods[sipmethod].text, p->callid);
19257 }
19258 break;
19259 case 501:
19260 if (sipmethod == SIP_INVITE)
19261 handle_response_invite(p, resp, rest, req, seqno);
19262 else if (sipmethod == SIP_REFER)
19263 handle_response_refer(p, resp, rest, req, seqno);
19264 break;
19265 case 603:
19266 if (sipmethod == SIP_REFER) {
19267 handle_response_refer(p, resp, rest, req, seqno);
19268 break;
19269 }
19270
19271 default:
19272 if ((resp >= 100) && (resp < 200)) {
19273 if (sipmethod == SIP_INVITE) {
19274 if (!req->ignore && sip_cancel_destroy(p))
19275 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
19276 }
19277 }
19278 if ((resp >= 300) && (resp < 700)) {
19279 if ((resp != 487))
19280 ast_verb(3, "Incoming call: Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_inet_ntoa(p->sa.sin_addr));
19281 switch(resp) {
19282 case 415:
19283 case 488:
19284 case 603:
19285 case 500:
19286 case 502:
19287 case 503:
19288 case 504:
19289
19290
19291 if (sipmethod == SIP_INVITE && sip_cancel_destroy(p))
19292 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
19293 break;
19294 }
19295 }
19296 break;
19297 }
19298 }
19299 }
19300
19301
19302
19303
19304
19305
19306
19307 static void *sip_park_thread(void *stuff)
19308 {
19309 struct ast_channel *transferee, *transferer;
19310 struct sip_dual *d;
19311 struct sip_request req = {0,};
19312 int ext;
19313 int res;
19314
19315 d = stuff;
19316 transferee = d->chan1;
19317 transferer = d->chan2;
19318 copy_request(&req, &d->req);
19319
19320 if (!transferee || !transferer) {
19321 ast_log(LOG_ERROR, "Missing channels for parking! Transferer %s Transferee %s\n", transferer ? "<available>" : "<missing>", transferee ? "<available>" : "<missing>" );
19322 deinit_req(&d->req);
19323 ast_free(d);
19324 return NULL;
19325 }
19326 ast_debug(4, "SIP Park: Transferer channel %s, Transferee %s\n", transferer->name, transferee->name);
19327
19328 ast_channel_lock(transferee);
19329 if (ast_do_masquerade(transferee)) {
19330 ast_log(LOG_WARNING, "Masquerade failed.\n");
19331 transmit_response(transferer->tech_pvt, "503 Internal error", &req);
19332 ast_channel_unlock(transferee);
19333 deinit_req(&d->req);
19334 ast_free(d);
19335 return NULL;
19336 }
19337 ast_channel_unlock(transferee);
19338
19339 res = ast_park_call(transferee, transferer, 0, &ext);
19340
19341
19342 #ifdef WHEN_WE_KNOW_THAT_THE_CLIENT_SUPPORTS_MESSAGE
19343 if (!res) {
19344 transmit_message_with_text(transferer->tech_pvt, "Unable to park call.\n");
19345 } else {
19346
19347 sprintf(buf, "Call parked on extension '%d'", ext);
19348 transmit_message_with_text(transferer->tech_pvt, buf);
19349 }
19350 #endif
19351
19352
19353
19354 if (!res) {
19355
19356 append_history(transferer->tech_pvt, "SIPpark", "Parked call on %d", ext);
19357 transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "200 OK", TRUE);
19358 transferer->hangupcause = AST_CAUSE_NORMAL_CLEARING;
19359 ast_hangup(transferer);
19360 ast_debug(1, "SIP Call parked on extension '%d'\n", ext);
19361 } else {
19362 transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "503 Service Unavailable", TRUE);
19363 append_history(transferer->tech_pvt, "SIPpark", "Parking failed\n");
19364 ast_debug(1, "SIP Call parked failed \n");
19365
19366 }
19367 deinit_req(&d->req);
19368 ast_free(d);
19369 return NULL;
19370 }
19371
19372
19373
19374
19375 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno)
19376 {
19377 struct sip_dual *d;
19378 struct ast_channel *transferee, *transferer;
19379
19380 pthread_t th;
19381
19382 transferee = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan1->accountcode, chan1->exten, chan1->context, chan1->amaflags, "Parking/%s", chan1->name);
19383 transferer = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan2->accountcode, chan2->exten, chan2->context, chan2->amaflags, "SIPPeer/%s", chan2->name);
19384 if ((!transferer) || (!transferee)) {
19385 if (transferee) {
19386 transferee->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
19387 ast_hangup(transferee);
19388 }
19389 if (transferer) {
19390 transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
19391 ast_hangup(transferer);
19392 }
19393 return -1;
19394 }
19395
19396
19397 transferee->readformat = chan1->readformat;
19398 transferee->writeformat = chan1->writeformat;
19399
19400
19401 ast_channel_masquerade(transferee, chan1);
19402
19403
19404 ast_copy_string(transferee->context, chan1->context, sizeof(transferee->context));
19405 ast_copy_string(transferee->exten, chan1->exten, sizeof(transferee->exten));
19406 transferee->priority = chan1->priority;
19407
19408
19409
19410
19411
19412 transferer->readformat = chan2->readformat;
19413 transferer->writeformat = chan2->writeformat;
19414 if (!ast_strlen_zero(chan2->parkinglot))
19415 ast_string_field_set(transferer, parkinglot, chan2->parkinglot);
19416
19417
19418
19419
19420 while (ast_channel_trylock(chan2)) {
19421 struct sip_pvt *pvt = chan2->tech_pvt;
19422 sip_pvt_unlock(pvt);
19423 usleep(1);
19424 sip_pvt_lock(pvt);
19425 }
19426 ast_channel_masquerade(transferer, chan2);
19427 ast_channel_unlock(chan2);
19428
19429
19430 ast_copy_string(transferer->context, chan2->context, sizeof(transferer->context));
19431 ast_copy_string(transferer->exten, chan2->exten, sizeof(transferer->exten));
19432 transferer->priority = chan2->priority;
19433
19434 ast_channel_lock(transferer);
19435 if (ast_do_masquerade(transferer)) {
19436 ast_log(LOG_WARNING, "Masquerade failed :(\n");
19437 ast_channel_unlock(transferer);
19438 transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
19439 ast_hangup(transferer);
19440 return -1;
19441 }
19442 ast_channel_unlock(transferer);
19443 if (!transferer || !transferee) {
19444 if (!transferer) {
19445 ast_debug(1, "No transferer channel, giving up parking\n");
19446 }
19447 if (!transferee) {
19448 ast_debug(1, "No transferee channel, giving up parking\n");
19449 }
19450 return -1;
19451 }
19452 if (!(d = ast_calloc(1, sizeof(*d)))) {
19453 return -1;
19454 }
19455
19456
19457 copy_request(&d->req, req);
19458 d->chan1 = transferee;
19459 d->chan2 = transferer;
19460 d->seqno = seqno;
19461 if (ast_pthread_create_detached_background(&th, NULL, sip_park_thread, d) < 0) {
19462
19463 deinit_req(&d->req);
19464 ast_free(d);
19465
19466 return -1;
19467 }
19468 return 0;
19469 }
19470
19471
19472
19473
19474 static void ast_quiet_chan(struct ast_channel *chan)
19475 {
19476 if (chan && chan->_state == AST_STATE_UP) {
19477 if (ast_test_flag(chan, AST_FLAG_MOH))
19478 ast_moh_stop(chan);
19479 else if (chan->generatordata)
19480 ast_deactivate_generator(chan);
19481 }
19482 }
19483
19484
19485
19486 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target)
19487 {
19488 int res = 0;
19489 struct ast_channel *peera = NULL,
19490 *peerb = NULL,
19491 *peerc = NULL,
19492 *peerd = NULL;
19493
19494
19495
19496
19497 ast_debug(4, "Sip transfer:--------------------\n");
19498 if (transferer->chan1)
19499 ast_debug(4, "-- Transferer to PBX channel: %s State %s\n", transferer->chan1->name, ast_state2str(transferer->chan1->_state));
19500 else
19501 ast_debug(4, "-- No transferer first channel - odd??? \n");
19502 if (target->chan1)
19503 ast_debug(4, "-- Transferer to PBX second channel (target): %s State %s\n", target->chan1->name, ast_state2str(target->chan1->_state));
19504 else
19505 ast_debug(4, "-- No target first channel ---\n");
19506 if (transferer->chan2)
19507 ast_debug(4, "-- Bridged call to transferee: %s State %s\n", transferer->chan2->name, ast_state2str(transferer->chan2->_state));
19508 else
19509 ast_debug(4, "-- No bridged call to transferee\n");
19510 if (target->chan2)
19511 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)");
19512 else
19513 ast_debug(4, "-- No target second channel ---\n");
19514 ast_debug(4, "-- END Sip transfer:--------------------\n");
19515 if (transferer->chan2) {
19516 peera = transferer->chan1;
19517 peerb = target->chan1;
19518 peerc = transferer->chan2;
19519 peerd = target->chan2;
19520 ast_debug(3, "SIP transfer: Four channels to handle\n");
19521 } else if (target->chan2) {
19522 peera = target->chan1;
19523 peerb = transferer->chan1;
19524 peerc = target->chan2;
19525 peerd = transferer->chan2;
19526 ast_debug(3, "SIP transfer: Three channels to handle\n");
19527 }
19528
19529 if (peera && peerb && peerc && (peerb != peerc)) {
19530 ast_quiet_chan(peera);
19531 ast_quiet_chan(peerb);
19532 ast_quiet_chan(peerc);
19533 if (peerd)
19534 ast_quiet_chan(peerd);
19535
19536 ast_debug(4, "SIP transfer: trying to masquerade %s into %s\n", peerc->name, peerb->name);
19537 if (ast_channel_masquerade(peerb, peerc)) {
19538 ast_log(LOG_WARNING, "Failed to masquerade %s into %s\n", peerb->name, peerc->name);
19539 res = -1;
19540 } else
19541 ast_debug(4, "SIP transfer: Succeeded to masquerade channels.\n");
19542 return res;
19543 } else {
19544 ast_log(LOG_NOTICE, "SIP Transfer attempted with no appropriate bridged calls to transfer\n");
19545 if (transferer->chan1)
19546 ast_softhangup_nolock(transferer->chan1, AST_SOFTHANGUP_DEV);
19547 if (target->chan1)
19548 ast_softhangup_nolock(target->chan1, AST_SOFTHANGUP_DEV);
19549 return -1;
19550 }
19551 return 0;
19552 }
19553
19554
19555
19556
19557
19558
19559 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize)
19560 {
19561 const char *thetag;
19562
19563 if (!tagbuf)
19564 return NULL;
19565 tagbuf[0] = '\0';
19566 thetag = get_header(req, header);
19567 thetag = strcasestr(thetag, ";tag=");
19568 if (thetag) {
19569 thetag += 5;
19570 ast_copy_string(tagbuf, thetag, tagbufsize);
19571 return strsep(&tagbuf, ";");
19572 }
19573 return NULL;
19574 }
19575
19576
19577 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e)
19578 {
19579
19580
19581 int res = 0;
19582 const char *event = get_header(req, "Event");
19583 char *eventid = NULL;
19584 char *sep;
19585
19586 if( (sep = strchr(event, ';')) ) {
19587 *sep++ = '\0';
19588 eventid = sep;
19589 }
19590
19591 if (sipdebug)
19592 ast_debug(2, "Got NOTIFY Event: %s\n", event);
19593
19594 if (!strcmp(event, "refer")) {
19595
19596
19597
19598
19599
19600 char buf[1024];
19601 char *cmd, *code;
19602 int respcode;
19603 int success = TRUE;
19604
19605
19606
19607
19608
19609
19610
19611
19612 if (strncasecmp(get_header(req, "Content-Type"), "message/sipfrag", strlen("message/sipfrag"))) {
19613
19614 transmit_response(p, "400 Bad request", req);
19615 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19616 return -1;
19617 }
19618
19619
19620 if (get_msg_text(buf, sizeof(buf), req, TRUE)) {
19621 ast_log(LOG_WARNING, "Unable to retrieve attachment from NOTIFY %s\n", p->callid);
19622 transmit_response(p, "400 Bad request", req);
19623 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19624 return -1;
19625 }
19626
19627
19628
19629
19630
19631
19632
19633
19634
19635
19636
19637
19638
19639
19640
19641
19642
19643
19644
19645
19646
19647 ast_debug(3, "* SIP Transfer NOTIFY Attachment: \n---%s\n---\n", buf);
19648 cmd = ast_skip_blanks(buf);
19649 code = cmd;
19650
19651 while(*code && (*code > 32)) {
19652 code++;
19653 }
19654 *code++ = '\0';
19655 code = ast_skip_blanks(code);
19656 sep = code;
19657 sep++;
19658 while(*sep && (*sep > 32)) {
19659 sep++;
19660 }
19661 *sep++ = '\0';
19662 respcode = atoi(code);
19663 switch (respcode) {
19664 case 100:
19665 case 101:
19666
19667 break;
19668 case 183:
19669
19670 break;
19671 case 200:
19672
19673 break;
19674 case 301:
19675 case 302:
19676
19677 success = FALSE;
19678 break;
19679 case 503:
19680
19681 success = FALSE;
19682 break;
19683 case 603:
19684
19685 success = FALSE;
19686 break;
19687 }
19688 if (!success) {
19689 ast_log(LOG_NOTICE, "Transfer failed. Sorry. Nothing further to do with this call\n");
19690 }
19691
19692
19693 transmit_response(p, "200 OK", req);
19694 } else if (p->mwi && !strcmp(event, "message-summary")) {
19695 char *c = ast_strdupa(get_body(req, "Voice-Message", ':'));
19696
19697 if (!ast_strlen_zero(c)) {
19698 char *old = strsep(&c, " ");
19699 char *new = strsep(&old, "/");
19700 struct ast_event *event;
19701
19702 if ((event = ast_event_new(AST_EVENT_MWI,
19703 AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, p->mwi->mailbox,
19704 AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, "SIP_Remote",
19705 AST_EVENT_IE_NEWMSGS, AST_EVENT_IE_PLTYPE_UINT, atoi(new),
19706 AST_EVENT_IE_OLDMSGS, AST_EVENT_IE_PLTYPE_UINT, atoi(old),
19707 AST_EVENT_IE_END))) {
19708 ast_event_queue_and_cache(event);
19709 }
19710 }
19711
19712 transmit_response(p, "200 OK", req);
19713 } else if (!strcmp(event, "keep-alive")) {
19714
19715
19716 transmit_response(p, "200 OK", req);
19717 } else {
19718
19719 transmit_response(p, "489 Bad event", req);
19720 res = -1;
19721 }
19722
19723 if (!p->lastinvite)
19724 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19725
19726 return res;
19727 }
19728
19729
19730
19731
19732 static int handle_request_options(struct sip_pvt *p, struct sip_request *req)
19733 {
19734 int res;
19735
19736
19737
19738
19739
19740
19741
19742
19743
19744
19745
19746 if (p->lastinvite) {
19747
19748 transmit_response_with_allow(p, "200 OK", req, 0);
19749 return 0;
19750 }
19751
19752 res = get_destination(p, req);
19753 build_contact(p);
19754
19755 if (ast_strlen_zero(p->context))
19756 ast_string_field_set(p, context, sip_cfg.default_context);
19757
19758 if (ast_shutting_down())
19759 transmit_response_with_allow(p, "503 Unavailable", req, 0);
19760 else if (res < 0)
19761 transmit_response_with_allow(p, "404 Not Found", req, 0);
19762 else
19763 transmit_response_with_allow(p, "200 OK", req, 0);
19764
19765
19766
19767 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19768
19769 return res;
19770 }
19771
19772
19773
19774
19775
19776
19777
19778
19779
19780
19781 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin, int *nounlock)
19782 {
19783 int earlyreplace = 0;
19784 int oneleggedreplace = 0;
19785 struct ast_channel *c = p->owner;
19786 struct ast_channel *replacecall = p->refer->refer_call->owner;
19787 struct ast_channel *targetcall;
19788
19789 struct ast_channel *test;
19790
19791
19792 if (replacecall->_state == AST_STATE_RING)
19793 earlyreplace = 1;
19794
19795
19796 if (!(targetcall = ast_bridged_channel(replacecall))) {
19797
19798 if (!earlyreplace) {
19799 ast_debug(2, " Attended transfer attempted to replace call with no bridge (maybe ringing). Channel %s!\n", replacecall->name);
19800 oneleggedreplace = 1;
19801 }
19802 }
19803 if (targetcall && targetcall->_state == AST_STATE_RINGING)
19804 ast_debug(4, "SIP transfer: Target channel is in ringing state\n");
19805
19806 if (targetcall)
19807 ast_debug(4, "SIP transfer: Invite Replace incoming channel should bridge to channel %s while hanging up channel %s\n", targetcall->name, replacecall->name);
19808 else
19809 ast_debug(4, "SIP transfer: Invite Replace incoming channel should replace and hang up channel %s (one call leg)\n", replacecall->name);
19810
19811 if (req->ignore) {
19812 ast_log(LOG_NOTICE, "Ignoring this INVITE with replaces in a stupid way.\n");
19813
19814
19815
19816 transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE);
19817
19818 if (c) {
19819 *nounlock = 1;
19820 ast_channel_unlock(c);
19821 }
19822 ast_channel_unlock(replacecall);
19823 sip_pvt_unlock(p->refer->refer_call);
19824 return 1;
19825 }
19826 if (!c) {
19827
19828 ast_log(LOG_ERROR, "Unable to create new channel. Invite/replace failed.\n");
19829 transmit_response_reliable(p, "503 Service Unavailable", req);
19830 append_history(p, "Xfer", "INVITE/Replace Failed. No new channel.");
19831 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19832 ast_channel_unlock(replacecall);
19833 sip_pvt_unlock(p->refer->refer_call);
19834 return 1;
19835 }
19836 append_history(p, "Xfer", "INVITE/Replace received");
19837
19838
19839
19840
19841
19842
19843
19844
19845
19846
19847
19848 transmit_response(p, "100 Trying", req);
19849 ast_setstate(c, AST_STATE_RING);
19850
19851
19852
19853
19854
19855 transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE);
19856
19857 ast_setstate(c, AST_STATE_UP);
19858
19859
19860 ast_quiet_chan(replacecall);
19861 ast_quiet_chan(targetcall);
19862 ast_debug(4, "Invite/Replaces: preparing to masquerade %s into %s\n", c->name, replacecall->name);
19863
19864
19865 if (! earlyreplace && ! oneleggedreplace )
19866 ast_set_flag(&p->refer->refer_call->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
19867
19868
19869 if(ast_channel_masquerade(replacecall, c))
19870 ast_log(LOG_ERROR, "Failed to masquerade C into Replacecall\n");
19871 else
19872 ast_debug(4, "Invite/Replaces: Going to masquerade %s into %s\n", c->name, replacecall->name);
19873
19874
19875 if (ast_do_masquerade(replacecall)) {
19876 ast_log(LOG_WARNING, "Failed to perform masquerade with INVITE replaces\n");
19877 }
19878
19879 if (earlyreplace || oneleggedreplace ) {
19880 c->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
19881 }
19882
19883 ast_setstate(c, AST_STATE_DOWN);
19884 ast_debug(4, "After transfer:----------------------------\n");
19885 ast_debug(4, " -- C: %s State %s\n", c->name, ast_state2str(c->_state));
19886 if (replacecall)
19887 ast_debug(4, " -- replacecall: %s State %s\n", replacecall->name, ast_state2str(replacecall->_state));
19888 if (p->owner) {
19889 ast_debug(4, " -- P->owner: %s State %s\n", p->owner->name, ast_state2str(p->owner->_state));
19890 test = ast_bridged_channel(p->owner);
19891 if (test)
19892 ast_debug(4, " -- Call bridged to P->owner: %s State %s\n", test->name, ast_state2str(test->_state));
19893 else
19894 ast_debug(4, " -- No call bridged to C->owner \n");
19895 } else
19896 ast_debug(4, " -- No channel yet \n");
19897 ast_debug(4, "End After transfer:----------------------------\n");
19898
19899
19900 ast_channel_unlock(replacecall);
19901 ast_channel_unlock(c);
19902 sip_pvt_unlock(p->refer->refer_call);
19903 sip_pvt_unlock(p);
19904 *nounlock = 1;
19905
19906
19907 c->tech_pvt = dialog_unref(c->tech_pvt, "unref dialog c->tech_pvt");
19908 ast_hangup(c);
19909 sip_pvt_lock(p);
19910
19911 return 0;
19912 }
19913
19914
19915
19916
19917
19918
19919
19920
19921
19922
19923
19924
19925
19926
19927
19928
19929
19930
19931 static int sip_uri_params_cmp(const char *input1, const char *input2)
19932 {
19933 char *params1 = NULL;
19934 char *params2 = NULL;
19935 char *pos1;
19936 char *pos2;
19937 int zerolength1 = 0;
19938 int zerolength2 = 0;
19939 int maddrmatch = 0;
19940 int ttlmatch = 0;
19941 int usermatch = 0;
19942 int methodmatch = 0;
19943
19944 if (ast_strlen_zero(input1)) {
19945 zerolength1 = 1;
19946 } else {
19947 params1 = ast_strdupa(input1);
19948 }
19949 if (ast_strlen_zero(input2)) {
19950 zerolength2 = 1;
19951 } else {
19952 params2 = ast_strdupa(input2);
19953 }
19954
19955
19956
19957
19958 if (zerolength1 && zerolength2) {
19959 return 0;
19960 }
19961
19962 for (pos1 = strsep(¶ms1, ";"); pos1; pos1 = strsep(¶ms1, ";")) {
19963 char *value1 = pos1;
19964 char *name1 = strsep(&value1, "=");
19965 char *params2dup = NULL;
19966 int matched = 0;
19967 if (!value1) {
19968 value1 = "";
19969 }
19970
19971
19972
19973
19974 if (!zerolength2) {
19975 params2dup = ast_strdupa(params2);
19976 }
19977 for (pos2 = strsep(¶ms2dup, ";"); pos2; pos2 = strsep(¶ms2dup, ";")) {
19978 char *name2 = pos2;
19979 char *value2 = strchr(pos2, '=');
19980 if (!value2) {
19981 value2 = "";
19982 } else {
19983 *value2++ = '\0';
19984 }
19985 if (!strcasecmp(name1, name2)) {
19986 if (strcasecmp(value1, value2)) {
19987 goto fail;
19988 } else {
19989 matched = 1;
19990 break;
19991 }
19992 }
19993 }
19994
19995 if (!strcasecmp(name1, "maddr")) {
19996 if (matched) {
19997 maddrmatch = 1;
19998 } else {
19999 goto fail;
20000 }
20001 } else if (!strcasecmp(name1, "ttl")) {
20002 if (matched) {
20003 ttlmatch = 1;
20004 } else {
20005 goto fail;
20006 }
20007 } else if (!strcasecmp(name1, "user")) {
20008 if (matched) {
20009 usermatch = 1;
20010 } else {
20011 goto fail;
20012 }
20013 } else if (!strcasecmp(name1, "method")) {
20014 if (matched) {
20015 methodmatch = 1;
20016 } else {
20017 goto fail;
20018 }
20019 }
20020 }
20021
20022
20023
20024
20025
20026 for (pos2 = strsep(¶ms2, ";"); pos2; pos2 = strsep(¶ms2, ";")) {
20027 char *value2 = pos2;
20028 char *name2 = strsep(&value2, "=");
20029 if (!value2) {
20030 value2 = "";
20031 }
20032 if ((!strcasecmp(name2, "maddr") && !maddrmatch) ||
20033 (!strcasecmp(name2, "ttl") && !ttlmatch) ||
20034 (!strcasecmp(name2, "user") && !usermatch) ||
20035 (!strcasecmp(name2, "method") && !methodmatch)) {
20036 goto fail;
20037 }
20038 }
20039 return 0;
20040
20041 fail:
20042 return 1;
20043 }
20044
20045
20046
20047
20048
20049
20050
20051
20052
20053
20054
20055
20056 static int sip_uri_headers_cmp(const char *input1, const char *input2)
20057 {
20058 char *headers1 = NULL;
20059 char *headers2 = NULL;
20060 int zerolength1 = 0;
20061 int zerolength2 = 0;
20062 int different = 0;
20063 char *header1;
20064
20065 if (ast_strlen_zero(input1)) {
20066 zerolength1 = 1;
20067 } else {
20068 headers1 = ast_strdupa(input1);
20069 }
20070
20071 if (ast_strlen_zero(input2)) {
20072 zerolength2 = 1;
20073 } else {
20074 headers2 = ast_strdupa(input2);
20075 }
20076
20077 if ((zerolength1 && !zerolength2) ||
20078 (zerolength2 && !zerolength1))
20079 return 1;
20080
20081 if (zerolength1 && zerolength2)
20082 return 0;
20083
20084
20085
20086
20087
20088 if (strlen(headers1) != strlen(headers2)) {
20089 return 1;
20090 }
20091
20092 for (header1 = strsep(&headers1, "&"); header1; header1 = strsep(&headers1, "&")) {
20093 if (!strcasestr(headers2, header1)) {
20094 different = 1;
20095 break;
20096 }
20097 }
20098
20099 return different;
20100 }
20101
20102 static int sip_uri_cmp(const char *input1, const char *input2)
20103 {
20104 char *uri1 = ast_strdupa(input1);
20105 char *uri2 = ast_strdupa(input2);
20106 char *host1;
20107 char *host2;
20108 char *params1;
20109 char *params2;
20110 char *headers1;
20111 char *headers2;
20112
20113
20114
20115
20116 strsep(&uri1, ":");
20117 strsep(&uri2, ":");
20118
20119 if ((host1 = strchr(uri1, '@'))) {
20120 *host1++ = '\0';
20121 }
20122 if ((host2 = strchr(uri2, '@'))) {
20123 *host2++ = '\0';
20124 }
20125
20126
20127
20128
20129 if ((host1 && !host2) ||
20130 (host2 && !host1) ||
20131 (host1 && host2 && strcmp(uri1, uri2))) {
20132 return 1;
20133 }
20134
20135 if (!host1)
20136 host1 = uri1;
20137 if (!host2)
20138 host2 = uri2;
20139
20140
20141
20142
20143
20144 if ((params1 = strchr(host1, ';'))) {
20145 *params1++ = '\0';
20146 }
20147 if ((params2 = strchr(host2, ';'))) {
20148 *params2++ = '\0';
20149 }
20150
20151
20152
20153
20154 if ((headers1 = strchr(S_OR(params1, host1), '?'))) {
20155 *headers1++ = '\0';
20156 }
20157 if ((headers2 = strchr(S_OR(params2, host2), '?'))) {
20158 *headers2++ = '\0';
20159 }
20160
20161
20162
20163
20164
20165
20166
20167
20168
20169
20170
20171 if (strcasecmp(host1, host2)) {
20172 return 1;
20173 }
20174
20175
20176 if (sip_uri_headers_cmp(headers1, headers2)) {
20177 return 1;
20178 }
20179
20180
20181 return sip_uri_params_cmp(params1, params2);
20182 }
20183
20184 static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context)
20185 {
20186 struct ast_str *str = ast_str_alloca(AST_MAX_EXTENSION + AST_MAX_CONTEXT + 2);
20187 struct ast_app *pickup = pbx_findapp("Pickup");
20188
20189 if (!pickup) {
20190 ast_log(LOG_ERROR, "Unable to perform pickup: Application 'Pickup' not loaded (app_directed_pickup.so).\n");
20191 return -1;
20192 }
20193
20194 ast_str_set(&str, 0, "%s@%s", extension, sip_cfg.notifycid == IGNORE_CONTEXT ? "PICKUPMARK" : context);
20195
20196 ast_debug(2, "About to call Pickup(%s)\n", str->str);
20197
20198
20199
20200
20201 pbx_exec(channel, pickup, str->str);
20202
20203 return 0;
20204 }
20205
20206
20207 static int sip_t38_abort(const void *data)
20208 {
20209 struct sip_pvt *p = (struct sip_pvt *) data;
20210
20211 sip_pvt_lock(p);
20212
20213
20214
20215
20216
20217 if (p->t38id != -1) {
20218 change_t38_state(p, T38_DISABLED);
20219 transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
20220 p->t38id = -1;
20221 dialog_unref(p, "unref the dialog ptr from sip_t38_abort, because it held a dialog ptr");
20222 }
20223 sip_pvt_unlock(p);
20224 return 0;
20225 }
20226
20227
20228
20229
20230
20231
20232
20233 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)
20234 {
20235 int res = 1;
20236 int gotdest;
20237 const char *p_replaces;
20238 char *replace_id = NULL;
20239 int refer_locked = 0;
20240 const char *required;
20241 unsigned int required_profile = 0;
20242 struct ast_channel *c = NULL;
20243 int reinvite = 0;
20244 int rtn;
20245
20246 const char *p_uac_se_hdr;
20247 const char *p_uac_min_se;
20248 int uac_max_se = -1;
20249 int uac_min_se = -1;
20250 int st_active = FALSE;
20251 int st_interval = 0;
20252 enum st_refresher st_ref;
20253 int dlg_min_se = -1;
20254 struct {
20255 char exten[AST_MAX_EXTENSION];
20256 char context[AST_MAX_CONTEXT];
20257 } pickup = {
20258 .exten = "",
20259 };
20260 st_ref = SESSION_TIMER_REFRESHER_AUTO;
20261
20262
20263 if (!p->sipoptions) {
20264 const char *supported = get_header(req, "Supported");
20265 if (!ast_strlen_zero(supported))
20266 parse_sip_options(p, supported);
20267 }
20268
20269
20270 required = get_header(req, "Require");
20271 if (!ast_strlen_zero(required)) {
20272 required_profile = parse_sip_options(NULL, required);
20273 if (required_profile && !(required_profile & (SIP_OPT_REPLACES | SIP_OPT_TIMER))) {
20274
20275 transmit_response_with_unsupported(p, "420 Bad extension (unsupported)", req, required);
20276 ast_log(LOG_WARNING, "Received SIP INVITE with unsupported required extension: %s\n", required);
20277 p->invitestate = INV_COMPLETED;
20278 if (!p->lastinvite)
20279 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20280 res = -1;
20281 goto request_invite_cleanup;
20282 }
20283 }
20284
20285
20286
20287 p->sipoptions |= required_profile;
20288 p->reqsipoptions = required_profile;
20289
20290
20291 if (ast_test_flag(&p->flags[0], SIP_OUTGOING) && p->owner && (p->invitestate != INV_TERMINATED && p->invitestate != INV_CONFIRMED)) {
20292
20293
20294
20295
20296
20297 int different;
20298 char *initial_rlPart2 = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
20299 char *this_rlPart2 = REQ_OFFSET_TO_STR(req, rlPart2);
20300 if (sip_cfg.pedanticsipchecking)
20301 different = sip_uri_cmp(initial_rlPart2, this_rlPart2);
20302 else
20303 different = strcmp(initial_rlPart2, this_rlPart2);
20304 if (!different) {
20305 transmit_response(p, "482 Loop Detected", req);
20306 p->invitestate = INV_COMPLETED;
20307 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20308 res = 0;
20309 goto request_invite_cleanup;
20310 } else {
20311
20312
20313
20314
20315
20316
20317
20318 char *uri = ast_strdupa(this_rlPart2);
20319 char *at = strchr(uri, '@');
20320 char *peerorhost;
20321 ast_debug(2, "Potential spiral detected. Original RURI was %s, new RURI is %s\n", initial_rlPart2, this_rlPart2);
20322 transmit_response(p, "100 Trying", req);
20323 if (at) {
20324 *at = '\0';
20325 }
20326
20327 if ((peerorhost = strchr(uri, ':'))) {
20328 *peerorhost++ = '\0';
20329 }
20330 ast_string_field_set(p, theirtag, NULL);
20331
20332
20333 ast_string_field_set(p->owner, call_forward, peerorhost);
20334 ast_queue_control(p->owner, AST_CONTROL_BUSY);
20335 res = 0;
20336 goto request_invite_cleanup;
20337 }
20338 }
20339
20340 if (!req->ignore && p->pendinginvite) {
20341 if (!ast_test_flag(&p->flags[0], SIP_OUTGOING) && (p->invitestate == INV_COMPLETED || p->invitestate == INV_TERMINATED)) {
20342
20343
20344
20345
20346
20347
20348
20349
20350
20351
20352 __sip_ack(p, p->pendinginvite, 1, 0);
20353 } else {
20354
20355 p->glareinvite = seqno;
20356 if (p->rtp && find_sdp(req)) {
20357 struct sockaddr_in sin;
20358 if (get_ip_and_port_from_sdp(req, SDP_AUDIO, &sin)) {
20359 ast_log(LOG_WARNING, "Failed to set an alternate media source on glared reinvite. Audio may not work properly on this call.\n");
20360 } else {
20361 ast_rtp_set_alt_peer(p->rtp, &sin);
20362 }
20363 if (p->vrtp) {
20364 if (get_ip_and_port_from_sdp(req, SDP_VIDEO, &sin)) {
20365 ast_log(LOG_WARNING, "Failed to set an alternate media source on glared reinvite. Video may not work properly on this call.\n");
20366 } else {
20367 ast_rtp_set_alt_peer(p->vrtp, &sin);
20368 }
20369 }
20370 }
20371 transmit_response_reliable(p, "491 Request Pending", req);
20372 ast_debug(1, "Got INVITE on call where we already have pending INVITE, deferring that - %s\n", p->callid);
20373
20374 res = 0;
20375 goto request_invite_cleanup;
20376 }
20377 }
20378
20379 p_replaces = get_header(req, "Replaces");
20380 if (!ast_strlen_zero(p_replaces)) {
20381
20382 char *ptr;
20383 char *fromtag = NULL;
20384 char *totag = NULL;
20385 char *start, *to;
20386 int error = 0;
20387
20388 if (p->owner) {
20389 ast_debug(3, "INVITE w Replaces on existing call? Refusing action. [%s]\n", p->callid);
20390 transmit_response_reliable(p, "400 Bad request", req);
20391
20392 res = -1;
20393 goto request_invite_cleanup;
20394 }
20395
20396 if (sipdebug)
20397 ast_debug(3, "INVITE part of call transfer. Replaces [%s]\n", p_replaces);
20398
20399 replace_id = ast_strdupa(p_replaces);
20400 ast_uri_decode(replace_id);
20401
20402 if (!p->refer && !sip_refer_allocate(p)) {
20403 transmit_response_reliable(p, "500 Server Internal Error", req);
20404 append_history(p, "Xfer", "INVITE/Replace Failed. Out of memory.");
20405 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20406 p->invitestate = INV_COMPLETED;
20407 res = -1;
20408 goto request_invite_cleanup;
20409 }
20410
20411
20412
20413
20414
20415
20416
20417
20418
20419
20420 replace_id = ast_skip_blanks(replace_id);
20421
20422 start = replace_id;
20423 while ( (ptr = strsep(&start, ";")) ) {
20424 ptr = ast_skip_blanks(ptr);
20425 if ( (to = strcasestr(ptr, "to-tag=") ) )
20426 totag = to + 7;
20427 else if ( (to = strcasestr(ptr, "from-tag=") ) ) {
20428 fromtag = to + 9;
20429 fromtag = strsep(&fromtag, "&");
20430 }
20431 }
20432
20433 if (sipdebug)
20434 ast_debug(4, "Invite/replaces: Will use Replace-Call-ID : %s Fromtag: %s Totag: %s\n",
20435 replace_id,
20436 fromtag ? fromtag : "<no from tag>",
20437 totag ? totag : "<no to tag>");
20438
20439
20440
20441
20442
20443 if (strncmp(replace_id, "pickup-", 7) == 0) {
20444 struct sip_pvt *subscription = NULL;
20445 replace_id += 7;
20446
20447 if ((subscription = get_sip_pvt_byid_locked(replace_id, totag, fromtag)) == NULL) {
20448 ast_log(LOG_NOTICE, "Unable to find subscription with call-id: %s\n", replace_id);
20449 transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
20450 error = 1;
20451 } else {
20452 ast_log(LOG_NOTICE, "Trying to pick up %s@%s\n", subscription->exten, subscription->context);
20453 ast_copy_string(pickup.exten, subscription->exten, sizeof(pickup.exten));
20454 ast_copy_string(pickup.context, subscription->context, sizeof(pickup.context));
20455 sip_pvt_unlock(subscription);
20456 if (subscription->owner) {
20457 ast_channel_unlock(subscription->owner);
20458 }
20459 }
20460 }
20461
20462
20463 if (!error && ast_strlen_zero(pickup.exten) && (p->refer->refer_call = get_sip_pvt_byid_locked(replace_id, totag, fromtag)) == NULL) {
20464 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existent call id (%s)!\n", replace_id);
20465 transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
20466 error = 1;
20467 } else {
20468 refer_locked = 1;
20469 }
20470
20471
20472
20473
20474
20475 if (p->refer->refer_call == p) {
20476 ast_log(LOG_NOTICE, "INVITE with replaces into it's own call id (%s == %s)!\n", replace_id, p->callid);
20477 p->refer->refer_call = dialog_unref(p->refer->refer_call, "unref dialog p->refer->refer_call");
20478 transmit_response_reliable(p, "400 Bad request", req);
20479 error = 1;
20480 }
20481
20482 if (!error && ast_strlen_zero(pickup.exten) && !p->refer->refer_call->owner) {
20483
20484 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existing call id (%s)!\n", replace_id);
20485
20486 transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replace)", req);
20487 error = 1;
20488 }
20489
20490 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) {
20491 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-ringing or active call id (%s)!\n", replace_id);
20492 transmit_response_reliable(p, "603 Declined (Replaces)", req);
20493 error = 1;
20494 }
20495
20496 if (error) {
20497 append_history(p, "Xfer", "INVITE/Replace Failed.");
20498 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20499 sip_pvt_unlock(p);
20500 if (p->refer->refer_call) {
20501 sip_pvt_unlock(p->refer->refer_call);
20502 if (p->refer->refer_call->owner) {
20503 ast_channel_unlock(p->refer->refer_call->owner);
20504 }
20505 }
20506 refer_locked = 0;
20507 p->invitestate = INV_COMPLETED;
20508 res = -1;
20509 goto request_invite_cleanup;
20510 }
20511 }
20512
20513
20514
20515
20516 if (!req->ignore) {
20517 int newcall = (p->initreq.headers ? TRUE : FALSE);
20518
20519 if (sip_cancel_destroy(p))
20520 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
20521
20522 p->pendinginvite = seqno;
20523 check_via(p, req);
20524
20525 copy_request(&p->initreq, req);
20526 if (sipdebug)
20527 ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
20528 if (!p->owner) {
20529 if (debug)
20530 ast_verbose("Using INVITE request as basis request - %s\n", p->callid);
20531 if (newcall)
20532 append_history(p, "Invite", "New call: %s", p->callid);
20533 parse_ok_contact(p, req);
20534 } else {
20535 ast_clear_flag(&p->flags[0], SIP_OUTGOING);
20536
20537 if (find_sdp(req)) {
20538 if (process_sdp(p, req, SDP_T38_INITIATE)) {
20539 transmit_response_reliable(p, "488 Not acceptable here", req);
20540 if (!p->lastinvite)
20541 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20542 res = -1;
20543 goto request_invite_cleanup;
20544 }
20545 ast_queue_control(p->owner, AST_CONTROL_SRCUPDATE);
20546 } else {
20547 p->jointcapability = p->capability;
20548 ast_debug(1, "Hm.... No sdp for the moment\n");
20549
20550
20551
20552 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
20553 ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
20554
20555 ast_queue_frame(p->owner, &ast_null_frame);
20556 change_hold_state(p, req, FALSE, 0);
20557 }
20558 }
20559 if (p->do_history)
20560 append_history(p, "ReInv", "Re-invite received");
20561 }
20562 } else if (debug)
20563 ast_verbose("Ignoring this INVITE request\n");
20564
20565 if (!p->lastinvite && !req->ignore && !p->owner) {
20566
20567
20568 res = check_user(p, req, SIP_INVITE, e, XMIT_RELIABLE, sin);
20569 if (res == AUTH_CHALLENGE_SENT) {
20570 p->invitestate = INV_COMPLETED;
20571 res = 0;
20572 goto request_invite_cleanup;
20573 }
20574 if (res < 0) {
20575 if (res == AUTH_FAKE_AUTH) {
20576 ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", get_header(req, "From"));
20577 transmit_fake_auth_response(p, SIP_INVITE, req, XMIT_RELIABLE);
20578 } else {
20579 ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", get_header(req, "From"));
20580 transmit_response_reliable(p, "403 Forbidden", req);
20581 }
20582 p->invitestate = INV_COMPLETED;
20583 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20584 ast_string_field_set(p, theirtag, NULL);
20585 res = 0;
20586 goto request_invite_cleanup;
20587 }
20588
20589
20590 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) && !p->udptl) {
20591 if ((p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr))) {
20592 p->t38_maxdatagram = global_t38_maxdatagram;
20593 set_t38_capabilities(p);
20594 } else {
20595
20596 ast_debug(1, "UDPTL creation failed on dialog.\n");
20597 ast_clear_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT);
20598 }
20599 }
20600
20601 req->authenticated = 1;
20602
20603
20604 if (find_sdp(req)) {
20605 if (process_sdp(p, req, SDP_T38_INITIATE)) {
20606
20607 transmit_response_reliable(p, "488 Not acceptable here", req);
20608 p->invitestate = INV_COMPLETED;
20609 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20610 ast_debug(1, "No compatible codecs for this SIP call.\n");
20611 res = -1;
20612 goto request_invite_cleanup;
20613 }
20614 } else {
20615 p->jointcapability = p->capability;
20616 ast_debug(2, "No SDP in Invite, third party call control\n");
20617 }
20618
20619
20620
20621 if (p->owner)
20622 ast_queue_frame(p->owner, &ast_null_frame);
20623
20624
20625
20626 if (ast_strlen_zero(p->context))
20627 ast_string_field_set(p, context, sip_cfg.default_context);
20628
20629
20630
20631 ast_debug(1, "Checking SIP call limits for device %s\n", p->username);
20632 if ((res = update_call_counter(p, INC_CALL_LIMIT))) {
20633 if (res < 0) {
20634 ast_log(LOG_NOTICE, "Failed to place call for device %s, too many calls\n", p->username);
20635 transmit_response_reliable(p, "480 Temporarily Unavailable (Call limit) ", req);
20636 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20637 p->invitestate = INV_COMPLETED;
20638 }
20639 res = 0;
20640 goto request_invite_cleanup;
20641 }
20642 gotdest = get_destination(p, NULL);
20643 get_rdnis(p, NULL);
20644 extract_uri(p, req);
20645 build_contact(p);
20646
20647 if (p->rtp) {
20648 ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
20649 ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
20650 }
20651
20652 if (!replace_id && gotdest) {
20653 if (gotdest == 1 && ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP))
20654 transmit_response_reliable(p, "484 Address Incomplete", req);
20655 else {
20656 char *decoded_exten = ast_strdupa(p->exten);
20657
20658 transmit_response_reliable(p, "404 Not Found", req);
20659 ast_uri_decode(decoded_exten);
20660 ast_log(LOG_NOTICE, "Call from '%s' to extension"
20661 " '%s' rejected because extension not found in context '%s'.\n",
20662 S_OR(p->username, p->peername), decoded_exten, p->context);
20663 }
20664 p->invitestate = INV_COMPLETED;
20665 update_call_counter(p, DEC_CALL_LIMIT);
20666 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20667 res = 0;
20668 goto request_invite_cleanup;
20669 } else {
20670
20671
20672
20673 if (ast_strlen_zero(p->exten))
20674 ast_string_field_set(p, exten, "s");
20675
20676
20677 make_our_tag(p->tag, sizeof(p->tag));
20678
20679
20680 c = sip_new(p, AST_STATE_DOWN, S_OR(p->peername, NULL));
20681 *recount = 1;
20682
20683
20684 build_route(p, req, 0);
20685
20686 if (c) {
20687
20688 ast_channel_lock(c);
20689 }
20690 }
20691 } else {
20692 if (sipdebug) {
20693 if (!req->ignore)
20694 ast_debug(2, "Got a SIP re-invite for call %s\n", p->callid);
20695 else
20696 ast_debug(2, "Got a SIP re-transmit of INVITE for call %s\n", p->callid);
20697 }
20698 if (!req->ignore)
20699 reinvite = 1;
20700 c = p->owner;
20701 }
20702
20703
20704 if ((p->sipoptions & SIP_OPT_TIMER) && !ast_strlen_zero(get_header(req, "Session-Expires"))) {
20705
20706
20707 ast_debug(2, "Incoming INVITE with 'timer' option supported and \"Session-Expires\" header.\n");
20708
20709
20710 if (!p->stimer)
20711 sip_st_alloc(p);
20712
20713
20714 p_uac_se_hdr = get_header(req, "Session-Expires");
20715 rtn = parse_session_expires(p_uac_se_hdr, &uac_max_se, &st_ref);
20716 if (rtn != 0) {
20717 transmit_response_reliable(p, "400 Session-Expires Invalid Syntax", req);
20718 p->invitestate = INV_COMPLETED;
20719 if (!p->lastinvite) {
20720 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20721 }
20722 res = -1;
20723 goto request_invite_cleanup;
20724 }
20725
20726
20727 p_uac_min_se = get_header(req, "Min-SE");
20728 if (!ast_strlen_zero(p_uac_min_se)) {
20729 rtn = parse_minse(p_uac_min_se, &uac_min_se);
20730 if (rtn != 0) {
20731 transmit_response_reliable(p, "400 Min-SE Invalid Syntax", req);
20732 p->invitestate = INV_COMPLETED;
20733 if (!p->lastinvite) {
20734 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20735 }
20736 res = -1;
20737 goto request_invite_cleanup;
20738 }
20739 }
20740
20741 dlg_min_se = st_get_se(p, FALSE);
20742 switch (st_get_mode(p)) {
20743 case SESSION_TIMER_MODE_ACCEPT:
20744 case SESSION_TIMER_MODE_ORIGINATE:
20745 if (uac_max_se > 0 && uac_max_se < dlg_min_se) {
20746 transmit_response_with_minse(p, "422 Session Interval Too Small", req, dlg_min_se);
20747 p->invitestate = INV_COMPLETED;
20748 if (!p->lastinvite) {
20749 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20750 }
20751 res = -1;
20752 goto request_invite_cleanup;
20753 }
20754
20755 p->stimer->st_active_peer_ua = TRUE;
20756 st_active = TRUE;
20757 if (st_ref == SESSION_TIMER_REFRESHER_AUTO) {
20758 st_ref = st_get_refresher(p);
20759 }
20760
20761 if (uac_max_se > 0) {
20762 int dlg_max_se = st_get_se(p, TRUE);
20763 if (dlg_max_se >= uac_min_se) {
20764 st_interval = (uac_max_se < dlg_max_se) ? uac_max_se : dlg_max_se;
20765 } else {
20766 st_interval = uac_max_se;
20767 }
20768 } else {
20769
20770 st_interval = global_max_se;
20771 }
20772 break;
20773
20774 case SESSION_TIMER_MODE_REFUSE:
20775 if (p->reqsipoptions & SIP_OPT_TIMER) {
20776 transmit_response_with_unsupported(p, "420 Option Disabled", req, required);
20777 ast_log(LOG_WARNING, "Received SIP INVITE with supported but disabled option: %s\n", required);
20778 p->invitestate = INV_COMPLETED;
20779 if (!p->lastinvite) {
20780 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20781 }
20782 res = -1;
20783 goto request_invite_cleanup;
20784 }
20785 break;
20786
20787 default:
20788 ast_log(LOG_ERROR, "Internal Error %d at %s:%d\n", st_get_mode(p), __FILE__, __LINE__);
20789 break;
20790 }
20791 } else {
20792
20793
20794
20795 switch (st_get_mode(p)) {
20796 case SESSION_TIMER_MODE_ORIGINATE:
20797 st_active = TRUE;
20798 st_interval = st_get_se(p, TRUE);
20799 st_ref = SESSION_TIMER_REFRESHER_UAS;
20800 p->stimer->st_active_peer_ua = FALSE;
20801 break;
20802
20803 default:
20804 break;
20805 }
20806 }
20807
20808 if (reinvite == 0) {
20809
20810 if (st_active == TRUE) {
20811 p->stimer->st_active = TRUE;
20812 p->stimer->st_interval = st_interval;
20813 p->stimer->st_ref = st_ref;
20814 start_session_timer(p);
20815 }
20816 } else {
20817 if (p->stimer->st_active == TRUE) {
20818
20819
20820
20821 ast_debug (2, "Restarting session-timers on a refresh - %s\n", p->callid);
20822
20823
20824 if (st_interval > 0) {
20825 p->stimer->st_interval = st_interval;
20826 p->stimer->st_ref = st_ref;
20827 }
20828
20829 restart_session_timer(p);
20830 if (p->stimer->st_expirys > 0) {
20831 p->stimer->st_expirys--;
20832 }
20833 }
20834 }
20835
20836 if (!req->ignore && p)
20837 p->lastinvite = seqno;
20838
20839 if (c && replace_id) {
20840 if (!ast_strlen_zero(pickup.exten)) {
20841 append_history(p, "Xfer", "INVITE/Replace received");
20842
20843
20844 transmit_response(p, "100 Trying", req);
20845 p->invitestate = INV_PROCEEDING;
20846 ast_setstate(c, AST_STATE_RING);
20847
20848
20849 ast_channel_unlock(c);
20850 *nounlock = 1;
20851 do_magic_pickup(c, pickup.exten, pickup.context);
20852
20853
20854 sip_pvt_unlock(p);
20855 ast_hangup(c);
20856 sip_pvt_lock(p);
20857
20858 res = 0;
20859 goto request_invite_cleanup;
20860 } else {
20861
20862 if (sipdebug)
20863 ast_debug(4, "Sending this call to the invite/replcaes handler %s\n", p->callid);
20864 res = handle_invite_replaces(p, req, debug, seqno, sin, nounlock);
20865 refer_locked = 0;
20866 goto request_invite_cleanup;
20867 }
20868 }
20869
20870
20871 if (c) {
20872 enum ast_channel_state c_state = c->_state;
20873
20874 if (c_state != AST_STATE_UP && reinvite &&
20875 (p->invitestate == INV_TERMINATED || p->invitestate == INV_CONFIRMED)) {
20876
20877
20878
20879
20880
20881
20882
20883
20884
20885 c_state = AST_STATE_UP;
20886 }
20887
20888 switch(c_state) {
20889 case AST_STATE_DOWN:
20890 ast_debug(2, "%s: New call is still down.... Trying... \n", c->name);
20891 transmit_provisional_response(p, "100 Trying", req, 0);
20892 p->invitestate = INV_PROCEEDING;
20893 ast_setstate(c, AST_STATE_RING);
20894 if (strcmp(p->exten, ast_pickup_ext())) {
20895 enum ast_pbx_result result;
20896
20897 result = ast_pbx_start(c);
20898
20899 switch(result) {
20900 case AST_PBX_FAILED:
20901 ast_log(LOG_WARNING, "Failed to start PBX :(\n");
20902 p->invitestate = INV_COMPLETED;
20903 transmit_response_reliable(p, "503 Unavailable", req);
20904 break;
20905 case AST_PBX_CALL_LIMIT:
20906 ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
20907 p->invitestate = INV_COMPLETED;
20908 transmit_response_reliable(p, "480 Temporarily Unavailable", req);
20909 break;
20910 case AST_PBX_SUCCESS:
20911
20912 break;
20913 }
20914
20915 if (result) {
20916
20917
20918 ast_channel_unlock(c);
20919 sip_pvt_unlock(p);
20920 ast_hangup(c);
20921 sip_pvt_lock(p);
20922 c = NULL;
20923 }
20924 } else {
20925 ast_channel_unlock(c);
20926 *nounlock = 1;
20927 if (ast_pickup_call(c)) {
20928 ast_log(LOG_NOTICE, "Nothing to pick up for %s\n", p->callid);
20929 transmit_response_reliable(p, "503 Unavailable", req);
20930 sip_alreadygone(p);
20931
20932 sip_pvt_unlock(p);
20933 c->hangupcause = AST_CAUSE_CALL_REJECTED;
20934 } else {
20935 sip_pvt_unlock(p);
20936 ast_setstate(c, AST_STATE_DOWN);
20937 c->hangupcause = AST_CAUSE_NORMAL_CLEARING;
20938 }
20939 p->invitestate = INV_COMPLETED;
20940 ast_hangup(c);
20941 sip_pvt_lock(p);
20942 c = NULL;
20943 }
20944 break;
20945 case AST_STATE_RING:
20946 transmit_provisional_response(p, "100 Trying", req, 0);
20947 p->invitestate = INV_PROCEEDING;
20948 break;
20949 case AST_STATE_RINGING:
20950 transmit_provisional_response(p, "180 Ringing", req, 0);
20951 p->invitestate = INV_PROCEEDING;
20952 break;
20953 case AST_STATE_UP:
20954 ast_debug(2, "%s: This call is UP.... \n", c->name);
20955
20956 transmit_response(p, "100 Trying", req);
20957
20958 if (p->t38.state == T38_PEER_REINVITE) {
20959 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."));
20960 } else if (p->t38.state == T38_ENABLED) {
20961 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
20962 transmit_response_with_t38_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL)));
20963 } else if (p->t38.state == T38_DISABLED) {
20964
20965 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
20966 transmit_response_with_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL)), p->session_modify == TRUE ? FALSE:TRUE);
20967 }
20968
20969 p->invitestate = INV_TERMINATED;
20970 break;
20971 default:
20972 ast_log(LOG_WARNING, "Don't know how to handle INVITE in state %d\n", c->_state);
20973 transmit_response(p, "100 Trying", req);
20974 break;
20975 }
20976 } else {
20977 if (p && (p->autokillid == -1)) {
20978 const char *msg;
20979
20980 if (!p->jointcapability)
20981 msg = "488 Not Acceptable Here (codec error)";
20982 else {
20983 ast_log(LOG_NOTICE, "Unable to create/find SIP channel for this INVITE\n");
20984 msg = "503 Unavailable";
20985 }
20986 transmit_response_reliable(p, msg, req);
20987 p->invitestate = INV_COMPLETED;
20988 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20989 }
20990 }
20991
20992 request_invite_cleanup:
20993
20994 if (refer_locked && p->refer && p->refer->refer_call) {
20995 sip_pvt_unlock(p->refer->refer_call);
20996 if (p->refer->refer_call->owner) {
20997 ast_channel_unlock(p->refer->refer_call->owner);
20998 }
20999 }
21000
21001 return res;
21002 }
21003
21004
21005
21006 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno)
21007 {
21008 struct sip_dual target;
21009
21010 int res = 0;
21011 struct sip_pvt *targetcall_pvt;
21012
21013
21014 if (!(targetcall_pvt = get_sip_pvt_byid_locked(transferer->refer->replaces_callid, transferer->refer->replaces_callid_totag,
21015 transferer->refer->replaces_callid_fromtag))) {
21016 if (transferer->refer->localtransfer) {
21017
21018
21019
21020 transmit_notify_with_sipfrag(transferer, seqno, "481 Call leg/transaction does not exist", TRUE);
21021 append_history(transferer, "Xfer", "Refer failed");
21022 ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
21023 transferer->refer->status = REFER_FAILED;
21024 return -1;
21025 }
21026
21027 ast_debug(3, "SIP attended transfer: Not our call - generating INVITE with replaces\n");
21028 return 0;
21029 }
21030
21031
21032 append_history(transferer, "Xfer", "Refer accepted");
21033 if (!targetcall_pvt->owner) {
21034 ast_debug(4, "SIP attended transfer: Error: No owner of target call\n");
21035
21036 transmit_notify_with_sipfrag(transferer, seqno, "503 Service Unavailable", TRUE);
21037 append_history(transferer, "Xfer", "Refer failed");
21038 ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
21039 transferer->refer->status = REFER_FAILED;
21040 sip_pvt_unlock(targetcall_pvt);
21041 if (targetcall_pvt)
21042 ao2_t_ref(targetcall_pvt, -1, "Drop targetcall_pvt pointer");
21043 return -1;
21044 }
21045
21046
21047 target.chan1 = targetcall_pvt->owner;
21048 target.chan2 = ast_bridged_channel(targetcall_pvt->owner);
21049
21050 if (!target.chan2 || !(target.chan2->_state == AST_STATE_UP || target.chan2->_state == AST_STATE_RINGING) ) {
21051
21052 if (target.chan2)
21053 ast_debug(4, "SIP attended transfer: Error: Wrong state of target call: %s\n", ast_state2str(target.chan2->_state));
21054 else if (target.chan1->_state != AST_STATE_RING)
21055 ast_debug(4, "SIP attended transfer: Error: No target channel\n");
21056 else
21057 ast_debug(4, "SIP attended transfer: Attempting transfer in ringing state\n");
21058 }
21059
21060
21061 if (sipdebug) {
21062 if (current->chan2)
21063 ast_debug(4, "SIP attended transfer: trying to bridge %s and %s\n", target.chan1->name, current->chan2->name);
21064 else
21065 ast_debug(4, "SIP attended transfer: trying to make %s take over (masq) %s\n", target.chan1->name, current->chan1->name);
21066 }
21067
21068 ast_set_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
21069
21070
21071 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",
21072 transferer->owner->name,
21073 transferer->owner->uniqueid,
21074 transferer->callid,
21075 target.chan1->name,
21076 target.chan1->uniqueid);
21077 res = attempt_transfer(current, &target);
21078 sip_pvt_unlock(targetcall_pvt);
21079 if (res) {
21080
21081 transmit_notify_with_sipfrag(transferer, seqno, "486 Busy Here", TRUE);
21082 append_history(transferer, "Xfer", "Refer failed");
21083 if (targetcall_pvt->owner)
21084 ast_channel_unlock(targetcall_pvt->owner);
21085 ast_clear_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
21086 } else {
21087
21088 const char *xfersound = pbx_builtin_getvar_helper(target.chan1, "ATTENDED_TRANSFER_COMPLETE_SOUND");
21089
21090
21091 transmit_notify_with_sipfrag(transferer, seqno, "200 OK", TRUE);
21092 append_history(transferer, "Xfer", "Refer succeeded");
21093 transferer->refer->status = REFER_200OK;
21094 if (target.chan2 && !ast_strlen_zero(xfersound) && ast_streamfile(target.chan2, xfersound, target.chan2->language) >= 0) {
21095 ast_waitstream(target.chan2, "");
21096 }
21097 if (targetcall_pvt->owner) {
21098 ast_debug(1, "SIP attended transfer: Unlocking channel %s\n", targetcall_pvt->owner->name);
21099 ast_channel_unlock(targetcall_pvt->owner);
21100 }
21101 }
21102 if (targetcall_pvt)
21103 ao2_t_ref(targetcall_pvt, -1, "drop targetcall_pvt");
21104 return 1;
21105 }
21106
21107
21108
21109
21110
21111
21112
21113
21114
21115
21116
21117
21118
21119
21120
21121
21122
21123
21124
21125
21126
21127
21128
21129
21130
21131
21132
21133
21134
21135
21136
21137
21138
21139
21140
21141
21142
21143
21144
21145
21146
21147
21148
21149
21150
21151
21152
21153
21154
21155
21156
21157
21158
21159
21160
21161
21162
21163
21164
21165
21166
21167
21168
21169
21170
21171 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock)
21172 {
21173 struct sip_dual current;
21174
21175
21176 int res = 0;
21177 current.req.data = NULL;
21178
21179 if (req->debug)
21180 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");
21181
21182 if (!p->owner) {
21183
21184
21185 ast_debug(3, "Call %s: Declined REFER, outside of dialog...\n", p->callid);
21186 transmit_response(p, "603 Declined (No dialog)", req);
21187 if (!req->ignore) {
21188 append_history(p, "Xfer", "Refer failed. Outside of dialog.");
21189 sip_alreadygone(p);
21190 pvt_set_needdestroy(p, "outside of dialog");
21191 }
21192 return 0;
21193 }
21194
21195
21196
21197 if (p->allowtransfer == TRANSFER_CLOSED ) {
21198
21199 transmit_response(p, "603 Declined (policy)", req);
21200 append_history(p, "Xfer", "Refer failed. Allowtransfer == closed.");
21201
21202 return 0;
21203 }
21204
21205 if (!req->ignore && ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
21206
21207 transmit_response(p, "491 Request pending", req);
21208 append_history(p, "Xfer", "Refer failed. Request pending.");
21209 return 0;
21210 }
21211
21212
21213 if (!p->refer && !sip_refer_allocate(p)) {
21214 transmit_response(p, "500 Internal Server Error", req);
21215 append_history(p, "Xfer", "Refer failed. Memory allocation error.");
21216 return -3;
21217 }
21218
21219 res = get_refer_info(p, req);
21220
21221 p->refer->status = REFER_SENT;
21222
21223 if (res != 0) {
21224 switch (res) {
21225 case -2:
21226 transmit_response(p, "400 Bad Request (Refer-to missing)", req);
21227 append_history(p, "Xfer", "Refer failed. Refer-to missing.");
21228 if (req->debug)
21229 ast_debug(1, "SIP transfer to black hole can't be handled (no refer-to: )\n");
21230 break;
21231 case -3:
21232 transmit_response(p, "603 Declined (Non sip: uri)", req);
21233 append_history(p, "Xfer", "Refer failed. Non SIP uri");
21234 if (req->debug)
21235 ast_debug(1, "SIP transfer to non-SIP uri denied\n");
21236 break;
21237 default:
21238
21239 transmit_response(p, "202 Accepted", req);
21240 append_history(p, "Xfer", "Refer failed. Bad extension.");
21241 transmit_notify_with_sipfrag(p, seqno, "404 Not found", TRUE);
21242 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
21243 if (req->debug)
21244 ast_debug(1, "SIP transfer to bad extension: %s\n", p->refer->refer_to);
21245 break;
21246 }
21247 return 0;
21248 }
21249 if (ast_strlen_zero(p->context))
21250 ast_string_field_set(p, context, sip_cfg.default_context);
21251
21252
21253 if (sip_cfg.allow_external_domains && check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
21254 p->refer->localtransfer = 1;
21255 if (sipdebug)
21256 ast_debug(3, "This SIP transfer is local : %s\n", p->refer->refer_to_domain);
21257 } else if (AST_LIST_EMPTY(&domain_list) || check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
21258
21259 p->refer->localtransfer = 1;
21260 } else if (sipdebug)
21261 ast_debug(3, "This SIP transfer is to a remote SIP extension (remote domain %s)\n", p->refer->refer_to_domain);
21262
21263
21264
21265 if (req->ignore)
21266 return res;
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 current.chan1 = p->owner;
21295
21296
21297 current.chan2 = ast_bridged_channel(current.chan1);
21298
21299 if (sipdebug)
21300 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>");
21301
21302 if (!current.chan2 && !p->refer->attendedtransfer) {
21303
21304
21305
21306 if (sipdebug)
21307 ast_debug(3, "Refused SIP transfer on non-bridged channel.\n");
21308 p->refer->status = REFER_FAILED;
21309 append_history(p, "Xfer", "Refer failed. Non-bridged channel.");
21310 transmit_response(p, "603 Declined", req);
21311 return -1;
21312 }
21313
21314 if (current.chan2) {
21315 if (sipdebug)
21316 ast_debug(4, "Got SIP transfer, applying to bridged peer '%s'\n", current.chan2->name);
21317
21318 ast_queue_control(current.chan1, AST_CONTROL_UNHOLD);
21319 }
21320
21321 ast_set_flag(&p->flags[0], SIP_GOTREFER);
21322
21323
21324 transmit_response(p, "202 Accepted", req);
21325
21326
21327 if (p->refer->attendedtransfer) {
21328 if ((res = local_attended_transfer(p, ¤t, req, seqno)))
21329 return res;
21330
21331 if (sipdebug)
21332 ast_debug(4, "SIP attended transfer: Still not our call - generating INVITE with replaces\n");
21333
21334 }
21335
21336
21337
21338 if (p->refer->localtransfer && !strcmp(p->refer->refer_to, ast_parking_ext())) {
21339
21340 *nounlock = 1;
21341 ast_channel_unlock(current.chan1);
21342 copy_request(¤t.req, req);
21343 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
21344 p->refer->status = REFER_200OK;
21345 append_history(p, "Xfer", "REFER to call parking.");
21346 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",
21347 current.chan1->name,
21348 current.chan1->uniqueid,
21349 p->callid,
21350 current.chan2->name,
21351 current.chan2->uniqueid,
21352 p->refer->refer_to);
21353 if (sipdebug)
21354 ast_debug(4, "SIP transfer to parking: trying to park %s. Parked by %s\n", current.chan2->name, current.chan1->name);
21355 if ((res = sip_park(current.chan2, current.chan1, req, seqno))) {
21356 transmit_notify_with_sipfrag(p, seqno, "500 Internal Server Error", TRUE);
21357 }
21358 return res;
21359 }
21360
21361
21362 if (current.chan1 && current.chan2) {
21363 ast_debug(3, "chan1->name: %s\n", current.chan1->name);
21364 pbx_builtin_setvar_helper(current.chan1, "BLINDTRANSFER", current.chan2->name);
21365 }
21366 if (current.chan2) {
21367 pbx_builtin_setvar_helper(current.chan2, "BLINDTRANSFER", current.chan1->name);
21368 pbx_builtin_setvar_helper(current.chan2, "SIPDOMAIN", p->refer->refer_to_domain);
21369 pbx_builtin_setvar_helper(current.chan2, "SIPTRANSFER", "yes");
21370
21371 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER", "yes");
21372
21373 if (p->refer->referred_by)
21374 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REFERER", p->refer->referred_by);
21375 }
21376
21377 if (!ast_strlen_zero(p->refer->replaces_callid)) {
21378 char tempheader[SIPBUFSIZE];
21379 snprintf(tempheader, sizeof(tempheader), "%s%s%s%s%s", p->refer->replaces_callid,
21380 p->refer->replaces_callid_totag ? ";to-tag=" : "",
21381 p->refer->replaces_callid_totag,
21382 p->refer->replaces_callid_fromtag ? ";from-tag=" : "",
21383 p->refer->replaces_callid_fromtag);
21384 if (current.chan2)
21385 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REPLACES", tempheader);
21386 }
21387
21388
21389 *nounlock = 1;
21390 ast_channel_unlock(current.chan1);
21391
21392
21393
21394
21395 if (!p->refer->attendedtransfer)
21396 transmit_notify_with_sipfrag(p, seqno, "183 Ringing", FALSE);
21397
21398
21399
21400
21401
21402 if (!current.chan2) {
21403
21404
21405
21406
21407
21408
21409
21410 p->refer->status = REFER_FAILED;
21411 transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable (can't handle one-legged xfers)", TRUE);
21412 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
21413 append_history(p, "Xfer", "Refer failed (only bridged calls).");
21414 return -1;
21415 }
21416 ast_set_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
21417
21418
21419
21420
21421
21422
21423 ast_indicate(current.chan2, AST_CONTROL_UNHOLD);
21424 res = ast_async_goto(current.chan2, p->refer->refer_to_context, p->refer->refer_to, 1);
21425
21426 if (!res) {
21427 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",
21428 current.chan1->name,
21429 current.chan1->uniqueid,
21430 p->callid,
21431 current.chan2->name,
21432 current.chan2->uniqueid,
21433 p->refer->refer_to, p->refer->refer_to_context);
21434
21435 ast_debug(3, "%s transfer succeeded. Telling transferer.\n", p->refer->attendedtransfer? "Attended" : "Blind");
21436 transmit_notify_with_sipfrag(p, seqno, "200 Ok", TRUE);
21437 if (p->refer->localtransfer)
21438 p->refer->status = REFER_200OK;
21439 if (p->owner)
21440 p->owner->hangupcause = AST_CAUSE_NORMAL_CLEARING;
21441 append_history(p, "Xfer", "Refer succeeded.");
21442 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
21443
21444
21445 res = 0;
21446 } else {
21447 ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
21448 ast_debug(3, "%s transfer failed. Resuming original call.\n", p->refer->attendedtransfer? "Attended" : "Blind");
21449 append_history(p, "Xfer", "Refer failed.");
21450
21451 p->refer->status = REFER_FAILED;
21452 transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable", TRUE);
21453 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
21454 res = -1;
21455 }
21456 return res;
21457 }
21458
21459
21460 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req)
21461 {
21462
21463 check_via(p, req);
21464 sip_alreadygone(p);
21465
21466
21467
21468
21469
21470
21471 if (p->invitestate == INV_TERMINATED)
21472 __sip_pretend_ack(p);
21473 else
21474 p->invitestate = INV_CANCELLED;
21475
21476 if (p->owner && p->owner->_state == AST_STATE_UP) {
21477
21478 transmit_response(p, "200 OK", req);
21479 ast_debug(1, "Got CANCEL on an answered call. Ignoring... \n");
21480 return 0;
21481 }
21482
21483 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD))
21484 update_call_counter(p, DEC_CALL_LIMIT);
21485
21486 stop_media_flows(p);
21487 if (p->owner)
21488 ast_queue_hangup(p->owner);
21489 else
21490 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21491 if (p->initreq.len > 0) {
21492 struct sip_pkt *pkt, *prev_pkt;
21493
21494
21495
21496
21497
21498
21499
21500
21501
21502
21503
21504 for (pkt = p->packets, prev_pkt = NULL; pkt; prev_pkt = pkt, pkt = pkt->next) {
21505 if (pkt->seqno == p->lastinvite && pkt->response_code == 487) {
21506 AST_SCHED_DEL(sched, pkt->retransid);
21507 UNLINK(pkt, p->packets, prev_pkt);
21508 ast_free(pkt);
21509 break;
21510 }
21511 }
21512 transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
21513 transmit_response(p, "200 OK", req);
21514 return 1;
21515 } else {
21516 transmit_response(p, "481 Call Leg Does Not Exist", req);
21517 return 0;
21518 }
21519 }
21520
21521 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen)
21522 {
21523 struct sip_pvt *p = chan->tech_pvt;
21524 char *all = "", *parse = ast_strdupa(preparse);
21525 int res = 0;
21526 AST_DECLARE_APP_ARGS(args,
21527 AST_APP_ARG(param);
21528 AST_APP_ARG(type);
21529 AST_APP_ARG(field);
21530 );
21531 AST_STANDARD_APP_ARGS(args, parse);
21532
21533
21534 if (!IS_SIP_TECH(chan->tech)) {
21535 ast_log(LOG_ERROR, "Cannot call %s on a non-SIP channel\n", funcname);
21536 return 0;
21537 }
21538
21539 memset(buf, 0, buflen);
21540
21541 if (p == NULL) {
21542 return -1;
21543 }
21544
21545 if (!strcasecmp(args.param, "peerip")) {
21546 ast_copy_string(buf, p->sa.sin_addr.s_addr ? ast_inet_ntoa(p->sa.sin_addr) : "", buflen);
21547 } else if (!strcasecmp(args.param, "recvip")) {
21548 ast_copy_string(buf, p->recv.sin_addr.s_addr ? ast_inet_ntoa(p->recv.sin_addr) : "", buflen);
21549 } else if (!strcasecmp(args.param, "from")) {
21550 ast_copy_string(buf, p->from, buflen);
21551 } else if (!strcasecmp(args.param, "uri")) {
21552 ast_copy_string(buf, p->uri, buflen);
21553 } else if (!strcasecmp(args.param, "useragent")) {
21554 ast_copy_string(buf, p->useragent, buflen);
21555 } else if (!strcasecmp(args.param, "peername")) {
21556 ast_copy_string(buf, p->peername, buflen);
21557 } else if (!strcasecmp(args.param, "t38passthrough")) {
21558 ast_copy_string(buf, (p->t38.state == T38_DISABLED) ? "0" : "1", buflen);
21559 } else if (!strcasecmp(args.param, "rtpdest")) {
21560 struct sockaddr_in sin;
21561 struct ast_rtp *stream = NULL;
21562
21563 if (ast_strlen_zero(args.type))
21564 args.type = "audio";
21565
21566 if (!strcasecmp(args.type, "audio")) {
21567 stream = p->rtp;
21568 } else if (!strcasecmp(args.type, "video")) {
21569 stream = p->vrtp;
21570 } else if (!strcasecmp(args.type, "text")) {
21571 stream = p->trtp;
21572 } else {
21573 return -1;
21574 }
21575
21576 if (!stream) {
21577 return -1;
21578 }
21579
21580 ast_rtp_get_peer(stream, &sin);
21581 snprintf(buf, buflen, "%s:%d", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
21582 } else if (!strcasecmp(args.param, "rtpqos")) {
21583 struct ast_rtp_quality qos;
21584 struct ast_rtp *rtp = p->rtp;
21585
21586 memset(&qos, 0, sizeof(qos));
21587
21588 if (ast_strlen_zero(args.type))
21589 args.type = "audio";
21590 if (ast_strlen_zero(args.field))
21591 args.field = "all";
21592
21593 if (!strcasecmp(args.type, "AUDIO")) {
21594 all = ast_rtp_get_quality(rtp = p->rtp, &qos, RTPQOS_SUMMARY);
21595 } else if (!strcasecmp(args.type, "VIDEO")) {
21596 all = ast_rtp_get_quality(rtp = p->vrtp, &qos, RTPQOS_SUMMARY);
21597 } else if (!strcasecmp(args.type, "TEXT")) {
21598 all = ast_rtp_get_quality(rtp = p->trtp, &qos, RTPQOS_SUMMARY);
21599 } else {
21600 return -1;
21601 }
21602
21603 if (!strcasecmp(args.field, "local_ssrc"))
21604 snprintf(buf, buflen, "%u", qos.local_ssrc);
21605 else if (!strcasecmp(args.field, "local_lostpackets"))
21606 snprintf(buf, buflen, "%u", qos.local_lostpackets);
21607 else if (!strcasecmp(args.field, "local_jitter"))
21608 snprintf(buf, buflen, "%.0f", qos.local_jitter * 1000.0);
21609 else if (!strcasecmp(args.field, "local_count"))
21610 snprintf(buf, buflen, "%u", qos.local_count);
21611 else if (!strcasecmp(args.field, "remote_ssrc"))
21612 snprintf(buf, buflen, "%u", qos.remote_ssrc);
21613 else if (!strcasecmp(args.field, "remote_lostpackets"))
21614 snprintf(buf, buflen, "%u", qos.remote_lostpackets);
21615 else if (!strcasecmp(args.field, "remote_jitter"))
21616 snprintf(buf, buflen, "%.0f", qos.remote_jitter * 1000.0);
21617 else if (!strcasecmp(args.field, "remote_count"))
21618 snprintf(buf, buflen, "%u", qos.remote_count);
21619 else if (!strcasecmp(args.field, "rtt"))
21620 snprintf(buf, buflen, "%.0f", qos.rtt * 1000.0);
21621 else if (!strcasecmp(args.field, "all"))
21622 ast_copy_string(buf, all, buflen);
21623 else if (!ast_rtp_get_qos(rtp, args.field, buf, buflen))
21624 ;
21625 else {
21626 ast_log(LOG_WARNING, "Unrecognized argument '%s' to %s\n", preparse, funcname);
21627 return -1;
21628 }
21629 } else {
21630 res = -1;
21631 }
21632 return res;
21633 }
21634
21635
21636 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req)
21637 {
21638 struct ast_channel *c=NULL;
21639 int res;
21640 struct ast_channel *bridged_to;
21641
21642
21643 if (p->pendinginvite && !ast_test_flag(&p->flags[0], SIP_OUTGOING) && !req->ignore) {
21644 transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
21645 }
21646
21647 __sip_pretend_ack(p);
21648
21649 p->invitestate = INV_TERMINATED;
21650
21651 copy_request(&p->initreq, req);
21652 if (sipdebug)
21653 ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
21654 check_via(p, req);
21655 sip_alreadygone(p);
21656
21657
21658 if (p->do_history || p->owner) {
21659 struct ast_channel *bridge = p->owner ? ast_bridged_channel(p->owner) : NULL;
21660 char *videoqos, *textqos;
21661
21662
21663
21664
21665 while (bridge && ast_channel_trylock(bridge)) {
21666 ast_channel_unlock(p->owner);
21667 do {
21668
21669 sip_pvt_unlock(p);
21670 usleep(1);
21671 sip_pvt_lock(p);
21672 } while (p->owner && ast_channel_trylock(p->owner));
21673 bridge = p->owner ? ast_bridged_channel(p->owner) : NULL;
21674 }
21675
21676 if (p->rtp) {
21677 if (p->do_history) {
21678 char *audioqos,
21679 *audioqos_jitter,
21680 *audioqos_loss,
21681 *audioqos_rtt;
21682
21683 audioqos = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_SUMMARY);
21684 audioqos_jitter = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_JITTER);
21685 audioqos_loss = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_LOSS);
21686 audioqos_rtt = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_RTT);
21687
21688 append_history(p, "RTCPaudio", "Quality:%s", audioqos);
21689 append_history(p, "RTCPaudioJitter", "Quality:%s", audioqos_jitter);
21690 append_history(p, "RTCPaudioLoss", "Quality:%s", audioqos_loss);
21691 append_history(p, "RTCPaudioRTT", "Quality:%s", audioqos_rtt);
21692 }
21693
21694 if (p->owner) {
21695 ast_rtp_set_vars(p->owner, p->rtp);
21696 }
21697 }
21698
21699 if (bridge) {
21700 struct sip_pvt *q = bridge->tech_pvt;
21701
21702 if (IS_SIP_TECH(bridge->tech) && q && q->rtp)
21703 ast_rtp_set_vars(bridge, q->rtp);
21704 ast_channel_unlock(bridge);
21705 }
21706
21707 if (p->vrtp) {
21708 videoqos = ast_rtp_get_quality(p->vrtp, NULL, RTPQOS_SUMMARY);
21709 if (p->do_history)
21710 append_history(p, "RTCPvideo", "Quality:%s", videoqos);
21711 if (p->owner)
21712 pbx_builtin_setvar_helper(p->owner, "RTPVIDEOQOS", videoqos);
21713 }
21714
21715 if (p->trtp) {
21716 textqos = ast_rtp_get_quality(p->trtp, NULL, RTPQOS_SUMMARY);
21717 if (p->do_history)
21718 append_history(p, "RTCPtext", "Quality:%s", textqos);
21719 if (p->owner)
21720 pbx_builtin_setvar_helper(p->owner, "RTPTEXTQOS", textqos);
21721 }
21722 }
21723
21724 stop_media_flows(p);
21725 stop_session_timer(p);
21726
21727 if (!ast_strlen_zero(get_header(req, "Also"))) {
21728 ast_log(LOG_NOTICE, "Client '%s' using deprecated BYE/Also transfer method. Ask vendor to support REFER instead\n",
21729 ast_inet_ntoa(p->recv.sin_addr));
21730 if (ast_strlen_zero(p->context))
21731 ast_string_field_set(p, context, sip_cfg.default_context);
21732 res = get_also_info(p, req);
21733 if (!res) {
21734 c = p->owner;
21735 if (c) {
21736 bridged_to = ast_bridged_channel(c);
21737 if (bridged_to) {
21738
21739 ast_queue_control(c, AST_CONTROL_UNHOLD);
21740 ast_async_goto(bridged_to, p->context, p->refer->refer_to, 1);
21741 } else
21742 ast_queue_hangup(p->owner);
21743 }
21744 } else {
21745 ast_log(LOG_WARNING, "Invalid transfer information from '%s'\n", ast_inet_ntoa(p->recv.sin_addr));
21746 if (p->owner)
21747 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
21748 }
21749 } else if (p->owner) {
21750 ast_queue_hangup(p->owner);
21751 ast_debug(3, "Received bye, issuing owner hangup\n");
21752 } else {
21753 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21754 ast_debug(3, "Received bye, no owner, selfdestruct soon.\n");
21755 }
21756 ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
21757 transmit_response(p, "200 OK", req);
21758
21759 return 1;
21760 }
21761
21762
21763 static int handle_request_message(struct sip_pvt *p, struct sip_request *req)
21764 {
21765 if (!req->ignore) {
21766 if (req->debug)
21767 ast_verbose("Receiving message!\n");
21768 receive_message(p, req);
21769 } else
21770 transmit_response(p, "202 Accepted", req);
21771 return 1;
21772 }
21773
21774 static void add_peer_mwi_subs(struct sip_peer *peer)
21775 {
21776 struct sip_mailbox *mailbox;
21777
21778 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
21779 mailbox->event_sub = ast_event_subscribe(AST_EVENT_MWI, mwi_event_cb, peer,
21780 AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox->mailbox,
21781 AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, S_OR(mailbox->context, "default"),
21782 AST_EVENT_IE_END);
21783 }
21784 }
21785
21786
21787 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e)
21788 {
21789 int gotdest = 0;
21790 int res = 0;
21791 int firststate = AST_EXTENSION_REMOVED;
21792 struct sip_peer *authpeer = NULL;
21793 const char *eventheader = get_header(req, "Event");
21794 int resubscribe = (p->subscribed != NONE) && !req->ignore;
21795 char *temp, *event;
21796
21797 if (p->initreq.headers) {
21798
21799 if (p->initreq.method != SIP_SUBSCRIBE) {
21800
21801
21802 transmit_response(p, "403 Forbidden (within dialog)", req);
21803
21804 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);
21805 return 0;
21806 } else if (req->debug) {
21807 if (resubscribe)
21808 ast_debug(1, "Got a re-subscribe on existing subscription %s\n", p->callid);
21809 else
21810 ast_debug(1, "Got a new subscription %s (possibly with auth) or retransmission\n", p->callid);
21811 }
21812 }
21813
21814
21815
21816
21817 if (!sip_cfg.allowsubscribe) {
21818 transmit_response(p, "403 Forbidden (policy)", req);
21819 pvt_set_needdestroy(p, "forbidden");
21820 return 0;
21821 }
21822
21823 if (!req->ignore && !resubscribe) {
21824 const char *to = get_header(req, "To");
21825 char totag[128];
21826
21827
21828 if (!ast_strlen_zero(to) && gettag(req, "To", totag, sizeof(totag))) {
21829 if (req->debug)
21830 ast_verbose("Received resubscription for a dialog we no longer know about. Telling remote side to subscribe again.\n");
21831 transmit_response(p, "481 Subscription does not exist", req);
21832 pvt_set_needdestroy(p, "subscription does not exist");
21833 return 0;
21834 }
21835
21836
21837 if (req->debug)
21838 ast_verbose("Creating new subscription\n");
21839
21840 copy_request(&p->initreq, req);
21841 if (sipdebug)
21842 ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
21843 check_via(p, req);
21844 build_route(p, req, 0);
21845 } else if (req->debug && req->ignore)
21846 ast_verbose("Ignoring this SUBSCRIBE request\n");
21847
21848
21849 if (ast_strlen_zero(eventheader)) {
21850 transmit_response(p, "489 Bad Event", req);
21851 ast_debug(2, "Received SIP subscribe for unknown event package: <none>\n");
21852 pvt_set_needdestroy(p, "unknown event package in subscribe");
21853 return 0;
21854 }
21855
21856 if ( (strchr(eventheader, ';'))) {
21857 event = ast_strdupa(eventheader);
21858 temp = strchr(event, ';');
21859 *temp = '\0';
21860
21861 } else
21862 event = (char *) eventheader;
21863
21864
21865
21866
21867 if (p->subscribed == NONE || resubscribe) {
21868 res = check_user_full(p, req, SIP_SUBSCRIBE, e, 0, sin, &authpeer);
21869
21870
21871 if (res == AUTH_CHALLENGE_SENT)
21872 return 0;
21873 if (res < 0) {
21874 if (res == AUTH_FAKE_AUTH) {
21875 ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", get_header(req, "From"));
21876 transmit_fake_auth_response(p, SIP_SUBSCRIBE, req, XMIT_UNRELIABLE);
21877 } else {
21878 ast_log(LOG_NOTICE, "Failed to authenticate device %s for SUBSCRIBE\n", get_header(req, "From"));
21879 transmit_response_reliable(p, "403 Forbidden", req);
21880 }
21881
21882 pvt_set_needdestroy(p, "authentication failed");
21883 return 0;
21884 }
21885 }
21886
21887
21888
21889
21890
21891
21892
21893 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
21894 transmit_response(p, "403 Forbidden (policy)", req);
21895 pvt_set_needdestroy(p, "subscription not allowed");
21896 if (authpeer)
21897 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 1)");
21898 return 0;
21899 }
21900
21901 if (strcmp(event, "message-summary")) {
21902
21903 gotdest = get_destination(p, NULL);
21904 }
21905
21906
21907 parse_ok_contact(p, req);
21908
21909 build_contact(p);
21910 if (gotdest) {
21911 transmit_response(p, "404 Not Found", req);
21912 pvt_set_needdestroy(p, "subscription target not found");
21913 if (authpeer)
21914 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
21915 return 0;
21916 }
21917
21918
21919 if (ast_strlen_zero(p->tag))
21920 make_our_tag(p->tag, sizeof(p->tag));
21921
21922 if (!strcmp(event, "presence") || !strcmp(event, "dialog")) {
21923 unsigned int pidf_xml;
21924 const char *accept;
21925 int start = 0;
21926 enum subscriptiontype subscribed = NONE;
21927 const char *unknown_acceptheader = NULL;
21928
21929 if (authpeer)
21930 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
21931
21932
21933
21934 accept = __get_header(req, "Accept", &start);
21935 while ((subscribed == NONE) && !ast_strlen_zero(accept)) {
21936 pidf_xml = strstr(accept, "application/pidf+xml") ? 1 : 0;
21937
21938
21939
21940 if (pidf_xml && strstr(p->useragent, "Polycom")) {
21941 subscribed = XPIDF_XML;
21942 } else if (pidf_xml) {
21943 subscribed = PIDF_XML;
21944 } else if (strstr(accept, "application/dialog-info+xml")) {
21945 subscribed = DIALOG_INFO_XML;
21946
21947 } else if (strstr(accept, "application/cpim-pidf+xml")) {
21948 subscribed = CPIM_PIDF_XML;
21949 } else if (strstr(accept, "application/xpidf+xml")) {
21950 subscribed = XPIDF_XML;
21951 } else {
21952 unknown_acceptheader = accept;
21953 }
21954
21955 accept = __get_header(req, "Accept", &start);
21956 }
21957
21958 if (!start) {
21959 if (p->subscribed == NONE) {
21960 transmit_response(p, "489 Bad Event", req);
21961 ast_log(LOG_WARNING,"SUBSCRIBE failure: no Accept header: pvt: "
21962 "stateid: %d, laststate: %d, dialogver: %d, subscribecont: "
21963 "'%s', subscribeuri: '%s'\n",
21964 p->stateid,
21965 p->laststate,
21966 p->dialogver,
21967 p->subscribecontext,
21968 p->subscribeuri);
21969 pvt_set_needdestroy(p, "no Accept header");
21970 return 0;
21971 }
21972
21973
21974 } else if (subscribed == NONE) {
21975
21976 char mybuf[200];
21977 if (!ast_strlen_zero(unknown_acceptheader)) {
21978 snprintf(mybuf, sizeof(mybuf), "489 Bad Event (format %s)", unknown_acceptheader);
21979 } else {
21980 snprintf(mybuf, sizeof(mybuf), "489 Bad Event");
21981 }
21982 transmit_response(p, mybuf, req);
21983 ast_log(LOG_WARNING,"SUBSCRIBE failure: unrecognized format:"
21984 "'%s' pvt: subscribed: %d, stateid: %d, laststate: %d,"
21985 "dialogver: %d, subscribecont: '%s', subscribeuri: '%s'\n",
21986 unknown_acceptheader,
21987 (int)p->subscribed,
21988 p->stateid,
21989 p->laststate,
21990 p->dialogver,
21991 p->subscribecontext,
21992 p->subscribeuri);
21993 pvt_set_needdestroy(p, "unrecognized format");
21994 return 0;
21995 } else {
21996 p->subscribed = subscribed;
21997 }
21998 } else if (!strcmp(event, "message-summary")) {
21999 int start = 0;
22000 int found_supported = 0;
22001 const char *acceptheader;
22002
22003 acceptheader = __get_header(req, "Accept", &start);
22004 while (!found_supported && !ast_strlen_zero(acceptheader)) {
22005 found_supported = strcmp(acceptheader, "application/simple-message-summary") ? 0 : 1;
22006 if (!found_supported && (option_debug > 2)) {
22007 ast_log(LOG_DEBUG, "Received SIP mailbox subscription for unknown format: %s\n", acceptheader);
22008 }
22009 acceptheader = __get_header(req, "Accept", &start);
22010 }
22011 if (start && !found_supported) {
22012
22013 transmit_response(p, "406 Not Acceptable", req);
22014 ast_debug(2, "Received SIP mailbox subscription for unknown format: %s\n", acceptheader);
22015 pvt_set_needdestroy(p, "unknown format");
22016 if (authpeer)
22017 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 3)");
22018 return 0;
22019 }
22020
22021
22022
22023
22024
22025
22026 if (!authpeer || AST_LIST_EMPTY(&authpeer->mailboxes)) {
22027 transmit_response(p, "404 Not found (no mailbox)", req);
22028 pvt_set_needdestroy(p, "received 404 response");
22029 ast_log(LOG_NOTICE, "Received SIP subscribe for peer without mailbox: %s\n", authpeer->name);
22030 if (authpeer)
22031 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 4)");
22032 return 0;
22033 }
22034
22035 p->subscribed = MWI_NOTIFICATION;
22036 if (ast_test_flag(&authpeer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY)) {
22037 add_peer_mwi_subs(authpeer);
22038 }
22039 if (authpeer->mwipvt && authpeer->mwipvt != p) {
22040
22041 dialog_unlink_all(authpeer->mwipvt, TRUE, TRUE);
22042 authpeer->mwipvt = dialog_unref(authpeer->mwipvt, "unref dialog authpeer->mwipvt");
22043
22044 }
22045 if (authpeer->mwipvt)
22046 dialog_unref(authpeer->mwipvt, "Unref previously stored mwipvt dialog pointer");
22047 authpeer->mwipvt = dialog_ref(p, "setting peers' mwipvt to p");
22048 if (p->relatedpeer)
22049 unref_peer(p->relatedpeer, "Unref previously stored relatedpeer ptr");
22050 p->relatedpeer = ref_peer(authpeer, "setting dialog's relatedpeer pointer");
22051
22052 } else {
22053 transmit_response(p, "489 Bad Event", req);
22054 ast_debug(2, "Received SIP subscribe for unknown event package: %s\n", event);
22055 pvt_set_needdestroy(p, "unknown event package");
22056 if (authpeer)
22057 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 5)");
22058 return 0;
22059 }
22060
22061
22062 if (p->subscribed != MWI_NOTIFICATION && !resubscribe) {
22063 if (p->stateid > -1) {
22064 ast_extension_state_del(p->stateid, cb_extensionstate);
22065
22066 dialog_unref(p, "the extensionstate containing this dialog ptr was deleted");
22067 }
22068 p->stateid = ast_extension_state_add(p->context, p->exten, cb_extensionstate, dialog_ref(p,"copying dialog ptr into extension state struct"));
22069 }
22070
22071 if (!req->ignore && p)
22072 p->lastinvite = seqno;
22073 if (p && !p->needdestroy) {
22074 p->expiry = atoi(get_header(req, "Expires"));
22075
22076
22077 if (p->expiry > max_expiry)
22078 p->expiry = max_expiry;
22079 if (p->expiry < min_expiry && p->expiry > 0)
22080 p->expiry = min_expiry;
22081
22082 if (sipdebug) {
22083 if (p->subscribed == MWI_NOTIFICATION && p->relatedpeer)
22084 ast_debug(2, "Adding subscription for mailbox notification - peer %s\n", p->relatedpeer->name);
22085 else
22086 ast_debug(2, "Adding subscription for extension %s context %s for peer %s\n", p->exten, p->context, p->username);
22087 }
22088 if (p->autokillid > -1 && sip_cancel_destroy(p))
22089 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
22090 if (p->expiry > 0)
22091 sip_scheddestroy(p, (p->expiry + 10) * 1000);
22092
22093 if (p->subscribed == MWI_NOTIFICATION) {
22094 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
22095 transmit_response(p, "200 OK", req);
22096 if (p->relatedpeer) {
22097 ao2_lock(p->relatedpeer);
22098 sip_send_mwi_to_peer(p->relatedpeer, NULL, 0);
22099 ao2_unlock(p->relatedpeer);
22100 }
22101 } else {
22102
22103 if ((firststate = ast_extension_state(NULL, p->context, p->exten)) < 0) {
22104
22105 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));
22106 transmit_response(p, "404 Not found", req);
22107 pvt_set_needdestroy(p, "no extension for SUBSCRIBE");
22108 return 0;
22109 }
22110 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
22111 transmit_response(p, "200 OK", req);
22112 transmit_state_notify(p, firststate, 1, FALSE);
22113 append_history(p, "Subscribestatus", "%s", ast_extension_state2str(firststate));
22114
22115 ast_string_field_build(p, subscribeuri, "%s@%s", p->exten, p->context);
22116
22117
22118 }
22119 if (!p->expiry) {
22120 pvt_set_needdestroy(p, "forcing expiration");
22121 }
22122 }
22123 return 1;
22124 }
22125
22126
22127 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e)
22128 {
22129 enum check_auth_result res;
22130
22131
22132
22133 if (p->initreq.headers && p->initreq.method != SIP_REGISTER) {
22134 ast_log(LOG_WARNING, "Ignoring spurious REGISTER with Call-ID: %s\n", p->callid);
22135 return -1;
22136 }
22137
22138
22139 copy_request(&p->initreq, req);
22140 if (sipdebug)
22141 ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
22142 check_via(p, req);
22143 if ((res = register_verify(p, sin, req, e)) < 0) {
22144 const char *reason;
22145
22146 switch (res) {
22147 case AUTH_SECRET_FAILED:
22148 reason = "Wrong password";
22149 break;
22150 case AUTH_USERNAME_MISMATCH:
22151 reason = "Username/auth name mismatch";
22152 break;
22153 case AUTH_NOT_FOUND:
22154 reason = "No matching peer found";
22155 break;
22156 case AUTH_UNKNOWN_DOMAIN:
22157 reason = "Not a local domain";
22158 break;
22159 case AUTH_PEER_NOT_DYNAMIC:
22160 reason = "Peer is not supposed to register";
22161 break;
22162 case AUTH_ACL_FAILED:
22163 reason = "Device does not match ACL";
22164 break;
22165 case AUTH_BAD_TRANSPORT:
22166 reason = "Device not configured to use this transport type";
22167 break;
22168 default:
22169 reason = "Unknown failure";
22170 break;
22171 }
22172 ast_log(LOG_NOTICE, "Registration from '%s' failed for '%s' - %s\n",
22173 get_header(req, "To"), ast_inet_ntoa(sin->sin_addr),
22174 reason);
22175 append_history(p, "RegRequest", "Failed : Account %s : %s", get_header(req, "To"), reason);
22176 } else {
22177 req->authenticated = 1;
22178 append_history(p, "RegRequest", "Succeeded : Account %s", get_header(req, "To"));
22179 }
22180
22181 if (res < 1) {
22182
22183
22184 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22185 }
22186 return res;
22187 }
22188
22189
22190
22191
22192
22193
22194
22195
22196 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock)
22197 {
22198
22199
22200 const char *cmd;
22201 const char *cseq;
22202 const char *useragent;
22203 const char *via;
22204 const char *callid;
22205 int via_pos = 0;
22206 int seqno;
22207 int len;
22208 int respid;
22209 int res = 0;
22210 int debug = sip_debug_test_pvt(p);
22211 char *e;
22212 int error = 0;
22213 int oldmethod = p->method;
22214 int acked = 0;
22215
22216
22217
22218
22219 cseq = get_header(req, "Cseq");
22220 cmd = REQ_OFFSET_TO_STR(req, header[0]);
22221
22222 via = __get_header(req, "Via", &via_pos);
22223
22224 callid = get_header(req, "Call-ID");
22225
22226
22227 if (ast_strlen_zero(cmd) || ast_strlen_zero(cseq) || ast_strlen_zero(via)) {
22228 ast_log(LOG_ERROR, "Dropping this SIP message with Call-ID '%s', it's incomplete.\n", callid);
22229 error = 1;
22230 }
22231 if (!error && sscanf(cseq, "%30d%n", &seqno, &len) != 1) {
22232 ast_log(LOG_ERROR, "No seqno in '%s'. Dropping incomplete message.\n", cmd);
22233 error = 1;
22234 }
22235 if (error) {
22236 if (!p->initreq.headers) {
22237 pvt_set_needdestroy(p, "no headers");
22238 }
22239 return -1;
22240 }
22241
22242
22243 cmd = REQ_OFFSET_TO_STR(req, rlPart1);
22244 e = ast_skip_blanks(REQ_OFFSET_TO_STR(req, rlPart2));
22245
22246
22247 useragent = get_header(req, "User-Agent");
22248 if (!ast_strlen_zero(useragent))
22249 ast_string_field_set(p, useragent, useragent);
22250
22251
22252 if (req->method == SIP_RESPONSE) {
22253
22254
22255
22256
22257
22258
22259 if (ast_strlen_zero(e)) {
22260 return 0;
22261 }
22262 if (sscanf(e, "%30d %n", &respid, &len) != 1) {
22263 ast_log(LOG_WARNING, "Invalid response: '%s'\n", e);
22264 return 0;
22265 }
22266 if (respid <= 0) {
22267 ast_log(LOG_WARNING, "Invalid SIP response code: '%d'\n", respid);
22268 return 0;
22269 }
22270
22271
22272
22273 if (!ast_strlen_zero(__get_header(req, "via", &via_pos))) {
22274 ast_log(LOG_WARNING, "Misrouted SIP response '%s' with Call-ID '%s', too many vias\n", e, callid);
22275 return 0;
22276 }
22277 if (p->ocseq && (p->ocseq < seqno)) {
22278 if (option_debug)
22279 ast_log(LOG_DEBUG, "Ignoring out of order response %d (expecting %d)\n", seqno, p->ocseq);
22280 return -1;
22281 } else {
22282 if ((respid == 200) || ((respid >= 300) && (respid <= 399))) {
22283 extract_uri(p, req);
22284 }
22285 handle_response(p, respid, e + len, req, seqno);
22286 }
22287 return 0;
22288 }
22289
22290
22291
22292
22293
22294 p->method = req->method;
22295 ast_debug(4, "**** Received %s (%d) - Command in SIP %s\n", sip_methods[p->method].text, sip_methods[p->method].id, cmd);
22296
22297 if (p->icseq && (p->icseq > seqno) ) {
22298 if (p->pendinginvite && seqno == p->pendinginvite && (req->method == SIP_ACK || req->method == SIP_CANCEL)) {
22299 ast_debug(2, "Got CANCEL or ACK on INVITE with transactions in between.\n");
22300 } else {
22301 ast_debug(1, "Ignoring too old SIP packet packet %d (expecting >= %d)\n", seqno, p->icseq);
22302 if (req->method != SIP_ACK)
22303 transmit_response(p, "500 Server error", req);
22304 return -1;
22305 }
22306 } else if (p->icseq &&
22307 p->icseq == seqno &&
22308 req->method != SIP_ACK &&
22309 (p->method != SIP_CANCEL || p->alreadygone)) {
22310
22311
22312
22313 req->ignore = 1;
22314 ast_debug(3, "Ignoring SIP message because of retransmit (%s Seqno %d, ours %d)\n", sip_methods[p->method].text, p->icseq, seqno);
22315 }
22316
22317 if (seqno >= p->icseq)
22318
22319
22320
22321 p->icseq = seqno;
22322
22323
22324 if (ast_strlen_zero(p->theirtag)) {
22325 char tag[128];
22326
22327 gettag(req, "From", tag, sizeof(tag));
22328 ast_string_field_set(p, theirtag, tag);
22329 }
22330 snprintf(p->lastmsg, sizeof(p->lastmsg), "Rx: %s", cmd);
22331
22332 if (sip_cfg.pedanticsipchecking) {
22333
22334
22335
22336
22337 if (!p->initreq.headers && req->has_to_tag) {
22338
22339 if (!req->ignore && req->method == SIP_INVITE) {
22340 transmit_response_reliable(p, "481 Call/Transaction Does Not Exist", req);
22341
22342 } else if (req->method != SIP_ACK) {
22343 transmit_response(p, "481 Call/Transaction Does Not Exist", req);
22344 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22345 } else {
22346 ast_debug(1, "Got ACK for unknown dialog... strange.\n");
22347 }
22348 return res;
22349 }
22350 }
22351
22352 if (!e && (p->method == SIP_INVITE || p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER || p->method == SIP_NOTIFY)) {
22353 transmit_response(p, "400 Bad request", req);
22354 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22355 return -1;
22356 }
22357
22358
22359 switch (p->method) {
22360 case SIP_OPTIONS:
22361 res = handle_request_options(p, req);
22362 break;
22363 case SIP_INVITE:
22364 res = handle_request_invite(p, req, debug, seqno, sin, recount, e, nounlock);
22365 break;
22366 case SIP_REFER:
22367 res = handle_request_refer(p, req, debug, seqno, nounlock);
22368 break;
22369 case SIP_CANCEL:
22370 res = handle_request_cancel(p, req);
22371 break;
22372 case SIP_BYE:
22373 res = handle_request_bye(p, req);
22374 break;
22375 case SIP_MESSAGE:
22376 res = handle_request_message(p, req);
22377 break;
22378 case SIP_SUBSCRIBE:
22379 res = handle_request_subscribe(p, req, sin, seqno, e);
22380 break;
22381 case SIP_REGISTER:
22382 res = handle_request_register(p, req, sin, e);
22383 break;
22384 case SIP_INFO:
22385 if (req->debug)
22386 ast_verbose("Receiving INFO!\n");
22387 if (!req->ignore)
22388 handle_request_info(p, req);
22389 else
22390 transmit_response(p, "200 OK", req);
22391 break;
22392 case SIP_NOTIFY:
22393 res = handle_request_notify(p, req, sin, seqno, e);
22394 break;
22395 case SIP_ACK:
22396
22397 if (seqno == p->pendinginvite) {
22398 p->invitestate = INV_TERMINATED;
22399 p->pendinginvite = 0;
22400 acked = __sip_ack(p, seqno, 1 , 0);
22401 if (find_sdp(req)) {
22402 if (process_sdp(p, req, SDP_T38_NONE))
22403 return -1;
22404 }
22405 check_pendings(p);
22406 } else if (p->glareinvite == seqno) {
22407
22408 p->glareinvite = 0;
22409 acked = __sip_ack(p, seqno, 1, 0);
22410 }
22411 if (!acked) {
22412
22413
22414 p->method = oldmethod;
22415 }
22416 if (!p->lastinvite && ast_strlen_zero(p->randdata)) {
22417 pvt_set_needdestroy(p, "unmatched ACK");
22418 }
22419 break;
22420 default:
22421 transmit_response_with_allow(p, "501 Method Not Implemented", req, 0);
22422 ast_log(LOG_NOTICE, "Unknown SIP command '%s' from '%s'\n",
22423 cmd, ast_inet_ntoa(p->sa.sin_addr));
22424
22425 if (!p->initreq.headers) {
22426 pvt_set_needdestroy(p, "unimplemented method");
22427 }
22428 break;
22429 }
22430 return res;
22431 }
22432
22433 static void process_request_queue(struct sip_pvt *p, int *recount, int *nounlock)
22434 {
22435 struct sip_request *req;
22436
22437 while ((req = AST_LIST_REMOVE_HEAD(&p->request_queue, next))) {
22438 if (handle_incoming(p, req, &p->recv, recount, nounlock) == -1) {
22439
22440 if (option_debug) {
22441 ast_log(LOG_DEBUG, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
22442 }
22443 }
22444 ast_free(req);
22445 }
22446 }
22447
22448 static int scheduler_process_request_queue(const void *data)
22449 {
22450 struct sip_pvt *p = (struct sip_pvt *) data;
22451 int recount = 0;
22452 int nounlock = 0;
22453 int lockretry;
22454
22455 for (lockretry = 10; lockretry > 0; lockretry--) {
22456 sip_pvt_lock(p);
22457
22458
22459
22460 if (!p->owner || !ast_channel_trylock(p->owner)) {
22461 break;
22462 }
22463
22464 if (lockretry != 1) {
22465 sip_pvt_unlock(p);
22466
22467 usleep(1);
22468 }
22469 }
22470
22471 if (!lockretry) {
22472 int retry = !AST_LIST_EMPTY(&p->request_queue);
22473
22474
22475
22476
22477
22478
22479 sip_pvt_unlock(p);
22480 if (!retry) {
22481 dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
22482 }
22483 return retry;
22484 };
22485
22486 process_request_queue(p, &recount, &nounlock);
22487 p->request_queue_sched_id = -1;
22488
22489 if (p->owner && !nounlock) {
22490 ast_channel_unlock(p->owner);
22491 }
22492 sip_pvt_unlock(p);
22493
22494 if (recount) {
22495 ast_update_use_count();
22496 }
22497
22498 dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
22499
22500 return 0;
22501 }
22502
22503 static int queue_request(struct sip_pvt *p, const struct sip_request *req)
22504 {
22505 struct sip_request *newreq;
22506
22507 if (!(newreq = ast_calloc(1, sizeof(*newreq)))) {
22508 return -1;
22509 }
22510
22511 copy_request(newreq, req);
22512 AST_LIST_INSERT_TAIL(&p->request_queue, newreq, next);
22513 if (p->request_queue_sched_id == -1) {
22514 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) {
22515 dialog_unref(p, "Decrement refcount due to sched_add failure");
22516 }
22517 }
22518
22519 return 0;
22520 }
22521
22522
22523
22524
22525
22526
22527 static int sipsock_read(int *id, int fd, short events, void *ignore)
22528 {
22529 struct sip_request req;
22530 struct sockaddr_in sin = { 0, };
22531 int res;
22532 socklen_t len = sizeof(sin);
22533 static char readbuf[65535];
22534
22535 memset(&req, 0, sizeof(req));
22536 res = recvfrom(fd, readbuf, sizeof(readbuf) - 1, 0, (struct sockaddr *)&sin, &len);
22537 if (res < 0) {
22538 #if !defined(__FreeBSD__)
22539 if (errno == EAGAIN)
22540 ast_log(LOG_NOTICE, "SIP: Received packet with bad UDP checksum\n");
22541 else
22542 #endif
22543 if (errno != ECONNREFUSED)
22544 ast_log(LOG_WARNING, "Recv error: %s\n", strerror(errno));
22545 return 1;
22546 }
22547
22548 readbuf[res] = '\0';
22549
22550 if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
22551 return 1;
22552 }
22553
22554 if (ast_str_set(&req.data, 0, "%s", readbuf) == AST_DYNSTR_BUILD_FAILED) {
22555 return -1;
22556 }
22557
22558 req.len = res;
22559 req.socket.fd = sipsock;
22560 set_socket_transport(&req.socket, SIP_TRANSPORT_UDP);
22561 req.socket.tcptls_session = NULL;
22562 req.socket.port = bindaddr.sin_port;
22563
22564 handle_request_do(&req, &sin);
22565 deinit_req(&req);
22566
22567 return 1;
22568 }
22569
22570
22571
22572
22573
22574 static int handle_request_do(struct sip_request *req, struct sockaddr_in *sin)
22575 {
22576 struct sip_pvt *p;
22577 int recount = 0;
22578 int nounlock = 0;
22579 int lockretry;
22580
22581 if (sip_debug_test_addr(sin))
22582 req->debug = 1;
22583 if (sip_cfg.pedanticsipchecking)
22584 req->len = lws2sws(req->data->str, req->len);
22585 if (req->debug) {
22586 ast_verbose("\n<--- SIP read from %s:%s:%d --->\n%s\n<------------->\n",
22587 get_transport(req->socket.type), ast_inet_ntoa(sin->sin_addr),
22588 ntohs(sin->sin_port), req->data->str);
22589 }
22590
22591 if (parse_request(req) == -1) {
22592 ast_str_reset(req->data);
22593 return 1;
22594 }
22595 req->method = find_sip_method(REQ_OFFSET_TO_STR(req, rlPart1));
22596
22597 if (req->debug)
22598 ast_verbose("--- (%d headers %d lines)%s ---\n", req->headers, req->lines, (req->headers + req->lines == 0) ? " Nat keepalive" : "");
22599
22600 if (req->headers < 2) {
22601 ast_str_reset(req->data);
22602 return 1;
22603 }
22604
22605
22606 for (lockretry = 10; lockretry > 0; lockretry--) {
22607 ast_mutex_lock(&netlock);
22608
22609
22610 p = find_call(req, sin, req->method);
22611 if (p == NULL) {
22612 ast_debug(1, "Invalid SIP message - rejected , no callid, len %d\n", req->len);
22613 ast_mutex_unlock(&netlock);
22614 return 1;
22615 }
22616
22617 copy_socket_data(&p->socket, &req->socket);
22618
22619
22620
22621 if (!p->owner || !ast_channel_trylock(p->owner))
22622 break;
22623
22624 if (lockretry != 1) {
22625 sip_pvt_unlock(p);
22626 ao2_t_ref(p, -1, "release p (from find_call) inside lockretry loop");
22627 ast_mutex_unlock(&netlock);
22628
22629 usleep(1);
22630 }
22631 }
22632 p->recv = *sin;
22633
22634
22635 if (p->owner) {
22636 req->authenticated = 1;
22637 }
22638
22639 if (p->do_history)
22640 append_history(p, "Rx", "%s / %s / %s", req->data->str, get_header(req, "CSeq"), REQ_OFFSET_TO_STR(req, rlPart2));
22641
22642 if (!lockretry) {
22643 if (!queue_request(p, req)) {
22644
22645 sip_pvt_unlock(p);
22646 ao2_t_ref(p, -1, "release p (from find_call) after queueing request");
22647 ast_mutex_unlock(&netlock);
22648 return 1;
22649 }
22650
22651 if (p->owner)
22652 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 ??? - "));
22653 ast_log(LOG_ERROR, "SIP transaction failed: %s \n", p->callid);
22654 if (req->method != SIP_ACK)
22655 transmit_response(p, "503 Server error", req);
22656
22657 append_history(p, "LockFail", "Owner lock failed, transaction failed.");
22658 sip_pvt_unlock(p);
22659 ao2_t_ref(p, -1, "release p (from find_call) at end of lockretry");
22660 ast_mutex_unlock(&netlock);
22661 return 1;
22662 }
22663
22664
22665
22666
22667 if (!AST_LIST_EMPTY(&p->request_queue)) {
22668 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"));
22669 process_request_queue(p, &recount, &nounlock);
22670 }
22671
22672 if (handle_incoming(p, req, sin, &recount, &nounlock) == -1) {
22673
22674 ast_debug(1, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
22675 }
22676
22677 if (recount)
22678 ast_update_use_count();
22679
22680 if (p->owner && !nounlock)
22681 ast_channel_unlock(p->owner);
22682 sip_pvt_unlock(p);
22683 ao2_t_ref(p, -1, "throw away dialog ptr from find_call at end of routine");
22684 ast_mutex_unlock(&netlock);
22685 return 1;
22686 }
22687
22688
22689
22690
22691
22692
22693
22694 static int sip_standard_port(enum sip_transport type, int port)
22695 {
22696 if (type & SIP_TRANSPORT_TLS)
22697 return port == STANDARD_TLS_PORT;
22698 else
22699 return port == STANDARD_SIP_PORT;
22700 }
22701
22702 static int threadinfo_locate_cb(void *obj, void *arg, int flags)
22703 {
22704 struct sip_threadinfo *th = obj;
22705 struct sockaddr_in *s = arg;
22706
22707 if (!inaddrcmp(&th->tcptls_session->remote_address, s)) {
22708 return CMP_MATCH | CMP_STOP;
22709 }
22710
22711 return 0;
22712 }
22713
22714
22715
22716
22717
22718
22719 static struct ast_tcptls_session_instance *sip_tcp_locate(struct sockaddr_in *s)
22720 {
22721 struct sip_threadinfo *th;
22722 struct ast_tcptls_session_instance *tcptls_instance = NULL;
22723
22724 if ((th = ao2_callback(threadt, 0, threadinfo_locate_cb, s))) {
22725 tcptls_instance = (ao2_ref(th->tcptls_session, +1), th->tcptls_session);
22726 ao2_t_ref(th, -1, "decrement ref from callback");
22727 }
22728 return tcptls_instance;
22729 }
22730
22731
22732 static int sip_prepare_socket(struct sip_pvt *p)
22733 {
22734 struct sip_socket *s = &p->socket;
22735 static const char name[] = "SIP socket";
22736 struct sip_threadinfo *th = NULL;
22737 struct ast_tcptls_session_instance *tcptls_session;
22738 struct ast_tcptls_session_args tmp_ca = {
22739 .name = name,
22740 .accept_fd = -1,
22741 };
22742 struct ast_tcptls_session_args *ca;
22743
22744
22745 if ((s->fd != -1) && (s->type == SIP_TRANSPORT_UDP)) {
22746 return s->fd;
22747 }
22748 if ((s->type & (SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS)) &&
22749 (s->tcptls_session) &&
22750 (s->tcptls_session->fd != -1)) {
22751 return s->tcptls_session->fd;
22752 }
22753
22754
22755
22756
22757 if (p->outboundproxy && p->outboundproxy->transport) {
22758 s->type = p->outboundproxy->transport;
22759 }
22760
22761 if (s->type == SIP_TRANSPORT_UDP) {
22762 s->fd = sipsock;
22763 return s->fd;
22764 }
22765
22766
22767
22768
22769
22770
22771
22772
22773
22774
22775
22776 tmp_ca.remote_address = *(sip_real_dst(p));
22777 if ((tcptls_session = sip_tcp_locate(&tmp_ca.remote_address))) {
22778 s->fd = tcptls_session->fd;
22779 if (s->tcptls_session) {
22780 ao2_ref(s->tcptls_session, -1);
22781 s->tcptls_session = NULL;
22782 }
22783 s->tcptls_session = tcptls_session;
22784 return s->fd;
22785
22786 } else if (s->tcptls_session) {
22787 return s->fd;
22788 }
22789
22790
22791
22792 if (!(ca = ao2_alloc(sizeof(*ca), sip_tcptls_client_args_destructor)) ||
22793 !(ca->name = ast_strdup(name))) {
22794 goto create_tcptls_session_fail;
22795 }
22796 ca->accept_fd = -1;
22797 ca->remote_address = *(sip_real_dst(p));
22798
22799 if (s->type == SIP_TRANSPORT_TLS) {
22800 if (!(ca->tls_cfg = ast_calloc(1, sizeof(*ca->tls_cfg)))) {
22801 goto create_tcptls_session_fail;
22802 }
22803 memcpy(ca->tls_cfg, &default_tls_cfg, sizeof(*ca->tls_cfg));
22804
22805 if (!(ca->tls_cfg->certfile = ast_strdup(default_tls_cfg.certfile)) ||
22806 !(ca->tls_cfg->cipher = ast_strdup(default_tls_cfg.cipher)) ||
22807 !(ca->tls_cfg->cafile = ast_strdup(default_tls_cfg.cafile)) ||
22808 !(ca->tls_cfg->capath = ast_strdup(default_tls_cfg.capath))) {
22809
22810 goto create_tcptls_session_fail;
22811 }
22812
22813
22814 if (!ast_strlen_zero(p->tohost)) {
22815 ast_copy_string(ca->hostname, p->tohost, sizeof(ca->hostname));
22816 }
22817 }
22818
22819 if (!(s->tcptls_session = ast_tcptls_client_create(ca))) {
22820 goto create_tcptls_session_fail;
22821 }
22822
22823 s->fd = s->tcptls_session->fd;
22824
22825
22826
22827
22828
22829 if (!(th = sip_threadinfo_create(s->tcptls_session, s->type))) {
22830 goto create_tcptls_session_fail;
22831
22832 }
22833
22834
22835 ao2_ref(s->tcptls_session, +1);
22836
22837 if (ast_pthread_create_background(&ca->master, NULL, sip_tcp_worker_fn, s->tcptls_session)) {
22838 ast_debug(1, "Unable to launch '%s'.", ca->name);
22839 ao2_ref(s->tcptls_session, -1);
22840 goto create_tcptls_session_fail;
22841 }
22842
22843 return s->fd;
22844
22845 create_tcptls_session_fail:
22846 if (ca) {
22847 ao2_t_ref(ca, -1, "failed to create client, getting rid of client tcptls_session arguments");
22848 }
22849 if (s->tcptls_session) {
22850 close(tcptls_session->fd);
22851 s->fd = tcptls_session->fd = -1;
22852 ao2_ref(s->tcptls_session, -1);
22853 s->tcptls_session = NULL;
22854 }
22855 if (th) {
22856 ao2_t_unlink(threadt, th, "Removing tcptls thread info object, thread failed to open");
22857 }
22858
22859 return -1;
22860 }
22861
22862
22863
22864
22865
22866 static int sip_parse_host(char *line, int lineno, char **hostname, int *portnum, enum sip_transport *transport)
22867 {
22868 char *port;
22869
22870 if ((*hostname = strstr(line, "://"))) {
22871 *hostname += 3;
22872
22873 if (!strncasecmp(line, "tcp", 3))
22874 *transport = SIP_TRANSPORT_TCP;
22875 else if (!strncasecmp(line, "tls", 3))
22876 *transport = SIP_TRANSPORT_TLS;
22877 else if (!strncasecmp(line, "udp", 3))
22878 *transport = SIP_TRANSPORT_UDP;
22879 else
22880 ast_log(LOG_NOTICE, "'%.3s' is not a valid transport type on line %d of sip.conf. defaulting to udp.\n", line, lineno);
22881 } else {
22882 *hostname = line;
22883 *transport = SIP_TRANSPORT_UDP;
22884 }
22885
22886 if ((line = strrchr(*hostname, '@')))
22887 line++;
22888 else
22889 line = *hostname;
22890
22891 if ((port = strrchr(line, ':'))) {
22892 *port++ = '\0';
22893
22894 if (!sscanf(port, "%5u", portnum)) {
22895 ast_log(LOG_NOTICE, "'%s' is not a valid port number on line %d of sip.conf. using default.\n", port, lineno);
22896 port = NULL;
22897 }
22898 }
22899
22900 if (!port) {
22901 if (*transport & SIP_TRANSPORT_TLS) {
22902 *portnum = STANDARD_TLS_PORT;
22903 } else {
22904 *portnum = STANDARD_SIP_PORT;
22905 }
22906 }
22907
22908 return 0;
22909 }
22910
22911
22912
22913
22914
22915
22916 static int get_cached_mwi(struct sip_peer *peer, int *new, int *old)
22917 {
22918 struct sip_mailbox *mailbox;
22919
22920 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
22921 struct ast_event *event;
22922 event = ast_event_get_cached(AST_EVENT_MWI,
22923 AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox->mailbox,
22924 AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, S_OR(mailbox->context, "default"),
22925 AST_EVENT_IE_END);
22926 if (!event)
22927 continue;
22928 *new += ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
22929 *old += ast_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS);
22930 ast_event_destroy(event);
22931 }
22932
22933 return (*new || *old) ? 0 : 1;
22934 }
22935
22936
22937 static int sip_send_mwi_to_peer(struct sip_peer *peer, const struct ast_event *event, int cache_only)
22938 {
22939
22940 struct sip_pvt *p;
22941 int newmsgs = 0, oldmsgs = 0;
22942
22943 if (ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY) && !peer->mwipvt)
22944 return 0;
22945
22946
22947 if (!peer->addr.sin_addr.s_addr && !peer->defaddr.sin_addr.s_addr)
22948 return 0;
22949
22950 if (event) {
22951 newmsgs = ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
22952 oldmsgs = ast_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS);
22953 } else if (!cache_only) {
22954 struct ast_str *mailbox_str = ast_str_alloca(512);
22955 peer_mailboxes_to_str(&mailbox_str, peer);
22956 ast_app_inboxcount(mailbox_str->str, &newmsgs, &oldmsgs);
22957 } else {
22958 get_cached_mwi(peer, &newmsgs, &oldmsgs);
22959 }
22960
22961 if (peer->mwipvt) {
22962
22963 p = dialog_ref(peer->mwipvt, "sip_send_mwi_to_peer: Setting dialog ptr p from peer->mwipvt-- should this be done?");
22964 } else {
22965
22966 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL)))
22967 return -1;
22968
22969
22970
22971
22972 set_socket_transport(&p->socket, 0);
22973 if (create_addr_from_peer(p, peer)) {
22974
22975 dialog_unlink_all(p, TRUE, TRUE);
22976 dialog_unref(p, "unref dialog p just created via sip_alloc");
22977
22978 return 0;
22979 }
22980
22981 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
22982 build_via(p);
22983 ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
22984 build_callid_pvt(p);
22985 ao2_t_link(dialogs, p, "Linking in under new name");
22986
22987 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22988 }
22989
22990
22991 ast_set_flag(&p->flags[0], SIP_OUTGOING);
22992
22993 transmit_notify_with_mwi(p, newmsgs, oldmsgs, peer->vmexten);
22994 dialog_unref(p, "unref dialog ptr p just before it goes out of scope at the end of sip_send_mwi_to_peer.");
22995 return 0;
22996 }
22997
22998
22999 static void check_rtp_timeout(struct sip_pvt *dialog, time_t t)
23000 {
23001
23002 if (!dialog->rtp || !dialog->owner)
23003 return;
23004
23005
23006 if (dialog->owner->_state != AST_STATE_UP || dialog->redirip.sin_addr.s_addr)
23007 return;
23008
23009
23010 if (dialog->t38.state == T38_ENABLED)
23011 return;
23012
23013
23014 if ((ast_rtp_get_rtpkeepalive(dialog->rtp) == 0) && (ast_rtp_get_rtptimeout(dialog->rtp) == 0) && (ast_rtp_get_rtpholdtimeout(dialog->rtp) == 0))
23015 return;
23016
23017
23018 if (dialog->lastrtptx && ast_rtp_get_rtpkeepalive(dialog->rtp) &&
23019 (t > dialog->lastrtptx + ast_rtp_get_rtpkeepalive(dialog->rtp))) {
23020
23021 dialog->lastrtptx = time(NULL);
23022 ast_rtp_sendcng(dialog->rtp, 0);
23023 }
23024
23025
23026
23027
23028
23029
23030
23031
23032 if (dialog->lastrtprx && (ast_rtp_get_rtptimeout(dialog->rtp) || ast_rtp_get_rtpholdtimeout(dialog->rtp)) &&
23033 (t > dialog->lastrtprx + ast_rtp_get_rtptimeout(dialog->rtp))) {
23034
23035
23036 struct sockaddr_in sin;
23037 ast_rtp_get_peer(dialog->rtp, &sin);
23038 if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD) || (ast_rtp_get_rtpholdtimeout(dialog->rtp) &&
23039 (t > dialog->lastrtprx + ast_rtp_get_rtpholdtimeout(dialog->rtp)))) {
23040
23041 if (ast_rtp_get_rtptimeout(dialog->rtp)) {
23042 while (dialog->owner && ast_channel_trylock(dialog->owner)) {
23043 sip_pvt_unlock(dialog);
23044 usleep(1);
23045 sip_pvt_lock(dialog);
23046 }
23047 if (!dialog->owner) {
23048 return;
23049 }
23050 ast_log(LOG_NOTICE, "Disconnecting call '%s' for lack of RTP activity in %ld seconds\n",
23051 dialog->owner->name, (long) (t - dialog->lastrtprx));
23052
23053 ast_softhangup_nolock(dialog->owner, AST_SOFTHANGUP_DEV);
23054 ast_channel_unlock(dialog->owner);
23055
23056
23057
23058
23059 ast_rtp_set_rtptimeout(dialog->rtp, 0);
23060 ast_rtp_set_rtpholdtimeout(dialog->rtp, 0);
23061 if (dialog->vrtp) {
23062 ast_rtp_set_rtptimeout(dialog->vrtp, 0);
23063 ast_rtp_set_rtpholdtimeout(dialog->vrtp, 0);
23064 }
23065 }
23066 }
23067 }
23068 }
23069
23070
23071
23072
23073
23074 static void *do_monitor(void *data)
23075 {
23076 int res;
23077 time_t t;
23078 int reloading;
23079
23080
23081 if (sipsock > -1)
23082 sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
23083
23084
23085 for(;;) {
23086
23087 ast_mutex_lock(&sip_reload_lock);
23088 reloading = sip_reloading;
23089 sip_reloading = FALSE;
23090 ast_mutex_unlock(&sip_reload_lock);
23091 if (reloading) {
23092 ast_verb(1, "Reloading SIP\n");
23093 sip_do_reload(sip_reloadreason);
23094
23095
23096 if (sipsock > -1) {
23097 if (sipsock_read_id)
23098 sipsock_read_id = ast_io_change(io, sipsock_read_id, sipsock, NULL, 0, NULL);
23099 else
23100 sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
23101 } else if (sipsock_read_id) {
23102 ast_io_remove(io, sipsock_read_id);
23103 sipsock_read_id = NULL;
23104 }
23105 }
23106
23107
23108 t = time(NULL);
23109
23110
23111
23112
23113 ao2_t_callback(dialogs, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, dialog_needdestroy, &t,
23114 "callback to remove dialogs w/needdestroy");
23115
23116
23117
23118
23119
23120
23121
23122
23123
23124
23125
23126 pthread_testcancel();
23127
23128 res = ast_sched_wait(sched);
23129 if ((res < 0) || (res > 1000))
23130 res = 1000;
23131 res = ast_io_wait(io, res);
23132 if (res > 20)
23133 ast_debug(1, "chan_sip: ast_io_wait ran %d all at once\n", res);
23134 ast_mutex_lock(&monlock);
23135 res = ast_sched_runq(sched);
23136 if (res >= 20)
23137 ast_debug(1, "chan_sip: ast_sched_runq ran %d all at once\n", res);
23138 ast_mutex_unlock(&monlock);
23139 }
23140
23141
23142 return NULL;
23143 }
23144
23145
23146 static int restart_monitor(void)
23147 {
23148
23149 if (monitor_thread == AST_PTHREADT_STOP)
23150 return 0;
23151 ast_mutex_lock(&monlock);
23152 if (monitor_thread == pthread_self()) {
23153 ast_mutex_unlock(&monlock);
23154 ast_log(LOG_WARNING, "Cannot kill myself\n");
23155 return -1;
23156 }
23157 if (monitor_thread != AST_PTHREADT_NULL) {
23158
23159 pthread_kill(monitor_thread, SIGURG);
23160 } else {
23161
23162 if (ast_pthread_create_background(&monitor_thread, NULL, do_monitor, NULL) < 0) {
23163 ast_mutex_unlock(&monlock);
23164 ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
23165 return -1;
23166 }
23167 }
23168 ast_mutex_unlock(&monlock);
23169 return 0;
23170 }
23171
23172
23173
23174 static void restart_session_timer(struct sip_pvt *p)
23175 {
23176 if (!p->stimer) {
23177 ast_log(LOG_WARNING, "Null stimer in restart_session_timer - %s\n", p->callid);
23178 return;
23179 }
23180
23181 if (p->stimer->st_active == TRUE) {
23182 AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
23183 dialog_unref(p, "Removing session timer ref"));
23184 ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
23185 start_session_timer(p);
23186 }
23187 }
23188
23189
23190
23191 static void stop_session_timer(struct sip_pvt *p)
23192 {
23193 if (!p->stimer) {
23194 ast_log(LOG_WARNING, "Null stimer in stop_session_timer - %s\n", p->callid);
23195 return;
23196 }
23197
23198 if (p->stimer->st_active == TRUE) {
23199 p->stimer->st_active = FALSE;
23200 AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
23201 dialog_unref(p, "removing session timer ref"));
23202 ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
23203 }
23204 }
23205
23206
23207
23208 static void start_session_timer(struct sip_pvt *p)
23209 {
23210 if (!p->stimer) {
23211 ast_log(LOG_WARNING, "Null stimer in start_session_timer - %s\n", p->callid);
23212 return;
23213 }
23214
23215 p->stimer->st_schedid = ast_sched_add(sched, p->stimer->st_interval * 1000 / 2, proc_session_timer,
23216 dialog_ref(p, "adding session timer ref"));
23217 if (p->stimer->st_schedid < 0) {
23218 dialog_unref(p, "removing session timer ref");
23219 ast_log(LOG_ERROR, "ast_sched_add failed.\n");
23220 }
23221 ast_debug(2, "Session timer started: %d - %s\n", p->stimer->st_schedid, p->callid);
23222 }
23223
23224
23225
23226 static int proc_session_timer(const void *vp)
23227 {
23228 struct sip_pvt *p = (struct sip_pvt *) vp;
23229 int sendreinv = FALSE;
23230 int res = 0;
23231
23232 if (!p->stimer) {
23233 ast_log(LOG_WARNING, "Null stimer in proc_session_timer - %s\n", p->callid);
23234 goto return_unref;
23235 }
23236
23237 ast_debug(2, "Session timer expired: %d - %s\n", p->stimer->st_schedid, p->callid);
23238
23239 if (!p->owner) {
23240 goto return_unref;
23241 }
23242
23243 if ((p->stimer->st_active != TRUE) || (p->owner->_state != AST_STATE_UP)) {
23244 goto return_unref;
23245 }
23246
23247 switch (p->stimer->st_ref) {
23248 case SESSION_TIMER_REFRESHER_UAC:
23249 if (p->outgoing_call == TRUE) {
23250 sendreinv = TRUE;
23251 }
23252 break;
23253 case SESSION_TIMER_REFRESHER_UAS:
23254 if (p->outgoing_call != TRUE) {
23255 sendreinv = TRUE;
23256 }
23257 break;
23258 default:
23259 ast_log(LOG_ERROR, "Unknown session refresher %d\n", p->stimer->st_ref);
23260 goto return_unref;
23261 }
23262
23263 if (sendreinv == TRUE) {
23264 res = 1;
23265 transmit_reinvite_with_sdp(p, FALSE, TRUE);
23266 } else {
23267 p->stimer->st_expirys++;
23268 if (p->stimer->st_expirys >= 2) {
23269 if (p->stimer->quit_flag) {
23270 goto return_unref;
23271 }
23272 ast_log(LOG_WARNING, "Session-Timer expired - %s\n", p->callid);
23273 sip_pvt_lock(p);
23274 while (p->owner && ast_channel_trylock(p->owner)) {
23275 sip_pvt_unlock(p);
23276 usleep(1);
23277 if (p->stimer && p->stimer->quit_flag) {
23278 goto return_unref;
23279 }
23280 sip_pvt_lock(p);
23281 }
23282
23283 ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
23284 ast_channel_unlock(p->owner);
23285 sip_pvt_unlock(p);
23286 }
23287 }
23288
23289 return_unref:
23290 if (!res) {
23291
23292 if (p->stimer) {
23293 p->stimer->st_schedid = -1;
23294 stop_session_timer(p);
23295 }
23296
23297
23298
23299 dialog_unref(p, "removing session timer ref");
23300 }
23301
23302 return res;
23303 }
23304
23305
23306
23307 int parse_minse (const char *p_hdrval, int *const p_interval)
23308 {
23309 if (ast_strlen_zero(p_hdrval)) {
23310 ast_log(LOG_WARNING, "Null Min-SE header\n");
23311 return -1;
23312 }
23313
23314 *p_interval = 0;
23315 p_hdrval = ast_skip_blanks(p_hdrval);
23316 if (!sscanf(p_hdrval, "%30d", p_interval)) {
23317 ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
23318 return -1;
23319 }
23320
23321 ast_debug(2, "Received Min-SE: %d\n", *p_interval);
23322 return 0;
23323 }
23324
23325
23326
23327 int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref)
23328 {
23329 char *p_token;
23330 int ref_idx;
23331 char *p_se_hdr;
23332
23333 if (ast_strlen_zero(p_hdrval)) {
23334 ast_log(LOG_WARNING, "Null Session-Expires header\n");
23335 return -1;
23336 }
23337
23338 *p_ref = SESSION_TIMER_REFRESHER_AUTO;
23339 *p_interval = 0;
23340
23341 p_se_hdr = ast_strdupa(p_hdrval);
23342 p_se_hdr = ast_skip_blanks(p_se_hdr);
23343
23344 while ((p_token = strsep(&p_se_hdr, ";"))) {
23345 p_token = ast_skip_blanks(p_token);
23346 if (!sscanf(p_token, "%30d", p_interval)) {
23347 ast_log(LOG_WARNING, "Parsing of Session-Expires failed\n");
23348 return -1;
23349 }
23350
23351 ast_debug(2, "Session-Expires: %d\n", *p_interval);
23352
23353 if (!p_se_hdr)
23354 continue;
23355
23356 p_se_hdr = ast_skip_blanks(p_se_hdr);
23357 ref_idx = strlen("refresher=");
23358 if (!strncasecmp(p_se_hdr, "refresher=", ref_idx)) {
23359 p_se_hdr += ref_idx;
23360 p_se_hdr = ast_skip_blanks(p_se_hdr);
23361
23362 if (!strncasecmp(p_se_hdr, "uac", strlen("uac"))) {
23363 *p_ref = SESSION_TIMER_REFRESHER_UAC;
23364 ast_debug(2, "Refresher: UAC\n");
23365 } else if (!strncasecmp(p_se_hdr, "uas", strlen("uas"))) {
23366 *p_ref = SESSION_TIMER_REFRESHER_UAS;
23367 ast_debug(2, "Refresher: UAS\n");
23368 } else {
23369 ast_log(LOG_WARNING, "Invalid refresher value %s\n", p_se_hdr);
23370 return -1;
23371 }
23372 break;
23373 }
23374 }
23375 return 0;
23376 }
23377
23378
23379
23380
23381
23382
23383
23384
23385
23386 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp)
23387 {
23388 int rtn;
23389 const char *p_hdrval;
23390 int minse;
23391
23392 p_hdrval = get_header(rsp, "Min-SE");
23393 if (ast_strlen_zero(p_hdrval)) {
23394 ast_log(LOG_WARNING, "422 response without a Min-SE header %s\n", p_hdrval);
23395 return;
23396 }
23397 rtn = parse_minse(p_hdrval, &minse);
23398 if (rtn != 0) {
23399 ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
23400 return;
23401 }
23402 p->stimer->st_interval = minse;
23403 transmit_invite(p, SIP_INVITE, 1, 2);
23404 }
23405
23406
23407
23408
23409
23410
23411 int st_get_se(struct sip_pvt *p, int max)
23412 {
23413 if (max == TRUE) {
23414 if (p->stimer->st_cached_max_se) {
23415 return p->stimer->st_cached_max_se;
23416 } else if (p->peername) {
23417 struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE, 0);
23418 if (pp) {
23419 p->stimer->st_cached_max_se = pp->stimer.st_max_se;
23420 unref_peer(pp, "unref peer pointer from find_peer call in st_get_se");
23421 return (p->stimer->st_cached_max_se);
23422 }
23423 }
23424 p->stimer->st_cached_max_se = global_max_se;
23425 return (p->stimer->st_cached_max_se);
23426 } else {
23427 if (p->stimer->st_cached_min_se) {
23428 return p->stimer->st_cached_min_se;
23429 } else if (p->peername) {
23430 struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE, 0);
23431 if (pp) {
23432 p->stimer->st_cached_min_se = pp->stimer.st_min_se;
23433 unref_peer(pp, "unref peer pointer from find_peer call in st_get_se (2)");
23434 return (p->stimer->st_cached_min_se);
23435 }
23436 }
23437 p->stimer->st_cached_min_se = global_min_se;
23438 return (p->stimer->st_cached_min_se);
23439 }
23440 }
23441
23442
23443
23444
23445
23446 enum st_refresher st_get_refresher(struct sip_pvt *p)
23447 {
23448 if (p->stimer->st_cached_ref != SESSION_TIMER_REFRESHER_AUTO)
23449 return p->stimer->st_cached_ref;
23450
23451 if (p->peername) {
23452 struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE, 0);
23453 if (pp) {
23454 p->stimer->st_cached_ref = pp->stimer.st_ref;
23455 unref_peer(pp, "unref peer pointer from find_peer call in st_get_refresher");
23456 return pp->stimer.st_ref;
23457 }
23458 }
23459
23460 p->stimer->st_cached_ref = global_st_refresher;
23461 return global_st_refresher;
23462 }
23463
23464
23465
23466
23467
23468 enum st_mode st_get_mode(struct sip_pvt *p)
23469 {
23470 if (!p->stimer)
23471 sip_st_alloc(p);
23472
23473 if (p->stimer->st_cached_mode != SESSION_TIMER_MODE_INVALID)
23474 return p->stimer->st_cached_mode;
23475
23476 if (p->peername) {
23477 struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE, 0);
23478 if (pp) {
23479 p->stimer->st_cached_mode = pp->stimer.st_mode_oper;
23480 unref_peer(pp, "unref peer pointer from find_peer call in st_get_mode");
23481 return pp->stimer.st_mode_oper;
23482 }
23483 }
23484
23485 p->stimer->st_cached_mode = global_st_mode;
23486 return global_st_mode;
23487 }
23488
23489
23490
23491 static int sip_poke_noanswer(const void *data)
23492 {
23493 struct sip_peer *peer = (struct sip_peer *)data;
23494
23495 peer->pokeexpire = -1;
23496
23497 if (peer->lastms > -1) {
23498 ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE! Last qualify: %d\n", peer->name, peer->lastms);
23499 if (sip_cfg.peer_rtupdate) {
23500 ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", "-1", SENTINEL);
23501 }
23502 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer->name, -1);
23503 if (sip_cfg.regextenonqualify) {
23504 register_peer_exten(peer, FALSE);
23505 }
23506 }
23507
23508 if (peer->call) {
23509 dialog_unlink_all(peer->call, TRUE, TRUE);
23510 peer->call = dialog_unref(peer->call, "unref dialog peer->call");
23511
23512 }
23513
23514
23515 if (peer->lastms > -1) {
23516 peer->lastms = -1;
23517 ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
23518 }
23519
23520
23521 AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
23522 DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer,
23523 unref_peer(_data, "removing poke peer ref"),
23524 unref_peer(peer, "removing poke peer ref"),
23525 ref_peer(peer, "adding poke peer ref"));
23526
23527
23528 unref_peer(peer, "release peer poke noanswer ref");
23529
23530 return 0;
23531 }
23532
23533
23534
23535
23536
23537
23538 static int sip_poke_peer(struct sip_peer *peer, int force)
23539 {
23540 struct sip_pvt *p;
23541 int xmitres = 0;
23542
23543 if ((!peer->maxms && !force) || !peer->addr.sin_addr.s_addr) {
23544
23545
23546 AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
23547 unref_peer(peer, "removing poke peer ref"));
23548
23549 peer->lastms = 0;
23550 if (peer->call) {
23551 peer->call = dialog_unref(peer->call, "unref dialog peer->call");
23552 }
23553 return 0;
23554 }
23555 if (peer->call) {
23556 if (sipdebug) {
23557 ast_log(LOG_NOTICE, "Still have a QUALIFY dialog active, deleting\n");
23558 }
23559 dialog_unlink_all(peer->call, TRUE, TRUE);
23560 peer->call = dialog_unref(peer->call, "unref dialog peer->call");
23561
23562 }
23563 if (!(p = sip_alloc(NULL, NULL, 0, SIP_OPTIONS, NULL))) {
23564 return -1;
23565 }
23566 peer->call = dialog_ref(p, "copy sip alloc from p to peer->call");
23567
23568 p->sa = peer->addr;
23569 p->recv = peer->addr;
23570 copy_socket_data(&p->socket, &peer->socket);
23571 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
23572 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
23573
23574
23575 if (!ast_strlen_zero(peer->fullcontact))
23576 ast_string_field_set(p, fullcontact, peer->fullcontact);
23577
23578 if (!ast_strlen_zero(peer->tohost))
23579 ast_string_field_set(p, tohost, peer->tohost);
23580 else
23581 ast_string_field_set(p, tohost, ast_inet_ntoa(peer->addr.sin_addr));
23582
23583
23584 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
23585 build_via(p);
23586 ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
23587 build_callid_pvt(p);
23588 ao2_t_link(dialogs, p, "Linking in under new name");
23589
23590 AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
23591 unref_peer(peer, "removing poke peer ref"));
23592
23593 if (p->relatedpeer)
23594 p->relatedpeer = unref_peer(p->relatedpeer,"unsetting the relatedpeer field in the dialog, before it is set to something else.");
23595 p->relatedpeer = ref_peer(peer, "setting the relatedpeer field in the dialog");
23596 ast_set_flag(&p->flags[0], SIP_OUTGOING);
23597 #ifdef VOCAL_DATA_HACK
23598 ast_copy_string(p->username, "__VOCAL_DATA_SHOULD_READ_THE_SIP_SPEC__", sizeof(p->username));
23599 xmitres = transmit_invite(p, SIP_INVITE, 0, 2);
23600 #else
23601 xmitres = transmit_invite(p, SIP_OPTIONS, 0, 2);
23602 #endif
23603 peer->ps = ast_tvnow();
23604 if (xmitres == XMIT_ERROR) {
23605 sip_poke_noanswer(peer);
23606 } else if (!force) {
23607 AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, peer->maxms * 2, sip_poke_noanswer, peer,
23608 unref_peer(_data, "removing poke peer ref"),
23609 unref_peer(peer, "removing poke peer ref"),
23610 ref_peer(peer, "adding poke peer ref"));
23611 }
23612 dialog_unref(p, "unref dialog at end of sip_poke_peer, obtained from sip_alloc, just before it goes out of scope");
23613 return 0;
23614 }
23615
23616
23617
23618
23619
23620
23621
23622
23623
23624
23625
23626
23627
23628
23629
23630
23631
23632
23633
23634
23635
23636
23637
23638
23639
23640
23641
23642
23643
23644
23645
23646
23647
23648
23649 static int sip_devicestate(void *data)
23650 {
23651 char *host;
23652 char *tmp;
23653 struct sip_peer *p;
23654
23655 int res = AST_DEVICE_INVALID;
23656
23657
23658 host = ast_strdupa(data ? data : "");
23659 if ((tmp = strchr(host, '@')))
23660 host = tmp + 1;
23661
23662 ast_debug(3, "Checking device state for peer %s\n", host);
23663
23664
23665
23666
23667
23668
23669
23670
23671 if ((p = find_peer(host, NULL, FALSE, FINDALLDEVICES, TRUE, 0))) {
23672 if (p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) {
23673
23674
23675
23676
23677
23678
23679
23680
23681
23682
23683
23684 if (p->onHold)
23685
23686 res = AST_DEVICE_ONHOLD;
23687 else if (p->inRinging) {
23688 if (p->inRinging == p->inUse)
23689 res = AST_DEVICE_RINGING;
23690 else
23691 res = AST_DEVICE_RINGINUSE;
23692 } else if (p->call_limit && (p->inUse == p->call_limit))
23693
23694 res = AST_DEVICE_BUSY;
23695 else if (p->call_limit && p->busy_level && p->inUse >= p->busy_level)
23696
23697 res = AST_DEVICE_BUSY;
23698 else if (p->call_limit && p->inUse)
23699
23700 res = AST_DEVICE_INUSE;
23701 else if (p->maxms && ((p->lastms > p->maxms) || (p->lastms < 0)))
23702
23703 res = AST_DEVICE_UNAVAILABLE;
23704 else
23705 res = AST_DEVICE_NOT_INUSE;
23706 } else {
23707
23708 res = AST_DEVICE_UNAVAILABLE;
23709 }
23710 unref_peer(p, "unref_peer, from sip_devicestate, release ref from find_peer");
23711 } else {
23712 res = AST_DEVICE_UNKNOWN;
23713 }
23714
23715 return res;
23716 }
23717
23718
23719
23720
23721
23722
23723
23724
23725
23726
23727
23728 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause)
23729 {
23730 struct sip_pvt *p;
23731 struct ast_channel *tmpc = NULL;
23732 char *ext = NULL, *host;
23733 char tmp[256];
23734 char *dest = data;
23735 char *dnid;
23736 char *secret = NULL;
23737 char *md5secret = NULL;
23738 char *authname = NULL;
23739 char *trans = NULL;
23740 enum sip_transport transport = 0;
23741 int oldformat = format;
23742
23743
23744
23745
23746
23747
23748
23749
23750 format &= AST_FORMAT_AUDIO_MASK;
23751 if (!format) {
23752 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));
23753 *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
23754 return NULL;
23755 }
23756 ast_debug(1, "Asked to create a SIP channel with formats: %s\n", ast_getformatname_multiple(tmp, sizeof(tmp), oldformat));
23757
23758 if (ast_strlen_zero(dest)) {
23759 ast_log(LOG_ERROR, "Unable to create channel with empty destination.\n");
23760 *cause = AST_CAUSE_CHANNEL_UNACCEPTABLE;
23761 return NULL;
23762 }
23763
23764 if (!(p = sip_alloc(NULL, NULL, 0, SIP_INVITE, NULL))) {
23765 ast_log(LOG_ERROR, "Unable to build sip pvt data for '%s' (Out of memory or socket error)\n", dest);
23766 *cause = AST_CAUSE_SWITCH_CONGESTION;
23767 return NULL;
23768 }
23769
23770 p->outgoing_call = TRUE;
23771
23772 if (!(p->options = ast_calloc(1, sizeof(*p->options)))) {
23773 dialog_unlink_all(p, TRUE, TRUE);
23774 dialog_unref(p, "unref dialog p from mem fail");
23775
23776 ast_log(LOG_ERROR, "Unable to build option SIP data structure - Out of memory\n");
23777 *cause = AST_CAUSE_SWITCH_CONGESTION;
23778 return NULL;
23779 }
23780
23781
23782 ast_copy_string(tmp, dest, sizeof(tmp));
23783
23784
23785
23786 dnid = strchr(tmp, '!');
23787 if (dnid != NULL) {
23788 *dnid++ = '\0';
23789 ast_string_field_set(p, todnid, dnid);
23790 }
23791
23792
23793 host = strchr(tmp, '@');
23794 if (host) {
23795 *host++ = '\0';
23796 ext = tmp;
23797 secret = strchr(ext, ':');
23798 }
23799 if (secret) {
23800 *secret++ = '\0';
23801 md5secret = strchr(secret, ':');
23802 }
23803 if (md5secret) {
23804 *md5secret++ = '\0';
23805 authname = strchr(md5secret, ':');
23806 }
23807 if (authname) {
23808 *authname++ = '\0';
23809 trans = strchr(authname, ':');
23810 }
23811 if (trans) {
23812 *trans++ = '\0';
23813 if (!strcasecmp(trans, "tcp"))
23814 transport = SIP_TRANSPORT_TCP;
23815 else if (!strcasecmp(trans, "tls"))
23816 transport = SIP_TRANSPORT_TLS;
23817 else {
23818 if (strcasecmp(trans, "udp"))
23819 ast_log(LOG_WARNING, "'%s' is not a valid transport option to Dial() for SIP calls, using udp by default.\n", trans);
23820 transport = SIP_TRANSPORT_UDP;
23821 }
23822 } else {
23823 transport = SIP_TRANSPORT_UDP;
23824 }
23825
23826 if (!host) {
23827 ext = strchr(tmp, '/');
23828 if (ext)
23829 *ext++ = '\0';
23830 host = tmp;
23831 }
23832
23833 set_socket_transport(&p->socket, transport);
23834
23835
23836
23837
23838
23839
23840 if (create_addr(p, host, NULL, 1)) {
23841 *cause = AST_CAUSE_UNREGISTERED;
23842 ast_debug(3, "Cant create SIP call - target device not registered\n");
23843 dialog_unlink_all(p, TRUE, TRUE);
23844 dialog_unref(p, "unref dialog p UNREGISTERED");
23845
23846 return NULL;
23847 }
23848 if (ast_strlen_zero(p->peername) && ext)
23849 ast_string_field_set(p, peername, ext);
23850
23851 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
23852 build_via(p);
23853 ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
23854 build_callid_pvt(p);
23855 ao2_t_link(dialogs, p, "Linking in under new name");
23856
23857
23858
23859
23860
23861
23862 if (ext) {
23863 ast_string_field_set(p, username, ext);
23864 ast_string_field_set(p, fullcontact, NULL);
23865 }
23866 if (secret && !ast_strlen_zero(secret))
23867 ast_string_field_set(p, peersecret, secret);
23868
23869 if (md5secret && !ast_strlen_zero(md5secret))
23870 ast_string_field_set(p, peermd5secret, md5secret);
23871
23872 if (authname && !ast_strlen_zero(authname))
23873 ast_string_field_set(p, authname, authname);
23874 #if 0
23875 printf("Setting up to call extension '%s' at '%s'\n", ext ? ext : "<none>", host);
23876 #endif
23877 p->prefcodec = oldformat;
23878 p->jointcapability = oldformat & p->capability;
23879 sip_pvt_lock(p);
23880 tmpc = sip_new(p, AST_STATE_DOWN, host);
23881 if (sip_cfg.callevents)
23882 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
23883 "Channel: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
23884 p->owner? p->owner->name : "", "SIP", p->callid, p->fullcontact, p->peername);
23885 sip_pvt_unlock(p);
23886 if (!tmpc) {
23887 dialog_unlink_all(p, TRUE, TRUE);
23888
23889 }
23890 dialog_unref(p, "toss pvt ptr at end of sip_request_call");
23891 ast_update_use_count();
23892 restart_monitor();
23893 return tmpc;
23894 }
23895
23896
23897 static void set_insecure_flags (struct ast_flags *flags, const char *value, int lineno)
23898 {
23899 if (ast_strlen_zero(value))
23900 return;
23901
23902 if (!ast_false(value)) {
23903 char buf[64];
23904 char *word, *next;
23905
23906 ast_copy_string(buf, value, sizeof(buf));
23907 next = buf;
23908 while ((word = strsep(&next, ","))) {
23909 if (!strcasecmp(word, "port"))
23910 ast_set_flag(&flags[0], SIP_INSECURE_PORT);
23911 else if (!strcasecmp(word, "invite"))
23912 ast_set_flag(&flags[0], SIP_INSECURE_INVITE);
23913 else
23914 ast_log(LOG_WARNING, "Unknown insecure mode '%s' on line %d\n", value, lineno);
23915 }
23916 }
23917 }
23918
23919
23920
23921
23922
23923 static int handle_t38_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v,
23924 int *maxdatagram)
23925 {
23926 int res = 1;
23927
23928 if (!strcasecmp(v->name, "t38pt_udptl")) {
23929 char *buf = ast_strdupa(v->value);
23930 char *word, *next = buf;
23931
23932 ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT);
23933
23934 while ((word = strsep(&next, ","))) {
23935 if (ast_true(word) || !strcasecmp(word, "fec")) {
23936 ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
23937 ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_FEC);
23938 } else if (!strcasecmp(word, "redundancy")) {
23939 ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
23940 ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY);
23941 } else if (!strcasecmp(word, "none")) {
23942 ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
23943 ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL);
23944 } else if (!strncasecmp(word, "maxdatagram=", 12)) {
23945 if (sscanf(&word[12], "%30u", maxdatagram) != 1) {
23946 ast_log(LOG_WARNING, "Invalid maxdatagram '%s' at line %d of %s\n", v->value, v->lineno, config);
23947 *maxdatagram = global_t38_maxdatagram;
23948 }
23949 }
23950 }
23951 } else if (!strcasecmp(v->name, "t38pt_usertpsource")) {
23952 ast_set_flag(&mask[1], SIP_PAGE2_UDPTL_DESTINATION);
23953 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_UDPTL_DESTINATION);
23954 } else if (!strcasecmp(v->name, "forwardloopdetected")) {
23955 ast_set_flag(&mask[1], SIP_PAGE2_FORWARD_LOOP_DETECTED);
23956 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_FORWARD_LOOP_DETECTED);
23957 } else {
23958 res = 0;
23959 }
23960
23961 return res;
23962 }
23963
23964
23965
23966
23967
23968
23969
23970
23971 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v)
23972 {
23973 int res = 1;
23974
23975 if (!strcasecmp(v->name, "trustrpid")) {
23976 ast_set_flag(&mask[0], SIP_TRUSTRPID);
23977 ast_set2_flag(&flags[0], ast_true(v->value), SIP_TRUSTRPID);
23978 } else if (!strcasecmp(v->name, "sendrpid")) {
23979 ast_set_flag(&mask[0], SIP_SENDRPID);
23980 ast_set2_flag(&flags[0], ast_true(v->value), SIP_SENDRPID);
23981 } else if (!strcasecmp(v->name, "g726nonstandard")) {
23982 ast_set_flag(&mask[0], SIP_G726_NONSTANDARD);
23983 ast_set2_flag(&flags[0], ast_true(v->value), SIP_G726_NONSTANDARD);
23984 } else if (!strcasecmp(v->name, "useclientcode")) {
23985 ast_set_flag(&mask[0], SIP_USECLIENTCODE);
23986 ast_set2_flag(&flags[0], ast_true(v->value), SIP_USECLIENTCODE);
23987 } else if (!strcasecmp(v->name, "dtmfmode")) {
23988 ast_set_flag(&mask[0], SIP_DTMF);
23989 ast_clear_flag(&flags[0], SIP_DTMF);
23990 if (!strcasecmp(v->value, "inband"))
23991 ast_set_flag(&flags[0], SIP_DTMF_INBAND);
23992 else if (!strcasecmp(v->value, "rfc2833"))
23993 ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
23994 else if (!strcasecmp(v->value, "info"))
23995 ast_set_flag(&flags[0], SIP_DTMF_INFO);
23996 else if (!strcasecmp(v->value, "shortinfo"))
23997 ast_set_flag(&flags[0], SIP_DTMF_SHORTINFO);
23998 else if (!strcasecmp(v->value, "auto"))
23999 ast_set_flag(&flags[0], SIP_DTMF_AUTO);
24000 else {
24001 ast_log(LOG_WARNING, "Unknown dtmf mode '%s' on line %d, using rfc2833\n", v->value, v->lineno);
24002 ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
24003 }
24004 } else if (!strcasecmp(v->name, "nat")) {
24005 ast_set_flag(&mask[0], SIP_NAT);
24006 ast_clear_flag(&flags[0], SIP_NAT);
24007 if (!strcasecmp(v->value, "never"))
24008 ast_set_flag(&flags[0], SIP_NAT_NEVER);
24009 else if (!strcasecmp(v->value, "route"))
24010 ast_set_flag(&flags[0], SIP_NAT_ROUTE);
24011 else if (ast_true(v->value))
24012 ast_set_flag(&flags[0], SIP_NAT_ALWAYS);
24013 else
24014 ast_set_flag(&flags[0], SIP_NAT_RFC3581);
24015 } else if (!strcasecmp(v->name, "directmedia") || !strcasecmp(v->name, "canreinvite")) {
24016 ast_set_flag(&mask[0], SIP_REINVITE);
24017 ast_clear_flag(&flags[0], SIP_REINVITE);
24018 if (ast_true(v->value)) {
24019 ast_set_flag(&flags[0], SIP_DIRECT_MEDIA | SIP_DIRECT_MEDIA_NAT);
24020 } else if (!ast_false(v->value)) {
24021 char buf[64];
24022 char *word, *next = buf;
24023
24024 ast_copy_string(buf, v->value, sizeof(buf));
24025 while ((word = strsep(&next, ","))) {
24026 if (!strcasecmp(word, "update")) {
24027 ast_set_flag(&flags[0], SIP_REINVITE_UPDATE | SIP_DIRECT_MEDIA);
24028 } else if (!strcasecmp(word, "nonat")) {
24029 ast_set_flag(&flags[0], SIP_DIRECT_MEDIA);
24030 ast_clear_flag(&flags[0], SIP_DIRECT_MEDIA_NAT);
24031 } else {
24032 ast_log(LOG_WARNING, "Unknown directmedia mode '%s' on line %d\n", v->value, v->lineno);
24033 }
24034 }
24035 }
24036 } else if (!strcasecmp(v->name, "insecure")) {
24037 ast_set_flag(&mask[0], SIP_INSECURE);
24038 ast_clear_flag(&flags[0], SIP_INSECURE);
24039 set_insecure_flags(&flags[0], v->value, v->lineno);
24040 } else if (!strcasecmp(v->name, "progressinband")) {
24041 ast_set_flag(&mask[0], SIP_PROG_INBAND);
24042 ast_clear_flag(&flags[0], SIP_PROG_INBAND);
24043 if (ast_true(v->value))
24044 ast_set_flag(&flags[0], SIP_PROG_INBAND_YES);
24045 else if (strcasecmp(v->value, "never"))
24046 ast_set_flag(&flags[0], SIP_PROG_INBAND_NO);
24047 } else if (!strcasecmp(v->name, "promiscredir")) {
24048 ast_set_flag(&mask[0], SIP_PROMISCREDIR);
24049 ast_set2_flag(&flags[0], ast_true(v->value), SIP_PROMISCREDIR);
24050 } else if (!strcasecmp(v->name, "videosupport")) {
24051 if (!strcasecmp(v->value, "always")) {
24052 ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
24053 ast_set_flag(&flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
24054 } else {
24055 ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT);
24056 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_VIDEOSUPPORT);
24057 }
24058 } else if (!strcasecmp(v->name, "textsupport")) {
24059 ast_set_flag(&mask[1], SIP_PAGE2_TEXTSUPPORT);
24060 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_TEXTSUPPORT);
24061 res = 1;
24062 } else if (!strcasecmp(v->name, "allowoverlap")) {
24063 ast_set_flag(&mask[1], SIP_PAGE2_ALLOWOVERLAP);
24064 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWOVERLAP);
24065 } else if (!strcasecmp(v->name, "allowsubscribe")) {
24066 ast_set_flag(&mask[1], SIP_PAGE2_ALLOWSUBSCRIBE);
24067 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWSUBSCRIBE);
24068 } else if (!strcasecmp(v->name, "ignoresdpversion")) {
24069 ast_set_flag(&mask[1], SIP_PAGE2_IGNORESDPVERSION);
24070 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_IGNORESDPVERSION);
24071 } else if (!strcasecmp(v->name, "faxdetect")) {
24072 ast_set_flag(&mask[1], SIP_PAGE2_FAX_DETECT);
24073 if (ast_true(v->value)) {
24074 ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_BOTH);
24075 } else if (ast_false(v->value)) {
24076 ast_clear_flag(&flags[1], SIP_PAGE2_FAX_DETECT_BOTH);
24077 } else {
24078 char *buf = ast_strdupa(v->value);
24079 char *word, *next = buf;
24080
24081 while ((word = strsep(&next, ","))) {
24082 if (!strcasecmp(word, "cng")) {
24083 ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_CNG);
24084 } else if (!strcasecmp(word, "t38")) {
24085 ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_T38);
24086 } else {
24087 ast_log(LOG_WARNING, "Unknown faxdetect mode '%s' on line %d.\n", word, v->lineno);
24088 }
24089 }
24090 }
24091 } else if (!strcasecmp(v->name, "rfc2833compensate")) {
24092 ast_set_flag(&mask[1], SIP_PAGE2_RFC2833_COMPENSATE);
24093 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RFC2833_COMPENSATE);
24094 } else if (!strcasecmp(v->name, "buggymwi")) {
24095 ast_set_flag(&mask[1], SIP_PAGE2_BUGGY_MWI);
24096 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_BUGGY_MWI);
24097 } else
24098 res = 0;
24099
24100 return res;
24101 }
24102
24103
24104 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context)
24105 {
24106 struct domain *d;
24107
24108 if (ast_strlen_zero(domain)) {
24109 ast_log(LOG_WARNING, "Zero length domain.\n");
24110 return 1;
24111 }
24112
24113 if (!(d = ast_calloc(1, sizeof(*d))))
24114 return 0;
24115
24116 ast_copy_string(d->domain, domain, sizeof(d->domain));
24117
24118 if (!ast_strlen_zero(context))
24119 ast_copy_string(d->context, context, sizeof(d->context));
24120
24121 d->mode = mode;
24122
24123 AST_LIST_LOCK(&domain_list);
24124 AST_LIST_INSERT_TAIL(&domain_list, d, list);
24125 AST_LIST_UNLOCK(&domain_list);
24126
24127 if (sipdebug)
24128 ast_debug(1, "Added local SIP domain '%s'\n", domain);
24129
24130 return 1;
24131 }
24132
24133
24134 static int check_sip_domain(const char *domain, char *context, size_t len)
24135 {
24136 struct domain *d;
24137 int result = 0;
24138
24139 AST_LIST_LOCK(&domain_list);
24140 AST_LIST_TRAVERSE(&domain_list, d, list) {
24141 if (strcasecmp(d->domain, domain))
24142 continue;
24143
24144 if (len && !ast_strlen_zero(d->context))
24145 ast_copy_string(context, d->context, len);
24146
24147 result = 1;
24148 break;
24149 }
24150 AST_LIST_UNLOCK(&domain_list);
24151
24152 return result;
24153 }
24154
24155
24156 static void clear_sip_domains(void)
24157 {
24158 struct domain *d;
24159
24160 AST_LIST_LOCK(&domain_list);
24161 while ((d = AST_LIST_REMOVE_HEAD(&domain_list, list)))
24162 ast_free(d);
24163 AST_LIST_UNLOCK(&domain_list);
24164 }
24165
24166
24167
24168 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, const char *configuration, int lineno)
24169 {
24170 char authcopy[256];
24171 char *username=NULL, *realm=NULL, *secret=NULL, *md5secret=NULL;
24172 struct sip_auth *a, *b, *auth;
24173
24174 if (ast_strlen_zero(configuration))
24175 return authlist;
24176
24177 ast_debug(1, "Auth config :: %s\n", configuration);
24178
24179 ast_copy_string(authcopy, configuration, sizeof(authcopy));
24180 username = authcopy;
24181
24182
24183 realm = strrchr(username, '@');
24184 if (realm)
24185 *realm++ = '\0';
24186 if (ast_strlen_zero(username) || ast_strlen_zero(realm)) {
24187 ast_log(LOG_WARNING, "Format for authentication entry is user[:secret]@realm at line %d\n", lineno);
24188 return authlist;
24189 }
24190
24191
24192 if ((secret = strchr(username, ':'))) {
24193 *secret++ = '\0';
24194 } else if ((md5secret = strchr(username, '#'))) {
24195 *md5secret++ = '\0';
24196 }
24197
24198 if (!(auth = ast_calloc(1, sizeof(*auth))))
24199 return authlist;
24200
24201 ast_copy_string(auth->realm, realm, sizeof(auth->realm));
24202 ast_copy_string(auth->username, username, sizeof(auth->username));
24203 if (secret)
24204 ast_copy_string(auth->secret, secret, sizeof(auth->secret));
24205 if (md5secret)
24206 ast_copy_string(auth->md5secret, md5secret, sizeof(auth->md5secret));
24207
24208
24209 for (b = NULL, a = authlist; a ; b = a, a = a->next)
24210 ;
24211 if (b)
24212 b->next = auth;
24213 else
24214 authlist = auth;
24215
24216 ast_verb(3, "Added authentication for realm %s\n", realm);
24217
24218 return authlist;
24219
24220 }
24221
24222
24223 static int clear_realm_authentication(struct sip_auth *authlist)
24224 {
24225 struct sip_auth *a = authlist;
24226 struct sip_auth *b;
24227
24228 while (a) {
24229 b = a;
24230 a = a->next;
24231 ast_free(b);
24232 }
24233
24234 return 1;
24235 }
24236
24237
24238 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm)
24239 {
24240 struct sip_auth *a;
24241
24242 for (a = authlist; a; a = a->next) {
24243 if (!strcasecmp(a->realm, realm))
24244 break;
24245 }
24246
24247 return a;
24248 }
24249
24250
24251
24252
24253 static struct ast_variable *add_var(const char *buf, struct ast_variable *list)
24254 {
24255 struct ast_variable *tmpvar = NULL;
24256 char *varname = ast_strdupa(buf), *varval = NULL;
24257
24258 if ((varval = strchr(varname, '='))) {
24259 *varval++ = '\0';
24260 if ((tmpvar = ast_variable_new(varname, varval, ""))) {
24261 tmpvar->next = list;
24262 list = tmpvar;
24263 }
24264 }
24265 return list;
24266 }
24267
24268
24269 static void set_peer_defaults(struct sip_peer *peer)
24270 {
24271 if (peer->expire == 0) {
24272
24273
24274
24275 peer->expire = -1;
24276 peer->pokeexpire = -1;
24277 peer->addr.sin_port = htons(STANDARD_SIP_PORT);
24278 set_socket_transport(&peer->socket, SIP_TRANSPORT_UDP);
24279 }
24280 peer->type = SIP_TYPE_PEER;
24281 ast_copy_flags(&peer->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
24282 ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
24283 ast_string_field_set(peer, context, sip_cfg.default_context);
24284 ast_string_field_set(peer, subscribecontext, sip_cfg.default_subscribecontext);
24285 ast_string_field_set(peer, language, default_language);
24286 ast_string_field_set(peer, mohinterpret, default_mohinterpret);
24287 ast_string_field_set(peer, mohsuggest, default_mohsuggest);
24288 peer->addr.sin_family = AF_INET;
24289 peer->defaddr.sin_family = AF_INET;
24290 peer->capability = global_capability;
24291 peer->maxcallbitrate = default_maxcallbitrate;
24292 peer->rtptimeout = global_rtptimeout;
24293 peer->rtpholdtimeout = global_rtpholdtimeout;
24294 peer->rtpkeepalive = global_rtpkeepalive;
24295 peer->allowtransfer = sip_cfg.allowtransfer;
24296 peer->autoframing = global_autoframing;
24297 peer->t38_maxdatagram = global_t38_maxdatagram;
24298 peer->qualifyfreq = global_qualifyfreq;
24299 if (global_callcounter)
24300 peer->call_limit=INT_MAX;
24301 ast_string_field_set(peer, vmexten, default_vmexten);
24302 ast_string_field_set(peer, secret, "");
24303 ast_string_field_set(peer, remotesecret, "");
24304 ast_string_field_set(peer, md5secret, "");
24305 ast_string_field_set(peer, cid_num, "");
24306 ast_string_field_set(peer, cid_name, "");
24307 ast_string_field_set(peer, fromdomain, "");
24308 ast_string_field_set(peer, fromuser, "");
24309 ast_string_field_set(peer, regexten, "");
24310 peer->callgroup = 0;
24311 peer->pickupgroup = 0;
24312 peer->maxms = default_qualify;
24313 peer->prefs = default_prefs;
24314 peer->stimer.st_mode_oper = global_st_mode;
24315 peer->stimer.st_ref = global_st_refresher;
24316 peer->stimer.st_min_se = global_min_se;
24317 peer->stimer.st_max_se = global_max_se;
24318 peer->timer_t1 = global_t1;
24319 peer->timer_b = global_timer_b;
24320 clear_peer_mailboxes(peer);
24321 peer->transports = default_transports;
24322 peer->default_outbound_transport = default_primary_transport;
24323 }
24324
24325
24326 static struct sip_peer *temp_peer(const char *name)
24327 {
24328 struct sip_peer *peer;
24329
24330 if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct")))
24331 return NULL;
24332
24333 if (ast_string_field_init(peer, 512)) {
24334 ao2_t_ref(peer, -1, "failed to string_field_init, drop peer");
24335 return NULL;
24336 }
24337
24338 ast_atomic_fetchadd_int(&apeerobjs, 1);
24339 set_peer_defaults(peer);
24340
24341 ast_copy_string(peer->name, name, sizeof(peer->name));
24342
24343 peer->selfdestruct = TRUE;
24344 peer->host_dynamic = TRUE;
24345 peer->prefs = default_prefs;
24346 reg_source_db(peer);
24347
24348 return peer;
24349 }
24350
24351
24352 static void add_peer_mailboxes(struct sip_peer *peer, const char *value)
24353 {
24354 char *next, *mbox, *context;
24355
24356 next = ast_strdupa(value);
24357
24358 while ((mbox = context = strsep(&next, ","))) {
24359 struct sip_mailbox *mailbox;
24360 int duplicate = 0;
24361
24362 strsep(&context, "@");
24363
24364 if (ast_strlen_zero(mbox)) {
24365 continue;
24366 }
24367
24368
24369 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
24370 if (!strcmp(mailbox->mailbox, mbox) && !strcmp(S_OR(mailbox->context, ""), S_OR(context, ""))) {
24371 duplicate = 1;
24372 mailbox->delme = 1;
24373 break;
24374 }
24375 }
24376 if (duplicate) {
24377 continue;
24378 }
24379
24380 if (!(mailbox = ast_calloc(1, sizeof(*mailbox)))) {
24381 continue;
24382 }
24383
24384 mailbox->mailbox = ast_strdup(mbox);
24385 mailbox->context = ast_strdup(context);
24386
24387 AST_LIST_INSERT_TAIL(&peer->mailboxes, mailbox, entry);
24388 }
24389 }
24390
24391
24392 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only)
24393 {
24394 struct sip_peer *peer = NULL;
24395 struct ast_ha *oldha = NULL;
24396 int found = 0;
24397 int firstpass = 1;
24398 uint16_t port = 0;
24399 int format = 0;
24400 time_t regseconds = 0;
24401 struct ast_flags peerflags[2] = {{(0)}};
24402 struct ast_flags mask[2] = {{(0)}};
24403 char callback[256] = "";
24404 struct sip_peer tmp_peer;
24405 const char *srvlookup = NULL;
24406 static int deprecation_warning = 1;
24407 int alt_fullcontact = alt ? 1 : 0;
24408 struct ast_str *fullcontact = ast_str_alloca(512);
24409
24410 if (!realtime || ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
24411
24412
24413
24414
24415
24416 ast_copy_string(tmp_peer.name, name, sizeof(tmp_peer.name));
24417 peer = ao2_t_find(peers, &tmp_peer, OBJ_POINTER | OBJ_UNLINK, "find and unlink peer from peers table");
24418 }
24419
24420 if (peer) {
24421
24422 found++;
24423 if (!(peer->the_mark))
24424 firstpass = 0;
24425 } else {
24426 if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct")))
24427 return NULL;
24428
24429 if (ast_string_field_init(peer, 512)) {
24430 ao2_t_ref(peer, -1, "failed to string_field_init, drop peer");
24431 return NULL;
24432 }
24433
24434 if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
24435 ast_atomic_fetchadd_int(&rpeerobjs, 1);
24436 ast_debug(3, "-REALTIME- peer built. Name: %s. Peer objects: %d\n", name, rpeerobjs);
24437 } else
24438 ast_atomic_fetchadd_int(&speerobjs, 1);
24439 }
24440
24441
24442 if (firstpass) {
24443 peer->lastmsgssent = -1;
24444 oldha = peer->ha;
24445 peer->ha = NULL;
24446 set_peer_defaults(peer);
24447 peer->type = 0;
24448 }
24449 if (!found && name)
24450 ast_copy_string(peer->name, name, sizeof(peer->name));
24451
24452
24453 if (peer->chanvars) {
24454 ast_variables_destroy(peer->chanvars);
24455 peer->chanvars = NULL;
24456
24457 }
24458
24459 if (found)
24460 peer->portinuri = 0;
24461
24462
24463 clear_realm_authentication(peer->auth);
24464 peer->auth = NULL;
24465
24466 peer->default_outbound_transport = 0;
24467 peer->transports = 0;
24468
24469 if (!devstate_only) {
24470 struct sip_mailbox *mailbox;
24471 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
24472 mailbox->delme = 1;
24473 }
24474 }
24475
24476 for (; v || ((v = alt) && !(alt=NULL)); v = v->next) {
24477 if (!devstate_only) {
24478 if (handle_common_options(&peerflags[0], &mask[0], v)) {
24479 continue;
24480 }
24481 if (handle_t38_options(&peerflags[0], &mask[0], v, &peer->t38_maxdatagram)) {
24482 continue;
24483 }
24484 if (!strcasecmp(v->name, "transport") && !ast_strlen_zero(v->value)) {
24485 char *val = ast_strdupa(v->value);
24486 char *trans;
24487
24488 while ((trans = strsep(&val, ","))) {
24489 trans = ast_skip_blanks(trans);
24490
24491 if (!strncasecmp(trans, "udp", 3)) {
24492 peer->transports |= SIP_TRANSPORT_UDP;
24493 } else if (!strncasecmp(trans, "tcp", 3)) {
24494 peer->transports |= SIP_TRANSPORT_TCP;
24495 } else if (!strncasecmp(trans, "tls", 3)) {
24496 peer->transports |= SIP_TRANSPORT_TLS;
24497 } else {
24498 ast_log(LOG_NOTICE, "'%s' is not a valid transport type. if no other is specified, udp will be used.\n", trans);
24499 }
24500
24501 if (!peer->default_outbound_transport) {
24502 peer->default_outbound_transport = peer->transports;
24503 }
24504 }
24505 } else if (realtime && !strcasecmp(v->name, "regseconds")) {
24506 ast_get_time_t(v->value, ®seconds, 0, NULL);
24507 } else if (realtime && !strcasecmp(v->name, "name")) {
24508 ast_copy_string(peer->name, v->value, sizeof(peer->name));
24509 } else if (realtime && !strcasecmp(v->name, "useragent")) {
24510 ast_string_field_set(peer, useragent, v->value);
24511 } else if (!strcasecmp(v->name, "type")) {
24512 if (!strcasecmp(v->value, "peer")) {
24513 peer->type |= SIP_TYPE_PEER;
24514 } else if (!strcasecmp(v->value, "user")) {
24515 peer->type |= SIP_TYPE_USER;
24516 } else if (!strcasecmp(v->value, "friend")) {
24517 peer->type = SIP_TYPE_USER | SIP_TYPE_PEER;
24518 }
24519 } else if (!strcasecmp(v->name, "remotesecret")) {
24520 ast_string_field_set(peer, remotesecret, v->value);
24521 } else if (!strcasecmp(v->name, "secret")) {
24522 ast_string_field_set(peer, secret, v->value);
24523 } else if (!strcasecmp(v->name, "md5secret")) {
24524 ast_string_field_set(peer, md5secret, v->value);
24525 } else if (!strcasecmp(v->name, "auth")) {
24526 peer->auth = add_realm_authentication(peer->auth, v->value, v->lineno);
24527 } else if (!strcasecmp(v->name, "callerid")) {
24528 char cid_name[80] = { '\0' }, cid_num[80] = { '\0' };
24529
24530 ast_callerid_split(v->value, cid_name, sizeof(cid_name), cid_num, sizeof(cid_num));
24531 ast_string_field_set(peer, cid_name, cid_name);
24532 ast_string_field_set(peer, cid_num, cid_num);
24533 } else if (!strcasecmp(v->name, "fullname")) {
24534 ast_string_field_set(peer, cid_name, v->value);
24535 } else if (!strcasecmp(v->name, "trunkname")) {
24536
24537 ast_string_field_set(peer, cid_name, "");
24538 } else if (!strcasecmp(v->name, "cid_number")) {
24539 ast_string_field_set(peer, cid_num, v->value);
24540 } else if (!strcasecmp(v->name, "context")) {
24541 ast_string_field_set(peer, context, v->value);
24542 ast_set_flag(&peer->flags[1], SIP_PAGE2_HAVEPEERCONTEXT);
24543 } else if (!strcasecmp(v->name, "subscribecontext")) {
24544 ast_string_field_set(peer, subscribecontext, v->value);
24545 } else if (!strcasecmp(v->name, "fromdomain")) {
24546 ast_string_field_set(peer, fromdomain, v->value);
24547 } else if (!strcasecmp(v->name, "usereqphone")) {
24548 ast_set2_flag(&peer->flags[0], ast_true(v->value), SIP_USEREQPHONE);
24549 } else if (!strcasecmp(v->name, "fromuser")) {
24550 ast_string_field_set(peer, fromuser, v->value);
24551 } else if (!strcasecmp(v->name, "outboundproxy")) {
24552 char *port, *next, *force, *proxyname;
24553 int forceopt = FALSE;
24554
24555 next = proxyname = ast_strdupa(v->value);
24556 if ((port = strchr(proxyname, ':'))) {
24557 *port++ = '\0';
24558 next = port;
24559 }
24560 if ((force = strchr(next, ','))) {
24561 *force++ = '\0';
24562 forceopt = strcmp(force, "force");
24563 }
24564
24565 peer->outboundproxy = proxy_allocate(proxyname, port, forceopt);
24566 } else if (!strcasecmp(v->name, "host")) {
24567 if (!strcasecmp(v->value, "dynamic")) {
24568
24569 if (!found || !peer->host_dynamic) {
24570
24571
24572 memset(&peer->addr.sin_addr, 0, 4);
24573 peer->addr.sin_port = 0;
24574 }
24575 peer->host_dynamic = TRUE;
24576 } else {
24577
24578 AST_SCHED_DEL_UNREF(sched, peer->expire,
24579 unref_peer(peer, "removing register expire ref"));
24580
24581 peer->addr.sin_port = 0;
24582 peer->host_dynamic = FALSE;
24583 srvlookup = v->value;
24584 }
24585 } else if (!strcasecmp(v->name, "defaultip")) {
24586 if (!ast_strlen_zero(v->value) && ast_get_ip(&peer->defaddr, v->value)) {
24587 unref_peer(peer, "unref_peer: from build_peer defaultip");
24588 return NULL;
24589 }
24590 } else if (!strcasecmp(v->name, "permit") || !strcasecmp(v->name, "deny")) {
24591 int ha_error = 0;
24592 if (!ast_strlen_zero(v->value)) {
24593 peer->ha = ast_append_ha(v->name, v->value, peer->ha, &ha_error);
24594 }
24595 if (ha_error) {
24596 ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
24597 }
24598 } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny")) {
24599 int ha_error = 0;
24600 if (!ast_strlen_zero(v->value)) {
24601 peer->contactha = ast_append_ha(v->name + 7, v->value, peer->contactha, &ha_error);
24602 }
24603 if (ha_error) {
24604 ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
24605 }
24606 } else if (!strcasecmp(v->name, "port")) {
24607 peer->portinuri = 1;
24608 if (!(port = port_str2int(v->value, 0))) {
24609 if (realtime) {
24610
24611 peer->portinuri = 0;
24612 } else {
24613 ast_log(LOG_WARNING, "Invalid peer port configuration at line %d : %s\n", v->lineno, v->value);
24614 }
24615 }
24616 } else if (!strcasecmp(v->name, "callingpres")) {
24617 peer->callingpres = ast_parse_caller_presentation(v->value);
24618 if (peer->callingpres == -1) {
24619 peer->callingpres = atoi(v->value);
24620 }
24621 } else if (!strcasecmp(v->name, "username") || !strcmp(v->name, "defaultuser")) {
24622 ast_string_field_set(peer, username, v->value);
24623 if (!strcasecmp(v->name, "username")) {
24624 if (deprecation_warning) {
24625 ast_log(LOG_NOTICE, "The 'username' field for sip peers has been deprecated in favor of the term 'defaultuser'\n");
24626 deprecation_warning = 0;
24627 }
24628 peer->deprecated_username = 1;
24629 }
24630 } else if (!strcasecmp(v->name, "language")) {
24631 ast_string_field_set(peer, language, v->value);
24632 } else if (!strcasecmp(v->name, "regexten")) {
24633 ast_string_field_set(peer, regexten, v->value);
24634 } else if (!strcasecmp(v->name, "callbackextension")) {
24635 ast_copy_string(callback, v->value, sizeof(callback));
24636 } else if (!strcasecmp(v->name, "amaflags")) {
24637 format = ast_cdr_amaflags2int(v->value);
24638 if (format < 0) {
24639 ast_log(LOG_WARNING, "Invalid AMA Flags for peer: %s at line %d\n", v->value, v->lineno);
24640 } else {
24641 peer->amaflags = format;
24642 }
24643 } else if (!strcasecmp(v->name, "accountcode")) {
24644 ast_string_field_set(peer, accountcode, v->value);
24645 } else if (!strcasecmp(v->name, "mohinterpret")) {
24646 ast_string_field_set(peer, mohinterpret, v->value);
24647 } else if (!strcasecmp(v->name, "mohsuggest")) {
24648 ast_string_field_set(peer, mohsuggest, v->value);
24649 } else if (!strcasecmp(v->name, "parkinglot")) {
24650 ast_string_field_set(peer, parkinglot, v->value);
24651 } else if (!strcasecmp(v->name, "mailbox")) {
24652 add_peer_mailboxes(peer, v->value);
24653 } else if (!strcasecmp(v->name, "hasvoicemail")) {
24654
24655
24656 if (ast_true(v->value) && AST_LIST_EMPTY(&peer->mailboxes)) {
24657 add_peer_mailboxes(peer, name);
24658 }
24659 } else if (!strcasecmp(v->name, "subscribemwi")) {
24660 ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_SUBSCRIBEMWIONLY);
24661 } else if (!strcasecmp(v->name, "vmexten")) {
24662 ast_string_field_set(peer, vmexten, v->value);
24663 } else if (!strcasecmp(v->name, "callgroup")) {
24664 peer->callgroup = ast_get_group(v->value);
24665 } else if (!strcasecmp(v->name, "allowtransfer")) {
24666 peer->allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
24667 } else if (!strcasecmp(v->name, "pickupgroup")) {
24668 peer->pickupgroup = ast_get_group(v->value);
24669 } else if (!strcasecmp(v->name, "allow")) {
24670 int error = ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, TRUE);
24671 if (error) {
24672 ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
24673 }
24674 } else if (!strcasecmp(v->name, "disallow")) {
24675 int error = ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, FALSE);
24676 if (error) {
24677 ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
24678 }
24679 } else if (!strcasecmp(v->name, "registertrying")) {
24680 ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_REGISTERTRYING);
24681 } else if (!strcasecmp(v->name, "autoframing")) {
24682 peer->autoframing = ast_true(v->value);
24683 } else if (!strcasecmp(v->name, "rtptimeout")) {
24684 if ((sscanf(v->value, "%30d", &peer->rtptimeout) != 1) || (peer->rtptimeout < 0)) {
24685 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
24686 peer->rtptimeout = global_rtptimeout;
24687 }
24688 } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
24689 if ((sscanf(v->value, "%30d", &peer->rtpholdtimeout) != 1) || (peer->rtpholdtimeout < 0)) {
24690 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
24691 peer->rtpholdtimeout = global_rtpholdtimeout;
24692 }
24693 } else if (!strcasecmp(v->name, "rtpkeepalive")) {
24694 if ((sscanf(v->value, "%30d", &peer->rtpkeepalive) != 1) || (peer->rtpkeepalive < 0)) {
24695 ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d. Using default.\n", v->value, v->lineno);
24696 peer->rtpkeepalive = global_rtpkeepalive;
24697 }
24698 } else if (!strcasecmp(v->name, "timert1")) {
24699 if ((sscanf(v->value, "%30d", &peer->timer_t1) != 1) || (peer->timer_t1 < 0)) {
24700 ast_log(LOG_WARNING, "'%s' is not a valid T1 time at line %d. Using default.\n", v->value, v->lineno);
24701 peer->timer_t1 = global_t1;
24702 }
24703
24704
24705 if (peer->timer_b < peer->timer_t1 * 64) {
24706 peer->timer_b = peer->timer_t1 * 64;
24707 }
24708 } else if (!strcasecmp(v->name, "timerb")) {
24709 if ((sscanf(v->value, "%30d", &peer->timer_b) != 1) || (peer->timer_b < 0)) {
24710 ast_log(LOG_WARNING, "'%s' is not a valid Timer B time at line %d. Using default.\n", v->value, v->lineno);
24711 peer->timer_b = global_timer_b;
24712 }
24713 if (peer->timer_b < peer->timer_t1 * 64) {
24714 static int warning = 0;
24715 if (warning++ % 20 == 0) {
24716 ast_log(LOG_WARNING, "Timer B has been set lower than recommended. (RFC 3261, 17.1.1.2)\n");
24717 }
24718 }
24719 } else if (!strcasecmp(v->name, "setvar")) {
24720 peer->chanvars = add_var(v->value, peer->chanvars);
24721 } else if (!strcasecmp(v->name, "qualifyfreq")) {
24722 int i;
24723 if (sscanf(v->value, "%30d", &i) == 1) {
24724 peer->qualifyfreq = i * 1000;
24725 } else {
24726 ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
24727 peer->qualifyfreq = global_qualifyfreq;
24728 }
24729 } else if (!strcasecmp(v->name, "maxcallbitrate")) {
24730 peer->maxcallbitrate = atoi(v->value);
24731 if (peer->maxcallbitrate < 0) {
24732 peer->maxcallbitrate = default_maxcallbitrate;
24733 }
24734 } else if (!strcasecmp(v->name, "session-timers")) {
24735 int i = (int) str2stmode(v->value);
24736 if (i < 0) {
24737 ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
24738 peer->stimer.st_mode_oper = global_st_mode;
24739 } else {
24740 peer->stimer.st_mode_oper = i;
24741 }
24742 } else if (!strcasecmp(v->name, "session-expires")) {
24743 if (sscanf(v->value, "%30d", &peer->stimer.st_max_se) != 1) {
24744 ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
24745 peer->stimer.st_max_se = global_max_se;
24746 }
24747 } else if (!strcasecmp(v->name, "session-minse")) {
24748 if (sscanf(v->value, "%30d", &peer->stimer.st_min_se) != 1) {
24749 ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
24750 peer->stimer.st_min_se = global_min_se;
24751 }
24752 if (peer->stimer.st_min_se < 90) {
24753 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);
24754 peer->stimer.st_min_se = global_min_se;
24755 }
24756 } else if (!strcasecmp(v->name, "session-refresher")) {
24757 int i = (int) str2strefresher(v->value);
24758 if (i < 0) {
24759 ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
24760 peer->stimer.st_ref = global_st_refresher;
24761 } else {
24762 peer->stimer.st_ref = i;
24763 }
24764 }
24765 }
24766
24767
24768 if (realtime && !strcasecmp(v->name, "lastms")) {
24769 sscanf(v->value, "%30d", &peer->lastms);
24770 } else if (realtime && !strcasecmp(v->name, "ipaddr") && !ast_strlen_zero(v->value) ) {
24771 inet_aton(v->value, &(peer->addr.sin_addr));
24772 } else if (realtime && !strcasecmp(v->name, "fullcontact")) {
24773 if (alt_fullcontact && !alt) {
24774
24775
24776
24777
24778
24779 alt_fullcontact = 0;
24780 ast_str_reset(fullcontact);
24781 }
24782
24783 if (fullcontact->used > 0) {
24784 ast_str_append(&fullcontact, 0, ";%s", v->value);
24785 } else {
24786 ast_str_set(&fullcontact, 0, "%s", v->value);
24787 }
24788 } else if (!strcasecmp(v->name, "qualify")) {
24789 if (!strcasecmp(v->value, "no")) {
24790 peer->maxms = 0;
24791 } else if (!strcasecmp(v->value, "yes")) {
24792 peer->maxms = default_qualify ? default_qualify : DEFAULT_MAXMS;
24793 } else if (sscanf(v->value, "%30d", &peer->maxms) != 1) {
24794 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);
24795 peer->maxms = 0;
24796 }
24797 if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && peer->maxms > 0) {
24798
24799
24800
24801
24802 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);
24803 peer->maxms = 0;
24804 }
24805 } else if (!strcasecmp(v->name, "callcounter")) {
24806 peer->call_limit = ast_true(v->value) ? INT_MAX : 0;
24807 } else if (!strcasecmp(v->name, "call-limit")) {
24808 peer->call_limit = atoi(v->value);
24809 if (peer->call_limit < 0) {
24810 peer->call_limit = 0;
24811 }
24812 } else if (!strcasecmp(v->name, "busylevel")) {
24813 peer->busy_level = atoi(v->value);
24814 if (peer->busy_level < 0) {
24815 peer->busy_level = 0;
24816 }
24817 }
24818 }
24819
24820 if (!devstate_only) {
24821 struct sip_mailbox *mailbox;
24822 AST_LIST_TRAVERSE_SAFE_BEGIN(&peer->mailboxes, mailbox, entry) {
24823 if (mailbox->delme) {
24824 AST_LIST_REMOVE_CURRENT(entry);
24825 destroy_mailbox(mailbox);
24826 }
24827 }
24828 AST_LIST_TRAVERSE_SAFE_END;
24829 }
24830
24831 if (!peer->default_outbound_transport) {
24832
24833 peer->transports = default_transports;
24834
24835 peer->default_outbound_transport = default_primary_transport;
24836 }
24837
24838
24839
24840
24841
24842 if (((peer->socket.type != peer->default_outbound_transport) && (peer->expire == -1)) ||
24843 !(peer->socket.type & peer->transports) || !(peer->socket.type)) {
24844
24845 set_socket_transport(&peer->socket, peer->default_outbound_transport);
24846 }
24847
24848 if (port && !realtime && peer->host_dynamic) {
24849 peer->defaddr.sin_port = htons(port);
24850 } else if (port) {
24851 peer->addr.sin_port = htons(port);
24852 }
24853
24854 if (ast_str_strlen(fullcontact)) {
24855 ast_string_field_set(peer, fullcontact, ast_str_buffer(fullcontact));
24856 peer->rt_fromcontact = TRUE;
24857
24858
24859
24860
24861
24862
24863
24864
24865 if (!ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) || !peer->addr.sin_addr.s_addr) {
24866 __set_address_from_contact(fullcontact->str, &peer->addr, 0);
24867 }
24868 }
24869
24870 if (srvlookup && peer->dnsmgr == NULL) {
24871 char transport[MAXHOSTNAMELEN];
24872 char _srvlookup[MAXHOSTNAMELEN];
24873 char *params;
24874
24875 ast_copy_string(_srvlookup, srvlookup, sizeof(_srvlookup));
24876 if ((params = strchr(_srvlookup, ';'))) {
24877 *params++ = '\0';
24878 }
24879
24880 snprintf(transport, sizeof(transport), "_%s._%s", get_srv_service(peer->socket.type), get_srv_protocol(peer->socket.type));
24881
24882 if (ast_dnsmgr_lookup(_srvlookup, &peer->addr, &peer->dnsmgr, sip_cfg.srvlookup && !peer->portinuri ? transport : NULL)) {
24883 ast_log(LOG_ERROR, "srvlookup failed for host: %s, on peer %s, removing peer\n", _srvlookup, peer->name);
24884 unref_peer(peer, "getting rid of a peer pointer");
24885 return NULL;
24886 }
24887
24888 ast_string_field_set(peer, tohost, srvlookup);
24889 if (global_dynamic_exclude_static) {
24890 int err = 0;
24891 global_contact_ha = ast_append_ha("deny", (char *)ast_inet_ntoa(peer->addr.sin_addr), global_contact_ha, &err);
24892 if (err) {
24893 ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
24894 }
24895 }
24896 }
24897
24898 if (!peer->addr.sin_port) {
24899 peer->addr.sin_port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
24900 }
24901 if (!peer->defaddr.sin_port) {
24902 peer->defaddr.sin_port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
24903 }
24904 if (!peer->socket.port) {
24905 peer->socket.port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
24906 }
24907
24908 if (!sip_cfg.ignore_regexpire && peer->host_dynamic && realtime) {
24909 time_t nowtime = time(NULL);
24910
24911 if ((nowtime - regseconds) > 0) {
24912 destroy_association(peer);
24913 memset(&peer->addr, 0, sizeof(peer->addr));
24914 peer->lastms = -1;
24915 ast_debug(1, "Bah, we're expired (%d/%d/%d)!\n", (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
24916 }
24917 }
24918
24919
24920 if (!devstate_only && realtime && peer->lastms > 0) {
24921 ref_peer(peer, "schedule qualify");
24922 sip_poke_peer(peer, 0);
24923 }
24924
24925 ast_copy_flags(&peer->flags[0], &peerflags[0], mask[0].flags);
24926 ast_copy_flags(&peer->flags[1], &peerflags[1], mask[1].flags);
24927 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
24928 sip_cfg.allowsubscribe = TRUE;
24929 }
24930 if (peer->host_dynamic && !peer->is_realtime) {
24931 reg_source_db(peer);
24932 }
24933
24934
24935
24936 if (!devstate_only && !ast_test_flag(&peer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY) &&
24937 !AST_LIST_EMPTY(&peer->mailboxes)) {
24938 add_peer_mwi_subs(peer);
24939
24940
24941
24942 sip_send_mwi_to_peer(peer, NULL, 1);
24943 }
24944
24945 peer->the_mark = 0;
24946
24947 ast_free_ha(oldha);
24948 if (!ast_strlen_zero(callback)) {
24949 char *reg_string;
24950 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) {
24951 ast_log(LOG_WARNING, "asprintf() failed: %s\n", strerror(errno));
24952 } else if (reg_string) {
24953 sip_register(reg_string, 0);
24954 ast_free(reg_string);
24955 }
24956 }
24957 return peer;
24958 }
24959
24960 static int peer_markall_func(void *device, void *arg, int flags)
24961 {
24962 struct sip_peer *peer = device;
24963 peer->the_mark = 1;
24964 return 0;
24965 }
24966
24967
24968
24969
24970
24971
24972
24973 static int reload_config(enum channelreloadreason reason)
24974 {
24975 struct ast_config *cfg, *ucfg;
24976 struct ast_variable *v;
24977 struct sip_peer *peer;
24978 char *cat, *stringp, *context, *oldregcontext;
24979 char newcontexts[AST_MAX_CONTEXT], oldcontexts[AST_MAX_CONTEXT];
24980 struct ast_flags dummy[2];
24981 struct ast_flags config_flags = { reason == CHANNEL_MODULE_LOAD ? 0 : ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) ? 0 : CONFIG_FLAG_FILEUNCHANGED };
24982 int auto_sip_domains = FALSE;
24983 struct sockaddr_in old_bindaddr = bindaddr;
24984 int registry_count = 0, peer_count = 0;
24985 time_t run_start, run_end;
24986
24987 run_start = time(0);
24988 ast_unload_realtime("sipregs");
24989 ast_unload_realtime("sippeers");
24990 cfg = ast_config_load(config, config_flags);
24991
24992
24993 if (!cfg) {
24994 ast_log(LOG_NOTICE, "Unable to load config %s\n", config);
24995 return -1;
24996 } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
24997 ucfg = ast_config_load("users.conf", config_flags);
24998 if (ucfg == CONFIG_STATUS_FILEUNCHANGED) {
24999 return 1;
25000 } else if (ucfg == CONFIG_STATUS_FILEINVALID) {
25001 ast_log(LOG_ERROR, "Contents of users.conf are invalid and cannot be parsed\n");
25002 return 1;
25003 }
25004
25005 ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
25006 if ((cfg = ast_config_load(config, config_flags)) == CONFIG_STATUS_FILEINVALID) {
25007 ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed\n", config);
25008 ast_config_destroy(ucfg);
25009 return 1;
25010 }
25011 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
25012 ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed\n", config);
25013 return 1;
25014 } else {
25015 ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
25016 if ((ucfg = ast_config_load("users.conf", config_flags)) == CONFIG_STATUS_FILEINVALID) {
25017 ast_log(LOG_ERROR, "Contents of users.conf are invalid and cannot be parsed\n");
25018 ast_config_destroy(cfg);
25019 return 1;
25020 }
25021 }
25022
25023
25024 memset(&sip_tcp_desc.local_address, 0, sizeof(sip_tcp_desc.local_address));
25025 memset(&sip_tls_desc.local_address, 0, sizeof(sip_tls_desc.local_address));
25026
25027 ast_free_ha(global_contact_ha);
25028 global_contact_ha = NULL;
25029
25030 default_tls_cfg.enabled = FALSE;
25031
25032 sip_tcp_desc.local_address.sin_port = htons(STANDARD_SIP_PORT);
25033 sip_tls_desc.local_address.sin_port = htons(STANDARD_TLS_PORT);
25034
25035 if (reason != CHANNEL_MODULE_LOAD) {
25036 ast_debug(4, "--------------- SIP reload started\n");
25037
25038 clear_realm_authentication(authl);
25039 clear_sip_domains();
25040 authl = NULL;
25041
25042
25043
25044 ASTOBJ_CONTAINER_TRAVERSE(®l, 1, do {
25045
25046 ASTOBJ_RDLOCK(iterator);
25047 if (iterator->call) {
25048 ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", iterator->username, iterator->hostname);
25049
25050 dialog_unlink_all(iterator->call, TRUE, TRUE);
25051 iterator->call = dialog_unref(iterator->call, "remove iterator->call from registry traversal");
25052 }
25053 if (iterator->expire > -1) {
25054 AST_SCHED_DEL_UNREF(sched, iterator->expire, registry_unref(iterator, "reg ptr unref from reload config"));
25055 }
25056 if (iterator->timeout > -1) {
25057 AST_SCHED_DEL_UNREF(sched, iterator->timeout, registry_unref(iterator, "reg ptr unref from reload config"));
25058 }
25059 ASTOBJ_UNLOCK(iterator);
25060
25061 } while(0));
25062
25063
25064 ASTOBJ_CONTAINER_DESTROYALL(®l, sip_registry_destroy);
25065 ast_debug(4, "--------------- Done destroying registry list\n");
25066 ao2_t_callback(peers, OBJ_NODATA, peer_markall_func, NULL, "callback to mark all peers");
25067 }
25068
25069
25070 if (reason != CHANNEL_MODULE_LOAD) {
25071 ast_free(default_tls_cfg.certfile);
25072 ast_free(default_tls_cfg.cipher);
25073 ast_free(default_tls_cfg.cafile);
25074 ast_free(default_tls_cfg.capath);
25075 }
25076 default_tls_cfg.certfile = ast_strdup(AST_CERTFILE);
25077 default_tls_cfg.cipher = ast_strdup("");
25078 default_tls_cfg.cafile = ast_strdup("");
25079 default_tls_cfg.capath = ast_strdup("");
25080
25081
25082
25083 ast_copy_string(oldcontexts, global_regcontext, sizeof(oldcontexts));
25084 oldregcontext = oldcontexts;
25085
25086
25087
25088 sipdebug &= sip_debug_console;
25089 ast_clear_flag(&global_flags[0], AST_FLAGS_ALL);
25090 ast_clear_flag(&global_flags[1], AST_FLAGS_ALL);
25091
25092
25093 memset(&bindaddr, 0, sizeof(bindaddr));
25094 memset(&stunaddr, 0, sizeof(stunaddr));
25095 memset(&internip, 0, sizeof(internip));
25096
25097
25098 ast_free_ha(localaddr);
25099 memset(&localaddr, 0, sizeof(localaddr));
25100 memset(&externip, 0, sizeof(externip));
25101 memset(&default_prefs, 0 , sizeof(default_prefs));
25102 memset(&sip_cfg.outboundproxy, 0, sizeof(struct sip_proxy));
25103 sip_cfg.outboundproxy.ip.sin_port = htons(STANDARD_SIP_PORT);
25104 sip_cfg.outboundproxy.ip.sin_family = AF_INET;
25105 sip_cfg.outboundproxy.force = FALSE;
25106 default_transports = 0;
25107 default_primary_transport = 0;
25108 ourport_tcp = STANDARD_SIP_PORT;
25109 ourport_tls = STANDARD_TLS_PORT;
25110 bindaddr.sin_port = htons(STANDARD_SIP_PORT);
25111 sip_cfg.srvlookup = DEFAULT_SRVLOOKUP;
25112 global_tos_sip = DEFAULT_TOS_SIP;
25113 global_tos_audio = DEFAULT_TOS_AUDIO;
25114 global_tos_video = DEFAULT_TOS_VIDEO;
25115 global_tos_text = DEFAULT_TOS_TEXT;
25116 global_cos_sip = DEFAULT_COS_SIP;
25117 global_cos_audio = DEFAULT_COS_AUDIO;
25118 global_cos_video = DEFAULT_COS_VIDEO;
25119 global_cos_text = DEFAULT_COS_TEXT;
25120
25121 externhost[0] = '\0';
25122 externexpire = 0;
25123 externrefresh = 10;
25124
25125
25126 sip_cfg.allow_external_domains = DEFAULT_ALLOW_EXT_DOM;
25127 global_regcontext[0] = '\0';
25128 sip_cfg.regextenonqualify = DEFAULT_REGEXTENONQUALIFY;
25129 sip_cfg.notifyringing = DEFAULT_NOTIFYRINGING;
25130 sip_cfg.notifycid = DEFAULT_NOTIFYCID;
25131 sip_cfg.notifyhold = FALSE;
25132 sip_cfg.directrtpsetup = FALSE;
25133 sip_cfg.alwaysauthreject = DEFAULT_ALWAYSAUTHREJECT;
25134 sip_cfg.allowsubscribe = FALSE;
25135 snprintf(global_useragent, sizeof(global_useragent), "%s %s", DEFAULT_USERAGENT, ast_get_version());
25136 snprintf(global_sdpsession, sizeof(global_sdpsession), "%s %s", DEFAULT_SDPSESSION, ast_get_version());
25137 snprintf(global_sdpowner, sizeof(global_sdpowner), "%s", DEFAULT_SDPOWNER);
25138 global_prematuremediafilter = TRUE;
25139 ast_copy_string(default_notifymime, DEFAULT_NOTIFYMIME, sizeof(default_notifymime));
25140 ast_copy_string(sip_cfg.realm, S_OR(ast_config_AST_SYSTEM_NAME, DEFAULT_REALM), sizeof(sip_cfg.realm));
25141 ast_copy_string(default_callerid, DEFAULT_CALLERID, sizeof(default_callerid));
25142 sip_cfg.compactheaders = DEFAULT_COMPACTHEADERS;
25143 global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
25144 global_regattempts_max = 0;
25145 sip_cfg.pedanticsipchecking = DEFAULT_PEDANTIC;
25146 sip_cfg.autocreatepeer = DEFAULT_AUTOCREATEPEER;
25147 global_autoframing = 0;
25148 sip_cfg.allowguest = DEFAULT_ALLOWGUEST;
25149 global_callcounter = DEFAULT_CALLCOUNTER;
25150 global_match_auth_username = FALSE;
25151 global_rtptimeout = 0;
25152 global_rtpholdtimeout = 0;
25153 global_rtpkeepalive = DEFAULT_RTPKEEPALIVE;
25154 sip_cfg.allowtransfer = TRANSFER_OPENFORALL;
25155 sip_cfg.rtautoclear = 120;
25156 ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE);
25157 ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP);
25158 sip_cfg.peer_rtupdate = TRUE;
25159 global_dynamic_exclude_static = 0;
25160
25161
25162 global_st_mode = SESSION_TIMER_MODE_ACCEPT;
25163 global_st_refresher = SESSION_TIMER_REFRESHER_UAS;
25164 global_min_se = DEFAULT_MIN_SE;
25165 global_max_se = DEFAULT_MAX_SE;
25166
25167
25168 global_qualify_gap = DEFAULT_QUALIFY_GAP;
25169 global_qualify_peers = DEFAULT_QUALIFY_PEERS;
25170
25171
25172 ast_copy_string(sip_cfg.default_context, DEFAULT_CONTEXT, sizeof(sip_cfg.default_context));
25173 sip_cfg.default_subscribecontext[0] = '\0';
25174 default_language[0] = '\0';
25175 default_fromdomain[0] = '\0';
25176 default_qualify = DEFAULT_QUALIFY;
25177 default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
25178 ast_copy_string(default_mohinterpret, DEFAULT_MOHINTERPRET, sizeof(default_mohinterpret));
25179 ast_copy_string(default_mohsuggest, DEFAULT_MOHSUGGEST, sizeof(default_mohsuggest));
25180 ast_copy_string(default_vmexten, DEFAULT_VMEXTEN, sizeof(default_vmexten));
25181 ast_set_flag(&global_flags[0], SIP_DTMF_RFC2833);
25182 ast_set_flag(&global_flags[0], SIP_NAT_RFC3581);
25183 ast_set_flag(&global_flags[0], SIP_DIRECT_MEDIA);
25184 ast_set_flag(&global_flags[1], SIP_PAGE2_FORWARD_LOOP_DETECTED);
25185
25186
25187 dumphistory = FALSE;
25188 recordhistory = FALSE;
25189 sipdebug &= ~sip_debug_config;
25190
25191
25192 global_relaxdtmf = FALSE;
25193 sip_cfg.callevents = DEFAULT_CALLEVENTS;
25194 global_authfailureevents = FALSE;
25195 global_t1 = DEFAULT_TIMER_T1;
25196 global_timer_b = 64 * DEFAULT_TIMER_T1;
25197 global_t1min = DEFAULT_T1MIN;
25198 global_qualifyfreq = DEFAULT_QUALIFYFREQ;
25199 global_t38_maxdatagram = -1;
25200 global_shrinkcallerid = 1;
25201 authlimit = DEFAULT_AUTHLIMIT;
25202 authtimeout = DEFAULT_AUTHTIMEOUT;
25203
25204 sip_cfg.matchexterniplocally = DEFAULT_MATCHEXTERNIPLOCALLY;
25205
25206
25207 memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
25208
25209 ast_clear_flag(&global_flags[1], SIP_PAGE2_FAX_DETECT);
25210 ast_clear_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT | SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
25211 ast_clear_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT);
25212 ast_clear_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION);
25213
25214
25215
25216 for (v = ast_variable_browse(cfg, "general"); v; v = v->next) {
25217 if (handle_common_options(&global_flags[0], &dummy[0], v))
25218 continue;
25219 if (handle_t38_options(&global_flags[0], &dummy[0], v, &global_t38_maxdatagram)) {
25220 continue;
25221 }
25222
25223 if (!ast_jb_read_conf(&global_jbconf, v->name, v->value))
25224 continue;
25225
25226 if (!strcasecmp(v->name, "context")) {
25227 ast_copy_string(sip_cfg.default_context, v->value, sizeof(sip_cfg.default_context));
25228 } else if (!strcasecmp(v->name, "subscribecontext")) {
25229 ast_copy_string(sip_cfg.default_subscribecontext, v->value, sizeof(sip_cfg.default_subscribecontext));
25230 } else if (!strcasecmp(v->name, "callcounter")) {
25231 global_callcounter = ast_true(v->value) ? 1 : 0;
25232 } else if (!strcasecmp(v->name, "allowguest")) {
25233 sip_cfg.allowguest = ast_true(v->value) ? 1 : 0;
25234 } else if (!strcasecmp(v->name, "realm")) {
25235 ast_copy_string(sip_cfg.realm, v->value, sizeof(sip_cfg.realm));
25236 } else if (!strcasecmp(v->name, "useragent")) {
25237 ast_copy_string(global_useragent, v->value, sizeof(global_useragent));
25238 ast_debug(1, "Setting SIP channel User-Agent Name to %s\n", global_useragent);
25239 } else if (!strcasecmp(v->name, "sdpsession")) {
25240 ast_copy_string(global_sdpsession, v->value, sizeof(global_sdpsession));
25241 } else if (!strcasecmp(v->name, "sdpowner")) {
25242
25243 if (!strstr(v->value, " "))
25244 ast_copy_string(global_sdpowner, v->value, sizeof(global_sdpowner));
25245 else
25246 ast_log(LOG_WARNING, "'%s' must not contain spaces at line %d. Using default.\n", v->value, v->lineno);
25247 } else if (!strcasecmp(v->name, "allowtransfer")) {
25248 sip_cfg.allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
25249 } else if (!strcasecmp(v->name, "rtcachefriends")) {
25250 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTCACHEFRIENDS);
25251 } else if (!strcasecmp(v->name, "rtsavesysname")) {
25252 sip_cfg.rtsave_sysname = ast_true(v->value);
25253 } else if (!strcasecmp(v->name, "rtupdate")) {
25254 sip_cfg.peer_rtupdate = ast_true(v->value);
25255 } else if (!strcasecmp(v->name, "ignoreregexpire")) {
25256 sip_cfg.ignore_regexpire = ast_true(v->value);
25257 } else if (!strcasecmp(v->name, "timert1")) {
25258
25259
25260
25261 global_t1 = atoi(v->value);
25262
25263 global_timer_b = global_t1 * 64;
25264 } else if (!strcasecmp(v->name, "t1min")) {
25265 global_t1min = atoi(v->value);
25266 } else if (!strcasecmp(v->name, "transport") && !ast_strlen_zero(v->value)) {
25267 char *val = ast_strdupa(v->value);
25268 char *trans;
25269
25270 while ((trans = strsep(&val, ","))) {
25271 trans = ast_skip_blanks(trans);
25272
25273 if (!strncasecmp(trans, "udp", 3))
25274 default_transports |= SIP_TRANSPORT_UDP;
25275 else if (!strncasecmp(trans, "tcp", 3))
25276 default_transports |= SIP_TRANSPORT_TCP;
25277 else if (!strncasecmp(trans, "tls", 3))
25278 default_transports |= SIP_TRANSPORT_TLS;
25279 else
25280 ast_log(LOG_NOTICE, "'%s' is not a valid transport type. if no other is specified, udp will be used.\n", trans);
25281 if (default_primary_transport == 0) {
25282 default_primary_transport = default_transports;
25283 }
25284 }
25285 } else if (!strcasecmp(v->name, "tcpenable")) {
25286 sip_tcp_desc.local_address.sin_family = ast_false(v->value) ? 0 : AF_INET;
25287 ast_debug(2, "Enabling TCP socket for listening\n");
25288 } else if (!strcasecmp(v->name, "tcpbindaddr")) {
25289 int family = sip_tcp_desc.local_address.sin_family;
25290 if (ast_parse_arg(v->value, PARSE_INADDR, &sip_tcp_desc.local_address))
25291 ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n", v->name, v->value, v->lineno, config);
25292 sip_tcp_desc.local_address.sin_family = family;
25293 ast_debug(2, "Setting TCP socket address to %s\n", v->value);
25294 } else if (!strcasecmp(v->name, "tlsenable")) {
25295 default_tls_cfg.enabled = ast_true(v->value) ? TRUE : FALSE;
25296 sip_tls_desc.local_address.sin_family = AF_INET;
25297 } else if (!strcasecmp(v->name, "tlscertfile")) {
25298 ast_free(default_tls_cfg.certfile);
25299 default_tls_cfg.certfile = ast_strdup(v->value);
25300 } else if (!strcasecmp(v->name, "tlscipher")) {
25301 ast_free(default_tls_cfg.cipher);
25302 default_tls_cfg.cipher = ast_strdup(v->value);
25303 } else if (!strcasecmp(v->name, "tlscafile")) {
25304 ast_free(default_tls_cfg.cafile);
25305 default_tls_cfg.cafile = ast_strdup(v->value);
25306 } else if (!strcasecmp(v->name, "tlscapath")) {
25307 ast_free(default_tls_cfg.capath);
25308 default_tls_cfg.capath = ast_strdup(v->value);
25309 } else if (!strcasecmp(v->name, "tlsverifyclient")) {
25310 ast_set2_flag(&default_tls_cfg.flags, ast_true(v->value), AST_SSL_VERIFY_CLIENT);
25311 } else if (!strcasecmp(v->name, "tlsdontverifyserver")) {
25312 ast_set2_flag(&default_tls_cfg.flags, ast_true(v->value), AST_SSL_DONT_VERIFY_SERVER);
25313 } else if (!strcasecmp(v->name, "tlsbindaddr")) {
25314 if (ast_parse_arg(v->value, PARSE_INADDR, &sip_tls_desc.local_address))
25315 ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n", v->name, v->value, v->lineno, config);
25316 } else if (!strcasecmp(v->name, "dynamic_exclude_static") || !strcasecmp(v->name, "dynamic_excludes_static")) {
25317 global_dynamic_exclude_static = ast_true(v->value);
25318 } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny")) {
25319 int ha_error = 0;
25320 global_contact_ha = ast_append_ha(v->name + 7, v->value, global_contact_ha, &ha_error);
25321 if (ha_error) {
25322 ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
25323 }
25324 } else if (!strcasecmp(v->name, "rtautoclear")) {
25325 int i = atoi(v->value);
25326 if (i > 0)
25327 sip_cfg.rtautoclear = i;
25328 else
25329 i = 0;
25330 ast_set2_flag(&global_flags[1], i || ast_true(v->value), SIP_PAGE2_RTAUTOCLEAR);
25331 } else if (!strcasecmp(v->name, "usereqphone")) {
25332 ast_set2_flag(&global_flags[0], ast_true(v->value), SIP_USEREQPHONE);
25333 } else if (!strcasecmp(v->name, "prematuremedia")) {
25334 global_prematuremediafilter = ast_true(v->value);
25335 } else if (!strcasecmp(v->name, "relaxdtmf")) {
25336 global_relaxdtmf = ast_true(v->value);
25337 } else if (!strcasecmp(v->name, "vmexten")) {
25338 ast_copy_string(default_vmexten, v->value, sizeof(default_vmexten));
25339 } else if (!strcasecmp(v->name, "rtptimeout")) {
25340 if ((sscanf(v->value, "%30d", &global_rtptimeout) != 1) || (global_rtptimeout < 0)) {
25341 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
25342 global_rtptimeout = 0;
25343 }
25344 } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
25345 if ((sscanf(v->value, "%30d", &global_rtpholdtimeout) != 1) || (global_rtpholdtimeout < 0)) {
25346 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
25347 global_rtpholdtimeout = 0;
25348 }
25349 } else if (!strcasecmp(v->name, "rtpkeepalive")) {
25350 if ((sscanf(v->value, "%30d", &global_rtpkeepalive) != 1) || (global_rtpkeepalive < 0)) {
25351 ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d. Using default.\n", v->value, v->lineno);
25352 global_rtpkeepalive = DEFAULT_RTPKEEPALIVE;
25353 }
25354 } else if (!strcasecmp(v->name, "compactheaders")) {
25355 sip_cfg.compactheaders = ast_true(v->value);
25356 } else if (!strcasecmp(v->name, "notifymimetype")) {
25357 ast_copy_string(default_notifymime, v->value, sizeof(default_notifymime));
25358 } else if (!strcasecmp(v->name, "directrtpsetup")) {
25359 sip_cfg.directrtpsetup = ast_true(v->value);
25360 } else if (!strcasecmp(v->name, "notifyringing")) {
25361 sip_cfg.notifyringing = ast_true(v->value);
25362 } else if (!strcasecmp(v->name, "notifyhold")) {
25363 sip_cfg.notifyhold = ast_true(v->value);
25364 } else if (!strcasecmp(v->name, "notifycid")) {
25365 if (!strcasecmp(v->value, "ignore-context")) {
25366 sip_cfg.notifycid = IGNORE_CONTEXT;
25367 } else {
25368 sip_cfg.notifycid = ast_true(v->value);
25369 }
25370 } else if (!strcasecmp(v->name, "alwaysauthreject")) {
25371 sip_cfg.alwaysauthreject = ast_true(v->value);
25372 } else if (!strcasecmp(v->name, "mohinterpret")) {
25373 ast_copy_string(default_mohinterpret, v->value, sizeof(default_mohinterpret));
25374 } else if (!strcasecmp(v->name, "mohsuggest")) {
25375 ast_copy_string(default_mohsuggest, v->value, sizeof(default_mohsuggest));
25376 } else if (!strcasecmp(v->name, "language")) {
25377 ast_copy_string(default_language, v->value, sizeof(default_language));
25378 } else if (!strcasecmp(v->name, "regcontext")) {
25379 ast_copy_string(newcontexts, v->value, sizeof(newcontexts));
25380 stringp = newcontexts;
25381
25382 cleanup_stale_contexts(stringp, oldregcontext);
25383
25384 while ((context = strsep(&stringp, "&"))) {
25385 ast_copy_string(used_context, context, sizeof(used_context));
25386 ast_context_find_or_create(NULL, NULL, context, "SIP");
25387 }
25388 ast_copy_string(global_regcontext, v->value, sizeof(global_regcontext));
25389 } else if (!strcasecmp(v->name, "regextenonqualify")) {
25390 sip_cfg.regextenonqualify = ast_true(v->value);
25391 } else if (!strcasecmp(v->name, "callerid")) {
25392 ast_copy_string(default_callerid, v->value, sizeof(default_callerid));
25393 } else if (!strcasecmp(v->name, "fromdomain")) {
25394 ast_copy_string(default_fromdomain, v->value, sizeof(default_fromdomain));
25395 } else if (!strcasecmp(v->name, "outboundproxy")) {
25396 int portnum;
25397 char *tok, *proxyname;
25398
25399 if (ast_strlen_zero(v->value)) {
25400 ast_log(LOG_WARNING, "no value given for outbound proxy on line %d of sip.conf.", v->lineno);
25401 continue;
25402 }
25403
25404 tok = ast_skip_blanks(strtok(ast_strdupa(v->value), ","));
25405
25406 sip_parse_host(tok, v->lineno, &proxyname, &portnum, &sip_cfg.outboundproxy.transport);
25407
25408 sip_cfg.outboundproxy.ip.sin_port = htons(portnum);
25409
25410 if ((tok = strtok(NULL, ","))) {
25411 sip_cfg.outboundproxy.force = !strncasecmp(ast_skip_blanks(tok), "force", 5);
25412 } else {
25413 sip_cfg.outboundproxy.force = FALSE;
25414 }
25415
25416 if (ast_strlen_zero(proxyname)) {
25417 ast_log(LOG_WARNING, "you must specify a name for the outboundproxy on line %d of sip.conf.", v->lineno);
25418 sip_cfg.outboundproxy.name[0] = '\0';
25419 continue;
25420 }
25421
25422 ast_copy_string(sip_cfg.outboundproxy.name, proxyname, sizeof(sip_cfg.outboundproxy.name));
25423
25424 proxy_update(&sip_cfg.outboundproxy);
25425 } else if (!strcasecmp(v->name, "autocreatepeer")) {
25426 sip_cfg.autocreatepeer = ast_true(v->value);
25427 } else if (!strcasecmp(v->name, "match_auth_username")) {
25428 global_match_auth_username = ast_true(v->value);
25429 } else if (!strcasecmp(v->name, "srvlookup")) {
25430 sip_cfg.srvlookup = ast_true(v->value);
25431 } else if (!strcasecmp(v->name, "pedantic")) {
25432 sip_cfg.pedanticsipchecking = ast_true(v->value);
25433 } else if (!strcasecmp(v->name, "maxexpirey") || !strcasecmp(v->name, "maxexpiry")) {
25434 max_expiry = atoi(v->value);
25435 if (max_expiry < 1)
25436 max_expiry = DEFAULT_MAX_EXPIRY;
25437 } else if (!strcasecmp(v->name, "minexpirey") || !strcasecmp(v->name, "minexpiry")) {
25438 min_expiry = atoi(v->value);
25439 if (min_expiry < 1)
25440 min_expiry = DEFAULT_MIN_EXPIRY;
25441 } else if (!strcasecmp(v->name, "defaultexpiry") || !strcasecmp(v->name, "defaultexpirey")) {
25442 default_expiry = atoi(v->value);
25443 if (default_expiry < 1)
25444 default_expiry = DEFAULT_DEFAULT_EXPIRY;
25445 } else if (!strcasecmp(v->name, "mwiexpiry") || !strcasecmp(v->name, "mwiexpirey")) {
25446 mwi_expiry = atoi(v->value);
25447 if (mwi_expiry < 1)
25448 mwi_expiry = DEFAULT_MWI_EXPIRY;
25449 } else if (!strcasecmp(v->name, "tcpauthtimeout")) {
25450 if (ast_parse_arg(v->value, PARSE_INT32|PARSE_DEFAULT|PARSE_IN_RANGE,
25451 &authtimeout, DEFAULT_AUTHTIMEOUT, 1, INT_MAX)) {
25452 ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n",
25453 v->name, v->value, v->lineno, config);
25454 }
25455 } else if (!strcasecmp(v->name, "tcpauthlimit")) {
25456 if (ast_parse_arg(v->value, PARSE_INT32|PARSE_DEFAULT|PARSE_IN_RANGE,
25457 &authlimit, DEFAULT_AUTHLIMIT, 1, INT_MAX)) {
25458 ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n",
25459 v->name, v->value, v->lineno, config);
25460 }
25461 } else if (!strcasecmp(v->name, "sipdebug")) {
25462 if (ast_true(v->value))
25463 sipdebug |= sip_debug_config;
25464 } else if (!strcasecmp(v->name, "dumphistory")) {
25465 dumphistory = ast_true(v->value);
25466 } else if (!strcasecmp(v->name, "recordhistory")) {
25467 recordhistory = ast_true(v->value);
25468 } else if (!strcasecmp(v->name, "registertimeout")) {
25469 global_reg_timeout = atoi(v->value);
25470 if (global_reg_timeout < 1)
25471 global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
25472 } else if (!strcasecmp(v->name, "registerattempts")) {
25473 global_regattempts_max = atoi(v->value);
25474 } else if (!strcasecmp(v->name, "stunaddr")) {
25475 stunaddr.sin_port = htons(3478);
25476 if (ast_parse_arg(v->value, PARSE_INADDR, &stunaddr))
25477 ast_log(LOG_WARNING, "Invalid STUN server address: %s\n", v->value);
25478 externexpire = time(NULL);
25479 } else if (!strcasecmp(v->name, "bindaddr") || !strcasecmp(v->name, "udpbindaddr")) {
25480 if (ast_parse_arg(v->value, PARSE_INADDR, &bindaddr))
25481 ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
25482 } else if (!strcasecmp(v->name, "localnet")) {
25483 struct ast_ha *na;
25484 int ha_error = 0;
25485
25486 if (!(na = ast_append_ha("d", v->value, localaddr, &ha_error)))
25487 ast_log(LOG_WARNING, "Invalid localnet value: %s\n", v->value);
25488 else
25489 localaddr = na;
25490 if (ha_error)
25491 ast_log(LOG_ERROR, "Bad localnet configuration value line %d : %s\n", v->lineno, v->value);
25492 } else if (!strcasecmp(v->name, "externip")) {
25493 if (ast_parse_arg(v->value, PARSE_INADDR, &externip))
25494 ast_log(LOG_WARNING, "Invalid address for externip keyword: %s\n", v->value);
25495 externexpire = 0;
25496
25497 if (!externip.sin_port)
25498 externip.sin_port = bindaddr.sin_port;
25499 } else if (!strcasecmp(v->name, "externhost")) {
25500 ast_copy_string(externhost, v->value, sizeof(externhost));
25501 if (ast_parse_arg(externhost, PARSE_INADDR, &externip))
25502 ast_log(LOG_WARNING, "Invalid address for externhost keyword: %s\n", externhost);
25503 externexpire = time(NULL);
25504
25505 if (!externip.sin_port)
25506 externip.sin_port = bindaddr.sin_port;
25507 } else if (!strcasecmp(v->name, "externrefresh")) {
25508 if (sscanf(v->value, "%30d", &externrefresh) != 1) {
25509 ast_log(LOG_WARNING, "Invalid externrefresh value '%s', must be an integer >0 at line %d\n", v->value, v->lineno);
25510 externrefresh = 10;
25511 }
25512 } else if (!strcasecmp(v->name, "allow")) {
25513 int error = ast_parse_allow_disallow(&default_prefs, &global_capability, v->value, TRUE);
25514 if (error)
25515 ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
25516 } else if (!strcasecmp(v->name, "disallow")) {
25517 int error = ast_parse_allow_disallow(&default_prefs, &global_capability, v->value, FALSE);
25518 if (error)
25519 ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
25520 } else if (!strcasecmp(v->name, "autoframing")) {
25521 global_autoframing = ast_true(v->value);
25522 } else if (!strcasecmp(v->name, "allowexternaldomains")) {
25523 sip_cfg.allow_external_domains = ast_true(v->value);
25524 } else if (!strcasecmp(v->name, "autodomain")) {
25525 auto_sip_domains = ast_true(v->value);
25526 } else if (!strcasecmp(v->name, "domain")) {
25527 char *domain = ast_strdupa(v->value);
25528 char *cntx = strchr(domain, ',');
25529
25530 if (cntx)
25531 *cntx++ = '\0';
25532
25533 if (ast_strlen_zero(cntx))
25534 ast_debug(1, "No context specified at line %d for domain '%s'\n", v->lineno, domain);
25535 if (ast_strlen_zero(domain))
25536 ast_log(LOG_WARNING, "Empty domain specified at line %d\n", v->lineno);
25537 else
25538 add_sip_domain(ast_strip(domain), SIP_DOMAIN_CONFIG, cntx ? ast_strip(cntx) : "");
25539 } else if (!strcasecmp(v->name, "register")) {
25540 if (sip_register(v->value, v->lineno) == 0)
25541 registry_count++;
25542 } else if (!strcasecmp(v->name, "mwi")) {
25543 sip_subscribe_mwi(v->value, v->lineno);
25544 } else if (!strcasecmp(v->name, "tos_sip")) {
25545 if (ast_str2tos(v->value, &global_tos_sip))
25546 ast_log(LOG_WARNING, "Invalid tos_sip value at line %d, refer to QoS documentation\n", v->lineno);
25547 } else if (!strcasecmp(v->name, "tos_audio")) {
25548 if (ast_str2tos(v->value, &global_tos_audio))
25549 ast_log(LOG_WARNING, "Invalid tos_audio value at line %d, refer to QoS documentation\n", v->lineno);
25550 } else if (!strcasecmp(v->name, "tos_video")) {
25551 if (ast_str2tos(v->value, &global_tos_video))
25552 ast_log(LOG_WARNING, "Invalid tos_video value at line %d, refer to QoS documentation\n", v->lineno);
25553 } else if (!strcasecmp(v->name, "tos_text")) {
25554 if (ast_str2tos(v->value, &global_tos_text))
25555 ast_log(LOG_WARNING, "Invalid tos_text value at line %d, refer to QoS documentation\n", v->lineno);
25556 } else if (!strcasecmp(v->name, "cos_sip")) {
25557 if (ast_str2cos(v->value, &global_cos_sip))
25558 ast_log(LOG_WARNING, "Invalid cos_sip value at line %d, refer to QoS documentation\n", v->lineno);
25559 } else if (!strcasecmp(v->name, "cos_audio")) {
25560 if (ast_str2cos(v->value, &global_cos_audio))
25561 ast_log(LOG_WARNING, "Invalid cos_audio value at line %d, refer to QoS documentation\n", v->lineno);
25562 } else if (!strcasecmp(v->name, "cos_video")) {
25563 if (ast_str2cos(v->value, &global_cos_video))
25564 ast_log(LOG_WARNING, "Invalid cos_video value at line %d, refer to QoS documentation\n", v->lineno);
25565 } else if (!strcasecmp(v->name, "cos_text")) {
25566 if (ast_str2cos(v->value, &global_cos_text))
25567 ast_log(LOG_WARNING, "Invalid cos_text value at line %d, refer to QoS documentation\n", v->lineno);
25568 } else if (!strcasecmp(v->name, "bindport")) {
25569 int i;
25570 if (sscanf(v->value, "%5d", &i) == 1) {
25571 bindaddr.sin_port = htons(i);
25572 } else {
25573 ast_log(LOG_WARNING, "Invalid port number '%s' at line %d of %s\n", v->value, v->lineno, config);
25574 }
25575 } else if (!strcasecmp(v->name, "qualify")) {
25576 if (!strcasecmp(v->value, "no")) {
25577 default_qualify = 0;
25578 } else if (!strcasecmp(v->value, "yes")) {
25579 default_qualify = DEFAULT_MAXMS;
25580 } else if (sscanf(v->value, "%30d", &default_qualify) != 1) {
25581 ast_log(LOG_WARNING, "Qualification default should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", v->lineno);
25582 default_qualify = 0;
25583 }
25584 } else if (!strcasecmp(v->name, "qualifyfreq")) {
25585 int i;
25586 if (sscanf(v->value, "%30d", &i) == 1)
25587 global_qualifyfreq = i * 1000;
25588 else {
25589 ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
25590 global_qualifyfreq = DEFAULT_QUALIFYFREQ;
25591 }
25592 } else if (!strcasecmp(v->name, "callevents")) {
25593 sip_cfg.callevents = ast_true(v->value);
25594 } else if (!strcasecmp(v->name, "authfailureevents")) {
25595 global_authfailureevents = ast_true(v->value);
25596 } else if (!strcasecmp(v->name, "maxcallbitrate")) {
25597 default_maxcallbitrate = atoi(v->value);
25598 if (default_maxcallbitrate < 0)
25599 default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
25600 } else if (!strcasecmp(v->name, "matchexterniplocally")) {
25601 sip_cfg.matchexterniplocally = ast_true(v->value);
25602 } else if (!strcasecmp(v->name, "session-timers")) {
25603 int i = (int) str2stmode(v->value);
25604 if (i < 0) {
25605 ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
25606 global_st_mode = SESSION_TIMER_MODE_ACCEPT;
25607 } else {
25608 global_st_mode = i;
25609 }
25610 } else if (!strcasecmp(v->name, "session-expires")) {
25611 if (sscanf(v->value, "%30d", &global_max_se) != 1) {
25612 ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
25613 global_max_se = DEFAULT_MAX_SE;
25614 }
25615 } else if (!strcasecmp(v->name, "session-minse")) {
25616 if (sscanf(v->value, "%30d", &global_min_se) != 1) {
25617 ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
25618 global_min_se = DEFAULT_MIN_SE;
25619 }
25620 if (global_min_se < 90) {
25621 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);
25622 global_min_se = DEFAULT_MIN_SE;
25623 }
25624 } else if (!strcasecmp(v->name, "session-refresher")) {
25625 int i = (int) str2strefresher(v->value);
25626 if (i < 0) {
25627 ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
25628 global_st_refresher = SESSION_TIMER_REFRESHER_UAS;
25629 } else {
25630 global_st_refresher = i;
25631 }
25632 } else if (!strcasecmp(v->name, "qualifygap")) {
25633 if (sscanf(v->value, "%30d", &global_qualify_gap) != 1) {
25634 ast_log(LOG_WARNING, "Invalid qualifygap '%s' at line %d of %s\n", v->value, v->lineno, config);
25635 global_qualify_gap = DEFAULT_QUALIFY_GAP;
25636 }
25637 } else if (!strcasecmp(v->name, "qualifypeers")) {
25638 if (sscanf(v->value, "%30d", &global_qualify_peers) != 1) {
25639 ast_log(LOG_WARNING, "Invalid pokepeers '%s' at line %d of %s\n", v->value, v->lineno, config);
25640 global_qualify_peers = DEFAULT_QUALIFY_PEERS;
25641 }
25642 } else if (!strcasecmp(v->name, "shrinkcallerid")) {
25643 if (ast_true(v->value)) {
25644 global_shrinkcallerid = 1;
25645 } else if (ast_false(v->value)) {
25646 global_shrinkcallerid = 0;
25647 } else {
25648 ast_log(LOG_WARNING, "shrinkcallerid value %s is not valid at line %d.\n", v->value, v->lineno);
25649 }
25650 }
25651 }
25652
25653 if (!sip_cfg.allow_external_domains && AST_LIST_EMPTY(&domain_list)) {
25654 ast_log(LOG_WARNING, "To disallow external domains, you need to configure local SIP domains.\n");
25655 sip_cfg.allow_external_domains = 1;
25656 }
25657
25658 if (default_transports == 0) {
25659 default_transports = default_primary_transport = SIP_TRANSPORT_UDP;
25660 }
25661
25662
25663 for (v = ast_variable_browse(cfg, "authentication"); v ; v = v->next) {
25664
25665 if (!strcasecmp(v->name, "auth"))
25666 authl = add_realm_authentication(authl, v->value, v->lineno);
25667 }
25668
25669
25670 bindaddr.sin_family = AF_INET;
25671 internip = bindaddr;
25672 if (ast_find_ourip(&internip.sin_addr, bindaddr)) {
25673 ast_log(LOG_WARNING, "Unable to get own IP address, SIP disabled\n");
25674 ast_config_destroy(cfg);
25675 return 0;
25676 }
25677
25678 ast_mutex_lock(&netlock);
25679 if ((sipsock > -1) && (memcmp(&old_bindaddr, &bindaddr, sizeof(struct sockaddr_in)))) {
25680 close(sipsock);
25681 sipsock = -1;
25682 }
25683 if (sipsock < 0) {
25684 sipsock = socket(AF_INET, SOCK_DGRAM, 0);
25685 if (sipsock < 0) {
25686 ast_log(LOG_WARNING, "Unable to create SIP socket: %s\n", strerror(errno));
25687 ast_config_destroy(cfg);
25688 ast_mutex_unlock(&netlock);
25689 return -1;
25690 } else {
25691
25692 const int reuseFlag = 1;
25693
25694 setsockopt(sipsock, SOL_SOCKET, SO_REUSEADDR,
25695 (const char*)&reuseFlag,
25696 sizeof reuseFlag);
25697
25698 ast_enable_packet_fragmentation(sipsock);
25699
25700 if (bind(sipsock, (struct sockaddr *)&bindaddr, sizeof(bindaddr)) < 0) {
25701 ast_log(LOG_WARNING, "Failed to bind to %s:%d: %s\n",
25702 ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port),
25703 strerror(errno));
25704 close(sipsock);
25705 sipsock = -1;
25706 } else {
25707 ast_verb(2, "SIP Listening on %s:%d\n",
25708 ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port));
25709 ast_netsock_set_qos(sipsock, global_tos_sip, global_cos_sip, "SIP");
25710 }
25711 }
25712 } else {
25713 ast_netsock_set_qos(sipsock, global_tos_sip, global_cos_sip, "SIP");
25714 }
25715 if (stunaddr.sin_addr.s_addr != 0) {
25716 ast_debug(1, "stun to %s:%d\n",
25717 ast_inet_ntoa(stunaddr.sin_addr) , ntohs(stunaddr.sin_port));
25718 ast_stun_request(sipsock, &stunaddr,
25719 NULL, &externip);
25720 ast_debug(1, "STUN sees us at %s:%d\n",
25721 ast_inet_ntoa(externip.sin_addr) , ntohs(externip.sin_port));
25722 }
25723 ast_mutex_unlock(&netlock);
25724
25725
25726 ast_tcptls_server_start(&sip_tcp_desc);
25727 if (sip_tcp_desc.accept_fd == -1 && sip_tcp_desc.local_address.sin_family == AF_INET) {
25728
25729 ast_log(LOG_ERROR, "SIP TCP Server start failed. Not listening on TCP socket.\n");
25730 sip_tcp_desc.local_address.sin_family = 0;
25731 } else {
25732 ast_debug(2, "SIP TCP server started\n");
25733 }
25734
25735
25736 memcpy(sip_tls_desc.tls_cfg, &default_tls_cfg, sizeof(default_tls_cfg));
25737
25738 if (ast_ssl_setup(sip_tls_desc.tls_cfg)) {
25739 ast_tcptls_server_start(&sip_tls_desc);
25740 if (default_tls_cfg.enabled && sip_tls_desc.accept_fd == -1) {
25741 ast_log(LOG_ERROR, "TLS Server start failed. Not listening on TLS socket.\n");
25742 sip_tls_desc.tls_cfg = NULL;
25743 }
25744 } else if (sip_tls_desc.tls_cfg->enabled) {
25745 sip_tls_desc.tls_cfg = NULL;
25746 ast_log(LOG_WARNING, "SIP TLS server did not load because of errors.\n");
25747 }
25748
25749 if (ucfg) {
25750 struct ast_variable *gen;
25751 int genhassip, genregistersip;
25752 const char *hassip, *registersip;
25753
25754 genhassip = ast_true(ast_variable_retrieve(ucfg, "general", "hassip"));
25755 genregistersip = ast_true(ast_variable_retrieve(ucfg, "general", "registersip"));
25756 gen = ast_variable_browse(ucfg, "general");
25757 cat = ast_category_browse(ucfg, NULL);
25758 while (cat) {
25759 if (strcasecmp(cat, "general")) {
25760 hassip = ast_variable_retrieve(ucfg, cat, "hassip");
25761 registersip = ast_variable_retrieve(ucfg, cat, "registersip");
25762 if (ast_true(hassip) || (!hassip && genhassip)) {
25763 peer = build_peer(cat, gen, ast_variable_browse(ucfg, cat), 0, 0);
25764 if (peer) {
25765
25766 peer->type = SIP_TYPE_USER | SIP_TYPE_PEER;
25767 ao2_t_link(peers, peer, "link peer into peer table");
25768 if ((peer->type & SIP_TYPE_PEER) && peer->addr.sin_addr.s_addr) {
25769 ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
25770 }
25771
25772 unref_peer(peer, "unref_peer: from reload_config");
25773 peer_count++;
25774 }
25775 }
25776 if (ast_true(registersip) || (!registersip && genregistersip)) {
25777 char tmp[256];
25778 const char *host = ast_variable_retrieve(ucfg, cat, "host");
25779 const char *username = ast_variable_retrieve(ucfg, cat, "username");
25780 const char *secret = ast_variable_retrieve(ucfg, cat, "secret");
25781 const char *contact = ast_variable_retrieve(ucfg, cat, "contact");
25782 const char *authuser = ast_variable_retrieve(ucfg, cat, "authuser");
25783 if (!host)
25784 host = ast_variable_retrieve(ucfg, "general", "host");
25785 if (!username)
25786 username = ast_variable_retrieve(ucfg, "general", "username");
25787 if (!secret)
25788 secret = ast_variable_retrieve(ucfg, "general", "secret");
25789 if (!contact)
25790 contact = "s";
25791 if (!ast_strlen_zero(username) && !ast_strlen_zero(host)) {
25792 if (!ast_strlen_zero(secret)) {
25793 if (!ast_strlen_zero(authuser)) {
25794 snprintf(tmp, sizeof(tmp), "%s?%s:%s:%s@%s/%s", cat, username, secret, authuser, host, contact);
25795 } else {
25796 snprintf(tmp, sizeof(tmp), "%s?%s:%s@%s/%s", cat, username, secret, host, contact);
25797 }
25798 } else if (!ast_strlen_zero(authuser)) {
25799 snprintf(tmp, sizeof(tmp), "%s?%s::%s@%s/%s", cat, username, authuser, host, contact);
25800 } else {
25801 snprintf(tmp, sizeof(tmp), "%s?%s@%s/%s", cat, username, host, contact);
25802 }
25803 if (sip_register(tmp, 0) == 0)
25804 registry_count++;
25805 }
25806 }
25807 }
25808 cat = ast_category_browse(ucfg, cat);
25809 }
25810 ast_config_destroy(ucfg);
25811 }
25812
25813
25814 cat = NULL;
25815 while ( (cat = ast_category_browse(cfg, cat)) ) {
25816 const char *utype;
25817 if (!strcasecmp(cat, "general") || !strcasecmp(cat, "authentication"))
25818 continue;
25819 utype = ast_variable_retrieve(cfg, cat, "type");
25820 if (!utype) {
25821 ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
25822 continue;
25823 } else {
25824 if (!strcasecmp(utype, "user")) {
25825 ;
25826 } else if (!strcasecmp(utype, "friend")) {
25827 ;
25828 } else if (!strcasecmp(utype, "peer")) {
25829 ;
25830 } else {
25831 ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, "sip.conf");
25832 continue;
25833 }
25834 peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0, 0);
25835 if (peer) {
25836 ao2_t_link(peers, peer, "link peer into peers table");
25837 if ((peer->type & SIP_TYPE_PEER) && peer->addr.sin_addr.s_addr) {
25838 ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
25839 }
25840 unref_peer(peer, "unref the result of the build_peer call. Now, the links from the tables are the only ones left.");
25841 peer_count++;
25842 }
25843 }
25844 }
25845
25846
25847
25848
25849
25850
25851 if (auto_sip_domains) {
25852 char temp[MAXHOSTNAMELEN];
25853
25854
25855 if (bindaddr.sin_addr.s_addr) {
25856 add_sip_domain(ast_inet_ntoa(bindaddr.sin_addr), SIP_DOMAIN_AUTO, NULL);
25857 } else if (internip.sin_addr.s_addr) {
25858
25859 add_sip_domain(ast_inet_ntoa(internip.sin_addr), SIP_DOMAIN_AUTO, NULL);
25860 } else {
25861 ast_log(LOG_NOTICE, "Can't add wildcard IP address to domain list, please add IP address to domain manually.\n");
25862 }
25863
25864
25865 if (sip_tcp_desc.local_address.sin_addr.s_addr && !inaddrcmp(&bindaddr, &sip_tcp_desc.local_address))
25866 add_sip_domain(ast_inet_ntoa(sip_tcp_desc.local_address.sin_addr), SIP_DOMAIN_AUTO, NULL);
25867
25868
25869 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))
25870 add_sip_domain(ast_inet_ntoa(sip_tls_desc.local_address.sin_addr), SIP_DOMAIN_AUTO, NULL);
25871
25872
25873 if (externip.sin_addr.s_addr)
25874 add_sip_domain(ast_inet_ntoa(externip.sin_addr), SIP_DOMAIN_AUTO, NULL);
25875
25876
25877 if (!ast_strlen_zero(externhost))
25878 add_sip_domain(externhost, SIP_DOMAIN_AUTO, NULL);
25879
25880
25881 if (!gethostname(temp, sizeof(temp)))
25882 add_sip_domain(temp, SIP_DOMAIN_AUTO, NULL);
25883 }
25884
25885
25886 ast_config_destroy(cfg);
25887
25888
25889 if (notify_types)
25890 ast_config_destroy(notify_types);
25891 if ((notify_types = ast_config_load(notify_config, config_flags)) == CONFIG_STATUS_FILEINVALID) {
25892 ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed.\n", notify_config);
25893 notify_types = NULL;
25894 }
25895
25896
25897 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);
25898 run_end = time(0);
25899 ast_debug(4, "SIP reload_config done...Runtime= %d sec\n", (int)(run_end-run_start));
25900
25901 return 0;
25902 }
25903
25904 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan)
25905 {
25906 struct sip_pvt *p;
25907 struct ast_udptl *udptl = NULL;
25908
25909 p = chan->tech_pvt;
25910 if (!p)
25911 return NULL;
25912
25913 sip_pvt_lock(p);
25914 if (p->udptl && ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA))
25915 udptl = p->udptl;
25916 sip_pvt_unlock(p);
25917 return udptl;
25918 }
25919
25920 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl)
25921 {
25922 struct sip_pvt *p;
25923
25924 p = chan->tech_pvt;
25925 if (!p)
25926 return -1;
25927 sip_pvt_lock(p);
25928 if (udptl)
25929 ast_udptl_get_peer(udptl, &p->udptlredirip);
25930 else
25931 memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
25932 if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
25933 if (!p->pendinginvite) {
25934 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);
25935 transmit_reinvite_with_sdp(p, TRUE, FALSE);
25936 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
25937 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);
25938 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
25939 }
25940 }
25941
25942 p->lastrtprx = p->lastrtptx = time(NULL);
25943 sip_pvt_unlock(p);
25944 return 0;
25945 }
25946
25947
25948 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
25949 {
25950 struct sip_pvt *p = NULL;
25951 enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
25952
25953 if (!(p = chan->tech_pvt))
25954 return AST_RTP_GET_FAILED;
25955
25956 sip_pvt_lock(p);
25957 if (!(p->rtp)) {
25958 sip_pvt_unlock(p);
25959 return AST_RTP_GET_FAILED;
25960 }
25961
25962 *rtp = p->rtp;
25963
25964 if (ast_rtp_getnat(*rtp) && !ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA_NAT))
25965 res = AST_RTP_TRY_PARTIAL;
25966 else if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA))
25967 res = AST_RTP_TRY_NATIVE;
25968 else if (ast_test_flag(&global_jbconf, AST_JB_FORCED))
25969 res = AST_RTP_GET_FAILED;
25970
25971 sip_pvt_unlock(p);
25972
25973 return res;
25974 }
25975
25976
25977 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
25978 {
25979 struct sip_pvt *p = NULL;
25980 enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
25981
25982 if (!(p = chan->tech_pvt))
25983 return AST_RTP_GET_FAILED;
25984
25985 sip_pvt_lock(p);
25986 if (!(p->vrtp)) {
25987 sip_pvt_unlock(p);
25988 return AST_RTP_GET_FAILED;
25989 }
25990
25991 *rtp = p->vrtp;
25992
25993 if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA))
25994 res = AST_RTP_TRY_NATIVE;
25995
25996 sip_pvt_unlock(p);
25997
25998 return res;
25999 }
26000
26001
26002 static enum ast_rtp_get_result sip_get_trtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
26003 {
26004 struct sip_pvt *p = NULL;
26005 enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
26006
26007 if (!(p = chan->tech_pvt))
26008 return AST_RTP_GET_FAILED;
26009
26010 sip_pvt_lock(p);
26011 if (!(p->trtp)) {
26012 sip_pvt_unlock(p);
26013 return AST_RTP_GET_FAILED;
26014 }
26015
26016 *rtp = p->trtp;
26017
26018 if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA))
26019 res = AST_RTP_TRY_NATIVE;
26020
26021 sip_pvt_unlock(p);
26022
26023 return res;
26024 }
26025
26026
26027 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)
26028 {
26029 struct sip_pvt *p;
26030 int changed = 0;
26031
26032 p = chan->tech_pvt;
26033 if (!p)
26034 return -1;
26035
26036
26037 if (!ast_bridged_channel(chan) && !sip_cfg.directrtpsetup)
26038 return 0;
26039
26040 sip_pvt_lock(p);
26041 if (p->alreadygone) {
26042
26043 sip_pvt_unlock(p);
26044 return 0;
26045 }
26046
26047
26048
26049
26050 if (nat_active && !ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA_NAT)) {
26051 sip_pvt_unlock(p);
26052 return 0;
26053 }
26054
26055 if (rtp) {
26056 changed |= ast_rtp_get_peer(rtp, &p->redirip);
26057 } else if (p->redirip.sin_addr.s_addr || ntohs(p->redirip.sin_port) != 0) {
26058 memset(&p->redirip, 0, sizeof(p->redirip));
26059 changed = 1;
26060 }
26061 if (vrtp) {
26062 changed |= ast_rtp_get_peer(vrtp, &p->vredirip);
26063 } else if (p->vredirip.sin_addr.s_addr || ntohs(p->vredirip.sin_port) != 0) {
26064 memset(&p->vredirip, 0, sizeof(p->vredirip));
26065 changed = 1;
26066 }
26067 if (trtp) {
26068 changed |= ast_rtp_get_peer(trtp, &p->tredirip);
26069 } else if (p->tredirip.sin_addr.s_addr || ntohs(p->tredirip.sin_port) != 0) {
26070 memset(&p->tredirip, 0, sizeof(p->tredirip));
26071 changed = 1;
26072 }
26073 if (codecs && (p->redircodecs != codecs)) {
26074 p->redircodecs = codecs;
26075 changed = 1;
26076 }
26077 if (changed && !ast_test_flag(&p->flags[0], SIP_GOTREFER) && !ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
26078 if (chan->_state != AST_STATE_UP) {
26079 if (p->do_history)
26080 append_history(p, "ExtInv", "Initial invite sent with remote bridge proposal.");
26081 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));
26082 } else if (!p->pendinginvite) {
26083 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));
26084 transmit_reinvite_with_sdp(p, FALSE, FALSE);
26085 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
26086 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));
26087
26088 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
26089 }
26090 }
26091
26092 p->lastrtprx = p->lastrtptx = time(NULL);
26093 sip_pvt_unlock(p);
26094 return 0;
26095 }
26096
26097 static char *app_dtmfmode = "SIPDtmfMode";
26098 static char *app_sipaddheader = "SIPAddHeader";
26099 static char *app_sipremoveheader = "SIPRemoveHeader";
26100
26101
26102 static int sip_dtmfmode(struct ast_channel *chan, void *data)
26103 {
26104 struct sip_pvt *p;
26105 char *mode = data;
26106
26107 if (!data) {
26108 ast_log(LOG_WARNING, "This application requires the argument: info, inband, rfc2833\n");
26109 return 0;
26110 }
26111 ast_channel_lock(chan);
26112 if (!IS_SIP_TECH(chan->tech)) {
26113 ast_log(LOG_WARNING, "Call this application only on SIP incoming calls\n");
26114 ast_channel_unlock(chan);
26115 return 0;
26116 }
26117 p = chan->tech_pvt;
26118 if (!p) {
26119 ast_channel_unlock(chan);
26120 return 0;
26121 }
26122 sip_pvt_lock(p);
26123 if (!strcasecmp(mode, "info")) {
26124 ast_clear_flag(&p->flags[0], SIP_DTMF);
26125 ast_set_flag(&p->flags[0], SIP_DTMF_INFO);
26126 p->jointnoncodeccapability &= ~AST_RTP_DTMF;
26127 } else if (!strcasecmp(mode, "shortinfo")) {
26128 ast_clear_flag(&p->flags[0], SIP_DTMF);
26129 ast_set_flag(&p->flags[0], SIP_DTMF_SHORTINFO);
26130 p->jointnoncodeccapability &= ~AST_RTP_DTMF;
26131 } else if (!strcasecmp(mode, "rfc2833")) {
26132 ast_clear_flag(&p->flags[0], SIP_DTMF);
26133 ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
26134 p->jointnoncodeccapability |= AST_RTP_DTMF;
26135 } else if (!strcasecmp(mode, "inband")) {
26136 ast_clear_flag(&p->flags[0], SIP_DTMF);
26137 ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
26138 p->jointnoncodeccapability &= ~AST_RTP_DTMF;
26139 } else
26140 ast_log(LOG_WARNING, "I don't know about this dtmf mode: %s\n", mode);
26141 if (p->rtp)
26142 ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
26143 if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
26144 if (!p->dsp) {
26145 p->dsp = ast_dsp_new();
26146 ast_dsp_set_features(p->dsp, DSP_FEATURE_DIGIT_DETECT);
26147 }
26148 } else {
26149 if (p->dsp) {
26150 ast_dsp_free(p->dsp);
26151 p->dsp = NULL;
26152 }
26153 }
26154 sip_pvt_unlock(p);
26155 ast_channel_unlock(chan);
26156 return 0;
26157 }
26158
26159
26160 static int sip_addheader(struct ast_channel *chan, void *data)
26161 {
26162 int no = 0;
26163 int ok = FALSE;
26164 char varbuf[30];
26165 char *inbuf = data, *subbuf;
26166
26167 if (ast_strlen_zero(inbuf)) {
26168 ast_log(LOG_WARNING, "This application requires the argument: Header\n");
26169 return 0;
26170 }
26171 ast_channel_lock(chan);
26172
26173
26174 while (!ok && no <= 50) {
26175 no++;
26176 snprintf(varbuf, sizeof(varbuf), "__SIPADDHEADER%.2d", no);
26177
26178
26179 if ((pbx_builtin_getvar_helper(chan, (const char *) varbuf + 2) == (const char *) NULL)) {
26180 ok = TRUE;
26181 }
26182 }
26183 if (ok) {
26184 size_t len = strlen(inbuf);
26185 subbuf = alloca(len + 1);
26186 ast_get_encoded_str(inbuf, subbuf, len + 1);
26187 pbx_builtin_setvar_helper(chan, varbuf, subbuf);
26188 if (sipdebug) {
26189 ast_debug(1, "SIP Header added \"%s\" as %s\n", inbuf, varbuf);
26190 }
26191 } else {
26192 ast_log(LOG_WARNING, "Too many SIP headers added, max 50\n");
26193 }
26194 ast_channel_unlock(chan);
26195 return 0;
26196 }
26197
26198
26199 static int sip_removeheader(struct ast_channel *chan, void *data)
26200 {
26201 struct ast_var_t *newvariable;
26202 struct varshead *headp;
26203 int removeall = 0;
26204 char *inbuf = (char *) data;
26205
26206 if (ast_strlen_zero(inbuf)) {
26207 removeall = 1;
26208 }
26209 ast_channel_lock(chan);
26210
26211 headp=&chan->varshead;
26212 AST_LIST_TRAVERSE_SAFE_BEGIN (headp, newvariable, entries) {
26213 if (strncasecmp(ast_var_name(newvariable), "SIPADDHEADER", strlen("SIPADDHEADER")) == 0) {
26214 if (removeall || (!strncasecmp(ast_var_value(newvariable),inbuf,strlen(inbuf)))) {
26215 if (sipdebug)
26216 ast_log(LOG_DEBUG,"removing SIP Header \"%s\" as %s\n",
26217 ast_var_value(newvariable),
26218 ast_var_name(newvariable));
26219 AST_LIST_REMOVE_CURRENT(entries);
26220 ast_var_delete(newvariable);
26221 }
26222 }
26223 }
26224 AST_LIST_TRAVERSE_SAFE_END;
26225
26226 ast_channel_unlock(chan);
26227 return 0;
26228 }
26229
26230
26231
26232
26233
26234
26235
26236 static int sip_sipredirect(struct sip_pvt *p, const char *dest)
26237 {
26238 char *cdest;
26239 char *extension, *host, *port;
26240 char tmp[80];
26241
26242 cdest = ast_strdupa(dest);
26243
26244 extension = strsep(&cdest, "@");
26245 host = strsep(&cdest, ":");
26246 port = strsep(&cdest, ":");
26247 if (ast_strlen_zero(extension)) {
26248 ast_log(LOG_ERROR, "Missing mandatory argument: extension\n");
26249 return 0;
26250 }
26251
26252
26253 if (!host) {
26254 char *localtmp;
26255
26256 ast_copy_string(tmp, get_header(&p->initreq, "To"), sizeof(tmp));
26257 if (ast_strlen_zero(tmp)) {
26258 ast_log(LOG_ERROR, "Cannot retrieve the 'To' header from the original SIP request!\n");
26259 return 0;
26260 }
26261 if ( ( (localtmp = strcasestr(tmp, "sip:")) || (localtmp = strcasestr(tmp, "sips:")) )
26262 && (localtmp = strchr(localtmp, '@'))) {
26263 char lhost[80], lport[80];
26264
26265 memset(lhost, 0, sizeof(lhost));
26266 memset(lport, 0, sizeof(lport));
26267 localtmp++;
26268
26269 sscanf(localtmp, "%80[^<>:; ]:%80[^<>:; ]", lhost, lport);
26270 if (ast_strlen_zero(lhost)) {
26271 ast_log(LOG_ERROR, "Can't find the host address\n");
26272 return 0;
26273 }
26274 host = ast_strdupa(lhost);
26275 if (!ast_strlen_zero(lport)) {
26276 port = ast_strdupa(lport);
26277 }
26278 }
26279 }
26280
26281 ast_string_field_build(p, our_contact, "Transfer <sip:%s@%s%s%s>", extension, host, port ? ":" : "", port ? port : "");
26282 transmit_response_reliable(p, "302 Moved Temporarily", &p->initreq);
26283
26284 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
26285 sip_alreadygone(p);
26286
26287 return 0;
26288 }
26289
26290
26291 static int sip_get_codec(struct ast_channel *chan)
26292 {
26293 struct sip_pvt *p = chan->tech_pvt;
26294 return p->jointcapability ? p->jointcapability : p->capability;
26295 }
26296
26297
26298 static void sip_poke_all_peers(void)
26299 {
26300 int ms = 0, num = 0;
26301 struct ao2_iterator i;
26302 struct sip_peer *peer;
26303
26304 if (!speerobjs)
26305 return;
26306
26307 i = ao2_iterator_init(peers, 0);
26308 while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
26309 ao2_lock(peer);
26310 if (num == global_qualify_peers) {
26311 ms += global_qualify_gap;
26312 num = 0;
26313 } else {
26314 num++;
26315 }
26316 AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, ms, sip_poke_peer_s, peer,
26317 unref_peer(_data, "removing poke peer ref"),
26318 unref_peer(peer, "removing poke peer ref"),
26319 ref_peer(peer, "adding poke peer ref"));
26320 ao2_unlock(peer);
26321 unref_peer(peer, "toss iterator peer ptr");
26322 }
26323 ao2_iterator_destroy(&i);
26324 }
26325
26326
26327 static void sip_send_all_registers(void)
26328 {
26329 int ms;
26330 int regspacing;
26331 if (!regobjs)
26332 return;
26333 regspacing = default_expiry * 1000/regobjs;
26334 if (regspacing > 100)
26335 regspacing = 100;
26336 ms = regspacing;
26337 ASTOBJ_CONTAINER_TRAVERSE(®l, 1, do {
26338 ASTOBJ_WRLOCK(iterator);
26339 ms += regspacing;
26340 AST_SCHED_REPLACE_UNREF(iterator->expire, sched, ms, sip_reregister, iterator,
26341 registry_unref(_data, "REPLACE sched del decs the refcount"),
26342 registry_unref(iterator, "REPLACE sched add failure decs the refcount"),
26343 registry_addref(iterator, "REPLACE sched add incs the refcount"));
26344 ASTOBJ_UNLOCK(iterator);
26345 } while (0)
26346 );
26347 }
26348
26349
26350 static void sip_send_all_mwi_subscriptions(void)
26351 {
26352 ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
26353 ASTOBJ_WRLOCK(iterator);
26354 AST_SCHED_DEL(sched, iterator->resub);
26355 if ((iterator->resub = ast_sched_add(sched, 1, sip_subscribe_mwi_do, ASTOBJ_REF(iterator))) < 0) {
26356 ASTOBJ_UNREF(iterator, sip_subscribe_mwi_destroy);
26357 }
26358 ASTOBJ_UNLOCK(iterator);
26359 } while (0));
26360 }
26361
26362
26363 static int sip_do_reload(enum channelreloadreason reason)
26364 {
26365 time_t start_poke, end_poke;
26366
26367 reload_config(reason);
26368 ast_sched_dump(sched);
26369
26370 start_poke = time(0);
26371
26372 unlink_marked_peers_from_tables();
26373
26374 ast_debug(4, "--------------- Done destroying pruned peers\n");
26375
26376
26377 sip_poke_all_peers();
26378
26379
26380 sip_send_all_registers();
26381
26382 sip_send_all_mwi_subscriptions();
26383
26384 end_poke = time(0);
26385
26386 ast_debug(4, "do_reload finished. peer poke/prune reg contact time = %d sec.\n", (int)(end_poke-start_poke));
26387
26388 ast_debug(4, "--------------- SIP reload done\n");
26389
26390 return 0;
26391 }
26392
26393
26394 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
26395 {
26396
26397 switch (cmd) {
26398 case CLI_INIT:
26399 e->command = "sip reload";
26400 e->usage =
26401 "Usage: sip reload\n"
26402 " Reloads SIP configuration from sip.conf\n";
26403 return NULL;
26404 case CLI_GENERATE:
26405 return NULL;
26406 }
26407
26408 ast_mutex_lock(&sip_reload_lock);
26409 if (sip_reloading)
26410 ast_verbose("Previous SIP reload not yet done\n");
26411 else {
26412 sip_reloading = TRUE;
26413 sip_reloadreason = (a && a->fd) ? CHANNEL_CLI_RELOAD : CHANNEL_MODULE_RELOAD;
26414 }
26415 ast_mutex_unlock(&sip_reload_lock);
26416 restart_monitor();
26417
26418 return CLI_SUCCESS;
26419 }
26420
26421
26422 static int reload(void)
26423 {
26424 if (sip_reload(0, 0, NULL))
26425 return 0;
26426 return 1;
26427 }
26428
26429
26430 static struct ast_cli_entry cli_sip[] = {
26431 AST_CLI_DEFINE(sip_show_channels, "List active SIP channels or subscriptions"),
26432 AST_CLI_DEFINE(sip_show_channelstats, "List statistics for active SIP channels"),
26433 AST_CLI_DEFINE(sip_show_domains, "List our local SIP domains"),
26434 AST_CLI_DEFINE(sip_show_inuse, "List all inuse/limits"),
26435 AST_CLI_DEFINE(sip_show_objects, "List all SIP object allocations"),
26436 AST_CLI_DEFINE(sip_show_peers, "List defined SIP peers"),
26437 AST_CLI_DEFINE(sip_show_registry, "List SIP registration status"),
26438 AST_CLI_DEFINE(sip_unregister, "Unregister (force expiration) a SIP peer from the registry"),
26439 AST_CLI_DEFINE(sip_show_settings, "Show SIP global settings"),
26440 AST_CLI_DEFINE(sip_show_mwi, "Show MWI subscriptions"),
26441 AST_CLI_DEFINE(sip_cli_notify, "Send a notify packet to a SIP peer"),
26442 AST_CLI_DEFINE(sip_show_channel, "Show detailed SIP channel info"),
26443 AST_CLI_DEFINE(sip_show_history, "Show SIP dialog history"),
26444 AST_CLI_DEFINE(sip_show_peer, "Show details on specific SIP peer"),
26445 AST_CLI_DEFINE(sip_show_users, "List defined SIP users"),
26446 AST_CLI_DEFINE(sip_show_user, "Show details on specific SIP user"),
26447 AST_CLI_DEFINE(sip_qualify_peer, "Send an OPTIONS packet to a peer"),
26448 AST_CLI_DEFINE(sip_show_sched, "Present a report on the status of the sched queue"),
26449 AST_CLI_DEFINE(sip_prune_realtime, "Prune cached Realtime users/peers"),
26450 AST_CLI_DEFINE(sip_do_debug, "Enable/Disable SIP debugging"),
26451 AST_CLI_DEFINE(sip_set_history, "Enable/Disable SIP history"),
26452 AST_CLI_DEFINE(sip_reload, "Reload SIP configuration"),
26453 AST_CLI_DEFINE(sip_show_tcp, "List TCP Connections")
26454 };
26455
26456
26457 static int load_module(void)
26458 {
26459 ast_verbose("SIP channel loading...\n");
26460
26461
26462 peers = ao2_t_container_alloc(HASH_PEER_SIZE, peer_hash_cb, peer_cmp_cb, "allocate peers");
26463 peers_by_ip = ao2_t_container_alloc(HASH_PEER_SIZE, peer_iphash_cb, peer_ipcmp_cb, "allocate peers_by_ip");
26464 dialogs = ao2_t_container_alloc(HASH_DIALOG_SIZE, dialog_hash_cb, dialog_cmp_cb, "allocate dialogs");
26465 threadt = ao2_t_container_alloc(HASH_DIALOG_SIZE, threadt_hash_cb, threadt_cmp_cb, "allocate threadt table");
26466
26467 ASTOBJ_CONTAINER_INIT(®l);
26468 ASTOBJ_CONTAINER_INIT(&submwil);
26469
26470 if (!(sched = sched_context_create())) {
26471 ast_log(LOG_ERROR, "Unable to create scheduler context\n");
26472 return AST_MODULE_LOAD_FAILURE;
26473 }
26474
26475 if (!(io = io_context_create())) {
26476 ast_log(LOG_ERROR, "Unable to create I/O context\n");
26477 sched_context_destroy(sched);
26478 return AST_MODULE_LOAD_FAILURE;
26479 }
26480
26481 sip_reloadreason = CHANNEL_MODULE_LOAD;
26482
26483 if(reload_config(sip_reloadreason))
26484 return AST_MODULE_LOAD_DECLINE;
26485
26486
26487
26488
26489
26490 memcpy(&sip_tech_info, &sip_tech, sizeof(sip_tech));
26491 memset((void *) &sip_tech_info.send_digit_begin, 0, sizeof(sip_tech_info.send_digit_begin));
26492
26493
26494 if (ast_channel_register(&sip_tech)) {
26495 ast_log(LOG_ERROR, "Unable to register channel type 'SIP'\n");
26496 io_context_destroy(io);
26497 sched_context_destroy(sched);
26498 return AST_MODULE_LOAD_FAILURE;
26499 }
26500
26501
26502 ast_cli_register_multiple(cli_sip, ARRAY_LEN(cli_sip));
26503
26504
26505 ast_rtp_proto_register(&sip_rtp);
26506
26507
26508 ast_udptl_proto_register(&sip_udptl);
26509
26510
26511 ast_register_application_xml(app_dtmfmode, sip_dtmfmode);
26512 ast_register_application_xml(app_sipaddheader, sip_addheader);
26513 ast_register_application_xml(app_sipremoveheader, sip_removeheader);
26514
26515
26516 ast_custom_function_register(&sip_header_function);
26517 ast_custom_function_register(&sippeer_function);
26518 ast_custom_function_register(&sipchaninfo_function);
26519 ast_custom_function_register(&checksipdomain_function);
26520
26521
26522 ast_manager_register2("SIPpeers", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peers,
26523 "List SIP peers (text format)", mandescr_show_peers);
26524 ast_manager_register2("SIPshowpeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peer,
26525 "Show SIP peer (text format)", mandescr_show_peer);
26526 ast_manager_register2("SIPqualifypeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_qualify_peer,
26527 "Show SIP peer (text format)", mandescr_show_peer);
26528 ast_manager_register2("SIPshowregistry", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_show_registry,
26529 "Show SIP registrations (text format)", mandescr_show_registry);
26530 ast_manager_register2("SIPnotify", EVENT_FLAG_SYSTEM, manager_sipnotify,
26531 "Send a SIP notify", mandescr_sipnotify);
26532 sip_poke_all_peers();
26533 sip_send_all_registers();
26534 sip_send_all_mwi_subscriptions();
26535
26536
26537 restart_monitor();
26538
26539 ast_realtime_require_field(ast_check_realtime("sipregs") ? "sipregs" : "sippeers",
26540 "name", RQ_CHAR, 10,
26541 "ipaddr", RQ_CHAR, 15,
26542 "port", RQ_UINTEGER2, 5,
26543 "regseconds", RQ_INTEGER4, 11,
26544 "defaultuser", RQ_CHAR, 10,
26545 "fullcontact", RQ_CHAR, 35,
26546 "regserver", RQ_CHAR, 20,
26547 "useragent", RQ_CHAR, 20,
26548 "lastms", RQ_INTEGER4, 11,
26549 SENTINEL);
26550
26551 return AST_MODULE_LOAD_SUCCESS;
26552 }
26553
26554
26555 static int unload_module(void)
26556 {
26557 struct sip_pvt *p;
26558 struct sip_threadinfo *th;
26559 struct ast_context *con;
26560 struct ao2_iterator i;
26561
26562 ast_sched_dump(sched);
26563
26564
26565 ast_channel_unregister(&sip_tech);
26566
26567
26568 ast_custom_function_unregister(&sipchaninfo_function);
26569 ast_custom_function_unregister(&sippeer_function);
26570 ast_custom_function_unregister(&sip_header_function);
26571 ast_custom_function_unregister(&checksipdomain_function);
26572
26573
26574 ast_unregister_application(app_dtmfmode);
26575 ast_unregister_application(app_sipaddheader);
26576 ast_unregister_application(app_sipremoveheader);
26577
26578
26579 ast_cli_unregister_multiple(cli_sip, ARRAY_LEN(cli_sip));
26580
26581
26582 ast_rtp_proto_unregister(&sip_rtp);
26583
26584
26585 ast_udptl_proto_unregister(&sip_udptl);
26586
26587
26588 ast_manager_unregister("SIPpeers");
26589 ast_manager_unregister("SIPshowpeer");
26590 ast_manager_unregister("SIPqualifypeer");
26591 ast_manager_unregister("SIPshowregistry");
26592 ast_manager_unregister("SIPnotify");
26593
26594
26595 if (sip_tcp_desc.master)
26596 ast_tcptls_server_stop(&sip_tcp_desc);
26597 if (sip_tls_desc.master)
26598 ast_tcptls_server_stop(&sip_tls_desc);
26599
26600
26601 i = ao2_iterator_init(threadt, 0);
26602 while ((th = ao2_t_iterator_next(&i, "iterate through tcp threads for 'sip show tcp'"))) {
26603 pthread_t thread = th->threadid;
26604 th->stop = 1;
26605 pthread_kill(thread, SIGURG);
26606 pthread_join(thread, NULL);
26607 ao2_t_ref(th, -1, "decrement ref from iterator");
26608 }
26609 ao2_iterator_destroy(&i);
26610
26611
26612 i = ao2_iterator_init(dialogs, 0);
26613 while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
26614 if (p->owner)
26615 ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
26616 ao2_t_ref(p, -1, "toss dialog ptr from iterator_next");
26617 }
26618 ao2_iterator_destroy(&i);
26619
26620 ast_mutex_lock(&monlock);
26621 if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP) && (monitor_thread != AST_PTHREADT_NULL)) {
26622 pthread_cancel(monitor_thread);
26623 pthread_kill(monitor_thread, SIGURG);
26624 pthread_join(monitor_thread, NULL);
26625 }
26626 monitor_thread = AST_PTHREADT_STOP;
26627 ast_mutex_unlock(&monlock);
26628
26629
26630 i = ao2_iterator_init(dialogs, 0);
26631 while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
26632 dialog_unlink_all(p, TRUE, TRUE);
26633 ao2_t_ref(p, -1, "throw away iterator result");
26634 }
26635 ao2_iterator_destroy(&i);
26636
26637
26638 ast_free_ha(localaddr);
26639
26640 clear_realm_authentication(authl);
26641
26642
26643 if (default_tls_cfg.certfile)
26644 ast_free(default_tls_cfg.certfile);
26645 if (default_tls_cfg.cipher)
26646 ast_free(default_tls_cfg.cipher);
26647 if (default_tls_cfg.cafile)
26648 ast_free(default_tls_cfg.cafile);
26649 if (default_tls_cfg.capath)
26650 ast_free(default_tls_cfg.capath);
26651
26652 ASTOBJ_CONTAINER_DESTROYALL(®l, sip_registry_destroy);
26653 ASTOBJ_CONTAINER_DESTROY(®l);
26654 ASTOBJ_CONTAINER_DESTROYALL(&submwil, sip_subscribe_mwi_destroy);
26655 ASTOBJ_CONTAINER_DESTROY(&submwil);
26656
26657 ao2_t_ref(peers, -1, "unref the peers table");
26658 ao2_t_ref(peers_by_ip, -1, "unref the peers_by_ip table");
26659 ao2_t_ref(dialogs, -1, "unref the dialogs table");
26660 ao2_t_ref(threadt, -1, "unref the thread table");
26661
26662 clear_sip_domains();
26663 ast_free_ha(global_contact_ha);
26664 close(sipsock);
26665 sched_context_destroy(sched);
26666 con = ast_context_find(used_context);
26667 if (con)
26668 ast_context_destroy(con, "SIP");
26669 ast_unload_realtime("sipregs");
26670 ast_unload_realtime("sippeers");
26671
26672 return 0;
26673 }
26674
26675 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Session Initiation Protocol (SIP)",
26676 .load = load_module,
26677 .unload = unload_module,
26678 .reload = reload,
26679 );