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: 261315 $")
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
00504
00505
00506 #define EXPIRY_GUARD_SECS 15
00507 #define EXPIRY_GUARD_LIMIT 30
00508
00509 #define EXPIRY_GUARD_MIN 500
00510
00511
00512
00513 #define EXPIRY_GUARD_PCT 0.20
00514
00515 #define DEFAULT_EXPIRY 900
00516
00517 static int min_expiry = DEFAULT_MIN_EXPIRY;
00518 static int max_expiry = DEFAULT_MAX_EXPIRY;
00519 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
00520 static int mwi_expiry = DEFAULT_MWI_EXPIRY;
00521
00522 #define DEFAULT_QUALIFY_GAP 100
00523 #define DEFAULT_QUALIFY_PEERS 1
00524
00525
00526 #define CALLERID_UNKNOWN "Anonymous"
00527 #define FROMDOMAIN_INVALID "anonymous.invalid"
00528
00529 #define DEFAULT_MAXMS 2000
00530 #define DEFAULT_QUALIFYFREQ 60 * 1000
00531 #define DEFAULT_FREQ_NOTOK 10 * 1000
00532
00533 #define DEFAULT_RETRANS 1000
00534 #define MAX_RETRANS 6
00535 #define DEFAULT_TIMER_T1 500
00536 #define SIP_TRANS_TIMEOUT 64 * DEFAULT_TIMER_T1
00537
00538
00539 #define DEFAULT_TRANS_TIMEOUT -1
00540 #define PROVIS_KEEPALIVE_TIMEOUT 60000
00541 #define MAX_AUTHTRIES 3
00542
00543 #define SIP_MAX_HEADERS 64
00544 #define SIP_MAX_LINES 64
00545 #define SIP_MIN_PACKET 4096
00546 #define MAX_HISTORY_ENTRIES 50
00547
00548 #define INITIAL_CSEQ 101
00549
00550 #define DEFAULT_MAX_SE 1800
00551 #define DEFAULT_MIN_SE 90
00552
00553 #define SDP_MAX_RTPMAP_CODECS 32
00554
00555
00556 static struct ast_jb_conf default_jbconf =
00557 {
00558 .flags = 0,
00559 .max_size = -1,
00560 .resync_threshold = -1,
00561 .impl = "",
00562 .target_extra = -1,
00563 };
00564 static struct ast_jb_conf global_jbconf;
00565
00566 static const char config[] = "sip.conf";
00567 static const char notify_config[] = "sip_notify.conf";
00568
00569 #define RTP 1
00570 #define NO_RTP 0
00571
00572
00573
00574
00575
00576 enum transfermodes {
00577 TRANSFER_OPENFORALL,
00578 TRANSFER_CLOSED,
00579 };
00580
00581
00582
00583 enum sip_result {
00584 AST_SUCCESS = 0,
00585 AST_FAILURE = -1,
00586 };
00587
00588
00589
00590
00591 enum invitestates {
00592 INV_NONE = 0,
00593 INV_CALLING = 1,
00594 INV_PROCEEDING = 2,
00595 INV_EARLY_MEDIA = 3,
00596 INV_COMPLETED = 4,
00597 INV_CONFIRMED = 5,
00598 INV_TERMINATED = 6,
00599
00600 INV_CANCELLED = 7,
00601 };
00602
00603
00604
00605 static const struct invstate2stringtable {
00606 const enum invitestates state;
00607 const char *desc;
00608 } invitestate2string[] = {
00609 {INV_NONE, "None" },
00610 {INV_CALLING, "Calling (Trying)"},
00611 {INV_PROCEEDING, "Proceeding "},
00612 {INV_EARLY_MEDIA, "Early media"},
00613 {INV_COMPLETED, "Completed (done)"},
00614 {INV_CONFIRMED, "Confirmed (up)"},
00615 {INV_TERMINATED, "Done"},
00616 {INV_CANCELLED, "Cancelled"}
00617 };
00618
00619
00620
00621
00622 enum xmittype {
00623 XMIT_CRITICAL = 2,
00624
00625 XMIT_RELIABLE = 1,
00626 XMIT_UNRELIABLE = 0,
00627 };
00628
00629
00630 enum parse_register_result {
00631 PARSE_REGISTER_DENIED,
00632 PARSE_REGISTER_FAILED,
00633 PARSE_REGISTER_UPDATE,
00634 PARSE_REGISTER_QUERY,
00635 };
00636
00637
00638 enum subscriptiontype {
00639 NONE = 0,
00640 XPIDF_XML,
00641 DIALOG_INFO_XML,
00642 CPIM_PIDF_XML,
00643 PIDF_XML,
00644 MWI_NOTIFICATION
00645 };
00646
00647
00648
00649
00650
00651
00652 static const struct cfsubscription_types {
00653 enum subscriptiontype type;
00654 const char * const event;
00655 const char * const mediatype;
00656 const char * const text;
00657 } subscription_types[] = {
00658 { NONE, "-", "unknown", "unknown" },
00659
00660 { DIALOG_INFO_XML, "dialog", "application/dialog-info+xml", "dialog-info+xml" },
00661 { CPIM_PIDF_XML, "presence", "application/cpim-pidf+xml", "cpim-pidf+xml" },
00662 { PIDF_XML, "presence", "application/pidf+xml", "pidf+xml" },
00663 { XPIDF_XML, "presence", "application/xpidf+xml", "xpidf+xml" },
00664 { MWI_NOTIFICATION, "message-summary", "application/simple-message-summary", "mwi" }
00665 };
00666
00667
00668
00669
00670
00671
00672
00673 enum sip_auth_type {
00674 PROXY_AUTH = 407,
00675 WWW_AUTH = 401,
00676 };
00677
00678
00679 enum check_auth_result {
00680 AUTH_DONT_KNOW = -100,
00681
00682
00683 AUTH_SUCCESSFUL = 0,
00684 AUTH_CHALLENGE_SENT = 1,
00685 AUTH_SECRET_FAILED = -1,
00686 AUTH_USERNAME_MISMATCH = -2,
00687 AUTH_NOT_FOUND = -3,
00688 AUTH_FAKE_AUTH = -4,
00689 AUTH_UNKNOWN_DOMAIN = -5,
00690 AUTH_PEER_NOT_DYNAMIC = -6,
00691 AUTH_ACL_FAILED = -7,
00692 AUTH_BAD_TRANSPORT = -8,
00693 };
00694
00695
00696 enum sipregistrystate {
00697 REG_STATE_UNREGISTERED = 0,
00698
00699
00700
00701
00702 REG_STATE_REGSENT,
00703
00704
00705
00706
00707 REG_STATE_AUTHSENT,
00708
00709
00710
00711
00712 REG_STATE_REGISTERED,
00713
00714 REG_STATE_REJECTED,
00715
00716
00717
00718
00719
00720 REG_STATE_TIMEOUT,
00721
00722
00723 REG_STATE_NOAUTH,
00724
00725
00726 REG_STATE_FAILED,
00727
00728 };
00729
00730
00731 enum st_mode {
00732 SESSION_TIMER_MODE_INVALID = 0,
00733 SESSION_TIMER_MODE_ACCEPT,
00734 SESSION_TIMER_MODE_ORIGINATE,
00735 SESSION_TIMER_MODE_REFUSE
00736 };
00737
00738
00739 enum st_refresher {
00740 SESSION_TIMER_REFRESHER_AUTO,
00741 SESSION_TIMER_REFRESHER_UAC,
00742 SESSION_TIMER_REFRESHER_UAS
00743 };
00744
00745
00746
00747
00748 enum sip_transport {
00749 SIP_TRANSPORT_UDP = 1,
00750 SIP_TRANSPORT_TCP = 1 << 1,
00751 SIP_TRANSPORT_TLS = 1 << 2,
00752 };
00753
00754
00755
00756
00757
00758
00759
00760
00761 struct sip_proxy {
00762 char name[MAXHOSTNAMELEN];
00763 struct sockaddr_in ip;
00764 time_t last_dnsupdate;
00765 enum sip_transport transport;
00766 int force;
00767
00768 };
00769
00770
00771 struct __show_chan_arg {
00772 int fd;
00773 int subscriptions;
00774 int numchans;
00775 };
00776
00777
00778
00779 enum can_create_dialog {
00780 CAN_NOT_CREATE_DIALOG,
00781 CAN_CREATE_DIALOG,
00782 CAN_CREATE_DIALOG_UNSUPPORTED_METHOD,
00783 };
00784
00785
00786
00787
00788
00789
00790
00791
00792
00793
00794
00795 enum sipmethod {
00796 SIP_UNKNOWN,
00797 SIP_RESPONSE,
00798 SIP_REGISTER,
00799 SIP_OPTIONS,
00800 SIP_NOTIFY,
00801 SIP_INVITE,
00802 SIP_ACK,
00803 SIP_PRACK,
00804 SIP_BYE,
00805 SIP_REFER,
00806 SIP_SUBSCRIBE,
00807 SIP_MESSAGE,
00808 SIP_UPDATE,
00809 SIP_INFO,
00810 SIP_CANCEL,
00811 SIP_PUBLISH,
00812 SIP_PING,
00813 };
00814
00815
00816 enum notifycid_setting {
00817 DISABLED = 0,
00818 ENABLED = 1,
00819 IGNORE_CONTEXT = 2,
00820 };
00821
00822
00823
00824
00825
00826 static const struct cfsip_methods {
00827 enum sipmethod id;
00828 int need_rtp;
00829 char * const text;
00830 enum can_create_dialog can_create;
00831 } sip_methods[] = {
00832 { SIP_UNKNOWN, RTP, "-UNKNOWN-", CAN_CREATE_DIALOG },
00833 { SIP_RESPONSE, NO_RTP, "SIP/2.0", CAN_NOT_CREATE_DIALOG },
00834 { SIP_REGISTER, NO_RTP, "REGISTER", CAN_CREATE_DIALOG },
00835 { SIP_OPTIONS, NO_RTP, "OPTIONS", CAN_CREATE_DIALOG },
00836 { SIP_NOTIFY, NO_RTP, "NOTIFY", CAN_CREATE_DIALOG },
00837 { SIP_INVITE, RTP, "INVITE", CAN_CREATE_DIALOG },
00838 { SIP_ACK, NO_RTP, "ACK", CAN_NOT_CREATE_DIALOG },
00839 { SIP_PRACK, NO_RTP, "PRACK", CAN_NOT_CREATE_DIALOG },
00840 { SIP_BYE, NO_RTP, "BYE", CAN_NOT_CREATE_DIALOG },
00841 { SIP_REFER, NO_RTP, "REFER", CAN_CREATE_DIALOG },
00842 { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE", CAN_CREATE_DIALOG },
00843 { SIP_MESSAGE, NO_RTP, "MESSAGE", CAN_CREATE_DIALOG },
00844 { SIP_UPDATE, NO_RTP, "UPDATE", CAN_NOT_CREATE_DIALOG },
00845 { SIP_INFO, NO_RTP, "INFO", CAN_NOT_CREATE_DIALOG },
00846 { SIP_CANCEL, NO_RTP, "CANCEL", CAN_NOT_CREATE_DIALOG },
00847 { SIP_PUBLISH, NO_RTP, "PUBLISH", CAN_CREATE_DIALOG_UNSUPPORTED_METHOD },
00848 { SIP_PING, NO_RTP, "PING", CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
00849 };
00850
00851 static unsigned int chan_idx;
00852
00853
00854
00855
00856
00857
00858
00859
00860
00861
00862
00863 #define SUPPORTED 1
00864 #define NOT_SUPPORTED 0
00865
00866
00867 #define SIP_OPT_REPLACES (1 << 0)
00868 #define SIP_OPT_100REL (1 << 1)
00869 #define SIP_OPT_TIMER (1 << 2)
00870 #define SIP_OPT_EARLY_SESSION (1 << 3)
00871 #define SIP_OPT_JOIN (1 << 4)
00872 #define SIP_OPT_PATH (1 << 5)
00873 #define SIP_OPT_PREF (1 << 6)
00874 #define SIP_OPT_PRECONDITION (1 << 7)
00875 #define SIP_OPT_PRIVACY (1 << 8)
00876 #define SIP_OPT_SDP_ANAT (1 << 9)
00877 #define SIP_OPT_SEC_AGREE (1 << 10)
00878 #define SIP_OPT_EVENTLIST (1 << 11)
00879 #define SIP_OPT_GRUU (1 << 12)
00880 #define SIP_OPT_TARGET_DIALOG (1 << 13)
00881 #define SIP_OPT_NOREFERSUB (1 << 14)
00882 #define SIP_OPT_HISTINFO (1 << 15)
00883 #define SIP_OPT_RESPRIORITY (1 << 16)
00884 #define SIP_OPT_FROMCHANGE (1 << 17)
00885 #define SIP_OPT_RECLISTINV (1 << 18)
00886 #define SIP_OPT_RECLISTSUB (1 << 19)
00887 #define SIP_OPT_OUTBOUND (1 << 20)
00888 #define SIP_OPT_UNKNOWN (1 << 21)
00889
00890
00891
00892
00893 static const struct cfsip_options {
00894 int id;
00895 int supported;
00896 char * const text;
00897 } sip_options[] = {
00898
00899 { SIP_OPT_100REL, NOT_SUPPORTED, "100rel" },
00900
00901 { SIP_OPT_EARLY_SESSION, NOT_SUPPORTED, "early-session" },
00902
00903 { SIP_OPT_EVENTLIST, NOT_SUPPORTED, "eventlist" },
00904
00905 { SIP_OPT_FROMCHANGE, NOT_SUPPORTED, "from-change" },
00906
00907 { SIP_OPT_GRUU, NOT_SUPPORTED, "gruu" },
00908
00909 { SIP_OPT_HISTINFO, NOT_SUPPORTED, "histinfo" },
00910
00911 { SIP_OPT_JOIN, NOT_SUPPORTED, "join" },
00912
00913 { SIP_OPT_NOREFERSUB, NOT_SUPPORTED, "norefersub" },
00914
00915 { SIP_OPT_OUTBOUND, NOT_SUPPORTED, "outbound" },
00916
00917 { SIP_OPT_PATH, NOT_SUPPORTED, "path" },
00918
00919 { SIP_OPT_PREF, NOT_SUPPORTED, "pref" },
00920
00921 { SIP_OPT_PRECONDITION, NOT_SUPPORTED, "precondition" },
00922
00923 { SIP_OPT_PRIVACY, NOT_SUPPORTED, "privacy" },
00924
00925 { SIP_OPT_RECLISTINV, NOT_SUPPORTED, "recipient-list-invite" },
00926
00927 { SIP_OPT_RECLISTSUB, NOT_SUPPORTED, "recipient-list-subscribe" },
00928
00929 { SIP_OPT_REPLACES, SUPPORTED, "replaces" },
00930
00931 { SIP_OPT_REPLACES, SUPPORTED, "replace" },
00932
00933 { SIP_OPT_RESPRIORITY, NOT_SUPPORTED, "resource-priority" },
00934
00935 { SIP_OPT_SEC_AGREE, NOT_SUPPORTED, "sec_agree" },
00936
00937 { SIP_OPT_SDP_ANAT, NOT_SUPPORTED, "sdp-anat" },
00938
00939 { SIP_OPT_TIMER, SUPPORTED, "timer" },
00940
00941 { SIP_OPT_TARGET_DIALOG,NOT_SUPPORTED, "tdialog" },
00942 };
00943
00944
00945
00946
00947
00948
00949 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY, INFO"
00950
00951
00952
00953
00954
00955
00956 #define SUPPORTED_EXTENSIONS "replaces, timer"
00957
00958
00959 #define STANDARD_SIP_PORT 5060
00960
00961 #define STANDARD_TLS_PORT 5061
00962
00963
00964
00965
00966
00967
00968
00969
00970
00971
00972
00973
00974
00975
00976
00977
00978
00979 #define DEFAULT_CONTEXT "default"
00980 #define DEFAULT_MOHINTERPRET "default"
00981 #define DEFAULT_MOHSUGGEST ""
00982 #define DEFAULT_VMEXTEN "asterisk"
00983 #define DEFAULT_CALLERID "asterisk"
00984 #define DEFAULT_NOTIFYMIME "application/simple-message-summary"
00985 #define DEFAULT_ALLOWGUEST TRUE
00986 #define DEFAULT_RTPKEEPALIVE 0
00987 #define DEFAULT_CALLCOUNTER FALSE
00988 #define DEFAULT_SRVLOOKUP TRUE
00989 #define DEFAULT_COMPACTHEADERS FALSE
00990 #define DEFAULT_TOS_SIP 0
00991 #define DEFAULT_TOS_AUDIO 0
00992 #define DEFAULT_TOS_VIDEO 0
00993 #define DEFAULT_TOS_TEXT 0
00994 #define DEFAULT_COS_SIP 4
00995 #define DEFAULT_COS_AUDIO 5
00996 #define DEFAULT_COS_VIDEO 6
00997 #define DEFAULT_COS_TEXT 5
00998 #define DEFAULT_ALLOW_EXT_DOM TRUE
00999 #define DEFAULT_REALM "asterisk"
01000 #define DEFAULT_NOTIFYRINGING TRUE
01001 #define DEFAULT_NOTIFYCID DISABLED
01002 #define DEFAULT_PEDANTIC FALSE
01003 #define DEFAULT_AUTOCREATEPEER FALSE
01004 #define DEFAULT_MATCHEXTERNIPLOCALLY FALSE
01005 #define DEFAULT_QUALIFY FALSE
01006 #define DEFAULT_CALLEVENTS FALSE
01007 #define DEFAULT_ALWAYSAUTHREJECT FALSE
01008 #define DEFAULT_REGEXTENONQUALIFY FALSE
01009 #define DEFAULT_T1MIN 100
01010 #define DEFAULT_MAX_CALL_BITRATE (384)
01011 #ifndef DEFAULT_USERAGENT
01012 #define DEFAULT_USERAGENT "Asterisk PBX"
01013 #define DEFAULT_SDPSESSION "Asterisk PBX"
01014 #define DEFAULT_SDPOWNER "root"
01015 #endif
01016
01017
01018
01019
01020
01021
01022
01023 static char default_language[MAX_LANGUAGE];
01024 static char default_callerid[AST_MAX_EXTENSION];
01025 static char default_fromdomain[AST_MAX_EXTENSION];
01026 static char default_notifymime[AST_MAX_EXTENSION];
01027 static int default_qualify;
01028 static char default_vmexten[AST_MAX_EXTENSION];
01029 static char default_mohinterpret[MAX_MUSICCLASS];
01030 static char default_mohsuggest[MAX_MUSICCLASS];
01031
01032 static char default_parkinglot[AST_MAX_CONTEXT];
01033 static int default_maxcallbitrate;
01034 static struct ast_codec_pref default_prefs;
01035 static unsigned int default_transports;
01036 static unsigned int default_primary_transport;
01037
01038
01039
01040
01041
01042
01043
01044
01045
01046
01047
01048
01049
01050 struct sip_settings {
01051 int peer_rtupdate;
01052 int rtsave_sysname;
01053 int ignore_regexpire;
01054 int rtautoclear;
01055 int directrtpsetup;
01056 int pedanticsipchecking;
01057 int autocreatepeer;
01058 int srvlookup;
01059 int allowguest;
01060 int alwaysauthreject;
01061 int compactheaders;
01062 int allow_external_domains;
01063 int callevents;
01064 int regextenonqualify;
01065 int matchexterniplocally;
01066 int notifyringing;
01067 int notifyhold;
01068 enum notifycid_setting notifycid;
01069 enum transfermodes allowtransfer;
01070 int allowsubscribe;
01071
01072 char realm[MAXHOSTNAMELEN];
01073 struct sip_proxy outboundproxy;
01074 char default_context[AST_MAX_CONTEXT];
01075 char default_subscribecontext[AST_MAX_CONTEXT];
01076 };
01077
01078 static struct sip_settings sip_cfg;
01079
01080 static int global_match_auth_username;
01081
01082 static int global_relaxdtmf;
01083 static int global_prematuremediafilter;
01084 static int global_relaxdtmf;
01085 static int global_rtptimeout;
01086 static int global_rtpholdtimeout;
01087 static int global_rtpkeepalive;
01088 static int global_reg_timeout;
01089 static int global_regattempts_max;
01090 static int global_shrinkcallerid;
01091 static int global_callcounter;
01092
01093
01094 static unsigned int global_tos_sip;
01095 static unsigned int global_tos_audio;
01096 static unsigned int global_tos_video;
01097 static unsigned int global_tos_text;
01098 static unsigned int global_cos_sip;
01099 static unsigned int global_cos_audio;
01100 static unsigned int global_cos_video;
01101 static unsigned int global_cos_text;
01102 static int recordhistory;
01103 static int dumphistory;
01104 static char global_regcontext[AST_MAX_CONTEXT];
01105 static char global_useragent[AST_MAX_EXTENSION];
01106 static char global_sdpsession[AST_MAX_EXTENSION];
01107 static char global_sdpowner[AST_MAX_EXTENSION];
01108 static int global_authfailureevents;
01109 static int global_t1;
01110 static int global_t1min;
01111 static int global_timer_b;
01112 static int global_autoframing;
01113 static int global_qualifyfreq;
01114 static int global_qualify_gap;
01115 static int global_qualify_peers;
01116
01117
01118
01119 static int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
01120
01121 static enum st_mode global_st_mode;
01122 static enum st_refresher global_st_refresher;
01123 static int global_min_se;
01124 static int global_max_se;
01125
01126 static int global_dynamic_exclude_static = 0;
01127
01128
01129
01130 static struct ast_ha *global_contact_ha = NULL;
01131
01132
01133
01134
01135 static int speerobjs = 0;
01136 static int rpeerobjs = 0;
01137 static int apeerobjs = 0;
01138 static int regobjs = 0;
01139
01140
01141 static struct ast_flags global_flags[2] = {{0}};
01142 static int global_t38_maxdatagram;
01143
01144 static char used_context[AST_MAX_CONTEXT];
01145
01146
01147 AST_MUTEX_DEFINE_STATIC(netlock);
01148
01149
01150
01151 AST_MUTEX_DEFINE_STATIC(monlock);
01152
01153 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
01154
01155
01156
01157 static pthread_t monitor_thread = AST_PTHREADT_NULL;
01158
01159 static int sip_reloading = FALSE;
01160 static enum channelreloadreason sip_reloadreason;
01161
01162 static struct sched_context *sched;
01163 static struct io_context *io;
01164 static int *sipsock_read_id;
01165
01166 #define DEC_CALL_LIMIT 0
01167 #define INC_CALL_LIMIT 1
01168 #define DEC_CALL_RINGING 2
01169 #define INC_CALL_RINGING 3
01170
01171
01172 struct sip_socket {
01173 enum sip_transport type;
01174 int fd;
01175 uint16_t port;
01176 struct ast_tcptls_session_instance *tcptls_session;
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
01203 struct sip_request {
01204 ptrdiff_t rlPart1;
01205 ptrdiff_t rlPart2;
01206 int len;
01207 int headers;
01208 int method;
01209 int lines;
01210 unsigned int sdp_start;
01211 unsigned int sdp_count;
01212 char debug;
01213 char has_to_tag;
01214 char ignore;
01215
01216 ptrdiff_t header[SIP_MAX_HEADERS];
01217
01218 ptrdiff_t line[SIP_MAX_LINES];
01219 struct ast_str *data;
01220
01221 struct sip_socket socket;
01222 AST_LIST_ENTRY(sip_request) next;
01223 };
01224
01225
01226
01227
01228
01229
01230
01231
01232 #define REQ_OFFSET_TO_STR(req,offset) (ast_str_buffer((req)->data) + ((req)->offset))
01233
01234
01235 struct sip_dual {
01236 struct ast_channel *chan1;
01237 struct ast_channel *chan2;
01238 struct sip_request req;
01239 int seqno;
01240 };
01241
01242 struct sip_pkt;
01243
01244
01245 struct sip_invite_param {
01246 int addsipheaders;
01247 const char *uri_options;
01248 const char *vxml_url;
01249 char *auth;
01250 char *authheader;
01251 enum sip_auth_type auth_type;
01252 const char *replaces;
01253 int transfer;
01254 };
01255
01256
01257 struct sip_route {
01258 struct sip_route *next;
01259 char hop[0];
01260 };
01261
01262
01263 enum domain_mode {
01264 SIP_DOMAIN_AUTO,
01265 SIP_DOMAIN_CONFIG,
01266 };
01267
01268
01269
01270
01271
01272 struct domain {
01273 char domain[MAXHOSTNAMELEN];
01274 char context[AST_MAX_EXTENSION];
01275 enum domain_mode mode;
01276 AST_LIST_ENTRY(domain) list;
01277 };
01278
01279 static AST_LIST_HEAD_STATIC(domain_list, domain);
01280
01281
01282
01283 struct sip_history {
01284 AST_LIST_ENTRY(sip_history) list;
01285 char event[0];
01286 };
01287
01288 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history);
01289
01290
01291 struct sip_auth {
01292 char realm[AST_MAX_EXTENSION];
01293 char username[256];
01294 char secret[256];
01295 char md5secret[256];
01296 struct sip_auth *next;
01297 };
01298
01299
01300
01301
01302
01303
01304
01305
01306
01307
01308
01309 #define SIP_OUTGOING (1 << 0)
01310 #define SIP_RINGING (1 << 2)
01311 #define SIP_PROGRESS_SENT (1 << 3)
01312 #define SIP_NEEDREINVITE (1 << 4)
01313 #define SIP_PENDINGBYE (1 << 5)
01314 #define SIP_GOTREFER (1 << 6)
01315 #define SIP_CALL_LIMIT (1 << 7)
01316 #define SIP_INC_COUNT (1 << 8)
01317 #define SIP_INC_RINGING (1 << 9)
01318 #define SIP_DEFER_BYE_ON_TRANSFER (1 << 10)
01319
01320 #define SIP_PROMISCREDIR (1 << 11)
01321 #define SIP_TRUSTRPID (1 << 12)
01322 #define SIP_USEREQPHONE (1 << 13)
01323 #define SIP_USECLIENTCODE (1 << 14)
01324
01325
01326 #define SIP_DTMF (7 << 15)
01327 #define SIP_DTMF_RFC2833 (0 << 15)
01328 #define SIP_DTMF_INBAND (1 << 15)
01329 #define SIP_DTMF_INFO (2 << 15)
01330 #define SIP_DTMF_AUTO (3 << 15)
01331 #define SIP_DTMF_SHORTINFO (4 << 15)
01332
01333
01334 #define SIP_NAT (3 << 18)
01335 #define SIP_NAT_NEVER (0 << 18)
01336 #define SIP_NAT_RFC3581 (1 << 18)
01337 #define SIP_NAT_ROUTE (2 << 18)
01338 #define SIP_NAT_ALWAYS (3 << 18)
01339
01340
01341 #define SIP_REINVITE (7 << 20)
01342 #define SIP_REINVITE_NONE (0 << 20)
01343 #define SIP_DIRECT_MEDIA (1 << 20)
01344 #define SIP_DIRECT_MEDIA_NAT (2 << 20)
01345 #define SIP_REINVITE_UPDATE (4 << 20)
01346
01347
01348 #define SIP_INSECURE (3 << 23)
01349 #define SIP_INSECURE_NONE (0 << 23)
01350 #define SIP_INSECURE_PORT (1 << 23)
01351 #define SIP_INSECURE_INVITE (1 << 24)
01352
01353
01354 #define SIP_PROG_INBAND (3 << 25)
01355 #define SIP_PROG_INBAND_NEVER (0 << 25)
01356 #define SIP_PROG_INBAND_NO (1 << 25)
01357 #define SIP_PROG_INBAND_YES (2 << 25)
01358
01359 #define SIP_SENDRPID (1 << 29)
01360 #define SIP_G726_NONSTANDARD (1 << 31)
01361
01362
01363 #define SIP_FLAGS_TO_COPY \
01364 (SIP_PROMISCREDIR | SIP_TRUSTRPID | SIP_SENDRPID | SIP_DTMF | SIP_REINVITE | \
01365 SIP_PROG_INBAND | SIP_USECLIENTCODE | SIP_NAT | SIP_G726_NONSTANDARD | \
01366 SIP_USEREQPHONE | SIP_INSECURE)
01367
01368
01369
01370
01371
01372
01373 #define SIP_PAGE2_RTCACHEFRIENDS (1 << 0)
01374 #define SIP_PAGE2_RTAUTOCLEAR (1 << 2)
01375 #define SIP_PAGE2_HAVEPEERCONTEXT (1 << 3)
01376
01377 #define SIP_PAGE2_STATECHANGEQUEUE (1 << 9)
01378
01379 #define SIP_PAGE2_RPORT_PRESENT (1 << 10)
01380 #define SIP_PAGE2_VIDEOSUPPORT (1 << 14)
01381 #define SIP_PAGE2_TEXTSUPPORT (1 << 15)
01382 #define SIP_PAGE2_ALLOWSUBSCRIBE (1 << 16)
01383 #define SIP_PAGE2_ALLOWOVERLAP (1 << 17)
01384 #define SIP_PAGE2_SUBSCRIBEMWIONLY (1 << 18)
01385 #define SIP_PAGE2_IGNORESDPVERSION (1 << 19)
01386
01387 #define SIP_PAGE2_T38SUPPORT (3 << 20)
01388 #define SIP_PAGE2_T38SUPPORT_UDPTL (1 << 20)
01389 #define SIP_PAGE2_T38SUPPORT_UDPTL_FEC (2 << 20)
01390 #define SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY (3 << 20)
01391
01392 #define SIP_PAGE2_CALL_ONHOLD (3 << 23)
01393 #define SIP_PAGE2_CALL_ONHOLD_ACTIVE (1 << 23)
01394 #define SIP_PAGE2_CALL_ONHOLD_ONEDIR (2 << 23)
01395 #define SIP_PAGE2_CALL_ONHOLD_INACTIVE (3 << 23)
01396
01397 #define SIP_PAGE2_RFC2833_COMPENSATE (1 << 25)
01398 #define SIP_PAGE2_BUGGY_MWI (1 << 26)
01399 #define SIP_PAGE2_DIALOG_ESTABLISHED (1 << 27)
01400 #define SIP_PAGE2_FAX_DETECT (3 << 28)
01401 #define SIP_PAGE2_FAX_DETECT_CNG (1 << 28)
01402 #define SIP_PAGE2_FAX_DETECT_T38 (2 << 28)
01403 #define SIP_PAGE2_FAX_DETECT_BOTH (3 << 28)
01404 #define SIP_PAGE2_REGISTERTRYING (1 << 29)
01405 #define SIP_PAGE2_UDPTL_DESTINATION (1 << 30)
01406 #define SIP_PAGE2_VIDEOSUPPORT_ALWAYS (1 << 31)
01407
01408 #define SIP_PAGE2_FLAGS_TO_COPY \
01409 (SIP_PAGE2_ALLOWSUBSCRIBE | SIP_PAGE2_ALLOWOVERLAP | SIP_PAGE2_IGNORESDPVERSION | \
01410 SIP_PAGE2_VIDEOSUPPORT | SIP_PAGE2_T38SUPPORT | SIP_PAGE2_RFC2833_COMPENSATE | \
01411 SIP_PAGE2_BUGGY_MWI | SIP_PAGE2_TEXTSUPPORT | SIP_PAGE2_FAX_DETECT | \
01412 SIP_PAGE2_UDPTL_DESTINATION | SIP_PAGE2_VIDEOSUPPORT_ALWAYS | \
01413 SIP_PAGE2_HAVEPEERCONTEXT)
01414
01415
01416
01417
01418
01419
01420
01421
01422
01423 enum sip_debug_e {
01424 sip_debug_none = 0,
01425 sip_debug_config = 1,
01426 sip_debug_console = 2,
01427 };
01428
01429 static enum sip_debug_e sipdebug;
01430
01431
01432
01433
01434
01435 static int sipdebug_text;
01436
01437
01438 enum t38state {
01439 T38_DISABLED = 0,
01440 T38_LOCAL_REINVITE,
01441 T38_PEER_REINVITE,
01442 T38_ENABLED
01443 };
01444
01445
01446 struct t38properties {
01447 enum t38state state;
01448 struct ast_control_t38_parameters our_parms;
01449 struct ast_control_t38_parameters their_parms;
01450 };
01451
01452
01453 enum referstatus {
01454 REFER_IDLE,
01455 REFER_SENT,
01456 REFER_RECEIVED,
01457 REFER_CONFIRMED,
01458 REFER_ACCEPTED,
01459 REFER_RINGING,
01460 REFER_200OK,
01461 REFER_FAILED,
01462 REFER_NOAUTH
01463 };
01464
01465
01466
01467
01468
01469
01470 struct _map_x_s {
01471 int x;
01472 const char *s;
01473 };
01474
01475 static const struct _map_x_s referstatusstrings[] = {
01476 { REFER_IDLE, "<none>" },
01477 { REFER_SENT, "Request sent" },
01478 { REFER_RECEIVED, "Request received" },
01479 { REFER_CONFIRMED, "Confirmed" },
01480 { REFER_ACCEPTED, "Accepted" },
01481 { REFER_RINGING, "Target ringing" },
01482 { REFER_200OK, "Done" },
01483 { REFER_FAILED, "Failed" },
01484 { REFER_NOAUTH, "Failed - auth failure" },
01485 { -1, NULL}
01486 };
01487
01488
01489
01490 struct sip_refer {
01491 char refer_to[AST_MAX_EXTENSION];
01492 char refer_to_domain[AST_MAX_EXTENSION];
01493 char refer_to_urioption[AST_MAX_EXTENSION];
01494 char refer_to_context[AST_MAX_EXTENSION];
01495 char referred_by[AST_MAX_EXTENSION];
01496 char referred_by_name[AST_MAX_EXTENSION];
01497 char refer_contact[AST_MAX_EXTENSION];
01498 char replaces_callid[SIPBUFSIZE];
01499 char replaces_callid_totag[SIPBUFSIZE/2];
01500 char replaces_callid_fromtag[SIPBUFSIZE/2];
01501 struct sip_pvt *refer_call;
01502
01503
01504
01505 int attendedtransfer;
01506 int localtransfer;
01507 enum referstatus status;
01508 };
01509
01510
01511
01512
01513
01514 struct sip_st_dlg {
01515 int st_active;
01516 int st_interval;
01517 int st_schedid;
01518 enum st_refresher st_ref;
01519 int st_expirys;
01520 int st_active_peer_ua;
01521 int st_cached_min_se;
01522 int st_cached_max_se;
01523 enum st_mode st_cached_mode;
01524 enum st_refresher st_cached_ref;
01525 unsigned char quit_flag:1;
01526 };
01527
01528
01529
01530
01531
01532 struct sip_st_cfg {
01533 enum st_mode st_mode_oper;
01534 enum st_refresher st_ref;
01535 int st_min_se;
01536 int st_max_se;
01537 };
01538
01539 struct offered_media {
01540 int offered;
01541 char text[128];
01542 };
01543
01544
01545
01546
01547
01548 struct sip_pvt {
01549 struct sip_pvt *next;
01550 enum invitestates invitestate;
01551 int method;
01552 AST_DECLARE_STRING_FIELDS(
01553 AST_STRING_FIELD(callid);
01554 AST_STRING_FIELD(randdata);
01555 AST_STRING_FIELD(accountcode);
01556 AST_STRING_FIELD(realm);
01557 AST_STRING_FIELD(nonce);
01558 AST_STRING_FIELD(opaque);
01559 AST_STRING_FIELD(qop);
01560 AST_STRING_FIELD(domain);
01561 AST_STRING_FIELD(from);
01562 AST_STRING_FIELD(useragent);
01563 AST_STRING_FIELD(exten);
01564 AST_STRING_FIELD(context);
01565 AST_STRING_FIELD(subscribecontext);
01566 AST_STRING_FIELD(subscribeuri);
01567 AST_STRING_FIELD(fromdomain);
01568 AST_STRING_FIELD(fromuser);
01569 AST_STRING_FIELD(fromname);
01570 AST_STRING_FIELD(tohost);
01571 AST_STRING_FIELD(todnid);
01572 AST_STRING_FIELD(language);
01573 AST_STRING_FIELD(mohinterpret);
01574 AST_STRING_FIELD(mohsuggest);
01575 AST_STRING_FIELD(rdnis);
01576 AST_STRING_FIELD(redircause);
01577 AST_STRING_FIELD(theirtag);
01578 AST_STRING_FIELD(username);
01579 AST_STRING_FIELD(peername);
01580 AST_STRING_FIELD(authname);
01581 AST_STRING_FIELD(uri);
01582 AST_STRING_FIELD(okcontacturi);
01583 AST_STRING_FIELD(peersecret);
01584 AST_STRING_FIELD(peermd5secret);
01585 AST_STRING_FIELD(cid_num);
01586 AST_STRING_FIELD(cid_name);
01587 AST_STRING_FIELD(fullcontact);
01588
01589 AST_STRING_FIELD(our_contact);
01590 AST_STRING_FIELD(rpid);
01591 AST_STRING_FIELD(rpid_from);
01592 AST_STRING_FIELD(url);
01593 AST_STRING_FIELD(parkinglot);
01594 );
01595 char via[128];
01596 struct sip_socket socket;
01597 unsigned int ocseq;
01598 unsigned int icseq;
01599 ast_group_t callgroup;
01600 ast_group_t pickupgroup;
01601 int lastinvite;
01602 struct ast_flags flags[2];
01603
01604
01605 char do_history;
01606 char alreadygone;
01607 char needdestroy;
01608 char outgoing_call;
01609 char answered_elsewhere;
01610 char novideo;
01611 char notext;
01612
01613 int timer_t1;
01614 int timer_b;
01615 unsigned int sipoptions;
01616 unsigned int reqsipoptions;
01617 struct ast_codec_pref prefs;
01618 int capability;
01619 int jointcapability;
01620 int peercapability;
01621 int prefcodec;
01622 int noncodeccapability;
01623 int jointnoncodeccapability;
01624 int redircodecs;
01625 int maxcallbitrate;
01626 int t38_maxdatagram;
01627 struct sip_proxy *outboundproxy;
01628 struct t38properties t38;
01629 struct sockaddr_in udptlredirip;
01630 struct ast_udptl *udptl;
01631 int callingpres;
01632 int authtries;
01633 int expiry;
01634 long branch;
01635 long invite_branch;
01636 char tag[11];
01637 int sessionid;
01638 int sessionversion;
01639 int64_t sessionversion_remote;
01640 int session_modify;
01641 unsigned int portinuri:1;
01642 struct sockaddr_in sa;
01643 struct sockaddr_in redirip;
01644 struct sockaddr_in vredirip;
01645 struct sockaddr_in tredirip;
01646 time_t lastrtprx;
01647 time_t lastrtptx;
01648 int rtptimeout;
01649 struct sockaddr_in recv;
01650 struct sockaddr_in ourip;
01651 struct ast_channel *owner;
01652 struct sip_route *route;
01653 int route_persistant;
01654 struct ast_variable *notify_headers;
01655 struct sip_auth *peerauth;
01656 int noncecount;
01657 unsigned int stalenonce:1;
01658 char lastmsg[256];
01659 int amaflags;
01660 int pendinginvite;
01661 int glareinvite;
01662
01663
01664 struct sip_request initreq;
01665
01666
01667
01668 int initid;
01669 int waitid;
01670 int autokillid;
01671 int t38id;
01672 enum transfermodes allowtransfer;
01673 struct sip_refer *refer;
01674 enum subscriptiontype subscribed;
01675 int stateid;
01676 int laststate;
01677 int dialogver;
01678
01679 struct ast_dsp *dsp;
01680
01681 struct sip_peer *relatedpeer;
01682
01683 struct sip_registry *registry;
01684 struct ast_rtp *rtp;
01685 struct ast_rtp *vrtp;
01686 struct ast_rtp *trtp;
01687 struct sip_pkt *packets;
01688 struct sip_history_head *history;
01689 size_t history_entries;
01690 struct ast_variable *chanvars;
01691 AST_LIST_HEAD_NOLOCK(request_queue, sip_request) request_queue;
01692 int request_queue_sched_id;
01693 int provisional_keepalive_sched_id;
01694 const char *last_provisional;
01695 struct sip_invite_param *options;
01696 int autoframing;
01697
01698
01699
01700 struct sip_st_dlg *stimer;
01701
01702 int red;
01703 int hangupcause;
01704
01705 struct sip_subscription_mwi *mwi;
01706
01707
01708
01709
01710
01711
01712
01713
01714
01715
01716
01717
01718
01719
01720 struct offered_media offered_media[4];
01721 };
01722
01723
01724
01725
01726
01727
01728
01729
01730
01731
01732 struct ao2_container *dialogs;
01733
01734 #define sip_pvt_lock(x) ao2_lock(x)
01735 #define sip_pvt_trylock(x) ao2_trylock(x)
01736 #define sip_pvt_unlock(x) ao2_unlock(x)
01737
01738
01739
01740
01741
01742
01743 #ifdef REF_DEBUG
01744 #define dialog_ref(arg1,arg2) dialog_ref_debug((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
01745 #define dialog_unref(arg1,arg2) dialog_unref_debug((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
01746
01747 static struct sip_pvt *dialog_ref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
01748 {
01749 if (p)
01750 _ao2_ref_debug(p, 1, tag, file, line, func);
01751 else
01752 ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
01753 return p;
01754 }
01755
01756 static struct sip_pvt *dialog_unref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
01757 {
01758 if (p)
01759 _ao2_ref_debug(p, -1, tag, file, line, func);
01760 return NULL;
01761 }
01762 #else
01763 static struct sip_pvt *dialog_ref(struct sip_pvt *p, char *tag)
01764 {
01765 if (p)
01766 ao2_ref(p, 1);
01767 else
01768 ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
01769 return p;
01770 }
01771
01772 static struct sip_pvt *dialog_unref(struct sip_pvt *p, char *tag)
01773 {
01774 if (p)
01775 ao2_ref(p, -1);
01776 return NULL;
01777 }
01778 #endif
01779
01780
01781
01782
01783
01784
01785
01786 struct sip_pkt {
01787 struct sip_pkt *next;
01788 int retrans;
01789 int method;
01790 int seqno;
01791 char is_resp;
01792 char is_fatal;
01793 int response_code;
01794 struct sip_pvt *owner;
01795 int retransid;
01796 int timer_a;
01797 int timer_t1;
01798 int packetlen;
01799 struct ast_str *data;
01800 };
01801
01802
01803
01804
01805
01806
01807
01808 struct sip_mailbox {
01809 char *mailbox;
01810 char *context;
01811
01812 struct ast_event_sub *event_sub;
01813 AST_LIST_ENTRY(sip_mailbox) entry;
01814 };
01815
01816 enum sip_peer_type {
01817 SIP_TYPE_PEER = (1 << 0),
01818 SIP_TYPE_USER = (1 << 1),
01819 };
01820
01821
01822
01823
01824 struct sip_peer {
01825 char name[80];
01826 AST_DECLARE_STRING_FIELDS(
01827 AST_STRING_FIELD(secret);
01828 AST_STRING_FIELD(md5secret);
01829 AST_STRING_FIELD(remotesecret);
01830 AST_STRING_FIELD(context);
01831 AST_STRING_FIELD(subscribecontext);
01832 AST_STRING_FIELD(username);
01833 AST_STRING_FIELD(accountcode);
01834 AST_STRING_FIELD(tohost);
01835 AST_STRING_FIELD(regexten);
01836 AST_STRING_FIELD(fromuser);
01837 AST_STRING_FIELD(fromdomain);
01838 AST_STRING_FIELD(fullcontact);
01839 AST_STRING_FIELD(cid_num);
01840 AST_STRING_FIELD(cid_name);
01841 AST_STRING_FIELD(vmexten);
01842 AST_STRING_FIELD(language);
01843 AST_STRING_FIELD(mohinterpret);
01844 AST_STRING_FIELD(mohsuggest);
01845 AST_STRING_FIELD(parkinglot);
01846 AST_STRING_FIELD(useragent);
01847 );
01848 struct sip_socket socket;
01849 enum sip_transport default_outbound_transport;
01850
01851 unsigned int transports:3;
01852 struct sip_auth *auth;
01853 int amaflags;
01854 int callingpres;
01855 int inUse;
01856 int inRinging;
01857 int onHold;
01858 int call_limit;
01859 int t38_maxdatagram;
01860 int busy_level;
01861 enum transfermodes allowtransfer;
01862 struct ast_codec_pref prefs;
01863 int lastmsgssent;
01864 unsigned int sipoptions;
01865 struct ast_flags flags[2];
01866
01867
01868 AST_LIST_HEAD_NOLOCK(, sip_mailbox) mailboxes;
01869
01870
01871 char is_realtime;
01872 char rt_fromcontact;
01873 char host_dynamic;
01874 char selfdestruct;
01875 char the_mark;
01876
01877 int expire;
01878 int capability;
01879 int rtptimeout;
01880 int rtpholdtimeout;
01881 int rtpkeepalive;
01882 ast_group_t callgroup;
01883 ast_group_t pickupgroup;
01884 struct sip_proxy *outboundproxy;
01885 struct ast_dnsmgr_entry *dnsmgr;
01886 struct sockaddr_in addr;
01887 int maxcallbitrate;
01888 unsigned int portinuri:1;
01889
01890
01891 struct sip_pvt *call;
01892 int pokeexpire;
01893 int lastms;
01894 int maxms;
01895 int qualifyfreq;
01896 struct timeval ps;
01897 struct sockaddr_in defaddr;
01898 struct ast_ha *ha;
01899 struct ast_ha *contactha;
01900 struct ast_variable *chanvars;
01901 struct sip_pvt *mwipvt;
01902 int autoframing;
01903 struct sip_st_cfg stimer;
01904 int timer_t1;
01905 int timer_b;
01906 int deprecated_username;
01907
01908
01909 enum sip_peer_type type;
01910 };
01911
01912
01913
01914
01915
01916
01917
01918
01919
01920
01921
01922
01923
01924
01925 struct sip_registry {
01926 ASTOBJ_COMPONENTS_FULL(struct sip_registry,1,1);
01927 AST_DECLARE_STRING_FIELDS(
01928 AST_STRING_FIELD(callid);
01929 AST_STRING_FIELD(realm);
01930 AST_STRING_FIELD(nonce);
01931 AST_STRING_FIELD(opaque);
01932 AST_STRING_FIELD(qop);
01933 AST_STRING_FIELD(domain);
01934 AST_STRING_FIELD(username);
01935 AST_STRING_FIELD(authuser);
01936 AST_STRING_FIELD(hostname);
01937 AST_STRING_FIELD(secret);
01938 AST_STRING_FIELD(md5secret);
01939 AST_STRING_FIELD(callback);
01940 AST_STRING_FIELD(random);
01941 AST_STRING_FIELD(peername);
01942 );
01943 enum sip_transport transport;
01944 int portno;
01945 int expire;
01946 int configured_expiry;
01947 int expiry;
01948 int regattempts;
01949 int timeout;
01950 int refresh;
01951 struct sip_pvt *call;
01952 enum sipregistrystate regstate;
01953 struct timeval regtime;
01954 int callid_valid;
01955 unsigned int ocseq;
01956 struct ast_dnsmgr_entry *dnsmgr;
01957 struct sockaddr_in us;
01958 int noncecount;
01959 char lastmsg[256];
01960 };
01961
01962 enum sip_tcptls_alert {
01963
01964 TCPTLS_ALERT_DATA,
01965
01966 TCPTLS_ALERT_STOP,
01967 };
01968
01969 struct tcptls_packet {
01970 AST_LIST_ENTRY(tcptls_packet) entry;
01971 struct ast_str *data;
01972 size_t len;
01973 };
01974
01975 struct sip_threadinfo {
01976 int stop;
01977 int alert_pipe[2];
01978 pthread_t threadid;
01979 struct ast_tcptls_session_instance *tcptls_session;
01980 enum sip_transport type;
01981 AST_LIST_HEAD_NOLOCK(, tcptls_packet) packet_q;
01982 };
01983
01984
01985 struct sip_subscription_mwi {
01986 ASTOBJ_COMPONENTS_FULL(struct sip_subscription_mwi,1,1);
01987 AST_DECLARE_STRING_FIELDS(
01988 AST_STRING_FIELD(username);
01989 AST_STRING_FIELD(authuser);
01990 AST_STRING_FIELD(hostname);
01991 AST_STRING_FIELD(secret);
01992 AST_STRING_FIELD(mailbox);
01993 );
01994 enum sip_transport transport;
01995 int portno;
01996 int resub;
01997 unsigned int subscribed:1;
01998 struct sip_pvt *call;
01999 struct ast_dnsmgr_entry *dnsmgr;
02000 struct sockaddr_in us;
02001 };
02002
02003
02004
02005 #ifdef LOW_MEMORY
02006 static int hash_peer_size = 17;
02007 static int hash_dialog_size = 17;
02008 static int hash_user_size = 17;
02009 #else
02010 static int hash_peer_size = 563;
02011 static int hash_dialog_size = 563;
02012 static int hash_user_size = 563;
02013 #endif
02014
02015
02016 static struct ao2_container *threadt;
02017
02018
02019 struct ao2_container *peers;
02020 struct ao2_container *peers_by_ip;
02021
02022
02023 static struct ast_register_list {
02024 ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
02025 int recheck;
02026 } regl;
02027
02028
02029 static struct ast_subscription_mwi_list {
02030 ASTOBJ_CONTAINER_COMPONENTS(struct sip_subscription_mwi);
02031 } submwil;
02032
02033
02034
02035
02036 static int peer_hash_cb(const void *obj, const int flags)
02037 {
02038 const struct sip_peer *peer = obj;
02039
02040 return ast_str_case_hash(peer->name);
02041 }
02042
02043
02044
02045
02046 static int peer_cmp_cb(void *obj, void *arg, int flags)
02047 {
02048 struct sip_peer *peer = obj, *peer2 = arg;
02049
02050 return !strcasecmp(peer->name, peer2->name) ? CMP_MATCH | CMP_STOP : 0;
02051 }
02052
02053
02054
02055
02056 static int peer_iphash_cb(const void *obj, const int flags)
02057 {
02058 const struct sip_peer *peer = obj;
02059 int ret1 = peer->addr.sin_addr.s_addr;
02060 if (ret1 < 0)
02061 ret1 = -ret1;
02062
02063 return ret1;
02064 }
02065
02066
02067
02068
02069
02070
02071
02072
02073
02074
02075
02076
02077
02078
02079
02080
02081
02082
02083
02084 static int peer_ipcmp_cb(void *obj, void *arg, int flags)
02085 {
02086 struct sip_peer *peer = obj, *peer2 = arg;
02087
02088 if (peer->addr.sin_addr.s_addr != peer2->addr.sin_addr.s_addr) {
02089
02090 return 0;
02091 }
02092
02093
02094 if ((peer->transports & peer2->transports) & (SIP_TRANSPORT_TLS | SIP_TRANSPORT_TCP)) {
02095
02096 return CMP_MATCH | CMP_STOP;
02097 } else if (ast_test_flag(&peer2->flags[0], SIP_INSECURE_PORT)) {
02098
02099
02100 return ast_test_flag(&peer->flags[0], SIP_INSECURE_PORT) ?
02101 (CMP_MATCH | CMP_STOP) : 0;
02102 }
02103
02104
02105 return peer->addr.sin_port == peer2->addr.sin_port ? (CMP_MATCH | CMP_STOP) : 0;
02106 }
02107
02108
02109 static int threadt_hash_cb(const void *obj, const int flags)
02110 {
02111 const struct sip_threadinfo *th = obj;
02112
02113 return (int) th->tcptls_session->remote_address.sin_addr.s_addr;
02114 }
02115
02116 static int threadt_cmp_cb(void *obj, void *arg, int flags)
02117 {
02118 struct sip_threadinfo *th = obj, *th2 = arg;
02119
02120 return (th->tcptls_session == th2->tcptls_session) ? CMP_MATCH | CMP_STOP : 0;
02121 }
02122
02123
02124
02125
02126 static int dialog_hash_cb(const void *obj, const int flags)
02127 {
02128 const struct sip_pvt *pvt = obj;
02129
02130 return ast_str_case_hash(pvt->callid);
02131 }
02132
02133
02134
02135
02136 static int dialog_cmp_cb(void *obj, void *arg, int flags)
02137 {
02138 struct sip_pvt *pvt = obj, *pvt2 = arg;
02139
02140 return !strcasecmp(pvt->callid, pvt2->callid) ? CMP_MATCH | CMP_STOP : 0;
02141 }
02142
02143 static int temp_pvt_init(void *);
02144 static void temp_pvt_cleanup(void *);
02145
02146
02147 AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
02148
02149 #ifdef LOW_MEMORY
02150 static void ts_ast_rtp_destroy(void *);
02151
02152 AST_THREADSTORAGE_CUSTOM(ts_audio_rtp, NULL, ts_ast_rtp_destroy);
02153 AST_THREADSTORAGE_CUSTOM(ts_video_rtp, NULL, ts_ast_rtp_destroy);
02154 AST_THREADSTORAGE_CUSTOM(ts_text_rtp, NULL, ts_ast_rtp_destroy);
02155 #endif
02156
02157
02158
02159 static struct sip_auth *authl = NULL;
02160
02161
02162
02163
02164
02165
02166
02167
02168
02169
02170
02171
02172
02173
02174
02175
02176
02177
02178 static int sipsock = -1;
02179
02180 static struct sockaddr_in bindaddr;
02181
02182
02183
02184
02185
02186
02187
02188 static struct sockaddr_in internip;
02189
02190
02191
02192
02193
02194
02195
02196
02197
02198
02199
02200
02201
02202
02203
02204
02205
02206
02207
02208 static struct sockaddr_in externip;
02209
02210 static char externhost[MAXHOSTNAMELEN];
02211 static time_t externexpire;
02212 static int externrefresh = 10;
02213 static struct sockaddr_in stunaddr;
02214
02215
02216
02217
02218
02219
02220
02221 static struct ast_ha *localaddr;
02222
02223 static int ourport_tcp;
02224 static int ourport_tls;
02225 static struct sockaddr_in debugaddr;
02226
02227 static struct ast_config *notify_types = NULL;
02228
02229
02230
02231 #define UNLINK(element, head, prev) do { \
02232 if (prev) \
02233 (prev)->next = (element)->next; \
02234 else \
02235 (head) = (element)->next; \
02236 } while (0)
02237
02238 enum t38_action_flag {
02239 SDP_T38_NONE = 0,
02240 SDP_T38_INITIATE,
02241 SDP_T38_ACCEPT,
02242 };
02243
02244
02245
02246
02247
02248
02249 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause);
02250 static int sip_devicestate(void *data);
02251 static int sip_sendtext(struct ast_channel *ast, const char *text);
02252 static int sip_call(struct ast_channel *ast, char *dest, int timeout);
02253 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen);
02254 static int sip_hangup(struct ast_channel *ast);
02255 static int sip_answer(struct ast_channel *ast);
02256 static struct ast_frame *sip_read(struct ast_channel *ast);
02257 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
02258 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
02259 static int sip_transfer(struct ast_channel *ast, const char *dest);
02260 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
02261 static int sip_senddigit_begin(struct ast_channel *ast, char digit);
02262 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
02263 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen);
02264 static const char *sip_get_callid(struct ast_channel *chan);
02265
02266 static int handle_request_do(struct sip_request *req, struct sockaddr_in *sin);
02267 static int sip_standard_port(enum sip_transport type, int port);
02268 static int sip_prepare_socket(struct sip_pvt *p);
02269 static int sip_parse_host(char *line, int lineno, char **hostname, int *portnum, enum sip_transport *transport);
02270
02271
02272 static int sipsock_read(int *id, int fd, short events, void *ignore);
02273 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len);
02274 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, struct ast_str *data, int len, int fatal, int sipmethod);
02275 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
02276 static int retrans_pkt(const void *data);
02277 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);
02278 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
02279 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
02280 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
02281 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable, int oldsdp);
02282 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
02283 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);
02284 static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp);
02285 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
02286 static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable);
02287 static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
02288 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch);
02289 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init);
02290 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp);
02291 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
02292 static int transmit_info_with_vidupdate(struct sip_pvt *p);
02293 static int transmit_message_with_text(struct sip_pvt *p, const char *text);
02294 static int transmit_refer(struct sip_pvt *p, const char *dest);
02295 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten);
02296 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
02297 static int transmit_notify_custom(struct sip_pvt *p, struct ast_variable *vars);
02298 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
02299 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
02300 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
02301 static void copy_request(struct sip_request *dst, const struct sip_request *src);
02302 static void receive_message(struct sip_pvt *p, struct sip_request *req);
02303 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req);
02304 static int sip_send_mwi_to_peer(struct sip_peer *peer, const struct ast_event *event, int cache_only);
02305
02306
02307 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
02308 int useglobal_nat, const int intended_method, struct sip_request *req);
02309 static int __sip_autodestruct(const void *data);
02310 static void sip_scheddestroy(struct sip_pvt *p, int ms);
02311 static int sip_cancel_destroy(struct sip_pvt *p);
02312 static struct sip_pvt *sip_destroy(struct sip_pvt *p);
02313 static void *dialog_unlink_all(struct sip_pvt *dialog, int lockowner, int lockdialoglist);
02314 static void *registry_unref(struct sip_registry *reg, char *tag);
02315 static void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist);
02316 static int __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
02317 static void __sip_pretend_ack(struct sip_pvt *p);
02318 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
02319 static int auto_congest(const void *arg);
02320 static int update_call_counter(struct sip_pvt *fup, int event);
02321 static int hangup_sip2cause(int cause);
02322 static const char *hangup_cause2sip(int cause);
02323 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method);
02324 static void free_old_route(struct sip_route *route);
02325 static void list_route(struct sip_route *route);
02326 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards);
02327 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
02328 struct sip_request *req, char *uri);
02329 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
02330 static void check_pendings(struct sip_pvt *p);
02331 static void *sip_park_thread(void *stuff);
02332 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno);
02333 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
02334
02335
02336 static void try_suggested_sip_codec(struct sip_pvt *p);
02337 static const char *get_sdp_iterate(int* start, struct sip_request *req, const char *name);
02338 static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value);
02339 static int find_sdp(struct sip_request *req);
02340 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action);
02341 static int process_sdp_o(const char *o, struct sip_pvt *p);
02342 static int process_sdp_c(const char *c, struct ast_hostent *hp);
02343 static int process_sdp_a_sendonly(const char *a, int *sendonly);
02344 static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp *newaudiortp, int *last_rtpmap_codec);
02345 static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp *newvideortp, int *last_rtpmap_codec);
02346 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);
02347 static int process_sdp_a_image(const char *a, struct sip_pvt *p);
02348 static void add_codec_to_sdp(const struct sip_pvt *p, int codec,
02349 struct ast_str **m_buf, struct ast_str **a_buf,
02350 int debug, int *min_packet_size);
02351 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
02352 struct ast_str **m_buf, struct ast_str **a_buf,
02353 int debug);
02354 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38);
02355 static void do_setnat(struct sip_pvt *p, int natflags);
02356 static void stop_media_flows(struct sip_pvt *p);
02357
02358
02359 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
02360 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
02361 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
02362 const char *secret, const char *md5secret, int sipmethod,
02363 char *uri, enum xmittype reliable, int ignore);
02364 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
02365 int sipmethod, char *uri, enum xmittype reliable,
02366 struct sockaddr_in *sin, struct sip_peer **authpeer);
02367 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin);
02368
02369
02370 static int check_sip_domain(const char *domain, char *context, size_t len);
02371 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
02372 static void clear_sip_domains(void);
02373
02374
02375 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, const char *configuration, int lineno);
02376 static int clear_realm_authentication(struct sip_auth *authlist);
02377 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm);
02378
02379
02380 static void check_rtp_timeout(struct sip_pvt *dialog, time_t t);
02381 static int sip_do_reload(enum channelreloadreason reason);
02382 static int reload_config(enum channelreloadreason reason);
02383 static int expire_register(const void *data);
02384 static void *do_monitor(void *data);
02385 static int restart_monitor(void);
02386 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer);
02387 static struct ast_variable *copy_vars(struct ast_variable *src);
02388
02389 static int sip_refer_allocate(struct sip_pvt *p);
02390 static void ast_quiet_chan(struct ast_channel *chan);
02391 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
02392 static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context);
02393
02394
02395
02396
02397
02398
02399
02400
02401 #define check_request_transport(peer, tmpl) ({ \
02402 int ret = 0; \
02403 if (peer->socket.type == tmpl->socket.type) \
02404 ; \
02405 else if (!(peer->transports & tmpl->socket.type)) {\
02406 ast_log(LOG_ERROR, \
02407 "'%s' is not a valid transport for '%s'. we only use '%s'! ending call.\n", \
02408 get_transport(tmpl->socket.type), peer->name, get_transport_list(peer->transports) \
02409 ); \
02410 ret = 1; \
02411 } else if (peer->socket.type & SIP_TRANSPORT_TLS) { \
02412 ast_log(LOG_WARNING, \
02413 "peer '%s' HAS NOT USED (OR SWITCHED TO) TLS in favor of '%s' (but this was allowed in sip.conf)!\n", \
02414 peer->name, get_transport(tmpl->socket.type) \
02415 ); \
02416 } else { \
02417 ast_debug(1, \
02418 "peer '%s' has contacted us over %s even though we prefer %s.\n", \
02419 peer->name, get_transport(tmpl->socket.type), get_transport(peer->socket.type) \
02420 ); \
02421 }\
02422 (ret); \
02423 })
02424
02425
02426
02427 static int cb_extensionstate(char *context, char* exten, int state, void *data);
02428 static int sip_devicestate(void *data);
02429 static int sip_poke_noanswer(const void *data);
02430 static int sip_poke_peer(struct sip_peer *peer, int force);
02431 static void sip_poke_all_peers(void);
02432 static void sip_peer_hold(struct sip_pvt *p, int hold);
02433 static void mwi_event_cb(const struct ast_event *, void *);
02434
02435
02436 static const char *sip_nat_mode(const struct sip_pvt *p);
02437 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02438 static char *transfermode2str(enum transfermodes mode) attribute_const;
02439 static const char *nat2str(int nat) attribute_const;
02440 static int peer_status(struct sip_peer *peer, char *status, int statuslen);
02441 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02442 static char * _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
02443 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02444 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02445 static void print_group(int fd, ast_group_t group, int crlf);
02446 static const char *dtmfmode2str(int mode) attribute_const;
02447 static int str2dtmfmode(const char *str) attribute_unused;
02448 static const char *insecure2str(int mode) attribute_const;
02449 static void cleanup_stale_contexts(char *new, char *old);
02450 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
02451 static const char *domain_mode_to_text(const enum domain_mode mode);
02452 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02453 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
02454 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02455 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
02456 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02457 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02458 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02459 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02460 static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02461 static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
02462 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
02463 static char *complete_sip_peer(const char *word, int state, int flags2);
02464 static char *complete_sip_registered_peer(const char *word, int state, int flags2);
02465 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state);
02466 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
02467 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state);
02468 static char *complete_sipnotify(const char *line, const char *word, int pos, int state);
02469 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02470 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02471 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02472 static char *sip_do_debug_ip(int fd, char *arg);
02473 static char *sip_do_debug_peer(int fd, char *arg);
02474 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02475 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02476 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02477 static int sip_dtmfmode(struct ast_channel *chan, void *data);
02478 static int sip_addheader(struct ast_channel *chan, void *data);
02479 static int sip_do_reload(enum channelreloadreason reason);
02480 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02481 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
02482
02483
02484
02485
02486
02487 static void sip_dump_history(struct sip_pvt *dialog);
02488 static inline int sip_debug_test_addr(const struct sockaddr_in *addr);
02489 static inline int sip_debug_test_pvt(struct sip_pvt *p);
02490
02491
02492
02493
02494 #define append_history(p, event, fmt , args... ) append_history_full(p, "%-15s " fmt, event, ## args)
02495 static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
02496 static void sip_dump_history(struct sip_pvt *dialog);
02497
02498
02499 static struct sip_peer *temp_peer(const char *name);
02500 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only);
02501 static int update_call_counter(struct sip_pvt *fup, int event);
02502 static void sip_destroy_peer(struct sip_peer *peer);
02503 static void sip_destroy_peer_fn(void *peer);
02504 static void set_peer_defaults(struct sip_peer *peer);
02505 static struct sip_peer *temp_peer(const char *name);
02506 static void register_peer_exten(struct sip_peer *peer, int onoff);
02507 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime, int forcenamematch, int devstate_only, int transport);
02508 static int sip_poke_peer_s(const void *data);
02509 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
02510 static void reg_source_db(struct sip_peer *peer);
02511 static void destroy_association(struct sip_peer *peer);
02512 static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
02513 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
02514 static void set_socket_transport(struct sip_socket *socket, int transport);
02515
02516
02517 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);
02518 static void update_peer(struct sip_peer *p, int expire);
02519 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config);
02520 static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername);
02521 static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin, int devstate_only);
02522 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02523
02524
02525 static void ast_sip_ouraddrfor(struct in_addr *them, struct sockaddr_in *us, struct sip_pvt *p);
02526 static void sip_registry_destroy(struct sip_registry *reg);
02527 static int sip_register(const char *value, int lineno);
02528 static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
02529 static int sip_reregister(const void *data);
02530 static int __sip_do_register(struct sip_registry *r);
02531 static int sip_reg_timeout(const void *data);
02532 static void sip_send_all_registers(void);
02533 static int sip_reinvite_retry(const void *data);
02534
02535
02536 static void append_date(struct sip_request *req);
02537 static int determine_firstline_parts(struct sip_request *req);
02538 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
02539 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
02540 static int find_sip_method(const char *msg);
02541 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported);
02542 static int parse_request(struct sip_request *req);
02543 static const char *get_header(const struct sip_request *req, const char *name);
02544 static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
02545 static int method_match(enum sipmethod id, const char *name);
02546 static void parse_copy(struct sip_request *dst, const struct sip_request *src);
02547 static char *get_in_brackets(char *tmp);
02548 static const char *find_alias(const char *name, const char *_default);
02549 static const char *__get_header(const struct sip_request *req, const char *name, int *start);
02550 static int lws2sws(char *msgbuf, int len);
02551 static void extract_uri(struct sip_pvt *p, struct sip_request *req);
02552 static char *remove_uri_parameters(char *uri);
02553 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
02554 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
02555 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
02556 static int set_address_from_contact(struct sip_pvt *pvt);
02557 static void check_via(struct sip_pvt *p, struct sip_request *req);
02558 static char *get_calleridname(const char *input, char *output, size_t outputsize);
02559 static int get_rpid_num(const char *input, char *output, int maxlen);
02560 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq);
02561 static int get_destination(struct sip_pvt *p, struct sip_request *oreq);
02562 static int get_msg_text(char *buf, int len, struct sip_request *req, int addnewline);
02563 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout);
02564
02565
02566 static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session);
02567 static void *sip_tcp_worker_fn(void *);
02568
02569
02570 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
02571 static int init_req(struct sip_request *req, int sipmethod, const char *recip);
02572 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch);
02573 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod);
02574 static int init_resp(struct sip_request *resp, const char *msg);
02575 static inline int resp_needs_contact(const char *msg, enum sipmethod method);
02576 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
02577 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p);
02578 static void build_via(struct sip_pvt *p);
02579 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
02580 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct sockaddr_in *sin, int newdialog);
02581 static char *generate_random_string(char *buf, size_t size);
02582 static void build_callid_pvt(struct sip_pvt *pvt);
02583 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain);
02584 static void make_our_tag(char *tagbuf, size_t len);
02585 static int add_header(struct sip_request *req, const char *var, const char *value);
02586 static int add_header_contentLength(struct sip_request *req, int len);
02587 static int add_line(struct sip_request *req, const char *line);
02588 static int add_text(struct sip_request *req, const char *text);
02589 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode);
02590 static int add_vidupdate(struct sip_request *req);
02591 static void add_route(struct sip_request *req, struct sip_route *route);
02592 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
02593 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
02594 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
02595 static void set_destination(struct sip_pvt *p, char *uri);
02596 static void append_date(struct sip_request *req);
02597 static void build_contact(struct sip_pvt *p);
02598 static void build_rpid(struct sip_pvt *p);
02599
02600
02601 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock);
02602 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);
02603 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock);
02604 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
02605 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e);
02606 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
02607 static int handle_request_message(struct sip_pvt *p, struct sip_request *req);
02608 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
02609 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
02610 static int handle_request_options(struct sip_pvt *p, struct sip_request *req);
02611 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin, int *nounlock);
02612 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
02613 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno);
02614
02615
02616 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02617 static void handle_response_notify(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02618 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02619 static void handle_response_subscribe(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02620 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02621 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02622
02623
02624 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);
02625 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
02626 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
02627 static enum ast_rtp_get_result sip_get_trtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
02628 static int sip_get_codec(struct ast_channel *chan);
02629 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect);
02630
02631
02632 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
02633 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
02634 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
02635 static void change_t38_state(struct sip_pvt *p, int state);
02636
02637
02638 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp);
02639 static int proc_session_timer(const void *vp);
02640 static void stop_session_timer(struct sip_pvt *p);
02641 static void start_session_timer(struct sip_pvt *p);
02642 static void restart_session_timer(struct sip_pvt *p);
02643 static const char *strefresher2str(enum st_refresher r);
02644 static int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref);
02645 static int parse_minse(const char *p_hdrval, int *const p_interval);
02646 static int st_get_se(struct sip_pvt *, int max);
02647 static enum st_refresher st_get_refresher(struct sip_pvt *);
02648 static enum st_mode st_get_mode(struct sip_pvt *);
02649 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p);
02650
02651
02652 static int sip_subscribe_mwi(const char *value, int lineno);
02653 static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi);
02654 static void sip_send_all_mwi_subscriptions(void);
02655 static int sip_subscribe_mwi_do(const void *data);
02656 static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi);
02657
02658
02659 static const struct ast_channel_tech sip_tech = {
02660 .type = "SIP",
02661 .description = "Session Initiation Protocol (SIP)",
02662 .capabilities = AST_FORMAT_AUDIO_MASK,
02663 .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
02664 .requester = sip_request_call,
02665 .devicestate = sip_devicestate,
02666 .call = sip_call,
02667 .send_html = sip_sendhtml,
02668 .hangup = sip_hangup,
02669 .answer = sip_answer,
02670 .read = sip_read,
02671 .write = sip_write,
02672 .write_video = sip_write,
02673 .write_text = sip_write,
02674 .indicate = sip_indicate,
02675 .transfer = sip_transfer,
02676 .fixup = sip_fixup,
02677 .send_digit_begin = sip_senddigit_begin,
02678 .send_digit_end = sip_senddigit_end,
02679 .bridge = ast_rtp_bridge,
02680 .early_bridge = ast_rtp_early_bridge,
02681 .send_text = sip_sendtext,
02682 .func_channel_read = acf_channel_read,
02683 .queryoption = sip_queryoption,
02684 .get_pvt_uniqueid = sip_get_callid,
02685 };
02686
02687
02688
02689
02690
02691
02692
02693 static struct ast_channel_tech sip_tech_info;
02694
02695
02696
02697 static struct ast_tls_config sip_tls_cfg;
02698
02699
02700 static struct ast_tls_config default_tls_cfg;
02701
02702
02703 static struct ast_tcptls_session_args sip_tcp_desc = {
02704 .accept_fd = -1,
02705 .master = AST_PTHREADT_NULL,
02706 .tls_cfg = NULL,
02707 .poll_timeout = -1,
02708 .name = "SIP TCP server",
02709 .accept_fn = ast_tcptls_server_root,
02710 .worker_fn = sip_tcp_worker_fn,
02711 };
02712
02713
02714 static struct ast_tcptls_session_args sip_tls_desc = {
02715 .accept_fd = -1,
02716 .master = AST_PTHREADT_NULL,
02717 .tls_cfg = &sip_tls_cfg,
02718 .poll_timeout = -1,
02719 .name = "SIP TLS server",
02720 .accept_fn = ast_tcptls_server_root,
02721 .worker_fn = sip_tcp_worker_fn,
02722 };
02723
02724
02725 #define IS_SIP_TECH(t) ((t) == &sip_tech || (t) == &sip_tech_info)
02726
02727
02728
02729
02730 static const char *map_x_s(const struct _map_x_s *table, int x, const char *errorstring)
02731 {
02732 const struct _map_x_s *cur;
02733
02734 for (cur = table; cur->s; cur++)
02735 if (cur->x == x)
02736 return cur->s;
02737 return errorstring;
02738 }
02739
02740
02741
02742
02743 static int map_s_x(const struct _map_x_s *table, const char *s, int errorvalue)
02744 {
02745 const struct _map_x_s *cur;
02746
02747 for (cur = table; cur->s; cur++)
02748 if (!strcasecmp(cur->s, s))
02749 return cur->x;
02750 return errorvalue;
02751 }
02752
02753
02754
02755 static struct ast_rtp_protocol sip_rtp = {
02756 .type = "SIP",
02757 .get_rtp_info = sip_get_rtp_peer,
02758 .get_vrtp_info = sip_get_vrtp_peer,
02759 .get_trtp_info = sip_get_trtp_peer,
02760 .set_rtp_peer = sip_set_rtp_peer,
02761 .get_codec = sip_get_codec,
02762 };
02763
02764
02765
02766
02767 static struct ast_variable *copy_vars(struct ast_variable *src)
02768 {
02769 struct ast_variable *res = NULL, *tmp, *v = NULL;
02770
02771 for (v = src ; v ; v = v->next) {
02772 if ((tmp = ast_variable_new(v->name, v->value, v->file))) {
02773 tmp->next = res;
02774 res = tmp;
02775 }
02776 }
02777 return res;
02778 }
02779
02780 static void tcptls_packet_destructor(void *obj)
02781 {
02782 struct tcptls_packet *packet = obj;
02783
02784 ast_free(packet->data);
02785 }
02786
02787 static void sip_tcptls_client_args_destructor(void *obj)
02788 {
02789 struct ast_tcptls_session_args *args = obj;
02790 if (args->tls_cfg) {
02791 ast_free(args->tls_cfg->certfile);
02792 ast_free(args->tls_cfg->cipher);
02793 ast_free(args->tls_cfg->cafile);
02794 ast_free(args->tls_cfg->capath);
02795 }
02796 ast_free(args->tls_cfg);
02797 ast_free((char *) args->name);
02798 }
02799
02800 static void sip_threadinfo_destructor(void *obj)
02801 {
02802 struct sip_threadinfo *th = obj;
02803 struct tcptls_packet *packet;
02804 if (th->alert_pipe[1] > -1) {
02805 close(th->alert_pipe[0]);
02806 }
02807 if (th->alert_pipe[1] > -1) {
02808 close(th->alert_pipe[1]);
02809 }
02810 th->alert_pipe[0] = th->alert_pipe[1] = -1;
02811
02812 while ((packet = AST_LIST_REMOVE_HEAD(&th->packet_q, entry))) {
02813 ao2_t_ref(packet, -1, "thread destruction, removing packet from frame queue");
02814 }
02815
02816 if (th->tcptls_session) {
02817 ao2_t_ref(th->tcptls_session, -1, "remove tcptls_session for sip_threadinfo object");
02818 }
02819 }
02820
02821
02822 static struct sip_threadinfo *sip_threadinfo_create(struct ast_tcptls_session_instance *tcptls_session, int transport)
02823 {
02824 struct sip_threadinfo *th;
02825
02826 if (!tcptls_session || !(th = ao2_alloc(sizeof(*th), sip_threadinfo_destructor))) {
02827 return NULL;
02828 }
02829
02830 th->alert_pipe[0] = th->alert_pipe[1] = -1;
02831
02832 if (pipe(th->alert_pipe) == -1) {
02833 ao2_t_ref(th, -1, "Failed to open alert pipe on sip_threadinfo");
02834 ast_log(LOG_ERROR, "Could not create sip alert pipe in tcptls thread, error %s\n", strerror(errno));
02835 return NULL;
02836 }
02837 ao2_t_ref(tcptls_session, +1, "tcptls_session ref for sip_threadinfo object");
02838 th->tcptls_session = tcptls_session;
02839 th->type = transport ? transport : (tcptls_session->ssl ? SIP_TRANSPORT_TLS: SIP_TRANSPORT_TCP);
02840 ao2_t_link(threadt, th, "Adding new tcptls helper thread");
02841 ao2_t_ref(th, -1, "Decrementing threadinfo ref from alloc, only table ref remains");
02842 return th;
02843 }
02844
02845
02846 static int sip_tcptls_write(struct ast_tcptls_session_instance *tcptls_session, const void *buf, size_t len)
02847 {
02848 int res = len;
02849 struct sip_threadinfo *th = NULL;
02850 struct tcptls_packet *packet = NULL;
02851 struct sip_threadinfo tmp = {
02852 .tcptls_session = tcptls_session,
02853 };
02854 enum sip_tcptls_alert alert = TCPTLS_ALERT_DATA;
02855
02856 if (!tcptls_session) {
02857 return XMIT_ERROR;
02858 }
02859
02860 ast_mutex_lock(&tcptls_session->lock);
02861
02862 if ((tcptls_session->fd == -1) ||
02863 !(th = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread")) ||
02864 !(packet = ao2_alloc(sizeof(*packet), tcptls_packet_destructor)) ||
02865 !(packet->data = ast_str_create(len))) {
02866 goto tcptls_write_setup_error;
02867 }
02868
02869
02870 ast_str_set(&packet->data, 0, "%s", (char *) buf);
02871 packet->len = len;
02872
02873
02874
02875
02876 ao2_lock(th);
02877 if (write(th->alert_pipe[1], &alert, sizeof(alert)) == -1) {
02878 ast_log(LOG_ERROR, "write() to alert pipe failed: %s\n", strerror(errno));
02879 ao2_t_ref(packet, -1, "could not write to alert pipe, remove packet");
02880 packet = NULL;
02881 res = XMIT_ERROR;
02882 } else {
02883 AST_LIST_INSERT_TAIL(&th->packet_q, packet, entry);
02884 }
02885 ao2_unlock(th);
02886
02887 ast_mutex_unlock(&tcptls_session->lock);
02888 ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo object after finding it");
02889 return res;
02890
02891 tcptls_write_setup_error:
02892 if (th) {
02893 ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo obj, could not create packet");
02894 }
02895 if (packet) {
02896 ao2_t_ref(packet, -1, "could not allocate packet's data");
02897 }
02898 ast_mutex_unlock(&tcptls_session->lock);
02899
02900 return XMIT_ERROR;
02901 }
02902
02903
02904 static void *sip_tcp_worker_fn(void *data)
02905 {
02906 struct ast_tcptls_session_instance *tcptls_session = data;
02907
02908 return _sip_tcp_helper_thread(NULL, tcptls_session);
02909 }
02910
02911
02912
02913
02914 static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session)
02915 {
02916 int res, cl;
02917 struct sip_request req = { 0, } , reqcpy = { 0, };
02918 struct sip_threadinfo *me = NULL;
02919 char buf[1024] = "";
02920 struct pollfd fds[2] = { { 0 }, { 0 }, };
02921 struct ast_tcptls_session_args *ca = NULL;
02922
02923
02924
02925
02926
02927
02928
02929
02930
02931
02932
02933 if (!tcptls_session->client) {
02934 if (!(me = sip_threadinfo_create(tcptls_session, tcptls_session->ssl ? SIP_TRANSPORT_TLS : SIP_TRANSPORT_TCP))) {
02935 goto cleanup;
02936 }
02937 ao2_t_ref(me, +1, "Adding threadinfo ref for tcp_helper_thread");
02938 } else {
02939 struct sip_threadinfo tmp = {
02940 .tcptls_session = tcptls_session,
02941 };
02942
02943 if ((!(ca = tcptls_session->parent)) ||
02944 (!(me = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread"))) ||
02945 (!(tcptls_session = ast_tcptls_client_start(tcptls_session)))) {
02946 goto cleanup;
02947 }
02948 }
02949
02950 me->threadid = pthread_self();
02951 ast_debug(2, "Starting thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");
02952
02953
02954 fds[0].fd = tcptls_session->fd;
02955 fds[1].fd = me->alert_pipe[0];
02956 fds[0].events = fds[1].events = POLLIN | POLLPRI;
02957
02958 if (!(req.data = ast_str_create(SIP_MIN_PACKET)))
02959 goto cleanup;
02960 if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET)))
02961 goto cleanup;
02962
02963 for (;;) {
02964 struct ast_str *str_save;
02965
02966 res = ast_poll(fds, 2, -1);
02967
02968 if (res < 0) {
02969 ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", tcptls_session->ssl ? "SSL": "TCP", res);
02970 goto cleanup;
02971 }
02972
02973
02974
02975 if (fds[0].revents) {
02976
02977 fds[0].revents = 0;
02978
02979
02980 str_save = req.data;
02981 memset(&req, 0, sizeof(req));
02982 req.data = str_save;
02983 ast_str_reset(req.data);
02984
02985 str_save = reqcpy.data;
02986 memset(&reqcpy, 0, sizeof(reqcpy));
02987 reqcpy.data = str_save;
02988 ast_str_reset(reqcpy.data);
02989
02990 memset(buf, 0, sizeof(buf));
02991
02992 if (tcptls_session->ssl) {
02993 set_socket_transport(&req.socket, SIP_TRANSPORT_TLS);
02994 req.socket.port = htons(ourport_tls);
02995 } else {
02996 set_socket_transport(&req.socket, SIP_TRANSPORT_TCP);
02997 req.socket.port = htons(ourport_tcp);
02998 }
02999 req.socket.fd = tcptls_session->fd;
03000
03001
03002 while (req.len < 4 || strncmp(REQ_OFFSET_TO_STR(&req, len - 4), "\r\n\r\n", 4)) {
03003 ast_mutex_lock(&tcptls_session->lock);
03004 if (!fgets(buf, sizeof(buf), tcptls_session->f)) {
03005 ast_mutex_unlock(&tcptls_session->lock);
03006 goto cleanup;
03007 }
03008 ast_mutex_unlock(&tcptls_session->lock);
03009 if (me->stop)
03010 goto cleanup;
03011 ast_str_append(&req.data, 0, "%s", buf);
03012 req.len = req.data->used;
03013 }
03014 copy_request(&reqcpy, &req);
03015 parse_request(&reqcpy);
03016
03017 if (sscanf(get_header(&reqcpy, "Content-Length"), "%30d", &cl)) {
03018 while (cl > 0) {
03019 size_t bytes_read;
03020 ast_mutex_lock(&tcptls_session->lock);
03021 if (!(bytes_read = fread(buf, 1, MIN(sizeof(buf) - 1, cl), tcptls_session->f))) {
03022 ast_mutex_unlock(&tcptls_session->lock);
03023 goto cleanup;
03024 }
03025 buf[bytes_read] = '\0';
03026 ast_mutex_unlock(&tcptls_session->lock);
03027 if (me->stop)
03028 goto cleanup;
03029 cl -= strlen(buf);
03030 ast_str_append(&req.data, 0, "%s", buf);
03031 req.len = req.data->used;
03032 }
03033 }
03034
03035
03036
03037 req.socket.tcptls_session = tcptls_session;
03038 handle_request_do(&req, &tcptls_session->remote_address);
03039 }
03040
03041 if (fds[1].revents) {
03042 enum sip_tcptls_alert alert;
03043 struct tcptls_packet *packet;
03044
03045 fds[1].revents = 0;
03046
03047 if (read(me->alert_pipe[0], &alert, sizeof(alert)) == -1) {
03048 ast_log(LOG_ERROR, "read() failed: %s\n", strerror(errno));
03049 continue;
03050 }
03051
03052 switch (alert) {
03053 case TCPTLS_ALERT_STOP:
03054 goto cleanup;
03055 case TCPTLS_ALERT_DATA:
03056 ao2_lock(me);
03057 if (!(packet = AST_LIST_REMOVE_HEAD(&me->packet_q, entry))) {
03058 ast_log(LOG_WARNING, "TCPTLS thread alert_pipe indicated packet should be sent, but frame_q is empty");
03059 } else if (ast_tcptls_server_write(tcptls_session, ast_str_buffer(packet->data), packet->len) == -1) {
03060 ast_log(LOG_WARNING, "Failure to write to tcp/tls socket\n");
03061 }
03062
03063 if (packet) {
03064 ao2_t_ref(packet, -1, "tcptls packet sent, this is no longer needed");
03065 }
03066 ao2_unlock(me);
03067 break;
03068 default:
03069 ast_log(LOG_ERROR, "Unknown tcptls thread alert '%d'\n", alert);
03070 }
03071 }
03072 }
03073
03074 ast_debug(2, "Shutting down thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");
03075
03076 cleanup:
03077 if (me) {
03078 ao2_t_unlink(threadt, me, "Removing tcptls helper thread, thread is closing");
03079 ao2_t_ref(me, -1, "Removing tcp_helper_threads threadinfo ref");
03080 }
03081 if (reqcpy.data) {
03082 ast_free(reqcpy.data);
03083 }
03084
03085 if (req.data) {
03086 ast_free(req.data);
03087 req.data = NULL;
03088 }
03089
03090
03091 if (ca) {
03092 ao2_t_ref(ca, -1, "closing tcptls thread, getting rid of client tcptls_session arguments");
03093 }
03094
03095 if (tcptls_session) {
03096 ast_mutex_lock(&tcptls_session->lock);
03097 if (tcptls_session->f) {
03098 fclose(tcptls_session->f);
03099 tcptls_session->f = NULL;
03100 }
03101 if (tcptls_session->fd != -1) {
03102 close(tcptls_session->fd);
03103 tcptls_session->fd = -1;
03104 }
03105 tcptls_session->parent = NULL;
03106 ast_mutex_unlock(&tcptls_session->lock);
03107
03108 ao2_ref(tcptls_session, -1);
03109 tcptls_session = NULL;
03110 }
03111 return NULL;
03112 }
03113
03114
03115
03116
03117
03118
03119
03120 static void *unref_peer(struct sip_peer *peer, char *tag)
03121 {
03122 ao2_t_ref(peer, -1, tag);
03123 return NULL;
03124 }
03125
03126 static struct sip_peer *ref_peer(struct sip_peer *peer, char *tag)
03127 {
03128 ao2_t_ref(peer, 1, tag);
03129 return peer;
03130 }
03131
03132
03133
03134
03135
03136
03137
03138
03139
03140
03141
03142
03143 static void ref_proxy(struct sip_pvt *pvt, struct sip_proxy *proxy)
03144 {
03145 struct sip_proxy *old_obproxy = pvt->outboundproxy;
03146
03147
03148
03149 if (proxy && proxy != &sip_cfg.outboundproxy) {
03150 ao2_ref(proxy, +1);
03151 }
03152 pvt->outboundproxy = proxy;
03153 if (old_obproxy && old_obproxy != &sip_cfg.outboundproxy) {
03154 ao2_ref(old_obproxy, -1);
03155 }
03156 }
03157
03158
03159
03160
03161
03162
03163
03164
03165 static void *dialog_unlink_all(struct sip_pvt *dialog, int lockowner, int lockdialoglist)
03166 {
03167 struct sip_pkt *cp;
03168
03169 dialog_ref(dialog, "Let's bump the count in the unlink so it doesn't accidentally become dead before we are done");
03170
03171 ao2_t_unlink(dialogs, dialog, "unlinking dialog via ao2_unlink");
03172
03173
03174 if (dialog->owner) {
03175 if (lockowner)
03176 ast_channel_lock(dialog->owner);
03177 ast_debug(1, "Detaching from channel %s\n", dialog->owner->name);
03178 dialog->owner->tech_pvt = dialog_unref(dialog->owner->tech_pvt, "resetting channel dialog ptr in unlink_all");
03179 if (lockowner)
03180 ast_channel_unlock(dialog->owner);
03181 }
03182 if (dialog->registry) {
03183 if (dialog->registry->call == dialog)
03184 dialog->registry->call = dialog_unref(dialog->registry->call, "nulling out the registry's call dialog field in unlink_all");
03185 dialog->registry = registry_unref(dialog->registry, "delete dialog->registry");
03186 }
03187 if (dialog->stateid > -1) {
03188 ast_extension_state_del(dialog->stateid, NULL);
03189 dialog_unref(dialog, "removing extension_state, should unref the associated dialog ptr that was stored there.");
03190 dialog->stateid = -1;
03191 }
03192
03193 if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog)
03194 dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
03195 if (dialog->relatedpeer && dialog->relatedpeer->call == dialog)
03196 dialog->relatedpeer->call = dialog_unref(dialog->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
03197
03198
03199 while((cp = dialog->packets)) {
03200 dialog->packets = dialog->packets->next;
03201 AST_SCHED_DEL(sched, cp->retransid);
03202 dialog_unref(cp->owner, "remove all current packets in this dialog, and the pointer to the dialog too as part of __sip_destroy");
03203 if (cp->data) {
03204 ast_free(cp->data);
03205 }
03206 ast_free(cp);
03207 }
03208
03209 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"));
03210
03211 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"));
03212
03213 if (dialog->autokillid > -1)
03214 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"));
03215
03216 if (dialog->request_queue_sched_id > -1) {
03217 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"));
03218 }
03219
03220 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"));
03221
03222 if (dialog->t38id > -1) {
03223 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"));
03224 }
03225
03226 dialog_unref(dialog, "Let's unbump the count in the unlink so the poor pvt can disappear if it is time");
03227 return NULL;
03228 }
03229
03230 static void *registry_unref(struct sip_registry *reg, char *tag)
03231 {
03232 ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount - 1);
03233 ASTOBJ_UNREF(reg, sip_registry_destroy);
03234 return NULL;
03235 }
03236
03237
03238 static struct sip_registry *registry_addref(struct sip_registry *reg, char *tag)
03239 {
03240 ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount + 1);
03241 return ASTOBJ_REF(reg);
03242 }
03243
03244
03245 static struct ast_udptl_protocol sip_udptl = {
03246 type: "SIP",
03247 get_udptl_info: sip_get_udptl_peer,
03248 set_udptl_peer: sip_set_udptl_peer,
03249 };
03250
03251 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
03252 __attribute__((format(printf, 2, 3)));
03253
03254
03255
03256 static const char *referstatus2str(enum referstatus rstatus)
03257 {
03258 return map_x_s(referstatusstrings, rstatus, "");
03259 }
03260
03261 static inline void pvt_set_needdestroy(struct sip_pvt *pvt, const char *reason)
03262 {
03263 append_history(pvt, "NeedDestroy", "Setting needdestroy because %s", reason);
03264 pvt->needdestroy = 1;
03265 }
03266
03267
03268
03269
03270 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
03271 {
03272 if (p->initreq.headers)
03273 ast_debug(1, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
03274 else
03275 ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
03276
03277 copy_request(&p->initreq, req);
03278 parse_request(&p->initreq);
03279 if (req->debug)
03280 ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
03281 }
03282
03283
03284 static void sip_alreadygone(struct sip_pvt *dialog)
03285 {
03286 ast_debug(3, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
03287 dialog->alreadygone = 1;
03288 }
03289
03290
03291 static int proxy_update(struct sip_proxy *proxy)
03292 {
03293
03294
03295 if (!inet_aton(proxy->name, &proxy->ip.sin_addr)) {
03296
03297
03298 if (ast_get_ip_or_srv(&proxy->ip, proxy->name, sip_cfg.srvlookup ? "_sip._udp" : NULL) < 0) {
03299 ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
03300 return FALSE;
03301 }
03302 }
03303 proxy->last_dnsupdate = time(NULL);
03304 return TRUE;
03305 }
03306
03307
03308
03309
03310
03311 static int port_str2int(const char *pt, unsigned int standard)
03312 {
03313 int port = standard;
03314 if (ast_strlen_zero(pt) || (sscanf(pt, "%30d", &port) != 1) || (port < 1) || (port > 65535)) {
03315 port = standard;
03316 }
03317
03318 return port;
03319 }
03320
03321
03322 static struct sip_proxy *proxy_allocate(char *name, char *port, int force)
03323 {
03324 struct sip_proxy *proxy;
03325
03326 if (ast_strlen_zero(name)) {
03327 return NULL;
03328 }
03329
03330 proxy = ao2_alloc(sizeof(*proxy), NULL);
03331 if (!proxy)
03332 return NULL;
03333 proxy->force = force;
03334 ast_copy_string(proxy->name, name, sizeof(proxy->name));
03335 proxy->ip.sin_port = htons(port_str2int(port, STANDARD_SIP_PORT));
03336 proxy_update(proxy);
03337 return proxy;
03338 }
03339
03340
03341 static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
03342 {
03343 if (peer && peer->outboundproxy) {
03344 if (sipdebug)
03345 ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
03346 append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
03347 return peer->outboundproxy;
03348 }
03349 if (sip_cfg.outboundproxy.name[0]) {
03350 if (sipdebug)
03351 ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
03352 append_history(dialog, "OBproxy", "Using global obproxy %s", sip_cfg.outboundproxy.name);
03353 return &sip_cfg.outboundproxy;
03354 }
03355 if (sipdebug)
03356 ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
03357 return NULL;
03358 }
03359
03360
03361
03362
03363
03364
03365
03366 static int method_match(enum sipmethod id, const char *name)
03367 {
03368 int len = strlen(sip_methods[id].text);
03369 int l_name = name ? strlen(name) : 0;
03370
03371 return (l_name >= len && name[len] < 33 &&
03372 !strncasecmp(sip_methods[id].text, name, len));
03373 }
03374
03375
03376 static int find_sip_method(const char *msg)
03377 {
03378 int i, res = 0;
03379
03380 if (ast_strlen_zero(msg))
03381 return 0;
03382 for (i = 1; i < ARRAY_LEN(sip_methods) && !res; i++) {
03383 if (method_match(i, msg))
03384 res = sip_methods[i].id;
03385 }
03386 return res;
03387 }
03388
03389
03390 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported)
03391 {
03392 char *next, *sep;
03393 char *temp;
03394 unsigned int profile = 0;
03395 int i, found;
03396
03397 if (ast_strlen_zero(supported) )
03398 return 0;
03399 temp = ast_strdupa(supported);
03400
03401 if (sipdebug)
03402 ast_debug(3, "Begin: parsing SIP \"Supported: %s\"\n", supported);
03403
03404 for (next = temp; next; next = sep) {
03405 found = FALSE;
03406 if ( (sep = strchr(next, ',')) != NULL)
03407 *sep++ = '\0';
03408 next = ast_skip_blanks(next);
03409 if (sipdebug)
03410 ast_debug(3, "Found SIP option: -%s-\n", next);
03411 for (i = 0; i < ARRAY_LEN(sip_options); i++) {
03412 if (!strcasecmp(next, sip_options[i].text)) {
03413 profile |= sip_options[i].id;
03414 found = TRUE;
03415 if (sipdebug)
03416 ast_debug(3, "Matched SIP option: %s\n", next);
03417 break;
03418 }
03419 }
03420
03421
03422
03423
03424
03425 if (!found)
03426 profile |= SIP_OPT_UNKNOWN;
03427
03428 if (!found && sipdebug) {
03429 if (!strncasecmp(next, "x-", 2))
03430 ast_debug(3, "Found private SIP option, not supported: %s\n", next);
03431 else
03432 ast_debug(3, "Found no match for SIP option: %s (Please file bug report!)\n", next);
03433 }
03434 }
03435
03436 if (pvt)
03437 pvt->sipoptions = profile;
03438 return profile;
03439 }
03440
03441
03442 static inline int sip_debug_test_addr(const struct sockaddr_in *addr)
03443 {
03444 if (!sipdebug)
03445 return 0;
03446 if (debugaddr.sin_addr.s_addr) {
03447 if (((ntohs(debugaddr.sin_port) != 0)
03448 && (debugaddr.sin_port != addr->sin_port))
03449 || (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
03450 return 0;
03451 }
03452 return 1;
03453 }
03454
03455
03456 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p)
03457 {
03458 if (p->outboundproxy)
03459 return &p->outboundproxy->ip;
03460
03461 return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? &p->recv : &p->sa;
03462 }
03463
03464
03465 static const char *sip_nat_mode(const struct sip_pvt *p)
03466 {
03467 return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? "NAT" : "no NAT";
03468 }
03469
03470
03471 static inline int sip_debug_test_pvt(struct sip_pvt *p)
03472 {
03473 if (!sipdebug)
03474 return 0;
03475 return sip_debug_test_addr(sip_real_dst(p));
03476 }
03477
03478
03479 static int get_transport_str2enum(const char *transport)
03480 {
03481 int res = 0;
03482
03483 if (ast_strlen_zero(transport)) {
03484 return res;
03485 }
03486
03487 if (!strcasecmp(transport, "udp")) {
03488 res |= SIP_TRANSPORT_UDP;
03489 }
03490 if (!strcasecmp(transport, "tcp")) {
03491 res |= SIP_TRANSPORT_TCP;
03492 }
03493 if (!strcasecmp(transport, "tls")) {
03494 res |= SIP_TRANSPORT_TLS;
03495 }
03496
03497 return res;
03498 }
03499
03500
03501 static inline const char *get_transport_list(unsigned int transports) {
03502 switch (transports) {
03503 case SIP_TRANSPORT_UDP:
03504 return "UDP";
03505 case SIP_TRANSPORT_TCP:
03506 return "TCP";
03507 case SIP_TRANSPORT_TLS:
03508 return "TLS";
03509 case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TCP:
03510 return "TCP,UDP";
03511 case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TLS:
03512 return "TLS,UDP";
03513 case SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS:
03514 return "TLS,TCP";
03515 default:
03516 return transports ?
03517 "TLS,TCP,UDP" : "UNKNOWN";
03518 }
03519 }
03520
03521
03522 static inline const char *get_transport(enum sip_transport t)
03523 {
03524 switch (t) {
03525 case SIP_TRANSPORT_UDP:
03526 return "UDP";
03527 case SIP_TRANSPORT_TCP:
03528 return "TCP";
03529 case SIP_TRANSPORT_TLS:
03530 return "TLS";
03531 }
03532
03533 return "UNKNOWN";
03534 }
03535
03536
03537
03538
03539
03540
03541
03542 static inline const char *get_transport_pvt(struct sip_pvt *p)
03543 {
03544 if (p->outboundproxy && p->outboundproxy->transport) {
03545 set_socket_transport(&p->socket, p->outboundproxy->transport);
03546 }
03547
03548 return get_transport(p->socket.type);
03549 }
03550
03551
03552
03553
03554
03555
03556 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len)
03557 {
03558 int res = 0;
03559 const struct sockaddr_in *dst = sip_real_dst(p);
03560
03561 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));
03562
03563 if (sip_prepare_socket(p) < 0)
03564 return XMIT_ERROR;
03565
03566 if (p->socket.type == SIP_TRANSPORT_UDP) {
03567 res = sendto(p->socket.fd, data->str, len, 0, (const struct sockaddr *)dst, sizeof(struct sockaddr_in));
03568 } else if (p->socket.tcptls_session) {
03569 res = sip_tcptls_write(p->socket.tcptls_session, data->str, len);
03570 } else {
03571 ast_debug(2, "Socket type is TCP but no tcptls_session is present to write to\n");
03572 return XMIT_ERROR;
03573 }
03574
03575 if (res == -1) {
03576 switch (errno) {
03577 case EBADF:
03578 case EHOSTUNREACH:
03579 case ENETDOWN:
03580 case ENETUNREACH:
03581 case ECONNREFUSED:
03582 res = XMIT_ERROR;
03583 }
03584 }
03585 if (res != len)
03586 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));
03587
03588 return res;
03589 }
03590
03591
03592 static void build_via(struct sip_pvt *p)
03593 {
03594
03595 const char *rport = ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_RFC3581 ? ";rport" : "";
03596
03597
03598 snprintf(p->via, sizeof(p->via), "SIP/2.0/%s %s:%d;branch=z9hG4bK%08x%s",
03599 get_transport_pvt(p),
03600 ast_inet_ntoa(p->ourip.sin_addr),
03601 ntohs(p->ourip.sin_port), (int) p->branch, rport);
03602 }
03603
03604
03605
03606
03607
03608
03609
03610
03611 static void ast_sip_ouraddrfor(struct in_addr *them, struct sockaddr_in *us, struct sip_pvt *p)
03612 {
03613 struct sockaddr_in theirs;
03614
03615
03616
03617
03618
03619
03620
03621
03622
03623
03624
03625
03626 int want_remap;
03627
03628 *us = internip;
03629
03630 ast_ouraddrfor(them, &us->sin_addr);
03631 theirs.sin_addr = *them;
03632
03633 want_remap = localaddr &&
03634 (externip.sin_addr.s_addr || stunaddr.sin_addr.s_addr) &&
03635 ast_apply_ha(localaddr, &theirs) == AST_SENSE_ALLOW ;
03636
03637 if (want_remap &&
03638 (!sip_cfg.matchexterniplocally || !ast_apply_ha(localaddr, us)) ) {
03639
03640 if (externexpire && time(NULL) >= externexpire) {
03641 if (stunaddr.sin_addr.s_addr) {
03642 ast_stun_request(sipsock, &stunaddr, NULL, &externip);
03643 } else {
03644 if (ast_parse_arg(externhost, PARSE_INADDR, &externip))
03645 ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
03646 }
03647 externexpire = time(NULL) + externrefresh;
03648 }
03649 if (externip.sin_addr.s_addr)
03650 *us = externip;
03651 else
03652 ast_log(LOG_WARNING, "stun failed\n");
03653 ast_debug(1, "Target address %s is not local, substituting externip\n",
03654 ast_inet_ntoa(*(struct in_addr *)&them->s_addr));
03655 } else if (p) {
03656
03657 switch (p->socket.type) {
03658 case SIP_TRANSPORT_TCP:
03659 if (sip_tcp_desc.local_address.sin_addr.s_addr) {
03660 *us = sip_tcp_desc.local_address;
03661 } else {
03662 us->sin_port = sip_tcp_desc.local_address.sin_port;
03663 }
03664 break;
03665 case SIP_TRANSPORT_TLS:
03666 if (sip_tls_desc.local_address.sin_addr.s_addr) {
03667 *us = sip_tls_desc.local_address;
03668 } else {
03669 us->sin_port = sip_tls_desc.local_address.sin_port;
03670 }
03671 break;
03672 case SIP_TRANSPORT_UDP:
03673
03674 default:
03675 if (bindaddr.sin_addr.s_addr) {
03676 *us = bindaddr;
03677 }
03678 }
03679 } else if (bindaddr.sin_addr.s_addr) {
03680 *us = bindaddr;
03681 }
03682 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));
03683 }
03684
03685
03686 static __attribute__((format(printf, 2, 0))) void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
03687 {
03688 char buf[80], *c = buf;
03689 struct sip_history *hist;
03690 int l;
03691
03692 vsnprintf(buf, sizeof(buf), fmt, ap);
03693 strsep(&c, "\r\n");
03694 l = strlen(buf) + 1;
03695 if (!(hist = ast_calloc(1, sizeof(*hist) + l)))
03696 return;
03697 if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
03698 ast_free(hist);
03699 return;
03700 }
03701 memcpy(hist->event, buf, l);
03702 if (p->history_entries == MAX_HISTORY_ENTRIES) {
03703 struct sip_history *oldest;
03704 oldest = AST_LIST_REMOVE_HEAD(p->history, list);
03705 p->history_entries--;
03706 ast_free(oldest);
03707 }
03708 AST_LIST_INSERT_TAIL(p->history, hist, list);
03709 p->history_entries++;
03710 }
03711
03712
03713 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
03714 {
03715 va_list ap;
03716
03717 if (!p)
03718 return;
03719
03720 if (!p->do_history && !recordhistory && !dumphistory)
03721 return;
03722
03723 va_start(ap, fmt);
03724 append_history_va(p, fmt, ap);
03725 va_end(ap);
03726
03727 return;
03728 }
03729
03730
03731 static int retrans_pkt(const void *data)
03732 {
03733 struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
03734 int reschedule = DEFAULT_RETRANS;
03735 int xmitres = 0;
03736
03737
03738 sip_pvt_lock(pkt->owner);
03739
03740 if (pkt->retrans < MAX_RETRANS) {
03741 pkt->retrans++;
03742 if (!pkt->timer_t1) {
03743 if (sipdebug)
03744 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);
03745 } else {
03746 int siptimer_a;
03747
03748 if (sipdebug)
03749 ast_debug(4, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n", pkt->retransid, pkt->retrans, sip_methods[pkt->method].text, pkt->method);
03750 if (!pkt->timer_a)
03751 pkt->timer_a = 2 ;
03752 else
03753 pkt->timer_a = 2 * pkt->timer_a;
03754
03755
03756 siptimer_a = pkt->timer_t1 * pkt->timer_a;
03757 if (pkt->method != SIP_INVITE && siptimer_a > 4000)
03758 siptimer_a = 4000;
03759
03760
03761 reschedule = siptimer_a;
03762 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);
03763 }
03764
03765 if (sip_debug_test_pvt(pkt->owner)) {
03766 const struct sockaddr_in *dst = sip_real_dst(pkt->owner);
03767 ast_verbose("Retransmitting #%d (%s) to %s:%d:\n%s\n---\n",
03768 pkt->retrans, sip_nat_mode(pkt->owner),
03769 ast_inet_ntoa(dst->sin_addr),
03770 ntohs(dst->sin_port), pkt->data->str);
03771 }
03772
03773 append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data->str);
03774 xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
03775 sip_pvt_unlock(pkt->owner);
03776 if (xmitres == XMIT_ERROR)
03777 ast_log(LOG_WARNING, "Network error on retransmit in dialog %s\n", pkt->owner->callid);
03778 else
03779 return reschedule;
03780 }
03781
03782 if (pkt->owner && pkt->method != SIP_OPTIONS && xmitres == 0) {
03783 if (pkt->is_fatal || sipdebug)
03784 ast_log(LOG_WARNING, "Maximum retries exceeded on transmission %s for seqno %d (%s %s) -- See doc/sip-retransmit.txt.\n",
03785 pkt->owner->callid, pkt->seqno,
03786 pkt->is_fatal ? "Critical" : "Non-critical", pkt->is_resp ? "Response" : "Request");
03787 } else if (pkt->method == SIP_OPTIONS && sipdebug) {
03788 ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s) -- See doc/sip-retransmit.txt.\n", pkt->owner->callid);
03789
03790 }
03791 if (xmitres == XMIT_ERROR) {
03792 ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission on Call ID %s\n", pkt->owner->callid);
03793 append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03794 } else
03795 append_history(pkt->owner, "MaxRetries", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03796
03797 pkt->retransid = -1;
03798
03799 if (pkt->is_fatal) {
03800 while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
03801 sip_pvt_unlock(pkt->owner);
03802 usleep(1);
03803 sip_pvt_lock(pkt->owner);
03804 }
03805
03806 if (pkt->owner->owner && !pkt->owner->owner->hangupcause)
03807 pkt->owner->owner->hangupcause = AST_CAUSE_NO_USER_RESPONSE;
03808
03809 if (pkt->owner->owner) {
03810 sip_alreadygone(pkt->owner);
03811 ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet (see doc/sip-retransmit.txt).\n", pkt->owner->callid);
03812 ast_queue_hangup_with_cause(pkt->owner->owner, AST_CAUSE_PROTOCOL_ERROR);
03813 ast_channel_unlock(pkt->owner->owner);
03814 } else {
03815
03816
03817
03818 if (pkt->method != SIP_OPTIONS && pkt->method != SIP_REGISTER) {
03819 pvt_set_needdestroy(pkt->owner, "no response to critical packet");
03820 sip_alreadygone(pkt->owner);
03821 append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
03822 }
03823 }
03824 }
03825
03826 if (pkt->method == SIP_BYE) {
03827
03828 if (pkt->owner->owner)
03829 ast_channel_unlock(pkt->owner->owner);
03830 append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
03831 pvt_set_needdestroy(pkt->owner, "no response to BYE");
03832 }
03833
03834
03835 for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
03836 if (cur == pkt) {
03837 UNLINK(cur, pkt->owner->packets, prev);
03838 sip_pvt_unlock(pkt->owner);
03839 if (pkt->owner)
03840 pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
03841 if (pkt->data)
03842 ast_free(pkt->data);
03843 pkt->data = NULL;
03844 ast_free(pkt);
03845 return 0;
03846 }
03847 }
03848
03849 ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
03850 sip_pvt_unlock(pkt->owner);
03851 return 0;
03852 }
03853
03854
03855
03856
03857 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)
03858 {
03859 struct sip_pkt *pkt = NULL;
03860 int siptimer_a = DEFAULT_RETRANS;
03861 int xmitres = 0;
03862 int respid;
03863
03864 if (sipmethod == SIP_INVITE) {
03865
03866 p->pendinginvite = seqno;
03867 }
03868
03869
03870
03871
03872 if (!(p->socket.type & SIP_TRANSPORT_UDP)) {
03873 xmitres = __sip_xmit(p, data, len);
03874 if (xmitres == XMIT_ERROR) {
03875 append_history(p, "XmitErr", "%s", fatal ? "(Critical)" : "(Non-critical)");
03876 return AST_FAILURE;
03877 } else {
03878 return AST_SUCCESS;
03879 }
03880 }
03881
03882 if (!(pkt = ast_calloc(1, sizeof(*pkt) + len + 1)))
03883 return AST_FAILURE;
03884
03885 if (!(pkt->data = ast_str_create(len))) {
03886 ast_free(pkt);
03887 return AST_FAILURE;
03888 }
03889 ast_str_set(&pkt->data, 0, "%s%s", data->str, "\0");
03890 pkt->packetlen = len;
03891
03892 pkt->method = sipmethod;
03893 pkt->seqno = seqno;
03894 pkt->is_resp = resp;
03895 pkt->is_fatal = fatal;
03896 pkt->owner = dialog_ref(p, "__sip_reliable_xmit: setting pkt->owner");
03897 pkt->next = p->packets;
03898 p->packets = pkt;
03899 if (resp) {
03900
03901 if (sscanf(ast_str_buffer(pkt->data), "SIP/2.0 %30u", &respid) == 1) {
03902 pkt->response_code = respid;
03903 }
03904 }
03905 pkt->timer_t1 = p->timer_t1;
03906 pkt->retransid = -1;
03907 if (pkt->timer_t1)
03908 siptimer_a = pkt->timer_t1 * 2;
03909
03910
03911 AST_SCHED_REPLACE_VARIABLE(pkt->retransid, sched, siptimer_a, retrans_pkt, pkt, 1);
03912 if (sipdebug)
03913 ast_debug(4, "*** SIP TIMER: Initializing retransmit timer on packet: Id #%d\n", pkt->retransid);
03914
03915 xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
03916
03917 if (xmitres == XMIT_ERROR) {
03918 append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03919 ast_log(LOG_ERROR, "Serious Network Trouble; __sip_xmit returns error for pkt data\n");
03920 AST_SCHED_DEL(sched, pkt->retransid);
03921 p->packets = pkt->next;
03922 pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
03923 ast_free(pkt->data);
03924 ast_free(pkt);
03925 return AST_FAILURE;
03926 } else {
03927 return AST_SUCCESS;
03928 }
03929 }
03930
03931
03932
03933
03934
03935
03936 static int __sip_autodestruct(const void *data)
03937 {
03938 struct sip_pvt *p = (struct sip_pvt *)data;
03939
03940
03941 if (p->subscribed) {
03942 transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE);
03943 p->subscribed = NONE;
03944 append_history(p, "Subscribestatus", "timeout");
03945 ast_debug(3, "Re-scheduled destruction of SIP subscription %s\n", p->callid ? p->callid : "<unknown>");
03946 return 10000;
03947 }
03948
03949
03950 if (p->packets) {
03951 if (!p->needdestroy) {
03952 char method_str[31];
03953 ast_debug(3, "Re-scheduled destruction of SIP call %s\n", p->callid ? p->callid : "<unknown>");
03954 append_history(p, "ReliableXmit", "timeout");
03955 if (sscanf(p->lastmsg, "Tx: %30s", method_str) == 1 || sscanf(p->lastmsg, "Rx: %30s", method_str) == 1) {
03956 if (method_match(SIP_CANCEL, method_str) || method_match(SIP_BYE, method_str)) {
03957 pvt_set_needdestroy(p, "autodestruct");
03958 }
03959 }
03960 return 10000;
03961 } else {
03962
03963 __sip_pretend_ack(p);
03964 }
03965 }
03966
03967 if (p->subscribed == MWI_NOTIFICATION)
03968 if (p->relatedpeer)
03969 p->relatedpeer = unref_peer(p->relatedpeer, "__sip_autodestruct: unref peer p->relatedpeer");
03970
03971
03972 p->autokillid = -1;
03973
03974 if (p->owner) {
03975 ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
03976 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
03977 } else if (p->refer && !p->alreadygone) {
03978 ast_debug(3, "Finally hanging up channel after transfer: %s\n", p->callid);
03979 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
03980 append_history(p, "ReferBYE", "Sending BYE on transferer call leg %s", p->callid);
03981 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
03982 } else {
03983 append_history(p, "AutoDestroy", "%s", p->callid);
03984 ast_debug(3, "Auto destroying SIP dialog '%s'\n", p->callid);
03985 dialog_unlink_all(p, TRUE, TRUE);
03986
03987
03988
03989 }
03990 dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
03991 return 0;
03992 }
03993
03994
03995 static void sip_scheddestroy(struct sip_pvt *p, int ms)
03996 {
03997 if (ms < 0) {
03998 if (p->timer_t1 == 0) {
03999 p->timer_t1 = global_t1;
04000 p->timer_b = global_timer_b;
04001 }
04002 ms = p->timer_t1 * 64;
04003 }
04004 if (sip_debug_test_pvt(p))
04005 ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
04006 if (sip_cancel_destroy(p))
04007 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
04008
04009 if (p->do_history)
04010 append_history(p, "SchedDestroy", "%d ms", ms);
04011 p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, dialog_ref(p, "setting ref as passing into ast_sched_add for __sip_autodestruct"));
04012
04013 if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_schedid > 0)
04014 stop_session_timer(p);
04015 }
04016
04017
04018
04019
04020
04021 static int sip_cancel_destroy(struct sip_pvt *p)
04022 {
04023 int res = 0;
04024 if (p->autokillid > -1) {
04025 int res3;
04026
04027 if (!(res3 = ast_sched_del(sched, p->autokillid))) {
04028 append_history(p, "CancelDestroy", "");
04029 p->autokillid = -1;
04030 dialog_unref(p, "dialog unrefd because autokillid is de-sched'd");
04031 }
04032 }
04033 return res;
04034 }
04035
04036
04037
04038 static int __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
04039 {
04040 struct sip_pkt *cur, *prev = NULL;
04041 const char *msg = "Not Found";
04042 int res = FALSE;
04043
04044
04045
04046
04047
04048
04049 if (p->outboundproxy && !p->outboundproxy->force){
04050 ref_proxy(p, NULL);
04051 }
04052
04053 for (cur = p->packets; cur; prev = cur, cur = cur->next) {
04054 if (cur->seqno != seqno || cur->is_resp != resp)
04055 continue;
04056 if (cur->is_resp || cur->method == sipmethod) {
04057 res = TRUE;
04058 msg = "Found";
04059 if (!resp && (seqno == p->pendinginvite)) {
04060 ast_debug(1, "Acked pending invite %d\n", p->pendinginvite);
04061 p->pendinginvite = 0;
04062 }
04063 if (cur->retransid > -1) {
04064 if (sipdebug)
04065 ast_debug(4, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
04066 }
04067
04068
04069
04070
04071
04072
04073
04074
04075
04076
04077
04078
04079
04080
04081
04082
04083 while (cur->retransid > -1 && ast_sched_del(sched, cur->retransid)) {
04084 sip_pvt_unlock(p);
04085 usleep(1);
04086 sip_pvt_lock(p);
04087 }
04088 UNLINK(cur, p->packets, prev);
04089 dialog_unref(cur->owner, "unref pkt cur->owner dialog from sip ack before freeing pkt");
04090 if (cur->data)
04091 ast_free(cur->data);
04092 ast_free(cur);
04093 break;
04094 }
04095 }
04096 ast_debug(1, "Stopping retransmission on '%s' of %s %d: Match %s\n",
04097 p->callid, resp ? "Response" : "Request", seqno, msg);
04098 return res;
04099 }
04100
04101
04102
04103 static void __sip_pretend_ack(struct sip_pvt *p)
04104 {
04105 struct sip_pkt *cur = NULL;
04106
04107 while (p->packets) {
04108 int method;
04109 if (cur == p->packets) {
04110 ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
04111 return;
04112 }
04113 cur = p->packets;
04114 method = (cur->method) ? cur->method : find_sip_method(cur->data->str);
04115 __sip_ack(p, cur->seqno, cur->is_resp, method);
04116 }
04117 }
04118
04119
04120 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
04121 {
04122 struct sip_pkt *cur;
04123 int res = FALSE;
04124
04125 for (cur = p->packets; cur; cur = cur->next) {
04126 if (cur->seqno == seqno && cur->is_resp == resp &&
04127 (cur->is_resp || method_match(sipmethod, cur->data->str))) {
04128
04129 if (cur->retransid > -1) {
04130 if (sipdebug)
04131 ast_debug(4, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
04132 }
04133 AST_SCHED_DEL(sched, cur->retransid);
04134 res = TRUE;
04135 break;
04136 }
04137 }
04138 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");
04139 return res;
04140 }
04141
04142
04143
04144 static void parse_copy(struct sip_request *dst, const struct sip_request *src)
04145 {
04146 copy_request(dst, src);
04147 parse_request(dst);
04148 }
04149
04150
04151 static void add_blank(struct sip_request *req)
04152 {
04153 if (!req->lines) {
04154
04155 ast_str_append(&req->data, 0, "\r\n");
04156 req->len = ast_str_strlen(req->data);
04157 }
04158 }
04159
04160 static int send_provisional_keepalive_full(struct sip_pvt *pvt, int with_sdp)
04161 {
04162 const char *msg = NULL;
04163
04164 if (!pvt->last_provisional || !strncasecmp(pvt->last_provisional, "100", 3)) {
04165 msg = "183 Session Progress";
04166 }
04167
04168 if (pvt->invitestate < INV_COMPLETED) {
04169 if (with_sdp) {
04170 transmit_response_with_sdp(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq, XMIT_UNRELIABLE, FALSE);
04171 } else {
04172 transmit_response(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq);
04173 }
04174 return PROVIS_KEEPALIVE_TIMEOUT;
04175 }
04176
04177 return 0;
04178 }
04179
04180 static int send_provisional_keepalive(const void *data) {
04181 struct sip_pvt *pvt = (struct sip_pvt *) data;
04182
04183 return send_provisional_keepalive_full(pvt, 0);
04184 }
04185
04186 static int send_provisional_keepalive_with_sdp(const void *data) {
04187 struct sip_pvt *pvt = (void *)data;
04188
04189 return send_provisional_keepalive_full(pvt, 1);
04190 }
04191
04192 static void update_provisional_keepalive(struct sip_pvt *pvt, int with_sdp)
04193 {
04194 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"));
04195
04196 pvt->provisional_keepalive_sched_id = ast_sched_add(sched, PROVIS_KEEPALIVE_TIMEOUT,
04197 with_sdp ? send_provisional_keepalive_with_sdp : send_provisional_keepalive, dialog_ref(pvt, "Increment refcount to pass dialog pointer to sched callback"));
04198 }
04199
04200
04201 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
04202 {
04203 int res;
04204
04205 add_blank(req);
04206 if (sip_debug_test_pvt(p)) {
04207 const struct sockaddr_in *dst = sip_real_dst(p);
04208
04209 ast_verbose("\n<--- %sTransmitting (%s) to %s:%d --->\n%s\n<------------>\n",
04210 reliable ? "Reliably " : "", sip_nat_mode(p),
04211 ast_inet_ntoa(dst->sin_addr),
04212 ntohs(dst->sin_port), req->data->str);
04213 }
04214 if (p->do_history) {
04215 struct sip_request tmp = { .rlPart1 = 0, };
04216 parse_copy(&tmp, req);
04217 append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", tmp.data->str, get_header(&tmp, "CSeq"),
04218 (tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? REQ_OFFSET_TO_STR(&tmp, rlPart2) : sip_methods[tmp.method].text);
04219 ast_free(tmp.data);
04220 }
04221
04222
04223 if (p->initreq.method == SIP_INVITE && reliable == XMIT_CRITICAL) {
04224 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"));
04225 }
04226
04227 res = (reliable) ?
04228 __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
04229 __sip_xmit(p, req->data, req->len);
04230 ast_free(req->data);
04231 req->data = NULL;
04232 if (res > 0)
04233 return 0;
04234 return res;
04235 }
04236
04237
04238 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
04239 {
04240 int res;
04241
04242
04243
04244
04245 if (p->outboundproxy) {
04246 p->sa = p->outboundproxy->ip;
04247 }
04248
04249 add_blank(req);
04250 if (sip_debug_test_pvt(p)) {
04251 if (ast_test_flag(&p->flags[0], SIP_NAT_ROUTE))
04252 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);
04253 else
04254 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);
04255 }
04256 if (p->do_history) {
04257 struct sip_request tmp = { .rlPart1 = 0, };
04258 parse_copy(&tmp, req);
04259 append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", tmp.data->str, get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
04260 ast_free(tmp.data);
04261 }
04262 res = (reliable) ?
04263 __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
04264 __sip_xmit(p, req->data, req->len);
04265 if (req->data) {
04266 ast_free(req->data);
04267 req->data = NULL;
04268 }
04269 return res;
04270 }
04271
04272
04273 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen)
04274 {
04275 int res = -1;
04276 enum ast_t38_state state = T38_STATE_UNAVAILABLE;
04277 struct sip_pvt *p = (struct sip_pvt *) chan->tech_pvt;
04278
04279 switch (option) {
04280 case AST_OPTION_T38_STATE:
04281
04282 if (*datalen != sizeof(enum ast_t38_state)) {
04283 ast_log(LOG_ERROR, "Invalid datalen for AST_OPTION_T38_STATE option. Expected %d, got %d\n", (int)sizeof(enum ast_t38_state), *datalen);
04284 return -1;
04285 }
04286
04287 sip_pvt_lock(p);
04288
04289
04290 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
04291 switch (p->t38.state) {
04292 case T38_LOCAL_REINVITE:
04293 case T38_PEER_REINVITE:
04294 state = T38_STATE_NEGOTIATING;
04295 break;
04296 case T38_ENABLED:
04297 state = T38_STATE_NEGOTIATED;
04298 break;
04299 default:
04300 state = T38_STATE_UNKNOWN;
04301 }
04302 }
04303
04304 sip_pvt_unlock(p);
04305
04306 *((enum ast_t38_state *) data) = state;
04307 res = 0;
04308
04309 break;
04310 default:
04311 break;
04312 }
04313
04314 return res;
04315 }
04316
04317
04318
04319
04320
04321 static const char *find_closing_quote(const char *start, const char *lim)
04322 {
04323 char last_char = '\0';
04324 const char *s;
04325 for (s = start; *s && s != lim; last_char = *s++) {
04326 if (*s == '"' && last_char != '\\')
04327 break;
04328 }
04329 return s;
04330 }
04331
04332
04333
04334
04335
04336
04337
04338
04339
04340
04341
04342
04343
04344 static char *get_in_brackets(char *tmp)
04345 {
04346 const char *parse = tmp;
04347 char *first_bracket;
04348
04349
04350
04351
04352
04353 while ( (first_bracket = strchr(parse, '<')) ) {
04354 char *first_quote = strchr(parse, '"');
04355
04356 if (!first_quote || first_quote > first_bracket)
04357 break;
04358
04359 parse = find_closing_quote(first_quote + 1, NULL);
04360 if (!*parse) {
04361
04362 ast_log(LOG_WARNING, "No closing quote found in '%s'\n", tmp);
04363 break;
04364 }
04365 parse++;
04366 }
04367 if (first_bracket) {
04368 char *second_bracket = strchr(first_bracket + 1, '>');
04369 if (second_bracket) {
04370 *second_bracket = '\0';
04371 tmp = first_bracket + 1;
04372 } else {
04373 ast_log(LOG_WARNING, "No closing bracket found in '%s'\n", tmp);
04374 }
04375 }
04376
04377 return tmp;
04378 }
04379
04380
04381
04382
04383
04384
04385
04386
04387
04388
04389
04390
04391
04392
04393
04394
04395
04396
04397
04398
04399 static int parse_uri(char *uri, const char *scheme,
04400 char **ret_name, char **pass, char **domain, char **port, char **options, char **transport)
04401 {
04402 char *name = NULL;
04403 int error = 0;
04404
04405
04406 if (pass)
04407 *pass = "";
04408 if (port)
04409 *port = "";
04410 if (scheme) {
04411 int l;
04412 char *scheme2 = ast_strdupa(scheme);
04413 char *cur = strsep(&scheme2, ",");
04414 for (; !ast_strlen_zero(cur); cur = strsep(&scheme2, ",")) {
04415 l = strlen(cur);
04416 if (!strncasecmp(uri, cur, l)) {
04417 uri += l;
04418 break;
04419 }
04420 }
04421 if (ast_strlen_zero(cur)) {
04422 ast_debug(1, "No supported scheme found in '%s' using the scheme[s] %s\n", uri, scheme);
04423 error = -1;
04424 }
04425 }
04426 if (transport) {
04427 char *t, *type = "";
04428 *transport = "";
04429 if ((t = strstr(uri, "transport="))) {
04430 strsep(&t, "=");
04431 if ((type = strsep(&t, ";"))) {
04432 *transport = type;
04433 }
04434 }
04435 }
04436
04437 if (!domain) {
04438
04439
04440
04441 } else {
04442
04443
04444
04445 char *c, *dom = "";
04446
04447 if ((c = strchr(uri, '@')) == NULL) {
04448
04449 dom = uri;
04450 name = "";
04451 } else {
04452 *c++ = '\0';
04453 dom = c;
04454 name = uri;
04455 }
04456
04457
04458 dom = strsep(&dom, ";");
04459 name = strsep(&name, ";");
04460
04461 if (port && (c = strchr(dom, ':'))) {
04462 *c++ = '\0';
04463 *port = c;
04464 }
04465 if (pass && (c = strchr(name, ':'))) {
04466 *c++ = '\0';
04467 *pass = c;
04468 }
04469 *domain = dom;
04470 }
04471 if (ret_name)
04472 *ret_name = name;
04473 if (options)
04474 *options = uri ? uri : "";
04475
04476 return error;
04477 }
04478
04479
04480 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
04481 {
04482 struct sip_pvt *p = chan->tech_pvt;
04483
04484 if (subclass != AST_HTML_URL)
04485 return -1;
04486
04487 ast_string_field_build(p, url, "<%s>;mode=active", data);
04488
04489 if (sip_debug_test_pvt(p))
04490 ast_debug(1, "Send URL %s, state = %d!\n", data, chan->_state);
04491
04492 switch (chan->_state) {
04493 case AST_STATE_RING:
04494 transmit_response(p, "100 Trying", &p->initreq);
04495 break;
04496 case AST_STATE_RINGING:
04497 transmit_response(p, "180 Ringing", &p->initreq);
04498 break;
04499 case AST_STATE_UP:
04500 if (!p->pendinginvite) {
04501 transmit_reinvite_with_sdp(p, FALSE, FALSE);
04502 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
04503 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
04504 }
04505 break;
04506 default:
04507 ast_log(LOG_WARNING, "Don't know how to send URI when state is %d!\n", chan->_state);
04508 }
04509
04510 return 0;
04511 }
04512
04513
04514 static const char *sip_get_callid(struct ast_channel *chan)
04515 {
04516 return chan->tech_pvt ? ((struct sip_pvt *) chan->tech_pvt)->callid : "";
04517 }
04518
04519
04520
04521 static int sip_sendtext(struct ast_channel *ast, const char *text)
04522 {
04523 struct sip_pvt *p = ast->tech_pvt;
04524 int debug = sip_debug_test_pvt(p);
04525
04526 if (debug)
04527 ast_verbose("Sending text %s on %s\n", text, ast->name);
04528 if (!p)
04529 return -1;
04530
04531
04532 if (!text)
04533 return 0;
04534 if (debug)
04535 ast_verbose("Really sending text %s on %s\n", text, ast->name);
04536 transmit_message_with_text(p, text);
04537 return 0;
04538 }
04539
04540
04541
04542
04543
04544
04545 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)
04546 {
04547 char port[10];
04548 char ipaddr[INET_ADDRSTRLEN];
04549 char regseconds[20];
04550 char *tablename = NULL;
04551 char str_lastms[20];
04552
04553 const char *sysname = ast_config_AST_SYSTEM_NAME;
04554 char *syslabel = NULL;
04555
04556 time_t nowtime = time(NULL) + expirey;
04557 const char *fc = fullcontact ? "fullcontact" : NULL;
04558
04559 int realtimeregs = ast_check_realtime("sipregs");
04560
04561 tablename = realtimeregs ? "sipregs" : "sippeers";
04562
04563
04564 snprintf(str_lastms, sizeof(str_lastms), "%d", lastms);
04565 snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime);
04566 ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
04567 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
04568
04569 if (ast_strlen_zero(sysname))
04570 sysname = NULL;
04571 else if (sip_cfg.rtsave_sysname)
04572 syslabel = "regserver";
04573
04574 if (fc) {
04575 ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
04576 "port", port, "regseconds", regseconds,
04577 deprecated_username ? "username" : "defaultuser", defaultuser,
04578 "useragent", useragent, "lastms", str_lastms,
04579 fc, fullcontact, syslabel, sysname, SENTINEL);
04580 } else {
04581 ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
04582 "port", port, "regseconds", regseconds,
04583 "useragent", useragent, "lastms", str_lastms,
04584 deprecated_username ? "username" : "defaultuser", defaultuser,
04585 syslabel, sysname, SENTINEL);
04586 }
04587 }
04588
04589
04590 static void register_peer_exten(struct sip_peer *peer, int onoff)
04591 {
04592 char multi[256];
04593 char *stringp, *ext, *context;
04594 struct pbx_find_info q = { .stacklen = 0 };
04595
04596
04597
04598
04599
04600 if (ast_strlen_zero(global_regcontext))
04601 return;
04602
04603 ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
04604 stringp = multi;
04605 while ((ext = strsep(&stringp, "&"))) {
04606 if ((context = strchr(ext, '@'))) {
04607 *context++ = '\0';
04608 if (!ast_context_find(context)) {
04609 ast_log(LOG_WARNING, "Context %s must exist in regcontext= in sip.conf!\n", context);
04610 continue;
04611 }
04612 } else {
04613 context = global_regcontext;
04614 }
04615 if (onoff) {
04616 if (!ast_exists_extension(NULL, context, ext, 1, NULL)) {
04617 ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
04618 ast_strdup(peer->name), ast_free_ptr, "SIP");
04619 }
04620 } else if (pbx_find_extension(NULL, NULL, &q, context, ext, 1, NULL, "", E_MATCH)) {
04621 ast_context_remove_extension(context, ext, 1, NULL);
04622 }
04623 }
04624 }
04625
04626
04627 static void destroy_mailbox(struct sip_mailbox *mailbox)
04628 {
04629 if (mailbox->mailbox)
04630 ast_free(mailbox->mailbox);
04631 if (mailbox->context)
04632 ast_free(mailbox->context);
04633 if (mailbox->event_sub)
04634 ast_event_unsubscribe(mailbox->event_sub);
04635 ast_free(mailbox);
04636 }
04637
04638
04639 static void clear_peer_mailboxes(struct sip_peer *peer)
04640 {
04641 struct sip_mailbox *mailbox;
04642
04643 while ((mailbox = AST_LIST_REMOVE_HEAD(&peer->mailboxes, entry)))
04644 destroy_mailbox(mailbox);
04645 }
04646
04647 static void sip_destroy_peer_fn(void *peer)
04648 {
04649 sip_destroy_peer(peer);
04650 }
04651
04652
04653 static void sip_destroy_peer(struct sip_peer *peer)
04654 {
04655 ast_debug(3, "Destroying SIP peer %s\n", peer->name);
04656 if (peer->outboundproxy)
04657 ao2_ref(peer->outboundproxy, -1);
04658 peer->outboundproxy = NULL;
04659
04660
04661 if (peer->call) {
04662 dialog_unlink_all(peer->call, TRUE, TRUE);
04663 peer->call = dialog_unref(peer->call, "peer->call is being unset");
04664 }
04665
04666
04667 if (peer->mwipvt) {
04668 dialog_unlink_all(peer->mwipvt, TRUE, TRUE);
04669 peer->mwipvt = dialog_unref(peer->mwipvt, "unreffing peer->mwipvt");
04670 }
04671
04672 if (peer->chanvars) {
04673 ast_variables_destroy(peer->chanvars);
04674 peer->chanvars = NULL;
04675 }
04676
04677 register_peer_exten(peer, FALSE);
04678 ast_free_ha(peer->ha);
04679 if (peer->selfdestruct)
04680 ast_atomic_fetchadd_int(&apeerobjs, -1);
04681 else if (peer->is_realtime) {
04682 ast_atomic_fetchadd_int(&rpeerobjs, -1);
04683 ast_debug(3, "-REALTIME- peer Destroyed. Name: %s. Realtime Peer objects: %d\n", peer->name, rpeerobjs);
04684 } else
04685 ast_atomic_fetchadd_int(&speerobjs, -1);
04686 clear_realm_authentication(peer->auth);
04687 peer->auth = NULL;
04688 if (peer->dnsmgr)
04689 ast_dnsmgr_release(peer->dnsmgr);
04690 clear_peer_mailboxes(peer);
04691
04692 if (peer->socket.tcptls_session) {
04693 ao2_ref(peer->socket.tcptls_session, -1);
04694 peer->socket.tcptls_session = NULL;
04695 }
04696
04697 ast_string_field_free_memory(peer);
04698 }
04699
04700
04701 static void update_peer(struct sip_peer *p, int expire)
04702 {
04703 int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
04704 if (sip_cfg.peer_rtupdate &&
04705 (p->is_realtime || rtcachefriends)) {
04706 realtime_update_peer(p->name, &p->addr, p->username, rtcachefriends ? p->fullcontact : NULL, p->useragent, expire, p->deprecated_username, p->lastms);
04707 }
04708 }
04709
04710 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *cfg)
04711 {
04712 struct ast_variable *var = NULL;
04713 struct ast_flags flags = {0};
04714 char *cat = NULL;
04715 const char *insecure;
04716 while ((cat = ast_category_browse(cfg, cat))) {
04717 insecure = ast_variable_retrieve(cfg, cat, "insecure");
04718 set_insecure_flags(&flags, insecure, -1);
04719 if (ast_test_flag(&flags, SIP_INSECURE_PORT)) {
04720 var = ast_category_root(cfg, cat);
04721 break;
04722 }
04723 }
04724 return var;
04725 }
04726
04727 static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername)
04728 {
04729 struct ast_variable *tmp;
04730 for (tmp = var; tmp; tmp = tmp->next) {
04731 if (!newpeername && !strcasecmp(tmp->name, "name"))
04732 newpeername = tmp->value;
04733 }
04734 return newpeername;
04735 }
04736
04737
04738
04739
04740
04741
04742
04743 static struct sip_peer *realtime_peer(const char *newpeername, struct sockaddr_in *sin, int devstate_only)
04744 {
04745 struct sip_peer *peer;
04746 struct ast_variable *var = NULL;
04747 struct ast_variable *varregs = NULL;
04748 struct ast_variable *tmp;
04749 struct ast_config *peerlist = NULL;
04750 char ipaddr[INET_ADDRSTRLEN];
04751 char portstring[6];
04752 char *cat = NULL;
04753 unsigned short portnum;
04754 int realtimeregs = ast_check_realtime("sipregs");
04755
04756
04757 if (newpeername) {
04758 if (realtimeregs)
04759 varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04760
04761 var = ast_load_realtime("sippeers", "name", newpeername, "host", "dynamic", SENTINEL);
04762 if (!var && sin)
04763 var = ast_load_realtime("sippeers", "name", newpeername, "host", ast_inet_ntoa(sin->sin_addr), SENTINEL);
04764 if (!var) {
04765 var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
04766
04767
04768
04769
04770
04771
04772 if (var && sin) {
04773 for (tmp = var; tmp; tmp = tmp->next) {
04774 if (!strcasecmp(tmp->name, "host")) {
04775 struct hostent *hp;
04776 struct ast_hostent ahp;
04777 if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || (memcmp(hp->h_addr, &sin->sin_addr, sizeof(hp->h_addr)))) {
04778
04779 ast_variables_destroy(var);
04780 var = NULL;
04781 }
04782 break;
04783 }
04784 }
04785 }
04786 }
04787 }
04788
04789 if (!var && sin) {
04790 ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
04791 portnum = ntohs(sin->sin_port);
04792 sprintf(portstring, "%u", portnum);
04793 var = ast_load_realtime("sippeers", "host", ipaddr, "port", portstring, SENTINEL);
04794 if (var) {
04795 if (realtimeregs) {
04796 newpeername = get_name_from_variable(var, newpeername);
04797 varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04798 }
04799 } else {
04800 if (realtimeregs)
04801 varregs = ast_load_realtime("sipregs", "ipaddr", ipaddr, "port", portstring, SENTINEL);
04802 else
04803 var = ast_load_realtime("sippeers", "ipaddr", ipaddr, "port", portstring, SENTINEL);
04804 if (varregs) {
04805 newpeername = get_name_from_variable(varregs, newpeername);
04806 var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
04807 }
04808 }
04809 if (!var) {
04810 peerlist = ast_load_realtime_multientry("sippeers", "host", ipaddr, SENTINEL);
04811 if (peerlist) {
04812 var = get_insecure_variable_from_config(peerlist);
04813 if(var) {
04814 if (realtimeregs) {
04815 newpeername = get_name_from_variable(var, newpeername);
04816 varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04817 }
04818 } else {
04819 peerlist = NULL;
04820 cat = NULL;
04821 peerlist = ast_load_realtime_multientry("sippeers", "ipaddr", ipaddr, SENTINEL);
04822 if(peerlist) {
04823 var = get_insecure_variable_from_config(peerlist);
04824 if(var) {
04825 if (realtimeregs) {
04826 newpeername = get_name_from_variable(var, newpeername);
04827 varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04828 }
04829 }
04830 }
04831 }
04832 } else {
04833 if (realtimeregs) {
04834 peerlist = ast_load_realtime_multientry("sipregs", "ipaddr", ipaddr, SENTINEL);
04835 if (peerlist) {
04836 varregs = get_insecure_variable_from_config(peerlist);
04837 if (varregs) {
04838 newpeername = get_name_from_variable(varregs, newpeername);
04839 var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
04840 }
04841 }
04842 } else {
04843 peerlist = ast_load_realtime_multientry("sippeers", "ipaddr", ipaddr, SENTINEL);
04844 if (peerlist) {
04845 var = get_insecure_variable_from_config(peerlist);
04846 if (var) {
04847 newpeername = get_name_from_variable(var, newpeername);
04848 varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04849 }
04850 }
04851 }
04852 }
04853 }
04854 }
04855
04856 if (!var) {
04857 if (peerlist)
04858 ast_config_destroy(peerlist);
04859 return NULL;
04860 }
04861
04862 for (tmp = var; tmp; tmp = tmp->next) {
04863
04864 if (!strcasecmp(tmp->name, "type") &&
04865 !strcasecmp(tmp->value, "user")) {
04866 if(peerlist)
04867 ast_config_destroy(peerlist);
04868 else {
04869 ast_variables_destroy(var);
04870 ast_variables_destroy(varregs);
04871 }
04872 return NULL;
04873 } else if (!newpeername && !strcasecmp(tmp->name, "name")) {
04874 newpeername = tmp->value;
04875 }
04876 }
04877
04878 if (!newpeername) {
04879 ast_log(LOG_WARNING, "Cannot Determine peer name ip=%s\n", ipaddr);
04880 if(peerlist)
04881 ast_config_destroy(peerlist);
04882 else
04883 ast_variables_destroy(var);
04884 return NULL;
04885 }
04886
04887
04888
04889 peer = build_peer(newpeername, var, varregs, TRUE, devstate_only);
04890 if (!peer) {
04891 if(peerlist)
04892 ast_config_destroy(peerlist);
04893 else {
04894 ast_variables_destroy(var);
04895 ast_variables_destroy(varregs);
04896 }
04897 return NULL;
04898 }
04899
04900 ast_debug(3, "-REALTIME- loading peer from database to memory. Name: %s. Peer objects: %d\n", peer->name, rpeerobjs);
04901
04902 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && !devstate_only) {
04903
04904 ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
04905 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
04906 AST_SCHED_REPLACE_UNREF(peer->expire, sched, sip_cfg.rtautoclear * 1000, expire_register, peer,
04907 unref_peer(_data, "remove registration ref"),
04908 unref_peer(peer, "remove registration ref"),
04909 ref_peer(peer, "add registration ref"));
04910 }
04911 ao2_t_link(peers, peer, "link peer into peers table");
04912 if (peer->addr.sin_addr.s_addr) {
04913 ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
04914 }
04915 }
04916 peer->is_realtime = 1;
04917 if (peerlist)
04918 ast_config_destroy(peerlist);
04919 else {
04920 ast_variables_destroy(var);
04921 ast_variables_destroy(varregs);
04922 }
04923
04924 return peer;
04925 }
04926
04927
04928 static int find_by_name(void *obj, void *arg, void *data, int flags)
04929 {
04930 struct sip_peer *search = obj, *match = arg;
04931 int *which_objects = data;
04932
04933
04934 if (strcmp(search->name, match->name)) {
04935 return 0;
04936 }
04937
04938 switch (*which_objects) {
04939 case FINDUSERS:
04940 if (!(search->type & SIP_TYPE_USER)) {
04941 return 0;
04942 }
04943 break;
04944 case FINDPEERS:
04945 if (!(search->type & SIP_TYPE_PEER)) {
04946 return 0;
04947 }
04948 break;
04949 case FINDALLDEVICES:
04950 break;
04951 }
04952
04953 return CMP_MATCH | CMP_STOP;
04954 }
04955
04956
04957
04958
04959
04960
04961
04962
04963
04964
04965
04966
04967
04968
04969 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime, int which_objects, int devstate_only, int transport)
04970 {
04971 struct sip_peer *p = NULL;
04972 struct sip_peer tmp_peer;
04973
04974 if (peer) {
04975 ast_copy_string(tmp_peer.name, peer, sizeof(tmp_peer.name));
04976 p = ao2_t_callback_data(peers, OBJ_POINTER, find_by_name, &tmp_peer, &which_objects, "ao2_find in peers table");
04977 } else if (sin) {
04978 tmp_peer.addr.sin_addr.s_addr = sin->sin_addr.s_addr;
04979 tmp_peer.addr.sin_port = sin->sin_port;
04980 tmp_peer.flags[0].flags = 0;
04981 tmp_peer.transports = transport;
04982 p = ao2_t_find(peers_by_ip, &tmp_peer, OBJ_POINTER, "ao2_find in peers_by_ip table");
04983 if (!p) {
04984 ast_set_flag(&tmp_peer.flags[0], SIP_INSECURE_PORT);
04985 p = ao2_t_find(peers_by_ip, &tmp_peer, OBJ_POINTER, "ao2_find in peers_by_ip table 2");
04986 if (p) {
04987 return p;
04988 }
04989 }
04990 }
04991
04992 if (!p && (realtime || devstate_only)) {
04993 p = realtime_peer(peer, sin, devstate_only);
04994 }
04995
04996 return p;
04997 }
04998
04999
05000 static void do_setnat(struct sip_pvt *p, int natflags)
05001 {
05002 const char *mode = natflags ? "On" : "Off";
05003
05004 if (p->rtp) {
05005 ast_debug(1, "Setting NAT on RTP to %s\n", mode);
05006 ast_rtp_setnat(p->rtp, natflags);
05007 }
05008 if (p->vrtp) {
05009 ast_debug(1, "Setting NAT on VRTP to %s\n", mode);
05010 ast_rtp_setnat(p->vrtp, natflags);
05011 }
05012 if (p->udptl) {
05013 ast_debug(1, "Setting NAT on UDPTL to %s\n", mode);
05014 ast_udptl_setnat(p->udptl, natflags);
05015 }
05016 if (p->trtp) {
05017 ast_debug(1, "Setting NAT on TRTP to %s\n", mode);
05018 ast_rtp_setnat(p->trtp, natflags);
05019 }
05020 }
05021
05022
05023 static void change_t38_state(struct sip_pvt *p, int state)
05024 {
05025 int old = p->t38.state;
05026 struct ast_channel *chan = p->owner;
05027 struct ast_control_t38_parameters parameters = { .request_response = 0 };
05028
05029
05030 if (old == state)
05031 return;
05032
05033 p->t38.state = state;
05034 ast_debug(2, "T38 state changed to %d on channel %s\n", p->t38.state, chan ? chan->name : "<none>");
05035
05036
05037 if (!chan)
05038 return;
05039
05040
05041 switch (state) {
05042 case T38_PEER_REINVITE:
05043 parameters = p->t38.their_parms;
05044 parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
05045 parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
05046 ast_udptl_set_tag(p->udptl, "SIP/%s", p->username);
05047 break;
05048 case T38_ENABLED:
05049 parameters = p->t38.their_parms;
05050 parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
05051 parameters.request_response = AST_T38_NEGOTIATED;
05052 ast_udptl_set_tag(p->udptl, "SIP/%s", p->username);
05053 break;
05054 case T38_DISABLED:
05055 if (old == T38_ENABLED) {
05056 parameters.request_response = AST_T38_TERMINATED;
05057 } else if (old == T38_LOCAL_REINVITE) {
05058 parameters.request_response = AST_T38_REFUSED;
05059 }
05060 break;
05061 case T38_LOCAL_REINVITE:
05062
05063 break;
05064 }
05065
05066
05067 if (parameters.request_response)
05068 ast_queue_control_data(chan, AST_CONTROL_T38_PARAMETERS, ¶meters, sizeof(parameters));
05069 }
05070
05071
05072 static void set_t38_capabilities(struct sip_pvt *p)
05073 {
05074 if (p->udptl) {
05075 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY) {
05076 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
05077 } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_FEC) {
05078 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
05079 } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL) {
05080 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
05081 }
05082 }
05083 }
05084
05085 static void copy_socket_data(struct sip_socket *to_sock, const struct sip_socket *from_sock)
05086 {
05087 if (to_sock->tcptls_session) {
05088 ao2_ref(to_sock->tcptls_session, -1);
05089 to_sock->tcptls_session = NULL;
05090 }
05091
05092 if (from_sock->tcptls_session) {
05093 ao2_ref(from_sock->tcptls_session, +1);
05094 }
05095
05096 *to_sock = *from_sock;
05097 }
05098
05099
05100
05101
05102
05103
05104
05105
05106 static int create_addr_from_peer(struct sip_pvt *dialog, struct sip_peer *peer)
05107 {
05108
05109
05110
05111
05112 if (dialog->socket.type && check_request_transport(peer, dialog))
05113 return -1;
05114 copy_socket_data(&dialog->socket, &peer->socket);
05115
05116 if ((peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr) &&
05117 (!peer->maxms || ((peer->lastms >= 0) && (peer->lastms <= peer->maxms)))) {
05118 dialog->sa = (peer->addr.sin_addr.s_addr) ? peer->addr : peer->defaddr;
05119 dialog->recv = dialog->sa;
05120 } else
05121 return -1;
05122
05123 ast_copy_flags(&dialog->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
05124 ast_copy_flags(&dialog->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
05125 dialog->capability = peer->capability;
05126 if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS) &&
05127 (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT) ||
05128 !(dialog->capability & AST_FORMAT_VIDEO_MASK)) &&
05129 dialog->vrtp) {
05130 ast_rtp_destroy(dialog->vrtp);
05131 dialog->vrtp = NULL;
05132 }
05133 if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_TEXTSUPPORT) && dialog->trtp) {
05134 ast_rtp_destroy(dialog->trtp);
05135 dialog->trtp = NULL;
05136 }
05137 dialog->prefs = peer->prefs;
05138 if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_T38SUPPORT)) {
05139 if (!dialog->udptl) {
05140
05141 dialog->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr);
05142 }
05143 dialog->t38_maxdatagram = peer->t38_maxdatagram;
05144 set_t38_capabilities(dialog);
05145 } else if (dialog->udptl) {
05146 ast_udptl_destroy(dialog->udptl);
05147 dialog->udptl = NULL;
05148 }
05149 do_setnat(dialog, ast_test_flag(&dialog->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
05150
05151 if (dialog->rtp) {
05152 ast_rtp_setdtmf(dialog->rtp, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
05153 ast_rtp_setdtmfcompensate(dialog->rtp, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
05154 ast_rtp_set_rtptimeout(dialog->rtp, peer->rtptimeout);
05155 ast_rtp_set_rtpholdtimeout(dialog->rtp, peer->rtpholdtimeout);
05156 ast_rtp_set_rtpkeepalive(dialog->rtp, peer->rtpkeepalive);
05157
05158 ast_rtp_codec_setpref(dialog->rtp, &dialog->prefs);
05159 dialog->autoframing = peer->autoframing;
05160 }
05161 if (dialog->vrtp) {
05162 ast_rtp_setdtmf(dialog->vrtp, 0);
05163 ast_rtp_setdtmfcompensate(dialog->vrtp, 0);
05164 ast_rtp_set_rtptimeout(dialog->vrtp, peer->rtptimeout);
05165 ast_rtp_set_rtpholdtimeout(dialog->vrtp, peer->rtpholdtimeout);
05166 ast_rtp_set_rtpkeepalive(dialog->vrtp, peer->rtpkeepalive);
05167 }
05168 if (dialog->trtp) {
05169 ast_rtp_setdtmf(dialog->trtp, 0);
05170 ast_rtp_setdtmfcompensate(dialog->trtp, 0);
05171 ast_rtp_set_rtptimeout(dialog->trtp, peer->rtptimeout);
05172 ast_rtp_set_rtpholdtimeout(dialog->trtp, peer->rtpholdtimeout);
05173 ast_rtp_set_rtpkeepalive(dialog->trtp, peer->rtpkeepalive);
05174 }
05175
05176 ast_string_field_set(dialog, peername, peer->name);
05177 ast_string_field_set(dialog, authname, peer->username);
05178 ast_string_field_set(dialog, username, peer->username);
05179 ast_string_field_set(dialog, peersecret, peer->secret);
05180 ast_string_field_set(dialog, peermd5secret, peer->md5secret);
05181 ast_string_field_set(dialog, mohsuggest, peer->mohsuggest);
05182 ast_string_field_set(dialog, mohinterpret, peer->mohinterpret);
05183 ast_string_field_set(dialog, tohost, peer->tohost);
05184 ast_string_field_set(dialog, fullcontact, peer->fullcontact);
05185 ast_string_field_set(dialog, context, peer->context);
05186 ast_string_field_set(dialog, parkinglot, peer->parkinglot);
05187 ref_proxy(dialog, obproxy_get(dialog, peer));
05188 dialog->callgroup = peer->callgroup;
05189 dialog->pickupgroup = peer->pickupgroup;
05190 dialog->allowtransfer = peer->allowtransfer;
05191 dialog->jointnoncodeccapability = dialog->noncodeccapability;
05192 dialog->rtptimeout = peer->rtptimeout;
05193 dialog->peerauth = peer->auth;
05194 dialog->maxcallbitrate = peer->maxcallbitrate;
05195 if (ast_strlen_zero(dialog->tohost))
05196 ast_string_field_set(dialog, tohost, ast_inet_ntoa(dialog->sa.sin_addr));
05197 if (!ast_strlen_zero(peer->fromdomain)) {
05198 ast_string_field_set(dialog, fromdomain, peer->fromdomain);
05199 if (!dialog->initreq.headers) {
05200 char *c;
05201 char *tmpcall = ast_strdupa(dialog->callid);
05202
05203 c = strchr(tmpcall, '@');
05204 if (c) {
05205 *c = '\0';
05206 ao2_t_unlink(dialogs, dialog, "About to change the callid -- remove the old name");
05207 ast_string_field_build(dialog, callid, "%s@%s", tmpcall, peer->fromdomain);
05208 ao2_t_link(dialogs, dialog, "New dialog callid -- inserted back into table");
05209 }
05210 }
05211 }
05212 if (!ast_strlen_zero(peer->fromuser))
05213 ast_string_field_set(dialog, fromuser, peer->fromuser);
05214 if (!ast_strlen_zero(peer->language))
05215 ast_string_field_set(dialog, language, peer->language);
05216
05217
05218
05219
05220 if (peer->maxms && peer->lastms)
05221 dialog->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
05222 else
05223 dialog->timer_t1 = peer->timer_t1;
05224
05225
05226
05227 if (peer->timer_b)
05228 dialog->timer_b = peer->timer_b;
05229 else
05230 dialog->timer_b = 64 * dialog->timer_t1;
05231
05232 if ((ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
05233 (ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
05234 dialog->noncodeccapability |= AST_RTP_DTMF;
05235 else
05236 dialog->noncodeccapability &= ~AST_RTP_DTMF;
05237 if (peer->call_limit)
05238 ast_set_flag(&dialog->flags[0], SIP_CALL_LIMIT);
05239 if (!dialog->portinuri)
05240 dialog->portinuri = peer->portinuri;
05241
05242 dialog->chanvars = copy_vars(peer->chanvars);
05243
05244 return 0;
05245 }
05246
05247
05248
05249
05250 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct sockaddr_in *sin, int newdialog)
05251 {
05252 struct hostent *hp;
05253 struct ast_hostent ahp;
05254 struct sip_peer *peer;
05255 char *port;
05256 int portno = 0;
05257 char host[MAXHOSTNAMELEN], *hostn;
05258 char peername[256];
05259 int srv_ret = 0;
05260
05261 ast_copy_string(peername, opeer, sizeof(peername));
05262 port = strchr(peername, ':');
05263 if (port) {
05264 *port++ = '\0';
05265 dialog->portinuri = 1;
05266 }
05267 dialog->sa.sin_family = AF_INET;
05268 dialog->timer_t1 = global_t1;
05269 dialog->timer_b = global_timer_b;
05270 peer = find_peer(peername, NULL, TRUE, FINDPEERS, FALSE, 0);
05271
05272 if (peer) {
05273 int res;
05274 if (newdialog) {
05275 set_socket_transport(&dialog->socket, 0);
05276 }
05277 res = create_addr_from_peer(dialog, peer);
05278 if (!ast_strlen_zero(port)) {
05279 if ((portno = atoi(port))) {
05280 dialog->sa.sin_port = dialog->recv.sin_port = htons(portno);
05281 }
05282 }
05283 unref_peer(peer, "create_addr: unref peer from find_peer hashtab lookup");
05284 return res;
05285 }
05286
05287 do_setnat(dialog, ast_test_flag(&dialog->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
05288
05289 ast_string_field_set(dialog, tohost, peername);
05290
05291
05292 ref_proxy(dialog, obproxy_get(dialog, NULL));
05293
05294 if (sin) {
05295
05296 memcpy(&dialog->sa.sin_addr, &sin->sin_addr, sizeof(dialog->sa.sin_addr));
05297 if (!sin->sin_port) {
05298 portno = port_str2int(port, (dialog->socket.type == SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT);
05299 } else {
05300 portno = ntohs(sin->sin_port);
05301 }
05302 } else {
05303
05304
05305
05306
05307
05308
05309 hostn = peername;
05310
05311
05312
05313 if (!port && sip_cfg.srvlookup) {
05314 char service[MAXHOSTNAMELEN];
05315 int tportno;
05316
05317 snprintf(service, sizeof(service), "_sip._%s.%s", get_transport(dialog->socket.type), peername);
05318 srv_ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
05319 if (srv_ret > 0) {
05320 hostn = host;
05321 portno = tportno;
05322 }
05323 }
05324 if (!portno)
05325 portno = port_str2int(port, (dialog->socket.type == SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT);
05326 hp = ast_gethostbyname(hostn, &ahp);
05327 if (!hp) {
05328 ast_log(LOG_WARNING, "No such host: %s\n", peername);
05329 return -1;
05330 }
05331 memcpy(&dialog->sa.sin_addr, hp->h_addr, sizeof(dialog->sa.sin_addr));
05332 }
05333
05334 if (!dialog->socket.type)
05335 set_socket_transport(&dialog->socket, SIP_TRANSPORT_UDP);
05336 if (!dialog->socket.port)
05337 dialog->socket.port = bindaddr.sin_port;
05338 dialog->sa.sin_port = htons(portno);
05339 dialog->recv = dialog->sa;
05340 return 0;
05341 }
05342
05343
05344
05345
05346 static int auto_congest(const void *arg)
05347 {
05348 struct sip_pvt *p = (struct sip_pvt *)arg;
05349
05350 sip_pvt_lock(p);
05351 p->initid = -1;
05352 if (p->owner) {
05353
05354 if (!ast_channel_trylock(p->owner)) {
05355 append_history(p, "Cong", "Auto-congesting (timer)");
05356 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
05357 ast_channel_unlock(p->owner);
05358 }
05359
05360
05361 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
05362 }
05363 sip_pvt_unlock(p);
05364 dialog_unref(p, "unreffing arg passed into auto_congest callback (p->initid)");
05365 return 0;
05366 }
05367
05368
05369
05370
05371 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
05372 {
05373 int res;
05374 struct sip_pvt *p = ast->tech_pvt;
05375 struct varshead *headp;
05376 struct ast_var_t *current;
05377 const char *referer = NULL;
05378
05379 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
05380 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
05381 return -1;
05382 }
05383
05384
05385 headp=&ast->varshead;
05386 AST_LIST_TRAVERSE(headp, current, entries) {
05387
05388 if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
05389 p->options->vxml_url = ast_var_value(current);
05390 } else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
05391 p->options->uri_options = ast_var_value(current);
05392 } else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
05393
05394 p->options->addsipheaders = 1;
05395 } else if (!strcasecmp(ast_var_name(current), "SIPFROMDOMAIN")) {
05396 ast_string_field_set(p, fromdomain, ast_var_value(current));
05397 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER")) {
05398
05399 p->options->transfer = 1;
05400 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REFERER")) {
05401
05402 referer = ast_var_value(current);
05403 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REPLACES")) {
05404
05405 p->options->replaces = ast_var_value(current);
05406 }
05407 }
05408
05409 res = 0;
05410 ast_set_flag(&p->flags[0], SIP_OUTGOING);
05411
05412
05413
05414
05415 ast_clear_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_T38);
05416
05417 if (p->options->transfer) {
05418 char buf[SIPBUFSIZE/2];
05419
05420 if (referer) {
05421 if (sipdebug)
05422 ast_debug(3, "Call for %s transfered by %s\n", p->username, referer);
05423 snprintf(buf, sizeof(buf)-1, "-> %s (via %s)", p->cid_name, referer);
05424 } else
05425 snprintf(buf, sizeof(buf)-1, "-> %s", p->cid_name);
05426 ast_string_field_set(p, cid_name, buf);
05427 }
05428 ast_debug(1, "Outgoing Call for %s\n", p->username);
05429
05430 res = update_call_counter(p, INC_CALL_RINGING);
05431
05432 if (res == -1) {
05433 ast->hangupcause = AST_CAUSE_USER_BUSY;
05434 return res;
05435 }
05436 p->callingpres = ast->cid.cid_pres;
05437 p->jointcapability = ast_translate_available_formats(p->capability, p->prefcodec);
05438 p->jointnoncodeccapability = p->noncodeccapability;
05439
05440
05441 if (!(p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
05442 ast_log(LOG_WARNING, "No audio format found to offer. Cancelling call to %s\n", p->username);
05443 res = -1;
05444 } else {
05445 int xmitres;
05446
05447 xmitres = transmit_invite(p, SIP_INVITE, 1, 2);
05448 if (xmitres == XMIT_ERROR)
05449 return -1;
05450 p->invitestate = INV_CALLING;
05451
05452
05453 AST_SCHED_REPLACE_UNREF(p->initid, sched, p->timer_b, auto_congest, p,
05454 dialog_unref(_data, "dialog ptr dec when SCHED_REPLACE del op succeeded"),
05455 dialog_unref(p, "dialog ptr dec when SCHED_REPLACE add failed"),
05456 dialog_ref(p, "dialog ptr inc when SCHED_REPLACE add succeeded") );
05457 }
05458 return res;
05459 }
05460
05461
05462
05463 static void sip_registry_destroy(struct sip_registry *reg)
05464 {
05465
05466 ast_debug(3, "Destroying registry entry for %s@%s\n", reg->username, reg->hostname);
05467
05468 if (reg->call) {
05469
05470
05471 reg->call->registry = registry_unref(reg->call->registry, "destroy reg->call->registry");
05472 ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", reg->username, reg->hostname);
05473 dialog_unlink_all(reg->call, TRUE, TRUE);
05474 reg->call = dialog_unref(reg->call, "unref reg->call");
05475
05476 }
05477 AST_SCHED_DEL(sched, reg->expire);
05478 AST_SCHED_DEL(sched, reg->timeout);
05479
05480 ast_string_field_free_memory(reg);
05481 ast_atomic_fetchadd_int(®objs, -1);
05482 ast_dnsmgr_release(reg->dnsmgr);
05483 ast_free(reg);
05484 }
05485
05486
05487 static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi)
05488 {
05489 if (mwi->call) {
05490 mwi->call->mwi = NULL;
05491 sip_destroy(mwi->call);
05492 }
05493
05494 AST_SCHED_DEL(sched, mwi->resub);
05495 ast_string_field_free_memory(mwi);
05496 ast_dnsmgr_release(mwi->dnsmgr);
05497 ast_free(mwi);
05498 }
05499
05500
05501 static void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist)
05502 {
05503 struct sip_request *req;
05504
05505 if (p->stimer) {
05506 ast_free(p->stimer);
05507 p->stimer = NULL;
05508 }
05509
05510 if (sip_debug_test_pvt(p))
05511 ast_verbose("Really destroying SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
05512
05513 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
05514 update_call_counter(p, DEC_CALL_LIMIT);
05515 ast_debug(2, "This call did not properly clean up call limits. Call ID %s\n", p->callid);
05516 }
05517
05518
05519 if (p->owner) {
05520 if (lockowner)
05521 ast_channel_lock(p->owner);
05522 if (option_debug)
05523 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
05524 p->owner->tech_pvt = NULL;
05525
05526 p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
05527 if (lockowner)
05528 ast_channel_unlock(p->owner);
05529
05530 usleep(1);
05531 }
05532
05533
05534 if (p->relatedpeer && p->relatedpeer->mwipvt)
05535 p->relatedpeer->mwipvt = dialog_unref(p->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
05536 if (p->relatedpeer && p->relatedpeer->call == p)
05537 p->relatedpeer->call = dialog_unref(p->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
05538
05539 if (p->relatedpeer)
05540 p->relatedpeer = unref_peer(p->relatedpeer,"unsetting a dialog relatedpeer field in sip_destroy");
05541
05542 if (p->registry) {
05543 if (p->registry->call == p)
05544 p->registry->call = dialog_unref(p->registry->call, "nulling out the registry's call dialog field in unlink_all");
05545 p->registry = registry_unref(p->registry, "delete p->registry");
05546 }
05547
05548 if (p->mwi) {
05549 p->mwi->call = NULL;
05550 }
05551
05552 if (dumphistory)
05553 sip_dump_history(p);
05554
05555 if (p->options)
05556 ast_free(p->options);
05557
05558 if (p->notify_headers) {
05559 ast_variables_destroy(p->notify_headers);
05560 p->notify_headers = NULL;
05561 }
05562 if (p->rtp) {
05563 ast_rtp_destroy(p->rtp);
05564 }
05565 if (p->vrtp) {
05566 ast_rtp_destroy(p->vrtp);
05567 }
05568 if (p->trtp) {
05569 while (ast_rtp_get_bridged(p->trtp))
05570 usleep(1);
05571 ast_rtp_destroy(p->trtp);
05572 }
05573 if (p->udptl)
05574 ast_udptl_destroy(p->udptl);
05575 if (p->refer)
05576 ast_free(p->refer);
05577 if (p->route) {
05578 free_old_route(p->route);
05579 p->route = NULL;
05580 }
05581 if (p->initreq.data)
05582 ast_free(p->initreq.data);
05583
05584
05585 if (p->stimer) {
05586 p->stimer->quit_flag = 1;
05587 if (p->stimer->st_active == TRUE && p->stimer->st_schedid > -1) {
05588 AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
05589 dialog_unref(p, "removing session timer ref"));
05590 }
05591 ast_free(p->stimer);
05592 p->stimer = NULL;
05593 }
05594
05595
05596 if (p->history) {
05597 struct sip_history *hist;
05598 while ( (hist = AST_LIST_REMOVE_HEAD(p->history, list)) ) {
05599 ast_free(hist);
05600 p->history_entries--;
05601 }
05602 ast_free(p->history);
05603 p->history = NULL;
05604 }
05605
05606 while ((req = AST_LIST_REMOVE_HEAD(&p->request_queue, next))) {
05607 ast_free(req);
05608 }
05609
05610 if (p->chanvars) {
05611 ast_variables_destroy(p->chanvars);
05612 p->chanvars = NULL;
05613 }
05614
05615 ast_string_field_free_memory(p);
05616
05617 if (p->socket.tcptls_session) {
05618 ao2_ref(p->socket.tcptls_session, -1);
05619 p->socket.tcptls_session = NULL;
05620 }
05621 }
05622
05623
05624
05625
05626
05627
05628
05629
05630
05631
05632
05633
05634
05635
05636
05637 static int update_call_counter(struct sip_pvt *fup, int event)
05638 {
05639 char name[256];
05640 int *inuse = NULL, *call_limit = NULL, *inringing = NULL;
05641 int outgoing = fup->outgoing_call;
05642 struct sip_peer *p = NULL;
05643
05644 ast_debug(3, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
05645
05646
05647
05648
05649 if (!ast_test_flag(&fup->flags[0], SIP_CALL_LIMIT) && !ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD))
05650 return 0;
05651
05652 ast_copy_string(name, fup->username, sizeof(name));
05653
05654
05655 if ((p = find_peer(ast_strlen_zero(fup->peername) ? name : fup->peername, NULL, TRUE, FINDALLDEVICES, FALSE, 0))) {
05656 inuse = &p->inUse;
05657 call_limit = &p->call_limit;
05658 inringing = &p->inRinging;
05659 ast_copy_string(name, fup->peername, sizeof(name));
05660 }
05661 if (!p) {
05662 ast_debug(2, "%s is not a local device, no call limit\n", name);
05663 return 0;
05664 }
05665
05666 switch(event) {
05667
05668 case DEC_CALL_LIMIT:
05669
05670 if (inuse) {
05671 sip_pvt_lock(fup);
05672 ao2_lock(p);
05673 if (*inuse > 0) {
05674 if (ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
05675 (*inuse)--;
05676 ast_clear_flag(&fup->flags[0], SIP_INC_COUNT);
05677 }
05678 } else {
05679 *inuse = 0;
05680 }
05681 ao2_unlock(p);
05682 sip_pvt_unlock(fup);
05683 }
05684
05685
05686 if (inringing) {
05687 sip_pvt_lock(fup);
05688 ao2_lock(p);
05689 if (*inringing > 0) {
05690 if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
05691 (*inringing)--;
05692 ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
05693 }
05694 } else {
05695 *inringing = 0;
05696 }
05697 ao2_unlock(p);
05698 sip_pvt_unlock(fup);
05699 }
05700
05701
05702 sip_pvt_lock(fup);
05703 ao2_lock(p);
05704 if (ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD) && sip_cfg.notifyhold) {
05705 ast_clear_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD);
05706 ao2_unlock(p);
05707 sip_pvt_unlock(fup);
05708 sip_peer_hold(fup, FALSE);
05709 } else {
05710 ao2_unlock(p);
05711 sip_pvt_unlock(fup);
05712 }
05713 if (sipdebug)
05714 ast_debug(2, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
05715 break;
05716
05717 case INC_CALL_RINGING:
05718 case INC_CALL_LIMIT:
05719
05720 if (*call_limit > 0 ) {
05721 if (*inuse >= *call_limit) {
05722 ast_log(LOG_NOTICE, "Call %s %s '%s' rejected due to usage limit of %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
05723 unref_peer(p, "update_call_counter: unref peer p, call limit exceeded");
05724 return -1;
05725 }
05726 }
05727 if (inringing && (event == INC_CALL_RINGING)) {
05728 sip_pvt_lock(fup);
05729 ao2_lock(p);
05730 if (!ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
05731 (*inringing)++;
05732 ast_set_flag(&fup->flags[0], SIP_INC_RINGING);
05733 }
05734 ao2_unlock(p);
05735 sip_pvt_unlock(fup);
05736 }
05737 if (inuse) {
05738 sip_pvt_lock(fup);
05739 ao2_lock(p);
05740 if (!ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
05741 (*inuse)++;
05742 ast_set_flag(&fup->flags[0], SIP_INC_COUNT);
05743 }
05744 ao2_unlock(p);
05745 sip_pvt_unlock(fup);
05746 }
05747 if (sipdebug) {
05748 ast_debug(2, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", "peer", name, *inuse, *call_limit);
05749 }
05750 break;
05751
05752 case DEC_CALL_RINGING:
05753 if (inringing) {
05754 sip_pvt_lock(fup);
05755 ao2_lock(p);
05756 if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
05757 if (*inringing > 0) {
05758 (*inringing)--;
05759 }
05760 ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
05761 }
05762 ao2_unlock(p);
05763 sip_pvt_unlock(fup);
05764 }
05765 break;
05766
05767 default:
05768 ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
05769 }
05770
05771 if (p) {
05772 ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", p->name);
05773 unref_peer(p, "update_call_counter: unref_peer from call counter");
05774 }
05775 return 0;
05776 }
05777
05778
05779 static void sip_destroy_fn(void *p)
05780 {
05781 sip_destroy(p);
05782 }
05783
05784
05785
05786
05787
05788
05789 static struct sip_pvt * sip_destroy(struct sip_pvt *p)
05790 {
05791 ast_debug(3, "Destroying SIP dialog %s\n", p->callid);
05792 __sip_destroy(p, TRUE, TRUE);
05793 return NULL;
05794 }
05795
05796
05797 static int hangup_sip2cause(int cause)
05798 {
05799
05800
05801 switch(cause) {
05802 case 401:
05803 return AST_CAUSE_CALL_REJECTED;
05804 case 403:
05805 return AST_CAUSE_CALL_REJECTED;
05806 case 404:
05807 return AST_CAUSE_UNALLOCATED;
05808 case 405:
05809 return AST_CAUSE_INTERWORKING;
05810 case 407:
05811 return AST_CAUSE_CALL_REJECTED;
05812 case 408:
05813 return AST_CAUSE_NO_USER_RESPONSE;
05814 case 409:
05815 return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
05816 case 410:
05817 return AST_CAUSE_NUMBER_CHANGED;
05818 case 411:
05819 return AST_CAUSE_INTERWORKING;
05820 case 413:
05821 return AST_CAUSE_INTERWORKING;
05822 case 414:
05823 return AST_CAUSE_INTERWORKING;
05824 case 415:
05825 return AST_CAUSE_INTERWORKING;
05826 case 420:
05827 return AST_CAUSE_NO_ROUTE_DESTINATION;
05828 case 480:
05829 return AST_CAUSE_NO_ANSWER;
05830 case 481:
05831 return AST_CAUSE_INTERWORKING;
05832 case 482:
05833 return AST_CAUSE_INTERWORKING;
05834 case 483:
05835 return AST_CAUSE_NO_ANSWER;
05836 case 484:
05837 return AST_CAUSE_INVALID_NUMBER_FORMAT;
05838 case 485:
05839 return AST_CAUSE_UNALLOCATED;
05840 case 486:
05841 return AST_CAUSE_BUSY;
05842 case 487:
05843 return AST_CAUSE_INTERWORKING;
05844 case 488:
05845 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
05846 case 491:
05847 return AST_CAUSE_INTERWORKING;
05848 case 493:
05849 return AST_CAUSE_INTERWORKING;
05850 case 500:
05851 return AST_CAUSE_FAILURE;
05852 case 501:
05853 return AST_CAUSE_FACILITY_REJECTED;
05854 case 502:
05855 return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
05856 case 503:
05857 return AST_CAUSE_CONGESTION;
05858 case 504:
05859 return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
05860 case 505:
05861 return AST_CAUSE_INTERWORKING;
05862 case 600:
05863 return AST_CAUSE_USER_BUSY;
05864 case 603:
05865 return AST_CAUSE_CALL_REJECTED;
05866 case 604:
05867 return AST_CAUSE_UNALLOCATED;
05868 case 606:
05869 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
05870 default:
05871 return AST_CAUSE_NORMAL;
05872 }
05873
05874 return 0;
05875 }
05876
05877
05878
05879
05880
05881
05882
05883
05884
05885
05886
05887
05888
05889
05890
05891
05892
05893
05894
05895
05896
05897
05898
05899
05900
05901
05902
05903
05904
05905
05906
05907
05908
05909 static const char *hangup_cause2sip(int cause)
05910 {
05911 switch (cause) {
05912 case AST_CAUSE_UNALLOCATED:
05913 case AST_CAUSE_NO_ROUTE_DESTINATION:
05914 case AST_CAUSE_NO_ROUTE_TRANSIT_NET:
05915 return "404 Not Found";
05916 case AST_CAUSE_CONGESTION:
05917 case AST_CAUSE_SWITCH_CONGESTION:
05918 return "503 Service Unavailable";
05919 case AST_CAUSE_NO_USER_RESPONSE:
05920 return "408 Request Timeout";
05921 case AST_CAUSE_NO_ANSWER:
05922 case AST_CAUSE_UNREGISTERED:
05923 return "480 Temporarily unavailable";
05924 case AST_CAUSE_CALL_REJECTED:
05925 return "403 Forbidden";
05926 case AST_CAUSE_NUMBER_CHANGED:
05927 return "410 Gone";
05928 case AST_CAUSE_NORMAL_UNSPECIFIED:
05929 return "480 Temporarily unavailable";
05930 case AST_CAUSE_INVALID_NUMBER_FORMAT:
05931 return "484 Address incomplete";
05932 case AST_CAUSE_USER_BUSY:
05933 return "486 Busy here";
05934 case AST_CAUSE_FAILURE:
05935 return "500 Server internal failure";
05936 case AST_CAUSE_FACILITY_REJECTED:
05937 return "501 Not Implemented";
05938 case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
05939 return "503 Service Unavailable";
05940
05941 case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
05942 return "502 Bad Gateway";
05943 case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL:
05944 return "488 Not Acceptable Here";
05945
05946 case AST_CAUSE_NOTDEFINED:
05947 default:
05948 ast_debug(1, "AST hangup cause %d (no match found in SIP)\n", cause);
05949 return NULL;
05950 }
05951
05952
05953 return 0;
05954 }
05955
05956
05957
05958
05959 static int sip_hangup(struct ast_channel *ast)
05960 {
05961 struct sip_pvt *p = ast->tech_pvt;
05962 int needcancel = FALSE;
05963 int needdestroy = 0;
05964 struct ast_channel *oldowner = ast;
05965
05966 if (!p) {
05967 ast_debug(1, "Asked to hangup channel that was not connected\n");
05968 return 0;
05969 }
05970 if (ast_test_flag(ast, AST_FLAG_ANSWERED_ELSEWHERE) || ast->hangupcause == AST_CAUSE_ANSWERED_ELSEWHERE) {
05971 ast_debug(1, "This call was answered elsewhere");
05972 if (ast->hangupcause == AST_CAUSE_ANSWERED_ELSEWHERE) {
05973 ast_debug(1, "####### It's the cause code, buddy. The cause code!!!\n");
05974 }
05975 append_history(p, "Cancel", "Call answered elsewhere");
05976 p->answered_elsewhere = TRUE;
05977 }
05978
05979
05980 if (p->owner)
05981 p->hangupcause = p->owner->hangupcause;
05982
05983 if (ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
05984 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
05985 if (sipdebug)
05986 ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
05987 update_call_counter(p, DEC_CALL_LIMIT);
05988 }
05989 ast_debug(4, "SIP Transfer: Not hanging up right now... Rescheduling hangup for %s.\n", p->callid);
05990 if (p->autokillid > -1 && sip_cancel_destroy(p))
05991 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
05992 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
05993 ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
05994 p->needdestroy = 0;
05995 p->owner->tech_pvt = dialog_unref(p->owner->tech_pvt, "unref p->owner->tech_pvt");
05996 sip_pvt_lock(p);
05997 p->owner = NULL;
05998 sip_pvt_unlock(p);
05999 return 0;
06000 }
06001
06002 if (ast_test_flag(ast, AST_FLAG_ZOMBIE)) {
06003 if (p->refer)
06004 ast_debug(1, "SIP Transfer: Hanging up Zombie channel %s after transfer ... Call-ID: %s\n", ast->name, p->callid);
06005 else
06006 ast_debug(1, "Hanging up zombie call. Be scared.\n");
06007 } else
06008 ast_debug(1, "Hangup call %s, SIP callid %s\n", ast->name, p->callid);
06009
06010 sip_pvt_lock(p);
06011 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
06012 if (sipdebug)
06013 ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
06014 update_call_counter(p, DEC_CALL_LIMIT);
06015 }
06016
06017
06018 if (p->owner != ast) {
06019 ast_log(LOG_WARNING, "Huh? We aren't the owner? Can't hangup call.\n");
06020 sip_pvt_unlock(p);
06021 return 0;
06022 }
06023
06024
06025 if (p->invitestate < INV_COMPLETED && p->owner->_state != AST_STATE_UP) {
06026 needcancel = TRUE;
06027 ast_debug(4, "Hanging up channel in state %s (not UP)\n", ast_state2str(ast->_state));
06028 }
06029
06030 stop_media_flows(p);
06031
06032 append_history(p, needcancel ? "Cancel" : "Hangup", "Cause %s", p->owner ? ast_cause2str(p->hangupcause) : "Unknown");
06033
06034
06035 if (p->dsp)
06036 ast_dsp_free(p->dsp);
06037
06038 p->owner = NULL;
06039 ast->tech_pvt = dialog_unref(ast->tech_pvt, "unref ast->tech_pvt");
06040
06041 ast_module_unref(ast_module_info->self);
06042
06043
06044
06045
06046
06047
06048 if (p->alreadygone)
06049 needdestroy = 1;
06050 else if (p->invitestate != INV_CALLING)
06051 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06052
06053
06054 if (!p->alreadygone && p->initreq.data && !ast_strlen_zero(p->initreq.data->str)) {
06055 if (needcancel) {
06056 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06057
06058
06059 if (p->invitestate == INV_CALLING) {
06060
06061 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
06062 __sip_pretend_ack(p);
06063
06064 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06065 append_history(p, "DELAY", "Not sending cancel, waiting for timeout");
06066 } else {
06067 struct sip_pkt *cur;
06068
06069 for (cur = p->packets; cur; cur = cur->next) {
06070 __sip_semi_ack(p, cur->seqno, cur->is_resp, cur->method ? cur->method : find_sip_method(cur->data->str));
06071 }
06072 p->invitestate = INV_CANCELLED;
06073
06074 transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
06075
06076
06077 needdestroy = 0;
06078 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06079 }
06080 } else {
06081 const char *res;
06082 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"));
06083 if (p->hangupcause && (res = hangup_cause2sip(p->hangupcause)))
06084 transmit_response_reliable(p, res, &p->initreq);
06085 else
06086 transmit_response_reliable(p, "603 Declined", &p->initreq);
06087 p->invitestate = INV_TERMINATED;
06088 }
06089 } else {
06090 if (p->stimer->st_active == TRUE) {
06091 stop_session_timer(p);
06092 }
06093
06094 if (!p->pendinginvite) {
06095 struct ast_channel *bridge = ast_bridged_channel(oldowner);
06096 char *audioqos = "";
06097 char *videoqos = "";
06098 char *textqos = "";
06099
06100
06101
06102
06103 while (bridge && ast_channel_trylock(bridge)) {
06104 sip_pvt_unlock(p);
06105 do {
06106
06107 CHANNEL_DEADLOCK_AVOIDANCE(oldowner);
06108 } while (sip_pvt_trylock(p));
06109 bridge = ast_bridged_channel(oldowner);
06110 }
06111
06112 if (p->rtp)
06113 ast_rtp_set_vars(oldowner, p->rtp);
06114
06115 if (bridge) {
06116 struct sip_pvt *q = bridge->tech_pvt;
06117
06118 if (IS_SIP_TECH(bridge->tech) && q && q->rtp)
06119 ast_rtp_set_vars(bridge, q->rtp);
06120 ast_channel_unlock(bridge);
06121 }
06122
06123 if (p->vrtp)
06124 videoqos = ast_rtp_get_quality(p->vrtp, NULL, RTPQOS_SUMMARY);
06125 if (p->trtp)
06126 textqos = ast_rtp_get_quality(p->trtp, NULL, RTPQOS_SUMMARY);
06127
06128 if (oldowner->_state == AST_STATE_UP) {
06129 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
06130 }
06131
06132
06133 if (p->do_history) {
06134 if (p->rtp)
06135 append_history(p, "RTCPaudio", "Quality:%s", audioqos);
06136 if (p->vrtp)
06137 append_history(p, "RTCPvideo", "Quality:%s", videoqos);
06138 if (p->trtp)
06139 append_history(p, "RTCPtext", "Quality:%s", textqos);
06140 }
06141 if (p->rtp && oldowner)
06142 pbx_builtin_setvar_helper(oldowner, "RTPAUDIOQOS", audioqos);
06143 if (p->vrtp && oldowner)
06144 pbx_builtin_setvar_helper(oldowner, "RTPVIDEOQOS", videoqos);
06145 if (p->trtp && oldowner)
06146 pbx_builtin_setvar_helper(oldowner, "RTPTEXTQOS", textqos);
06147 } else {
06148
06149
06150 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
06151 ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);
06152 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"));
06153 if (sip_cancel_destroy(p))
06154 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
06155 }
06156 }
06157 }
06158 if (needdestroy) {
06159 pvt_set_needdestroy(p, "hangup");
06160 }
06161 sip_pvt_unlock(p);
06162 return 0;
06163 }
06164
06165
06166 static void try_suggested_sip_codec(struct sip_pvt *p)
06167 {
06168 int fmt;
06169 const char *codec;
06170
06171 codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC");
06172 if (!codec)
06173 return;
06174
06175 fmt = ast_getformatbyname(codec);
06176 if (fmt) {
06177 ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC} variable\n", codec);
06178 if (p->jointcapability & fmt) {
06179 p->jointcapability &= fmt;
06180 p->capability &= fmt;
06181 } else
06182 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
06183 } else
06184 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n", codec);
06185 return;
06186 }
06187
06188
06189
06190 static int sip_answer(struct ast_channel *ast)
06191 {
06192 int res = 0;
06193 struct sip_pvt *p = ast->tech_pvt;
06194
06195 sip_pvt_lock(p);
06196 if (ast->_state != AST_STATE_UP) {
06197 try_suggested_sip_codec(p);
06198
06199 ast_setstate(ast, AST_STATE_UP);
06200 ast_debug(1, "SIP answering channel: %s\n", ast->name);
06201 ast_rtp_new_source(p->rtp);
06202 res = transmit_response_with_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL, FALSE);
06203 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
06204 }
06205 sip_pvt_unlock(p);
06206 return res;
06207 }
06208
06209
06210 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
06211 {
06212 struct sip_pvt *p = ast->tech_pvt;
06213 int res = 0;
06214
06215 switch (frame->frametype) {
06216 case AST_FRAME_VOICE:
06217 if (!(frame->subclass & ast->nativeformats)) {
06218 char s1[512], s2[512], s3[512];
06219 ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %s(%d) read/write = %s(%d)/%s(%d)\n",
06220 frame->subclass,
06221 ast_getformatname_multiple(s1, sizeof(s1) - 1, ast->nativeformats & AST_FORMAT_AUDIO_MASK),
06222 ast->nativeformats & AST_FORMAT_AUDIO_MASK,
06223 ast_getformatname_multiple(s2, sizeof(s2) - 1, ast->readformat),
06224 ast->readformat,
06225 ast_getformatname_multiple(s3, sizeof(s3) - 1, ast->writeformat),
06226 ast->writeformat);
06227 return 0;
06228 }
06229 if (p) {
06230 sip_pvt_lock(p);
06231 if (p->rtp) {
06232
06233 if ((ast->_state != AST_STATE_UP) &&
06234 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06235 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06236 ast_rtp_new_source(p->rtp);
06237 if (!global_prematuremediafilter) {
06238 p->invitestate = INV_EARLY_MEDIA;
06239 transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06240 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06241 }
06242 } else if (p->t38.state == T38_ENABLED) {
06243
06244 } else {
06245 p->lastrtptx = time(NULL);
06246 res = ast_rtp_write(p->rtp, frame);
06247 }
06248 }
06249 sip_pvt_unlock(p);
06250 }
06251 break;
06252 case AST_FRAME_VIDEO:
06253 if (p) {
06254 sip_pvt_lock(p);
06255 if (p->vrtp) {
06256
06257 if ((ast->_state != AST_STATE_UP) &&
06258 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06259 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06260 p->invitestate = INV_EARLY_MEDIA;
06261 transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06262 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06263 }
06264 p->lastrtptx = time(NULL);
06265 res = ast_rtp_write(p->vrtp, frame);
06266 }
06267 sip_pvt_unlock(p);
06268 }
06269 break;
06270 case AST_FRAME_TEXT:
06271 if (p) {
06272 sip_pvt_lock(p);
06273 if (p->red) {
06274 red_buffer_t140(p->trtp, frame);
06275 } else {
06276 if (p->trtp) {
06277
06278 if ((ast->_state != AST_STATE_UP) &&
06279 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06280 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06281 p->invitestate = INV_EARLY_MEDIA;
06282 transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06283 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06284 }
06285 p->lastrtptx = time(NULL);
06286 res = ast_rtp_write(p->trtp, frame);
06287 }
06288 }
06289 sip_pvt_unlock(p);
06290 }
06291 break;
06292 case AST_FRAME_IMAGE:
06293 return 0;
06294 break;
06295 case AST_FRAME_MODEM:
06296 if (p) {
06297 sip_pvt_lock(p);
06298
06299
06300
06301
06302 if ((ast->_state == AST_STATE_UP) &&
06303 p->udptl &&
06304 (p->t38.state == T38_ENABLED)) {
06305 res = ast_udptl_write(p->udptl, frame);
06306 }
06307 sip_pvt_unlock(p);
06308 }
06309 break;
06310 default:
06311 ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
06312 return 0;
06313 }
06314
06315 return res;
06316 }
06317
06318
06319
06320 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
06321 {
06322 int ret = -1;
06323 struct sip_pvt *p;
06324
06325 if (newchan && ast_test_flag(newchan, AST_FLAG_ZOMBIE))
06326 ast_debug(1, "New channel is zombie\n");
06327 if (oldchan && ast_test_flag(oldchan, AST_FLAG_ZOMBIE))
06328 ast_debug(1, "Old channel is zombie\n");
06329
06330 if (!newchan || !newchan->tech_pvt) {
06331 if (!newchan)
06332 ast_log(LOG_WARNING, "No new channel! Fixup of %s failed.\n", oldchan->name);
06333 else
06334 ast_log(LOG_WARNING, "No SIP tech_pvt! Fixup of %s failed.\n", oldchan->name);
06335 return -1;
06336 }
06337 p = newchan->tech_pvt;
06338
06339 sip_pvt_lock(p);
06340 append_history(p, "Masq", "Old channel: %s\n", oldchan->name);
06341 append_history(p, "Masq (cont)", "...new owner: %s\n", newchan->name);
06342 if (p->owner != oldchan)
06343 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
06344 else {
06345 p->owner = newchan;
06346
06347
06348
06349
06350
06351
06352 sip_set_rtp_peer(newchan, NULL, NULL, 0, 0, 0);
06353 ret = 0;
06354 }
06355 ast_debug(3, "SIP Fixup: New owner for dialogue %s: %s (Old parent: %s)\n", p->callid, p->owner->name, oldchan->name);
06356
06357 sip_pvt_unlock(p);
06358 return ret;
06359 }
06360
06361 static int sip_senddigit_begin(struct ast_channel *ast, char digit)
06362 {
06363 struct sip_pvt *p = ast->tech_pvt;
06364 int res = 0;
06365
06366 sip_pvt_lock(p);
06367 switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
06368 case SIP_DTMF_INBAND:
06369 res = -1;
06370 break;
06371 case SIP_DTMF_RFC2833:
06372 if (p->rtp)
06373 ast_rtp_senddigit_begin(p->rtp, digit);
06374 break;
06375 default:
06376 break;
06377 }
06378 sip_pvt_unlock(p);
06379
06380 return res;
06381 }
06382
06383
06384
06385 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration)
06386 {
06387 struct sip_pvt *p = ast->tech_pvt;
06388 int res = 0;
06389
06390 sip_pvt_lock(p);
06391 switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
06392 case SIP_DTMF_INFO:
06393 case SIP_DTMF_SHORTINFO:
06394 transmit_info_with_digit(p, digit, duration);
06395 break;
06396 case SIP_DTMF_RFC2833:
06397 if (p->rtp)
06398 ast_rtp_senddigit_end(p->rtp, digit);
06399 break;
06400 case SIP_DTMF_INBAND:
06401 res = -1;
06402 break;
06403 }
06404 sip_pvt_unlock(p);
06405
06406 return res;
06407 }
06408
06409
06410 static int sip_transfer(struct ast_channel *ast, const char *dest)
06411 {
06412 struct sip_pvt *p = ast->tech_pvt;
06413 int res;
06414
06415 if (dest == NULL)
06416 dest = "";
06417 sip_pvt_lock(p);
06418 if (ast->_state == AST_STATE_RING)
06419 res = sip_sipredirect(p, dest);
06420 else
06421 res = transmit_refer(p, dest);
06422 sip_pvt_unlock(p);
06423 return res;
06424 }
06425
06426
06427 static int interpret_t38_parameters(struct sip_pvt *p, const struct ast_control_t38_parameters *parameters)
06428 {
06429 int res = 0;
06430
06431 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
06432 return -1;
06433 }
06434 switch (parameters->request_response) {
06435 case AST_T38_NEGOTIATED:
06436 case AST_T38_REQUEST_NEGOTIATE:
06437
06438 if (!parameters->max_ifp) {
06439 change_t38_state(p, T38_DISABLED);
06440 if (p->t38.state == T38_PEER_REINVITE) {
06441 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"));
06442 transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
06443 }
06444 break;
06445 } else if (p->t38.state == T38_PEER_REINVITE) {
06446 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"));
06447 p->t38.our_parms = *parameters;
06448
06449
06450
06451 if (!p->t38.their_parms.fill_bit_removal) {
06452 p->t38.our_parms.fill_bit_removal = FALSE;
06453 }
06454 if (!p->t38.their_parms.transcoding_mmr) {
06455 p->t38.our_parms.transcoding_mmr = FALSE;
06456 }
06457 if (!p->t38.their_parms.transcoding_jbig) {
06458 p->t38.our_parms.transcoding_jbig = FALSE;
06459 }
06460 p->t38.our_parms.version = MIN(p->t38.our_parms.version, p->t38.their_parms.version);
06461 p->t38.our_parms.rate_management = p->t38.their_parms.rate_management;
06462 ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
06463 change_t38_state(p, T38_ENABLED);
06464 transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
06465 } else if (p->t38.state != T38_ENABLED) {
06466 p->t38.our_parms = *parameters;
06467 ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
06468 change_t38_state(p, T38_LOCAL_REINVITE);
06469 if (!p->pendinginvite) {
06470 transmit_reinvite_with_sdp(p, TRUE, FALSE);
06471 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
06472 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
06473 }
06474 }
06475 break;
06476 case AST_T38_TERMINATED:
06477 case AST_T38_REFUSED:
06478 case AST_T38_REQUEST_TERMINATE:
06479 if (p->t38.state == T38_PEER_REINVITE) {
06480 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"));
06481 change_t38_state(p, T38_DISABLED);
06482 transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
06483 } else if (p->t38.state == T38_ENABLED)
06484 transmit_reinvite_with_sdp(p, FALSE, FALSE);
06485 break;
06486 case AST_T38_REQUEST_PARMS: {
06487 struct ast_control_t38_parameters parameters = p->t38.their_parms;
06488
06489 if (p->t38.state == T38_PEER_REINVITE) {
06490 AST_SCHED_DEL(sched, p->t38id);
06491 parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
06492 parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
06493 ast_queue_control_data(p->owner, AST_CONTROL_T38_PARAMETERS, ¶meters, sizeof(parameters));
06494
06495
06496
06497
06498 res = AST_T38_REQUEST_PARMS;
06499 }
06500 break;
06501 }
06502 default:
06503 res = -1;
06504 break;
06505 }
06506
06507 return res;
06508 }
06509
06510
06511
06512
06513
06514
06515 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
06516 {
06517 struct sip_pvt *p = ast->tech_pvt;
06518 int res = 0;
06519
06520 sip_pvt_lock(p);
06521 switch(condition) {
06522 case AST_CONTROL_RINGING:
06523 if (ast->_state == AST_STATE_RING) {
06524 p->invitestate = INV_EARLY_MEDIA;
06525 if (!ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) ||
06526 (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) {
06527
06528 transmit_provisional_response(p, "180 Ringing", &p->initreq, 0);
06529 ast_set_flag(&p->flags[0], SIP_RINGING);
06530 if (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) != SIP_PROG_INBAND_YES)
06531 break;
06532 } else {
06533
06534 }
06535 }
06536 res = -1;
06537 break;
06538 case AST_CONTROL_BUSY:
06539 if (ast->_state != AST_STATE_UP) {
06540 transmit_response_reliable(p, "486 Busy Here", &p->initreq);
06541 p->invitestate = INV_COMPLETED;
06542 sip_alreadygone(p);
06543 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
06544 break;
06545 }
06546 res = -1;
06547 break;
06548 case AST_CONTROL_CONGESTION:
06549 if (ast->_state != AST_STATE_UP) {
06550 transmit_response_reliable(p, "503 Service Unavailable", &p->initreq);
06551 p->invitestate = INV_COMPLETED;
06552 sip_alreadygone(p);
06553 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
06554 break;
06555 }
06556 res = -1;
06557 break;
06558 case AST_CONTROL_PROCEEDING:
06559 if ((ast->_state != AST_STATE_UP) &&
06560 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06561 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06562 transmit_response(p, "100 Trying", &p->initreq);
06563 p->invitestate = INV_PROCEEDING;
06564 break;
06565 }
06566 res = -1;
06567 break;
06568 case AST_CONTROL_PROGRESS:
06569 if ((ast->_state != AST_STATE_UP) &&
06570 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06571 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06572 p->invitestate = INV_EARLY_MEDIA;
06573 transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06574 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06575 break;
06576 }
06577 res = -1;
06578 break;
06579 case AST_CONTROL_HOLD:
06580 ast_rtp_new_source(p->rtp);
06581 ast_moh_start(ast, data, p->mohinterpret);
06582 break;
06583 case AST_CONTROL_UNHOLD:
06584 ast_rtp_new_source(p->rtp);
06585 ast_moh_stop(ast);
06586 break;
06587 case AST_CONTROL_VIDUPDATE:
06588 if (p->vrtp && !p->novideo) {
06589 transmit_info_with_vidupdate(p);
06590
06591 } else
06592 res = -1;
06593 break;
06594 case AST_CONTROL_T38_PARAMETERS:
06595 if (datalen != sizeof(struct ast_control_t38_parameters)) {
06596 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);
06597 res = -1;
06598 } else {
06599 const struct ast_control_t38_parameters *parameters = data;
06600 res = interpret_t38_parameters(p, parameters);
06601 }
06602 break;
06603 case AST_CONTROL_SRCUPDATE:
06604 ast_rtp_new_source(p->rtp);
06605 break;
06606 case AST_CONTROL_SRCCHANGE:
06607 ast_rtp_change_source(p->rtp);
06608 break;
06609 case -1:
06610 res = -1;
06611 break;
06612 default:
06613 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
06614 res = -1;
06615 break;
06616 }
06617 sip_pvt_unlock(p);
06618 return res;
06619 }
06620
06621
06622
06623
06624
06625
06626
06627 static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title)
06628 {
06629 struct ast_channel *tmp;
06630 struct ast_variable *v = NULL;
06631 int fmt;
06632 int what;
06633 int video;
06634 int text;
06635 int needvideo = 0;
06636 int needtext = 0;
06637 char buf[SIPBUFSIZE];
06638 char *decoded_exten;
06639
06640 {
06641 const char *my_name;
06642
06643 if (title) {
06644 my_name = title;
06645 } else {
06646 char *port = NULL;
06647 my_name = ast_strdupa(i->fromdomain);
06648 if ((port = strchr(i->fromdomain, ':'))) {
06649 *port = '\0';
06650 }
06651 }
06652
06653 sip_pvt_unlock(i);
06654
06655 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));
06656
06657 }
06658 if (!tmp) {
06659 ast_log(LOG_WARNING, "Unable to allocate AST channel structure for SIP channel\n");
06660 sip_pvt_lock(i);
06661 return NULL;
06662 }
06663 sip_pvt_lock(i);
06664
06665 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;
06666
06667
06668
06669 if (i->jointcapability) {
06670 what = i->jointcapability;
06671 video = i->jointcapability & AST_FORMAT_VIDEO_MASK;
06672 text = i->jointcapability & AST_FORMAT_TEXT_MASK;
06673 } else if (i->capability) {
06674 what = i->capability;
06675 video = i->capability & AST_FORMAT_VIDEO_MASK;
06676 text = i->capability & AST_FORMAT_TEXT_MASK;
06677 } else {
06678 what = global_capability;
06679 video = global_capability & AST_FORMAT_VIDEO_MASK;
06680 text = global_capability & AST_FORMAT_TEXT_MASK;
06681 }
06682
06683
06684 tmp->nativeformats = ast_codec_choose(&i->prefs, what, 1) | video | text;
06685 ast_debug(3, "*** Our native formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, tmp->nativeformats));
06686 ast_debug(3, "*** Joint capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->jointcapability));
06687 ast_debug(3, "*** Our capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->capability));
06688 ast_debug(3, "*** AST_CODEC_CHOOSE formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, ast_codec_choose(&i->prefs, what, 1)));
06689 if (i->prefcodec)
06690 ast_debug(3, "*** Our preferred formats from the incoming channel are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->prefcodec));
06691
06692
06693 fmt = ast_best_codec(tmp->nativeformats);
06694
06695
06696
06697
06698
06699 if (i->vrtp) {
06700 if (ast_test_flag(&i->flags[1], SIP_PAGE2_VIDEOSUPPORT))
06701 needvideo = AST_FORMAT_VIDEO_MASK;
06702 else if (i->prefcodec)
06703 needvideo = i->prefcodec & AST_FORMAT_VIDEO_MASK;
06704 else
06705 needvideo = i->jointcapability & AST_FORMAT_VIDEO_MASK;
06706 }
06707
06708 if (i->trtp) {
06709 if (i->prefcodec)
06710 needtext = i->prefcodec & AST_FORMAT_TEXT_MASK;
06711 else
06712 needtext = i->jointcapability & AST_FORMAT_TEXT_MASK;
06713 }
06714
06715 if (needvideo)
06716 ast_debug(3, "This channel can handle video! HOLLYWOOD next!\n");
06717 else
06718 ast_debug(3, "This channel will not be able to handle video.\n");
06719
06720 if ((ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) || (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) ||
06721 (ast_test_flag(&i->flags[1], SIP_PAGE2_FAX_DETECT))) {
06722 int features = 0;
06723
06724 if ((ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) || (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
06725 features |= DSP_FEATURE_DIGIT_DETECT;
06726 }
06727
06728 if (ast_test_flag(&i->flags[1], SIP_PAGE2_FAX_DETECT)) {
06729 features |= DSP_FEATURE_FAX_DETECT;
06730 }
06731
06732 i->dsp = ast_dsp_new();
06733 ast_dsp_set_features(i->dsp, features);
06734 if (global_relaxdtmf)
06735 ast_dsp_set_digitmode(i->dsp, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
06736 }
06737
06738
06739 if (i->rtp) {
06740 ast_channel_set_fd(tmp, 0, ast_rtp_fd(i->rtp));
06741 ast_channel_set_fd(tmp, 1, ast_rtcp_fd(i->rtp));
06742 }
06743 if (needvideo && i->vrtp) {
06744 ast_channel_set_fd(tmp, 2, ast_rtp_fd(i->vrtp));
06745 ast_channel_set_fd(tmp, 3, ast_rtcp_fd(i->vrtp));
06746 }
06747 if (needtext && i->trtp)
06748 ast_channel_set_fd(tmp, 4, ast_rtp_fd(i->trtp));
06749 if (i->udptl)
06750 ast_channel_set_fd(tmp, 5, ast_udptl_fd(i->udptl));
06751
06752 if (state == AST_STATE_RING)
06753 tmp->rings = 1;
06754 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
06755 tmp->writeformat = fmt;
06756 tmp->rawwriteformat = fmt;
06757 tmp->readformat = fmt;
06758 tmp->rawreadformat = fmt;
06759 tmp->tech_pvt = dialog_ref(i, "sip_new: set chan->tech_pvt to i");
06760
06761 tmp->callgroup = i->callgroup;
06762 tmp->pickupgroup = i->pickupgroup;
06763 tmp->cid.cid_pres = i->callingpres;
06764 if (!ast_strlen_zero(i->parkinglot))
06765 ast_string_field_set(tmp, parkinglot, i->parkinglot);
06766 if (!ast_strlen_zero(i->accountcode))
06767 ast_string_field_set(tmp, accountcode, i->accountcode);
06768 if (i->amaflags)
06769 tmp->amaflags = i->amaflags;
06770 if (!ast_strlen_zero(i->language))
06771 ast_string_field_set(tmp, language, i->language);
06772 i->owner = tmp;
06773 ast_module_ref(ast_module_info->self);
06774 ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
06775
06776
06777
06778
06779 decoded_exten = ast_strdupa(i->exten);
06780 ast_uri_decode(decoded_exten);
06781 ast_copy_string(tmp->exten, decoded_exten, sizeof(tmp->exten));
06782
06783
06784
06785 tmp->cid.cid_ani = ast_strdup(i->cid_num);
06786 if (!ast_strlen_zero(i->rdnis))
06787 tmp->cid.cid_rdnis = ast_strdup(i->rdnis);
06788
06789 if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s"))
06790 tmp->cid.cid_dnid = ast_strdup(i->exten);
06791
06792 tmp->priority = 1;
06793 if (!ast_strlen_zero(i->uri))
06794 pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
06795 if (!ast_strlen_zero(i->domain))
06796 pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
06797 if (!ast_strlen_zero(i->callid))
06798 pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
06799 if (i->rtp)
06800 ast_jb_configure(tmp, &global_jbconf);
06801
06802
06803 for (v = i->chanvars ; v ; v = v->next) {
06804 char valuebuf[1024];
06805 pbx_builtin_setvar_helper(tmp, v->name, ast_get_encoded_str(v->value, valuebuf, sizeof(valuebuf)));
06806 }
06807
06808 if (state != AST_STATE_DOWN && ast_pbx_start(tmp)) {
06809 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
06810 tmp->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
06811 ast_hangup(tmp);
06812 tmp = NULL;
06813 }
06814
06815 if (i->do_history)
06816 append_history(i, "NewChan", "Channel %s - from %s", tmp->name, i->callid);
06817
06818
06819 if (sip_cfg.callevents)
06820 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
06821 "Channel: %s\r\nUniqueid: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\n",
06822 tmp->name, tmp->uniqueid, "SIP", i->callid, i->fullcontact);
06823
06824 return tmp;
06825 }
06826
06827
06828 static char *get_body_by_line(const char *line, const char *name, int nameLen, char delimiter)
06829 {
06830 if (!strncasecmp(line, name, nameLen) && line[nameLen] == delimiter)
06831 return ast_skip_blanks(line + nameLen + 1);
06832
06833 return "";
06834 }
06835
06836
06837
06838
06839
06840 static const char *get_sdp_iterate(int *start, struct sip_request *req, const char *name)
06841 {
06842 int len = strlen(name);
06843
06844 while (*start < (req->sdp_start + req->sdp_count)) {
06845 const char *r = get_body_by_line(REQ_OFFSET_TO_STR(req, line[(*start)++]), name, len, '=');
06846 if (r[0] != '\0')
06847 return r;
06848 }
06849
06850
06851 (*start)++;
06852
06853 return "";
06854 }
06855
06856
06857
06858
06859
06860
06861 static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value)
06862 {
06863 char type = '\0';
06864 const char *line = NULL;
06865
06866 if (stop > (req->sdp_start + req->sdp_count)) {
06867 stop = req->sdp_start + req->sdp_count;
06868 }
06869
06870 while (*start < stop) {
06871 line = REQ_OFFSET_TO_STR(req, line[(*start)++]);
06872 if (line[1] == '=') {
06873 type = line[0];
06874 *value = ast_skip_blanks(line + 2);
06875 break;
06876 }
06877 }
06878
06879 return type;
06880 }
06881
06882
06883 static char *get_body(struct sip_request *req, char *name, char delimiter)
06884 {
06885 int x;
06886 int len = strlen(name);
06887 char *r;
06888
06889 for (x = 0; x < req->lines; x++) {
06890 r = get_body_by_line(REQ_OFFSET_TO_STR(req, line[x]), name, len, delimiter);
06891 if (r[0] != '\0')
06892 return r;
06893 }
06894
06895 return "";
06896 }
06897
06898
06899 static const char *find_alias(const char *name, const char *_default)
06900 {
06901
06902 static const struct cfalias {
06903 char * const fullname;
06904 char * const shortname;
06905 } aliases[] = {
06906 { "Content-Type", "c" },
06907 { "Content-Encoding", "e" },
06908 { "From", "f" },
06909 { "Call-ID", "i" },
06910 { "Contact", "m" },
06911 { "Content-Length", "l" },
06912 { "Subject", "s" },
06913 { "To", "t" },
06914 { "Supported", "k" },
06915 { "Refer-To", "r" },
06916 { "Referred-By", "b" },
06917 { "Allow-Events", "u" },
06918 { "Event", "o" },
06919 { "Via", "v" },
06920 { "Accept-Contact", "a" },
06921 { "Reject-Contact", "j" },
06922 { "Request-Disposition", "d" },
06923 { "Session-Expires", "x" },
06924 { "Identity", "y" },
06925 { "Identity-Info", "n" },
06926 };
06927 int x;
06928
06929 for (x = 0; x < ARRAY_LEN(aliases); x++) {
06930 if (!strcasecmp(aliases[x].fullname, name))
06931 return aliases[x].shortname;
06932 }
06933
06934 return _default;
06935 }
06936
06937 static const char *__get_header(const struct sip_request *req, const char *name, int *start)
06938 {
06939 int pass;
06940
06941
06942
06943
06944
06945
06946
06947
06948
06949
06950 for (pass = 0; name && pass < 2;pass++) {
06951 int x, len = strlen(name);
06952 for (x = *start; x < req->headers; x++) {
06953 char *header = REQ_OFFSET_TO_STR(req, header[x]);
06954 if (!strncasecmp(header, name, len)) {
06955 char *r = header + len;
06956 if (sip_cfg.pedanticsipchecking)
06957 r = ast_skip_blanks(r);
06958
06959 if (*r == ':') {
06960 *start = x+1;
06961 return ast_skip_blanks(r+1);
06962 }
06963 }
06964 }
06965 if (pass == 0)
06966 name = find_alias(name, NULL);
06967 }
06968
06969
06970 return "";
06971 }
06972
06973
06974
06975
06976 static const char *get_header(const struct sip_request *req, const char *name)
06977 {
06978 int start = 0;
06979 return __get_header(req, name, &start);
06980 }
06981
06982
06983 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect)
06984 {
06985
06986 struct ast_frame *f;
06987
06988 if (!p->rtp) {
06989
06990 return &ast_null_frame;
06991 }
06992
06993 switch(ast->fdno) {
06994 case 0:
06995 f = ast_rtp_read(p->rtp);
06996 break;
06997 case 1:
06998 f = ast_rtcp_read(p->rtp);
06999 break;
07000 case 2:
07001 f = ast_rtp_read(p->vrtp);
07002 break;
07003 case 3:
07004 f = ast_rtcp_read(p->vrtp);
07005 break;
07006 case 4:
07007 f = ast_rtp_read(p->trtp);
07008 if (sipdebug_text) {
07009 int i;
07010 unsigned char* arr = f->data.ptr;
07011 for (i=0; i < f->datalen; i++)
07012 ast_verbose("%c", (arr[i] > ' ' && arr[i] < '}') ? arr[i] : '.');
07013 ast_verbose(" -> ");
07014 for (i=0; i < f->datalen; i++)
07015 ast_verbose("%02X ", arr[i]);
07016 ast_verbose("\n");
07017 }
07018 break;
07019 case 5:
07020 f = ast_udptl_read(p->udptl);
07021 break;
07022 default:
07023 f = &ast_null_frame;
07024 }
07025
07026 if (f && (f->frametype == AST_FRAME_DTMF_BEGIN || f->frametype == AST_FRAME_DTMF_END) &&
07027 (ast_test_flag(&p->flags[0], SIP_DTMF) != SIP_DTMF_RFC2833)) {
07028 ast_debug(1, "Ignoring DTMF (%c) RTP frame because dtmfmode is not RFC2833\n", f->subclass);
07029 return &ast_null_frame;
07030 }
07031
07032
07033 if (!p->owner || (f && f->frametype != AST_FRAME_VOICE))
07034 return f;
07035
07036 if (f && f->subclass != (p->owner->nativeformats & AST_FORMAT_AUDIO_MASK)) {
07037 if (!(f->subclass & p->jointcapability)) {
07038 ast_debug(1, "Bogus frame of format '%s' received from '%s'!\n",
07039 ast_getformatname(f->subclass), p->owner->name);
07040 return &ast_null_frame;
07041 }
07042 ast_debug(1, "Oooh, format changed to %d %s\n",
07043 f->subclass, ast_getformatname(f->subclass));
07044 p->owner->nativeformats = (p->owner->nativeformats & (AST_FORMAT_VIDEO_MASK | AST_FORMAT_TEXT_MASK)) | f->subclass;
07045 ast_set_read_format(p->owner, p->owner->readformat);
07046 ast_set_write_format(p->owner, p->owner->writeformat);
07047 }
07048
07049 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) {
07050 f = ast_dsp_process(p->owner, p->dsp, f);
07051 if (f && f->frametype == AST_FRAME_DTMF) {
07052 if (f->subclass == 'f') {
07053 if (option_debug)
07054 ast_log(LOG_DEBUG, "Fax CNG detected on %s\n", ast->name);
07055 *faxdetect = 1;
07056
07057 if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
07058 ast_dsp_set_features(p->dsp, DSP_FEATURE_DIGIT_DETECT);
07059 } else {
07060 ast_dsp_free(p->dsp);
07061 p->dsp = NULL;
07062 }
07063 } else {
07064 ast_debug(1, "* Detected inband DTMF '%c'\n", f->subclass);
07065 }
07066 }
07067 }
07068
07069 return f;
07070 }
07071
07072
07073 static struct ast_frame *sip_read(struct ast_channel *ast)
07074 {
07075 struct ast_frame *fr;
07076 struct sip_pvt *p = ast->tech_pvt;
07077 int faxdetected = FALSE;
07078
07079 sip_pvt_lock(p);
07080 fr = sip_rtp_read(ast, p, &faxdetected);
07081 p->lastrtprx = time(NULL);
07082
07083
07084 if (faxdetected && ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_CNG)) {
07085 ast_channel_lock(ast);
07086 if (strcmp(ast->exten, "fax")) {
07087 const char *target_context = S_OR(ast->macrocontext, ast->context);
07088 ast_channel_unlock(ast);
07089 if (ast_exists_extension(ast, target_context, "fax", 1, ast->cid.cid_num)) {
07090 ast_verbose(VERBOSE_PREFIX_2 "Redirecting '%s' to fax extension due to CNG detection\n", ast->name);
07091 pbx_builtin_setvar_helper(ast, "FAXEXTEN", ast->exten);
07092 if (ast_async_goto(ast, target_context, "fax", 1)) {
07093 ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", ast->name, target_context);
07094 }
07095 fr = &ast_null_frame;
07096 } else {
07097 ast_log(LOG_NOTICE, "FAX CNG detected but no fax extension\n");
07098 }
07099 } else {
07100 ast_channel_unlock(ast);
07101 }
07102 }
07103
07104
07105 if (fr && fr->frametype == AST_FRAME_VOICE && p->invitestate != INV_EARLY_MEDIA && ast->_state != AST_STATE_UP) {
07106 fr = &ast_null_frame;
07107 }
07108
07109 sip_pvt_unlock(p);
07110
07111 return fr;
07112 }
07113
07114
07115
07116 static char *generate_random_string(char *buf, size_t size)
07117 {
07118 long val[4];
07119 int x;
07120
07121 for (x=0; x<4; x++)
07122 val[x] = ast_random();
07123 snprintf(buf, size, "%08lx%08lx%08lx%08lx", val[0], val[1], val[2], val[3]);
07124
07125 return buf;
07126 }
07127
07128
07129 static void build_callid_pvt(struct sip_pvt *pvt)
07130 {
07131 char buf[33];
07132
07133 const char *host = S_OR(pvt->fromdomain, ast_inet_ntoa(pvt->ourip.sin_addr));
07134
07135 ast_string_field_build(pvt, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
07136
07137 }
07138
07139
07140 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain)
07141 {
07142 char buf[33];
07143
07144 const char *host = S_OR(fromdomain, ast_inet_ntoa(ourip));
07145
07146 ast_string_field_build(reg, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
07147 }
07148
07149
07150 static void make_our_tag(char *tagbuf, size_t len)
07151 {
07152 snprintf(tagbuf, len, "as%08lx", ast_random());
07153 }
07154
07155
07156 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p)
07157 {
07158 struct sip_st_dlg *stp;
07159
07160 if (p->stimer) {
07161 ast_log(LOG_ERROR, "Session-Timer struct already allocated\n");
07162 return p->stimer;
07163 }
07164
07165 if (!(stp = ast_calloc(1, sizeof(struct sip_st_dlg))))
07166 return NULL;
07167
07168 p->stimer = stp;
07169
07170 stp->st_schedid = -1;
07171
07172 return p->stimer;
07173 }
07174
07175
07176
07177
07178
07179 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
07180 int useglobal_nat, const int intended_method, struct sip_request *req)
07181 {
07182 struct sip_pvt *p;
07183
07184 if (!(p = ao2_t_alloc(sizeof(*p), sip_destroy_fn, "allocate a dialog(pvt) struct")))
07185 return NULL;
07186
07187 if (ast_string_field_init(p, 512)) {
07188 ao2_t_ref(p, -1, "failed to string_field_init, drop p");
07189 return NULL;
07190 }
07191
07192 if (req) {
07193 set_socket_transport(&p->socket, req->socket.type);
07194 } else {
07195 set_socket_transport(&p->socket, SIP_TRANSPORT_UDP);
07196 }
07197
07198 p->socket.fd = -1;
07199 p->method = intended_method;
07200 p->initid = -1;
07201 p->waitid = -1;
07202 p->autokillid = -1;
07203 p->request_queue_sched_id = -1;
07204 p->provisional_keepalive_sched_id = -1;
07205 p->t38id = -1;
07206 p->subscribed = NONE;
07207 p->stateid = -1;
07208 p->sessionversion_remote = -1;
07209 p->session_modify = TRUE;
07210 p->stimer = NULL;
07211 p->prefs = default_prefs;
07212
07213 if (intended_method != SIP_OPTIONS) {
07214 p->timer_t1 = global_t1;
07215 p->timer_b = global_timer_b;
07216 }
07217
07218 if (!sin)
07219 p->ourip = internip;
07220 else {
07221 p->sa = *sin;
07222 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
07223 }
07224
07225
07226 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
07227 ast_copy_flags(&p->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
07228
07229 p->do_history = recordhistory;
07230
07231 p->branch = ast_random();
07232 make_our_tag(p->tag, sizeof(p->tag));
07233 p->ocseq = INITIAL_CSEQ;
07234
07235 if (sip_methods[intended_method].need_rtp) {
07236 p->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
07237
07238 if (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT))
07239 p->vrtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
07240 if (ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT))
07241 p->trtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
07242 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT))
07243 p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr);
07244 if (!p->rtp|| (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) && !p->vrtp)
07245 || (ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT) && !p->trtp)) {
07246 ast_log(LOG_WARNING, "Unable to create RTP audio %s%ssession: %s\n",
07247 ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "and video " : "",
07248 ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT) ? "and text " : "", strerror(errno));
07249 if (p->chanvars) {
07250 ast_variables_destroy(p->chanvars);
07251 p->chanvars = NULL;
07252 }
07253 ao2_t_ref(p, -1, "failed to create RTP audio session, drop p");
07254 return NULL;
07255 p->t38_maxdatagram = global_t38_maxdatagram;
07256 }
07257 ast_rtp_setqos(p->rtp, global_tos_audio, global_cos_audio, "SIP RTP");
07258 ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
07259 ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
07260 ast_rtp_set_rtptimeout(p->rtp, global_rtptimeout);
07261 ast_rtp_set_rtpholdtimeout(p->rtp, global_rtpholdtimeout);
07262 ast_rtp_set_rtpkeepalive(p->rtp, global_rtpkeepalive);
07263 if (p->vrtp) {
07264 ast_rtp_setqos(p->vrtp, global_tos_video, global_cos_video, "SIP VRTP");
07265 ast_rtp_setdtmf(p->vrtp, 0);
07266 ast_rtp_setdtmfcompensate(p->vrtp, 0);
07267 ast_rtp_set_rtptimeout(p->vrtp, global_rtptimeout);
07268 ast_rtp_set_rtpholdtimeout(p->vrtp, global_rtpholdtimeout);
07269 ast_rtp_set_rtpkeepalive(p->vrtp, global_rtpkeepalive);
07270 }
07271 if (p->trtp) {
07272 ast_rtp_setqos(p->trtp, global_tos_text, global_cos_text, "SIP TRTP");
07273 ast_rtp_setdtmf(p->trtp, 0);
07274 ast_rtp_setdtmfcompensate(p->trtp, 0);
07275 }
07276 if (p->udptl)
07277 ast_udptl_setqos(p->udptl, global_tos_audio, global_cos_audio);
07278 p->maxcallbitrate = default_maxcallbitrate;
07279 p->autoframing = global_autoframing;
07280 ast_rtp_codec_setpref(p->rtp, &p->prefs);
07281 }
07282
07283 if (useglobal_nat && sin) {
07284
07285 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT);
07286 p->recv = *sin;
07287 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
07288 }
07289
07290 if (p->method != SIP_REGISTER)
07291 ast_string_field_set(p, fromdomain, default_fromdomain);
07292 build_via(p);
07293 if (!callid)
07294 build_callid_pvt(p);
07295 else
07296 ast_string_field_set(p, callid, callid);
07297
07298 ast_string_field_set(p, mohinterpret, default_mohinterpret);
07299 ast_string_field_set(p, mohsuggest, default_mohsuggest);
07300 p->capability = global_capability;
07301 p->allowtransfer = sip_cfg.allowtransfer;
07302 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
07303 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
07304 p->noncodeccapability |= AST_RTP_DTMF;
07305 if (p->udptl) {
07306 p->t38_maxdatagram = global_t38_maxdatagram;
07307 set_t38_capabilities(p);
07308 }
07309 ast_string_field_set(p, context, sip_cfg.default_context);
07310 ast_string_field_set(p, parkinglot, default_parkinglot);
07311
07312 AST_LIST_HEAD_INIT_NOLOCK(&p->request_queue);
07313
07314
07315
07316 ao2_t_link(dialogs, p, "link pvt into dialogs table");
07317
07318 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");
07319 return p;
07320 }
07321
07322
07323 struct find_call_cb_arg {
07324 enum sipmethod method;
07325 const char *callid;
07326 const char *fromtag;
07327 const char *totag;
07328 const char *tag;
07329 };
07330
07331
07332
07333
07334
07335 static int find_call_cb(void *__pvt, void *__arg, int flags)
07336 {
07337 struct sip_pvt *p = __pvt;
07338 struct find_call_cb_arg *arg = __arg;
07339
07340 int found = FALSE;
07341
07342 if (!ast_strlen_zero(p->callid)) {
07343 if (arg->method == SIP_REGISTER)
07344 found = (!strcmp(p->callid, arg->callid));
07345 else {
07346 found = !strcmp(p->callid, arg->callid);
07347 if (sip_cfg.pedanticsipchecking && found) {
07348 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);
07349 }
07350 }
07351
07352 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);
07353
07354
07355 if (sip_cfg.pedanticsipchecking && found && arg->method != SIP_RESPONSE) {
07356 if (p->tag[0] == '\0' && arg->totag[0]) {
07357
07358 found = FALSE;
07359 } else if (arg->totag[0]) {
07360 if (strcmp(arg->totag, p->tag)) {
07361 found = FALSE;
07362 }
07363 }
07364 if (!found)
07365 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);
07366 }
07367 }
07368 return found;
07369 }
07370
07371
07372
07373
07374
07375
07376 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method)
07377 {
07378 struct sip_pvt *p = NULL;
07379 char *tag = "";
07380 char totag[128];
07381 char fromtag[128];
07382 struct find_call_cb_arg arg;
07383 const char *callid = get_header(req, "Call-ID");
07384 const char *from = get_header(req, "From");
07385 const char *to = get_header(req, "To");
07386 const char *cseq = get_header(req, "Cseq");
07387 struct sip_pvt *sip_pvt_ptr;
07388
07389
07390
07391 if (ast_strlen_zero(callid) || ast_strlen_zero(to) ||
07392 ast_strlen_zero(from) || ast_strlen_zero(cseq))
07393 return NULL;
07394
07395 arg.method = req->method;
07396 arg.callid = callid;
07397 arg.fromtag = fromtag;
07398 arg.totag = totag;
07399 arg.tag = "";
07400
07401 if (sip_cfg.pedanticsipchecking) {
07402
07403
07404
07405
07406
07407
07408 if (gettag(req, "To", totag, sizeof(totag)))
07409 req->has_to_tag = 1;
07410 gettag(req, "From", fromtag, sizeof(fromtag));
07411
07412 tag = (req->method == SIP_RESPONSE) ? totag : fromtag;
07413
07414 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);
07415
07416
07417 if (ast_strlen_zero(fromtag)) {
07418 ast_debug(5, "%s request has no from tag, dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
07419 return NULL;
07420 }
07421
07422 if (ast_strlen_zero(totag) && (req->method == SIP_ACK || req->method == SIP_BYE || req->method == SIP_INFO )) {
07423 ast_debug(5, "%s must have a to tag. dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
07424 return NULL;
07425 }
07426 }
07427
07428 restartsearch:
07429 if (!sip_cfg.pedanticsipchecking) {
07430 struct sip_pvt tmp_dialog = {
07431 .callid = callid,
07432 };
07433 sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find in dialogs");
07434 if (sip_pvt_ptr) {
07435
07436 sip_pvt_lock(sip_pvt_ptr);
07437 return sip_pvt_ptr;
07438 }
07439 } else {
07440 ao2_lock(dialogs);
07441 p = ao2_t_callback(dialogs, 0 , find_call_cb, &arg, "pedantic linear search for dialog");
07442 if (p) {
07443 if (sip_pvt_trylock(p)) {
07444 ao2_unlock(dialogs);
07445 usleep(1);
07446 goto restartsearch;
07447 }
07448 ao2_unlock(dialogs);
07449 return p;
07450 }
07451 ao2_unlock(dialogs);
07452 }
07453
07454
07455 if (sip_methods[intended_method].can_create == CAN_CREATE_DIALOG) {
07456 if (intended_method == SIP_REFER) {
07457
07458 transmit_response_using_temp(callid, sin, 1, intended_method, req, "603 Declined (no dialog)");
07459 } else if (intended_method == SIP_NOTIFY) {
07460
07461
07462 transmit_response_using_temp(callid, sin, 1, intended_method, req, "489 Bad event");
07463 } else {
07464
07465 if ((p = sip_alloc(callid, sin, 1, intended_method, req))) {
07466
07467 sip_pvt_lock(p);
07468 } else {
07469
07470
07471
07472
07473
07474
07475
07476
07477 transmit_response_using_temp(callid, sin, 1, intended_method, req, "500 Server internal error");
07478 ast_debug(4, "Failed allocating SIP dialog, sending 500 Server internal error and giving up\n");
07479 }
07480 }
07481 return p;
07482 } else if( sip_methods[intended_method].can_create == CAN_CREATE_DIALOG_UNSUPPORTED_METHOD) {
07483
07484 transmit_response_using_temp(callid, sin, 1, intended_method, req, "501 Method Not Implemented");
07485 ast_debug(2, "Got a request with unsupported SIP method.\n");
07486 } else if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
07487
07488 transmit_response_using_temp(callid, sin, 1, intended_method, req, "481 Call leg/transaction does not exist");
07489 ast_debug(2, "That's odd... Got a request in unknown dialog. Callid %s\n", callid ? callid : "<unknown>");
07490 }
07491
07492
07493 if (intended_method == SIP_RESPONSE)
07494 ast_debug(2, "That's odd... Got a response on a call we dont know about. Callid %s\n", callid ? callid : "<unknown>");
07495
07496 return NULL;
07497 }
07498
07499
07500 static int sip_register(const char *value, int lineno)
07501 {
07502 struct sip_registry *reg;
07503 int portnum = 0;
07504 enum sip_transport transport = SIP_TRANSPORT_UDP;
07505 char buf[256] = "";
07506 char *userpart = NULL, *hostpart = NULL;
07507
07508 AST_DECLARE_APP_ARGS(pre1,
07509 AST_APP_ARG(peer);
07510 AST_APP_ARG(userpart);
07511 );
07512 AST_DECLARE_APP_ARGS(pre2,
07513 AST_APP_ARG(transport);
07514 AST_APP_ARG(blank);
07515 AST_APP_ARG(userpart);
07516 );
07517 AST_DECLARE_APP_ARGS(user1,
07518 AST_APP_ARG(userpart);
07519 AST_APP_ARG(secret);
07520 AST_APP_ARG(authuser);
07521 );
07522 AST_DECLARE_APP_ARGS(host1,
07523 AST_APP_ARG(hostpart);
07524 AST_APP_ARG(expiry);
07525 );
07526 AST_DECLARE_APP_ARGS(host2,
07527 AST_APP_ARG(hostpart);
07528 AST_APP_ARG(extension);
07529 );
07530 AST_DECLARE_APP_ARGS(host3,
07531 AST_APP_ARG(host);
07532 AST_APP_ARG(port);
07533 );
07534
07535 if (!value)
07536 return -1;
07537 ast_copy_string(buf, value, sizeof(buf));
07538
07539
07540
07541
07542
07543
07544 if ((hostpart = strrchr(buf, '@'))) {
07545 *hostpart++ = '\0';
07546 userpart = buf;
07547 }
07548
07549 if (ast_strlen_zero(userpart) || ast_strlen_zero(hostpart)) {
07550 ast_log(LOG_WARNING, "Format for registration is [peer?][transport://]user[@domain][:secret[:authuser]]@host[:port][/extension][~expiry] at line %d\n", lineno);
07551 return -1;
07552 }
07553
07554
07555
07556
07557
07558
07559 AST_NONSTANDARD_RAW_ARGS(pre1, userpart, '?');
07560 if (ast_strlen_zero(pre1.userpart)) {
07561 pre1.userpart = pre1.peer;
07562 pre1.peer = NULL;
07563 }
07564
07565
07566
07567
07568
07569
07570
07571 AST_NONSTANDARD_RAW_ARGS(pre2, pre1.userpart, '/');
07572 if (ast_strlen_zero(pre2.userpart)) {
07573 pre2.userpart = pre2.transport;
07574 pre2.transport = NULL;
07575 } else {
07576 pre2.transport[strlen(pre2.transport) - 1] = '\0';
07577 }
07578
07579 if (!ast_strlen_zero(pre2.blank)) {
07580 ast_log(LOG_WARNING, "Format for registration is [peer?][transport://]user[@domain][:secret[:authuser]]@host[:port][/extension][~expiry] at line %d\n", lineno);
07581 return -1;
07582 }
07583
07584
07585
07586
07587
07588
07589
07590
07591
07592 AST_NONSTANDARD_RAW_ARGS(user1, pre2.userpart, ':');
07593
07594
07595
07596
07597
07598
07599
07600
07601
07602
07603 AST_NONSTANDARD_RAW_ARGS(host1, hostpart, '~');
07604
07605
07606
07607
07608
07609
07610
07611
07612
07613
07614
07615 AST_NONSTANDARD_RAW_ARGS(host2, host1.hostpart, '/');
07616
07617
07618
07619
07620
07621
07622
07623
07624
07625
07626
07627
07628 AST_NONSTANDARD_RAW_ARGS(host3, host2.hostpart, ':');
07629
07630 if (host3.port) {
07631 if (!(portnum = port_str2int(host3.port, 0))) {
07632 ast_log(LOG_NOTICE, "'%s' is not a valid port number on line %d of sip.conf. using default.\n", host3.port, lineno);
07633 }
07634 }
07635
07636
07637 if (!pre2.transport) {
07638 transport = SIP_TRANSPORT_UDP;
07639 } else if (!strncasecmp(pre2.transport, "tcp", 3)) {
07640 transport = SIP_TRANSPORT_TCP;
07641 } else if (!strncasecmp(pre2.transport, "tls", 3)) {
07642 transport = SIP_TRANSPORT_TLS;
07643 } else if (!strncasecmp(pre2.transport, "udp", 3)) {
07644 transport = SIP_TRANSPORT_UDP;
07645 } else {
07646 transport = SIP_TRANSPORT_UDP;
07647 ast_log(LOG_NOTICE, "'%.3s' is not a valid transport type on line %d of sip.conf. defaulting to udp.\n", pre2.transport, lineno);
07648 }
07649
07650
07651 if (!portnum) {
07652 if (transport == SIP_TRANSPORT_TLS) {
07653 portnum = STANDARD_TLS_PORT;
07654 } else {
07655 portnum = STANDARD_SIP_PORT;
07656 }
07657 }
07658
07659 if (!(reg = ast_calloc(1, sizeof(*reg)))) {
07660 ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry entry\n");
07661 return -1;
07662 }
07663
07664 if (ast_string_field_init(reg, 256)) {
07665 ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry strings\n");
07666 ast_free(reg);
07667 return -1;
07668 }
07669
07670 ast_atomic_fetchadd_int(®objs, 1);
07671 ASTOBJ_INIT(reg);
07672 ast_string_field_set(reg, callback, ast_strip_quoted(S_OR(host2.extension, "s"), "\"", "\""));
07673 ast_string_field_set(reg, username, ast_strip_quoted(S_OR(user1.userpart, ""), "\"", "\""));
07674 ast_string_field_set(reg, hostname, ast_strip_quoted(S_OR(host3.host, ""), "\"", "\""));
07675 ast_string_field_set(reg, authuser, ast_strip_quoted(S_OR(user1.authuser, ""), "\"", "\""));
07676 ast_string_field_set(reg, secret, ast_strip_quoted(S_OR(user1.secret, ""), "\"", "\""));
07677 ast_string_field_set(reg, peername, ast_strip_quoted(S_OR(pre1.peer, ""), "\"", "\""));
07678
07679 reg->transport = transport;
07680 reg->timeout = reg->expire = -1;
07681 reg->refresh = reg->expiry = reg->configured_expiry = (host1.expiry ? atoi(ast_strip_quoted(host1.expiry, "\"", "\"")) : default_expiry);
07682 reg->portno = portnum;
07683 reg->callid_valid = FALSE;
07684 reg->ocseq = INITIAL_CSEQ;
07685 ASTOBJ_CONTAINER_LINK(®l, reg);
07686 registry_unref(reg, "unref the reg pointer");
07687 return 0;
07688 }
07689
07690
07691 static int sip_subscribe_mwi(const char *value, int lineno)
07692 {
07693 struct sip_subscription_mwi *mwi;
07694 int portnum = 0;
07695 enum sip_transport transport = SIP_TRANSPORT_UDP;
07696 char buf[256] = "";
07697 char *username = NULL, *hostname = NULL, *secret = NULL, *authuser = NULL, *porta = NULL, *mailbox = NULL;
07698
07699 if (!value) {
07700 return -1;
07701 }
07702
07703 ast_copy_string(buf, value, sizeof(buf));
07704
07705 sip_parse_host(buf, lineno, &username, &portnum, &transport);
07706
07707 if ((hostname = strrchr(username, '@'))) {
07708 *hostname++ = '\0';
07709 }
07710
07711 if ((secret = strchr(username, ':'))) {
07712 *secret++ = '\0';
07713 if ((authuser = strchr(secret, ':'))) {
07714 *authuser++ = '\0';
07715 }
07716 }
07717
07718 if ((mailbox = strchr(hostname, '/'))) {
07719 *mailbox++ = '\0';
07720 }
07721
07722 if (ast_strlen_zero(username) || ast_strlen_zero(hostname) || ast_strlen_zero(mailbox)) {
07723 ast_log(LOG_WARNING, "Format for MWI subscription is user[:secret[:authuser]]@host[:port][/mailbox] at line %d\n", lineno);
07724 return -1;
07725 }
07726
07727 if ((porta = strchr(hostname, ':'))) {
07728 *porta++ = '\0';
07729 if (!(portnum = atoi(porta))) {
07730 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
07731 return -1;
07732 }
07733 }
07734
07735 if (!(mwi = ast_calloc(1, sizeof(*mwi)))) {
07736 return -1;
07737 }
07738
07739 if (ast_string_field_init(mwi, 256)) {
07740 ast_free(mwi);
07741 return -1;
07742 }
07743
07744 ASTOBJ_INIT(mwi);
07745 ast_string_field_set(mwi, username, username);
07746 if (secret) {
07747 ast_string_field_set(mwi, secret, secret);
07748 }
07749 if (authuser) {
07750 ast_string_field_set(mwi, authuser, authuser);
07751 }
07752 ast_string_field_set(mwi, hostname, hostname);
07753 ast_string_field_set(mwi, mailbox, mailbox);
07754 mwi->resub = -1;
07755 mwi->portno = portnum;
07756 mwi->transport = transport;
07757
07758 ASTOBJ_CONTAINER_LINK(&submwil, mwi);
07759 ASTOBJ_UNREF(mwi, sip_subscribe_mwi_destroy);
07760
07761 return 0;
07762 }
07763
07764
07765
07766 static int lws2sws(char *msgbuf, int len)
07767 {
07768 int h = 0, t = 0;
07769 int lws = 0;
07770
07771 for (; h < len;) {
07772
07773 if (msgbuf[h] == '\r') {
07774 h++;
07775 continue;
07776 }
07777
07778 if (msgbuf[h] == '\n') {
07779
07780 if (h + 1 == len)
07781 break;
07782
07783 if (msgbuf[h + 1] == ' ' || msgbuf[h + 1] == '\t') {
07784
07785 h++;
07786 continue;
07787 }
07788
07789 msgbuf[t++] = msgbuf[h++];
07790 lws = 0;
07791 continue;
07792 }
07793 if (msgbuf[h] == ' ' || msgbuf[h] == '\t') {
07794 if (lws) {
07795 h++;
07796 continue;
07797 }
07798 msgbuf[t++] = msgbuf[h++];
07799 lws = 1;
07800 continue;
07801 }
07802 msgbuf[t++] = msgbuf[h++];
07803 if (lws)
07804 lws = 0;
07805 }
07806 msgbuf[t] = '\0';
07807 return t;
07808 }
07809
07810
07811
07812
07813 static int parse_request(struct sip_request *req)
07814 {
07815 char *c = req->data->str;
07816 ptrdiff_t *dst = req->header;
07817 int i = 0, lim = SIP_MAX_HEADERS - 1;
07818 unsigned int skipping_headers = 0;
07819 ptrdiff_t current_header_offset = 0;
07820 char *previous_header = "";
07821
07822 req->header[0] = 0;
07823 req->headers = -1;
07824 for (; *c; c++) {
07825 if (*c == '\r') {
07826 *c = '\0';
07827 } else if (*c == '\n') {
07828 *c = '\0';
07829 current_header_offset = (c + 1) - req->data->str;
07830 previous_header = req->data->str + dst[i];
07831 if (skipping_headers) {
07832
07833
07834
07835 if (ast_strlen_zero(previous_header)) {
07836 skipping_headers = 0;
07837 }
07838 dst[i] = current_header_offset;
07839 continue;
07840 }
07841 if (sipdebug) {
07842 ast_debug(4, "%7s %2d [%3d]: %s\n",
07843 req->headers < 0 ? "Header" : "Body",
07844 i, (int) strlen(previous_header), previous_header);
07845 }
07846 if (ast_strlen_zero(previous_header) && req->headers < 0) {
07847 req->headers = i;
07848 dst = req->line;
07849 i = 0;
07850 lim = SIP_MAX_LINES - 1;
07851 } else {
07852 if (i++ == lim) {
07853
07854
07855
07856 if (req->headers != -1) {
07857 break;
07858 } else {
07859 req->headers = i;
07860 dst = req->line;
07861 i = 0;
07862 lim = SIP_MAX_LINES - 1;
07863 skipping_headers = 1;
07864 }
07865 }
07866 }
07867 dst[i] = current_header_offset;
07868 }
07869 }
07870
07871
07872
07873
07874
07875
07876 previous_header = req->data->str + dst[i];
07877 if ((i < lim) && !ast_strlen_zero(previous_header)) {
07878 if (sipdebug) {
07879 ast_debug(4, "%7s %2d [%3d]: %s\n",
07880 req->headers < 0 ? "Header" : "Body",
07881 i, (int) strlen(previous_header), previous_header );
07882 }
07883 i++;
07884 }
07885
07886
07887 if (req->headers >= 0) {
07888 req->lines = i;
07889 } else {
07890 req->headers = i;
07891 req->lines = 0;
07892
07893 req->line[0] = ast_str_strlen(req->data);
07894 }
07895
07896 if (*c) {
07897 ast_log(LOG_WARNING, "Too many lines, skipping <%s>\n", c);
07898 }
07899
07900
07901 return determine_firstline_parts(req);
07902 }
07903
07904
07905
07906
07907
07908
07909
07910
07911
07912 static int find_sdp(struct sip_request *req)
07913 {
07914 const char *content_type;
07915 const char *content_length;
07916 const char *search;
07917 char *boundary;
07918 unsigned int x;
07919 int boundaryisquoted = FALSE;
07920 int found_application_sdp = FALSE;
07921 int found_end_of_headers = FALSE;
07922
07923 content_length = get_header(req, "Content-Length");
07924
07925 if (!ast_strlen_zero(content_length)) {
07926 if (sscanf(content_length, "%30u", &x) != 1) {
07927 ast_log(LOG_WARNING, "Invalid Content-Length: %s\n", content_length);
07928 return 0;
07929 }
07930
07931
07932
07933 if (x == 0)
07934 return 0;
07935 }
07936
07937 content_type = get_header(req, "Content-Type");
07938
07939
07940 if (!strncasecmp(content_type, "application/sdp", 15)) {
07941 req->sdp_start = 0;
07942 req->sdp_count = req->lines;
07943 return req->lines ? 1 : 0;
07944 }
07945
07946
07947 if (strncasecmp(content_type, "multipart/mixed", 15))
07948 return 0;
07949
07950
07951 if ((search = strcasestr(content_type, ";boundary=")))
07952 search += 10;
07953 else if ((search = strcasestr(content_type, "; boundary=")))
07954 search += 11;
07955 else
07956 return 0;
07957
07958 if (ast_strlen_zero(search))
07959 return 0;
07960
07961
07962 if (*search == '\"') {
07963 search++;
07964 boundaryisquoted = TRUE;
07965 }
07966
07967
07968
07969 boundary = ast_strdupa(search - 2);
07970 boundary[0] = boundary[1] = '-';
07971
07972 if (boundaryisquoted)
07973 boundary[strlen(boundary) - 1] = '\0';
07974
07975
07976
07977
07978 for (x = 0; x < (req->lines); x++) {
07979 char *line = REQ_OFFSET_TO_STR(req, line[x]);
07980 if (!strncasecmp(line, boundary, strlen(boundary))){
07981 if (found_application_sdp && found_end_of_headers) {
07982 req->sdp_count = (x - 1) - req->sdp_start;
07983 return 1;
07984 }
07985 found_application_sdp = FALSE;
07986 }
07987 if (!strcasecmp(line, "Content-Type: application/sdp"))
07988 found_application_sdp = TRUE;
07989
07990 if (ast_strlen_zero(line)) {
07991 if (found_application_sdp && !found_end_of_headers){
07992 req->sdp_start = x;
07993 found_end_of_headers = TRUE;
07994 }
07995 }
07996 }
07997 if (found_application_sdp && found_end_of_headers) {
07998 req->sdp_count = x - req->sdp_start;
07999 return TRUE;
08000 }
08001 return FALSE;
08002 }
08003
08004 enum media_type {
08005 SDP_AUDIO,
08006 SDP_VIDEO,
08007 SDP_IMAGE,
08008 SDP_TEXT,
08009 };
08010
08011 static int get_ip_and_port_from_sdp(struct sip_request *req, const enum media_type media, struct sockaddr_in *sin)
08012 {
08013 const char *m;
08014 const char *c;
08015 int miterator = req->sdp_start;
08016 int citerator = req->sdp_start;
08017 int x = 0;
08018 int numberofports;
08019 int len;
08020 char host[258] = "";
08021 struct ast_hostent audiohp;
08022 struct hostent *hp;
08023
08024 c = get_sdp_iterate(&citerator, req, "c");
08025 if (sscanf(c, "IN IP4 %256s", host) != 1) {
08026 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
08027
08028 }
08029
08030 for (m = get_sdp_iterate(&miterator, req, "m"); !ast_strlen_zero(m); m = get_sdp_iterate(&miterator, req, "m")) {
08031 if ((media == SDP_AUDIO && ((sscanf(m, "audio %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08032 (sscanf(m, "audio %30u RTP/AVP %n", &x, &len) == 1 && len > 0))) ||
08033 (media == SDP_VIDEO && ((sscanf(m, "video %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08034 (sscanf(m, "video %30u RTP/AVP %n", &x, &len) == 1 && len > 0)))) {
08035
08036
08037
08038
08039 c = get_sdp_iterate(&citerator, req, "c");
08040 if (!ast_strlen_zero(c)) {
08041 sscanf(c, "IN IP4 %256s", host);
08042 }
08043 break;
08044 }
08045 }
08046
08047 if (ast_strlen_zero(host) || x == 0) {
08048 ast_log(LOG_WARNING, "Failed to read an alternate host or port in SDP. Expect %s problems\n", media == SDP_AUDIO ? "audio" : "video");
08049 return -1;
08050 }
08051
08052 hp = ast_gethostbyname(host, &audiohp);
08053 if (!hp) {
08054 ast_log(LOG_WARNING, "Could not look up IP address of alternate hostname. Expect %s problems\n", media == SDP_AUDIO? "audio" : "video");
08055 return -1;
08056 }
08057
08058 memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
08059 sin->sin_port = htons(x);
08060 return 0;
08061 }
08062
08063
08064
08065
08066
08067
08068 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action)
08069 {
08070
08071 int start = req->sdp_start;
08072 int next = start;
08073 int iterator = start;
08074
08075
08076 char type = '\0';
08077 const char *value = NULL;
08078 const char *m = NULL;
08079 const char *nextm = NULL;
08080 int len = -1;
08081
08082
08083 struct ast_hostent sessionhp;
08084 struct ast_hostent audiohp;
08085 struct ast_hostent videohp;
08086 struct ast_hostent texthp;
08087 struct ast_hostent imagehp;
08088 struct hostent *hp = NULL;
08089 struct hostent *vhp = NULL;
08090 struct hostent *thp = NULL;
08091 struct hostent *ihp = NULL;
08092 int portno = -1;
08093 int vportno = -1;
08094 int tportno = -1;
08095 int udptlportno = -1;
08096 struct sockaddr_in sin;
08097 struct sockaddr_in vsin;
08098 struct sockaddr_in isin;
08099 struct sockaddr_in tsin;
08100
08101
08102 int peercapability = 0, peernoncodeccapability = 0;
08103 int vpeercapability = 0, vpeernoncodeccapability = 0;
08104 int tpeercapability = 0, tpeernoncodeccapability = 0;
08105
08106 struct ast_rtp *newaudiortp, *newvideortp, *newtextrtp;
08107 int newjointcapability;
08108 int newpeercapability;
08109 int newnoncodeccapability;
08110
08111 const char *codecs;
08112 int codec;
08113
08114
08115 int sendonly = -1;
08116 int vsendonly = -1;
08117 int numberofports;
08118 int numberofmediastreams = 0;
08119 int last_rtpmap_codec = 0;
08120 int red_data_pt[10];
08121 int red_num_gen = 0;
08122 char red_fmtp[100] = "empty";
08123 int debug = sip_debug_test_pvt(p);
08124
08125
08126 char buf[SIPBUFSIZE];
08127
08128
08129
08130 if (!p->rtp) {
08131 ast_log(LOG_ERROR, "Got SDP but have no RTP session allocated.\n");
08132 return -1;
08133 }
08134
08135
08136 #ifdef LOW_MEMORY
08137 newaudiortp = ast_threadstorage_get(&ts_audio_rtp, ast_rtp_alloc_size());
08138 #else
08139 newaudiortp = alloca(ast_rtp_alloc_size());
08140 #endif
08141 memset(newaudiortp, 0, ast_rtp_alloc_size());
08142 ast_rtp_new_init(newaudiortp);
08143 ast_rtp_pt_clear(newaudiortp);
08144
08145 #ifdef LOW_MEMORY
08146 newvideortp = ast_threadstorage_get(&ts_video_rtp, ast_rtp_alloc_size());
08147 #else
08148 newvideortp = alloca(ast_rtp_alloc_size());
08149 #endif
08150 memset(newvideortp, 0, ast_rtp_alloc_size());
08151 ast_rtp_new_init(newvideortp);
08152 ast_rtp_pt_clear(newvideortp);
08153
08154 #ifdef LOW_MEMORY
08155 newtextrtp = ast_threadstorage_get(&ts_text_rtp, ast_rtp_alloc_size());
08156 #else
08157 newtextrtp = alloca(ast_rtp_alloc_size());
08158 #endif
08159 memset(newtextrtp, 0, ast_rtp_alloc_size());
08160 ast_rtp_new_init(newtextrtp);
08161 ast_rtp_pt_clear(newtextrtp);
08162
08163
08164 p->lastrtprx = p->lastrtptx = time(NULL);
08165
08166 memset(p->offered_media, 0, sizeof(p->offered_media));
08167
08168
08169
08170 p->novideo = TRUE;
08171 p->notext = TRUE;
08172
08173 if (p->vrtp)
08174 ast_rtp_pt_clear(newvideortp);
08175
08176 if (p->trtp)
08177 ast_rtp_pt_clear(newtextrtp);
08178
08179
08180 nextm = get_sdp_iterate(&next, req, "m");
08181 if (ast_strlen_zero(nextm)) {
08182 ast_log(LOG_WARNING, "Insufficient information for SDP (m= not found)\n");
08183 return -1;
08184 }
08185
08186
08187 while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
08188 int processed = FALSE;
08189 switch (type) {
08190 case 'o':
08191
08192
08193
08194 if (!process_sdp_o(value, p))
08195 return (p->session_modify == FALSE) ? 0 : -1;
08196 break;
08197 case 'c':
08198 if (process_sdp_c(value, &sessionhp)) {
08199 processed = TRUE;
08200 hp = &sessionhp.hp;
08201 vhp = hp;
08202 thp = hp;
08203 ihp = hp;
08204 }
08205 break;
08206 case 'a':
08207 if (process_sdp_a_sendonly(value, &sendonly)) {
08208 processed = TRUE;
08209 vsendonly = sendonly;
08210 }
08211 else if (process_sdp_a_audio(value, p, newaudiortp, &last_rtpmap_codec))
08212 processed = TRUE;
08213 else if (process_sdp_a_video(value, p, newvideortp, &last_rtpmap_codec))
08214 processed = TRUE;
08215 else if (process_sdp_a_text(value, p, newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec))
08216 processed = TRUE;
08217 else if (process_sdp_a_image(value, p))
08218 processed = TRUE;
08219 break;
08220 }
08221
08222 if (option_debug > 2)
08223 ast_log(LOG_DEBUG, "Processing session-level SDP %c=%s... %s\n", type, value, (processed == TRUE)? "OK." : "UNSUPPORTED.");
08224 }
08225
08226
08227
08228
08229 while (!ast_strlen_zero(nextm)) {
08230 int audio = FALSE;
08231 int video = FALSE;
08232 int image = FALSE;
08233 int text = FALSE;
08234 int x;
08235
08236 numberofports = 1;
08237 len = -1;
08238 start = next;
08239 m = nextm;
08240 iterator = next;
08241 nextm = get_sdp_iterate(&next, req, "m");
08242
08243
08244 if ((sscanf(m, "audio %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08245 (sscanf(m, "audio %30u RTP/AVP %n", &x, &len) == 1 && len > 0)) {
08246 audio = TRUE;
08247 p->offered_media[SDP_AUDIO].offered = TRUE;
08248 numberofmediastreams++;
08249 portno = x;
08250
08251
08252 codecs = m + len;
08253 ast_copy_string(p->offered_media[SDP_AUDIO].text, codecs, sizeof(p->offered_media[SDP_AUDIO].text));
08254 for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
08255 if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
08256 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
08257 return -1;
08258 }
08259 if (debug)
08260 ast_verbose("Found RTP audio format %d\n", codec);
08261
08262 ast_rtp_set_m_type(newaudiortp, codec);
08263 }
08264
08265 } else if ((sscanf(m, "video %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08266 (sscanf(m, "video %30u RTP/AVP %n", &x, &len) == 1 && len >= 0)) {
08267 video = TRUE;
08268 p->novideo = FALSE;
08269 p->offered_media[SDP_VIDEO].offered = TRUE;
08270 numberofmediastreams++;
08271 vportno = x;
08272
08273
08274 codecs = m + len;
08275 ast_copy_string(p->offered_media[SDP_VIDEO].text, codecs, sizeof(p->offered_media[SDP_VIDEO].text));
08276 for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
08277 if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
08278 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
08279 return -1;
08280 }
08281 if (debug)
08282 ast_verbose("Found RTP video format %d\n", codec);
08283 ast_rtp_set_m_type(newvideortp, codec);
08284 }
08285
08286 } else if ((sscanf(m, "text %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08287 (sscanf(m, "text %30u RTP/AVP %n", &x, &len) == 1 && len > 0)) {
08288 text = TRUE;
08289 p->notext = FALSE;
08290 p->offered_media[SDP_TEXT].offered = TRUE;
08291 numberofmediastreams++;
08292 tportno = x;
08293
08294
08295 codecs = m + len;
08296 ast_copy_string(p->offered_media[SDP_TEXT].text, codecs, sizeof(p->offered_media[SDP_TEXT].text));
08297 for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
08298 if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
08299 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
08300 return -1;
08301 }
08302 if (debug)
08303 ast_verbose("Found RTP text format %d\n", codec);
08304 ast_rtp_set_m_type(newtextrtp, codec);
08305 }
08306
08307 } else if (p->udptl && ((sscanf(m, "image %30u udptl t38%n", &x, &len) == 1 && len > 0) ||
08308 (sscanf(m, "image %30u UDPTL t38%n", &x, &len) == 1 && len > 0) )) {
08309 image = TRUE;
08310 if (debug)
08311 ast_verbose("Got T.38 offer in SDP in dialog %s\n", p->callid);
08312 p->offered_media[SDP_IMAGE].offered = TRUE;
08313 udptlportno = x;
08314 numberofmediastreams++;
08315
08316 if (p->t38.state != T38_ENABLED) {
08317 memset(&p->t38.their_parms, 0, sizeof(p->t38.their_parms));
08318 }
08319 } else {
08320 ast_log(LOG_WARNING, "Unsupported SDP media type in offer: %s\n", m);
08321 continue;
08322 }
08323
08324
08325 if (numberofports > 1)
08326 ast_log(LOG_WARNING, "SDP offered %d ports for media, not supported by Asterisk. Will try anyway...\n", numberofports);
08327
08328
08329
08330
08331 while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
08332 int processed = FALSE;
08333
08334 switch (type) {
08335 case 'c':
08336 if (audio) {
08337 if (process_sdp_c(value, &audiohp)) {
08338 processed = TRUE;
08339 hp = &audiohp.hp;
08340 }
08341 } else if (video) {
08342 if (process_sdp_c(value, &videohp)) {
08343 processed = TRUE;
08344 vhp = &videohp.hp;
08345 }
08346 } else if (text) {
08347 if (process_sdp_c(value, &texthp)) {
08348 processed = TRUE;
08349 thp = &texthp.hp;
08350 }
08351 } else if (image) {
08352 if (process_sdp_c(value, &imagehp)) {
08353 processed = TRUE;
08354 ihp = &imagehp.hp;
08355 }
08356 }
08357 break;
08358 case 'a':
08359
08360 if (audio) {
08361 if (process_sdp_a_sendonly(value, &sendonly))
08362 processed = TRUE;
08363 else if (process_sdp_a_audio(value, p, newaudiortp, &last_rtpmap_codec))
08364 processed = TRUE;
08365 }
08366
08367 else if (video) {
08368 if (process_sdp_a_sendonly(value, &vsendonly))
08369 processed = TRUE;
08370 else if (process_sdp_a_video(value, p, newvideortp, &last_rtpmap_codec))
08371 processed = TRUE;
08372 }
08373
08374 else if (text) {
08375 if (process_sdp_a_text(value, p, newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec))
08376 processed = TRUE;
08377 }
08378
08379 else if (image) {
08380 if (process_sdp_a_image(value, p))
08381 processed = TRUE;
08382 }
08383 break;
08384 }
08385
08386 if (option_debug > 2)
08387 ast_log(LOG_DEBUG, "Processing media-level (%s) SDP %c=%s... %s\n",
08388 (audio == TRUE)? "audio" : (video == TRUE)? "video" : "image",
08389 type, value,
08390 (processed == TRUE)? "OK." : "UNSUPPORTED.");
08391 }
08392 }
08393
08394
08395
08396 if (!hp && !vhp && !thp && !ihp) {
08397 ast_log(LOG_WARNING, "Insufficient information in SDP (c=)...\n");
08398 return -1;
08399 }
08400
08401 if (portno == -1 && vportno == -1 && udptlportno == -1 && tportno == -1)
08402
08403
08404 return -2;
08405
08406 if (numberofmediastreams > 3)
08407
08408 return -3;
08409
08410 if (udptlportno == -1) {
08411 change_t38_state(p, T38_DISABLED);
08412 }
08413
08414
08415
08416 ast_rtp_get_current_formats(newaudiortp, &peercapability, &peernoncodeccapability);
08417 ast_rtp_get_current_formats(newvideortp, &vpeercapability, &vpeernoncodeccapability);
08418 ast_rtp_get_current_formats(newtextrtp, &tpeercapability, &tpeernoncodeccapability);
08419
08420 newjointcapability = p->capability & (peercapability | vpeercapability | tpeercapability);
08421 newpeercapability = (peercapability | vpeercapability | tpeercapability);
08422 newnoncodeccapability = p->noncodeccapability & peernoncodeccapability;
08423
08424 if (debug) {
08425
08426 char s1[SIPBUFSIZE], s2[SIPBUFSIZE], s3[SIPBUFSIZE], s4[SIPBUFSIZE], s5[SIPBUFSIZE];
08427
08428 ast_verbose("Capabilities: us - %s, peer - audio=%s/video=%s/text=%s, combined - %s\n",
08429 ast_getformatname_multiple(s1, SIPBUFSIZE, p->capability),
08430 ast_getformatname_multiple(s2, SIPBUFSIZE, peercapability),
08431 ast_getformatname_multiple(s3, SIPBUFSIZE, vpeercapability),
08432 ast_getformatname_multiple(s4, SIPBUFSIZE, tpeercapability),
08433 ast_getformatname_multiple(s5, SIPBUFSIZE, newjointcapability));
08434
08435 ast_verbose("Non-codec capabilities (dtmf): us - %s, peer - %s, combined - %s\n",
08436 ast_rtp_lookup_mime_multiple(s1, SIPBUFSIZE, p->noncodeccapability, 0, 0),
08437 ast_rtp_lookup_mime_multiple(s2, SIPBUFSIZE, peernoncodeccapability, 0, 0),
08438 ast_rtp_lookup_mime_multiple(s3, SIPBUFSIZE, newnoncodeccapability, 0, 0));
08439 }
08440 if (!newjointcapability && (portno != -1)) {
08441 ast_log(LOG_NOTICE, "No compatible codecs, not accepting this offer!\n");
08442
08443 return -1;
08444 }
08445
08446
08447 if (p->rtp) {
08448 if (portno > 0) {
08449 sin.sin_family = AF_INET;
08450 sin.sin_port = htons(portno);
08451 memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
08452 ast_rtp_set_peer(p->rtp, &sin);
08453 if (debug)
08454 ast_verbose("Peer audio RTP is at port %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
08455
08456
08457 p->jointcapability = newjointcapability;
08458 p->peercapability = newpeercapability;
08459 p->jointnoncodeccapability = newnoncodeccapability;
08460
08461 ast_rtp_pt_copy(p->rtp, newaudiortp);
08462
08463 if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) {
08464 ast_clear_flag(&p->flags[0], SIP_DTMF);
08465 if (newnoncodeccapability & AST_RTP_DTMF) {
08466
08467 ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
08468
08469 ast_rtp_setdtmf(p->rtp, 1);
08470 ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
08471 } else {
08472 ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
08473 }
08474 }
08475 } else if (udptlportno > 0) {
08476 if (debug)
08477 ast_verbose("Got T.38 Re-invite without audio. Keeping RTP active during T.38 session.\n");
08478 } else {
08479 ast_rtp_stop(p->rtp);
08480 if (debug)
08481 ast_verbose("Peer doesn't provide audio\n");
08482 }
08483 }
08484
08485
08486 if (p->vrtp) {
08487 if (vportno > 0) {
08488 vsin.sin_family = AF_INET;
08489 vsin.sin_port = htons(vportno);
08490 memcpy(&vsin.sin_addr, vhp->h_addr, sizeof(vsin.sin_addr));
08491 ast_rtp_set_peer(p->vrtp, &vsin);
08492 if (debug)
08493 ast_verbose("Peer video RTP is at port %s:%d\n", ast_inet_ntoa(vsin.sin_addr), ntohs(vsin.sin_port));
08494 ast_rtp_pt_copy(p->vrtp, newvideortp);
08495 } else {
08496 ast_rtp_stop(p->vrtp);
08497 if (debug)
08498 ast_verbose("Peer doesn't provide video\n");
08499 }
08500 }
08501
08502
08503 if (p->trtp) {
08504 if (tportno > 0) {
08505 tsin.sin_family = AF_INET;
08506 tsin.sin_port = htons(tportno);
08507 memcpy(&tsin.sin_addr, thp->h_addr, sizeof(tsin.sin_addr));
08508 ast_rtp_set_peer(p->trtp, &tsin);
08509 if (debug)
08510 ast_verbose("Peer T.140 RTP is at port %s:%d\n", ast_inet_ntoa(tsin.sin_addr), ntohs(tsin.sin_port));
08511 if ((p->jointcapability & AST_FORMAT_T140RED)) {
08512 p->red = 1;
08513 rtp_red_init(p->trtp, 300, red_data_pt, 2);
08514 } else {
08515 p->red = 0;
08516 }
08517 ast_rtp_pt_copy(p->trtp, newtextrtp);
08518 } else {
08519 ast_rtp_stop(p->trtp);
08520 if (debug)
08521 ast_verbose("Peer doesn't provide T.140\n");
08522 }
08523 }
08524
08525 if (p->udptl) {
08526 if (udptlportno > 0) {
08527 isin.sin_family = AF_INET;
08528 isin.sin_port = htons(udptlportno);
08529 if (ast_test_flag(&p->flags[0], SIP_NAT) && ast_test_flag(&p->flags[1], SIP_PAGE2_UDPTL_DESTINATION)) {
08530 struct sockaddr_in remote_address = { 0, };
08531 ast_rtp_get_peer(p->rtp, &remote_address);
08532 if (remote_address.sin_addr.s_addr) {
08533 memcpy(&isin, &remote_address, sizeof(isin));
08534 if (debug) {
08535 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));
08536 }
08537 }
08538 } else {
08539 memcpy(&isin.sin_addr, ihp->h_addr, sizeof(isin.sin_addr));
08540 }
08541 ast_udptl_set_peer(p->udptl, &isin);
08542 if (debug)
08543 ast_debug(1,"Peer T.38 UDPTL is at port %s:%d\n", ast_inet_ntoa(isin.sin_addr), ntohs(isin.sin_port));
08544
08545
08546 if (!ast_udptl_get_far_max_datagram(p->udptl)) {
08547
08548 ast_udptl_set_far_max_datagram(p->udptl, 0);
08549 }
08550
08551
08552 if ((t38action == SDP_T38_ACCEPT) &&
08553 (p->t38.state == T38_LOCAL_REINVITE)) {
08554 change_t38_state(p, T38_ENABLED);
08555 } else if ((t38action == SDP_T38_INITIATE) &&
08556 p->owner && p->lastinvite) {
08557 change_t38_state(p, T38_PEER_REINVITE);
08558
08559 if (ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_T38)) {
08560 ast_channel_lock(p->owner);
08561 if (strcmp(p->owner->exten, "fax")) {
08562 const char *target_context = S_OR(p->owner->macrocontext, p->owner->context);
08563 ast_channel_unlock(p->owner);
08564 if (ast_exists_extension(p->owner, target_context, "fax", 1, p->owner->cid.cid_num)) {
08565 ast_verbose(VERBOSE_PREFIX_2 "Redirecting '%s' to fax extension due to peer T.38 re-INVITE\n", p->owner->name);
08566 pbx_builtin_setvar_helper(p->owner, "FAXEXTEN", p->owner->exten);
08567 if (ast_async_goto(p->owner, target_context, "fax", 1)) {
08568 ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", p->owner->name, target_context);
08569 }
08570 } else {
08571 ast_log(LOG_NOTICE, "T.38 re-INVITE detected but no fax extension\n");
08572 }
08573 } else {
08574 ast_channel_unlock(p->owner);
08575 }
08576 }
08577 }
08578 } else {
08579 ast_udptl_stop(p->udptl);
08580 if (debug)
08581 ast_debug(1, "Peer doesn't provide T.38 UDPTL\n");
08582 }
08583 }
08584
08585 if ((portno == -1) && (p->t38.state != T38_DISABLED)) {
08586 ast_debug(3, "Have T.38 but no audio, accepting offer anyway\n");
08587 return 0;
08588 }
08589
08590
08591 ast_debug(2, "We're settling with these formats: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, p->jointcapability));
08592
08593 if (!p->owner)
08594 return 0;
08595
08596 ast_debug(4, "We have an owner, now see if we need to change this call\n");
08597
08598 if (!(p->owner->nativeformats & p->jointcapability) && (p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
08599 if (debug) {
08600 char s1[SIPBUFSIZE], s2[SIPBUFSIZE];
08601 ast_debug(1, "Oooh, we need to change our audio formats since our peer supports only %s and not %s\n",
08602 ast_getformatname_multiple(s1, SIPBUFSIZE, p->jointcapability),
08603 ast_getformatname_multiple(s2, SIPBUFSIZE, p->owner->nativeformats));
08604 }
08605 p->owner->nativeformats = ast_codec_choose(&p->prefs, p->jointcapability, 1) | (p->capability & vpeercapability) | (p->capability & tpeercapability);
08606 ast_set_read_format(p->owner, p->owner->readformat);
08607 ast_set_write_format(p->owner, p->owner->writeformat);
08608 }
08609
08610 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) && sin.sin_addr.s_addr && (!sendonly || sendonly == -1)) {
08611 ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
08612
08613 ast_queue_frame(p->owner, &ast_null_frame);
08614
08615 append_history(p, "Unhold", "%s", req->data->str);
08616 if (sip_cfg.callevents)
08617 manager_event(EVENT_FLAG_CALL, "Hold",
08618 "Status: Off\r\n"
08619 "Channel: %s\r\n"
08620 "Uniqueid: %s\r\n",
08621 p->owner->name,
08622 p->owner->uniqueid);
08623 if (sip_cfg.notifyhold)
08624 sip_peer_hold(p, FALSE);
08625 ast_clear_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD);
08626 } else if (!sin.sin_addr.s_addr || (sendonly && sendonly != -1)) {
08627 int already_on_hold = ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD);
08628 ast_queue_control_data(p->owner, AST_CONTROL_HOLD,
08629 S_OR(p->mohsuggest, NULL),
08630 !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
08631 if (sendonly)
08632 ast_rtp_stop(p->rtp);
08633
08634
08635 ast_queue_frame(p->owner, &ast_null_frame);
08636
08637 append_history(p, "Hold", "%s", req->data->str);
08638 if (sip_cfg.callevents && !ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
08639 manager_event(EVENT_FLAG_CALL, "Hold",
08640 "Status: On\r\n"
08641 "Channel: %s\r\n"
08642 "Uniqueid: %s\r\n",
08643 p->owner->name,
08644 p->owner->uniqueid);
08645 }
08646 if (sendonly == 1)
08647 ast_set_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD_ONEDIR);
08648 else if (sendonly == 2)
08649 ast_set_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD_INACTIVE);
08650 else
08651 ast_set_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD_ACTIVE);
08652 if (sip_cfg.notifyhold && !already_on_hold)
08653 sip_peer_hold(p, TRUE);
08654 }
08655
08656 return 0;
08657 }
08658
08659 static int process_sdp_o(const char *o, struct sip_pvt *p)
08660 {
08661 char *o_copy;
08662 char *token;
08663 int64_t rua_version;
08664
08665
08666
08667
08668
08669
08670
08671
08672
08673
08674 p->session_modify = TRUE;
08675
08676 if (ast_strlen_zero(o)) {
08677 ast_log(LOG_WARNING, "SDP syntax error. SDP without an o= line\n");
08678 return FALSE;
08679 }
08680
08681 o_copy = ast_strdupa(o);
08682 token = strsep(&o_copy, " ");
08683 if (!o_copy) {
08684 ast_log(LOG_WARNING, "SDP syntax error in o= line username\n");
08685 return FALSE;
08686 }
08687 token = strsep(&o_copy, " ");
08688 if (!o_copy) {
08689 ast_log(LOG_WARNING, "SDP syntax error in o= line session-id\n");
08690 return FALSE;
08691 }
08692 token = strsep(&o_copy, " ");
08693 if (!o_copy) {
08694 ast_log(LOG_WARNING, "SDP syntax error in o= line\n");
08695 return FALSE;
08696 }
08697 if (!sscanf(token, "%30" SCNd64, &rua_version)) {
08698 ast_log(LOG_WARNING, "SDP syntax error in o= line version\n");
08699 return FALSE;
08700 }
08701
08702
08703
08704
08705
08706
08707
08708
08709
08710
08711
08712
08713
08714
08715
08716
08717
08718
08719
08720 if (ast_test_flag(&p->flags[1], SIP_PAGE2_IGNORESDPVERSION) ||
08721 (p->sessionversion_remote < 0) ||
08722 (p->sessionversion_remote < rua_version)) {
08723 p->sessionversion_remote = rua_version;
08724 } else {
08725 if (p->t38.state == T38_LOCAL_REINVITE) {
08726 p->sessionversion_remote = rua_version;
08727 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);
08728 } else {
08729 p->session_modify = FALSE;
08730 ast_debug(2, "Call %s responded to our reinvite without changing SDP version; ignoring SDP.\n", p->callid);
08731 return FALSE;
08732 }
08733 }
08734
08735 return TRUE;
08736 }
08737
08738 static int process_sdp_c(const char *c, struct ast_hostent *ast_hp)
08739 {
08740 char host[258];
08741 struct hostent *hp;
08742
08743
08744 if (sscanf(c, "IN IP4 %255s", host) != 1) {
08745 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
08746 return FALSE;
08747 } else {
08748 if (!(hp = ast_gethostbyname(host, ast_hp))) {
08749 ast_log(LOG_WARNING, "Unable to lookup RTP Audio host in c= line, '%s'\n", c);
08750 return FALSE;
08751 }
08752 return TRUE;
08753 }
08754 return FALSE;
08755 }
08756
08757 static int process_sdp_a_sendonly(const char *a, int *sendonly)
08758 {
08759 int found = FALSE;
08760
08761 if (!strcasecmp(a, "sendonly")) {
08762 if (*sendonly == -1)
08763 *sendonly = 1;
08764 found = TRUE;
08765 } else if (!strcasecmp(a, "inactive")) {
08766 if (*sendonly == -1)
08767 *sendonly = 2;
08768 found = TRUE;
08769 } else if (!strcasecmp(a, "sendrecv")) {
08770 if (*sendonly == -1)
08771 *sendonly = 0;
08772 found = TRUE;
08773 }
08774 return found;
08775 }
08776
08777 static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp *newaudiortp, int *last_rtpmap_codec)
08778 {
08779 int found = FALSE;
08780 int codec;
08781 char mimeSubtype[128];
08782 char fmtp_string[64];
08783 unsigned int sample_rate;
08784 int debug = sip_debug_test_pvt(p);
08785
08786 if (!strncasecmp(a, "ptime", 5)) {
08787 char *tmp = strrchr(a, ':');
08788 long int framing = 0;
08789 if (tmp) {
08790 tmp++;
08791 framing = strtol(tmp, NULL, 10);
08792 if (framing == LONG_MIN || framing == LONG_MAX) {
08793 framing = 0;
08794 ast_debug(1, "Can't read framing from SDP: %s\n", a);
08795 }
08796 }
08797 if (framing && p->autoframing) {
08798 struct ast_codec_pref *pref = ast_rtp_codec_getpref(p->rtp);
08799 int codec_n;
08800 int format = 0;
08801 for (codec_n = 0; codec_n < MAX_RTP_PT; codec_n++) {
08802 format = ast_rtp_codec_getformat(codec_n);
08803 if (!format)
08804 continue;
08805 if (option_debug)
08806 ast_log(LOG_DEBUG, "Setting framing for %d to %ld\n", format, framing);
08807 ast_codec_pref_setsize(pref, format, framing);
08808 }
08809 ast_rtp_codec_setpref(p->rtp, pref);
08810 }
08811 found = TRUE;
08812 } else if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
08813
08814 if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
08815 if (ast_rtp_set_rtpmap_type_rate(newaudiortp, codec, "audio", mimeSubtype,
08816 ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0, sample_rate) != -1) {
08817 if (debug)
08818 ast_verbose("Found audio description format %s for ID %d\n", mimeSubtype, codec);
08819
08820 (*last_rtpmap_codec)++;
08821 found = TRUE;
08822 } else {
08823 ast_rtp_unset_m_type(newaudiortp, codec);
08824 if (debug)
08825 ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
08826 }
08827 } else {
08828 if (debug)
08829 ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
08830 }
08831 } else if (sscanf(a, "fmtp: %30u %63s", &codec, fmtp_string) == 2) {
08832 struct rtpPayloadType payload;
08833
08834 payload = ast_rtp_lookup_pt(newaudiortp, codec);
08835 if (payload.code && payload.isAstFormat) {
08836 unsigned int bit_rate;
08837
08838 switch (payload.code) {
08839 case AST_FORMAT_SIREN7:
08840 if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
08841 if (bit_rate != 32000) {
08842 ast_log(LOG_WARNING, "Got Siren7 offer at %d bps, but only 32000 bps supported; ignoring.\n", bit_rate);
08843 ast_rtp_unset_m_type(newaudiortp, codec);
08844 } else {
08845 found = TRUE;
08846 }
08847 }
08848 break;
08849 case AST_FORMAT_SIREN14:
08850 if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
08851 if (bit_rate != 48000) {
08852 ast_log(LOG_WARNING, "Got Siren14 offer at %d bps, but only 48000 bps supported; ignoring.\n", bit_rate);
08853 ast_rtp_unset_m_type(newaudiortp, codec);
08854 } else {
08855 found = TRUE;
08856 }
08857 }
08858 break;
08859 }
08860 }
08861 }
08862
08863 return found;
08864 }
08865
08866 static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp *newvideortp, int *last_rtpmap_codec)
08867 {
08868 int found = FALSE;
08869 int codec;
08870 char mimeSubtype[128];
08871 unsigned int sample_rate;
08872 int debug = sip_debug_test_pvt(p);
08873
08874 if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
08875
08876 if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
08877
08878 if (!strncasecmp(mimeSubtype, "H26", 3) || !strncasecmp(mimeSubtype, "MP4", 3)) {
08879 if (ast_rtp_set_rtpmap_type_rate(newvideortp, codec, "video", mimeSubtype, 0, sample_rate) != -1) {
08880 if (debug)
08881 ast_verbose("Found video description format %s for ID %d\n", mimeSubtype, codec);
08882
08883 (*last_rtpmap_codec)++;
08884 found = TRUE;
08885 } else {
08886 ast_rtp_unset_m_type(newvideortp, codec);
08887 if (debug)
08888 ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
08889 }
08890 }
08891 } else {
08892 if (debug)
08893 ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
08894 }
08895 }
08896
08897 return found;
08898 }
08899
08900 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)
08901 {
08902 int found = FALSE;
08903 int codec;
08904 char mimeSubtype[128];
08905 unsigned int sample_rate;
08906 char *red_cp;
08907 int debug = sip_debug_test_pvt(p);
08908
08909 if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
08910
08911 if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
08912 if (!strncasecmp(mimeSubtype, "T140", 4)) {
08913 if (p->trtp) {
08914
08915 ast_rtp_set_rtpmap_type(newtextrtp, codec, "text", mimeSubtype, 0);
08916 found = TRUE;
08917 }
08918 } else if (!strncasecmp(mimeSubtype, "RED", 3)) {
08919 if (p->trtp) {
08920 ast_rtp_set_rtpmap_type(newtextrtp, codec, "text", mimeSubtype, 0);
08921 sprintf(red_fmtp, "fmtp:%d ", codec);
08922 if (debug)
08923 ast_verbose("RED submimetype has payload type: %d\n", codec);
08924 found = TRUE;
08925 }
08926 }
08927 } else {
08928 if (debug)
08929 ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
08930 }
08931 } else if (!strncmp(a, red_fmtp, strlen(red_fmtp))) {
08932
08933 red_cp = &red_fmtp[strlen(red_fmtp)];
08934 strncpy(red_fmtp, a, 100);
08935
08936 sscanf(red_cp, "%30u", &red_data_pt[*red_num_gen]);
08937 red_cp = strtok(red_cp, "/");
08938 while (red_cp && (*red_num_gen)++ < RED_MAX_GENERATION) {
08939 sscanf(red_cp, "%30u", &red_data_pt[*red_num_gen]);
08940 red_cp = strtok(NULL, "/");
08941 }
08942 red_cp = red_fmtp;
08943 found = TRUE;
08944 }
08945
08946 return found;
08947 }
08948
08949 static int process_sdp_a_image(const char *a, struct sip_pvt *p)
08950 {
08951 int found = FALSE;
08952 char s[256];
08953 unsigned int x;
08954
08955 if ((sscanf(a, "T38FaxMaxBuffer:%30u", &x) == 1)) {
08956 ast_debug(3, "MaxBufferSize:%d\n", x);
08957 found = TRUE;
08958 } else if ((sscanf(a, "T38MaxBitRate:%30u", &x) == 1) || (sscanf(a, "T38FaxMaxRate:%30u", &x) == 1)) {
08959 ast_debug(3, "T38MaxBitRate: %d\n", x);
08960 switch (x) {
08961 case 14400:
08962 p->t38.their_parms.rate = AST_T38_RATE_14400;
08963 break;
08964 case 12000:
08965 p->t38.their_parms.rate = AST_T38_RATE_12000;
08966 break;
08967 case 9600:
08968 p->t38.their_parms.rate = AST_T38_RATE_9600;
08969 break;
08970 case 7200:
08971 p->t38.their_parms.rate = AST_T38_RATE_7200;
08972 break;
08973 case 4800:
08974 p->t38.their_parms.rate = AST_T38_RATE_4800;
08975 break;
08976 case 2400:
08977 p->t38.their_parms.rate = AST_T38_RATE_2400;
08978 break;
08979 }
08980 found = TRUE;
08981 } else if ((sscanf(a, "T38FaxVersion:%30u", &x) == 1)) {
08982 ast_debug(3, "FaxVersion: %u\n", x);
08983 p->t38.their_parms.version = x;
08984 found = TRUE;
08985 } else if ((sscanf(a, "T38FaxMaxDatagram:%30u", &x) == 1) || (sscanf(a, "T38MaxDatagram:%30u", &x) == 1)) {
08986
08987 if (((signed int) p->t38_maxdatagram >= 0) && ((unsigned int) p->t38_maxdatagram > x)) {
08988 ast_debug(1, "Overriding T38FaxMaxDatagram '%d' with '%d'\n", x, p->t38_maxdatagram);
08989 x = p->t38_maxdatagram;
08990 }
08991 ast_debug(3, "FaxMaxDatagram: %u\n", x);
08992 ast_udptl_set_far_max_datagram(p->udptl, x);
08993 found = TRUE;
08994 } else if ((strncmp(a, "T38FaxFillBitRemoval", 20) == 0)) {
08995 if (sscanf(a, "T38FaxFillBitRemoval:%30u", &x) == 1) {
08996 ast_debug(3, "FillBitRemoval: %d\n", x);
08997 if (x == 1) {
08998 p->t38.their_parms.fill_bit_removal = TRUE;
08999 }
09000 } else {
09001 ast_debug(3, "FillBitRemoval\n");
09002 p->t38.their_parms.fill_bit_removal = TRUE;
09003 }
09004 found = TRUE;
09005 } else if ((strncmp(a, "T38FaxTranscodingMMR", 20) == 0)) {
09006 if (sscanf(a, "T38FaxTranscodingMMR:%30u", &x) == 1) {
09007 ast_debug(3, "Transcoding MMR: %d\n", x);
09008 if (x == 1) {
09009 p->t38.their_parms.transcoding_mmr = TRUE;
09010 }
09011 } else {
09012 ast_debug(3, "Transcoding MMR\n");
09013 p->t38.their_parms.transcoding_mmr = TRUE;
09014 }
09015 found = TRUE;
09016 } else if ((strncmp(a, "T38FaxTranscodingJBIG", 21) == 0)) {
09017 if (sscanf(a, "T38FaxTranscodingJBIG:%30u", &x) == 1) {
09018 ast_debug(3, "Transcoding JBIG: %d\n", x);
09019 if (x == 1) {
09020 p->t38.their_parms.transcoding_jbig = TRUE;
09021 }
09022 } else {
09023 ast_debug(3, "Transcoding JBIG\n");
09024 p->t38.their_parms.transcoding_jbig = TRUE;
09025 }
09026 found = TRUE;
09027 } else if ((sscanf(a, "T38FaxRateManagement:%255s", s) == 1)) {
09028 ast_debug(3, "RateManagement: %s\n", s);
09029 if (!strcasecmp(s, "localTCF"))
09030 p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_LOCAL_TCF;
09031 else if (!strcasecmp(s, "transferredTCF"))
09032 p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF;
09033 found = TRUE;
09034 } else if ((sscanf(a, "T38FaxUdpEC:%255s", s) == 1)) {
09035 ast_debug(3, "UDP EC: %s\n", s);
09036 if (!strcasecmp(s, "t38UDPRedundancy")) {
09037 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
09038 } else if (!strcasecmp(s, "t38UDPFEC")) {
09039 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
09040 } else {
09041 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
09042 }
09043 found = TRUE;
09044 }
09045
09046 return found;
09047 }
09048
09049
09050 #ifdef LOW_MEMORY
09051 static void ts_ast_rtp_destroy(void *data)
09052 {
09053 struct ast_rtp *tmp = data;
09054 ast_rtp_destroy(tmp);
09055 }
09056 #endif
09057
09058
09059 static int add_header(struct sip_request *req, const char *var, const char *value)
09060 {
09061 if (req->headers == SIP_MAX_HEADERS) {
09062 ast_log(LOG_WARNING, "Out of SIP header space\n");
09063 return -1;
09064 }
09065
09066 if (req->lines) {
09067 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
09068 return -1;
09069 }
09070
09071 if (sip_cfg.compactheaders) {
09072 var = find_alias(var, var);
09073 }
09074
09075 ast_str_append(&req->data, 0, "%s: %s\r\n", var, value);
09076 req->header[req->headers] = req->len;
09077
09078 req->len = ast_str_strlen(req->data);
09079 req->headers++;
09080
09081 return 0;
09082 }
09083
09084
09085 static int add_header_contentLength(struct sip_request *req, int len)
09086 {
09087 char clen[10];
09088
09089 snprintf(clen, sizeof(clen), "%d", len);
09090 return add_header(req, "Content-Length", clen);
09091 }
09092
09093
09094 static int add_line(struct sip_request *req, const char *line)
09095 {
09096 if (req->lines == SIP_MAX_LINES) {
09097 ast_log(LOG_WARNING, "Out of SIP line space\n");
09098 return -1;
09099 }
09100 if (!req->lines)
09101
09102 req->len += ast_str_append(&req->data, 0, "\r\n");
09103 req->line[req->lines] = req->len;
09104 ast_str_append(&req->data, 0, "%s", line);
09105 req->len = ast_str_strlen(req->data);
09106 req->lines++;
09107 return 0;
09108 }
09109
09110
09111 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field)
09112 {
09113 const char *tmp = get_header(orig, field);
09114
09115 if (!ast_strlen_zero(tmp))
09116 return add_header(req, field, tmp);
09117 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
09118 return -1;
09119 }
09120
09121
09122 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field)
09123 {
09124 int start = 0;
09125 int copied = 0;
09126 for (;;) {
09127 const char *tmp = __get_header(orig, field, &start);
09128
09129 if (ast_strlen_zero(tmp))
09130 break;
09131
09132 add_header(req, field, tmp);
09133 copied++;
09134 }
09135 return copied ? 0 : -1;
09136 }
09137
09138
09139
09140
09141
09142
09143
09144
09145
09146 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field)
09147 {
09148 int copied = 0;
09149 int start = 0;
09150
09151 for (;;) {
09152 char new[512];
09153 const char *oh = __get_header(orig, field, &start);
09154
09155 if (ast_strlen_zero(oh))
09156 break;
09157
09158 if (!copied) {
09159 char leftmost[512], *others, *rport;
09160
09161
09162 ast_copy_string(leftmost, oh, sizeof(leftmost));
09163 others = strchr(leftmost, ',');
09164 if (others)
09165 *others++ = '\0';
09166
09167
09168 rport = strstr(leftmost, ";rport");
09169 if (rport && *(rport+6) == '=')
09170 rport = NULL;
09171
09172
09173 if (rport && ((ast_test_flag(&p->flags[0], SIP_NAT) == SIP_NAT_ALWAYS) || (ast_test_flag(&p->flags[0], SIP_NAT) == SIP_NAT_RFC3581))) {
09174
09175 char *end;
09176
09177 rport = strstr(leftmost, ";rport");
09178
09179 if (rport) {
09180 end = strchr(rport + 1, ';');
09181 if (end)
09182 memmove(rport, end, strlen(end) + 1);
09183 else
09184 *rport = '\0';
09185 }
09186
09187
09188 snprintf(new, sizeof(new), "%s;received=%s;rport=%d%s%s",
09189 leftmost, ast_inet_ntoa(p->recv.sin_addr),
09190 ntohs(p->recv.sin_port),
09191 others ? "," : "", others ? others : "");
09192 } else {
09193
09194 snprintf(new, sizeof(new), "%s;received=%s%s%s",
09195 leftmost, ast_inet_ntoa(p->recv.sin_addr),
09196 others ? "," : "", others ? others : "");
09197 }
09198 oh = new;
09199 }
09200 add_header(req, field, oh);
09201 copied++;
09202 }
09203 if (!copied) {
09204 ast_log(LOG_NOTICE, "No header field '%s' present to copy\n", field);
09205 return -1;
09206 }
09207 return 0;
09208 }
09209
09210
09211 static void add_route(struct sip_request *req, struct sip_route *route)
09212 {
09213 char r[SIPBUFSIZE*2], *p;
09214 int n, rem = sizeof(r);
09215
09216 if (!route)
09217 return;
09218
09219 p = r;
09220 for (;route ; route = route->next) {
09221 n = strlen(route->hop);
09222 if (rem < n+3)
09223 break;
09224 if (p != r) {
09225 *p++ = ',';
09226 --rem;
09227 }
09228 *p++ = '<';
09229 ast_copy_string(p, route->hop, rem);
09230 p += n;
09231 *p++ = '>';
09232 rem -= (n+2);
09233 }
09234 *p = '\0';
09235 add_header(req, "Route", r);
09236 }
09237
09238
09239
09240
09241
09242
09243
09244
09245
09246
09247 static void set_destination(struct sip_pvt *p, char *uri)
09248 {
09249 char *h, *maddr, hostname[256];
09250 int port, hn;
09251 struct hostent *hp;
09252 struct ast_hostent ahp;
09253 int debug=sip_debug_test_pvt(p);
09254 int tls_on = FALSE;
09255 int use_dns = sip_cfg.srvlookup;
09256
09257 if (debug)
09258 ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
09259
09260
09261 h = strchr(uri, '@');
09262 if (h)
09263 ++h;
09264 else {
09265 h = uri;
09266 if (!strncasecmp(h, "sip:", 4)) {
09267 h += 4;
09268 } else if (!strncasecmp(h, "sips:", 5)) {
09269 h += 5;
09270 tls_on = TRUE;
09271 }
09272 }
09273 hn = strcspn(h, ":;>") + 1;
09274 if (hn > sizeof(hostname))
09275 hn = sizeof(hostname);
09276 ast_copy_string(hostname, h, hn);
09277
09278 h += hn - 1;
09279
09280
09281 if (*h == ':') {
09282
09283 ++h;
09284 port = strtol(h, &h, 10);
09285 use_dns = FALSE;
09286 } else
09287 port = tls_on ? STANDARD_TLS_PORT : STANDARD_SIP_PORT;
09288
09289
09290 maddr = strstr(h, "maddr=");
09291 if (maddr) {
09292 maddr += 6;
09293 hn = strspn(maddr, "0123456789.") + 1;
09294 if (hn > sizeof(hostname))
09295 hn = sizeof(hostname);
09296 ast_copy_string(hostname, maddr, hn);
09297 }
09298
09299
09300
09301 hp = ast_gethostbyname(hostname, &ahp);
09302 if (hp == NULL) {
09303 ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
09304 return;
09305 }
09306 p->sa.sin_family = AF_INET;
09307 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
09308 p->sa.sin_port = htons(port);
09309 if (debug)
09310 ast_verbose("set_destination: set destination to %s, port %d\n", ast_inet_ntoa(p->sa.sin_addr), port);
09311 }
09312
09313
09314 static int init_resp(struct sip_request *resp, const char *msg)
09315 {
09316
09317 memset(resp, 0, sizeof(*resp));
09318 resp->method = SIP_RESPONSE;
09319 if (!(resp->data = ast_str_create(SIP_MIN_PACKET)))
09320 return -1;
09321 resp->header[0] = 0;
09322 ast_str_set(&resp->data, 0, "SIP/2.0 %s\r\n", msg);
09323 resp->len = resp->data->used;
09324 resp->headers++;
09325 return 0;
09326 }
09327
09328
09329 static int init_req(struct sip_request *req, int sipmethod, const char *recip)
09330 {
09331
09332 memset(req, 0, sizeof(*req));
09333 if (!(req->data = ast_str_create(SIP_MIN_PACKET)))
09334 return -1;
09335 req->method = sipmethod;
09336 req->header[0] = 0;
09337 ast_str_set(&req->data, 0, "%s %s SIP/2.0\r\n", sip_methods[sipmethod].text, recip);
09338 req->len = ast_str_strlen(req->data);
09339 req->headers++;
09340 return 0;
09341 }
09342
09343
09344 static inline int resp_needs_contact(const char *msg, enum sipmethod method) {
09345
09346
09347
09348
09349
09350
09351
09352
09353
09354
09355
09356
09357
09358
09359
09360 switch (method) {
09361
09362 case SIP_INVITE:
09363 case SIP_UPDATE:
09364 case SIP_SUBSCRIBE:
09365 case SIP_NOTIFY:
09366 if ((msg[0] >= '1' && msg[0] <= '3') || !strncmp(msg, "485", 3))
09367 return 1;
09368 break;
09369
09370
09371 case SIP_REGISTER:
09372 case SIP_OPTIONS:
09373 if (msg[0] == '2' || msg[0] == '3' || !strncmp(msg, "485", 3))
09374 return 1;
09375 break;
09376
09377
09378 case SIP_BYE:
09379 case SIP_PRACK:
09380 case SIP_MESSAGE:
09381 case SIP_PUBLISH:
09382 if (msg[0] == '3' || !strncmp(msg, "485", 3))
09383 return 1;
09384 break;
09385
09386
09387 case SIP_REFER:
09388 if (msg[0] >= '2' && msg[0] <= '6')
09389 return 1;
09390 break;
09391
09392
09393 case SIP_ACK:
09394 case SIP_CANCEL:
09395 case SIP_INFO:
09396 case SIP_PING:
09397 default:
09398 return 0;
09399 }
09400 return 0;
09401 }
09402
09403
09404 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req)
09405 {
09406 char newto[256];
09407 const char *ot;
09408
09409 init_resp(resp, msg);
09410 copy_via_headers(p, resp, req, "Via");
09411 if (msg[0] == '1' || msg[0] == '2')
09412 copy_all_header(resp, req, "Record-Route");
09413 copy_header(resp, req, "From");
09414 ot = get_header(req, "To");
09415 if (!strcasestr(ot, "tag=") && strncmp(msg, "100", 3)) {
09416
09417
09418 if (!ast_strlen_zero(p->theirtag) && ast_test_flag(&p->flags[0], SIP_OUTGOING))
09419 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
09420 else if (p->tag && !ast_test_flag(&p->flags[0], SIP_OUTGOING))
09421 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
09422 else
09423 ast_copy_string(newto, ot, sizeof(newto));
09424 ot = newto;
09425 }
09426 add_header(resp, "To", ot);
09427 copy_header(resp, req, "Call-ID");
09428 copy_header(resp, req, "CSeq");
09429 if (!ast_strlen_zero(global_useragent))
09430 add_header(resp, "Server", global_useragent);
09431 add_header(resp, "Allow", ALLOWED_METHODS);
09432 add_header(resp, "Supported", SUPPORTED_EXTENSIONS);
09433
09434
09435 if (p->method == SIP_INVITE && p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE) {
09436 char se_hdr[256];
09437 snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval,
09438 strefresher2str(p->stimer->st_ref));
09439 add_header(resp, "Require", "timer");
09440 add_header(resp, "Session-Expires", se_hdr);
09441 }
09442
09443 if (msg[0] == '2' && (p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER)) {
09444
09445
09446 char tmp[256];
09447
09448 snprintf(tmp, sizeof(tmp), "%d", p->expiry);
09449 add_header(resp, "Expires", tmp);
09450 if (p->expiry) {
09451 char contact[SIPBUFSIZE];
09452 const char *contact_uri = p->method == SIP_SUBSCRIBE ? p->our_contact : p->fullcontact;
09453 char *brackets = strchr(contact_uri, '<');
09454 snprintf(contact, sizeof(contact), "%s%s%s;expires=%d", brackets ? "" : "<", contact_uri, brackets ? "" : ">", p->expiry);
09455 add_header(resp, "Contact", contact);
09456 }
09457 } else if (!ast_strlen_zero(p->our_contact) && resp_needs_contact(msg, p->method)) {
09458 add_header(resp, "Contact", p->our_contact);
09459 }
09460
09461 if (!ast_strlen_zero(p->url)) {
09462 add_header(resp, "Access-URL", p->url);
09463 ast_string_field_set(p, url, NULL);
09464 }
09465
09466 return 0;
09467 }
09468
09469
09470 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch)
09471 {
09472 struct sip_request *orig = &p->initreq;
09473 char stripped[80];
09474 char tmp[80];
09475 char newto[256];
09476 const char *c;
09477 const char *ot, *of;
09478 int is_strict = FALSE;
09479 int is_outbound = ast_test_flag(&p->flags[0], SIP_OUTGOING);
09480
09481 memset(req, 0, sizeof(struct sip_request));
09482
09483 snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", sip_methods[sipmethod].text);
09484
09485 if (!seqno) {
09486 p->ocseq++;
09487 seqno = p->ocseq;
09488 }
09489
09490
09491 if (sipmethod == SIP_CANCEL) {
09492 p->branch = p->invite_branch;
09493 build_via(p);
09494 } else if (newbranch && (sipmethod == SIP_INVITE)) {
09495 p->branch ^= ast_random();
09496 p->invite_branch = p->branch;
09497 build_via(p);
09498 } else if (newbranch) {
09499 p->branch ^= ast_random();
09500 build_via(p);
09501 }
09502
09503
09504 if (p->route && !ast_strlen_zero(p->route->hop) && strstr(p->route->hop, ";lr") == NULL) {
09505 is_strict = TRUE;
09506 if (sipdebug)
09507 ast_debug(1, "Strict routing enforced for session %s\n", p->callid);
09508 }
09509
09510 if (sipmethod == SIP_CANCEL)
09511 c = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
09512 else if (sipmethod == SIP_ACK) {
09513
09514
09515 if (!ast_strlen_zero(p->okcontacturi))
09516 c = is_strict ? p->route->hop : p->okcontacturi;
09517 else
09518 c = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
09519 } else if (!ast_strlen_zero(p->okcontacturi))
09520 c = is_strict ? p->route->hop : p->okcontacturi;
09521 else if (!ast_strlen_zero(p->uri))
09522 c = p->uri;
09523 else {
09524 char *n;
09525
09526 ast_copy_string(stripped, get_header(orig, is_outbound ? "To" : "From"),
09527 sizeof(stripped));
09528 n = get_in_brackets(stripped);
09529 c = remove_uri_parameters(n);
09530 }
09531 init_req(req, sipmethod, c);
09532
09533 snprintf(tmp, sizeof(tmp), "%d %s", seqno, sip_methods[sipmethod].text);
09534
09535 add_header(req, "Via", p->via);
09536 if (p->route) {
09537 set_destination(p, p->route->hop);
09538 add_route(req, is_strict ? p->route->next : p->route);
09539 }
09540 add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
09541
09542 ot = get_header(orig, "To");
09543 of = get_header(orig, "From");
09544
09545
09546
09547 if (!strcasestr(ot, "tag=") && sipmethod != SIP_CANCEL) {
09548
09549
09550 if (is_outbound && !ast_strlen_zero(p->theirtag))
09551 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
09552 else if (!is_outbound)
09553 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
09554 else
09555 snprintf(newto, sizeof(newto), "%s", ot);
09556 ot = newto;
09557 }
09558
09559 if (is_outbound) {
09560 add_header(req, "From", of);
09561 add_header(req, "To", ot);
09562 } else {
09563 add_header(req, "From", ot);
09564 add_header(req, "To", of);
09565 }
09566
09567 if (sipmethod != SIP_BYE && sipmethod != SIP_CANCEL && sipmethod != SIP_MESSAGE)
09568 add_header(req, "Contact", p->our_contact);
09569
09570 copy_header(req, orig, "Call-ID");
09571 add_header(req, "CSeq", tmp);
09572
09573 if (!ast_strlen_zero(global_useragent))
09574 add_header(req, "User-Agent", global_useragent);
09575
09576 if (!ast_strlen_zero(p->rpid))
09577 add_header(req, "Remote-Party-ID", p->rpid);
09578
09579 if (!ast_strlen_zero(p->url)) {
09580 add_header(req, "Access-URL", p->url);
09581 ast_string_field_set(p, url, NULL);
09582 }
09583
09584
09585
09586
09587
09588
09589
09590
09591 if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE
09592 && sipmethod == SIP_INVITE) {
09593 char se_hdr[256];
09594 snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval,
09595 strefresher2str(p->stimer->st_ref));
09596 add_header(req, "Require", "timer");
09597 add_header(req, "Session-Expires", se_hdr);
09598 snprintf(se_hdr, sizeof(se_hdr), "%d", st_get_se(p, FALSE));
09599 add_header(req, "Min-SE", se_hdr);
09600 }
09601
09602 return 0;
09603 }
09604
09605
09606 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
09607 {
09608 struct sip_request resp;
09609 int seqno = 0;
09610
09611 if (reliable && (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1)) {
09612 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
09613 return -1;
09614 }
09615 respprep(&resp, p, msg, req);
09616 add_header_contentLength(&resp, 0);
09617
09618
09619 if (p->method == SIP_INVITE && msg[0] != '1' && p->owner && p->owner->hangupcause) {
09620 char buf[10];
09621
09622 add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->owner->hangupcause));
09623 snprintf(buf, sizeof(buf), "%d", p->owner->hangupcause);
09624 add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
09625 }
09626 return send_response(p, &resp, reliable, seqno);
09627 }
09628
09629 static int temp_pvt_init(void *data)
09630 {
09631 struct sip_pvt *p = data;
09632
09633 p->do_history = 0;
09634 return ast_string_field_init(p, 512);
09635 }
09636
09637 static void temp_pvt_cleanup(void *data)
09638 {
09639 struct sip_pvt *p = data;
09640
09641 ast_string_field_free_memory(p);
09642
09643 ast_free(data);
09644 }
09645
09646
09647 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)
09648 {
09649 struct sip_pvt *p = NULL;
09650
09651 if (!(p = ast_threadstorage_get(&ts_temp_pvt, sizeof(*p)))) {
09652 ast_log(LOG_ERROR, "Failed to get temporary pvt\n");
09653 return -1;
09654 }
09655
09656
09657
09658
09659
09660
09661
09662
09663
09664 p->method = intended_method;
09665
09666 if (!sin)
09667 p->ourip = internip;
09668 else {
09669 p->sa = *sin;
09670 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
09671 }
09672
09673 p->branch = ast_random();
09674 make_our_tag(p->tag, sizeof(p->tag));
09675 p->ocseq = INITIAL_CSEQ;
09676
09677 if (useglobal_nat && sin) {
09678 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT);
09679 p->recv = *sin;
09680 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
09681 }
09682
09683 ast_string_field_set(p, fromdomain, default_fromdomain);
09684 build_via(p);
09685 ast_string_field_set(p, callid, callid);
09686
09687 copy_socket_data(&p->socket, &req->socket);
09688
09689
09690 __transmit_response(p, msg, req, XMIT_UNRELIABLE);
09691
09692
09693 ast_string_field_init(p, 0);
09694
09695 return 0;
09696 }
09697
09698
09699 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req)
09700 {
09701 return __transmit_response(p, msg, req, XMIT_UNRELIABLE);
09702 }
09703
09704
09705 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported)
09706 {
09707 struct sip_request resp;
09708 respprep(&resp, p, msg, req);
09709 append_date(&resp);
09710 add_header(&resp, "Unsupported", unsupported);
09711 add_header_contentLength(&resp, 0);
09712 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
09713 }
09714
09715
09716 static int transmit_response_with_minse(struct sip_pvt *p, const char *msg, const struct sip_request *req, int minse_int)
09717 {
09718 struct sip_request resp;
09719 char minse_str[20];
09720
09721 respprep(&resp, p, msg, req);
09722 append_date(&resp);
09723
09724 snprintf(minse_str, sizeof(minse_str), "%d", minse_int);
09725 add_header(&resp, "Min-SE", minse_str);
09726
09727 add_header_contentLength(&resp, 0);
09728 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
09729 }
09730
09731
09732
09733
09734
09735 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req)
09736 {
09737 return __transmit_response(p, msg, req, req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL);
09738 }
09739
09740
09741 static void append_date(struct sip_request *req)
09742 {
09743 char tmpdat[256];
09744 struct tm tm;
09745 time_t t = time(NULL);
09746
09747 gmtime_r(&t, &tm);
09748 strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
09749 add_header(req, "Date", tmpdat);
09750 }
09751
09752
09753 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req)
09754 {
09755 struct sip_request resp;
09756 respprep(&resp, p, msg, req);
09757 append_date(&resp);
09758 add_header_contentLength(&resp, 0);
09759 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
09760 }
09761
09762
09763 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
09764 {
09765 struct sip_request resp;
09766 respprep(&resp, p, msg, req);
09767 add_header(&resp, "Accept", "application/sdp");
09768 add_header_contentLength(&resp, 0);
09769 return send_response(p, &resp, reliable, 0);
09770 }
09771
09772
09773 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)
09774 {
09775 struct sip_request resp;
09776 char tmp[512];
09777 int seqno = 0;
09778
09779 if (reliable && (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1)) {
09780 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
09781 return -1;
09782 }
09783
09784
09785 snprintf(tmp, sizeof(tmp), "Digest algorithm=MD5, realm=\"%s\", nonce=\"%s\"%s", sip_cfg.realm, randdata, stale ? ", stale=true" : "");
09786 respprep(&resp, p, msg, req);
09787 add_header(&resp, header, tmp);
09788 add_header_contentLength(&resp, 0);
09789 append_history(p, "AuthChal", "Auth challenge sent for %s - nc %d", p->username, p->noncecount);
09790 return send_response(p, &resp, reliable, seqno);
09791 }
09792
09793
09794 static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp)
09795 {
09796 int res;
09797
09798 if (!(res = with_sdp ? transmit_response_with_sdp(p, msg, req, XMIT_UNRELIABLE, FALSE) : transmit_response(p, msg, req))) {
09799 p->last_provisional = msg;
09800 update_provisional_keepalive(p, with_sdp);
09801 }
09802
09803 return res;
09804 }
09805
09806
09807 static int add_text(struct sip_request *req, const char *text)
09808 {
09809
09810 add_header(req, "Content-Type", "text/plain;charset=UTF-8");
09811 add_header_contentLength(req, strlen(text));
09812 add_line(req, text);
09813 return 0;
09814 }
09815
09816
09817
09818
09819
09820 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode)
09821 {
09822 char tmp[256];
09823 int event;
09824 if (mode) {
09825
09826 if (digit == '*')
09827 event = 10;
09828 else if (digit == '#')
09829 event = 11;
09830 else if ((digit >= 'A') && (digit <= 'D'))
09831 event = 12 + digit - 'A';
09832 else
09833 event = atoi(&digit);
09834 snprintf(tmp, sizeof(tmp), "%d\r\n", event);
09835 add_header(req, "Content-Type", "application/dtmf");
09836 add_header_contentLength(req, strlen(tmp));
09837 add_line(req, tmp);
09838 } else {
09839
09840 snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=%u\r\n", digit, duration);
09841 add_header(req, "Content-Type", "application/dtmf-relay");
09842 add_header_contentLength(req, strlen(tmp));
09843 add_line(req, tmp);
09844 }
09845 return 0;
09846 }
09847
09848
09849
09850 static int add_vidupdate(struct sip_request *req)
09851 {
09852 const char *xml_is_a_huge_waste_of_space =
09853 "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
09854 " <media_control>\r\n"
09855 " <vc_primitive>\r\n"
09856 " <to_encoder>\r\n"
09857 " <picture_fast_update>\r\n"
09858 " </picture_fast_update>\r\n"
09859 " </to_encoder>\r\n"
09860 " </vc_primitive>\r\n"
09861 " </media_control>\r\n";
09862 add_header(req, "Content-Type", "application/media_control+xml");
09863 add_header_contentLength(req, strlen(xml_is_a_huge_waste_of_space));
09864 add_line(req, xml_is_a_huge_waste_of_space);
09865 return 0;
09866 }
09867
09868
09869 static void add_codec_to_sdp(const struct sip_pvt *p, int codec,
09870 struct ast_str **m_buf, struct ast_str **a_buf,
09871 int debug, int *min_packet_size)
09872 {
09873 int rtp_code;
09874 struct ast_format_list fmt;
09875
09876
09877 if (debug)
09878 ast_verbose("Adding codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
09879 if ((rtp_code = ast_rtp_lookup_code(p->rtp, 1, codec)) == -1)
09880 return;
09881
09882 if (p->rtp) {
09883 struct ast_codec_pref *pref = ast_rtp_codec_getpref(p->rtp);
09884 fmt = ast_codec_pref_getsize(pref, codec);
09885 } else
09886 return;
09887 ast_str_append(m_buf, 0, " %d", rtp_code);
09888 ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
09889 ast_rtp_lookup_mime_subtype(1, codec,
09890 ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0),
09891 ast_rtp_lookup_sample_rate(1, codec));
09892
09893 switch (codec) {
09894 case AST_FORMAT_G729A:
09895
09896 ast_str_append(a_buf, 0, "a=fmtp:%d annexb=no\r\n", rtp_code);
09897 break;
09898 case AST_FORMAT_G723_1:
09899
09900 ast_str_append(a_buf, 0, "a=fmtp:%d annexa=no\r\n", rtp_code);
09901 break;
09902 case AST_FORMAT_ILBC:
09903
09904 ast_str_append(a_buf, 0, "a=fmtp:%d mode=%d\r\n", rtp_code, fmt.cur_ms);
09905 break;
09906 case AST_FORMAT_SIREN7:
09907
09908 ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=32000\r\n", rtp_code);
09909 break;
09910 case AST_FORMAT_SIREN14:
09911
09912 ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=48000\r\n", rtp_code);
09913 break;
09914 }
09915
09916 if (fmt.cur_ms && (fmt.cur_ms < *min_packet_size))
09917 *min_packet_size = fmt.cur_ms;
09918
09919
09920 if ((*min_packet_size)==0 && fmt.cur_ms)
09921 *min_packet_size = fmt.cur_ms;
09922 }
09923
09924
09925
09926 static void add_vcodec_to_sdp(const struct sip_pvt *p, int codec,
09927 struct ast_str **m_buf, struct ast_str **a_buf,
09928 int debug, int *min_packet_size)
09929 {
09930 int rtp_code;
09931
09932 if (!p->vrtp)
09933 return;
09934
09935 if (debug)
09936 ast_verbose("Adding video codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
09937
09938 if ((rtp_code = ast_rtp_lookup_code(p->vrtp, 1, codec)) == -1)
09939 return;
09940
09941 ast_str_append(m_buf, 0, " %d", rtp_code);
09942 ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
09943 ast_rtp_lookup_mime_subtype(1, codec, 0),
09944 ast_rtp_lookup_sample_rate(1, codec));
09945
09946 }
09947
09948
09949 static void add_tcodec_to_sdp(const struct sip_pvt *p, int codec,
09950 struct ast_str **m_buf, struct ast_str **a_buf,
09951 int debug, int *min_packet_size)
09952 {
09953 int rtp_code;
09954
09955 if (!p->trtp)
09956 return;
09957
09958 if (debug)
09959 ast_verbose("Adding text codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
09960
09961 if ((rtp_code = ast_rtp_lookup_code(p->trtp, 1, codec)) == -1)
09962 return;
09963
09964 ast_str_append(m_buf, 0, " %d", rtp_code);
09965 ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
09966 ast_rtp_lookup_mime_subtype(1, codec, 0),
09967 ast_rtp_lookup_sample_rate(1, codec));
09968
09969
09970 if (codec == AST_FORMAT_T140RED) {
09971 ast_str_append(a_buf, 0, "a=fmtp:%d %d/%d/%d\r\n", rtp_code,
09972 ast_rtp_lookup_code(p->trtp, 1, AST_FORMAT_T140),
09973 ast_rtp_lookup_code(p->trtp, 1, AST_FORMAT_T140),
09974 ast_rtp_lookup_code(p->trtp, 1, AST_FORMAT_T140));
09975
09976 }
09977 }
09978
09979
09980
09981 static unsigned int t38_get_rate(enum ast_control_t38_rate rate)
09982 {
09983 switch (rate) {
09984 case AST_T38_RATE_2400:
09985 return 2400;
09986 case AST_T38_RATE_4800:
09987 return 4800;
09988 case AST_T38_RATE_7200:
09989 return 7200;
09990 case AST_T38_RATE_9600:
09991 return 9600;
09992 case AST_T38_RATE_12000:
09993 return 12000;
09994 case AST_T38_RATE_14400:
09995 return 14400;
09996 default:
09997 return 0;
09998 }
09999 }
10000
10001
10002 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
10003 struct ast_str **m_buf, struct ast_str **a_buf,
10004 int debug)
10005 {
10006 int rtp_code;
10007
10008 if (debug)
10009 ast_verbose("Adding non-codec 0x%x (%s) to SDP\n", format, ast_rtp_lookup_mime_subtype(0, format, 0));
10010 if ((rtp_code = ast_rtp_lookup_code(p->rtp, 0, format)) == -1)
10011 return;
10012
10013 ast_str_append(m_buf, 0, " %d", rtp_code);
10014 ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
10015 ast_rtp_lookup_mime_subtype(0, format, 0),
10016 ast_rtp_lookup_sample_rate(0, format));
10017 if (format == AST_RTP_DTMF)
10018 ast_str_append(a_buf, 0, "a=fmtp:%d 0-16\r\n", rtp_code);
10019 }
10020
10021
10022
10023
10024 static void get_our_media_address(struct sip_pvt *p, int needvideo,
10025 struct sockaddr_in *sin, struct sockaddr_in *vsin, struct sockaddr_in *tsin,
10026 struct sockaddr_in *dest, struct sockaddr_in *vdest)
10027 {
10028
10029 ast_rtp_get_us(p->rtp, sin);
10030 if (p->vrtp)
10031 ast_rtp_get_us(p->vrtp, vsin);
10032 if (p->trtp)
10033 ast_rtp_get_us(p->trtp, tsin);
10034
10035
10036
10037 if (p->redirip.sin_addr.s_addr) {
10038 dest->sin_port = p->redirip.sin_port;
10039 dest->sin_addr = p->redirip.sin_addr;
10040 } else {
10041 dest->sin_addr = p->ourip.sin_addr;
10042 dest->sin_port = sin->sin_port;
10043 }
10044 if (needvideo) {
10045
10046 if (p->vredirip.sin_addr.s_addr) {
10047 vdest->sin_addr = p->vredirip.sin_addr;
10048 vdest->sin_port = p->vredirip.sin_port;
10049 } else {
10050 vdest->sin_addr = p->ourip.sin_addr;
10051 vdest->sin_port = vsin->sin_port;
10052 }
10053 }
10054
10055 }
10056
10057
10058
10059
10060
10061
10062
10063 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38)
10064 {
10065 int len = 0;
10066 int alreadysent = 0;
10067
10068 struct sockaddr_in sin;
10069 struct sockaddr_in vsin;
10070 struct sockaddr_in tsin;
10071 struct sockaddr_in dest;
10072 struct sockaddr_in udptlsin;
10073 struct sockaddr_in vdest = { 0, };
10074 struct sockaddr_in tdest = { 0, };
10075 struct sockaddr_in udptldest = { 0, };
10076
10077
10078 char *version = "v=0\r\n";
10079 char subject[256];
10080 char owner[256];
10081 char connection[256];
10082 char *session_time = "t=0 0\r\n";
10083 char bandwidth[256] = "";
10084 char *hold = "";
10085 struct ast_str *m_audio = ast_str_alloca(256);
10086 struct ast_str *m_video = ast_str_alloca(256);
10087 struct ast_str *m_text = ast_str_alloca(256);
10088 struct ast_str *m_modem = ast_str_alloca(256);
10089 struct ast_str *a_audio = ast_str_alloca(1024);
10090 struct ast_str *a_video = ast_str_alloca(1024);
10091 struct ast_str *a_text = ast_str_alloca(1024);
10092 struct ast_str *a_modem = ast_str_alloca(1024);
10093
10094 int x;
10095 int capability = 0;
10096 int needaudio = FALSE;
10097 int needvideo = FALSE;
10098 int needtext = FALSE;
10099 int debug = sip_debug_test_pvt(p);
10100 int min_audio_packet_size = 0;
10101 int min_video_packet_size = 0;
10102 int min_text_packet_size = 0;
10103
10104 char codecbuf[SIPBUFSIZE];
10105 char buf[SIPBUFSIZE];
10106 char dummy_answer[256];
10107
10108
10109 snprintf(subject, sizeof(subject), "s=%s\r\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
10110
10111 if (!p->rtp) {
10112 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
10113 return AST_FAILURE;
10114 }
10115
10116
10117
10118
10119 if (!p->sessionid) {
10120 p->sessionid = (int)ast_random();
10121 p->sessionversion = p->sessionid;
10122 } else {
10123 if (oldsdp == FALSE)
10124 p->sessionversion++;
10125 }
10126
10127 if (add_audio) {
10128
10129 if ((p->jointcapability & AST_FORMAT_VIDEO_MASK) && !p->novideo) {
10130 if (p->vrtp) {
10131 needvideo = TRUE;
10132 ast_debug(2, "This call needs video offers!\n");
10133 } else
10134 ast_debug(2, "This call needs video offers, but there's no video support enabled!\n");
10135 }
10136
10137 if ((p->jointcapability & AST_FORMAT_TEXT_MASK) && !p->notext) {
10138 if (sipdebug_text)
10139 ast_verbose("We think we can do text\n");
10140 if (p->trtp) {
10141 if (sipdebug_text) {
10142 ast_verbose("And we have a text rtp object\n");
10143 }
10144 needtext = TRUE;
10145 ast_debug(2, "This call needs text offers! \n");
10146 } else {
10147 ast_debug(2, "This call needs text offers, but there's no text support enabled ! \n");
10148 }
10149 }
10150 }
10151
10152 get_our_media_address(p, needvideo, &sin, &vsin, &tsin, &dest, &vdest);
10153
10154 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));
10155 snprintf(connection, sizeof(connection), "c=IN IP4 %s\r\n", ast_inet_ntoa(dest.sin_addr));
10156
10157 if (add_audio) {
10158 capability = p->jointcapability;
10159
10160
10161 ast_debug(1, "** Our capability: %s Video flag: %s Text flag: %s\n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), capability),
10162 p->novideo ? "True" : "False", p->notext ? "True" : "False");
10163 ast_debug(1, "** Our prefcodec: %s \n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), p->prefcodec));
10164
10165
10166 if (capability & AST_FORMAT_AUDIO_MASK)
10167 needaudio = TRUE;
10168
10169 if (debug)
10170 ast_verbose("Audio is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(sin.sin_port));
10171
10172
10173
10174 if (needvideo) {
10175 ast_str_append(&m_video, 0, "m=video %d RTP/AVP", ntohs(vdest.sin_port));
10176
10177
10178 if (p->maxcallbitrate)
10179 snprintf(bandwidth, sizeof(bandwidth), "b=CT:%d\r\n", p->maxcallbitrate);
10180 if (debug)
10181 ast_verbose("Video is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(vdest.sin_port));
10182 }
10183
10184
10185
10186 if (needtext) {
10187 if (sipdebug_text)
10188 ast_verbose("Lets set up the text sdp\n");
10189
10190 if (p->tredirip.sin_addr.s_addr) {
10191 tdest.sin_addr = p->tredirip.sin_addr;
10192 tdest.sin_port = p->tredirip.sin_port;
10193 } else {
10194 tdest.sin_addr = p->ourip.sin_addr;
10195 tdest.sin_port = tsin.sin_port;
10196 }
10197 ast_str_append(&m_text, 0, "m=text %d RTP/AVP", ntohs(tdest.sin_port));
10198 if (debug)
10199 ast_verbose("Text is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(tsin.sin_port));
10200
10201 }
10202
10203
10204
10205
10206
10207
10208 ast_str_append(&m_audio, 0, "m=audio %d RTP/AVP", ntohs(dest.sin_port));
10209
10210 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_ONEDIR)
10211 hold = "a=recvonly\r\n";
10212 else if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_INACTIVE)
10213 hold = "a=inactive\r\n";
10214 else
10215 hold = "a=sendrecv\r\n";
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226 if (capability & p->prefcodec) {
10227 int codec = p->prefcodec & AST_FORMAT_AUDIO_MASK;
10228
10229 add_codec_to_sdp(p, codec, &m_audio, &a_audio, debug, &min_audio_packet_size);
10230 alreadysent |= codec;
10231 }
10232
10233
10234 for (x = 0; x < 32; x++) {
10235 int codec;
10236
10237 if (!(codec = ast_codec_pref_index(&p->prefs, x)))
10238 break;
10239
10240 if (!(capability & codec))
10241 continue;
10242
10243 if (alreadysent & codec)
10244 continue;
10245
10246 add_codec_to_sdp(p, codec, &m_audio, &a_audio, debug, &min_audio_packet_size);
10247 alreadysent |= codec;
10248 }
10249
10250
10251 for (x = 1; x <= (needtext ? AST_FORMAT_TEXT_MASK : (needvideo ? AST_FORMAT_VIDEO_MASK : AST_FORMAT_AUDIO_MASK)); x <<= 1) {
10252 if (!(capability & x))
10253 continue;
10254
10255 if (alreadysent & x)
10256 continue;
10257
10258 if (x & AST_FORMAT_AUDIO_MASK)
10259 add_codec_to_sdp(p, x, &m_audio, &a_audio, debug, &min_audio_packet_size);
10260 else if (x & AST_FORMAT_VIDEO_MASK)
10261 add_vcodec_to_sdp(p, x, &m_video, &a_video, debug, &min_video_packet_size);
10262 else if (x & AST_FORMAT_TEXT_MASK)
10263 add_tcodec_to_sdp(p, x, &m_text, &a_text, debug, &min_text_packet_size);
10264 }
10265
10266
10267 for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
10268 if (!(p->jointnoncodeccapability & x))
10269 continue;
10270
10271 add_noncodec_to_sdp(p, x, &m_audio, &a_audio, debug);
10272 }
10273
10274 ast_debug(3, "-- Done with adding codecs to SDP\n");
10275
10276 if (!p->owner || !ast_internal_timing_enabled(p->owner))
10277 ast_str_append(&a_audio, 0, "a=silenceSupp:off - - - -\r\n");
10278
10279 if (min_audio_packet_size)
10280 ast_str_append(&a_audio, 0, "a=ptime:%d\r\n", min_audio_packet_size);
10281
10282
10283 if (min_video_packet_size)
10284 ast_str_append(&a_video, 0, "a=ptime:%d\r\n", min_video_packet_size);
10285
10286
10287 if (min_text_packet_size)
10288 ast_str_append(&a_text, 0, "a=ptime:%d\r\n", min_text_packet_size);
10289
10290 if (m_audio->len - m_audio->used < 2 || m_video->len - m_video->used < 2 ||
10291 m_text->len - m_text->used < 2 || a_text->len - a_text->used < 2 ||
10292 a_audio->len - a_audio->used < 2 || a_video->len - a_video->used < 2)
10293 ast_log(LOG_WARNING, "SIP SDP may be truncated due to undersized buffer!!\n");
10294 }
10295
10296 if (add_t38) {
10297
10298 ast_udptl_get_us(p->udptl, &udptlsin);
10299
10300
10301 if (p->udptlredirip.sin_addr.s_addr) {
10302 udptldest.sin_port = p->udptlredirip.sin_port;
10303 udptldest.sin_addr = p->udptlredirip.sin_addr;
10304 } else {
10305 udptldest.sin_addr = p->ourip.sin_addr;
10306 udptldest.sin_port = udptlsin.sin_port;
10307 }
10308
10309 if (debug)
10310 ast_debug(1, "T.38 UDPTL is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(udptlsin.sin_port));
10311
10312
10313
10314
10315 ast_str_append(&m_modem, 0, "m=image %d udptl t38\r\n", ntohs(udptldest.sin_port));
10316
10317 ast_str_append(&a_modem, 0, "a=T38FaxVersion:%d\r\n", p->t38.our_parms.version);
10318 ast_str_append(&a_modem, 0, "a=T38MaxBitRate:%d\r\n", t38_get_rate(p->t38.our_parms.rate));
10319 if (p->t38.our_parms.fill_bit_removal) {
10320 ast_str_append(&a_modem, 0, "a=T38FaxFillBitRemoval\r\n");
10321 }
10322 if (p->t38.our_parms.transcoding_mmr) {
10323 ast_str_append(&a_modem, 0, "a=T38FaxTranscodingMMR\r\n");
10324 }
10325 if (p->t38.our_parms.transcoding_jbig) {
10326 ast_str_append(&a_modem, 0, "a=T38FaxTranscodingJBIG\r\n");
10327 }
10328 switch (p->t38.our_parms.rate_management) {
10329 case AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF:
10330 ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:transferredTCF\r\n");
10331 break;
10332 case AST_T38_RATE_MANAGEMENT_LOCAL_TCF:
10333 ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:localTCF\r\n");
10334 break;
10335 }
10336 ast_str_append(&a_modem, 0, "a=T38FaxMaxDatagram:%u\r\n", ast_udptl_get_local_max_datagram(p->udptl));
10337 switch (ast_udptl_get_error_correction_scheme(p->udptl)) {
10338 case UDPTL_ERROR_CORRECTION_NONE:
10339 break;
10340 case UDPTL_ERROR_CORRECTION_FEC:
10341 ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPFEC\r\n");
10342 break;
10343 case UDPTL_ERROR_CORRECTION_REDUNDANCY:
10344 ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPRedundancy\r\n");
10345 break;
10346 }
10347 }
10348
10349 if (needaudio)
10350 ast_str_append(&m_audio, 0, "\r\n");
10351 if (needvideo)
10352 ast_str_append(&m_video, 0, "\r\n");
10353 if (needtext)
10354 ast_str_append(&m_text, 0, "\r\n");
10355
10356 len = strlen(version) + strlen(subject) + strlen(owner) +
10357 strlen(connection) + strlen(session_time);
10358 if (needaudio)
10359 len += m_audio->used + a_audio->used + strlen(hold);
10360 if (needvideo)
10361 len += m_video->used + a_video->used + strlen(bandwidth) + strlen(hold);
10362 if (needtext)
10363 len += m_text->used + a_text->used + strlen(hold);
10364 if (add_t38)
10365 len += m_modem->used + a_modem->used;
10366
10367 add_header(resp, "Content-Type", "application/sdp");
10368 add_header_contentLength(resp, len);
10369 add_line(resp, version);
10370 add_line(resp, owner);
10371 add_line(resp, subject);
10372 add_line(resp, connection);
10373 if (needvideo)
10374 add_line(resp, bandwidth);
10375 add_line(resp, session_time);
10376 if (needaudio) {
10377 add_line(resp, m_audio->str);
10378 add_line(resp, a_audio->str);
10379 add_line(resp, hold);
10380 } else if (p->offered_media[SDP_AUDIO].offered) {
10381 snprintf(dummy_answer, sizeof(dummy_answer), "m=audio 0 RTP/AVP %s\r\n", p->offered_media[SDP_AUDIO].text);
10382 add_line(resp, dummy_answer);
10383 }
10384 if (needvideo) {
10385 add_line(resp, m_video->str);
10386 add_line(resp, a_video->str);
10387 add_line(resp, hold);
10388 } else if (p->offered_media[SDP_VIDEO].offered) {
10389 snprintf(dummy_answer, sizeof(dummy_answer), "m=video 0 RTP/AVP %s\r\n", p->offered_media[SDP_VIDEO].text);
10390 add_line(resp, dummy_answer);
10391 }
10392 if (needtext) {
10393 add_line(resp, m_text->str);
10394 add_line(resp, a_text->str);
10395 add_line(resp, hold);
10396 } else if (p->offered_media[SDP_TEXT].offered) {
10397 snprintf(dummy_answer, sizeof(dummy_answer), "m=text 0 RTP/AVP %s\r\n", p->offered_media[SDP_TEXT].text);
10398 add_line(resp, dummy_answer);
10399 }
10400 if (add_t38) {
10401 add_line(resp, m_modem->str);
10402 add_line(resp, a_modem->str);
10403 } else if (p->offered_media[SDP_IMAGE].offered) {
10404 add_line(resp, "m=image 0 udptl t38\r\n");
10405 }
10406
10407
10408 p->lastrtprx = p->lastrtptx = time(NULL);
10409
10410 ast_debug(3, "Done building SDP. Settling with this capability: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, capability));
10411
10412 return AST_SUCCESS;
10413 }
10414
10415
10416 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
10417 {
10418 struct sip_request resp;
10419 int seqno;
10420
10421 if (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1) {
10422 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
10423 return -1;
10424 }
10425 respprep(&resp, p, msg, req);
10426 if (p->udptl) {
10427 add_sdp(&resp, p, 0, 0, 1);
10428 } else
10429 ast_log(LOG_ERROR, "Can't add SDP to response, since we have no UDPTL session allocated. Call-ID %s\n", p->callid);
10430 if (retrans && !p->pendinginvite)
10431 p->pendinginvite = seqno;
10432 return send_response(p, &resp, retrans, seqno);
10433 }
10434
10435
10436 static void copy_request(struct sip_request *dst, const struct sip_request *src)
10437 {
10438 struct ast_str *duplicate = dst->data;
10439
10440
10441 memcpy(dst, src, sizeof(*dst));
10442 dst->data = duplicate;
10443
10444
10445
10446
10447
10448
10449
10450 if (!dst->data && !(dst->data = ast_str_create(src->data->used + 1)))
10451 return;
10452 else if (dst->data->len < src->data->used + 1)
10453 ast_str_make_space(&dst->data, src->data->used + 1);
10454
10455 memcpy(dst->data->str, src->data->str, src->data->used + 1);
10456 dst->data->used = src->data->used;
10457 }
10458
10459
10460
10461
10462 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable, int oldsdp)
10463 {
10464 struct sip_request resp;
10465 int seqno;
10466 if (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1) {
10467 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
10468 return -1;
10469 }
10470 respprep(&resp, p, msg, req);
10471 if (p->rtp) {
10472 if (!p->autoframing && !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
10473 ast_debug(1, "Setting framing from config on incoming call\n");
10474 ast_rtp_codec_setpref(p->rtp, &p->prefs);
10475 }
10476 try_suggested_sip_codec(p);
10477 if (p->t38.state == T38_ENABLED) {
10478 add_sdp(&resp, p, oldsdp, TRUE, TRUE);
10479 } else {
10480 add_sdp(&resp, p, oldsdp, TRUE, FALSE);
10481 }
10482 } else
10483 ast_log(LOG_ERROR, "Can't add SDP to response, since we have no RTP session allocated. Call-ID %s\n", p->callid);
10484 if (reliable && !p->pendinginvite)
10485 p->pendinginvite = seqno;
10486 return send_response(p, &resp, reliable, seqno);
10487 }
10488
10489
10490 static int determine_firstline_parts(struct sip_request *req)
10491 {
10492 char *e = ast_skip_blanks(req->data->str);
10493 char *local_rlPart1;
10494
10495 if (!*e)
10496 return -1;
10497 req->rlPart1 = e - req->data->str;
10498 local_rlPart1 = e;
10499 e = ast_skip_nonblanks(e);
10500 if (*e)
10501 *e++ = '\0';
10502
10503 e = ast_skip_blanks(e);
10504 if ( !*e )
10505 return -1;
10506 ast_trim_blanks(e);
10507
10508 if (!strcasecmp(local_rlPart1, "SIP/2.0") ) {
10509 if (strlen(e) < 3)
10510 return -1;
10511 req->rlPart2 = e - req->data->str;
10512 } else {
10513 if ( *e == '<' ) {
10514 ast_debug(3, "Oops. Bogus uri in <> %s\n", e);
10515 e++;
10516 if (!*e)
10517 return -1;
10518 }
10519 req->rlPart2 = e - req->data->str;
10520 e = ast_skip_nonblanks(e);
10521 if (*e)
10522 *e++ = '\0';
10523 e = ast_skip_blanks(e);
10524 if (strcasecmp(e, "SIP/2.0") ) {
10525 ast_debug(3, "Skipping packet - Bad request protocol %s\n", e);
10526 return -1;
10527 }
10528 }
10529 return 1;
10530 }
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp)
10546 {
10547 struct sip_request req;
10548
10549 reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ? SIP_UPDATE : SIP_INVITE, 0, 1);
10550
10551 add_header(&req, "Allow", ALLOWED_METHODS);
10552 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
10553 if (sipdebug) {
10554 if (oldsdp == TRUE)
10555 add_header(&req, "X-asterisk-Info", "SIP re-invite (Session-Timers)");
10556 else
10557 add_header(&req, "X-asterisk-Info", "SIP re-invite (External RTP bridge)");
10558 }
10559
10560 if (p->do_history)
10561 append_history(p, "ReInv", "Re-invite sent");
10562 memset(p->offered_media, 0, sizeof(p->offered_media));
10563
10564 if (t38version)
10565 add_sdp(&req, p, oldsdp, FALSE, TRUE);
10566 else
10567 add_sdp(&req, p, oldsdp, TRUE, FALSE);
10568
10569
10570 initialize_initreq(p, &req);
10571 p->lastinvite = p->ocseq;
10572 ast_set_flag(&p->flags[0], SIP_OUTGOING);
10573
10574 return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
10575 }
10576
10577
10578 static char *remove_uri_parameters(char *uri)
10579 {
10580 char *atsign;
10581 atsign = strchr(uri, '@');
10582 if (!atsign)
10583 atsign = uri;
10584 atsign = strchr(atsign, ';');
10585 if (atsign)
10586 *atsign = '\0';
10587 return uri;
10588 }
10589
10590
10591 static void extract_uri(struct sip_pvt *p, struct sip_request *req)
10592 {
10593 char stripped[SIPBUFSIZE];
10594 char *c;
10595
10596 ast_copy_string(stripped, get_header(req, "Contact"), sizeof(stripped));
10597 c = get_in_brackets(stripped);
10598
10599 c = remove_uri_parameters(c);
10600 if (!ast_strlen_zero(c))
10601 ast_string_field_set(p, uri, c);
10602
10603 }
10604
10605
10606 static void build_contact(struct sip_pvt *p)
10607 {
10608
10609 int ourport = ntohs(p->ourip.sin_port);
10610
10611 if (!sip_standard_port(p->socket.type, ourport)) {
10612 if (p->socket.type == SIP_TRANSPORT_UDP)
10613 ast_string_field_build(p, our_contact, "<sip:%s%s%s:%d>", p->exten, ast_strlen_zero(p->exten) ? "" : "@", ast_inet_ntoa(p->ourip.sin_addr), ourport);
10614 else
10615 ast_string_field_build(p, our_contact, "<sip:%s%s%s:%d;transport=%s>", p->exten, ast_strlen_zero(p->exten) ? "" : "@", ast_inet_ntoa(p->ourip.sin_addr), ourport, get_transport(p->socket.type));
10616 } else {
10617 if (p->socket.type == SIP_TRANSPORT_UDP)
10618 ast_string_field_build(p, our_contact, "<sip:%s%s%s>", p->exten, ast_strlen_zero(p->exten) ? "" : "@", ast_inet_ntoa(p->ourip.sin_addr));
10619 else
10620 ast_string_field_build(p, our_contact, "<sip:%s%s%s;transport=%s>", p->exten, ast_strlen_zero(p->exten) ? "" : "@", ast_inet_ntoa(p->ourip.sin_addr), get_transport(p->socket.type));
10621 }
10622 }
10623
10624
10625 static void build_rpid(struct sip_pvt *p)
10626 {
10627 int send_pres_tags = TRUE;
10628 const char *privacy=NULL;
10629 const char *screen=NULL;
10630 char buf[256];
10631 const char *clid = default_callerid;
10632 const char *clin = NULL;
10633 const char *fromdomain;
10634
10635 if (!ast_strlen_zero(p->rpid) || !ast_strlen_zero(p->rpid_from))
10636 return;
10637
10638 if (p->owner && !ast_strlen_zero(p->owner->cid.cid_num))
10639 clid = p->owner->cid.cid_num;
10640 if (p->owner && p->owner->cid.cid_name)
10641 clin = p->owner->cid.cid_name;
10642 if (ast_strlen_zero(clin))
10643 clin = clid;
10644
10645 switch (p->callingpres) {
10646 case AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED:
10647 privacy = "off";
10648 screen = "no";
10649 break;
10650 case AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN:
10651 privacy = "off";
10652 screen = "yes";
10653 break;
10654 case AST_PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN:
10655 privacy = "off";
10656 screen = "no";
10657 break;
10658 case AST_PRES_ALLOWED_NETWORK_NUMBER:
10659 privacy = "off";
10660 screen = "yes";
10661 break;
10662 case AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED:
10663 privacy = "full";
10664 screen = "no";
10665 break;
10666 case AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN:
10667 privacy = "full";
10668 screen = "yes";
10669 break;
10670 case AST_PRES_PROHIB_USER_NUMBER_FAILED_SCREEN:
10671 privacy = "full";
10672 screen = "no";
10673 break;
10674 case AST_PRES_PROHIB_NETWORK_NUMBER:
10675 privacy = "full";
10676 screen = "yes";
10677 break;
10678 case AST_PRES_NUMBER_NOT_AVAILABLE:
10679 send_pres_tags = FALSE;
10680 break;
10681 default:
10682 ast_log(LOG_WARNING, "Unsupported callingpres (%d)\n", p->callingpres);
10683 if ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)
10684 privacy = "full";
10685 else
10686 privacy = "off";
10687 screen = "no";
10688 break;
10689 }
10690
10691 fromdomain = S_OR(p->fromdomain, ast_inet_ntoa(p->ourip.sin_addr));
10692
10693 snprintf(buf, sizeof(buf), "\"%s\" <sip:%s@%s>", clin, clid, fromdomain);
10694 if (send_pres_tags)
10695 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ";privacy=%s;screen=%s", privacy, screen);
10696 ast_string_field_set(p, rpid, buf);
10697
10698 ast_string_field_build(p, rpid_from, "\"%s\" <sip:%s@%s>;tag=%s", clin,
10699 S_OR(p->fromuser, clid),
10700 fromdomain, p->tag);
10701 }
10702
10703
10704 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod)
10705 {
10706 struct ast_str *invite = ast_str_alloca(256);
10707 char from[256];
10708 char to[256];
10709 char tmp_n[SIPBUFSIZE/2];
10710 char tmp_l[SIPBUFSIZE/2];
10711 const char *l = NULL;
10712 const char *n = NULL;
10713 const char *d = NULL;
10714 const char *urioptions = "";
10715 int ourport;
10716
10717 if (ast_test_flag(&p->flags[0], SIP_USEREQPHONE)) {
10718 const char *s = p->username;
10719
10720
10721
10722
10723
10724
10725 if (*s == '+')
10726 s++;
10727 for (; *s; s++) {
10728 if (!strchr(AST_DIGIT_ANYNUM, *s) )
10729 break;
10730 }
10731
10732 if (!*s)
10733 urioptions = ";user=phone";
10734 }
10735
10736
10737 snprintf(p->lastmsg, sizeof(p->lastmsg), "Init: %s", sip_methods[sipmethod].text);
10738
10739 d = S_OR(p->fromdomain, ast_inet_ntoa(p->ourip.sin_addr));
10740 if (p->owner) {
10741 l = p->owner->cid.cid_num;
10742 n = p->owner->cid.cid_name;
10743 }
10744
10745 if (!ast_test_flag(&p->flags[0], SIP_SENDRPID) &&
10746 ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)) {
10747 l = CALLERID_UNKNOWN;
10748 n = l;
10749 d = FROMDOMAIN_INVALID;
10750 }
10751 if (ast_strlen_zero(l))
10752 l = default_callerid;
10753 if (ast_strlen_zero(n))
10754 n = l;
10755
10756 if (!ast_strlen_zero(p->fromuser))
10757 l = p->fromuser;
10758 else
10759 ast_string_field_set(p, fromuser, l);
10760
10761
10762 if (!ast_strlen_zero(p->fromname))
10763 n = p->fromname;
10764 else
10765 ast_string_field_set(p, fromname, n);
10766
10767 if (sip_cfg.pedanticsipchecking) {
10768 ast_uri_encode(n, tmp_n, sizeof(tmp_n), 0);
10769 n = tmp_n;
10770 ast_uri_encode(l, tmp_l, sizeof(tmp_l), 0);
10771 l = tmp_l;
10772 }
10773
10774 ourport = ntohs(p->ourip.sin_port);
10775 if (!sip_standard_port(p->socket.type, ourport) && ast_strlen_zero(p->fromdomain))
10776 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s:%d>;tag=%s", n, l, d, ourport, p->tag);
10777 else
10778 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=%s", n, l, d, p->tag);
10779
10780
10781 if (!ast_strlen_zero(p->fullcontact)) {
10782
10783 ast_str_append(&invite, 0, "%s", p->fullcontact);
10784 } else {
10785
10786 ast_str_append(&invite, 0, "sip:");
10787 if (!ast_strlen_zero(p->username)) {
10788 n = p->username;
10789 if (sip_cfg.pedanticsipchecking) {
10790 ast_uri_encode(n, tmp_n, sizeof(tmp_n), 0);
10791 n = tmp_n;
10792 }
10793 ast_str_append(&invite, 0, "%s@", n);
10794 }
10795 ast_str_append(&invite, 0, "%s", p->tohost);
10796 if (p->portinuri)
10797 ast_str_append(&invite, 0, ":%d", ntohs(p->sa.sin_port));
10798 ast_str_append(&invite, 0, "%s", urioptions);
10799 }
10800
10801
10802 if (p->options && !ast_strlen_zero(p->options->uri_options))
10803 ast_str_append(&invite, 0, ";%s", p->options->uri_options);
10804
10805
10806
10807
10808 ast_string_field_set(p, uri, invite->str);
10809
10810 if (!ast_strlen_zero(p->todnid)) {
10811
10812 if (!strchr(p->todnid, '@')) {
10813
10814 snprintf(to, sizeof(to), "<sip:%s@%s>%s%s", p->todnid, p->tohost, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
10815 } else {
10816 snprintf(to, sizeof(to), "<sip:%s>%s%s", p->todnid, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
10817 }
10818 } else {
10819 if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->theirtag)) {
10820
10821 snprintf(to, sizeof(to), "<%s%s>;tag=%s", (strncasecmp(p->uri, "sip:", 4) ? "sip:" : ""), p->uri, p->theirtag);
10822 } else if (p->options && p->options->vxml_url) {
10823
10824 snprintf(to, sizeof(to), "<%s>;%s", p->uri, p->options->vxml_url);
10825 } else
10826 snprintf(to, sizeof(to), "<%s>", p->uri);
10827 }
10828
10829 init_req(req, sipmethod, p->uri);
10830
10831 snprintf(tmp_n, sizeof(tmp_n), "%d %s", ++p->ocseq, sip_methods[sipmethod].text);
10832
10833 add_header(req, "Via", p->via);
10834 add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
10835
10836
10837
10838
10839 add_route(req, p->route);
10840
10841
10842 if (ast_test_flag(&p->flags[0], SIP_SENDRPID) && (sipmethod == SIP_INVITE)) {
10843 build_rpid(p);
10844 add_header(req, "From", p->rpid_from);
10845 } else
10846 add_header(req, "From", from);
10847 add_header(req, "To", to);
10848 ast_string_field_set(p, exten, l);
10849 build_contact(p);
10850 add_header(req, "Contact", p->our_contact);
10851 add_header(req, "Call-ID", p->callid);
10852 add_header(req, "CSeq", tmp_n);
10853 if (!ast_strlen_zero(global_useragent))
10854 add_header(req, "User-Agent", global_useragent);
10855 if (!ast_strlen_zero(p->rpid))
10856 add_header(req, "Remote-Party-ID", p->rpid);
10857 }
10858
10859
10860
10861
10862
10863
10864
10865
10866 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init)
10867 {
10868 struct sip_request req;
10869 struct ast_variable *var;
10870
10871 req.method = sipmethod;
10872 if (init) {
10873 p->branch ^= ast_random();
10874 p->invite_branch = p->branch;
10875 build_via(p);
10876 }
10877 if (init > 1)
10878 initreqprep(&req, p, sipmethod);
10879 else
10880
10881 reqprep(&req, p, sipmethod, 0, init ? 0 : 1);
10882
10883 if (p->options && p->options->auth)
10884 add_header(&req, p->options->authheader, p->options->auth);
10885 append_date(&req);
10886 if (sipmethod == SIP_REFER) {
10887 if (p->refer) {
10888 char buf[SIPBUFSIZE];
10889 if (!ast_strlen_zero(p->refer->refer_to))
10890 add_header(&req, "Refer-To", p->refer->refer_to);
10891 if (!ast_strlen_zero(p->refer->referred_by)) {
10892 snprintf(buf, sizeof(buf), "%s <%s>", p->refer->referred_by_name, p->refer->referred_by);
10893 add_header(&req, "Referred-By", buf);
10894 }
10895 }
10896 } else if (sipmethod == SIP_SUBSCRIBE) {
10897 char buf[SIPBUFSIZE];
10898
10899 add_header(&req, "Event", "message-summary");
10900 add_header(&req, "Accept", "application/simple-message-summary");
10901 snprintf(buf, sizeof(buf), "%d", mwi_expiry);
10902 add_header(&req, "Expires", buf);
10903 }
10904
10905
10906
10907 if (p->options && !ast_strlen_zero(p->options->replaces)) {
10908 add_header(&req, "Replaces", p->options->replaces);
10909 add_header(&req, "Require", "replaces");
10910 }
10911
10912
10913 if (st_get_mode(p) == SESSION_TIMER_MODE_ORIGINATE) {
10914 char i2astr[10];
10915
10916 if (!p->stimer->st_interval)
10917 p->stimer->st_interval = st_get_se(p, TRUE);
10918
10919 p->stimer->st_active = TRUE;
10920
10921 snprintf(i2astr, sizeof(i2astr), "%d", p->stimer->st_interval);
10922 add_header(&req, "Session-Expires", i2astr);
10923 snprintf(i2astr, sizeof(i2astr), "%d", st_get_se(p, FALSE));
10924 add_header(&req, "Min-SE", i2astr);
10925 }
10926
10927 add_header(&req, "Allow", ALLOWED_METHODS);
10928 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
10929
10930 if(p->notify_headers) {
10931 char buf[512];
10932 for (var = p->notify_headers; var; var = var->next) {
10933 ast_copy_string(buf, var->value, sizeof(buf));
10934 add_header(&req, var->name, ast_unescape_semicolon(buf));
10935 }
10936 }
10937 if (p->options && p->options->addsipheaders && p->owner) {
10938 struct ast_channel *chan = p->owner;
10939 struct varshead *headp;
10940
10941 ast_channel_lock(chan);
10942
10943 headp = &chan->varshead;
10944
10945 if (!headp)
10946 ast_log(LOG_WARNING, "No Headp for the channel...ooops!\n");
10947 else {
10948 const struct ast_var_t *current;
10949 AST_LIST_TRAVERSE(headp, current, entries) {
10950
10951 if (!strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
10952 char *content, *end;
10953 const char *header = ast_var_value(current);
10954 char *headdup = ast_strdupa(header);
10955
10956
10957 if (*headdup == '"')
10958 headdup++;
10959 if ((content = strchr(headdup, ':'))) {
10960 *content++ = '\0';
10961 content = ast_skip_blanks(content);
10962
10963 end = content + strlen(content) -1;
10964 if (*end == '"')
10965 *end = '\0';
10966
10967 add_header(&req, headdup, content);
10968 if (sipdebug)
10969 ast_debug(1, "Adding SIP Header \"%s\" with content :%s: \n", headdup, content);
10970 }
10971 }
10972 }
10973 }
10974
10975 ast_channel_unlock(chan);
10976 }
10977 if (sdp) {
10978 memset(p->offered_media, 0, sizeof(p->offered_media));
10979 if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
10980 ast_debug(1, "T38 is in state %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
10981 add_sdp(&req, p, FALSE, FALSE, TRUE);
10982 } else if (p->rtp)
10983 add_sdp(&req, p, FALSE, TRUE, FALSE);
10984 } else {
10985 if (!p->notify_headers) {
10986 add_header_contentLength(&req, 0);
10987 }
10988 }
10989
10990 if (!p->initreq.headers || init > 2)
10991 initialize_initreq(p, &req);
10992 p->lastinvite = p->ocseq;
10993 return send_request(p, &req, init ? XMIT_CRITICAL : XMIT_RELIABLE, p->ocseq);
10994 }
10995
10996
10997 static int sip_subscribe_mwi_do(const void *data)
10998 {
10999 struct sip_subscription_mwi *mwi = (struct sip_subscription_mwi*)data;
11000
11001 if (!mwi) {
11002 return -1;
11003 }
11004
11005 mwi->resub = -1;
11006 __sip_subscribe_mwi_do(mwi);
11007 ASTOBJ_UNREF(mwi, sip_subscribe_mwi_destroy);
11008
11009 return 0;
11010 }
11011
11012
11013 static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi)
11014 {
11015
11016 if (!mwi->dnsmgr) {
11017 char transport[MAXHOSTNAMELEN];
11018 snprintf(transport, sizeof(transport), "_sip._%s", get_transport(mwi->transport));
11019 ast_dnsmgr_lookup(mwi->hostname, &mwi->us, &mwi->dnsmgr, sip_cfg.srvlookup ? transport : NULL);
11020 }
11021
11022
11023 if (mwi->call) {
11024 transmit_invite(mwi->call, SIP_SUBSCRIBE, 0, 0);
11025 return 0;
11026 }
11027
11028
11029 if (!(mwi->call = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL))) {
11030 return -1;
11031 }
11032
11033 ref_proxy(mwi->call, obproxy_get(mwi->call, NULL));
11034
11035 if (!mwi->us.sin_port && mwi->portno) {
11036 mwi->us.sin_port = htons(mwi->portno);
11037 }
11038
11039
11040 if (create_addr(mwi->call, mwi->hostname, &mwi->us, 0)) {
11041 dialog_unlink_all(mwi->call, TRUE, TRUE);
11042 mwi->call = dialog_unref(mwi->call, "unref dialog after unlink_all");
11043 return 0;
11044 }
11045
11046 if (!mwi->dnsmgr && mwi->portno) {
11047 mwi->call->sa.sin_port = htons(mwi->portno);
11048 mwi->call->recv.sin_port = htons(mwi->portno);
11049 } else {
11050 mwi->portno = ntohs(mwi->call->sa.sin_port);
11051 }
11052
11053
11054 if (!ast_strlen_zero(mwi->authuser)) {
11055 ast_string_field_set(mwi->call, peername, mwi->authuser);
11056 ast_string_field_set(mwi->call, authname, mwi->authuser);
11057 ast_string_field_set(mwi->call, fromuser, mwi->authuser);
11058 } else {
11059 ast_string_field_set(mwi->call, peername, mwi->username);
11060 ast_string_field_set(mwi->call, authname, mwi->username);
11061 ast_string_field_set(mwi->call, fromuser, mwi->username);
11062 }
11063 ast_string_field_set(mwi->call, username, mwi->username);
11064 if (!ast_strlen_zero(mwi->secret)) {
11065 ast_string_field_set(mwi->call, peersecret, mwi->secret);
11066 }
11067 set_socket_transport(&mwi->call->socket, mwi->transport);
11068 mwi->call->socket.port = htons(mwi->portno);
11069 ast_sip_ouraddrfor(&mwi->call->sa.sin_addr, &mwi->call->ourip, mwi->call);
11070 build_contact(mwi->call);
11071 build_via(mwi->call);
11072 build_callid_pvt(mwi->call);
11073 ast_set_flag(&mwi->call->flags[0], SIP_OUTGOING);
11074
11075
11076 mwi->call->mwi = ASTOBJ_REF(mwi);
11077
11078
11079 transmit_invite(mwi->call, SIP_SUBSCRIBE, 0, 2);
11080
11081 return 0;
11082 }
11083
11084 static int find_calling_channel(struct ast_channel *c, void *data) {
11085 struct sip_pvt *p = data;
11086
11087 return (c->pbx &&
11088 (!strcasecmp(c->macroexten, p->exten) || !strcasecmp(c->exten, p->exten)) &&
11089 (sip_cfg.notifycid == IGNORE_CONTEXT || !strcasecmp(c->context, p->context)));
11090 }
11091
11092
11093 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout)
11094 {
11095 struct ast_str *tmp = ast_str_alloca(4000);
11096 char from[256], to[256];
11097 char *c, *mfrom, *mto;
11098 struct sip_request req;
11099 char hint[AST_MAX_EXTENSION];
11100 char *statestring = "terminated";
11101 const struct cfsubscription_types *subscriptiontype;
11102 enum state { NOTIFY_OPEN, NOTIFY_INUSE, NOTIFY_CLOSED } local_state = NOTIFY_OPEN;
11103 char *pidfstate = "--";
11104 char *pidfnote= "Ready";
11105
11106 memset(from, 0, sizeof(from));
11107 memset(to, 0, sizeof(to));
11108
11109 switch (state) {
11110 case (AST_EXTENSION_RINGING | AST_EXTENSION_INUSE):
11111 statestring = (sip_cfg.notifyringing) ? "early" : "confirmed";
11112 local_state = NOTIFY_INUSE;
11113 pidfstate = "busy";
11114 pidfnote = "Ringing";
11115 break;
11116 case AST_EXTENSION_RINGING:
11117 statestring = "early";
11118 local_state = NOTIFY_INUSE;
11119 pidfstate = "busy";
11120 pidfnote = "Ringing";
11121 break;
11122 case AST_EXTENSION_INUSE:
11123 statestring = "confirmed";
11124 local_state = NOTIFY_INUSE;
11125 pidfstate = "busy";
11126 pidfnote = "On the phone";
11127 break;
11128 case AST_EXTENSION_BUSY:
11129 statestring = "confirmed";
11130 local_state = NOTIFY_CLOSED;
11131 pidfstate = "busy";
11132 pidfnote = "On the phone";
11133 break;
11134 case AST_EXTENSION_UNAVAILABLE:
11135 statestring = "terminated";
11136 local_state = NOTIFY_CLOSED;
11137 pidfstate = "away";
11138 pidfnote = "Unavailable";
11139 break;
11140 case AST_EXTENSION_ONHOLD:
11141 statestring = "confirmed";
11142 local_state = NOTIFY_CLOSED;
11143 pidfstate = "busy";
11144 pidfnote = "On hold";
11145 break;
11146 case AST_EXTENSION_NOT_INUSE:
11147 default:
11148
11149 break;
11150 }
11151
11152 subscriptiontype = find_subscription_type(p->subscribed);
11153
11154
11155 if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, p->exten)) {
11156 char *hint2 = hint, *individual_hint = NULL;
11157 int hint_count = 0, unavailable_count = 0;
11158
11159 while ((individual_hint = strsep(&hint2, "&"))) {
11160 hint_count++;
11161
11162 if (ast_device_state(individual_hint) == AST_DEVICE_UNAVAILABLE)
11163 unavailable_count++;
11164 }
11165
11166
11167
11168
11169 if (hint_count > 0 && hint_count == unavailable_count) {
11170 local_state = NOTIFY_CLOSED;
11171 pidfstate = "away";
11172 pidfnote = "Not online";
11173 }
11174 }
11175
11176 ast_copy_string(from, get_header(&p->initreq, "From"), sizeof(from));
11177 c = get_in_brackets(from);
11178 if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
11179 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
11180 return -1;
11181 }
11182
11183 mfrom = remove_uri_parameters(c);
11184
11185 ast_copy_string(to, get_header(&p->initreq, "To"), sizeof(to));
11186 c = get_in_brackets(to);
11187 if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
11188 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
11189 return -1;
11190 }
11191 mto = remove_uri_parameters(c);
11192
11193 reqprep(&req, p, SIP_NOTIFY, 0, 1);
11194
11195
11196 add_header(&req, "Event", subscriptiontype->event);
11197 add_header(&req, "Content-Type", subscriptiontype->mediatype);
11198 switch(state) {
11199 case AST_EXTENSION_DEACTIVATED:
11200 if (timeout)
11201 add_header(&req, "Subscription-State", "terminated;reason=timeout");
11202 else {
11203 add_header(&req, "Subscription-State", "terminated;reason=probation");
11204 add_header(&req, "Retry-After", "60");
11205 }
11206 break;
11207 case AST_EXTENSION_REMOVED:
11208 add_header(&req, "Subscription-State", "terminated;reason=noresource");
11209 break;
11210 default:
11211 if (p->expiry)
11212 add_header(&req, "Subscription-State", "active");
11213 else
11214 add_header(&req, "Subscription-State", "terminated;reason=timeout");
11215 }
11216 switch (p->subscribed) {
11217 case XPIDF_XML:
11218 case CPIM_PIDF_XML:
11219 ast_str_append(&tmp, 0,
11220 "<?xml version=\"1.0\"?>\n"
11221 "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n"
11222 "<presence>\n");
11223 ast_str_append(&tmp, 0, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
11224 ast_str_append(&tmp, 0, "<atom id=\"%s\">\n", p->exten);
11225 ast_str_append(&tmp, 0, "<address uri=\"%s;user=ip\" priority=\"0.800000\">\n", mto);
11226 ast_str_append(&tmp, 0, "<status status=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "open" : (local_state == NOTIFY_INUSE) ? "inuse" : "closed");
11227 ast_str_append(&tmp, 0, "<msnsubstatus substatus=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "online" : (local_state == NOTIFY_INUSE) ? "onthephone" : "offline");
11228 ast_str_append(&tmp, 0, "</address>\n</atom>\n</presence>\n");
11229 break;
11230 case PIDF_XML:
11231 ast_str_append(&tmp, 0,
11232 "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"
11233 "<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);
11234 ast_str_append(&tmp, 0, "<pp:person><status>\n");
11235 if (pidfstate[0] != '-')
11236 ast_str_append(&tmp, 0, "<ep:activities><ep:%s/></ep:activities>\n", pidfstate);
11237 ast_str_append(&tmp, 0, "</status></pp:person>\n");
11238 ast_str_append(&tmp, 0, "<note>%s</note>\n", pidfnote);
11239 ast_str_append(&tmp, 0, "<tuple id=\"%s\">\n", p->exten);
11240 ast_str_append(&tmp, 0, "<contact priority=\"1\">%s</contact>\n", mto);
11241 if (pidfstate[0] == 'b')
11242 ast_str_append(&tmp, 0, "<status><basic>open</basic></status>\n");
11243 else
11244 ast_str_append(&tmp, 0, "<status><basic>%s</basic></status>\n", (local_state != NOTIFY_CLOSED) ? "open" : "closed");
11245 ast_str_append(&tmp, 0, "</tuple>\n</presence>\n");
11246 break;
11247 case DIALOG_INFO_XML:
11248 ast_str_append(&tmp, 0, "<?xml version=\"1.0\"?>\n");
11249 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);
11250 if ((state & AST_EXTENSION_RINGING) && sip_cfg.notifyringing) {
11251 const char *local_display = p->exten;
11252 char *local_target = mto;
11253
11254
11255
11256
11257 if (sip_cfg.notifycid) {
11258 struct ast_channel *caller = ast_channel_search_locked(find_calling_channel, p);
11259
11260 if (caller) {
11261 int need = strlen(caller->cid.cid_num) + strlen(p->fromdomain) + sizeof("sip:@");
11262 local_target = alloca(need);
11263 snprintf(local_target, need, "sip:%s@%s", caller->cid.cid_num, p->fromdomain);
11264 local_display = ast_strdupa(caller->cid.cid_name);
11265 ast_channel_unlock(caller);
11266 caller = NULL;
11267 }
11268 }
11269
11270
11271
11272 ast_str_append(&tmp, 0,
11273 "<dialog id=\"%s\" call-id=\"pickup-%s\" direction=\"recipient\">\n"
11274 "<remote>\n"
11275
11276
11277 "<identity display=\"%s\">%s</identity>\n"
11278 "<target uri=\"%s\"/>\n"
11279 "</remote>\n"
11280 "<local>\n"
11281 "<identity>%s</identity>\n"
11282 "<target uri=\"%s\"/>\n"
11283 "</local>\n",
11284 p->exten, p->callid, local_display, local_target, local_target, mto, mto);
11285 } else {
11286 ast_str_append(&tmp, 0, "<dialog id=\"%s\">\n", p->exten);
11287 }
11288 ast_str_append(&tmp, 0, "<state>%s</state>\n", statestring);
11289 if (state == AST_EXTENSION_ONHOLD) {
11290 ast_str_append(&tmp, 0, "<local>\n<target uri=\"%s\">\n"
11291 "<param pname=\"+sip.rendering\" pvalue=\"no\"/>\n"
11292 "</target>\n</local>\n", mto);
11293 }
11294 ast_str_append(&tmp, 0, "</dialog>\n</dialog-info>\n");
11295 break;
11296 case NONE:
11297 default:
11298 break;
11299 }
11300
11301 add_header_contentLength(&req, tmp->used);
11302 add_line(&req, tmp->str);
11303
11304 p->pendinginvite = p->ocseq;
11305
11306 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11307 }
11308
11309
11310
11311
11312
11313
11314
11315 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten)
11316 {
11317 struct sip_request req;
11318 struct ast_str *out = ast_str_alloca(500);
11319 int ourport = ntohs(p->ourip.sin_port);
11320 const char *exten = S_OR(vmexten, default_vmexten);
11321
11322 initreqprep(&req, p, SIP_NOTIFY);
11323 add_header(&req, "Event", "message-summary");
11324 add_header(&req, "Content-Type", default_notifymime);
11325 ast_str_append(&out, 0, "Messages-Waiting: %s\r\n", newmsgs ? "yes" : "no");
11326
11327 if (!ast_strlen_zero(p->fromdomain)) {
11328 ast_str_append(&out, 0, "Message-Account: sip:%s@%s\r\n", exten, p->fromdomain);
11329 } else if (!sip_standard_port(p->socket.type, ourport)) {
11330 if (p->socket.type == SIP_TRANSPORT_UDP) {
11331 ast_str_append(&out, 0, "Message-Account: sip:%s@%s:%d\r\n", exten, ast_inet_ntoa(p->ourip.sin_addr), ourport);
11332 } else {
11333 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));
11334 }
11335 } else {
11336 if (p->socket.type == SIP_TRANSPORT_UDP) {
11337 ast_str_append(&out, 0, "Message-Account: sip:%s@%s\r\n", exten, ast_inet_ntoa(p->ourip.sin_addr));
11338 } else {
11339 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));
11340 }
11341 }
11342
11343
11344
11345 ast_str_append(&out, 0, "Voice-Message: %d/%d%s\r\n",
11346 newmsgs, oldmsgs, (ast_test_flag(&p->flags[1], SIP_PAGE2_BUGGY_MWI) ? "" : " (0/0)"));
11347
11348 if (p->subscribed) {
11349 if (p->expiry)
11350 add_header(&req, "Subscription-State", "active");
11351 else
11352 add_header(&req, "Subscription-State", "terminated;reason=timeout");
11353 }
11354
11355 add_header_contentLength(&req, out->used);
11356 add_line(&req, out->str);
11357
11358 if (!p->initreq.headers)
11359 initialize_initreq(p, &req);
11360 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11361 }
11362
11363
11364 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate)
11365 {
11366 struct sip_request req;
11367 char tmp[SIPBUFSIZE/2];
11368
11369 reqprep(&req, p, SIP_NOTIFY, 0, 1);
11370 snprintf(tmp, sizeof(tmp), "refer;id=%d", cseq);
11371 add_header(&req, "Event", tmp);
11372 add_header(&req, "Subscription-state", terminate ? "terminated;reason=noresource" : "active");
11373 add_header(&req, "Content-Type", "message/sipfrag;version=2.0");
11374 add_header(&req, "Allow", ALLOWED_METHODS);
11375 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
11376
11377 snprintf(tmp, sizeof(tmp), "SIP/2.0 %s\r\n", message);
11378 add_header_contentLength(&req, strlen(tmp));
11379 add_line(&req, tmp);
11380
11381 if (!p->initreq.headers)
11382 initialize_initreq(p, &req);
11383
11384 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11385 }
11386
11387
11388 static int transmit_notify_custom(struct sip_pvt *p, struct ast_variable *vars) {
11389 struct sip_request req;
11390 struct ast_variable *var, *newvar;
11391
11392 initreqprep(&req, p, SIP_NOTIFY);
11393
11394
11395 p->notify_headers = newvar = ast_variable_new("Subscription-State", "terminated", "");
11396 add_header(&req, newvar->name, newvar->value);
11397 for (var = vars; var; var = var->next) {
11398 char buf[512];
11399 ast_debug(2, " Adding pair %s=%s\n", var->name, var->value);
11400 ast_copy_string(buf, var->value, sizeof(buf));
11401 add_header(&req, var->name, ast_unescape_semicolon(buf));
11402 newvar->next = ast_variable_new(var->name, var->value, "");
11403 newvar = newvar->next;
11404 }
11405
11406 if (!p->initreq.headers) {
11407 initialize_initreq(p, &req);
11408 }
11409
11410 return send_request(p, &req, XMIT_UNRELIABLE, p->ocseq);
11411 }
11412
11413 static int manager_sipnotify(struct mansession *s, const struct message *m)
11414 {
11415 const char *channame = astman_get_header(m, "Channel");
11416 struct ast_variable *vars = astman_get_variables(m);
11417 struct sip_pvt *p;
11418
11419 if (ast_strlen_zero(channame)) {
11420 astman_send_error(s, m, "SIPNotify requires a channel name");
11421 return 0;
11422 }
11423
11424 if (!strncasecmp(channame, "sip/", 4)) {
11425 channame += 4;
11426 }
11427
11428 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
11429 astman_send_error(s, m, "Unable to build sip pvt data for notify (memory/socket error)");
11430 return 0;
11431 }
11432
11433 if (create_addr(p, channame, NULL, 0)) {
11434
11435 dialog_unlink_all(p, TRUE, TRUE);
11436 dialog_unref(p, "unref dialog inside for loop" );
11437
11438 astman_send_error(s, m, "Could not create address");
11439 return 0;
11440 }
11441
11442
11443 ast_set_flag(&p->flags[0], SIP_OUTGOING);
11444
11445
11446 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
11447 build_via(p);
11448 ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
11449 build_callid_pvt(p);
11450 ao2_t_link(dialogs, p, "Linking in new name");
11451 dialog_ref(p, "bump the count of p, which transmit_sip_request will decrement.");
11452 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
11453
11454 if (!transmit_notify_custom(p, vars)) {
11455 astman_send_ack(s, m, "Notify Sent");
11456 } else {
11457 astman_send_error(s, m, "Unable to send notify");
11458 }
11459 ast_variables_destroy(vars);
11460 return 0;
11461 }
11462
11463 static char mandescr_sipnotify[] =
11464 "Description: Sends a SIP Notify event\n"
11465 "All parameters for this event must be specified in the body of this request\n"
11466 "via multiple Variable: name=value sequences.\n"
11467 "Variables: \n"
11468 " *Channel: <peername> Peer to receive the notify. Required.\n"
11469 " *Variable: <name>=<value> At least one variable pair must be specified.\n"
11470 " ActionID: <id> Action ID for this transaction. Will be returned.\n";
11471
11472 static const struct _map_x_s regstatestrings[] = {
11473 { REG_STATE_FAILED, "Failed" },
11474 { REG_STATE_UNREGISTERED, "Unregistered"},
11475 { REG_STATE_REGSENT, "Request Sent"},
11476 { REG_STATE_AUTHSENT, "Auth. Sent"},
11477 { REG_STATE_REGISTERED, "Registered"},
11478 { REG_STATE_REJECTED, "Rejected"},
11479 { REG_STATE_TIMEOUT, "Timeout"},
11480 { REG_STATE_NOAUTH, "No Authentication"},
11481 { -1, NULL }
11482 };
11483
11484
11485 static const char *regstate2str(enum sipregistrystate regstate)
11486 {
11487 return map_x_s(regstatestrings, regstate, "Unknown");
11488 }
11489
11490
11491
11492
11493
11494
11495
11496 static int sip_reregister(const void *data)
11497 {
11498
11499 struct sip_registry *r= (struct sip_registry *) data;
11500
11501
11502 if (!r)
11503 return 0;
11504
11505 if (r->call && r->call->do_history)
11506 append_history(r->call, "RegistryRenew", "Account: %s@%s", r->username, r->hostname);
11507
11508
11509 if (sipdebug)
11510 ast_log(LOG_NOTICE, " -- Re-registration for %s@%s\n", r->username, r->hostname);
11511
11512 r->expire = -1;
11513 r->expiry = r->configured_expiry;
11514 __sip_do_register(r);
11515 registry_unref(r, "unref the re-register scheduled event");
11516 return 0;
11517 }
11518
11519
11520 static int __sip_do_register(struct sip_registry *r)
11521 {
11522 int res;
11523
11524 res = transmit_register(r, SIP_REGISTER, NULL, NULL);
11525 return res;
11526 }
11527
11528
11529
11530
11531
11532
11533
11534 static int sip_reg_timeout(const void *data)
11535 {
11536
11537
11538 struct sip_registry *r = (struct sip_registry *)data;
11539 struct sip_pvt *p;
11540 int res;
11541
11542
11543 if (!r)
11544 return 0;
11545
11546 if (r->dnsmgr) {
11547
11548 ast_dnsmgr_refresh(r->dnsmgr);
11549 }
11550
11551 ast_log(LOG_NOTICE, " -- Registration for '%s@%s' timed out, trying again (Attempt #%d)\n", r->username, r->hostname, r->regattempts);
11552
11553
11554
11555
11556 if (r->call) {
11557
11558
11559 p = r->call;
11560 sip_pvt_lock(p);
11561 pvt_set_needdestroy(p, "registration timeout");
11562
11563 __sip_pretend_ack(p);
11564 sip_pvt_unlock(p);
11565
11566
11567
11568 if (p->registry)
11569 p->registry = registry_unref(p->registry, "p->registry unreffed");
11570 r->call = dialog_unref(r->call, "unrefing r->call");
11571 }
11572
11573 r->timeout = -1;
11574 if (global_regattempts_max && r->regattempts > global_regattempts_max) {
11575
11576
11577
11578 ast_log(LOG_NOTICE, " -- Giving up forever trying to register '%s@%s'\n", r->username, r->hostname);
11579 r->regstate = REG_STATE_FAILED;
11580 } else {
11581 r->regstate = REG_STATE_UNREGISTERED;
11582 res=transmit_register(r, SIP_REGISTER, NULL, NULL);
11583 }
11584 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));
11585 registry_unref(r, "unreffing registry_unref r");
11586 return 0;
11587 }
11588
11589
11590
11591
11592 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader)
11593 {
11594 struct sip_request req;
11595 char from[256];
11596 char to[256];
11597 char tmp[80];
11598 char addr[80];
11599 struct sip_pvt *p;
11600 struct sip_peer *peer = NULL;
11601 int res;
11602 char *fromdomain;
11603 char *domainport = NULL;
11604
11605
11606 if (r == NULL || ((auth == NULL) && (r->regstate == REG_STATE_REGSENT || r->regstate == REG_STATE_AUTHSENT))) {
11607 if (r) {
11608 ast_log(LOG_NOTICE, "Strange, trying to register %s@%s when registration already pending\n", r->username, r->hostname);
11609 }
11610 return 0;
11611 }
11612
11613 if (r->dnsmgr == NULL) {
11614 char transport[MAXHOSTNAMELEN];
11615 peer = find_peer(r->hostname, NULL, TRUE, FINDPEERS, FALSE, 0);
11616 snprintf(transport, sizeof(transport), "_sip._%s", get_transport(r->transport));
11617 ast_dnsmgr_lookup(peer ? peer->tohost : r->hostname, &r->us, &r->dnsmgr, sip_cfg.srvlookup ? transport : NULL);
11618 if (peer) {
11619 peer = unref_peer(peer, "removing peer ref for dnsmgr_lookup");
11620 }
11621 }
11622
11623 if (r->call) {
11624 if (!auth) {
11625 ast_log(LOG_WARNING, "Already have a REGISTER going on to %s@%s?? \n", r->username, r->hostname);
11626 return 0;
11627 } else {
11628 p = dialog_ref(r->call, "getting a copy of the r->call dialog in transmit_register");
11629 make_our_tag(p->tag, sizeof(p->tag));
11630 ast_string_field_set(p, theirtag, NULL);
11631 }
11632 } else {
11633
11634 if (!r->callid_valid) {
11635 build_callid_registry(r, internip.sin_addr, default_fromdomain);
11636 r->callid_valid = TRUE;
11637 }
11638
11639 if (!(p = sip_alloc( r->callid, NULL, 0, SIP_REGISTER, NULL))) {
11640 ast_log(LOG_WARNING, "Unable to allocate registration transaction (memory or socket error)\n");
11641 return 0;
11642 }
11643
11644 if (p->do_history)
11645 append_history(p, "RegistryInit", "Account: %s@%s", r->username, r->hostname);
11646
11647 if (!ast_strlen_zero(r->peername)) {
11648 if (!(peer = find_peer(r->peername, NULL, 1, FINDPEERS, FALSE, 0))) {
11649 ast_log(LOG_WARNING, "Could not find peer %s in transmit_register\n", r->peername);
11650 } else {
11651 p->peerauth = peer->auth;
11652 }
11653 }
11654 ref_proxy(p, obproxy_get(p, peer));
11655 if (peer) {
11656 unref_peer(peer, "transmit_registration: from find_peer operation");
11657 }
11658
11659 if (!r->us.sin_port && r->portno)
11660 r->us.sin_port = htons(r->portno);
11661
11662
11663 if (create_addr(p, r->hostname, &r->us, 0)) {
11664
11665
11666 dialog_unlink_all(p, TRUE, TRUE);
11667 p = dialog_unref(p, "unref dialog after unlink_all");
11668 if (r->timeout > -1) {
11669 AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
11670 registry_unref(_data, "del for REPLACE of registry ptr"),
11671 registry_unref(r, "object ptr dec when SCHED_REPLACE add failed"),
11672 registry_addref(r,"add for REPLACE registry ptr"));
11673 ast_log(LOG_WARNING, "Still have a registration timeout for %s@%s (create_addr() error), %d\n", r->username, r->hostname, r->timeout);
11674 } else {
11675 r->timeout = ast_sched_add(sched, global_reg_timeout * 1000, sip_reg_timeout, registry_addref(r, "add for REPLACE registry ptr"));
11676 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);
11677 }
11678 r->regattempts++;
11679 return 0;
11680 }
11681
11682
11683 ast_string_field_set(r, callid, p->callid);
11684 if (!r->dnsmgr && r->portno) {
11685 p->sa.sin_port = htons(r->portno);
11686 p->recv.sin_port = htons(r->portno);
11687 } else {
11688 r->portno = ntohs(p->sa.sin_port);
11689 }
11690 ast_set_flag(&p->flags[0], SIP_OUTGOING);
11691 r->call = dialog_ref(p, "copying dialog into registry r->call");
11692 p->registry = registry_addref(r, "transmit_register: addref to p->registry in transmit_register");
11693 if (!ast_strlen_zero(r->secret)) {
11694 ast_string_field_set(p, peersecret, r->secret);
11695 }
11696 if (!ast_strlen_zero(r->md5secret))
11697 ast_string_field_set(p, peermd5secret, r->md5secret);
11698
11699
11700 if (!ast_strlen_zero(r->authuser)) {
11701 ast_string_field_set(p, peername, r->authuser);
11702 ast_string_field_set(p, authname, r->authuser);
11703 } else if (!ast_strlen_zero(r->username)) {
11704 ast_string_field_set(p, peername, r->username);
11705 ast_string_field_set(p, authname, r->username);
11706 ast_string_field_set(p, fromuser, r->username);
11707 }
11708 if (!ast_strlen_zero(r->username))
11709 ast_string_field_set(p, username, r->username);
11710
11711 if (!ast_strlen_zero(r->callback))
11712 ast_string_field_set(p, exten, r->callback);
11713
11714
11715 set_socket_transport(&p->socket, r->transport);
11716 if (r->transport == SIP_TRANSPORT_TLS || r->transport == SIP_TRANSPORT_TCP) {
11717 p->socket.port = sip_tcp_desc.local_address.sin_port;
11718 }
11719
11720
11721
11722
11723
11724
11725 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
11726 build_contact(p);
11727 }
11728
11729
11730 if (auth == NULL) {
11731 if (r->timeout > -1)
11732 ast_log(LOG_WARNING, "Still have a registration timeout, #%d - deleting it\n", r->timeout);
11733 AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
11734 registry_unref(_data,"reg ptr unrefed from del in SCHED_REPLACE"),
11735 registry_unref(r,"reg ptr unrefed from add failure in SCHED_REPLACE"),
11736 registry_addref(r,"reg ptr reffed from add in SCHED_REPLACE"));
11737 ast_debug(1, "Scheduled a registration timeout for %s id #%d \n", r->hostname, r->timeout);
11738 }
11739
11740 if ((fromdomain = strchr(r->username, '@'))) {
11741
11742 fromdomain++ ;
11743
11744 snprintf(from, sizeof(from), "<sip:%s>;tag=%s", r->username, p->tag);
11745 if (!ast_strlen_zero(p->theirtag))
11746 snprintf(to, sizeof(to), "<sip:%s>;tag=%s", r->username, p->theirtag);
11747 else
11748 snprintf(to, sizeof(to), "<sip:%s>", r->username);
11749
11750
11751
11752 if (ast_strlen_zero(p->fromdomain)) {
11753 ast_string_field_set(p, fromdomain, fromdomain);
11754 }
11755 } else {
11756 snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->tag);
11757 if (!ast_strlen_zero(p->theirtag))
11758 snprintf(to, sizeof(to), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->theirtag);
11759 else
11760 snprintf(to, sizeof(to), "<sip:%s@%s>", r->username, p->tohost);
11761 }
11762
11763
11764
11765 if (!ast_strlen_zero(p->fromdomain)) {
11766 domainport = strrchr(p->fromdomain, ':');
11767 if (domainport) {
11768 *domainport++ = '\0';
11769 if (ast_strlen_zero(domainport))
11770 domainport = NULL;
11771 }
11772 if (domainport) {
11773 if (atoi(domainport) != STANDARD_SIP_PORT)
11774 snprintf(addr, sizeof(addr), "sip:%s:%s", p->fromdomain, domainport);
11775 else
11776 snprintf(addr, sizeof(addr), "sip:%s", p->fromdomain);
11777 } else {
11778 if (r->portno && r->portno != STANDARD_SIP_PORT)
11779 snprintf(addr, sizeof(addr), "sip:%s:%d", p->fromdomain, r->portno);
11780 else
11781 snprintf(addr, sizeof(addr), "sip:%s", p->fromdomain);
11782 }
11783 } else {
11784 if (r->portno && r->portno != STANDARD_SIP_PORT)
11785 snprintf(addr, sizeof(addr), "sip:%s:%d", r->hostname, r->portno);
11786 else
11787 snprintf(addr, sizeof(addr), "sip:%s", r->hostname);
11788 }
11789 ast_string_field_set(p, uri, addr);
11790
11791 p->branch ^= ast_random();
11792
11793 init_req(&req, sipmethod, addr);
11794
11795
11796 snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, sip_methods[sipmethod].text);
11797 p->ocseq = r->ocseq;
11798
11799 build_via(p);
11800 add_header(&req, "Via", p->via);
11801 add_header(&req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
11802 add_header(&req, "From", from);
11803 add_header(&req, "To", to);
11804 add_header(&req, "Call-ID", p->callid);
11805 add_header(&req, "CSeq", tmp);
11806 if (!ast_strlen_zero(global_useragent))
11807 add_header(&req, "User-Agent", global_useragent);
11808
11809
11810 if (auth)
11811 add_header(&req, authheader, auth);
11812 else if (!ast_strlen_zero(r->nonce)) {
11813 char digest[1024];
11814
11815
11816
11817
11818
11819
11820 if (sipdebug)
11821 ast_debug(1, " >>> Re-using Auth data for %s@%s\n", r->username, r->hostname);
11822 ast_string_field_set(p, realm, r->realm);
11823 ast_string_field_set(p, nonce, r->nonce);
11824 ast_string_field_set(p, domain, r->domain);
11825 ast_string_field_set(p, opaque, r->opaque);
11826 ast_string_field_set(p, qop, r->qop);
11827 p->noncecount = ++r->noncecount;
11828
11829 memset(digest, 0, sizeof(digest));
11830 if(!build_reply_digest(p, sipmethod, digest, sizeof(digest)))
11831 add_header(&req, "Authorization", digest);
11832 else
11833 ast_log(LOG_NOTICE, "No authorization available for authentication of registration to %s@%s\n", r->username, r->hostname);
11834
11835 }
11836
11837 snprintf(tmp, sizeof(tmp), "%d", r->expiry);
11838 add_header(&req, "Expires", tmp);
11839 add_header(&req, "Contact", p->our_contact);
11840 add_header_contentLength(&req, 0);
11841
11842 initialize_initreq(p, &req);
11843 if (sip_debug_test_pvt(p)) {
11844 ast_verbose("REGISTER %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
11845 }
11846 r->regstate = auth ? REG_STATE_AUTHSENT : REG_STATE_REGSENT;
11847 r->regattempts++;
11848 ast_debug(4, "REGISTER attempt %d to %s@%s\n", r->regattempts, r->username, r->hostname);
11849 res = send_request(p, &req, XMIT_CRITICAL, p->ocseq);
11850 dialog_unref(p, "p is finished here at the end of transmit_register");
11851 return res;
11852 }
11853
11854
11855 static int transmit_message_with_text(struct sip_pvt *p, const char *text)
11856 {
11857 struct sip_request req;
11858
11859 reqprep(&req, p, SIP_MESSAGE, 0, 1);
11860 add_text(&req, text);
11861 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11862 }
11863
11864
11865 static int sip_refer_allocate(struct sip_pvt *p)
11866 {
11867 p->refer = ast_calloc(1, sizeof(struct sip_refer));
11868 return p->refer ? 1 : 0;
11869 }
11870
11871
11872
11873
11874
11875
11876 static int transmit_refer(struct sip_pvt *p, const char *dest)
11877 {
11878 struct sip_request req = {
11879 .headers = 0,
11880 };
11881 char from[256];
11882 const char *of;
11883 char *c;
11884 char referto[256];
11885 char *ttag, *ftag;
11886 char *theirtag = ast_strdupa(p->theirtag);
11887 int use_tls=FALSE;
11888
11889 if (sipdebug)
11890 ast_debug(1, "SIP transfer of %s to %s\n", p->callid, dest);
11891
11892
11893 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
11894 of = get_header(&p->initreq, "To");
11895 ttag = theirtag;
11896 ftag = p->tag;
11897 } else {
11898 of = get_header(&p->initreq, "From");
11899 ftag = theirtag;
11900 ttag = p->tag;
11901 }
11902
11903 ast_copy_string(from, of, sizeof(from));
11904 of = get_in_brackets(from);
11905 ast_string_field_set(p, from, of);
11906 if (!strncasecmp(of, "sip:", 4)) {
11907 of += 4;
11908 }else if (!strncasecmp(of, "sips:", 5)) {
11909 of += 5;
11910 use_tls = TRUE;
11911 } else {
11912 ast_log(LOG_NOTICE, "From address missing 'sip(s):', assuming sip:\n");
11913 }
11914
11915 if ((c = strchr(dest, '@')))
11916 c = NULL;
11917 else if ((c = strchr(of, '@')))
11918 *c++ = '\0';
11919 if (c)
11920 snprintf(referto, sizeof(referto), "<sip%s:%s@%s>", use_tls ? "s" : "", dest, c);
11921 else
11922 snprintf(referto, sizeof(referto), "<sip%s:%s>", use_tls ? "s" : "", dest);
11923
11924
11925 sip_refer_allocate(p);
11926 ast_copy_string(p->refer->refer_to, referto, sizeof(p->refer->refer_to));
11927 ast_copy_string(p->refer->referred_by, p->our_contact, sizeof(p->refer->referred_by));
11928 p->refer->status = REFER_SENT;
11929
11930 reqprep(&req, p, SIP_REFER, 0, 1);
11931
11932 add_header(&req, "Refer-To", referto);
11933 add_header(&req, "Allow", ALLOWED_METHODS);
11934 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
11935 if (!ast_strlen_zero(p->our_contact))
11936 add_header(&req, "Referred-By", p->our_contact);
11937
11938 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948 }
11949
11950
11951
11952 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration)
11953 {
11954 struct sip_request req;
11955
11956 reqprep(&req, p, SIP_INFO, 0, 1);
11957 add_digit(&req, digit, duration, (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_SHORTINFO));
11958 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11959 }
11960
11961
11962 static int transmit_info_with_vidupdate(struct sip_pvt *p)
11963 {
11964 struct sip_request req;
11965
11966 reqprep(&req, p, SIP_INFO, 0, 1);
11967 add_vidupdate(&req);
11968 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11969 }
11970
11971
11972
11973
11974 static int transmit_request(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
11975 {
11976 struct sip_request resp;
11977
11978 if (sipmethod == SIP_ACK)
11979 p->invitestate = INV_CONFIRMED;
11980
11981 reqprep(&resp, p, sipmethod, seqno, newbranch);
11982 if (sipmethod == SIP_CANCEL && p->answered_elsewhere)
11983 add_header(&resp, "Reason", "SIP;cause=200;text=\"Call completed elsewhere\"");
11984
11985 add_header_contentLength(&resp, 0);
11986 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
11987 }
11988
11989
11990 static void auth_headers(enum sip_auth_type code, char **header, char **respheader)
11991 {
11992 if (code == WWW_AUTH) {
11993 *header = "WWW-Authenticate";
11994 *respheader = "Authorization";
11995 } else if (code == PROXY_AUTH) {
11996 *header = "Proxy-Authenticate";
11997 *respheader = "Proxy-Authorization";
11998 } else {
11999 ast_verbose("-- wrong response code %d\n", code);
12000 *header = *respheader = "Invalid";
12001 }
12002 }
12003
12004
12005 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
12006 {
12007 struct sip_request resp;
12008
12009 reqprep(&resp, p, sipmethod, seqno, newbranch);
12010 if (!ast_strlen_zero(p->realm)) {
12011 char digest[1024];
12012
12013 memset(digest, 0, sizeof(digest));
12014 if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
12015 char *dummy, *response;
12016 enum sip_auth_type code = p->options ? p->options->auth_type : PROXY_AUTH;
12017 auth_headers(code, &dummy, &response);
12018 add_header(&resp, response, digest);
12019 } else
12020 ast_log(LOG_WARNING, "No authentication available for call %s\n", p->callid);
12021 }
12022
12023
12024 if (sipmethod == SIP_BYE) {
12025 char buf[10];
12026
12027 add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->hangupcause));
12028 snprintf(buf, sizeof(buf), "%d", p->hangupcause);
12029 add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
12030 }
12031
12032 add_header_contentLength(&resp, 0);
12033 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
12034 }
12035
12036
12037 static void destroy_association(struct sip_peer *peer)
12038 {
12039 int realtimeregs = ast_check_realtime("sipregs");
12040 char *tablename = (realtimeregs) ? "sipregs" : "sippeers";
12041
12042 if (!sip_cfg.ignore_regexpire) {
12043 if (peer->rt_fromcontact && sip_cfg.peer_rtupdate) {
12044 ast_update_realtime(tablename, "name", peer->name, "fullcontact", "", "ipaddr", "", "port", "", "regseconds", "0", peer->deprecated_username ? "username" : "defaultuser", "", "regserver", "", "useragent", "", "lastms", "", SENTINEL);
12045 } else {
12046 ast_db_del("SIP/Registry", peer->name);
12047 }
12048 }
12049 }
12050
12051 static void set_socket_transport(struct sip_socket *socket, int transport)
12052 {
12053
12054 if (socket->type != transport) {
12055 socket->fd = -1;
12056 socket->type = transport;
12057 if (socket->tcptls_session) {
12058 ao2_ref(socket->tcptls_session, -1);
12059 socket->tcptls_session = NULL;
12060 }
12061 }
12062 }
12063
12064
12065 static int expire_register(const void *data)
12066 {
12067 struct sip_peer *peer = (struct sip_peer *)data;
12068
12069 if (!peer)
12070 return 0;
12071
12072 peer->expire = -1;
12073 peer->portinuri = 0;
12074 memset(&peer->addr, 0, sizeof(peer->addr));
12075
12076 destroy_association(peer);
12077 set_socket_transport(&peer->socket, peer->default_outbound_transport);
12078
12079 if (peer->socket.tcptls_session) {
12080 ao2_ref(peer->socket.tcptls_session, -1);
12081 peer->socket.tcptls_session = NULL;
12082 }
12083
12084 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
12085 register_peer_exten(peer, FALSE);
12086 ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
12087
12088
12089
12090
12091 if (peer->is_realtime)
12092 ast_debug(3, "-REALTIME- peer expired registration. Name: %s. Realtime peer objects now %d\n", peer->name, rpeerobjs);
12093
12094 if (peer->selfdestruct ||
12095 ast_test_flag(&peer->flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
12096 ao2_t_unlink(peers, peer, "ao2_unlink of peer from peers table");
12097 if (peer->addr.sin_addr.s_addr) {
12098 ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
12099 }
12100 }
12101
12102 unref_peer(peer, "removing peer ref for expire_register");
12103
12104 return 0;
12105 }
12106
12107
12108 static int sip_poke_peer_s(const void *data)
12109 {
12110 struct sip_peer *peer = (struct sip_peer *)data;
12111
12112 peer->pokeexpire = -1;
12113
12114 sip_poke_peer(peer, 0);
12115
12116 unref_peer(peer, "removing poke peer ref");
12117
12118 return 0;
12119 }
12120
12121
12122 static void reg_source_db(struct sip_peer *peer)
12123 {
12124 char data[256];
12125 struct in_addr in;
12126 int expire;
12127 int port;
12128 char *scan, *addr, *port_str, *expiry_str, *username, *contact;
12129
12130 if (peer->rt_fromcontact)
12131 return;
12132 if (ast_db_get("SIP/Registry", peer->name, data, sizeof(data)))
12133 return;
12134
12135 scan = data;
12136 addr = strsep(&scan, ":");
12137 port_str = strsep(&scan, ":");
12138 expiry_str = strsep(&scan, ":");
12139 username = strsep(&scan, ":");
12140 contact = scan;
12141
12142 if (!inet_aton(addr, &in))
12143 return;
12144
12145 if (port_str)
12146 port = atoi(port_str);
12147 else
12148 return;
12149
12150 if (expiry_str)
12151 expire = atoi(expiry_str);
12152 else
12153 return;
12154
12155 if (username)
12156 ast_string_field_set(peer, username, username);
12157 if (contact)
12158 ast_string_field_set(peer, fullcontact, contact);
12159
12160 ast_debug(2, "SIP Seeding peer from astdb: '%s' at %s@%s:%d for %d\n",
12161 peer->name, peer->username, ast_inet_ntoa(in), port, expire);
12162
12163 memset(&peer->addr, 0, sizeof(peer->addr));
12164 peer->addr.sin_family = AF_INET;
12165 peer->addr.sin_addr = in;
12166 peer->addr.sin_port = htons(port);
12167 if (sipsock < 0) {
12168
12169 AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, ast_random() % 5000 + 1, sip_poke_peer_s, peer,
12170 unref_peer(_data, "removing poke peer ref"),
12171 unref_peer(peer, "removing poke peer ref"),
12172 ref_peer(peer, "adding poke peer ref"));
12173 } else {
12174 sip_poke_peer(peer, 0);
12175 }
12176 AST_SCHED_REPLACE_UNREF(peer->expire, sched, (expire + 10) * 1000, expire_register, peer,
12177 unref_peer(_data, "remove registration ref"),
12178 unref_peer(peer, "remove registration ref"),
12179 ref_peer(peer, "add registration ref"));
12180 register_peer_exten(peer, TRUE);
12181 }
12182
12183
12184 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req)
12185 {
12186 char contact[SIPBUFSIZE];
12187 char *c;
12188
12189
12190 ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
12191 c = get_in_brackets(contact);
12192
12193
12194 ast_string_field_set(pvt, fullcontact, c);
12195
12196
12197 ast_string_field_set(pvt, okcontacturi, c);
12198
12199
12200
12201 return TRUE;
12202 }
12203
12204 static int __set_address_from_contact(const char *fullcontact, struct sockaddr_in *sin, int tcp)
12205 {
12206 struct hostent *hp;
12207 struct ast_hostent ahp;
12208 int port = STANDARD_SIP_PORT;
12209 char *host, *pt, *transport;
12210 char contact_buf[256];
12211 char *contact;
12212
12213
12214 ast_copy_string(contact_buf, fullcontact, sizeof(contact_buf));
12215 contact = contact_buf;
12216
12217
12218
12219
12220
12221
12222
12223
12224 if (parse_uri(contact, "sip:,sips:", &contact, NULL, &host, &pt, NULL, &transport)) {
12225 ast_log(LOG_WARNING, "Invalid contact uri %s (missing sip: or sips:), attempting to use anyway\n", fullcontact);
12226 }
12227
12228
12229 if (((get_transport_str2enum(transport) == SIP_TRANSPORT_TLS)) || !(strncasecmp(fullcontact, "sips", 4))) {
12230 port = port_str2int(pt, STANDARD_TLS_PORT);
12231 } else {
12232 port = port_str2int(pt, STANDARD_SIP_PORT);
12233 }
12234
12235
12236
12237
12238
12239
12240
12241
12242 hp = ast_gethostbyname(host, &ahp);
12243 if (!hp) {
12244 ast_log(LOG_WARNING, "Invalid host name in Contact: (can't resolve in DNS) : '%s'\n", host);
12245 return -1;
12246 }
12247 sin->sin_family = AF_INET;
12248 memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
12249 sin->sin_port = htons(port);
12250
12251 return 0;
12252 }
12253
12254
12255 static int set_address_from_contact(struct sip_pvt *pvt)
12256 {
12257 if (ast_test_flag(&pvt->flags[0], SIP_NAT_ROUTE)) {
12258
12259
12260
12261 pvt->sa = pvt->recv;
12262 return 0;
12263 }
12264
12265 return __set_address_from_contact(pvt->fullcontact, &pvt->sa, pvt->socket.type == SIP_TRANSPORT_TLS ? 1 : 0);
12266 }
12267
12268
12269 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *peer, struct sip_request *req)
12270 {
12271 char contact[SIPBUFSIZE];
12272 char data[SIPBUFSIZE];
12273 const char *expires = get_header(req, "Expires");
12274 int expire = atoi(expires);
12275 char *curi, *host, *pt, *transport;
12276 int port;
12277 int transport_type;
12278 const char *useragent;
12279 struct hostent *hp;
12280 struct ast_hostent ahp;
12281 struct sockaddr_in oldsin, testsin;
12282
12283
12284 ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
12285
12286 if (ast_strlen_zero(expires)) {
12287 char *s = strcasestr(contact, ";expires=");
12288 if (s) {
12289 expires = strsep(&s, ";");
12290 if (sscanf(expires + 9, "%30d", &expire) != 1)
12291 expire = default_expiry;
12292 } else {
12293
12294 expire = default_expiry;
12295 }
12296 }
12297
12298 copy_socket_data(&pvt->socket, &req->socket);
12299
12300
12301 curi = contact;
12302 if (strchr(contact, '<') == NULL)
12303 strsep(&curi, ";");
12304 curi = get_in_brackets(contact);
12305
12306
12307
12308
12309
12310 if (ast_strlen_zero(curi) && ast_strlen_zero(expires)) {
12311
12312 if (peer->expire > -1 && !ast_strlen_zero(peer->fullcontact))
12313 pvt->expiry = ast_sched_when(sched, peer->expire);
12314 return PARSE_REGISTER_QUERY;
12315 } else if (!strcasecmp(curi, "*") || !expire) {
12316
12317 memset(&peer->addr, 0, sizeof(peer->addr));
12318 set_socket_transport(&peer->socket, peer->default_outbound_transport);
12319
12320 AST_SCHED_DEL_UNREF(sched, peer->expire,
12321 unref_peer(peer, "remove register expire ref"));
12322
12323 destroy_association(peer);
12324
12325 register_peer_exten(peer, FALSE);
12326 ast_string_field_set(peer, fullcontact, "");
12327 ast_string_field_set(peer, useragent, "");
12328 peer->sipoptions = 0;
12329 peer->lastms = 0;
12330 peer->portinuri = 0;
12331 pvt->expiry = 0;
12332
12333 ast_verb(3, "Unregistered SIP '%s'\n", peer->name);
12334
12335 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unregistered\r\n", peer->name);
12336 return PARSE_REGISTER_UPDATE;
12337 }
12338
12339
12340 ast_string_field_set(peer, fullcontact, curi);
12341
12342
12343 ast_string_field_build(pvt, our_contact, "<%s>", curi);
12344
12345
12346 if (parse_uri(curi, "sip:,sips:", &curi, NULL, &host, &pt, NULL, &transport)) {
12347 ast_log(LOG_NOTICE, "Not a valid SIP contact (missing sip:) trying to use anyway\n");
12348 }
12349
12350
12351
12352 peer->portinuri = !ast_strlen_zero(pt) ? TRUE : FALSE;
12353
12354
12355 if ((transport_type = get_transport_str2enum(transport))) {
12356
12357
12358
12359
12360 port = port_str2int(pt, (transport_type == SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT);
12361 } else {
12362 port = port_str2int(pt, STANDARD_SIP_PORT);
12363 transport_type = pvt->socket.type;
12364 }
12365
12366
12367
12368
12369 if ((peer->socket.type != transport_type) && (peer->transports & transport_type)) {
12370 set_socket_transport(&peer->socket, transport_type);
12371 }
12372
12373 oldsin = peer->addr;
12374
12375
12376 if (peer->addr.sin_addr.s_addr) {
12377 ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
12378 }
12379
12380
12381
12382
12383 hp = ast_gethostbyname(host, &ahp);
12384 if (!hp) {
12385 ast_log(LOG_WARNING, "Invalid host '%s'\n", host);
12386 ast_string_field_set(peer, fullcontact, "");
12387 ast_string_field_set(pvt, our_contact, "");
12388 return PARSE_REGISTER_FAILED;
12389 }
12390 memcpy(&testsin.sin_addr, hp->h_addr, sizeof(testsin.sin_addr));
12391 if (ast_apply_ha(global_contact_ha, &testsin) != AST_SENSE_ALLOW ||
12392 ast_apply_ha(peer->contactha, &testsin) != AST_SENSE_ALLOW) {
12393 ast_log(LOG_WARNING, "Host '%s' disallowed by contact ACL (violating IP %s)\n", host, ast_inet_ntoa(testsin.sin_addr));
12394 ast_string_field_set(peer, fullcontact, "");
12395 ast_string_field_set(pvt, our_contact, "");
12396 return PARSE_REGISTER_DENIED;
12397 }
12398
12399
12400
12401 if (!ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE)) {
12402 peer->addr.sin_family = AF_INET;
12403 memcpy(&peer->addr.sin_addr, hp->h_addr, sizeof(peer->addr.sin_addr));
12404 peer->addr.sin_port = htons(port);
12405 } else {
12406
12407
12408 peer->addr = pvt->recv;
12409 }
12410
12411
12412
12413
12414 if ((peer->socket.type == pvt->socket.type) &&
12415 (peer->addr.sin_addr.s_addr == pvt->recv.sin_addr.s_addr) &&
12416 (peer->addr.sin_port == pvt->recv.sin_port)){
12417
12418 copy_socket_data(&peer->socket, &pvt->socket);
12419 }
12420
12421
12422 ao2_t_link(peers_by_ip, peer, "ao2_link into peers_by_ip table");
12423
12424
12425 peer->sipoptions = pvt->sipoptions;
12426
12427 if (!ast_strlen_zero(curi) && ast_strlen_zero(peer->username))
12428 ast_string_field_set(peer, username, curi);
12429
12430 AST_SCHED_DEL_UNREF(sched, peer->expire,
12431 unref_peer(peer, "remove register expire ref"));
12432
12433 if (expire > max_expiry)
12434 expire = max_expiry;
12435 if (expire < min_expiry)
12436 expire = min_expiry;
12437 if (peer->is_realtime && !ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
12438 peer->expire = -1;
12439 } else {
12440 peer->expire = ast_sched_add(sched, (expire + 10) * 1000, expire_register,
12441 ref_peer(peer, "add registration ref"));
12442 if (peer->expire == -1) {
12443 unref_peer(peer, "remote registration ref");
12444 }
12445 }
12446 pvt->expiry = expire;
12447 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);
12448
12449
12450
12451
12452 if (!peer->rt_fromcontact && (peer->socket.type & SIP_TRANSPORT_UDP))
12453 ast_db_put("SIP/Registry", peer->name, data);
12454 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));
12455
12456
12457 if (VERBOSITY_ATLEAST(2) && inaddrcmp(&peer->addr, &oldsin)) {
12458 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));
12459 }
12460 sip_poke_peer(peer, 0);
12461 register_peer_exten(peer, 1);
12462
12463
12464 useragent = get_header(req, "User-Agent");
12465 if (strcasecmp(useragent, peer->useragent)) {
12466 ast_string_field_set(peer, useragent, useragent);
12467 ast_verb(4, "Saved useragent \"%s\" for peer %s\n", peer->useragent, peer->name);
12468 }
12469 return PARSE_REGISTER_UPDATE;
12470 }
12471
12472
12473 static void free_old_route(struct sip_route *route)
12474 {
12475 struct sip_route *next;
12476
12477 while (route) {
12478 next = route->next;
12479 ast_free(route);
12480 route = next;
12481 }
12482 }
12483
12484
12485 static void list_route(struct sip_route *route)
12486 {
12487 if (!route)
12488 ast_verbose("list_route: no route\n");
12489 else {
12490 for (;route; route = route->next)
12491 ast_verbose("list_route: hop: <%s>\n", route->hop);
12492 }
12493 }
12494
12495
12496 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards)
12497 {
12498 struct sip_route *thishop, *head, *tail;
12499 int start = 0;
12500 int len;
12501 const char *rr, *contact, *c;
12502
12503
12504 if (p->route && p->route_persistant) {
12505 ast_debug(1, "build_route: Retaining previous route: <%s>\n", p->route->hop);
12506 return;
12507 }
12508
12509 if (p->route) {
12510 free_old_route(p->route);
12511 p->route = NULL;
12512 }
12513
12514
12515 p->route_persistant = 1;
12516
12517
12518
12519
12520
12521
12522 head = NULL;
12523 tail = head;
12524
12525 for (;;) {
12526
12527 rr = __get_header(req, "Record-Route", &start);
12528 if (*rr == '\0')
12529 break;
12530 for (; (rr = strchr(rr, '<')) ; rr += len) {
12531 ++rr;
12532 len = strcspn(rr, ">") + 1;
12533
12534 if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
12535
12536 ast_copy_string(thishop->hop, rr, len);
12537 ast_debug(2, "build_route: Record-Route hop: <%s>\n", thishop->hop);
12538
12539 if (backwards) {
12540
12541 thishop->next = head;
12542 head = thishop;
12543
12544 if (!tail)
12545 tail = thishop;
12546 } else {
12547 thishop->next = NULL;
12548
12549 if (tail)
12550 tail->next = thishop;
12551 else
12552 head = thishop;
12553 tail = thishop;
12554 }
12555 }
12556 }
12557 }
12558
12559
12560 if (!head || (!ast_strlen_zero(head->hop) && strstr(head->hop, ";lr") == NULL) ) {
12561
12562
12563 contact = get_header(req, "Contact");
12564 if (!ast_strlen_zero(contact)) {
12565 ast_debug(2, "build_route: Contact hop: %s\n", contact);
12566
12567 c = strchr(contact, '<');
12568 if (c) {
12569
12570 ++c;
12571 len = strcspn(c, ">") + 1;
12572 } else {
12573
12574 c = contact;
12575 len = strlen(contact) + 1;
12576 }
12577 if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
12578
12579 ast_copy_string(thishop->hop, c, len);
12580 thishop->next = NULL;
12581
12582 if (tail)
12583 tail->next = thishop;
12584 else
12585 head = thishop;
12586 }
12587 }
12588 }
12589
12590
12591 p->route = head;
12592
12593
12594 if (sip_debug_test_pvt(p))
12595 list_route(p->route);
12596 }
12597
12598
12599
12600
12601
12602
12603
12604 static void set_nonce_randdata(struct sip_pvt *p, int forceupdate)
12605 {
12606 if (p->stalenonce || forceupdate || ast_strlen_zero(p->randdata)) {
12607 ast_string_field_build(p, randdata, "%08lx", ast_random());
12608 p->stalenonce = 0;
12609 }
12610 }
12611
12612 AST_THREADSTORAGE(check_auth_buf);
12613 #define CHECK_AUTH_BUF_INITLEN 256
12614
12615
12616
12617
12618
12619
12620 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
12621 const char *secret, const char *md5secret, int sipmethod,
12622 char *uri, enum xmittype reliable, int ignore)
12623 {
12624 const char *response;
12625 char *reqheader, *respheader;
12626 const char *authtoken;
12627 char a1_hash[256];
12628 char resp_hash[256]="";
12629 char *c;
12630 int wrongnonce = FALSE;
12631 int good_response;
12632 const char *usednonce = p->randdata;
12633 struct ast_str *buf;
12634 int res;
12635
12636
12637 enum keys { K_RESP, K_URI, K_USER, K_NONCE, K_LAST };
12638 struct x {
12639 const char *key;
12640 const char *s;
12641 } *i, keys[] = {
12642 [K_RESP] = { "response=", "" },
12643 [K_URI] = { "uri=", "" },
12644 [K_USER] = { "username=", "" },
12645 [K_NONCE] = { "nonce=", "" },
12646 [K_LAST] = { NULL, NULL}
12647 };
12648
12649
12650 if (ast_strlen_zero(secret) && ast_strlen_zero(md5secret))
12651 return AUTH_SUCCESSFUL;
12652
12653
12654
12655 response = "401 Unauthorized";
12656
12657
12658
12659
12660
12661 auth_headers(WWW_AUTH, &respheader, &reqheader);
12662
12663 authtoken = get_header(req, reqheader);
12664 if (ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
12665
12666
12667 if (!reliable) {
12668
12669
12670 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
12671
12672 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12673 }
12674 return AUTH_CHALLENGE_SENT;
12675 } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
12676
12677 set_nonce_randdata(p, 1);
12678 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
12679
12680 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12681 return AUTH_CHALLENGE_SENT;
12682 }
12683
12684
12685
12686
12687
12688
12689 if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN)))
12690 return AUTH_SECRET_FAILED;
12691
12692
12693 res = ast_str_set(&buf, 0, "%s", authtoken);
12694
12695 if (res == AST_DYNSTR_BUILD_FAILED)
12696 return AUTH_SECRET_FAILED;
12697
12698 c = buf->str;
12699
12700 while(c && *(c = ast_skip_blanks(c)) ) {
12701 for (i = keys; i->key != NULL; i++) {
12702 const char *separator = ",";
12703
12704 if (strncasecmp(c, i->key, strlen(i->key)) != 0)
12705 continue;
12706
12707 c += strlen(i->key);
12708 if (*c == '"') {
12709 c++;
12710 separator = "\"";
12711 }
12712 i->s = c;
12713 strsep(&c, separator);
12714 break;
12715 }
12716 if (i->key == NULL)
12717 strsep(&c, " ,");
12718 }
12719
12720
12721 if (strcmp(username, keys[K_USER].s)) {
12722 ast_log(LOG_WARNING, "username mismatch, have <%s>, digest has <%s>\n",
12723 username, keys[K_USER].s);
12724
12725 return AUTH_USERNAME_MISMATCH;
12726 }
12727
12728
12729
12730 if (strcasecmp(p->randdata, keys[K_NONCE].s) || p->stalenonce) {
12731 wrongnonce = TRUE;
12732 usednonce = keys[K_NONCE].s;
12733 } else {
12734 p->stalenonce = 1;
12735 }
12736
12737 if (!ast_strlen_zero(md5secret))
12738 ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
12739 else {
12740 char a1[256];
12741 snprintf(a1, sizeof(a1), "%s:%s:%s", username, sip_cfg.realm, secret);
12742 ast_md5_hash(a1_hash, a1);
12743 }
12744
12745
12746 {
12747 char a2[256];
12748 char a2_hash[256];
12749 char resp[256];
12750
12751 snprintf(a2, sizeof(a2), "%s:%s", sip_methods[sipmethod].text,
12752 S_OR(keys[K_URI].s, uri));
12753 ast_md5_hash(a2_hash, a2);
12754 snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, usednonce, a2_hash);
12755 ast_md5_hash(resp_hash, resp);
12756 }
12757
12758 good_response = keys[K_RESP].s &&
12759 !strncasecmp(keys[K_RESP].s, resp_hash, strlen(resp_hash));
12760 if (wrongnonce) {
12761 if (good_response) {
12762 if (sipdebug)
12763 ast_log(LOG_NOTICE, "Correct auth, but based on stale nonce received from '%s'\n", get_header(req, "To"));
12764
12765 set_nonce_randdata(p, 0);
12766 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, TRUE);
12767 } else {
12768
12769 if (!req->ignore) {
12770 if (sipdebug)
12771 ast_log(LOG_NOTICE, "Bad authentication received from '%s'\n", get_header(req, "To"));
12772 set_nonce_randdata(p, 1);
12773 } else {
12774 if (sipdebug)
12775 ast_log(LOG_NOTICE, "Duplicate authentication received from '%s'\n", get_header(req, "To"));
12776 }
12777 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
12778 }
12779
12780
12781 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12782 return AUTH_CHALLENGE_SENT;
12783 }
12784 if (good_response) {
12785 append_history(p, "AuthOK", "Auth challenge succesful for %s", username);
12786 return AUTH_SUCCESSFUL;
12787 }
12788
12789
12790
12791
12792
12793
12794 return AUTH_SECRET_FAILED;
12795 }
12796
12797
12798 static void sip_peer_hold(struct sip_pvt *p, int hold)
12799 {
12800 struct sip_peer *peer = find_peer(p->peername, NULL, 1, FINDALLDEVICES, FALSE, 0);
12801
12802 if (!peer)
12803 return;
12804
12805
12806 ast_atomic_fetchadd_int(&peer->onHold, (hold ? +1 : -1));
12807
12808
12809 ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
12810 unref_peer(peer, "sip_peer_hold: from find_peer operation");
12811
12812 return;
12813 }
12814
12815
12816 static void mwi_event_cb(const struct ast_event *event, void *userdata)
12817 {
12818 struct sip_peer *peer = userdata;
12819
12820 ao2_lock(peer);
12821 sip_send_mwi_to_peer(peer, event, 0);
12822 ao2_unlock(peer);
12823 }
12824
12825
12826
12827
12828 static int cb_extensionstate(char *context, char* exten, int state, void *data)
12829 {
12830 struct sip_pvt *p = data;
12831
12832 sip_pvt_lock(p);
12833
12834 switch(state) {
12835 case AST_EXTENSION_DEACTIVATED:
12836 case AST_EXTENSION_REMOVED:
12837 if (p->autokillid > -1 && sip_cancel_destroy(p))
12838 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
12839 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12840 ast_verb(2, "Extension state: Watcher for hint %s %s. Notify User %s\n", exten, state == AST_EXTENSION_DEACTIVATED ? "deactivated" : "removed", p->username);
12841 p->stateid = -1;
12842 p->subscribed = NONE;
12843 append_history(p, "Subscribestatus", "%s", state == AST_EXTENSION_REMOVED ? "HintRemoved" : "Deactivated");
12844 break;
12845 default:
12846 p->laststate = state;
12847 break;
12848 }
12849 if (p->subscribed != NONE) {
12850 if (!p->pendinginvite) {
12851 transmit_state_notify(p, state, 1, FALSE);
12852 } else {
12853
12854
12855 ast_set_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
12856 }
12857 }
12858 ast_verb(2, "Extension Changed %s[%s] new state %s for Notify User %s %s\n", exten, context, ast_extension_state2str(state), p->username,
12859 ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE) ? "(queued)" : "");
12860
12861 sip_pvt_unlock(p);
12862
12863 return 0;
12864 }
12865
12866
12867
12868
12869 static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable)
12870 {
12871
12872
12873 const char *response = "407 Proxy Authentication Required";
12874 const char *reqheader = "Proxy-Authorization";
12875 const char *respheader = "Proxy-Authenticate";
12876 const char *authtoken;
12877 struct ast_str *buf;
12878 char *c;
12879
12880
12881 enum keys { K_NONCE, K_LAST };
12882 struct x {
12883 const char *key;
12884 const char *s;
12885 } *i, keys[] = {
12886 [K_NONCE] = { "nonce=", "" },
12887 [K_LAST] = { NULL, NULL}
12888 };
12889
12890 if (sipmethod == SIP_REGISTER || sipmethod == SIP_SUBSCRIBE) {
12891 response = "401 Unauthorized";
12892 reqheader = "Authorization";
12893 respheader = "WWW-Authenticate";
12894 }
12895 authtoken = get_header(req, reqheader);
12896 if (req->ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
12897
12898
12899 transmit_response_with_auth(p, response, req, p->randdata, 0, respheader, 0);
12900
12901 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12902 return;
12903 } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
12904
12905 set_nonce_randdata(p, 1);
12906 transmit_response_with_auth(p, response, req, p->randdata, 0, respheader, 0);
12907
12908 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12909 return;
12910 }
12911
12912 if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN))) {
12913 transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
12914 return;
12915 }
12916
12917
12918 if (ast_str_set(&buf, 0, "%s", authtoken) == AST_DYNSTR_BUILD_FAILED) {
12919 transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
12920 return;
12921 }
12922
12923 c = buf->str;
12924
12925 while (c && *(c = ast_skip_blanks(c))) {
12926 for (i = keys; i->key != NULL; i++) {
12927 const char *separator = ",";
12928
12929 if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
12930 continue;
12931 }
12932
12933 c += strlen(i->key);
12934 if (*c == '"') {
12935 c++;
12936 separator = "\"";
12937 }
12938 i->s = c;
12939 strsep(&c, separator);
12940 break;
12941 }
12942 if (i->key == NULL) {
12943 strsep(&c, " ,");
12944 }
12945 }
12946
12947
12948 if (strcasecmp(p->randdata, keys[K_NONCE].s)) {
12949 if (!req->ignore) {
12950 set_nonce_randdata(p, 1);
12951 }
12952 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
12953
12954
12955 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12956 } else {
12957 transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
12958 }
12959 }
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975 static char *terminate_uri(char *uri)
12976 {
12977 char *t = uri;
12978 while (*t && *t > ' ' && *t != ';')
12979 t++;
12980 *t = '\0';
12981 return uri;
12982 }
12983
12984
12985
12986
12987
12988
12989 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
12990 struct sip_request *req, char *uri)
12991 {
12992 enum check_auth_result res = AUTH_NOT_FOUND;
12993 struct sip_peer *peer;
12994 char tmp[256];
12995 char *name, *c;
12996 char *domain;
12997
12998 terminate_uri(uri);
12999
13000 ast_copy_string(tmp, get_header(req, "To"), sizeof(tmp));
13001 if (sip_cfg.pedanticsipchecking)
13002 ast_uri_decode(tmp);
13003
13004 c = get_in_brackets(tmp);
13005 c = remove_uri_parameters(c);
13006
13007 if (!strncasecmp(c, "sip:", 4)) {
13008 name = c + 4;
13009 } else if (!strncasecmp(c, "sips:", 5)) {
13010 name = c + 5;
13011 } else {
13012 name = c;
13013 ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, ast_inet_ntoa(sin->sin_addr));
13014 }
13015
13016
13017
13018
13019
13020 if ((c = strchr(name, '@'))) {
13021 *c++ = '\0';
13022 domain = c;
13023 if ((c = strchr(domain, ':')))
13024 *c = '\0';
13025 if (!AST_LIST_EMPTY(&domain_list)) {
13026 if (!check_sip_domain(domain, NULL, 0)) {
13027 transmit_response(p, "404 Not found (unknown domain)", &p->initreq);
13028 return AUTH_UNKNOWN_DOMAIN;
13029 }
13030 }
13031 }
13032 c = strchr(name, ';');
13033 if (c)
13034 *c = '\0';
13035
13036 ast_string_field_set(p, exten, name);
13037 build_contact(p);
13038 if (req->ignore) {
13039
13040 const char *expires = get_header(req, "Expires");
13041 int expire = atoi(expires);
13042
13043 if (ast_strlen_zero(expires)) {
13044 if ((expires = strcasestr(get_header(req, "Contact"), ";expires="))) {
13045 expire = atoi(expires + 9);
13046 }
13047 }
13048 if (!ast_strlen_zero(expires) && expire == 0) {
13049 transmit_response_with_date(p, "200 OK", req);
13050 return 0;
13051 }
13052 }
13053 peer = find_peer(name, NULL, TRUE, FINDPEERS, FALSE, 0);
13054 if (!(peer && ast_apply_ha(peer->ha, sin))) {
13055
13056 if (peer) {
13057 unref_peer(peer, "register_verify: unref_peer: from find_peer operation");
13058 peer = NULL;
13059 res = AUTH_ACL_FAILED;
13060 } else
13061 res = AUTH_NOT_FOUND;
13062 }
13063
13064 if (peer) {
13065
13066
13067 if (p->rtp) {
13068 ast_rtp_codec_setpref(p->rtp, &peer->prefs);
13069 p->autoframing = peer->autoframing;
13070 }
13071 if (!peer->host_dynamic) {
13072 ast_log(LOG_ERROR, "Peer '%s' is trying to register, but not configured as host=dynamic\n", peer->name);
13073 res = AUTH_PEER_NOT_DYNAMIC;
13074 } else {
13075 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_NAT);
13076 if (ast_test_flag(&p->flags[1], SIP_PAGE2_REGISTERTRYING))
13077 transmit_response(p, "100 Trying", req);
13078 if (!(res = check_auth(p, req, peer->name, peer->secret, peer->md5secret, SIP_REGISTER, uri, XMIT_UNRELIABLE, req->ignore))) {
13079 if (sip_cancel_destroy(p))
13080 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
13081
13082 if (check_request_transport(peer, req)) {
13083 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
13084 transmit_response_with_date(p, "403 Forbidden", req);
13085 res = AUTH_BAD_TRANSPORT;
13086 } else {
13087
13088
13089
13090 switch (parse_register_contact(p, peer, req)) {
13091 case PARSE_REGISTER_DENIED:
13092 ast_log(LOG_WARNING, "Registration denied because of contact ACL\n");
13093 transmit_response_with_date(p, "603 Denied", req);
13094 peer->lastmsgssent = -1;
13095 res = 0;
13096 break;
13097 case PARSE_REGISTER_FAILED:
13098 ast_log(LOG_WARNING, "Failed to parse contact info\n");
13099 transmit_response_with_date(p, "400 Bad Request", req);
13100 peer->lastmsgssent = -1;
13101 res = 0;
13102 break;
13103 case PARSE_REGISTER_QUERY:
13104 ast_string_field_set(p, fullcontact, peer->fullcontact);
13105 transmit_response_with_date(p, "200 OK", req);
13106 peer->lastmsgssent = -1;
13107 res = 0;
13108 break;
13109 case PARSE_REGISTER_UPDATE:
13110 ast_string_field_set(p, fullcontact, peer->fullcontact);
13111 update_peer(peer, p->expiry);
13112
13113 transmit_response_with_date(p, "200 OK", req);
13114 if (!ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY))
13115 peer->lastmsgssent = -1;
13116 res = 0;
13117 break;
13118 }
13119 }
13120
13121 }
13122 }
13123 }
13124 if (!peer && sip_cfg.autocreatepeer) {
13125
13126 peer = temp_peer(name);
13127 if (peer) {
13128 ao2_t_link(peers, peer, "link peer into peer table");
13129 if (peer->addr.sin_addr.s_addr) {
13130 ao2_t_link(peers_by_ip, peer, "link peer into peers-by-ip table");
13131 }
13132
13133 if (sip_cancel_destroy(p))
13134 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
13135 switch (parse_register_contact(p, peer, req)) {
13136 case PARSE_REGISTER_DENIED:
13137 ast_log(LOG_WARNING, "Registration denied because of contact ACL\n");
13138 transmit_response_with_date(p, "403 Forbidden (ACL)", req);
13139 peer->lastmsgssent = -1;
13140 res = 0;
13141 break;
13142 case PARSE_REGISTER_FAILED:
13143 ast_log(LOG_WARNING, "Failed to parse contact info\n");
13144 transmit_response_with_date(p, "400 Bad Request", req);
13145 peer->lastmsgssent = -1;
13146 res = 0;
13147 break;
13148 case PARSE_REGISTER_QUERY:
13149 ast_string_field_set(p, fullcontact, peer->fullcontact);
13150 transmit_response_with_date(p, "200 OK", req);
13151 peer->lastmsgssent = -1;
13152 res = 0;
13153 break;
13154 case PARSE_REGISTER_UPDATE:
13155 ast_string_field_set(p, fullcontact, peer->fullcontact);
13156
13157 transmit_response_with_date(p, "200 OK", req);
13158 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));
13159 peer->lastmsgssent = -1;
13160 res = 0;
13161 break;
13162 }
13163 }
13164 }
13165 if (!peer && sip_cfg.alwaysauthreject) {
13166
13167
13168
13169 transmit_response(p, "100 Trying", req);
13170
13171 sched_yield();
13172 }
13173 if (!res) {
13174 ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
13175 }
13176 if (res < 0) {
13177 switch (res) {
13178 case AUTH_SECRET_FAILED:
13179
13180 transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
13181 if (global_authfailureevents)
13182 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",
13183 name, ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
13184 break;
13185 case AUTH_USERNAME_MISMATCH:
13186
13187
13188
13189
13190 case AUTH_NOT_FOUND:
13191 case AUTH_PEER_NOT_DYNAMIC:
13192 case AUTH_ACL_FAILED:
13193 if (sip_cfg.alwaysauthreject) {
13194 transmit_fake_auth_response(p, SIP_REGISTER, &p->initreq, XMIT_UNRELIABLE);
13195 if (global_authfailureevents) {
13196 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",
13197 name, res == AUTH_PEER_NOT_DYNAMIC ? "AUTH_PEER_NOT_DYNAMIC" : "URI_NOT_FOUND",
13198 ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
13199 }
13200 } else {
13201
13202 if (res == AUTH_PEER_NOT_DYNAMIC) {
13203 transmit_response(p, "403 Forbidden", &p->initreq);
13204 if (global_authfailureevents) {
13205 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
13206 "ChannelType: SIP\r\n"
13207 "Peer: SIP/%s\r\n"
13208 "PeerStatus: Rejected\r\n"
13209 "Cause: AUTH_PEER_NOT_DYNAMIC\r\n"
13210 "Address: %s\r\n"
13211 "Port: %d\r\n",
13212 name, ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
13213 }
13214 } else {
13215 transmit_response(p, "404 Not found", &p->initreq);
13216 if (global_authfailureevents) {
13217 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
13218 "ChannelType: SIP\r\n"
13219 "Peer: SIP/%s\r\n"
13220 "PeerStatus: Rejected\r\n"
13221 "Cause: %s\r\n"
13222 "Address: %s\r\n"
13223 "Port: %d\r\n",
13224 name,
13225 (res == AUTH_USERNAME_MISMATCH) ? "AUTH_USERNAME_MISMATCH" : "URI_NOT_FOUND",
13226 ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
13227 }
13228 }
13229 }
13230 break;
13231 case AUTH_BAD_TRANSPORT:
13232 default:
13233 break;
13234 }
13235 }
13236 if (peer)
13237 unref_peer(peer, "register_verify: unref_peer: tossing stack peer pointer at end of func");
13238
13239 return res;
13240 }
13241
13242
13243 static void sip_set_redirstr(struct sip_pvt *p, char *reason) {
13244
13245 if (!strcmp(reason, "unknown")) {
13246 ast_string_field_set(p, redircause, "UNKNOWN");
13247 } else if (!strcmp(reason, "user-busy")) {
13248 ast_string_field_set(p, redircause, "BUSY");
13249 } else if (!strcmp(reason, "no-answer")) {
13250 ast_string_field_set(p, redircause, "NOANSWER");
13251 } else if (!strcmp(reason, "unavailable")) {
13252 ast_string_field_set(p, redircause, "UNREACHABLE");
13253 } else if (!strcmp(reason, "unconditional")) {
13254 ast_string_field_set(p, redircause, "UNCONDITIONAL");
13255 } else if (!strcmp(reason, "time-of-day")) {
13256 ast_string_field_set(p, redircause, "UNKNOWN");
13257 } else if (!strcmp(reason, "do-not-disturb")) {
13258 ast_string_field_set(p, redircause, "UNKNOWN");
13259 } else if (!strcmp(reason, "deflection")) {
13260 ast_string_field_set(p, redircause, "UNKNOWN");
13261 } else if (!strcmp(reason, "follow-me")) {
13262 ast_string_field_set(p, redircause, "UNKNOWN");
13263 } else if (!strcmp(reason, "out-of-service")) {
13264 ast_string_field_set(p, redircause, "UNREACHABLE");
13265 } else if (!strcmp(reason, "away")) {
13266 ast_string_field_set(p, redircause, "UNREACHABLE");
13267 } else {
13268 ast_string_field_set(p, redircause, "UNKNOWN");
13269 }
13270 }
13271
13272
13273 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq)
13274 {
13275 char tmp[256], *exten, *rexten, *rdomain;
13276 char *params, *reason = NULL;
13277 struct sip_request *req;
13278
13279 req = oreq ? oreq : &p->initreq;
13280
13281 ast_copy_string(tmp, get_header(req, "Diversion"), sizeof(tmp));
13282 if (ast_strlen_zero(tmp))
13283 return 0;
13284
13285
13286
13287
13288 params = strchr(tmp, ';');
13289
13290 exten = get_in_brackets(tmp);
13291 if (!strncasecmp(exten, "sip:", 4)) {
13292 exten += 4;
13293 } else if (!strncasecmp(exten, "sips:", 5)) {
13294 exten += 5;
13295 } else {
13296 ast_log(LOG_WARNING, "Huh? Not an RDNIS SIP header (%s)?\n", exten);
13297 return -1;
13298 }
13299
13300
13301 if (params) {
13302 *params = '\0';
13303 params++;
13304 while (*params == ';' || *params == ' ')
13305 params++;
13306
13307 if ((reason = strcasestr(params, "reason="))) {
13308 reason+=7;
13309
13310 if (*reason == '"')
13311 ast_strip_quoted(reason, "\"", "\"");
13312 if (!ast_strlen_zero(reason)) {
13313 sip_set_redirstr(p, reason);
13314 if (p->owner) {
13315 pbx_builtin_setvar_helper(p->owner, "__PRIREDIRECTREASON", p->redircause);
13316 pbx_builtin_setvar_helper(p->owner, "__SIPREDIRECTREASON", reason);
13317 }
13318 }
13319 }
13320 }
13321
13322 rdomain = exten;
13323 rexten = strsep(&rdomain, "@");
13324 if (p->owner)
13325 pbx_builtin_setvar_helper(p->owner, "__SIPRDNISDOMAIN", rdomain);
13326
13327 if (sip_debug_test_pvt(p))
13328 ast_verbose("RDNIS for this call is is %s (reason %s)\n", exten, reason ? reason : "");
13329
13330 ast_string_field_set(p, rdnis, rexten);
13331
13332 return 0;
13333 }
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347 static int get_destination(struct sip_pvt *p, struct sip_request *oreq)
13348 {
13349 char tmp[256] = "", *uri, *a;
13350 char tmpf[256] = "", *from = NULL;
13351 struct sip_request *req;
13352 char *colon;
13353 char *decoded_uri;
13354
13355 req = oreq;
13356 if (!req)
13357 req = &p->initreq;
13358
13359
13360 if (req->rlPart2)
13361 ast_copy_string(tmp, REQ_OFFSET_TO_STR(req, rlPart2), sizeof(tmp));
13362
13363 if (sip_cfg.pedanticsipchecking)
13364 ast_uri_decode(tmp);
13365
13366 uri = get_in_brackets(tmp);
13367
13368 if (!strncasecmp(uri, "sip:", 4)) {
13369 uri += 4;
13370 } else if (!strncasecmp(uri, "sips:", 5)) {
13371 uri += 5;
13372 } else {
13373 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", uri);
13374 return -1;
13375 }
13376
13377
13378
13379
13380
13381 ast_copy_string(tmpf, get_header(req, "From"), sizeof(tmpf));
13382 if (!ast_strlen_zero(tmpf)) {
13383 if (sip_cfg.pedanticsipchecking)
13384 ast_uri_decode(tmpf);
13385 from = get_in_brackets(tmpf);
13386 }
13387
13388 if (!ast_strlen_zero(from)) {
13389 if (!strncasecmp(from, "sip:", 4)) {
13390 from += 4;
13391 } else if (!strncasecmp(from, "sips:", 5)) {
13392 from += 5;
13393 } else {
13394 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", from);
13395 return -1;
13396 }
13397 if ((a = strchr(from, '@')))
13398 *a++ = '\0';
13399 else
13400 a = from;
13401 from = strsep(&from, ";");
13402 a = strsep(&a, ";");
13403 ast_string_field_set(p, fromdomain, a);
13404 }
13405
13406
13407
13408
13409 if ((a = strchr(uri, '@'))) {
13410 *a++ = '\0';
13411 } else {
13412 a = uri;
13413 uri = "s";
13414 }
13415 colon = strchr(a, ':');
13416 if (colon)
13417 *colon = '\0';
13418
13419 uri = strsep(&uri, ";");
13420 a = strsep(&a, ";");
13421
13422 ast_string_field_set(p, domain, a);
13423
13424 if (!AST_LIST_EMPTY(&domain_list)) {
13425 char domain_context[AST_MAX_EXTENSION];
13426
13427 domain_context[0] = '\0';
13428 if (!check_sip_domain(p->domain, domain_context, sizeof(domain_context))) {
13429 if (!sip_cfg.allow_external_domains && (req->method == SIP_INVITE || req->method == SIP_REFER)) {
13430 ast_debug(1, "Got SIP %s to non-local domain '%s'; refusing request.\n", sip_methods[req->method].text, p->domain);
13431 return -2;
13432 }
13433 }
13434
13435
13436 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_HAVEPEERCONTEXT) && !ast_strlen_zero(domain_context))
13437 ast_string_field_set(p, context, domain_context);
13438 }
13439
13440
13441 if (req->method == SIP_SUBSCRIBE && !ast_strlen_zero(p->subscribecontext))
13442 ast_string_field_set(p, context, p->subscribecontext);
13443
13444 if (sip_debug_test_pvt(p))
13445 ast_verbose("Looking for %s in %s (domain %s)\n", uri, p->context, p->domain);
13446
13447
13448 if (req->method == SIP_SUBSCRIBE) {
13449 char hint[AST_MAX_EXTENSION];
13450 return (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, p->exten) ? 0 : -1);
13451 } else {
13452 decoded_uri = ast_strdupa(uri);
13453 ast_uri_decode(decoded_uri);
13454
13455
13456
13457
13458
13459 if (ast_exists_extension(NULL, p->context, uri, 1, S_OR(p->cid_num, from)) || ast_exists_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from)) ||
13460 !strcmp(decoded_uri, ast_pickup_ext())) {
13461 if (!oreq)
13462 ast_string_field_set(p, exten, decoded_uri);
13463 return 0;
13464 }
13465 }
13466
13467
13468 if((ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP) &&
13469 ast_canmatch_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from))) ||
13470 !strncmp(decoded_uri, ast_pickup_ext(), strlen(decoded_uri))) {
13471 return 1;
13472 }
13473
13474 return -1;
13475 }
13476
13477
13478
13479
13480 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag)
13481 {
13482 struct sip_pvt *sip_pvt_ptr;
13483 struct sip_pvt tmp_dialog = {
13484 .callid = callid,
13485 };
13486
13487 if (totag)
13488 ast_debug(4, "Looking for callid %s (fromtag %s totag %s)\n", callid, fromtag ? fromtag : "<no fromtag>", totag ? totag : "<no totag>");
13489
13490
13491
13492 sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find of dialog in dialogs table");
13493 if (sip_pvt_ptr) {
13494
13495 sip_pvt_lock(sip_pvt_ptr);
13496 if (sip_cfg.pedanticsipchecking) {
13497 unsigned char frommismatch = 0, tomismatch = 0;
13498
13499 if (ast_strlen_zero(fromtag)) {
13500 sip_pvt_unlock(sip_pvt_ptr);
13501 ast_debug(4, "Matched %s call for callid=%s - no from tag specified, pedantic check fails\n",
13502 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
13503 return NULL;
13504 }
13505
13506 if (ast_strlen_zero(totag)) {
13507 sip_pvt_unlock(sip_pvt_ptr);
13508 ast_debug(4, "Matched %s call for callid=%s - no to tag specified, pedantic check fails\n",
13509 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
13510 return NULL;
13511 }
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526 frommismatch = !!strcmp(fromtag, sip_pvt_ptr->theirtag);
13527 tomismatch = !!strcmp(totag, sip_pvt_ptr->tag);
13528
13529 if (frommismatch || tomismatch) {
13530 sip_pvt_unlock(sip_pvt_ptr);
13531 if (frommismatch) {
13532 ast_debug(4, "Matched %s call for callid=%s - pedantic from tag check fails; their tag is %s our tag is %s\n",
13533 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid,
13534 fromtag, sip_pvt_ptr->theirtag);
13535 }
13536 if (tomismatch) {
13537 ast_debug(4, "Matched %s call for callid=%s - pedantic to tag check fails; their tag is %s our tag is %s\n",
13538 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid,
13539 totag, sip_pvt_ptr->tag);
13540 }
13541 return NULL;
13542 }
13543 }
13544
13545 if (totag)
13546 ast_debug(4, "Matched %s call - their tag is %s Our tag is %s\n",
13547 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING",
13548 sip_pvt_ptr->theirtag, sip_pvt_ptr->tag);
13549
13550
13551 while (sip_pvt_ptr->owner && ast_channel_trylock(sip_pvt_ptr->owner)) {
13552 sip_pvt_unlock(sip_pvt_ptr);
13553 usleep(1);
13554 sip_pvt_lock(sip_pvt_ptr);
13555 }
13556 }
13557
13558 return sip_pvt_ptr;
13559 }
13560
13561
13562
13563
13564
13565
13566
13567
13568 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req)
13569 {
13570
13571 const char *p_referred_by = NULL;
13572 char *h_refer_to = NULL;
13573 char *h_referred_by = NULL;
13574 char *refer_to;
13575 const char *p_refer_to;
13576 char *referred_by_uri = NULL;
13577 char *ptr;
13578 struct sip_request *req = NULL;
13579 const char *transfer_context = NULL;
13580 struct sip_refer *referdata;
13581
13582
13583 req = outgoing_req;
13584 referdata = transferer->refer;
13585
13586 if (!req)
13587 req = &transferer->initreq;
13588
13589 p_refer_to = get_header(req, "Refer-To");
13590 if (ast_strlen_zero(p_refer_to)) {
13591 ast_log(LOG_WARNING, "Refer-To Header missing. Skipping transfer.\n");
13592 return -2;
13593 }
13594 h_refer_to = ast_strdupa(p_refer_to);
13595 refer_to = get_in_brackets(h_refer_to);
13596 if (sip_cfg.pedanticsipchecking)
13597 ast_uri_decode(refer_to);
13598
13599 if (!strncasecmp(refer_to, "sip:", 4)) {
13600 refer_to += 4;
13601 } else if (!strncasecmp(refer_to, "sips:", 5)) {
13602 refer_to += 5;
13603 } else {
13604 ast_log(LOG_WARNING, "Can't transfer to non-sip: URI. (Refer-to: %s)?\n", refer_to);
13605 return -3;
13606 }
13607
13608
13609 p_referred_by = get_header(req, "Referred-By");
13610
13611
13612 if (transferer->owner) {
13613 struct ast_channel *peer = ast_bridged_channel(transferer->owner);
13614 if (peer) {
13615 pbx_builtin_setvar_helper(peer, "SIPREFERRINGCONTEXT", transferer->context);
13616 pbx_builtin_setvar_helper(peer, "SIPREFERREDBYHDR", p_referred_by);
13617 }
13618 }
13619
13620 if (!ast_strlen_zero(p_referred_by)) {
13621 char *lessthan;
13622 h_referred_by = ast_strdupa(p_referred_by);
13623 if (sip_cfg.pedanticsipchecking)
13624 ast_uri_decode(h_referred_by);
13625
13626
13627 ast_copy_string(referdata->referred_by_name, h_referred_by, sizeof(referdata->referred_by_name));
13628 if ((lessthan = strchr(referdata->referred_by_name, '<'))) {
13629 *(lessthan - 1) = '\0';
13630 }
13631
13632 referred_by_uri = get_in_brackets(h_referred_by);
13633 if (!strncasecmp(referred_by_uri, "sip:", 4)) {
13634 referred_by_uri += 4;
13635 } else if (!strncasecmp(referred_by_uri, "sips:", 5)) {
13636 referred_by_uri += 5;
13637 } else {
13638 ast_log(LOG_WARNING, "Huh? Not a sip: header (Referred-by: %s). Skipping.\n", referred_by_uri);
13639 referred_by_uri = NULL;
13640 }
13641 }
13642
13643
13644 if ((ptr = strcasestr(refer_to, "replaces="))) {
13645 char *to = NULL, *from = NULL;
13646
13647
13648 referdata->attendedtransfer = 1;
13649 ast_copy_string(referdata->replaces_callid, ptr+9, sizeof(referdata->replaces_callid));
13650 ast_uri_decode(referdata->replaces_callid);
13651 if ((ptr = strchr(referdata->replaces_callid, ';'))) {
13652 *ptr++ = '\0';
13653 }
13654
13655 if (ptr) {
13656
13657 to = strcasestr(ptr, "to-tag=");
13658 from = strcasestr(ptr, "from-tag=");
13659 }
13660
13661
13662 if (to) {
13663 ptr = to + 7;
13664 if ((to = strchr(ptr, '&')))
13665 *to = '\0';
13666 if ((to = strchr(ptr, ';')))
13667 *to = '\0';
13668 ast_copy_string(referdata->replaces_callid_totag, ptr, sizeof(referdata->replaces_callid_totag));
13669 }
13670
13671 if (from) {
13672 ptr = from + 9;
13673 if ((to = strchr(ptr, '&')))
13674 *to = '\0';
13675 if ((to = strchr(ptr, ';')))
13676 *to = '\0';
13677 ast_copy_string(referdata->replaces_callid_fromtag, ptr, sizeof(referdata->replaces_callid_fromtag));
13678 }
13679
13680 if (!sip_cfg.pedanticsipchecking)
13681 ast_debug(2, "Attended transfer: Will use Replace-Call-ID : %s (No check of from/to tags)\n", referdata->replaces_callid );
13682 else
13683 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>" );
13684 }
13685
13686 if ((ptr = strchr(refer_to, '@'))) {
13687 char *urioption = NULL, *domain;
13688 *ptr++ = '\0';
13689
13690 if ((urioption = strchr(ptr, ';')))
13691 *urioption++ = '\0';
13692
13693 domain = ptr;
13694 if ((ptr = strchr(domain, ':')))
13695 *ptr = '\0';
13696
13697
13698 ast_copy_string(referdata->refer_to_domain, domain, sizeof(referdata->refer_to_domain));
13699 if (urioption)
13700 ast_copy_string(referdata->refer_to_urioption, urioption, sizeof(referdata->refer_to_urioption));
13701 }
13702
13703 if ((ptr = strchr(refer_to, ';')))
13704 *ptr = '\0';
13705 ast_copy_string(referdata->refer_to, refer_to, sizeof(referdata->refer_to));
13706
13707 if (referred_by_uri) {
13708 if ((ptr = strchr(referred_by_uri, ';')))
13709 *ptr = '\0';
13710 ast_copy_string(referdata->referred_by, referred_by_uri, sizeof(referdata->referred_by));
13711 } else {
13712 referdata->referred_by[0] = '\0';
13713 }
13714
13715
13716 if (transferer->owner)
13717 transfer_context = pbx_builtin_getvar_helper(transferer->owner, "TRANSFER_CONTEXT");
13718
13719
13720 if (ast_strlen_zero(transfer_context)) {
13721 transfer_context = S_OR(transferer->owner->macrocontext,
13722 S_OR(transferer->context, sip_cfg.default_context));
13723 }
13724
13725 ast_copy_string(referdata->refer_to_context, transfer_context, sizeof(referdata->refer_to_context));
13726
13727
13728 if (referdata->attendedtransfer || ast_exists_extension(NULL, transfer_context, refer_to, 1, NULL) ) {
13729 if (sip_debug_test_pvt(transferer)) {
13730 ast_verbose("SIP transfer to extension %s@%s by %s\n", refer_to, transfer_context, referred_by_uri);
13731 }
13732
13733 return 0;
13734 }
13735 if (sip_debug_test_pvt(transferer))
13736 ast_verbose("Failed SIP Transfer to non-existing extension %s in context %s\n n", refer_to, transfer_context);
13737
13738
13739 return -1;
13740 }
13741
13742
13743
13744
13745
13746 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq)
13747 {
13748 char tmp[256] = "", *c, *a;
13749 struct sip_request *req = oreq ? oreq : &p->initreq;
13750 struct sip_refer *referdata = NULL;
13751 const char *transfer_context = NULL;
13752
13753 if (!p->refer && !sip_refer_allocate(p))
13754 return -1;
13755
13756 referdata = p->refer;
13757
13758 ast_copy_string(tmp, get_header(req, "Also"), sizeof(tmp));
13759 c = get_in_brackets(tmp);
13760
13761 if (sip_cfg.pedanticsipchecking)
13762 ast_uri_decode(c);
13763
13764 if (!strncasecmp(c, "sip:", 4)) {
13765 c += 4;
13766 } else if (!strncasecmp(c, "sips:", 5)) {
13767 c += 5;
13768 } else {
13769 ast_log(LOG_WARNING, "Huh? Not a SIP header in Also: transfer (%s)?\n", c);
13770 return -1;
13771 }
13772
13773 if ((a = strchr(c, ';')))
13774 *a = '\0';
13775
13776 if ((a = strchr(c, '@'))) {
13777 *a++ = '\0';
13778 ast_copy_string(referdata->refer_to_domain, a, sizeof(referdata->refer_to_domain));
13779 }
13780
13781 if (sip_debug_test_pvt(p))
13782 ast_verbose("Looking for %s in %s\n", c, p->context);
13783
13784 if (p->owner)
13785 transfer_context = pbx_builtin_getvar_helper(p->owner, "TRANSFER_CONTEXT");
13786
13787
13788 if (ast_strlen_zero(transfer_context)) {
13789 transfer_context = S_OR(p->owner->macrocontext,
13790 S_OR(p->context, sip_cfg.default_context));
13791 }
13792 if (ast_exists_extension(NULL, transfer_context, c, 1, NULL)) {
13793
13794 ast_debug(1, "SIP Bye-also transfer to Extension %s@%s \n", c, transfer_context);
13795 ast_copy_string(referdata->refer_to, c, sizeof(referdata->refer_to));
13796 ast_copy_string(referdata->referred_by, "", sizeof(referdata->referred_by));
13797 ast_copy_string(referdata->refer_contact, "", sizeof(referdata->refer_contact));
13798 referdata->refer_call = dialog_unref(referdata->refer_call, "unreffing referdata->refer_call");
13799
13800 ast_string_field_set(p, context, transfer_context);
13801 return 0;
13802 } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
13803 return 1;
13804 }
13805
13806 return -1;
13807 }
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819 static attribute_unused void check_via_response(struct sip_pvt *p, struct sip_request *req)
13820 {
13821 char via[256];
13822 char *cur, *opts;
13823
13824 ast_copy_string(via, get_header(req, "Via"), sizeof(via));
13825
13826
13827 opts = strchr(via, ',');
13828 if (opts)
13829 *opts = '\0';
13830
13831
13832 opts = strchr(via, ';');
13833 if (!opts)
13834 return;
13835 *opts++ = '\0';
13836 while ( (cur = strsep(&opts, ";")) ) {
13837 if (!strncmp(cur, "rport=", 6)) {
13838 int port = strtol(cur+6, NULL, 10);
13839
13840 p->ourip.sin_port = ntohs(port);
13841 } else if (!strncmp(cur, "received=", 9)) {
13842 if (ast_parse_arg(cur+9, PARSE_INADDR, &p->ourip))
13843 ;
13844 }
13845 }
13846 }
13847
13848
13849 static void check_via(struct sip_pvt *p, struct sip_request *req)
13850 {
13851 char via[512];
13852 char *c, *pt, *maddr;
13853 struct hostent *hp;
13854 struct ast_hostent ahp;
13855
13856 ast_copy_string(via, get_header(req, "Via"), sizeof(via));
13857
13858
13859 c = strchr(via, ',');
13860 if (c)
13861 *c = '\0';
13862
13863
13864 c = strstr(via, ";rport");
13865 if (c && (c[6] != '='))
13866 ast_set_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT);
13867
13868
13869 maddr = strstr(via, "maddr=");
13870 if (maddr) {
13871 maddr += 6;
13872 c = maddr + strspn(maddr, "0123456789.");
13873 *c = '\0';
13874 }
13875
13876 c = strchr(via, ';');
13877 if (c)
13878 *c = '\0';
13879
13880 c = strchr(via, ' ');
13881 if (c) {
13882 *c = '\0';
13883 c = ast_skip_blanks(c+1);
13884 if (strcasecmp(via, "SIP/2.0/UDP") && strcasecmp(via, "SIP/2.0/TCP") && strcasecmp(via, "SIP/2.0/TLS")) {
13885 ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
13886 return;
13887 }
13888 pt = strchr(c, ':');
13889 if (pt)
13890 *pt++ = '\0';
13891
13892 if (maddr)
13893 c = maddr;
13894 hp = ast_gethostbyname(c, &ahp);
13895 if (!hp) {
13896 ast_log(LOG_WARNING, "'%s' is not a valid host\n", c);
13897 return;
13898 }
13899 memset(&p->sa, 0, sizeof(p->sa));
13900 p->sa.sin_family = AF_INET;
13901 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
13902 p->sa.sin_port = htons(port_str2int(pt, STANDARD_SIP_PORT));
13903
13904 if (sip_debug_test_pvt(p)) {
13905 const struct sockaddr_in *dst = sip_real_dst(p);
13906 ast_verbose("Sending to %s : %d (%s)\n", ast_inet_ntoa(dst->sin_addr), ntohs(dst->sin_port), sip_nat_mode(p));
13907 }
13908 }
13909 }
13910
13911
13912 static char *get_calleridname(const char *input, char *output, size_t outputsize)
13913 {
13914 const char *end = strchr(input, '<');
13915 const char *tmp = strchr(input, '"');
13916 int bytes = 0;
13917 int maxbytes = outputsize - 1;
13918
13919 if (!end || end == input)
13920 return NULL;
13921
13922 end--;
13923
13924 if (tmp && tmp <= end) {
13925
13926
13927
13928 end = strchr(tmp+1, '"');
13929 if (!end)
13930 return NULL;
13931 bytes = (int) (end - tmp);
13932
13933 if (bytes > maxbytes)
13934 bytes = maxbytes;
13935 ast_copy_string(output, tmp + 1, bytes);
13936 } else {
13937
13938
13939 input = ast_skip_blanks(input);
13940
13941 while(*end && *end < 33 && end > input)
13942 end--;
13943 if (end >= input) {
13944 bytes = (int) (end - input) + 2;
13945
13946 if (bytes > maxbytes)
13947 bytes = maxbytes;
13948 ast_copy_string(output, input, bytes);
13949 } else
13950 return NULL;
13951 }
13952 return output;
13953 }
13954
13955
13956
13957
13958
13959 static int get_rpid_num(const char *input, char *output, int maxlen)
13960 {
13961 char *start;
13962 char *end;
13963
13964 start = strchr(input, ':');
13965 if (!start) {
13966 output[0] = '\0';
13967 return 0;
13968 }
13969 start++;
13970
13971
13972 ast_copy_string(output, start, maxlen);
13973 output[maxlen-1] = '\0';
13974
13975 end = strchr(output, '@');
13976 if (end)
13977 *end = '\0';
13978 else
13979 output[0] = '\0';
13980 if (strstr(input, "privacy=full") || strstr(input, "privacy=uri"))
13981 return AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
13982
13983 return 0;
13984 }
13985
13986
13987
13988 static void replace_cid(struct sip_pvt *p, const char *rpid_num, const char *calleridname)
13989 {
13990
13991 if (!ast_strlen_zero(rpid_num) && ast_test_flag(&p->flags[0], SIP_TRUSTRPID)) {
13992 char *tmp = ast_strdupa(rpid_num);
13993 if (!ast_strlen_zero(calleridname))
13994 ast_string_field_set(p, cid_name, calleridname);
13995 if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
13996 ast_shrink_phone_number(tmp);
13997 ast_string_field_set(p, cid_num, tmp);
13998 }
13999 }
14000
14001
14002 static enum check_auth_result check_peer_ok(struct sip_pvt *p, char *of,
14003 struct sip_request *req, int sipmethod, struct sockaddr_in *sin,
14004 struct sip_peer **authpeer,
14005 enum xmittype reliable,
14006 char *rpid_num, char *calleridname, char *uri2)
14007 {
14008 enum check_auth_result res;
14009 int debug=sip_debug_test_addr(sin);
14010 struct sip_peer *peer;
14011
14012 if (sipmethod == SIP_SUBSCRIBE) {
14013
14014
14015
14016 peer = find_peer(of, NULL, TRUE, FINDALLDEVICES, FALSE, 0);
14017 } else {
14018
14019 peer = find_peer(of, NULL, TRUE, FINDUSERS, FALSE, 0);
14020
14021
14022 if (!peer) {
14023 peer = find_peer(NULL, &p->recv, TRUE, FINDPEERS, FALSE, p->socket.type);
14024 }
14025 }
14026
14027 if (!peer) {
14028 if (debug)
14029 ast_verbose("No matching peer for '%s' from '%s:%d'\n",
14030 of, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
14031 return AUTH_DONT_KNOW;
14032 }
14033 if (!ast_apply_ha(peer->ha, sin)) {
14034 ast_debug(2, "Found peer '%s' for '%s', but fails host access\n", peer->name, of);
14035 unref_peer(peer, "unref_peer: check_peer_ok: from find_peer call, early return of AUTH_ACL_FAILED");
14036 return AUTH_ACL_FAILED;
14037 }
14038 if (debug)
14039 ast_verbose("Found peer '%s' for '%s' from %s:%d\n",
14040 peer->name, of, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
14041
14042
14043
14044 if (p->rtp) {
14045 ast_rtp_codec_setpref(p->rtp, &peer->prefs);
14046 p->autoframing = peer->autoframing;
14047 }
14048
14049
14050 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
14051 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
14052
14053 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) && p->udptl) {
14054 p->t38_maxdatagram = peer->t38_maxdatagram;
14055 set_t38_capabilities(p);
14056 }
14057
14058
14059
14060 if (p->sipoptions)
14061 peer->sipoptions = p->sipoptions;
14062
14063 replace_cid(p, rpid_num, calleridname);
14064 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT_ROUTE));
14065
14066 ast_string_field_set(p, peersecret, peer->secret);
14067 ast_string_field_set(p, peermd5secret, peer->md5secret);
14068 ast_string_field_set(p, subscribecontext, peer->subscribecontext);
14069 ast_string_field_set(p, mohinterpret, peer->mohinterpret);
14070 ast_string_field_set(p, mohsuggest, peer->mohsuggest);
14071 ast_string_field_set(p, parkinglot, peer->parkinglot);
14072 if (peer->callingpres)
14073 p->callingpres = peer->callingpres;
14074 if (peer->maxms && peer->lastms)
14075 p->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
14076 else
14077 p->timer_t1 = peer->timer_t1;
14078
14079
14080 if (peer->timer_b)
14081 p->timer_b = peer->timer_b;
14082 else
14083 p->timer_b = 64 * p->timer_t1;
14084
14085 if (ast_test_flag(&peer->flags[0], SIP_INSECURE_INVITE)) {
14086
14087 ast_string_field_set(p, peersecret, NULL);
14088 ast_string_field_set(p, peermd5secret, NULL);
14089 }
14090 if (!(res = check_auth(p, req, peer->name, p->peersecret, p->peermd5secret, sipmethod, uri2, reliable, req->ignore))) {
14091 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
14092 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
14093
14094 if (peer->call_limit)
14095 ast_set_flag(&p->flags[0], SIP_CALL_LIMIT);
14096 ast_string_field_set(p, peername, peer->name);
14097 ast_string_field_set(p, authname, peer->name);
14098
14099 if (sipmethod == SIP_INVITE) {
14100
14101 p->chanvars = copy_vars(peer->chanvars);
14102 }
14103
14104 if (authpeer) {
14105 ao2_t_ref(peer, 1, "copy pointer into (*authpeer)");
14106 (*authpeer) = peer;
14107 }
14108
14109 if (!ast_strlen_zero(peer->username)) {
14110 ast_string_field_set(p, username, peer->username);
14111
14112
14113 ast_string_field_set(p, authname, peer->username);
14114 }
14115 if (!ast_strlen_zero(peer->cid_num)) {
14116 char *tmp = ast_strdupa(peer->cid_num);
14117 if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
14118 ast_shrink_phone_number(tmp);
14119 ast_string_field_set(p, cid_num, tmp);
14120 }
14121 if (!ast_strlen_zero(peer->cid_name))
14122 ast_string_field_set(p, cid_name, peer->cid_name);
14123 ast_string_field_set(p, fullcontact, peer->fullcontact);
14124 if (!ast_strlen_zero(peer->context))
14125 ast_string_field_set(p, context, peer->context);
14126 ast_string_field_set(p, peersecret, peer->secret);
14127 ast_string_field_set(p, peermd5secret, peer->md5secret);
14128 ast_string_field_set(p, language, peer->language);
14129 ast_string_field_set(p, accountcode, peer->accountcode);
14130 p->amaflags = peer->amaflags;
14131 p->callgroup = peer->callgroup;
14132 p->pickupgroup = peer->pickupgroup;
14133 p->capability = peer->capability;
14134 p->prefs = peer->prefs;
14135 p->jointcapability = peer->capability;
14136 if (p->peercapability)
14137 p->jointcapability &= p->peercapability;
14138 p->maxcallbitrate = peer->maxcallbitrate;
14139 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS) &&
14140 (!ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) ||
14141 !(p->capability & AST_FORMAT_VIDEO_MASK)) &&
14142 p->vrtp) {
14143 ast_rtp_destroy(p->vrtp);
14144 p->vrtp = NULL;
14145 }
14146 if ((!ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT) || !(p->capability & AST_FORMAT_TEXT_MASK)) && p->trtp) {
14147 ast_rtp_destroy(p->trtp);
14148 p->trtp = NULL;
14149 }
14150 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
14151 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
14152 p->noncodeccapability |= AST_RTP_DTMF;
14153 else
14154 p->noncodeccapability &= ~AST_RTP_DTMF;
14155 p->jointnoncodeccapability = p->noncodeccapability;
14156 }
14157 unref_peer(peer, "check_peer_ok: unref_peer: tossing temp ptr to peer from find_peer");
14158 return res;
14159 }
14160
14161
14162
14163
14164
14165
14166
14167 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
14168 int sipmethod, char *uri, enum xmittype reliable,
14169 struct sockaddr_in *sin, struct sip_peer **authpeer)
14170 {
14171 char from[256];
14172 char *dummy;
14173 char *domain;
14174 char *of;
14175 char rpid_num[50];
14176 const char *rpid;
14177 enum check_auth_result res;
14178 char calleridname[50];
14179 char *uri2 = ast_strdupa(uri);
14180
14181 terminate_uri(uri2);
14182
14183 ast_copy_string(from, get_header(req, "From"), sizeof(from));
14184 if (sip_cfg.pedanticsipchecking)
14185 ast_uri_decode(from);
14186
14187 memset(calleridname, 0, sizeof(calleridname));
14188 get_calleridname(from, calleridname, sizeof(calleridname));
14189 if (calleridname[0])
14190 ast_string_field_set(p, cid_name, calleridname);
14191
14192 rpid = get_header(req, "Remote-Party-ID");
14193 memset(rpid_num, 0, sizeof(rpid_num));
14194 if (!ast_strlen_zero(rpid))
14195 p->callingpres = get_rpid_num(rpid, rpid_num, sizeof(rpid_num));
14196
14197 of = get_in_brackets(from);
14198 if (ast_strlen_zero(p->exten)) {
14199 char *t = uri2;
14200 if (!strncasecmp(t, "sip:", 4))
14201 t+= 4;
14202 else if (!strncasecmp(t, "sips:", 5))
14203 t += 5;
14204 ast_string_field_set(p, exten, t);
14205 t = strchr(p->exten, '@');
14206 if (t)
14207 *t = '\0';
14208 if (ast_strlen_zero(p->our_contact))
14209 build_contact(p);
14210 }
14211
14212 ast_string_field_set(p, from, of);
14213
14214
14215 if (parse_uri(of, "sip:,sips:", &of, &dummy, &domain, &dummy, &dummy, NULL)) {
14216 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
14217 }
14218
14219 if (ast_strlen_zero(of)) {
14220
14221
14222
14223
14224
14225
14226 of = domain;
14227 } else {
14228 char *tmp = ast_strdupa(of);
14229
14230
14231
14232 tmp = strsep(&tmp, ";");
14233 if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
14234 ast_shrink_phone_number(tmp);
14235 ast_string_field_set(p, cid_num, tmp);
14236 }
14237
14238 if (global_match_auth_username) {
14239
14240
14241
14242
14243
14244
14245
14246
14247 const char *hdr = get_header(req, "Authorization");
14248 if (ast_strlen_zero(hdr))
14249 hdr = get_header(req, "Proxy-Authorization");
14250
14251 if ( !ast_strlen_zero(hdr) && (hdr = strstr(hdr, "username=\"")) ) {
14252 ast_copy_string(from, hdr + strlen("username=\""), sizeof(from));
14253 of = from;
14254 of = strsep(&of, "\"");
14255 }
14256 }
14257
14258 res = check_peer_ok(p, of, req, sipmethod, sin,
14259 authpeer, reliable, rpid_num, calleridname, uri2);
14260 if (res != AUTH_DONT_KNOW)
14261 return res;
14262
14263
14264 if (sip_cfg.allowguest) {
14265 replace_cid(p, rpid_num, calleridname);
14266 res = AUTH_SUCCESSFUL;
14267 } else if (sip_cfg.alwaysauthreject)
14268 res = AUTH_FAKE_AUTH;
14269 else
14270 res = AUTH_SECRET_FAILED;
14271
14272
14273 if (ast_test_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT)) {
14274 ast_set_flag(&p->flags[0], SIP_NAT_ROUTE);
14275 }
14276
14277 return res;
14278 }
14279
14280
14281
14282
14283 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin)
14284 {
14285 return check_user_full(p, req, sipmethod, uri, reliable, sin, NULL);
14286 }
14287
14288
14289 static int get_msg_text(char *buf, int len, struct sip_request *req, int addnewline)
14290 {
14291 int x;
14292 int y;
14293
14294 buf[0] = '\0';
14295
14296 y = len - strlen(buf) - 5;
14297 if (y < 0)
14298 y = 0;
14299 for (x = 0; x < req->lines; x++) {
14300 char *line = REQ_OFFSET_TO_STR(req, line[x]);
14301 strncat(buf, line, y);
14302 y -= strlen(line) + 1;
14303 if (y < 0)
14304 y = 0;
14305 if (y != 0 && addnewline)
14306 strcat(buf, "\n");
14307 }
14308 return 0;
14309 }
14310
14311
14312
14313
14314
14315 static void receive_message(struct sip_pvt *p, struct sip_request *req)
14316 {
14317 char buf[1400];
14318 struct ast_frame f;
14319 const char *content_type = get_header(req, "Content-Type");
14320
14321 if (strncmp(content_type, "text/plain", strlen("text/plain"))) {
14322 transmit_response(p, "415 Unsupported Media Type", req);
14323 if (!p->owner)
14324 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14325 return;
14326 }
14327
14328 if (get_msg_text(buf, sizeof(buf), req, FALSE)) {
14329 ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
14330 transmit_response(p, "202 Accepted", req);
14331 if (!p->owner)
14332 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14333 return;
14334 }
14335
14336 if (p->owner) {
14337 if (sip_debug_test_pvt(p))
14338 ast_verbose("SIP Text message received: '%s'\n", buf);
14339 memset(&f, 0, sizeof(f));
14340 f.frametype = AST_FRAME_TEXT;
14341 f.subclass = 0;
14342 f.offset = 0;
14343 f.data.ptr = buf;
14344 f.datalen = strlen(buf);
14345 ast_queue_frame(p->owner, &f);
14346 transmit_response(p, "202 Accepted", req);
14347 return;
14348 }
14349
14350
14351 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);
14352 transmit_response(p, "405 Method Not Allowed", req);
14353 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14354 return;
14355 }
14356
14357
14358 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14359 {
14360 #define FORMAT "%-25.25s %-15.15s %-15.15s \n"
14361 #define FORMAT2 "%-25.25s %-15.15s %-15.15s \n"
14362 char ilimits[40];
14363 char iused[40];
14364 int showall = FALSE;
14365 struct ao2_iterator i;
14366 struct sip_peer *peer;
14367
14368 switch (cmd) {
14369 case CLI_INIT:
14370 e->command = "sip show inuse";
14371 e->usage =
14372 "Usage: sip show inuse [all]\n"
14373 " List all SIP devices usage counters and limits.\n"
14374 " Add option \"all\" to show all devices, not only those with a limit.\n";
14375 return NULL;
14376 case CLI_GENERATE:
14377 return NULL;
14378 }
14379
14380 if (a->argc < 3)
14381 return CLI_SHOWUSAGE;
14382
14383 if (a->argc == 4 && !strcmp(a->argv[3], "all"))
14384 showall = TRUE;
14385
14386 ast_cli(a->fd, FORMAT, "* Peer name", "In use", "Limit");
14387
14388 i = ao2_iterator_init(peers, 0);
14389 while ((peer = ao2_t_iterator_next(&i, "iterate thru peer table"))) {
14390 ao2_lock(peer);
14391 if (peer->call_limit)
14392 snprintf(ilimits, sizeof(ilimits), "%d", peer->call_limit);
14393 else
14394 ast_copy_string(ilimits, "N/A", sizeof(ilimits));
14395 snprintf(iused, sizeof(iused), "%d/%d/%d", peer->inUse, peer->inRinging, peer->onHold);
14396 if (showall || peer->call_limit)
14397 ast_cli(a->fd, FORMAT2, peer->name, iused, ilimits);
14398 ao2_unlock(peer);
14399 unref_peer(peer, "toss iterator pointer");
14400 }
14401 ao2_iterator_destroy(&i);
14402
14403 return CLI_SUCCESS;
14404 #undef FORMAT
14405 #undef FORMAT2
14406 }
14407
14408
14409
14410 static char *transfermode2str(enum transfermodes mode)
14411 {
14412 if (mode == TRANSFER_OPENFORALL)
14413 return "open";
14414 else if (mode == TRANSFER_CLOSED)
14415 return "closed";
14416 return "strict";
14417 }
14418
14419 static struct _map_x_s natmodes[] = {
14420 { SIP_NAT_NEVER, "No"},
14421 { SIP_NAT_ROUTE, "Route"},
14422 { SIP_NAT_ALWAYS, "Always"},
14423 { SIP_NAT_RFC3581, "RFC3581"},
14424 { -1, NULL},
14425 };
14426
14427
14428 static const char *nat2str(int nat)
14429 {
14430 return map_x_s(natmodes, nat, "Unknown");
14431 }
14432
14433 #ifdef NOTUSED
14434
14435
14436
14437
14438 static struct _map_x_s natcfgmodes[] = {
14439 { SIP_NAT_NEVER, "never"},
14440 { SIP_NAT_ROUTE, "route"},
14441 { SIP_NAT_ALWAYS, "yes"},
14442 { SIP_NAT_RFC3581, "no"},
14443 { -1, NULL},
14444 };
14445
14446
14447 static const char *nat2strconfig(int nat)
14448 {
14449 return map_x_s(natcfgmodes, nat, "Unknown");
14450 }
14451 #endif
14452
14453
14454
14455
14456
14457
14458
14459 static struct _map_x_s stmodes[] = {
14460 { SESSION_TIMER_MODE_ACCEPT, "Accept"},
14461 { SESSION_TIMER_MODE_ORIGINATE, "Originate"},
14462 { SESSION_TIMER_MODE_REFUSE, "Refuse"},
14463 { -1, NULL},
14464 };
14465
14466 static const char *stmode2str(enum st_mode m)
14467 {
14468 return map_x_s(stmodes, m, "Unknown");
14469 }
14470
14471 static enum st_mode str2stmode(const char *s)
14472 {
14473 return map_s_x(stmodes, s, -1);
14474 }
14475
14476
14477 static struct _map_x_s strefreshers[] = {
14478 { SESSION_TIMER_REFRESHER_AUTO, "auto"},
14479 { SESSION_TIMER_REFRESHER_UAC, "uac"},
14480 { SESSION_TIMER_REFRESHER_UAS, "uas"},
14481 { -1, NULL},
14482 };
14483
14484 static const char *strefresher2str(enum st_refresher r)
14485 {
14486 return map_x_s(strefreshers, r, "Unknown");
14487 }
14488
14489 static enum st_refresher str2strefresher(const char *s)
14490 {
14491 return map_s_x(strefreshers, s, -1);
14492 }
14493
14494
14495 static int peer_status(struct sip_peer *peer, char *status, int statuslen)
14496 {
14497 int res = 0;
14498 if (peer->maxms) {
14499 if (peer->lastms < 0) {
14500 ast_copy_string(status, "UNREACHABLE", statuslen);
14501 } else if (peer->lastms > peer->maxms) {
14502 snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
14503 res = 1;
14504 } else if (peer->lastms) {
14505 snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
14506 res = 1;
14507 } else {
14508 ast_copy_string(status, "UNKNOWN", statuslen);
14509 }
14510 } else {
14511 ast_copy_string(status, "Unmonitored", statuslen);
14512
14513 res = -1;
14514 }
14515 return res;
14516 }
14517
14518
14519
14520
14521
14522
14523 static const char *cli_yesno(int x)
14524 {
14525 return x ? "Yes" : "No";
14526 }
14527
14528
14529 static char *sip_show_tcp(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14530 {
14531 struct sip_threadinfo *th;
14532 struct ao2_iterator i;
14533
14534 #define FORMAT2 "%-30.30s %3.6s %9.9s %6.6s\n"
14535 #define FORMAT "%-30.30s %-6d %-9.9s %-6.6s\n"
14536
14537 switch (cmd) {
14538 case CLI_INIT:
14539 e->command = "sip show tcp";
14540 e->usage =
14541 "Usage: sip show tcp\n"
14542 " Lists all active TCP/TLS sessions.\n";
14543 return NULL;
14544 case CLI_GENERATE:
14545 return NULL;
14546 }
14547
14548 if (a->argc != 3)
14549 return CLI_SHOWUSAGE;
14550
14551 ast_cli(a->fd, FORMAT2, "Host", "Port", "Transport", "Type");
14552 i = ao2_iterator_init(threadt, 0);
14553 while ((th = ao2_t_iterator_next(&i, "iterate through tcp threads for 'sip show tcp'"))) {
14554 ast_cli(a->fd, FORMAT, ast_inet_ntoa(th->tcptls_session->remote_address.sin_addr),
14555 ntohs(th->tcptls_session->remote_address.sin_port),
14556 get_transport(th->type),
14557 (th->tcptls_session->client ? "Client" : "Server"));
14558 ao2_t_ref(th, -1, "decrement ref from iterator");
14559 }
14560 ao2_iterator_destroy(&i);
14561 return CLI_SUCCESS;
14562 #undef FORMAT
14563 #undef FORMAT2
14564 }
14565
14566
14567 static char *sip_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14568 {
14569 regex_t regexbuf;
14570 int havepattern = FALSE;
14571 struct ao2_iterator user_iter;
14572 struct sip_peer *user;
14573
14574 #define FORMAT "%-25.25s %-15.15s %-15.15s %-15.15s %-5.5s%-10.10s\n"
14575
14576 switch (cmd) {
14577 case CLI_INIT:
14578 e->command = "sip show users";
14579 e->usage =
14580 "Usage: sip show users [like <pattern>]\n"
14581 " Lists all known SIP users.\n"
14582 " Optional regular expression pattern is used to filter the user list.\n";
14583 return NULL;
14584 case CLI_GENERATE:
14585 return NULL;
14586 }
14587
14588 switch (a->argc) {
14589 case 5:
14590 if (!strcasecmp(a->argv[3], "like")) {
14591 if (regcomp(®exbuf, a->argv[4], REG_EXTENDED | REG_NOSUB))
14592 return CLI_SHOWUSAGE;
14593 havepattern = TRUE;
14594 } else
14595 return CLI_SHOWUSAGE;
14596 case 3:
14597 break;
14598 default:
14599 return CLI_SHOWUSAGE;
14600 }
14601
14602 ast_cli(a->fd, FORMAT, "Username", "Secret", "Accountcode", "Def.Context", "ACL", "NAT");
14603
14604 user_iter = ao2_iterator_init(peers, 0);
14605 while ((user = ao2_iterator_next(&user_iter))) {
14606 ao2_lock(user);
14607 if (!(user->type & SIP_TYPE_USER)) {
14608 ao2_unlock(user);
14609 unref_peer(user, "sip show users");
14610 continue;
14611 }
14612
14613 if (havepattern && regexec(®exbuf, user->name, 0, NULL, 0)) {
14614 ao2_unlock(user);
14615 unref_peer(user, "sip show users");
14616 continue;
14617 }
14618
14619 ast_cli(a->fd, FORMAT, user->name,
14620 user->secret,
14621 user->accountcode,
14622 user->context,
14623 cli_yesno(user->ha != NULL),
14624 nat2str(ast_test_flag(&user->flags[0], SIP_NAT)));
14625 ao2_unlock(user);
14626 unref_peer(user, "sip show users");
14627 }
14628 ao2_iterator_destroy(&user_iter);
14629
14630 if (havepattern)
14631 regfree(®exbuf);
14632
14633 return CLI_SUCCESS;
14634 #undef FORMAT
14635 }
14636
14637
14638 static char mandescr_show_registry[] =
14639 "Description: Lists all registration requests and status\n"
14640 "Registrations will follow as separate events. followed by a final event called\n"
14641 "RegistrationsComplete.\n"
14642 "Variables: \n"
14643 " ActionID: <id> Action ID for this transaction. Will be returned.\n";
14644
14645
14646 static int manager_show_registry(struct mansession *s, const struct message *m)
14647 {
14648 const char *id = astman_get_header(m, "ActionID");
14649 char idtext[256] = "";
14650 int total = 0;
14651
14652 if (!ast_strlen_zero(id))
14653 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
14654
14655 astman_send_listack(s, m, "Registrations will follow", "start");
14656
14657 ASTOBJ_CONTAINER_TRAVERSE(®l, 1, do {
14658 ASTOBJ_RDLOCK(iterator);
14659 astman_append(s,
14660 "Event: RegistryEntry\r\n"
14661 "%s"
14662 "Host: %s\r\n"
14663 "Port: %d\r\n"
14664 "Username: %s\r\n"
14665 "Refresh: %d\r\n"
14666 "State: %s\r\n"
14667 "RegistrationTime: %ld\r\n"
14668 "\r\n", idtext, iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT,
14669 iterator->username, iterator->refresh, regstate2str(iterator->regstate), (long) iterator->regtime.tv_sec);
14670 ASTOBJ_UNLOCK(iterator);
14671 total++;
14672 } while(0));
14673
14674 astman_append(s,
14675 "Event: RegistrationsComplete\r\n"
14676 "EventList: Complete\r\n"
14677 "ListItems: %d\r\n"
14678 "%s"
14679 "\r\n", total, idtext);
14680
14681 return 0;
14682 }
14683
14684 static char mandescr_show_peers[] =
14685 "Description: Lists SIP peers in text format with details on current status.\n"
14686 "Peerlist will follow as separate events, followed by a final event called\n"
14687 "PeerlistComplete.\n"
14688 "Variables: \n"
14689 " ActionID: <id> Action ID for this transaction. Will be returned.\n";
14690
14691
14692
14693 static int manager_sip_show_peers(struct mansession *s, const struct message *m)
14694 {
14695 const char *id = astman_get_header(m, "ActionID");
14696 const char *a[] = {"sip", "show", "peers"};
14697 char idtext[256] = "";
14698 int total = 0;
14699
14700 if (!ast_strlen_zero(id))
14701 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
14702
14703 astman_send_listack(s, m, "Peer status list will follow", "start");
14704
14705 _sip_show_peers(-1, &total, s, m, 3, a);
14706
14707 astman_append(s,
14708 "Event: PeerlistComplete\r\n"
14709 "EventList: Complete\r\n"
14710 "ListItems: %d\r\n"
14711 "%s"
14712 "\r\n", total, idtext);
14713 return 0;
14714 }
14715
14716
14717 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14718 {
14719 switch (cmd) {
14720 case CLI_INIT:
14721 e->command = "sip show peers";
14722 e->usage =
14723 "Usage: sip show peers [like <pattern>]\n"
14724 " Lists all known SIP peers.\n"
14725 " Optional regular expression pattern is used to filter the peer list.\n";
14726 return NULL;
14727 case CLI_GENERATE:
14728 return NULL;
14729 }
14730
14731 return _sip_show_peers(a->fd, NULL, NULL, NULL, a->argc, (const char **) a->argv);
14732 }
14733
14734 int peercomparefunc(const void *a, const void *b);
14735
14736 int peercomparefunc(const void *a, const void *b)
14737 {
14738 struct sip_peer **ap = (struct sip_peer **)a;
14739 struct sip_peer **bp = (struct sip_peer **)b;
14740 return strcmp((*ap)->name, (*bp)->name);
14741 }
14742
14743
14744
14745 static char *_sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[])
14746 {
14747 regex_t regexbuf;
14748 int havepattern = FALSE;
14749 struct sip_peer *peer;
14750 struct ao2_iterator i;
14751
14752
14753 #define FORMAT2 "%-25.25s %-15.15s %-3.3s %-3.3s %-3.3s %-8s %-10s %s\n"
14754 #define FORMAT "%-25.25s %-15.15s %-3.3s %-3.3s %-3.3s %-8d %-10s %s\n"
14755
14756 char name[256];
14757 int total_peers = 0;
14758 int peers_mon_online = 0;
14759 int peers_mon_offline = 0;
14760 int peers_unmon_offline = 0;
14761 int peers_unmon_online = 0;
14762 const char *id;
14763 char idtext[256] = "";
14764 int realtimepeers;
14765 int objcount = ao2_container_count(peers);
14766 struct sip_peer **peerarray;
14767 int k;
14768
14769
14770 realtimepeers = ast_check_realtime("sippeers");
14771 peerarray = ast_calloc(sizeof(struct sip_peer *), objcount);
14772
14773 if (s) {
14774 id = astman_get_header(m, "ActionID");
14775 if (!ast_strlen_zero(id))
14776 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
14777 }
14778
14779 switch (argc) {
14780 case 5:
14781 if (!strcasecmp(argv[3], "like")) {
14782 if (regcomp(®exbuf, argv[4], REG_EXTENDED | REG_NOSUB))
14783 return CLI_SHOWUSAGE;
14784 havepattern = TRUE;
14785 } else
14786 return CLI_SHOWUSAGE;
14787 case 3:
14788 break;
14789 default:
14790 return CLI_SHOWUSAGE;
14791 }
14792
14793 if (!s)
14794 ast_cli(fd, FORMAT2, "Name/username", "Host", "Dyn", "Nat", "ACL", "Port", "Status", (realtimepeers ? "Realtime" : ""));
14795
14796
14797 i = ao2_iterator_init(peers, 0);
14798 while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
14799 ao2_lock(peer);
14800
14801 if (!(peer->type & SIP_TYPE_PEER)) {
14802 ao2_unlock(peer);
14803 unref_peer(peer, "unref peer because it's actually a user");
14804 continue;
14805 }
14806
14807 if (havepattern && regexec(®exbuf, peer->name, 0, NULL, 0)) {
14808 objcount--;
14809 ao2_unlock(peer);
14810 unref_peer(peer, "toss iterator peer ptr before continue");
14811 continue;
14812 }
14813
14814 peerarray[total_peers++] = peer;
14815 ao2_unlock(peer);
14816 }
14817 ao2_iterator_destroy(&i);
14818
14819 qsort(peerarray, total_peers, sizeof(struct sip_peer *), peercomparefunc);
14820
14821 for(k=0; k < total_peers; k++) {
14822 char status[20] = "";
14823 char srch[2000];
14824 char pstatus;
14825 peer = peerarray[k];
14826
14827 ao2_lock(peer);
14828 if (havepattern && regexec(®exbuf, peer->name, 0, NULL, 0)) {
14829 ao2_unlock(peer);
14830 unref_peer(peer, "toss iterator peer ptr before continue");
14831 continue;
14832 }
14833
14834 if (!ast_strlen_zero(peer->username) && !s)
14835 snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
14836 else
14837 ast_copy_string(name, peer->name, sizeof(name));
14838
14839 pstatus = peer_status(peer, status, sizeof(status));
14840 if (pstatus == 1)
14841 peers_mon_online++;
14842 else if (pstatus == 0)
14843 peers_mon_offline++;
14844 else {
14845 if (peer->addr.sin_port == 0)
14846 peers_unmon_offline++;
14847 else
14848 peers_unmon_online++;
14849 }
14850
14851 snprintf(srch, sizeof(srch), FORMAT, name,
14852 peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
14853 peer->host_dynamic ? " D " : " ",
14854 ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) ? " N " : " ",
14855 peer->ha ? " A " : " ",
14856 ntohs(peer->addr.sin_port), status,
14857 realtimepeers ? (peer->is_realtime ? "Cached RT":"") : "");
14858
14859 if (!s) {
14860 ast_cli(fd, FORMAT, name,
14861 peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
14862 peer->host_dynamic ? " D " : " ",
14863 ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) ? " N " : " ",
14864 peer->ha ? " A " : " ",
14865
14866 ntohs(peer->addr.sin_port), status,
14867 realtimepeers ? (peer->is_realtime ? "Cached RT":"") : "");
14868 } else {
14869
14870 astman_append(s,
14871 "Event: PeerEntry\r\n%s"
14872 "Channeltype: SIP\r\n"
14873 "ObjectName: %s\r\n"
14874 "ChanObjectType: peer\r\n"
14875 "IPaddress: %s\r\n"
14876 "IPport: %d\r\n"
14877 "Dynamic: %s\r\n"
14878 "Natsupport: %s\r\n"
14879 "VideoSupport: %s\r\n"
14880 "TextSupport: %s\r\n"
14881 "ACL: %s\r\n"
14882 "Status: %s\r\n"
14883 "RealtimeDevice: %s\r\n\r\n",
14884 idtext,
14885 peer->name,
14886 peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "-none-",
14887 ntohs(peer->addr.sin_port),
14888 peer->host_dynamic ? "yes" : "no",
14889 ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) ? "yes" : "no",
14890 ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "yes" : "no",
14891 ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT) ? "yes" : "no",
14892 peer->ha ? "yes" : "no",
14893 status,
14894 realtimepeers ? (peer->is_realtime ? "yes":"no") : "no");
14895 }
14896 ao2_unlock(peer);
14897 unref_peer(peer, "toss iterator peer ptr");
14898 }
14899
14900 if (!s)
14901 ast_cli(fd, "%d sip peers [Monitored: %d online, %d offline Unmonitored: %d online, %d offline]\n",
14902 total_peers, peers_mon_online, peers_mon_offline, peers_unmon_online, peers_unmon_offline);
14903
14904 if (havepattern)
14905 regfree(®exbuf);
14906
14907 if (total)
14908 *total = total_peers;
14909
14910 ast_free(peerarray);
14911
14912 return CLI_SUCCESS;
14913 #undef FORMAT
14914 #undef FORMAT2
14915 }
14916
14917 static int peer_dump_func(void *userobj, void *arg, int flags)
14918 {
14919 struct sip_peer *peer = userobj;
14920 int refc = ao2_t_ref(userobj, 0, "");
14921 int *fd = arg;
14922
14923 ast_cli(*fd, "name: %s\ntype: peer\nobjflags: %d\nrefcount: %d\n\n",
14924 peer->name, 0, refc);
14925 return 0;
14926 }
14927
14928 static int dialog_dump_func(void *userobj, void *arg, int flags)
14929 {
14930 struct sip_pvt *pvt = userobj;
14931 int refc = ao2_t_ref(userobj, 0, "");
14932 int *fd = arg;
14933
14934 ast_cli(*fd, "name: %s\ntype: dialog\nobjflags: %d\nrefcount: %d\n\n",
14935 pvt->callid, 0, refc);
14936 return 0;
14937 }
14938
14939
14940
14941 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14942 {
14943 char tmp[256];
14944
14945 switch (cmd) {
14946 case CLI_INIT:
14947 e->command = "sip show objects";
14948 e->usage =
14949 "Usage: sip show objects\n"
14950 " Lists status of known SIP objects\n";
14951 return NULL;
14952 case CLI_GENERATE:
14953 return NULL;
14954 }
14955
14956 if (a->argc != 3)
14957 return CLI_SHOWUSAGE;
14958 ast_cli(a->fd, "-= Peer objects: %d static, %d realtime, %d autocreate =-\n\n", speerobjs, rpeerobjs, apeerobjs);
14959 ao2_t_callback(peers, OBJ_NODATA, peer_dump_func, &a->fd, "initiate ao2_callback to dump peers");
14960 ast_cli(a->fd, "-= Registry objects: %d =-\n\n", regobjs);
14961 ASTOBJ_CONTAINER_DUMP(a->fd, tmp, sizeof(tmp), ®l);
14962 ast_cli(a->fd, "-= Dialog objects:\n\n");
14963 ao2_t_callback(dialogs, OBJ_NODATA, dialog_dump_func, &a->fd, "initiate ao2_callback to dump dialogs");
14964 return CLI_SUCCESS;
14965 }
14966
14967 static void print_group(int fd, ast_group_t group, int crlf)
14968 {
14969 char buf[256];
14970 ast_cli(fd, crlf ? "%s\r\n" : "%s\n", ast_print_group(buf, sizeof(buf), group) );
14971 }
14972
14973
14974 static struct _map_x_s dtmfstr[] = {
14975 { SIP_DTMF_RFC2833, "rfc2833" },
14976 { SIP_DTMF_INFO, "info" },
14977 { SIP_DTMF_SHORTINFO, "shortinfo" },
14978 { SIP_DTMF_INBAND, "inband" },
14979 { SIP_DTMF_AUTO, "auto" },
14980 { -1, NULL },
14981 };
14982
14983
14984 static const char *dtmfmode2str(int mode)
14985 {
14986 return map_x_s(dtmfstr, mode, "<error>");
14987 }
14988
14989
14990 static int str2dtmfmode(const char *str)
14991 {
14992 return map_s_x(dtmfstr, str, -1);
14993 }
14994
14995 static struct _map_x_s insecurestr[] = {
14996 { SIP_INSECURE_PORT, "port" },
14997 { SIP_INSECURE_INVITE, "invite" },
14998 { SIP_INSECURE_PORT | SIP_INSECURE_INVITE, "port,invite" },
14999 { 0, "no" },
15000 { -1, NULL },
15001 };
15002
15003
15004 static const char *insecure2str(int mode)
15005 {
15006 return map_x_s(insecurestr, mode, "<error>");
15007 }
15008
15009
15010
15011
15012 static void cleanup_stale_contexts(char *new, char *old)
15013 {
15014 char *oldcontext, *newcontext, *stalecontext, *stringp, newlist[AST_MAX_CONTEXT];
15015
15016 while ((oldcontext = strsep(&old, "&"))) {
15017 stalecontext = '\0';
15018 ast_copy_string(newlist, new, sizeof(newlist));
15019 stringp = newlist;
15020 while ((newcontext = strsep(&stringp, "&"))) {
15021 if (!strcmp(newcontext, oldcontext)) {
15022
15023 stalecontext = '\0';
15024 break;
15025 } else if (strcmp(newcontext, oldcontext)) {
15026 stalecontext = oldcontext;
15027 }
15028
15029 }
15030 if (stalecontext)
15031 ast_context_destroy(ast_context_find(stalecontext), "SIP");
15032 }
15033 }
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047 static int dialog_needdestroy(void *dialogobj, void *arg, int flags)
15048 {
15049 struct sip_pvt *dialog = dialogobj;
15050 time_t *t = arg;
15051
15052 if (sip_pvt_trylock(dialog)) {
15053
15054
15055 return 0;
15056 }
15057
15058
15059 check_rtp_timeout(dialog, *t);
15060
15061
15062
15063
15064 if (dialog->needdestroy && !dialog->packets && !dialog->owner) {
15065
15066 if (dialog->rtp && ast_rtp_get_bridged(dialog->rtp)) {
15067 ast_debug(2, "Bridge still active. Delaying destruction of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
15068 sip_pvt_unlock(dialog);
15069 return 0;
15070 }
15071
15072 if (dialog->vrtp && ast_rtp_get_bridged(dialog->vrtp)) {
15073 ast_debug(2, "Bridge still active. Delaying destroy of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
15074 sip_pvt_unlock(dialog);
15075 return 0;
15076 }
15077
15078 sip_pvt_unlock(dialog);
15079
15080
15081 dialog_unlink_all(dialog, TRUE, FALSE);
15082 return 0;
15083 }
15084
15085 sip_pvt_unlock(dialog);
15086
15087 return 0;
15088 }
15089
15090
15091
15092 static int peer_is_marked(void *peerobj, void *arg, int flags)
15093 {
15094 struct sip_peer *peer = peerobj;
15095 return peer->the_mark ? CMP_MATCH : 0;
15096 }
15097
15098
15099
15100 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15101 {
15102 struct sip_peer *peer, *pi;
15103 int prunepeer = FALSE;
15104 int multi = FALSE;
15105 char *name = NULL;
15106 regex_t regexbuf;
15107 struct ao2_iterator i;
15108 static char *choices[] = { "all", "like", NULL };
15109 char *cmplt;
15110
15111 if (cmd == CLI_INIT) {
15112 e->command = "sip prune realtime [peer|all]";
15113 e->usage =
15114 "Usage: sip prune realtime [peer [<name>|all|like <pattern>]|all]\n"
15115 " Prunes object(s) from the cache.\n"
15116 " Optional regular expression pattern is used to filter the objects.\n";
15117 return NULL;
15118 } else if (cmd == CLI_GENERATE) {
15119 if (a->pos == 4 && !strcasecmp(a->argv[3], "peer")) {
15120 cmplt = ast_cli_complete(a->word, choices, a->n);
15121 if (!cmplt)
15122 cmplt = complete_sip_peer(a->word, a->n - sizeof(choices), SIP_PAGE2_RTCACHEFRIENDS);
15123 return cmplt;
15124 }
15125 if (a->pos == 5 && !strcasecmp(a->argv[4], "like"))
15126 return complete_sip_peer(a->word, a->n, SIP_PAGE2_RTCACHEFRIENDS);
15127 return NULL;
15128 }
15129 switch (a->argc) {
15130 case 4:
15131 name = a->argv[3];
15132
15133 if (!strcasecmp(name, "peer") || !strcasecmp(name, "like"))
15134 return CLI_SHOWUSAGE;
15135 prunepeer = TRUE;
15136 if (!strcasecmp(name, "all")) {
15137 multi = TRUE;
15138 name = NULL;
15139 }
15140
15141 break;
15142 case 5:
15143
15144 name = a->argv[4];
15145 if (!strcasecmp(a->argv[3], "peer"))
15146 prunepeer = TRUE;
15147 else if (!strcasecmp(a->argv[3], "like")) {
15148 prunepeer = TRUE;
15149 multi = TRUE;
15150 } else
15151 return CLI_SHOWUSAGE;
15152 if (!strcasecmp(name, "like"))
15153 return CLI_SHOWUSAGE;
15154 if (!multi && !strcasecmp(name, "all")) {
15155 multi = TRUE;
15156 name = NULL;
15157 }
15158 break;
15159 case 6:
15160 name = a->argv[5];
15161 multi = TRUE;
15162
15163 if (strcasecmp(a->argv[4], "like"))
15164 return CLI_SHOWUSAGE;
15165 if (!strcasecmp(a->argv[3], "peer")) {
15166 prunepeer = TRUE;
15167 } else
15168 return CLI_SHOWUSAGE;
15169 break;
15170 default:
15171 return CLI_SHOWUSAGE;
15172 }
15173
15174 if (multi && name) {
15175 if (regcomp(®exbuf, name, REG_EXTENDED | REG_NOSUB))
15176 return CLI_SHOWUSAGE;
15177 }
15178
15179 if (multi) {
15180 if (prunepeer) {
15181 int pruned = 0;
15182
15183 i = ao2_iterator_init(peers, 0);
15184 while ((pi = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
15185 ao2_lock(pi);
15186 if (name && regexec(®exbuf, pi->name, 0, NULL, 0)) {
15187 unref_peer(pi, "toss iterator peer ptr before continue");
15188 ao2_unlock(pi);
15189 continue;
15190 };
15191 if (ast_test_flag(&pi->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
15192 pi->the_mark = 1;
15193 pruned++;
15194 }
15195 ao2_unlock(pi);
15196 unref_peer(pi, "toss iterator peer ptr");
15197 }
15198 ao2_iterator_destroy(&i);
15199 if (pruned) {
15200 ao2_t_callback(peers, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, peer_is_marked, NULL,
15201 "initiating callback to remove marked peers");
15202 ast_cli(a->fd, "%d peers pruned.\n", pruned);
15203 } else
15204 ast_cli(a->fd, "No peers found to prune.\n");
15205 }
15206 } else {
15207 if (prunepeer) {
15208 struct sip_peer tmp;
15209 ast_copy_string(tmp.name, name, sizeof(tmp.name));
15210 if ((peer = ao2_t_find(peers, &tmp, OBJ_POINTER | OBJ_UNLINK, "finding to unlink from peers"))) {
15211 if (peer->addr.sin_addr.s_addr) {
15212 ao2_t_unlink(peers_by_ip, peer, "unlinking peer from peers_by_ip also");
15213 }
15214 if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
15215 ast_cli(a->fd, "Peer '%s' is not a Realtime peer, cannot be pruned.\n", name);
15216
15217 ao2_t_link(peers, peer, "link peer into peer table");
15218 if (peer->addr.sin_addr.s_addr) {
15219 ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
15220 }
15221
15222 } else
15223 ast_cli(a->fd, "Peer '%s' pruned.\n", name);
15224 unref_peer(peer, "sip_prune_realtime: unref_peer: tossing temp peer ptr");
15225 } else
15226 ast_cli(a->fd, "Peer '%s' not found.\n", name);
15227 }
15228 }
15229
15230 return CLI_SUCCESS;
15231 }
15232
15233
15234 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref)
15235 {
15236 int x, codec;
15237
15238 for(x = 0; x < 32 ; x++) {
15239 codec = ast_codec_pref_index(pref, x);
15240 if (!codec)
15241 break;
15242 ast_cli(fd, "%s", ast_getformatname(codec));
15243 ast_cli(fd, ":%d", pref->framing[x]);
15244 if (x < 31 && ast_codec_pref_index(pref, x + 1))
15245 ast_cli(fd, ",");
15246 }
15247 if (!x)
15248 ast_cli(fd, "none");
15249 }
15250
15251
15252 static const char *domain_mode_to_text(const enum domain_mode mode)
15253 {
15254 switch (mode) {
15255 case SIP_DOMAIN_AUTO:
15256 return "[Automatic]";
15257 case SIP_DOMAIN_CONFIG:
15258 return "[Configured]";
15259 }
15260
15261 return "";
15262 }
15263
15264
15265 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15266 {
15267 struct domain *d;
15268 #define FORMAT "%-40.40s %-20.20s %-16.16s\n"
15269
15270 switch (cmd) {
15271 case CLI_INIT:
15272 e->command = "sip show domains";
15273 e->usage =
15274 "Usage: sip show domains\n"
15275 " Lists all configured SIP local domains.\n"
15276 " Asterisk only responds to SIP messages to local domains.\n";
15277 return NULL;
15278 case CLI_GENERATE:
15279 return NULL;
15280 }
15281
15282 if (AST_LIST_EMPTY(&domain_list)) {
15283 ast_cli(a->fd, "SIP Domain support not enabled.\n\n");
15284 return CLI_SUCCESS;
15285 } else {
15286 ast_cli(a->fd, FORMAT, "Our local SIP domains:", "Context", "Set by");
15287 AST_LIST_LOCK(&domain_list);
15288 AST_LIST_TRAVERSE(&domain_list, d, list)
15289 ast_cli(a->fd, FORMAT, d->domain, S_OR(d->context, "(default)"),
15290 domain_mode_to_text(d->mode));
15291 AST_LIST_UNLOCK(&domain_list);
15292 ast_cli(a->fd, "\n");
15293 return CLI_SUCCESS;
15294 }
15295 }
15296 #undef FORMAT
15297
15298 static char mandescr_show_peer[] =
15299 "Description: Show one SIP peer with details on current status.\n"
15300 "Variables: \n"
15301 " Peer: <name> The peer name you want to check.\n"
15302 " ActionID: <id> Optional action ID for this AMI transaction.\n";
15303
15304
15305 static int manager_sip_show_peer(struct mansession *s, const struct message *m)
15306 {
15307 const char *a[4];
15308 const char *peer;
15309
15310 peer = astman_get_header(m, "Peer");
15311 if (ast_strlen_zero(peer)) {
15312 astman_send_error(s, m, "Peer: <name> missing.");
15313 return 0;
15314 }
15315 a[0] = "sip";
15316 a[1] = "show";
15317 a[2] = "peer";
15318 a[3] = peer;
15319
15320 _sip_show_peer(1, -1, s, m, 4, a);
15321 astman_append(s, "\r\n\r\n" );
15322 return 0;
15323 }
15324
15325
15326 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15327 {
15328 switch (cmd) {
15329 case CLI_INIT:
15330 e->command = "sip show peer";
15331 e->usage =
15332 "Usage: sip show peer <name> [load]\n"
15333 " Shows all details on one SIP peer and the current status.\n"
15334 " Option \"load\" forces lookup of peer in realtime storage.\n";
15335 return NULL;
15336 case CLI_GENERATE:
15337 return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
15338 }
15339 return _sip_show_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
15340 }
15341
15342
15343 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
15344 {
15345 struct sip_peer *peer;
15346 int load_realtime;
15347
15348 if (argc < 4)
15349 return CLI_SHOWUSAGE;
15350
15351 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
15352 if ((peer = find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0))) {
15353 sip_poke_peer(peer, 1);
15354 unref_peer(peer, "qualify: done with peer");
15355 } else if (type == 0) {
15356 ast_cli(fd, "Peer '%s' not found\n", argv[3]);
15357 } else {
15358 astman_send_error(s, m, "Peer not found");
15359 }
15360 return CLI_SUCCESS;
15361 }
15362
15363
15364 static int manager_sip_qualify_peer(struct mansession *s, const struct message *m)
15365 {
15366 const char *a[4];
15367 const char *peer;
15368
15369 peer = astman_get_header(m, "Peer");
15370 if (ast_strlen_zero(peer)) {
15371 astman_send_error(s, m, "Peer: <name> missing.");
15372 return 0;
15373 }
15374 a[0] = "sip";
15375 a[1] = "qualify";
15376 a[2] = "peer";
15377 a[3] = peer;
15378
15379 _sip_qualify_peer(1, -1, s, m, 4, a);
15380 astman_append(s, "\r\n\r\n" );
15381 return 0;
15382 }
15383
15384
15385 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15386 {
15387 switch (cmd) {
15388 case CLI_INIT:
15389 e->command = "sip qualify peer";
15390 e->usage =
15391 "Usage: sip qualify peer <name> [load]\n"
15392 " Requests a response from one SIP peer and the current status.\n"
15393 " Option \"load\" forces lookup of peer in realtime storage.\n";
15394 return NULL;
15395 case CLI_GENERATE:
15396 return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
15397 }
15398 return _sip_qualify_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
15399 }
15400
15401
15402 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer)
15403 {
15404 struct sip_mailbox *mailbox;
15405
15406 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
15407 ast_str_append(mailbox_str, 0, "%s%s%s%s",
15408 mailbox->mailbox,
15409 ast_strlen_zero(mailbox->context) ? "" : "@",
15410 S_OR(mailbox->context, ""),
15411 AST_LIST_NEXT(mailbox, entry) ? "," : "");
15412 }
15413 }
15414
15415 static struct _map_x_s faxecmodes[] = {
15416 { SIP_PAGE2_T38SUPPORT_UDPTL, "None"},
15417 { SIP_PAGE2_T38SUPPORT_UDPTL_FEC, "FEC"},
15418 { SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY, "Redundancy"},
15419 { -1, NULL},
15420 };
15421
15422 static const char *faxec2str(int faxec)
15423 {
15424 return map_x_s(faxecmodes, faxec, "Unknown");
15425 }
15426
15427
15428 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
15429 {
15430 char status[30] = "";
15431 char cbuf[256];
15432 struct sip_peer *peer;
15433 char codec_buf[512];
15434 struct ast_codec_pref *pref;
15435 struct ast_variable *v;
15436 struct sip_auth *auth;
15437 int x = 0, codec = 0, load_realtime;
15438 int realtimepeers;
15439
15440 realtimepeers = ast_check_realtime("sippeers");
15441
15442 if (argc < 4)
15443 return CLI_SHOWUSAGE;
15444
15445 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
15446 peer = find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0);
15447
15448 if (s) {
15449 if (peer) {
15450 const char *id = astman_get_header(m, "ActionID");
15451
15452 astman_append(s, "Response: Success\r\n");
15453 if (!ast_strlen_zero(id))
15454 astman_append(s, "ActionID: %s\r\n", id);
15455 } else {
15456 snprintf (cbuf, sizeof(cbuf), "Peer %s not found.", argv[3]);
15457 astman_send_error(s, m, cbuf);
15458 return CLI_SUCCESS;
15459 }
15460 }
15461 if (peer && type==0 ) {
15462 struct ast_str *mailbox_str = ast_str_alloca(512);
15463 ast_cli(fd, "\n\n");
15464 ast_cli(fd, " * Name : %s\n", peer->name);
15465 if (realtimepeers) {
15466 ast_cli(fd, " Realtime peer: %s\n", peer->is_realtime ? "Yes, cached" : "No");
15467 }
15468 ast_cli(fd, " Secret : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
15469 ast_cli(fd, " MD5Secret : %s\n", ast_strlen_zero(peer->md5secret)?"<Not set>":"<Set>");
15470 ast_cli(fd, " Remote Secret: %s\n", ast_strlen_zero(peer->remotesecret)?"<Not set>":"<Set>");
15471 for (auth = peer->auth; auth; auth = auth->next) {
15472 ast_cli(fd, " Realm-auth : Realm %-15.15s User %-10.20s ", auth->realm, auth->username);
15473 ast_cli(fd, "%s\n", !ast_strlen_zero(auth->secret)?"<Secret set>":(!ast_strlen_zero(auth->md5secret)?"<MD5secret set>" : "<Not set>"));
15474 }
15475 ast_cli(fd, " Context : %s\n", peer->context);
15476 ast_cli(fd, " Subscr.Cont. : %s\n", S_OR(peer->subscribecontext, "<Not set>") );
15477 ast_cli(fd, " Language : %s\n", peer->language);
15478 if (!ast_strlen_zero(peer->accountcode))
15479 ast_cli(fd, " Accountcode : %s\n", peer->accountcode);
15480 ast_cli(fd, " AMA flags : %s\n", ast_cdr_flags2str(peer->amaflags));
15481 ast_cli(fd, " Transfer mode: %s\n", transfermode2str(peer->allowtransfer));
15482 ast_cli(fd, " CallingPres : %s\n", ast_describe_caller_presentation(peer->callingpres));
15483 if (!ast_strlen_zero(peer->fromuser))
15484 ast_cli(fd, " FromUser : %s\n", peer->fromuser);
15485 if (!ast_strlen_zero(peer->fromdomain))
15486 ast_cli(fd, " FromDomain : %s\n", peer->fromdomain);
15487 ast_cli(fd, " Callgroup : ");
15488 print_group(fd, peer->callgroup, 0);
15489 ast_cli(fd, " Pickupgroup : ");
15490 print_group(fd, peer->pickupgroup, 0);
15491 peer_mailboxes_to_str(&mailbox_str, peer);
15492 ast_cli(fd, " Mailbox : %s\n", mailbox_str->str);
15493 ast_cli(fd, " VM Extension : %s\n", peer->vmexten);
15494 ast_cli(fd, " LastMsgsSent : %d/%d\n", (peer->lastmsgssent & 0x7fff0000) >> 16, peer->lastmsgssent & 0xffff);
15495 ast_cli(fd, " Call limit : %d\n", peer->call_limit);
15496 if (peer->busy_level)
15497 ast_cli(fd, " Busy level : %d\n", peer->busy_level);
15498 ast_cli(fd, " Dynamic : %s\n", cli_yesno(peer->host_dynamic));
15499 ast_cli(fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
15500 ast_cli(fd, " MaxCallBR : %d kbps\n", peer->maxcallbitrate);
15501 ast_cli(fd, " Expire : %ld\n", ast_sched_when(sched, peer->expire));
15502 ast_cli(fd, " Insecure : %s\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
15503 ast_cli(fd, " Nat : %s\n", nat2str(ast_test_flag(&peer->flags[0], SIP_NAT)));
15504 ast_cli(fd, " ACL : %s\n", cli_yesno(peer->ha != NULL));
15505 ast_cli(fd, " T.38 support : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
15506 ast_cli(fd, " T.38 EC mode : %s\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
15507 ast_cli(fd, " T.38 MaxDtgrm: %d\n", peer->t38_maxdatagram);
15508 ast_cli(fd, " DirectMedia : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)));
15509 ast_cli(fd, " PromiscRedir : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)));
15510 ast_cli(fd, " User=Phone : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)));
15511 ast_cli(fd, " Video Support: %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)));
15512 ast_cli(fd, " Text Support : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)));
15513 ast_cli(fd, " Ign SDP ver : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_IGNORESDPVERSION)));
15514 ast_cli(fd, " Trust RPID : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_TRUSTRPID)));
15515 ast_cli(fd, " Send RPID : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_SENDRPID)));
15516 ast_cli(fd, " Subscriptions: %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
15517 ast_cli(fd, " Overlap dial : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWOVERLAP)));
15518 if (peer->outboundproxy)
15519 ast_cli(fd, " Outb. proxy : %s %s\n", ast_strlen_zero(peer->outboundproxy->name) ? "<not set>" : peer->outboundproxy->name,
15520 peer->outboundproxy->force ? "(forced)" : "");
15521
15522
15523 ast_cli(fd, " DTMFmode : %s\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
15524 ast_cli(fd, " Timer T1 : %d\n", peer->timer_t1);
15525 ast_cli(fd, " Timer B : %d\n", peer->timer_b);
15526 ast_cli(fd, " ToHost : %s\n", peer->tohost);
15527 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));
15528 ast_cli(fd, " Defaddr->IP : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
15529 ast_cli(fd, " Prim.Transp. : %s\n", get_transport(peer->socket.type));
15530 ast_cli(fd, " Allowed.Trsp : %s\n", get_transport_list(peer->transports));
15531 if (!ast_strlen_zero(global_regcontext))
15532 ast_cli(fd, " Reg. exten : %s\n", peer->regexten);
15533 ast_cli(fd, " Def. Username: %s\n", peer->username);
15534 ast_cli(fd, " SIP Options : ");
15535 if (peer->sipoptions) {
15536 int lastoption = -1;
15537 for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
15538 if (sip_options[x].id != lastoption) {
15539 if (peer->sipoptions & sip_options[x].id)
15540 ast_cli(fd, "%s ", sip_options[x].text);
15541 lastoption = x;
15542 }
15543 }
15544 } else
15545 ast_cli(fd, "(none)");
15546
15547 ast_cli(fd, "\n");
15548 ast_cli(fd, " Codecs : ");
15549 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
15550 ast_cli(fd, "%s\n", codec_buf);
15551 ast_cli(fd, " Codec Order : (");
15552 print_codec_to_cli(fd, &peer->prefs);
15553 ast_cli(fd, ")\n");
15554
15555 ast_cli(fd, " Auto-Framing : %s \n", cli_yesno(peer->autoframing));
15556 ast_cli(fd, " 100 on REG : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_REGISTERTRYING) ? "Yes" : "No");
15557 ast_cli(fd, " Status : ");
15558 peer_status(peer, status, sizeof(status));
15559 ast_cli(fd, "%s\n", status);
15560 ast_cli(fd, " Useragent : %s\n", peer->useragent);
15561 ast_cli(fd, " Reg. Contact : %s\n", peer->fullcontact);
15562 ast_cli(fd, " Qualify Freq : %d ms\n", peer->qualifyfreq);
15563 if (peer->chanvars) {
15564 ast_cli(fd, " Variables :\n");
15565 for (v = peer->chanvars ; v ; v = v->next)
15566 ast_cli(fd, " %s = %s\n", v->name, v->value);
15567 }
15568
15569 ast_cli(fd, " Sess-Timers : %s\n", stmode2str(peer->stimer.st_mode_oper));
15570 ast_cli(fd, " Sess-Refresh : %s\n", strefresher2str(peer->stimer.st_ref));
15571 ast_cli(fd, " Sess-Expires : %d secs\n", peer->stimer.st_max_se);
15572 ast_cli(fd, " Min-Sess : %d secs\n", peer->stimer.st_min_se);
15573 ast_cli(fd, " Parkinglot : %s\n", peer->parkinglot);
15574 ast_cli(fd, "\n");
15575 peer = unref_peer(peer, "sip_show_peer: unref_peer: done with peer ptr");
15576 } else if (peer && type == 1) {
15577 char buffer[256];
15578 struct ast_str *mailbox_str = ast_str_alloca(512);
15579 astman_append(s, "Channeltype: SIP\r\n");
15580 astman_append(s, "ObjectName: %s\r\n", peer->name);
15581 astman_append(s, "ChanObjectType: peer\r\n");
15582 astman_append(s, "SecretExist: %s\r\n", ast_strlen_zero(peer->secret)?"N":"Y");
15583 astman_append(s, "RemoteSecretExist: %s\r\n", ast_strlen_zero(peer->remotesecret)?"N":"Y");
15584 astman_append(s, "MD5SecretExist: %s\r\n", ast_strlen_zero(peer->md5secret)?"N":"Y");
15585 astman_append(s, "Context: %s\r\n", peer->context);
15586 astman_append(s, "Language: %s\r\n", peer->language);
15587 if (!ast_strlen_zero(peer->accountcode))
15588 astman_append(s, "Accountcode: %s\r\n", peer->accountcode);
15589 astman_append(s, "AMAflags: %s\r\n", ast_cdr_flags2str(peer->amaflags));
15590 astman_append(s, "CID-CallingPres: %s\r\n", ast_describe_caller_presentation(peer->callingpres));
15591 if (!ast_strlen_zero(peer->fromuser))
15592 astman_append(s, "SIP-FromUser: %s\r\n", peer->fromuser);
15593 if (!ast_strlen_zero(peer->fromdomain))
15594 astman_append(s, "SIP-FromDomain: %s\r\n", peer->fromdomain);
15595 astman_append(s, "Callgroup: ");
15596 astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->callgroup));
15597 astman_append(s, "Pickupgroup: ");
15598 astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->pickupgroup));
15599 peer_mailboxes_to_str(&mailbox_str, peer);
15600 astman_append(s, "VoiceMailbox: %s\r\n", mailbox_str->str);
15601 astman_append(s, "TransferMode: %s\r\n", transfermode2str(peer->allowtransfer));
15602 astman_append(s, "LastMsgsSent: %d\r\n", peer->lastmsgssent);
15603 astman_append(s, "Call-limit: %d\r\n", peer->call_limit);
15604 astman_append(s, "Busy-level: %d\r\n", peer->busy_level);
15605 astman_append(s, "MaxCallBR: %d kbps\r\n", peer->maxcallbitrate);
15606 astman_append(s, "Dynamic: %s\r\n", peer->host_dynamic?"Y":"N");
15607 astman_append(s, "Callerid: %s\r\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, ""));
15608 astman_append(s, "RegExpire: %ld seconds\r\n", ast_sched_when(sched, peer->expire));
15609 astman_append(s, "SIP-AuthInsecure: %s\r\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
15610 astman_append(s, "SIP-NatSupport: %s\r\n", nat2str(ast_test_flag(&peer->flags[0], SIP_NAT)));
15611 astman_append(s, "ACL: %s\r\n", (peer->ha?"Y":"N"));
15612 astman_append(s, "SIP-CanReinvite: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)?"Y":"N"));
15613 astman_append(s, "SIP-DirectMedia: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)?"Y":"N"));
15614 astman_append(s, "SIP-PromiscRedir: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)?"Y":"N"));
15615 astman_append(s, "SIP-UserPhone: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)?"Y":"N"));
15616 astman_append(s, "SIP-VideoSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)?"Y":"N"));
15617 astman_append(s, "SIP-TextSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)?"Y":"N"));
15618 astman_append(s, "SIP-T.38Support: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)?"Y":"N"));
15619 astman_append(s, "SIP-T.38EC: %s\r\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
15620 astman_append(s, "SIP-T.38MaxDtgrm: %d\r\n", peer->t38_maxdatagram);
15621 astman_append(s, "SIP-Sess-Timers: %s\r\n", stmode2str(peer->stimer.st_mode_oper));
15622 astman_append(s, "SIP-Sess-Refresh: %s\r\n", strefresher2str(peer->stimer.st_ref));
15623 astman_append(s, "SIP-Sess-Expires: %d\r\n", peer->stimer.st_max_se);
15624 astman_append(s, "SIP-Sess-Min: %d\r\n", peer->stimer.st_min_se);
15625
15626
15627 astman_append(s, "SIP-DTMFmode: %s\r\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
15628 astman_append(s, "ToHost: %s\r\n", peer->tohost);
15629 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));
15630 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));
15631 astman_append(s, "Default-Username: %s\r\n", peer->username);
15632 if (!ast_strlen_zero(global_regcontext))
15633 astman_append(s, "RegExtension: %s\r\n", peer->regexten);
15634 astman_append(s, "Codecs: ");
15635 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
15636 astman_append(s, "%s\r\n", codec_buf);
15637 astman_append(s, "CodecOrder: ");
15638 pref = &peer->prefs;
15639 for(x = 0; x < 32 ; x++) {
15640 codec = ast_codec_pref_index(pref, x);
15641 if (!codec)
15642 break;
15643 astman_append(s, "%s", ast_getformatname(codec));
15644 if (x < 31 && ast_codec_pref_index(pref, x+1))
15645 astman_append(s, ",");
15646 }
15647
15648 astman_append(s, "\r\n");
15649 astman_append(s, "Status: ");
15650 peer_status(peer, status, sizeof(status));
15651 astman_append(s, "%s\r\n", status);
15652 astman_append(s, "SIP-Useragent: %s\r\n", peer->useragent);
15653 astman_append(s, "Reg-Contact: %s\r\n", peer->fullcontact);
15654 astman_append(s, "QualifyFreq: %d ms\r\n", peer->qualifyfreq);
15655 astman_append(s, "Parkinglot: %s\r\n", peer->parkinglot);
15656 if (peer->chanvars) {
15657 for (v = peer->chanvars ; v ; v = v->next) {
15658 astman_append(s, "ChanVariable: %s=%s\r\n", v->name, v->value);
15659 }
15660 }
15661
15662 peer = unref_peer(peer, "sip_show_peer: unref_peer: done with peer");
15663
15664 } else {
15665 ast_cli(fd, "Peer %s not found.\n", argv[3]);
15666 ast_cli(fd, "\n");
15667 }
15668
15669 return CLI_SUCCESS;
15670 }
15671
15672
15673 static char *complete_sip_user(const char *word, int state)
15674 {
15675 char *result = NULL;
15676 int wordlen = strlen(word);
15677 int which = 0;
15678 struct ao2_iterator user_iter;
15679 struct sip_peer *user;
15680
15681 user_iter = ao2_iterator_init(peers, 0);
15682 while ((user = ao2_iterator_next(&user_iter))) {
15683 ao2_lock(user);
15684 if (!(user->type & SIP_TYPE_USER)) {
15685 ao2_unlock(user);
15686 unref_peer(user, "complete sip user");
15687 continue;
15688 }
15689
15690 if (!strncasecmp(word, user->name, wordlen) && ++which > state) {
15691 result = ast_strdup(user->name);
15692 }
15693 ao2_unlock(user);
15694 unref_peer(user, "complete sip user");
15695 }
15696 ao2_iterator_destroy(&user_iter);
15697 return result;
15698 }
15699
15700 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state)
15701 {
15702 if (pos == 3)
15703 return complete_sip_user(word, state);
15704
15705 return NULL;
15706 }
15707
15708
15709 static char *sip_show_user(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15710 {
15711 char cbuf[256];
15712 struct sip_peer *user;
15713 struct ast_variable *v;
15714 int load_realtime;
15715
15716 switch (cmd) {
15717 case CLI_INIT:
15718 e->command = "sip show user";
15719 e->usage =
15720 "Usage: sip show user <name> [load]\n"
15721 " Shows all details on one SIP user and the current status.\n"
15722 " Option \"load\" forces lookup of peer in realtime storage.\n";
15723 return NULL;
15724 case CLI_GENERATE:
15725 return complete_sip_show_user(a->line, a->word, a->pos, a->n);
15726 }
15727
15728 if (a->argc < 4)
15729 return CLI_SHOWUSAGE;
15730
15731
15732 load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? TRUE : FALSE;
15733
15734 if ((user = find_peer(a->argv[3], NULL, load_realtime, FINDUSERS, FALSE, 0))) {
15735 ao2_lock(user);
15736 ast_cli(a->fd, "\n\n");
15737 ast_cli(a->fd, " * Name : %s\n", user->name);
15738 ast_cli(a->fd, " Secret : %s\n", ast_strlen_zero(user->secret)?"<Not set>":"<Set>");
15739 ast_cli(a->fd, " MD5Secret : %s\n", ast_strlen_zero(user->md5secret)?"<Not set>":"<Set>");
15740 ast_cli(a->fd, " Context : %s\n", user->context);
15741 ast_cli(a->fd, " Language : %s\n", user->language);
15742 if (!ast_strlen_zero(user->accountcode))
15743 ast_cli(a->fd, " Accountcode : %s\n", user->accountcode);
15744 ast_cli(a->fd, " AMA flags : %s\n", ast_cdr_flags2str(user->amaflags));
15745 ast_cli(a->fd, " Transfer mode: %s\n", transfermode2str(user->allowtransfer));
15746 ast_cli(a->fd, " MaxCallBR : %d kbps\n", user->maxcallbitrate);
15747 ast_cli(a->fd, " CallingPres : %s\n", ast_describe_caller_presentation(user->callingpres));
15748 ast_cli(a->fd, " Call limit : %d\n", user->call_limit);
15749 ast_cli(a->fd, " Callgroup : ");
15750 print_group(a->fd, user->callgroup, 0);
15751 ast_cli(a->fd, " Pickupgroup : ");
15752 print_group(a->fd, user->pickupgroup, 0);
15753 ast_cli(a->fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), user->cid_name, user->cid_num, "<unspecified>"));
15754 ast_cli(a->fd, " ACL : %s\n", cli_yesno(user->ha != NULL));
15755 ast_cli(a->fd, " Sess-Timers : %s\n", stmode2str(user->stimer.st_mode_oper));
15756 ast_cli(a->fd, " Sess-Refresh : %s\n", strefresher2str(user->stimer.st_ref));
15757 ast_cli(a->fd, " Sess-Expires : %d secs\n", user->stimer.st_max_se);
15758 ast_cli(a->fd, " Sess-Min-SE : %d secs\n", user->stimer.st_min_se);
15759
15760 ast_cli(a->fd, " Codec Order : (");
15761 print_codec_to_cli(a->fd, &user->prefs);
15762 ast_cli(a->fd, ")\n");
15763
15764 ast_cli(a->fd, " Auto-Framing: %s \n", cli_yesno(user->autoframing));
15765 if (user->chanvars) {
15766 ast_cli(a->fd, " Variables :\n");
15767 for (v = user->chanvars ; v ; v = v->next)
15768 ast_cli(a->fd, " %s = %s\n", v->name, v->value);
15769 }
15770
15771 ast_cli(a->fd, "\n");
15772
15773 ao2_unlock(user);
15774 unref_peer(user, "sip show user");
15775 } else {
15776 ast_cli(a->fd, "User %s not found.\n", a->argv[3]);
15777 ast_cli(a->fd, "\n");
15778 }
15779
15780 return CLI_SUCCESS;
15781 }
15782
15783
15784 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15785 {
15786 struct ast_str *cbuf;
15787 struct ast_cb_names cbnames = {9, { "retrans_pkt",
15788 "__sip_autodestruct",
15789 "expire_register",
15790 "auto_congest",
15791 "sip_reg_timeout",
15792 "sip_poke_peer_s",
15793 "sip_poke_noanswer",
15794 "sip_reregister",
15795 "sip_reinvite_retry"},
15796 { retrans_pkt,
15797 __sip_autodestruct,
15798 expire_register,
15799 auto_congest,
15800 sip_reg_timeout,
15801 sip_poke_peer_s,
15802 sip_poke_noanswer,
15803 sip_reregister,
15804 sip_reinvite_retry}};
15805
15806 switch (cmd) {
15807 case CLI_INIT:
15808 e->command = "sip show sched";
15809 e->usage =
15810 "Usage: sip show sched\n"
15811 " Shows stats on what's in the sched queue at the moment\n";
15812 return NULL;
15813 case CLI_GENERATE:
15814 return NULL;
15815 }
15816
15817 cbuf = ast_str_alloca(2048);
15818
15819 ast_cli(a->fd, "\n");
15820 ast_sched_report(sched, &cbuf, &cbnames);
15821 ast_cli(a->fd, "%s", cbuf->str);
15822
15823 return CLI_SUCCESS;
15824 }
15825
15826
15827 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15828 {
15829 #define FORMAT2 "%-30.30s %-6.6s %-12.12s %8.8s %-20.20s %-25.25s\n"
15830 #define FORMAT "%-30.30s %-6.6s %-12.12s %8d %-20.20s %-25.25s\n"
15831 char host[80];
15832 char tmpdat[256];
15833 struct ast_tm tm;
15834 int counter = 0;
15835
15836 switch (cmd) {
15837 case CLI_INIT:
15838 e->command = "sip show registry";
15839 e->usage =
15840 "Usage: sip show registry\n"
15841 " Lists all registration requests and status.\n";
15842 return NULL;
15843 case CLI_GENERATE:
15844 return NULL;
15845 }
15846
15847 if (a->argc != 3)
15848 return CLI_SHOWUSAGE;
15849 ast_cli(a->fd, FORMAT2, "Host", "dnsmgr", "Username", "Refresh", "State", "Reg.Time");
15850
15851 ASTOBJ_CONTAINER_TRAVERSE(®l, 1, do {
15852 ASTOBJ_RDLOCK(iterator);
15853 snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
15854 if (iterator->regtime.tv_sec) {
15855 ast_localtime(&iterator->regtime, &tm, NULL);
15856 ast_strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T", &tm);
15857 } else
15858 tmpdat[0] = '\0';
15859 ast_cli(a->fd, FORMAT, host, (iterator->dnsmgr) ? "Y" : "N", iterator->username, iterator->refresh, regstate2str(iterator->regstate), tmpdat);
15860 ASTOBJ_UNLOCK(iterator);
15861 counter++;
15862 } while(0));
15863 ast_cli(a->fd, "%d SIP registrations.\n", counter);
15864 return CLI_SUCCESS;
15865 #undef FORMAT
15866 #undef FORMAT2
15867 }
15868
15869
15870
15871
15872
15873 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15874 {
15875 struct sip_peer *peer;
15876 int load_realtime = 0;
15877
15878 switch (cmd) {
15879 case CLI_INIT:
15880 e->command = "sip unregister";
15881 e->usage =
15882 "Usage: sip unregister <peer>\n"
15883 " Unregister (force expiration) a SIP peer from the registry\n";
15884 return NULL;
15885 case CLI_GENERATE:
15886 return complete_sip_unregister(a->line, a->word, a->pos, a->n);
15887 }
15888
15889 if (a->argc != 3)
15890 return CLI_SHOWUSAGE;
15891
15892 if ((peer = find_peer(a->argv[2], NULL, load_realtime, FINDPEERS, TRUE, 0))) {
15893 if (peer->expire > 0) {
15894 AST_SCHED_DEL_UNREF(sched, peer->expire,
15895 unref_peer(peer, "remove register expire ref"));
15896 expire_register(ref_peer(peer, "ref for expire_register"));
15897 ast_cli(a->fd, "Unregistered peer \'%s\'\n\n", a->argv[2]);
15898 } else {
15899 ast_cli(a->fd, "Peer %s not registered\n", a->argv[2]);
15900 }
15901 unref_peer(peer, "sip_unregister: unref_peer via sip_unregister: done with peer from find_peer call");
15902 } else {
15903 ast_cli(a->fd, "Peer unknown: \'%s\'. Not unregistered.\n", a->argv[2]);
15904 }
15905
15906 return CLI_SUCCESS;
15907 }
15908
15909
15910 static int show_chanstats_cb(void *__cur, void *__arg, int flags)
15911 {
15912 #define FORMAT2 "%-15.15s %-11.11s %-8.8s %-10.10s %-10.10s ( %%) %-6.6s %-10.10s %-10.10s ( %%) %-6.6s\n"
15913 #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"
15914 struct sip_pvt *cur = __cur;
15915 unsigned int rxcount, txcount, rxploss, txploss;
15916 char durbuf[10];
15917 int duration;
15918 int durh, durm, durs;
15919 struct ast_channel *c = cur->owner;
15920 struct __show_chan_arg *arg = __arg;
15921 int fd = arg->fd;
15922
15923
15924 if (cur->subscribed != NONE)
15925 return 0;
15926
15927 if (!cur->rtp) {
15928 if (sipdebug)
15929 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");
15930 return 0;
15931 }
15932 rxcount = ast_rtp_get_qosvalue(cur->rtp, AST_RTP_RXCOUNT);
15933 txcount = ast_rtp_get_qosvalue(cur->rtp, AST_RTP_TXCOUNT);
15934 rxploss = ast_rtp_get_qosvalue(cur->rtp, AST_RTP_RXPLOSS);
15935 txploss = ast_rtp_get_qosvalue(cur->rtp, AST_RTP_TXPLOSS);
15936
15937
15938 if (c && c->cdr && !ast_tvzero(c->cdr->start)) {
15939 duration = (int)(ast_tvdiff_ms(ast_tvnow(), c->cdr->start) / 1000);
15940 durh = duration / 3600;
15941 durm = (duration % 3600) / 60;
15942 durs = duration % 60;
15943 snprintf(durbuf, sizeof(durbuf), "%02d:%02d:%02d", durh, durm, durs);
15944 } else {
15945 durbuf[0] = '\0';
15946 }
15947
15948 ast_cli(fd, FORMAT,
15949 ast_inet_ntoa(cur->sa.sin_addr),
15950 cur->callid,
15951 durbuf,
15952 rxcount > (unsigned int) 100000 ? (unsigned int) (rxcount)/(unsigned int) 1000 : rxcount,
15953 rxcount > (unsigned int) 100000 ? "K":" ",
15954 rxploss,
15955 (rxcount + rxploss) > 0 ? (double) rxploss / (rxcount + rxploss) * 100 : 0,
15956 ast_rtp_get_qosvalue(cur->rtp, AST_RTP_RXJITTER),
15957 txcount > (unsigned int) 100000 ? (unsigned int) (txcount)/(unsigned int) 1000 : txcount,
15958 txcount > (unsigned int) 100000 ? "K":" ",
15959 txploss,
15960 txcount > 0 ? (double) txploss / txcount * 100 : 0,
15961 ast_rtp_get_qosvalue(cur->rtp, AST_RTP_TXJITTER)
15962 );
15963 arg->numchans++;
15964
15965 return 0;
15966 }
15967
15968
15969 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15970 {
15971 struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
15972
15973 switch (cmd) {
15974 case CLI_INIT:
15975 e->command = "sip show channelstats";
15976 e->usage =
15977 "Usage: sip show channelstats\n"
15978 " Lists all currently active SIP channel's RTCP statistics.\n"
15979 " Note that calls in the much optimized RTP P2P bridge mode will not show any packets here.";
15980 return NULL;
15981 case CLI_GENERATE:
15982 return NULL;
15983 }
15984
15985 if (a->argc != 3)
15986 return CLI_SHOWUSAGE;
15987
15988 ast_cli(a->fd, FORMAT2, "Peer", "Call ID", "Duration", "Recv: Pack", "Lost", "Jitter", "Send: Pack", "Lost", "Jitter");
15989
15990 ao2_t_callback(dialogs, OBJ_NODATA, show_chanstats_cb, &arg, "callback to sip show chanstats");
15991 ast_cli(a->fd, "%d active SIP channel%s\n", arg.numchans, (arg.numchans != 1) ? "s" : "");
15992 return CLI_SUCCESS;
15993 }
15994 #undef FORMAT
15995 #undef FORMAT2
15996
15997
15998 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15999 {
16000 int realtimepeers;
16001 int realtimeregs;
16002 char codec_buf[SIPBUFSIZE];
16003 const char *msg;
16004
16005 switch (cmd) {
16006 case CLI_INIT:
16007 e->command = "sip show settings";
16008 e->usage =
16009 "Usage: sip show settings\n"
16010 " Provides detailed list of the configuration of the SIP channel.\n";
16011 return NULL;
16012 case CLI_GENERATE:
16013 return NULL;
16014 }
16015
16016
16017 realtimepeers = ast_check_realtime("sippeers");
16018 realtimeregs = ast_check_realtime("sipregs");
16019
16020 if (a->argc != 3)
16021 return CLI_SHOWUSAGE;
16022 ast_cli(a->fd, "\n\nGlobal Settings:\n");
16023 ast_cli(a->fd, "----------------\n");
16024 ast_cli(a->fd, " UDP SIP Port: %d\n", ntohs(bindaddr.sin_port));
16025 ast_cli(a->fd, " UDP Bindaddress: %s\n", ast_inet_ntoa(bindaddr.sin_addr));
16026 ast_cli(a->fd, " TCP SIP Port: ");
16027 if (sip_tcp_desc.local_address.sin_family == AF_INET) {
16028 ast_cli(a->fd, "%d\n", ntohs(sip_tcp_desc.local_address.sin_port));
16029 ast_cli(a->fd, " TCP Bindaddress: %s\n", ast_inet_ntoa(sip_tcp_desc.local_address.sin_addr));
16030 } else {
16031 ast_cli(a->fd, "Disabled\n");
16032 }
16033 ast_cli(a->fd, " TLS SIP Port: ");
16034 if (default_tls_cfg.enabled != FALSE) {
16035 ast_cli(a->fd, "%d\n", ntohs(sip_tls_desc.local_address.sin_port));
16036 ast_cli(a->fd, " TLS Bindaddress: %s\n", ast_inet_ntoa(sip_tls_desc.local_address.sin_addr));
16037 } else {
16038 ast_cli(a->fd, "Disabled\n");
16039 }
16040 ast_cli(a->fd, " Videosupport: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT)));
16041 ast_cli(a->fd, " Textsupport: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT)));
16042 ast_cli(a->fd, " Ignore SDP sess. ver.: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION)));
16043 ast_cli(a->fd, " AutoCreate Peer: %s\n", cli_yesno(sip_cfg.autocreatepeer));
16044 ast_cli(a->fd, " Match Auth Username: %s\n", cli_yesno(global_match_auth_username));
16045 ast_cli(a->fd, " Allow unknown access: %s\n", cli_yesno(sip_cfg.allowguest));
16046 ast_cli(a->fd, " Allow subscriptions: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
16047 ast_cli(a->fd, " Allow overlap dialing: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP)));
16048 ast_cli(a->fd, " Allow promsic. redir: %s\n", cli_yesno(ast_test_flag(&global_flags[0], SIP_PROMISCREDIR)));
16049 ast_cli(a->fd, " Enable call counters: %s\n", cli_yesno(global_callcounter));
16050 ast_cli(a->fd, " SIP domain support: %s\n", cli_yesno(!AST_LIST_EMPTY(&domain_list)));
16051 ast_cli(a->fd, " Realm. auth: %s\n", cli_yesno(authl != NULL));
16052 ast_cli(a->fd, " Our auth realm %s\n", sip_cfg.realm);
16053 ast_cli(a->fd, " Call to non-local dom.: %s\n", cli_yesno(sip_cfg.allow_external_domains));
16054 ast_cli(a->fd, " URI user is phone no: %s\n", cli_yesno(ast_test_flag(&global_flags[0], SIP_USEREQPHONE)));
16055 ast_cli(a->fd, " Always auth rejects: %s\n", cli_yesno(sip_cfg.alwaysauthreject));
16056 ast_cli(a->fd, " Direct RTP setup: %s\n", cli_yesno(sip_cfg.directrtpsetup));
16057 ast_cli(a->fd, " User Agent: %s\n", global_useragent);
16058 ast_cli(a->fd, " SDP Session Name: %s\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
16059 ast_cli(a->fd, " SDP Owner Name: %s\n", ast_strlen_zero(global_sdpowner) ? "-" : global_sdpowner);
16060 ast_cli(a->fd, " Reg. context: %s\n", S_OR(global_regcontext, "(not set)"));
16061 ast_cli(a->fd, " Regexten on Qualify: %s\n", cli_yesno(sip_cfg.regextenonqualify));
16062 ast_cli(a->fd, " Caller ID: %s\n", default_callerid);
16063 ast_cli(a->fd, " From: Domain: %s\n", default_fromdomain);
16064 ast_cli(a->fd, " Record SIP history: %s\n", recordhistory ? "On" : "Off");
16065 ast_cli(a->fd, " Call Events: %s\n", sip_cfg.callevents ? "On" : "Off");
16066 ast_cli(a->fd, " Auth. Failure Events: %s\n", global_authfailureevents ? "On" : "Off");
16067
16068 ast_cli(a->fd, " T.38 support: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
16069 ast_cli(a->fd, " T.38 EC mode: %s\n", faxec2str(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
16070 ast_cli(a->fd, " T.38 MaxDtgrm: %d\n", global_t38_maxdatagram);
16071
16072 if (!realtimepeers && !realtimeregs)
16073 ast_cli(a->fd, " SIP realtime: Disabled\n" );
16074 else
16075 ast_cli(a->fd, " SIP realtime: Enabled\n" );
16076 ast_cli(a->fd, " Qualify Freq : %d ms\n", global_qualifyfreq);
16077 ast_cli(a->fd, "\nNetwork QoS Settings:\n");
16078 ast_cli(a->fd, "---------------------------\n");
16079 ast_cli(a->fd, " IP ToS SIP: %s\n", ast_tos2str(global_tos_sip));
16080 ast_cli(a->fd, " IP ToS RTP audio: %s\n", ast_tos2str(global_tos_audio));
16081 ast_cli(a->fd, " IP ToS RTP video: %s\n", ast_tos2str(global_tos_video));
16082 ast_cli(a->fd, " IP ToS RTP text: %s\n", ast_tos2str(global_tos_text));
16083 ast_cli(a->fd, " 802.1p CoS SIP: %d\n", global_cos_sip);
16084 ast_cli(a->fd, " 802.1p CoS RTP audio: %d\n", global_cos_audio);
16085 ast_cli(a->fd, " 802.1p CoS RTP video: %d\n", global_cos_video);
16086 ast_cli(a->fd, " 802.1p CoS RTP text: %d\n", global_cos_text);
16087 ast_cli(a->fd, " Jitterbuffer enabled: %s\n", cli_yesno(ast_test_flag(&global_jbconf, AST_JB_ENABLED)));
16088 ast_cli(a->fd, " Jitterbuffer forced: %s\n", cli_yesno(ast_test_flag(&global_jbconf, AST_JB_FORCED)));
16089 ast_cli(a->fd, " Jitterbuffer max size: %ld\n", global_jbconf.max_size);
16090 ast_cli(a->fd, " Jitterbuffer resync: %ld\n", global_jbconf.resync_threshold);
16091 ast_cli(a->fd, " Jitterbuffer impl: %s\n", global_jbconf.impl);
16092 ast_cli(a->fd, " Jitterbuffer log: %s\n", cli_yesno(ast_test_flag(&global_jbconf, AST_JB_LOG)));
16093
16094 ast_cli(a->fd, "\nNetwork Settings:\n");
16095 ast_cli(a->fd, "---------------------------\n");
16096
16097 if (localaddr == NULL)
16098 msg = "Disabled, no localnet list";
16099 else if (externip.sin_addr.s_addr == 0)
16100 msg = "Disabled, externip is 0.0.0.0";
16101 else if (stunaddr.sin_addr.s_addr != 0)
16102 msg = "Enabled using STUN";
16103 else if (!ast_strlen_zero(externhost))
16104 msg = "Enabled using externhost";
16105 else
16106 msg = "Enabled using externip";
16107 ast_cli(a->fd, " SIP address remapping: %s\n", msg);
16108 ast_cli(a->fd, " Externhost: %s\n", S_OR(externhost, "<none>"));
16109 ast_cli(a->fd, " Externip: %s:%d\n", ast_inet_ntoa(externip.sin_addr), ntohs(externip.sin_port));
16110 ast_cli(a->fd, " Externrefresh: %d\n", externrefresh);
16111 ast_cli(a->fd, " Internal IP: %s:%d\n", ast_inet_ntoa(internip.sin_addr), ntohs(internip.sin_port));
16112 {
16113 struct ast_ha *d;
16114 const char *prefix = "Localnet:";
16115 char buf[INET_ADDRSTRLEN];
16116
16117 for (d = localaddr; d ; prefix = "", d = d->next) {
16118 ast_cli(a->fd, " %-24s%s/%s\n",
16119 prefix, ast_inet_ntoa(d->netaddr),
16120 inet_ntop(AF_INET, &d->netmask, buf, sizeof(buf)) );
16121 }
16122 }
16123 ast_cli(a->fd, " STUN server: %s:%d\n", ast_inet_ntoa(stunaddr.sin_addr), ntohs(stunaddr.sin_port));
16124
16125 ast_cli(a->fd, "\nGlobal Signalling Settings:\n");
16126 ast_cli(a->fd, "---------------------------\n");
16127 ast_cli(a->fd, " Codecs: ");
16128 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, global_capability);
16129 ast_cli(a->fd, "%s\n", codec_buf);
16130 ast_cli(a->fd, " Codec Order: ");
16131 print_codec_to_cli(a->fd, &default_prefs);
16132 ast_cli(a->fd, "\n");
16133 ast_cli(a->fd, " Relax DTMF: %s\n", cli_yesno(global_relaxdtmf));
16134 ast_cli(a->fd, " RFC2833 Compensation: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_RFC2833_COMPENSATE)));
16135 ast_cli(a->fd, " Compact SIP headers: %s\n", cli_yesno(sip_cfg.compactheaders));
16136 ast_cli(a->fd, " RTP Keepalive: %d %s\n", global_rtpkeepalive, global_rtpkeepalive ? "" : "(Disabled)" );
16137 ast_cli(a->fd, " RTP Timeout: %d %s\n", global_rtptimeout, global_rtptimeout ? "" : "(Disabled)" );
16138 ast_cli(a->fd, " RTP Hold Timeout: %d %s\n", global_rtpholdtimeout, global_rtpholdtimeout ? "" : "(Disabled)");
16139 ast_cli(a->fd, " MWI NOTIFY mime type: %s\n", default_notifymime);
16140 ast_cli(a->fd, " DNS SRV lookup: %s\n", cli_yesno(sip_cfg.srvlookup));
16141 ast_cli(a->fd, " Pedantic SIP support: %s\n", cli_yesno(sip_cfg.pedanticsipchecking));
16142 ast_cli(a->fd, " Reg. min duration %d secs\n", min_expiry);
16143 ast_cli(a->fd, " Reg. max duration: %d secs\n", max_expiry);
16144 ast_cli(a->fd, " Reg. default duration: %d secs\n", default_expiry);
16145 ast_cli(a->fd, " Outbound reg. timeout: %d secs\n", global_reg_timeout);
16146 ast_cli(a->fd, " Outbound reg. attempts: %d\n", global_regattempts_max);
16147 ast_cli(a->fd, " Notify ringing state: %s\n", cli_yesno(sip_cfg.notifyringing));
16148 if (sip_cfg.notifyringing) {
16149 ast_cli(a->fd, " Include CID: %s%s\n",
16150 cli_yesno(sip_cfg.notifycid),
16151 sip_cfg.notifycid == IGNORE_CONTEXT ? " (Ignoring context)" : "");
16152 }
16153 ast_cli(a->fd, " Notify hold state: %s\n", cli_yesno(sip_cfg.notifyhold));
16154 ast_cli(a->fd, " SIP Transfer mode: %s\n", transfermode2str(sip_cfg.allowtransfer));
16155 ast_cli(a->fd, " Max Call Bitrate: %d kbps\n", default_maxcallbitrate);
16156 ast_cli(a->fd, " Auto-Framing: %s\n", cli_yesno(global_autoframing));
16157 ast_cli(a->fd, " Outb. proxy: %s %s\n", ast_strlen_zero(sip_cfg.outboundproxy.name) ? "<not set>" : sip_cfg.outboundproxy.name,
16158 sip_cfg.outboundproxy.force ? "(forced)" : "");
16159 ast_cli(a->fd, " Session Timers: %s\n", stmode2str(global_st_mode));
16160 ast_cli(a->fd, " Session Refresher: %s\n", strefresher2str (global_st_refresher));
16161 ast_cli(a->fd, " Session Expires: %d secs\n", global_max_se);
16162 ast_cli(a->fd, " Session Min-SE: %d secs\n", global_min_se);
16163 ast_cli(a->fd, " Timer T1: %d\n", global_t1);
16164 ast_cli(a->fd, " Timer T1 minimum: %d\n", global_t1min);
16165 ast_cli(a->fd, " Timer B: %d\n", global_timer_b);
16166 ast_cli(a->fd, " No premature media: %s\n", global_prematuremediafilter ? "Yes" : "No");
16167
16168 ast_cli(a->fd, "\nDefault Settings:\n");
16169 ast_cli(a->fd, "-----------------\n");
16170 ast_cli(a->fd, " Allowed transports: %s\n", get_transport_list(default_transports));
16171 ast_cli(a->fd, " Outbound transport: %s\n", get_transport(default_primary_transport));
16172 ast_cli(a->fd, " Context: %s\n", sip_cfg.default_context);
16173 ast_cli(a->fd, " Nat: %s\n", nat2str(ast_test_flag(&global_flags[0], SIP_NAT)));
16174 ast_cli(a->fd, " DTMF: %s\n", dtmfmode2str(ast_test_flag(&global_flags[0], SIP_DTMF)));
16175 ast_cli(a->fd, " Qualify: %d\n", default_qualify);
16176 ast_cli(a->fd, " Use ClientCode: %s\n", cli_yesno(ast_test_flag(&global_flags[0], SIP_USECLIENTCODE)));
16177 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" );
16178 ast_cli(a->fd, " Language: %s\n", default_language);
16179 ast_cli(a->fd, " MOH Interpret: %s\n", default_mohinterpret);
16180 ast_cli(a->fd, " MOH Suggest: %s\n", default_mohsuggest);
16181 ast_cli(a->fd, " Voice Mail Extension: %s\n", default_vmexten);
16182
16183
16184 if (realtimepeers || realtimeregs) {
16185 ast_cli(a->fd, "\nRealtime SIP Settings:\n");
16186 ast_cli(a->fd, "----------------------\n");
16187 ast_cli(a->fd, " Realtime Peers: %s\n", cli_yesno(realtimepeers));
16188 ast_cli(a->fd, " Realtime Regs: %s\n", cli_yesno(realtimeregs));
16189 ast_cli(a->fd, " Cache Friends: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)));
16190 ast_cli(a->fd, " Update: %s\n", cli_yesno(sip_cfg.peer_rtupdate));
16191 ast_cli(a->fd, " Ignore Reg. Expire: %s\n", cli_yesno(sip_cfg.ignore_regexpire));
16192 ast_cli(a->fd, " Save sys. name: %s\n", cli_yesno(sip_cfg.rtsave_sysname));
16193 ast_cli(a->fd, " Auto Clear: %d\n", sip_cfg.rtautoclear);
16194 }
16195 ast_cli(a->fd, "\n----\n");
16196 return CLI_SUCCESS;
16197 }
16198
16199 static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16200 {
16201 #define FORMAT "%-30.30s %-12.12s %-10.10s %-10.10s\n"
16202 char host[80];
16203
16204 switch (cmd) {
16205 case CLI_INIT:
16206 e->command = "sip show mwi";
16207 e->usage =
16208 "Usage: sip show mwi\n"
16209 " Provides a list of MWI subscriptions and status.\n";
16210 return NULL;
16211 case CLI_GENERATE:
16212 return NULL;
16213 }
16214
16215 ast_cli(a->fd, FORMAT, "Host", "Username", "Mailbox", "Subscribed");
16216
16217 ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
16218 ASTOBJ_RDLOCK(iterator);
16219 snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
16220 ast_cli(a->fd, FORMAT, host, iterator->username, iterator->mailbox, iterator->subscribed ? "Yes" : "No");
16221 ASTOBJ_UNLOCK(iterator);
16222 } while(0));
16223
16224 return CLI_SUCCESS;
16225 #undef FORMAT
16226 }
16227
16228
16229
16230 static const char *subscription_type2str(enum subscriptiontype subtype)
16231 {
16232 int i;
16233
16234 for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
16235 if (subscription_types[i].type == subtype) {
16236 return subscription_types[i].text;
16237 }
16238 }
16239 return subscription_types[0].text;
16240 }
16241
16242
16243 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype)
16244 {
16245 int i;
16246
16247 for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
16248 if (subscription_types[i].type == subtype) {
16249 return &subscription_types[i];
16250 }
16251 }
16252 return &subscription_types[0];
16253 }
16254
16255
16256
16257
16258
16259
16260
16261
16262 #define FORMAT4 "%-15.15s %-15.15s %-15.15s %-15.15s %-13.13s %-15.15s %-10.10s %-6.6d\n"
16263 #define FORMAT3 "%-15.15s %-15.15s %-15.15s %-15.15s %-13.13s %-15.15s %-10.10s %-6.6s\n"
16264 #define FORMAT2 "%-15.15s %-15.15s %-15.15s %-15.15s %-7.7s %-15.15s %-6.6s\n"
16265 #define FORMAT "%-15.15s %-15.15s %-15.15s %-15.15s %-3.3s %-3.3s %-15.15s %-10.10s\n"
16266
16267
16268 static int show_channels_cb(void *__cur, void *__arg, int flags)
16269 {
16270 struct sip_pvt *cur = __cur;
16271 struct __show_chan_arg *arg = __arg;
16272 const struct sockaddr_in *dst = sip_real_dst(cur);
16273
16274
16275 if (cur->subscribed == NONE && !arg->subscriptions) {
16276
16277 const char *referstatus = cur->refer ? referstatus2str(cur->refer->status) : "";
16278 char formatbuf[SIPBUFSIZE/2];
16279
16280 ast_cli(arg->fd, FORMAT, ast_inet_ntoa(dst->sin_addr),
16281 S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
16282 cur->callid,
16283 ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0),
16284 cli_yesno(ast_test_flag(&cur->flags[1], SIP_PAGE2_CALL_ONHOLD)),
16285 cur->needdestroy ? "(d)" : "",
16286 cur->lastmsg ,
16287 referstatus
16288 );
16289 arg->numchans++;
16290 }
16291 if (cur->subscribed != NONE && arg->subscriptions) {
16292 struct ast_str *mailbox_str = ast_str_alloca(512);
16293 if (cur->subscribed == MWI_NOTIFICATION && cur->relatedpeer)
16294 peer_mailboxes_to_str(&mailbox_str, cur->relatedpeer);
16295 ast_cli(arg->fd, FORMAT4, ast_inet_ntoa(dst->sin_addr),
16296 S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
16297 cur->callid,
16298
16299 cur->subscribed == MWI_NOTIFICATION ? "--" : cur->subscribeuri,
16300 cur->subscribed == MWI_NOTIFICATION ? "<none>" : ast_extension_state2str(cur->laststate),
16301 subscription_type2str(cur->subscribed),
16302 cur->subscribed == MWI_NOTIFICATION ? S_OR(mailbox_str->str, "<none>") : "<none>",
16303 cur->expiry
16304 );
16305 arg->numchans++;
16306 }
16307 return 0;
16308 }
16309
16310
16311
16312
16313
16314
16315 static char *sip_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16316 {
16317 struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
16318
16319
16320 if (cmd == CLI_INIT) {
16321 e->command = "sip show {channels|subscriptions}";
16322 e->usage =
16323 "Usage: sip show channels\n"
16324 " Lists all currently active SIP calls (dialogs).\n"
16325 "Usage: sip show subscriptions\n"
16326 " Lists active SIP subscriptions.\n";
16327 return NULL;
16328 } else if (cmd == CLI_GENERATE)
16329 return NULL;
16330
16331 if (a->argc != e->args)
16332 return CLI_SHOWUSAGE;
16333 arg.subscriptions = !strcasecmp(a->argv[e->args - 1], "subscriptions");
16334 if (!arg.subscriptions)
16335 ast_cli(arg.fd, FORMAT2, "Peer", "User/ANR", "Call ID", "Format", "Hold", "Last Message", "Expiry");
16336 else
16337 ast_cli(arg.fd, FORMAT3, "Peer", "User", "Call ID", "Extension", "Last state", "Type", "Mailbox", "Expiry");
16338
16339
16340 ao2_t_callback(dialogs, OBJ_NODATA, show_channels_cb, &arg, "callback to show channels");
16341
16342
16343 ast_cli(arg.fd, "%d active SIP %s%s\n", arg.numchans,
16344 (arg.subscriptions ? "subscription" : "dialog"),
16345 ESS(arg.numchans));
16346 return CLI_SUCCESS;
16347 #undef FORMAT
16348 #undef FORMAT2
16349 #undef FORMAT3
16350 }
16351
16352
16353
16354
16355
16356
16357 static char *complete_sipch(const char *line, const char *word, int pos, int state)
16358 {
16359 int which=0;
16360 struct sip_pvt *cur;
16361 char *c = NULL;
16362 int wordlen = strlen(word);
16363 struct ao2_iterator i;
16364
16365 if (pos != 3) {
16366 return NULL;
16367 }
16368
16369 i = ao2_iterator_init(dialogs, 0);
16370 while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
16371 sip_pvt_lock(cur);
16372 if (!strncasecmp(word, cur->callid, wordlen) && ++which > state) {
16373 c = ast_strdup(cur->callid);
16374 sip_pvt_unlock(cur);
16375 dialog_unref(cur, "drop ref in iterator loop break");
16376 break;
16377 }
16378 sip_pvt_unlock(cur);
16379 dialog_unref(cur, "drop ref in iterator loop");
16380 }
16381 ao2_iterator_destroy(&i);
16382 return c;
16383 }
16384
16385
16386
16387 static char *complete_sip_peer(const char *word, int state, int flags2)
16388 {
16389 char *result = NULL;
16390 int wordlen = strlen(word);
16391 int which = 0;
16392 struct ao2_iterator i = ao2_iterator_init(peers, 0);
16393 struct sip_peer *peer;
16394
16395 while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
16396
16397 if (!strncasecmp(word, peer->name, wordlen) &&
16398 (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
16399 ++which > state)
16400 result = ast_strdup(peer->name);
16401 unref_peer(peer, "toss iterator peer ptr before break");
16402 if (result) {
16403 break;
16404 }
16405 }
16406 ao2_iterator_destroy(&i);
16407 return result;
16408 }
16409
16410
16411 static char *complete_sip_registered_peer(const char *word, int state, int flags2)
16412 {
16413 char *result = NULL;
16414 int wordlen = strlen(word);
16415 int which = 0;
16416 struct ao2_iterator i;
16417 struct sip_peer *peer;
16418
16419 i = ao2_iterator_init(peers, 0);
16420 while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
16421 if (!strncasecmp(word, peer->name, wordlen) &&
16422 (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
16423 ++which > state && peer->expire > 0)
16424 result = ast_strdup(peer->name);
16425 if (result) {
16426 unref_peer(peer, "toss iterator peer ptr before break");
16427 break;
16428 }
16429 unref_peer(peer, "toss iterator peer ptr");
16430 }
16431 ao2_iterator_destroy(&i);
16432 return result;
16433 }
16434
16435
16436 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state)
16437 {
16438 if (pos == 3)
16439 return complete_sipch(line, word, pos, state);
16440
16441 return NULL;
16442 }
16443
16444
16445 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state)
16446 {
16447 if (pos == 3) {
16448 return complete_sip_peer(word, state, 0);
16449 }
16450
16451 return NULL;
16452 }
16453
16454
16455 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state)
16456 {
16457 if (pos == 2)
16458 return complete_sip_registered_peer(word, state, 0);
16459
16460 return NULL;
16461 }
16462
16463
16464 static char *complete_sipnotify(const char *line, const char *word, int pos, int state)
16465 {
16466 char *c = NULL;
16467
16468 if (pos == 2) {
16469 int which = 0;
16470 char *cat = NULL;
16471 int wordlen = strlen(word);
16472
16473
16474
16475 if (!notify_types)
16476 return NULL;
16477
16478 while ( (cat = ast_category_browse(notify_types, cat)) ) {
16479 if (!strncasecmp(word, cat, wordlen) && ++which > state) {
16480 c = ast_strdup(cat);
16481 break;
16482 }
16483 }
16484 return c;
16485 }
16486
16487 if (pos > 2)
16488 return complete_sip_peer(word, state, 0);
16489
16490 return NULL;
16491 }
16492
16493
16494 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16495 {
16496 struct sip_pvt *cur;
16497 size_t len;
16498 int found = 0;
16499 struct ao2_iterator i;
16500
16501 switch (cmd) {
16502 case CLI_INIT:
16503 e->command = "sip show channel";
16504 e->usage =
16505 "Usage: sip show channel <call-id>\n"
16506 " Provides detailed status on a given SIP dialog (identified by SIP call-id).\n";
16507 return NULL;
16508 case CLI_GENERATE:
16509 return complete_sipch(a->line, a->word, a->pos, a->n);
16510 }
16511
16512 if (a->argc != 4)
16513 return CLI_SHOWUSAGE;
16514 len = strlen(a->argv[3]);
16515
16516 i = ao2_iterator_init(dialogs, 0);
16517 while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
16518 sip_pvt_lock(cur);
16519
16520 if (!strncasecmp(cur->callid, a->argv[3], len)) {
16521 char formatbuf[SIPBUFSIZE/2];
16522 ast_cli(a->fd, "\n");
16523 if (cur->subscribed != NONE)
16524 ast_cli(a->fd, " * Subscription (type: %s)\n", subscription_type2str(cur->subscribed));
16525 else
16526 ast_cli(a->fd, " * SIP Call\n");
16527 ast_cli(a->fd, " Curr. trans. direction: %s\n", ast_test_flag(&cur->flags[0], SIP_OUTGOING) ? "Outgoing" : "Incoming");
16528 ast_cli(a->fd, " Call-ID: %s\n", cur->callid);
16529 ast_cli(a->fd, " Owner channel ID: %s\n", cur->owner ? cur->owner->name : "<none>");
16530 ast_cli(a->fd, " Our Codec Capability: %d\n", cur->capability);
16531 ast_cli(a->fd, " Non-Codec Capability (DTMF): %d\n", cur->noncodeccapability);
16532 ast_cli(a->fd, " Their Codec Capability: %d\n", cur->peercapability);
16533 ast_cli(a->fd, " Joint Codec Capability: %d\n", cur->jointcapability);
16534 ast_cli(a->fd, " Format: %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0) );
16535 ast_cli(a->fd, " T.38 support %s\n", cli_yesno(cur->udptl != NULL));
16536 ast_cli(a->fd, " Video support %s\n", cli_yesno(cur->vrtp != NULL));
16537 ast_cli(a->fd, " MaxCallBR: %d kbps\n", cur->maxcallbitrate);
16538 ast_cli(a->fd, " Theoretical Address: %s:%d\n", ast_inet_ntoa(cur->sa.sin_addr), ntohs(cur->sa.sin_port));
16539 ast_cli(a->fd, " Received Address: %s:%d\n", ast_inet_ntoa(cur->recv.sin_addr), ntohs(cur->recv.sin_port));
16540 ast_cli(a->fd, " SIP Transfer mode: %s\n", transfermode2str(cur->allowtransfer));
16541 ast_cli(a->fd, " NAT Support: %s\n", nat2str(ast_test_flag(&cur->flags[0], SIP_NAT)));
16542 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)" );
16543 ast_cli(a->fd, " Our Tag: %s\n", cur->tag);
16544 ast_cli(a->fd, " Their Tag: %s\n", cur->theirtag);
16545 ast_cli(a->fd, " SIP User agent: %s\n", cur->useragent);
16546 if (!ast_strlen_zero(cur->username))
16547 ast_cli(a->fd, " Username: %s\n", cur->username);
16548 if (!ast_strlen_zero(cur->peername))
16549 ast_cli(a->fd, " Peername: %s\n", cur->peername);
16550 if (!ast_strlen_zero(cur->uri))
16551 ast_cli(a->fd, " Original uri: %s\n", cur->uri);
16552 if (!ast_strlen_zero(cur->cid_num))
16553 ast_cli(a->fd, " Caller-ID: %s\n", cur->cid_num);
16554 ast_cli(a->fd, " Need Destroy: %s\n", cli_yesno(cur->needdestroy));
16555 ast_cli(a->fd, " Last Message: %s\n", cur->lastmsg);
16556 ast_cli(a->fd, " Promiscuous Redir: %s\n", cli_yesno(ast_test_flag(&cur->flags[0], SIP_PROMISCREDIR)));
16557 ast_cli(a->fd, " Route: %s\n", cur->route ? cur->route->hop : "N/A");
16558 ast_cli(a->fd, " DTMF Mode: %s\n", dtmfmode2str(ast_test_flag(&cur->flags[0], SIP_DTMF)));
16559 ast_cli(a->fd, " SIP Options: ");
16560 if (cur->sipoptions) {
16561 int x;
16562 for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
16563 if (cur->sipoptions & sip_options[x].id)
16564 ast_cli(a->fd, "%s ", sip_options[x].text);
16565 }
16566 ast_cli(a->fd, "\n");
16567 } else
16568 ast_cli(a->fd, "(none)\n");
16569
16570 if (!cur->stimer)
16571 ast_cli(a->fd, " Session-Timer: Uninitiallized\n");
16572 else {
16573 ast_cli(a->fd, " Session-Timer: %s\n", cur->stimer->st_active ? "Active" : "Inactive");
16574 if (cur->stimer->st_active == TRUE) {
16575 ast_cli(a->fd, " S-Timer Interval: %d\n", cur->stimer->st_interval);
16576 ast_cli(a->fd, " S-Timer Refresher: %s\n", strefresher2str(cur->stimer->st_ref));
16577 ast_cli(a->fd, " S-Timer Expirys: %d\n", cur->stimer->st_expirys);
16578 ast_cli(a->fd, " S-Timer Sched Id: %d\n", cur->stimer->st_schedid);
16579 ast_cli(a->fd, " S-Timer Peer Sts: %s\n", cur->stimer->st_active_peer_ua ? "Active" : "Inactive");
16580 ast_cli(a->fd, " S-Timer Cached Min-SE: %d\n", cur->stimer->st_cached_min_se);
16581 ast_cli(a->fd, " S-Timer Cached SE: %d\n", cur->stimer->st_cached_max_se);
16582 ast_cli(a->fd, " S-Timer Cached Ref: %s\n", strefresher2str(cur->stimer->st_cached_ref));
16583 ast_cli(a->fd, " S-Timer Cached Mode: %s\n", stmode2str(cur->stimer->st_cached_mode));
16584 }
16585 }
16586
16587 ast_cli(a->fd, "\n\n");
16588
16589 found++;
16590 }
16591
16592 sip_pvt_unlock(cur);
16593
16594 ao2_t_ref(cur, -1, "toss dialog ptr set by iterator_next");
16595 }
16596 ao2_iterator_destroy(&i);
16597
16598 if (!found)
16599 ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
16600
16601 return CLI_SUCCESS;
16602 }
16603
16604
16605 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16606 {
16607 struct sip_pvt *cur;
16608 size_t len;
16609 int found = 0;
16610 struct ao2_iterator i;
16611
16612 switch (cmd) {
16613 case CLI_INIT:
16614 e->command = "sip show history";
16615 e->usage =
16616 "Usage: sip show history <call-id>\n"
16617 " Provides detailed dialog history on a given SIP call (specified by call-id).\n";
16618 return NULL;
16619 case CLI_GENERATE:
16620 return complete_sip_show_history(a->line, a->word, a->pos, a->n);
16621 }
16622
16623 if (a->argc != 4)
16624 return CLI_SHOWUSAGE;
16625
16626 if (!recordhistory)
16627 ast_cli(a->fd, "\n***Note: History recording is currently DISABLED. Use 'sip set history on' to ENABLE.\n");
16628
16629 len = strlen(a->argv[3]);
16630
16631 i = ao2_iterator_init(dialogs, 0);
16632 while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
16633 sip_pvt_lock(cur);
16634 if (!strncasecmp(cur->callid, a->argv[3], len)) {
16635 struct sip_history *hist;
16636 int x = 0;
16637
16638 ast_cli(a->fd, "\n");
16639 if (cur->subscribed != NONE)
16640 ast_cli(a->fd, " * Subscription\n");
16641 else
16642 ast_cli(a->fd, " * SIP Call\n");
16643 if (cur->history)
16644 AST_LIST_TRAVERSE(cur->history, hist, list)
16645 ast_cli(a->fd, "%d. %s\n", ++x, hist->event);
16646 if (x == 0)
16647 ast_cli(a->fd, "Call '%s' has no history\n", cur->callid);
16648 found++;
16649 }
16650 sip_pvt_unlock(cur);
16651 ao2_t_ref(cur, -1, "toss dialog ptr from iterator_next");
16652 }
16653 ao2_iterator_destroy(&i);
16654
16655 if (!found)
16656 ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
16657
16658 return CLI_SUCCESS;
16659 }
16660
16661
16662 static void sip_dump_history(struct sip_pvt *dialog)
16663 {
16664 int x = 0;
16665 struct sip_history *hist;
16666 static int errmsg = 0;
16667
16668 if (!dialog)
16669 return;
16670
16671 if (!option_debug && !sipdebug) {
16672 if (!errmsg) {
16673 ast_log(LOG_NOTICE, "You must have debugging enabled (SIP or Asterisk) in order to dump SIP history.\n");
16674 errmsg = 1;
16675 }
16676 return;
16677 }
16678
16679 ast_debug(1, "\n---------- SIP HISTORY for '%s' \n", dialog->callid);
16680 if (dialog->subscribed)
16681 ast_debug(1, " * Subscription\n");
16682 else
16683 ast_debug(1, " * SIP Call\n");
16684 if (dialog->history)
16685 AST_LIST_TRAVERSE(dialog->history, hist, list)
16686 ast_debug(1, " %-3.3d. %s\n", ++x, hist->event);
16687 if (!x)
16688 ast_debug(1, "Call '%s' has no history\n", dialog->callid);
16689 ast_debug(1, "\n---------- END SIP HISTORY for '%s' \n", dialog->callid);
16690 }
16691
16692
16693
16694 static void handle_request_info(struct sip_pvt *p, struct sip_request *req)
16695 {
16696 char buf[1024];
16697 unsigned int event;
16698 const char *c = get_header(req, "Content-Type");
16699
16700
16701 if (!strcasecmp(c, "application/dtmf-relay") ||
16702 !strcasecmp(c, "application/vnd.nortelnetworks.digits")) {
16703 unsigned int duration = 0;
16704
16705 if (!p->owner) {
16706 transmit_response(p, "481 Call leg/transaction does not exist", req);
16707 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16708 return;
16709 }
16710
16711
16712 if (ast_strlen_zero(c = get_body(req, "Signal", '=')) && ast_strlen_zero(c = get_body(req, "d", '='))) {
16713 ast_log(LOG_WARNING, "Unable to retrieve DTMF signal from INFO message from %s\n", p->callid);
16714 transmit_response(p, "200 OK", req);
16715 return;
16716 } else {
16717 ast_copy_string(buf, c, sizeof(buf));
16718 }
16719
16720 if (!ast_strlen_zero((c = get_body(req, "Duration", '='))))
16721 duration = atoi(c);
16722 if (!duration)
16723 duration = 100;
16724
16725
16726 if (ast_strlen_zero(buf)) {
16727 transmit_response(p, "200 OK", req);
16728 return;
16729 }
16730
16731 if (buf[0] == '*')
16732 event = 10;
16733 else if (buf[0] == '#')
16734 event = 11;
16735 else if ((buf[0] >= 'A') && (buf[0] <= 'D'))
16736 event = 12 + buf[0] - 'A';
16737 else if (buf[0] == '!')
16738 event = 16;
16739 else
16740 event = atoi(buf);
16741 if (event == 16) {
16742
16743 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_FLASH, };
16744 ast_queue_frame(p->owner, &f);
16745 if (sipdebug)
16746 ast_verbose("* DTMF-relay event received: FLASH\n");
16747 } else {
16748
16749 struct ast_frame f = { AST_FRAME_DTMF, };
16750 if (event < 10) {
16751 f.subclass = '0' + event;
16752 } else if (event < 11) {
16753 f.subclass = '*';
16754 } else if (event < 12) {
16755 f.subclass = '#';
16756 } else if (event < 16) {
16757 f.subclass = 'A' + (event - 12);
16758 }
16759 f.len = duration;
16760 ast_queue_frame(p->owner, &f);
16761 if (sipdebug)
16762 ast_verbose("* DTMF-relay event received: %c\n", f.subclass);
16763 }
16764 transmit_response(p, "200 OK", req);
16765 return;
16766 } else if (!strcasecmp(c, "application/dtmf")) {
16767
16768 unsigned int duration = 0;
16769
16770 if (!p->owner) {
16771 transmit_response(p, "481 Call leg/transaction does not exist", req);
16772 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16773 return;
16774 }
16775
16776 get_msg_text(buf, sizeof(buf), req, TRUE);
16777 duration = 100;
16778
16779 if (ast_strlen_zero(buf)) {
16780 transmit_response(p, "200 OK", req);
16781 return;
16782 }
16783 event = atoi(buf);
16784 if (event == 16) {
16785
16786 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_FLASH, };
16787 ast_queue_frame(p->owner, &f);
16788 if (sipdebug)
16789 ast_verbose("* DTMF-relay event received: FLASH\n");
16790 } else {
16791
16792 struct ast_frame f = { AST_FRAME_DTMF, };
16793 if (event < 10) {
16794 f.subclass = '0' + event;
16795 } else if (event < 11) {
16796 f.subclass = '*';
16797 } else if (event < 12) {
16798 f.subclass = '#';
16799 } else if (event < 16) {
16800 f.subclass = 'A' + (event - 12);
16801 }
16802 f.len = duration;
16803 ast_queue_frame(p->owner, &f);
16804 if (sipdebug)
16805 ast_verbose("* DTMF-relay event received: %c\n", f.subclass);
16806 }
16807 transmit_response(p, "200 OK", req);
16808 return;
16809
16810 } else if (!strcasecmp(c, "application/media_control+xml")) {
16811
16812 if (p->owner)
16813 ast_queue_control(p->owner, AST_CONTROL_VIDUPDATE);
16814 transmit_response(p, "200 OK", req);
16815 return;
16816 } else if (!ast_strlen_zero(c = get_header(req, "X-ClientCode"))) {
16817
16818 if (ast_test_flag(&p->flags[0], SIP_USECLIENTCODE)) {
16819 if (p->owner && p->owner->cdr)
16820 ast_cdr_setuserfield(p->owner, c);
16821 if (p->owner && ast_bridged_channel(p->owner) && ast_bridged_channel(p->owner)->cdr)
16822 ast_cdr_setuserfield(ast_bridged_channel(p->owner), c);
16823 transmit_response(p, "200 OK", req);
16824 } else {
16825 transmit_response(p, "403 Forbidden", req);
16826 }
16827 return;
16828 } else if (!ast_strlen_zero(c = get_header(req, "Record"))) {
16829
16830
16831
16832
16833
16834
16835
16836 struct ast_call_feature *feat;
16837 int j;
16838 struct ast_frame f = { AST_FRAME_DTMF, };
16839
16840 ast_rdlock_call_features();
16841 feat = ast_find_call_feature("automon");
16842 if (!feat || ast_strlen_zero(feat->exten)) {
16843 ast_log(LOG_WARNING, "Recording requested, but no One Touch Monitor registered. (See features.conf)\n");
16844
16845 transmit_response(p, "403 Forbidden", req);
16846 ast_unlock_call_features();
16847 return;
16848 }
16849
16850 f.len = 100;
16851 for (j=0; j < strlen(feat->exten); j++) {
16852 f.subclass = feat->exten[j];
16853 ast_queue_frame(p->owner, &f);
16854 if (sipdebug)
16855 ast_verbose("* DTMF-relay event faked: %c\n", f.subclass);
16856 }
16857 ast_unlock_call_features();
16858
16859 ast_debug(1, "Got a Request to Record the channel, state %s\n", c);
16860 transmit_response(p, "200 OK", req);
16861 return;
16862 } else if (ast_strlen_zero(c = get_header(req, "Content-Length")) || !strcasecmp(c, "0")) {
16863
16864 transmit_response(p, "200 OK", req);
16865 return;
16866 }
16867
16868
16869
16870
16871 ast_log(LOG_WARNING, "Unable to parse INFO message from %s. Content %s\n", p->callid, buf);
16872 transmit_response(p, "415 Unsupported media type", req);
16873 return;
16874 }
16875
16876
16877 static char *sip_do_debug_ip(int fd, char *arg)
16878 {
16879 struct hostent *hp;
16880 struct ast_hostent ahp;
16881 int port = 0;
16882 char *p;
16883
16884 p = arg;
16885 strsep(&p, ":");
16886 if (p)
16887 port = atoi(p);
16888 hp = ast_gethostbyname(arg, &ahp);
16889 if (hp == NULL)
16890 return CLI_SHOWUSAGE;
16891
16892 debugaddr.sin_family = AF_INET;
16893 memcpy(&debugaddr.sin_addr, hp->h_addr, sizeof(debugaddr.sin_addr));
16894 debugaddr.sin_port = htons(port);
16895 if (port == 0)
16896 ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_inet_ntoa(debugaddr.sin_addr));
16897 else
16898 ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(debugaddr.sin_addr), port);
16899
16900 sipdebug |= sip_debug_console;
16901
16902 return CLI_SUCCESS;
16903 }
16904
16905
16906 static char *sip_do_debug_peer(int fd, char *arg)
16907 {
16908 struct sip_peer *peer = find_peer(arg, NULL, TRUE, FINDPEERS, FALSE, 0);
16909 if (!peer)
16910 ast_cli(fd, "No such peer '%s'\n", arg);
16911 else if (peer->addr.sin_addr.s_addr == 0)
16912 ast_cli(fd, "Unable to get IP address of peer '%s'\n", arg);
16913 else {
16914 debugaddr.sin_family = AF_INET;
16915 debugaddr.sin_addr = peer->addr.sin_addr;
16916 debugaddr.sin_port = peer->addr.sin_port;
16917 ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n",
16918 ast_inet_ntoa(debugaddr.sin_addr), ntohs(debugaddr.sin_port));
16919 sipdebug |= sip_debug_console;
16920 }
16921 if (peer)
16922 unref_peer(peer, "sip_do_debug_peer: unref_peer, from find_peer call");
16923 return CLI_SUCCESS;
16924 }
16925
16926
16927 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16928 {
16929 int oldsipdebug = sipdebug & sip_debug_console;
16930 char *what;
16931
16932 if (cmd == CLI_INIT) {
16933 e->command = "sip set debug {on|off|ip|peer}";
16934 e->usage =
16935 "Usage: sip set debug {off|on|ip addr[:port]|peer peername}\n"
16936 " Globally disables dumping of SIP packets,\n"
16937 " or enables it either globally or for a (single)\n"
16938 " IP address or registered peer.\n";
16939 return NULL;
16940 } else if (cmd == CLI_GENERATE) {
16941 if (a->pos == 4 && !strcasecmp(a->argv[3], "peer"))
16942 return complete_sip_peer(a->word, a->n, 0);
16943 return NULL;
16944 }
16945
16946 what = a->argv[e->args-1];
16947 if (a->argc == e->args) {
16948 if (!strcasecmp(what, "on")) {
16949 sipdebug |= sip_debug_console;
16950 sipdebug_text = 1;
16951 memset(&debugaddr, 0, sizeof(debugaddr));
16952 ast_cli(a->fd, "SIP Debugging %senabled\n", oldsipdebug ? "re-" : "");
16953 return CLI_SUCCESS;
16954 } else if (!strcasecmp(what, "off")) {
16955 sipdebug &= ~sip_debug_console;
16956 sipdebug_text = 0;
16957 ast_cli(a->fd, "SIP Debugging Disabled\n");
16958 return CLI_SUCCESS;
16959 }
16960 } else if (a->argc == e->args +1) {
16961 if (!strcasecmp(what, "ip"))
16962 return sip_do_debug_ip(a->fd, a->argv[e->args]);
16963 else if (!strcasecmp(what, "peer"))
16964 return sip_do_debug_peer(a->fd, a->argv[e->args]);
16965 }
16966 return CLI_SHOWUSAGE;
16967 }
16968
16969
16970 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16971 {
16972 struct ast_variable *varlist;
16973 int i;
16974
16975 switch (cmd) {
16976 case CLI_INIT:
16977 e->command = "sip notify";
16978 e->usage =
16979 "Usage: sip notify <type> <peer> [<peer>...]\n"
16980 " Send a NOTIFY message to a SIP peer or peers\n"
16981 " Message types are defined in sip_notify.conf\n";
16982 return NULL;
16983 case CLI_GENERATE:
16984 return complete_sipnotify(a->line, a->word, a->pos, a->n);
16985 }
16986
16987 if (a->argc < 4)
16988 return CLI_SHOWUSAGE;
16989
16990 if (!notify_types) {
16991 ast_cli(a->fd, "No %s file found, or no types listed there\n", notify_config);
16992 return CLI_FAILURE;
16993 }
16994
16995 varlist = ast_variable_browse(notify_types, a->argv[2]);
16996
16997 if (!varlist) {
16998 ast_cli(a->fd, "Unable to find notify type '%s'\n", a->argv[2]);
16999 return CLI_FAILURE;
17000 }
17001
17002 for (i = 3; i < a->argc; i++) {
17003 struct sip_pvt *p;
17004
17005 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
17006 ast_log(LOG_WARNING, "Unable to build sip pvt data for notify (memory/socket error)\n");
17007 return CLI_FAILURE;
17008 }
17009
17010 if (create_addr(p, a->argv[i], NULL, 1)) {
17011
17012 dialog_unlink_all(p, TRUE, TRUE);
17013 dialog_unref(p, "unref dialog inside for loop" );
17014
17015 ast_cli(a->fd, "Could not create address for '%s'\n", a->argv[i]);
17016 continue;
17017 }
17018
17019
17020 ast_set_flag(&p->flags[0], SIP_OUTGOING);
17021
17022
17023 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
17024 build_via(p);
17025 ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
17026 build_callid_pvt(p);
17027 ao2_t_link(dialogs, p, "Linking in new name");
17028 ast_cli(a->fd, "Sending NOTIFY of type '%s' to '%s'\n", a->argv[2], a->argv[i]);
17029 dialog_ref(p, "bump the count of p, which transmit_sip_request will decrement.");
17030 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
17031 transmit_notify_custom(p, varlist);
17032 }
17033
17034 return CLI_SUCCESS;
17035 }
17036
17037
17038 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17039 {
17040 switch (cmd) {
17041 case CLI_INIT:
17042 e->command = "sip set history {on|off}";
17043 e->usage =
17044 "Usage: sip set history {on|off}\n"
17045 " Enables/Disables recording of SIP dialog history for debugging purposes.\n"
17046 " Use 'sip show history' to view the history of a call number.\n";
17047 return NULL;
17048 case CLI_GENERATE:
17049 return NULL;
17050 }
17051
17052 if (a->argc != e->args)
17053 return CLI_SHOWUSAGE;
17054
17055 if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
17056 recordhistory = TRUE;
17057 ast_cli(a->fd, "SIP History Recording Enabled (use 'sip show history')\n");
17058 } else if (!strncasecmp(a->argv[e->args - 1], "off", 3)) {
17059 recordhistory = FALSE;
17060 ast_cli(a->fd, "SIP History Recording Disabled\n");
17061 } else {
17062 return CLI_SHOWUSAGE;
17063 }
17064 return CLI_SUCCESS;
17065 }
17066
17067
17068 static int do_register_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code)
17069 {
17070 char *header, *respheader;
17071 char digest[1024];
17072
17073 p->authtries++;
17074 auth_headers(code, &header, &respheader);
17075 memset(digest, 0, sizeof(digest));
17076 if (reply_digest(p, req, header, SIP_REGISTER, digest, sizeof(digest))) {
17077
17078
17079 if (sip_debug_test_pvt(p) && p->registry)
17080 ast_verbose("No authentication challenge, sending blank registration to domain/host name %s\n", p->registry->hostname);
17081
17082 return -1;
17083 }
17084 if (p->do_history)
17085 append_history(p, "RegistryAuth", "Try: %d", p->authtries);
17086 if (sip_debug_test_pvt(p) && p->registry)
17087 ast_verbose("Responding to challenge, registration to domain/host name %s\n", p->registry->hostname);
17088 return transmit_register(p->registry, SIP_REGISTER, digest, respheader);
17089 }
17090
17091
17092 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code, int sipmethod, int init)
17093 {
17094 char *header, *respheader;
17095 char digest[1024];
17096
17097 if (!p->options && !(p->options = ast_calloc(1, sizeof(*p->options))))
17098 return -2;
17099
17100 p->authtries++;
17101 auth_headers(code, &header, &respheader);
17102 ast_debug(2, "Auth attempt %d on %s\n", p->authtries, sip_methods[sipmethod].text);
17103 memset(digest, 0, sizeof(digest));
17104 if (reply_digest(p, req, header, sipmethod, digest, sizeof(digest) )) {
17105
17106 return -1;
17107 }
17108
17109 p->options->auth = digest;
17110 p->options->authheader = respheader;
17111 return transmit_invite(p, sipmethod, sipmethod == SIP_INVITE, init);
17112 }
17113
17114
17115
17116
17117
17118 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len)
17119 {
17120 char tmp[512];
17121 char *c;
17122 char oldnonce[256];
17123
17124
17125 const struct x {
17126 const char *key;
17127 const ast_string_field *field;
17128 } *i, keys[] = {
17129 { "realm=", &p->realm },
17130 { "nonce=", &p->nonce },
17131 { "opaque=", &p->opaque },
17132 { "qop=", &p->qop },
17133 { "domain=", &p->domain },
17134 { NULL, 0 },
17135 };
17136
17137 ast_copy_string(tmp, get_header(req, header), sizeof(tmp));
17138 if (ast_strlen_zero(tmp))
17139 return -1;
17140 if (strncasecmp(tmp, "Digest ", strlen("Digest "))) {
17141 ast_log(LOG_WARNING, "missing Digest.\n");
17142 return -1;
17143 }
17144 c = tmp + strlen("Digest ");
17145 ast_copy_string(oldnonce, p->nonce, sizeof(oldnonce));
17146 while (c && *(c = ast_skip_blanks(c))) {
17147 for (i = keys; i->key != NULL; i++) {
17148 char *src, *separator;
17149 if (strncasecmp(c, i->key, strlen(i->key)) != 0)
17150 continue;
17151
17152 c += strlen(i->key);
17153 if (*c == '"') {
17154 src = ++c;
17155 separator = "\"";
17156 } else {
17157 src = c;
17158 separator = ",";
17159 }
17160 strsep(&c, separator);
17161 ast_string_field_ptr_set(p, i->field, src);
17162 break;
17163 }
17164 if (i->key == NULL)
17165 strsep(&c, ",");
17166 }
17167
17168 if (strcmp(p->nonce, oldnonce))
17169 p->noncecount = 0;
17170
17171
17172 if (p->registry) {
17173 struct sip_registry *r = p->registry;
17174
17175 if (strcmp(r->nonce, p->nonce)) {
17176 ast_string_field_set(r, realm, p->realm);
17177 ast_string_field_set(r, nonce, p->nonce);
17178 ast_string_field_set(r, domain, p->domain);
17179 ast_string_field_set(r, opaque, p->opaque);
17180 ast_string_field_set(r, qop, p->qop);
17181 r->noncecount = 0;
17182 }
17183 }
17184 return build_reply_digest(p, sipmethod, digest, digest_len);
17185 }
17186
17187
17188
17189
17190
17191
17192 static int build_reply_digest(struct sip_pvt *p, int method, char* digest, int digest_len)
17193 {
17194 char a1[256];
17195 char a2[256];
17196 char a1_hash[256];
17197 char a2_hash[256];
17198 char resp[256];
17199 char resp_hash[256];
17200 char uri[256];
17201 char opaque[256] = "";
17202 char cnonce[80];
17203 const char *username;
17204 const char *secret;
17205 const char *md5secret;
17206 struct sip_auth *auth = NULL;
17207
17208 if (!ast_strlen_zero(p->domain))
17209 ast_copy_string(uri, p->domain, sizeof(uri));
17210 else if (!ast_strlen_zero(p->uri))
17211 ast_copy_string(uri, p->uri, sizeof(uri));
17212 else
17213 snprintf(uri, sizeof(uri), "sip:%s@%s", p->username, ast_inet_ntoa(p->sa.sin_addr));
17214
17215 snprintf(cnonce, sizeof(cnonce), "%08lx", ast_random());
17216
17217
17218 if(!(auth = find_realm_authentication(p->peerauth, p->realm)))
17219 auth = find_realm_authentication(authl, p->realm);
17220
17221 if (auth) {
17222 ast_debug(3, "use realm [%s] from peer [%s][%s]\n", auth->username, p->peername, p->username);
17223 username = auth->username;
17224 secret = auth->secret;
17225 md5secret = auth->md5secret;
17226 if (sipdebug)
17227 ast_debug(1, "Using realm %s authentication for call %s\n", p->realm, p->callid);
17228 } else {
17229
17230 username = p->authname;
17231 secret = p->peersecret;
17232 md5secret = p->peermd5secret;
17233 }
17234 if (ast_strlen_zero(username))
17235 return -1;
17236
17237
17238 snprintf(a1, sizeof(a1), "%s:%s:%s", username, p->realm, secret);
17239 snprintf(a2, sizeof(a2), "%s:%s", sip_methods[method].text, uri);
17240 if (!ast_strlen_zero(md5secret))
17241 ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
17242 else
17243 ast_md5_hash(a1_hash, a1);
17244 ast_md5_hash(a2_hash, a2);
17245
17246 p->noncecount++;
17247 if (!ast_strlen_zero(p->qop))
17248 snprintf(resp, sizeof(resp), "%s:%s:%08x:%s:%s:%s", a1_hash, p->nonce, p->noncecount, cnonce, "auth", a2_hash);
17249 else
17250 snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, p->nonce, a2_hash);
17251 ast_md5_hash(resp_hash, resp);
17252
17253
17254 if (!ast_strlen_zero(p->opaque)) {
17255 snprintf(opaque, sizeof(opaque), ", opaque=\"%s\"", p->opaque);
17256 }
17257
17258
17259 if (!ast_strlen_zero(p->qop))
17260 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);
17261 else
17262 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);
17263
17264 append_history(p, "AuthResp", "Auth response sent for %s in realm %s - nc %d", username, p->realm, p->noncecount);
17265
17266 return 0;
17267 }
17268
17269
17270 static int func_header_read(struct ast_channel *chan, const char *function, char *data, char *buf, size_t len)
17271 {
17272 struct sip_pvt *p;
17273 const char *content = NULL;
17274 AST_DECLARE_APP_ARGS(args,
17275 AST_APP_ARG(header);
17276 AST_APP_ARG(number);
17277 );
17278 int i, number, start = 0;
17279
17280 if (ast_strlen_zero(data)) {
17281 ast_log(LOG_WARNING, "This function requires a header name.\n");
17282 return -1;
17283 }
17284
17285 ast_channel_lock(chan);
17286 if (!IS_SIP_TECH(chan->tech)) {
17287 ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
17288 ast_channel_unlock(chan);
17289 return -1;
17290 }
17291
17292 AST_STANDARD_APP_ARGS(args, data);
17293 if (!args.number) {
17294 number = 1;
17295 } else {
17296 sscanf(args.number, "%30d", &number);
17297 if (number < 1)
17298 number = 1;
17299 }
17300
17301 p = chan->tech_pvt;
17302
17303
17304 if (!p) {
17305 ast_channel_unlock(chan);
17306 return -1;
17307 }
17308
17309 for (i = 0; i < number; i++)
17310 content = __get_header(&p->initreq, args.header, &start);
17311
17312 if (ast_strlen_zero(content)) {
17313 ast_channel_unlock(chan);
17314 return -1;
17315 }
17316
17317 ast_copy_string(buf, content, len);
17318 ast_channel_unlock(chan);
17319
17320 return 0;
17321 }
17322
17323 static struct ast_custom_function sip_header_function = {
17324 .name = "SIP_HEADER",
17325 .read = func_header_read,
17326 };
17327
17328
17329 static int func_check_sipdomain(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
17330 {
17331 if (ast_strlen_zero(data)) {
17332 ast_log(LOG_WARNING, "CHECKSIPDOMAIN requires an argument - A domain name\n");
17333 return -1;
17334 }
17335 if (check_sip_domain(data, NULL, 0))
17336 ast_copy_string(buf, data, len);
17337 else
17338 buf[0] = '\0';
17339 return 0;
17340 }
17341
17342 static struct ast_custom_function checksipdomain_function = {
17343 .name = "CHECKSIPDOMAIN",
17344 .read = func_check_sipdomain,
17345 };
17346
17347
17348 static int function_sippeer(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
17349 {
17350 struct sip_peer *peer;
17351 char *colname;
17352
17353 if ((colname = strchr(data, ':'))) {
17354 static int deprecation_warning = 0;
17355 *colname++ = '\0';
17356 if (deprecation_warning++ % 10 == 0)
17357 ast_log(LOG_WARNING, "SIPPEER(): usage of ':' to separate arguments is deprecated. Please use ',' instead.\n");
17358 } else if ((colname = strchr(data, ',')))
17359 *colname++ = '\0';
17360 else
17361 colname = "ip";
17362
17363 if (!(peer = find_peer(data, NULL, TRUE, FINDPEERS, FALSE, 0)))
17364 return -1;
17365
17366 if (!strcasecmp(colname, "ip")) {
17367 ast_copy_string(buf, peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "", len);
17368 } else if (!strcasecmp(colname, "port")) {
17369 snprintf(buf, len, "%d", ntohs(peer->addr.sin_port));
17370 } else if (!strcasecmp(colname, "status")) {
17371 peer_status(peer, buf, len);
17372 } else if (!strcasecmp(colname, "language")) {
17373 ast_copy_string(buf, peer->language, len);
17374 } else if (!strcasecmp(colname, "regexten")) {
17375 ast_copy_string(buf, peer->regexten, len);
17376 } else if (!strcasecmp(colname, "limit")) {
17377 snprintf(buf, len, "%d", peer->call_limit);
17378 } else if (!strcasecmp(colname, "busylevel")) {
17379 snprintf(buf, len, "%d", peer->busy_level);
17380 } else if (!strcasecmp(colname, "curcalls")) {
17381 snprintf(buf, len, "%d", peer->inUse);
17382 } else if (!strcasecmp(colname, "accountcode")) {
17383 ast_copy_string(buf, peer->accountcode, len);
17384 } else if (!strcasecmp(colname, "callgroup")) {
17385 ast_print_group(buf, len, peer->callgroup);
17386 } else if (!strcasecmp(colname, "pickupgroup")) {
17387 ast_print_group(buf, len, peer->pickupgroup);
17388 } else if (!strcasecmp(colname, "useragent")) {
17389 ast_copy_string(buf, peer->useragent, len);
17390 } else if (!strcasecmp(colname, "mailbox")) {
17391 struct ast_str *mailbox_str = ast_str_alloca(512);
17392 peer_mailboxes_to_str(&mailbox_str, peer);
17393 ast_copy_string(buf, mailbox_str->str, len);
17394 } else if (!strcasecmp(colname, "context")) {
17395 ast_copy_string(buf, peer->context, len);
17396 } else if (!strcasecmp(colname, "expire")) {
17397 snprintf(buf, len, "%d", peer->expire);
17398 } else if (!strcasecmp(colname, "dynamic")) {
17399 ast_copy_string(buf, peer->host_dynamic ? "yes" : "no", len);
17400 } else if (!strcasecmp(colname, "callerid_name")) {
17401 ast_copy_string(buf, peer->cid_name, len);
17402 } else if (!strcasecmp(colname, "callerid_num")) {
17403 ast_copy_string(buf, peer->cid_num, len);
17404 } else if (!strcasecmp(colname, "codecs")) {
17405 ast_getformatname_multiple(buf, len -1, peer->capability);
17406 } else if (!strncasecmp(colname, "chanvar[", 8)) {
17407 char *chanvar=colname + 8;
17408 struct ast_variable *v;
17409
17410 chanvar = strsep(&chanvar, "]");
17411 for (v = peer->chanvars ; v ; v = v->next) {
17412 if (!strcasecmp(v->name, chanvar)) {
17413 ast_copy_string(buf, v->value, len);
17414 }
17415 }
17416 } else if (!strncasecmp(colname, "codec[", 6)) {
17417 char *codecnum;
17418 int codec = 0;
17419
17420 codecnum = colname + 6;
17421 codecnum = strsep(&codecnum, "]");
17422 if((codec = ast_codec_pref_index(&peer->prefs, atoi(codecnum)))) {
17423 ast_copy_string(buf, ast_getformatname(codec), len);
17424 } else {
17425 buf[0] = '\0';
17426 }
17427 } else {
17428 buf[0] = '\0';
17429 }
17430
17431 unref_peer(peer, "unref_peer from function_sippeer, just before return");
17432
17433 return 0;
17434 }
17435
17436
17437 static struct ast_custom_function sippeer_function = {
17438 .name = "SIPPEER",
17439 .read = function_sippeer,
17440 };
17441
17442
17443 static int function_sipchaninfo_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
17444 {
17445 struct sip_pvt *p;
17446 static int deprecated = 0;
17447
17448 *buf = 0;
17449
17450 if (!data) {
17451 ast_log(LOG_WARNING, "This function requires a parameter name.\n");
17452 return -1;
17453 }
17454
17455 ast_channel_lock(chan);
17456 if (!IS_SIP_TECH(chan->tech)) {
17457 ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
17458 ast_channel_unlock(chan);
17459 return -1;
17460 }
17461
17462 if (deprecated++ % 20 == 0) {
17463
17464 ast_log(LOG_WARNING, "SIPCHANINFO() is deprecated. Please transition to using CHANNEL().\n");
17465 }
17466
17467 p = chan->tech_pvt;
17468
17469
17470 if (!p) {
17471 ast_channel_unlock(chan);
17472 return -1;
17473 }
17474
17475 if (!strcasecmp(data, "peerip")) {
17476 ast_copy_string(buf, p->sa.sin_addr.s_addr ? ast_inet_ntoa(p->sa.sin_addr) : "", len);
17477 } else if (!strcasecmp(data, "recvip")) {
17478 ast_copy_string(buf, p->recv.sin_addr.s_addr ? ast_inet_ntoa(p->recv.sin_addr) : "", len);
17479 } else if (!strcasecmp(data, "from")) {
17480 ast_copy_string(buf, p->from, len);
17481 } else if (!strcasecmp(data, "uri")) {
17482 ast_copy_string(buf, p->uri, len);
17483 } else if (!strcasecmp(data, "useragent")) {
17484 ast_copy_string(buf, p->useragent, len);
17485 } else if (!strcasecmp(data, "peername")) {
17486 ast_copy_string(buf, p->peername, len);
17487 } else if (!strcasecmp(data, "t38passthrough")) {
17488 if (p->t38.state == T38_DISABLED) {
17489 ast_copy_string(buf, "0", len);
17490 } else {
17491 ast_copy_string(buf, "1", len);
17492 }
17493 } else {
17494 ast_channel_unlock(chan);
17495 return -1;
17496 }
17497 ast_channel_unlock(chan);
17498
17499 return 0;
17500 }
17501
17502
17503 static struct ast_custom_function sipchaninfo_function = {
17504 .name = "SIPCHANINFO",
17505 .read = function_sipchaninfo_read,
17506 };
17507
17508
17509
17510
17511
17512
17513
17514 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req)
17515 {
17516 char tmp[SIPBUFSIZE];
17517 char *s, *e, *t, *trans;
17518 char *domain;
17519 enum sip_transport transport = SIP_TRANSPORT_UDP;
17520
17521 ast_copy_string(tmp, get_header(req, "Contact"), sizeof(tmp));
17522 if ((t = strchr(tmp, ',')))
17523 *t = '\0';
17524
17525 s = get_in_brackets(tmp);
17526 if ((trans = strcasestr(s, ";transport="))) do {
17527 trans += 11;
17528
17529 if ((e = strchr(trans, ';')))
17530 *e = '\0';
17531
17532 if (!strncasecmp(trans, "tcp", 3))
17533 transport = SIP_TRANSPORT_TCP;
17534 else if (!strncasecmp(trans, "tls", 3))
17535 transport = SIP_TRANSPORT_TLS;
17536 else {
17537 if (strncasecmp(trans, "udp", 3))
17538 ast_debug(1, "received contact with an invalid transport, '%s'\n", s);
17539
17540 transport = SIP_TRANSPORT_UDP;
17541 }
17542 } while(0);
17543 s = remove_uri_parameters(s);
17544
17545 if (p->socket.tcptls_session) {
17546 ao2_ref(p->socket.tcptls_session, -1);
17547 p->socket.tcptls_session = NULL;
17548 }
17549
17550 set_socket_transport(&p->socket, transport);
17551
17552 if (ast_test_flag(&p->flags[0], SIP_PROMISCREDIR)) {
17553 char *host = NULL;
17554 if (!strncasecmp(s, "sip:", 4))
17555 s += 4;
17556 else if (!strncasecmp(s, "sips:", 5))
17557 s += 5;
17558 e = strchr(s, '/');
17559 if (e)
17560 *e = '\0';
17561 if ((host = strchr(s, '@'))) {
17562 *host++ = '\0';
17563 ast_debug(2, "Found promiscuous redirection to 'SIP/%s::::%s@%s'\n", s, get_transport(transport), host);
17564 if (p->owner)
17565 ast_string_field_build(p->owner, call_forward, "SIP/%s::::%s@%s", s, get_transport(transport), host);
17566 } else {
17567 ast_debug(2, "Found promiscuous redirection to 'SIP/::::%s@%s'\n", get_transport(transport), s);
17568 if (p->owner)
17569 ast_string_field_build(p->owner, call_forward, "SIP/::::%s@%s", get_transport(transport), s);
17570 }
17571 } else {
17572 e = strchr(tmp, '@');
17573 if (e) {
17574 *e++ = '\0';
17575 domain = e;
17576 } else {
17577
17578 domain = tmp;
17579 }
17580 e = strchr(tmp, '/');
17581 if (e)
17582 *e = '\0';
17583
17584 if (!strncasecmp(s, "sip:", 4))
17585 s += 4;
17586 else if (!strncasecmp(s, "sips:", 5))
17587 s += 5;
17588 e = strchr(s, ';');
17589 if (e)
17590 *e = '\0';
17591 ast_debug(2, "Received 302 Redirect to extension '%s' (domain %s)\n", s, domain);
17592 if (p->owner) {
17593 pbx_builtin_setvar_helper(p->owner, "SIPDOMAIN", domain);
17594 ast_string_field_set(p->owner, call_forward, s);
17595 }
17596 }
17597 }
17598
17599
17600 static void check_pendings(struct sip_pvt *p)
17601 {
17602 if (ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
17603
17604 if (p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA)
17605 transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
17606
17607
17608 else {
17609
17610
17611 if (p->pendinginvite)
17612 return;
17613
17614
17615 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, TRUE);
17616 }
17617 ast_clear_flag(&p->flags[0], SIP_PENDINGBYE);
17618 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17619 } else if (ast_test_flag(&p->flags[0], SIP_NEEDREINVITE)) {
17620
17621 if (p->pendinginvite || p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA || p->waitid > 0) {
17622 ast_debug(2, "NOT Sending pending reinvite (yet) on '%s'\n", p->callid);
17623 } else {
17624 ast_debug(2, "Sending pending reinvite on '%s'\n", p->callid);
17625
17626 transmit_reinvite_with_sdp(p, (p->t38.state == T38_LOCAL_REINVITE ? TRUE : FALSE), FALSE);
17627 ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);
17628 }
17629 }
17630 }
17631
17632
17633
17634
17635
17636 static int sip_reinvite_retry(const void *data)
17637 {
17638 struct sip_pvt *p = (struct sip_pvt *) data;
17639
17640 sip_pvt_lock(p);
17641 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
17642 p->waitid = -1;
17643 check_pendings(p);
17644 sip_pvt_unlock(p);
17645 dialog_unref(p, "unref the dialog ptr from sip_reinvite_retry, because it held a dialog ptr");
17646 return 0;
17647 }
17648
17649
17650
17651 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
17652 {
17653 int outgoing = ast_test_flag(&p->flags[0], SIP_OUTGOING);
17654 int res = 0;
17655 int xmitres = 0;
17656 int reinvite = (p->owner && p->owner->_state == AST_STATE_UP);
17657 char *p_hdrval;
17658 int rtn;
17659
17660 if (reinvite)
17661 ast_debug(4, "SIP response %d to RE-invite on %s call %s\n", resp, outgoing ? "outgoing" : "incoming", p->callid);
17662 else
17663 ast_debug(4, "SIP response %d to standard invite\n", resp);
17664
17665 if (p->alreadygone) {
17666 ast_debug(1, "Got response on call that is already terminated: %s (ignoring)\n", p->callid);
17667 return;
17668 }
17669
17670
17671
17672 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"));
17673
17674
17675
17676
17677 if (resp > 100 && resp < 200 && resp!=101 && resp != 180 && resp != 182 && resp != 183)
17678 resp = 183;
17679
17680
17681 if (resp >= 100 && resp < 200 && p->invitestate == INV_CALLING)
17682 p->invitestate = INV_PROCEEDING;
17683
17684
17685 if (resp >= 300 && (p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA ))
17686 p->invitestate = INV_COMPLETED;
17687
17688
17689 if ((resp == 200 || resp >= 300) && p->pendinginvite && seqno == p->pendinginvite)
17690 p->pendinginvite = 0;
17691
17692 switch (resp) {
17693 case 100:
17694 case 101:
17695 if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p))
17696 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
17697 check_pendings(p);
17698 break;
17699
17700 case 180:
17701 case 182:
17702 if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p))
17703 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
17704 if (!req->ignore && p->owner) {
17705 ast_queue_control(p->owner, AST_CONTROL_RINGING);
17706 if (p->owner->_state != AST_STATE_UP) {
17707 ast_setstate(p->owner, AST_STATE_RINGING);
17708 }
17709 }
17710 if (find_sdp(req)) {
17711 if (p->invitestate != INV_CANCELLED)
17712 p->invitestate = INV_EARLY_MEDIA;
17713 res = process_sdp(p, req, SDP_T38_NONE);
17714 if (!req->ignore && p->owner) {
17715
17716 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
17717 }
17718 }
17719 check_pendings(p);
17720 break;
17721
17722 case 183:
17723 if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
17724 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
17725 if (find_sdp(req)) {
17726 if (p->invitestate != INV_CANCELLED)
17727 p->invitestate = INV_EARLY_MEDIA;
17728 res = process_sdp(p, req, SDP_T38_NONE);
17729 if (!req->ignore && p->owner) {
17730
17731 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
17732 }
17733 } else {
17734
17735
17736
17737
17738 if (!req->ignore && p->owner) {
17739 ast_queue_control(p->owner, AST_CONTROL_RINGING);
17740 }
17741 }
17742 check_pendings(p);
17743 break;
17744
17745 case 200:
17746 if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
17747 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
17748 p->authtries = 0;
17749 if (find_sdp(req)) {
17750 if ((res = process_sdp(p, req, SDP_T38_ACCEPT)) && !req->ignore)
17751 if (!reinvite)
17752
17753
17754 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
17755 }
17756
17757
17758
17759
17760 if (outgoing) {
17761 update_call_counter(p, DEC_CALL_RINGING);
17762 parse_ok_contact(p, req);
17763
17764 if (!reinvite)
17765 build_route(p, req, 1);
17766
17767 if(set_address_from_contact(p)) {
17768
17769
17770 if (!p->route && !req->ignore)
17771 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
17772 }
17773
17774 }
17775
17776 if (!req->ignore && p->owner) {
17777 if (!reinvite) {
17778 ast_queue_control(p->owner, AST_CONTROL_ANSWER);
17779 if (sip_cfg.callevents)
17780 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
17781 "Channel: %s\r\nChanneltype: %s\r\nUniqueid: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
17782 p->owner->name, "SIP", p->owner->uniqueid, p->callid, p->fullcontact, p->peername);
17783 } else {
17784 ast_queue_frame(p->owner, &ast_null_frame);
17785 }
17786 } else {
17787
17788
17789
17790 if (!req->ignore)
17791 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
17792 }
17793
17794
17795 if (st_get_mode(p) != SESSION_TIMER_MODE_REFUSE && p->outgoing_call == TRUE && !reinvite) {
17796 p_hdrval = (char*)get_header(req, "Session-Expires");
17797 if (!ast_strlen_zero(p_hdrval)) {
17798
17799 enum st_refresher tmp_st_ref = SESSION_TIMER_REFRESHER_AUTO;
17800 int tmp_st_interval = 0;
17801 rtn = parse_session_expires(p_hdrval, &tmp_st_interval, &tmp_st_ref);
17802 if (rtn != 0) {
17803 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
17804 }
17805 if (tmp_st_ref == SESSION_TIMER_REFRESHER_UAC ||
17806 tmp_st_ref == SESSION_TIMER_REFRESHER_UAS) {
17807 p->stimer->st_ref = tmp_st_ref;
17808 }
17809 if (tmp_st_interval) {
17810 p->stimer->st_interval = tmp_st_interval;
17811 }
17812 p->stimer->st_active = TRUE;
17813 p->stimer->st_active_peer_ua = TRUE;
17814 start_session_timer(p);
17815 } else {
17816
17817 if (st_get_mode(p) == SESSION_TIMER_MODE_ORIGINATE) {
17818 p->stimer->st_ref = SESSION_TIMER_REFRESHER_UAC;
17819 p->stimer->st_active_peer_ua = FALSE;
17820 start_session_timer(p);
17821 }
17822 }
17823 }
17824
17825
17826
17827 p->invitestate = INV_TERMINATED;
17828 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
17829 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, TRUE);
17830 check_pendings(p);
17831 break;
17832
17833 case 407:
17834 case 401:
17835
17836 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17837 if (p->options)
17838 p->options->auth_type = resp;
17839
17840
17841 ast_string_field_set(p, theirtag, NULL);
17842 if (!req->ignore) {
17843 if (p->authtries < MAX_AUTHTRIES)
17844 p->invitestate = INV_CALLING;
17845 if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, SIP_INVITE, 1)) {
17846 ast_log(LOG_NOTICE, "Failed to authenticate on INVITE to '%s'\n", get_header(&p->initreq, "From"));
17847 pvt_set_needdestroy(p, "failed to authenticate on INVITE");
17848 sip_alreadygone(p);
17849 if (p->owner)
17850 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17851 }
17852 }
17853 break;
17854
17855 case 403:
17856
17857 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17858 ast_log(LOG_WARNING, "Received response: \"Forbidden\" from '%s'\n", get_header(&p->initreq, "From"));
17859 if (!req->ignore && p->owner)
17860 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17861 pvt_set_needdestroy(p, "received 403 response");
17862 sip_alreadygone(p);
17863 break;
17864
17865 case 404:
17866 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17867 if (p->owner && !req->ignore)
17868 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17869 sip_alreadygone(p);
17870 break;
17871
17872 case 408:
17873 case 481:
17874
17875 ast_log(LOG_WARNING, "Re-invite to non-existing call leg on other UA. SIP dialog '%s'. Giving up.\n", p->callid);
17876 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17877 if (p->owner)
17878 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17879 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17880 break;
17881
17882 case 422:
17883 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17884 ast_string_field_set(p, theirtag, NULL);
17885 proc_422_rsp(p, req);
17886 break;
17887
17888 case 428:
17889 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17890 append_history(p, "Identity", "SIP identity is required. Not supported by Asterisk.");
17891 ast_log(LOG_WARNING, "SIP identity required by proxy. SIP dialog '%s'. Giving up.\n", p->callid);
17892 if (p->owner)
17893 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17894 break;
17895
17896
17897
17898 case 487:
17899
17900
17901
17902 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17903 if (p->owner && !req->ignore) {
17904 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_NORMAL_CLEARING);
17905 append_history(p, "Hangup", "Got 487 on CANCEL request from us. Queued AST hangup request");
17906 } else if (!req->ignore) {
17907 update_call_counter(p, DEC_CALL_LIMIT);
17908 append_history(p, "Hangup", "Got 487 on CANCEL request from us on call without owner. Killing this dialog.");
17909 pvt_set_needdestroy(p, "received 487 response");
17910 sip_alreadygone(p);
17911 }
17912 break;
17913 case 415:
17914 case 488:
17915 case 606:
17916 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17917 if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
17918 change_t38_state(p, T38_DISABLED);
17919
17920 ast_rtp_set_rtptimers_onhold(p->rtp);
17921
17922
17923 transmit_reinvite_with_sdp(p, FALSE, FALSE);
17924 } else {
17925
17926 if (p->owner && !req->ignore)
17927 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17928 pvt_set_needdestroy(p, "received 488 response");
17929
17930 if (!reinvite)
17931 sip_alreadygone(p);
17932 }
17933 break;
17934 case 491:
17935 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17936 if (p->owner && !req->ignore) {
17937 if (p->owner->_state != AST_STATE_UP) {
17938 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17939 pvt_set_needdestroy(p, "received 491 response");
17940 } else {
17941
17942
17943
17944 int wait;
17945
17946
17947 if (p->outgoing_call) {
17948 wait = 2100 + ast_random() % 2000;
17949 } else {
17950 wait = ast_random() % 2000;
17951 }
17952 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."));
17953 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);
17954 ast_debug(2, "Reinvite race. Waiting %d secs before retry\n", wait);
17955 }
17956 }
17957 break;
17958
17959 case 501:
17960 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17961 if (p->owner)
17962 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17963 break;
17964 }
17965 if (xmitres == XMIT_ERROR)
17966 ast_log(LOG_WARNING, "Could not transmit message in dialog %s\n", p->callid);
17967 }
17968
17969
17970
17971
17972 static void handle_response_notify(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
17973 {
17974 switch (resp) {
17975 case 200:
17976
17977 if (p->owner) {
17978 if (!p->refer) {
17979 ast_log(LOG_WARNING, "Notify answer on an owned channel? - %s\n", p->owner->name);
17980 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_NORMAL_UNSPECIFIED);
17981 } else {
17982 ast_debug(4, "Got OK on REFER Notify message\n");
17983 }
17984 } else {
17985 if (p->subscribed == NONE) {
17986 ast_debug(4, "Got 200 accepted on NOTIFY\n");
17987 pvt_set_needdestroy(p, "received 200 response");
17988 }
17989 if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
17990
17991 ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
17992 cb_extensionstate((char *)p->context, (char *)p->exten, p->laststate, (void *) p);
17993 }
17994 }
17995 break;
17996 case 401:
17997 case 407:
17998 if (!p->notify_headers) {
17999 break;
18000 }
18001 ast_string_field_set(p, theirtag, NULL);
18002 if (ast_strlen_zero(p->authname)) {
18003 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));
18004 pvt_set_needdestroy(p, "unable to authenticate NOTIFY");
18005 }
18006 if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_NOTIFY, 0)) {
18007 ast_log(LOG_NOTICE, "Failed to authenticate on NOTIFY to '%s'\n", get_header(&p->initreq, "From"));
18008 pvt_set_needdestroy(p, "failed to authenticate NOTIFY");
18009 }
18010 break;
18011 }
18012 }
18013
18014
18015 static void handle_response_subscribe(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
18016 {
18017 if (!p->mwi) {
18018 return;
18019 }
18020
18021 switch (resp) {
18022 case 200:
18023 ast_debug(3, "Got 200 OK on subscription for MWI\n");
18024 if (p->options) {
18025 ast_free(p->options);
18026 p->options = NULL;
18027 }
18028 p->mwi->subscribed = 1;
18029 if ((p->mwi->resub = ast_sched_add(sched, mwi_expiry * 1000, sip_subscribe_mwi_do, ASTOBJ_REF(p->mwi))) < 0) {
18030 ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18031 }
18032 break;
18033 case 401:
18034 case 407:
18035 ast_string_field_set(p, theirtag, NULL);
18036 if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_SUBSCRIBE, 0)) {
18037 ast_log(LOG_NOTICE, "Failed to authenticate on SUBSCRIBE to '%s'\n", get_header(&p->initreq, "From"));
18038 p->mwi->call = NULL;
18039 ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18040 pvt_set_needdestroy(p, "failed to authenticate SUBSCRIBE");
18041 }
18042 break;
18043 case 403:
18044 transmit_response_with_date(p, "200 OK", req);
18045 ast_log(LOG_WARNING, "Authentication failed while trying to subscribe for MWI.\n");
18046 p->mwi->call = NULL;
18047 ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18048 pvt_set_needdestroy(p, "received 403 response");
18049 sip_alreadygone(p);
18050 break;
18051 case 404:
18052 ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side said that a mailbox may not have been configured.\n");
18053 p->mwi->call = NULL;
18054 ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18055 pvt_set_needdestroy(p, "received 404 response");
18056 break;
18057 case 481:
18058 ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side said that our dialog did not exist.\n");
18059 p->mwi->call = NULL;
18060 ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18061 pvt_set_needdestroy(p, "received 481 response");
18062 break;
18063 case 500:
18064 case 501:
18065 ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side may have suffered a heart attack.\n");
18066 p->mwi->call = NULL;
18067 ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18068 pvt_set_needdestroy(p, "received 500/501 response");
18069 break;
18070 }
18071 }
18072
18073
18074
18075
18076 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
18077 {
18078
18079 if (!p->refer)
18080 return;
18081
18082 switch (resp) {
18083 case 202:
18084
18085
18086 p->refer->status = REFER_ACCEPTED;
18087
18088 ast_debug(3, "Got 202 accepted on transfer\n");
18089
18090 break;
18091
18092 case 401:
18093 case 407:
18094 if (ast_strlen_zero(p->authname)) {
18095 ast_log(LOG_WARNING, "Asked to authenticate REFER to %s:%d but we have no matching peer or realm auth!\n",
18096 ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
18097 pvt_set_needdestroy(p, "unable to authenticate REFER");
18098 }
18099 if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_REFER, 0)) {
18100 ast_log(LOG_NOTICE, "Failed to authenticate on REFER to '%s'\n", get_header(&p->initreq, "From"));
18101 p->refer->status = REFER_NOAUTH;
18102 pvt_set_needdestroy(p, "failed to authenticat REFER");
18103 }
18104 break;
18105 case 481:
18106
18107
18108
18109
18110 ast_log(LOG_WARNING, "Remote host can't match REFER request to call '%s'. Giving up.\n", p->callid);
18111 if (p->owner)
18112 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18113 pvt_set_needdestroy(p, "received 481 response");
18114 break;
18115
18116 case 500:
18117 case 501:
18118
18119
18120 ast_log(LOG_NOTICE, "SIP transfer to %s failed, call miserably fails. \n", p->refer->refer_to);
18121 pvt_set_needdestroy(p, "received 500/501 response");
18122 p->refer->status = REFER_FAILED;
18123 break;
18124 case 603:
18125 ast_log(LOG_NOTICE, "SIP transfer to %s declined, call miserably fails. \n", p->refer->refer_to);
18126 p->refer->status = REFER_FAILED;
18127 pvt_set_needdestroy(p, "received 603 response");
18128 break;
18129 }
18130 }
18131
18132
18133 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
18134 {
18135 int expires, expires_ms;
18136 struct sip_registry *r;
18137 r=p->registry;
18138
18139 switch (resp) {
18140 case 401:
18141 if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
18142 ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s@%s' (Tries %d)\n", p->registry->username, p->registry->hostname, p->authtries);
18143 pvt_set_needdestroy(p, "failed to authenticate REGISTER");
18144 }
18145 break;
18146 case 403:
18147 ast_log(LOG_WARNING, "Forbidden - wrong password on authentication for REGISTER for '%s' to '%s'\n", p->registry->username, p->registry->hostname);
18148 AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 403"));
18149 r->regstate = REG_STATE_NOAUTH;
18150 pvt_set_needdestroy(p, "received 403 response");
18151 break;
18152 case 404:
18153 ast_log(LOG_WARNING, "Got 404 Not found on SIP register to service %s@%s, giving up\n", p->registry->username, p->registry->hostname);
18154 pvt_set_needdestroy(p, "received 404 response");
18155 if (r->call)
18156 r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 404");
18157 r->regstate = REG_STATE_REJECTED;
18158 AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 404"));
18159 break;
18160 case 407:
18161 if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
18162 ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s' (tries '%d')\n", get_header(&p->initreq, "From"), p->authtries);
18163 pvt_set_needdestroy(p, "failed to authenticate REGISTER");
18164 }
18165 break;
18166 case 408:
18167
18168 if (r) {
18169 r->regattempts = 0;
18170 } else {
18171 ast_log(LOG_WARNING, "Got a 408 response to our REGISTER on call %s after we had destroyed the registry object\n", p->callid);
18172 }
18173 break;
18174 case 423:
18175 r->expiry = atoi(get_header(req, "Min-Expires"));
18176 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);
18177 AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 423"));
18178 if (r->call) {
18179 r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 423");
18180 pvt_set_needdestroy(p, "received 423 response");
18181 }
18182 if (r->expiry > max_expiry) {
18183 ast_log(LOG_WARNING, "Required expiration time from %s@%s is too high, giving up\n", p->registry->username, p->registry->hostname);
18184 r->expiry = r->configured_expiry;
18185 r->regstate = REG_STATE_REJECTED;
18186 } else {
18187 r->regstate = REG_STATE_UNREGISTERED;
18188 transmit_register(r, SIP_REGISTER, NULL, NULL);
18189 }
18190 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));
18191 break;
18192 case 479:
18193 ast_log(LOG_WARNING, "Got error 479 on register to %s@%s, giving up (check config)\n", p->registry->username, p->registry->hostname);
18194 pvt_set_needdestroy(p, "received 479 response");
18195 if (r->call)
18196 r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 479");
18197 r->regstate = REG_STATE_REJECTED;
18198 AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 479"));
18199 break;
18200 case 200:
18201 if (!r) {
18202 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));
18203 pvt_set_needdestroy(p, "received erroneous 200 response");
18204 return 0;
18205 }
18206
18207 r->regstate = REG_STATE_REGISTERED;
18208 r->regtime = ast_tvnow();
18209 manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelType: SIP\r\nDomain: %s\r\nStatus: %s\r\n", r->hostname, regstate2str(r->regstate));
18210 r->regattempts = 0;
18211 ast_debug(1, "Registration successful\n");
18212 if (r->timeout > -1) {
18213 ast_debug(1, "Cancelling timeout %d\n", r->timeout);
18214 }
18215 AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 200"));
18216 if (r->call)
18217 r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 200");
18218 p->registry = registry_unref(p->registry, "unref registry entry p->registry");
18219
18220 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18221
18222
18223
18224
18225
18226
18227 expires = 0;
18228
18229
18230 if (!ast_strlen_zero(get_header(req, "Contact"))) {
18231 const char *contact = NULL;
18232 const char *tmptmp = NULL;
18233 int start = 0;
18234 for(;;) {
18235 contact = __get_header(req, "Contact", &start);
18236
18237 if(!ast_strlen_zero(contact)) {
18238 if( (tmptmp=strstr(contact, p->our_contact))) {
18239 contact=tmptmp;
18240 break;
18241 }
18242 } else
18243 break;
18244 }
18245 tmptmp = strcasestr(contact, "expires=");
18246 if (tmptmp) {
18247 if (sscanf(tmptmp + 8, "%30d;", &expires) != 1)
18248 expires = 0;
18249 }
18250
18251 }
18252 if (!expires)
18253 expires=atoi(get_header(req, "expires"));
18254 if (!expires)
18255 expires=default_expiry;
18256
18257 expires_ms = expires * 1000;
18258 if (expires <= EXPIRY_GUARD_LIMIT)
18259 expires_ms -= MAX((expires_ms * EXPIRY_GUARD_PCT), EXPIRY_GUARD_MIN);
18260 else
18261 expires_ms -= EXPIRY_GUARD_SECS * 1000;
18262 if (sipdebug)
18263 ast_log(LOG_NOTICE, "Outbound Registration: Expiry for %s is %d sec (Scheduling reregistration in %d s)\n", r->hostname, expires, expires_ms/1000);
18264
18265 r->refresh= (int) expires_ms / 1000;
18266
18267
18268 AST_SCHED_REPLACE_UNREF(r->expire, sched, expires_ms, sip_reregister, r,
18269 registry_unref(_data,"unref in REPLACE del fail"),
18270 registry_unref(r,"unref in REPLACE add fail"),
18271 registry_addref(r,"The Addition side of REPLACE"));
18272 }
18273 return 1;
18274 }
18275
18276
18277 static void handle_response_peerpoke(struct sip_pvt *p, int resp, struct sip_request *req)
18278 {
18279 struct sip_peer *peer = p->relatedpeer ;
18280 int statechanged, is_reachable, was_reachable;
18281 int pingtime = ast_tvdiff_ms(ast_tvnow(), peer->ps);
18282
18283
18284
18285
18286
18287
18288 if (pingtime < 1)
18289 pingtime = 1;
18290
18291
18292
18293
18294
18295 was_reachable = peer->lastms > 0 && peer->lastms <= peer->maxms;
18296 is_reachable = pingtime <= peer->maxms;
18297 statechanged = peer->lastms == 0
18298 || was_reachable != is_reachable;
18299
18300 peer->lastms = pingtime;
18301 peer->call = dialog_unref(peer->call, "unref dialog peer->call");
18302 if (statechanged) {
18303 const char *s = is_reachable ? "Reachable" : "Lagged";
18304 char str_lastms[20];
18305 snprintf(str_lastms, sizeof(str_lastms), "%d", pingtime);
18306
18307 ast_log(LOG_NOTICE, "Peer '%s' is now %s. (%dms / %dms)\n",
18308 peer->name, s, pingtime, peer->maxms);
18309 ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
18310 if (sip_cfg.peer_rtupdate) {
18311 ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", str_lastms, SENTINEL);
18312 }
18313 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
18314 "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: %s\r\nTime: %d\r\n",
18315 peer->name, s, pingtime);
18316 if (is_reachable && sip_cfg.regextenonqualify)
18317 register_peer_exten(peer, TRUE);
18318 }
18319
18320 pvt_set_needdestroy(p, "got OPTIONS response");
18321
18322
18323 AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
18324 is_reachable ? peer->qualifyfreq : DEFAULT_FREQ_NOTOK,
18325 sip_poke_peer_s, peer,
18326 unref_peer(_data, "removing poke peer ref"),
18327 unref_peer(peer, "removing poke peer ref"),
18328 ref_peer(peer, "adding poke peer ref"));
18329 }
18330
18331
18332 static void stop_media_flows(struct sip_pvt *p)
18333 {
18334
18335 if (p->rtp)
18336 ast_rtp_stop(p->rtp);
18337 if (p->vrtp)
18338 ast_rtp_stop(p->vrtp);
18339 if (p->trtp)
18340 ast_rtp_stop(p->trtp);
18341 if (p->udptl)
18342 ast_udptl_stop(p->udptl);
18343 }
18344
18345
18346
18347 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
18348 {
18349 struct ast_channel *owner;
18350 int sipmethod;
18351 int res = 1;
18352 const char *c = get_header(req, "Cseq");
18353
18354 char *c_copy = ast_strdupa(c);
18355
18356 const char *msg = ast_skip_blanks(ast_skip_nonblanks(c_copy));
18357
18358 if (!msg)
18359 msg = "";
18360
18361 sipmethod = find_sip_method(msg);
18362
18363 owner = p->owner;
18364 if (owner)
18365 owner->hangupcause = hangup_sip2cause(resp);
18366
18367 if (p->socket.type == SIP_TRANSPORT_UDP) {
18368 int ack_res;
18369
18370
18371 if ((resp >= 100) && (resp <= 199)) {
18372 ack_res = __sip_semi_ack(p, seqno, 0, sipmethod);
18373 } else {
18374 ack_res = __sip_ack(p, seqno, 0, sipmethod);
18375 }
18376
18377 if (ack_res == FALSE) {
18378 append_history(p, "Ignore", "Ignoring this retransmit\n");
18379 return;
18380 }
18381 }
18382
18383
18384 if (!p->owner && sipmethod == SIP_NOTIFY && p->pendinginvite)
18385 p->pendinginvite = 0;
18386
18387
18388 if (ast_strlen_zero(p->theirtag) || (resp >= 200)) {
18389 char tag[128];
18390
18391 gettag(req, "To", tag, sizeof(tag));
18392 ast_string_field_set(p, theirtag, tag);
18393 }
18394
18395
18396
18397
18398
18399
18400
18401
18402
18403
18404
18405
18406
18407
18408
18409 if ((resp == 404 || resp == 408 || resp == 481) && sipmethod == SIP_BYE) {
18410 pvt_set_needdestroy(p, "received 4XX response to a BYE");
18411 return;
18412 }
18413
18414 if (p->relatedpeer && p->method == SIP_OPTIONS) {
18415
18416
18417
18418 if (resp != 100)
18419 handle_response_peerpoke(p, resp, req);
18420 } else if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
18421 switch(resp) {
18422 case 100:
18423 case 101:
18424 case 183:
18425 case 180:
18426 case 182:
18427 if (sipmethod == SIP_INVITE)
18428 handle_response_invite(p, resp, rest, req, seqno);
18429 break;
18430 case 200:
18431 p->authtries = 0;
18432 if (sipmethod == SIP_MESSAGE || sipmethod == SIP_INFO) {
18433
18434
18435
18436 } else if (sipmethod == SIP_INVITE) {
18437 handle_response_invite(p, resp, rest, req, seqno);
18438 } else if (sipmethod == SIP_NOTIFY) {
18439 handle_response_notify(p, resp, rest, req, seqno);
18440 } else if (sipmethod == SIP_REGISTER) {
18441 res = handle_response_register(p, resp, rest, req, seqno);
18442 } else if (sipmethod == SIP_SUBSCRIBE) {
18443 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
18444 handle_response_subscribe(p, resp, rest, req, seqno);
18445 } else if (sipmethod == SIP_BYE) {
18446 pvt_set_needdestroy(p, "received 200 response");
18447 ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
18448 }
18449 break;
18450 case 202:
18451 if (sipmethod == SIP_REFER)
18452 handle_response_refer(p, resp, rest, req, seqno);
18453 break;
18454 case 401:
18455 case 407:
18456 if (sipmethod == SIP_INVITE)
18457 handle_response_invite(p, resp, rest, req, seqno);
18458 else if (sipmethod == SIP_NOTIFY)
18459 handle_response_notify(p, resp, rest, req, seqno);
18460 else if (sipmethod == SIP_REFER)
18461 handle_response_refer(p, resp, rest, req, seqno);
18462 else if (sipmethod == SIP_SUBSCRIBE)
18463 handle_response_subscribe(p, resp, rest, req, seqno);
18464 else if (p->registry && sipmethod == SIP_REGISTER)
18465 res = handle_response_register(p, resp, rest, req, seqno);
18466 else if (sipmethod == SIP_BYE) {
18467 if (p->options)
18468 p->options->auth_type = resp;
18469 if (ast_strlen_zero(p->authname)) {
18470 ast_log(LOG_WARNING, "Asked to authenticate %s, to %s:%d but we have no matching peer!\n",
18471 msg, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
18472 pvt_set_needdestroy(p, "unable to authenticate BYE");
18473 } else if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp, sipmethod, 0)) {
18474 ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
18475 pvt_set_needdestroy(p, "failed to authenticate BYE");
18476 }
18477 } else {
18478 ast_log(LOG_WARNING, "Got authentication request (%d) on %s to '%s'\n", resp, sip_methods[sipmethod].text, get_header(req, "To"));
18479 pvt_set_needdestroy(p, "received 407 response");
18480 }
18481 break;
18482 case 403:
18483 if (sipmethod == SIP_INVITE)
18484 handle_response_invite(p, resp, rest, req, seqno);
18485 else if (sipmethod == SIP_SUBSCRIBE)
18486 handle_response_subscribe(p, resp, rest, req, seqno);
18487 else if (p->registry && sipmethod == SIP_REGISTER)
18488 res = handle_response_register(p, resp, rest, req, seqno);
18489 else {
18490 ast_log(LOG_WARNING, "Forbidden - maybe wrong password on authentication for %s\n", msg);
18491 pvt_set_needdestroy(p, "received 403 response");
18492 }
18493 break;
18494 case 404:
18495 if (p->registry && sipmethod == SIP_REGISTER)
18496 res = handle_response_register(p, resp, rest, req, seqno);
18497 else if (sipmethod == SIP_INVITE)
18498 handle_response_invite(p, resp, rest, req, seqno);
18499 else if (sipmethod == SIP_SUBSCRIBE)
18500 handle_response_subscribe(p, resp, rest, req, seqno);
18501 else if (owner)
18502 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18503 break;
18504 case 423:
18505 if (sipmethod == SIP_REGISTER)
18506 res = handle_response_register(p, resp, rest, req, seqno);
18507 break;
18508 case 408:
18509 if (sipmethod == SIP_INVITE)
18510 handle_response_invite(p, resp, rest, req, seqno);
18511 else if (sipmethod == SIP_REGISTER)
18512 res = handle_response_register(p, resp, rest, req, seqno);
18513 else if (sipmethod == SIP_BYE) {
18514 pvt_set_needdestroy(p, "received 408 response");
18515 ast_debug(4, "Got timeout on bye. Thanks for the answer. Now, kill this call\n");
18516 } else {
18517 if (owner)
18518 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18519 pvt_set_needdestroy(p, "received 408 response");
18520 }
18521 break;
18522
18523 case 422:
18524 if (sipmethod == SIP_INVITE) {
18525 handle_response_invite(p, resp, rest, req, seqno);
18526 }
18527 break;
18528
18529 case 481:
18530 if (sipmethod == SIP_INVITE) {
18531 handle_response_invite(p, resp, rest, req, seqno);
18532 } else if (sipmethod == SIP_REFER) {
18533 handle_response_refer(p, resp, rest, req, seqno);
18534 } else if (sipmethod == SIP_SUBSCRIBE) {
18535 handle_response_subscribe(p, resp, rest, req, seqno);
18536 } else if (sipmethod == SIP_BYE) {
18537
18538
18539 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
18540 } else if (sipmethod == SIP_CANCEL) {
18541
18542
18543 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
18544 } else {
18545 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
18546
18547 }
18548 break;
18549 case 487:
18550 if (sipmethod == SIP_INVITE)
18551 handle_response_invite(p, resp, rest, req, seqno);
18552 break;
18553 case 415:
18554 case 488:
18555 case 606:
18556 if (sipmethod == SIP_INVITE)
18557 handle_response_invite(p, resp, rest, req, seqno);
18558 break;
18559 case 491:
18560 if (sipmethod == SIP_INVITE)
18561 handle_response_invite(p, resp, rest, req, seqno);
18562 else {
18563 ast_debug(1, "Got 491 on %s, unsupported. Call ID %s\n", sip_methods[sipmethod].text, p->callid);
18564 pvt_set_needdestroy(p, "received 491 response");
18565 }
18566 break;
18567 case 501:
18568 if (sipmethod == SIP_INVITE)
18569 handle_response_invite(p, resp, rest, req, seqno);
18570 else if (sipmethod == SIP_REFER)
18571 handle_response_refer(p, resp, rest, req, seqno);
18572 else
18573 ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n", ast_inet_ntoa(p->sa.sin_addr), msg);
18574 break;
18575 case 603:
18576 if (sipmethod == SIP_REFER) {
18577 handle_response_refer(p, resp, rest, req, seqno);
18578 break;
18579 }
18580
18581 default:
18582 if ((resp >= 300) && (resp < 700)) {
18583
18584 if ((resp != 487))
18585 ast_verb(3, "Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_inet_ntoa(p->sa.sin_addr));
18586
18587 if (sipmethod == SIP_INVITE)
18588 stop_media_flows(p);
18589
18590
18591 switch(resp) {
18592 case 300:
18593 case 301:
18594 case 302:
18595 case 305:
18596 parse_moved_contact(p, req);
18597
18598 case 486:
18599 case 600:
18600 case 603:
18601 if (p->owner)
18602 ast_queue_control(p->owner, AST_CONTROL_BUSY);
18603 break;
18604 case 482:
18605
18606
18607
18608
18609 ast_debug(1, "Hairpin detected, setting up call forward for what it's worth\n");
18610 if (p->owner)
18611 ast_string_field_build(p->owner, call_forward,
18612 "Local/%s@%s", p->username, p->context);
18613
18614 case 480:
18615 case 404:
18616 case 410:
18617 case 400:
18618 case 500:
18619 if (sipmethod == SIP_REFER) {
18620 handle_response_refer(p, resp, rest, req, seqno);
18621 break;
18622 } else if (sipmethod == SIP_SUBSCRIBE) {
18623 handle_response_subscribe(p, resp, rest, req, seqno);
18624 break;
18625 }
18626
18627 case 502:
18628 case 503:
18629 case 504:
18630 if (owner)
18631 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18632 break;
18633 default:
18634
18635 if (owner && sipmethod != SIP_MESSAGE && sipmethod != SIP_INFO && sipmethod != SIP_BYE)
18636 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
18637 break;
18638 }
18639
18640 if (sipmethod == SIP_INVITE)
18641 transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
18642 if (sipmethod != SIP_MESSAGE && sipmethod != SIP_INFO)
18643 sip_alreadygone(p);
18644 if (!p->owner) {
18645 pvt_set_needdestroy(p, "transaction completed");
18646 }
18647 } else if ((resp >= 100) && (resp < 200)) {
18648 if (sipmethod == SIP_INVITE) {
18649 if (!req->ignore && sip_cancel_destroy(p))
18650 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
18651 if (find_sdp(req))
18652 process_sdp(p, req, SDP_T38_NONE);
18653 if (p->owner) {
18654
18655 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
18656 }
18657 }
18658 } else
18659 ast_log(LOG_NOTICE, "Dont know how to handle a %d %s response from %s\n", resp, rest, p->owner ? p->owner->name : ast_inet_ntoa(p->sa.sin_addr));
18660 }
18661 } else {
18662
18663
18664 if (req->debug)
18665 ast_verbose("SIP Response message for INCOMING dialog %s arrived\n", msg);
18666
18667 if (sipmethod == SIP_INVITE && resp == 200) {
18668
18669
18670 char tag[128];
18671
18672 gettag(req, "To", tag, sizeof(tag));
18673 ast_string_field_set(p, theirtag, tag);
18674 }
18675
18676 switch(resp) {
18677 case 200:
18678 if (sipmethod == SIP_INVITE) {
18679 handle_response_invite(p, resp, rest, req, seqno);
18680 } else if (sipmethod == SIP_CANCEL) {
18681 ast_debug(1, "Got 200 OK on CANCEL\n");
18682
18683
18684 } else if (sipmethod == SIP_NOTIFY) {
18685
18686 if (p->owner) {
18687 if (p->refer) {
18688 ast_debug(1, "Got 200 OK on NOTIFY for transfer\n");
18689 } else
18690 ast_log(LOG_WARNING, "Notify answer on an owned channel?\n");
18691
18692 } else {
18693 if (!p->subscribed && !p->refer) {
18694 pvt_set_needdestroy(p, "transaction completed");
18695 }
18696 if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
18697
18698 ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
18699 cb_extensionstate((char *)p->context, (char *)p->exten, p->laststate, (void *) p);
18700 }
18701 }
18702 } else if (sipmethod == SIP_BYE) {
18703 pvt_set_needdestroy(p, "transaction completed");
18704 } else if (sipmethod == SIP_MESSAGE || sipmethod == SIP_INFO) {
18705
18706
18707 ;
18708 }
18709 break;
18710 case 202:
18711 if (sipmethod == SIP_REFER)
18712 handle_response_refer(p, resp, rest, req, seqno);
18713 break;
18714 case 401:
18715 case 407:
18716 if (sipmethod == SIP_REFER)
18717 handle_response_refer(p, resp, rest, req, seqno);
18718 else if (sipmethod == SIP_INVITE)
18719 handle_response_invite(p, resp, rest, req, seqno);
18720 else if (sipmethod == SIP_BYE) {
18721 if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, sipmethod, 0)) {
18722 ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
18723 pvt_set_needdestroy(p, "failed to authenticate BYE");
18724 }
18725 }
18726 break;
18727 case 481:
18728 if (sipmethod == SIP_INVITE) {
18729
18730 handle_response_invite(p, resp, rest, req, seqno);
18731 } else if (sipmethod == SIP_BYE) {
18732 pvt_set_needdestroy(p, "received 481 response");
18733 } else if (sipdebug) {
18734 ast_debug(1, "Remote host can't match request %s to call '%s'. Giving up\n", sip_methods[sipmethod].text, p->callid);
18735 }
18736 break;
18737 case 501:
18738 if (sipmethod == SIP_INVITE)
18739 handle_response_invite(p, resp, rest, req, seqno);
18740 else if (sipmethod == SIP_REFER)
18741 handle_response_refer(p, resp, rest, req, seqno);
18742 break;
18743 case 603:
18744 if (sipmethod == SIP_REFER) {
18745 handle_response_refer(p, resp, rest, req, seqno);
18746 break;
18747 }
18748
18749 default:
18750 if ((resp >= 100) && (resp < 200)) {
18751 if (sipmethod == SIP_INVITE) {
18752 if (!req->ignore && sip_cancel_destroy(p))
18753 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
18754 }
18755 }
18756 if ((resp >= 300) && (resp < 700)) {
18757 if ((resp != 487))
18758 ast_verb(3, "Incoming call: Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_inet_ntoa(p->sa.sin_addr));
18759 switch(resp) {
18760 case 415:
18761 case 488:
18762 case 603:
18763 case 500:
18764 case 502:
18765 case 503:
18766 case 504:
18767
18768
18769 if (sipmethod == SIP_INVITE && sip_cancel_destroy(p))
18770 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
18771 break;
18772 }
18773 }
18774 break;
18775 }
18776 }
18777 }
18778
18779
18780
18781
18782
18783
18784
18785 static void *sip_park_thread(void *stuff)
18786 {
18787 struct ast_channel *transferee, *transferer;
18788 struct sip_dual *d;
18789 struct sip_request req = {0,};
18790 int ext;
18791 int res;
18792
18793 d = stuff;
18794 transferee = d->chan1;
18795 transferer = d->chan2;
18796 copy_request(&req, &d->req);
18797
18798 if (!transferee || !transferer) {
18799 ast_log(LOG_ERROR, "Missing channels for parking! Transferer %s Transferee %s\n", transferer ? "<available>" : "<missing>", transferee ? "<available>" : "<missing>" );
18800 if (d->req.data)
18801 ast_free(d->req.data);
18802 free(d);
18803 return NULL;
18804 }
18805 ast_debug(4, "SIP Park: Transferer channel %s, Transferee %s\n", transferer->name, transferee->name);
18806
18807 ast_channel_lock(transferee);
18808 if (ast_do_masquerade(transferee)) {
18809 ast_log(LOG_WARNING, "Masquerade failed.\n");
18810 transmit_response(transferer->tech_pvt, "503 Internal error", &req);
18811 ast_channel_unlock(transferee);
18812 if (d->req.data)
18813 ast_free(d->req.data);
18814 free(d);
18815 return NULL;
18816 }
18817 ast_channel_unlock(transferee);
18818
18819 res = ast_park_call(transferee, transferer, 0, &ext);
18820
18821
18822 #ifdef WHEN_WE_KNOW_THAT_THE_CLIENT_SUPPORTS_MESSAGE
18823 if (!res) {
18824 transmit_message_with_text(transferer->tech_pvt, "Unable to park call.\n");
18825 } else {
18826
18827 sprintf(buf, "Call parked on extension '%d'", ext);
18828 transmit_message_with_text(transferer->tech_pvt, buf);
18829 }
18830 #endif
18831
18832
18833
18834 transmit_response(transferer->tech_pvt, "202 Accepted", &req);
18835 if (!res) {
18836
18837 append_history(transferer->tech_pvt, "SIPpark", "Parked call on %d", ext);
18838 transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "200 OK", TRUE);
18839 transferer->hangupcause = AST_CAUSE_NORMAL_CLEARING;
18840 ast_hangup(transferer);
18841 ast_debug(1, "SIP Call parked on extension '%d'\n", ext);
18842 } else {
18843 transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "503 Service Unavailable", TRUE);
18844 append_history(transferer->tech_pvt, "SIPpark", "Parking failed\n");
18845 ast_debug(1, "SIP Call parked failed \n");
18846
18847 }
18848 if (d->req.data)
18849 ast_free(d->req.data);
18850 free(d);
18851 return NULL;
18852 }
18853
18854
18855
18856
18857 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno)
18858 {
18859 struct sip_dual *d;
18860 struct ast_channel *transferee, *transferer;
18861
18862 pthread_t th;
18863
18864 transferee = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan1->accountcode, chan1->exten, chan1->context, chan1->amaflags, "Parking/%s", chan1->name);
18865 transferer = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan2->accountcode, chan2->exten, chan2->context, chan2->amaflags, "SIPPeer/%s", chan2->name);
18866 if ((!transferer) || (!transferee)) {
18867 if (transferee) {
18868 transferee->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
18869 ast_hangup(transferee);
18870 }
18871 if (transferer) {
18872 transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
18873 ast_hangup(transferer);
18874 }
18875 return -1;
18876 }
18877
18878
18879 transferee->readformat = chan1->readformat;
18880 transferee->writeformat = chan1->writeformat;
18881
18882
18883 ast_channel_masquerade(transferee, chan1);
18884
18885
18886 ast_copy_string(transferee->context, chan1->context, sizeof(transferee->context));
18887 ast_copy_string(transferee->exten, chan1->exten, sizeof(transferee->exten));
18888 transferee->priority = chan1->priority;
18889
18890
18891
18892
18893
18894 transferer->readformat = chan2->readformat;
18895 transferer->writeformat = chan2->writeformat;
18896 if (!ast_strlen_zero(chan2->parkinglot))
18897 ast_string_field_set(transferer, parkinglot, chan2->parkinglot);
18898
18899
18900
18901
18902 while (ast_channel_trylock(chan2)) {
18903 struct sip_pvt *pvt = chan2->tech_pvt;
18904 sip_pvt_unlock(pvt);
18905 usleep(1);
18906 sip_pvt_lock(pvt);
18907 }
18908 ast_channel_masquerade(transferer, chan2);
18909 ast_channel_unlock(chan2);
18910
18911
18912 ast_copy_string(transferer->context, chan2->context, sizeof(transferer->context));
18913 ast_copy_string(transferer->exten, chan2->exten, sizeof(transferer->exten));
18914 transferer->priority = chan2->priority;
18915
18916 ast_channel_lock(transferer);
18917 if (ast_do_masquerade(transferer)) {
18918 ast_log(LOG_WARNING, "Masquerade failed :(\n");
18919 ast_channel_unlock(transferer);
18920 transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
18921 ast_hangup(transferer);
18922 return -1;
18923 }
18924 ast_channel_unlock(transferer);
18925 if (!transferer || !transferee) {
18926 if (!transferer) {
18927 ast_debug(1, "No transferer channel, giving up parking\n");
18928 }
18929 if (!transferee) {
18930 ast_debug(1, "No transferee channel, giving up parking\n");
18931 }
18932 return -1;
18933 }
18934 if ((d = ast_calloc(1, sizeof(*d)))) {
18935
18936
18937 copy_request(&d->req, req);
18938 d->chan1 = transferee;
18939 d->chan2 = transferer;
18940 d->seqno = seqno;
18941 if (ast_pthread_create_detached_background(&th, NULL, sip_park_thread, d) < 0) {
18942
18943 if (d->req.data)
18944 ast_free(d->req.data);
18945 ast_free(d);
18946
18947 return 0;
18948 }
18949 }
18950 return -1;
18951 }
18952
18953
18954
18955
18956 static void ast_quiet_chan(struct ast_channel *chan)
18957 {
18958 if (chan && chan->_state == AST_STATE_UP) {
18959 if (ast_test_flag(chan, AST_FLAG_MOH))
18960 ast_moh_stop(chan);
18961 else if (chan->generatordata)
18962 ast_deactivate_generator(chan);
18963 }
18964 }
18965
18966
18967
18968 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target)
18969 {
18970 int res = 0;
18971 struct ast_channel *peera = NULL,
18972 *peerb = NULL,
18973 *peerc = NULL,
18974 *peerd = NULL;
18975
18976
18977
18978
18979 ast_debug(4, "Sip transfer:--------------------\n");
18980 if (transferer->chan1)
18981 ast_debug(4, "-- Transferer to PBX channel: %s State %s\n", transferer->chan1->name, ast_state2str(transferer->chan1->_state));
18982 else
18983 ast_debug(4, "-- No transferer first channel - odd??? \n");
18984 if (target->chan1)
18985 ast_debug(4, "-- Transferer to PBX second channel (target): %s State %s\n", target->chan1->name, ast_state2str(target->chan1->_state));
18986 else
18987 ast_debug(4, "-- No target first channel ---\n");
18988 if (transferer->chan2)
18989 ast_debug(4, "-- Bridged call to transferee: %s State %s\n", transferer->chan2->name, ast_state2str(transferer->chan2->_state));
18990 else
18991 ast_debug(4, "-- No bridged call to transferee\n");
18992 if (target->chan2)
18993 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)");
18994 else
18995 ast_debug(4, "-- No target second channel ---\n");
18996 ast_debug(4, "-- END Sip transfer:--------------------\n");
18997 if (transferer->chan2) {
18998 peera = transferer->chan1;
18999 peerb = target->chan1;
19000 peerc = transferer->chan2;
19001 peerd = target->chan2;
19002 ast_debug(3, "SIP transfer: Four channels to handle\n");
19003 } else if (target->chan2) {
19004 peera = target->chan1;
19005 peerb = transferer->chan1;
19006 peerc = target->chan2;
19007 peerd = transferer->chan2;
19008 ast_debug(3, "SIP transfer: Three channels to handle\n");
19009 }
19010
19011 if (peera && peerb && peerc && (peerb != peerc)) {
19012 ast_quiet_chan(peera);
19013 ast_quiet_chan(peerb);
19014 ast_quiet_chan(peerc);
19015 if (peerd)
19016 ast_quiet_chan(peerd);
19017
19018 ast_debug(4, "SIP transfer: trying to masquerade %s into %s\n", peerc->name, peerb->name);
19019 if (ast_channel_masquerade(peerb, peerc)) {
19020 ast_log(LOG_WARNING, "Failed to masquerade %s into %s\n", peerb->name, peerc->name);
19021 res = -1;
19022 } else
19023 ast_debug(4, "SIP transfer: Succeeded to masquerade channels.\n");
19024 return res;
19025 } else {
19026 ast_log(LOG_NOTICE, "SIP Transfer attempted with no appropriate bridged calls to transfer\n");
19027 if (transferer->chan1)
19028 ast_softhangup_nolock(transferer->chan1, AST_SOFTHANGUP_DEV);
19029 if (target->chan1)
19030 ast_softhangup_nolock(target->chan1, AST_SOFTHANGUP_DEV);
19031 return -1;
19032 }
19033 return 0;
19034 }
19035
19036
19037
19038
19039
19040
19041 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize)
19042 {
19043 const char *thetag;
19044
19045 if (!tagbuf)
19046 return NULL;
19047 tagbuf[0] = '\0';
19048 thetag = get_header(req, header);
19049 thetag = strcasestr(thetag, ";tag=");
19050 if (thetag) {
19051 thetag += 5;
19052 ast_copy_string(tagbuf, thetag, tagbufsize);
19053 return strsep(&tagbuf, ";");
19054 }
19055 return NULL;
19056 }
19057
19058
19059 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e)
19060 {
19061
19062
19063 int res = 0;
19064 const char *event = get_header(req, "Event");
19065 char *eventid = NULL;
19066 char *sep;
19067
19068 if( (sep = strchr(event, ';')) ) {
19069 *sep++ = '\0';
19070 eventid = sep;
19071 }
19072
19073 if (sipdebug)
19074 ast_debug(2, "Got NOTIFY Event: %s\n", event);
19075
19076 if (!strcmp(event, "refer")) {
19077
19078
19079
19080
19081
19082 char buf[1024];
19083 char *cmd, *code;
19084 int respcode;
19085 int success = TRUE;
19086
19087
19088
19089
19090
19091
19092
19093
19094 if (strncasecmp(get_header(req, "Content-Type"), "message/sipfrag", strlen("message/sipfrag"))) {
19095
19096 transmit_response(p, "400 Bad request", req);
19097 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19098 return -1;
19099 }
19100
19101
19102 if (get_msg_text(buf, sizeof(buf), req, TRUE)) {
19103 ast_log(LOG_WARNING, "Unable to retrieve attachment from NOTIFY %s\n", p->callid);
19104 transmit_response(p, "400 Bad request", req);
19105 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19106 return -1;
19107 }
19108
19109
19110
19111
19112
19113
19114
19115
19116
19117
19118
19119
19120
19121
19122
19123
19124
19125
19126
19127
19128
19129 ast_debug(3, "* SIP Transfer NOTIFY Attachment: \n---%s\n---\n", buf);
19130 cmd = ast_skip_blanks(buf);
19131 code = cmd;
19132
19133 while(*code && (*code > 32)) {
19134 code++;
19135 }
19136 *code++ = '\0';
19137 code = ast_skip_blanks(code);
19138 sep = code;
19139 sep++;
19140 while(*sep && (*sep > 32)) {
19141 sep++;
19142 }
19143 *sep++ = '\0';
19144 respcode = atoi(code);
19145 switch (respcode) {
19146 case 100:
19147 case 101:
19148
19149 break;
19150 case 183:
19151
19152 break;
19153 case 200:
19154
19155 break;
19156 case 301:
19157 case 302:
19158
19159 success = FALSE;
19160 break;
19161 case 503:
19162
19163 success = FALSE;
19164 break;
19165 case 603:
19166
19167 success = FALSE;
19168 break;
19169 }
19170 if (!success) {
19171 ast_log(LOG_NOTICE, "Transfer failed. Sorry. Nothing further to do with this call\n");
19172 }
19173
19174
19175 transmit_response(p, "200 OK", req);
19176 } else if (p->mwi && !strcmp(event, "message-summary")) {
19177 char *c = ast_strdupa(get_body(req, "Voice-Message", ':'));
19178
19179 if (!ast_strlen_zero(c)) {
19180 char *old = strsep(&c, " ");
19181 char *new = strsep(&old, "/");
19182 struct ast_event *event;
19183
19184 if ((event = ast_event_new(AST_EVENT_MWI,
19185 AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, p->mwi->mailbox,
19186 AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, "SIP_Remote",
19187 AST_EVENT_IE_NEWMSGS, AST_EVENT_IE_PLTYPE_UINT, atoi(new),
19188 AST_EVENT_IE_OLDMSGS, AST_EVENT_IE_PLTYPE_UINT, atoi(old),
19189 AST_EVENT_IE_END))) {
19190 ast_event_queue_and_cache(event);
19191 }
19192 }
19193
19194 transmit_response(p, "200 OK", req);
19195 } else if (!strcmp(event, "keep-alive")) {
19196
19197
19198 transmit_response(p, "200 OK", req);
19199 } else {
19200
19201 transmit_response(p, "489 Bad event", req);
19202 res = -1;
19203 }
19204
19205 if (!p->lastinvite)
19206 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19207
19208 return res;
19209 }
19210
19211
19212
19213
19214 static int handle_request_options(struct sip_pvt *p, struct sip_request *req)
19215 {
19216 int res;
19217
19218
19219
19220
19221
19222
19223
19224
19225
19226
19227
19228 if (p->lastinvite) {
19229
19230 transmit_response_with_allow(p, "200 OK", req, 0);
19231 return 0;
19232 }
19233
19234 res = get_destination(p, req);
19235 build_contact(p);
19236
19237 if (ast_strlen_zero(p->context))
19238 ast_string_field_set(p, context, sip_cfg.default_context);
19239
19240 if (ast_shutting_down())
19241 transmit_response_with_allow(p, "503 Unavailable", req, 0);
19242 else if (res < 0)
19243 transmit_response_with_allow(p, "404 Not Found", req, 0);
19244 else
19245 transmit_response_with_allow(p, "200 OK", req, 0);
19246
19247
19248
19249 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19250
19251 return res;
19252 }
19253
19254
19255
19256
19257
19258
19259
19260
19261
19262
19263 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin, int *nounlock)
19264 {
19265 int earlyreplace = 0;
19266 int oneleggedreplace = 0;
19267 struct ast_channel *c = p->owner;
19268 struct ast_channel *replacecall = p->refer->refer_call->owner;
19269 struct ast_channel *targetcall;
19270
19271 struct ast_channel *test;
19272
19273
19274 if (replacecall->_state == AST_STATE_RING)
19275 earlyreplace = 1;
19276
19277
19278 if (!(targetcall = ast_bridged_channel(replacecall))) {
19279
19280 if (!earlyreplace) {
19281 ast_debug(2, " Attended transfer attempted to replace call with no bridge (maybe ringing). Channel %s!\n", replacecall->name);
19282 oneleggedreplace = 1;
19283 }
19284 }
19285 if (targetcall && targetcall->_state == AST_STATE_RINGING)
19286 ast_debug(4, "SIP transfer: Target channel is in ringing state\n");
19287
19288 if (targetcall)
19289 ast_debug(4, "SIP transfer: Invite Replace incoming channel should bridge to channel %s while hanging up channel %s\n", targetcall->name, replacecall->name);
19290 else
19291 ast_debug(4, "SIP transfer: Invite Replace incoming channel should replace and hang up channel %s (one call leg)\n", replacecall->name);
19292
19293 if (req->ignore) {
19294 ast_log(LOG_NOTICE, "Ignoring this INVITE with replaces in a stupid way.\n");
19295
19296
19297
19298 transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE);
19299
19300 if (c) {
19301 *nounlock = 1;
19302 ast_channel_unlock(c);
19303 }
19304 ast_channel_unlock(replacecall);
19305 sip_pvt_unlock(p->refer->refer_call);
19306 return 1;
19307 }
19308 if (!c) {
19309
19310 ast_log(LOG_ERROR, "Unable to create new channel. Invite/replace failed.\n");
19311 transmit_response_reliable(p, "503 Service Unavailable", req);
19312 append_history(p, "Xfer", "INVITE/Replace Failed. No new channel.");
19313 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19314 ast_channel_unlock(replacecall);
19315 sip_pvt_unlock(p->refer->refer_call);
19316 return 1;
19317 }
19318 append_history(p, "Xfer", "INVITE/Replace received");
19319
19320
19321
19322
19323
19324
19325
19326
19327
19328
19329
19330 transmit_response(p, "100 Trying", req);
19331 ast_setstate(c, AST_STATE_RING);
19332
19333
19334
19335
19336
19337 transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE);
19338
19339 ast_setstate(c, AST_STATE_UP);
19340
19341
19342 ast_quiet_chan(replacecall);
19343 ast_quiet_chan(targetcall);
19344 ast_debug(4, "Invite/Replaces: preparing to masquerade %s into %s\n", c->name, replacecall->name);
19345
19346
19347 if (! earlyreplace && ! oneleggedreplace )
19348 ast_set_flag(&p->refer->refer_call->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
19349
19350
19351 if(ast_channel_masquerade(replacecall, c))
19352 ast_log(LOG_ERROR, "Failed to masquerade C into Replacecall\n");
19353 else
19354 ast_debug(4, "Invite/Replaces: Going to masquerade %s into %s\n", c->name, replacecall->name);
19355
19356
19357 if (ast_do_masquerade(replacecall)) {
19358 ast_log(LOG_WARNING, "Failed to perform masquerade with INVITE replaces\n");
19359 }
19360
19361 if (earlyreplace || oneleggedreplace ) {
19362 c->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
19363 }
19364
19365 ast_setstate(c, AST_STATE_DOWN);
19366 ast_debug(4, "After transfer:----------------------------\n");
19367 ast_debug(4, " -- C: %s State %s\n", c->name, ast_state2str(c->_state));
19368 if (replacecall)
19369 ast_debug(4, " -- replacecall: %s State %s\n", replacecall->name, ast_state2str(replacecall->_state));
19370 if (p->owner) {
19371 ast_debug(4, " -- P->owner: %s State %s\n", p->owner->name, ast_state2str(p->owner->_state));
19372 test = ast_bridged_channel(p->owner);
19373 if (test)
19374 ast_debug(4, " -- Call bridged to P->owner: %s State %s\n", test->name, ast_state2str(test->_state));
19375 else
19376 ast_debug(4, " -- No call bridged to C->owner \n");
19377 } else
19378 ast_debug(4, " -- No channel yet \n");
19379 ast_debug(4, "End After transfer:----------------------------\n");
19380
19381
19382 ast_channel_unlock(replacecall);
19383 ast_channel_unlock(c);
19384 sip_pvt_unlock(p->refer->refer_call);
19385 sip_pvt_unlock(p);
19386 *nounlock = 1;
19387
19388
19389 c->tech_pvt = dialog_unref(c->tech_pvt, "unref dialog c->tech_pvt");
19390 ast_hangup(c);
19391 sip_pvt_lock(p);
19392
19393 return 0;
19394 }
19395
19396
19397
19398
19399
19400
19401
19402
19403
19404
19405
19406
19407
19408
19409
19410
19411
19412 static int sip_uri_params_cmp(const char *input1, const char *input2)
19413 {
19414 char *params1 = NULL;
19415 char *params2 = NULL;
19416 char *pos1;
19417 char *pos2;
19418 int zerolength1 = 0;
19419 int zerolength2 = 0;
19420 int maddrmatch = 0;
19421 int ttlmatch = 0;
19422 int usermatch = 0;
19423 int methodmatch = 0;
19424
19425 if (ast_strlen_zero(input1)) {
19426 zerolength1 = 1;
19427 } else {
19428 params1 = ast_strdupa(input1);
19429 }
19430 if (ast_strlen_zero(input2)) {
19431 zerolength2 = 1;
19432 } else {
19433 params2 = ast_strdupa(input2);
19434 }
19435
19436
19437
19438
19439 if (zerolength1 && zerolength2) {
19440 return 0;
19441 }
19442
19443 pos1 = params1;
19444 while (!ast_strlen_zero(pos1)) {
19445 char *name1 = pos1;
19446 char *value1 = strchr(pos1, '=');
19447 char *semicolon1 = strchr(pos1, ';');
19448 int matched = 0;
19449 if (semicolon1) {
19450 *semicolon1++ = '\0';
19451 }
19452 if (!value1) {
19453 goto fail;
19454 }
19455 *value1++ = '\0';
19456
19457
19458
19459
19460
19461 pos2 = ast_strdupa(params2);
19462 while (!ast_strlen_zero(pos2)) {
19463 char *name2 = pos2;
19464 char *value2 = strchr(pos2, '=');
19465 char *semicolon2 = strchr(pos2, ';');
19466 if (semicolon2) {
19467 *semicolon2++ = '\0';
19468 }
19469 if (!value2) {
19470 goto fail;
19471 }
19472 *value2++ = '\0';
19473 if (!strcasecmp(name1, name2)) {
19474 if (strcasecmp(value1, value2)) {
19475 goto fail;
19476 } else {
19477 matched = 1;
19478 break;
19479 }
19480 }
19481 pos2 = semicolon2;
19482 }
19483
19484 if (!strcasecmp(name1, "maddr")) {
19485 if (matched) {
19486 maddrmatch = 1;
19487 } else {
19488 goto fail;
19489 }
19490 } else if (!strcasecmp(name1, "ttl")) {
19491 if (matched) {
19492 ttlmatch = 1;
19493 } else {
19494 goto fail;
19495 }
19496 } else if (!strcasecmp(name1, "user")) {
19497 if (matched) {
19498 usermatch = 1;
19499 } else {
19500 goto fail;
19501 }
19502 } else if (!strcasecmp(name1, "method")) {
19503 if (matched) {
19504 methodmatch = 1;
19505 } else {
19506 goto fail;
19507 }
19508 }
19509 pos1 = semicolon1;
19510 }
19511
19512
19513
19514
19515
19516 pos2 = params2;
19517 while (!ast_strlen_zero(pos2)) {
19518 char *name2 = pos2;
19519 char *value2 = strchr(pos2, '=');
19520 char *semicolon2 = strchr(pos2, ';');
19521 if (semicolon2) {
19522 *semicolon2++ = '\0';
19523 }
19524 if (!value2) {
19525 goto fail;
19526 }
19527 *value2++ = '\0';
19528 if ((!strcasecmp(name2, "maddr") && !maddrmatch) ||
19529 (!strcasecmp(name2, "ttl") && !ttlmatch) ||
19530 (!strcasecmp(name2, "user") && !usermatch) ||
19531 (!strcasecmp(name2, "method") && !methodmatch)) {
19532 goto fail;
19533 }
19534 }
19535 return 0;
19536
19537 fail:
19538 return 1;
19539 }
19540
19541
19542
19543
19544
19545
19546
19547
19548
19549
19550
19551
19552 static int sip_uri_headers_cmp(const char *input1, const char *input2)
19553 {
19554 char *headers1 = NULL;
19555 char *headers2 = NULL;
19556 int zerolength1 = 0;
19557 int zerolength2 = 0;
19558 int different = 0;
19559 char *header1;
19560
19561 if (ast_strlen_zero(input1)) {
19562 zerolength1 = 1;
19563 } else {
19564 headers1 = ast_strdupa(input1);
19565 }
19566
19567 if (ast_strlen_zero(input2)) {
19568 zerolength2 = 1;
19569 } else {
19570 headers2 = ast_strdupa(input2);
19571 }
19572
19573 if ((zerolength1 && !zerolength2) ||
19574 (zerolength2 && !zerolength1))
19575 return 1;
19576
19577 if (zerolength1 && zerolength2)
19578 return 0;
19579
19580
19581
19582
19583
19584 if (strlen(headers1) != strlen(headers2)) {
19585 return 1;
19586 }
19587
19588 for (header1 = strsep(&headers1, "&"); header1; header1 = strsep(&headers1, "&")) {
19589 if (!strcasestr(headers2, header1)) {
19590 different = 1;
19591 break;
19592 }
19593 }
19594
19595 return different;
19596 }
19597
19598 static int sip_uri_cmp(const char *input1, const char *input2)
19599 {
19600 char *uri1 = ast_strdupa(input1);
19601 char *uri2 = ast_strdupa(input2);
19602 char *host1;
19603 char *host2;
19604 char *params1;
19605 char *params2;
19606 char *headers1;
19607 char *headers2;
19608
19609
19610
19611
19612 strsep(&uri1, ":");
19613 strsep(&uri2, ":");
19614
19615 if ((host1 = strchr(uri1, '@'))) {
19616 *host1++ = '\0';
19617 }
19618 if ((host2 = strchr(uri2, '@'))) {
19619 *host2++ = '\0';
19620 }
19621
19622
19623
19624
19625 if ((host1 && !host2) ||
19626 (host2 && !host1) ||
19627 (host1 && host2 && strcmp(uri1, uri2))) {
19628 return 1;
19629 }
19630
19631 if (!host1)
19632 host1 = uri1;
19633 if (!host2)
19634 host2 = uri2;
19635
19636
19637
19638
19639
19640 if ((params1 = strchr(host1, ';'))) {
19641 *params1++ = '\0';
19642 }
19643 if ((params2 = strchr(host2, ';'))) {
19644 *params2++ = '\0';
19645 }
19646
19647
19648
19649
19650 if ((headers1 = strchr(S_OR(params1, host1), '?'))) {
19651 *headers1++ = '\0';
19652 }
19653 if ((headers2 = strchr(S_OR(params2, host2), '?'))) {
19654 *headers2++ = '\0';
19655 }
19656
19657
19658
19659
19660
19661
19662
19663
19664
19665
19666
19667 if (strcasecmp(host1, host2)) {
19668 return 1;
19669 }
19670
19671
19672 if (sip_uri_headers_cmp(headers1, headers2)) {
19673 return 1;
19674 }
19675
19676
19677 return sip_uri_params_cmp(params1, params2);
19678 }
19679
19680 static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context)
19681 {
19682 struct ast_str *str = ast_str_alloca(AST_MAX_EXTENSION + AST_MAX_CONTEXT + 2);
19683 struct ast_app *pickup = pbx_findapp("Pickup");
19684
19685 if (!pickup) {
19686 ast_log(LOG_ERROR, "Unable to perform pickup: Application 'Pickup' not loaded (app_directed_pickup.so).\n");
19687 return -1;
19688 }
19689
19690 ast_str_set(&str, 0, "%s@%s", extension, sip_cfg.notifycid == IGNORE_CONTEXT ? "PICKUPMARK" : context);
19691
19692 ast_debug(2, "About to call Pickup(%s)\n", str->str);
19693
19694
19695
19696
19697 pbx_exec(channel, pickup, str->str);
19698
19699 return 0;
19700 }
19701
19702
19703 static int sip_t38_abort(const void *data)
19704 {
19705 struct sip_pvt *p = (struct sip_pvt *) data;
19706
19707 sip_pvt_lock(p);
19708
19709
19710
19711
19712
19713 if (p->t38id != -1) {
19714 change_t38_state(p, T38_DISABLED);
19715 transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
19716 p->t38id = -1;
19717 dialog_unref(p, "unref the dialog ptr from sip_t38_abort, because it held a dialog ptr");
19718 }
19719 sip_pvt_unlock(p);
19720 return 0;
19721 }
19722
19723
19724
19725
19726
19727
19728
19729 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)
19730 {
19731 int res = 1;
19732 int gotdest;
19733 const char *p_replaces;
19734 char *replace_id = NULL;
19735 int refer_locked = 0;
19736 const char *required;
19737 unsigned int required_profile = 0;
19738 struct ast_channel *c = NULL;
19739 int reinvite = 0;
19740 int rtn;
19741
19742 const char *p_uac_se_hdr;
19743 const char *p_uac_min_se;
19744 int uac_max_se = -1;
19745 int uac_min_se = -1;
19746 int st_active = FALSE;
19747 int st_interval = 0;
19748 enum st_refresher st_ref;
19749 int dlg_min_se = -1;
19750 struct {
19751 char exten[AST_MAX_EXTENSION];
19752 char context[AST_MAX_CONTEXT];
19753 } pickup = {
19754 .exten = "",
19755 };
19756 st_ref = SESSION_TIMER_REFRESHER_AUTO;
19757
19758
19759 if (!p->sipoptions) {
19760 const char *supported = get_header(req, "Supported");
19761 if (!ast_strlen_zero(supported))
19762 parse_sip_options(p, supported);
19763 }
19764
19765
19766 required = get_header(req, "Require");
19767 if (!ast_strlen_zero(required)) {
19768 required_profile = parse_sip_options(NULL, required);
19769 if (required_profile && !(required_profile & (SIP_OPT_REPLACES | SIP_OPT_TIMER))) {
19770
19771 transmit_response_with_unsupported(p, "420 Bad extension (unsupported)", req, required);
19772 ast_log(LOG_WARNING, "Received SIP INVITE with unsupported required extension: %s\n", required);
19773 p->invitestate = INV_COMPLETED;
19774 if (!p->lastinvite)
19775 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19776 res = -1;
19777 goto request_invite_cleanup;
19778 }
19779 }
19780
19781
19782
19783 p->sipoptions |= required_profile;
19784 p->reqsipoptions = required_profile;
19785
19786
19787 if (ast_test_flag(&p->flags[0], SIP_OUTGOING) && p->owner && (p->invitestate != INV_TERMINATED && p->invitestate != INV_CONFIRMED)) {
19788
19789
19790
19791
19792
19793 int different;
19794 char *initial_rlPart2 = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
19795 char *this_rlPart2 = REQ_OFFSET_TO_STR(req, rlPart2);
19796 if (sip_cfg.pedanticsipchecking)
19797 different = sip_uri_cmp(initial_rlPart2, this_rlPart2);
19798 else
19799 different = strcmp(initial_rlPart2, this_rlPart2);
19800 if (!different) {
19801 transmit_response(p, "482 Loop Detected", req);
19802 p->invitestate = INV_COMPLETED;
19803 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19804 res = 0;
19805 goto request_invite_cleanup;
19806 } else {
19807
19808
19809
19810
19811
19812
19813
19814 char *uri = ast_strdupa(this_rlPart2);
19815 char *at = strchr(uri, '@');
19816 char *peerorhost;
19817 ast_debug(2, "Potential spiral detected. Original RURI was %s, new RURI is %s\n", initial_rlPart2, this_rlPart2);
19818 transmit_response(p, "100 Trying", req);
19819 if (at) {
19820 *at = '\0';
19821 }
19822
19823 if ((peerorhost = strchr(uri, ':'))) {
19824 *peerorhost++ = '\0';
19825 }
19826 ast_string_field_set(p, theirtag, NULL);
19827
19828
19829 ast_string_field_set(p->owner, call_forward, peerorhost);
19830 ast_queue_control(p->owner, AST_CONTROL_BUSY);
19831 res = 0;
19832 goto request_invite_cleanup;
19833 }
19834 }
19835
19836 if (!req->ignore && p->pendinginvite) {
19837 if (!ast_test_flag(&p->flags[0], SIP_OUTGOING) && (p->invitestate == INV_COMPLETED || p->invitestate == INV_TERMINATED)) {
19838
19839
19840
19841
19842
19843
19844
19845
19846
19847
19848 __sip_ack(p, p->pendinginvite, 1, 0);
19849 } else {
19850
19851 p->glareinvite = seqno;
19852 if (p->rtp && find_sdp(req)) {
19853 struct sockaddr_in sin;
19854 if (get_ip_and_port_from_sdp(req, SDP_AUDIO, &sin)) {
19855 ast_log(LOG_WARNING, "Failed to set an alternate media source on glared reinvite. Audio may not work properly on this call.\n");
19856 } else {
19857 ast_rtp_set_alt_peer(p->rtp, &sin);
19858 }
19859 if (p->vrtp) {
19860 if (get_ip_and_port_from_sdp(req, SDP_VIDEO, &sin)) {
19861 ast_log(LOG_WARNING, "Failed to set an alternate media source on glared reinvite. Video may not work properly on this call.\n");
19862 } else {
19863 ast_rtp_set_alt_peer(p->vrtp, &sin);
19864 }
19865 }
19866 }
19867 transmit_response_reliable(p, "491 Request Pending", req);
19868 ast_debug(1, "Got INVITE on call where we already have pending INVITE, deferring that - %s\n", p->callid);
19869
19870 res = 0;
19871 goto request_invite_cleanup;
19872 }
19873 }
19874
19875 p_replaces = get_header(req, "Replaces");
19876 if (!ast_strlen_zero(p_replaces)) {
19877
19878 char *ptr;
19879 char *fromtag = NULL;
19880 char *totag = NULL;
19881 char *start, *to;
19882 int error = 0;
19883
19884 if (p->owner) {
19885 ast_debug(3, "INVITE w Replaces on existing call? Refusing action. [%s]\n", p->callid);
19886 transmit_response_reliable(p, "400 Bad request", req);
19887
19888 res = -1;
19889 goto request_invite_cleanup;
19890 }
19891
19892 if (sipdebug)
19893 ast_debug(3, "INVITE part of call transfer. Replaces [%s]\n", p_replaces);
19894
19895 replace_id = ast_strdupa(p_replaces);
19896 ast_uri_decode(replace_id);
19897
19898 if (!p->refer && !sip_refer_allocate(p)) {
19899 transmit_response_reliable(p, "500 Server Internal Error", req);
19900 append_history(p, "Xfer", "INVITE/Replace Failed. Out of memory.");
19901 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19902 p->invitestate = INV_COMPLETED;
19903 res = -1;
19904 goto request_invite_cleanup;
19905 }
19906
19907
19908
19909
19910
19911
19912
19913
19914
19915
19916 replace_id = ast_skip_blanks(replace_id);
19917
19918 start = replace_id;
19919 while ( (ptr = strsep(&start, ";")) ) {
19920 ptr = ast_skip_blanks(ptr);
19921 if ( (to = strcasestr(ptr, "to-tag=") ) )
19922 totag = to + 7;
19923 else if ( (to = strcasestr(ptr, "from-tag=") ) ) {
19924 fromtag = to + 9;
19925 fromtag = strsep(&fromtag, "&");
19926 }
19927 }
19928
19929 if (sipdebug)
19930 ast_debug(4, "Invite/replaces: Will use Replace-Call-ID : %s Fromtag: %s Totag: %s\n",
19931 replace_id,
19932 fromtag ? fromtag : "<no from tag>",
19933 totag ? totag : "<no to tag>");
19934
19935
19936
19937
19938
19939 if (strncmp(replace_id, "pickup-", 7) == 0) {
19940 struct sip_pvt *subscription = NULL;
19941 replace_id += 7;
19942
19943 if ((subscription = get_sip_pvt_byid_locked(replace_id, NULL, NULL)) == NULL) {
19944 ast_log(LOG_NOTICE, "Unable to find subscription with call-id: %s\n", replace_id);
19945 transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
19946 error = 1;
19947 } else {
19948 ast_log(LOG_NOTICE, "Trying to pick up %s@%s\n", subscription->exten, subscription->context);
19949 ast_copy_string(pickup.exten, subscription->exten, sizeof(pickup.exten));
19950 ast_copy_string(pickup.context, subscription->context, sizeof(pickup.context));
19951 sip_pvt_unlock(subscription);
19952 if (subscription->owner) {
19953 ast_channel_unlock(subscription->owner);
19954 }
19955 }
19956 }
19957
19958
19959 if (!error && ast_strlen_zero(pickup.exten) && (p->refer->refer_call = get_sip_pvt_byid_locked(replace_id, totag, fromtag)) == NULL) {
19960 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existent call id (%s)!\n", replace_id);
19961 transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
19962 error = 1;
19963 } else {
19964 refer_locked = 1;
19965 }
19966
19967
19968
19969
19970
19971 if (p->refer->refer_call == p) {
19972 ast_log(LOG_NOTICE, "INVITE with replaces into it's own call id (%s == %s)!\n", replace_id, p->callid);
19973 p->refer->refer_call = dialog_unref(p->refer->refer_call, "unref dialog p->refer->refer_call");
19974 transmit_response_reliable(p, "400 Bad request", req);
19975 error = 1;
19976 }
19977
19978 if (!error && ast_strlen_zero(pickup.exten) && !p->refer->refer_call->owner) {
19979
19980 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existing call id (%s)!\n", replace_id);
19981
19982 transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replace)", req);
19983 error = 1;
19984 }
19985
19986 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) {
19987 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-ringing or active call id (%s)!\n", replace_id);
19988 transmit_response_reliable(p, "603 Declined (Replaces)", req);
19989 error = 1;
19990 }
19991
19992 if (error) {
19993 append_history(p, "Xfer", "INVITE/Replace Failed.");
19994 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19995 sip_pvt_unlock(p);
19996 if (p->refer->refer_call) {
19997 sip_pvt_unlock(p->refer->refer_call);
19998 if (p->refer->refer_call->owner) {
19999 ast_channel_unlock(p->refer->refer_call->owner);
20000 }
20001 }
20002 refer_locked = 0;
20003 p->invitestate = INV_COMPLETED;
20004 res = -1;
20005 goto request_invite_cleanup;
20006 }
20007 }
20008
20009
20010
20011
20012 if (!req->ignore) {
20013 int newcall = (p->initreq.headers ? TRUE : FALSE);
20014
20015 if (sip_cancel_destroy(p))
20016 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
20017
20018 p->pendinginvite = seqno;
20019 check_via(p, req);
20020
20021 copy_request(&p->initreq, req);
20022 if (sipdebug)
20023 ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
20024 if (!p->owner) {
20025 if (debug)
20026 ast_verbose("Using INVITE request as basis request - %s\n", p->callid);
20027 if (newcall)
20028 append_history(p, "Invite", "New call: %s", p->callid);
20029 parse_ok_contact(p, req);
20030 } else {
20031 ast_clear_flag(&p->flags[0], SIP_OUTGOING);
20032
20033 if (find_sdp(req)) {
20034 if (process_sdp(p, req, SDP_T38_INITIATE)) {
20035 transmit_response_reliable(p, "488 Not acceptable here", req);
20036 if (!p->lastinvite)
20037 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20038 res = -1;
20039 goto request_invite_cleanup;
20040 }
20041 ast_queue_control(p->owner, AST_CONTROL_SRCUPDATE);
20042 } else {
20043 p->jointcapability = p->capability;
20044 ast_debug(1, "Hm.... No sdp for the moment\n");
20045 }
20046 if (p->do_history)
20047 append_history(p, "ReInv", "Re-invite received");
20048 }
20049 } else if (debug)
20050 ast_verbose("Ignoring this INVITE request\n");
20051
20052 if (!p->lastinvite && !req->ignore && !p->owner) {
20053
20054
20055 res = check_user(p, req, SIP_INVITE, e, XMIT_RELIABLE, sin);
20056 if (res == AUTH_CHALLENGE_SENT) {
20057 p->invitestate = INV_COMPLETED;
20058 res = 0;
20059 goto request_invite_cleanup;
20060 }
20061 if (res < 0) {
20062 if (res == AUTH_FAKE_AUTH) {
20063 ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", get_header(req, "From"));
20064 transmit_fake_auth_response(p, SIP_INVITE, req, XMIT_RELIABLE);
20065 } else {
20066 ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", get_header(req, "From"));
20067 transmit_response_reliable(p, "403 Forbidden", req);
20068 }
20069 p->invitestate = INV_COMPLETED;
20070 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20071 ast_string_field_set(p, theirtag, NULL);
20072 res = 0;
20073 goto request_invite_cleanup;
20074 }
20075
20076
20077 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) && !p->udptl && (p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr))) {
20078 p->t38_maxdatagram = global_t38_maxdatagram;
20079 set_t38_capabilities(p);
20080 }
20081
20082
20083 if (find_sdp(req)) {
20084 if (process_sdp(p, req, SDP_T38_INITIATE)) {
20085
20086 transmit_response_reliable(p, "488 Not acceptable here", req);
20087 p->invitestate = INV_COMPLETED;
20088 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20089 ast_debug(1, "No compatible codecs for this SIP call.\n");
20090 res = -1;
20091 goto request_invite_cleanup;
20092 }
20093 } else {
20094 p->jointcapability = p->capability;
20095 ast_debug(2, "No SDP in Invite, third party call control\n");
20096 }
20097
20098
20099
20100 if (p->owner)
20101 ast_queue_frame(p->owner, &ast_null_frame);
20102
20103
20104
20105 if (ast_strlen_zero(p->context))
20106 ast_string_field_set(p, context, sip_cfg.default_context);
20107
20108
20109
20110 ast_debug(1, "Checking SIP call limits for device %s\n", p->username);
20111 if ((res = update_call_counter(p, INC_CALL_LIMIT))) {
20112 if (res < 0) {
20113 ast_log(LOG_NOTICE, "Failed to place call for device %s, too many calls\n", p->username);
20114 transmit_response_reliable(p, "480 Temporarily Unavailable (Call limit) ", req);
20115 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20116 p->invitestate = INV_COMPLETED;
20117 }
20118 res = 0;
20119 goto request_invite_cleanup;
20120 }
20121 gotdest = get_destination(p, NULL);
20122 get_rdnis(p, NULL);
20123 extract_uri(p, req);
20124 build_contact(p);
20125
20126 if (p->rtp) {
20127 ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
20128 ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
20129 }
20130
20131 if (!replace_id && gotdest) {
20132 if (gotdest == 1 && ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP))
20133 transmit_response_reliable(p, "484 Address Incomplete", req);
20134 else {
20135 char *decoded_exten = ast_strdupa(p->exten);
20136
20137 transmit_response_reliable(p, "404 Not Found", req);
20138 ast_uri_decode(decoded_exten);
20139 ast_log(LOG_NOTICE, "Call from '%s' to extension"
20140 " '%s' rejected because extension not found.\n",
20141 S_OR(p->username, p->peername), decoded_exten);
20142 }
20143 p->invitestate = INV_COMPLETED;
20144 update_call_counter(p, DEC_CALL_LIMIT);
20145 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20146 res = 0;
20147 goto request_invite_cleanup;
20148 } else {
20149
20150
20151
20152 if (ast_strlen_zero(p->exten))
20153 ast_string_field_set(p, exten, "s");
20154
20155
20156 make_our_tag(p->tag, sizeof(p->tag));
20157
20158 c = sip_new(p, AST_STATE_DOWN, S_OR(p->peername, NULL));
20159 *recount = 1;
20160
20161
20162 build_route(p, req, 0);
20163
20164 if (c) {
20165
20166 ast_channel_lock(c);
20167 }
20168 }
20169 } else {
20170 if (sipdebug) {
20171 if (!req->ignore)
20172 ast_debug(2, "Got a SIP re-invite for call %s\n", p->callid);
20173 else
20174 ast_debug(2, "Got a SIP re-transmit of INVITE for call %s\n", p->callid);
20175 }
20176 if (!req->ignore)
20177 reinvite = 1;
20178 c = p->owner;
20179 }
20180
20181
20182 if (p->sipoptions & SIP_OPT_TIMER) {
20183
20184
20185 ast_debug(2, "Incoming INVITE with 'timer' option enabled\n");
20186
20187
20188 if (!p->stimer)
20189 sip_st_alloc(p);
20190
20191
20192 p_uac_se_hdr = get_header(req, "Session-Expires");
20193 if (!ast_strlen_zero(p_uac_se_hdr)) {
20194 rtn = parse_session_expires(p_uac_se_hdr, &uac_max_se, &st_ref);
20195 if (rtn != 0) {
20196 transmit_response_reliable(p, "400 Session-Expires Invalid Syntax", req);
20197 p->invitestate = INV_COMPLETED;
20198 if (!p->lastinvite) {
20199 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20200 }
20201 res = -1;
20202 goto request_invite_cleanup;
20203 }
20204 }
20205
20206
20207 p_uac_min_se = get_header(req, "Min-SE");
20208 if (!ast_strlen_zero(p_uac_min_se)) {
20209 rtn = parse_minse(p_uac_min_se, &uac_min_se);
20210 if (rtn != 0) {
20211 transmit_response_reliable(p, "400 Min-SE Invalid Syntax", req);
20212 p->invitestate = INV_COMPLETED;
20213 if (!p->lastinvite) {
20214 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20215 }
20216 res = -1;
20217 goto request_invite_cleanup;
20218 }
20219 }
20220
20221 dlg_min_se = st_get_se(p, FALSE);
20222 switch (st_get_mode(p)) {
20223 case SESSION_TIMER_MODE_ACCEPT:
20224 case SESSION_TIMER_MODE_ORIGINATE:
20225 if (uac_max_se > 0 && uac_max_se < dlg_min_se) {
20226 transmit_response_with_minse(p, "422 Session Interval Too Small", req, dlg_min_se);
20227 p->invitestate = INV_COMPLETED;
20228 if (!p->lastinvite) {
20229 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20230 }
20231 res = -1;
20232 goto request_invite_cleanup;
20233 }
20234
20235 p->stimer->st_active_peer_ua = TRUE;
20236 st_active = TRUE;
20237 if (st_ref == SESSION_TIMER_REFRESHER_AUTO) {
20238 st_ref = st_get_refresher(p);
20239 }
20240
20241 if (uac_max_se > 0) {
20242 int dlg_max_se = st_get_se(p, TRUE);
20243 if (dlg_max_se >= uac_min_se) {
20244 st_interval = (uac_max_se < dlg_max_se) ? uac_max_se : dlg_max_se;
20245 } else {
20246 st_interval = uac_max_se;
20247 }
20248 } else {
20249
20250 st_interval = global_max_se;
20251 }
20252 break;
20253
20254 case SESSION_TIMER_MODE_REFUSE:
20255 if (p->reqsipoptions & SIP_OPT_TIMER) {
20256 transmit_response_with_unsupported(p, "420 Option Disabled", req, required);
20257 ast_log(LOG_WARNING, "Received SIP INVITE with supported but disabled option: %s\n", required);
20258 p->invitestate = INV_COMPLETED;
20259 if (!p->lastinvite) {
20260 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20261 }
20262 res = -1;
20263 goto request_invite_cleanup;
20264 }
20265 break;
20266
20267 default:
20268 ast_log(LOG_ERROR, "Internal Error %d at %s:%d\n", st_get_mode(p), __FILE__, __LINE__);
20269 break;
20270 }
20271 } else {
20272
20273
20274
20275 switch (st_get_mode(p)) {
20276 case SESSION_TIMER_MODE_ORIGINATE:
20277 st_active = TRUE;
20278 st_interval = st_get_se(p, TRUE);
20279 st_ref = SESSION_TIMER_REFRESHER_UAS;
20280 p->stimer->st_active_peer_ua = FALSE;
20281 break;
20282
20283 default:
20284 break;
20285 }
20286 }
20287
20288 if (reinvite == 0) {
20289
20290 if (st_active == TRUE) {
20291 p->stimer->st_active = TRUE;
20292 p->stimer->st_interval = st_interval;
20293 p->stimer->st_ref = st_ref;
20294 start_session_timer(p);
20295 }
20296 } else {
20297 if (p->stimer->st_active == TRUE) {
20298
20299
20300
20301 ast_debug (2, "Restarting session-timers on a refresh - %s\n", p->callid);
20302
20303
20304 if (st_interval > 0) {
20305 p->stimer->st_interval = st_interval;
20306 p->stimer->st_ref = st_ref;
20307 }
20308
20309 restart_session_timer(p);
20310 if (p->stimer->st_expirys > 0) {
20311 p->stimer->st_expirys--;
20312 }
20313 }
20314 }
20315
20316 if (!req->ignore && p)
20317 p->lastinvite = seqno;
20318
20319 if (replace_id) {
20320 if (!ast_strlen_zero(pickup.exten)) {
20321 append_history(p, "Xfer", "INVITE/Replace received");
20322
20323
20324 transmit_response(p, "100 Trying", req);
20325 ast_setstate(c, AST_STATE_RING);
20326
20327
20328 ast_channel_unlock(c);
20329 *nounlock = 1;
20330 do_magic_pickup(c, pickup.exten, pickup.context);
20331
20332
20333 sip_pvt_unlock(p);
20334 ast_hangup(c);
20335 sip_pvt_lock(p);
20336
20337 res = 0;
20338 goto request_invite_cleanup;
20339 } else {
20340
20341 if (sipdebug)
20342 ast_debug(4, "Sending this call to the invite/replcaes handler %s\n", p->callid);
20343 res = handle_invite_replaces(p, req, debug, seqno, sin, nounlock);
20344 refer_locked = 0;
20345 goto request_invite_cleanup;
20346 }
20347 }
20348
20349
20350 if (c) {
20351 enum ast_channel_state c_state = c->_state;
20352
20353 if (c_state != AST_STATE_UP && reinvite &&
20354 (p->invitestate == INV_TERMINATED || p->invitestate == INV_CONFIRMED)) {
20355
20356
20357
20358
20359
20360
20361
20362
20363
20364 c_state = AST_STATE_UP;
20365 }
20366
20367 switch(c_state) {
20368 case AST_STATE_DOWN:
20369 ast_debug(2, "%s: New call is still down.... Trying... \n", c->name);
20370 transmit_provisional_response(p, "100 Trying", req, 0);
20371 p->invitestate = INV_PROCEEDING;
20372 ast_setstate(c, AST_STATE_RING);
20373 if (strcmp(p->exten, ast_pickup_ext())) {
20374 enum ast_pbx_result result;
20375
20376 result = ast_pbx_start(c);
20377
20378 switch(result) {
20379 case AST_PBX_FAILED:
20380 ast_log(LOG_WARNING, "Failed to start PBX :(\n");
20381 p->invitestate = INV_COMPLETED;
20382 transmit_response_reliable(p, "503 Unavailable", req);
20383 break;
20384 case AST_PBX_CALL_LIMIT:
20385 ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
20386 p->invitestate = INV_COMPLETED;
20387 transmit_response_reliable(p, "480 Temporarily Unavailable", req);
20388 break;
20389 case AST_PBX_SUCCESS:
20390
20391 break;
20392 }
20393
20394 if (result) {
20395
20396
20397 ast_channel_unlock(c);
20398 sip_pvt_unlock(p);
20399 ast_hangup(c);
20400 sip_pvt_lock(p);
20401 c = NULL;
20402 }
20403 } else {
20404 ast_channel_unlock(c);
20405 *nounlock = 1;
20406 if (ast_pickup_call(c)) {
20407 ast_log(LOG_NOTICE, "Nothing to pick up for %s\n", p->callid);
20408 transmit_response_reliable(p, "503 Unavailable", req);
20409 sip_alreadygone(p);
20410
20411 sip_pvt_unlock(p);
20412 c->hangupcause = AST_CAUSE_CALL_REJECTED;
20413 } else {
20414 sip_pvt_unlock(p);
20415 ast_setstate(c, AST_STATE_DOWN);
20416 c->hangupcause = AST_CAUSE_NORMAL_CLEARING;
20417 }
20418 p->invitestate = INV_COMPLETED;
20419 ast_hangup(c);
20420 sip_pvt_lock(p);
20421 c = NULL;
20422 }
20423 break;
20424 case AST_STATE_RING:
20425 transmit_provisional_response(p, "100 Trying", req, 0);
20426 p->invitestate = INV_PROCEEDING;
20427 break;
20428 case AST_STATE_RINGING:
20429 transmit_provisional_response(p, "180 Ringing", req, 0);
20430 p->invitestate = INV_PROCEEDING;
20431 break;
20432 case AST_STATE_UP:
20433 ast_debug(2, "%s: This call is UP.... \n", c->name);
20434
20435 transmit_response(p, "100 Trying", req);
20436
20437 if (p->t38.state == T38_PEER_REINVITE) {
20438 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."));
20439 } else if (p->t38.state == T38_ENABLED) {
20440 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
20441 transmit_response_with_t38_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL)));
20442 } else if (p->t38.state == T38_DISABLED) {
20443
20444 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
20445 transmit_response_with_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL)), p->session_modify == TRUE ? FALSE:TRUE);
20446 }
20447
20448 p->invitestate = INV_TERMINATED;
20449 break;
20450 default:
20451 ast_log(LOG_WARNING, "Don't know how to handle INVITE in state %d\n", c->_state);
20452 transmit_response(p, "100 Trying", req);
20453 break;
20454 }
20455 } else {
20456 if (p && (p->autokillid == -1)) {
20457 const char *msg;
20458
20459 if (!p->jointcapability)
20460 msg = "488 Not Acceptable Here (codec error)";
20461 else {
20462 ast_log(LOG_NOTICE, "Unable to create/find SIP channel for this INVITE\n");
20463 msg = "503 Unavailable";
20464 }
20465 transmit_response_reliable(p, msg, req);
20466 p->invitestate = INV_COMPLETED;
20467 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20468 }
20469 }
20470
20471 request_invite_cleanup:
20472
20473 if (refer_locked && p->refer && p->refer->refer_call) {
20474 sip_pvt_unlock(p->refer->refer_call);
20475 if (p->refer->refer_call->owner) {
20476 ast_channel_unlock(p->refer->refer_call->owner);
20477 }
20478 }
20479
20480 return res;
20481 }
20482
20483
20484
20485 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno)
20486 {
20487 struct sip_dual target;
20488
20489 int res = 0;
20490 struct sip_pvt *targetcall_pvt;
20491
20492
20493 if (!(targetcall_pvt = get_sip_pvt_byid_locked(transferer->refer->replaces_callid, transferer->refer->replaces_callid_totag,
20494 transferer->refer->replaces_callid_fromtag))) {
20495 if (transferer->refer->localtransfer) {
20496
20497 transmit_response(transferer, "202 Accepted", req);
20498
20499
20500 transmit_notify_with_sipfrag(transferer, seqno, "481 Call leg/transaction does not exist", TRUE);
20501 append_history(transferer, "Xfer", "Refer failed");
20502 ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
20503 transferer->refer->status = REFER_FAILED;
20504 return -1;
20505 }
20506
20507 ast_debug(3, "SIP attended transfer: Not our call - generating INVITE with replaces\n");
20508 return 0;
20509 }
20510
20511
20512 transmit_response(transferer, "202 Accepted", req);
20513 append_history(transferer, "Xfer", "Refer accepted");
20514 if (!targetcall_pvt->owner) {
20515 ast_debug(4, "SIP attended transfer: Error: No owner of target call\n");
20516
20517 transmit_notify_with_sipfrag(transferer, seqno, "503 Service Unavailable", TRUE);
20518 append_history(transferer, "Xfer", "Refer failed");
20519 ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
20520 transferer->refer->status = REFER_FAILED;
20521 sip_pvt_unlock(targetcall_pvt);
20522 if (targetcall_pvt)
20523 ao2_t_ref(targetcall_pvt, -1, "Drop targetcall_pvt pointer");
20524 return -1;
20525 }
20526
20527
20528 target.chan1 = targetcall_pvt->owner;
20529 target.chan2 = ast_bridged_channel(targetcall_pvt->owner);
20530
20531 if (!target.chan2 || !(target.chan2->_state == AST_STATE_UP || target.chan2->_state == AST_STATE_RINGING) ) {
20532
20533 if (target.chan2)
20534 ast_debug(4, "SIP attended transfer: Error: Wrong state of target call: %s\n", ast_state2str(target.chan2->_state));
20535 else if (target.chan1->_state != AST_STATE_RING)
20536 ast_debug(4, "SIP attended transfer: Error: No target channel\n");
20537 else
20538 ast_debug(4, "SIP attended transfer: Attempting transfer in ringing state\n");
20539 }
20540
20541
20542 if (sipdebug) {
20543 if (current->chan2)
20544 ast_debug(4, "SIP attended transfer: trying to bridge %s and %s\n", target.chan1->name, current->chan2->name);
20545 else
20546 ast_debug(4, "SIP attended transfer: trying to make %s take over (masq) %s\n", target.chan1->name, current->chan1->name);
20547 }
20548
20549 ast_set_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
20550
20551
20552 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",
20553 transferer->owner->name,
20554 transferer->owner->uniqueid,
20555 transferer->callid,
20556 target.chan1->name,
20557 target.chan1->uniqueid);
20558 res = attempt_transfer(current, &target);
20559 sip_pvt_unlock(targetcall_pvt);
20560 if (res) {
20561
20562 transmit_notify_with_sipfrag(transferer, seqno, "486 Busy Here", TRUE);
20563 append_history(transferer, "Xfer", "Refer failed");
20564 if (targetcall_pvt->owner)
20565 ast_channel_unlock(targetcall_pvt->owner);
20566 ast_clear_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
20567 } else {
20568
20569 const char *xfersound = pbx_builtin_getvar_helper(target.chan1, "ATTENDED_TRANSFER_COMPLETE_SOUND");
20570
20571
20572 transmit_notify_with_sipfrag(transferer, seqno, "200 OK", TRUE);
20573 append_history(transferer, "Xfer", "Refer succeeded");
20574 transferer->refer->status = REFER_200OK;
20575 if (target.chan2 && !ast_strlen_zero(xfersound) && ast_streamfile(target.chan2, xfersound, target.chan2->language) >= 0) {
20576 ast_waitstream(target.chan2, "");
20577 }
20578 if (targetcall_pvt->owner) {
20579 ast_debug(1, "SIP attended transfer: Unlocking channel %s\n", targetcall_pvt->owner->name);
20580 ast_channel_unlock(targetcall_pvt->owner);
20581 }
20582 }
20583 if (targetcall_pvt)
20584 ao2_t_ref(targetcall_pvt, -1, "drop targetcall_pvt");
20585 return 1;
20586 }
20587
20588
20589
20590
20591
20592
20593
20594
20595
20596
20597
20598
20599
20600
20601
20602
20603
20604
20605
20606
20607
20608
20609
20610
20611
20612
20613
20614
20615
20616
20617
20618
20619
20620
20621
20622
20623
20624
20625
20626
20627
20628
20629
20630
20631
20632
20633
20634
20635
20636
20637
20638
20639
20640
20641
20642
20643
20644
20645
20646
20647
20648
20649
20650
20651
20652 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock)
20653 {
20654 struct sip_dual current;
20655
20656
20657 int res = 0;
20658 current.req.data = NULL;
20659
20660 if (req->debug)
20661 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");
20662
20663 if (!p->owner) {
20664
20665
20666 ast_debug(3, "Call %s: Declined REFER, outside of dialog...\n", p->callid);
20667 transmit_response(p, "603 Declined (No dialog)", req);
20668 if (!req->ignore) {
20669 append_history(p, "Xfer", "Refer failed. Outside of dialog.");
20670 sip_alreadygone(p);
20671 pvt_set_needdestroy(p, "outside of dialog");
20672 }
20673 return 0;
20674 }
20675
20676
20677
20678 if (p->allowtransfer == TRANSFER_CLOSED ) {
20679
20680 transmit_response(p, "603 Declined (policy)", req);
20681 append_history(p, "Xfer", "Refer failed. Allowtransfer == closed.");
20682
20683 return 0;
20684 }
20685
20686 if (!req->ignore && ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
20687
20688 transmit_response(p, "491 Request pending", req);
20689 append_history(p, "Xfer", "Refer failed. Request pending.");
20690 return 0;
20691 }
20692
20693
20694 if (!p->refer && !sip_refer_allocate(p)) {
20695 transmit_response(p, "500 Internal Server Error", req);
20696 append_history(p, "Xfer", "Refer failed. Memory allocation error.");
20697 return -3;
20698 }
20699
20700 res = get_refer_info(p, req);
20701
20702 p->refer->status = REFER_SENT;
20703
20704 if (res != 0) {
20705 switch (res) {
20706 case -2:
20707 transmit_response(p, "400 Bad Request (Refer-to missing)", req);
20708 append_history(p, "Xfer", "Refer failed. Refer-to missing.");
20709 if (req->debug)
20710 ast_debug(1, "SIP transfer to black hole can't be handled (no refer-to: )\n");
20711 break;
20712 case -3:
20713 transmit_response(p, "603 Declined (Non sip: uri)", req);
20714 append_history(p, "Xfer", "Refer failed. Non SIP uri");
20715 if (req->debug)
20716 ast_debug(1, "SIP transfer to non-SIP uri denied\n");
20717 break;
20718 default:
20719
20720 transmit_response(p, "202 Accepted", req);
20721 append_history(p, "Xfer", "Refer failed. Bad extension.");
20722 transmit_notify_with_sipfrag(p, seqno, "404 Not found", TRUE);
20723 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
20724 if (req->debug)
20725 ast_debug(1, "SIP transfer to bad extension: %s\n", p->refer->refer_to);
20726 break;
20727 }
20728 return 0;
20729 }
20730 if (ast_strlen_zero(p->context))
20731 ast_string_field_set(p, context, sip_cfg.default_context);
20732
20733
20734 if (sip_cfg.allow_external_domains && check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
20735 p->refer->localtransfer = 1;
20736 if (sipdebug)
20737 ast_debug(3, "This SIP transfer is local : %s\n", p->refer->refer_to_domain);
20738 } else if (AST_LIST_EMPTY(&domain_list) || check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
20739
20740 p->refer->localtransfer = 1;
20741 } else if (sipdebug)
20742 ast_debug(3, "This SIP transfer is to a remote SIP extension (remote domain %s)\n", p->refer->refer_to_domain);
20743
20744
20745
20746 if (req->ignore)
20747 return res;
20748
20749
20750
20751
20752
20753
20754
20755
20756
20757
20758
20759
20760
20761
20762
20763
20764
20765
20766
20767
20768
20769
20770
20771
20772
20773
20774
20775 current.chan1 = p->owner;
20776
20777
20778 current.chan2 = ast_bridged_channel(current.chan1);
20779
20780 if (sipdebug)
20781 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>");
20782
20783 if (!current.chan2 && !p->refer->attendedtransfer) {
20784
20785
20786
20787 if (sipdebug)
20788 ast_debug(3, "Refused SIP transfer on non-bridged channel.\n");
20789 p->refer->status = REFER_FAILED;
20790 append_history(p, "Xfer", "Refer failed. Non-bridged channel.");
20791 transmit_response(p, "603 Declined", req);
20792 return -1;
20793 }
20794
20795 if (current.chan2) {
20796 if (sipdebug)
20797 ast_debug(4, "Got SIP transfer, applying to bridged peer '%s'\n", current.chan2->name);
20798
20799 ast_queue_control(current.chan1, AST_CONTROL_UNHOLD);
20800 }
20801
20802 ast_set_flag(&p->flags[0], SIP_GOTREFER);
20803
20804
20805 if (p->refer->attendedtransfer) {
20806 if ((res = local_attended_transfer(p, ¤t, req, seqno)))
20807 return res;
20808
20809 if (sipdebug)
20810 ast_debug(4, "SIP attended transfer: Still not our call - generating INVITE with replaces\n");
20811
20812 }
20813
20814
20815
20816 if (p->refer->localtransfer && !strcmp(p->refer->refer_to, ast_parking_ext())) {
20817
20818 *nounlock = 1;
20819 ast_channel_unlock(current.chan1);
20820 copy_request(¤t.req, req);
20821 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
20822 p->refer->status = REFER_200OK;
20823 append_history(p, "Xfer", "REFER to call parking.");
20824 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",
20825 current.chan1->name,
20826 current.chan1->uniqueid,
20827 p->callid,
20828 current.chan2->name,
20829 current.chan2->uniqueid,
20830 p->refer->refer_to);
20831 if (sipdebug)
20832 ast_debug(4, "SIP transfer to parking: trying to park %s. Parked by %s\n", current.chan2->name, current.chan1->name);
20833 sip_park(current.chan2, current.chan1, req, seqno);
20834 return res;
20835 }
20836
20837
20838 transmit_response(p, "202 Accepted", req);
20839
20840 if (current.chan1 && current.chan2) {
20841 ast_debug(3, "chan1->name: %s\n", current.chan1->name);
20842 pbx_builtin_setvar_helper(current.chan1, "BLINDTRANSFER", current.chan2->name);
20843 }
20844 if (current.chan2) {
20845 pbx_builtin_setvar_helper(current.chan2, "BLINDTRANSFER", current.chan1->name);
20846 pbx_builtin_setvar_helper(current.chan2, "SIPDOMAIN", p->refer->refer_to_domain);
20847 pbx_builtin_setvar_helper(current.chan2, "SIPTRANSFER", "yes");
20848
20849 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER", "yes");
20850
20851 if (p->refer->referred_by)
20852 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REFERER", p->refer->referred_by);
20853 }
20854
20855 if (!ast_strlen_zero(p->refer->replaces_callid)) {
20856 char tempheader[SIPBUFSIZE];
20857 snprintf(tempheader, sizeof(tempheader), "%s%s%s%s%s", p->refer->replaces_callid,
20858 p->refer->replaces_callid_totag ? ";to-tag=" : "",
20859 p->refer->replaces_callid_totag,
20860 p->refer->replaces_callid_fromtag ? ";from-tag=" : "",
20861 p->refer->replaces_callid_fromtag);
20862 if (current.chan2)
20863 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REPLACES", tempheader);
20864 }
20865
20866
20867 *nounlock = 1;
20868 ast_channel_unlock(current.chan1);
20869
20870
20871
20872
20873 if (!p->refer->attendedtransfer)
20874 transmit_notify_with_sipfrag(p, seqno, "183 Ringing", FALSE);
20875
20876
20877
20878
20879
20880 if (!current.chan2) {
20881
20882
20883
20884
20885
20886
20887
20888 p->refer->status = REFER_FAILED;
20889 transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable (can't handle one-legged xfers)", TRUE);
20890 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
20891 append_history(p, "Xfer", "Refer failed (only bridged calls).");
20892 return -1;
20893 }
20894 ast_set_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
20895
20896
20897
20898
20899 res = ast_async_goto(current.chan2, p->refer->refer_to_context, p->refer->refer_to, 1);
20900
20901 if (!res) {
20902 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",
20903 current.chan1->name,
20904 current.chan1->uniqueid,
20905 p->callid,
20906 current.chan2->name,
20907 current.chan2->uniqueid,
20908 p->refer->refer_to, p->refer->refer_to_context);
20909
20910 ast_debug(3, "%s transfer succeeded. Telling transferer.\n", p->refer->attendedtransfer? "Attended" : "Blind");
20911 transmit_notify_with_sipfrag(p, seqno, "200 Ok", TRUE);
20912 if (p->refer->localtransfer)
20913 p->refer->status = REFER_200OK;
20914 if (p->owner)
20915 p->owner->hangupcause = AST_CAUSE_NORMAL_CLEARING;
20916 append_history(p, "Xfer", "Refer succeeded.");
20917 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
20918
20919
20920 res = 0;
20921 } else {
20922 ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
20923 ast_debug(3, "%s transfer failed. Resuming original call.\n", p->refer->attendedtransfer? "Attended" : "Blind");
20924 append_history(p, "Xfer", "Refer failed.");
20925
20926 p->refer->status = REFER_FAILED;
20927 transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable", TRUE);
20928 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
20929 res = -1;
20930 }
20931 return res;
20932 }
20933
20934
20935 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req)
20936 {
20937
20938 check_via(p, req);
20939 sip_alreadygone(p);
20940
20941
20942
20943
20944
20945
20946 if (p->invitestate == INV_TERMINATED)
20947 __sip_pretend_ack(p);
20948 else
20949 p->invitestate = INV_CANCELLED;
20950
20951 if (p->owner && p->owner->_state == AST_STATE_UP) {
20952
20953 transmit_response(p, "200 OK", req);
20954 ast_debug(1, "Got CANCEL on an answered call. Ignoring... \n");
20955 return 0;
20956 }
20957
20958 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD))
20959 update_call_counter(p, DEC_CALL_LIMIT);
20960
20961 stop_media_flows(p);
20962 if (p->owner)
20963 ast_queue_hangup(p->owner);
20964 else
20965 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20966 if (p->initreq.len > 0) {
20967 struct sip_pkt *pkt, *prev_pkt;
20968
20969
20970
20971
20972
20973
20974
20975
20976
20977
20978
20979 for (pkt = p->packets, prev_pkt = NULL; pkt; prev_pkt = pkt, pkt = pkt->next) {
20980 if (pkt->seqno == p->lastinvite && pkt->response_code == 487) {
20981 AST_SCHED_DEL(sched, pkt->retransid);
20982 UNLINK(pkt, p->packets, prev_pkt);
20983 ast_free(pkt);
20984 break;
20985 }
20986 }
20987 transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
20988 transmit_response(p, "200 OK", req);
20989 return 1;
20990 } else {
20991 transmit_response(p, "481 Call Leg Does Not Exist", req);
20992 return 0;
20993 }
20994 }
20995
20996 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen)
20997 {
20998 struct sip_pvt *p = chan->tech_pvt;
20999 char *all = "", *parse = ast_strdupa(preparse);
21000 int res = 0;
21001 AST_DECLARE_APP_ARGS(args,
21002 AST_APP_ARG(param);
21003 AST_APP_ARG(type);
21004 AST_APP_ARG(field);
21005 );
21006 AST_STANDARD_APP_ARGS(args, parse);
21007
21008
21009 if (!IS_SIP_TECH(chan->tech)) {
21010 ast_log(LOG_ERROR, "Cannot call %s on a non-SIP channel\n", funcname);
21011 return 0;
21012 }
21013
21014 memset(buf, 0, buflen);
21015
21016 if (p == NULL) {
21017 return -1;
21018 }
21019
21020 if (!strcasecmp(args.param, "peerip")) {
21021 ast_copy_string(buf, p->sa.sin_addr.s_addr ? ast_inet_ntoa(p->sa.sin_addr) : "", buflen);
21022 } else if (!strcasecmp(args.param, "recvip")) {
21023 ast_copy_string(buf, p->recv.sin_addr.s_addr ? ast_inet_ntoa(p->recv.sin_addr) : "", buflen);
21024 } else if (!strcasecmp(args.param, "from")) {
21025 ast_copy_string(buf, p->from, buflen);
21026 } else if (!strcasecmp(args.param, "uri")) {
21027 ast_copy_string(buf, p->uri, buflen);
21028 } else if (!strcasecmp(args.param, "useragent")) {
21029 ast_copy_string(buf, p->useragent, buflen);
21030 } else if (!strcasecmp(args.param, "peername")) {
21031 ast_copy_string(buf, p->peername, buflen);
21032 } else if (!strcasecmp(args.param, "t38passthrough")) {
21033 ast_copy_string(buf, (p->t38.state == T38_DISABLED) ? "0" : "1", buflen);
21034 } else if (!strcasecmp(args.param, "rtpdest")) {
21035 struct sockaddr_in sin;
21036 struct ast_rtp *stream = NULL;
21037
21038 if (ast_strlen_zero(args.type))
21039 args.type = "audio";
21040
21041 if (!strcasecmp(args.type, "audio")) {
21042 stream = p->rtp;
21043 } else if (!strcasecmp(args.type, "video")) {
21044 stream = p->vrtp;
21045 } else if (!strcasecmp(args.type, "text")) {
21046 stream = p->trtp;
21047 } else {
21048 return -1;
21049 }
21050
21051 if (!stream) {
21052 return -1;
21053 }
21054
21055 ast_rtp_get_peer(stream, &sin);
21056 snprintf(buf, buflen, "%s:%d", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
21057 } else if (!strcasecmp(args.param, "rtpqos")) {
21058 struct ast_rtp_quality qos;
21059 struct ast_rtp *rtp = p->rtp;
21060
21061 memset(&qos, 0, sizeof(qos));
21062
21063 if (ast_strlen_zero(args.type))
21064 args.type = "audio";
21065 if (ast_strlen_zero(args.field))
21066 args.field = "all";
21067
21068 if (!strcasecmp(args.type, "AUDIO")) {
21069 all = ast_rtp_get_quality(rtp = p->rtp, &qos, RTPQOS_SUMMARY);
21070 } else if (!strcasecmp(args.type, "VIDEO")) {
21071 all = ast_rtp_get_quality(rtp = p->vrtp, &qos, RTPQOS_SUMMARY);
21072 } else if (!strcasecmp(args.type, "TEXT")) {
21073 all = ast_rtp_get_quality(rtp = p->trtp, &qos, RTPQOS_SUMMARY);
21074 } else {
21075 return -1;
21076 }
21077
21078 if (!strcasecmp(args.field, "local_ssrc"))
21079 snprintf(buf, buflen, "%u", qos.local_ssrc);
21080 else if (!strcasecmp(args.field, "local_lostpackets"))
21081 snprintf(buf, buflen, "%u", qos.local_lostpackets);
21082 else if (!strcasecmp(args.field, "local_jitter"))
21083 snprintf(buf, buflen, "%.0f", qos.local_jitter * 1000.0);
21084 else if (!strcasecmp(args.field, "local_count"))
21085 snprintf(buf, buflen, "%u", qos.local_count);
21086 else if (!strcasecmp(args.field, "remote_ssrc"))
21087 snprintf(buf, buflen, "%u", qos.remote_ssrc);
21088 else if (!strcasecmp(args.field, "remote_lostpackets"))
21089 snprintf(buf, buflen, "%u", qos.remote_lostpackets);
21090 else if (!strcasecmp(args.field, "remote_jitter"))
21091 snprintf(buf, buflen, "%.0f", qos.remote_jitter * 1000.0);
21092 else if (!strcasecmp(args.field, "remote_count"))
21093 snprintf(buf, buflen, "%u", qos.remote_count);
21094 else if (!strcasecmp(args.field, "rtt"))
21095 snprintf(buf, buflen, "%.0f", qos.rtt * 1000.0);
21096 else if (!strcasecmp(args.field, "all"))
21097 ast_copy_string(buf, all, buflen);
21098 else if (!ast_rtp_get_qos(rtp, args.field, buf, buflen))
21099 ;
21100 else {
21101 ast_log(LOG_WARNING, "Unrecognized argument '%s' to %s\n", preparse, funcname);
21102 return -1;
21103 }
21104 } else {
21105 res = -1;
21106 }
21107 return res;
21108 }
21109
21110
21111 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req)
21112 {
21113 struct ast_channel *c=NULL;
21114 int res;
21115 struct ast_channel *bridged_to;
21116
21117
21118 if (p->pendinginvite && !ast_test_flag(&p->flags[0], SIP_OUTGOING) && !req->ignore) {
21119 transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
21120 }
21121
21122 __sip_pretend_ack(p);
21123
21124 p->invitestate = INV_TERMINATED;
21125
21126 copy_request(&p->initreq, req);
21127 if (sipdebug)
21128 ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
21129 check_via(p, req);
21130 sip_alreadygone(p);
21131
21132
21133 if (p->do_history || p->owner) {
21134 struct ast_channel *bridge = p->owner ? ast_bridged_channel(p->owner) : NULL;
21135 char *videoqos, *textqos;
21136
21137
21138
21139
21140 while (bridge && ast_channel_trylock(bridge)) {
21141 ast_channel_unlock(p->owner);
21142 do {
21143
21144 sip_pvt_unlock(p);
21145 usleep(1);
21146 sip_pvt_lock(p);
21147 } while (p->owner && ast_channel_trylock(p->owner));
21148 bridge = p->owner ? ast_bridged_channel(p->owner) : NULL;
21149 }
21150
21151 if (p->rtp) {
21152 if (p->do_history) {
21153 char *audioqos,
21154 *audioqos_jitter,
21155 *audioqos_loss,
21156 *audioqos_rtt;
21157
21158 audioqos = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_SUMMARY);
21159 audioqos_jitter = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_JITTER);
21160 audioqos_loss = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_LOSS);
21161 audioqos_rtt = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_RTT);
21162
21163 append_history(p, "RTCPaudio", "Quality:%s", audioqos);
21164 append_history(p, "RTCPaudioJitter", "Quality:%s", audioqos_jitter);
21165 append_history(p, "RTCPaudioLoss", "Quality:%s", audioqos_loss);
21166 append_history(p, "RTCPaudioRTT", "Quality:%s", audioqos_rtt);
21167 }
21168
21169 if (p->owner) {
21170 ast_rtp_set_vars(p->owner, p->rtp);
21171 }
21172 }
21173
21174 if (bridge) {
21175 struct sip_pvt *q = bridge->tech_pvt;
21176
21177 if (IS_SIP_TECH(bridge->tech) && q && q->rtp)
21178 ast_rtp_set_vars(bridge, q->rtp);
21179 ast_channel_unlock(bridge);
21180 }
21181
21182 if (p->vrtp) {
21183 videoqos = ast_rtp_get_quality(p->vrtp, NULL, RTPQOS_SUMMARY);
21184 if (p->do_history)
21185 append_history(p, "RTCPvideo", "Quality:%s", videoqos);
21186 if (p->owner)
21187 pbx_builtin_setvar_helper(p->owner, "RTPVIDEOQOS", videoqos);
21188 }
21189
21190 if (p->trtp) {
21191 textqos = ast_rtp_get_quality(p->trtp, NULL, RTPQOS_SUMMARY);
21192 if (p->do_history)
21193 append_history(p, "RTCPtext", "Quality:%s", textqos);
21194 if (p->owner)
21195 pbx_builtin_setvar_helper(p->owner, "RTPTEXTQOS", textqos);
21196 }
21197 }
21198
21199 stop_media_flows(p);
21200 stop_session_timer(p);
21201
21202 if (!ast_strlen_zero(get_header(req, "Also"))) {
21203 ast_log(LOG_NOTICE, "Client '%s' using deprecated BYE/Also transfer method. Ask vendor to support REFER instead\n",
21204 ast_inet_ntoa(p->recv.sin_addr));
21205 if (ast_strlen_zero(p->context))
21206 ast_string_field_set(p, context, sip_cfg.default_context);
21207 res = get_also_info(p, req);
21208 if (!res) {
21209 c = p->owner;
21210 if (c) {
21211 bridged_to = ast_bridged_channel(c);
21212 if (bridged_to) {
21213
21214 ast_queue_control(c, AST_CONTROL_UNHOLD);
21215 ast_async_goto(bridged_to, p->context, p->refer->refer_to, 1);
21216 } else
21217 ast_queue_hangup(p->owner);
21218 }
21219 } else {
21220 ast_log(LOG_WARNING, "Invalid transfer information from '%s'\n", ast_inet_ntoa(p->recv.sin_addr));
21221 if (p->owner)
21222 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
21223 }
21224 } else if (p->owner) {
21225 ast_queue_hangup(p->owner);
21226 ast_debug(3, "Received bye, issuing owner hangup\n");
21227 } else {
21228 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21229 ast_debug(3, "Received bye, no owner, selfdestruct soon.\n");
21230 }
21231 ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
21232 transmit_response(p, "200 OK", req);
21233
21234 return 1;
21235 }
21236
21237
21238 static int handle_request_message(struct sip_pvt *p, struct sip_request *req)
21239 {
21240 if (!req->ignore) {
21241 if (req->debug)
21242 ast_verbose("Receiving message!\n");
21243 receive_message(p, req);
21244 } else
21245 transmit_response(p, "202 Accepted", req);
21246 return 1;
21247 }
21248
21249 static void add_peer_mwi_subs(struct sip_peer *peer)
21250 {
21251 struct sip_mailbox *mailbox;
21252
21253 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
21254 mailbox->event_sub = ast_event_subscribe(AST_EVENT_MWI, mwi_event_cb, peer,
21255 AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox->mailbox,
21256 AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, S_OR(mailbox->context, "default"),
21257 AST_EVENT_IE_END);
21258 }
21259 }
21260
21261
21262 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e)
21263 {
21264 int gotdest = 0;
21265 int res = 0;
21266 int firststate = AST_EXTENSION_REMOVED;
21267 struct sip_peer *authpeer = NULL;
21268 const char *eventheader = get_header(req, "Event");
21269 const char *acceptheader = get_header(req, "Accept");
21270 int resubscribe = (p->subscribed != NONE);
21271 char *temp, *event;
21272 struct ao2_iterator i;
21273
21274 if (p->initreq.headers) {
21275
21276 if (p->initreq.method != SIP_SUBSCRIBE) {
21277
21278
21279 transmit_response(p, "403 Forbidden (within dialog)", req);
21280
21281 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);
21282 return 0;
21283 } else if (req->debug) {
21284 if (resubscribe)
21285 ast_debug(1, "Got a re-subscribe on existing subscription %s\n", p->callid);
21286 else
21287 ast_debug(1, "Got a new subscription %s (possibly with auth)\n", p->callid);
21288 }
21289 }
21290
21291
21292
21293
21294 if (!sip_cfg.allowsubscribe) {
21295 transmit_response(p, "403 Forbidden (policy)", req);
21296 pvt_set_needdestroy(p, "forbidden");
21297 return 0;
21298 }
21299
21300 if (!req->ignore && !resubscribe) {
21301 const char *to = get_header(req, "To");
21302 char totag[128];
21303
21304
21305 if (!ast_strlen_zero(to) && gettag(req, "To", totag, sizeof(totag))) {
21306 if (req->debug)
21307 ast_verbose("Received resubscription for a dialog we no longer know about. Telling remote side to subscribe again.\n");
21308 transmit_response(p, "481 Subscription does not exist", req);
21309 pvt_set_needdestroy(p, "subscription does not exist");
21310 return 0;
21311 }
21312
21313
21314 if (req->debug)
21315 ast_verbose("Creating new subscription\n");
21316
21317 copy_request(&p->initreq, req);
21318 if (sipdebug)
21319 ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
21320 check_via(p, req);
21321 build_route(p, req, 0);
21322 } else if (req->debug && req->ignore)
21323 ast_verbose("Ignoring this SUBSCRIBE request\n");
21324
21325
21326 if (ast_strlen_zero(eventheader)) {
21327 transmit_response(p, "489 Bad Event", req);
21328 ast_debug(2, "Received SIP subscribe for unknown event package: <none>\n");
21329 pvt_set_needdestroy(p, "unknown event package in subscribe");
21330 return 0;
21331 }
21332
21333 if ( (strchr(eventheader, ';'))) {
21334 event = ast_strdupa(eventheader);
21335 temp = strchr(event, ';');
21336 *temp = '\0';
21337
21338 } else
21339 event = (char *) eventheader;
21340
21341
21342 res = check_user_full(p, req, SIP_SUBSCRIBE, e, 0, sin, &authpeer);
21343
21344 if (res == AUTH_CHALLENGE_SENT)
21345 return 0;
21346 if (res < 0) {
21347 if (res == AUTH_FAKE_AUTH) {
21348 ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", get_header(req, "From"));
21349 transmit_fake_auth_response(p, SIP_SUBSCRIBE, req, XMIT_UNRELIABLE);
21350 } else {
21351 ast_log(LOG_NOTICE, "Failed to authenticate device %s for SUBSCRIBE\n", get_header(req, "From"));
21352 transmit_response_reliable(p, "403 Forbidden", req);
21353 }
21354 pvt_set_needdestroy(p, "authentication failed");
21355 return 0;
21356 }
21357
21358
21359
21360
21361
21362
21363
21364 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
21365 transmit_response(p, "403 Forbidden (policy)", req);
21366 pvt_set_needdestroy(p, "subscription not allowed");
21367 if (authpeer)
21368 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 1)");
21369 return 0;
21370 }
21371
21372 if (strcmp(event, "message-summary")) {
21373
21374 gotdest = get_destination(p, NULL);
21375 }
21376
21377
21378 parse_ok_contact(p, req);
21379
21380 build_contact(p);
21381 if (gotdest) {
21382 transmit_response(p, "404 Not Found", req);
21383 pvt_set_needdestroy(p, "subscription target not found");
21384 if (authpeer)
21385 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
21386 return 0;
21387 }
21388
21389
21390 if (ast_strlen_zero(p->tag))
21391 make_our_tag(p->tag, sizeof(p->tag));
21392
21393 if (!strcmp(event, "presence") || !strcmp(event, "dialog")) {
21394 unsigned int pidf_xml;
21395
21396 if (authpeer)
21397 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
21398
21399
21400
21401 pidf_xml = strstr(acceptheader, "application/pidf+xml") ? 1 : 0;
21402
21403
21404
21405 if (pidf_xml && strstr(p->useragent, "Polycom")) {
21406 p->subscribed = XPIDF_XML;
21407 } else if (pidf_xml) {
21408 p->subscribed = PIDF_XML;
21409 } else if (strstr(acceptheader, "application/dialog-info+xml")) {
21410 p->subscribed = DIALOG_INFO_XML;
21411
21412 } else if (strstr(acceptheader, "application/cpim-pidf+xml")) {
21413 p->subscribed = CPIM_PIDF_XML;
21414 } else if (strstr(acceptheader, "application/xpidf+xml")) {
21415 p->subscribed = XPIDF_XML;
21416 } else if (ast_strlen_zero(acceptheader)) {
21417 if (p->subscribed == NONE) {
21418 transmit_response(p, "489 Bad Event", req);
21419
21420 ast_log(LOG_WARNING, "SUBSCRIBE failure: no Accept header: pvt: stateid: %d, laststate: %d, dialogver: %d, subscribecont: '%s', subscribeuri: '%s'\n",
21421 p->stateid, p->laststate, p->dialogver, p->subscribecontext, p->subscribeuri);
21422 pvt_set_needdestroy(p, "no Accept header");
21423 return 0;
21424 }
21425
21426
21427 } else {
21428
21429 char mybuf[200];
21430 snprintf(mybuf, sizeof(mybuf), "489 Bad Event (format %s)", acceptheader);
21431 transmit_response(p, mybuf, req);
21432
21433 ast_log(LOG_WARNING, "SUBSCRIBE failure: unrecognized format: '%s' pvt: subscribed: %d, stateid: %d, laststate: %d, dialogver: %d, subscribecont: '%s', subscribeuri: '%s'\n",
21434 acceptheader, (int)p->subscribed, p->stateid, p->laststate, p->dialogver, p->subscribecontext, p->subscribeuri);
21435 pvt_set_needdestroy(p, "unrecognized format");
21436 return 0;
21437 }
21438 } else if (!strcmp(event, "message-summary")) {
21439 if (!ast_strlen_zero(acceptheader) && strcmp(acceptheader, "application/simple-message-summary")) {
21440
21441 transmit_response(p, "406 Not Acceptable", req);
21442 ast_debug(2, "Received SIP mailbox subscription for unknown format: %s\n", acceptheader);
21443 pvt_set_needdestroy(p, "unknown format");
21444 if (authpeer)
21445 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 3)");
21446 return 0;
21447 }
21448
21449
21450
21451
21452
21453 if (!authpeer || AST_LIST_EMPTY(&authpeer->mailboxes)) {
21454 transmit_response(p, "404 Not found (no mailbox)", req);
21455 pvt_set_needdestroy(p, "received 404 response");
21456 ast_log(LOG_NOTICE, "Received SIP subscribe for peer without mailbox: %s\n", authpeer->name);
21457 if (authpeer)
21458 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 4)");
21459 return 0;
21460 }
21461
21462 p->subscribed = MWI_NOTIFICATION;
21463 if (ast_test_flag(&authpeer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY)) {
21464 add_peer_mwi_subs(authpeer);
21465 }
21466 if (authpeer->mwipvt && authpeer->mwipvt != p) {
21467
21468 dialog_unlink_all(authpeer->mwipvt, TRUE, TRUE);
21469 authpeer->mwipvt = dialog_unref(authpeer->mwipvt, "unref dialog authpeer->mwipvt");
21470
21471 }
21472 if (authpeer->mwipvt)
21473 dialog_unref(authpeer->mwipvt, "Unref previously stored mwipvt dialog pointer");
21474 authpeer->mwipvt = dialog_ref(p, "setting peers' mwipvt to p");
21475 if (p->relatedpeer)
21476 unref_peer(p->relatedpeer, "Unref previously stored relatedpeer ptr");
21477 p->relatedpeer = ref_peer(authpeer, "setting dialog's relatedpeer pointer");
21478
21479 } else {
21480 transmit_response(p, "489 Bad Event", req);
21481 ast_debug(2, "Received SIP subscribe for unknown event package: %s\n", event);
21482 pvt_set_needdestroy(p, "unknown event package");
21483 if (authpeer)
21484 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 5)");
21485 return 0;
21486 }
21487
21488
21489 if (p->subscribed != MWI_NOTIFICATION && !resubscribe) {
21490 if (p->stateid > -1) {
21491 ast_extension_state_del(p->stateid, cb_extensionstate);
21492
21493 dialog_unref(p, "the extensionstate containing this dialog ptr was deleted");
21494 }
21495 p->stateid = ast_extension_state_add(p->context, p->exten, cb_extensionstate, dialog_ref(p,"copying dialog ptr into extension state struct"));
21496 }
21497
21498 if (!req->ignore && p)
21499 p->lastinvite = seqno;
21500 if (p && !p->needdestroy) {
21501 p->expiry = atoi(get_header(req, "Expires"));
21502
21503
21504 if (p->expiry > max_expiry)
21505 p->expiry = max_expiry;
21506 if (p->expiry < min_expiry && p->expiry > 0)
21507 p->expiry = min_expiry;
21508
21509 if (sipdebug) {
21510 if (p->subscribed == MWI_NOTIFICATION && p->relatedpeer)
21511 ast_debug(2, "Adding subscription for mailbox notification - peer %s\n", p->relatedpeer->name);
21512 else
21513 ast_debug(2, "Adding subscription for extension %s context %s for peer %s\n", p->exten, p->context, p->username);
21514 }
21515 if (p->autokillid > -1 && sip_cancel_destroy(p))
21516 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
21517 if (p->expiry > 0)
21518 sip_scheddestroy(p, (p->expiry + 10) * 1000);
21519
21520 if (p->subscribed == MWI_NOTIFICATION) {
21521 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
21522 transmit_response(p, "200 OK", req);
21523 if (p->relatedpeer) {
21524 ao2_lock(p->relatedpeer);
21525 sip_send_mwi_to_peer(p->relatedpeer, NULL, 0);
21526 ao2_unlock(p->relatedpeer);
21527 }
21528 } else {
21529 struct sip_pvt *p_old;
21530
21531 if ((firststate = ast_extension_state(NULL, p->context, p->exten)) < 0) {
21532
21533 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));
21534 transmit_response(p, "404 Not found", req);
21535 pvt_set_needdestroy(p, "no extension for SUBSCRIBE");
21536 return 0;
21537 }
21538 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
21539 transmit_response(p, "200 OK", req);
21540 transmit_state_notify(p, firststate, 1, FALSE);
21541 append_history(p, "Subscribestatus", "%s", ast_extension_state2str(firststate));
21542
21543 ast_string_field_build(p, subscribeuri, "%s@%s", p->exten, p->context);
21544
21545
21546
21547
21548
21549
21550 i = ao2_iterator_init(dialogs, 0);
21551 while ((p_old = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
21552 if (p_old == p) {
21553 ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next before continue");
21554 continue;
21555 }
21556 if (p_old->initreq.method != SIP_SUBSCRIBE) {
21557 ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next before continue");
21558 continue;
21559 }
21560 if (p_old->subscribed == NONE) {
21561 ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next before continue");
21562 continue;
21563 }
21564 sip_pvt_lock(p_old);
21565 if (!strcmp(p_old->username, p->username)) {
21566 if (!strcmp(p_old->exten, p->exten) &&
21567 !strcmp(p_old->context, p->context)) {
21568 pvt_set_needdestroy(p_old, "replacing subscription");
21569 sip_pvt_unlock(p_old);
21570 ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next before break");
21571 break;
21572 }
21573 }
21574 sip_pvt_unlock(p_old);
21575 ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next");
21576 }
21577 ao2_iterator_destroy(&i);
21578 }
21579 if (!p->expiry) {
21580 pvt_set_needdestroy(p, "forcing expiration");
21581 }
21582 }
21583 return 1;
21584 }
21585
21586
21587 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e)
21588 {
21589 enum check_auth_result res;
21590
21591
21592 copy_request(&p->initreq, req);
21593 if (sipdebug)
21594 ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
21595 check_via(p, req);
21596 if ((res = register_verify(p, sin, req, e)) < 0) {
21597 const char *reason;
21598
21599 switch (res) {
21600 case AUTH_SECRET_FAILED:
21601 reason = "Wrong password";
21602 break;
21603 case AUTH_USERNAME_MISMATCH:
21604 reason = "Username/auth name mismatch";
21605 break;
21606 case AUTH_NOT_FOUND:
21607 reason = "No matching peer found";
21608 break;
21609 case AUTH_UNKNOWN_DOMAIN:
21610 reason = "Not a local domain";
21611 break;
21612 case AUTH_PEER_NOT_DYNAMIC:
21613 reason = "Peer is not supposed to register";
21614 break;
21615 case AUTH_ACL_FAILED:
21616 reason = "Device does not match ACL";
21617 break;
21618 case AUTH_BAD_TRANSPORT:
21619 reason = "Device not configured to use this transport type";
21620 break;
21621 default:
21622 reason = "Unknown failure";
21623 break;
21624 }
21625 ast_log(LOG_NOTICE, "Registration from '%s' failed for '%s' - %s\n",
21626 get_header(req, "To"), ast_inet_ntoa(sin->sin_addr),
21627 reason);
21628 append_history(p, "RegRequest", "Failed : Account %s : %s", get_header(req, "To"), reason);
21629 } else
21630 append_history(p, "RegRequest", "Succeeded : Account %s", get_header(req, "To"));
21631
21632 if (res < 1) {
21633
21634
21635 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21636 }
21637 return res;
21638 }
21639
21640
21641
21642
21643 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock)
21644 {
21645
21646
21647 const char *cmd;
21648 const char *cseq;
21649 const char *useragent;
21650 int seqno;
21651 int len;
21652 int respid;
21653 int res = 0;
21654 int debug = sip_debug_test_pvt(p);
21655 char *e;
21656 int error = 0;
21657 int oldmethod = p->method;
21658 int acked = 0;
21659
21660
21661 cseq = get_header(req, "Cseq");
21662 cmd = REQ_OFFSET_TO_STR(req, header[0]);
21663
21664
21665 if (ast_strlen_zero(cmd) || ast_strlen_zero(cseq)) {
21666 ast_log(LOG_ERROR, "Missing Cseq. Dropping this SIP message, it's incomplete.\n");
21667 error = 1;
21668 }
21669 if (!error && sscanf(cseq, "%30d%n", &seqno, &len) != 1) {
21670 ast_log(LOG_ERROR, "No seqno in '%s'. Dropping incomplete message.\n", cmd);
21671 error = 1;
21672 }
21673 if (error) {
21674 if (!p->initreq.headers) {
21675 pvt_set_needdestroy(p, "no headers");
21676 }
21677 return -1;
21678 }
21679
21680
21681 cmd = REQ_OFFSET_TO_STR(req, rlPart1);
21682 e = ast_skip_blanks(REQ_OFFSET_TO_STR(req, rlPart2));
21683
21684
21685 useragent = get_header(req, "User-Agent");
21686 if (!ast_strlen_zero(useragent))
21687 ast_string_field_set(p, useragent, useragent);
21688
21689
21690 if (req->method == SIP_RESPONSE) {
21691
21692
21693
21694
21695
21696
21697 if (ast_strlen_zero(e)) {
21698 return 0;
21699 }
21700 if (sscanf(e, "%30d %n", &respid, &len) != 1) {
21701 ast_log(LOG_WARNING, "Invalid response: '%s'\n", e);
21702 return 0;
21703 }
21704 if (respid <= 0) {
21705 ast_log(LOG_WARNING, "Invalid SIP response code: '%d'\n", respid);
21706 return 0;
21707 }
21708 if (p->ocseq && (p->ocseq < seqno)) {
21709 if (option_debug)
21710 ast_log(LOG_DEBUG, "Ignoring out of order response %d (expecting %d)\n", seqno, p->ocseq);
21711 return -1;
21712 } else {
21713 if ((respid == 200) || ((respid >= 300) && (respid <= 399))) {
21714 extract_uri(p, req);
21715 }
21716 handle_response(p, respid, e + len, req, seqno);
21717 }
21718 return 0;
21719 }
21720
21721
21722
21723
21724
21725 p->method = req->method;
21726 ast_debug(4, "**** Received %s (%d) - Command in SIP %s\n", sip_methods[p->method].text, sip_methods[p->method].id, cmd);
21727
21728 if (p->icseq && (p->icseq > seqno) ) {
21729 if (p->pendinginvite && seqno == p->pendinginvite && (req->method == SIP_ACK || req->method == SIP_CANCEL)) {
21730 ast_debug(2, "Got CANCEL or ACK on INVITE with transactions in between.\n");
21731 } else {
21732 ast_debug(1, "Ignoring too old SIP packet packet %d (expecting >= %d)\n", seqno, p->icseq);
21733 if (req->method != SIP_ACK)
21734 transmit_response(p, "503 Server error", req);
21735 return -1;
21736 }
21737 } else if (p->icseq &&
21738 p->icseq == seqno &&
21739 req->method != SIP_ACK &&
21740 (p->method != SIP_CANCEL || p->alreadygone)) {
21741
21742
21743
21744 req->ignore = 1;
21745 ast_debug(3, "Ignoring SIP message because of retransmit (%s Seqno %d, ours %d)\n", sip_methods[p->method].text, p->icseq, seqno);
21746 }
21747
21748 if (seqno >= p->icseq)
21749
21750
21751
21752 p->icseq = seqno;
21753
21754
21755 if (ast_strlen_zero(p->theirtag)) {
21756 char tag[128];
21757
21758 gettag(req, "From", tag, sizeof(tag));
21759 ast_string_field_set(p, theirtag, tag);
21760 }
21761 snprintf(p->lastmsg, sizeof(p->lastmsg), "Rx: %s", cmd);
21762
21763 if (sip_cfg.pedanticsipchecking) {
21764
21765
21766
21767
21768 if (!p->initreq.headers && req->has_to_tag) {
21769
21770 if (!req->ignore && req->method == SIP_INVITE) {
21771 transmit_response_reliable(p, "481 Call/Transaction Does Not Exist", req);
21772
21773 } else if (req->method != SIP_ACK) {
21774 transmit_response(p, "481 Call/Transaction Does Not Exist", req);
21775 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21776 } else {
21777 ast_debug(1, "Got ACK for unknown dialog... strange.\n");
21778 }
21779 return res;
21780 }
21781 }
21782
21783 if (!e && (p->method == SIP_INVITE || p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER || p->method == SIP_NOTIFY)) {
21784 transmit_response(p, "400 Bad request", req);
21785 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21786 return -1;
21787 }
21788
21789
21790 switch (p->method) {
21791 case SIP_OPTIONS:
21792 res = handle_request_options(p, req);
21793 break;
21794 case SIP_INVITE:
21795 res = handle_request_invite(p, req, debug, seqno, sin, recount, e, nounlock);
21796 break;
21797 case SIP_REFER:
21798 res = handle_request_refer(p, req, debug, seqno, nounlock);
21799 break;
21800 case SIP_CANCEL:
21801 res = handle_request_cancel(p, req);
21802 break;
21803 case SIP_BYE:
21804 res = handle_request_bye(p, req);
21805 break;
21806 case SIP_MESSAGE:
21807 res = handle_request_message(p, req);
21808 break;
21809 case SIP_SUBSCRIBE:
21810 res = handle_request_subscribe(p, req, sin, seqno, e);
21811 break;
21812 case SIP_REGISTER:
21813 res = handle_request_register(p, req, sin, e);
21814 break;
21815 case SIP_INFO:
21816 if (req->debug)
21817 ast_verbose("Receiving INFO!\n");
21818 if (!req->ignore)
21819 handle_request_info(p, req);
21820 else
21821 transmit_response(p, "200 OK", req);
21822 break;
21823 case SIP_NOTIFY:
21824 res = handle_request_notify(p, req, sin, seqno, e);
21825 break;
21826 case SIP_ACK:
21827
21828 if (seqno == p->pendinginvite) {
21829 p->invitestate = INV_TERMINATED;
21830 p->pendinginvite = 0;
21831 acked = __sip_ack(p, seqno, 1 , 0);
21832 if (find_sdp(req)) {
21833 if (process_sdp(p, req, SDP_T38_NONE))
21834 return -1;
21835 }
21836 check_pendings(p);
21837 } else if (p->glareinvite == seqno) {
21838
21839 p->glareinvite = 0;
21840 acked = __sip_ack(p, seqno, 1, 0);
21841 }
21842 if (!acked) {
21843
21844
21845 p->method = oldmethod;
21846 }
21847 if (!p->lastinvite && ast_strlen_zero(p->randdata)) {
21848 pvt_set_needdestroy(p, "unmatched ACK");
21849 }
21850 break;
21851 default:
21852 transmit_response_with_allow(p, "501 Method Not Implemented", req, 0);
21853 ast_log(LOG_NOTICE, "Unknown SIP command '%s' from '%s'\n",
21854 cmd, ast_inet_ntoa(p->sa.sin_addr));
21855
21856 if (!p->initreq.headers) {
21857 pvt_set_needdestroy(p, "unimplemented method");
21858 }
21859 break;
21860 }
21861 return res;
21862 }
21863
21864 static void process_request_queue(struct sip_pvt *p, int *recount, int *nounlock)
21865 {
21866 struct sip_request *req;
21867
21868 while ((req = AST_LIST_REMOVE_HEAD(&p->request_queue, next))) {
21869 if (handle_incoming(p, req, &p->recv, recount, nounlock) == -1) {
21870
21871 if (option_debug) {
21872 ast_log(LOG_DEBUG, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
21873 }
21874 }
21875 ast_free(req);
21876 }
21877 }
21878
21879 static int scheduler_process_request_queue(const void *data)
21880 {
21881 struct sip_pvt *p = (struct sip_pvt *) data;
21882 int recount = 0;
21883 int nounlock = 0;
21884 int lockretry;
21885
21886 for (lockretry = 10; lockretry > 0; lockretry--) {
21887 sip_pvt_lock(p);
21888
21889
21890
21891 if (!p->owner || !ast_channel_trylock(p->owner)) {
21892 break;
21893 }
21894
21895 if (lockretry != 1) {
21896 sip_pvt_unlock(p);
21897
21898 usleep(1);
21899 }
21900 }
21901
21902 if (!lockretry) {
21903 int retry = !AST_LIST_EMPTY(&p->request_queue);
21904
21905
21906
21907
21908
21909
21910 sip_pvt_unlock(p);
21911 if (!retry) {
21912 dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
21913 }
21914 return retry;
21915 };
21916
21917 process_request_queue(p, &recount, &nounlock);
21918 p->request_queue_sched_id = -1;
21919
21920 if (p->owner && !nounlock) {
21921 ast_channel_unlock(p->owner);
21922 }
21923 sip_pvt_unlock(p);
21924
21925 if (recount) {
21926 ast_update_use_count();
21927 }
21928
21929 dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
21930
21931 return 0;
21932 }
21933
21934 static int queue_request(struct sip_pvt *p, const struct sip_request *req)
21935 {
21936 struct sip_request *newreq;
21937
21938 if (!(newreq = ast_calloc(1, sizeof(*newreq)))) {
21939 return -1;
21940 }
21941
21942 copy_request(newreq, req);
21943 AST_LIST_INSERT_TAIL(&p->request_queue, newreq, next);
21944 if (p->request_queue_sched_id == -1) {
21945 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) {
21946 dialog_unref(p, "Decrement refcount due to sched_add failure");
21947 }
21948 }
21949
21950 return 0;
21951 }
21952
21953
21954
21955
21956
21957
21958 static int sipsock_read(int *id, int fd, short events, void *ignore)
21959 {
21960 struct sip_request req;
21961 struct sockaddr_in sin = { 0, };
21962 int res;
21963 socklen_t len = sizeof(sin);
21964 static char readbuf[65535];
21965
21966 memset(&req, 0, sizeof(req));
21967 res = recvfrom(fd, readbuf, sizeof(readbuf) - 1, 0, (struct sockaddr *)&sin, &len);
21968 if (res < 0) {
21969 #if !defined(__FreeBSD__)
21970 if (errno == EAGAIN)
21971 ast_log(LOG_NOTICE, "SIP: Received packet with bad UDP checksum\n");
21972 else
21973 #endif
21974 if (errno != ECONNREFUSED)
21975 ast_log(LOG_WARNING, "Recv error: %s\n", strerror(errno));
21976 return 1;
21977 }
21978
21979 readbuf[res] = '\0';
21980
21981 if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
21982 return 1;
21983 }
21984
21985 if (ast_str_set(&req.data, 0, "%s", readbuf) == AST_DYNSTR_BUILD_FAILED) {
21986 return -1;
21987 }
21988
21989 req.len = res;
21990 req.socket.fd = sipsock;
21991 set_socket_transport(&req.socket, SIP_TRANSPORT_UDP);
21992 req.socket.tcptls_session = NULL;
21993 req.socket.port = bindaddr.sin_port;
21994
21995 handle_request_do(&req, &sin);
21996 if (req.data) {
21997 ast_free(req.data);
21998 req.data = NULL;
21999 }
22000
22001 return 1;
22002 }
22003
22004
22005
22006
22007
22008 static int handle_request_do(struct sip_request *req, struct sockaddr_in *sin)
22009 {
22010 struct sip_pvt *p;
22011 int recount = 0;
22012 int nounlock = 0;
22013 int lockretry;
22014
22015 if (sip_debug_test_addr(sin))
22016 req->debug = 1;
22017 if (sip_cfg.pedanticsipchecking)
22018 req->len = lws2sws(req->data->str, req->len);
22019 if (req->debug) {
22020 ast_verbose("\n<--- SIP read from %s:%s:%d --->\n%s\n<------------->\n",
22021 get_transport(req->socket.type), ast_inet_ntoa(sin->sin_addr),
22022 ntohs(sin->sin_port), req->data->str);
22023 }
22024
22025 if (parse_request(req) == -1) {
22026 ast_str_reset(req->data);
22027 return 1;
22028 }
22029 req->method = find_sip_method(REQ_OFFSET_TO_STR(req, rlPart1));
22030
22031 if (req->debug)
22032 ast_verbose("--- (%d headers %d lines)%s ---\n", req->headers, req->lines, (req->headers + req->lines == 0) ? " Nat keepalive" : "");
22033
22034 if (req->headers < 2) {
22035 ast_str_reset(req->data);
22036 return 1;
22037 }
22038
22039
22040 for (lockretry = 10; lockretry > 0; lockretry--) {
22041 ast_mutex_lock(&netlock);
22042
22043
22044 p = find_call(req, sin, req->method);
22045 if (p == NULL) {
22046 ast_debug(1, "Invalid SIP message - rejected , no callid, len %d\n", req->len);
22047 ast_mutex_unlock(&netlock);
22048 return 1;
22049 }
22050
22051 copy_socket_data(&p->socket, &req->socket);
22052
22053
22054
22055 if (!p->owner || !ast_channel_trylock(p->owner))
22056 break;
22057
22058 if (lockretry != 1) {
22059 sip_pvt_unlock(p);
22060 ao2_t_ref(p, -1, "release p (from find_call) inside lockretry loop");
22061 ast_mutex_unlock(&netlock);
22062
22063 usleep(1);
22064 }
22065 }
22066 p->recv = *sin;
22067
22068 if (p->do_history)
22069 append_history(p, "Rx", "%s / %s / %s", req->data->str, get_header(req, "CSeq"), REQ_OFFSET_TO_STR(req, rlPart2));
22070
22071 if (!lockretry) {
22072 if (!queue_request(p, req)) {
22073
22074 sip_pvt_unlock(p);
22075 ao2_t_ref(p, -1, "release p (from find_call) after queueing request");
22076 ast_mutex_unlock(&netlock);
22077 return 1;
22078 }
22079
22080 if (p->owner)
22081 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 ??? - "));
22082 ast_log(LOG_ERROR, "SIP transaction failed: %s \n", p->callid);
22083 if (req->method != SIP_ACK)
22084 transmit_response(p, "503 Server error", req);
22085
22086 append_history(p, "LockFail", "Owner lock failed, transaction failed.");
22087 sip_pvt_unlock(p);
22088 ao2_t_ref(p, -1, "release p (from find_call) at end of lockretry");
22089 ast_mutex_unlock(&netlock);
22090 return 1;
22091 }
22092
22093
22094
22095
22096 if (!AST_LIST_EMPTY(&p->request_queue)) {
22097 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"));
22098 process_request_queue(p, &recount, &nounlock);
22099 }
22100
22101 if (handle_incoming(p, req, sin, &recount, &nounlock) == -1) {
22102
22103 ast_debug(1, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
22104 }
22105
22106 if (recount)
22107 ast_update_use_count();
22108
22109 if (p->owner && !nounlock)
22110 ast_channel_unlock(p->owner);
22111 sip_pvt_unlock(p);
22112 ast_mutex_unlock(&netlock);
22113 ao2_t_ref(p, -1, "throw away dialog ptr from find_call at end of routine");
22114 return 1;
22115 }
22116
22117
22118
22119
22120
22121
22122
22123 static int sip_standard_port(enum sip_transport type, int port)
22124 {
22125 if (type & SIP_TRANSPORT_TLS)
22126 return port == STANDARD_TLS_PORT;
22127 else
22128 return port == STANDARD_SIP_PORT;
22129 }
22130
22131 static int threadinfo_locate_cb(void *obj, void *arg, int flags)
22132 {
22133 struct sip_threadinfo *th = obj;
22134 struct sockaddr_in *s = arg;
22135
22136 if (!inaddrcmp(&th->tcptls_session->remote_address, s)) {
22137 return CMP_MATCH | CMP_STOP;
22138 }
22139
22140 return 0;
22141 }
22142
22143
22144
22145
22146
22147
22148 static struct ast_tcptls_session_instance *sip_tcp_locate(struct sockaddr_in *s)
22149 {
22150 struct sip_threadinfo *th;
22151 struct ast_tcptls_session_instance *tcptls_instance = NULL;
22152
22153 if ((th = ao2_callback(threadt, 0, threadinfo_locate_cb, s))) {
22154 tcptls_instance = (ao2_ref(th->tcptls_session, +1), th->tcptls_session);
22155 ao2_t_ref(th, -1, "decrement ref from callback");
22156 }
22157 return tcptls_instance;
22158 }
22159
22160
22161 static int sip_prepare_socket(struct sip_pvt *p)
22162 {
22163 struct sip_socket *s = &p->socket;
22164 static const char name[] = "SIP socket";
22165 struct sip_threadinfo *th = NULL;
22166 struct ast_tcptls_session_instance *tcptls_session;
22167 struct ast_tcptls_session_args tmp_ca = {
22168 .name = name,
22169 .accept_fd = -1,
22170 };
22171 struct ast_tcptls_session_args *ca;
22172
22173
22174 if ((s->fd != -1) && (s->type == SIP_TRANSPORT_UDP)) {
22175 return s->fd;
22176 }
22177 if ((s->type & (SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS)) &&
22178 (s->tcptls_session) &&
22179 (s->tcptls_session->fd != -1)) {
22180 return s->tcptls_session->fd;
22181 }
22182
22183
22184
22185
22186 if (p->outboundproxy && p->outboundproxy->transport) {
22187 s->type = p->outboundproxy->transport;
22188 }
22189
22190 if (s->type == SIP_TRANSPORT_UDP) {
22191 s->fd = sipsock;
22192 return s->fd;
22193 }
22194
22195
22196
22197
22198
22199
22200
22201
22202
22203
22204
22205 tmp_ca.remote_address = *(sip_real_dst(p));
22206 if ((tcptls_session = sip_tcp_locate(&tmp_ca.remote_address))) {
22207 s->fd = tcptls_session->fd;
22208 if (s->tcptls_session) {
22209 ao2_ref(s->tcptls_session, -1);
22210 s->tcptls_session = NULL;
22211 }
22212 s->tcptls_session = tcptls_session;
22213 return s->fd;
22214
22215 } else if (s->tcptls_session) {
22216 return s->fd;
22217 }
22218
22219
22220
22221 if (!(ca = ao2_alloc(sizeof(*ca), sip_tcptls_client_args_destructor)) ||
22222 !(ca->name = ast_strdup(name))) {
22223 goto create_tcptls_session_fail;
22224 }
22225 ca->accept_fd = -1;
22226 ca->remote_address = *(sip_real_dst(p));
22227
22228 if (s->type == SIP_TRANSPORT_TLS) {
22229 if (!(ca->tls_cfg = ast_calloc(1, sizeof(*ca->tls_cfg)))) {
22230 goto create_tcptls_session_fail;
22231 }
22232 memcpy(ca->tls_cfg, &default_tls_cfg, sizeof(*ca->tls_cfg));
22233
22234 if (!(ca->tls_cfg->certfile = ast_strdup(default_tls_cfg.certfile)) ||
22235 !(ca->tls_cfg->cipher = ast_strdup(default_tls_cfg.cipher)) ||
22236 !(ca->tls_cfg->cafile = ast_strdup(default_tls_cfg.cafile)) ||
22237 !(ca->tls_cfg->capath = ast_strdup(default_tls_cfg.capath))) {
22238
22239 goto create_tcptls_session_fail;
22240 }
22241
22242
22243 if (!ast_strlen_zero(p->tohost)) {
22244 ast_copy_string(ca->hostname, p->tohost, sizeof(ca->hostname));
22245 }
22246 }
22247
22248 if (!(s->tcptls_session = ast_tcptls_client_create(ca))) {
22249 goto create_tcptls_session_fail;
22250 }
22251
22252 s->fd = s->tcptls_session->fd;
22253
22254
22255
22256
22257
22258 if (!(th = sip_threadinfo_create(s->tcptls_session, s->type))) {
22259 goto create_tcptls_session_fail;
22260
22261 }
22262
22263
22264 ao2_ref(s->tcptls_session, +1);
22265
22266 if (ast_pthread_create_background(&ca->master, NULL, sip_tcp_worker_fn, s->tcptls_session)) {
22267 ast_debug(1, "Unable to launch '%s'.", ca->name);
22268 ao2_ref(s->tcptls_session, -1);
22269 goto create_tcptls_session_fail;
22270 }
22271
22272 return s->fd;
22273
22274 create_tcptls_session_fail:
22275 if (ca) {
22276 ao2_t_ref(ca, -1, "failed to create client, getting rid of client tcptls_session arguments");
22277 }
22278 if (s->tcptls_session) {
22279 close(tcptls_session->fd);
22280 s->fd = tcptls_session->fd = -1;
22281 ao2_ref(s->tcptls_session, -1);
22282 s->tcptls_session = NULL;
22283 }
22284 if (th) {
22285 ao2_t_unlink(threadt, th, "Removing tcptls thread info object, thread failed to open");
22286 }
22287
22288 return -1;
22289 }
22290
22291
22292
22293
22294
22295 static int sip_parse_host(char *line, int lineno, char **hostname, int *portnum, enum sip_transport *transport)
22296 {
22297 char *port;
22298
22299 if ((*hostname = strstr(line, "://"))) {
22300 *hostname += 3;
22301
22302 if (!strncasecmp(line, "tcp", 3))
22303 *transport = SIP_TRANSPORT_TCP;
22304 else if (!strncasecmp(line, "tls", 3))
22305 *transport = SIP_TRANSPORT_TLS;
22306 else if (!strncasecmp(line, "udp", 3))
22307 *transport = SIP_TRANSPORT_UDP;
22308 else
22309 ast_log(LOG_NOTICE, "'%.3s' is not a valid transport type on line %d of sip.conf. defaulting to udp.\n", line, lineno);
22310 } else {
22311 *hostname = line;
22312 *transport = SIP_TRANSPORT_UDP;
22313 }
22314
22315 if ((line = strrchr(*hostname, '@')))
22316 line++;
22317 else
22318 line = *hostname;
22319
22320 if ((port = strrchr(line, ':'))) {
22321 *port++ = '\0';
22322
22323 if (!sscanf(port, "%5u", portnum)) {
22324 ast_log(LOG_NOTICE, "'%s' is not a valid port number on line %d of sip.conf. using default.\n", port, lineno);
22325 port = NULL;
22326 }
22327 }
22328
22329 if (!port) {
22330 if (*transport & SIP_TRANSPORT_TLS) {
22331 *portnum = STANDARD_TLS_PORT;
22332 } else {
22333 *portnum = STANDARD_SIP_PORT;
22334 }
22335 }
22336
22337 return 0;
22338 }
22339
22340
22341
22342
22343
22344
22345 static int get_cached_mwi(struct sip_peer *peer, int *new, int *old)
22346 {
22347 struct sip_mailbox *mailbox;
22348
22349 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
22350 struct ast_event *event;
22351 event = ast_event_get_cached(AST_EVENT_MWI,
22352 AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox->mailbox,
22353 AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, S_OR(mailbox->context, "default"),
22354 AST_EVENT_IE_END);
22355 if (!event)
22356 continue;
22357 *new += ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
22358 *old += ast_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS);
22359 ast_event_destroy(event);
22360 }
22361
22362 return (*new || *old) ? 0 : 1;
22363 }
22364
22365
22366 static int sip_send_mwi_to_peer(struct sip_peer *peer, const struct ast_event *event, int cache_only)
22367 {
22368
22369 struct sip_pvt *p;
22370 int newmsgs = 0, oldmsgs = 0;
22371
22372 if (ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY) && !peer->mwipvt)
22373 return 0;
22374
22375
22376 if (!peer->addr.sin_addr.s_addr && !peer->defaddr.sin_addr.s_addr)
22377 return 0;
22378
22379 if (event) {
22380 newmsgs = ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
22381 oldmsgs = ast_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS);
22382 } else if (!get_cached_mwi(peer, &newmsgs, &oldmsgs)) {
22383
22384 } else if (cache_only) {
22385 return 0;
22386 } else {
22387 struct ast_str *mailbox_str = ast_str_alloca(512);
22388 peer_mailboxes_to_str(&mailbox_str, peer);
22389 ast_app_inboxcount(mailbox_str->str, &newmsgs, &oldmsgs);
22390 }
22391
22392 if (peer->mwipvt) {
22393
22394 p = dialog_ref(peer->mwipvt, "sip_send_mwi_to_peer: Setting dialog ptr p from peer->mwipvt-- should this be done?");
22395 } else {
22396
22397 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL)))
22398 return -1;
22399
22400
22401
22402
22403 set_socket_transport(&p->socket, 0);
22404 if (create_addr_from_peer(p, peer)) {
22405
22406 dialog_unlink_all(p, TRUE, TRUE);
22407 dialog_unref(p, "unref dialog p just created via sip_alloc");
22408
22409 return 0;
22410 }
22411
22412 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
22413 build_via(p);
22414 ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
22415 build_callid_pvt(p);
22416 ao2_t_link(dialogs, p, "Linking in under new name");
22417
22418 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22419 }
22420
22421
22422 ast_set_flag(&p->flags[0], SIP_OUTGOING);
22423
22424 transmit_notify_with_mwi(p, newmsgs, oldmsgs, peer->vmexten);
22425 dialog_unref(p, "unref dialog ptr p just before it goes out of scope at the end of sip_send_mwi_to_peer.");
22426 return 0;
22427 }
22428
22429
22430 static void check_rtp_timeout(struct sip_pvt *dialog, time_t t)
22431 {
22432
22433 if (!dialog->rtp || !dialog->owner)
22434 return;
22435
22436
22437 if (dialog->owner->_state != AST_STATE_UP || dialog->redirip.sin_addr.s_addr)
22438 return;
22439
22440
22441 if (dialog->t38.state == T38_ENABLED)
22442 return;
22443
22444
22445 if ((ast_rtp_get_rtpkeepalive(dialog->rtp) == 0) && (ast_rtp_get_rtptimeout(dialog->rtp) == 0) && (ast_rtp_get_rtpholdtimeout(dialog->rtp) == 0))
22446 return;
22447
22448
22449 if (dialog->lastrtptx && ast_rtp_get_rtpkeepalive(dialog->rtp) &&
22450 (t > dialog->lastrtptx + ast_rtp_get_rtpkeepalive(dialog->rtp))) {
22451
22452 dialog->lastrtptx = time(NULL);
22453 ast_rtp_sendcng(dialog->rtp, 0);
22454 }
22455
22456
22457
22458
22459
22460
22461
22462
22463 if (dialog->lastrtprx && (ast_rtp_get_rtptimeout(dialog->rtp) || ast_rtp_get_rtpholdtimeout(dialog->rtp)) &&
22464 (t > dialog->lastrtprx + ast_rtp_get_rtptimeout(dialog->rtp))) {
22465
22466
22467 struct sockaddr_in sin;
22468 ast_rtp_get_peer(dialog->rtp, &sin);
22469 if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD) || (ast_rtp_get_rtpholdtimeout(dialog->rtp) &&
22470 (t > dialog->lastrtprx + ast_rtp_get_rtpholdtimeout(dialog->rtp)))) {
22471
22472 if (ast_rtp_get_rtptimeout(dialog->rtp)) {
22473 while (dialog->owner && ast_channel_trylock(dialog->owner)) {
22474 sip_pvt_unlock(dialog);
22475 usleep(1);
22476 sip_pvt_lock(dialog);
22477 }
22478 ast_log(LOG_NOTICE, "Disconnecting call '%s' for lack of RTP activity in %ld seconds\n",
22479 dialog->owner->name, (long) (t - dialog->lastrtprx));
22480
22481 ast_softhangup_nolock(dialog->owner, AST_SOFTHANGUP_DEV);
22482 ast_channel_unlock(dialog->owner);
22483
22484
22485
22486
22487 ast_rtp_set_rtptimeout(dialog->rtp, 0);
22488 ast_rtp_set_rtpholdtimeout(dialog->rtp, 0);
22489 if (dialog->vrtp) {
22490 ast_rtp_set_rtptimeout(dialog->vrtp, 0);
22491 ast_rtp_set_rtpholdtimeout(dialog->vrtp, 0);
22492 }
22493 }
22494 }
22495 }
22496 }
22497
22498
22499
22500
22501
22502 static void *do_monitor(void *data)
22503 {
22504 int res;
22505 time_t t;
22506 int reloading;
22507
22508
22509 if (sipsock > -1)
22510 sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
22511
22512
22513 for(;;) {
22514
22515 ast_mutex_lock(&sip_reload_lock);
22516 reloading = sip_reloading;
22517 sip_reloading = FALSE;
22518 ast_mutex_unlock(&sip_reload_lock);
22519 if (reloading) {
22520 ast_verb(1, "Reloading SIP\n");
22521 sip_do_reload(sip_reloadreason);
22522
22523
22524 if (sipsock > -1) {
22525 if (sipsock_read_id)
22526 sipsock_read_id = ast_io_change(io, sipsock_read_id, sipsock, NULL, 0, NULL);
22527 else
22528 sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
22529 } else if (sipsock_read_id) {
22530 ast_io_remove(io, sipsock_read_id);
22531 sipsock_read_id = NULL;
22532 }
22533 }
22534
22535
22536 t = time(NULL);
22537
22538
22539
22540
22541 ao2_t_callback(dialogs, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, dialog_needdestroy, &t,
22542 "callback to remove dialogs w/needdestroy");
22543
22544
22545
22546
22547
22548
22549
22550
22551
22552
22553
22554 pthread_testcancel();
22555
22556 res = ast_sched_wait(sched);
22557 if ((res < 0) || (res > 1000))
22558 res = 1000;
22559 res = ast_io_wait(io, res);
22560 if (res > 20)
22561 ast_debug(1, "chan_sip: ast_io_wait ran %d all at once\n", res);
22562 ast_mutex_lock(&monlock);
22563 res = ast_sched_runq(sched);
22564 if (res >= 20)
22565 ast_debug(1, "chan_sip: ast_sched_runq ran %d all at once\n", res);
22566 ast_mutex_unlock(&monlock);
22567 }
22568
22569
22570 return NULL;
22571 }
22572
22573
22574 static int restart_monitor(void)
22575 {
22576
22577 if (monitor_thread == AST_PTHREADT_STOP)
22578 return 0;
22579 ast_mutex_lock(&monlock);
22580 if (monitor_thread == pthread_self()) {
22581 ast_mutex_unlock(&monlock);
22582 ast_log(LOG_WARNING, "Cannot kill myself\n");
22583 return -1;
22584 }
22585 if (monitor_thread != AST_PTHREADT_NULL) {
22586
22587 pthread_kill(monitor_thread, SIGURG);
22588 } else {
22589
22590 if (ast_pthread_create_background(&monitor_thread, NULL, do_monitor, NULL) < 0) {
22591 ast_mutex_unlock(&monlock);
22592 ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
22593 return -1;
22594 }
22595 }
22596 ast_mutex_unlock(&monlock);
22597 return 0;
22598 }
22599
22600
22601
22602 static void restart_session_timer(struct sip_pvt *p)
22603 {
22604 if (!p->stimer) {
22605 ast_log(LOG_WARNING, "Null stimer in restart_session_timer - %s\n", p->callid);
22606 return;
22607 }
22608
22609 if (p->stimer->st_active == TRUE) {
22610 AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
22611 dialog_unref(p, "Removing session timer ref"));
22612 ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
22613 start_session_timer(p);
22614 }
22615 }
22616
22617
22618
22619 static void stop_session_timer(struct sip_pvt *p)
22620 {
22621 if (!p->stimer) {
22622 ast_log(LOG_WARNING, "Null stimer in stop_session_timer - %s\n", p->callid);
22623 return;
22624 }
22625
22626 if (p->stimer->st_active == TRUE) {
22627 p->stimer->st_active = FALSE;
22628 AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
22629 dialog_unref(p, "removing session timer ref"));
22630 ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
22631 }
22632 }
22633
22634
22635
22636 static void start_session_timer(struct sip_pvt *p)
22637 {
22638 if (!p->stimer) {
22639 ast_log(LOG_WARNING, "Null stimer in start_session_timer - %s\n", p->callid);
22640 return;
22641 }
22642
22643 p->stimer->st_schedid = ast_sched_add(sched, p->stimer->st_interval * 1000 / 2, proc_session_timer,
22644 dialog_ref(p, "adding session timer ref"));
22645 if (p->stimer->st_schedid < 0) {
22646 dialog_unref(p, "removing session timer ref");
22647 ast_log(LOG_ERROR, "ast_sched_add failed.\n");
22648 }
22649 ast_debug(2, "Session timer started: %d - %s\n", p->stimer->st_schedid, p->callid);
22650 }
22651
22652
22653
22654 static int proc_session_timer(const void *vp)
22655 {
22656 struct sip_pvt *p = (struct sip_pvt *) vp;
22657 int sendreinv = FALSE;
22658 int res = 0;
22659
22660 if (!p->stimer) {
22661 ast_log(LOG_WARNING, "Null stimer in proc_session_timer - %s\n", p->callid);
22662 goto return_unref;
22663 }
22664
22665 ast_debug(2, "Session timer expired: %d - %s\n", p->stimer->st_schedid, p->callid);
22666
22667 if (!p->owner) {
22668 goto return_unref;
22669 }
22670
22671 if ((p->stimer->st_active != TRUE) || (p->owner->_state != AST_STATE_UP)) {
22672 goto return_unref;
22673 }
22674
22675 switch (p->stimer->st_ref) {
22676 case SESSION_TIMER_REFRESHER_UAC:
22677 if (p->outgoing_call == TRUE) {
22678 sendreinv = TRUE;
22679 }
22680 break;
22681 case SESSION_TIMER_REFRESHER_UAS:
22682 if (p->outgoing_call != TRUE) {
22683 sendreinv = TRUE;
22684 }
22685 break;
22686 default:
22687 ast_log(LOG_ERROR, "Unknown session refresher %d\n", p->stimer->st_ref);
22688 goto return_unref;
22689 }
22690
22691 if (sendreinv == TRUE) {
22692 res = 1;
22693 transmit_reinvite_with_sdp(p, FALSE, TRUE);
22694 } else {
22695 p->stimer->st_expirys++;
22696 if (p->stimer->st_expirys >= 2) {
22697 if (p->stimer->quit_flag) {
22698 goto return_unref;
22699 }
22700 ast_log(LOG_WARNING, "Session-Timer expired - %s\n", p->callid);
22701 sip_pvt_lock(p);
22702 while (p->owner && ast_channel_trylock(p->owner)) {
22703 sip_pvt_unlock(p);
22704 usleep(1);
22705 if (p->stimer && p->stimer->quit_flag) {
22706 goto return_unref;
22707 }
22708 sip_pvt_lock(p);
22709 }
22710
22711 ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
22712 ast_channel_unlock(p->owner);
22713 sip_pvt_unlock(p);
22714 }
22715 }
22716
22717 return_unref:
22718 if (!res) {
22719
22720 if (p->stimer) {
22721 p->stimer->st_schedid = -1;
22722 stop_session_timer(p);
22723 }
22724
22725
22726
22727 dialog_unref(p, "removing session timer ref");
22728 }
22729
22730 return res;
22731 }
22732
22733
22734
22735 int parse_minse (const char *p_hdrval, int *const p_interval)
22736 {
22737 if (ast_strlen_zero(p_hdrval)) {
22738 ast_log(LOG_WARNING, "Null Min-SE header\n");
22739 return -1;
22740 }
22741
22742 *p_interval = 0;
22743 p_hdrval = ast_skip_blanks(p_hdrval);
22744 if (!sscanf(p_hdrval, "%30d", p_interval)) {
22745 ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
22746 return -1;
22747 }
22748
22749 ast_debug(2, "Received Min-SE: %d\n", *p_interval);
22750 return 0;
22751 }
22752
22753
22754
22755 int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref)
22756 {
22757 char *p_token;
22758 int ref_idx;
22759 char *p_se_hdr;
22760
22761 if (ast_strlen_zero(p_hdrval)) {
22762 ast_log(LOG_WARNING, "Null Session-Expires header\n");
22763 return -1;
22764 }
22765
22766 *p_ref = SESSION_TIMER_REFRESHER_AUTO;
22767 *p_interval = 0;
22768
22769 p_se_hdr = ast_strdupa(p_hdrval);
22770 p_se_hdr = ast_skip_blanks(p_se_hdr);
22771
22772 while ((p_token = strsep(&p_se_hdr, ";"))) {
22773 p_token = ast_skip_blanks(p_token);
22774 if (!sscanf(p_token, "%30d", p_interval)) {
22775 ast_log(LOG_WARNING, "Parsing of Session-Expires failed\n");
22776 return -1;
22777 }
22778
22779 ast_debug(2, "Session-Expires: %d\n", *p_interval);
22780
22781 if (!p_se_hdr)
22782 continue;
22783
22784 p_se_hdr = ast_skip_blanks(p_se_hdr);
22785 ref_idx = strlen("refresher=");
22786 if (!strncasecmp(p_se_hdr, "refresher=", ref_idx)) {
22787 p_se_hdr += ref_idx;
22788 p_se_hdr = ast_skip_blanks(p_se_hdr);
22789
22790 if (!strncasecmp(p_se_hdr, "uac", strlen("uac"))) {
22791 *p_ref = SESSION_TIMER_REFRESHER_UAC;
22792 ast_debug(2, "Refresher: UAC\n");
22793 } else if (!strncasecmp(p_se_hdr, "uas", strlen("uas"))) {
22794 *p_ref = SESSION_TIMER_REFRESHER_UAS;
22795 ast_debug(2, "Refresher: UAS\n");
22796 } else {
22797 ast_log(LOG_WARNING, "Invalid refresher value %s\n", p_se_hdr);
22798 return -1;
22799 }
22800 break;
22801 }
22802 }
22803 return 0;
22804 }
22805
22806
22807
22808
22809
22810
22811
22812
22813
22814 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp)
22815 {
22816 int rtn;
22817 const char *p_hdrval;
22818 int minse;
22819
22820 p_hdrval = get_header(rsp, "Min-SE");
22821 if (ast_strlen_zero(p_hdrval)) {
22822 ast_log(LOG_WARNING, "422 response without a Min-SE header %s\n", p_hdrval);
22823 return;
22824 }
22825 rtn = parse_minse(p_hdrval, &minse);
22826 if (rtn != 0) {
22827 ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
22828 return;
22829 }
22830 p->stimer->st_interval = minse;
22831 transmit_invite(p, SIP_INVITE, 1, 2);
22832 }
22833
22834
22835
22836
22837
22838
22839 int st_get_se(struct sip_pvt *p, int max)
22840 {
22841 if (max == TRUE) {
22842 if (p->stimer->st_cached_max_se) {
22843 return p->stimer->st_cached_max_se;
22844 } else if (p->peername) {
22845 struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE, 0);
22846 if (pp) {
22847 p->stimer->st_cached_max_se = pp->stimer.st_max_se;
22848 unref_peer(pp, "unref peer pointer from find_peer call in st_get_se");
22849 return (p->stimer->st_cached_max_se);
22850 }
22851 }
22852 p->stimer->st_cached_max_se = global_max_se;
22853 return (p->stimer->st_cached_max_se);
22854 } else {
22855 if (p->stimer->st_cached_min_se) {
22856 return p->stimer->st_cached_min_se;
22857 } else if (p->peername) {
22858 struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE, 0);
22859 if (pp) {
22860 p->stimer->st_cached_min_se = pp->stimer.st_min_se;
22861 unref_peer(pp, "unref peer pointer from find_peer call in st_get_se (2)");
22862 return (p->stimer->st_cached_min_se);
22863 }
22864 }
22865 p->stimer->st_cached_min_se = global_min_se;
22866 return (p->stimer->st_cached_min_se);
22867 }
22868 }
22869
22870
22871
22872
22873
22874 enum st_refresher st_get_refresher(struct sip_pvt *p)
22875 {
22876 if (p->stimer->st_cached_ref != SESSION_TIMER_REFRESHER_AUTO)
22877 return p->stimer->st_cached_ref;
22878
22879 if (p->peername) {
22880 struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE, 0);
22881 if (pp) {
22882 p->stimer->st_cached_ref = pp->stimer.st_ref;
22883 unref_peer(pp, "unref peer pointer from find_peer call in st_get_refresher");
22884 return pp->stimer.st_ref;
22885 }
22886 }
22887
22888 p->stimer->st_cached_ref = global_st_refresher;
22889 return global_st_refresher;
22890 }
22891
22892
22893
22894
22895
22896 enum st_mode st_get_mode(struct sip_pvt *p)
22897 {
22898 if (!p->stimer)
22899 sip_st_alloc(p);
22900
22901 if (p->stimer->st_cached_mode != SESSION_TIMER_MODE_INVALID)
22902 return p->stimer->st_cached_mode;
22903
22904 if (p->peername) {
22905 struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE, 0);
22906 if (pp) {
22907 p->stimer->st_cached_mode = pp->stimer.st_mode_oper;
22908 unref_peer(pp, "unref peer pointer from find_peer call in st_get_mode");
22909 return pp->stimer.st_mode_oper;
22910 }
22911 }
22912
22913 p->stimer->st_cached_mode = global_st_mode;
22914 return global_st_mode;
22915 }
22916
22917
22918
22919 static int sip_poke_noanswer(const void *data)
22920 {
22921 struct sip_peer *peer = (struct sip_peer *)data;
22922
22923 peer->pokeexpire = -1;
22924
22925 if (peer->lastms > -1) {
22926 ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE! Last qualify: %d\n", peer->name, peer->lastms);
22927 if (sip_cfg.peer_rtupdate) {
22928 ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", "-1", SENTINEL);
22929 }
22930 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer->name, -1);
22931 if (sip_cfg.regextenonqualify) {
22932 register_peer_exten(peer, FALSE);
22933 }
22934 }
22935
22936 if (peer->call) {
22937 dialog_unlink_all(peer->call, TRUE, TRUE);
22938 peer->call = dialog_unref(peer->call, "unref dialog peer->call");
22939
22940 }
22941
22942 peer->lastms = -1;
22943 ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
22944
22945
22946 AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
22947 DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer,
22948 unref_peer(_data, "removing poke peer ref"),
22949 unref_peer(peer, "removing poke peer ref"),
22950 ref_peer(peer, "adding poke peer ref"));
22951
22952
22953 unref_peer(peer, "release peer poke noanswer ref");
22954
22955 return 0;
22956 }
22957
22958
22959
22960
22961
22962
22963 static int sip_poke_peer(struct sip_peer *peer, int force)
22964 {
22965 struct sip_pvt *p;
22966 int xmitres = 0;
22967
22968 if ((!peer->maxms && !force) || !peer->addr.sin_addr.s_addr) {
22969
22970
22971 AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
22972 unref_peer(peer, "removing poke peer ref"));
22973
22974 peer->lastms = 0;
22975 if (peer->call) {
22976 peer->call = dialog_unref(peer->call, "unref dialog peer->call");
22977 }
22978 return 0;
22979 }
22980 if (peer->call) {
22981 if (sipdebug) {
22982 ast_log(LOG_NOTICE, "Still have a QUALIFY dialog active, deleting\n");
22983 }
22984 dialog_unlink_all(peer->call, TRUE, TRUE);
22985 peer->call = dialog_unref(peer->call, "unref dialog peer->call");
22986
22987 }
22988 if (!(p = sip_alloc(NULL, NULL, 0, SIP_OPTIONS, NULL))) {
22989 return -1;
22990 }
22991 peer->call = dialog_ref(p, "copy sip alloc from p to peer->call");
22992
22993 p->sa = peer->addr;
22994 p->recv = peer->addr;
22995 copy_socket_data(&p->socket, &peer->socket);
22996 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
22997 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
22998
22999
23000 if (!ast_strlen_zero(peer->fullcontact))
23001 ast_string_field_set(p, fullcontact, peer->fullcontact);
23002
23003 if (!ast_strlen_zero(peer->tohost))
23004 ast_string_field_set(p, tohost, peer->tohost);
23005 else
23006 ast_string_field_set(p, tohost, ast_inet_ntoa(peer->addr.sin_addr));
23007
23008
23009 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
23010 build_via(p);
23011 ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
23012 build_callid_pvt(p);
23013 ao2_t_link(dialogs, p, "Linking in under new name");
23014
23015 AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
23016 unref_peer(peer, "removing poke peer ref"));
23017
23018 if (p->relatedpeer)
23019 p->relatedpeer = unref_peer(p->relatedpeer,"unsetting the relatedpeer field in the dialog, before it is set to something else.");
23020 p->relatedpeer = ref_peer(peer, "setting the relatedpeer field in the dialog");
23021 ast_set_flag(&p->flags[0], SIP_OUTGOING);
23022 #ifdef VOCAL_DATA_HACK
23023 ast_copy_string(p->username, "__VOCAL_DATA_SHOULD_READ_THE_SIP_SPEC__", sizeof(p->username));
23024 xmitres = transmit_invite(p, SIP_INVITE, 0, 2);
23025 #else
23026 xmitres = transmit_invite(p, SIP_OPTIONS, 0, 2);
23027 #endif
23028 peer->ps = ast_tvnow();
23029 if (xmitres == XMIT_ERROR) {
23030 sip_poke_noanswer(peer);
23031 } else if (!force) {
23032 AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, peer->maxms * 2, sip_poke_noanswer, peer,
23033 unref_peer(_data, "removing poke peer ref"),
23034 unref_peer(peer, "removing poke peer ref"),
23035 ref_peer(peer, "adding poke peer ref"));
23036 }
23037 dialog_unref(p, "unref dialog at end of sip_poke_peer, obtained from sip_alloc, just before it goes out of scope");
23038 return 0;
23039 }
23040
23041
23042
23043
23044
23045
23046
23047
23048
23049
23050
23051
23052
23053
23054
23055
23056
23057
23058
23059
23060
23061
23062
23063
23064
23065
23066
23067
23068
23069
23070
23071
23072
23073
23074 static int sip_devicestate(void *data)
23075 {
23076 char *host;
23077 char *tmp;
23078 struct sip_peer *p;
23079
23080 int res = AST_DEVICE_INVALID;
23081
23082
23083 host = ast_strdupa(data ? data : "");
23084 if ((tmp = strchr(host, '@')))
23085 host = tmp + 1;
23086
23087 ast_debug(3, "Checking device state for peer %s\n", host);
23088
23089
23090
23091
23092
23093
23094
23095
23096 if ((p = find_peer(host, NULL, FALSE, FINDALLDEVICES, TRUE, 0))) {
23097 if (p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) {
23098
23099
23100
23101
23102
23103
23104
23105
23106
23107
23108
23109 if (p->onHold)
23110
23111 res = AST_DEVICE_ONHOLD;
23112 else if (p->inRinging) {
23113 if (p->inRinging == p->inUse)
23114 res = AST_DEVICE_RINGING;
23115 else
23116 res = AST_DEVICE_RINGINUSE;
23117 } else if (p->call_limit && (p->inUse == p->call_limit))
23118
23119 res = AST_DEVICE_BUSY;
23120 else if (p->call_limit && p->busy_level && p->inUse >= p->busy_level)
23121
23122 res = AST_DEVICE_BUSY;
23123 else if (p->call_limit && p->inUse)
23124
23125 res = AST_DEVICE_INUSE;
23126 else if (p->maxms && ((p->lastms > p->maxms) || (p->lastms < 0)))
23127
23128 res = AST_DEVICE_UNAVAILABLE;
23129 else
23130 res = AST_DEVICE_NOT_INUSE;
23131 } else {
23132
23133 res = AST_DEVICE_UNAVAILABLE;
23134 }
23135 unref_peer(p, "unref_peer, from sip_devicestate, release ref from find_peer");
23136 } else {
23137 res = AST_DEVICE_UNKNOWN;
23138 }
23139
23140 return res;
23141 }
23142
23143
23144
23145
23146
23147
23148
23149
23150
23151
23152
23153 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause)
23154 {
23155 struct sip_pvt *p;
23156 struct ast_channel *tmpc = NULL;
23157 char *ext = NULL, *host;
23158 char tmp[256];
23159 char *dest = data;
23160 char *dnid;
23161 char *secret = NULL;
23162 char *md5secret = NULL;
23163 char *authname = NULL;
23164 char *trans = NULL;
23165 enum sip_transport transport = 0;
23166 int oldformat = format;
23167
23168
23169
23170
23171
23172
23173
23174
23175 format &= AST_FORMAT_AUDIO_MASK;
23176 if (!format) {
23177 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));
23178 *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
23179 return NULL;
23180 }
23181 ast_debug(1, "Asked to create a SIP channel with formats: %s\n", ast_getformatname_multiple(tmp, sizeof(tmp), oldformat));
23182
23183 if (!(p = sip_alloc(NULL, NULL, 0, SIP_INVITE, NULL))) {
23184 ast_log(LOG_ERROR, "Unable to build sip pvt data for '%s' (Out of memory or socket error)\n", dest);
23185 *cause = AST_CAUSE_SWITCH_CONGESTION;
23186 return NULL;
23187 }
23188
23189 p->outgoing_call = TRUE;
23190
23191 if (!(p->options = ast_calloc(1, sizeof(*p->options)))) {
23192 dialog_unlink_all(p, TRUE, TRUE);
23193 dialog_unref(p, "unref dialog p from mem fail");
23194
23195 ast_log(LOG_ERROR, "Unable to build option SIP data structure - Out of memory\n");
23196 *cause = AST_CAUSE_SWITCH_CONGESTION;
23197 return NULL;
23198 }
23199
23200
23201 ast_copy_string(tmp, dest, sizeof(tmp));
23202
23203
23204
23205 dnid = strchr(tmp, '!');
23206 if (dnid != NULL) {
23207 *dnid++ = '\0';
23208 ast_string_field_set(p, todnid, dnid);
23209 }
23210
23211
23212 host = strchr(tmp, '@');
23213 if (host) {
23214 *host++ = '\0';
23215 ext = tmp;
23216 secret = strchr(ext, ':');
23217 }
23218 if (secret) {
23219 *secret++ = '\0';
23220 md5secret = strchr(secret, ':');
23221 }
23222 if (md5secret) {
23223 *md5secret++ = '\0';
23224 authname = strchr(md5secret, ':');
23225 }
23226 if (authname) {
23227 *authname++ = '\0';
23228 trans = strchr(authname, ':');
23229 }
23230 if (trans) {
23231 *trans++ = '\0';
23232 if (!strcasecmp(trans, "tcp"))
23233 transport = SIP_TRANSPORT_TCP;
23234 else if (!strcasecmp(trans, "tls"))
23235 transport = SIP_TRANSPORT_TLS;
23236 else {
23237 if (strcasecmp(trans, "udp"))
23238 ast_log(LOG_WARNING, "'%s' is not a valid transport option to Dial() for SIP calls, using udp by default.\n", trans);
23239 transport = SIP_TRANSPORT_UDP;
23240 }
23241 } else {
23242 transport = SIP_TRANSPORT_UDP;
23243 }
23244
23245 if (!host) {
23246 ext = strchr(tmp, '/');
23247 if (ext)
23248 *ext++ = '\0';
23249 host = tmp;
23250 }
23251
23252 set_socket_transport(&p->socket, transport);
23253
23254
23255
23256
23257
23258
23259 if (create_addr(p, host, NULL, 1)) {
23260 *cause = AST_CAUSE_UNREGISTERED;
23261 ast_debug(3, "Cant create SIP call - target device not registered\n");
23262 dialog_unlink_all(p, TRUE, TRUE);
23263 dialog_unref(p, "unref dialog p UNREGISTERED");
23264
23265 return NULL;
23266 }
23267 if (ast_strlen_zero(p->peername) && ext)
23268 ast_string_field_set(p, peername, ext);
23269
23270 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
23271 build_via(p);
23272 ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
23273 build_callid_pvt(p);
23274 ao2_t_link(dialogs, p, "Linking in under new name");
23275
23276
23277
23278
23279
23280
23281 if (ext) {
23282 ast_string_field_set(p, username, ext);
23283 ast_string_field_set(p, fullcontact, NULL);
23284 }
23285 if (secret && !ast_strlen_zero(secret))
23286 ast_string_field_set(p, peersecret, secret);
23287
23288 if (md5secret && !ast_strlen_zero(md5secret))
23289 ast_string_field_set(p, peermd5secret, md5secret);
23290
23291 if (authname && !ast_strlen_zero(authname))
23292 ast_string_field_set(p, authname, authname);
23293 #if 0
23294 printf("Setting up to call extension '%s' at '%s'\n", ext ? ext : "<none>", host);
23295 #endif
23296 p->prefcodec = oldformat;
23297 p->jointcapability = oldformat;
23298 sip_pvt_lock(p);
23299 tmpc = sip_new(p, AST_STATE_DOWN, host);
23300 if (sip_cfg.callevents)
23301 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
23302 "Channel: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
23303 p->owner? p->owner->name : "", "SIP", p->callid, p->fullcontact, p->peername);
23304 sip_pvt_unlock(p);
23305 if (!tmpc) {
23306 dialog_unlink_all(p, TRUE, TRUE);
23307
23308 }
23309 dialog_unref(p, "toss pvt ptr at end of sip_request_call");
23310 ast_update_use_count();
23311 restart_monitor();
23312 return tmpc;
23313 }
23314
23315
23316 static void set_insecure_flags (struct ast_flags *flags, const char *value, int lineno)
23317 {
23318 if (ast_strlen_zero(value))
23319 return;
23320
23321 if (!ast_false(value)) {
23322 char buf[64];
23323 char *word, *next;
23324
23325 ast_copy_string(buf, value, sizeof(buf));
23326 next = buf;
23327 while ((word = strsep(&next, ","))) {
23328 if (!strcasecmp(word, "port"))
23329 ast_set_flag(&flags[0], SIP_INSECURE_PORT);
23330 else if (!strcasecmp(word, "invite"))
23331 ast_set_flag(&flags[0], SIP_INSECURE_INVITE);
23332 else
23333 ast_log(LOG_WARNING, "Unknown insecure mode '%s' on line %d\n", value, lineno);
23334 }
23335 }
23336 }
23337
23338
23339
23340
23341
23342 static int handle_t38_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v,
23343 int *maxdatagram)
23344 {
23345 int res = 1;
23346
23347 if (!strcasecmp(v->name, "t38pt_udptl")) {
23348 char *buf = ast_strdupa(v->value);
23349 char *word, *next = buf;
23350
23351 ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT);
23352
23353 while ((word = strsep(&next, ","))) {
23354 if (ast_true(word) || !strcasecmp(word, "fec")) {
23355 ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
23356 ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_FEC);
23357 } else if (!strcasecmp(word, "redundancy")) {
23358 ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
23359 ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY);
23360 } else if (!strcasecmp(word, "none")) {
23361 ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
23362 ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL);
23363 } else if (!strncasecmp(word, "maxdatagram=", 12)) {
23364 if (sscanf(&word[12], "%30u", maxdatagram) != 1) {
23365 ast_log(LOG_WARNING, "Invalid maxdatagram '%s' at line %d of %s\n", v->value, v->lineno, config);
23366 *maxdatagram = global_t38_maxdatagram;
23367 }
23368 }
23369 }
23370 } else if (!strcasecmp(v->name, "t38pt_usertpsource")) {
23371 ast_set_flag(&mask[1], SIP_PAGE2_UDPTL_DESTINATION);
23372 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_UDPTL_DESTINATION);
23373 } else {
23374 res = 0;
23375 }
23376
23377 return res;
23378 }
23379
23380
23381
23382
23383
23384
23385
23386
23387 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v)
23388 {
23389 int res = 1;
23390
23391 if (!strcasecmp(v->name, "trustrpid")) {
23392 ast_set_flag(&mask[0], SIP_TRUSTRPID);
23393 ast_set2_flag(&flags[0], ast_true(v->value), SIP_TRUSTRPID);
23394 } else if (!strcasecmp(v->name, "sendrpid")) {
23395 ast_set_flag(&mask[0], SIP_SENDRPID);
23396 ast_set2_flag(&flags[0], ast_true(v->value), SIP_SENDRPID);
23397 } else if (!strcasecmp(v->name, "g726nonstandard")) {
23398 ast_set_flag(&mask[0], SIP_G726_NONSTANDARD);
23399 ast_set2_flag(&flags[0], ast_true(v->value), SIP_G726_NONSTANDARD);
23400 } else if (!strcasecmp(v->name, "useclientcode")) {
23401 ast_set_flag(&mask[0], SIP_USECLIENTCODE);
23402 ast_set2_flag(&flags[0], ast_true(v->value), SIP_USECLIENTCODE);
23403 } else if (!strcasecmp(v->name, "dtmfmode")) {
23404 ast_set_flag(&mask[0], SIP_DTMF);
23405 ast_clear_flag(&flags[0], SIP_DTMF);
23406 if (!strcasecmp(v->value, "inband"))
23407 ast_set_flag(&flags[0], SIP_DTMF_INBAND);
23408 else if (!strcasecmp(v->value, "rfc2833"))
23409 ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
23410 else if (!strcasecmp(v->value, "info"))
23411 ast_set_flag(&flags[0], SIP_DTMF_INFO);
23412 else if (!strcasecmp(v->value, "shortinfo"))
23413 ast_set_flag(&flags[0], SIP_DTMF_SHORTINFO);
23414 else if (!strcasecmp(v->value, "auto"))
23415 ast_set_flag(&flags[0], SIP_DTMF_AUTO);
23416 else {
23417 ast_log(LOG_WARNING, "Unknown dtmf mode '%s' on line %d, using rfc2833\n", v->value, v->lineno);
23418 ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
23419 }
23420 } else if (!strcasecmp(v->name, "nat")) {
23421 ast_set_flag(&mask[0], SIP_NAT);
23422 ast_clear_flag(&flags[0], SIP_NAT);
23423 if (!strcasecmp(v->value, "never"))
23424 ast_set_flag(&flags[0], SIP_NAT_NEVER);
23425 else if (!strcasecmp(v->value, "route"))
23426 ast_set_flag(&flags[0], SIP_NAT_ROUTE);
23427 else if (ast_true(v->value))
23428 ast_set_flag(&flags[0], SIP_NAT_ALWAYS);
23429 else
23430 ast_set_flag(&flags[0], SIP_NAT_RFC3581);
23431 } else if (!strcasecmp(v->name, "directmedia") || !strcasecmp(v->name, "canreinvite")) {
23432 ast_set_flag(&mask[0], SIP_REINVITE);
23433 ast_clear_flag(&flags[0], SIP_REINVITE);
23434 if (ast_true(v->value)) {
23435 ast_set_flag(&flags[0], SIP_DIRECT_MEDIA | SIP_DIRECT_MEDIA_NAT);
23436 } else if (!ast_false(v->value)) {
23437 char buf[64];
23438 char *word, *next = buf;
23439
23440 ast_copy_string(buf, v->value, sizeof(buf));
23441 while ((word = strsep(&next, ","))) {
23442 if (!strcasecmp(word, "update")) {
23443 ast_set_flag(&flags[0], SIP_REINVITE_UPDATE | SIP_DIRECT_MEDIA);
23444 } else if (!strcasecmp(word, "nonat")) {
23445 ast_set_flag(&flags[0], SIP_DIRECT_MEDIA);
23446 ast_clear_flag(&flags[0], SIP_DIRECT_MEDIA_NAT);
23447 } else {
23448 ast_log(LOG_WARNING, "Unknown directmedia mode '%s' on line %d\n", v->value, v->lineno);
23449 }
23450 }
23451 }
23452 } else if (!strcasecmp(v->name, "insecure")) {
23453 ast_set_flag(&mask[0], SIP_INSECURE);
23454 ast_clear_flag(&flags[0], SIP_INSECURE);
23455 set_insecure_flags(&flags[0], v->value, v->lineno);
23456 } else if (!strcasecmp(v->name, "progressinband")) {
23457 ast_set_flag(&mask[0], SIP_PROG_INBAND);
23458 ast_clear_flag(&flags[0], SIP_PROG_INBAND);
23459 if (ast_true(v->value))
23460 ast_set_flag(&flags[0], SIP_PROG_INBAND_YES);
23461 else if (strcasecmp(v->value, "never"))
23462 ast_set_flag(&flags[0], SIP_PROG_INBAND_NO);
23463 } else if (!strcasecmp(v->name, "promiscredir")) {
23464 ast_set_flag(&mask[0], SIP_PROMISCREDIR);
23465 ast_set2_flag(&flags[0], ast_true(v->value), SIP_PROMISCREDIR);
23466 } else if (!strcasecmp(v->name, "videosupport")) {
23467 if (!strcasecmp(v->value, "always")) {
23468 ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
23469 ast_set_flag(&flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
23470 } else {
23471 ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT);
23472 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_VIDEOSUPPORT);
23473 }
23474 } else if (!strcasecmp(v->name, "textsupport")) {
23475 ast_set_flag(&mask[1], SIP_PAGE2_TEXTSUPPORT);
23476 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_TEXTSUPPORT);
23477 res = 1;
23478 } else if (!strcasecmp(v->name, "allowoverlap")) {
23479 ast_set_flag(&mask[1], SIP_PAGE2_ALLOWOVERLAP);
23480 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWOVERLAP);
23481 } else if (!strcasecmp(v->name, "allowsubscribe")) {
23482 ast_set_flag(&mask[1], SIP_PAGE2_ALLOWSUBSCRIBE);
23483 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWSUBSCRIBE);
23484 } else if (!strcasecmp(v->name, "ignoresdpversion")) {
23485 ast_set_flag(&mask[1], SIP_PAGE2_IGNORESDPVERSION);
23486 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_IGNORESDPVERSION);
23487 } else if (!strcasecmp(v->name, "faxdetect")) {
23488 ast_set_flag(&mask[1], SIP_PAGE2_FAX_DETECT);
23489 if (ast_true(v->value)) {
23490 ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_BOTH);
23491 } else if (ast_false(v->value)) {
23492 ast_clear_flag(&flags[1], SIP_PAGE2_FAX_DETECT_BOTH);
23493 } else {
23494 char *buf = ast_strdupa(v->value);
23495 char *word, *next = buf;
23496
23497 while ((word = strsep(&next, ","))) {
23498 if (!strcasecmp(word, "cng")) {
23499 ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_CNG);
23500 } else if (!strcasecmp(word, "t38")) {
23501 ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_T38);
23502 } else {
23503 ast_log(LOG_WARNING, "Unknown faxdetect mode '%s' on line %d.\n", word, v->lineno);
23504 }
23505 }
23506 }
23507 } else if (!strcasecmp(v->name, "rfc2833compensate")) {
23508 ast_set_flag(&mask[1], SIP_PAGE2_RFC2833_COMPENSATE);
23509 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RFC2833_COMPENSATE);
23510 } else if (!strcasecmp(v->name, "buggymwi")) {
23511 ast_set_flag(&mask[1], SIP_PAGE2_BUGGY_MWI);
23512 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_BUGGY_MWI);
23513 } else
23514 res = 0;
23515
23516 return res;
23517 }
23518
23519
23520 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context)
23521 {
23522 struct domain *d;
23523
23524 if (ast_strlen_zero(domain)) {
23525 ast_log(LOG_WARNING, "Zero length domain.\n");
23526 return 1;
23527 }
23528
23529 if (!(d = ast_calloc(1, sizeof(*d))))
23530 return 0;
23531
23532 ast_copy_string(d->domain, domain, sizeof(d->domain));
23533
23534 if (!ast_strlen_zero(context))
23535 ast_copy_string(d->context, context, sizeof(d->context));
23536
23537 d->mode = mode;
23538
23539 AST_LIST_LOCK(&domain_list);
23540 AST_LIST_INSERT_TAIL(&domain_list, d, list);
23541 AST_LIST_UNLOCK(&domain_list);
23542
23543 if (sipdebug)
23544 ast_debug(1, "Added local SIP domain '%s'\n", domain);
23545
23546 return 1;
23547 }
23548
23549
23550 static int check_sip_domain(const char *domain, char *context, size_t len)
23551 {
23552 struct domain *d;
23553 int result = 0;
23554
23555 AST_LIST_LOCK(&domain_list);
23556 AST_LIST_TRAVERSE(&domain_list, d, list) {
23557 if (strcasecmp(d->domain, domain))
23558 continue;
23559
23560 if (len && !ast_strlen_zero(d->context))
23561 ast_copy_string(context, d->context, len);
23562
23563 result = 1;
23564 break;
23565 }
23566 AST_LIST_UNLOCK(&domain_list);
23567
23568 return result;
23569 }
23570
23571
23572 static void clear_sip_domains(void)
23573 {
23574 struct domain *d;
23575
23576 AST_LIST_LOCK(&domain_list);
23577 while ((d = AST_LIST_REMOVE_HEAD(&domain_list, list)))
23578 ast_free(d);
23579 AST_LIST_UNLOCK(&domain_list);
23580 }
23581
23582
23583
23584 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, const char *configuration, int lineno)
23585 {
23586 char authcopy[256];
23587 char *username=NULL, *realm=NULL, *secret=NULL, *md5secret=NULL;
23588 struct sip_auth *a, *b, *auth;
23589
23590 if (ast_strlen_zero(configuration))
23591 return authlist;
23592
23593 ast_debug(1, "Auth config :: %s\n", configuration);
23594
23595 ast_copy_string(authcopy, configuration, sizeof(authcopy));
23596 username = authcopy;
23597
23598
23599 realm = strrchr(username, '@');
23600 if (realm)
23601 *realm++ = '\0';
23602 if (ast_strlen_zero(username) || ast_strlen_zero(realm)) {
23603 ast_log(LOG_WARNING, "Format for authentication entry is user[:secret]@realm at line %d\n", lineno);
23604 return authlist;
23605 }
23606
23607
23608 if ((secret = strchr(username, ':'))) {
23609 *secret++ = '\0';
23610 } else if ((md5secret = strchr(username, '#'))) {
23611 *md5secret++ = '\0';
23612 }
23613
23614 if (!(auth = ast_calloc(1, sizeof(*auth))))
23615 return authlist;
23616
23617 ast_copy_string(auth->realm, realm, sizeof(auth->realm));
23618 ast_copy_string(auth->username, username, sizeof(auth->username));
23619 if (secret)
23620 ast_copy_string(auth->secret, secret, sizeof(auth->secret));
23621 if (md5secret)
23622 ast_copy_string(auth->md5secret, md5secret, sizeof(auth->md5secret));
23623
23624
23625 for (b = NULL, a = authlist; a ; b = a, a = a->next)
23626 ;
23627 if (b)
23628 b->next = auth;
23629 else
23630 authlist = auth;
23631
23632 ast_verb(3, "Added authentication for realm %s\n", realm);
23633
23634 return authlist;
23635
23636 }
23637
23638
23639 static int clear_realm_authentication(struct sip_auth *authlist)
23640 {
23641 struct sip_auth *a = authlist;
23642 struct sip_auth *b;
23643
23644 while (a) {
23645 b = a;
23646 a = a->next;
23647 ast_free(b);
23648 }
23649
23650 return 1;
23651 }
23652
23653
23654 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm)
23655 {
23656 struct sip_auth *a;
23657
23658 for (a = authlist; a; a = a->next) {
23659 if (!strcasecmp(a->realm, realm))
23660 break;
23661 }
23662
23663 return a;
23664 }
23665
23666
23667
23668
23669 static struct ast_variable *add_var(const char *buf, struct ast_variable *list)
23670 {
23671 struct ast_variable *tmpvar = NULL;
23672 char *varname = ast_strdupa(buf), *varval = NULL;
23673
23674 if ((varval = strchr(varname, '='))) {
23675 *varval++ = '\0';
23676 if ((tmpvar = ast_variable_new(varname, varval, ""))) {
23677 tmpvar->next = list;
23678 list = tmpvar;
23679 }
23680 }
23681 return list;
23682 }
23683
23684
23685 static void set_peer_defaults(struct sip_peer *peer)
23686 {
23687 if (peer->expire == 0) {
23688
23689
23690
23691 peer->expire = -1;
23692 peer->pokeexpire = -1;
23693 peer->addr.sin_port = htons(STANDARD_SIP_PORT);
23694 set_socket_transport(&peer->socket, SIP_TRANSPORT_UDP);
23695 }
23696 peer->type = SIP_TYPE_PEER;
23697 ast_copy_flags(&peer->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
23698 ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
23699 ast_string_field_set(peer, context, sip_cfg.default_context);
23700 ast_string_field_set(peer, subscribecontext, sip_cfg.default_subscribecontext);
23701 ast_string_field_set(peer, language, default_language);
23702 ast_string_field_set(peer, mohinterpret, default_mohinterpret);
23703 ast_string_field_set(peer, mohsuggest, default_mohsuggest);
23704 peer->addr.sin_family = AF_INET;
23705 peer->defaddr.sin_family = AF_INET;
23706 peer->capability = global_capability;
23707 peer->maxcallbitrate = default_maxcallbitrate;
23708 peer->rtptimeout = global_rtptimeout;
23709 peer->rtpholdtimeout = global_rtpholdtimeout;
23710 peer->rtpkeepalive = global_rtpkeepalive;
23711 peer->allowtransfer = sip_cfg.allowtransfer;
23712 peer->autoframing = global_autoframing;
23713 peer->t38_maxdatagram = global_t38_maxdatagram;
23714 peer->qualifyfreq = global_qualifyfreq;
23715 if (global_callcounter)
23716 peer->call_limit=INT_MAX;
23717 ast_string_field_set(peer, vmexten, default_vmexten);
23718 ast_string_field_set(peer, secret, "");
23719 ast_string_field_set(peer, remotesecret, "");
23720 ast_string_field_set(peer, md5secret, "");
23721 ast_string_field_set(peer, cid_num, "");
23722 ast_string_field_set(peer, cid_name, "");
23723 ast_string_field_set(peer, fromdomain, "");
23724 ast_string_field_set(peer, fromuser, "");
23725 ast_string_field_set(peer, regexten, "");
23726 peer->callgroup = 0;
23727 peer->pickupgroup = 0;
23728 peer->maxms = default_qualify;
23729 peer->prefs = default_prefs;
23730 peer->stimer.st_mode_oper = global_st_mode;
23731 peer->stimer.st_ref = global_st_refresher;
23732 peer->stimer.st_min_se = global_min_se;
23733 peer->stimer.st_max_se = global_max_se;
23734 peer->timer_t1 = global_t1;
23735 peer->timer_b = global_timer_b;
23736 clear_peer_mailboxes(peer);
23737 }
23738
23739
23740 static struct sip_peer *temp_peer(const char *name)
23741 {
23742 struct sip_peer *peer;
23743
23744 if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct")))
23745 return NULL;
23746
23747 if (ast_string_field_init(peer, 512)) {
23748 ao2_t_ref(peer, -1, "failed to string_field_init, drop peer");
23749 return NULL;
23750 }
23751
23752 ast_atomic_fetchadd_int(&apeerobjs, 1);
23753 set_peer_defaults(peer);
23754
23755 ast_copy_string(peer->name, name, sizeof(peer->name));
23756
23757 peer->selfdestruct = TRUE;
23758 peer->host_dynamic = TRUE;
23759 peer->prefs = default_prefs;
23760 reg_source_db(peer);
23761
23762 return peer;
23763 }
23764
23765
23766 static void add_peer_mailboxes(struct sip_peer *peer, const char *value)
23767 {
23768 char *next, *mbox, *context;
23769
23770 next = ast_strdupa(value);
23771
23772 while ((mbox = context = strsep(&next, ","))) {
23773 struct sip_mailbox *mailbox;
23774
23775 if (!(mailbox = ast_calloc(1, sizeof(*mailbox))))
23776 continue;
23777
23778 strsep(&context, "@");
23779 if (ast_strlen_zero(mbox)) {
23780 ast_free(mailbox);
23781 continue;
23782 }
23783 mailbox->mailbox = ast_strdup(mbox);
23784 mailbox->context = ast_strdup(context);
23785
23786 AST_LIST_INSERT_TAIL(&peer->mailboxes, mailbox, entry);
23787 }
23788 }
23789
23790
23791 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only)
23792 {
23793 struct sip_peer *peer = NULL;
23794 struct ast_ha *oldha = NULL;
23795 int found = 0;
23796 int firstpass = 1;
23797 uint16_t port = 0;
23798 int format = 0;
23799 time_t regseconds = 0;
23800 struct ast_flags peerflags[2] = {{(0)}};
23801 struct ast_flags mask[2] = {{(0)}};
23802 char callback[256] = "";
23803 struct sip_peer tmp_peer;
23804 const char *srvlookup = NULL;
23805 static int deprecation_warning = 1;
23806 int alt_fullcontact = alt ? 1 : 0;
23807 struct ast_str *fullcontact = ast_str_alloca(512);
23808
23809 if (!realtime || ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
23810
23811
23812
23813
23814
23815 ast_copy_string(tmp_peer.name, name, sizeof(tmp_peer.name));
23816 peer = ao2_t_find(peers, &tmp_peer, OBJ_POINTER | OBJ_UNLINK, "find and unlink peer from peers table");
23817 }
23818
23819 if (peer) {
23820
23821 found++;
23822 if (!(peer->the_mark))
23823 firstpass = 0;
23824 } else {
23825 if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct")))
23826 return NULL;
23827
23828 if (ast_string_field_init(peer, 512)) {
23829 ao2_t_ref(peer, -1, "failed to string_field_init, drop peer");
23830 return NULL;
23831 }
23832
23833 if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
23834 ast_atomic_fetchadd_int(&rpeerobjs, 1);
23835 ast_debug(3, "-REALTIME- peer built. Name: %s. Peer objects: %d\n", name, rpeerobjs);
23836 } else
23837 ast_atomic_fetchadd_int(&speerobjs, 1);
23838 }
23839
23840
23841 if (firstpass) {
23842 peer->lastmsgssent = -1;
23843 oldha = peer->ha;
23844 peer->ha = NULL;
23845 set_peer_defaults(peer);
23846 peer->type = 0;
23847 }
23848 if (!found && name)
23849 ast_copy_string(peer->name, name, sizeof(peer->name));
23850
23851
23852 if (peer->chanvars) {
23853 ast_variables_destroy(peer->chanvars);
23854 peer->chanvars = NULL;
23855
23856 }
23857
23858 if (found)
23859 peer->portinuri = 0;
23860
23861
23862 clear_realm_authentication(peer->auth);
23863 peer->auth = NULL;
23864 peer->default_outbound_transport = 0;
23865 peer->transports = 0;
23866
23867 for (; v || ((v = alt) && !(alt=NULL)); v = v->next) {
23868 if (!devstate_only) {
23869 if (handle_common_options(&peerflags[0], &mask[0], v)) {
23870 continue;
23871 }
23872 if (handle_t38_options(&peerflags[0], &mask[0], v, &peer->t38_maxdatagram)) {
23873 continue;
23874 }
23875 if (!strcasecmp(v->name, "transport") && !ast_strlen_zero(v->value)) {
23876 char *val = ast_strdupa(v->value);
23877 char *trans;
23878
23879 while ((trans = strsep(&val, ","))) {
23880 trans = ast_skip_blanks(trans);
23881
23882 if (!strncasecmp(trans, "udp", 3)) {
23883 peer->transports |= SIP_TRANSPORT_UDP;
23884 } else if (!strncasecmp(trans, "tcp", 3)) {
23885 peer->transports |= SIP_TRANSPORT_TCP;
23886 } else if (!strncasecmp(trans, "tls", 3)) {
23887 peer->transports |= SIP_TRANSPORT_TLS;
23888 } else {
23889 ast_log(LOG_NOTICE, "'%s' is not a valid transport type. if no other is specified, udp will be used.\n", trans);
23890 }
23891
23892 if (!peer->default_outbound_transport) {
23893 peer->default_outbound_transport = peer->transports;
23894 }
23895 }
23896 } else if (realtime && !strcasecmp(v->name, "regseconds")) {
23897 ast_get_time_t(v->value, ®seconds, 0, NULL);
23898 } else if (realtime && !strcasecmp(v->name, "name")) {
23899 ast_copy_string(peer->name, v->value, sizeof(peer->name));
23900 } else if (!strcasecmp(v->name, "type")) {
23901 if (!strcasecmp(v->value, "peer")) {
23902 peer->type |= SIP_TYPE_PEER;
23903 } else if (!strcasecmp(v->value, "user")) {
23904 peer->type |= SIP_TYPE_USER;
23905 } else if (!strcasecmp(v->value, "friend")) {
23906 peer->type = SIP_TYPE_USER | SIP_TYPE_PEER;
23907 }
23908 } else if (!strcasecmp(v->name, "remotesecret")) {
23909 ast_string_field_set(peer, remotesecret, v->value);
23910 } else if (!strcasecmp(v->name, "secret")) {
23911 ast_string_field_set(peer, secret, v->value);
23912 } else if (!strcasecmp(v->name, "md5secret")) {
23913 ast_string_field_set(peer, md5secret, v->value);
23914 } else if (!strcasecmp(v->name, "auth")) {
23915 peer->auth = add_realm_authentication(peer->auth, v->value, v->lineno);
23916 } else if (!strcasecmp(v->name, "callerid")) {
23917 char cid_name[80] = { '\0' }, cid_num[80] = { '\0' };
23918
23919 ast_callerid_split(v->value, cid_name, sizeof(cid_name), cid_num, sizeof(cid_num));
23920 ast_string_field_set(peer, cid_name, cid_name);
23921 ast_string_field_set(peer, cid_num, cid_num);
23922 } else if (!strcasecmp(v->name, "fullname")) {
23923 ast_string_field_set(peer, cid_name, v->value);
23924 } else if (!strcasecmp(v->name, "trunkname")) {
23925
23926 ast_string_field_set(peer, cid_name, "");
23927 } else if (!strcasecmp(v->name, "cid_number")) {
23928 ast_string_field_set(peer, cid_num, v->value);
23929 } else if (!strcasecmp(v->name, "context")) {
23930 ast_string_field_set(peer, context, v->value);
23931 ast_set_flag(&peer->flags[1], SIP_PAGE2_HAVEPEERCONTEXT);
23932 } else if (!strcasecmp(v->name, "subscribecontext")) {
23933 ast_string_field_set(peer, subscribecontext, v->value);
23934 } else if (!strcasecmp(v->name, "fromdomain")) {
23935 ast_string_field_set(peer, fromdomain, v->value);
23936 } else if (!strcasecmp(v->name, "usereqphone")) {
23937 ast_set2_flag(&peer->flags[0], ast_true(v->value), SIP_USEREQPHONE);
23938 } else if (!strcasecmp(v->name, "fromuser")) {
23939 ast_string_field_set(peer, fromuser, v->value);
23940 } else if (!strcasecmp(v->name, "outboundproxy")) {
23941 char *port, *next, *force, *proxyname;
23942 int forceopt = FALSE;
23943
23944 next = proxyname = ast_strdupa(v->value);
23945 if ((port = strchr(proxyname, ':'))) {
23946 *port++ = '\0';
23947 next = port;
23948 }
23949 if ((force = strchr(next, ','))) {
23950 *force++ = '\0';
23951 forceopt = strcmp(force, "force");
23952 }
23953
23954 peer->outboundproxy = proxy_allocate(proxyname, port, forceopt);
23955 } else if (!strcasecmp(v->name, "host")) {
23956 if (!strcasecmp(v->value, "dynamic")) {
23957
23958 if (!found || !peer->host_dynamic) {
23959
23960
23961 memset(&peer->addr.sin_addr, 0, 4);
23962 peer->addr.sin_port = 0;
23963 }
23964 peer->host_dynamic = TRUE;
23965 } else {
23966
23967 AST_SCHED_DEL_UNREF(sched, peer->expire,
23968 unref_peer(peer, "removing register expire ref"));
23969
23970 peer->addr.sin_port = 0;
23971 peer->host_dynamic = FALSE;
23972 srvlookup = v->value;
23973 if (global_dynamic_exclude_static) {
23974 int err = 0;
23975 global_contact_ha = ast_append_ha("deny", (char *)ast_inet_ntoa(peer->addr.sin_addr), global_contact_ha, &err);
23976 if (err) {
23977 ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
23978 }
23979 }
23980 }
23981 } else if (!strcasecmp(v->name, "defaultip")) {
23982 if (!ast_strlen_zero(v->value) && ast_get_ip(&peer->defaddr, v->value)) {
23983 unref_peer(peer, "unref_peer: from build_peer defaultip");
23984 return NULL;
23985 }
23986 } else if (!strcasecmp(v->name, "permit") || !strcasecmp(v->name, "deny")) {
23987 int ha_error = 0;
23988 if (!ast_strlen_zero(v->value)) {
23989 peer->ha = ast_append_ha(v->name, v->value, peer->ha, &ha_error);
23990 }
23991 if (ha_error) {
23992 ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
23993 }
23994 } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny")) {
23995 int ha_error = 0;
23996 if (!ast_strlen_zero(v->value)) {
23997 peer->contactha = ast_append_ha(v->name + 7, v->value, peer->contactha, &ha_error);
23998 }
23999 if (ha_error) {
24000 ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
24001 }
24002 } else if (!strcasecmp(v->name, "port")) {
24003 peer->portinuri = 1;
24004 if (!(port = port_str2int(v->value, 0))) {
24005 if (realtime) {
24006
24007 peer->portinuri = 0;
24008 } else {
24009 ast_log(LOG_WARNING, "Invalid peer port configuration at line %d : %s\n", v->lineno, v->value);
24010 }
24011 }
24012 } else if (!strcasecmp(v->name, "callingpres")) {
24013 peer->callingpres = ast_parse_caller_presentation(v->value);
24014 if (peer->callingpres == -1) {
24015 peer->callingpres = atoi(v->value);
24016 }
24017 } else if (!strcasecmp(v->name, "username") || !strcmp(v->name, "defaultuser")) {
24018 ast_string_field_set(peer, username, v->value);
24019 if (!strcasecmp(v->name, "username")) {
24020 if (deprecation_warning) {
24021 ast_log(LOG_NOTICE, "The 'username' field for sip peers has been deprecated in favor of the term 'defaultuser'\n");
24022 deprecation_warning = 0;
24023 }
24024 peer->deprecated_username = 1;
24025 }
24026 } else if (!strcasecmp(v->name, "language")) {
24027 ast_string_field_set(peer, language, v->value);
24028 } else if (!strcasecmp(v->name, "regexten")) {
24029 ast_string_field_set(peer, regexten, v->value);
24030 } else if (!strcasecmp(v->name, "callbackextension")) {
24031 ast_copy_string(callback, v->value, sizeof(callback));
24032 } else if (!strcasecmp(v->name, "amaflags")) {
24033 format = ast_cdr_amaflags2int(v->value);
24034 if (format < 0) {
24035 ast_log(LOG_WARNING, "Invalid AMA Flags for peer: %s at line %d\n", v->value, v->lineno);
24036 } else {
24037 peer->amaflags = format;
24038 }
24039 } else if (!strcasecmp(v->name, "accountcode")) {
24040 ast_string_field_set(peer, accountcode, v->value);
24041 } else if (!strcasecmp(v->name, "mohinterpret")) {
24042 ast_string_field_set(peer, mohinterpret, v->value);
24043 } else if (!strcasecmp(v->name, "mohsuggest")) {
24044 ast_string_field_set(peer, mohsuggest, v->value);
24045 } else if (!strcasecmp(v->name, "parkinglot")) {
24046 ast_string_field_set(peer, parkinglot, v->value);
24047 } else if (!strcasecmp(v->name, "mailbox")) {
24048 add_peer_mailboxes(peer, v->value);
24049 } else if (!strcasecmp(v->name, "hasvoicemail")) {
24050
24051
24052 if (ast_true(v->value) && AST_LIST_EMPTY(&peer->mailboxes)) {
24053 add_peer_mailboxes(peer, name);
24054 }
24055 } else if (!strcasecmp(v->name, "subscribemwi")) {
24056 ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_SUBSCRIBEMWIONLY);
24057 } else if (!strcasecmp(v->name, "vmexten")) {
24058 ast_string_field_set(peer, vmexten, v->value);
24059 } else if (!strcasecmp(v->name, "callgroup")) {
24060 peer->callgroup = ast_get_group(v->value);
24061 } else if (!strcasecmp(v->name, "allowtransfer")) {
24062 peer->allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
24063 } else if (!strcasecmp(v->name, "pickupgroup")) {
24064 peer->pickupgroup = ast_get_group(v->value);
24065 } else if (!strcasecmp(v->name, "allow")) {
24066 int error = ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, TRUE);
24067 if (error) {
24068 ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
24069 }
24070 } else if (!strcasecmp(v->name, "disallow")) {
24071 int error = ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, FALSE);
24072 if (error) {
24073 ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
24074 }
24075 } else if (!strcasecmp(v->name, "registertrying")) {
24076 ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_REGISTERTRYING);
24077 } else if (!strcasecmp(v->name, "autoframing")) {
24078 peer->autoframing = ast_true(v->value);
24079 } else if (!strcasecmp(v->name, "rtptimeout")) {
24080 if ((sscanf(v->value, "%30d", &peer->rtptimeout) != 1) || (peer->rtptimeout < 0)) {
24081 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
24082 peer->rtptimeout = global_rtptimeout;
24083 }
24084 } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
24085 if ((sscanf(v->value, "%30d", &peer->rtpholdtimeout) != 1) || (peer->rtpholdtimeout < 0)) {
24086 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
24087 peer->rtpholdtimeout = global_rtpholdtimeout;
24088 }
24089 } else if (!strcasecmp(v->name, "rtpkeepalive")) {
24090 if ((sscanf(v->value, "%30d", &peer->rtpkeepalive) != 1) || (peer->rtpkeepalive < 0)) {
24091 ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d. Using default.\n", v->value, v->lineno);
24092 peer->rtpkeepalive = global_rtpkeepalive;
24093 }
24094 } else if (!strcasecmp(v->name, "timert1")) {
24095 if ((sscanf(v->value, "%30d", &peer->timer_t1) != 1) || (peer->timer_t1 < 0)) {
24096 ast_log(LOG_WARNING, "'%s' is not a valid T1 time at line %d. Using default.\n", v->value, v->lineno);
24097 peer->timer_t1 = global_t1;
24098 }
24099
24100
24101 if (peer->timer_b < peer->timer_t1 * 64) {
24102 peer->timer_b = peer->timer_t1 * 64;
24103 }
24104 } else if (!strcasecmp(v->name, "timerb")) {
24105 if ((sscanf(v->value, "%30d", &peer->timer_b) != 1) || (peer->timer_b < 0)) {
24106 ast_log(LOG_WARNING, "'%s' is not a valid Timer B time at line %d. Using default.\n", v->value, v->lineno);
24107 peer->timer_b = global_timer_b;
24108 }
24109 if (peer->timer_b < peer->timer_t1 * 64) {
24110 static int warning = 0;
24111 if (warning++ % 20 == 0) {
24112 ast_log(LOG_WARNING, "Timer B has been set lower than recommended. (RFC 3261, 17.1.1.2)\n");
24113 }
24114 }
24115 } else if (!strcasecmp(v->name, "setvar")) {
24116 peer->chanvars = add_var(v->value, peer->chanvars);
24117 } else if (!strcasecmp(v->name, "qualifyfreq")) {
24118 int i;
24119 if (sscanf(v->value, "%30d", &i) == 1) {
24120 peer->qualifyfreq = i * 1000;
24121 } else {
24122 ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
24123 peer->qualifyfreq = global_qualifyfreq;
24124 }
24125 } else if (!strcasecmp(v->name, "maxcallbitrate")) {
24126 peer->maxcallbitrate = atoi(v->value);
24127 if (peer->maxcallbitrate < 0) {
24128 peer->maxcallbitrate = default_maxcallbitrate;
24129 }
24130 } else if (!strcasecmp(v->name, "session-timers")) {
24131 int i = (int) str2stmode(v->value);
24132 if (i < 0) {
24133 ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
24134 peer->stimer.st_mode_oper = global_st_mode;
24135 } else {
24136 peer->stimer.st_mode_oper = i;
24137 }
24138 } else if (!strcasecmp(v->name, "session-expires")) {
24139 if (sscanf(v->value, "%30d", &peer->stimer.st_max_se) != 1) {
24140 ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
24141 peer->stimer.st_max_se = global_max_se;
24142 }
24143 } else if (!strcasecmp(v->name, "session-minse")) {
24144 if (sscanf(v->value, "%30d", &peer->stimer.st_min_se) != 1) {
24145 ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
24146 peer->stimer.st_min_se = global_min_se;
24147 }
24148 if (peer->stimer.st_min_se < 90) {
24149 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);
24150 peer->stimer.st_min_se = global_min_se;
24151 }
24152 } else if (!strcasecmp(v->name, "session-refresher")) {
24153 int i = (int) str2strefresher(v->value);
24154 if (i < 0) {
24155 ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
24156 peer->stimer.st_ref = global_st_refresher;
24157 } else {
24158 peer->stimer.st_ref = i;
24159 }
24160 }
24161 }
24162
24163
24164 if (realtime && !strcasecmp(v->name, "lastms")) {
24165 sscanf(v->value, "%30d", &peer->lastms);
24166 } else if (realtime && !strcasecmp(v->name, "ipaddr") && !ast_strlen_zero(v->value) ) {
24167 inet_aton(v->value, &(peer->addr.sin_addr));
24168 } else if (realtime && !strcasecmp(v->name, "fullcontact")) {
24169 if (alt_fullcontact && !alt) {
24170
24171
24172
24173
24174
24175 alt_fullcontact = 0;
24176 ast_str_reset(fullcontact);
24177 }
24178
24179 if (fullcontact->used > 0) {
24180 ast_str_append(&fullcontact, 0, ";%s", v->value);
24181 } else {
24182 ast_str_set(&fullcontact, 0, "%s", v->value);
24183 }
24184 } else if (!strcasecmp(v->name, "qualify")) {
24185 if (!strcasecmp(v->value, "no")) {
24186 peer->maxms = 0;
24187 } else if (!strcasecmp(v->value, "yes")) {
24188 peer->maxms = default_qualify ? default_qualify : DEFAULT_MAXMS;
24189 } else if (sscanf(v->value, "%30d", &peer->maxms) != 1) {
24190 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);
24191 peer->maxms = 0;
24192 }
24193 if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && peer->maxms > 0) {
24194
24195
24196
24197
24198 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);
24199 peer->maxms = 0;
24200 }
24201 } else if (!strcasecmp(v->name, "callcounter")) {
24202 peer->call_limit = ast_true(v->value) ? INT_MAX : 0;
24203 } else if (!strcasecmp(v->name, "call-limit")) {
24204 peer->call_limit = atoi(v->value);
24205 if (peer->call_limit < 0) {
24206 peer->call_limit = 0;
24207 }
24208 } else if (!strcasecmp(v->name, "busylevel")) {
24209 peer->busy_level = atoi(v->value);
24210 if (peer->busy_level < 0) {
24211 peer->busy_level = 0;
24212 }
24213 }
24214 }
24215
24216 if (!peer->default_outbound_transport) {
24217
24218 peer->transports = default_transports;
24219
24220 peer->default_outbound_transport = default_primary_transport;
24221 }
24222
24223
24224
24225
24226
24227 if (((peer->socket.type != peer->default_outbound_transport) && (peer->expire == -1)) ||
24228 !(peer->socket.type & peer->transports) || !(peer->socket.type)) {
24229
24230 set_socket_transport(&peer->socket, peer->default_outbound_transport);
24231 }
24232
24233 if (port && !realtime && peer->host_dynamic) {
24234 peer->defaddr.sin_port = htons(port);
24235 } else if (port) {
24236 peer->addr.sin_port = htons(port);
24237 }
24238
24239 if (ast_str_strlen(fullcontact)) {
24240 ast_string_field_set(peer, fullcontact, ast_str_buffer(fullcontact));
24241 peer->rt_fromcontact = TRUE;
24242
24243
24244
24245
24246
24247
24248
24249
24250 if (!ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) || !peer->addr.sin_addr.s_addr) {
24251 __set_address_from_contact(fullcontact->str, &peer->addr, 0);
24252 }
24253 }
24254
24255 if (srvlookup && peer->dnsmgr == NULL) {
24256 char transport[MAXHOSTNAMELEN];
24257 char _srvlookup[MAXHOSTNAMELEN];
24258 char *params;
24259
24260 ast_copy_string(_srvlookup, srvlookup, sizeof(_srvlookup));
24261 if ((params = strchr(_srvlookup, ';'))) {
24262 *params++ = '\0';
24263 }
24264
24265 snprintf(transport, sizeof(transport), "_sip._%s", get_transport(peer->socket.type));
24266
24267 if (ast_dnsmgr_lookup(_srvlookup, &peer->addr, &peer->dnsmgr, sip_cfg.srvlookup && !peer->portinuri ? transport : NULL)) {
24268 ast_log(LOG_ERROR, "srvlookup failed for host: %s, on peer %s, removing peer\n", _srvlookup, peer->name);
24269 unref_peer(peer, "getting rid of a peer pointer");
24270 return NULL;
24271 }
24272
24273 ast_string_field_set(peer, tohost, srvlookup);
24274 }
24275
24276 if (!peer->addr.sin_port) {
24277 peer->addr.sin_port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
24278 }
24279 if (!peer->defaddr.sin_port) {
24280 peer->defaddr.sin_port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
24281 }
24282 if (!peer->socket.port) {
24283 peer->socket.port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
24284 }
24285
24286 if (!sip_cfg.ignore_regexpire && peer->host_dynamic && realtime) {
24287 time_t nowtime = time(NULL);
24288
24289 if ((nowtime - regseconds) > 0) {
24290 destroy_association(peer);
24291 memset(&peer->addr, 0, sizeof(peer->addr));
24292 peer->lastms = -1;
24293 ast_debug(1, "Bah, we're expired (%d/%d/%d)!\n", (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
24294 }
24295 }
24296
24297
24298 if (!devstate_only && realtime && peer->lastms > 0) {
24299 ref_peer(peer, "schedule qualify");
24300 sip_poke_peer(peer, 0);
24301 }
24302
24303 ast_copy_flags(&peer->flags[0], &peerflags[0], mask[0].flags);
24304 ast_copy_flags(&peer->flags[1], &peerflags[1], mask[1].flags);
24305 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
24306 sip_cfg.allowsubscribe = TRUE;
24307 }
24308 if (!found && peer->host_dynamic && !peer->is_realtime) {
24309 reg_source_db(peer);
24310 }
24311
24312
24313
24314 if (!devstate_only && !ast_test_flag(&peer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY) &&
24315 !AST_LIST_EMPTY(&peer->mailboxes)) {
24316 add_peer_mwi_subs(peer);
24317
24318
24319
24320 sip_send_mwi_to_peer(peer, NULL, 1);
24321 }
24322
24323 peer->the_mark = 0;
24324
24325 ast_free_ha(oldha);
24326 if (!ast_strlen_zero(callback)) {
24327 char *reg_string;
24328 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) {
24329 ast_log(LOG_WARNING, "asprintf() failed: %s\n", strerror(errno));
24330 } else if (reg_string) {
24331 sip_register(reg_string, 0);
24332 ast_free(reg_string);
24333 }
24334 }
24335 return peer;
24336 }
24337
24338 static int peer_markall_func(void *device, void *arg, int flags)
24339 {
24340 struct sip_peer *peer = device;
24341 peer->the_mark = 1;
24342 return 0;
24343 }
24344
24345
24346
24347
24348
24349
24350
24351 static int reload_config(enum channelreloadreason reason)
24352 {
24353 struct ast_config *cfg, *ucfg;
24354 struct ast_variable *v;
24355 struct sip_peer *peer;
24356 char *cat, *stringp, *context, *oldregcontext;
24357 char newcontexts[AST_MAX_CONTEXT], oldcontexts[AST_MAX_CONTEXT];
24358 struct ast_flags dummy[2];
24359 struct ast_flags config_flags = { reason == CHANNEL_MODULE_LOAD ? 0 : ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) ? 0 : CONFIG_FLAG_FILEUNCHANGED };
24360 int auto_sip_domains = FALSE;
24361 struct sockaddr_in old_bindaddr = bindaddr;
24362 int registry_count = 0, peer_count = 0;
24363 time_t run_start, run_end;
24364
24365 run_start = time(0);
24366 ast_unload_realtime("sipregs");
24367 ast_unload_realtime("sippeers");
24368 cfg = ast_config_load(config, config_flags);
24369
24370
24371 if (!cfg) {
24372 ast_log(LOG_NOTICE, "Unable to load config %s\n", config);
24373 return -1;
24374 } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
24375 ucfg = ast_config_load("users.conf", config_flags);
24376 if (ucfg == CONFIG_STATUS_FILEUNCHANGED) {
24377 return 1;
24378 } else if (ucfg == CONFIG_STATUS_FILEINVALID) {
24379 ast_log(LOG_ERROR, "Contents of users.conf are invalid and cannot be parsed\n");
24380 return 1;
24381 }
24382
24383 ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
24384 if ((cfg = ast_config_load(config, config_flags)) == CONFIG_STATUS_FILEINVALID) {
24385 ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed\n", config);
24386 ast_config_destroy(ucfg);
24387 return 1;
24388 }
24389 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
24390 ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed\n", config);
24391 return 1;
24392 } else {
24393 ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
24394 if ((ucfg = ast_config_load("users.conf", config_flags)) == CONFIG_STATUS_FILEINVALID) {
24395 ast_log(LOG_ERROR, "Contents of users.conf are invalid and cannot be parsed\n");
24396 ast_config_destroy(cfg);
24397 return 1;
24398 }
24399 }
24400
24401
24402 memset(&sip_tcp_desc.local_address, 0, sizeof(sip_tcp_desc.local_address));
24403 memset(&sip_tls_desc.local_address, 0, sizeof(sip_tls_desc.local_address));
24404
24405 ast_free_ha(global_contact_ha);
24406 global_contact_ha = NULL;
24407
24408 default_tls_cfg.enabled = FALSE;
24409
24410 sip_tcp_desc.local_address.sin_port = htons(STANDARD_SIP_PORT);
24411 sip_tls_desc.local_address.sin_port = htons(STANDARD_TLS_PORT);
24412
24413 if (reason != CHANNEL_MODULE_LOAD) {
24414 ast_debug(4, "--------------- SIP reload started\n");
24415
24416 clear_realm_authentication(authl);
24417 clear_sip_domains();
24418 authl = NULL;
24419
24420
24421
24422 ASTOBJ_CONTAINER_TRAVERSE(®l, 1, do {
24423
24424 ASTOBJ_RDLOCK(iterator);
24425 if (iterator->call) {
24426 ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", iterator->username, iterator->hostname);
24427
24428 dialog_unlink_all(iterator->call, TRUE, TRUE);
24429 iterator->call = dialog_unref(iterator->call, "remove iterator->call from registry traversal");
24430 }
24431 if (iterator->expire > -1) {
24432 AST_SCHED_DEL_UNREF(sched, iterator->expire, registry_unref(iterator, "reg ptr unref from reload config"));
24433 }
24434 if (iterator->timeout > -1) {
24435 AST_SCHED_DEL_UNREF(sched, iterator->timeout, registry_unref(iterator, "reg ptr unref from reload config"));
24436 }
24437 ASTOBJ_UNLOCK(iterator);
24438
24439 } while(0));
24440
24441
24442 ASTOBJ_CONTAINER_DESTROYALL(®l, sip_registry_destroy);
24443 ast_debug(4, "--------------- Done destroying registry list\n");
24444 ao2_t_callback(peers, OBJ_NODATA, peer_markall_func, NULL, "callback to mark all peers");
24445 }
24446
24447
24448 if (reason != CHANNEL_MODULE_LOAD) {
24449 ast_free(default_tls_cfg.certfile);
24450 ast_free(default_tls_cfg.cipher);
24451 ast_free(default_tls_cfg.cafile);
24452 ast_free(default_tls_cfg.capath);
24453 }
24454 default_tls_cfg.certfile = ast_strdup(AST_CERTFILE);
24455 default_tls_cfg.cipher = ast_strdup("");
24456 default_tls_cfg.cafile = ast_strdup("");
24457 default_tls_cfg.capath = ast_strdup("");
24458
24459
24460
24461 ast_copy_string(oldcontexts, global_regcontext, sizeof(oldcontexts));
24462 oldregcontext = oldcontexts;
24463
24464
24465
24466 sipdebug &= sip_debug_console;
24467 ast_clear_flag(&global_flags[0], AST_FLAGS_ALL);
24468 ast_clear_flag(&global_flags[1], AST_FLAGS_ALL);
24469
24470
24471 memset(&bindaddr, 0, sizeof(bindaddr));
24472 memset(&stunaddr, 0, sizeof(stunaddr));
24473 memset(&internip, 0, sizeof(internip));
24474
24475
24476 ast_free_ha(localaddr);
24477 memset(&localaddr, 0, sizeof(localaddr));
24478 memset(&externip, 0, sizeof(externip));
24479 memset(&default_prefs, 0 , sizeof(default_prefs));
24480 memset(&sip_cfg.outboundproxy, 0, sizeof(struct sip_proxy));
24481 sip_cfg.outboundproxy.ip.sin_port = htons(STANDARD_SIP_PORT);
24482 sip_cfg.outboundproxy.ip.sin_family = AF_INET;
24483 sip_cfg.outboundproxy.force = FALSE;
24484 default_transports = 0;
24485 default_primary_transport = 0;
24486 ourport_tcp = STANDARD_SIP_PORT;
24487 ourport_tls = STANDARD_TLS_PORT;
24488 bindaddr.sin_port = htons(STANDARD_SIP_PORT);
24489 sip_cfg.srvlookup = DEFAULT_SRVLOOKUP;
24490 global_tos_sip = DEFAULT_TOS_SIP;
24491 global_tos_audio = DEFAULT_TOS_AUDIO;
24492 global_tos_video = DEFAULT_TOS_VIDEO;
24493 global_tos_text = DEFAULT_TOS_TEXT;
24494 global_cos_sip = DEFAULT_COS_SIP;
24495 global_cos_audio = DEFAULT_COS_AUDIO;
24496 global_cos_video = DEFAULT_COS_VIDEO;
24497 global_cos_text = DEFAULT_COS_TEXT;
24498
24499 externhost[0] = '\0';
24500 externexpire = 0;
24501 externrefresh = 10;
24502
24503
24504 sip_cfg.allow_external_domains = DEFAULT_ALLOW_EXT_DOM;
24505 global_regcontext[0] = '\0';
24506 sip_cfg.regextenonqualify = DEFAULT_REGEXTENONQUALIFY;
24507 sip_cfg.notifyringing = DEFAULT_NOTIFYRINGING;
24508 sip_cfg.notifycid = DEFAULT_NOTIFYCID;
24509 sip_cfg.notifyhold = FALSE;
24510 sip_cfg.directrtpsetup = FALSE;
24511 sip_cfg.alwaysauthreject = DEFAULT_ALWAYSAUTHREJECT;
24512 sip_cfg.allowsubscribe = FALSE;
24513 snprintf(global_useragent, sizeof(global_useragent), "%s %s", DEFAULT_USERAGENT, ast_get_version());
24514 snprintf(global_sdpsession, sizeof(global_sdpsession), "%s %s", DEFAULT_SDPSESSION, ast_get_version());
24515 snprintf(global_sdpowner, sizeof(global_sdpowner), "%s", DEFAULT_SDPOWNER);
24516 global_prematuremediafilter = TRUE;
24517 ast_copy_string(default_notifymime, DEFAULT_NOTIFYMIME, sizeof(default_notifymime));
24518 ast_copy_string(sip_cfg.realm, S_OR(ast_config_AST_SYSTEM_NAME, DEFAULT_REALM), sizeof(sip_cfg.realm));
24519 ast_copy_string(default_callerid, DEFAULT_CALLERID, sizeof(default_callerid));
24520 sip_cfg.compactheaders = DEFAULT_COMPACTHEADERS;
24521 global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
24522 global_regattempts_max = 0;
24523 sip_cfg.pedanticsipchecking = DEFAULT_PEDANTIC;
24524 sip_cfg.autocreatepeer = DEFAULT_AUTOCREATEPEER;
24525 global_autoframing = 0;
24526 sip_cfg.allowguest = DEFAULT_ALLOWGUEST;
24527 global_callcounter = DEFAULT_CALLCOUNTER;
24528 global_match_auth_username = FALSE;
24529 global_rtptimeout = 0;
24530 global_rtpholdtimeout = 0;
24531 global_rtpkeepalive = DEFAULT_RTPKEEPALIVE;
24532 sip_cfg.allowtransfer = TRANSFER_OPENFORALL;
24533 sip_cfg.rtautoclear = 120;
24534 ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE);
24535 ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP);
24536 sip_cfg.peer_rtupdate = TRUE;
24537 global_dynamic_exclude_static = 0;
24538
24539
24540 global_st_mode = SESSION_TIMER_MODE_ACCEPT;
24541 global_st_refresher = SESSION_TIMER_REFRESHER_UAS;
24542 global_min_se = DEFAULT_MIN_SE;
24543 global_max_se = DEFAULT_MAX_SE;
24544
24545
24546 global_qualify_gap = DEFAULT_QUALIFY_GAP;
24547 global_qualify_peers = DEFAULT_QUALIFY_PEERS;
24548
24549
24550 ast_copy_string(sip_cfg.default_context, DEFAULT_CONTEXT, sizeof(sip_cfg.default_context));
24551 sip_cfg.default_subscribecontext[0] = '\0';
24552 default_language[0] = '\0';
24553 default_fromdomain[0] = '\0';
24554 default_qualify = DEFAULT_QUALIFY;
24555 default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
24556 ast_copy_string(default_mohinterpret, DEFAULT_MOHINTERPRET, sizeof(default_mohinterpret));
24557 ast_copy_string(default_mohsuggest, DEFAULT_MOHSUGGEST, sizeof(default_mohsuggest));
24558 ast_copy_string(default_vmexten, DEFAULT_VMEXTEN, sizeof(default_vmexten));
24559 ast_set_flag(&global_flags[0], SIP_DTMF_RFC2833);
24560 ast_set_flag(&global_flags[0], SIP_NAT_RFC3581);
24561 ast_set_flag(&global_flags[0], SIP_DIRECT_MEDIA);
24562
24563
24564 dumphistory = FALSE;
24565 recordhistory = FALSE;
24566 sipdebug &= ~sip_debug_config;
24567
24568
24569 global_relaxdtmf = FALSE;
24570 sip_cfg.callevents = DEFAULT_CALLEVENTS;
24571 global_authfailureevents = FALSE;
24572 global_t1 = DEFAULT_TIMER_T1;
24573 global_timer_b = 64 * DEFAULT_TIMER_T1;
24574 global_t1min = DEFAULT_T1MIN;
24575 global_qualifyfreq = DEFAULT_QUALIFYFREQ;
24576 global_t38_maxdatagram = -1;
24577 global_shrinkcallerid = 1;
24578
24579 sip_cfg.matchexterniplocally = DEFAULT_MATCHEXTERNIPLOCALLY;
24580
24581
24582 memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
24583
24584 ast_clear_flag(&global_flags[1], SIP_PAGE2_FAX_DETECT);
24585 ast_clear_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT | SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
24586 ast_clear_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT);
24587 ast_clear_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION);
24588
24589
24590
24591 for (v = ast_variable_browse(cfg, "general"); v; v = v->next) {
24592 if (handle_common_options(&global_flags[0], &dummy[0], v))
24593 continue;
24594 if (handle_t38_options(&global_flags[0], &dummy[0], v, &global_t38_maxdatagram)) {
24595 continue;
24596 }
24597
24598 if (!ast_jb_read_conf(&global_jbconf, v->name, v->value))
24599 continue;
24600
24601 if (!strcasecmp(v->name, "context")) {
24602 ast_copy_string(sip_cfg.default_context, v->value, sizeof(sip_cfg.default_context));
24603 } else if (!strcasecmp(v->name, "subscribecontext")) {
24604 ast_copy_string(sip_cfg.default_subscribecontext, v->value, sizeof(sip_cfg.default_subscribecontext));
24605 } else if (!strcasecmp(v->name, "callcounter")) {
24606 global_callcounter = ast_true(v->value) ? 1 : 0;
24607 } else if (!strcasecmp(v->name, "allowguest")) {
24608 sip_cfg.allowguest = ast_true(v->value) ? 1 : 0;
24609 } else if (!strcasecmp(v->name, "realm")) {
24610 ast_copy_string(sip_cfg.realm, v->value, sizeof(sip_cfg.realm));
24611 } else if (!strcasecmp(v->name, "useragent")) {
24612 ast_copy_string(global_useragent, v->value, sizeof(global_useragent));
24613 ast_debug(1, "Setting SIP channel User-Agent Name to %s\n", global_useragent);
24614 } else if (!strcasecmp(v->name, "sdpsession")) {
24615 ast_copy_string(global_sdpsession, v->value, sizeof(global_sdpsession));
24616 } else if (!strcasecmp(v->name, "sdpowner")) {
24617
24618 if (!strstr(v->value, " "))
24619 ast_copy_string(global_sdpowner, v->value, sizeof(global_sdpowner));
24620 else
24621 ast_log(LOG_WARNING, "'%s' must not contain spaces at line %d. Using default.\n", v->value, v->lineno);
24622 } else if (!strcasecmp(v->name, "allowtransfer")) {
24623 sip_cfg.allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
24624 } else if (!strcasecmp(v->name, "rtcachefriends")) {
24625 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTCACHEFRIENDS);
24626 } else if (!strcasecmp(v->name, "rtsavesysname")) {
24627 sip_cfg.rtsave_sysname = ast_true(v->value);
24628 } else if (!strcasecmp(v->name, "rtupdate")) {
24629 sip_cfg.peer_rtupdate = ast_true(v->value);
24630 } else if (!strcasecmp(v->name, "ignoreregexpire")) {
24631 sip_cfg.ignore_regexpire = ast_true(v->value);
24632 } else if (!strcasecmp(v->name, "timert1")) {
24633
24634
24635
24636 global_t1 = atoi(v->value);
24637
24638 global_timer_b = global_t1 * 64;
24639 } else if (!strcasecmp(v->name, "t1min")) {
24640 global_t1min = atoi(v->value);
24641 } else if (!strcasecmp(v->name, "transport") && !ast_strlen_zero(v->value)) {
24642 char *val = ast_strdupa(v->value);
24643 char *trans;
24644
24645 while ((trans = strsep(&val, ","))) {
24646 trans = ast_skip_blanks(trans);
24647
24648 if (!strncasecmp(trans, "udp", 3))
24649 default_transports |= SIP_TRANSPORT_UDP;
24650 else if (!strncasecmp(trans, "tcp", 3))
24651 default_transports |= SIP_TRANSPORT_TCP;
24652 else if (!strncasecmp(trans, "tls", 3))
24653 default_transports |= SIP_TRANSPORT_TLS;
24654 else
24655 ast_log(LOG_NOTICE, "'%s' is not a valid transport type. if no other is specified, udp will be used.\n", trans);
24656 if (default_primary_transport == 0) {
24657 default_primary_transport = default_transports;
24658 }
24659 }
24660 } else if (!strcasecmp(v->name, "tcpenable")) {
24661 sip_tcp_desc.local_address.sin_family = ast_false(v->value) ? 0 : AF_INET;
24662 ast_debug(2, "Enabling TCP socket for listening\n");
24663 } else if (!strcasecmp(v->name, "tcpbindaddr")) {
24664 int family = sip_tcp_desc.local_address.sin_family;
24665 if (ast_parse_arg(v->value, PARSE_INADDR, &sip_tcp_desc.local_address))
24666 ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n", v->name, v->value, v->lineno, config);
24667 sip_tcp_desc.local_address.sin_family = family;
24668 ast_debug(2, "Setting TCP socket address to %s\n", v->value);
24669 } else if (!strcasecmp(v->name, "tlsenable")) {
24670 default_tls_cfg.enabled = ast_true(v->value) ? TRUE : FALSE;
24671 sip_tls_desc.local_address.sin_family = AF_INET;
24672 } else if (!strcasecmp(v->name, "tlscertfile")) {
24673 ast_free(default_tls_cfg.certfile);
24674 default_tls_cfg.certfile = ast_strdup(v->value);
24675 } else if (!strcasecmp(v->name, "tlscipher")) {
24676 ast_free(default_tls_cfg.cipher);
24677 default_tls_cfg.cipher = ast_strdup(v->value);
24678 } else if (!strcasecmp(v->name, "tlscafile")) {
24679 ast_free(default_tls_cfg.cafile);
24680 default_tls_cfg.cafile = ast_strdup(v->value);
24681 } else if (!strcasecmp(v->name, "tlscapath")) {
24682 ast_free(default_tls_cfg.capath);
24683 default_tls_cfg.capath = ast_strdup(v->value);
24684 } else if (!strcasecmp(v->name, "tlsverifyclient")) {
24685 ast_set2_flag(&default_tls_cfg.flags, ast_true(v->value), AST_SSL_VERIFY_CLIENT);
24686 } else if (!strcasecmp(v->name, "tlsdontverifyserver")) {
24687 ast_set2_flag(&default_tls_cfg.flags, ast_true(v->value), AST_SSL_DONT_VERIFY_SERVER);
24688 } else if (!strcasecmp(v->name, "tlsbindaddr")) {
24689 if (ast_parse_arg(v->value, PARSE_INADDR, &sip_tls_desc.local_address))
24690 ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n", v->name, v->value, v->lineno, config);
24691 } else if (!strcasecmp(v->name, "dynamic_exclude_static") || !strcasecmp(v->name, "dynamic_excludes_static")) {
24692 global_dynamic_exclude_static = ast_true(v->value);
24693 } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny")) {
24694 int ha_error = 0;
24695 global_contact_ha = ast_append_ha(v->name + 7, v->value, global_contact_ha, &ha_error);
24696 if (ha_error) {
24697 ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
24698 }
24699 } else if (!strcasecmp(v->name, "rtautoclear")) {
24700 int i = atoi(v->value);
24701 if (i > 0)
24702 sip_cfg.rtautoclear = i;
24703 else
24704 i = 0;
24705 ast_set2_flag(&global_flags[1], i || ast_true(v->value), SIP_PAGE2_RTAUTOCLEAR);
24706 } else if (!strcasecmp(v->name, "usereqphone")) {
24707 ast_set2_flag(&global_flags[0], ast_true(v->value), SIP_USEREQPHONE);
24708 } else if (!strcasecmp(v->name, "prematuremedia")) {
24709 global_prematuremediafilter = ast_true(v->value);
24710 } else if (!strcasecmp(v->name, "relaxdtmf")) {
24711 global_relaxdtmf = ast_true(v->value);
24712 } else if (!strcasecmp(v->name, "vmexten")) {
24713 ast_copy_string(default_vmexten, v->value, sizeof(default_vmexten));
24714 } else if (!strcasecmp(v->name, "rtptimeout")) {
24715 if ((sscanf(v->value, "%30d", &global_rtptimeout) != 1) || (global_rtptimeout < 0)) {
24716 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
24717 global_rtptimeout = 0;
24718 }
24719 } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
24720 if ((sscanf(v->value, "%30d", &global_rtpholdtimeout) != 1) || (global_rtpholdtimeout < 0)) {
24721 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
24722 global_rtpholdtimeout = 0;
24723 }
24724 } else if (!strcasecmp(v->name, "rtpkeepalive")) {
24725 if ((sscanf(v->value, "%30d", &global_rtpkeepalive) != 1) || (global_rtpkeepalive < 0)) {
24726 ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d. Using default.\n", v->value, v->lineno);
24727 global_rtpkeepalive = DEFAULT_RTPKEEPALIVE;
24728 }
24729 } else if (!strcasecmp(v->name, "compactheaders")) {
24730 sip_cfg.compactheaders = ast_true(v->value);
24731 } else if (!strcasecmp(v->name, "notifymimetype")) {
24732 ast_copy_string(default_notifymime, v->value, sizeof(default_notifymime));
24733 } else if (!strcasecmp(v->name, "directrtpsetup")) {
24734 sip_cfg.directrtpsetup = ast_true(v->value);
24735 } else if (!strcasecmp(v->name, "notifyringing")) {
24736 sip_cfg.notifyringing = ast_true(v->value);
24737 } else if (!strcasecmp(v->name, "notifyhold")) {
24738 sip_cfg.notifyhold = ast_true(v->value);
24739 } else if (!strcasecmp(v->name, "notifycid")) {
24740 if (!strcasecmp(v->value, "ignore-context")) {
24741 sip_cfg.notifycid = IGNORE_CONTEXT;
24742 } else {
24743 sip_cfg.notifycid = ast_true(v->value);
24744 }
24745 } else if (!strcasecmp(v->name, "alwaysauthreject")) {
24746 sip_cfg.alwaysauthreject = ast_true(v->value);
24747 } else if (!strcasecmp(v->name, "mohinterpret")) {
24748 ast_copy_string(default_mohinterpret, v->value, sizeof(default_mohinterpret));
24749 } else if (!strcasecmp(v->name, "mohsuggest")) {
24750 ast_copy_string(default_mohsuggest, v->value, sizeof(default_mohsuggest));
24751 } else if (!strcasecmp(v->name, "language")) {
24752 ast_copy_string(default_language, v->value, sizeof(default_language));
24753 } else if (!strcasecmp(v->name, "regcontext")) {
24754 ast_copy_string(newcontexts, v->value, sizeof(newcontexts));
24755 stringp = newcontexts;
24756
24757 cleanup_stale_contexts(stringp, oldregcontext);
24758
24759 while ((context = strsep(&stringp, "&"))) {
24760 ast_copy_string(used_context, context, sizeof(used_context));
24761 ast_context_find_or_create(NULL, NULL, context, "SIP");
24762 }
24763 ast_copy_string(global_regcontext, v->value, sizeof(global_regcontext));
24764 } else if (!strcasecmp(v->name, "regextenonqualify")) {
24765 sip_cfg.regextenonqualify = ast_true(v->value);
24766 } else if (!strcasecmp(v->name, "callerid")) {
24767 ast_copy_string(default_callerid, v->value, sizeof(default_callerid));
24768 } else if (!strcasecmp(v->name, "fromdomain")) {
24769 ast_copy_string(default_fromdomain, v->value, sizeof(default_fromdomain));
24770 } else if (!strcasecmp(v->name, "outboundproxy")) {
24771 int portnum;
24772 char *tok, *proxyname;
24773
24774 if (ast_strlen_zero(v->value)) {
24775 ast_log(LOG_WARNING, "no value given for outbound proxy on line %d of sip.conf.", v->lineno);
24776 continue;
24777 }
24778
24779 tok = ast_skip_blanks(strtok(ast_strdupa(v->value), ","));
24780
24781 sip_parse_host(tok, v->lineno, &proxyname, &portnum, &sip_cfg.outboundproxy.transport);
24782
24783 sip_cfg.outboundproxy.ip.sin_port = htons(portnum);
24784
24785 if ((tok = strtok(NULL, ","))) {
24786 sip_cfg.outboundproxy.force = !strncasecmp(ast_skip_blanks(tok), "force", 5);
24787 } else {
24788 sip_cfg.outboundproxy.force = FALSE;
24789 }
24790
24791 if (ast_strlen_zero(proxyname)) {
24792 ast_log(LOG_WARNING, "you must specify a name for the outboundproxy on line %d of sip.conf.", v->lineno);
24793 sip_cfg.outboundproxy.name[0] = '\0';
24794 continue;
24795 }
24796
24797 ast_copy_string(sip_cfg.outboundproxy.name, proxyname, sizeof(sip_cfg.outboundproxy.name));
24798
24799 proxy_update(&sip_cfg.outboundproxy);
24800 } else if (!strcasecmp(v->name, "autocreatepeer")) {
24801 sip_cfg.autocreatepeer = ast_true(v->value);
24802 } else if (!strcasecmp(v->name, "match_auth_username")) {
24803 global_match_auth_username = ast_true(v->value);
24804 } else if (!strcasecmp(v->name, "srvlookup")) {
24805 sip_cfg.srvlookup = ast_true(v->value);
24806 } else if (!strcasecmp(v->name, "pedantic")) {
24807 sip_cfg.pedanticsipchecking = ast_true(v->value);
24808 } else if (!strcasecmp(v->name, "maxexpirey") || !strcasecmp(v->name, "maxexpiry")) {
24809 max_expiry = atoi(v->value);
24810 if (max_expiry < 1)
24811 max_expiry = DEFAULT_MAX_EXPIRY;
24812 } else if (!strcasecmp(v->name, "minexpirey") || !strcasecmp(v->name, "minexpiry")) {
24813 min_expiry = atoi(v->value);
24814 if (min_expiry < 1)
24815 min_expiry = DEFAULT_MIN_EXPIRY;
24816 } else if (!strcasecmp(v->name, "defaultexpiry") || !strcasecmp(v->name, "defaultexpirey")) {
24817 default_expiry = atoi(v->value);
24818 if (default_expiry < 1)
24819 default_expiry = DEFAULT_DEFAULT_EXPIRY;
24820 } else if (!strcasecmp(v->name, "mwiexpiry") || !strcasecmp(v->name, "mwiexpirey")) {
24821 mwi_expiry = atoi(v->value);
24822 if (mwi_expiry < 1)
24823 mwi_expiry = DEFAULT_MWI_EXPIRY;
24824 } else if (!strcasecmp(v->name, "sipdebug")) {
24825 if (ast_true(v->value))
24826 sipdebug |= sip_debug_config;
24827 } else if (!strcasecmp(v->name, "dumphistory")) {
24828 dumphistory = ast_true(v->value);
24829 } else if (!strcasecmp(v->name, "recordhistory")) {
24830 recordhistory = ast_true(v->value);
24831 } else if (!strcasecmp(v->name, "registertimeout")) {
24832 global_reg_timeout = atoi(v->value);
24833 if (global_reg_timeout < 1)
24834 global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
24835 } else if (!strcasecmp(v->name, "registerattempts")) {
24836 global_regattempts_max = atoi(v->value);
24837 } else if (!strcasecmp(v->name, "stunaddr")) {
24838 stunaddr.sin_port = htons(3478);
24839 if (ast_parse_arg(v->value, PARSE_INADDR, &stunaddr))
24840 ast_log(LOG_WARNING, "Invalid STUN server address: %s\n", v->value);
24841 externexpire = time(NULL);
24842 } else if (!strcasecmp(v->name, "bindaddr") || !strcasecmp(v->name, "udpbindaddr")) {
24843 if (ast_parse_arg(v->value, PARSE_INADDR, &bindaddr))
24844 ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
24845 } else if (!strcasecmp(v->name, "localnet")) {
24846 struct ast_ha *na;
24847 int ha_error = 0;
24848
24849 if (!(na = ast_append_ha("d", v->value, localaddr, &ha_error)))
24850 ast_log(LOG_WARNING, "Invalid localnet value: %s\n", v->value);
24851 else
24852 localaddr = na;
24853 if (ha_error)
24854 ast_log(LOG_ERROR, "Bad localnet configuration value line %d : %s\n", v->lineno, v->value);
24855 } else if (!strcasecmp(v->name, "externip")) {
24856 if (ast_parse_arg(v->value, PARSE_INADDR, &externip))
24857 ast_log(LOG_WARNING, "Invalid address for externip keyword: %s\n", v->value);
24858 externexpire = 0;
24859
24860 if (!externip.sin_port)
24861 externip.sin_port = bindaddr.sin_port;
24862 } else if (!strcasecmp(v->name, "externhost")) {
24863 ast_copy_string(externhost, v->value, sizeof(externhost));
24864 if (ast_parse_arg(externhost, PARSE_INADDR, &externip))
24865 ast_log(LOG_WARNING, "Invalid address for externhost keyword: %s\n", externhost);
24866 externexpire = time(NULL);
24867
24868 if (!externip.sin_port)
24869 externip.sin_port = bindaddr.sin_port;
24870 } else if (!strcasecmp(v->name, "externrefresh")) {
24871 if (sscanf(v->value, "%30d", &externrefresh) != 1) {
24872 ast_log(LOG_WARNING, "Invalid externrefresh value '%s', must be an integer >0 at line %d\n", v->value, v->lineno);
24873 externrefresh = 10;
24874 }
24875 } else if (!strcasecmp(v->name, "allow")) {
24876 int error = ast_parse_allow_disallow(&default_prefs, &global_capability, v->value, TRUE);
24877 if (error)
24878 ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
24879 } else if (!strcasecmp(v->name, "disallow")) {
24880 int error = ast_parse_allow_disallow(&default_prefs, &global_capability, v->value, FALSE);
24881 if (error)
24882 ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
24883 } else if (!strcasecmp(v->name, "autoframing")) {
24884 global_autoframing = ast_true(v->value);
24885 } else if (!strcasecmp(v->name, "allowexternaldomains")) {
24886 sip_cfg.allow_external_domains = ast_true(v->value);
24887 } else if (!strcasecmp(v->name, "autodomain")) {
24888 auto_sip_domains = ast_true(v->value);
24889 } else if (!strcasecmp(v->name, "domain")) {
24890 char *domain = ast_strdupa(v->value);
24891 char *cntx = strchr(domain, ',');
24892
24893 if (cntx)
24894 *cntx++ = '\0';
24895
24896 if (ast_strlen_zero(cntx))
24897 ast_debug(1, "No context specified at line %d for domain '%s'\n", v->lineno, domain);
24898 if (ast_strlen_zero(domain))
24899 ast_log(LOG_WARNING, "Empty domain specified at line %d\n", v->lineno);
24900 else
24901 add_sip_domain(ast_strip(domain), SIP_DOMAIN_CONFIG, cntx ? ast_strip(cntx) : "");
24902 } else if (!strcasecmp(v->name, "register")) {
24903 if (sip_register(v->value, v->lineno) == 0)
24904 registry_count++;
24905 } else if (!strcasecmp(v->name, "mwi")) {
24906 sip_subscribe_mwi(v->value, v->lineno);
24907 } else if (!strcasecmp(v->name, "tos_sip")) {
24908 if (ast_str2tos(v->value, &global_tos_sip))
24909 ast_log(LOG_WARNING, "Invalid tos_sip value at line %d, refer to QoS documentation\n", v->lineno);
24910 } else if (!strcasecmp(v->name, "tos_audio")) {
24911 if (ast_str2tos(v->value, &global_tos_audio))
24912 ast_log(LOG_WARNING, "Invalid tos_audio value at line %d, refer to QoS documentation\n", v->lineno);
24913 } else if (!strcasecmp(v->name, "tos_video")) {
24914 if (ast_str2tos(v->value, &global_tos_video))
24915 ast_log(LOG_WARNING, "Invalid tos_video value at line %d, refer to QoS documentation\n", v->lineno);
24916 } else if (!strcasecmp(v->name, "tos_text")) {
24917 if (ast_str2tos(v->value, &global_tos_text))
24918 ast_log(LOG_WARNING, "Invalid tos_text value at line %d, refer to QoS documentation\n", v->lineno);
24919 } else if (!strcasecmp(v->name, "cos_sip")) {
24920 if (ast_str2cos(v->value, &global_cos_sip))
24921 ast_log(LOG_WARNING, "Invalid cos_sip value at line %d, refer to QoS documentation\n", v->lineno);
24922 } else if (!strcasecmp(v->name, "cos_audio")) {
24923 if (ast_str2cos(v->value, &global_cos_audio))
24924 ast_log(LOG_WARNING, "Invalid cos_audio value at line %d, refer to QoS documentation\n", v->lineno);
24925 } else if (!strcasecmp(v->name, "cos_video")) {
24926 if (ast_str2cos(v->value, &global_cos_video))
24927 ast_log(LOG_WARNING, "Invalid cos_video value at line %d, refer to QoS documentation\n", v->lineno);
24928 } else if (!strcasecmp(v->name, "cos_text")) {
24929 if (ast_str2cos(v->value, &global_cos_text))
24930 ast_log(LOG_WARNING, "Invalid cos_text value at line %d, refer to QoS documentation\n", v->lineno);
24931 } else if (!strcasecmp(v->name, "bindport")) {
24932 int i;
24933 if (sscanf(v->value, "%5d", &i) == 1) {
24934 bindaddr.sin_port = htons(i);
24935 } else {
24936 ast_log(LOG_WARNING, "Invalid port number '%s' at line %d of %s\n", v->value, v->lineno, config);
24937 }
24938 } else if (!strcasecmp(v->name, "hash_user")) {
24939 int i;
24940 if (sscanf(v->value, "%30d", &i) == 1 && i > 2) {
24941 hash_user_size = i;
24942 } else {
24943 ast_log(LOG_WARNING, "Invalid hash_user size '%s' at line %d of %s -- should be much larger than 2\n", v->value, v->lineno, config);
24944 }
24945 } else if (!strcasecmp(v->name, "hash_peer")) {
24946 int i;
24947 if (sscanf(v->value, "%30d", &i) == 1 && i > 2) {
24948 hash_peer_size = i;
24949 } else {
24950 ast_log(LOG_WARNING, "Invalid hash_peer size '%s' at line %d of %s -- should be much larger than 2\n", v->value, v->lineno, config);
24951 }
24952 } else if (!strcasecmp(v->name, "hash_dialog")) {
24953 int i;
24954 if (sscanf(v->value, "%30d", &i) == 1 && i > 2) {
24955 hash_dialog_size = i;
24956 } else {
24957 ast_log(LOG_WARNING, "Invalid hash_dialog size '%s' at line %d of %s -- should be much larger than 2\n", v->value, v->lineno, config);
24958 }
24959 } else if (!strcasecmp(v->name, "qualify")) {
24960 if (!strcasecmp(v->value, "no")) {
24961 default_qualify = 0;
24962 } else if (!strcasecmp(v->value, "yes")) {
24963 default_qualify = DEFAULT_MAXMS;
24964 } else if (sscanf(v->value, "%30d", &default_qualify) != 1) {
24965 ast_log(LOG_WARNING, "Qualification default should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", v->lineno);
24966 default_qualify = 0;
24967 }
24968 } else if (!strcasecmp(v->name, "qualifyfreq")) {
24969 int i;
24970 if (sscanf(v->value, "%30d", &i) == 1)
24971 global_qualifyfreq = i * 1000;
24972 else {
24973 ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
24974 global_qualifyfreq = DEFAULT_QUALIFYFREQ;
24975 }
24976 } else if (!strcasecmp(v->name, "callevents")) {
24977 sip_cfg.callevents = ast_true(v->value);
24978 } else if (!strcasecmp(v->name, "authfailureevents")) {
24979 global_authfailureevents = ast_true(v->value);
24980 } else if (!strcasecmp(v->name, "maxcallbitrate")) {
24981 default_maxcallbitrate = atoi(v->value);
24982 if (default_maxcallbitrate < 0)
24983 default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
24984 } else if (!strcasecmp(v->name, "matchexterniplocally")) {
24985 sip_cfg.matchexterniplocally = ast_true(v->value);
24986 } else if (!strcasecmp(v->name, "session-timers")) {
24987 int i = (int) str2stmode(v->value);
24988 if (i < 0) {
24989 ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
24990 global_st_mode = SESSION_TIMER_MODE_ACCEPT;
24991 } else {
24992 global_st_mode = i;
24993 }
24994 } else if (!strcasecmp(v->name, "session-expires")) {
24995 if (sscanf(v->value, "%30d", &global_max_se) != 1) {
24996 ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
24997 global_max_se = DEFAULT_MAX_SE;
24998 }
24999 } else if (!strcasecmp(v->name, "session-minse")) {
25000 if (sscanf(v->value, "%30d", &global_min_se) != 1) {
25001 ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
25002 global_min_se = DEFAULT_MIN_SE;
25003 }
25004 if (global_min_se < 90) {
25005 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);
25006 global_min_se = DEFAULT_MIN_SE;
25007 }
25008 } else if (!strcasecmp(v->name, "session-refresher")) {
25009 int i = (int) str2strefresher(v->value);
25010 if (i < 0) {
25011 ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
25012 global_st_refresher = SESSION_TIMER_REFRESHER_UAS;
25013 } else {
25014 global_st_refresher = i;
25015 }
25016 } else if (!strcasecmp(v->name, "qualifygap")) {
25017 if (sscanf(v->value, "%30d", &global_qualify_gap) != 1) {
25018 ast_log(LOG_WARNING, "Invalid qualifygap '%s' at line %d of %s\n", v->value, v->lineno, config);
25019 global_qualify_gap = DEFAULT_QUALIFY_GAP;
25020 }
25021 } else if (!strcasecmp(v->name, "qualifypeers")) {
25022 if (sscanf(v->value, "%30d", &global_qualify_peers) != 1) {
25023 ast_log(LOG_WARNING, "Invalid pokepeers '%s' at line %d of %s\n", v->value, v->lineno, config);
25024 global_qualify_peers = DEFAULT_QUALIFY_PEERS;
25025 }
25026 } else if (!strcasecmp(v->name, "shrinkcallerid")) {
25027 if (ast_true(v->value)) {
25028 global_shrinkcallerid = 1;
25029 } else if (ast_false(v->value)) {
25030 global_shrinkcallerid = 0;
25031 } else {
25032 ast_log(LOG_WARNING, "shrinkcallerid value %s is not valid at line %d.\n", v->value, v->lineno);
25033 }
25034 }
25035 }
25036
25037 if (!sip_cfg.allow_external_domains && AST_LIST_EMPTY(&domain_list)) {
25038 ast_log(LOG_WARNING, "To disallow external domains, you need to configure local SIP domains.\n");
25039 sip_cfg.allow_external_domains = 1;
25040 }
25041
25042 if (default_transports == 0) {
25043 default_transports = default_primary_transport = SIP_TRANSPORT_UDP;
25044 }
25045
25046
25047 for (v = ast_variable_browse(cfg, "authentication"); v ; v = v->next) {
25048
25049 if (!strcasecmp(v->name, "auth"))
25050 authl = add_realm_authentication(authl, v->value, v->lineno);
25051 }
25052
25053 if (ucfg) {
25054 struct ast_variable *gen;
25055 int genhassip, genregistersip;
25056 const char *hassip, *registersip;
25057
25058 genhassip = ast_true(ast_variable_retrieve(ucfg, "general", "hassip"));
25059 genregistersip = ast_true(ast_variable_retrieve(ucfg, "general", "registersip"));
25060 gen = ast_variable_browse(ucfg, "general");
25061 cat = ast_category_browse(ucfg, NULL);
25062 while (cat) {
25063 if (strcasecmp(cat, "general")) {
25064 hassip = ast_variable_retrieve(ucfg, cat, "hassip");
25065 registersip = ast_variable_retrieve(ucfg, cat, "registersip");
25066 if (ast_true(hassip) || (!hassip && genhassip)) {
25067 peer = build_peer(cat, gen, ast_variable_browse(ucfg, cat), 0, 0);
25068 if (peer) {
25069
25070 peer->type = SIP_TYPE_USER | SIP_TYPE_PEER;
25071 ao2_t_link(peers, peer, "link peer into peer table");
25072 if ((peer->type & SIP_TYPE_PEER) && peer->addr.sin_addr.s_addr) {
25073 ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
25074 }
25075
25076 unref_peer(peer, "unref_peer: from reload_config");
25077 peer_count++;
25078 }
25079 }
25080 if (ast_true(registersip) || (!registersip && genregistersip)) {
25081 char tmp[256];
25082 const char *host = ast_variable_retrieve(ucfg, cat, "host");
25083 const char *username = ast_variable_retrieve(ucfg, cat, "username");
25084 const char *secret = ast_variable_retrieve(ucfg, cat, "secret");
25085 const char *contact = ast_variable_retrieve(ucfg, cat, "contact");
25086 const char *authuser = ast_variable_retrieve(ucfg, cat, "authuser");
25087 if (!host)
25088 host = ast_variable_retrieve(ucfg, "general", "host");
25089 if (!username)
25090 username = ast_variable_retrieve(ucfg, "general", "username");
25091 if (!secret)
25092 secret = ast_variable_retrieve(ucfg, "general", "secret");
25093 if (!contact)
25094 contact = "s";
25095 if (!ast_strlen_zero(username) && !ast_strlen_zero(host)) {
25096 if (!ast_strlen_zero(secret)) {
25097 if (!ast_strlen_zero(authuser)) {
25098 snprintf(tmp, sizeof(tmp), "%s:%s:%s@%s/%s", username, secret, authuser, host, contact);
25099 } else {
25100 snprintf(tmp, sizeof(tmp), "%s:%s@%s/%s", username, secret, host, contact);
25101 }
25102 } else if (!ast_strlen_zero(authuser)) {
25103 snprintf(tmp, sizeof(tmp), "%s::%s@%s/%s", username, authuser, host, contact);
25104 } else {
25105 snprintf(tmp, sizeof(tmp), "%s@%s/%s", username, host, contact);
25106 }
25107 if (sip_register(tmp, 0) == 0)
25108 registry_count++;
25109 }
25110 }
25111 }
25112 cat = ast_category_browse(ucfg, cat);
25113 }
25114 ast_config_destroy(ucfg);
25115 }
25116
25117
25118
25119 cat = NULL;
25120 while ( (cat = ast_category_browse(cfg, cat)) ) {
25121 const char *utype;
25122 if (!strcasecmp(cat, "general") || !strcasecmp(cat, "authentication"))
25123 continue;
25124 utype = ast_variable_retrieve(cfg, cat, "type");
25125 if (!utype) {
25126 ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
25127 continue;
25128 } else {
25129 if (!strcasecmp(utype, "user")) {
25130 ;
25131 } else if (!strcasecmp(utype, "friend")) {
25132 ;
25133 } else if (!strcasecmp(utype, "peer")) {
25134 ;
25135 } else {
25136 ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, "sip.conf");
25137 continue;
25138 }
25139 peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0, 0);
25140 if (peer) {
25141 ao2_t_link(peers, peer, "link peer into peers table");
25142 if ((peer->type & SIP_TYPE_PEER) && peer->addr.sin_addr.s_addr) {
25143 ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
25144 }
25145 unref_peer(peer, "unref the result of the build_peer call. Now, the links from the tables are the only ones left.");
25146 peer_count++;
25147 }
25148 }
25149 }
25150
25151
25152 bindaddr.sin_family = AF_INET;
25153 internip = bindaddr;
25154 if (ast_find_ourip(&internip.sin_addr, bindaddr)) {
25155 ast_log(LOG_WARNING, "Unable to get own IP address, SIP disabled\n");
25156 ast_config_destroy(cfg);
25157 return 0;
25158 }
25159 ast_mutex_lock(&netlock);
25160 if ((sipsock > -1) && (memcmp(&old_bindaddr, &bindaddr, sizeof(struct sockaddr_in)))) {
25161 close(sipsock);
25162 sipsock = -1;
25163 }
25164 if (sipsock < 0) {
25165 sipsock = socket(AF_INET, SOCK_DGRAM, 0);
25166 if (sipsock < 0) {
25167 ast_log(LOG_WARNING, "Unable to create SIP socket: %s\n", strerror(errno));
25168 ast_config_destroy(cfg);
25169 return -1;
25170 } else {
25171
25172 const int reuseFlag = 1;
25173
25174 setsockopt(sipsock, SOL_SOCKET, SO_REUSEADDR,
25175 (const char*)&reuseFlag,
25176 sizeof reuseFlag);
25177
25178 ast_enable_packet_fragmentation(sipsock);
25179
25180 if (bind(sipsock, (struct sockaddr *)&bindaddr, sizeof(bindaddr)) < 0) {
25181 ast_log(LOG_WARNING, "Failed to bind to %s:%d: %s\n",
25182 ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port),
25183 strerror(errno));
25184 close(sipsock);
25185 sipsock = -1;
25186 } else {
25187 ast_verb(2, "SIP Listening on %s:%d\n",
25188 ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port));
25189 ast_netsock_set_qos(sipsock, global_tos_sip, global_cos_sip, "SIP");
25190 }
25191 }
25192 }
25193 if (stunaddr.sin_addr.s_addr != 0) {
25194 ast_debug(1, "stun to %s:%d\n",
25195 ast_inet_ntoa(stunaddr.sin_addr) , ntohs(stunaddr.sin_port));
25196 ast_stun_request(sipsock, &stunaddr,
25197 NULL, &externip);
25198 ast_debug(1, "STUN sees us at %s:%d\n",
25199 ast_inet_ntoa(externip.sin_addr) , ntohs(externip.sin_port));
25200 }
25201 ast_mutex_unlock(&netlock);
25202
25203
25204 ast_tcptls_server_start(&sip_tcp_desc);
25205 if (sip_tcp_desc.accept_fd == -1 && sip_tcp_desc.local_address.sin_family == AF_INET) {
25206
25207 ast_log(LOG_ERROR, "SIP TCP Server start failed. Not listening on TCP socket.\n");
25208 sip_tcp_desc.local_address.sin_family = 0;
25209 } else {
25210 ast_debug(2, "SIP TCP server started\n");
25211 }
25212
25213
25214 memcpy(sip_tls_desc.tls_cfg, &default_tls_cfg, sizeof(default_tls_cfg));
25215
25216 if (ast_ssl_setup(sip_tls_desc.tls_cfg)) {
25217 ast_tcptls_server_start(&sip_tls_desc);
25218 if (default_tls_cfg.enabled && sip_tls_desc.accept_fd == -1) {
25219 ast_log(LOG_ERROR, "TLS Server start failed. Not listening on TLS socket.\n");
25220 sip_tls_desc.tls_cfg = NULL;
25221 }
25222 } else if (sip_tls_desc.tls_cfg->enabled) {
25223 sip_tls_desc.tls_cfg = NULL;
25224 ast_log(LOG_WARNING, "SIP TLS server did not load because of errors.\n");
25225 }
25226
25227
25228
25229
25230
25231
25232
25233 if (auto_sip_domains) {
25234 char temp[MAXHOSTNAMELEN];
25235
25236
25237 if (bindaddr.sin_addr.s_addr) {
25238 add_sip_domain(ast_inet_ntoa(bindaddr.sin_addr), SIP_DOMAIN_AUTO, NULL);
25239 } else if (internip.sin_addr.s_addr) {
25240
25241 add_sip_domain(ast_inet_ntoa(internip.sin_addr), SIP_DOMAIN_AUTO, NULL);
25242 } else {
25243 ast_log(LOG_NOTICE, "Can't add wildcard IP address to domain list, please add IP address to domain manually.\n");
25244 }
25245
25246
25247 if (sip_tcp_desc.local_address.sin_addr.s_addr && !inaddrcmp(&bindaddr, &sip_tcp_desc.local_address))
25248 add_sip_domain(ast_inet_ntoa(sip_tcp_desc.local_address.sin_addr), SIP_DOMAIN_AUTO, NULL);
25249
25250
25251 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))
25252 add_sip_domain(ast_inet_ntoa(sip_tls_desc.local_address.sin_addr), SIP_DOMAIN_AUTO, NULL);
25253
25254
25255 if (externip.sin_addr.s_addr)
25256 add_sip_domain(ast_inet_ntoa(externip.sin_addr), SIP_DOMAIN_AUTO, NULL);
25257
25258
25259 if (!ast_strlen_zero(externhost))
25260 add_sip_domain(externhost, SIP_DOMAIN_AUTO, NULL);
25261
25262
25263 if (!gethostname(temp, sizeof(temp)))
25264 add_sip_domain(temp, SIP_DOMAIN_AUTO, NULL);
25265 }
25266
25267
25268 ast_config_destroy(cfg);
25269
25270
25271 if (notify_types)
25272 ast_config_destroy(notify_types);
25273 if ((notify_types = ast_config_load(notify_config, config_flags)) == CONFIG_STATUS_FILEINVALID) {
25274 ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed.\n", notify_config);
25275 notify_types = NULL;
25276 }
25277
25278
25279 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);
25280 run_end = time(0);
25281 ast_debug(4, "SIP reload_config done...Runtime= %d sec\n", (int)(run_end-run_start));
25282
25283 return 0;
25284 }
25285
25286 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan)
25287 {
25288 struct sip_pvt *p;
25289 struct ast_udptl *udptl = NULL;
25290
25291 p = chan->tech_pvt;
25292 if (!p)
25293 return NULL;
25294
25295 sip_pvt_lock(p);
25296 if (p->udptl && ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA))
25297 udptl = p->udptl;
25298 sip_pvt_unlock(p);
25299 return udptl;
25300 }
25301
25302 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl)
25303 {
25304 struct sip_pvt *p;
25305
25306 p = chan->tech_pvt;
25307 if (!p)
25308 return -1;
25309 sip_pvt_lock(p);
25310 if (udptl)
25311 ast_udptl_get_peer(udptl, &p->udptlredirip);
25312 else
25313 memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
25314 if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
25315 if (!p->pendinginvite) {
25316 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);
25317 transmit_reinvite_with_sdp(p, TRUE, FALSE);
25318 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
25319 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);
25320 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
25321 }
25322 }
25323
25324 p->lastrtprx = p->lastrtptx = time(NULL);
25325 sip_pvt_unlock(p);
25326 return 0;
25327 }
25328
25329
25330 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
25331 {
25332 struct sip_pvt *p = NULL;
25333 enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
25334
25335 if (!(p = chan->tech_pvt))
25336 return AST_RTP_GET_FAILED;
25337
25338 sip_pvt_lock(p);
25339 if (!(p->rtp)) {
25340 sip_pvt_unlock(p);
25341 return AST_RTP_GET_FAILED;
25342 }
25343
25344 *rtp = p->rtp;
25345
25346 if (ast_rtp_getnat(*rtp) && !ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA_NAT))
25347 res = AST_RTP_TRY_PARTIAL;
25348 else if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA))
25349 res = AST_RTP_TRY_NATIVE;
25350 else if (ast_test_flag(&global_jbconf, AST_JB_FORCED))
25351 res = AST_RTP_GET_FAILED;
25352
25353 sip_pvt_unlock(p);
25354
25355 return res;
25356 }
25357
25358
25359 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
25360 {
25361 struct sip_pvt *p = NULL;
25362 enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
25363
25364 if (!(p = chan->tech_pvt))
25365 return AST_RTP_GET_FAILED;
25366
25367 sip_pvt_lock(p);
25368 if (!(p->vrtp)) {
25369 sip_pvt_unlock(p);
25370 return AST_RTP_GET_FAILED;
25371 }
25372
25373 *rtp = p->vrtp;
25374
25375 if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA))
25376 res = AST_RTP_TRY_NATIVE;
25377
25378 sip_pvt_unlock(p);
25379
25380 return res;
25381 }
25382
25383
25384 static enum ast_rtp_get_result sip_get_trtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
25385 {
25386 struct sip_pvt *p = NULL;
25387 enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
25388
25389 if (!(p = chan->tech_pvt))
25390 return AST_RTP_GET_FAILED;
25391
25392 sip_pvt_lock(p);
25393 if (!(p->trtp)) {
25394 sip_pvt_unlock(p);
25395 return AST_RTP_GET_FAILED;
25396 }
25397
25398 *rtp = p->trtp;
25399
25400 if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA))
25401 res = AST_RTP_TRY_NATIVE;
25402
25403 sip_pvt_unlock(p);
25404
25405 return res;
25406 }
25407
25408
25409 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)
25410 {
25411 struct sip_pvt *p;
25412 int changed = 0;
25413
25414 p = chan->tech_pvt;
25415 if (!p)
25416 return -1;
25417
25418
25419 if (!ast_bridged_channel(chan) && !sip_cfg.directrtpsetup)
25420 return 0;
25421
25422 sip_pvt_lock(p);
25423 if (p->alreadygone) {
25424
25425 sip_pvt_unlock(p);
25426 return 0;
25427 }
25428
25429
25430
25431
25432 if (nat_active && !ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA_NAT)) {
25433 sip_pvt_unlock(p);
25434 return 0;
25435 }
25436
25437 if (rtp) {
25438 changed |= ast_rtp_get_peer(rtp, &p->redirip);
25439 } else if (p->redirip.sin_addr.s_addr || ntohs(p->redirip.sin_port) != 0) {
25440 memset(&p->redirip, 0, sizeof(p->redirip));
25441 changed = 1;
25442 }
25443 if (vrtp) {
25444 changed |= ast_rtp_get_peer(vrtp, &p->vredirip);
25445 } else if (p->vredirip.sin_addr.s_addr || ntohs(p->vredirip.sin_port) != 0) {
25446 memset(&p->vredirip, 0, sizeof(p->vredirip));
25447 changed = 1;
25448 }
25449 if (trtp) {
25450 changed |= ast_rtp_get_peer(trtp, &p->tredirip);
25451 } else if (p->tredirip.sin_addr.s_addr || ntohs(p->tredirip.sin_port) != 0) {
25452 memset(&p->tredirip, 0, sizeof(p->tredirip));
25453 changed = 1;
25454 }
25455 if (codecs && (p->redircodecs != codecs)) {
25456 p->redircodecs = codecs;
25457 changed = 1;
25458 }
25459 if (changed && !ast_test_flag(&p->flags[0], SIP_GOTREFER) && !ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
25460 if (chan->_state != AST_STATE_UP) {
25461 if (p->do_history)
25462 append_history(p, "ExtInv", "Initial invite sent with remote bridge proposal.");
25463 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));
25464 } else if (!p->pendinginvite) {
25465 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));
25466 transmit_reinvite_with_sdp(p, FALSE, FALSE);
25467 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
25468 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));
25469
25470 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
25471 }
25472 }
25473
25474 p->lastrtprx = p->lastrtptx = time(NULL);
25475 sip_pvt_unlock(p);
25476 return 0;
25477 }
25478
25479 static char *app_dtmfmode = "SIPDtmfMode";
25480 static char *app_sipaddheader = "SIPAddHeader";
25481 static char *app_sipremoveheader = "SIPRemoveHeader";
25482
25483
25484 static int sip_dtmfmode(struct ast_channel *chan, void *data)
25485 {
25486 struct sip_pvt *p;
25487 char *mode = data;
25488
25489 if (!data) {
25490 ast_log(LOG_WARNING, "This application requires the argument: info, inband, rfc2833\n");
25491 return 0;
25492 }
25493 ast_channel_lock(chan);
25494 if (!IS_SIP_TECH(chan->tech)) {
25495 ast_log(LOG_WARNING, "Call this application only on SIP incoming calls\n");
25496 ast_channel_unlock(chan);
25497 return 0;
25498 }
25499 p = chan->tech_pvt;
25500 if (!p) {
25501 ast_channel_unlock(chan);
25502 return 0;
25503 }
25504 sip_pvt_lock(p);
25505 if (!strcasecmp(mode, "info")) {
25506 ast_clear_flag(&p->flags[0], SIP_DTMF);
25507 ast_set_flag(&p->flags[0], SIP_DTMF_INFO);
25508 p->jointnoncodeccapability &= ~AST_RTP_DTMF;
25509 } else if (!strcasecmp(mode, "shortinfo")) {
25510 ast_clear_flag(&p->flags[0], SIP_DTMF);
25511 ast_set_flag(&p->flags[0], SIP_DTMF_SHORTINFO);
25512 p->jointnoncodeccapability &= ~AST_RTP_DTMF;
25513 } else if (!strcasecmp(mode, "rfc2833")) {
25514 ast_clear_flag(&p->flags[0], SIP_DTMF);
25515 ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
25516 p->jointnoncodeccapability |= AST_RTP_DTMF;
25517 } else if (!strcasecmp(mode, "inband")) {
25518 ast_clear_flag(&p->flags[0], SIP_DTMF);
25519 ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
25520 p->jointnoncodeccapability &= ~AST_RTP_DTMF;
25521 } else
25522 ast_log(LOG_WARNING, "I don't know about this dtmf mode: %s\n", mode);
25523 if (p->rtp)
25524 ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
25525 if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
25526 if (!p->dsp) {
25527 p->dsp = ast_dsp_new();
25528 ast_dsp_set_features(p->dsp, DSP_FEATURE_DIGIT_DETECT);
25529 }
25530 } else {
25531 if (p->dsp) {
25532 ast_dsp_free(p->dsp);
25533 p->dsp = NULL;
25534 }
25535 }
25536 sip_pvt_unlock(p);
25537 ast_channel_unlock(chan);
25538 return 0;
25539 }
25540
25541
25542 static int sip_addheader(struct ast_channel *chan, void *data)
25543 {
25544 int no = 0;
25545 int ok = FALSE;
25546 char varbuf[30];
25547 char *inbuf = data, *subbuf;
25548
25549 if (ast_strlen_zero(inbuf)) {
25550 ast_log(LOG_WARNING, "This application requires the argument: Header\n");
25551 return 0;
25552 }
25553 ast_channel_lock(chan);
25554
25555
25556 while (!ok && no <= 50) {
25557 no++;
25558 snprintf(varbuf, sizeof(varbuf), "__SIPADDHEADER%.2d", no);
25559
25560
25561 if ((pbx_builtin_getvar_helper(chan, (const char *) varbuf + 2) == (const char *) NULL)) {
25562 ok = TRUE;
25563 }
25564 }
25565 if (ok) {
25566 size_t len = strlen(inbuf);
25567 subbuf = alloca(len + 1);
25568 ast_get_encoded_str(inbuf, subbuf, len + 1);
25569 pbx_builtin_setvar_helper(chan, varbuf, subbuf);
25570 if (sipdebug) {
25571 ast_debug(1, "SIP Header added \"%s\" as %s\n", inbuf, varbuf);
25572 }
25573 } else {
25574 ast_log(LOG_WARNING, "Too many SIP headers added, max 50\n");
25575 }
25576 ast_channel_unlock(chan);
25577 return 0;
25578 }
25579
25580
25581 static int sip_removeheader(struct ast_channel *chan, void *data)
25582 {
25583 struct ast_var_t *newvariable;
25584 struct varshead *headp;
25585 int removeall = 0;
25586 char *inbuf = (char *) data;
25587
25588 if (ast_strlen_zero(inbuf)) {
25589 removeall = 1;
25590 }
25591 ast_channel_lock(chan);
25592
25593 headp=&chan->varshead;
25594 AST_LIST_TRAVERSE_SAFE_BEGIN (headp, newvariable, entries) {
25595 if (strncasecmp(ast_var_name(newvariable), "SIPADDHEADER", strlen("SIPADDHEADER")) == 0) {
25596 if (removeall || (!strncasecmp(ast_var_value(newvariable),inbuf,strlen(inbuf)))) {
25597 if (sipdebug)
25598 ast_log(LOG_DEBUG,"removing SIP Header \"%s\" as %s\n",
25599 ast_var_value(newvariable),
25600 ast_var_name(newvariable));
25601 AST_LIST_REMOVE_CURRENT(entries);
25602 ast_var_delete(newvariable);
25603 }
25604 }
25605 }
25606 AST_LIST_TRAVERSE_SAFE_END;
25607
25608 ast_channel_unlock(chan);
25609 return 0;
25610 }
25611
25612
25613
25614
25615
25616
25617
25618 static int sip_sipredirect(struct sip_pvt *p, const char *dest)
25619 {
25620 char *cdest;
25621 char *extension, *host, *port;
25622 char tmp[80];
25623
25624 cdest = ast_strdupa(dest);
25625
25626 extension = strsep(&cdest, "@");
25627 host = strsep(&cdest, ":");
25628 port = strsep(&cdest, ":");
25629 if (ast_strlen_zero(extension)) {
25630 ast_log(LOG_ERROR, "Missing mandatory argument: extension\n");
25631 return 0;
25632 }
25633
25634
25635 if (!host) {
25636 char *localtmp;
25637
25638 ast_copy_string(tmp, get_header(&p->initreq, "To"), sizeof(tmp));
25639 if (ast_strlen_zero(tmp)) {
25640 ast_log(LOG_ERROR, "Cannot retrieve the 'To' header from the original SIP request!\n");
25641 return 0;
25642 }
25643 if ( ( (localtmp = strcasestr(tmp, "sip:")) || (localtmp = strcasestr(tmp, "sips:")) )
25644 && (localtmp = strchr(localtmp, '@'))) {
25645 char lhost[80], lport[80];
25646
25647 memset(lhost, 0, sizeof(lhost));
25648 memset(lport, 0, sizeof(lport));
25649 localtmp++;
25650
25651 sscanf(localtmp, "%80[^<>:; ]:%80[^<>:; ]", lhost, lport);
25652 if (ast_strlen_zero(lhost)) {
25653 ast_log(LOG_ERROR, "Can't find the host address\n");
25654 return 0;
25655 }
25656 host = ast_strdupa(lhost);
25657 if (!ast_strlen_zero(lport)) {
25658 port = ast_strdupa(lport);
25659 }
25660 }
25661 }
25662
25663 ast_string_field_build(p, our_contact, "Transfer <sip:%s@%s%s%s>", extension, host, port ? ":" : "", port ? port : "");
25664 transmit_response_reliable(p, "302 Moved Temporarily", &p->initreq);
25665
25666 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
25667 sip_alreadygone(p);
25668
25669 return 0;
25670 }
25671
25672
25673 static int sip_get_codec(struct ast_channel *chan)
25674 {
25675 struct sip_pvt *p = chan->tech_pvt;
25676 return p->jointcapability ? p->jointcapability : p->capability;
25677 }
25678
25679
25680 static void sip_poke_all_peers(void)
25681 {
25682 int ms = 0, num = 0;
25683 struct ao2_iterator i;
25684 struct sip_peer *peer;
25685
25686 if (!speerobjs)
25687 return;
25688
25689 i = ao2_iterator_init(peers, 0);
25690 while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
25691 ao2_lock(peer);
25692 if (num == global_qualify_peers) {
25693 ms += global_qualify_gap;
25694 num = 0;
25695 } else {
25696 num++;
25697 }
25698 AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, ms, sip_poke_peer_s, peer,
25699 unref_peer(_data, "removing poke peer ref"),
25700 unref_peer(peer, "removing poke peer ref"),
25701 ref_peer(peer, "adding poke peer ref"));
25702 ao2_unlock(peer);
25703 unref_peer(peer, "toss iterator peer ptr");
25704 }
25705 ao2_iterator_destroy(&i);
25706 }
25707
25708
25709 static void sip_send_all_registers(void)
25710 {
25711 int ms;
25712 int regspacing;
25713 if (!regobjs)
25714 return;
25715 regspacing = default_expiry * 1000/regobjs;
25716 if (regspacing > 100)
25717 regspacing = 100;
25718 ms = regspacing;
25719 ASTOBJ_CONTAINER_TRAVERSE(®l, 1, do {
25720 ASTOBJ_WRLOCK(iterator);
25721 ms += regspacing;
25722 AST_SCHED_REPLACE_UNREF(iterator->expire, sched, ms, sip_reregister, iterator,
25723 registry_unref(_data, "REPLACE sched del decs the refcount"),
25724 registry_unref(iterator, "REPLACE sched add failure decs the refcount"),
25725 registry_addref(iterator, "REPLACE sched add incs the refcount"));
25726 ASTOBJ_UNLOCK(iterator);
25727 } while (0)
25728 );
25729 }
25730
25731
25732 static void sip_send_all_mwi_subscriptions(void)
25733 {
25734 ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
25735 ASTOBJ_WRLOCK(iterator);
25736 AST_SCHED_DEL(sched, iterator->resub);
25737 if ((iterator->resub = ast_sched_add(sched, 1, sip_subscribe_mwi_do, ASTOBJ_REF(iterator))) < 0) {
25738 ASTOBJ_UNREF(iterator, sip_subscribe_mwi_destroy);
25739 }
25740 ASTOBJ_UNLOCK(iterator);
25741 } while (0));
25742 }
25743
25744
25745 static int sip_do_reload(enum channelreloadreason reason)
25746 {
25747 time_t start_poke, end_poke;
25748
25749 reload_config(reason);
25750 ast_sched_dump(sched);
25751
25752 start_poke = time(0);
25753
25754 ao2_t_callback(peers, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, peer_is_marked, NULL,
25755 "callback to remove marked peers");
25756
25757 ast_debug(4, "--------------- Done destroying pruned peers\n");
25758
25759
25760 sip_poke_all_peers();
25761
25762
25763 sip_send_all_registers();
25764
25765 sip_send_all_mwi_subscriptions();
25766
25767 end_poke = time(0);
25768
25769 ast_debug(4, "do_reload finished. peer poke/prune reg contact time = %d sec.\n", (int)(end_poke-start_poke));
25770
25771 ast_debug(4, "--------------- SIP reload done\n");
25772
25773 return 0;
25774 }
25775
25776
25777 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
25778 {
25779
25780 switch (cmd) {
25781 case CLI_INIT:
25782 e->command = "sip reload";
25783 e->usage =
25784 "Usage: sip reload\n"
25785 " Reloads SIP configuration from sip.conf\n";
25786 return NULL;
25787 case CLI_GENERATE:
25788 return NULL;
25789 }
25790
25791 ast_mutex_lock(&sip_reload_lock);
25792 if (sip_reloading)
25793 ast_verbose("Previous SIP reload not yet done\n");
25794 else {
25795 sip_reloading = TRUE;
25796 sip_reloadreason = (a && a->fd) ? CHANNEL_CLI_RELOAD : CHANNEL_MODULE_RELOAD;
25797 }
25798 ast_mutex_unlock(&sip_reload_lock);
25799 restart_monitor();
25800
25801 return CLI_SUCCESS;
25802 }
25803
25804
25805 static int reload(void)
25806 {
25807 if (sip_reload(0, 0, NULL))
25808 return 0;
25809 return 1;
25810 }
25811
25812
25813 static struct ast_cli_entry cli_sip[] = {
25814 AST_CLI_DEFINE(sip_show_channels, "List active SIP channels or subscriptions"),
25815 AST_CLI_DEFINE(sip_show_channelstats, "List statistics for active SIP channels"),
25816 AST_CLI_DEFINE(sip_show_domains, "List our local SIP domains"),
25817 AST_CLI_DEFINE(sip_show_inuse, "List all inuse/limits"),
25818 AST_CLI_DEFINE(sip_show_objects, "List all SIP object allocations"),
25819 AST_CLI_DEFINE(sip_show_peers, "List defined SIP peers"),
25820 AST_CLI_DEFINE(sip_show_registry, "List SIP registration status"),
25821 AST_CLI_DEFINE(sip_unregister, "Unregister (force expiration) a SIP peer from the registry"),
25822 AST_CLI_DEFINE(sip_show_settings, "Show SIP global settings"),
25823 AST_CLI_DEFINE(sip_show_mwi, "Show MWI subscriptions"),
25824 AST_CLI_DEFINE(sip_cli_notify, "Send a notify packet to a SIP peer"),
25825 AST_CLI_DEFINE(sip_show_channel, "Show detailed SIP channel info"),
25826 AST_CLI_DEFINE(sip_show_history, "Show SIP dialog history"),
25827 AST_CLI_DEFINE(sip_show_peer, "Show details on specific SIP peer"),
25828 AST_CLI_DEFINE(sip_show_users, "List defined SIP users"),
25829 AST_CLI_DEFINE(sip_show_user, "Show details on specific SIP user"),
25830 AST_CLI_DEFINE(sip_qualify_peer, "Send an OPTIONS packet to a peer"),
25831 AST_CLI_DEFINE(sip_show_sched, "Present a report on the status of the sched queue"),
25832 AST_CLI_DEFINE(sip_prune_realtime, "Prune cached Realtime users/peers"),
25833 AST_CLI_DEFINE(sip_do_debug, "Enable/Disable SIP debugging"),
25834 AST_CLI_DEFINE(sip_set_history, "Enable/Disable SIP history"),
25835 AST_CLI_DEFINE(sip_reload, "Reload SIP configuration"),
25836 AST_CLI_DEFINE(sip_show_tcp, "List TCP Connections")
25837 };
25838
25839
25840 static int load_module(void)
25841 {
25842 ast_verbose("SIP channel loading...\n");
25843
25844
25845 peers = ao2_t_container_alloc(hash_peer_size, peer_hash_cb, peer_cmp_cb, "allocate peers");
25846 peers_by_ip = ao2_t_container_alloc(hash_peer_size, peer_iphash_cb, peer_ipcmp_cb, "allocate peers_by_ip");
25847 dialogs = ao2_t_container_alloc(hash_dialog_size, dialog_hash_cb, dialog_cmp_cb, "allocate dialogs");
25848 threadt = ao2_t_container_alloc(hash_dialog_size, threadt_hash_cb, threadt_cmp_cb, "allocate threadt table");
25849
25850 ASTOBJ_CONTAINER_INIT(®l);
25851 ASTOBJ_CONTAINER_INIT(&submwil);
25852
25853 if (!(sched = sched_context_create())) {
25854 ast_log(LOG_ERROR, "Unable to create scheduler context\n");
25855 return AST_MODULE_LOAD_FAILURE;
25856 }
25857
25858 if (!(io = io_context_create())) {
25859 ast_log(LOG_ERROR, "Unable to create I/O context\n");
25860 sched_context_destroy(sched);
25861 return AST_MODULE_LOAD_FAILURE;
25862 }
25863
25864 sip_reloadreason = CHANNEL_MODULE_LOAD;
25865
25866 if(reload_config(sip_reloadreason))
25867 return AST_MODULE_LOAD_DECLINE;
25868
25869
25870
25871
25872
25873 memcpy(&sip_tech_info, &sip_tech, sizeof(sip_tech));
25874 memset((void *) &sip_tech_info.send_digit_begin, 0, sizeof(sip_tech_info.send_digit_begin));
25875
25876
25877 if (ast_channel_register(&sip_tech)) {
25878 ast_log(LOG_ERROR, "Unable to register channel type 'SIP'\n");
25879 io_context_destroy(io);
25880 sched_context_destroy(sched);
25881 return AST_MODULE_LOAD_FAILURE;
25882 }
25883
25884
25885 ast_cli_register_multiple(cli_sip, ARRAY_LEN(cli_sip));
25886
25887
25888 ast_rtp_proto_register(&sip_rtp);
25889
25890
25891 ast_udptl_proto_register(&sip_udptl);
25892
25893
25894 ast_register_application_xml(app_dtmfmode, sip_dtmfmode);
25895 ast_register_application_xml(app_sipaddheader, sip_addheader);
25896 ast_register_application_xml(app_sipremoveheader, sip_removeheader);
25897
25898
25899 ast_custom_function_register(&sip_header_function);
25900 ast_custom_function_register(&sippeer_function);
25901 ast_custom_function_register(&sipchaninfo_function);
25902 ast_custom_function_register(&checksipdomain_function);
25903
25904
25905 ast_manager_register2("SIPpeers", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peers,
25906 "List SIP peers (text format)", mandescr_show_peers);
25907 ast_manager_register2("SIPshowpeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peer,
25908 "Show SIP peer (text format)", mandescr_show_peer);
25909 ast_manager_register2("SIPqualifypeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_qualify_peer,
25910 "Show SIP peer (text format)", mandescr_show_peer);
25911 ast_manager_register2("SIPshowregistry", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_show_registry,
25912 "Show SIP registrations (text format)", mandescr_show_registry);
25913 ast_manager_register2("SIPnotify", EVENT_FLAG_SYSTEM, manager_sipnotify,
25914 "Send a SIP notify", mandescr_sipnotify);
25915 sip_poke_all_peers();
25916 sip_send_all_registers();
25917 sip_send_all_mwi_subscriptions();
25918
25919
25920 restart_monitor();
25921
25922 ast_realtime_require_field(ast_check_realtime("sipregs") ? "sipregs" : "sippeers",
25923 "name", RQ_CHAR, 10,
25924 "ipaddr", RQ_CHAR, 15,
25925 "port", RQ_UINTEGER2, 5,
25926 "regseconds", RQ_INTEGER4, 11,
25927 "defaultuser", RQ_CHAR, 10,
25928 "fullcontact", RQ_CHAR, 35,
25929 "regserver", RQ_CHAR, 20,
25930 "useragent", RQ_CHAR, 20,
25931 "lastms", RQ_INTEGER4, 11,
25932 SENTINEL);
25933
25934 return AST_MODULE_LOAD_SUCCESS;
25935 }
25936
25937
25938 static int unload_module(void)
25939 {
25940 struct sip_pvt *p;
25941 struct sip_threadinfo *th;
25942 struct ast_context *con;
25943 struct ao2_iterator i;
25944
25945 ast_sched_dump(sched);
25946
25947
25948 ast_channel_unregister(&sip_tech);
25949
25950
25951 ast_custom_function_unregister(&sipchaninfo_function);
25952 ast_custom_function_unregister(&sippeer_function);
25953 ast_custom_function_unregister(&sip_header_function);
25954 ast_custom_function_unregister(&checksipdomain_function);
25955
25956
25957 ast_unregister_application(app_dtmfmode);
25958 ast_unregister_application(app_sipaddheader);
25959 ast_unregister_application(app_sipremoveheader);
25960
25961
25962 ast_cli_unregister_multiple(cli_sip, ARRAY_LEN(cli_sip));
25963
25964
25965 ast_rtp_proto_unregister(&sip_rtp);
25966
25967
25968 ast_udptl_proto_unregister(&sip_udptl);
25969
25970
25971 ast_manager_unregister("SIPpeers");
25972 ast_manager_unregister("SIPshowpeer");
25973 ast_manager_unregister("SIPqualifypeer");
25974 ast_manager_unregister("SIPshowregistry");
25975 ast_manager_unregister("SIPnotify");
25976
25977
25978 if (sip_tcp_desc.master)
25979 ast_tcptls_server_stop(&sip_tcp_desc);
25980 if (sip_tls_desc.master)
25981 ast_tcptls_server_stop(&sip_tls_desc);
25982
25983
25984 i = ao2_iterator_init(threadt, 0);
25985 while ((th = ao2_t_iterator_next(&i, "iterate through tcp threads for 'sip show tcp'"))) {
25986 pthread_t thread = th->threadid;
25987 th->stop = 1;
25988 pthread_kill(thread, SIGURG);
25989 pthread_join(thread, NULL);
25990 ao2_t_ref(th, -1, "decrement ref from iterator");
25991 }
25992 ao2_iterator_destroy(&i);
25993
25994
25995 i = ao2_iterator_init(dialogs, 0);
25996 while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
25997 if (p->owner)
25998 ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
25999 ao2_t_ref(p, -1, "toss dialog ptr from iterator_next");
26000 }
26001 ao2_iterator_destroy(&i);
26002
26003 ast_mutex_lock(&monlock);
26004 if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP) && (monitor_thread != AST_PTHREADT_NULL)) {
26005 pthread_cancel(monitor_thread);
26006 pthread_kill(monitor_thread, SIGURG);
26007 pthread_join(monitor_thread, NULL);
26008 }
26009 monitor_thread = AST_PTHREADT_STOP;
26010 ast_mutex_unlock(&monlock);
26011
26012
26013 i = ao2_iterator_init(dialogs, 0);
26014 while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
26015 dialog_unlink_all(p, TRUE, TRUE);
26016 ao2_t_ref(p, -1, "throw away iterator result");
26017 }
26018 ao2_iterator_destroy(&i);
26019
26020
26021 ast_free_ha(localaddr);
26022
26023 clear_realm_authentication(authl);
26024
26025
26026 if (default_tls_cfg.certfile)
26027 ast_free(default_tls_cfg.certfile);
26028 if (default_tls_cfg.cipher)
26029 ast_free(default_tls_cfg.cipher);
26030 if (default_tls_cfg.cafile)
26031 ast_free(default_tls_cfg.cafile);
26032 if (default_tls_cfg.capath)
26033 ast_free(default_tls_cfg.capath);
26034
26035 ASTOBJ_CONTAINER_DESTROYALL(®l, sip_registry_destroy);
26036 ASTOBJ_CONTAINER_DESTROY(®l);
26037 ASTOBJ_CONTAINER_DESTROYALL(&submwil, sip_subscribe_mwi_destroy);
26038 ASTOBJ_CONTAINER_DESTROY(&submwil);
26039
26040 ao2_t_ref(peers, -1, "unref the peers table");
26041 ao2_t_ref(peers_by_ip, -1, "unref the peers_by_ip table");
26042 ao2_t_ref(dialogs, -1, "unref the dialogs table");
26043 ao2_t_ref(threadt, -1, "unref the thread table");
26044
26045 clear_sip_domains();
26046 ast_free_ha(global_contact_ha);
26047 close(sipsock);
26048 sched_context_destroy(sched);
26049 con = ast_context_find(used_context);
26050 if (con)
26051 ast_context_destroy(con, "SIP");
26052 ast_unload_realtime("sipregs");
26053 ast_unload_realtime("sippeers");
26054
26055 return 0;
26056 }
26057
26058 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Session Initiation Protocol (SIP)",
26059 .load = load_module,
26060 .unload = unload_module,
26061 .reload = reload,
26062 );