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: 282894 $")
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 256
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 struct ast_str *content;
01221
01222 struct sip_socket socket;
01223 AST_LIST_ENTRY(sip_request) next;
01224 };
01225
01226
01227
01228
01229
01230
01231
01232
01233 #define REQ_OFFSET_TO_STR(req,offset) (ast_str_buffer((req)->data) + ((req)->offset))
01234
01235
01236 struct sip_dual {
01237 struct ast_channel *chan1;
01238 struct ast_channel *chan2;
01239 struct sip_request req;
01240 int seqno;
01241 };
01242
01243 struct sip_pkt;
01244
01245
01246 struct sip_invite_param {
01247 int addsipheaders;
01248 const char *uri_options;
01249 const char *vxml_url;
01250 char *auth;
01251 char *authheader;
01252 enum sip_auth_type auth_type;
01253 const char *replaces;
01254 int transfer;
01255 };
01256
01257
01258 struct sip_route {
01259 struct sip_route *next;
01260 char hop[0];
01261 };
01262
01263
01264 enum domain_mode {
01265 SIP_DOMAIN_AUTO,
01266 SIP_DOMAIN_CONFIG,
01267 };
01268
01269
01270
01271
01272
01273 struct domain {
01274 char domain[MAXHOSTNAMELEN];
01275 char context[AST_MAX_EXTENSION];
01276 enum domain_mode mode;
01277 AST_LIST_ENTRY(domain) list;
01278 };
01279
01280 static AST_LIST_HEAD_STATIC(domain_list, domain);
01281
01282
01283
01284 struct sip_history {
01285 AST_LIST_ENTRY(sip_history) list;
01286 char event[0];
01287 };
01288
01289 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history);
01290
01291
01292 struct sip_auth {
01293 char realm[AST_MAX_EXTENSION];
01294 char username[256];
01295 char secret[256];
01296 char md5secret[256];
01297 struct sip_auth *next;
01298 };
01299
01300
01301
01302
01303
01304
01305
01306
01307
01308
01309
01310 #define SIP_OUTGOING (1 << 0)
01311 #define SIP_RINGING (1 << 2)
01312 #define SIP_PROGRESS_SENT (1 << 3)
01313 #define SIP_NEEDREINVITE (1 << 4)
01314 #define SIP_PENDINGBYE (1 << 5)
01315 #define SIP_GOTREFER (1 << 6)
01316 #define SIP_CALL_LIMIT (1 << 7)
01317 #define SIP_INC_COUNT (1 << 8)
01318 #define SIP_INC_RINGING (1 << 9)
01319 #define SIP_DEFER_BYE_ON_TRANSFER (1 << 10)
01320
01321 #define SIP_PROMISCREDIR (1 << 11)
01322 #define SIP_TRUSTRPID (1 << 12)
01323 #define SIP_USEREQPHONE (1 << 13)
01324 #define SIP_USECLIENTCODE (1 << 14)
01325
01326
01327 #define SIP_DTMF (7 << 15)
01328 #define SIP_DTMF_RFC2833 (0 << 15)
01329 #define SIP_DTMF_INBAND (1 << 15)
01330 #define SIP_DTMF_INFO (2 << 15)
01331 #define SIP_DTMF_AUTO (3 << 15)
01332 #define SIP_DTMF_SHORTINFO (4 << 15)
01333
01334
01335 #define SIP_NAT (3 << 18)
01336 #define SIP_NAT_NEVER (0 << 18)
01337 #define SIP_NAT_RFC3581 (1 << 18)
01338 #define SIP_NAT_ROUTE (2 << 18)
01339 #define SIP_NAT_ALWAYS (3 << 18)
01340
01341
01342 #define SIP_REINVITE (7 << 20)
01343 #define SIP_REINVITE_NONE (0 << 20)
01344 #define SIP_DIRECT_MEDIA (1 << 20)
01345 #define SIP_DIRECT_MEDIA_NAT (2 << 20)
01346 #define SIP_REINVITE_UPDATE (4 << 20)
01347
01348
01349 #define SIP_INSECURE (3 << 23)
01350 #define SIP_INSECURE_NONE (0 << 23)
01351 #define SIP_INSECURE_PORT (1 << 23)
01352 #define SIP_INSECURE_INVITE (1 << 24)
01353
01354
01355 #define SIP_PROG_INBAND (3 << 25)
01356 #define SIP_PROG_INBAND_NEVER (0 << 25)
01357 #define SIP_PROG_INBAND_NO (1 << 25)
01358 #define SIP_PROG_INBAND_YES (2 << 25)
01359
01360 #define SIP_SENDRPID (1 << 29)
01361 #define SIP_G726_NONSTANDARD (1 << 31)
01362
01363
01364 #define SIP_FLAGS_TO_COPY \
01365 (SIP_PROMISCREDIR | SIP_TRUSTRPID | SIP_SENDRPID | SIP_DTMF | SIP_REINVITE | \
01366 SIP_PROG_INBAND | SIP_USECLIENTCODE | SIP_NAT | SIP_G726_NONSTANDARD | \
01367 SIP_USEREQPHONE | SIP_INSECURE)
01368
01369
01370
01371
01372
01373
01374 #define SIP_PAGE2_RTCACHEFRIENDS (1 << 0)
01375 #define SIP_PAGE2_RTAUTOCLEAR (1 << 2)
01376 #define SIP_PAGE2_HAVEPEERCONTEXT (1 << 3)
01377
01378 #define SIP_PAGE2_FORWARD_LOOP_DETECTED (1 << 8)
01379 #define SIP_PAGE2_STATECHANGEQUEUE (1 << 9)
01380
01381 #define SIP_PAGE2_RPORT_PRESENT (1 << 10)
01382 #define SIP_PAGE2_VIDEOSUPPORT (1 << 14)
01383 #define SIP_PAGE2_TEXTSUPPORT (1 << 15)
01384 #define SIP_PAGE2_ALLOWSUBSCRIBE (1 << 16)
01385 #define SIP_PAGE2_ALLOWOVERLAP (1 << 17)
01386 #define SIP_PAGE2_SUBSCRIBEMWIONLY (1 << 18)
01387 #define SIP_PAGE2_IGNORESDPVERSION (1 << 19)
01388
01389 #define SIP_PAGE2_T38SUPPORT (3 << 20)
01390 #define SIP_PAGE2_T38SUPPORT_UDPTL (1 << 20)
01391 #define SIP_PAGE2_T38SUPPORT_UDPTL_FEC (2 << 20)
01392 #define SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY (3 << 20)
01393
01394 #define SIP_PAGE2_CALL_ONHOLD (3 << 23)
01395 #define SIP_PAGE2_CALL_ONHOLD_ACTIVE (1 << 23)
01396 #define SIP_PAGE2_CALL_ONHOLD_ONEDIR (2 << 23)
01397 #define SIP_PAGE2_CALL_ONHOLD_INACTIVE (3 << 23)
01398
01399 #define SIP_PAGE2_RFC2833_COMPENSATE (1 << 25)
01400 #define SIP_PAGE2_BUGGY_MWI (1 << 26)
01401 #define SIP_PAGE2_DIALOG_ESTABLISHED (1 << 27)
01402 #define SIP_PAGE2_FAX_DETECT (3 << 28)
01403 #define SIP_PAGE2_FAX_DETECT_CNG (1 << 28)
01404 #define SIP_PAGE2_FAX_DETECT_T38 (2 << 28)
01405 #define SIP_PAGE2_FAX_DETECT_BOTH (3 << 28)
01406 #define SIP_PAGE2_REGISTERTRYING (1 << 29)
01407 #define SIP_PAGE2_UDPTL_DESTINATION (1 << 30)
01408 #define SIP_PAGE2_VIDEOSUPPORT_ALWAYS (1 << 31)
01409
01410 #define SIP_PAGE2_FLAGS_TO_COPY \
01411 (SIP_PAGE2_ALLOWSUBSCRIBE | SIP_PAGE2_ALLOWOVERLAP | SIP_PAGE2_IGNORESDPVERSION | \
01412 SIP_PAGE2_VIDEOSUPPORT | SIP_PAGE2_T38SUPPORT | SIP_PAGE2_RFC2833_COMPENSATE | \
01413 SIP_PAGE2_BUGGY_MWI | SIP_PAGE2_TEXTSUPPORT | SIP_PAGE2_FAX_DETECT | \
01414 SIP_PAGE2_UDPTL_DESTINATION | SIP_PAGE2_VIDEOSUPPORT_ALWAYS | \
01415 SIP_PAGE2_HAVEPEERCONTEXT | SIP_PAGE2_FORWARD_LOOP_DETECTED)
01416
01417
01418
01419
01420
01421
01422
01423
01424
01425 enum sip_debug_e {
01426 sip_debug_none = 0,
01427 sip_debug_config = 1,
01428 sip_debug_console = 2,
01429 };
01430
01431 static enum sip_debug_e sipdebug;
01432
01433
01434
01435
01436
01437 static int sipdebug_text;
01438
01439
01440 enum t38state {
01441 T38_DISABLED = 0,
01442 T38_LOCAL_REINVITE,
01443 T38_PEER_REINVITE,
01444 T38_ENABLED
01445 };
01446
01447
01448 struct t38properties {
01449 enum t38state state;
01450 struct ast_control_t38_parameters our_parms;
01451 struct ast_control_t38_parameters their_parms;
01452 };
01453
01454
01455 enum referstatus {
01456 REFER_IDLE,
01457 REFER_SENT,
01458 REFER_RECEIVED,
01459 REFER_CONFIRMED,
01460 REFER_ACCEPTED,
01461 REFER_RINGING,
01462 REFER_200OK,
01463 REFER_FAILED,
01464 REFER_NOAUTH
01465 };
01466
01467
01468
01469
01470
01471
01472 struct _map_x_s {
01473 int x;
01474 const char *s;
01475 };
01476
01477 static const struct _map_x_s referstatusstrings[] = {
01478 { REFER_IDLE, "<none>" },
01479 { REFER_SENT, "Request sent" },
01480 { REFER_RECEIVED, "Request received" },
01481 { REFER_CONFIRMED, "Confirmed" },
01482 { REFER_ACCEPTED, "Accepted" },
01483 { REFER_RINGING, "Target ringing" },
01484 { REFER_200OK, "Done" },
01485 { REFER_FAILED, "Failed" },
01486 { REFER_NOAUTH, "Failed - auth failure" },
01487 { -1, NULL}
01488 };
01489
01490
01491
01492 struct sip_refer {
01493 char refer_to[AST_MAX_EXTENSION];
01494 char refer_to_domain[AST_MAX_EXTENSION];
01495 char refer_to_urioption[AST_MAX_EXTENSION];
01496 char refer_to_context[AST_MAX_EXTENSION];
01497 char referred_by[AST_MAX_EXTENSION];
01498 char referred_by_name[AST_MAX_EXTENSION];
01499 char refer_contact[AST_MAX_EXTENSION];
01500 char replaces_callid[SIPBUFSIZE];
01501 char replaces_callid_totag[SIPBUFSIZE/2];
01502 char replaces_callid_fromtag[SIPBUFSIZE/2];
01503 struct sip_pvt *refer_call;
01504
01505
01506
01507 int attendedtransfer;
01508 int localtransfer;
01509 enum referstatus status;
01510 };
01511
01512
01513
01514
01515
01516 struct sip_st_dlg {
01517 int st_active;
01518 int st_interval;
01519 int st_schedid;
01520 enum st_refresher st_ref;
01521 int st_expirys;
01522 int st_active_peer_ua;
01523 int st_cached_min_se;
01524 int st_cached_max_se;
01525 enum st_mode st_cached_mode;
01526 enum st_refresher st_cached_ref;
01527 unsigned char quit_flag:1;
01528 };
01529
01530
01531
01532
01533
01534 struct sip_st_cfg {
01535 enum st_mode st_mode_oper;
01536 enum st_refresher st_ref;
01537 int st_min_se;
01538 int st_max_se;
01539 };
01540
01541 struct offered_media {
01542 int offered;
01543 char text[128];
01544 };
01545
01546
01547
01548
01549
01550 struct sip_pvt {
01551 struct sip_pvt *next;
01552 enum invitestates invitestate;
01553 int method;
01554 AST_DECLARE_STRING_FIELDS(
01555 AST_STRING_FIELD(callid);
01556 AST_STRING_FIELD(randdata);
01557 AST_STRING_FIELD(accountcode);
01558 AST_STRING_FIELD(realm);
01559 AST_STRING_FIELD(nonce);
01560 AST_STRING_FIELD(opaque);
01561 AST_STRING_FIELD(qop);
01562 AST_STRING_FIELD(domain);
01563 AST_STRING_FIELD(from);
01564 AST_STRING_FIELD(useragent);
01565 AST_STRING_FIELD(exten);
01566 AST_STRING_FIELD(context);
01567 AST_STRING_FIELD(subscribecontext);
01568 AST_STRING_FIELD(subscribeuri);
01569 AST_STRING_FIELD(fromdomain);
01570 AST_STRING_FIELD(fromuser);
01571 AST_STRING_FIELD(fromname);
01572 AST_STRING_FIELD(tohost);
01573 AST_STRING_FIELD(todnid);
01574 AST_STRING_FIELD(language);
01575 AST_STRING_FIELD(mohinterpret);
01576 AST_STRING_FIELD(mohsuggest);
01577 AST_STRING_FIELD(rdnis);
01578 AST_STRING_FIELD(redircause);
01579 AST_STRING_FIELD(theirtag);
01580 AST_STRING_FIELD(username);
01581 AST_STRING_FIELD(peername);
01582 AST_STRING_FIELD(authname);
01583 AST_STRING_FIELD(uri);
01584 AST_STRING_FIELD(okcontacturi);
01585 AST_STRING_FIELD(peersecret);
01586 AST_STRING_FIELD(peermd5secret);
01587 AST_STRING_FIELD(cid_num);
01588 AST_STRING_FIELD(cid_name);
01589 AST_STRING_FIELD(fullcontact);
01590
01591 AST_STRING_FIELD(our_contact);
01592 AST_STRING_FIELD(rpid);
01593 AST_STRING_FIELD(rpid_from);
01594 AST_STRING_FIELD(url);
01595 AST_STRING_FIELD(parkinglot);
01596 );
01597 char via[128];
01598 struct sip_socket socket;
01599 unsigned int ocseq;
01600 unsigned int icseq;
01601 ast_group_t callgroup;
01602 ast_group_t pickupgroup;
01603 int lastinvite;
01604 struct ast_flags flags[2];
01605
01606
01607 char do_history;
01608 char alreadygone;
01609 char needdestroy;
01610 char outgoing_call;
01611 char answered_elsewhere;
01612 char novideo;
01613 char notext;
01614
01615 int timer_t1;
01616 int timer_b;
01617 unsigned int sipoptions;
01618 unsigned int reqsipoptions;
01619 struct ast_codec_pref prefs;
01620 int capability;
01621 int jointcapability;
01622 int peercapability;
01623 int prefcodec;
01624 int noncodeccapability;
01625 int jointnoncodeccapability;
01626 int redircodecs;
01627 int maxcallbitrate;
01628 int t38_maxdatagram;
01629 struct sip_proxy *outboundproxy;
01630 struct t38properties t38;
01631 struct sockaddr_in udptlredirip;
01632 struct ast_udptl *udptl;
01633 int callingpres;
01634 int authtries;
01635 int expiry;
01636 long branch;
01637 long invite_branch;
01638 char tag[11];
01639 int sessionid;
01640 int sessionversion;
01641 int64_t sessionversion_remote;
01642 int session_modify;
01643 unsigned int portinuri:1;
01644 struct sockaddr_in sa;
01645 struct sockaddr_in redirip;
01646 struct sockaddr_in vredirip;
01647 struct sockaddr_in tredirip;
01648 time_t lastrtprx;
01649 time_t lastrtptx;
01650 int rtptimeout;
01651 struct sockaddr_in recv;
01652 struct sockaddr_in ourip;
01653 struct ast_channel *owner;
01654 struct sip_route *route;
01655 int route_persistant;
01656 struct ast_variable *notify_headers;
01657 struct sip_auth *peerauth;
01658 int noncecount;
01659 unsigned int stalenonce:1;
01660 char lastmsg[256];
01661 int amaflags;
01662 int pendinginvite;
01663 int glareinvite;
01664
01665
01666 struct sip_request initreq;
01667
01668
01669
01670 int initid;
01671 int waitid;
01672 int autokillid;
01673 int t38id;
01674 enum transfermodes allowtransfer;
01675 struct sip_refer *refer;
01676 enum subscriptiontype subscribed;
01677 int stateid;
01678 int laststate;
01679 int dialogver;
01680
01681 struct ast_dsp *dsp;
01682
01683 struct sip_peer *relatedpeer;
01684
01685 struct sip_registry *registry;
01686 struct ast_rtp *rtp;
01687 struct ast_rtp *vrtp;
01688 struct ast_rtp *trtp;
01689 struct sip_pkt *packets;
01690 struct sip_history_head *history;
01691 size_t history_entries;
01692 struct ast_variable *chanvars;
01693 AST_LIST_HEAD_NOLOCK(request_queue, sip_request) request_queue;
01694 int request_queue_sched_id;
01695 int provisional_keepalive_sched_id;
01696 const char *last_provisional;
01697 struct sip_invite_param *options;
01698 int autoframing;
01699
01700
01701
01702 struct sip_st_dlg *stimer;
01703
01704 int red;
01705 int hangupcause;
01706
01707 struct sip_subscription_mwi *mwi;
01708
01709
01710
01711
01712
01713
01714
01715
01716
01717
01718
01719
01720
01721
01722 struct offered_media offered_media[4];
01723 };
01724
01725
01726
01727
01728
01729
01730
01731
01732
01733
01734 struct ao2_container *dialogs;
01735
01736 #define sip_pvt_lock(x) ao2_lock(x)
01737 #define sip_pvt_trylock(x) ao2_trylock(x)
01738 #define sip_pvt_unlock(x) ao2_unlock(x)
01739
01740
01741
01742
01743
01744
01745 #ifdef REF_DEBUG
01746 #define dialog_ref(arg1,arg2) dialog_ref_debug((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
01747 #define dialog_unref(arg1,arg2) dialog_unref_debug((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
01748
01749 static struct sip_pvt *dialog_ref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
01750 {
01751 if (p)
01752 _ao2_ref_debug(p, 1, tag, file, line, func);
01753 else
01754 ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
01755 return p;
01756 }
01757
01758 static struct sip_pvt *dialog_unref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
01759 {
01760 if (p)
01761 _ao2_ref_debug(p, -1, tag, file, line, func);
01762 return NULL;
01763 }
01764 #else
01765 static struct sip_pvt *dialog_ref(struct sip_pvt *p, char *tag)
01766 {
01767 if (p)
01768 ao2_ref(p, 1);
01769 else
01770 ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
01771 return p;
01772 }
01773
01774 static struct sip_pvt *dialog_unref(struct sip_pvt *p, char *tag)
01775 {
01776 if (p)
01777 ao2_ref(p, -1);
01778 return NULL;
01779 }
01780 #endif
01781
01782
01783
01784
01785
01786
01787
01788 struct sip_pkt {
01789 struct sip_pkt *next;
01790 int retrans;
01791 int method;
01792 int seqno;
01793 char is_resp;
01794 char is_fatal;
01795 int response_code;
01796 struct sip_pvt *owner;
01797 int retransid;
01798 int timer_a;
01799 int timer_t1;
01800 int packetlen;
01801 struct ast_str *data;
01802 };
01803
01804
01805
01806
01807
01808
01809
01810 struct sip_mailbox {
01811 char *mailbox;
01812 char *context;
01813 unsigned int delme:1;
01814
01815 struct ast_event_sub *event_sub;
01816 AST_LIST_ENTRY(sip_mailbox) entry;
01817 };
01818
01819 enum sip_peer_type {
01820 SIP_TYPE_PEER = (1 << 0),
01821 SIP_TYPE_USER = (1 << 1),
01822 };
01823
01824
01825
01826
01827 struct sip_peer {
01828 char name[80];
01829 AST_DECLARE_STRING_FIELDS(
01830 AST_STRING_FIELD(secret);
01831 AST_STRING_FIELD(md5secret);
01832 AST_STRING_FIELD(remotesecret);
01833 AST_STRING_FIELD(context);
01834 AST_STRING_FIELD(subscribecontext);
01835 AST_STRING_FIELD(username);
01836 AST_STRING_FIELD(accountcode);
01837 AST_STRING_FIELD(tohost);
01838 AST_STRING_FIELD(regexten);
01839 AST_STRING_FIELD(fromuser);
01840 AST_STRING_FIELD(fromdomain);
01841 AST_STRING_FIELD(fullcontact);
01842 AST_STRING_FIELD(cid_num);
01843 AST_STRING_FIELD(cid_name);
01844 AST_STRING_FIELD(vmexten);
01845 AST_STRING_FIELD(language);
01846 AST_STRING_FIELD(mohinterpret);
01847 AST_STRING_FIELD(mohsuggest);
01848 AST_STRING_FIELD(parkinglot);
01849 AST_STRING_FIELD(useragent);
01850 );
01851 struct sip_socket socket;
01852 enum sip_transport default_outbound_transport;
01853
01854 unsigned int transports:3;
01855 struct sip_auth *auth;
01856 int amaflags;
01857 int callingpres;
01858 int inUse;
01859 int inRinging;
01860 int onHold;
01861 int call_limit;
01862 int t38_maxdatagram;
01863 int busy_level;
01864 enum transfermodes allowtransfer;
01865 struct ast_codec_pref prefs;
01866 int lastmsgssent;
01867 unsigned int sipoptions;
01868 struct ast_flags flags[2];
01869
01870
01871 AST_LIST_HEAD_NOLOCK(, sip_mailbox) mailboxes;
01872
01873
01874 char is_realtime;
01875 char rt_fromcontact;
01876 char host_dynamic;
01877 char selfdestruct;
01878 char the_mark;
01879
01880 int expire;
01881 int capability;
01882 int rtptimeout;
01883 int rtpholdtimeout;
01884 int rtpkeepalive;
01885 ast_group_t callgroup;
01886 ast_group_t pickupgroup;
01887 struct sip_proxy *outboundproxy;
01888 struct ast_dnsmgr_entry *dnsmgr;
01889 struct sockaddr_in addr;
01890 int maxcallbitrate;
01891 unsigned int portinuri:1;
01892
01893
01894 struct sip_pvt *call;
01895 int pokeexpire;
01896 int lastms;
01897 int maxms;
01898 int qualifyfreq;
01899 struct timeval ps;
01900 struct sockaddr_in defaddr;
01901 struct ast_ha *ha;
01902 struct ast_ha *contactha;
01903 struct ast_variable *chanvars;
01904 struct sip_pvt *mwipvt;
01905 int autoframing;
01906 struct sip_st_cfg stimer;
01907 int timer_t1;
01908 int timer_b;
01909 int deprecated_username;
01910
01911
01912 enum sip_peer_type type;
01913 };
01914
01915
01916
01917
01918
01919
01920
01921
01922
01923
01924
01925
01926
01927
01928 struct sip_registry {
01929 ASTOBJ_COMPONENTS_FULL(struct sip_registry,1,1);
01930 AST_DECLARE_STRING_FIELDS(
01931 AST_STRING_FIELD(callid);
01932 AST_STRING_FIELD(realm);
01933 AST_STRING_FIELD(nonce);
01934 AST_STRING_FIELD(opaque);
01935 AST_STRING_FIELD(qop);
01936 AST_STRING_FIELD(domain);
01937 AST_STRING_FIELD(username);
01938 AST_STRING_FIELD(authuser);
01939 AST_STRING_FIELD(hostname);
01940 AST_STRING_FIELD(secret);
01941 AST_STRING_FIELD(md5secret);
01942 AST_STRING_FIELD(callback);
01943 AST_STRING_FIELD(random);
01944 AST_STRING_FIELD(peername);
01945 );
01946 enum sip_transport transport;
01947 int portno;
01948 int expire;
01949 int configured_expiry;
01950 int expiry;
01951 int regattempts;
01952 int timeout;
01953 int refresh;
01954 struct sip_pvt *call;
01955 enum sipregistrystate regstate;
01956 struct timeval regtime;
01957 int callid_valid;
01958 unsigned int ocseq;
01959 struct ast_dnsmgr_entry *dnsmgr;
01960 struct sockaddr_in us;
01961 int noncecount;
01962 char lastmsg[256];
01963 };
01964
01965 enum sip_tcptls_alert {
01966
01967 TCPTLS_ALERT_DATA,
01968
01969 TCPTLS_ALERT_STOP,
01970 };
01971
01972 struct tcptls_packet {
01973 AST_LIST_ENTRY(tcptls_packet) entry;
01974 struct ast_str *data;
01975 size_t len;
01976 };
01977
01978 struct sip_threadinfo {
01979 int stop;
01980 int alert_pipe[2];
01981 pthread_t threadid;
01982 struct ast_tcptls_session_instance *tcptls_session;
01983 enum sip_transport type;
01984 AST_LIST_HEAD_NOLOCK(, tcptls_packet) packet_q;
01985 };
01986
01987
01988 struct sip_subscription_mwi {
01989 ASTOBJ_COMPONENTS_FULL(struct sip_subscription_mwi,1,1);
01990 AST_DECLARE_STRING_FIELDS(
01991 AST_STRING_FIELD(username);
01992 AST_STRING_FIELD(authuser);
01993 AST_STRING_FIELD(hostname);
01994 AST_STRING_FIELD(secret);
01995 AST_STRING_FIELD(mailbox);
01996 );
01997 enum sip_transport transport;
01998 int portno;
01999 int resub;
02000 unsigned int subscribed:1;
02001 struct sip_pvt *call;
02002 struct ast_dnsmgr_entry *dnsmgr;
02003 struct sockaddr_in us;
02004 };
02005
02006
02007 #ifdef LOW_MEMORY
02008 static const int HASH_PEER_SIZE = 17;
02009 static const int HASH_DIALOG_SIZE = 17;
02010 #else
02011 static const int HASH_PEER_SIZE = 563;
02012 static const int HASH_DIALOG_SIZE = 563;
02013 #endif
02014 static struct ao2_container *threadt;
02015
02016
02017 struct ao2_container *peers;
02018 struct ao2_container *peers_by_ip;
02019
02020
02021 static struct ast_register_list {
02022 ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
02023 int recheck;
02024 } regl;
02025
02026
02027 static struct ast_subscription_mwi_list {
02028 ASTOBJ_CONTAINER_COMPONENTS(struct sip_subscription_mwi);
02029 } submwil;
02030
02031
02032
02033
02034 static int peer_hash_cb(const void *obj, const int flags)
02035 {
02036 const struct sip_peer *peer = obj;
02037
02038 return ast_str_case_hash(peer->name);
02039 }
02040
02041
02042
02043
02044 static int peer_cmp_cb(void *obj, void *arg, int flags)
02045 {
02046 struct sip_peer *peer = obj, *peer2 = arg;
02047
02048 return !strcasecmp(peer->name, peer2->name) ? CMP_MATCH | CMP_STOP : 0;
02049 }
02050
02051
02052
02053
02054 static int peer_iphash_cb(const void *obj, const int flags)
02055 {
02056 const struct sip_peer *peer = obj;
02057 int ret1 = peer->addr.sin_addr.s_addr;
02058 if (ret1 < 0)
02059 ret1 = -ret1;
02060
02061 return ret1;
02062 }
02063
02064
02065
02066
02067
02068
02069
02070
02071
02072
02073
02074
02075
02076
02077
02078
02079
02080
02081
02082 static int peer_ipcmp_cb(void *obj, void *arg, int flags)
02083 {
02084 struct sip_peer *peer = obj, *peer2 = arg;
02085
02086 if (peer->addr.sin_addr.s_addr != peer2->addr.sin_addr.s_addr) {
02087
02088 return 0;
02089 }
02090
02091
02092 if ((peer->transports & peer2->transports) & (SIP_TRANSPORT_TLS | SIP_TRANSPORT_TCP)) {
02093
02094 return CMP_MATCH | CMP_STOP;
02095 } else if (ast_test_flag(&peer2->flags[0], SIP_INSECURE_PORT)) {
02096
02097
02098 return ast_test_flag(&peer->flags[0], SIP_INSECURE_PORT) ?
02099 (CMP_MATCH | CMP_STOP) : 0;
02100 }
02101
02102
02103 return peer->addr.sin_port == peer2->addr.sin_port ? (CMP_MATCH | CMP_STOP) : 0;
02104 }
02105
02106
02107 static int threadt_hash_cb(const void *obj, const int flags)
02108 {
02109 const struct sip_threadinfo *th = obj;
02110
02111 return (int) th->tcptls_session->remote_address.sin_addr.s_addr;
02112 }
02113
02114 static int threadt_cmp_cb(void *obj, void *arg, int flags)
02115 {
02116 struct sip_threadinfo *th = obj, *th2 = arg;
02117
02118 return (th->tcptls_session == th2->tcptls_session) ? CMP_MATCH | CMP_STOP : 0;
02119 }
02120
02121
02122
02123
02124 static int dialog_hash_cb(const void *obj, const int flags)
02125 {
02126 const struct sip_pvt *pvt = obj;
02127
02128 return ast_str_case_hash(pvt->callid);
02129 }
02130
02131
02132
02133
02134 static int dialog_cmp_cb(void *obj, void *arg, int flags)
02135 {
02136 struct sip_pvt *pvt = obj, *pvt2 = arg;
02137
02138 return !strcasecmp(pvt->callid, pvt2->callid) ? CMP_MATCH | CMP_STOP : 0;
02139 }
02140
02141 static int temp_pvt_init(void *);
02142 static void temp_pvt_cleanup(void *);
02143
02144
02145 AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
02146
02147 #ifdef LOW_MEMORY
02148 static void ts_ast_rtp_destroy(void *);
02149
02150 AST_THREADSTORAGE_CUSTOM(ts_audio_rtp, NULL, ts_ast_rtp_destroy);
02151 AST_THREADSTORAGE_CUSTOM(ts_video_rtp, NULL, ts_ast_rtp_destroy);
02152 AST_THREADSTORAGE_CUSTOM(ts_text_rtp, NULL, ts_ast_rtp_destroy);
02153 #endif
02154
02155
02156
02157 static struct sip_auth *authl = NULL;
02158
02159
02160
02161
02162
02163
02164
02165
02166
02167
02168
02169
02170
02171
02172
02173
02174
02175
02176 static int sipsock = -1;
02177
02178 static struct sockaddr_in bindaddr;
02179
02180
02181
02182
02183
02184
02185
02186 static struct sockaddr_in internip;
02187
02188
02189
02190
02191
02192
02193
02194
02195
02196
02197
02198
02199
02200
02201
02202
02203
02204
02205
02206 static struct sockaddr_in externip;
02207
02208 static char externhost[MAXHOSTNAMELEN];
02209 static time_t externexpire;
02210 static int externrefresh = 10;
02211 static struct sockaddr_in stunaddr;
02212
02213
02214
02215
02216
02217
02218
02219 static struct ast_ha *localaddr;
02220
02221 static int ourport_tcp;
02222 static int ourport_tls;
02223 static struct sockaddr_in debugaddr;
02224
02225 static struct ast_config *notify_types = NULL;
02226
02227
02228
02229 #define UNLINK(element, head, prev) do { \
02230 if (prev) \
02231 (prev)->next = (element)->next; \
02232 else \
02233 (head) = (element)->next; \
02234 } while (0)
02235
02236 enum t38_action_flag {
02237 SDP_T38_NONE = 0,
02238 SDP_T38_INITIATE,
02239 SDP_T38_ACCEPT,
02240 };
02241
02242
02243
02244
02245
02246
02247 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause);
02248 static int sip_devicestate(void *data);
02249 static int sip_sendtext(struct ast_channel *ast, const char *text);
02250 static int sip_call(struct ast_channel *ast, char *dest, int timeout);
02251 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen);
02252 static int sip_hangup(struct ast_channel *ast);
02253 static int sip_answer(struct ast_channel *ast);
02254 static struct ast_frame *sip_read(struct ast_channel *ast);
02255 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
02256 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
02257 static int sip_transfer(struct ast_channel *ast, const char *dest);
02258 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
02259 static int sip_senddigit_begin(struct ast_channel *ast, char digit);
02260 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
02261 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen);
02262 static const char *sip_get_callid(struct ast_channel *chan);
02263
02264 static int handle_request_do(struct sip_request *req, struct sockaddr_in *sin);
02265 static int sip_standard_port(enum sip_transport type, int port);
02266 static int sip_prepare_socket(struct sip_pvt *p);
02267 static int sip_parse_host(char *line, int lineno, char **hostname, int *portnum, enum sip_transport *transport);
02268
02269
02270 static int sipsock_read(int *id, int fd, short events, void *ignore);
02271 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len);
02272 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, struct ast_str *data, int len, int fatal, int sipmethod);
02273 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
02274 static int retrans_pkt(const void *data);
02275 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);
02276 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
02277 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
02278 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
02279 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable, int oldsdp);
02280 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
02281 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);
02282 static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp);
02283 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
02284 static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable);
02285 static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
02286 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch);
02287 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init);
02288 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp);
02289 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
02290 static int transmit_info_with_vidupdate(struct sip_pvt *p);
02291 static int transmit_message_with_text(struct sip_pvt *p, const char *text);
02292 static int transmit_refer(struct sip_pvt *p, const char *dest);
02293 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten);
02294 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
02295 static int transmit_notify_custom(struct sip_pvt *p, struct ast_variable *vars);
02296 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
02297 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
02298 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
02299 static void copy_request(struct sip_request *dst, const struct sip_request *src);
02300 static void receive_message(struct sip_pvt *p, struct sip_request *req);
02301 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req);
02302 static int sip_send_mwi_to_peer(struct sip_peer *peer, const struct ast_event *event, int cache_only);
02303
02304
02305 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
02306 int useglobal_nat, const int intended_method, struct sip_request *req);
02307 static int __sip_autodestruct(const void *data);
02308 static void sip_scheddestroy(struct sip_pvt *p, int ms);
02309 static int sip_cancel_destroy(struct sip_pvt *p);
02310 static struct sip_pvt *sip_destroy(struct sip_pvt *p);
02311 static void *dialog_unlink_all(struct sip_pvt *dialog, int lockowner, int lockdialoglist);
02312 static void *registry_unref(struct sip_registry *reg, char *tag);
02313 static void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist);
02314 static int __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
02315 static void __sip_pretend_ack(struct sip_pvt *p);
02316 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
02317 static int auto_congest(const void *arg);
02318 static int update_call_counter(struct sip_pvt *fup, int event);
02319 static int hangup_sip2cause(int cause);
02320 static const char *hangup_cause2sip(int cause);
02321 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method);
02322 static void free_old_route(struct sip_route *route);
02323 static void list_route(struct sip_route *route);
02324 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards);
02325 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
02326 struct sip_request *req, char *uri);
02327 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
02328 static void check_pendings(struct sip_pvt *p);
02329 static void *sip_park_thread(void *stuff);
02330 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno);
02331 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
02332
02333
02334 static void try_suggested_sip_codec(struct sip_pvt *p);
02335 static const char *get_sdp_iterate(int* start, struct sip_request *req, const char *name);
02336 static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value);
02337 static int find_sdp(struct sip_request *req);
02338 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action);
02339 static int process_sdp_o(const char *o, struct sip_pvt *p);
02340 static int process_sdp_c(const char *c, struct ast_hostent *hp);
02341 static int process_sdp_a_sendonly(const char *a, int *sendonly);
02342 static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp *newaudiortp, int *last_rtpmap_codec);
02343 static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp *newvideortp, int *last_rtpmap_codec);
02344 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);
02345 static int process_sdp_a_image(const char *a, struct sip_pvt *p);
02346 static void add_codec_to_sdp(const struct sip_pvt *p, int codec,
02347 struct ast_str **m_buf, struct ast_str **a_buf,
02348 int debug, int *min_packet_size);
02349 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
02350 struct ast_str **m_buf, struct ast_str **a_buf,
02351 int debug);
02352 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38);
02353 static void do_setnat(struct sip_pvt *p, int natflags);
02354 static void stop_media_flows(struct sip_pvt *p);
02355
02356
02357 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
02358 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
02359 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
02360 const char *secret, const char *md5secret, int sipmethod,
02361 char *uri, enum xmittype reliable, int ignore);
02362 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
02363 int sipmethod, char *uri, enum xmittype reliable,
02364 struct sockaddr_in *sin, struct sip_peer **authpeer);
02365 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin);
02366
02367
02368 static int check_sip_domain(const char *domain, char *context, size_t len);
02369 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
02370 static void clear_sip_domains(void);
02371
02372
02373 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, const char *configuration, int lineno);
02374 static int clear_realm_authentication(struct sip_auth *authlist);
02375 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm);
02376
02377
02378 static void check_rtp_timeout(struct sip_pvt *dialog, time_t t);
02379 static int sip_do_reload(enum channelreloadreason reason);
02380 static int reload_config(enum channelreloadreason reason);
02381 static int expire_register(const void *data);
02382 static void *do_monitor(void *data);
02383 static int restart_monitor(void);
02384 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer);
02385 static struct ast_variable *copy_vars(struct ast_variable *src);
02386
02387 static int sip_refer_allocate(struct sip_pvt *p);
02388 static void ast_quiet_chan(struct ast_channel *chan);
02389 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
02390 static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context);
02391
02392
02393
02394
02395
02396
02397
02398
02399 #define check_request_transport(peer, tmpl) ({ \
02400 int ret = 0; \
02401 if (peer->socket.type == tmpl->socket.type) \
02402 ; \
02403 else if (!(peer->transports & tmpl->socket.type)) {\
02404 ast_log(LOG_ERROR, \
02405 "'%s' is not a valid transport for '%s'. we only use '%s'! ending call.\n", \
02406 get_transport(tmpl->socket.type), peer->name, get_transport_list(peer->transports) \
02407 ); \
02408 ret = 1; \
02409 } else if (peer->socket.type & SIP_TRANSPORT_TLS) { \
02410 ast_log(LOG_WARNING, \
02411 "peer '%s' HAS NOT USED (OR SWITCHED TO) TLS in favor of '%s' (but this was allowed in sip.conf)!\n", \
02412 peer->name, get_transport(tmpl->socket.type) \
02413 ); \
02414 } else { \
02415 ast_debug(1, \
02416 "peer '%s' has contacted us over %s even though we prefer %s.\n", \
02417 peer->name, get_transport(tmpl->socket.type), get_transport(peer->socket.type) \
02418 ); \
02419 }\
02420 (ret); \
02421 })
02422
02423
02424
02425 static int cb_extensionstate(char *context, char* exten, int state, void *data);
02426 static int sip_devicestate(void *data);
02427 static int sip_poke_noanswer(const void *data);
02428 static int sip_poke_peer(struct sip_peer *peer, int force);
02429 static void sip_poke_all_peers(void);
02430 static void sip_peer_hold(struct sip_pvt *p, int hold);
02431 static void mwi_event_cb(const struct ast_event *, void *);
02432
02433
02434 static const char *sip_nat_mode(const struct sip_pvt *p);
02435 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02436 static char *transfermode2str(enum transfermodes mode) attribute_const;
02437 static const char *nat2str(int nat) attribute_const;
02438 static int peer_status(struct sip_peer *peer, char *status, int statuslen);
02439 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02440 static char * _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
02441 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02442 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02443 static void print_group(int fd, ast_group_t group, int crlf);
02444 static const char *dtmfmode2str(int mode) attribute_const;
02445 static int str2dtmfmode(const char *str) attribute_unused;
02446 static const char *insecure2str(int mode) attribute_const;
02447 static void cleanup_stale_contexts(char *new, char *old);
02448 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
02449 static const char *domain_mode_to_text(const enum domain_mode mode);
02450 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02451 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
02452 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02453 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
02454 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02455 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02456 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02457 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02458 static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02459 static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
02460 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
02461 static char *complete_sip_peer(const char *word, int state, int flags2);
02462 static char *complete_sip_registered_peer(const char *word, int state, int flags2);
02463 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state);
02464 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
02465 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state);
02466 static char *complete_sipnotify(const char *line, const char *word, int pos, int state);
02467 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02468 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02469 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02470 static char *sip_do_debug_ip(int fd, char *arg);
02471 static char *sip_do_debug_peer(int fd, char *arg);
02472 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02473 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02474 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02475 static int sip_dtmfmode(struct ast_channel *chan, void *data);
02476 static int sip_addheader(struct ast_channel *chan, void *data);
02477 static int sip_do_reload(enum channelreloadreason reason);
02478 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02479 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
02480
02481
02482
02483
02484
02485 static void sip_dump_history(struct sip_pvt *dialog);
02486 static inline int sip_debug_test_addr(const struct sockaddr_in *addr);
02487 static inline int sip_debug_test_pvt(struct sip_pvt *p);
02488
02489
02490
02491
02492 #define append_history(p, event, fmt , args... ) append_history_full(p, "%-15s " fmt, event, ## args)
02493 static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
02494 static void sip_dump_history(struct sip_pvt *dialog);
02495
02496
02497 static struct sip_peer *temp_peer(const char *name);
02498 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only);
02499 static int update_call_counter(struct sip_pvt *fup, int event);
02500 static void sip_destroy_peer(struct sip_peer *peer);
02501 static void sip_destroy_peer_fn(void *peer);
02502 static void set_peer_defaults(struct sip_peer *peer);
02503 static struct sip_peer *temp_peer(const char *name);
02504 static void register_peer_exten(struct sip_peer *peer, int onoff);
02505 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime, int forcenamematch, int devstate_only, int transport);
02506 static int sip_poke_peer_s(const void *data);
02507 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
02508 static void reg_source_db(struct sip_peer *peer);
02509 static void destroy_association(struct sip_peer *peer);
02510 static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
02511 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
02512 static void set_socket_transport(struct sip_socket *socket, int transport);
02513
02514
02515 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);
02516 static void update_peer(struct sip_peer *p, int expire);
02517 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config);
02518 static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername);
02519 static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin, int devstate_only);
02520 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02521
02522
02523 static void ast_sip_ouraddrfor(struct in_addr *them, struct sockaddr_in *us, struct sip_pvt *p);
02524 static void sip_registry_destroy(struct sip_registry *reg);
02525 static int sip_register(const char *value, int lineno);
02526 static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
02527 static int sip_reregister(const void *data);
02528 static int __sip_do_register(struct sip_registry *r);
02529 static int sip_reg_timeout(const void *data);
02530 static void sip_send_all_registers(void);
02531 static int sip_reinvite_retry(const void *data);
02532
02533
02534 static void append_date(struct sip_request *req);
02535 static int determine_firstline_parts(struct sip_request *req);
02536 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
02537 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
02538 static int find_sip_method(const char *msg);
02539 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported);
02540 static int parse_request(struct sip_request *req);
02541 static const char *get_header(const struct sip_request *req, const char *name);
02542 static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
02543 static int method_match(enum sipmethod id, const char *name);
02544 static void parse_copy(struct sip_request *dst, const struct sip_request *src);
02545 static char *get_in_brackets(char *tmp);
02546 static const char *find_alias(const char *name, const char *_default);
02547 static const char *__get_header(const struct sip_request *req, const char *name, int *start);
02548 static int lws2sws(char *msgbuf, int len);
02549 static void extract_uri(struct sip_pvt *p, struct sip_request *req);
02550 static char *remove_uri_parameters(char *uri);
02551 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
02552 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
02553 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
02554 static int set_address_from_contact(struct sip_pvt *pvt);
02555 static void check_via(struct sip_pvt *p, struct sip_request *req);
02556 static char *get_calleridname(const char *input, char *output, size_t outputsize);
02557 static int get_rpid_num(const char *input, char *output, int maxlen);
02558 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq);
02559 static int get_destination(struct sip_pvt *p, struct sip_request *oreq);
02560 static int get_msg_text(char *buf, int len, struct sip_request *req, int addnewline);
02561 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout);
02562
02563
02564 static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session);
02565 static void *sip_tcp_worker_fn(void *);
02566
02567
02568 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
02569 static int init_req(struct sip_request *req, int sipmethod, const char *recip);
02570 static void deinit_req(struct sip_request *req);
02571 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch);
02572 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod);
02573 static int init_resp(struct sip_request *resp, const char *msg);
02574 static inline int resp_needs_contact(const char *msg, enum sipmethod method);
02575 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
02576 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p);
02577 static void build_via(struct sip_pvt *p);
02578 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
02579 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct sockaddr_in *sin, int newdialog);
02580 static char *generate_random_string(char *buf, size_t size);
02581 static void build_callid_pvt(struct sip_pvt *pvt);
02582 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain);
02583 static void make_our_tag(char *tagbuf, size_t len);
02584 static int add_header(struct sip_request *req, const char *var, const char *value);
02585 static int add_content(struct sip_request *req, const char *line);
02586 static int finalize_content(struct sip_request *req);
02587 static int add_text(struct sip_request *req, const char *text);
02588 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode);
02589 static int add_vidupdate(struct sip_request *req);
02590 static void add_route(struct sip_request *req, struct sip_route *route);
02591 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
02592 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
02593 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
02594 static void set_destination(struct sip_pvt *p, char *uri);
02595 static void append_date(struct sip_request *req);
02596 static void build_contact(struct sip_pvt *p);
02597 static void build_rpid(struct sip_pvt *p);
02598
02599
02600 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock);
02601 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);
02602 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock);
02603 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
02604 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e);
02605 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
02606 static int handle_request_message(struct sip_pvt *p, struct sip_request *req);
02607 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
02608 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
02609 static int handle_request_options(struct sip_pvt *p, struct sip_request *req);
02610 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin, int *nounlock);
02611 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
02612 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno);
02613
02614
02615 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02616 static void handle_response_notify(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02617 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02618 static void handle_response_subscribe(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02619 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02620 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02621
02622
02623 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);
02624 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
02625 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
02626 static enum ast_rtp_get_result sip_get_trtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
02627 static int sip_get_codec(struct ast_channel *chan);
02628 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect);
02629
02630
02631 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
02632 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
02633 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
02634 static void change_t38_state(struct sip_pvt *p, int state);
02635
02636
02637 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp);
02638 static int proc_session_timer(const void *vp);
02639 static void stop_session_timer(struct sip_pvt *p);
02640 static void start_session_timer(struct sip_pvt *p);
02641 static void restart_session_timer(struct sip_pvt *p);
02642 static const char *strefresher2str(enum st_refresher r);
02643 static int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref);
02644 static int parse_minse(const char *p_hdrval, int *const p_interval);
02645 static int st_get_se(struct sip_pvt *, int max);
02646 static enum st_refresher st_get_refresher(struct sip_pvt *);
02647 static enum st_mode st_get_mode(struct sip_pvt *);
02648 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p);
02649
02650
02651 static int sip_subscribe_mwi(const char *value, int lineno);
02652 static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi);
02653 static void sip_send_all_mwi_subscriptions(void);
02654 static int sip_subscribe_mwi_do(const void *data);
02655 static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi);
02656
02657
02658 static const struct ast_channel_tech sip_tech = {
02659 .type = "SIP",
02660 .description = "Session Initiation Protocol (SIP)",
02661 .capabilities = AST_FORMAT_AUDIO_MASK,
02662 .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
02663 .requester = sip_request_call,
02664 .devicestate = sip_devicestate,
02665 .call = sip_call,
02666 .send_html = sip_sendhtml,
02667 .hangup = sip_hangup,
02668 .answer = sip_answer,
02669 .read = sip_read,
02670 .write = sip_write,
02671 .write_video = sip_write,
02672 .write_text = sip_write,
02673 .indicate = sip_indicate,
02674 .transfer = sip_transfer,
02675 .fixup = sip_fixup,
02676 .send_digit_begin = sip_senddigit_begin,
02677 .send_digit_end = sip_senddigit_end,
02678 .bridge = ast_rtp_bridge,
02679 .early_bridge = ast_rtp_early_bridge,
02680 .send_text = sip_sendtext,
02681 .func_channel_read = acf_channel_read,
02682 .queryoption = sip_queryoption,
02683 .get_pvt_uniqueid = sip_get_callid,
02684 };
02685
02686
02687
02688
02689
02690
02691
02692 static struct ast_channel_tech sip_tech_info;
02693
02694
02695
02696 static struct ast_tls_config sip_tls_cfg;
02697
02698
02699 static struct ast_tls_config default_tls_cfg;
02700
02701
02702 static struct ast_tcptls_session_args sip_tcp_desc = {
02703 .accept_fd = -1,
02704 .master = AST_PTHREADT_NULL,
02705 .tls_cfg = NULL,
02706 .poll_timeout = -1,
02707 .name = "SIP TCP server",
02708 .accept_fn = ast_tcptls_server_root,
02709 .worker_fn = sip_tcp_worker_fn,
02710 };
02711
02712
02713 static struct ast_tcptls_session_args sip_tls_desc = {
02714 .accept_fd = -1,
02715 .master = AST_PTHREADT_NULL,
02716 .tls_cfg = &sip_tls_cfg,
02717 .poll_timeout = -1,
02718 .name = "SIP TLS server",
02719 .accept_fn = ast_tcptls_server_root,
02720 .worker_fn = sip_tcp_worker_fn,
02721 };
02722
02723
02724 #define IS_SIP_TECH(t) ((t) == &sip_tech || (t) == &sip_tech_info)
02725
02726
02727
02728
02729 static const char *map_x_s(const struct _map_x_s *table, int x, const char *errorstring)
02730 {
02731 const struct _map_x_s *cur;
02732
02733 for (cur = table; cur->s; cur++)
02734 if (cur->x == x)
02735 return cur->s;
02736 return errorstring;
02737 }
02738
02739
02740
02741
02742 static int map_s_x(const struct _map_x_s *table, const char *s, int errorvalue)
02743 {
02744 const struct _map_x_s *cur;
02745
02746 for (cur = table; cur->s; cur++)
02747 if (!strcasecmp(cur->s, s))
02748 return cur->x;
02749 return errorvalue;
02750 }
02751
02752
02753
02754 static struct ast_rtp_protocol sip_rtp = {
02755 .type = "SIP",
02756 .get_rtp_info = sip_get_rtp_peer,
02757 .get_vrtp_info = sip_get_vrtp_peer,
02758 .get_trtp_info = sip_get_trtp_peer,
02759 .set_rtp_peer = sip_set_rtp_peer,
02760 .get_codec = sip_get_codec,
02761 };
02762
02763
02764
02765
02766 static struct ast_variable *copy_vars(struct ast_variable *src)
02767 {
02768 struct ast_variable *res = NULL, *tmp, *v = NULL;
02769
02770 for (v = src ; v ; v = v->next) {
02771 if ((tmp = ast_variable_new(v->name, v->value, v->file))) {
02772 tmp->next = res;
02773 res = tmp;
02774 }
02775 }
02776 return res;
02777 }
02778
02779 static void tcptls_packet_destructor(void *obj)
02780 {
02781 struct tcptls_packet *packet = obj;
02782
02783 ast_free(packet->data);
02784 }
02785
02786 static void sip_tcptls_client_args_destructor(void *obj)
02787 {
02788 struct ast_tcptls_session_args *args = obj;
02789 if (args->tls_cfg) {
02790 ast_free(args->tls_cfg->certfile);
02791 ast_free(args->tls_cfg->cipher);
02792 ast_free(args->tls_cfg->cafile);
02793 ast_free(args->tls_cfg->capath);
02794 }
02795 ast_free(args->tls_cfg);
02796 ast_free((char *) args->name);
02797 }
02798
02799 static void sip_threadinfo_destructor(void *obj)
02800 {
02801 struct sip_threadinfo *th = obj;
02802 struct tcptls_packet *packet;
02803 if (th->alert_pipe[1] > -1) {
02804 close(th->alert_pipe[0]);
02805 }
02806 if (th->alert_pipe[1] > -1) {
02807 close(th->alert_pipe[1]);
02808 }
02809 th->alert_pipe[0] = th->alert_pipe[1] = -1;
02810
02811 while ((packet = AST_LIST_REMOVE_HEAD(&th->packet_q, entry))) {
02812 ao2_t_ref(packet, -1, "thread destruction, removing packet from frame queue");
02813 }
02814
02815 if (th->tcptls_session) {
02816 ao2_t_ref(th->tcptls_session, -1, "remove tcptls_session for sip_threadinfo object");
02817 }
02818 }
02819
02820
02821 static struct sip_threadinfo *sip_threadinfo_create(struct ast_tcptls_session_instance *tcptls_session, int transport)
02822 {
02823 struct sip_threadinfo *th;
02824
02825 if (!tcptls_session || !(th = ao2_alloc(sizeof(*th), sip_threadinfo_destructor))) {
02826 return NULL;
02827 }
02828
02829 th->alert_pipe[0] = th->alert_pipe[1] = -1;
02830
02831 if (pipe(th->alert_pipe) == -1) {
02832 ao2_t_ref(th, -1, "Failed to open alert pipe on sip_threadinfo");
02833 ast_log(LOG_ERROR, "Could not create sip alert pipe in tcptls thread, error %s\n", strerror(errno));
02834 return NULL;
02835 }
02836 ao2_t_ref(tcptls_session, +1, "tcptls_session ref for sip_threadinfo object");
02837 th->tcptls_session = tcptls_session;
02838 th->type = transport ? transport : (tcptls_session->ssl ? SIP_TRANSPORT_TLS: SIP_TRANSPORT_TCP);
02839 ao2_t_link(threadt, th, "Adding new tcptls helper thread");
02840 ao2_t_ref(th, -1, "Decrementing threadinfo ref from alloc, only table ref remains");
02841 return th;
02842 }
02843
02844
02845 static int sip_tcptls_write(struct ast_tcptls_session_instance *tcptls_session, const void *buf, size_t len)
02846 {
02847 int res = len;
02848 struct sip_threadinfo *th = NULL;
02849 struct tcptls_packet *packet = NULL;
02850 struct sip_threadinfo tmp = {
02851 .tcptls_session = tcptls_session,
02852 };
02853 enum sip_tcptls_alert alert = TCPTLS_ALERT_DATA;
02854
02855 if (!tcptls_session) {
02856 return XMIT_ERROR;
02857 }
02858
02859 ast_mutex_lock(&tcptls_session->lock);
02860
02861 if ((tcptls_session->fd == -1) ||
02862 !(th = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread")) ||
02863 !(packet = ao2_alloc(sizeof(*packet), tcptls_packet_destructor)) ||
02864 !(packet->data = ast_str_create(len))) {
02865 goto tcptls_write_setup_error;
02866 }
02867
02868
02869 ast_str_set(&packet->data, 0, "%s", (char *) buf);
02870 packet->len = len;
02871
02872
02873
02874
02875 ao2_lock(th);
02876 if (write(th->alert_pipe[1], &alert, sizeof(alert)) == -1) {
02877 ast_log(LOG_ERROR, "write() to alert pipe failed: %s\n", strerror(errno));
02878 ao2_t_ref(packet, -1, "could not write to alert pipe, remove packet");
02879 packet = NULL;
02880 res = XMIT_ERROR;
02881 } else {
02882 AST_LIST_INSERT_TAIL(&th->packet_q, packet, entry);
02883 }
02884 ao2_unlock(th);
02885
02886 ast_mutex_unlock(&tcptls_session->lock);
02887 ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo object after finding it");
02888 return res;
02889
02890 tcptls_write_setup_error:
02891 if (th) {
02892 ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo obj, could not create packet");
02893 }
02894 if (packet) {
02895 ao2_t_ref(packet, -1, "could not allocate packet's data");
02896 }
02897 ast_mutex_unlock(&tcptls_session->lock);
02898
02899 return XMIT_ERROR;
02900 }
02901
02902
02903 static void *sip_tcp_worker_fn(void *data)
02904 {
02905 struct ast_tcptls_session_instance *tcptls_session = data;
02906
02907 return _sip_tcp_helper_thread(NULL, tcptls_session);
02908 }
02909
02910
02911
02912
02913 static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session)
02914 {
02915 int res, cl;
02916 struct sip_request req = { 0, } , reqcpy = { 0, };
02917 struct sip_threadinfo *me = NULL;
02918 char buf[1024] = "";
02919 struct pollfd fds[2] = { { 0 }, { 0 }, };
02920 struct ast_tcptls_session_args *ca = NULL;
02921
02922
02923
02924
02925
02926
02927
02928
02929
02930
02931
02932 if (!tcptls_session->client) {
02933 if (!(me = sip_threadinfo_create(tcptls_session, tcptls_session->ssl ? SIP_TRANSPORT_TLS : SIP_TRANSPORT_TCP))) {
02934 goto cleanup;
02935 }
02936 ao2_t_ref(me, +1, "Adding threadinfo ref for tcp_helper_thread");
02937 } else {
02938 struct sip_threadinfo tmp = {
02939 .tcptls_session = tcptls_session,
02940 };
02941
02942 if ((!(ca = tcptls_session->parent)) ||
02943 (!(me = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread"))) ||
02944 (!(tcptls_session = ast_tcptls_client_start(tcptls_session)))) {
02945 goto cleanup;
02946 }
02947 }
02948
02949 me->threadid = pthread_self();
02950 ast_debug(2, "Starting thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");
02951
02952
02953 fds[0].fd = tcptls_session->fd;
02954 fds[1].fd = me->alert_pipe[0];
02955 fds[0].events = fds[1].events = POLLIN | POLLPRI;
02956
02957 if (!(req.data = ast_str_create(SIP_MIN_PACKET)))
02958 goto cleanup;
02959 if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET)))
02960 goto cleanup;
02961
02962 for (;;) {
02963 struct ast_str *str_save;
02964
02965 res = ast_poll(fds, 2, -1);
02966
02967 if (res < 0) {
02968 ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", tcptls_session->ssl ? "SSL": "TCP", res);
02969 goto cleanup;
02970 }
02971
02972
02973
02974 if (fds[0].revents) {
02975
02976 fds[0].revents = 0;
02977
02978
02979 str_save = req.data;
02980 memset(&req, 0, sizeof(req));
02981 req.data = str_save;
02982 ast_str_reset(req.data);
02983
02984 str_save = reqcpy.data;
02985 memset(&reqcpy, 0, sizeof(reqcpy));
02986 reqcpy.data = str_save;
02987 ast_str_reset(reqcpy.data);
02988
02989 memset(buf, 0, sizeof(buf));
02990
02991 if (tcptls_session->ssl) {
02992 set_socket_transport(&req.socket, SIP_TRANSPORT_TLS);
02993 req.socket.port = htons(ourport_tls);
02994 } else {
02995 set_socket_transport(&req.socket, SIP_TRANSPORT_TCP);
02996 req.socket.port = htons(ourport_tcp);
02997 }
02998 req.socket.fd = tcptls_session->fd;
02999
03000
03001 while (req.len < 4 || strncmp(REQ_OFFSET_TO_STR(&req, len - 4), "\r\n\r\n", 4)) {
03002 ast_mutex_lock(&tcptls_session->lock);
03003 if (!fgets(buf, sizeof(buf), tcptls_session->f)) {
03004 ast_mutex_unlock(&tcptls_session->lock);
03005 goto cleanup;
03006 }
03007 ast_mutex_unlock(&tcptls_session->lock);
03008 if (me->stop)
03009 goto cleanup;
03010 ast_str_append(&req.data, 0, "%s", buf);
03011 req.len = req.data->used;
03012 }
03013 copy_request(&reqcpy, &req);
03014 parse_request(&reqcpy);
03015
03016 if (sscanf(get_header(&reqcpy, "Content-Length"), "%30d", &cl)) {
03017 while (cl > 0) {
03018 size_t bytes_read;
03019 ast_mutex_lock(&tcptls_session->lock);
03020 if (!(bytes_read = fread(buf, 1, MIN(sizeof(buf) - 1, cl), tcptls_session->f))) {
03021 ast_mutex_unlock(&tcptls_session->lock);
03022 goto cleanup;
03023 }
03024 buf[bytes_read] = '\0';
03025 ast_mutex_unlock(&tcptls_session->lock);
03026 if (me->stop)
03027 goto cleanup;
03028 cl -= strlen(buf);
03029 ast_str_append(&req.data, 0, "%s", buf);
03030 req.len = req.data->used;
03031 }
03032 }
03033
03034
03035
03036 req.socket.tcptls_session = tcptls_session;
03037 handle_request_do(&req, &tcptls_session->remote_address);
03038 }
03039
03040 if (fds[1].revents) {
03041 enum sip_tcptls_alert alert;
03042 struct tcptls_packet *packet;
03043
03044 fds[1].revents = 0;
03045
03046 if (read(me->alert_pipe[0], &alert, sizeof(alert)) == -1) {
03047 ast_log(LOG_ERROR, "read() failed: %s\n", strerror(errno));
03048 continue;
03049 }
03050
03051 switch (alert) {
03052 case TCPTLS_ALERT_STOP:
03053 goto cleanup;
03054 case TCPTLS_ALERT_DATA:
03055 ao2_lock(me);
03056 if (!(packet = AST_LIST_REMOVE_HEAD(&me->packet_q, entry))) {
03057 ast_log(LOG_WARNING, "TCPTLS thread alert_pipe indicated packet should be sent, but frame_q is empty");
03058 } else if (ast_tcptls_server_write(tcptls_session, ast_str_buffer(packet->data), packet->len) == -1) {
03059 ast_log(LOG_WARNING, "Failure to write to tcp/tls socket\n");
03060 }
03061
03062 if (packet) {
03063 ao2_t_ref(packet, -1, "tcptls packet sent, this is no longer needed");
03064 }
03065 ao2_unlock(me);
03066 break;
03067 default:
03068 ast_log(LOG_ERROR, "Unknown tcptls thread alert '%d'\n", alert);
03069 }
03070 }
03071 }
03072
03073 ast_debug(2, "Shutting down thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");
03074
03075 cleanup:
03076 if (me) {
03077 ao2_t_unlink(threadt, me, "Removing tcptls helper thread, thread is closing");
03078 ao2_t_ref(me, -1, "Removing tcp_helper_threads threadinfo ref");
03079 }
03080 deinit_req(&reqcpy);
03081 deinit_req(&req);
03082
03083
03084 if (ca) {
03085 ao2_t_ref(ca, -1, "closing tcptls thread, getting rid of client tcptls_session arguments");
03086 }
03087
03088 if (tcptls_session) {
03089 ast_mutex_lock(&tcptls_session->lock);
03090 if (tcptls_session->f) {
03091 fclose(tcptls_session->f);
03092 tcptls_session->f = NULL;
03093 }
03094 if (tcptls_session->fd != -1) {
03095 close(tcptls_session->fd);
03096 tcptls_session->fd = -1;
03097 }
03098 tcptls_session->parent = NULL;
03099 ast_mutex_unlock(&tcptls_session->lock);
03100
03101 ao2_ref(tcptls_session, -1);
03102 tcptls_session = NULL;
03103 }
03104 return NULL;
03105 }
03106
03107
03108
03109 static int peer_is_marked(void *peerobj, void *arg, int flags)
03110 {
03111 struct sip_peer *peer = peerobj;
03112 return peer->the_mark ? CMP_MATCH : 0;
03113 }
03114
03115
03116
03117 static void unlink_marked_peers_from_tables(void)
03118 {
03119 ao2_t_callback(peers, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, peer_is_marked, NULL,
03120 "initiating callback to remove marked peers");
03121 ao2_t_callback(peers_by_ip, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, peer_is_marked, NULL,
03122 "initiating callback to remove marked peers");
03123 }
03124
03125
03126 static void unlink_peer_from_tables(struct sip_peer *peer)
03127 {
03128 ao2_t_unlink(peers, peer, "ao2_unlink of peer from peers table");
03129 if (peer->addr.sin_addr.s_addr) {
03130 ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
03131 }
03132 }
03133
03134
03135
03136
03137
03138
03139 static void *unref_peer(struct sip_peer *peer, char *tag)
03140 {
03141 ao2_t_ref(peer, -1, tag);
03142 return NULL;
03143 }
03144
03145 static struct sip_peer *ref_peer(struct sip_peer *peer, char *tag)
03146 {
03147 ao2_t_ref(peer, 1, tag);
03148 return peer;
03149 }
03150
03151
03152
03153
03154
03155
03156
03157
03158
03159
03160
03161
03162 static void ref_proxy(struct sip_pvt *pvt, struct sip_proxy *proxy)
03163 {
03164 struct sip_proxy *old_obproxy = pvt->outboundproxy;
03165
03166
03167
03168 if (proxy && proxy != &sip_cfg.outboundproxy) {
03169 ao2_ref(proxy, +1);
03170 }
03171 pvt->outboundproxy = proxy;
03172 if (old_obproxy && old_obproxy != &sip_cfg.outboundproxy) {
03173 ao2_ref(old_obproxy, -1);
03174 }
03175 }
03176
03177
03178
03179
03180
03181
03182
03183
03184 static void *dialog_unlink_all(struct sip_pvt *dialog, int lockowner, int lockdialoglist)
03185 {
03186 struct sip_pkt *cp;
03187
03188 dialog_ref(dialog, "Let's bump the count in the unlink so it doesn't accidentally become dead before we are done");
03189
03190 ao2_t_unlink(dialogs, dialog, "unlinking dialog via ao2_unlink");
03191
03192
03193 if (dialog->owner) {
03194 if (lockowner)
03195 ast_channel_lock(dialog->owner);
03196 ast_debug(1, "Detaching from channel %s\n", dialog->owner->name);
03197 dialog->owner->tech_pvt = dialog_unref(dialog->owner->tech_pvt, "resetting channel dialog ptr in unlink_all");
03198 if (lockowner)
03199 ast_channel_unlock(dialog->owner);
03200 }
03201 if (dialog->registry) {
03202 if (dialog->registry->call == dialog)
03203 dialog->registry->call = dialog_unref(dialog->registry->call, "nulling out the registry's call dialog field in unlink_all");
03204 dialog->registry = registry_unref(dialog->registry, "delete dialog->registry");
03205 }
03206 if (dialog->stateid > -1) {
03207 ast_extension_state_del(dialog->stateid, NULL);
03208 dialog_unref(dialog, "removing extension_state, should unref the associated dialog ptr that was stored there.");
03209 dialog->stateid = -1;
03210 }
03211
03212 if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog)
03213 dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
03214 if (dialog->relatedpeer && dialog->relatedpeer->call == dialog)
03215 dialog->relatedpeer->call = dialog_unref(dialog->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
03216
03217
03218 while((cp = dialog->packets)) {
03219 dialog->packets = dialog->packets->next;
03220 AST_SCHED_DEL(sched, cp->retransid);
03221 dialog_unref(cp->owner, "remove all current packets in this dialog, and the pointer to the dialog too as part of __sip_destroy");
03222 if (cp->data) {
03223 ast_free(cp->data);
03224 }
03225 ast_free(cp);
03226 }
03227
03228 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"));
03229
03230 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"));
03231
03232 if (dialog->autokillid > -1)
03233 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"));
03234
03235 if (dialog->request_queue_sched_id > -1) {
03236 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"));
03237 }
03238
03239 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"));
03240
03241 if (dialog->t38id > -1) {
03242 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"));
03243 }
03244
03245 dialog_unref(dialog, "Let's unbump the count in the unlink so the poor pvt can disappear if it is time");
03246 return NULL;
03247 }
03248
03249 static void *registry_unref(struct sip_registry *reg, char *tag)
03250 {
03251 ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount - 1);
03252 ASTOBJ_UNREF(reg, sip_registry_destroy);
03253 return NULL;
03254 }
03255
03256
03257 static struct sip_registry *registry_addref(struct sip_registry *reg, char *tag)
03258 {
03259 ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount + 1);
03260 return ASTOBJ_REF(reg);
03261 }
03262
03263
03264 static struct ast_udptl_protocol sip_udptl = {
03265 type: "SIP",
03266 get_udptl_info: sip_get_udptl_peer,
03267 set_udptl_peer: sip_set_udptl_peer,
03268 };
03269
03270 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
03271 __attribute__((format(printf, 2, 3)));
03272
03273
03274
03275 static const char *referstatus2str(enum referstatus rstatus)
03276 {
03277 return map_x_s(referstatusstrings, rstatus, "");
03278 }
03279
03280 static inline void pvt_set_needdestroy(struct sip_pvt *pvt, const char *reason)
03281 {
03282 append_history(pvt, "NeedDestroy", "Setting needdestroy because %s", reason);
03283 pvt->needdestroy = 1;
03284 }
03285
03286
03287
03288
03289 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
03290 {
03291 if (p->initreq.headers)
03292 ast_debug(1, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
03293 else
03294 ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
03295
03296 copy_request(&p->initreq, req);
03297 parse_request(&p->initreq);
03298 if (req->debug)
03299 ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
03300 }
03301
03302
03303 static void sip_alreadygone(struct sip_pvt *dialog)
03304 {
03305 ast_debug(3, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
03306 dialog->alreadygone = 1;
03307 }
03308
03309
03310 static int proxy_update(struct sip_proxy *proxy)
03311 {
03312
03313
03314 if (!inet_aton(proxy->name, &proxy->ip.sin_addr)) {
03315
03316
03317 if (ast_get_ip_or_srv(&proxy->ip, proxy->name, sip_cfg.srvlookup ? "_sip._udp" : NULL) < 0) {
03318 ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
03319 return FALSE;
03320 }
03321 }
03322 proxy->last_dnsupdate = time(NULL);
03323 return TRUE;
03324 }
03325
03326
03327
03328
03329
03330 static int port_str2int(const char *pt, unsigned int standard)
03331 {
03332 int port = standard;
03333 if (ast_strlen_zero(pt) || (sscanf(pt, "%30d", &port) != 1) || (port < 1) || (port > 65535)) {
03334 port = standard;
03335 }
03336
03337 return port;
03338 }
03339
03340
03341 static struct sip_proxy *proxy_allocate(char *name, char *port, int force)
03342 {
03343 struct sip_proxy *proxy;
03344
03345 if (ast_strlen_zero(name)) {
03346 return NULL;
03347 }
03348
03349 proxy = ao2_alloc(sizeof(*proxy), NULL);
03350 if (!proxy)
03351 return NULL;
03352 proxy->force = force;
03353 ast_copy_string(proxy->name, name, sizeof(proxy->name));
03354 proxy->ip.sin_port = htons(port_str2int(port, STANDARD_SIP_PORT));
03355 proxy->ip.sin_family = AF_INET;
03356 proxy_update(proxy);
03357 return proxy;
03358 }
03359
03360
03361 static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
03362 {
03363 if (peer && peer->outboundproxy) {
03364 if (sipdebug)
03365 ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
03366 append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
03367 return peer->outboundproxy;
03368 }
03369 if (sip_cfg.outboundproxy.name[0]) {
03370 if (sipdebug)
03371 ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
03372 append_history(dialog, "OBproxy", "Using global obproxy %s", sip_cfg.outboundproxy.name);
03373 return &sip_cfg.outboundproxy;
03374 }
03375 if (sipdebug)
03376 ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
03377 return NULL;
03378 }
03379
03380
03381
03382
03383
03384
03385
03386 static int method_match(enum sipmethod id, const char *name)
03387 {
03388 int len = strlen(sip_methods[id].text);
03389 int l_name = name ? strlen(name) : 0;
03390
03391 return (l_name >= len && name[len] < 33 &&
03392 !strncasecmp(sip_methods[id].text, name, len));
03393 }
03394
03395
03396 static int find_sip_method(const char *msg)
03397 {
03398 int i, res = 0;
03399
03400 if (ast_strlen_zero(msg))
03401 return 0;
03402 for (i = 1; i < ARRAY_LEN(sip_methods) && !res; i++) {
03403 if (method_match(i, msg))
03404 res = sip_methods[i].id;
03405 }
03406 return res;
03407 }
03408
03409
03410 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported)
03411 {
03412 char *next, *sep;
03413 char *temp;
03414 unsigned int profile = 0;
03415 int i, found;
03416
03417 if (ast_strlen_zero(supported) )
03418 return 0;
03419 temp = ast_strdupa(supported);
03420
03421 if (sipdebug)
03422 ast_debug(3, "Begin: parsing SIP \"Supported: %s\"\n", supported);
03423
03424 for (next = temp; next; next = sep) {
03425 found = FALSE;
03426 if ( (sep = strchr(next, ',')) != NULL)
03427 *sep++ = '\0';
03428 next = ast_skip_blanks(next);
03429 if (sipdebug)
03430 ast_debug(3, "Found SIP option: -%s-\n", next);
03431 for (i = 0; i < ARRAY_LEN(sip_options); i++) {
03432 if (!strcasecmp(next, sip_options[i].text)) {
03433 profile |= sip_options[i].id;
03434 found = TRUE;
03435 if (sipdebug)
03436 ast_debug(3, "Matched SIP option: %s\n", next);
03437 break;
03438 }
03439 }
03440
03441
03442
03443
03444
03445 if (!found)
03446 profile |= SIP_OPT_UNKNOWN;
03447
03448 if (!found && sipdebug) {
03449 if (!strncasecmp(next, "x-", 2))
03450 ast_debug(3, "Found private SIP option, not supported: %s\n", next);
03451 else
03452 ast_debug(3, "Found no match for SIP option: %s (Please file bug report!)\n", next);
03453 }
03454 }
03455
03456 if (pvt)
03457 pvt->sipoptions = profile;
03458 return profile;
03459 }
03460
03461
03462 static inline int sip_debug_test_addr(const struct sockaddr_in *addr)
03463 {
03464 if (!sipdebug)
03465 return 0;
03466 if (debugaddr.sin_addr.s_addr) {
03467 if (((ntohs(debugaddr.sin_port) != 0)
03468 && (debugaddr.sin_port != addr->sin_port))
03469 || (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
03470 return 0;
03471 }
03472 return 1;
03473 }
03474
03475
03476 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p)
03477 {
03478 if (p->outboundproxy)
03479 return &p->outboundproxy->ip;
03480
03481 return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? &p->recv : &p->sa;
03482 }
03483
03484
03485 static const char *sip_nat_mode(const struct sip_pvt *p)
03486 {
03487 return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? "NAT" : "no NAT";
03488 }
03489
03490
03491 static inline int sip_debug_test_pvt(struct sip_pvt *p)
03492 {
03493 if (!sipdebug)
03494 return 0;
03495 return sip_debug_test_addr(sip_real_dst(p));
03496 }
03497
03498
03499 static int get_transport_str2enum(const char *transport)
03500 {
03501 int res = 0;
03502
03503 if (ast_strlen_zero(transport)) {
03504 return res;
03505 }
03506
03507 if (!strcasecmp(transport, "udp")) {
03508 res |= SIP_TRANSPORT_UDP;
03509 }
03510 if (!strcasecmp(transport, "tcp")) {
03511 res |= SIP_TRANSPORT_TCP;
03512 }
03513 if (!strcasecmp(transport, "tls")) {
03514 res |= SIP_TRANSPORT_TLS;
03515 }
03516
03517 return res;
03518 }
03519
03520
03521 static inline const char *get_transport_list(unsigned int transports) {
03522 switch (transports) {
03523 case SIP_TRANSPORT_UDP:
03524 return "UDP";
03525 case SIP_TRANSPORT_TCP:
03526 return "TCP";
03527 case SIP_TRANSPORT_TLS:
03528 return "TLS";
03529 case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TCP:
03530 return "TCP,UDP";
03531 case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TLS:
03532 return "TLS,UDP";
03533 case SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS:
03534 return "TLS,TCP";
03535 default:
03536 return transports ?
03537 "TLS,TCP,UDP" : "UNKNOWN";
03538 }
03539 }
03540
03541
03542 static inline const char *get_transport(enum sip_transport t)
03543 {
03544 switch (t) {
03545 case SIP_TRANSPORT_UDP:
03546 return "UDP";
03547 case SIP_TRANSPORT_TCP:
03548 return "TCP";
03549 case SIP_TRANSPORT_TLS:
03550 return "TLS";
03551 }
03552
03553 return "UNKNOWN";
03554 }
03555
03556
03557 static inline const char *get_srv_protocol(enum sip_transport t)
03558 {
03559 switch (t) {
03560 case SIP_TRANSPORT_UDP:
03561 return "udp";
03562 case SIP_TRANSPORT_TLS:
03563 case SIP_TRANSPORT_TCP:
03564 return "tcp";
03565 }
03566
03567 return "udp";
03568 }
03569
03570
03571 static inline const char *get_srv_service(enum sip_transport t)
03572 {
03573 switch (t) {
03574 case SIP_TRANSPORT_TCP:
03575 case SIP_TRANSPORT_UDP:
03576 return "sip";
03577 case SIP_TRANSPORT_TLS:
03578 return "sips";
03579 }
03580 return "sip";
03581 }
03582
03583
03584
03585
03586
03587
03588
03589 static inline const char *get_transport_pvt(struct sip_pvt *p)
03590 {
03591 if (p->outboundproxy && p->outboundproxy->transport) {
03592 set_socket_transport(&p->socket, p->outboundproxy->transport);
03593 }
03594
03595 return get_transport(p->socket.type);
03596 }
03597
03598
03599
03600
03601
03602
03603 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len)
03604 {
03605 int res = 0;
03606 const struct sockaddr_in *dst = sip_real_dst(p);
03607
03608 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));
03609
03610 if (sip_prepare_socket(p) < 0)
03611 return XMIT_ERROR;
03612
03613 if (p->socket.type == SIP_TRANSPORT_UDP) {
03614 res = sendto(p->socket.fd, data->str, len, 0, (const struct sockaddr *)dst, sizeof(struct sockaddr_in));
03615 } else if (p->socket.tcptls_session) {
03616 res = sip_tcptls_write(p->socket.tcptls_session, data->str, len);
03617 } else {
03618 ast_debug(2, "Socket type is TCP but no tcptls_session is present to write to\n");
03619 return XMIT_ERROR;
03620 }
03621
03622 if (res == -1) {
03623 switch (errno) {
03624 case EBADF:
03625 case EHOSTUNREACH:
03626 case ENETDOWN:
03627 case ENETUNREACH:
03628 case ECONNREFUSED:
03629 res = XMIT_ERROR;
03630 }
03631 }
03632 if (res != len)
03633 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));
03634
03635 return res;
03636 }
03637
03638
03639 static void build_via(struct sip_pvt *p)
03640 {
03641
03642 const char *rport = ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_RFC3581 ? ";rport" : "";
03643
03644
03645 snprintf(p->via, sizeof(p->via), "SIP/2.0/%s %s:%d;branch=z9hG4bK%08x%s",
03646 get_transport_pvt(p),
03647 ast_inet_ntoa(p->ourip.sin_addr),
03648 ntohs(p->ourip.sin_port), (int) p->branch, rport);
03649 }
03650
03651
03652
03653
03654
03655
03656
03657
03658 static void ast_sip_ouraddrfor(struct in_addr *them, struct sockaddr_in *us, struct sip_pvt *p)
03659 {
03660 struct sockaddr_in theirs;
03661
03662
03663
03664
03665
03666
03667
03668
03669
03670
03671
03672
03673 int want_remap;
03674
03675 *us = internip;
03676
03677 ast_ouraddrfor(them, &us->sin_addr);
03678 theirs.sin_addr = *them;
03679
03680 want_remap = localaddr &&
03681 (externip.sin_addr.s_addr || stunaddr.sin_addr.s_addr) &&
03682 ast_apply_ha(localaddr, &theirs) == AST_SENSE_ALLOW ;
03683
03684 if (want_remap &&
03685 (!sip_cfg.matchexterniplocally || !ast_apply_ha(localaddr, us)) ) {
03686
03687 if (externexpire && time(NULL) >= externexpire) {
03688 if (stunaddr.sin_addr.s_addr) {
03689 ast_stun_request(sipsock, &stunaddr, NULL, &externip);
03690 } else {
03691 if (ast_parse_arg(externhost, PARSE_INADDR, &externip))
03692 ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
03693 }
03694 externexpire = time(NULL) + externrefresh;
03695 }
03696 if (externip.sin_addr.s_addr)
03697 *us = externip;
03698 else
03699 ast_log(LOG_WARNING, "stun failed\n");
03700 ast_debug(1, "Target address %s is not local, substituting externip\n",
03701 ast_inet_ntoa(*(struct in_addr *)&them->s_addr));
03702 } else if (p) {
03703
03704 switch (p->socket.type) {
03705 case SIP_TRANSPORT_TCP:
03706 if (sip_tcp_desc.local_address.sin_addr.s_addr) {
03707 *us = sip_tcp_desc.local_address;
03708 } else {
03709 us->sin_port = sip_tcp_desc.local_address.sin_port;
03710 }
03711 break;
03712 case SIP_TRANSPORT_TLS:
03713 if (sip_tls_desc.local_address.sin_addr.s_addr) {
03714 *us = sip_tls_desc.local_address;
03715 } else {
03716 us->sin_port = sip_tls_desc.local_address.sin_port;
03717 }
03718 break;
03719 case SIP_TRANSPORT_UDP:
03720
03721 default:
03722 if (bindaddr.sin_addr.s_addr) {
03723 *us = bindaddr;
03724 }
03725 }
03726 } else if (bindaddr.sin_addr.s_addr) {
03727 *us = bindaddr;
03728 }
03729 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));
03730 }
03731
03732
03733 static __attribute__((format(printf, 2, 0))) void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
03734 {
03735 char buf[80], *c = buf;
03736 struct sip_history *hist;
03737 int l;
03738
03739 vsnprintf(buf, sizeof(buf), fmt, ap);
03740 strsep(&c, "\r\n");
03741 l = strlen(buf) + 1;
03742 if (!(hist = ast_calloc(1, sizeof(*hist) + l)))
03743 return;
03744 if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
03745 ast_free(hist);
03746 return;
03747 }
03748 memcpy(hist->event, buf, l);
03749 if (p->history_entries == MAX_HISTORY_ENTRIES) {
03750 struct sip_history *oldest;
03751 oldest = AST_LIST_REMOVE_HEAD(p->history, list);
03752 p->history_entries--;
03753 ast_free(oldest);
03754 }
03755 AST_LIST_INSERT_TAIL(p->history, hist, list);
03756 p->history_entries++;
03757 }
03758
03759
03760 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
03761 {
03762 va_list ap;
03763
03764 if (!p)
03765 return;
03766
03767 if (!p->do_history && !recordhistory && !dumphistory)
03768 return;
03769
03770 va_start(ap, fmt);
03771 append_history_va(p, fmt, ap);
03772 va_end(ap);
03773
03774 return;
03775 }
03776
03777
03778 static int retrans_pkt(const void *data)
03779 {
03780 struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
03781 int reschedule = DEFAULT_RETRANS;
03782 int xmitres = 0;
03783
03784
03785 sip_pvt_lock(pkt->owner);
03786
03787 if (pkt->retrans < MAX_RETRANS) {
03788 pkt->retrans++;
03789 if (!pkt->timer_t1) {
03790 if (sipdebug)
03791 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);
03792 } else {
03793 int siptimer_a;
03794
03795 if (sipdebug)
03796 ast_debug(4, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n", pkt->retransid, pkt->retrans, sip_methods[pkt->method].text, pkt->method);
03797 if (!pkt->timer_a)
03798 pkt->timer_a = 2 ;
03799 else
03800 pkt->timer_a = 2 * pkt->timer_a;
03801
03802
03803 siptimer_a = pkt->timer_t1 * pkt->timer_a;
03804 if (pkt->method != SIP_INVITE && siptimer_a > 4000)
03805 siptimer_a = 4000;
03806
03807
03808 reschedule = siptimer_a;
03809 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);
03810 }
03811
03812 if (sip_debug_test_pvt(pkt->owner)) {
03813 const struct sockaddr_in *dst = sip_real_dst(pkt->owner);
03814 ast_verbose("Retransmitting #%d (%s) to %s:%d:\n%s\n---\n",
03815 pkt->retrans, sip_nat_mode(pkt->owner),
03816 ast_inet_ntoa(dst->sin_addr),
03817 ntohs(dst->sin_port), pkt->data->str);
03818 }
03819
03820 append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data->str);
03821 xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
03822 sip_pvt_unlock(pkt->owner);
03823 if (xmitres == XMIT_ERROR)
03824 ast_log(LOG_WARNING, "Network error on retransmit in dialog %s\n", pkt->owner->callid);
03825 else
03826 return reschedule;
03827 }
03828
03829 if (pkt->owner && pkt->method != SIP_OPTIONS && xmitres == 0) {
03830 if (pkt->is_fatal || sipdebug)
03831 ast_log(LOG_WARNING, "Maximum retries exceeded on transmission %s for seqno %d (%s %s) -- See doc/sip-retransmit.txt.\n",
03832 pkt->owner->callid, pkt->seqno,
03833 pkt->is_fatal ? "Critical" : "Non-critical", pkt->is_resp ? "Response" : "Request");
03834 } else if (pkt->method == SIP_OPTIONS && sipdebug) {
03835 ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s) -- See doc/sip-retransmit.txt.\n", pkt->owner->callid);
03836
03837 }
03838 if (xmitres == XMIT_ERROR) {
03839 ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission on Call ID %s\n", pkt->owner->callid);
03840 append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03841 } else
03842 append_history(pkt->owner, "MaxRetries", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03843
03844 pkt->retransid = -1;
03845
03846 if (pkt->is_fatal) {
03847 while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
03848 sip_pvt_unlock(pkt->owner);
03849 usleep(1);
03850 sip_pvt_lock(pkt->owner);
03851 }
03852
03853 if (pkt->owner->owner && !pkt->owner->owner->hangupcause)
03854 pkt->owner->owner->hangupcause = AST_CAUSE_NO_USER_RESPONSE;
03855
03856 if (pkt->owner->owner) {
03857 sip_alreadygone(pkt->owner);
03858 ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet (see doc/sip-retransmit.txt).\n", pkt->owner->callid);
03859 ast_queue_hangup_with_cause(pkt->owner->owner, AST_CAUSE_PROTOCOL_ERROR);
03860 ast_channel_unlock(pkt->owner->owner);
03861 } else {
03862
03863
03864
03865 if (pkt->method != SIP_OPTIONS && pkt->method != SIP_REGISTER) {
03866 pvt_set_needdestroy(pkt->owner, "no response to critical packet");
03867 sip_alreadygone(pkt->owner);
03868 append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
03869 }
03870 }
03871 }
03872
03873 if (pkt->method == SIP_BYE) {
03874
03875 if (pkt->owner->owner)
03876 ast_channel_unlock(pkt->owner->owner);
03877 append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
03878 pvt_set_needdestroy(pkt->owner, "no response to BYE");
03879 }
03880
03881
03882 for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
03883 if (cur == pkt) {
03884 UNLINK(cur, pkt->owner->packets, prev);
03885 sip_pvt_unlock(pkt->owner);
03886 if (pkt->owner)
03887 pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
03888 if (pkt->data)
03889 ast_free(pkt->data);
03890 pkt->data = NULL;
03891 ast_free(pkt);
03892 return 0;
03893 }
03894 }
03895
03896 ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
03897 sip_pvt_unlock(pkt->owner);
03898 return 0;
03899 }
03900
03901
03902
03903
03904 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)
03905 {
03906 struct sip_pkt *pkt = NULL;
03907 int siptimer_a = DEFAULT_RETRANS;
03908 int xmitres = 0;
03909 int respid;
03910
03911 if (sipmethod == SIP_INVITE) {
03912
03913 p->pendinginvite = seqno;
03914 }
03915
03916
03917
03918
03919 if (!(p->socket.type & SIP_TRANSPORT_UDP)) {
03920 xmitres = __sip_xmit(p, data, len);
03921 if (xmitres == XMIT_ERROR) {
03922 append_history(p, "XmitErr", "%s", fatal ? "(Critical)" : "(Non-critical)");
03923 return AST_FAILURE;
03924 } else {
03925 return AST_SUCCESS;
03926 }
03927 }
03928
03929 if (!(pkt = ast_calloc(1, sizeof(*pkt) + len + 1)))
03930 return AST_FAILURE;
03931
03932 if (!(pkt->data = ast_str_create(len))) {
03933 ast_free(pkt);
03934 return AST_FAILURE;
03935 }
03936 ast_str_set(&pkt->data, 0, "%s%s", data->str, "\0");
03937 pkt->packetlen = len;
03938
03939 pkt->method = sipmethod;
03940 pkt->seqno = seqno;
03941 pkt->is_resp = resp;
03942 pkt->is_fatal = fatal;
03943 pkt->owner = dialog_ref(p, "__sip_reliable_xmit: setting pkt->owner");
03944 pkt->next = p->packets;
03945 p->packets = pkt;
03946 if (resp) {
03947
03948 if (sscanf(ast_str_buffer(pkt->data), "SIP/2.0 %30u", &respid) == 1) {
03949 pkt->response_code = respid;
03950 }
03951 }
03952 pkt->timer_t1 = p->timer_t1;
03953 pkt->retransid = -1;
03954 if (pkt->timer_t1)
03955 siptimer_a = pkt->timer_t1 * 2;
03956
03957
03958 AST_SCHED_REPLACE_VARIABLE(pkt->retransid, sched, siptimer_a, retrans_pkt, pkt, 1);
03959 if (sipdebug)
03960 ast_debug(4, "*** SIP TIMER: Initializing retransmit timer on packet: Id #%d\n", pkt->retransid);
03961
03962 xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
03963
03964 if (xmitres == XMIT_ERROR) {
03965 append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03966 ast_log(LOG_ERROR, "Serious Network Trouble; __sip_xmit returns error for pkt data\n");
03967 AST_SCHED_DEL(sched, pkt->retransid);
03968 p->packets = pkt->next;
03969 pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
03970 ast_free(pkt->data);
03971 ast_free(pkt);
03972 return AST_FAILURE;
03973 } else {
03974 return AST_SUCCESS;
03975 }
03976 }
03977
03978
03979
03980
03981
03982
03983 static int __sip_autodestruct(const void *data)
03984 {
03985 struct sip_pvt *p = (struct sip_pvt *)data;
03986
03987
03988 if (p->subscribed) {
03989 transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE);
03990 p->subscribed = NONE;
03991 append_history(p, "Subscribestatus", "timeout");
03992 ast_debug(3, "Re-scheduled destruction of SIP subscription %s\n", p->callid ? p->callid : "<unknown>");
03993 return 10000;
03994 }
03995
03996
03997 if (p->packets) {
03998 if (!p->needdestroy) {
03999 char method_str[31];
04000 ast_debug(3, "Re-scheduled destruction of SIP call %s\n", p->callid ? p->callid : "<unknown>");
04001 append_history(p, "ReliableXmit", "timeout");
04002 if (sscanf(p->lastmsg, "Tx: %30s", method_str) == 1 || sscanf(p->lastmsg, "Rx: %30s", method_str) == 1) {
04003 if (method_match(SIP_CANCEL, method_str) || method_match(SIP_BYE, method_str)) {
04004 pvt_set_needdestroy(p, "autodestruct");
04005 }
04006 }
04007 return 10000;
04008 } else {
04009
04010 __sip_pretend_ack(p);
04011 }
04012 }
04013
04014 if (p->subscribed == MWI_NOTIFICATION)
04015 if (p->relatedpeer)
04016 p->relatedpeer = unref_peer(p->relatedpeer, "__sip_autodestruct: unref peer p->relatedpeer");
04017
04018
04019 p->autokillid = -1;
04020
04021 if (p->owner) {
04022 ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
04023 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
04024 } else if (p->refer && !p->alreadygone) {
04025 ast_debug(3, "Finally hanging up channel after transfer: %s\n", p->callid);
04026 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
04027 append_history(p, "ReferBYE", "Sending BYE on transferer call leg %s", p->callid);
04028 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
04029 } else {
04030 append_history(p, "AutoDestroy", "%s", p->callid);
04031 ast_debug(3, "Auto destroying SIP dialog '%s'\n", p->callid);
04032 dialog_unlink_all(p, TRUE, TRUE);
04033
04034
04035
04036 }
04037 dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
04038 return 0;
04039 }
04040
04041
04042 static void sip_scheddestroy(struct sip_pvt *p, int ms)
04043 {
04044 if (ms < 0) {
04045 if (p->timer_t1 == 0) {
04046 p->timer_t1 = global_t1;
04047 p->timer_b = global_timer_b;
04048 }
04049 ms = p->timer_t1 * 64;
04050 }
04051 if (sip_debug_test_pvt(p))
04052 ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
04053 if (sip_cancel_destroy(p))
04054 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
04055
04056 if (p->do_history)
04057 append_history(p, "SchedDestroy", "%d ms", ms);
04058 p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, dialog_ref(p, "setting ref as passing into ast_sched_add for __sip_autodestruct"));
04059
04060 if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_schedid > 0)
04061 stop_session_timer(p);
04062 }
04063
04064
04065
04066
04067
04068 static int sip_cancel_destroy(struct sip_pvt *p)
04069 {
04070 int res = 0;
04071 if (p->autokillid > -1) {
04072 int res3;
04073
04074 if (!(res3 = ast_sched_del(sched, p->autokillid))) {
04075 append_history(p, "CancelDestroy", "");
04076 p->autokillid = -1;
04077 dialog_unref(p, "dialog unrefd because autokillid is de-sched'd");
04078 }
04079 }
04080 return res;
04081 }
04082
04083
04084
04085 static int __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
04086 {
04087 struct sip_pkt *cur, *prev = NULL;
04088 const char *msg = "Not Found";
04089 int res = FALSE;
04090
04091
04092
04093
04094
04095
04096 if (p->outboundproxy && !p->outboundproxy->force){
04097 ref_proxy(p, NULL);
04098 }
04099
04100 for (cur = p->packets; cur; prev = cur, cur = cur->next) {
04101 if (cur->seqno != seqno || cur->is_resp != resp)
04102 continue;
04103 if (cur->is_resp || cur->method == sipmethod) {
04104 res = TRUE;
04105 msg = "Found";
04106 if (!resp && (seqno == p->pendinginvite)) {
04107 ast_debug(1, "Acked pending invite %d\n", p->pendinginvite);
04108 p->pendinginvite = 0;
04109 }
04110 if (cur->retransid > -1) {
04111 if (sipdebug)
04112 ast_debug(4, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
04113 }
04114
04115
04116
04117
04118
04119
04120
04121
04122
04123
04124
04125
04126
04127
04128
04129
04130 while (cur->retransid > -1 && ast_sched_del(sched, cur->retransid)) {
04131 sip_pvt_unlock(p);
04132 usleep(1);
04133 sip_pvt_lock(p);
04134 }
04135 UNLINK(cur, p->packets, prev);
04136 dialog_unref(cur->owner, "unref pkt cur->owner dialog from sip ack before freeing pkt");
04137 if (cur->data)
04138 ast_free(cur->data);
04139 ast_free(cur);
04140 break;
04141 }
04142 }
04143 ast_debug(1, "Stopping retransmission on '%s' of %s %d: Match %s\n",
04144 p->callid, resp ? "Response" : "Request", seqno, msg);
04145 return res;
04146 }
04147
04148
04149
04150 static void __sip_pretend_ack(struct sip_pvt *p)
04151 {
04152 struct sip_pkt *cur = NULL;
04153
04154 while (p->packets) {
04155 int method;
04156 if (cur == p->packets) {
04157 ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
04158 return;
04159 }
04160 cur = p->packets;
04161 method = (cur->method) ? cur->method : find_sip_method(cur->data->str);
04162 __sip_ack(p, cur->seqno, cur->is_resp, method);
04163 }
04164 }
04165
04166
04167 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
04168 {
04169 struct sip_pkt *cur;
04170 int res = FALSE;
04171
04172 for (cur = p->packets; cur; cur = cur->next) {
04173 if (cur->seqno == seqno && cur->is_resp == resp &&
04174 (cur->is_resp || method_match(sipmethod, cur->data->str))) {
04175
04176 if (cur->retransid > -1) {
04177 if (sipdebug)
04178 ast_debug(4, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
04179 }
04180 AST_SCHED_DEL(sched, cur->retransid);
04181 res = TRUE;
04182 break;
04183 }
04184 }
04185 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");
04186 return res;
04187 }
04188
04189
04190
04191 static void parse_copy(struct sip_request *dst, const struct sip_request *src)
04192 {
04193 copy_request(dst, src);
04194 parse_request(dst);
04195 }
04196
04197
04198 static void add_blank(struct sip_request *req)
04199 {
04200 if (!req->lines) {
04201
04202 ast_str_append(&req->data, 0, "\r\n");
04203 req->len = ast_str_strlen(req->data);
04204 }
04205 }
04206
04207 static int send_provisional_keepalive_full(struct sip_pvt *pvt, int with_sdp)
04208 {
04209 const char *msg = NULL;
04210
04211 if (!pvt->last_provisional || !strncasecmp(pvt->last_provisional, "100", 3)) {
04212 msg = "183 Session Progress";
04213 }
04214
04215 if (pvt->invitestate < INV_COMPLETED) {
04216 if (with_sdp) {
04217 transmit_response_with_sdp(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq, XMIT_UNRELIABLE, FALSE);
04218 } else {
04219 transmit_response(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq);
04220 }
04221 return PROVIS_KEEPALIVE_TIMEOUT;
04222 }
04223
04224 return 0;
04225 }
04226
04227 static int send_provisional_keepalive(const void *data) {
04228 struct sip_pvt *pvt = (struct sip_pvt *) data;
04229
04230 return send_provisional_keepalive_full(pvt, 0);
04231 }
04232
04233 static int send_provisional_keepalive_with_sdp(const void *data) {
04234 struct sip_pvt *pvt = (void *)data;
04235
04236 return send_provisional_keepalive_full(pvt, 1);
04237 }
04238
04239 static void update_provisional_keepalive(struct sip_pvt *pvt, int with_sdp)
04240 {
04241 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"));
04242
04243 pvt->provisional_keepalive_sched_id = ast_sched_add(sched, PROVIS_KEEPALIVE_TIMEOUT,
04244 with_sdp ? send_provisional_keepalive_with_sdp : send_provisional_keepalive, dialog_ref(pvt, "Increment refcount to pass dialog pointer to sched callback"));
04245 }
04246
04247
04248 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
04249 {
04250 int res;
04251
04252 finalize_content(req);
04253 add_blank(req);
04254 if (sip_debug_test_pvt(p)) {
04255 const struct sockaddr_in *dst = sip_real_dst(p);
04256
04257 ast_verbose("\n<--- %sTransmitting (%s) to %s:%d --->\n%s\n<------------>\n",
04258 reliable ? "Reliably " : "", sip_nat_mode(p),
04259 ast_inet_ntoa(dst->sin_addr),
04260 ntohs(dst->sin_port), req->data->str);
04261 }
04262 if (p->do_history) {
04263 struct sip_request tmp = { .rlPart1 = 0, };
04264 parse_copy(&tmp, req);
04265 append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", tmp.data->str, get_header(&tmp, "CSeq"),
04266 (tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? REQ_OFFSET_TO_STR(&tmp, rlPart2) : sip_methods[tmp.method].text);
04267 deinit_req(&tmp);
04268 }
04269
04270
04271 if (p->initreq.method == SIP_INVITE && reliable == XMIT_CRITICAL) {
04272 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"));
04273 }
04274
04275 res = (reliable) ?
04276 __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
04277 __sip_xmit(p, req->data, req->len);
04278 deinit_req(req);
04279 if (res > 0)
04280 return 0;
04281 return res;
04282 }
04283
04284
04285 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
04286 {
04287 int res;
04288
04289
04290
04291
04292 if (p->outboundproxy) {
04293 p->sa = p->outboundproxy->ip;
04294 }
04295
04296 finalize_content(req);
04297 add_blank(req);
04298 if (sip_debug_test_pvt(p)) {
04299 if (ast_test_flag(&p->flags[0], SIP_NAT_ROUTE))
04300 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);
04301 else
04302 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);
04303 }
04304 if (p->do_history) {
04305 struct sip_request tmp = { .rlPart1 = 0, };
04306 parse_copy(&tmp, req);
04307 append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", tmp.data->str, get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
04308 deinit_req(&tmp);
04309 }
04310 res = (reliable) ?
04311 __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
04312 __sip_xmit(p, req->data, req->len);
04313 deinit_req(req);
04314 return res;
04315 }
04316
04317
04318 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen)
04319 {
04320 int res = -1;
04321 enum ast_t38_state state = T38_STATE_UNAVAILABLE;
04322 struct sip_pvt *p = (struct sip_pvt *) chan->tech_pvt;
04323
04324 switch (option) {
04325 case AST_OPTION_T38_STATE:
04326
04327 if (*datalen != sizeof(enum ast_t38_state)) {
04328 ast_log(LOG_ERROR, "Invalid datalen for AST_OPTION_T38_STATE option. Expected %d, got %d\n", (int)sizeof(enum ast_t38_state), *datalen);
04329 return -1;
04330 }
04331
04332 sip_pvt_lock(p);
04333
04334
04335 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
04336 switch (p->t38.state) {
04337 case T38_LOCAL_REINVITE:
04338 case T38_PEER_REINVITE:
04339 state = T38_STATE_NEGOTIATING;
04340 break;
04341 case T38_ENABLED:
04342 state = T38_STATE_NEGOTIATED;
04343 break;
04344 default:
04345 state = T38_STATE_UNKNOWN;
04346 }
04347 }
04348
04349 sip_pvt_unlock(p);
04350
04351 *((enum ast_t38_state *) data) = state;
04352 res = 0;
04353
04354 break;
04355 default:
04356 break;
04357 }
04358
04359 return res;
04360 }
04361
04362
04363
04364
04365
04366 static const char *find_closing_quote(const char *start, const char *lim)
04367 {
04368 char last_char = '\0';
04369 const char *s;
04370 for (s = start; *s && s != lim; last_char = *s++) {
04371 if (*s == '"' && last_char != '\\')
04372 break;
04373 }
04374 return s;
04375 }
04376
04377
04378
04379
04380
04381
04382
04383
04384
04385
04386
04387
04388
04389 static char *get_in_brackets(char *tmp)
04390 {
04391 const char *parse = tmp;
04392 char *first_bracket;
04393
04394
04395
04396
04397
04398 while ( (first_bracket = strchr(parse, '<')) ) {
04399 char *first_quote = strchr(parse, '"');
04400
04401 if (!first_quote || first_quote > first_bracket)
04402 break;
04403
04404 parse = find_closing_quote(first_quote + 1, NULL);
04405 if (!*parse) {
04406
04407 ast_log(LOG_WARNING, "No closing quote found in '%s'\n", tmp);
04408 break;
04409 }
04410 parse++;
04411 }
04412 if (first_bracket) {
04413 char *second_bracket = strchr(first_bracket + 1, '>');
04414 if (second_bracket) {
04415 *second_bracket = '\0';
04416 tmp = first_bracket + 1;
04417 } else {
04418 ast_log(LOG_WARNING, "No closing bracket found in '%s'\n", tmp);
04419 }
04420 }
04421
04422 return tmp;
04423 }
04424
04425
04426
04427
04428
04429
04430
04431
04432
04433
04434
04435
04436
04437
04438
04439
04440
04441
04442
04443
04444 static int parse_uri(char *uri, const char *scheme,
04445 char **ret_name, char **pass, char **domain, char **port, char **options, char **transport)
04446 {
04447 char *name = NULL;
04448 int error = 0;
04449
04450
04451 if (pass)
04452 *pass = "";
04453 if (port)
04454 *port = "";
04455 if (scheme) {
04456 int l;
04457 char *scheme2 = ast_strdupa(scheme);
04458 char *cur = strsep(&scheme2, ",");
04459 for (; !ast_strlen_zero(cur); cur = strsep(&scheme2, ",")) {
04460 l = strlen(cur);
04461 if (!strncasecmp(uri, cur, l)) {
04462 uri += l;
04463 break;
04464 }
04465 }
04466 if (ast_strlen_zero(cur)) {
04467 ast_debug(1, "No supported scheme found in '%s' using the scheme[s] %s\n", uri, scheme);
04468 error = -1;
04469 }
04470 }
04471 if (transport) {
04472 char *t, *type = "";
04473 *transport = "";
04474 if ((t = strstr(uri, "transport="))) {
04475 strsep(&t, "=");
04476 if ((type = strsep(&t, ";"))) {
04477 *transport = type;
04478 }
04479 }
04480 }
04481
04482 if (!domain) {
04483
04484
04485
04486 } else {
04487
04488
04489
04490 char *c, *dom = "";
04491
04492 if ((c = strchr(uri, '@')) == NULL) {
04493
04494 dom = uri;
04495 name = "";
04496 } else {
04497 *c++ = '\0';
04498 dom = c;
04499 name = uri;
04500 }
04501
04502
04503 dom = strsep(&dom, ";");
04504 name = strsep(&name, ";");
04505
04506 if (port && (c = strchr(dom, ':'))) {
04507 *c++ = '\0';
04508 *port = c;
04509 }
04510 if (pass && (c = strchr(name, ':'))) {
04511 *c++ = '\0';
04512 *pass = c;
04513 }
04514 *domain = dom;
04515 }
04516 if (ret_name)
04517 *ret_name = name;
04518 if (options)
04519 *options = uri ? uri : "";
04520
04521 return error;
04522 }
04523
04524
04525 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
04526 {
04527 struct sip_pvt *p = chan->tech_pvt;
04528
04529 if (subclass != AST_HTML_URL)
04530 return -1;
04531
04532 ast_string_field_build(p, url, "<%s>;mode=active", data);
04533
04534 if (sip_debug_test_pvt(p))
04535 ast_debug(1, "Send URL %s, state = %d!\n", data, chan->_state);
04536
04537 switch (chan->_state) {
04538 case AST_STATE_RING:
04539 transmit_response(p, "100 Trying", &p->initreq);
04540 break;
04541 case AST_STATE_RINGING:
04542 transmit_response(p, "180 Ringing", &p->initreq);
04543 break;
04544 case AST_STATE_UP:
04545 if (!p->pendinginvite) {
04546 transmit_reinvite_with_sdp(p, FALSE, FALSE);
04547 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
04548 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
04549 }
04550 break;
04551 default:
04552 ast_log(LOG_WARNING, "Don't know how to send URI when state is %d!\n", chan->_state);
04553 }
04554
04555 return 0;
04556 }
04557
04558
04559 static const char *sip_get_callid(struct ast_channel *chan)
04560 {
04561 return chan->tech_pvt ? ((struct sip_pvt *) chan->tech_pvt)->callid : "";
04562 }
04563
04564
04565
04566 static int sip_sendtext(struct ast_channel *ast, const char *text)
04567 {
04568 struct sip_pvt *p = ast->tech_pvt;
04569 int debug = sip_debug_test_pvt(p);
04570
04571 if (debug)
04572 ast_verbose("Sending text %s on %s\n", text, ast->name);
04573 if (!p)
04574 return -1;
04575
04576
04577 if (!text)
04578 return 0;
04579 if (debug)
04580 ast_verbose("Really sending text %s on %s\n", text, ast->name);
04581 transmit_message_with_text(p, text);
04582 return 0;
04583 }
04584
04585
04586
04587
04588
04589
04590 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)
04591 {
04592 char port[10];
04593 char ipaddr[INET_ADDRSTRLEN];
04594 char regseconds[20];
04595 char *tablename = NULL;
04596 char str_lastms[20];
04597
04598 const char *sysname = ast_config_AST_SYSTEM_NAME;
04599 char *syslabel = NULL;
04600
04601 time_t nowtime = time(NULL) + expirey;
04602 const char *fc = fullcontact ? "fullcontact" : NULL;
04603
04604 int realtimeregs = ast_check_realtime("sipregs");
04605
04606 tablename = realtimeregs ? "sipregs" : "sippeers";
04607
04608
04609 snprintf(str_lastms, sizeof(str_lastms), "%d", lastms);
04610 snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime);
04611 ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
04612 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
04613
04614 if (ast_strlen_zero(sysname))
04615 sysname = NULL;
04616 else if (sip_cfg.rtsave_sysname)
04617 syslabel = "regserver";
04618
04619 if (fc) {
04620 ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
04621 "port", port, "regseconds", regseconds,
04622 deprecated_username ? "username" : "defaultuser", defaultuser,
04623 "useragent", useragent, "lastms", str_lastms,
04624 fc, fullcontact, syslabel, sysname, SENTINEL);
04625 } else {
04626 ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
04627 "port", port, "regseconds", regseconds,
04628 "useragent", useragent, "lastms", str_lastms,
04629 deprecated_username ? "username" : "defaultuser", defaultuser,
04630 syslabel, sysname, SENTINEL);
04631 }
04632 }
04633
04634
04635 static void register_peer_exten(struct sip_peer *peer, int onoff)
04636 {
04637 char multi[256];
04638 char *stringp, *ext, *context;
04639 struct pbx_find_info q = { .stacklen = 0 };
04640
04641
04642
04643
04644
04645 if (ast_strlen_zero(global_regcontext))
04646 return;
04647
04648 ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
04649 stringp = multi;
04650 while ((ext = strsep(&stringp, "&"))) {
04651 if ((context = strchr(ext, '@'))) {
04652 *context++ = '\0';
04653 if (!ast_context_find(context)) {
04654 ast_log(LOG_WARNING, "Context %s must exist in regcontext= in sip.conf!\n", context);
04655 continue;
04656 }
04657 } else {
04658 context = global_regcontext;
04659 }
04660 if (onoff) {
04661 if (!ast_exists_extension(NULL, context, ext, 1, NULL)) {
04662 ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
04663 ast_strdup(peer->name), ast_free_ptr, "SIP");
04664 }
04665 } else if (pbx_find_extension(NULL, NULL, &q, context, ext, 1, NULL, "", E_MATCH)) {
04666 ast_context_remove_extension(context, ext, 1, NULL);
04667 }
04668 }
04669 }
04670
04671
04672 static void destroy_mailbox(struct sip_mailbox *mailbox)
04673 {
04674 if (mailbox->mailbox)
04675 ast_free(mailbox->mailbox);
04676 if (mailbox->context)
04677 ast_free(mailbox->context);
04678 if (mailbox->event_sub)
04679 ast_event_unsubscribe(mailbox->event_sub);
04680 ast_free(mailbox);
04681 }
04682
04683
04684 static void clear_peer_mailboxes(struct sip_peer *peer)
04685 {
04686 struct sip_mailbox *mailbox;
04687
04688 while ((mailbox = AST_LIST_REMOVE_HEAD(&peer->mailboxes, entry)))
04689 destroy_mailbox(mailbox);
04690 }
04691
04692 static void sip_destroy_peer_fn(void *peer)
04693 {
04694 sip_destroy_peer(peer);
04695 }
04696
04697
04698 static void sip_destroy_peer(struct sip_peer *peer)
04699 {
04700 ast_debug(3, "Destroying SIP peer %s\n", peer->name);
04701 if (peer->outboundproxy)
04702 ao2_ref(peer->outboundproxy, -1);
04703 peer->outboundproxy = NULL;
04704
04705
04706 if (peer->call) {
04707 dialog_unlink_all(peer->call, TRUE, TRUE);
04708 peer->call = dialog_unref(peer->call, "peer->call is being unset");
04709 }
04710
04711
04712 if (peer->mwipvt) {
04713 dialog_unlink_all(peer->mwipvt, TRUE, TRUE);
04714 peer->mwipvt = dialog_unref(peer->mwipvt, "unreffing peer->mwipvt");
04715 }
04716
04717 if (peer->chanvars) {
04718 ast_variables_destroy(peer->chanvars);
04719 peer->chanvars = NULL;
04720 }
04721
04722 register_peer_exten(peer, FALSE);
04723 ast_free_ha(peer->ha);
04724 if (peer->selfdestruct)
04725 ast_atomic_fetchadd_int(&apeerobjs, -1);
04726 else if (peer->is_realtime) {
04727 ast_atomic_fetchadd_int(&rpeerobjs, -1);
04728 ast_debug(3, "-REALTIME- peer Destroyed. Name: %s. Realtime Peer objects: %d\n", peer->name, rpeerobjs);
04729 } else
04730 ast_atomic_fetchadd_int(&speerobjs, -1);
04731 clear_realm_authentication(peer->auth);
04732 peer->auth = NULL;
04733 if (peer->dnsmgr)
04734 ast_dnsmgr_release(peer->dnsmgr);
04735 clear_peer_mailboxes(peer);
04736
04737 if (peer->socket.tcptls_session) {
04738 ao2_ref(peer->socket.tcptls_session, -1);
04739 peer->socket.tcptls_session = NULL;
04740 }
04741
04742 ast_string_field_free_memory(peer);
04743 }
04744
04745
04746 static void update_peer(struct sip_peer *p, int expire)
04747 {
04748 int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
04749 if (sip_cfg.peer_rtupdate &&
04750 (p->is_realtime || rtcachefriends)) {
04751 realtime_update_peer(p->name, &p->addr, p->username, rtcachefriends ? p->fullcontact : NULL, p->useragent, expire, p->deprecated_username, p->lastms);
04752 }
04753 }
04754
04755 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *cfg)
04756 {
04757 struct ast_variable *var = NULL;
04758 struct ast_flags flags = {0};
04759 char *cat = NULL;
04760 const char *insecure;
04761 while ((cat = ast_category_browse(cfg, cat))) {
04762 insecure = ast_variable_retrieve(cfg, cat, "insecure");
04763 set_insecure_flags(&flags, insecure, -1);
04764 if (ast_test_flag(&flags, SIP_INSECURE_PORT)) {
04765 var = ast_category_root(cfg, cat);
04766 break;
04767 }
04768 }
04769 return var;
04770 }
04771
04772 static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername)
04773 {
04774 struct ast_variable *tmp;
04775 for (tmp = var; tmp; tmp = tmp->next) {
04776 if (!newpeername && !strcasecmp(tmp->name, "name"))
04777 newpeername = tmp->value;
04778 }
04779 return newpeername;
04780 }
04781
04782
04783
04784
04785
04786
04787
04788 static struct sip_peer *realtime_peer(const char *newpeername, struct sockaddr_in *sin, int devstate_only)
04789 {
04790 struct sip_peer *peer;
04791 struct ast_variable *var = NULL;
04792 struct ast_variable *varregs = NULL;
04793 struct ast_variable *tmp;
04794 struct ast_config *peerlist = NULL;
04795 char ipaddr[INET_ADDRSTRLEN];
04796 char portstring[6];
04797 char *cat = NULL;
04798 unsigned short portnum;
04799 int realtimeregs = ast_check_realtime("sipregs");
04800
04801
04802 if (newpeername) {
04803 if (realtimeregs)
04804 varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04805
04806 var = ast_load_realtime("sippeers", "name", newpeername, "host", "dynamic", SENTINEL);
04807 if (!var && sin)
04808 var = ast_load_realtime("sippeers", "name", newpeername, "host", ast_inet_ntoa(sin->sin_addr), SENTINEL);
04809 if (!var) {
04810 var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
04811
04812
04813
04814
04815
04816
04817 if (var && sin) {
04818 for (tmp = var; tmp; tmp = tmp->next) {
04819 if (!strcasecmp(tmp->name, "host")) {
04820 struct hostent *hp;
04821 struct ast_hostent ahp;
04822 if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || (memcmp(hp->h_addr, &sin->sin_addr, sizeof(hp->h_addr)))) {
04823
04824 ast_variables_destroy(var);
04825 var = NULL;
04826 }
04827 break;
04828 }
04829 }
04830 }
04831 }
04832 }
04833
04834 if (!var && sin) {
04835 ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
04836 portnum = ntohs(sin->sin_port);
04837 sprintf(portstring, "%u", portnum);
04838 var = ast_load_realtime("sippeers", "host", ipaddr, "port", portstring, SENTINEL);
04839 if (var) {
04840 if (realtimeregs) {
04841 newpeername = get_name_from_variable(var, newpeername);
04842 varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04843 }
04844 } else {
04845 if (realtimeregs)
04846 varregs = ast_load_realtime("sipregs", "ipaddr", ipaddr, "port", portstring, SENTINEL);
04847 else
04848 var = ast_load_realtime("sippeers", "ipaddr", ipaddr, "port", portstring, SENTINEL);
04849 if (varregs) {
04850 newpeername = get_name_from_variable(varregs, newpeername);
04851 var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
04852 }
04853 }
04854 if (!var) {
04855 peerlist = ast_load_realtime_multientry("sippeers", "host", ipaddr, SENTINEL);
04856 if (peerlist) {
04857 var = get_insecure_variable_from_config(peerlist);
04858 if(var) {
04859 if (realtimeregs) {
04860 newpeername = get_name_from_variable(var, newpeername);
04861 varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04862 }
04863 } else {
04864 peerlist = NULL;
04865 cat = NULL;
04866 peerlist = ast_load_realtime_multientry("sippeers", "ipaddr", ipaddr, SENTINEL);
04867 if(peerlist) {
04868 var = get_insecure_variable_from_config(peerlist);
04869 if(var) {
04870 if (realtimeregs) {
04871 newpeername = get_name_from_variable(var, newpeername);
04872 varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04873 }
04874 }
04875 }
04876 }
04877 } else {
04878 if (realtimeregs) {
04879 peerlist = ast_load_realtime_multientry("sipregs", "ipaddr", ipaddr, SENTINEL);
04880 if (peerlist) {
04881 varregs = get_insecure_variable_from_config(peerlist);
04882 if (varregs) {
04883 newpeername = get_name_from_variable(varregs, newpeername);
04884 var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
04885 }
04886 }
04887 } else {
04888 peerlist = ast_load_realtime_multientry("sippeers", "ipaddr", ipaddr, SENTINEL);
04889 if (peerlist) {
04890 var = get_insecure_variable_from_config(peerlist);
04891 if (var) {
04892 newpeername = get_name_from_variable(var, newpeername);
04893 varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04894 }
04895 }
04896 }
04897 }
04898 }
04899 }
04900
04901 if (!var) {
04902 if (peerlist)
04903 ast_config_destroy(peerlist);
04904 return NULL;
04905 }
04906
04907 for (tmp = var; tmp; tmp = tmp->next) {
04908 if (!newpeername && !strcasecmp(tmp->name, "name")) {
04909 newpeername = tmp->value;
04910 }
04911 }
04912
04913 if (!newpeername) {
04914 ast_log(LOG_WARNING, "Cannot Determine peer name ip=%s\n", ipaddr);
04915 if(peerlist)
04916 ast_config_destroy(peerlist);
04917 else
04918 ast_variables_destroy(var);
04919 return NULL;
04920 }
04921
04922
04923
04924 peer = build_peer(newpeername, var, varregs, TRUE, devstate_only);
04925 if (!peer) {
04926 if(peerlist)
04927 ast_config_destroy(peerlist);
04928 else {
04929 ast_variables_destroy(var);
04930 ast_variables_destroy(varregs);
04931 }
04932 return NULL;
04933 }
04934
04935 ast_debug(3, "-REALTIME- loading peer from database to memory. Name: %s. Peer objects: %d\n", peer->name, rpeerobjs);
04936
04937 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && !devstate_only) {
04938
04939 ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
04940 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
04941 AST_SCHED_REPLACE_UNREF(peer->expire, sched, sip_cfg.rtautoclear * 1000, expire_register, peer,
04942 unref_peer(_data, "remove registration ref"),
04943 unref_peer(peer, "remove registration ref"),
04944 ref_peer(peer, "add registration ref"));
04945 }
04946 ao2_t_link(peers, peer, "link peer into peers table");
04947 if (peer->addr.sin_addr.s_addr) {
04948 ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
04949 }
04950 }
04951 peer->is_realtime = 1;
04952 if (peerlist)
04953 ast_config_destroy(peerlist);
04954 else {
04955 ast_variables_destroy(var);
04956 ast_variables_destroy(varregs);
04957 }
04958
04959 return peer;
04960 }
04961
04962
04963 static int find_by_name(void *obj, void *arg, void *data, int flags)
04964 {
04965 struct sip_peer *search = obj, *match = arg;
04966 int *which_objects = data;
04967
04968
04969 if (strcmp(search->name, match->name)) {
04970 return 0;
04971 }
04972
04973 switch (*which_objects) {
04974 case FINDUSERS:
04975 if (!(search->type & SIP_TYPE_USER)) {
04976 return 0;
04977 }
04978 break;
04979 case FINDPEERS:
04980 if (!(search->type & SIP_TYPE_PEER)) {
04981 return 0;
04982 }
04983 break;
04984 case FINDALLDEVICES:
04985 break;
04986 }
04987
04988 return CMP_MATCH | CMP_STOP;
04989 }
04990
04991
04992
04993
04994
04995
04996
04997
04998
04999
05000
05001
05002
05003
05004 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime, int which_objects, int devstate_only, int transport)
05005 {
05006 struct sip_peer *p = NULL;
05007 struct sip_peer tmp_peer;
05008
05009 if (peer) {
05010 ast_copy_string(tmp_peer.name, peer, sizeof(tmp_peer.name));
05011 p = ao2_t_callback_data(peers, OBJ_POINTER, find_by_name, &tmp_peer, &which_objects, "ao2_find in peers table");
05012 } else if (sin) {
05013 tmp_peer.addr.sin_addr.s_addr = sin->sin_addr.s_addr;
05014 tmp_peer.addr.sin_port = sin->sin_port;
05015 tmp_peer.flags[0].flags = 0;
05016 tmp_peer.transports = transport;
05017 p = ao2_t_find(peers_by_ip, &tmp_peer, OBJ_POINTER, "ao2_find in peers_by_ip table");
05018 if (!p) {
05019 ast_set_flag(&tmp_peer.flags[0], SIP_INSECURE_PORT);
05020 p = ao2_t_find(peers_by_ip, &tmp_peer, OBJ_POINTER, "ao2_find in peers_by_ip table 2");
05021 if (p) {
05022 return p;
05023 }
05024 }
05025 }
05026
05027 if (!p && (realtime || devstate_only)) {
05028 p = realtime_peer(peer, sin, devstate_only);
05029 if (p) {
05030 switch (which_objects) {
05031 case FINDUSERS:
05032 if (!(p->type & SIP_TYPE_USER)) {
05033 unref_peer(p, "Wrong type of realtime SIP endpoint");
05034 return NULL;
05035 }
05036 break;
05037 case FINDPEERS:
05038 if (!(p->type & SIP_TYPE_PEER)) {
05039 unref_peer(p, "Wrong type of realtime SIP endpoint");
05040 return NULL;
05041 }
05042 break;
05043 case FINDALLDEVICES:
05044 break;
05045 }
05046 }
05047 }
05048
05049 return p;
05050 }
05051
05052
05053 static void do_setnat(struct sip_pvt *p, int natflags)
05054 {
05055 const char *mode = natflags ? "On" : "Off";
05056
05057 if (p->rtp) {
05058 ast_debug(1, "Setting NAT on RTP to %s\n", mode);
05059 ast_rtp_setnat(p->rtp, natflags);
05060 }
05061 if (p->vrtp) {
05062 ast_debug(1, "Setting NAT on VRTP to %s\n", mode);
05063 ast_rtp_setnat(p->vrtp, natflags);
05064 }
05065 if (p->udptl) {
05066 ast_debug(1, "Setting NAT on UDPTL to %s\n", mode);
05067 ast_udptl_setnat(p->udptl, natflags);
05068 }
05069 if (p->trtp) {
05070 ast_debug(1, "Setting NAT on TRTP to %s\n", mode);
05071 ast_rtp_setnat(p->trtp, natflags);
05072 }
05073 }
05074
05075
05076 static void change_t38_state(struct sip_pvt *p, int state)
05077 {
05078 int old = p->t38.state;
05079 struct ast_channel *chan = p->owner;
05080 struct ast_control_t38_parameters parameters = { .request_response = 0 };
05081
05082
05083 if (old == state)
05084 return;
05085
05086 p->t38.state = state;
05087 ast_debug(2, "T38 state changed to %d on channel %s\n", p->t38.state, chan ? chan->name : "<none>");
05088
05089
05090 if (!chan)
05091 return;
05092
05093
05094 switch (state) {
05095 case T38_PEER_REINVITE:
05096 parameters = p->t38.their_parms;
05097 parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
05098 parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
05099 ast_udptl_set_tag(p->udptl, "SIP/%s", p->username);
05100 break;
05101 case T38_ENABLED:
05102 parameters = p->t38.their_parms;
05103 parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
05104 parameters.request_response = AST_T38_NEGOTIATED;
05105 ast_udptl_set_tag(p->udptl, "SIP/%s", p->username);
05106 break;
05107 case T38_DISABLED:
05108 if (old == T38_ENABLED) {
05109 parameters.request_response = AST_T38_TERMINATED;
05110 } else if (old == T38_LOCAL_REINVITE) {
05111 parameters.request_response = AST_T38_REFUSED;
05112 }
05113 break;
05114 case T38_LOCAL_REINVITE:
05115
05116 break;
05117 }
05118
05119
05120 if (parameters.request_response)
05121 ast_queue_control_data(chan, AST_CONTROL_T38_PARAMETERS, ¶meters, sizeof(parameters));
05122 }
05123
05124
05125 static void set_t38_capabilities(struct sip_pvt *p)
05126 {
05127 if (p->udptl) {
05128 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY) {
05129 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
05130 } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_FEC) {
05131 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
05132 } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL) {
05133 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
05134 }
05135 }
05136 }
05137
05138 static void copy_socket_data(struct sip_socket *to_sock, const struct sip_socket *from_sock)
05139 {
05140 if (to_sock->tcptls_session) {
05141 ao2_ref(to_sock->tcptls_session, -1);
05142 to_sock->tcptls_session = NULL;
05143 }
05144
05145 if (from_sock->tcptls_session) {
05146 ao2_ref(from_sock->tcptls_session, +1);
05147 }
05148
05149 *to_sock = *from_sock;
05150 }
05151
05152
05153
05154
05155
05156
05157
05158
05159 static int create_addr_from_peer(struct sip_pvt *dialog, struct sip_peer *peer)
05160 {
05161
05162
05163
05164
05165 if (dialog->socket.type && check_request_transport(peer, dialog))
05166 return -1;
05167 copy_socket_data(&dialog->socket, &peer->socket);
05168
05169 if ((peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr) &&
05170 (!peer->maxms || ((peer->lastms >= 0) && (peer->lastms <= peer->maxms)))) {
05171 dialog->sa = (peer->addr.sin_addr.s_addr) ? peer->addr : peer->defaddr;
05172 dialog->recv = dialog->sa;
05173 } else
05174 return -1;
05175
05176 ast_copy_flags(&dialog->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
05177 ast_copy_flags(&dialog->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
05178 dialog->capability = peer->capability;
05179 if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS) &&
05180 (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT) ||
05181 !(dialog->capability & AST_FORMAT_VIDEO_MASK)) &&
05182 dialog->vrtp) {
05183 ast_rtp_destroy(dialog->vrtp);
05184 dialog->vrtp = NULL;
05185 }
05186 if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_TEXTSUPPORT) && dialog->trtp) {
05187 ast_rtp_destroy(dialog->trtp);
05188 dialog->trtp = NULL;
05189 }
05190 dialog->prefs = peer->prefs;
05191 if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_T38SUPPORT)) {
05192
05193 if (dialog->udptl || (!dialog->udptl && (dialog->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr)))) {
05194 dialog->t38_maxdatagram = peer->t38_maxdatagram;
05195 set_t38_capabilities(dialog);
05196 } else {
05197
05198 ast_debug(1, "UDPTL creation failed on dialog.\n");
05199 ast_clear_flag(&dialog->flags[1], SIP_PAGE2_T38SUPPORT);
05200 }
05201 } else if (dialog->udptl) {
05202 ast_udptl_destroy(dialog->udptl);
05203 dialog->udptl = NULL;
05204 }
05205 do_setnat(dialog, ast_test_flag(&dialog->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
05206
05207 if (dialog->rtp) {
05208 ast_rtp_setdtmf(dialog->rtp, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
05209 ast_rtp_setdtmfcompensate(dialog->rtp, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
05210 ast_rtp_set_rtptimeout(dialog->rtp, peer->rtptimeout);
05211 ast_rtp_set_rtpholdtimeout(dialog->rtp, peer->rtpholdtimeout);
05212 ast_rtp_set_rtpkeepalive(dialog->rtp, peer->rtpkeepalive);
05213
05214 ast_rtp_codec_setpref(dialog->rtp, &dialog->prefs);
05215 dialog->autoframing = peer->autoframing;
05216 }
05217 if (dialog->vrtp) {
05218 ast_rtp_setdtmf(dialog->vrtp, 0);
05219 ast_rtp_setdtmfcompensate(dialog->vrtp, 0);
05220 ast_rtp_set_rtptimeout(dialog->vrtp, peer->rtptimeout);
05221 ast_rtp_set_rtpholdtimeout(dialog->vrtp, peer->rtpholdtimeout);
05222 ast_rtp_set_rtpkeepalive(dialog->vrtp, peer->rtpkeepalive);
05223 }
05224 if (dialog->trtp) {
05225 ast_rtp_setdtmf(dialog->trtp, 0);
05226 ast_rtp_setdtmfcompensate(dialog->trtp, 0);
05227 ast_rtp_set_rtptimeout(dialog->trtp, peer->rtptimeout);
05228 ast_rtp_set_rtpholdtimeout(dialog->trtp, peer->rtpholdtimeout);
05229 ast_rtp_set_rtpkeepalive(dialog->trtp, peer->rtpkeepalive);
05230 }
05231
05232 ast_string_field_set(dialog, peername, peer->name);
05233 ast_string_field_set(dialog, authname, peer->username);
05234 ast_string_field_set(dialog, username, peer->username);
05235 ast_string_field_set(dialog, peersecret, peer->secret);
05236 ast_string_field_set(dialog, peermd5secret, peer->md5secret);
05237 ast_string_field_set(dialog, mohsuggest, peer->mohsuggest);
05238 ast_string_field_set(dialog, mohinterpret, peer->mohinterpret);
05239 ast_string_field_set(dialog, tohost, peer->tohost);
05240 ast_string_field_set(dialog, fullcontact, peer->fullcontact);
05241 ast_string_field_set(dialog, context, peer->context);
05242 ast_string_field_set(dialog, parkinglot, peer->parkinglot);
05243 ref_proxy(dialog, obproxy_get(dialog, peer));
05244 dialog->callgroup = peer->callgroup;
05245 dialog->pickupgroup = peer->pickupgroup;
05246 dialog->allowtransfer = peer->allowtransfer;
05247 dialog->jointnoncodeccapability = dialog->noncodeccapability;
05248 dialog->rtptimeout = peer->rtptimeout;
05249 dialog->peerauth = peer->auth;
05250 dialog->maxcallbitrate = peer->maxcallbitrate;
05251 if (ast_strlen_zero(dialog->tohost))
05252 ast_string_field_set(dialog, tohost, ast_inet_ntoa(dialog->sa.sin_addr));
05253 if (!ast_strlen_zero(peer->fromdomain)) {
05254 ast_string_field_set(dialog, fromdomain, peer->fromdomain);
05255 if (!dialog->initreq.headers) {
05256 char *c;
05257 char *tmpcall = ast_strdupa(dialog->callid);
05258
05259 c = strchr(tmpcall, '@');
05260 if (c) {
05261 *c = '\0';
05262 ao2_t_unlink(dialogs, dialog, "About to change the callid -- remove the old name");
05263 ast_string_field_build(dialog, callid, "%s@%s", tmpcall, peer->fromdomain);
05264 ao2_t_link(dialogs, dialog, "New dialog callid -- inserted back into table");
05265 }
05266 }
05267 }
05268 if (!ast_strlen_zero(peer->fromuser))
05269 ast_string_field_set(dialog, fromuser, peer->fromuser);
05270 if (!ast_strlen_zero(peer->language))
05271 ast_string_field_set(dialog, language, peer->language);
05272
05273
05274
05275
05276 if (peer->maxms && peer->lastms)
05277 dialog->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
05278 else
05279 dialog->timer_t1 = peer->timer_t1;
05280
05281
05282
05283 if (peer->timer_b)
05284 dialog->timer_b = peer->timer_b;
05285 else
05286 dialog->timer_b = 64 * dialog->timer_t1;
05287
05288 if ((ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
05289 (ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
05290 dialog->noncodeccapability |= AST_RTP_DTMF;
05291 else
05292 dialog->noncodeccapability &= ~AST_RTP_DTMF;
05293 if (peer->call_limit)
05294 ast_set_flag(&dialog->flags[0], SIP_CALL_LIMIT);
05295 if (!dialog->portinuri)
05296 dialog->portinuri = peer->portinuri;
05297
05298 dialog->chanvars = copy_vars(peer->chanvars);
05299
05300 return 0;
05301 }
05302
05303
05304
05305
05306 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct sockaddr_in *sin, int newdialog)
05307 {
05308 struct hostent *hp;
05309 struct ast_hostent ahp;
05310 struct sip_peer *peer;
05311 char *port;
05312 int portno = 0;
05313 char host[MAXHOSTNAMELEN], *hostn;
05314 char peername[256];
05315 int srv_ret = 0;
05316
05317 ast_copy_string(peername, opeer, sizeof(peername));
05318 port = strchr(peername, ':');
05319 if (port) {
05320 *port++ = '\0';
05321 dialog->portinuri = 1;
05322 }
05323 dialog->sa.sin_family = AF_INET;
05324 dialog->timer_t1 = global_t1;
05325 dialog->timer_b = global_timer_b;
05326 peer = find_peer(peername, NULL, TRUE, FINDPEERS, FALSE, 0);
05327
05328 if (peer) {
05329 int res;
05330 if (newdialog) {
05331 set_socket_transport(&dialog->socket, 0);
05332 }
05333 res = create_addr_from_peer(dialog, peer);
05334 if (!ast_strlen_zero(port)) {
05335 if ((portno = atoi(port))) {
05336 dialog->sa.sin_port = dialog->recv.sin_port = htons(portno);
05337 }
05338 }
05339 unref_peer(peer, "create_addr: unref peer from find_peer hashtab lookup");
05340 return res;
05341 }
05342
05343 do_setnat(dialog, ast_test_flag(&dialog->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
05344
05345 ast_string_field_set(dialog, tohost, peername);
05346
05347
05348 ref_proxy(dialog, obproxy_get(dialog, NULL));
05349
05350 if (sin) {
05351
05352 memcpy(&dialog->sa.sin_addr, &sin->sin_addr, sizeof(dialog->sa.sin_addr));
05353 if (!sin->sin_port) {
05354 portno = port_str2int(port, (dialog->socket.type == SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT);
05355 } else {
05356 portno = ntohs(sin->sin_port);
05357 }
05358 } else {
05359
05360
05361
05362
05363
05364
05365 hostn = peername;
05366
05367
05368
05369 if (!port && sip_cfg.srvlookup) {
05370 char service[MAXHOSTNAMELEN];
05371 int tportno;
05372 snprintf(service, sizeof(service), "_%s._%s.%s",
05373 get_srv_service(dialog->socket.type),
05374 get_srv_protocol(dialog->socket.type), peername);
05375 srv_ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
05376 if (srv_ret > 0) {
05377 hostn = host;
05378 portno = tportno;
05379 }
05380 }
05381 if (!portno)
05382 portno = port_str2int(port, (dialog->socket.type == SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT);
05383 hp = ast_gethostbyname(hostn, &ahp);
05384 if (!hp) {
05385 ast_log(LOG_WARNING, "No such host: %s\n", peername);
05386 return -1;
05387 }
05388 memcpy(&dialog->sa.sin_addr, hp->h_addr, sizeof(dialog->sa.sin_addr));
05389 }
05390
05391 if (!dialog->socket.type)
05392 set_socket_transport(&dialog->socket, SIP_TRANSPORT_UDP);
05393 if (!dialog->socket.port)
05394 dialog->socket.port = bindaddr.sin_port;
05395 dialog->sa.sin_port = htons(portno);
05396 dialog->recv = dialog->sa;
05397 return 0;
05398 }
05399
05400
05401
05402
05403 static int auto_congest(const void *arg)
05404 {
05405 struct sip_pvt *p = (struct sip_pvt *)arg;
05406
05407 sip_pvt_lock(p);
05408 p->initid = -1;
05409 if (p->owner) {
05410
05411 if (!ast_channel_trylock(p->owner)) {
05412 append_history(p, "Cong", "Auto-congesting (timer)");
05413 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
05414 ast_channel_unlock(p->owner);
05415 }
05416
05417
05418 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
05419 }
05420 sip_pvt_unlock(p);
05421 dialog_unref(p, "unreffing arg passed into auto_congest callback (p->initid)");
05422 return 0;
05423 }
05424
05425
05426
05427
05428 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
05429 {
05430 int res;
05431 struct sip_pvt *p = ast->tech_pvt;
05432 struct varshead *headp;
05433 struct ast_var_t *current;
05434 const char *referer = NULL;
05435
05436 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
05437 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
05438 return -1;
05439 }
05440
05441
05442 headp=&ast->varshead;
05443 AST_LIST_TRAVERSE(headp, current, entries) {
05444
05445 if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
05446 p->options->vxml_url = ast_var_value(current);
05447 } else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
05448 p->options->uri_options = ast_var_value(current);
05449 } else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
05450
05451 p->options->addsipheaders = 1;
05452 } else if (!strcasecmp(ast_var_name(current), "SIPFROMDOMAIN")) {
05453 ast_string_field_set(p, fromdomain, ast_var_value(current));
05454 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER")) {
05455
05456 p->options->transfer = 1;
05457 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REFERER")) {
05458
05459 referer = ast_var_value(current);
05460 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REPLACES")) {
05461
05462 p->options->replaces = ast_var_value(current);
05463 }
05464 }
05465
05466 res = 0;
05467 ast_set_flag(&p->flags[0], SIP_OUTGOING);
05468
05469
05470
05471
05472 ast_clear_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_T38);
05473
05474 if (p->options->transfer) {
05475 char buf[SIPBUFSIZE/2];
05476
05477 if (referer) {
05478 if (sipdebug)
05479 ast_debug(3, "Call for %s transfered by %s\n", p->username, referer);
05480 snprintf(buf, sizeof(buf)-1, "-> %s (via %s)", p->cid_name, referer);
05481 } else
05482 snprintf(buf, sizeof(buf)-1, "-> %s", p->cid_name);
05483 ast_string_field_set(p, cid_name, buf);
05484 }
05485 ast_debug(1, "Outgoing Call for %s\n", p->username);
05486
05487 res = update_call_counter(p, INC_CALL_RINGING);
05488
05489 if (res == -1) {
05490 ast->hangupcause = AST_CAUSE_USER_BUSY;
05491 return res;
05492 }
05493 p->callingpres = ast->cid.cid_pres;
05494 p->jointcapability = ast_translate_available_formats(p->capability, p->prefcodec);
05495 p->jointnoncodeccapability = p->noncodeccapability;
05496
05497
05498 if (!(p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
05499 ast_log(LOG_WARNING, "No audio format found to offer. Cancelling call to %s\n", p->username);
05500 res = -1;
05501 } else {
05502 int xmitres;
05503
05504 xmitres = transmit_invite(p, SIP_INVITE, 1, 2);
05505 if (xmitres == XMIT_ERROR)
05506 return -1;
05507 p->invitestate = INV_CALLING;
05508
05509
05510 AST_SCHED_REPLACE_UNREF(p->initid, sched, p->timer_b, auto_congest, p,
05511 dialog_unref(_data, "dialog ptr dec when SCHED_REPLACE del op succeeded"),
05512 dialog_unref(p, "dialog ptr dec when SCHED_REPLACE add failed"),
05513 dialog_ref(p, "dialog ptr inc when SCHED_REPLACE add succeeded") );
05514 }
05515 return res;
05516 }
05517
05518
05519
05520 static void sip_registry_destroy(struct sip_registry *reg)
05521 {
05522
05523 ast_debug(3, "Destroying registry entry for %s@%s\n", reg->username, reg->hostname);
05524
05525 if (reg->call) {
05526
05527
05528 reg->call->registry = registry_unref(reg->call->registry, "destroy reg->call->registry");
05529 ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", reg->username, reg->hostname);
05530 dialog_unlink_all(reg->call, TRUE, TRUE);
05531 reg->call = dialog_unref(reg->call, "unref reg->call");
05532
05533 }
05534 AST_SCHED_DEL(sched, reg->expire);
05535 AST_SCHED_DEL(sched, reg->timeout);
05536
05537 ast_string_field_free_memory(reg);
05538 ast_atomic_fetchadd_int(®objs, -1);
05539 ast_dnsmgr_release(reg->dnsmgr);
05540 ast_free(reg);
05541 }
05542
05543
05544 static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi)
05545 {
05546 if (mwi->call) {
05547 mwi->call->mwi = NULL;
05548 sip_destroy(mwi->call);
05549 }
05550
05551 AST_SCHED_DEL(sched, mwi->resub);
05552 ast_string_field_free_memory(mwi);
05553 ast_dnsmgr_release(mwi->dnsmgr);
05554 ast_free(mwi);
05555 }
05556
05557
05558 static void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist)
05559 {
05560 struct sip_request *req;
05561
05562 if (p->stimer) {
05563 ast_free(p->stimer);
05564 p->stimer = NULL;
05565 }
05566
05567 if (sip_debug_test_pvt(p))
05568 ast_verbose("Really destroying SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
05569
05570 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
05571 update_call_counter(p, DEC_CALL_LIMIT);
05572 ast_debug(2, "This call did not properly clean up call limits. Call ID %s\n", p->callid);
05573 }
05574
05575
05576 if (p->owner) {
05577 if (lockowner)
05578 ast_channel_lock(p->owner);
05579 if (option_debug)
05580 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
05581 p->owner->tech_pvt = NULL;
05582
05583 p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
05584 if (lockowner)
05585 ast_channel_unlock(p->owner);
05586
05587 usleep(1);
05588 }
05589
05590
05591 if (p->relatedpeer && p->relatedpeer->mwipvt)
05592 p->relatedpeer->mwipvt = dialog_unref(p->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
05593 if (p->relatedpeer && p->relatedpeer->call == p)
05594 p->relatedpeer->call = dialog_unref(p->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
05595
05596 if (p->relatedpeer)
05597 p->relatedpeer = unref_peer(p->relatedpeer,"unsetting a dialog relatedpeer field in sip_destroy");
05598
05599 if (p->registry) {
05600 if (p->registry->call == p)
05601 p->registry->call = dialog_unref(p->registry->call, "nulling out the registry's call dialog field in unlink_all");
05602 p->registry = registry_unref(p->registry, "delete p->registry");
05603 }
05604
05605 if (p->mwi) {
05606 p->mwi->call = NULL;
05607 }
05608
05609 if (dumphistory)
05610 sip_dump_history(p);
05611
05612 if (p->options)
05613 ast_free(p->options);
05614
05615 if (p->notify_headers) {
05616 ast_variables_destroy(p->notify_headers);
05617 p->notify_headers = NULL;
05618 }
05619 if (p->rtp) {
05620 ast_rtp_destroy(p->rtp);
05621 }
05622 if (p->vrtp) {
05623 ast_rtp_destroy(p->vrtp);
05624 }
05625 if (p->trtp) {
05626 while (ast_rtp_get_bridged(p->trtp))
05627 usleep(1);
05628 ast_rtp_destroy(p->trtp);
05629 }
05630 if (p->udptl)
05631 ast_udptl_destroy(p->udptl);
05632 if (p->refer)
05633 ast_free(p->refer);
05634 if (p->route) {
05635 free_old_route(p->route);
05636 p->route = NULL;
05637 }
05638 deinit_req(&p->initreq);
05639
05640
05641 if (p->stimer) {
05642 p->stimer->quit_flag = 1;
05643 if (p->stimer->st_active == TRUE && p->stimer->st_schedid > -1) {
05644 AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
05645 dialog_unref(p, "removing session timer ref"));
05646 }
05647 ast_free(p->stimer);
05648 p->stimer = NULL;
05649 }
05650
05651
05652 if (p->history) {
05653 struct sip_history *hist;
05654 while ( (hist = AST_LIST_REMOVE_HEAD(p->history, list)) ) {
05655 ast_free(hist);
05656 p->history_entries--;
05657 }
05658 ast_free(p->history);
05659 p->history = NULL;
05660 }
05661
05662 while ((req = AST_LIST_REMOVE_HEAD(&p->request_queue, next))) {
05663 ast_free(req);
05664 }
05665
05666 if (p->chanvars) {
05667 ast_variables_destroy(p->chanvars);
05668 p->chanvars = NULL;
05669 }
05670
05671 ast_string_field_free_memory(p);
05672
05673 if (p->socket.tcptls_session) {
05674 ao2_ref(p->socket.tcptls_session, -1);
05675 p->socket.tcptls_session = NULL;
05676 }
05677 }
05678
05679
05680
05681
05682
05683
05684
05685
05686
05687
05688
05689
05690
05691
05692
05693 static int update_call_counter(struct sip_pvt *fup, int event)
05694 {
05695 char name[256];
05696 int *inuse = NULL, *call_limit = NULL, *inringing = NULL;
05697 int outgoing = fup->outgoing_call;
05698 struct sip_peer *p = NULL;
05699
05700 ast_debug(3, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
05701
05702
05703
05704
05705 if (!ast_test_flag(&fup->flags[0], SIP_CALL_LIMIT) && !ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD))
05706 return 0;
05707
05708 ast_copy_string(name, fup->username, sizeof(name));
05709
05710
05711 if ((p = find_peer(ast_strlen_zero(fup->peername) ? name : fup->peername, NULL, TRUE, FINDALLDEVICES, FALSE, 0))) {
05712 inuse = &p->inUse;
05713 call_limit = &p->call_limit;
05714 inringing = &p->inRinging;
05715 ast_copy_string(name, fup->peername, sizeof(name));
05716 }
05717 if (!p) {
05718 ast_debug(2, "%s is not a local device, no call limit\n", name);
05719 return 0;
05720 }
05721
05722 switch(event) {
05723
05724 case DEC_CALL_LIMIT:
05725
05726 if (inuse) {
05727 sip_pvt_lock(fup);
05728 ao2_lock(p);
05729 if (*inuse > 0) {
05730 if (ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
05731 (*inuse)--;
05732 ast_clear_flag(&fup->flags[0], SIP_INC_COUNT);
05733 }
05734 } else {
05735 *inuse = 0;
05736 }
05737 ao2_unlock(p);
05738 sip_pvt_unlock(fup);
05739 }
05740
05741
05742 if (inringing) {
05743 sip_pvt_lock(fup);
05744 ao2_lock(p);
05745 if (*inringing > 0) {
05746 if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
05747 (*inringing)--;
05748 ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
05749 }
05750 } else {
05751 *inringing = 0;
05752 }
05753 ao2_unlock(p);
05754 sip_pvt_unlock(fup);
05755 }
05756
05757
05758 sip_pvt_lock(fup);
05759 ao2_lock(p);
05760 if (ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD) && sip_cfg.notifyhold) {
05761 ast_clear_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD);
05762 ao2_unlock(p);
05763 sip_pvt_unlock(fup);
05764 sip_peer_hold(fup, FALSE);
05765 } else {
05766 ao2_unlock(p);
05767 sip_pvt_unlock(fup);
05768 }
05769 if (sipdebug)
05770 ast_debug(2, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
05771 break;
05772
05773 case INC_CALL_RINGING:
05774 case INC_CALL_LIMIT:
05775
05776 if (*call_limit > 0 ) {
05777 if (*inuse >= *call_limit) {
05778 ast_log(LOG_NOTICE, "Call %s %s '%s' rejected due to usage limit of %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
05779 unref_peer(p, "update_call_counter: unref peer p, call limit exceeded");
05780 return -1;
05781 }
05782 }
05783 if (inringing && (event == INC_CALL_RINGING)) {
05784 sip_pvt_lock(fup);
05785 ao2_lock(p);
05786 if (!ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
05787 (*inringing)++;
05788 ast_set_flag(&fup->flags[0], SIP_INC_RINGING);
05789 }
05790 ao2_unlock(p);
05791 sip_pvt_unlock(fup);
05792 }
05793 if (inuse) {
05794 sip_pvt_lock(fup);
05795 ao2_lock(p);
05796 if (!ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
05797 (*inuse)++;
05798 ast_set_flag(&fup->flags[0], SIP_INC_COUNT);
05799 }
05800 ao2_unlock(p);
05801 sip_pvt_unlock(fup);
05802 }
05803 if (sipdebug) {
05804 ast_debug(2, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", "peer", name, *inuse, *call_limit);
05805 }
05806 break;
05807
05808 case DEC_CALL_RINGING:
05809 if (inringing) {
05810 sip_pvt_lock(fup);
05811 ao2_lock(p);
05812 if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
05813 if (*inringing > 0) {
05814 (*inringing)--;
05815 }
05816 ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
05817 }
05818 ao2_unlock(p);
05819 sip_pvt_unlock(fup);
05820 }
05821 break;
05822
05823 default:
05824 ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
05825 }
05826
05827 if (p) {
05828 ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", p->name);
05829 unref_peer(p, "update_call_counter: unref_peer from call counter");
05830 }
05831 return 0;
05832 }
05833
05834
05835 static void sip_destroy_fn(void *p)
05836 {
05837 sip_destroy(p);
05838 }
05839
05840
05841
05842
05843
05844
05845 static struct sip_pvt * sip_destroy(struct sip_pvt *p)
05846 {
05847 ast_debug(3, "Destroying SIP dialog %s\n", p->callid);
05848 __sip_destroy(p, TRUE, TRUE);
05849 return NULL;
05850 }
05851
05852
05853 static int hangup_sip2cause(int cause)
05854 {
05855
05856
05857 switch(cause) {
05858 case 401:
05859 return AST_CAUSE_CALL_REJECTED;
05860 case 403:
05861 return AST_CAUSE_CALL_REJECTED;
05862 case 404:
05863 return AST_CAUSE_UNALLOCATED;
05864 case 405:
05865 return AST_CAUSE_INTERWORKING;
05866 case 407:
05867 return AST_CAUSE_CALL_REJECTED;
05868 case 408:
05869 return AST_CAUSE_NO_USER_RESPONSE;
05870 case 409:
05871 return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
05872 case 410:
05873 return AST_CAUSE_NUMBER_CHANGED;
05874 case 411:
05875 return AST_CAUSE_INTERWORKING;
05876 case 413:
05877 return AST_CAUSE_INTERWORKING;
05878 case 414:
05879 return AST_CAUSE_INTERWORKING;
05880 case 415:
05881 return AST_CAUSE_INTERWORKING;
05882 case 420:
05883 return AST_CAUSE_NO_ROUTE_DESTINATION;
05884 case 480:
05885 return AST_CAUSE_NO_ANSWER;
05886 case 481:
05887 return AST_CAUSE_INTERWORKING;
05888 case 482:
05889 return AST_CAUSE_INTERWORKING;
05890 case 483:
05891 return AST_CAUSE_NO_ANSWER;
05892 case 484:
05893 return AST_CAUSE_INVALID_NUMBER_FORMAT;
05894 case 485:
05895 return AST_CAUSE_UNALLOCATED;
05896 case 486:
05897 return AST_CAUSE_BUSY;
05898 case 487:
05899 return AST_CAUSE_INTERWORKING;
05900 case 488:
05901 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
05902 case 491:
05903 return AST_CAUSE_INTERWORKING;
05904 case 493:
05905 return AST_CAUSE_INTERWORKING;
05906 case 500:
05907 return AST_CAUSE_FAILURE;
05908 case 501:
05909 return AST_CAUSE_FACILITY_REJECTED;
05910 case 502:
05911 return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
05912 case 503:
05913 return AST_CAUSE_CONGESTION;
05914 case 504:
05915 return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
05916 case 505:
05917 return AST_CAUSE_INTERWORKING;
05918 case 600:
05919 return AST_CAUSE_USER_BUSY;
05920 case 603:
05921 return AST_CAUSE_CALL_REJECTED;
05922 case 604:
05923 return AST_CAUSE_UNALLOCATED;
05924 case 606:
05925 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
05926 default:
05927 return AST_CAUSE_NORMAL;
05928 }
05929
05930 return 0;
05931 }
05932
05933
05934
05935
05936
05937
05938
05939
05940
05941
05942
05943
05944
05945
05946
05947
05948
05949
05950
05951
05952
05953
05954
05955
05956
05957
05958
05959
05960
05961
05962
05963
05964
05965 static const char *hangup_cause2sip(int cause)
05966 {
05967 switch (cause) {
05968 case AST_CAUSE_UNALLOCATED:
05969 case AST_CAUSE_NO_ROUTE_DESTINATION:
05970 case AST_CAUSE_NO_ROUTE_TRANSIT_NET:
05971 return "404 Not Found";
05972 case AST_CAUSE_CONGESTION:
05973 case AST_CAUSE_SWITCH_CONGESTION:
05974 return "503 Service Unavailable";
05975 case AST_CAUSE_NO_USER_RESPONSE:
05976 return "408 Request Timeout";
05977 case AST_CAUSE_NO_ANSWER:
05978 case AST_CAUSE_UNREGISTERED:
05979 return "480 Temporarily unavailable";
05980 case AST_CAUSE_CALL_REJECTED:
05981 return "403 Forbidden";
05982 case AST_CAUSE_NUMBER_CHANGED:
05983 return "410 Gone";
05984 case AST_CAUSE_NORMAL_UNSPECIFIED:
05985 return "480 Temporarily unavailable";
05986 case AST_CAUSE_INVALID_NUMBER_FORMAT:
05987 return "484 Address incomplete";
05988 case AST_CAUSE_USER_BUSY:
05989 return "486 Busy here";
05990 case AST_CAUSE_FAILURE:
05991 return "500 Server internal failure";
05992 case AST_CAUSE_FACILITY_REJECTED:
05993 return "501 Not Implemented";
05994 case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
05995 return "503 Service Unavailable";
05996
05997 case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
05998 return "502 Bad Gateway";
05999 case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL:
06000 return "488 Not Acceptable Here";
06001
06002 case AST_CAUSE_NOTDEFINED:
06003 default:
06004 ast_debug(1, "AST hangup cause %d (no match found in SIP)\n", cause);
06005 return NULL;
06006 }
06007
06008
06009 return 0;
06010 }
06011
06012
06013
06014
06015 static int sip_hangup(struct ast_channel *ast)
06016 {
06017 struct sip_pvt *p = ast->tech_pvt;
06018 int needcancel = FALSE;
06019 int needdestroy = 0;
06020 struct ast_channel *oldowner = ast;
06021
06022 if (!p) {
06023 ast_debug(1, "Asked to hangup channel that was not connected\n");
06024 return 0;
06025 }
06026 if (ast_test_flag(ast, AST_FLAG_ANSWERED_ELSEWHERE) || ast->hangupcause == AST_CAUSE_ANSWERED_ELSEWHERE) {
06027 ast_debug(1, "This call was answered elsewhere");
06028 if (ast->hangupcause == AST_CAUSE_ANSWERED_ELSEWHERE) {
06029 ast_debug(1, "####### It's the cause code, buddy. The cause code!!!\n");
06030 }
06031 append_history(p, "Cancel", "Call answered elsewhere");
06032 p->answered_elsewhere = TRUE;
06033 }
06034
06035
06036 if (p->owner)
06037 p->hangupcause = p->owner->hangupcause;
06038
06039 if (ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
06040 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
06041 if (sipdebug)
06042 ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
06043 update_call_counter(p, DEC_CALL_LIMIT);
06044 }
06045 ast_debug(4, "SIP Transfer: Not hanging up right now... Rescheduling hangup for %s.\n", p->callid);
06046 if (p->autokillid > -1 && sip_cancel_destroy(p))
06047 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
06048 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06049 ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
06050 p->needdestroy = 0;
06051 p->owner->tech_pvt = dialog_unref(p->owner->tech_pvt, "unref p->owner->tech_pvt");
06052 sip_pvt_lock(p);
06053 p->owner = NULL;
06054 sip_pvt_unlock(p);
06055 ast_module_unref(ast_module_info->self);
06056 return 0;
06057 }
06058
06059 if (ast_test_flag(ast, AST_FLAG_ZOMBIE)) {
06060 if (p->refer)
06061 ast_debug(1, "SIP Transfer: Hanging up Zombie channel %s after transfer ... Call-ID: %s\n", ast->name, p->callid);
06062 else
06063 ast_debug(1, "Hanging up zombie call. Be scared.\n");
06064 } else
06065 ast_debug(1, "Hangup call %s, SIP callid %s\n", ast->name, p->callid);
06066
06067 sip_pvt_lock(p);
06068 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
06069 if (sipdebug)
06070 ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
06071 update_call_counter(p, DEC_CALL_LIMIT);
06072 }
06073
06074
06075 if (p->owner != ast) {
06076 ast_log(LOG_WARNING, "Huh? We aren't the owner? Can't hangup call.\n");
06077 sip_pvt_unlock(p);
06078 return 0;
06079 }
06080
06081
06082 if (p->invitestate < INV_COMPLETED && p->owner->_state != AST_STATE_UP) {
06083 needcancel = TRUE;
06084 ast_debug(4, "Hanging up channel in state %s (not UP)\n", ast_state2str(ast->_state));
06085 }
06086
06087 stop_media_flows(p);
06088
06089 append_history(p, needcancel ? "Cancel" : "Hangup", "Cause %s", p->owner ? ast_cause2str(p->hangupcause) : "Unknown");
06090
06091
06092 if (p->dsp)
06093 ast_dsp_free(p->dsp);
06094
06095 p->owner = NULL;
06096 ast->tech_pvt = dialog_unref(ast->tech_pvt, "unref ast->tech_pvt");
06097
06098 ast_module_unref(ast_module_info->self);
06099
06100
06101
06102
06103
06104
06105 if (p->alreadygone)
06106 needdestroy = 1;
06107 else if (p->invitestate != INV_CALLING)
06108 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06109
06110
06111 if (!p->alreadygone && p->initreq.data && !ast_strlen_zero(p->initreq.data->str)) {
06112 if (needcancel) {
06113 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06114
06115
06116 if (p->invitestate == INV_CALLING) {
06117
06118 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
06119 __sip_pretend_ack(p);
06120
06121 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06122 append_history(p, "DELAY", "Not sending cancel, waiting for timeout");
06123 } else {
06124 struct sip_pkt *cur;
06125
06126 for (cur = p->packets; cur; cur = cur->next) {
06127 __sip_semi_ack(p, cur->seqno, cur->is_resp, cur->method ? cur->method : find_sip_method(cur->data->str));
06128 }
06129 p->invitestate = INV_CANCELLED;
06130
06131 transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
06132
06133
06134 needdestroy = 0;
06135 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06136 }
06137 } else {
06138 const char *res;
06139 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"));
06140 if (p->hangupcause && (res = hangup_cause2sip(p->hangupcause)))
06141 transmit_response_reliable(p, res, &p->initreq);
06142 else
06143 transmit_response_reliable(p, "603 Declined", &p->initreq);
06144 p->invitestate = INV_TERMINATED;
06145 }
06146 } else {
06147 if (p->stimer->st_active == TRUE) {
06148 stop_session_timer(p);
06149 }
06150
06151 if (!p->pendinginvite) {
06152 struct ast_channel *bridge = ast_bridged_channel(oldowner);
06153 char *audioqos = "";
06154 char *videoqos = "";
06155 char *textqos = "";
06156
06157
06158
06159
06160 while (bridge && ast_channel_trylock(bridge)) {
06161 sip_pvt_unlock(p);
06162 do {
06163
06164 CHANNEL_DEADLOCK_AVOIDANCE(oldowner);
06165 } while (sip_pvt_trylock(p));
06166 bridge = ast_bridged_channel(oldowner);
06167 }
06168
06169 if (p->rtp)
06170 ast_rtp_set_vars(oldowner, p->rtp);
06171
06172 if (bridge) {
06173 struct sip_pvt *q = bridge->tech_pvt;
06174
06175 if (IS_SIP_TECH(bridge->tech) && q && q->rtp)
06176 ast_rtp_set_vars(bridge, q->rtp);
06177 ast_channel_unlock(bridge);
06178 }
06179
06180 if (p->vrtp)
06181 videoqos = ast_rtp_get_quality(p->vrtp, NULL, RTPQOS_SUMMARY);
06182 if (p->trtp)
06183 textqos = ast_rtp_get_quality(p->trtp, NULL, RTPQOS_SUMMARY);
06184
06185 if (oldowner->_state == AST_STATE_UP) {
06186 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
06187 }
06188
06189
06190 if (p->do_history) {
06191 if (p->rtp)
06192 append_history(p, "RTCPaudio", "Quality:%s", audioqos);
06193 if (p->vrtp)
06194 append_history(p, "RTCPvideo", "Quality:%s", videoqos);
06195 if (p->trtp)
06196 append_history(p, "RTCPtext", "Quality:%s", textqos);
06197 }
06198 if (p->rtp && oldowner)
06199 pbx_builtin_setvar_helper(oldowner, "RTPAUDIOQOS", audioqos);
06200 if (p->vrtp && oldowner)
06201 pbx_builtin_setvar_helper(oldowner, "RTPVIDEOQOS", videoqos);
06202 if (p->trtp && oldowner)
06203 pbx_builtin_setvar_helper(oldowner, "RTPTEXTQOS", textqos);
06204 } else {
06205
06206
06207 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
06208 ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);
06209 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"));
06210 if (sip_cancel_destroy(p))
06211 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
06212 }
06213 }
06214 }
06215 if (needdestroy) {
06216 pvt_set_needdestroy(p, "hangup");
06217 }
06218 sip_pvt_unlock(p);
06219 return 0;
06220 }
06221
06222
06223 static void try_suggested_sip_codec(struct sip_pvt *p)
06224 {
06225 int fmt;
06226 const char *codec;
06227
06228 codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC");
06229 if (!codec)
06230 return;
06231
06232 fmt = ast_getformatbyname(codec);
06233 if (fmt) {
06234 ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC} variable\n", codec);
06235 if (p->jointcapability & fmt) {
06236 p->jointcapability &= fmt;
06237 p->capability &= fmt;
06238 } else
06239 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
06240 } else
06241 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n", codec);
06242 return;
06243 }
06244
06245
06246
06247 static int sip_answer(struct ast_channel *ast)
06248 {
06249 int res = 0;
06250 struct sip_pvt *p = ast->tech_pvt;
06251
06252 sip_pvt_lock(p);
06253 if (ast->_state != AST_STATE_UP) {
06254 try_suggested_sip_codec(p);
06255
06256 ast_setstate(ast, AST_STATE_UP);
06257 ast_debug(1, "SIP answering channel: %s\n", ast->name);
06258 ast_rtp_new_source(p->rtp);
06259 res = transmit_response_with_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL, FALSE);
06260 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
06261 }
06262 sip_pvt_unlock(p);
06263 return res;
06264 }
06265
06266
06267 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
06268 {
06269 struct sip_pvt *p = ast->tech_pvt;
06270 int res = 0;
06271
06272 switch (frame->frametype) {
06273 case AST_FRAME_VOICE:
06274 if (!(frame->subclass & ast->nativeformats)) {
06275 char s1[512], s2[512], s3[512];
06276 ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %s(%d) read/write = %s(%d)/%s(%d)\n",
06277 frame->subclass,
06278 ast_getformatname_multiple(s1, sizeof(s1) - 1, ast->nativeformats & AST_FORMAT_AUDIO_MASK),
06279 ast->nativeformats & AST_FORMAT_AUDIO_MASK,
06280 ast_getformatname_multiple(s2, sizeof(s2) - 1, ast->readformat),
06281 ast->readformat,
06282 ast_getformatname_multiple(s3, sizeof(s3) - 1, ast->writeformat),
06283 ast->writeformat);
06284 return 0;
06285 }
06286 if (p) {
06287 sip_pvt_lock(p);
06288 if (p->rtp) {
06289
06290 if ((ast->_state != AST_STATE_UP) &&
06291 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06292 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06293 ast_rtp_new_source(p->rtp);
06294 if (!global_prematuremediafilter) {
06295 p->invitestate = INV_EARLY_MEDIA;
06296 transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06297 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06298 }
06299 } else if (p->t38.state == T38_ENABLED) {
06300
06301 } else {
06302 p->lastrtptx = time(NULL);
06303 res = ast_rtp_write(p->rtp, frame);
06304 }
06305 }
06306 sip_pvt_unlock(p);
06307 }
06308 break;
06309 case AST_FRAME_VIDEO:
06310 if (p) {
06311 sip_pvt_lock(p);
06312 if (p->vrtp) {
06313
06314 if ((ast->_state != AST_STATE_UP) &&
06315 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06316 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06317 p->invitestate = INV_EARLY_MEDIA;
06318 transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06319 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06320 }
06321 p->lastrtptx = time(NULL);
06322 res = ast_rtp_write(p->vrtp, frame);
06323 }
06324 sip_pvt_unlock(p);
06325 }
06326 break;
06327 case AST_FRAME_TEXT:
06328 if (p) {
06329 sip_pvt_lock(p);
06330 if (p->red) {
06331 red_buffer_t140(p->trtp, frame);
06332 } else {
06333 if (p->trtp) {
06334
06335 if ((ast->_state != AST_STATE_UP) &&
06336 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06337 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06338 p->invitestate = INV_EARLY_MEDIA;
06339 transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06340 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06341 }
06342 p->lastrtptx = time(NULL);
06343 res = ast_rtp_write(p->trtp, frame);
06344 }
06345 }
06346 sip_pvt_unlock(p);
06347 }
06348 break;
06349 case AST_FRAME_IMAGE:
06350 return 0;
06351 break;
06352 case AST_FRAME_MODEM:
06353 if (p) {
06354 sip_pvt_lock(p);
06355
06356
06357
06358
06359 if ((ast->_state == AST_STATE_UP) &&
06360 p->udptl &&
06361 (p->t38.state == T38_ENABLED)) {
06362 res = ast_udptl_write(p->udptl, frame);
06363 }
06364 sip_pvt_unlock(p);
06365 }
06366 break;
06367 default:
06368 ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
06369 return 0;
06370 }
06371
06372 return res;
06373 }
06374
06375
06376
06377 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
06378 {
06379 int ret = -1;
06380 struct sip_pvt *p;
06381
06382 if (newchan && ast_test_flag(newchan, AST_FLAG_ZOMBIE))
06383 ast_debug(1, "New channel is zombie\n");
06384 if (oldchan && ast_test_flag(oldchan, AST_FLAG_ZOMBIE))
06385 ast_debug(1, "Old channel is zombie\n");
06386
06387 if (!newchan || !newchan->tech_pvt) {
06388 if (!newchan)
06389 ast_log(LOG_WARNING, "No new channel! Fixup of %s failed.\n", oldchan->name);
06390 else
06391 ast_log(LOG_WARNING, "No SIP tech_pvt! Fixup of %s failed.\n", oldchan->name);
06392 return -1;
06393 }
06394 p = newchan->tech_pvt;
06395
06396 sip_pvt_lock(p);
06397 append_history(p, "Masq", "Old channel: %s\n", oldchan->name);
06398 append_history(p, "Masq (cont)", "...new owner: %s\n", newchan->name);
06399 if (p->owner != oldchan)
06400 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
06401 else {
06402 p->owner = newchan;
06403
06404
06405
06406
06407
06408
06409 sip_set_rtp_peer(newchan, NULL, NULL, 0, 0, 0);
06410 ret = 0;
06411 }
06412 ast_debug(3, "SIP Fixup: New owner for dialogue %s: %s (Old parent: %s)\n", p->callid, p->owner->name, oldchan->name);
06413
06414 sip_pvt_unlock(p);
06415 return ret;
06416 }
06417
06418 static int sip_senddigit_begin(struct ast_channel *ast, char digit)
06419 {
06420 struct sip_pvt *p = ast->tech_pvt;
06421 int res = 0;
06422
06423 sip_pvt_lock(p);
06424 switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
06425 case SIP_DTMF_INBAND:
06426 res = -1;
06427 break;
06428 case SIP_DTMF_RFC2833:
06429 if (p->rtp)
06430 ast_rtp_senddigit_begin(p->rtp, digit);
06431 break;
06432 default:
06433 break;
06434 }
06435 sip_pvt_unlock(p);
06436
06437 return res;
06438 }
06439
06440
06441
06442 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration)
06443 {
06444 struct sip_pvt *p = ast->tech_pvt;
06445 int res = 0;
06446
06447 sip_pvt_lock(p);
06448 switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
06449 case SIP_DTMF_INFO:
06450 case SIP_DTMF_SHORTINFO:
06451 transmit_info_with_digit(p, digit, duration);
06452 break;
06453 case SIP_DTMF_RFC2833:
06454 if (p->rtp)
06455 ast_rtp_senddigit_end(p->rtp, digit);
06456 break;
06457 case SIP_DTMF_INBAND:
06458 res = -1;
06459 break;
06460 }
06461 sip_pvt_unlock(p);
06462
06463 return res;
06464 }
06465
06466
06467 static int sip_transfer(struct ast_channel *ast, const char *dest)
06468 {
06469 struct sip_pvt *p = ast->tech_pvt;
06470 int res;
06471
06472 if (dest == NULL)
06473 dest = "";
06474 sip_pvt_lock(p);
06475 if (ast->_state == AST_STATE_RING)
06476 res = sip_sipredirect(p, dest);
06477 else
06478 res = transmit_refer(p, dest);
06479 sip_pvt_unlock(p);
06480 return res;
06481 }
06482
06483
06484 static int interpret_t38_parameters(struct sip_pvt *p, const struct ast_control_t38_parameters *parameters)
06485 {
06486 int res = 0;
06487
06488 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) || !p->udptl) {
06489 return -1;
06490 }
06491 switch (parameters->request_response) {
06492 case AST_T38_NEGOTIATED:
06493 case AST_T38_REQUEST_NEGOTIATE:
06494
06495 if (!parameters->max_ifp) {
06496 change_t38_state(p, T38_DISABLED);
06497 if (p->t38.state == T38_PEER_REINVITE) {
06498 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"));
06499 transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
06500 }
06501 break;
06502 } else if (p->t38.state == T38_PEER_REINVITE) {
06503 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"));
06504 p->t38.our_parms = *parameters;
06505
06506
06507
06508 if (!p->t38.their_parms.fill_bit_removal) {
06509 p->t38.our_parms.fill_bit_removal = FALSE;
06510 }
06511 if (!p->t38.their_parms.transcoding_mmr) {
06512 p->t38.our_parms.transcoding_mmr = FALSE;
06513 }
06514 if (!p->t38.their_parms.transcoding_jbig) {
06515 p->t38.our_parms.transcoding_jbig = FALSE;
06516 }
06517 p->t38.our_parms.version = MIN(p->t38.our_parms.version, p->t38.their_parms.version);
06518 p->t38.our_parms.rate_management = p->t38.their_parms.rate_management;
06519 ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
06520 change_t38_state(p, T38_ENABLED);
06521 transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
06522 } else if (p->t38.state != T38_ENABLED) {
06523 p->t38.our_parms = *parameters;
06524 ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
06525 change_t38_state(p, T38_LOCAL_REINVITE);
06526 if (!p->pendinginvite) {
06527 transmit_reinvite_with_sdp(p, TRUE, FALSE);
06528 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
06529 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
06530 }
06531 }
06532 break;
06533 case AST_T38_TERMINATED:
06534 case AST_T38_REFUSED:
06535 case AST_T38_REQUEST_TERMINATE:
06536 if (p->t38.state == T38_PEER_REINVITE) {
06537 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"));
06538 change_t38_state(p, T38_DISABLED);
06539 transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
06540 } else if (p->t38.state == T38_ENABLED)
06541 transmit_reinvite_with_sdp(p, FALSE, FALSE);
06542 break;
06543 case AST_T38_REQUEST_PARMS: {
06544 struct ast_control_t38_parameters parameters = p->t38.their_parms;
06545
06546 if (p->t38.state == T38_PEER_REINVITE) {
06547 AST_SCHED_DEL(sched, p->t38id);
06548 parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
06549 parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
06550 ast_queue_control_data(p->owner, AST_CONTROL_T38_PARAMETERS, ¶meters, sizeof(parameters));
06551
06552
06553
06554
06555 res = AST_T38_REQUEST_PARMS;
06556 }
06557 break;
06558 }
06559 default:
06560 res = -1;
06561 break;
06562 }
06563
06564 return res;
06565 }
06566
06567
06568
06569
06570
06571
06572 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
06573 {
06574 struct sip_pvt *p = ast->tech_pvt;
06575 int res = 0;
06576
06577 sip_pvt_lock(p);
06578 switch(condition) {
06579 case AST_CONTROL_RINGING:
06580 if (ast->_state == AST_STATE_RING) {
06581 p->invitestate = INV_EARLY_MEDIA;
06582 if (!ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) ||
06583 (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) {
06584
06585 transmit_provisional_response(p, "180 Ringing", &p->initreq, 0);
06586 ast_set_flag(&p->flags[0], SIP_RINGING);
06587 if (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) != SIP_PROG_INBAND_YES)
06588 break;
06589 } else {
06590
06591 }
06592 }
06593 res = -1;
06594 break;
06595 case AST_CONTROL_BUSY:
06596 if (ast->_state != AST_STATE_UP) {
06597 transmit_response_reliable(p, "486 Busy Here", &p->initreq);
06598 p->invitestate = INV_COMPLETED;
06599 sip_alreadygone(p);
06600 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
06601 break;
06602 }
06603 res = -1;
06604 break;
06605 case AST_CONTROL_CONGESTION:
06606 if (ast->_state != AST_STATE_UP) {
06607 transmit_response_reliable(p, "503 Service Unavailable", &p->initreq);
06608 p->invitestate = INV_COMPLETED;
06609 sip_alreadygone(p);
06610 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
06611 break;
06612 }
06613 res = -1;
06614 break;
06615 case AST_CONTROL_PROCEEDING:
06616 if ((ast->_state != AST_STATE_UP) &&
06617 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06618 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06619 transmit_response(p, "100 Trying", &p->initreq);
06620 p->invitestate = INV_PROCEEDING;
06621 break;
06622 }
06623 res = -1;
06624 break;
06625 case AST_CONTROL_PROGRESS:
06626 if ((ast->_state != AST_STATE_UP) &&
06627 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06628 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06629 p->invitestate = INV_EARLY_MEDIA;
06630 transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06631 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06632 break;
06633 }
06634 res = -1;
06635 break;
06636 case AST_CONTROL_HOLD:
06637 ast_rtp_new_source(p->rtp);
06638 ast_moh_start(ast, data, p->mohinterpret);
06639 break;
06640 case AST_CONTROL_UNHOLD:
06641 ast_rtp_new_source(p->rtp);
06642 ast_moh_stop(ast);
06643 break;
06644 case AST_CONTROL_VIDUPDATE:
06645 if (p->vrtp && !p->novideo) {
06646 transmit_info_with_vidupdate(p);
06647
06648 } else
06649 res = -1;
06650 break;
06651 case AST_CONTROL_T38_PARAMETERS:
06652 if (datalen != sizeof(struct ast_control_t38_parameters)) {
06653 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);
06654 res = -1;
06655 } else {
06656 const struct ast_control_t38_parameters *parameters = data;
06657 res = interpret_t38_parameters(p, parameters);
06658 }
06659 break;
06660 case AST_CONTROL_SRCUPDATE:
06661 ast_rtp_new_source(p->rtp);
06662 break;
06663 case AST_CONTROL_SRCCHANGE:
06664 ast_rtp_change_source(p->rtp);
06665 break;
06666 case -1:
06667 res = -1;
06668 break;
06669 default:
06670 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
06671 res = -1;
06672 break;
06673 }
06674 sip_pvt_unlock(p);
06675 return res;
06676 }
06677
06678
06679
06680
06681
06682
06683
06684 static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title)
06685 {
06686 struct ast_channel *tmp;
06687 struct ast_variable *v = NULL;
06688 int fmt;
06689 int what;
06690 int video;
06691 int text;
06692 int needvideo = 0;
06693 int needtext = 0;
06694 char buf[SIPBUFSIZE];
06695 char *decoded_exten;
06696
06697 {
06698 const char *my_name;
06699
06700 if (title) {
06701 my_name = title;
06702 } else {
06703 char *port = NULL;
06704 my_name = ast_strdupa(i->fromdomain);
06705 if ((port = strchr(i->fromdomain, ':'))) {
06706 *port = '\0';
06707 }
06708 }
06709
06710 sip_pvt_unlock(i);
06711
06712 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));
06713
06714 }
06715 if (!tmp) {
06716 ast_log(LOG_WARNING, "Unable to allocate AST channel structure for SIP channel\n");
06717 sip_pvt_lock(i);
06718 return NULL;
06719 }
06720 sip_pvt_lock(i);
06721
06722 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;
06723
06724
06725
06726 if (i->jointcapability) {
06727 what = i->jointcapability;
06728 video = i->jointcapability & AST_FORMAT_VIDEO_MASK;
06729 text = i->jointcapability & AST_FORMAT_TEXT_MASK;
06730 } else if (i->capability) {
06731 what = i->capability;
06732 video = i->capability & AST_FORMAT_VIDEO_MASK;
06733 text = i->capability & AST_FORMAT_TEXT_MASK;
06734 } else {
06735 what = global_capability;
06736 video = global_capability & AST_FORMAT_VIDEO_MASK;
06737 text = global_capability & AST_FORMAT_TEXT_MASK;
06738 }
06739
06740
06741 tmp->nativeformats = ast_codec_choose(&i->prefs, what, 1) | video | text;
06742 ast_debug(3, "*** Our native formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, tmp->nativeformats));
06743 ast_debug(3, "*** Joint capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->jointcapability));
06744 ast_debug(3, "*** Our capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->capability));
06745 ast_debug(3, "*** AST_CODEC_CHOOSE formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, ast_codec_choose(&i->prefs, what, 1)));
06746 if (i->prefcodec)
06747 ast_debug(3, "*** Our preferred formats from the incoming channel are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->prefcodec));
06748
06749
06750 fmt = ast_best_codec(tmp->nativeformats);
06751
06752
06753
06754
06755
06756 if (i->vrtp) {
06757 if (ast_test_flag(&i->flags[1], SIP_PAGE2_VIDEOSUPPORT))
06758 needvideo = AST_FORMAT_VIDEO_MASK;
06759 else if (i->prefcodec)
06760 needvideo = i->prefcodec & AST_FORMAT_VIDEO_MASK;
06761 else
06762 needvideo = i->jointcapability & AST_FORMAT_VIDEO_MASK;
06763 }
06764
06765 if (i->trtp) {
06766 if (i->prefcodec)
06767 needtext = i->prefcodec & AST_FORMAT_TEXT_MASK;
06768 else
06769 needtext = i->jointcapability & AST_FORMAT_TEXT_MASK;
06770 }
06771
06772 if (needvideo)
06773 ast_debug(3, "This channel can handle video! HOLLYWOOD next!\n");
06774 else
06775 ast_debug(3, "This channel will not be able to handle video.\n");
06776
06777 if ((ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) || (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) ||
06778 (ast_test_flag(&i->flags[1], SIP_PAGE2_FAX_DETECT))) {
06779 int features = 0;
06780
06781 if ((ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) || (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
06782 features |= DSP_FEATURE_DIGIT_DETECT;
06783 }
06784
06785 if (ast_test_flag(&i->flags[1], SIP_PAGE2_FAX_DETECT)) {
06786 features |= DSP_FEATURE_FAX_DETECT;
06787 }
06788
06789 i->dsp = ast_dsp_new();
06790 ast_dsp_set_features(i->dsp, features);
06791 if (global_relaxdtmf)
06792 ast_dsp_set_digitmode(i->dsp, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
06793 }
06794
06795
06796 if (i->rtp) {
06797 ast_channel_set_fd(tmp, 0, ast_rtp_fd(i->rtp));
06798 ast_channel_set_fd(tmp, 1, ast_rtcp_fd(i->rtp));
06799 }
06800 if (needvideo && i->vrtp) {
06801 ast_channel_set_fd(tmp, 2, ast_rtp_fd(i->vrtp));
06802 ast_channel_set_fd(tmp, 3, ast_rtcp_fd(i->vrtp));
06803 }
06804 if (needtext && i->trtp)
06805 ast_channel_set_fd(tmp, 4, ast_rtp_fd(i->trtp));
06806 if (i->udptl)
06807 ast_channel_set_fd(tmp, 5, ast_udptl_fd(i->udptl));
06808
06809 if (state == AST_STATE_RING)
06810 tmp->rings = 1;
06811 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
06812 tmp->writeformat = fmt;
06813 tmp->rawwriteformat = fmt;
06814 tmp->readformat = fmt;
06815 tmp->rawreadformat = fmt;
06816 tmp->tech_pvt = dialog_ref(i, "sip_new: set chan->tech_pvt to i");
06817
06818 tmp->callgroup = i->callgroup;
06819 tmp->pickupgroup = i->pickupgroup;
06820 tmp->cid.cid_pres = i->callingpres;
06821 if (!ast_strlen_zero(i->parkinglot))
06822 ast_string_field_set(tmp, parkinglot, i->parkinglot);
06823 if (!ast_strlen_zero(i->accountcode))
06824 ast_string_field_set(tmp, accountcode, i->accountcode);
06825 if (i->amaflags)
06826 tmp->amaflags = i->amaflags;
06827 if (!ast_strlen_zero(i->language))
06828 ast_string_field_set(tmp, language, i->language);
06829 i->owner = tmp;
06830 ast_module_ref(ast_module_info->self);
06831 ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
06832
06833
06834
06835
06836 decoded_exten = ast_strdupa(i->exten);
06837 ast_uri_decode(decoded_exten);
06838 ast_copy_string(tmp->exten, decoded_exten, sizeof(tmp->exten));
06839
06840
06841
06842 tmp->cid.cid_ani = ast_strdup(i->cid_num);
06843 if (!ast_strlen_zero(i->rdnis))
06844 tmp->cid.cid_rdnis = ast_strdup(i->rdnis);
06845
06846 if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s"))
06847 tmp->cid.cid_dnid = ast_strdup(i->exten);
06848
06849 tmp->priority = 1;
06850 if (!ast_strlen_zero(i->uri))
06851 pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
06852 if (!ast_strlen_zero(i->domain))
06853 pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
06854 if (!ast_strlen_zero(i->callid))
06855 pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
06856 if (i->rtp)
06857 ast_jb_configure(tmp, &global_jbconf);
06858
06859
06860 for (v = i->chanvars ; v ; v = v->next) {
06861 char valuebuf[1024];
06862 pbx_builtin_setvar_helper(tmp, v->name, ast_get_encoded_str(v->value, valuebuf, sizeof(valuebuf)));
06863 }
06864
06865 if (state != AST_STATE_DOWN && ast_pbx_start(tmp)) {
06866 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
06867 tmp->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
06868 ast_hangup(tmp);
06869 tmp = NULL;
06870 }
06871
06872 if (i->do_history)
06873 append_history(i, "NewChan", "Channel %s - from %s", tmp->name, i->callid);
06874
06875
06876 if (sip_cfg.callevents)
06877 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
06878 "Channel: %s\r\nUniqueid: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\n",
06879 tmp->name, tmp->uniqueid, "SIP", i->callid, i->fullcontact);
06880
06881 return tmp;
06882 }
06883
06884
06885 static char *get_body_by_line(const char *line, const char *name, int nameLen, char delimiter)
06886 {
06887 if (!strncasecmp(line, name, nameLen) && line[nameLen] == delimiter)
06888 return ast_skip_blanks(line + nameLen + 1);
06889
06890 return "";
06891 }
06892
06893
06894
06895
06896
06897 static const char *get_sdp_iterate(int *start, struct sip_request *req, const char *name)
06898 {
06899 int len = strlen(name);
06900
06901 while (*start < (req->sdp_start + req->sdp_count)) {
06902 const char *r = get_body_by_line(REQ_OFFSET_TO_STR(req, line[(*start)++]), name, len, '=');
06903 if (r[0] != '\0')
06904 return r;
06905 }
06906
06907
06908 (*start)++;
06909
06910 return "";
06911 }
06912
06913
06914
06915
06916
06917
06918 static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value)
06919 {
06920 char type = '\0';
06921 const char *line = NULL;
06922
06923 if (stop > (req->sdp_start + req->sdp_count)) {
06924 stop = req->sdp_start + req->sdp_count;
06925 }
06926
06927 while (*start < stop) {
06928 line = REQ_OFFSET_TO_STR(req, line[(*start)++]);
06929 if (line[1] == '=') {
06930 type = line[0];
06931 *value = ast_skip_blanks(line + 2);
06932 break;
06933 }
06934 }
06935
06936 return type;
06937 }
06938
06939
06940 static char *get_body(struct sip_request *req, char *name, char delimiter)
06941 {
06942 int x;
06943 int len = strlen(name);
06944 char *r;
06945
06946 for (x = 0; x < req->lines; x++) {
06947 r = get_body_by_line(REQ_OFFSET_TO_STR(req, line[x]), name, len, delimiter);
06948 if (r[0] != '\0')
06949 return r;
06950 }
06951
06952 return "";
06953 }
06954
06955
06956 static const char *find_alias(const char *name, const char *_default)
06957 {
06958
06959 static const struct cfalias {
06960 char * const fullname;
06961 char * const shortname;
06962 } aliases[] = {
06963 { "Content-Type", "c" },
06964 { "Content-Encoding", "e" },
06965 { "From", "f" },
06966 { "Call-ID", "i" },
06967 { "Contact", "m" },
06968 { "Content-Length", "l" },
06969 { "Subject", "s" },
06970 { "To", "t" },
06971 { "Supported", "k" },
06972 { "Refer-To", "r" },
06973 { "Referred-By", "b" },
06974 { "Allow-Events", "u" },
06975 { "Event", "o" },
06976 { "Via", "v" },
06977 { "Accept-Contact", "a" },
06978 { "Reject-Contact", "j" },
06979 { "Request-Disposition", "d" },
06980 { "Session-Expires", "x" },
06981 { "Identity", "y" },
06982 { "Identity-Info", "n" },
06983 };
06984 int x;
06985
06986 for (x = 0; x < ARRAY_LEN(aliases); x++) {
06987 if (!strcasecmp(aliases[x].fullname, name))
06988 return aliases[x].shortname;
06989 }
06990
06991 return _default;
06992 }
06993
06994 static const char *__get_header(const struct sip_request *req, const char *name, int *start)
06995 {
06996 int pass;
06997
06998
06999
07000
07001
07002
07003
07004
07005
07006
07007 for (pass = 0; name && pass < 2;pass++) {
07008 int x, len = strlen(name);
07009 for (x = *start; x < req->headers; x++) {
07010 char *header = REQ_OFFSET_TO_STR(req, header[x]);
07011 if (!strncasecmp(header, name, len)) {
07012 char *r = header + len;
07013 if (sip_cfg.pedanticsipchecking)
07014 r = ast_skip_blanks(r);
07015
07016 if (*r == ':') {
07017 *start = x+1;
07018 return ast_skip_blanks(r+1);
07019 }
07020 }
07021 }
07022 if (pass == 0)
07023 name = find_alias(name, NULL);
07024 }
07025
07026
07027 return "";
07028 }
07029
07030
07031
07032
07033 static const char *get_header(const struct sip_request *req, const char *name)
07034 {
07035 int start = 0;
07036 return __get_header(req, name, &start);
07037 }
07038
07039
07040 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect)
07041 {
07042
07043 struct ast_frame *f;
07044
07045 if (!p->rtp) {
07046
07047 return &ast_null_frame;
07048 }
07049
07050 switch(ast->fdno) {
07051 case 0:
07052 f = ast_rtp_read(p->rtp);
07053 break;
07054 case 1:
07055 f = ast_rtcp_read(p->rtp);
07056 break;
07057 case 2:
07058 f = ast_rtp_read(p->vrtp);
07059 break;
07060 case 3:
07061 f = ast_rtcp_read(p->vrtp);
07062 break;
07063 case 4:
07064 f = ast_rtp_read(p->trtp);
07065 if (sipdebug_text) {
07066 int i;
07067 unsigned char* arr = f->data.ptr;
07068 for (i=0; i < f->datalen; i++)
07069 ast_verbose("%c", (arr[i] > ' ' && arr[i] < '}') ? arr[i] : '.');
07070 ast_verbose(" -> ");
07071 for (i=0; i < f->datalen; i++)
07072 ast_verbose("%02X ", arr[i]);
07073 ast_verbose("\n");
07074 }
07075 break;
07076 case 5:
07077 f = ast_udptl_read(p->udptl);
07078 break;
07079 default:
07080 f = &ast_null_frame;
07081 }
07082
07083 if (f && (f->frametype == AST_FRAME_DTMF_BEGIN || f->frametype == AST_FRAME_DTMF_END) &&
07084 (ast_test_flag(&p->flags[0], SIP_DTMF) != SIP_DTMF_RFC2833)) {
07085 ast_debug(1, "Ignoring DTMF (%c) RTP frame because dtmfmode is not RFC2833\n", f->subclass);
07086 return &ast_null_frame;
07087 }
07088
07089
07090 if (!p->owner || (f && f->frametype != AST_FRAME_VOICE))
07091 return f;
07092
07093 if (f && f->subclass != (p->owner->nativeformats & AST_FORMAT_AUDIO_MASK)) {
07094 if (!(f->subclass & p->jointcapability)) {
07095 ast_debug(1, "Bogus frame of format '%s' received from '%s'!\n",
07096 ast_getformatname(f->subclass), p->owner->name);
07097 return &ast_null_frame;
07098 }
07099 ast_debug(1, "Oooh, format changed to %d %s\n",
07100 f->subclass, ast_getformatname(f->subclass));
07101 p->owner->nativeformats = (p->owner->nativeformats & (AST_FORMAT_VIDEO_MASK | AST_FORMAT_TEXT_MASK)) | f->subclass;
07102 ast_set_read_format(p->owner, p->owner->readformat);
07103 ast_set_write_format(p->owner, p->owner->writeformat);
07104 }
07105
07106 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) {
07107 f = ast_dsp_process(p->owner, p->dsp, f);
07108 if (f && f->frametype == AST_FRAME_DTMF) {
07109 if (f->subclass == 'f') {
07110 if (option_debug)
07111 ast_log(LOG_DEBUG, "Fax CNG detected on %s\n", ast->name);
07112 *faxdetect = 1;
07113
07114 if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
07115 ast_dsp_set_features(p->dsp, DSP_FEATURE_DIGIT_DETECT);
07116 } else {
07117 ast_dsp_free(p->dsp);
07118 p->dsp = NULL;
07119 }
07120 } else {
07121 ast_debug(1, "* Detected inband DTMF '%c'\n", f->subclass);
07122 }
07123 }
07124 }
07125
07126 return f;
07127 }
07128
07129
07130 static struct ast_frame *sip_read(struct ast_channel *ast)
07131 {
07132 struct ast_frame *fr;
07133 struct sip_pvt *p = ast->tech_pvt;
07134 int faxdetected = FALSE;
07135
07136 sip_pvt_lock(p);
07137 fr = sip_rtp_read(ast, p, &faxdetected);
07138 p->lastrtprx = time(NULL);
07139
07140
07141 if (faxdetected && ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_CNG)) {
07142 ast_channel_lock(ast);
07143 if (strcmp(ast->exten, "fax")) {
07144 const char *target_context = S_OR(ast->macrocontext, ast->context);
07145 ast_channel_unlock(ast);
07146 if (ast_exists_extension(ast, target_context, "fax", 1, ast->cid.cid_num)) {
07147 ast_verbose(VERBOSE_PREFIX_2 "Redirecting '%s' to fax extension due to CNG detection\n", ast->name);
07148 pbx_builtin_setvar_helper(ast, "FAXEXTEN", ast->exten);
07149 if (ast_async_goto(ast, target_context, "fax", 1)) {
07150 ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", ast->name, target_context);
07151 }
07152 fr = &ast_null_frame;
07153 } else {
07154 ast_log(LOG_NOTICE, "FAX CNG detected but no fax extension\n");
07155 }
07156 } else {
07157 ast_channel_unlock(ast);
07158 }
07159 }
07160
07161
07162 if (fr && fr->frametype == AST_FRAME_VOICE && p->invitestate != INV_EARLY_MEDIA && ast->_state != AST_STATE_UP) {
07163 fr = &ast_null_frame;
07164 }
07165
07166 sip_pvt_unlock(p);
07167
07168 return fr;
07169 }
07170
07171
07172
07173 static char *generate_random_string(char *buf, size_t size)
07174 {
07175 long val[4];
07176 int x;
07177
07178 for (x=0; x<4; x++)
07179 val[x] = ast_random();
07180 snprintf(buf, size, "%08lx%08lx%08lx%08lx", val[0], val[1], val[2], val[3]);
07181
07182 return buf;
07183 }
07184
07185
07186 static void build_callid_pvt(struct sip_pvt *pvt)
07187 {
07188 char buf[33];
07189
07190 const char *host = S_OR(pvt->fromdomain, ast_inet_ntoa(pvt->ourip.sin_addr));
07191
07192 ast_string_field_build(pvt, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
07193
07194 }
07195
07196
07197 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain)
07198 {
07199 char buf[33];
07200
07201 const char *host = S_OR(fromdomain, ast_inet_ntoa(ourip));
07202
07203 ast_string_field_build(reg, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
07204 }
07205
07206
07207 static void make_our_tag(char *tagbuf, size_t len)
07208 {
07209 snprintf(tagbuf, len, "as%08lx", ast_random());
07210 }
07211
07212
07213 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p)
07214 {
07215 struct sip_st_dlg *stp;
07216
07217 if (p->stimer) {
07218 ast_log(LOG_ERROR, "Session-Timer struct already allocated\n");
07219 return p->stimer;
07220 }
07221
07222 if (!(stp = ast_calloc(1, sizeof(struct sip_st_dlg))))
07223 return NULL;
07224
07225 p->stimer = stp;
07226
07227 stp->st_schedid = -1;
07228
07229 return p->stimer;
07230 }
07231
07232
07233
07234
07235
07236 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
07237 int useglobal_nat, const int intended_method, struct sip_request *req)
07238 {
07239 struct sip_pvt *p;
07240
07241 if (!(p = ao2_t_alloc(sizeof(*p), sip_destroy_fn, "allocate a dialog(pvt) struct")))
07242 return NULL;
07243
07244 if (ast_string_field_init(p, 512)) {
07245 ao2_t_ref(p, -1, "failed to string_field_init, drop p");
07246 return NULL;
07247 }
07248
07249 if (req) {
07250 set_socket_transport(&p->socket, req->socket.type);
07251 } else {
07252 set_socket_transport(&p->socket, SIP_TRANSPORT_UDP);
07253 }
07254
07255 p->socket.fd = -1;
07256 p->method = intended_method;
07257 p->initid = -1;
07258 p->waitid = -1;
07259 p->autokillid = -1;
07260 p->request_queue_sched_id = -1;
07261 p->provisional_keepalive_sched_id = -1;
07262 p->t38id = -1;
07263 p->subscribed = NONE;
07264 p->stateid = -1;
07265 p->sessionversion_remote = -1;
07266 p->session_modify = TRUE;
07267 p->stimer = NULL;
07268 p->prefs = default_prefs;
07269
07270 if (intended_method != SIP_OPTIONS) {
07271 p->timer_t1 = global_t1;
07272 p->timer_b = global_timer_b;
07273 }
07274
07275 if (!sin)
07276 p->ourip = internip;
07277 else {
07278 p->sa = *sin;
07279 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
07280 }
07281
07282
07283 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
07284 ast_copy_flags(&p->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
07285
07286 p->do_history = recordhistory;
07287
07288 p->branch = ast_random();
07289 make_our_tag(p->tag, sizeof(p->tag));
07290 p->ocseq = INITIAL_CSEQ;
07291
07292 if (sip_methods[intended_method].need_rtp) {
07293 p->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
07294
07295 if (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) ||
07296 ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS))
07297 p->vrtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
07298 if (ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT))
07299 p->trtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
07300 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
07301 if (!(p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr))) {
07302
07303 ast_log(LOG_ERROR, "UDPTL creation failed\n");
07304 ast_clear_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT);
07305 }
07306 }
07307 if (!p->rtp|| (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) && !p->vrtp)
07308 || (ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT) && !p->trtp)) {
07309 ast_log(LOG_WARNING, "Unable to create RTP audio %s%ssession: %s\n",
07310 ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "and video " : "",
07311 ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT) ? "and text " : "", strerror(errno));
07312 if (p->chanvars) {
07313 ast_variables_destroy(p->chanvars);
07314 p->chanvars = NULL;
07315 }
07316 ao2_t_ref(p, -1, "failed to create RTP audio session, drop p");
07317 return NULL;
07318 p->t38_maxdatagram = global_t38_maxdatagram;
07319 }
07320 ast_rtp_setqos(p->rtp, global_tos_audio, global_cos_audio, "SIP RTP");
07321 ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
07322 ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
07323 ast_rtp_set_rtptimeout(p->rtp, global_rtptimeout);
07324 ast_rtp_set_rtpholdtimeout(p->rtp, global_rtpholdtimeout);
07325 ast_rtp_set_rtpkeepalive(p->rtp, global_rtpkeepalive);
07326 if (p->vrtp) {
07327 ast_rtp_setqos(p->vrtp, global_tos_video, global_cos_video, "SIP VRTP");
07328 ast_rtp_setdtmf(p->vrtp, 0);
07329 ast_rtp_setdtmfcompensate(p->vrtp, 0);
07330 ast_rtp_set_rtptimeout(p->vrtp, global_rtptimeout);
07331 ast_rtp_set_rtpholdtimeout(p->vrtp, global_rtpholdtimeout);
07332 ast_rtp_set_rtpkeepalive(p->vrtp, global_rtpkeepalive);
07333 }
07334 if (p->trtp) {
07335 ast_rtp_setqos(p->trtp, global_tos_text, global_cos_text, "SIP TRTP");
07336 ast_rtp_setdtmf(p->trtp, 0);
07337 ast_rtp_setdtmfcompensate(p->trtp, 0);
07338 }
07339 if (p->udptl)
07340 ast_udptl_setqos(p->udptl, global_tos_audio, global_cos_audio);
07341 p->maxcallbitrate = default_maxcallbitrate;
07342 p->autoframing = global_autoframing;
07343 ast_rtp_codec_setpref(p->rtp, &p->prefs);
07344 }
07345
07346 if (useglobal_nat && sin) {
07347
07348 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT);
07349 p->recv = *sin;
07350 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
07351 }
07352
07353 if (p->method != SIP_REGISTER)
07354 ast_string_field_set(p, fromdomain, default_fromdomain);
07355 build_via(p);
07356 if (!callid)
07357 build_callid_pvt(p);
07358 else
07359 ast_string_field_set(p, callid, callid);
07360
07361 ast_string_field_set(p, mohinterpret, default_mohinterpret);
07362 ast_string_field_set(p, mohsuggest, default_mohsuggest);
07363 p->capability = global_capability;
07364 p->allowtransfer = sip_cfg.allowtransfer;
07365 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
07366 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
07367 p->noncodeccapability |= AST_RTP_DTMF;
07368 if (p->udptl) {
07369 p->t38_maxdatagram = global_t38_maxdatagram;
07370 set_t38_capabilities(p);
07371 }
07372 ast_string_field_set(p, context, sip_cfg.default_context);
07373 ast_string_field_set(p, parkinglot, default_parkinglot);
07374
07375 AST_LIST_HEAD_INIT_NOLOCK(&p->request_queue);
07376
07377
07378
07379 ao2_t_link(dialogs, p, "link pvt into dialogs table");
07380
07381 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");
07382 return p;
07383 }
07384
07385
07386 struct find_call_cb_arg {
07387 enum sipmethod method;
07388 const char *callid;
07389 const char *fromtag;
07390 const char *totag;
07391 const char *tag;
07392 };
07393
07394
07395
07396
07397
07398 static int find_call_cb(void *__pvt, void *__arg, int flags)
07399 {
07400 struct sip_pvt *p = __pvt;
07401 struct find_call_cb_arg *arg = __arg;
07402
07403 int found = FALSE;
07404
07405 if (!ast_strlen_zero(p->callid)) {
07406 if (arg->method == SIP_REGISTER)
07407 found = (!strcmp(p->callid, arg->callid));
07408 else {
07409 found = !strcmp(p->callid, arg->callid);
07410 if (sip_cfg.pedanticsipchecking && found) {
07411 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);
07412 }
07413 }
07414
07415 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);
07416
07417
07418 if (sip_cfg.pedanticsipchecking && found && arg->method != SIP_RESPONSE) {
07419 if (p->tag[0] == '\0' && arg->totag[0]) {
07420
07421 found = FALSE;
07422 } else if (arg->totag[0]) {
07423 if (strcmp(arg->totag, p->tag)) {
07424 found = FALSE;
07425 }
07426 }
07427 if (!found)
07428 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);
07429 }
07430 }
07431 return found;
07432 }
07433
07434
07435
07436
07437
07438
07439 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method)
07440 {
07441 struct sip_pvt *p = NULL;
07442 char *tag = "";
07443 char totag[128];
07444 char fromtag[128];
07445 struct find_call_cb_arg arg;
07446 const char *callid = get_header(req, "Call-ID");
07447 const char *from = get_header(req, "From");
07448 const char *to = get_header(req, "To");
07449 const char *cseq = get_header(req, "Cseq");
07450 struct sip_pvt *sip_pvt_ptr;
07451
07452
07453
07454 if (ast_strlen_zero(callid) || ast_strlen_zero(to) ||
07455 ast_strlen_zero(from) || ast_strlen_zero(cseq))
07456 return NULL;
07457
07458 arg.method = req->method;
07459 arg.callid = callid;
07460 arg.fromtag = fromtag;
07461 arg.totag = totag;
07462 arg.tag = "";
07463
07464 if (sip_cfg.pedanticsipchecking) {
07465
07466
07467
07468
07469
07470
07471 if (gettag(req, "To", totag, sizeof(totag)))
07472 req->has_to_tag = 1;
07473 gettag(req, "From", fromtag, sizeof(fromtag));
07474
07475 tag = (req->method == SIP_RESPONSE) ? totag : fromtag;
07476
07477 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);
07478
07479
07480 if (ast_strlen_zero(fromtag)) {
07481 ast_debug(5, "%s request has no from tag, dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
07482 return NULL;
07483 }
07484
07485 if (ast_strlen_zero(totag) && (req->method == SIP_ACK || req->method == SIP_BYE || req->method == SIP_INFO )) {
07486 ast_debug(5, "%s must have a to tag. dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
07487 return NULL;
07488 }
07489 }
07490
07491 restartsearch:
07492 if (!sip_cfg.pedanticsipchecking) {
07493 struct sip_pvt tmp_dialog = {
07494 .callid = callid,
07495 };
07496 sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find in dialogs");
07497 if (sip_pvt_ptr) {
07498
07499 sip_pvt_lock(sip_pvt_ptr);
07500 return sip_pvt_ptr;
07501 }
07502 } else {
07503 ao2_lock(dialogs);
07504 p = ao2_t_callback(dialogs, 0 , find_call_cb, &arg, "pedantic linear search for dialog");
07505 if (p) {
07506 if (sip_pvt_trylock(p)) {
07507 ao2_unlock(dialogs);
07508 usleep(1);
07509 goto restartsearch;
07510 }
07511 ao2_unlock(dialogs);
07512 return p;
07513 }
07514 ao2_unlock(dialogs);
07515 }
07516
07517
07518 if (sip_methods[intended_method].can_create == CAN_CREATE_DIALOG) {
07519 if (intended_method == SIP_REFER) {
07520
07521 transmit_response_using_temp(callid, sin, 1, intended_method, req, "603 Declined (no dialog)");
07522 } else if (intended_method == SIP_NOTIFY) {
07523
07524
07525 transmit_response_using_temp(callid, sin, 1, intended_method, req, "489 Bad event");
07526 } else {
07527
07528 if ((p = sip_alloc(callid, sin, 1, intended_method, req))) {
07529
07530 sip_pvt_lock(p);
07531 } else {
07532
07533
07534
07535
07536
07537
07538
07539
07540 transmit_response_using_temp(callid, sin, 1, intended_method, req, "500 Server internal error");
07541 ast_debug(4, "Failed allocating SIP dialog, sending 500 Server internal error and giving up\n");
07542 }
07543 }
07544 return p;
07545 } else if( sip_methods[intended_method].can_create == CAN_CREATE_DIALOG_UNSUPPORTED_METHOD) {
07546
07547 transmit_response_using_temp(callid, sin, 1, intended_method, req, "501 Method Not Implemented");
07548 ast_debug(2, "Got a request with unsupported SIP method.\n");
07549 } else if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
07550
07551 transmit_response_using_temp(callid, sin, 1, intended_method, req, "481 Call leg/transaction does not exist");
07552 ast_debug(2, "That's odd... Got a request in unknown dialog. Callid %s\n", callid ? callid : "<unknown>");
07553 }
07554
07555
07556 if (intended_method == SIP_RESPONSE)
07557 ast_debug(2, "That's odd... Got a response on a call we don't know about. Callid %s\n", callid ? callid : "<unknown>");
07558
07559 return NULL;
07560 }
07561
07562
07563 static int sip_register(const char *value, int lineno)
07564 {
07565 struct sip_registry *reg;
07566 int portnum = 0;
07567 enum sip_transport transport = SIP_TRANSPORT_UDP;
07568 char buf[256] = "";
07569 char *userpart = NULL, *hostpart = NULL;
07570
07571 AST_DECLARE_APP_ARGS(pre1,
07572 AST_APP_ARG(peer);
07573 AST_APP_ARG(userpart);
07574 );
07575 AST_DECLARE_APP_ARGS(pre2,
07576 AST_APP_ARG(transport);
07577 AST_APP_ARG(blank);
07578 AST_APP_ARG(userpart);
07579 );
07580 AST_DECLARE_APP_ARGS(user1,
07581 AST_APP_ARG(userpart);
07582 AST_APP_ARG(secret);
07583 AST_APP_ARG(authuser);
07584 );
07585 AST_DECLARE_APP_ARGS(host1,
07586 AST_APP_ARG(hostpart);
07587 AST_APP_ARG(expiry);
07588 );
07589 AST_DECLARE_APP_ARGS(host2,
07590 AST_APP_ARG(hostpart);
07591 AST_APP_ARG(extension);
07592 );
07593 AST_DECLARE_APP_ARGS(host3,
07594 AST_APP_ARG(host);
07595 AST_APP_ARG(port);
07596 );
07597
07598 if (!value)
07599 return -1;
07600 ast_copy_string(buf, value, sizeof(buf));
07601
07602
07603
07604
07605
07606
07607 if ((hostpart = strrchr(buf, '@'))) {
07608 *hostpart++ = '\0';
07609 userpart = buf;
07610 }
07611
07612 if (ast_strlen_zero(userpart) || ast_strlen_zero(hostpart)) {
07613 ast_log(LOG_WARNING, "Format for registration is [peer?][transport://]user[@domain][:secret[:authuser]]@host[:port][/extension][~expiry] at line %d\n", lineno);
07614 return -1;
07615 }
07616
07617
07618
07619
07620
07621
07622 AST_NONSTANDARD_RAW_ARGS(pre1, userpart, '?');
07623 if (ast_strlen_zero(pre1.userpart)) {
07624 pre1.userpart = pre1.peer;
07625 pre1.peer = NULL;
07626 }
07627
07628
07629
07630
07631
07632
07633
07634 AST_NONSTANDARD_RAW_ARGS(pre2, pre1.userpart, '/');
07635 if (ast_strlen_zero(pre2.userpart)) {
07636 pre2.userpart = pre2.transport;
07637 pre2.transport = NULL;
07638 } else {
07639 pre2.transport[strlen(pre2.transport) - 1] = '\0';
07640 }
07641
07642 if (!ast_strlen_zero(pre2.blank)) {
07643 ast_log(LOG_WARNING, "Format for registration is [peer?][transport://]user[@domain][:secret[:authuser]]@host[:port][/extension][~expiry] at line %d\n", lineno);
07644 return -1;
07645 }
07646
07647
07648
07649
07650
07651
07652
07653
07654
07655 AST_NONSTANDARD_RAW_ARGS(user1, pre2.userpart, ':');
07656
07657
07658
07659
07660
07661
07662
07663
07664
07665
07666 AST_NONSTANDARD_RAW_ARGS(host1, hostpart, '~');
07667
07668
07669
07670
07671
07672
07673
07674
07675
07676
07677
07678 AST_NONSTANDARD_RAW_ARGS(host2, host1.hostpart, '/');
07679
07680
07681
07682
07683
07684
07685
07686
07687
07688
07689
07690
07691 AST_NONSTANDARD_RAW_ARGS(host3, host2.hostpart, ':');
07692
07693 if (host3.port) {
07694 if (!(portnum = port_str2int(host3.port, 0))) {
07695 ast_log(LOG_NOTICE, "'%s' is not a valid port number on line %d of sip.conf. using default.\n", host3.port, lineno);
07696 }
07697 }
07698
07699
07700 if (!pre2.transport) {
07701 transport = SIP_TRANSPORT_UDP;
07702 } else if (!strncasecmp(pre2.transport, "tcp", 3)) {
07703 transport = SIP_TRANSPORT_TCP;
07704 } else if (!strncasecmp(pre2.transport, "tls", 3)) {
07705 transport = SIP_TRANSPORT_TLS;
07706 } else if (!strncasecmp(pre2.transport, "udp", 3)) {
07707 transport = SIP_TRANSPORT_UDP;
07708 } else {
07709 transport = SIP_TRANSPORT_UDP;
07710 ast_log(LOG_NOTICE, "'%.3s' is not a valid transport type on line %d of sip.conf. defaulting to udp.\n", pre2.transport, lineno);
07711 }
07712
07713
07714 if (!portnum) {
07715 if (transport == SIP_TRANSPORT_TLS) {
07716 portnum = STANDARD_TLS_PORT;
07717 } else {
07718 portnum = STANDARD_SIP_PORT;
07719 }
07720 }
07721
07722 if (!(reg = ast_calloc(1, sizeof(*reg)))) {
07723 ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry entry\n");
07724 return -1;
07725 }
07726
07727 if (ast_string_field_init(reg, 256)) {
07728 ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry strings\n");
07729 ast_free(reg);
07730 return -1;
07731 }
07732
07733 ast_atomic_fetchadd_int(®objs, 1);
07734 ASTOBJ_INIT(reg);
07735 ast_string_field_set(reg, callback, ast_strip_quoted(S_OR(host2.extension, "s"), "\"", "\""));
07736 ast_string_field_set(reg, username, ast_strip_quoted(S_OR(user1.userpart, ""), "\"", "\""));
07737 ast_string_field_set(reg, hostname, ast_strip_quoted(S_OR(host3.host, ""), "\"", "\""));
07738 ast_string_field_set(reg, authuser, ast_strip_quoted(S_OR(user1.authuser, ""), "\"", "\""));
07739 ast_string_field_set(reg, secret, ast_strip_quoted(S_OR(user1.secret, ""), "\"", "\""));
07740 ast_string_field_set(reg, peername, ast_strip_quoted(S_OR(pre1.peer, ""), "\"", "\""));
07741
07742 reg->transport = transport;
07743 reg->timeout = reg->expire = -1;
07744 reg->refresh = reg->expiry = reg->configured_expiry = (host1.expiry ? atoi(ast_strip_quoted(host1.expiry, "\"", "\"")) : default_expiry);
07745 reg->portno = portnum;
07746 reg->callid_valid = FALSE;
07747 reg->ocseq = INITIAL_CSEQ;
07748 ASTOBJ_CONTAINER_LINK(®l, reg);
07749 registry_unref(reg, "unref the reg pointer");
07750 return 0;
07751 }
07752
07753
07754 static int sip_subscribe_mwi(const char *value, int lineno)
07755 {
07756 struct sip_subscription_mwi *mwi;
07757 int portnum = 0;
07758 enum sip_transport transport = SIP_TRANSPORT_UDP;
07759 char buf[256] = "";
07760 char *username = NULL, *hostname = NULL, *secret = NULL, *authuser = NULL, *porta = NULL, *mailbox = NULL;
07761
07762 if (!value) {
07763 return -1;
07764 }
07765
07766 ast_copy_string(buf, value, sizeof(buf));
07767
07768 sip_parse_host(buf, lineno, &username, &portnum, &transport);
07769
07770 if ((hostname = strrchr(username, '@'))) {
07771 *hostname++ = '\0';
07772 }
07773
07774 if ((secret = strchr(username, ':'))) {
07775 *secret++ = '\0';
07776 if ((authuser = strchr(secret, ':'))) {
07777 *authuser++ = '\0';
07778 }
07779 }
07780
07781 if ((mailbox = strchr(hostname, '/'))) {
07782 *mailbox++ = '\0';
07783 }
07784
07785 if (ast_strlen_zero(username) || ast_strlen_zero(hostname) || ast_strlen_zero(mailbox)) {
07786 ast_log(LOG_WARNING, "Format for MWI subscription is user[:secret[:authuser]]@host[:port][/mailbox] at line %d\n", lineno);
07787 return -1;
07788 }
07789
07790 if ((porta = strchr(hostname, ':'))) {
07791 *porta++ = '\0';
07792 if (!(portnum = atoi(porta))) {
07793 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
07794 return -1;
07795 }
07796 }
07797
07798 if (!(mwi = ast_calloc(1, sizeof(*mwi)))) {
07799 return -1;
07800 }
07801
07802 if (ast_string_field_init(mwi, 256)) {
07803 ast_free(mwi);
07804 return -1;
07805 }
07806
07807 ASTOBJ_INIT(mwi);
07808 ast_string_field_set(mwi, username, username);
07809 if (secret) {
07810 ast_string_field_set(mwi, secret, secret);
07811 }
07812 if (authuser) {
07813 ast_string_field_set(mwi, authuser, authuser);
07814 }
07815 ast_string_field_set(mwi, hostname, hostname);
07816 ast_string_field_set(mwi, mailbox, mailbox);
07817 mwi->resub = -1;
07818 mwi->portno = portnum;
07819 mwi->transport = transport;
07820
07821 ASTOBJ_CONTAINER_LINK(&submwil, mwi);
07822 ASTOBJ_UNREF(mwi, sip_subscribe_mwi_destroy);
07823
07824 return 0;
07825 }
07826
07827
07828
07829 static int lws2sws(char *msgbuf, int len)
07830 {
07831 int h = 0, t = 0;
07832 int lws = 0;
07833
07834 for (; h < len;) {
07835
07836 if (msgbuf[h] == '\r') {
07837 h++;
07838 continue;
07839 }
07840
07841 if (msgbuf[h] == '\n') {
07842
07843 if (h + 1 == len)
07844 break;
07845
07846 if (msgbuf[h + 1] == ' ' || msgbuf[h + 1] == '\t') {
07847
07848 h++;
07849 continue;
07850 }
07851
07852 msgbuf[t++] = msgbuf[h++];
07853 lws = 0;
07854 continue;
07855 }
07856 if (msgbuf[h] == ' ' || msgbuf[h] == '\t') {
07857 if (lws) {
07858 h++;
07859 continue;
07860 }
07861 msgbuf[t++] = msgbuf[h++];
07862 lws = 1;
07863 continue;
07864 }
07865 msgbuf[t++] = msgbuf[h++];
07866 if (lws)
07867 lws = 0;
07868 }
07869 msgbuf[t] = '\0';
07870 return t;
07871 }
07872
07873
07874
07875
07876 static int parse_request(struct sip_request *req)
07877 {
07878 char *c = req->data->str;
07879 ptrdiff_t *dst = req->header;
07880 int i = 0, lim = SIP_MAX_HEADERS - 1;
07881 unsigned int skipping_headers = 0;
07882 ptrdiff_t current_header_offset = 0;
07883 char *previous_header = "";
07884
07885 req->header[0] = 0;
07886 req->headers = -1;
07887 for (; *c; c++) {
07888 if (*c == '\r') {
07889 *c = '\0';
07890 } else if (*c == '\n') {
07891 *c = '\0';
07892 current_header_offset = (c + 1) - req->data->str;
07893 previous_header = req->data->str + dst[i];
07894 if (skipping_headers) {
07895
07896
07897
07898 if (ast_strlen_zero(previous_header)) {
07899 skipping_headers = 0;
07900 }
07901 dst[i] = current_header_offset;
07902 continue;
07903 }
07904 if (sipdebug) {
07905 ast_debug(4, "%7s %2d [%3d]: %s\n",
07906 req->headers < 0 ? "Header" : "Body",
07907 i, (int) strlen(previous_header), previous_header);
07908 }
07909 if (ast_strlen_zero(previous_header) && req->headers < 0) {
07910 req->headers = i;
07911 dst = req->line;
07912 i = 0;
07913 lim = SIP_MAX_LINES - 1;
07914 } else {
07915 if (i++ == lim) {
07916
07917
07918
07919 if (req->headers != -1) {
07920 break;
07921 } else {
07922 req->headers = i;
07923 dst = req->line;
07924 i = 0;
07925 lim = SIP_MAX_LINES - 1;
07926 skipping_headers = 1;
07927 }
07928 }
07929 }
07930 dst[i] = current_header_offset;
07931 }
07932 }
07933
07934
07935
07936
07937
07938
07939 previous_header = req->data->str + dst[i];
07940 if ((i < lim) && !ast_strlen_zero(previous_header)) {
07941 if (sipdebug) {
07942 ast_debug(4, "%7s %2d [%3d]: %s\n",
07943 req->headers < 0 ? "Header" : "Body",
07944 i, (int) strlen(previous_header), previous_header );
07945 }
07946 i++;
07947 }
07948
07949
07950 if (req->headers >= 0) {
07951 req->lines = i;
07952 } else {
07953 req->headers = i;
07954 req->lines = 0;
07955
07956 req->line[0] = ast_str_strlen(req->data);
07957 }
07958
07959 if (*c) {
07960 ast_log(LOG_WARNING, "Too many lines, skipping <%s>\n", c);
07961 }
07962
07963
07964 return determine_firstline_parts(req);
07965 }
07966
07967
07968
07969
07970
07971
07972
07973
07974
07975 static int find_sdp(struct sip_request *req)
07976 {
07977 const char *content_type;
07978 const char *content_length;
07979 const char *search;
07980 char *boundary;
07981 unsigned int x;
07982 int boundaryisquoted = FALSE;
07983 int found_application_sdp = FALSE;
07984 int found_end_of_headers = FALSE;
07985
07986 content_length = get_header(req, "Content-Length");
07987
07988 if (!ast_strlen_zero(content_length)) {
07989 if (sscanf(content_length, "%30u", &x) != 1) {
07990 ast_log(LOG_WARNING, "Invalid Content-Length: %s\n", content_length);
07991 return 0;
07992 }
07993
07994
07995
07996 if (x == 0)
07997 return 0;
07998 }
07999
08000 content_type = get_header(req, "Content-Type");
08001
08002
08003 if (!strncasecmp(content_type, "application/sdp", 15)) {
08004 req->sdp_start = 0;
08005 req->sdp_count = req->lines;
08006 return req->lines ? 1 : 0;
08007 }
08008
08009
08010 if (strncasecmp(content_type, "multipart/mixed", 15))
08011 return 0;
08012
08013
08014 if ((search = strcasestr(content_type, ";boundary=")))
08015 search += 10;
08016 else if ((search = strcasestr(content_type, "; boundary=")))
08017 search += 11;
08018 else
08019 return 0;
08020
08021 if (ast_strlen_zero(search))
08022 return 0;
08023
08024
08025 if (*search == '\"') {
08026 search++;
08027 boundaryisquoted = TRUE;
08028 }
08029
08030
08031
08032 boundary = ast_strdupa(search - 2);
08033 boundary[0] = boundary[1] = '-';
08034
08035 if (boundaryisquoted)
08036 boundary[strlen(boundary) - 1] = '\0';
08037
08038
08039
08040
08041 for (x = 0; x < (req->lines); x++) {
08042 char *line = REQ_OFFSET_TO_STR(req, line[x]);
08043 if (!strncasecmp(line, boundary, strlen(boundary))){
08044 if (found_application_sdp && found_end_of_headers) {
08045 req->sdp_count = (x - 1) - req->sdp_start;
08046 return 1;
08047 }
08048 found_application_sdp = FALSE;
08049 }
08050 if (!strcasecmp(line, "Content-Type: application/sdp"))
08051 found_application_sdp = TRUE;
08052
08053 if (ast_strlen_zero(line)) {
08054 if (found_application_sdp && !found_end_of_headers){
08055 req->sdp_start = x;
08056 found_end_of_headers = TRUE;
08057 }
08058 }
08059 }
08060 if (found_application_sdp && found_end_of_headers) {
08061 req->sdp_count = x - req->sdp_start;
08062 return TRUE;
08063 }
08064 return FALSE;
08065 }
08066
08067 enum media_type {
08068 SDP_AUDIO,
08069 SDP_VIDEO,
08070 SDP_IMAGE,
08071 SDP_TEXT,
08072 };
08073
08074 static int get_ip_and_port_from_sdp(struct sip_request *req, const enum media_type media, struct sockaddr_in *sin)
08075 {
08076 const char *m;
08077 const char *c;
08078 int miterator = req->sdp_start;
08079 int citerator = req->sdp_start;
08080 int x = 0;
08081 int numberofports;
08082 int len;
08083 char host[258] = "";
08084 struct ast_hostent audiohp;
08085 struct hostent *hp;
08086
08087 c = get_sdp_iterate(&citerator, req, "c");
08088 if (sscanf(c, "IN IP4 %256s", host) != 1) {
08089 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
08090
08091 }
08092
08093 for (m = get_sdp_iterate(&miterator, req, "m"); !ast_strlen_zero(m); m = get_sdp_iterate(&miterator, req, "m")) {
08094 if ((media == SDP_AUDIO && ((sscanf(m, "audio %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08095 (sscanf(m, "audio %30u RTP/AVP %n", &x, &len) == 1 && len > 0))) ||
08096 (media == SDP_VIDEO && ((sscanf(m, "video %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08097 (sscanf(m, "video %30u RTP/AVP %n", &x, &len) == 1 && len > 0)))) {
08098
08099
08100
08101
08102 c = get_sdp_iterate(&citerator, req, "c");
08103 if (!ast_strlen_zero(c)) {
08104 sscanf(c, "IN IP4 %256s", host);
08105 }
08106 break;
08107 }
08108 }
08109
08110 if (ast_strlen_zero(host) || x == 0) {
08111 ast_log(LOG_WARNING, "Failed to read an alternate host or port in SDP. Expect %s problems\n", media == SDP_AUDIO ? "audio" : "video");
08112 return -1;
08113 }
08114
08115 hp = ast_gethostbyname(host, &audiohp);
08116 if (!hp) {
08117 ast_log(LOG_WARNING, "Could not look up IP address of alternate hostname. Expect %s problems\n", media == SDP_AUDIO? "audio" : "video");
08118 return -1;
08119 }
08120
08121 memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
08122 sin->sin_port = htons(x);
08123 return 0;
08124 }
08125
08126
08127
08128
08129
08130
08131 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action)
08132 {
08133
08134 int start = req->sdp_start;
08135 int next = start;
08136 int iterator = start;
08137
08138
08139 char type = '\0';
08140 const char *value = NULL;
08141 const char *m = NULL;
08142 const char *nextm = NULL;
08143 int len = -1;
08144
08145
08146 struct ast_hostent sessionhp;
08147 struct ast_hostent audiohp;
08148 struct ast_hostent videohp;
08149 struct ast_hostent texthp;
08150 struct ast_hostent imagehp;
08151 struct hostent *hp = NULL;
08152 struct hostent *vhp = NULL;
08153 struct hostent *thp = NULL;
08154 struct hostent *ihp = NULL;
08155 int portno = -1;
08156 int vportno = -1;
08157 int tportno = -1;
08158 int udptlportno = -1;
08159 struct sockaddr_in sin = { 0, };
08160 struct sockaddr_in vsin = { 0, };
08161 struct sockaddr_in isin = { 0, };
08162 struct sockaddr_in tsin = { 0, };
08163
08164
08165 int peercapability = 0, peernoncodeccapability = 0;
08166 int vpeercapability = 0, vpeernoncodeccapability = 0;
08167 int tpeercapability = 0, tpeernoncodeccapability = 0;
08168
08169 struct ast_rtp *newaudiortp, *newvideortp, *newtextrtp;
08170 int newjointcapability;
08171 int newpeercapability;
08172 int newnoncodeccapability;
08173
08174 const char *codecs;
08175 int codec;
08176
08177
08178 int sendonly = -1;
08179 int vsendonly = -1;
08180 int numberofports;
08181 int numberofmediastreams = 0;
08182 int last_rtpmap_codec = 0;
08183 int red_data_pt[10];
08184 int red_num_gen = 0;
08185 char red_fmtp[100] = "empty";
08186 int debug = sip_debug_test_pvt(p);
08187
08188
08189 char buf[SIPBUFSIZE];
08190
08191
08192
08193 if (!p->rtp) {
08194 ast_log(LOG_ERROR, "Got SDP but have no RTP session allocated.\n");
08195 return -1;
08196 }
08197
08198
08199 #ifdef LOW_MEMORY
08200 newaudiortp = ast_threadstorage_get(&ts_audio_rtp, ast_rtp_alloc_size());
08201 #else
08202 newaudiortp = alloca(ast_rtp_alloc_size());
08203 #endif
08204 memset(newaudiortp, 0, ast_rtp_alloc_size());
08205 ast_rtp_new_init(newaudiortp);
08206 ast_rtp_pt_clear(newaudiortp);
08207
08208 #ifdef LOW_MEMORY
08209 newvideortp = ast_threadstorage_get(&ts_video_rtp, ast_rtp_alloc_size());
08210 #else
08211 newvideortp = alloca(ast_rtp_alloc_size());
08212 #endif
08213 memset(newvideortp, 0, ast_rtp_alloc_size());
08214 ast_rtp_new_init(newvideortp);
08215 ast_rtp_pt_clear(newvideortp);
08216
08217 #ifdef LOW_MEMORY
08218 newtextrtp = ast_threadstorage_get(&ts_text_rtp, ast_rtp_alloc_size());
08219 #else
08220 newtextrtp = alloca(ast_rtp_alloc_size());
08221 #endif
08222 memset(newtextrtp, 0, ast_rtp_alloc_size());
08223 ast_rtp_new_init(newtextrtp);
08224 ast_rtp_pt_clear(newtextrtp);
08225
08226
08227 p->lastrtprx = p->lastrtptx = time(NULL);
08228
08229 memset(p->offered_media, 0, sizeof(p->offered_media));
08230
08231
08232
08233 p->novideo = TRUE;
08234 p->notext = TRUE;
08235
08236 if (p->vrtp)
08237 ast_rtp_pt_clear(newvideortp);
08238
08239 if (p->trtp)
08240 ast_rtp_pt_clear(newtextrtp);
08241
08242
08243 nextm = get_sdp_iterate(&next, req, "m");
08244 if (ast_strlen_zero(nextm)) {
08245 ast_log(LOG_WARNING, "Insufficient information for SDP (m= not found)\n");
08246 return -1;
08247 }
08248
08249
08250 while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
08251 int processed = FALSE;
08252 switch (type) {
08253 case 'o':
08254
08255
08256
08257 if (!process_sdp_o(value, p))
08258 return (p->session_modify == FALSE) ? 0 : -1;
08259 break;
08260 case 'c':
08261 if (process_sdp_c(value, &sessionhp)) {
08262 processed = TRUE;
08263 hp = &sessionhp.hp;
08264 vhp = hp;
08265 thp = hp;
08266 ihp = hp;
08267 }
08268 break;
08269 case 'a':
08270 if (process_sdp_a_sendonly(value, &sendonly)) {
08271 processed = TRUE;
08272 vsendonly = sendonly;
08273 }
08274 else if (process_sdp_a_audio(value, p, newaudiortp, &last_rtpmap_codec))
08275 processed = TRUE;
08276 else if (process_sdp_a_video(value, p, newvideortp, &last_rtpmap_codec))
08277 processed = TRUE;
08278 else if (process_sdp_a_text(value, p, newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec))
08279 processed = TRUE;
08280 else if (process_sdp_a_image(value, p))
08281 processed = TRUE;
08282 break;
08283 }
08284
08285 if (option_debug > 2)
08286 ast_log(LOG_DEBUG, "Processing session-level SDP %c=%s... %s\n", type, value, (processed == TRUE)? "OK." : "UNSUPPORTED.");
08287 }
08288
08289
08290
08291
08292 while (!ast_strlen_zero(nextm)) {
08293 int audio = FALSE;
08294 int video = FALSE;
08295 int image = FALSE;
08296 int text = FALSE;
08297 int x;
08298
08299 numberofports = 1;
08300 len = -1;
08301 start = next;
08302 m = nextm;
08303 iterator = next;
08304 nextm = get_sdp_iterate(&next, req, "m");
08305
08306
08307 if ((sscanf(m, "audio %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08308 (sscanf(m, "audio %30u RTP/AVP %n", &x, &len) == 1 && len > 0)) {
08309 audio = TRUE;
08310 p->offered_media[SDP_AUDIO].offered = TRUE;
08311 numberofmediastreams++;
08312 portno = x;
08313
08314
08315 codecs = m + len;
08316 ast_copy_string(p->offered_media[SDP_AUDIO].text, codecs, sizeof(p->offered_media[SDP_AUDIO].text));
08317 for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
08318 if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
08319 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
08320 return -1;
08321 }
08322 if (debug)
08323 ast_verbose("Found RTP audio format %d\n", codec);
08324
08325 ast_rtp_set_m_type(newaudiortp, codec);
08326 }
08327
08328 } else if ((sscanf(m, "video %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08329 (sscanf(m, "video %30u RTP/AVP %n", &x, &len) == 1 && len >= 0)) {
08330 video = TRUE;
08331 p->novideo = FALSE;
08332 p->offered_media[SDP_VIDEO].offered = TRUE;
08333 numberofmediastreams++;
08334 vportno = x;
08335
08336
08337 codecs = m + len;
08338 ast_copy_string(p->offered_media[SDP_VIDEO].text, codecs, sizeof(p->offered_media[SDP_VIDEO].text));
08339 for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
08340 if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
08341 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
08342 return -1;
08343 }
08344 if (debug)
08345 ast_verbose("Found RTP video format %d\n", codec);
08346 ast_rtp_set_m_type(newvideortp, codec);
08347 }
08348
08349 } else if ((sscanf(m, "text %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08350 (sscanf(m, "text %30u RTP/AVP %n", &x, &len) == 1 && len > 0)) {
08351 text = TRUE;
08352 p->notext = FALSE;
08353 p->offered_media[SDP_TEXT].offered = TRUE;
08354 numberofmediastreams++;
08355 tportno = x;
08356
08357
08358 codecs = m + len;
08359 ast_copy_string(p->offered_media[SDP_TEXT].text, codecs, sizeof(p->offered_media[SDP_TEXT].text));
08360 for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
08361 if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
08362 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
08363 return -1;
08364 }
08365 if (debug)
08366 ast_verbose("Found RTP text format %d\n", codec);
08367 ast_rtp_set_m_type(newtextrtp, codec);
08368 }
08369
08370 } else if (p->udptl && ((sscanf(m, "image %30u udptl t38%n", &x, &len) == 1 && len > 0) ||
08371 (sscanf(m, "image %30u UDPTL t38%n", &x, &len) == 1 && len > 0) )) {
08372 image = TRUE;
08373 if (debug)
08374 ast_verbose("Got T.38 offer in SDP in dialog %s\n", p->callid);
08375 p->offered_media[SDP_IMAGE].offered = TRUE;
08376 udptlportno = x;
08377 numberofmediastreams++;
08378
08379 if (p->t38.state != T38_ENABLED) {
08380 memset(&p->t38.their_parms, 0, sizeof(p->t38.their_parms));
08381
08382
08383
08384 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
08385 }
08386 } else {
08387 ast_log(LOG_WARNING, "Unsupported SDP media type in offer: %s\n", m);
08388 continue;
08389 }
08390
08391
08392 if (numberofports > 1)
08393 ast_log(LOG_WARNING, "SDP offered %d ports for media, not supported by Asterisk. Will try anyway...\n", numberofports);
08394
08395
08396
08397
08398 while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
08399 int processed = FALSE;
08400
08401 switch (type) {
08402 case 'c':
08403 if (audio) {
08404 if (process_sdp_c(value, &audiohp)) {
08405 processed = TRUE;
08406 hp = &audiohp.hp;
08407 }
08408 } else if (video) {
08409 if (process_sdp_c(value, &videohp)) {
08410 processed = TRUE;
08411 vhp = &videohp.hp;
08412 }
08413 } else if (text) {
08414 if (process_sdp_c(value, &texthp)) {
08415 processed = TRUE;
08416 thp = &texthp.hp;
08417 }
08418 } else if (image) {
08419 if (process_sdp_c(value, &imagehp)) {
08420 processed = TRUE;
08421 ihp = &imagehp.hp;
08422 }
08423 }
08424 break;
08425 case 'a':
08426
08427 if (audio) {
08428 if (process_sdp_a_sendonly(value, &sendonly))
08429 processed = TRUE;
08430 else if (process_sdp_a_audio(value, p, newaudiortp, &last_rtpmap_codec))
08431 processed = TRUE;
08432 }
08433
08434 else if (video) {
08435 if (process_sdp_a_sendonly(value, &vsendonly))
08436 processed = TRUE;
08437 else if (process_sdp_a_video(value, p, newvideortp, &last_rtpmap_codec))
08438 processed = TRUE;
08439 }
08440
08441 else if (text) {
08442 if (process_sdp_a_text(value, p, newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec))
08443 processed = TRUE;
08444 }
08445
08446 else if (image) {
08447 if (process_sdp_a_image(value, p))
08448 processed = TRUE;
08449 }
08450 break;
08451 }
08452
08453 if (option_debug > 2)
08454 ast_log(LOG_DEBUG, "Processing media-level (%s) SDP %c=%s... %s\n",
08455 (audio == TRUE)? "audio" : (video == TRUE)? "video" : "image",
08456 type, value,
08457 (processed == TRUE)? "OK." : "UNSUPPORTED.");
08458 }
08459 }
08460
08461
08462
08463 if (!hp && !vhp && !thp && !ihp) {
08464 ast_log(LOG_WARNING, "Insufficient information in SDP (c=)...\n");
08465 return -1;
08466 }
08467
08468 if (portno == -1 && vportno == -1 && udptlportno == -1 && tportno == -1)
08469
08470
08471 return -2;
08472
08473 if (numberofmediastreams > 3)
08474
08475 return -3;
08476
08477 if (udptlportno == -1) {
08478 change_t38_state(p, T38_DISABLED);
08479 }
08480
08481
08482
08483 ast_rtp_get_current_formats(newaudiortp, &peercapability, &peernoncodeccapability);
08484 ast_rtp_get_current_formats(newvideortp, &vpeercapability, &vpeernoncodeccapability);
08485 ast_rtp_get_current_formats(newtextrtp, &tpeercapability, &tpeernoncodeccapability);
08486
08487 newjointcapability = p->capability & (peercapability | vpeercapability | tpeercapability);
08488 newpeercapability = (peercapability | vpeercapability | tpeercapability);
08489 newnoncodeccapability = p->noncodeccapability & peernoncodeccapability;
08490
08491 if (debug) {
08492
08493 char s1[SIPBUFSIZE], s2[SIPBUFSIZE], s3[SIPBUFSIZE], s4[SIPBUFSIZE], s5[SIPBUFSIZE];
08494
08495 ast_verbose("Capabilities: us - %s, peer - audio=%s/video=%s/text=%s, combined - %s\n",
08496 ast_getformatname_multiple(s1, SIPBUFSIZE, p->capability),
08497 ast_getformatname_multiple(s2, SIPBUFSIZE, peercapability),
08498 ast_getformatname_multiple(s3, SIPBUFSIZE, vpeercapability),
08499 ast_getformatname_multiple(s4, SIPBUFSIZE, tpeercapability),
08500 ast_getformatname_multiple(s5, SIPBUFSIZE, newjointcapability));
08501
08502 ast_verbose("Non-codec capabilities (dtmf): us - %s, peer - %s, combined - %s\n",
08503 ast_rtp_lookup_mime_multiple(s1, SIPBUFSIZE, p->noncodeccapability, 0, 0),
08504 ast_rtp_lookup_mime_multiple(s2, SIPBUFSIZE, peernoncodeccapability, 0, 0),
08505 ast_rtp_lookup_mime_multiple(s3, SIPBUFSIZE, newnoncodeccapability, 0, 0));
08506 }
08507 if (!newjointcapability && (portno != -1)) {
08508 ast_log(LOG_NOTICE, "No compatible codecs, not accepting this offer!\n");
08509
08510 return -1;
08511 }
08512
08513
08514 if (p->rtp) {
08515 if (portno > 0) {
08516 sin.sin_family = AF_INET;
08517 sin.sin_port = htons(portno);
08518 memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
08519 ast_rtp_set_peer(p->rtp, &sin);
08520 if (debug)
08521 ast_verbose("Peer audio RTP is at port %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
08522
08523
08524 p->jointcapability = newjointcapability;
08525 p->peercapability = newpeercapability;
08526 p->jointnoncodeccapability = newnoncodeccapability;
08527
08528 ast_rtp_pt_copy(p->rtp, newaudiortp);
08529
08530 if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) {
08531 ast_clear_flag(&p->flags[0], SIP_DTMF);
08532 if (newnoncodeccapability & AST_RTP_DTMF) {
08533
08534 ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
08535
08536 ast_rtp_setdtmf(p->rtp, 1);
08537 ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
08538 } else {
08539 ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
08540 }
08541 }
08542 } else if (udptlportno > 0) {
08543 if (debug)
08544 ast_verbose("Got T.38 Re-invite without audio. Keeping RTP active during T.38 session.\n");
08545 } else {
08546 ast_rtp_stop(p->rtp);
08547 if (debug)
08548 ast_verbose("Peer doesn't provide audio\n");
08549 }
08550 }
08551
08552
08553 if (p->vrtp) {
08554 if (vportno > 0) {
08555 vsin.sin_family = AF_INET;
08556 vsin.sin_port = htons(vportno);
08557 memcpy(&vsin.sin_addr, vhp->h_addr, sizeof(vsin.sin_addr));
08558 ast_rtp_set_peer(p->vrtp, &vsin);
08559 if (debug)
08560 ast_verbose("Peer video RTP is at port %s:%d\n", ast_inet_ntoa(vsin.sin_addr), ntohs(vsin.sin_port));
08561 ast_rtp_pt_copy(p->vrtp, newvideortp);
08562 } else {
08563 ast_rtp_stop(p->vrtp);
08564 if (debug)
08565 ast_verbose("Peer doesn't provide video\n");
08566 }
08567 }
08568
08569
08570 if (p->trtp) {
08571 if (tportno > 0) {
08572 tsin.sin_family = AF_INET;
08573 tsin.sin_port = htons(tportno);
08574 memcpy(&tsin.sin_addr, thp->h_addr, sizeof(tsin.sin_addr));
08575 ast_rtp_set_peer(p->trtp, &tsin);
08576 if (debug)
08577 ast_verbose("Peer T.140 RTP is at port %s:%d\n", ast_inet_ntoa(tsin.sin_addr), ntohs(tsin.sin_port));
08578 if ((p->jointcapability & AST_FORMAT_T140RED)) {
08579 p->red = 1;
08580 rtp_red_init(p->trtp, 300, red_data_pt, 2);
08581 } else {
08582 p->red = 0;
08583 }
08584 ast_rtp_pt_copy(p->trtp, newtextrtp);
08585 } else {
08586 ast_rtp_stop(p->trtp);
08587 if (debug)
08588 ast_verbose("Peer doesn't provide T.140\n");
08589 }
08590 }
08591
08592 if (p->udptl) {
08593 if (udptlportno > 0) {
08594 isin.sin_family = AF_INET;
08595 isin.sin_port = htons(udptlportno);
08596 if (ast_test_flag(&p->flags[0], SIP_NAT) && ast_test_flag(&p->flags[1], SIP_PAGE2_UDPTL_DESTINATION)) {
08597 struct sockaddr_in remote_address = { 0, };
08598 ast_rtp_get_peer(p->rtp, &remote_address);
08599 if (remote_address.sin_addr.s_addr) {
08600 memcpy(&isin, &remote_address, sizeof(isin));
08601 if (debug) {
08602 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));
08603 }
08604 }
08605 } else {
08606 memcpy(&isin.sin_addr, ihp->h_addr, sizeof(isin.sin_addr));
08607 }
08608 ast_udptl_set_peer(p->udptl, &isin);
08609 if (debug)
08610 ast_debug(1,"Peer T.38 UDPTL is at port %s:%d\n", ast_inet_ntoa(isin.sin_addr), ntohs(isin.sin_port));
08611
08612
08613 if (!ast_udptl_get_far_max_datagram(p->udptl)) {
08614
08615 ast_udptl_set_far_max_datagram(p->udptl, 0);
08616 }
08617
08618
08619 if ((t38action == SDP_T38_ACCEPT) &&
08620 (p->t38.state == T38_LOCAL_REINVITE)) {
08621 change_t38_state(p, T38_ENABLED);
08622 } else if ((t38action == SDP_T38_INITIATE) &&
08623 p->owner && p->lastinvite) {
08624 change_t38_state(p, T38_PEER_REINVITE);
08625
08626 if (ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_T38)) {
08627 ast_channel_lock(p->owner);
08628 if (strcmp(p->owner->exten, "fax")) {
08629 const char *target_context = S_OR(p->owner->macrocontext, p->owner->context);
08630 ast_channel_unlock(p->owner);
08631 if (ast_exists_extension(p->owner, target_context, "fax", 1, p->owner->cid.cid_num)) {
08632 ast_verbose(VERBOSE_PREFIX_2 "Redirecting '%s' to fax extension due to peer T.38 re-INVITE\n", p->owner->name);
08633 pbx_builtin_setvar_helper(p->owner, "FAXEXTEN", p->owner->exten);
08634 if (ast_async_goto(p->owner, target_context, "fax", 1)) {
08635 ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", p->owner->name, target_context);
08636 }
08637 } else {
08638 ast_log(LOG_NOTICE, "T.38 re-INVITE detected but no fax extension\n");
08639 }
08640 } else {
08641 ast_channel_unlock(p->owner);
08642 }
08643 }
08644 }
08645 } else {
08646 ast_udptl_stop(p->udptl);
08647 if (debug)
08648 ast_debug(1, "Peer doesn't provide T.38 UDPTL\n");
08649 }
08650 }
08651
08652 if ((portno == -1) && (p->t38.state != T38_DISABLED)) {
08653 ast_debug(3, "Have T.38 but no audio, accepting offer anyway\n");
08654 return 0;
08655 }
08656
08657
08658 ast_debug(2, "We're settling with these formats: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, p->jointcapability));
08659
08660 if (!p->owner)
08661 return 0;
08662
08663 ast_debug(4, "We have an owner, now see if we need to change this call\n");
08664
08665 if (!(p->owner->nativeformats & p->jointcapability) && (p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
08666 if (debug) {
08667 char s1[SIPBUFSIZE], s2[SIPBUFSIZE];
08668 ast_debug(1, "Oooh, we need to change our audio formats since our peer supports only %s and not %s\n",
08669 ast_getformatname_multiple(s1, SIPBUFSIZE, p->jointcapability),
08670 ast_getformatname_multiple(s2, SIPBUFSIZE, p->owner->nativeformats));
08671 }
08672 p->owner->nativeformats = ast_codec_choose(&p->prefs, p->jointcapability, 1) | (p->capability & vpeercapability) | (p->capability & tpeercapability);
08673 ast_set_read_format(p->owner, p->owner->readformat);
08674 ast_set_write_format(p->owner, p->owner->writeformat);
08675 }
08676
08677 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)
08678 && (sin.sin_addr.s_addr || vsin.sin_addr.s_addr ||
08679 isin.sin_addr.s_addr || tsin.sin_addr.s_addr)
08680 && (!sendonly || sendonly == -1)) {
08681 ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
08682
08683 ast_queue_frame(p->owner, &ast_null_frame);
08684
08685 append_history(p, "Unhold", "%s", req->data->str);
08686 if (sip_cfg.callevents)
08687 manager_event(EVENT_FLAG_CALL, "Hold",
08688 "Status: Off\r\n"
08689 "Channel: %s\r\n"
08690 "Uniqueid: %s\r\n",
08691 p->owner->name,
08692 p->owner->uniqueid);
08693 if (sip_cfg.notifyhold)
08694 sip_peer_hold(p, FALSE);
08695 ast_clear_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD);
08696 } else if (!(sin.sin_addr.s_addr || vsin.sin_addr.s_addr ||
08697 isin.sin_addr.s_addr || tsin.sin_addr.s_addr)
08698 || (sendonly && sendonly != -1)) {
08699 int already_on_hold = ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD);
08700 ast_queue_control_data(p->owner, AST_CONTROL_HOLD,
08701 S_OR(p->mohsuggest, NULL),
08702 !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
08703 if (sendonly)
08704 ast_rtp_stop(p->rtp);
08705
08706
08707 ast_queue_frame(p->owner, &ast_null_frame);
08708
08709 append_history(p, "Hold", "%s", req->data->str);
08710 if (sip_cfg.callevents && !ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
08711 manager_event(EVENT_FLAG_CALL, "Hold",
08712 "Status: On\r\n"
08713 "Channel: %s\r\n"
08714 "Uniqueid: %s\r\n",
08715 p->owner->name,
08716 p->owner->uniqueid);
08717 }
08718 if (sendonly == 1)
08719 ast_set_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD_ONEDIR);
08720 else if (sendonly == 2)
08721 ast_set_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD_INACTIVE);
08722 else
08723 ast_set_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD_ACTIVE);
08724 if (sip_cfg.notifyhold && !already_on_hold)
08725 sip_peer_hold(p, TRUE);
08726 }
08727
08728 return 0;
08729 }
08730
08731 static int process_sdp_o(const char *o, struct sip_pvt *p)
08732 {
08733 char *o_copy;
08734 char *token;
08735 int64_t rua_version;
08736
08737
08738
08739
08740
08741
08742
08743
08744
08745
08746 p->session_modify = TRUE;
08747
08748 if (ast_strlen_zero(o)) {
08749 ast_log(LOG_WARNING, "SDP syntax error. SDP without an o= line\n");
08750 return FALSE;
08751 }
08752
08753 o_copy = ast_strdupa(o);
08754 token = strsep(&o_copy, " ");
08755 if (!o_copy) {
08756 ast_log(LOG_WARNING, "SDP syntax error in o= line username\n");
08757 return FALSE;
08758 }
08759 token = strsep(&o_copy, " ");
08760 if (!o_copy) {
08761 ast_log(LOG_WARNING, "SDP syntax error in o= line session-id\n");
08762 return FALSE;
08763 }
08764 token = strsep(&o_copy, " ");
08765 if (!o_copy) {
08766 ast_log(LOG_WARNING, "SDP syntax error in o= line\n");
08767 return FALSE;
08768 }
08769 if (!sscanf(token, "%30" SCNd64, &rua_version)) {
08770 ast_log(LOG_WARNING, "SDP syntax error in o= line version\n");
08771 return FALSE;
08772 }
08773
08774
08775
08776
08777
08778
08779
08780
08781
08782
08783
08784
08785
08786
08787
08788
08789
08790
08791
08792 if (ast_test_flag(&p->flags[1], SIP_PAGE2_IGNORESDPVERSION) ||
08793 (p->sessionversion_remote < 0) ||
08794 (p->sessionversion_remote < rua_version)) {
08795 p->sessionversion_remote = rua_version;
08796 } else {
08797 if (p->t38.state == T38_LOCAL_REINVITE) {
08798 p->sessionversion_remote = rua_version;
08799 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);
08800 } else {
08801 p->session_modify = FALSE;
08802 ast_debug(2, "Call %s responded to our reinvite without changing SDP version; ignoring SDP.\n", p->callid);
08803 return FALSE;
08804 }
08805 }
08806
08807 return TRUE;
08808 }
08809
08810 static int process_sdp_c(const char *c, struct ast_hostent *ast_hp)
08811 {
08812 char host[258];
08813 struct hostent *hp;
08814
08815
08816 if (sscanf(c, "IN IP4 %255s", host) != 1) {
08817 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
08818 return FALSE;
08819 } else {
08820 if (!(hp = ast_gethostbyname(host, ast_hp))) {
08821 ast_log(LOG_WARNING, "Unable to lookup RTP Audio host in c= line, '%s'\n", c);
08822 return FALSE;
08823 }
08824 return TRUE;
08825 }
08826 return FALSE;
08827 }
08828
08829 static int process_sdp_a_sendonly(const char *a, int *sendonly)
08830 {
08831 int found = FALSE;
08832
08833 if (!strcasecmp(a, "sendonly")) {
08834 if (*sendonly == -1)
08835 *sendonly = 1;
08836 found = TRUE;
08837 } else if (!strcasecmp(a, "inactive")) {
08838 if (*sendonly == -1)
08839 *sendonly = 2;
08840 found = TRUE;
08841 } else if (!strcasecmp(a, "sendrecv")) {
08842 if (*sendonly == -1)
08843 *sendonly = 0;
08844 found = TRUE;
08845 }
08846 return found;
08847 }
08848
08849 static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp *newaudiortp, int *last_rtpmap_codec)
08850 {
08851 int found = FALSE;
08852 int codec;
08853 char mimeSubtype[128];
08854 char fmtp_string[64];
08855 unsigned int sample_rate;
08856 int debug = sip_debug_test_pvt(p);
08857
08858 if (!strncasecmp(a, "ptime", 5)) {
08859 char *tmp = strrchr(a, ':');
08860 long int framing = 0;
08861 if (tmp) {
08862 tmp++;
08863 framing = strtol(tmp, NULL, 10);
08864 if (framing == LONG_MIN || framing == LONG_MAX) {
08865 framing = 0;
08866 ast_debug(1, "Can't read framing from SDP: %s\n", a);
08867 }
08868 }
08869 if (framing && p->autoframing) {
08870 struct ast_codec_pref *pref = ast_rtp_codec_getpref(p->rtp);
08871 int codec_n;
08872 int format = 0;
08873 for (codec_n = 0; codec_n < MAX_RTP_PT; codec_n++) {
08874 format = ast_rtp_codec_getformat(codec_n);
08875 if (!format)
08876 continue;
08877 if (option_debug)
08878 ast_log(LOG_DEBUG, "Setting framing for %d to %ld\n", format, framing);
08879 ast_codec_pref_setsize(pref, format, framing);
08880 }
08881 ast_rtp_codec_setpref(p->rtp, pref);
08882 }
08883 found = TRUE;
08884 } else if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
08885
08886 if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
08887 if (ast_rtp_set_rtpmap_type_rate(newaudiortp, codec, "audio", mimeSubtype,
08888 ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0, sample_rate) != -1) {
08889 if (debug)
08890 ast_verbose("Found audio description format %s for ID %d\n", mimeSubtype, codec);
08891
08892 (*last_rtpmap_codec)++;
08893 found = TRUE;
08894 } else {
08895 ast_rtp_unset_m_type(newaudiortp, codec);
08896 if (debug)
08897 ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
08898 }
08899 } else {
08900 if (debug)
08901 ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
08902 }
08903 } else if (sscanf(a, "fmtp: %30u %63s", &codec, fmtp_string) == 2) {
08904 struct rtpPayloadType payload;
08905
08906 payload = ast_rtp_lookup_pt(newaudiortp, codec);
08907 if (payload.code && payload.isAstFormat) {
08908 unsigned int bit_rate;
08909
08910 switch (payload.code) {
08911 case AST_FORMAT_SIREN7:
08912 if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
08913 if (bit_rate != 32000) {
08914 ast_log(LOG_WARNING, "Got Siren7 offer at %d bps, but only 32000 bps supported; ignoring.\n", bit_rate);
08915 ast_rtp_unset_m_type(newaudiortp, codec);
08916 } else {
08917 found = TRUE;
08918 }
08919 }
08920 break;
08921 case AST_FORMAT_SIREN14:
08922 if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
08923 if (bit_rate != 48000) {
08924 ast_log(LOG_WARNING, "Got Siren14 offer at %d bps, but only 48000 bps supported; ignoring.\n", bit_rate);
08925 ast_rtp_unset_m_type(newaudiortp, codec);
08926 } else {
08927 found = TRUE;
08928 }
08929 }
08930 break;
08931 }
08932 }
08933 }
08934
08935 return found;
08936 }
08937
08938 static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp *newvideortp, int *last_rtpmap_codec)
08939 {
08940 int found = FALSE;
08941 int codec;
08942 char mimeSubtype[128];
08943 unsigned int sample_rate;
08944 int debug = sip_debug_test_pvt(p);
08945
08946 if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
08947
08948 if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
08949
08950 if (!strncasecmp(mimeSubtype, "H26", 3) || !strncasecmp(mimeSubtype, "MP4", 3)) {
08951 if (ast_rtp_set_rtpmap_type_rate(newvideortp, codec, "video", mimeSubtype, 0, sample_rate) != -1) {
08952 if (debug)
08953 ast_verbose("Found video description format %s for ID %d\n", mimeSubtype, codec);
08954
08955 (*last_rtpmap_codec)++;
08956 found = TRUE;
08957 } else {
08958 ast_rtp_unset_m_type(newvideortp, codec);
08959 if (debug)
08960 ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
08961 }
08962 }
08963 } else {
08964 if (debug)
08965 ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
08966 }
08967 }
08968
08969 return found;
08970 }
08971
08972 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)
08973 {
08974 int found = FALSE;
08975 int codec;
08976 char mimeSubtype[128];
08977 unsigned int sample_rate;
08978 char *red_cp;
08979 int debug = sip_debug_test_pvt(p);
08980
08981 if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
08982
08983 if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
08984 if (!strncasecmp(mimeSubtype, "T140", 4)) {
08985 if (p->trtp) {
08986
08987 ast_rtp_set_rtpmap_type(newtextrtp, codec, "text", mimeSubtype, 0);
08988 found = TRUE;
08989 }
08990 } else if (!strncasecmp(mimeSubtype, "RED", 3)) {
08991 if (p->trtp) {
08992 ast_rtp_set_rtpmap_type(newtextrtp, codec, "text", mimeSubtype, 0);
08993 sprintf(red_fmtp, "fmtp:%d ", codec);
08994 if (debug)
08995 ast_verbose("RED submimetype has payload type: %d\n", codec);
08996 found = TRUE;
08997 }
08998 }
08999 } else {
09000 if (debug)
09001 ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
09002 }
09003 } else if (!strncmp(a, red_fmtp, strlen(red_fmtp))) {
09004
09005 red_cp = &red_fmtp[strlen(red_fmtp)];
09006 strncpy(red_fmtp, a, 100);
09007
09008 sscanf(red_cp, "%30u", &red_data_pt[*red_num_gen]);
09009 red_cp = strtok(red_cp, "/");
09010 while (red_cp && (*red_num_gen)++ < RED_MAX_GENERATION) {
09011 sscanf(red_cp, "%30u", &red_data_pt[*red_num_gen]);
09012 red_cp = strtok(NULL, "/");
09013 }
09014 red_cp = red_fmtp;
09015 found = TRUE;
09016 }
09017
09018 return found;
09019 }
09020
09021 static int process_sdp_a_image(const char *a, struct sip_pvt *p)
09022 {
09023 int found = FALSE;
09024 char s[256];
09025 unsigned int x;
09026
09027 if ((sscanf(a, "T38FaxMaxBuffer:%30u", &x) == 1)) {
09028 ast_debug(3, "MaxBufferSize:%d\n", x);
09029 found = TRUE;
09030 } else if ((sscanf(a, "T38MaxBitRate:%30u", &x) == 1) || (sscanf(a, "T38FaxMaxRate:%30u", &x) == 1)) {
09031 ast_debug(3, "T38MaxBitRate: %d\n", x);
09032 switch (x) {
09033 case 14400:
09034 p->t38.their_parms.rate = AST_T38_RATE_14400;
09035 break;
09036 case 12000:
09037 p->t38.their_parms.rate = AST_T38_RATE_12000;
09038 break;
09039 case 9600:
09040 p->t38.their_parms.rate = AST_T38_RATE_9600;
09041 break;
09042 case 7200:
09043 p->t38.their_parms.rate = AST_T38_RATE_7200;
09044 break;
09045 case 4800:
09046 p->t38.their_parms.rate = AST_T38_RATE_4800;
09047 break;
09048 case 2400:
09049 p->t38.their_parms.rate = AST_T38_RATE_2400;
09050 break;
09051 }
09052 found = TRUE;
09053 } else if ((sscanf(a, "T38FaxVersion:%30u", &x) == 1)) {
09054 ast_debug(3, "FaxVersion: %u\n", x);
09055 p->t38.their_parms.version = x;
09056 found = TRUE;
09057 } else if ((sscanf(a, "T38FaxMaxDatagram:%30u", &x) == 1) || (sscanf(a, "T38MaxDatagram:%30u", &x) == 1)) {
09058
09059 if (((signed int) p->t38_maxdatagram >= 0) && ((unsigned int) p->t38_maxdatagram > x)) {
09060 ast_debug(1, "Overriding T38FaxMaxDatagram '%d' with '%d'\n", x, p->t38_maxdatagram);
09061 x = p->t38_maxdatagram;
09062 }
09063 ast_debug(3, "FaxMaxDatagram: %u\n", x);
09064 ast_udptl_set_far_max_datagram(p->udptl, x);
09065 found = TRUE;
09066 } else if ((strncmp(a, "T38FaxFillBitRemoval", 20) == 0)) {
09067 if (sscanf(a, "T38FaxFillBitRemoval:%30u", &x) == 1) {
09068 ast_debug(3, "FillBitRemoval: %d\n", x);
09069 if (x == 1) {
09070 p->t38.their_parms.fill_bit_removal = TRUE;
09071 }
09072 } else {
09073 ast_debug(3, "FillBitRemoval\n");
09074 p->t38.their_parms.fill_bit_removal = TRUE;
09075 }
09076 found = TRUE;
09077 } else if ((strncmp(a, "T38FaxTranscodingMMR", 20) == 0)) {
09078 if (sscanf(a, "T38FaxTranscodingMMR:%30u", &x) == 1) {
09079 ast_debug(3, "Transcoding MMR: %d\n", x);
09080 if (x == 1) {
09081 p->t38.their_parms.transcoding_mmr = TRUE;
09082 }
09083 } else {
09084 ast_debug(3, "Transcoding MMR\n");
09085 p->t38.their_parms.transcoding_mmr = TRUE;
09086 }
09087 found = TRUE;
09088 } else if ((strncmp(a, "T38FaxTranscodingJBIG", 21) == 0)) {
09089 if (sscanf(a, "T38FaxTranscodingJBIG:%30u", &x) == 1) {
09090 ast_debug(3, "Transcoding JBIG: %d\n", x);
09091 if (x == 1) {
09092 p->t38.their_parms.transcoding_jbig = TRUE;
09093 }
09094 } else {
09095 ast_debug(3, "Transcoding JBIG\n");
09096 p->t38.their_parms.transcoding_jbig = TRUE;
09097 }
09098 found = TRUE;
09099 } else if ((sscanf(a, "T38FaxRateManagement:%255s", s) == 1)) {
09100 ast_debug(3, "RateManagement: %s\n", s);
09101 if (!strcasecmp(s, "localTCF"))
09102 p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_LOCAL_TCF;
09103 else if (!strcasecmp(s, "transferredTCF"))
09104 p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF;
09105 found = TRUE;
09106 } else if ((sscanf(a, "T38FaxUdpEC:%255s", s) == 1)) {
09107 ast_debug(3, "UDP EC: %s\n", s);
09108 if (!strcasecmp(s, "t38UDPRedundancy")) {
09109 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
09110 } else if (!strcasecmp(s, "t38UDPFEC")) {
09111 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
09112 } else {
09113 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
09114 }
09115 found = TRUE;
09116 }
09117
09118 return found;
09119 }
09120
09121
09122 #ifdef LOW_MEMORY
09123 static void ts_ast_rtp_destroy(void *data)
09124 {
09125 struct ast_rtp *tmp = data;
09126 ast_rtp_destroy(tmp);
09127 }
09128 #endif
09129
09130
09131 static int add_header(struct sip_request *req, const char *var, const char *value)
09132 {
09133 if (req->headers == SIP_MAX_HEADERS) {
09134 ast_log(LOG_WARNING, "Out of SIP header space\n");
09135 return -1;
09136 }
09137
09138 if (req->lines) {
09139 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
09140 return -1;
09141 }
09142
09143 if (sip_cfg.compactheaders) {
09144 var = find_alias(var, var);
09145 }
09146
09147 ast_str_append(&req->data, 0, "%s: %s\r\n", var, value);
09148 req->header[req->headers] = req->len;
09149
09150 req->len = ast_str_strlen(req->data);
09151 req->headers++;
09152
09153 return 0;
09154 }
09155
09156
09157 static int finalize_content(struct sip_request *req)
09158 {
09159 char clen[10];
09160
09161 if (req->lines) {
09162 ast_log(LOG_WARNING, "finalize_content() called on a message that has already been finalized\n");
09163 return -1;
09164 }
09165
09166 snprintf(clen, sizeof(clen), "%zd", ast_str_strlen(req->content));
09167 add_header(req, "Content-Length", clen);
09168
09169 if (ast_str_strlen(req->content)) {
09170 ast_str_append(&req->data, 0, "\r\n%s", ast_str_buffer(req->content));
09171 req->len = ast_str_strlen(req->data);
09172 }
09173 req->lines = ast_str_strlen(req->content) ? 1 : 0;
09174 return 0;
09175 }
09176
09177
09178 static int add_content(struct sip_request *req, const char *line)
09179 {
09180 if (req->lines) {
09181 ast_log(LOG_WARNING, "Can't add more content when the content has been finalized\n");
09182 return -1;
09183 }
09184
09185 ast_str_append(&req->content, 0, "%s", line);
09186 return 0;
09187 }
09188
09189
09190 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field)
09191 {
09192 const char *tmp = get_header(orig, field);
09193
09194 if (!ast_strlen_zero(tmp))
09195 return add_header(req, field, tmp);
09196 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
09197 return -1;
09198 }
09199
09200
09201 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field)
09202 {
09203 int start = 0;
09204 int copied = 0;
09205 for (;;) {
09206 const char *tmp = __get_header(orig, field, &start);
09207
09208 if (ast_strlen_zero(tmp))
09209 break;
09210
09211 add_header(req, field, tmp);
09212 copied++;
09213 }
09214 return copied ? 0 : -1;
09215 }
09216
09217
09218
09219
09220
09221
09222
09223
09224
09225 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field)
09226 {
09227 int copied = 0;
09228 int start = 0;
09229
09230 for (;;) {
09231 char new[512];
09232 const char *oh = __get_header(orig, field, &start);
09233
09234 if (ast_strlen_zero(oh))
09235 break;
09236
09237 if (!copied) {
09238 char leftmost[512], *others, *rport;
09239
09240
09241 ast_copy_string(leftmost, oh, sizeof(leftmost));
09242 others = strchr(leftmost, ',');
09243 if (others)
09244 *others++ = '\0';
09245
09246
09247 rport = strstr(leftmost, ";rport");
09248 if (rport && *(rport+6) == '=')
09249 rport = NULL;
09250
09251
09252 if (rport && ((ast_test_flag(&p->flags[0], SIP_NAT) == SIP_NAT_ALWAYS) || (ast_test_flag(&p->flags[0], SIP_NAT) == SIP_NAT_RFC3581))) {
09253
09254 char *end;
09255
09256 rport = strstr(leftmost, ";rport");
09257
09258 if (rport) {
09259 end = strchr(rport + 1, ';');
09260 if (end)
09261 memmove(rport, end, strlen(end) + 1);
09262 else
09263 *rport = '\0';
09264 }
09265
09266
09267 snprintf(new, sizeof(new), "%s;received=%s;rport=%d%s%s",
09268 leftmost, ast_inet_ntoa(p->recv.sin_addr),
09269 ntohs(p->recv.sin_port),
09270 others ? "," : "", others ? others : "");
09271 } else {
09272
09273 snprintf(new, sizeof(new), "%s;received=%s%s%s",
09274 leftmost, ast_inet_ntoa(p->recv.sin_addr),
09275 others ? "," : "", others ? others : "");
09276 }
09277 oh = new;
09278 }
09279 add_header(req, field, oh);
09280 copied++;
09281 }
09282 if (!copied) {
09283 ast_log(LOG_NOTICE, "No header field '%s' present to copy\n", field);
09284 return -1;
09285 }
09286 return 0;
09287 }
09288
09289
09290 static void add_route(struct sip_request *req, struct sip_route *route)
09291 {
09292 char r[SIPBUFSIZE*2], *p;
09293 int n, rem = sizeof(r);
09294
09295 if (!route)
09296 return;
09297
09298 p = r;
09299 for (;route ; route = route->next) {
09300 n = strlen(route->hop);
09301 if (rem < n+3)
09302 break;
09303 if (p != r) {
09304 *p++ = ',';
09305 --rem;
09306 }
09307 *p++ = '<';
09308 ast_copy_string(p, route->hop, rem);
09309 p += n;
09310 *p++ = '>';
09311 rem -= (n+2);
09312 }
09313 *p = '\0';
09314 add_header(req, "Route", r);
09315 }
09316
09317
09318
09319
09320
09321
09322
09323
09324
09325
09326 static void set_destination(struct sip_pvt *p, char *uri)
09327 {
09328 char *h, *maddr, hostname[256];
09329 int port, hn;
09330 struct hostent *hp;
09331 struct ast_hostent ahp;
09332 int debug=sip_debug_test_pvt(p);
09333 int tls_on = FALSE;
09334 int use_dns = sip_cfg.srvlookup;
09335
09336 if (debug)
09337 ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
09338
09339
09340 h = strchr(uri, '@');
09341 if (h)
09342 ++h;
09343 else {
09344 h = uri;
09345 if (!strncasecmp(h, "sip:", 4)) {
09346 h += 4;
09347 } else if (!strncasecmp(h, "sips:", 5)) {
09348 h += 5;
09349 tls_on = TRUE;
09350 }
09351 }
09352 hn = strcspn(h, ":;>") + 1;
09353 if (hn > sizeof(hostname))
09354 hn = sizeof(hostname);
09355 ast_copy_string(hostname, h, hn);
09356
09357 h += hn - 1;
09358
09359
09360 if (*h == ':') {
09361
09362 ++h;
09363 port = strtol(h, &h, 10);
09364 use_dns = FALSE;
09365 } else
09366 port = tls_on ? STANDARD_TLS_PORT : STANDARD_SIP_PORT;
09367
09368
09369 maddr = strstr(h, "maddr=");
09370 if (maddr) {
09371 maddr += 6;
09372 hn = strspn(maddr, "0123456789.") + 1;
09373 if (hn > sizeof(hostname))
09374 hn = sizeof(hostname);
09375 ast_copy_string(hostname, maddr, hn);
09376 }
09377
09378
09379
09380 hp = ast_gethostbyname(hostname, &ahp);
09381 if (hp == NULL) {
09382 ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
09383 return;
09384 }
09385 p->sa.sin_family = AF_INET;
09386 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
09387 p->sa.sin_port = htons(port);
09388 if (debug)
09389 ast_verbose("set_destination: set destination to %s, port %d\n", ast_inet_ntoa(p->sa.sin_addr), port);
09390 }
09391
09392
09393 static int init_resp(struct sip_request *resp, const char *msg)
09394 {
09395
09396 memset(resp, 0, sizeof(*resp));
09397 resp->method = SIP_RESPONSE;
09398 if (!(resp->data = ast_str_create(SIP_MIN_PACKET)))
09399 goto e_return;
09400 if (!(resp->content = ast_str_create(SIP_MIN_PACKET)))
09401 goto e_free_data;
09402 resp->header[0] = 0;
09403 ast_str_set(&resp->data, 0, "SIP/2.0 %s\r\n", msg);
09404 resp->len = resp->data->used;
09405 resp->headers++;
09406 return 0;
09407
09408 e_free_data:
09409 ast_free(resp->data);
09410 resp->data = NULL;
09411 e_return:
09412 return -1;
09413 }
09414
09415
09416 static int init_req(struct sip_request *req, int sipmethod, const char *recip)
09417 {
09418
09419 memset(req, 0, sizeof(*req));
09420 if (!(req->data = ast_str_create(SIP_MIN_PACKET)))
09421 goto e_return;
09422 if (!(req->content = ast_str_create(SIP_MIN_PACKET)))
09423 goto e_free_data;
09424 req->method = sipmethod;
09425 req->header[0] = 0;
09426 ast_str_set(&req->data, 0, "%s %s SIP/2.0\r\n", sip_methods[sipmethod].text, recip);
09427 req->len = ast_str_strlen(req->data);
09428 req->headers++;
09429 return 0;
09430
09431 e_free_data:
09432 ast_free(req->data);
09433 req->data = NULL;
09434 e_return:
09435 return -1;
09436 }
09437
09438
09439 static void deinit_req(struct sip_request *req)
09440 {
09441 if (req->data) {
09442 ast_free(req->data);
09443 req->data = NULL;
09444 }
09445 if (req->content) {
09446 ast_free(req->content);
09447 req->content = NULL;
09448 }
09449 }
09450
09451
09452
09453 static inline int resp_needs_contact(const char *msg, enum sipmethod method) {
09454
09455
09456
09457
09458
09459
09460
09461
09462
09463
09464
09465
09466
09467
09468
09469 switch (method) {
09470
09471 case SIP_INVITE:
09472 case SIP_UPDATE:
09473 case SIP_SUBSCRIBE:
09474 case SIP_NOTIFY:
09475 if ((msg[0] >= '1' && msg[0] <= '3') || !strncmp(msg, "485", 3))
09476 return 1;
09477 break;
09478
09479
09480 case SIP_REGISTER:
09481 case SIP_OPTIONS:
09482 if (msg[0] == '2' || msg[0] == '3' || !strncmp(msg, "485", 3))
09483 return 1;
09484 break;
09485
09486
09487 case SIP_BYE:
09488 case SIP_PRACK:
09489 case SIP_MESSAGE:
09490 case SIP_PUBLISH:
09491 if (msg[0] == '3' || !strncmp(msg, "485", 3))
09492 return 1;
09493 break;
09494
09495
09496 case SIP_REFER:
09497 if (msg[0] >= '2' && msg[0] <= '6')
09498 return 1;
09499 break;
09500
09501
09502 case SIP_ACK:
09503 case SIP_CANCEL:
09504 case SIP_INFO:
09505 case SIP_PING:
09506 default:
09507 return 0;
09508 }
09509 return 0;
09510 }
09511
09512
09513 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req)
09514 {
09515 char newto[256];
09516 const char *ot;
09517
09518 init_resp(resp, msg);
09519 copy_via_headers(p, resp, req, "Via");
09520 if (msg[0] == '1' || msg[0] == '2')
09521 copy_all_header(resp, req, "Record-Route");
09522 copy_header(resp, req, "From");
09523 ot = get_header(req, "To");
09524 if (!strcasestr(ot, "tag=") && strncmp(msg, "100", 3)) {
09525
09526
09527 if (!ast_strlen_zero(p->theirtag) && ast_test_flag(&p->flags[0], SIP_OUTGOING))
09528 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
09529 else if (p->tag && !ast_test_flag(&p->flags[0], SIP_OUTGOING))
09530 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
09531 else
09532 ast_copy_string(newto, ot, sizeof(newto));
09533 ot = newto;
09534 }
09535 add_header(resp, "To", ot);
09536 copy_header(resp, req, "Call-ID");
09537 copy_header(resp, req, "CSeq");
09538 if (!ast_strlen_zero(global_useragent))
09539 add_header(resp, "Server", global_useragent);
09540 add_header(resp, "Allow", ALLOWED_METHODS);
09541 add_header(resp, "Supported", SUPPORTED_EXTENSIONS);
09542
09543
09544 if (p->method == SIP_INVITE && p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE) {
09545 char se_hdr[256];
09546 snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval,
09547 strefresher2str(p->stimer->st_ref));
09548 add_header(resp, "Require", "timer");
09549 add_header(resp, "Session-Expires", se_hdr);
09550 }
09551
09552 if (msg[0] == '2' && (p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER)) {
09553
09554
09555 char tmp[256];
09556
09557 snprintf(tmp, sizeof(tmp), "%d", p->expiry);
09558 add_header(resp, "Expires", tmp);
09559 if (p->expiry) {
09560 char contact[SIPBUFSIZE];
09561 const char *contact_uri = p->method == SIP_SUBSCRIBE ? p->our_contact : p->fullcontact;
09562 char *brackets = strchr(contact_uri, '<');
09563 snprintf(contact, sizeof(contact), "%s%s%s;expires=%d", brackets ? "" : "<", contact_uri, brackets ? "" : ">", p->expiry);
09564 add_header(resp, "Contact", contact);
09565 }
09566 } else if (!ast_strlen_zero(p->our_contact) && resp_needs_contact(msg, p->method)) {
09567 add_header(resp, "Contact", p->our_contact);
09568 }
09569
09570 if (!ast_strlen_zero(p->url)) {
09571 add_header(resp, "Access-URL", p->url);
09572 ast_string_field_set(p, url, NULL);
09573 }
09574
09575 return 0;
09576 }
09577
09578
09579 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch)
09580 {
09581 struct sip_request *orig = &p->initreq;
09582 char stripped[80];
09583 char tmp[80];
09584 char newto[256];
09585 const char *c;
09586 const char *ot, *of;
09587 int is_strict = FALSE;
09588 int is_outbound = ast_test_flag(&p->flags[0], SIP_OUTGOING);
09589
09590 memset(req, 0, sizeof(struct sip_request));
09591
09592 snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", sip_methods[sipmethod].text);
09593
09594 if (!seqno) {
09595 p->ocseq++;
09596 seqno = p->ocseq;
09597 }
09598
09599
09600 if (sipmethod == SIP_CANCEL) {
09601 p->branch = p->invite_branch;
09602 build_via(p);
09603 } else if (newbranch && (sipmethod == SIP_INVITE)) {
09604 p->branch ^= ast_random();
09605 p->invite_branch = p->branch;
09606 build_via(p);
09607 } else if (newbranch) {
09608 p->branch ^= ast_random();
09609 build_via(p);
09610 }
09611
09612
09613 if (p->route && !ast_strlen_zero(p->route->hop) && strstr(p->route->hop, ";lr") == NULL) {
09614 is_strict = TRUE;
09615 if (sipdebug)
09616 ast_debug(1, "Strict routing enforced for session %s\n", p->callid);
09617 }
09618
09619 if (sipmethod == SIP_CANCEL)
09620 c = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
09621 else if (sipmethod == SIP_ACK) {
09622
09623
09624 if (!ast_strlen_zero(p->okcontacturi))
09625 c = is_strict ? p->route->hop : p->okcontacturi;
09626 else
09627 c = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
09628 } else if (!ast_strlen_zero(p->okcontacturi))
09629 c = is_strict ? p->route->hop : p->okcontacturi;
09630 else if (!ast_strlen_zero(p->uri))
09631 c = p->uri;
09632 else {
09633 char *n;
09634
09635 ast_copy_string(stripped, get_header(orig, is_outbound ? "To" : "From"),
09636 sizeof(stripped));
09637 n = get_in_brackets(stripped);
09638 c = remove_uri_parameters(n);
09639 }
09640 init_req(req, sipmethod, c);
09641
09642 snprintf(tmp, sizeof(tmp), "%d %s", seqno, sip_methods[sipmethod].text);
09643
09644 add_header(req, "Via", p->via);
09645 if (p->route) {
09646 set_destination(p, p->route->hop);
09647 add_route(req, is_strict ? p->route->next : p->route);
09648 }
09649 add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
09650
09651 ot = get_header(orig, "To");
09652 of = get_header(orig, "From");
09653
09654
09655
09656 if (!strcasestr(ot, "tag=") && sipmethod != SIP_CANCEL) {
09657
09658
09659 if (is_outbound && !ast_strlen_zero(p->theirtag))
09660 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
09661 else if (!is_outbound)
09662 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
09663 else
09664 snprintf(newto, sizeof(newto), "%s", ot);
09665 ot = newto;
09666 }
09667
09668 if (is_outbound) {
09669 add_header(req, "From", of);
09670 add_header(req, "To", ot);
09671 } else {
09672 add_header(req, "From", ot);
09673 add_header(req, "To", of);
09674 }
09675
09676 if (sipmethod != SIP_BYE && sipmethod != SIP_CANCEL && sipmethod != SIP_MESSAGE)
09677 add_header(req, "Contact", p->our_contact);
09678
09679 copy_header(req, orig, "Call-ID");
09680 add_header(req, "CSeq", tmp);
09681
09682 if (!ast_strlen_zero(global_useragent))
09683 add_header(req, "User-Agent", global_useragent);
09684
09685 if (!ast_strlen_zero(p->rpid))
09686 add_header(req, "Remote-Party-ID", p->rpid);
09687
09688 if (!ast_strlen_zero(p->url)) {
09689 add_header(req, "Access-URL", p->url);
09690 ast_string_field_set(p, url, NULL);
09691 }
09692
09693
09694
09695
09696
09697
09698
09699
09700 if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE
09701 && sipmethod == SIP_INVITE) {
09702 char se_hdr[256];
09703 snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval,
09704 strefresher2str(p->stimer->st_ref));
09705 add_header(req, "Require", "timer");
09706 add_header(req, "Session-Expires", se_hdr);
09707 snprintf(se_hdr, sizeof(se_hdr), "%d", st_get_se(p, FALSE));
09708 add_header(req, "Min-SE", se_hdr);
09709 }
09710
09711 return 0;
09712 }
09713
09714
09715 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
09716 {
09717 struct sip_request resp;
09718 int seqno = 0;
09719
09720 if (reliable && (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1)) {
09721 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
09722 return -1;
09723 }
09724 respprep(&resp, p, msg, req);
09725
09726
09727 if (p->method == SIP_INVITE && msg[0] != '1' && p->owner && p->owner->hangupcause) {
09728 char buf[10];
09729
09730 add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->owner->hangupcause));
09731 snprintf(buf, sizeof(buf), "%d", p->owner->hangupcause);
09732 add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
09733 }
09734 return send_response(p, &resp, reliable, seqno);
09735 }
09736
09737 static int temp_pvt_init(void *data)
09738 {
09739 struct sip_pvt *p = data;
09740
09741 p->do_history = 0;
09742 return ast_string_field_init(p, 512);
09743 }
09744
09745 static void temp_pvt_cleanup(void *data)
09746 {
09747 struct sip_pvt *p = data;
09748
09749 ast_string_field_free_memory(p);
09750
09751 ast_free(data);
09752 }
09753
09754
09755 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)
09756 {
09757 struct sip_pvt *p = NULL;
09758
09759 if (!(p = ast_threadstorage_get(&ts_temp_pvt, sizeof(*p)))) {
09760 ast_log(LOG_ERROR, "Failed to get temporary pvt\n");
09761 return -1;
09762 }
09763
09764
09765
09766
09767
09768
09769
09770
09771
09772 p->method = intended_method;
09773
09774 if (!sin)
09775 p->ourip = internip;
09776 else {
09777 p->sa = *sin;
09778 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
09779 }
09780
09781 p->branch = ast_random();
09782 make_our_tag(p->tag, sizeof(p->tag));
09783 p->ocseq = INITIAL_CSEQ;
09784
09785 if (useglobal_nat && sin) {
09786 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT);
09787 p->recv = *sin;
09788 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
09789 }
09790
09791 ast_string_field_set(p, fromdomain, default_fromdomain);
09792 build_via(p);
09793 ast_string_field_set(p, callid, callid);
09794
09795 copy_socket_data(&p->socket, &req->socket);
09796
09797
09798 __transmit_response(p, msg, req, XMIT_UNRELIABLE);
09799
09800
09801 ast_string_field_init(p, 0);
09802
09803 return 0;
09804 }
09805
09806
09807 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req)
09808 {
09809 return __transmit_response(p, msg, req, XMIT_UNRELIABLE);
09810 }
09811
09812
09813 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported)
09814 {
09815 struct sip_request resp;
09816 respprep(&resp, p, msg, req);
09817 append_date(&resp);
09818 add_header(&resp, "Unsupported", unsupported);
09819 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
09820 }
09821
09822
09823 static int transmit_response_with_minse(struct sip_pvt *p, const char *msg, const struct sip_request *req, int minse_int)
09824 {
09825 struct sip_request resp;
09826 char minse_str[20];
09827
09828 respprep(&resp, p, msg, req);
09829 append_date(&resp);
09830
09831 snprintf(minse_str, sizeof(minse_str), "%d", minse_int);
09832 add_header(&resp, "Min-SE", minse_str);
09833 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
09834 }
09835
09836
09837
09838
09839
09840 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req)
09841 {
09842 return __transmit_response(p, msg, req, req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL);
09843 }
09844
09845
09846 static void append_date(struct sip_request *req)
09847 {
09848 char tmpdat[256];
09849 struct tm tm;
09850 time_t t = time(NULL);
09851
09852 gmtime_r(&t, &tm);
09853 strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
09854 add_header(req, "Date", tmpdat);
09855 }
09856
09857
09858 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req)
09859 {
09860 struct sip_request resp;
09861 respprep(&resp, p, msg, req);
09862 append_date(&resp);
09863 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
09864 }
09865
09866
09867 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
09868 {
09869 struct sip_request resp;
09870 respprep(&resp, p, msg, req);
09871 add_header(&resp, "Accept", "application/sdp");
09872 return send_response(p, &resp, reliable, 0);
09873 }
09874
09875
09876 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)
09877 {
09878 struct sip_request resp;
09879 char tmp[512];
09880 int seqno = 0;
09881
09882 if (reliable && (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1)) {
09883 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
09884 return -1;
09885 }
09886
09887
09888 snprintf(tmp, sizeof(tmp), "Digest algorithm=MD5, realm=\"%s\", nonce=\"%s\"%s", sip_cfg.realm, randdata, stale ? ", stale=true" : "");
09889 respprep(&resp, p, msg, req);
09890 add_header(&resp, header, tmp);
09891 append_history(p, "AuthChal", "Auth challenge sent for %s - nc %d", p->username, p->noncecount);
09892 return send_response(p, &resp, reliable, seqno);
09893 }
09894
09895
09896 static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp)
09897 {
09898 int res;
09899
09900 if (!(res = with_sdp ? transmit_response_with_sdp(p, msg, req, XMIT_UNRELIABLE, FALSE) : transmit_response(p, msg, req))) {
09901 p->last_provisional = msg;
09902 update_provisional_keepalive(p, with_sdp);
09903 }
09904
09905 return res;
09906 }
09907
09908
09909 static int add_text(struct sip_request *req, const char *text)
09910 {
09911
09912 add_header(req, "Content-Type", "text/plain;charset=UTF-8");
09913 add_content(req, text);
09914 return 0;
09915 }
09916
09917
09918
09919
09920
09921 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode)
09922 {
09923 char tmp[256];
09924 int event;
09925 if (mode) {
09926
09927 if (digit == '*')
09928 event = 10;
09929 else if (digit == '#')
09930 event = 11;
09931 else if ((digit >= 'A') && (digit <= 'D'))
09932 event = 12 + digit - 'A';
09933 else
09934 event = atoi(&digit);
09935 snprintf(tmp, sizeof(tmp), "%d\r\n", event);
09936 add_header(req, "Content-Type", "application/dtmf");
09937 add_content(req, tmp);
09938 } else {
09939
09940 snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=%u\r\n", digit, duration);
09941 add_header(req, "Content-Type", "application/dtmf-relay");
09942 add_content(req, tmp);
09943 }
09944 return 0;
09945 }
09946
09947
09948
09949 static int add_vidupdate(struct sip_request *req)
09950 {
09951 const char *xml_is_a_huge_waste_of_space =
09952 "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
09953 " <media_control>\r\n"
09954 " <vc_primitive>\r\n"
09955 " <to_encoder>\r\n"
09956 " <picture_fast_update>\r\n"
09957 " </picture_fast_update>\r\n"
09958 " </to_encoder>\r\n"
09959 " </vc_primitive>\r\n"
09960 " </media_control>\r\n";
09961 add_header(req, "Content-Type", "application/media_control+xml");
09962 add_content(req, xml_is_a_huge_waste_of_space);
09963 return 0;
09964 }
09965
09966
09967 static void add_codec_to_sdp(const struct sip_pvt *p, int codec,
09968 struct ast_str **m_buf, struct ast_str **a_buf,
09969 int debug, int *min_packet_size)
09970 {
09971 int rtp_code;
09972 struct ast_format_list fmt;
09973
09974
09975 if (debug)
09976 ast_verbose("Adding codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
09977 if ((rtp_code = ast_rtp_lookup_code(p->rtp, 1, codec)) == -1)
09978 return;
09979
09980 if (p->rtp) {
09981 struct ast_codec_pref *pref = ast_rtp_codec_getpref(p->rtp);
09982 fmt = ast_codec_pref_getsize(pref, codec);
09983 } else
09984 return;
09985 ast_str_append(m_buf, 0, " %d", rtp_code);
09986 ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
09987 ast_rtp_lookup_mime_subtype(1, codec,
09988 ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0),
09989 ast_rtp_lookup_sample_rate(1, codec));
09990
09991 switch (codec) {
09992 case AST_FORMAT_G729A:
09993
09994 ast_str_append(a_buf, 0, "a=fmtp:%d annexb=no\r\n", rtp_code);
09995 break;
09996 case AST_FORMAT_G723_1:
09997
09998 ast_str_append(a_buf, 0, "a=fmtp:%d annexa=no\r\n", rtp_code);
09999 break;
10000 case AST_FORMAT_ILBC:
10001
10002 ast_str_append(a_buf, 0, "a=fmtp:%d mode=%d\r\n", rtp_code, fmt.cur_ms);
10003 break;
10004 case AST_FORMAT_SIREN7:
10005
10006 ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=32000\r\n", rtp_code);
10007 break;
10008 case AST_FORMAT_SIREN14:
10009
10010 ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=48000\r\n", rtp_code);
10011 break;
10012 }
10013
10014 if (fmt.cur_ms && (fmt.cur_ms < *min_packet_size))
10015 *min_packet_size = fmt.cur_ms;
10016
10017
10018 if ((*min_packet_size)==0 && fmt.cur_ms)
10019 *min_packet_size = fmt.cur_ms;
10020 }
10021
10022
10023
10024 static void add_vcodec_to_sdp(const struct sip_pvt *p, int codec,
10025 struct ast_str **m_buf, struct ast_str **a_buf,
10026 int debug, int *min_packet_size)
10027 {
10028 int rtp_code;
10029
10030 if (!p->vrtp)
10031 return;
10032
10033 if (debug)
10034 ast_verbose("Adding video codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
10035
10036 if ((rtp_code = ast_rtp_lookup_code(p->vrtp, 1, codec)) == -1)
10037 return;
10038
10039 ast_str_append(m_buf, 0, " %d", rtp_code);
10040 ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
10041 ast_rtp_lookup_mime_subtype(1, codec, 0),
10042 ast_rtp_lookup_sample_rate(1, codec));
10043
10044 }
10045
10046
10047 static void add_tcodec_to_sdp(const struct sip_pvt *p, int codec,
10048 struct ast_str **m_buf, struct ast_str **a_buf,
10049 int debug, int *min_packet_size)
10050 {
10051 int rtp_code;
10052
10053 if (!p->trtp)
10054 return;
10055
10056 if (debug)
10057 ast_verbose("Adding text codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
10058
10059 if ((rtp_code = ast_rtp_lookup_code(p->trtp, 1, codec)) == -1)
10060 return;
10061
10062 ast_str_append(m_buf, 0, " %d", rtp_code);
10063 ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
10064 ast_rtp_lookup_mime_subtype(1, codec, 0),
10065 ast_rtp_lookup_sample_rate(1, codec));
10066
10067
10068 if (codec == AST_FORMAT_T140RED) {
10069 ast_str_append(a_buf, 0, "a=fmtp:%d %d/%d/%d\r\n", rtp_code,
10070 ast_rtp_lookup_code(p->trtp, 1, AST_FORMAT_T140),
10071 ast_rtp_lookup_code(p->trtp, 1, AST_FORMAT_T140),
10072 ast_rtp_lookup_code(p->trtp, 1, AST_FORMAT_T140));
10073
10074 }
10075 }
10076
10077
10078
10079 static unsigned int t38_get_rate(enum ast_control_t38_rate rate)
10080 {
10081 switch (rate) {
10082 case AST_T38_RATE_2400:
10083 return 2400;
10084 case AST_T38_RATE_4800:
10085 return 4800;
10086 case AST_T38_RATE_7200:
10087 return 7200;
10088 case AST_T38_RATE_9600:
10089 return 9600;
10090 case AST_T38_RATE_12000:
10091 return 12000;
10092 case AST_T38_RATE_14400:
10093 return 14400;
10094 default:
10095 return 0;
10096 }
10097 }
10098
10099
10100 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
10101 struct ast_str **m_buf, struct ast_str **a_buf,
10102 int debug)
10103 {
10104 int rtp_code;
10105
10106 if (debug)
10107 ast_verbose("Adding non-codec 0x%x (%s) to SDP\n", format, ast_rtp_lookup_mime_subtype(0, format, 0));
10108 if ((rtp_code = ast_rtp_lookup_code(p->rtp, 0, format)) == -1)
10109 return;
10110
10111 ast_str_append(m_buf, 0, " %d", rtp_code);
10112 ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
10113 ast_rtp_lookup_mime_subtype(0, format, 0),
10114 ast_rtp_lookup_sample_rate(0, format));
10115 if (format == AST_RTP_DTMF)
10116 ast_str_append(a_buf, 0, "a=fmtp:%d 0-16\r\n", rtp_code);
10117 }
10118
10119
10120
10121
10122 static void get_our_media_address(struct sip_pvt *p, int needvideo,
10123 struct sockaddr_in *sin, struct sockaddr_in *vsin, struct sockaddr_in *tsin,
10124 struct sockaddr_in *dest, struct sockaddr_in *vdest)
10125 {
10126
10127 ast_rtp_get_us(p->rtp, sin);
10128 if (p->vrtp)
10129 ast_rtp_get_us(p->vrtp, vsin);
10130 if (p->trtp)
10131 ast_rtp_get_us(p->trtp, tsin);
10132
10133
10134
10135 if (p->redirip.sin_addr.s_addr) {
10136 dest->sin_port = p->redirip.sin_port;
10137 dest->sin_addr = p->redirip.sin_addr;
10138 } else {
10139 dest->sin_addr = p->ourip.sin_addr;
10140 dest->sin_port = sin->sin_port;
10141 }
10142 if (needvideo) {
10143
10144 if (p->vredirip.sin_addr.s_addr) {
10145 vdest->sin_addr = p->vredirip.sin_addr;
10146 vdest->sin_port = p->vredirip.sin_port;
10147 } else {
10148 vdest->sin_addr = p->ourip.sin_addr;
10149 vdest->sin_port = vsin->sin_port;
10150 }
10151 }
10152
10153 }
10154
10155
10156
10157
10158
10159
10160
10161 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38)
10162 {
10163 int alreadysent = 0;
10164
10165 struct sockaddr_in sin;
10166 struct sockaddr_in vsin;
10167 struct sockaddr_in tsin;
10168 struct sockaddr_in dest;
10169 struct sockaddr_in udptlsin;
10170 struct sockaddr_in vdest = { 0, };
10171 struct sockaddr_in tdest = { 0, };
10172 struct sockaddr_in udptldest = { 0, };
10173
10174
10175 char *version = "v=0\r\n";
10176 char subject[256];
10177 char owner[256];
10178 char connection[256];
10179 char *session_time = "t=0 0\r\n";
10180 char bandwidth[256] = "";
10181 char *hold = "";
10182 struct ast_str *m_audio = ast_str_alloca(256);
10183 struct ast_str *m_video = ast_str_alloca(256);
10184 struct ast_str *m_text = ast_str_alloca(256);
10185 struct ast_str *m_modem = ast_str_alloca(256);
10186 struct ast_str *a_audio = ast_str_alloca(1024);
10187 struct ast_str *a_video = ast_str_alloca(1024);
10188 struct ast_str *a_text = ast_str_alloca(1024);
10189 struct ast_str *a_modem = ast_str_alloca(1024);
10190
10191 int x;
10192 int capability = 0;
10193 int needaudio = FALSE;
10194 int needvideo = FALSE;
10195 int needtext = FALSE;
10196 int debug = sip_debug_test_pvt(p);
10197 int min_audio_packet_size = 0;
10198 int min_video_packet_size = 0;
10199 int min_text_packet_size = 0;
10200
10201 char codecbuf[SIPBUFSIZE];
10202 char buf[SIPBUFSIZE];
10203 char dummy_answer[256];
10204
10205
10206 snprintf(subject, sizeof(subject), "s=%s\r\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
10207
10208 if (!p->rtp) {
10209 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
10210 return AST_FAILURE;
10211 }
10212
10213
10214
10215
10216 if (!p->sessionid) {
10217 p->sessionid = (int)ast_random();
10218 p->sessionversion = p->sessionid;
10219 } else {
10220 if (oldsdp == FALSE)
10221 p->sessionversion++;
10222 }
10223
10224 if (add_audio) {
10225
10226 if ((p->jointcapability & AST_FORMAT_VIDEO_MASK) && !p->novideo) {
10227 if (p->vrtp) {
10228 needvideo = TRUE;
10229 ast_debug(2, "This call needs video offers!\n");
10230 } else
10231 ast_debug(2, "This call needs video offers, but there's no video support enabled!\n");
10232 }
10233
10234 if ((p->jointcapability & AST_FORMAT_TEXT_MASK) && !p->notext) {
10235 if (sipdebug_text)
10236 ast_verbose("We think we can do text\n");
10237 if (p->trtp) {
10238 if (sipdebug_text) {
10239 ast_verbose("And we have a text rtp object\n");
10240 }
10241 needtext = TRUE;
10242 ast_debug(2, "This call needs text offers! \n");
10243 } else {
10244 ast_debug(2, "This call needs text offers, but there's no text support enabled ! \n");
10245 }
10246 }
10247 }
10248
10249 get_our_media_address(p, needvideo, &sin, &vsin, &tsin, &dest, &vdest);
10250
10251 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));
10252 snprintf(connection, sizeof(connection), "c=IN IP4 %s\r\n", ast_inet_ntoa(dest.sin_addr));
10253
10254 if (add_audio) {
10255 capability = p->jointcapability;
10256
10257
10258 ast_debug(1, "** Our capability: %s Video flag: %s Text flag: %s\n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), capability),
10259 p->novideo ? "True" : "False", p->notext ? "True" : "False");
10260 ast_debug(1, "** Our prefcodec: %s \n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), p->prefcodec));
10261
10262
10263 if (capability & AST_FORMAT_AUDIO_MASK)
10264 needaudio = TRUE;
10265
10266 if (debug)
10267 ast_verbose("Audio is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(sin.sin_port));
10268
10269
10270
10271 if (needvideo) {
10272 ast_str_append(&m_video, 0, "m=video %d RTP/AVP", ntohs(vdest.sin_port));
10273
10274
10275 if (p->maxcallbitrate)
10276 snprintf(bandwidth, sizeof(bandwidth), "b=CT:%d\r\n", p->maxcallbitrate);
10277 if (debug)
10278 ast_verbose("Video is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(vdest.sin_port));
10279 }
10280
10281
10282
10283 if (needtext) {
10284 if (sipdebug_text)
10285 ast_verbose("Lets set up the text sdp\n");
10286
10287 if (p->tredirip.sin_addr.s_addr) {
10288 tdest.sin_addr = p->tredirip.sin_addr;
10289 tdest.sin_port = p->tredirip.sin_port;
10290 } else {
10291 tdest.sin_addr = p->ourip.sin_addr;
10292 tdest.sin_port = tsin.sin_port;
10293 }
10294 ast_str_append(&m_text, 0, "m=text %d RTP/AVP", ntohs(tdest.sin_port));
10295 if (debug)
10296 ast_verbose("Text is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(tsin.sin_port));
10297
10298 }
10299
10300
10301
10302
10303
10304
10305 ast_str_append(&m_audio, 0, "m=audio %d RTP/AVP", ntohs(dest.sin_port));
10306
10307 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_ONEDIR)
10308 hold = "a=recvonly\r\n";
10309 else if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_INACTIVE)
10310 hold = "a=inactive\r\n";
10311 else
10312 hold = "a=sendrecv\r\n";
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323 if (capability & p->prefcodec) {
10324 int codec = p->prefcodec & AST_FORMAT_AUDIO_MASK;
10325
10326 add_codec_to_sdp(p, codec, &m_audio, &a_audio, debug, &min_audio_packet_size);
10327 alreadysent |= codec;
10328 }
10329
10330
10331 for (x = 0; x < 32; x++) {
10332 int codec;
10333
10334 if (!(codec = ast_codec_pref_index(&p->prefs, x)))
10335 break;
10336
10337 if (!(capability & codec))
10338 continue;
10339
10340 if (alreadysent & codec)
10341 continue;
10342
10343 add_codec_to_sdp(p, codec, &m_audio, &a_audio, debug, &min_audio_packet_size);
10344 alreadysent |= codec;
10345 }
10346
10347
10348 for (x = 1; x <= (needtext ? AST_FORMAT_TEXT_MASK : (needvideo ? AST_FORMAT_VIDEO_MASK : AST_FORMAT_AUDIO_MASK)); x <<= 1) {
10349 if (!(capability & x))
10350 continue;
10351
10352 if (alreadysent & x)
10353 continue;
10354
10355 if (x & AST_FORMAT_AUDIO_MASK)
10356 add_codec_to_sdp(p, x, &m_audio, &a_audio, debug, &min_audio_packet_size);
10357 else if (x & AST_FORMAT_VIDEO_MASK)
10358 add_vcodec_to_sdp(p, x, &m_video, &a_video, debug, &min_video_packet_size);
10359 else if (x & AST_FORMAT_TEXT_MASK)
10360 add_tcodec_to_sdp(p, x, &m_text, &a_text, debug, &min_text_packet_size);
10361 }
10362
10363
10364 for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
10365 if (!(p->jointnoncodeccapability & x))
10366 continue;
10367
10368 add_noncodec_to_sdp(p, x, &m_audio, &a_audio, debug);
10369 }
10370
10371 ast_debug(3, "-- Done with adding codecs to SDP\n");
10372
10373 if (!p->owner || !ast_internal_timing_enabled(p->owner))
10374 ast_str_append(&a_audio, 0, "a=silenceSupp:off - - - -\r\n");
10375
10376 if (min_audio_packet_size)
10377 ast_str_append(&a_audio, 0, "a=ptime:%d\r\n", min_audio_packet_size);
10378
10379
10380 if (min_video_packet_size)
10381 ast_str_append(&a_video, 0, "a=ptime:%d\r\n", min_video_packet_size);
10382
10383
10384 if (min_text_packet_size)
10385 ast_str_append(&a_text, 0, "a=ptime:%d\r\n", min_text_packet_size);
10386
10387 if (m_audio->len - m_audio->used < 2 || m_video->len - m_video->used < 2 ||
10388 m_text->len - m_text->used < 2 || a_text->len - a_text->used < 2 ||
10389 a_audio->len - a_audio->used < 2 || a_video->len - a_video->used < 2)
10390 ast_log(LOG_WARNING, "SIP SDP may be truncated due to undersized buffer!!\n");
10391 }
10392
10393 if (add_t38) {
10394
10395 ast_udptl_get_us(p->udptl, &udptlsin);
10396
10397
10398 if (p->udptlredirip.sin_addr.s_addr) {
10399 udptldest.sin_port = p->udptlredirip.sin_port;
10400 udptldest.sin_addr = p->udptlredirip.sin_addr;
10401 } else {
10402 udptldest.sin_addr = p->ourip.sin_addr;
10403 udptldest.sin_port = udptlsin.sin_port;
10404 }
10405
10406 if (debug)
10407 ast_debug(1, "T.38 UDPTL is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(udptlsin.sin_port));
10408
10409
10410
10411
10412 ast_str_append(&m_modem, 0, "m=image %d udptl t38\r\n", ntohs(udptldest.sin_port));
10413
10414 ast_str_append(&a_modem, 0, "a=T38FaxVersion:%d\r\n", p->t38.our_parms.version);
10415 ast_str_append(&a_modem, 0, "a=T38MaxBitRate:%d\r\n", t38_get_rate(p->t38.our_parms.rate));
10416 if (p->t38.our_parms.fill_bit_removal) {
10417 ast_str_append(&a_modem, 0, "a=T38FaxFillBitRemoval\r\n");
10418 }
10419 if (p->t38.our_parms.transcoding_mmr) {
10420 ast_str_append(&a_modem, 0, "a=T38FaxTranscodingMMR\r\n");
10421 }
10422 if (p->t38.our_parms.transcoding_jbig) {
10423 ast_str_append(&a_modem, 0, "a=T38FaxTranscodingJBIG\r\n");
10424 }
10425 switch (p->t38.our_parms.rate_management) {
10426 case AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF:
10427 ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:transferredTCF\r\n");
10428 break;
10429 case AST_T38_RATE_MANAGEMENT_LOCAL_TCF:
10430 ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:localTCF\r\n");
10431 break;
10432 }
10433 ast_str_append(&a_modem, 0, "a=T38FaxMaxDatagram:%u\r\n", ast_udptl_get_local_max_datagram(p->udptl));
10434 switch (ast_udptl_get_error_correction_scheme(p->udptl)) {
10435 case UDPTL_ERROR_CORRECTION_NONE:
10436 break;
10437 case UDPTL_ERROR_CORRECTION_FEC:
10438 ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPFEC\r\n");
10439 break;
10440 case UDPTL_ERROR_CORRECTION_REDUNDANCY:
10441 ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPRedundancy\r\n");
10442 break;
10443 }
10444 }
10445
10446 if (needaudio)
10447 ast_str_append(&m_audio, 0, "\r\n");
10448 if (needvideo)
10449 ast_str_append(&m_video, 0, "\r\n");
10450 if (needtext)
10451 ast_str_append(&m_text, 0, "\r\n");
10452
10453 add_header(resp, "Content-Type", "application/sdp");
10454 add_content(resp, version);
10455 add_content(resp, owner);
10456 add_content(resp, subject);
10457 add_content(resp, connection);
10458 if (needvideo)
10459 add_content(resp, bandwidth);
10460 add_content(resp, session_time);
10461 if (needaudio) {
10462 add_content(resp, m_audio->str);
10463 add_content(resp, a_audio->str);
10464 add_content(resp, hold);
10465 } else if (p->offered_media[SDP_AUDIO].offered) {
10466 snprintf(dummy_answer, sizeof(dummy_answer), "m=audio 0 RTP/AVP %s\r\n", p->offered_media[SDP_AUDIO].text);
10467 add_content(resp, dummy_answer);
10468 }
10469 if (needvideo) {
10470 add_content(resp, m_video->str);
10471 add_content(resp, a_video->str);
10472 add_content(resp, hold);
10473 } else if (p->offered_media[SDP_VIDEO].offered) {
10474 snprintf(dummy_answer, sizeof(dummy_answer), "m=video 0 RTP/AVP %s\r\n", p->offered_media[SDP_VIDEO].text);
10475 add_content(resp, dummy_answer);
10476 }
10477 if (needtext) {
10478 add_content(resp, m_text->str);
10479 add_content(resp, a_text->str);
10480 add_content(resp, hold);
10481 } else if (p->offered_media[SDP_TEXT].offered) {
10482 snprintf(dummy_answer, sizeof(dummy_answer), "m=text 0 RTP/AVP %s\r\n", p->offered_media[SDP_TEXT].text);
10483 add_content(resp, dummy_answer);
10484 }
10485 if (add_t38) {
10486 add_content(resp, m_modem->str);
10487 add_content(resp, a_modem->str);
10488 } else if (p->offered_media[SDP_IMAGE].offered) {
10489 add_content(resp, "m=image 0 udptl t38\r\n");
10490 }
10491
10492
10493 p->lastrtprx = p->lastrtptx = time(NULL);
10494
10495 ast_debug(3, "Done building SDP. Settling with this capability: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, capability));
10496
10497 return AST_SUCCESS;
10498 }
10499
10500
10501 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
10502 {
10503 struct sip_request resp;
10504 int seqno;
10505
10506 if (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1) {
10507 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
10508 return -1;
10509 }
10510 respprep(&resp, p, msg, req);
10511 if (p->udptl) {
10512 add_sdp(&resp, p, 0, 0, 1);
10513 } else
10514 ast_log(LOG_ERROR, "Can't add SDP to response, since we have no UDPTL session allocated. Call-ID %s\n", p->callid);
10515 if (retrans && !p->pendinginvite)
10516 p->pendinginvite = seqno;
10517 return send_response(p, &resp, retrans, seqno);
10518 }
10519
10520
10521 static void copy_request(struct sip_request *dst, const struct sip_request *src)
10522 {
10523
10524
10525
10526 struct ast_str *duplicate = dst->data;
10527 struct ast_str *duplicate_content = dst->content;
10528
10529
10530
10531 memcpy(dst, src, sizeof(*dst));
10532 dst->data = duplicate;
10533 dst->content = duplicate_content;
10534
10535
10536 if (!dst->data && !(dst->data = ast_str_create(ast_str_strlen(src->data) + 1)))
10537 return;
10538 ast_str_copy_string(&dst->data, src->data);
10539
10540
10541 if (src->content) {
10542 if (!dst->content && !(dst->content = ast_str_create(ast_str_strlen(src->content) + 1)))
10543 return;
10544 ast_str_copy_string(&dst->content, src->content);
10545 }
10546 }
10547
10548
10549
10550
10551 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable, int oldsdp)
10552 {
10553 struct sip_request resp;
10554 int seqno;
10555 if (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1) {
10556 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
10557 return -1;
10558 }
10559 respprep(&resp, p, msg, req);
10560 if (p->rtp) {
10561 if (!p->autoframing && !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
10562 ast_debug(1, "Setting framing from config on incoming call\n");
10563 ast_rtp_codec_setpref(p->rtp, &p->prefs);
10564 }
10565 try_suggested_sip_codec(p);
10566 if (p->t38.state == T38_ENABLED) {
10567 add_sdp(&resp, p, oldsdp, TRUE, TRUE);
10568 } else {
10569 add_sdp(&resp, p, oldsdp, TRUE, FALSE);
10570 }
10571 } else
10572 ast_log(LOG_ERROR, "Can't add SDP to response, since we have no RTP session allocated. Call-ID %s\n", p->callid);
10573 if (reliable && !p->pendinginvite)
10574 p->pendinginvite = seqno;
10575 return send_response(p, &resp, reliable, seqno);
10576 }
10577
10578
10579 static int determine_firstline_parts(struct sip_request *req)
10580 {
10581 char *e = ast_skip_blanks(req->data->str);
10582 char *local_rlPart1;
10583
10584 if (!*e)
10585 return -1;
10586 req->rlPart1 = e - req->data->str;
10587 local_rlPart1 = e;
10588 e = ast_skip_nonblanks(e);
10589 if (*e)
10590 *e++ = '\0';
10591
10592 e = ast_skip_blanks(e);
10593 if ( !*e )
10594 return -1;
10595 ast_trim_blanks(e);
10596
10597 if (!strcasecmp(local_rlPart1, "SIP/2.0") ) {
10598 if (strlen(e) < 3)
10599 return -1;
10600 req->rlPart2 = e - req->data->str;
10601 } else {
10602 if ( *e == '<' ) {
10603 ast_debug(3, "Oops. Bogus uri in <> %s\n", e);
10604 e++;
10605 if (!*e)
10606 return -1;
10607 }
10608 req->rlPart2 = e - req->data->str;
10609 e = ast_skip_nonblanks(e);
10610 if (*e)
10611 *e++ = '\0';
10612 e = ast_skip_blanks(e);
10613 if (strcasecmp(e, "SIP/2.0") ) {
10614 ast_debug(3, "Skipping packet - Bad request protocol %s\n", e);
10615 return -1;
10616 }
10617 }
10618 return 1;
10619 }
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp)
10635 {
10636 struct sip_request req;
10637
10638 reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ? SIP_UPDATE : SIP_INVITE, 0, 1);
10639
10640 add_header(&req, "Allow", ALLOWED_METHODS);
10641 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
10642 if (sipdebug) {
10643 if (oldsdp == TRUE)
10644 add_header(&req, "X-asterisk-Info", "SIP re-invite (Session-Timers)");
10645 else
10646 add_header(&req, "X-asterisk-Info", "SIP re-invite (External RTP bridge)");
10647 }
10648
10649 if (p->do_history)
10650 append_history(p, "ReInv", "Re-invite sent");
10651 memset(p->offered_media, 0, sizeof(p->offered_media));
10652
10653 if (t38version)
10654 add_sdp(&req, p, oldsdp, FALSE, TRUE);
10655 else
10656 add_sdp(&req, p, oldsdp, TRUE, FALSE);
10657
10658
10659 initialize_initreq(p, &req);
10660 p->lastinvite = p->ocseq;
10661 ast_set_flag(&p->flags[0], SIP_OUTGOING);
10662
10663 return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
10664 }
10665
10666
10667 static char *remove_uri_parameters(char *uri)
10668 {
10669 char *atsign;
10670 atsign = strchr(uri, '@');
10671 if (!atsign)
10672 atsign = uri;
10673 atsign = strchr(atsign, ';');
10674 if (atsign)
10675 *atsign = '\0';
10676 return uri;
10677 }
10678
10679
10680 static void extract_uri(struct sip_pvt *p, struct sip_request *req)
10681 {
10682 char stripped[SIPBUFSIZE];
10683 char *c;
10684
10685 ast_copy_string(stripped, get_header(req, "Contact"), sizeof(stripped));
10686 c = get_in_brackets(stripped);
10687
10688 c = remove_uri_parameters(c);
10689 if (!ast_strlen_zero(c))
10690 ast_string_field_set(p, uri, c);
10691
10692 }
10693
10694
10695 static void build_contact(struct sip_pvt *p)
10696 {
10697
10698 int ourport = ntohs(p->ourip.sin_port);
10699
10700 if (!sip_standard_port(p->socket.type, ourport)) {
10701 if (p->socket.type == SIP_TRANSPORT_UDP)
10702 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);
10703 else
10704 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));
10705 } else {
10706 if (p->socket.type == SIP_TRANSPORT_UDP)
10707 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));
10708 else
10709 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));
10710 }
10711 }
10712
10713
10714 static void build_rpid(struct sip_pvt *p)
10715 {
10716 int send_pres_tags = TRUE;
10717 const char *privacy=NULL;
10718 const char *screen=NULL;
10719 char buf[256];
10720 const char *clid = default_callerid;
10721 const char *clin = NULL;
10722 const char *fromdomain;
10723
10724 if (!ast_strlen_zero(p->rpid) || !ast_strlen_zero(p->rpid_from))
10725 return;
10726
10727 if (p->owner && !ast_strlen_zero(p->owner->cid.cid_num))
10728 clid = p->owner->cid.cid_num;
10729 if (p->owner && p->owner->cid.cid_name)
10730 clin = p->owner->cid.cid_name;
10731 if (ast_strlen_zero(clin))
10732 clin = clid;
10733
10734 switch (p->callingpres) {
10735 case AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED:
10736 privacy = "off";
10737 screen = "no";
10738 break;
10739 case AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN:
10740 privacy = "off";
10741 screen = "yes";
10742 break;
10743 case AST_PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN:
10744 privacy = "off";
10745 screen = "no";
10746 break;
10747 case AST_PRES_ALLOWED_NETWORK_NUMBER:
10748 privacy = "off";
10749 screen = "yes";
10750 break;
10751 case AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED:
10752 privacy = "full";
10753 screen = "no";
10754 break;
10755 case AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN:
10756 privacy = "full";
10757 screen = "yes";
10758 break;
10759 case AST_PRES_PROHIB_USER_NUMBER_FAILED_SCREEN:
10760 privacy = "full";
10761 screen = "no";
10762 break;
10763 case AST_PRES_PROHIB_NETWORK_NUMBER:
10764 privacy = "full";
10765 screen = "yes";
10766 break;
10767 case AST_PRES_NUMBER_NOT_AVAILABLE:
10768 send_pres_tags = FALSE;
10769 break;
10770 default:
10771 ast_log(LOG_WARNING, "Unsupported callingpres (%d)\n", p->callingpres);
10772 if ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)
10773 privacy = "full";
10774 else
10775 privacy = "off";
10776 screen = "no";
10777 break;
10778 }
10779
10780 fromdomain = S_OR(p->fromdomain, ast_inet_ntoa(p->ourip.sin_addr));
10781
10782 snprintf(buf, sizeof(buf), "\"%s\" <sip:%s@%s>", clin, clid, fromdomain);
10783 if (send_pres_tags)
10784 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ";privacy=%s;screen=%s", privacy, screen);
10785 ast_string_field_set(p, rpid, buf);
10786
10787 ast_string_field_build(p, rpid_from, "\"%s\" <sip:%s@%s>;tag=%s", clin,
10788 S_OR(p->fromuser, clid),
10789 fromdomain, p->tag);
10790 }
10791
10792
10793 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod)
10794 {
10795 struct ast_str *invite = ast_str_alloca(256);
10796 char from[256];
10797 char to[256];
10798 char tmp_n[SIPBUFSIZE/2];
10799 char tmp_l[SIPBUFSIZE/2];
10800 const char *l = NULL;
10801 const char *n = NULL;
10802 const char *d = NULL;
10803 const char *urioptions = "";
10804 int ourport;
10805
10806 if (ast_test_flag(&p->flags[0], SIP_USEREQPHONE)) {
10807 const char *s = p->username;
10808
10809
10810
10811
10812
10813
10814 if (*s == '+')
10815 s++;
10816 for (; *s; s++) {
10817 if (!strchr(AST_DIGIT_ANYNUM, *s) )
10818 break;
10819 }
10820
10821 if (!*s)
10822 urioptions = ";user=phone";
10823 }
10824
10825
10826 snprintf(p->lastmsg, sizeof(p->lastmsg), "Init: %s", sip_methods[sipmethod].text);
10827
10828 d = S_OR(p->fromdomain, ast_inet_ntoa(p->ourip.sin_addr));
10829 if (p->owner) {
10830 l = p->owner->cid.cid_num;
10831 n = p->owner->cid.cid_name;
10832 }
10833
10834 if (!ast_test_flag(&p->flags[0], SIP_SENDRPID) &&
10835 ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)) {
10836 l = CALLERID_UNKNOWN;
10837 n = l;
10838 d = FROMDOMAIN_INVALID;
10839 }
10840 if (ast_strlen_zero(l))
10841 l = default_callerid;
10842 if (ast_strlen_zero(n))
10843 n = l;
10844
10845 if (!ast_strlen_zero(p->fromuser))
10846 l = p->fromuser;
10847 else
10848 ast_string_field_set(p, fromuser, l);
10849
10850
10851 if (!ast_strlen_zero(p->fromname))
10852 n = p->fromname;
10853 else
10854 ast_string_field_set(p, fromname, n);
10855
10856 if (sip_cfg.pedanticsipchecking) {
10857 ast_uri_encode(n, tmp_n, sizeof(tmp_n), 0);
10858 n = tmp_n;
10859 ast_uri_encode(l, tmp_l, sizeof(tmp_l), 0);
10860 l = tmp_l;
10861 }
10862
10863 ourport = ntohs(p->ourip.sin_port);
10864 if (!sip_standard_port(p->socket.type, ourport) && ast_strlen_zero(p->fromdomain))
10865 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s:%d>;tag=%s", n, l, d, ourport, p->tag);
10866 else
10867 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=%s", n, l, d, p->tag);
10868
10869
10870 if (!ast_strlen_zero(p->fullcontact)) {
10871
10872 ast_str_append(&invite, 0, "%s", p->fullcontact);
10873 } else {
10874
10875 ast_str_append(&invite, 0, "sip:");
10876 if (!ast_strlen_zero(p->username)) {
10877 n = p->username;
10878 if (sip_cfg.pedanticsipchecking) {
10879 ast_uri_encode(n, tmp_n, sizeof(tmp_n), 0);
10880 n = tmp_n;
10881 }
10882 ast_str_append(&invite, 0, "%s@", n);
10883 }
10884 ast_str_append(&invite, 0, "%s", p->tohost);
10885 if (p->portinuri)
10886 ast_str_append(&invite, 0, ":%d", ntohs(p->sa.sin_port));
10887 ast_str_append(&invite, 0, "%s", urioptions);
10888 }
10889
10890
10891 if (p->options && !ast_strlen_zero(p->options->uri_options))
10892 ast_str_append(&invite, 0, ";%s", p->options->uri_options);
10893
10894
10895
10896
10897 ast_string_field_set(p, uri, invite->str);
10898
10899 if (!ast_strlen_zero(p->todnid)) {
10900
10901 if (!strchr(p->todnid, '@')) {
10902
10903 snprintf(to, sizeof(to), "<sip:%s@%s>%s%s", p->todnid, p->tohost, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
10904 } else {
10905 snprintf(to, sizeof(to), "<sip:%s>%s%s", p->todnid, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
10906 }
10907 } else {
10908 if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->theirtag)) {
10909
10910 snprintf(to, sizeof(to), "<%s%s>;tag=%s", (strncasecmp(p->uri, "sip:", 4) ? "sip:" : ""), p->uri, p->theirtag);
10911 } else if (p->options && p->options->vxml_url) {
10912
10913 snprintf(to, sizeof(to), "<%s>;%s", p->uri, p->options->vxml_url);
10914 } else
10915 snprintf(to, sizeof(to), "<%s>", p->uri);
10916 }
10917
10918 init_req(req, sipmethod, p->uri);
10919
10920 snprintf(tmp_n, sizeof(tmp_n), "%d %s", ++p->ocseq, sip_methods[sipmethod].text);
10921
10922 add_header(req, "Via", p->via);
10923 add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
10924
10925
10926
10927
10928 add_route(req, p->route);
10929
10930
10931 if (ast_test_flag(&p->flags[0], SIP_SENDRPID) && (sipmethod == SIP_INVITE)) {
10932 build_rpid(p);
10933 add_header(req, "From", p->rpid_from);
10934 } else
10935 add_header(req, "From", from);
10936 add_header(req, "To", to);
10937 ast_string_field_set(p, exten, l);
10938 build_contact(p);
10939 add_header(req, "Contact", p->our_contact);
10940 add_header(req, "Call-ID", p->callid);
10941 add_header(req, "CSeq", tmp_n);
10942 if (!ast_strlen_zero(global_useragent))
10943 add_header(req, "User-Agent", global_useragent);
10944 if (!ast_strlen_zero(p->rpid))
10945 add_header(req, "Remote-Party-ID", p->rpid);
10946 }
10947
10948
10949
10950
10951
10952
10953
10954
10955 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init)
10956 {
10957 struct sip_request req;
10958 struct ast_variable *var;
10959
10960 req.method = sipmethod;
10961 if (init) {
10962 p->branch ^= ast_random();
10963 p->invite_branch = p->branch;
10964 build_via(p);
10965 }
10966 if (init > 1)
10967 initreqprep(&req, p, sipmethod);
10968 else
10969
10970 reqprep(&req, p, sipmethod, 0, init ? 0 : 1);
10971
10972 if (p->options && p->options->auth)
10973 add_header(&req, p->options->authheader, p->options->auth);
10974 append_date(&req);
10975 if (sipmethod == SIP_REFER) {
10976 if (p->refer) {
10977 char buf[SIPBUFSIZE];
10978 if (!ast_strlen_zero(p->refer->refer_to))
10979 add_header(&req, "Refer-To", p->refer->refer_to);
10980 if (!ast_strlen_zero(p->refer->referred_by)) {
10981 snprintf(buf, sizeof(buf), "%s <%s>", p->refer->referred_by_name, p->refer->referred_by);
10982 add_header(&req, "Referred-By", buf);
10983 }
10984 }
10985 } else if (sipmethod == SIP_SUBSCRIBE) {
10986 char buf[SIPBUFSIZE];
10987
10988 add_header(&req, "Event", "message-summary");
10989 add_header(&req, "Accept", "application/simple-message-summary");
10990 snprintf(buf, sizeof(buf), "%d", mwi_expiry);
10991 add_header(&req, "Expires", buf);
10992 }
10993
10994
10995
10996 if (p->options && !ast_strlen_zero(p->options->replaces)) {
10997 add_header(&req, "Replaces", p->options->replaces);
10998 add_header(&req, "Require", "replaces");
10999 }
11000
11001
11002 if (st_get_mode(p) == SESSION_TIMER_MODE_ORIGINATE) {
11003 char i2astr[10];
11004
11005 if (!p->stimer->st_interval)
11006 p->stimer->st_interval = st_get_se(p, TRUE);
11007
11008 p->stimer->st_active = TRUE;
11009
11010 snprintf(i2astr, sizeof(i2astr), "%d", p->stimer->st_interval);
11011 add_header(&req, "Session-Expires", i2astr);
11012 snprintf(i2astr, sizeof(i2astr), "%d", st_get_se(p, FALSE));
11013 add_header(&req, "Min-SE", i2astr);
11014 }
11015
11016 add_header(&req, "Allow", ALLOWED_METHODS);
11017 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
11018
11019 if(p->notify_headers) {
11020 char buf[512];
11021 for (var = p->notify_headers; var; var = var->next) {
11022 ast_copy_string(buf, var->value, sizeof(buf));
11023 add_header(&req, var->name, ast_unescape_semicolon(buf));
11024 }
11025 }
11026 if (p->options && p->options->addsipheaders && p->owner) {
11027 struct ast_channel *chan = p->owner;
11028 struct varshead *headp;
11029
11030 ast_channel_lock(chan);
11031
11032 headp = &chan->varshead;
11033
11034 if (!headp)
11035 ast_log(LOG_WARNING, "No Headp for the channel...ooops!\n");
11036 else {
11037 const struct ast_var_t *current;
11038 AST_LIST_TRAVERSE(headp, current, entries) {
11039
11040 if (!strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
11041 char *content, *end;
11042 const char *header = ast_var_value(current);
11043 char *headdup = ast_strdupa(header);
11044
11045
11046 if (*headdup == '"')
11047 headdup++;
11048 if ((content = strchr(headdup, ':'))) {
11049 *content++ = '\0';
11050 content = ast_skip_blanks(content);
11051
11052 end = content + strlen(content) -1;
11053 if (*end == '"')
11054 *end = '\0';
11055
11056 add_header(&req, headdup, content);
11057 if (sipdebug)
11058 ast_debug(1, "Adding SIP Header \"%s\" with content :%s: \n", headdup, content);
11059 }
11060 }
11061 }
11062 }
11063
11064 ast_channel_unlock(chan);
11065 }
11066 if (sdp) {
11067 memset(p->offered_media, 0, sizeof(p->offered_media));
11068 if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
11069 ast_debug(1, "T38 is in state %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
11070 add_sdp(&req, p, FALSE, FALSE, TRUE);
11071 } else if (p->rtp)
11072 add_sdp(&req, p, FALSE, TRUE, FALSE);
11073 }
11074
11075 if (!p->initreq.headers || init > 2)
11076 initialize_initreq(p, &req);
11077 p->lastinvite = p->ocseq;
11078 return send_request(p, &req, init ? XMIT_CRITICAL : XMIT_RELIABLE, p->ocseq);
11079 }
11080
11081
11082 static int sip_subscribe_mwi_do(const void *data)
11083 {
11084 struct sip_subscription_mwi *mwi = (struct sip_subscription_mwi*)data;
11085
11086 if (!mwi) {
11087 return -1;
11088 }
11089
11090 mwi->resub = -1;
11091 __sip_subscribe_mwi_do(mwi);
11092 ASTOBJ_UNREF(mwi, sip_subscribe_mwi_destroy);
11093
11094 return 0;
11095 }
11096
11097
11098 static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi)
11099 {
11100
11101 if (!mwi->dnsmgr) {
11102 char transport[MAXHOSTNAMELEN];
11103 snprintf(transport, sizeof(transport), "_%s._%s", get_srv_service(mwi->transport), get_srv_protocol(mwi->transport));
11104 ast_dnsmgr_lookup(mwi->hostname, &mwi->us, &mwi->dnsmgr, sip_cfg.srvlookup ? transport : NULL);
11105 }
11106
11107
11108 if (mwi->call) {
11109 transmit_invite(mwi->call, SIP_SUBSCRIBE, 0, 0);
11110 return 0;
11111 }
11112
11113
11114 if (!(mwi->call = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL))) {
11115 return -1;
11116 }
11117
11118 ref_proxy(mwi->call, obproxy_get(mwi->call, NULL));
11119
11120 if (!mwi->us.sin_port && mwi->portno) {
11121 mwi->us.sin_port = htons(mwi->portno);
11122 }
11123
11124
11125 if (create_addr(mwi->call, mwi->hostname, &mwi->us, 0)) {
11126 dialog_unlink_all(mwi->call, TRUE, TRUE);
11127 mwi->call = dialog_unref(mwi->call, "unref dialog after unlink_all");
11128 return 0;
11129 }
11130
11131 if (!mwi->dnsmgr && mwi->portno) {
11132 mwi->call->sa.sin_port = htons(mwi->portno);
11133 mwi->call->recv.sin_port = htons(mwi->portno);
11134 } else {
11135 mwi->portno = ntohs(mwi->call->sa.sin_port);
11136 }
11137
11138
11139 if (!ast_strlen_zero(mwi->authuser)) {
11140 ast_string_field_set(mwi->call, peername, mwi->authuser);
11141 ast_string_field_set(mwi->call, authname, mwi->authuser);
11142 ast_string_field_set(mwi->call, fromuser, mwi->authuser);
11143 } else {
11144 ast_string_field_set(mwi->call, peername, mwi->username);
11145 ast_string_field_set(mwi->call, authname, mwi->username);
11146 ast_string_field_set(mwi->call, fromuser, mwi->username);
11147 }
11148 ast_string_field_set(mwi->call, username, mwi->username);
11149 if (!ast_strlen_zero(mwi->secret)) {
11150 ast_string_field_set(mwi->call, peersecret, mwi->secret);
11151 }
11152 set_socket_transport(&mwi->call->socket, mwi->transport);
11153 mwi->call->socket.port = htons(mwi->portno);
11154 ast_sip_ouraddrfor(&mwi->call->sa.sin_addr, &mwi->call->ourip, mwi->call);
11155 build_contact(mwi->call);
11156 build_via(mwi->call);
11157 build_callid_pvt(mwi->call);
11158 ast_set_flag(&mwi->call->flags[0], SIP_OUTGOING);
11159
11160
11161 mwi->call->mwi = ASTOBJ_REF(mwi);
11162
11163
11164 transmit_invite(mwi->call, SIP_SUBSCRIBE, 0, 2);
11165
11166 return 0;
11167 }
11168
11169 static int find_calling_channel(struct ast_channel *c, void *data) {
11170 struct sip_pvt *p = data;
11171
11172 return (c->pbx &&
11173 (!strcasecmp(c->macroexten, p->exten) || !strcasecmp(c->exten, p->exten)) &&
11174 (sip_cfg.notifycid == IGNORE_CONTEXT || !strcasecmp(c->context, p->context)));
11175 }
11176
11177
11178 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout)
11179 {
11180 struct ast_str *tmp = ast_str_alloca(4000);
11181 char from[256], to[256];
11182 char *c, *mfrom, *mto;
11183 struct sip_request req;
11184 char hint[AST_MAX_EXTENSION];
11185 char *statestring = "terminated";
11186 const struct cfsubscription_types *subscriptiontype;
11187 enum state { NOTIFY_OPEN, NOTIFY_INUSE, NOTIFY_CLOSED } local_state = NOTIFY_OPEN;
11188 char *pidfstate = "--";
11189 char *pidfnote= "Ready";
11190
11191 memset(from, 0, sizeof(from));
11192 memset(to, 0, sizeof(to));
11193
11194 switch (state) {
11195 case (AST_EXTENSION_RINGING | AST_EXTENSION_INUSE):
11196 statestring = (sip_cfg.notifyringing) ? "early" : "confirmed";
11197 local_state = NOTIFY_INUSE;
11198 pidfstate = "busy";
11199 pidfnote = "Ringing";
11200 break;
11201 case AST_EXTENSION_RINGING:
11202 statestring = "early";
11203 local_state = NOTIFY_INUSE;
11204 pidfstate = "busy";
11205 pidfnote = "Ringing";
11206 break;
11207 case AST_EXTENSION_INUSE:
11208 statestring = "confirmed";
11209 local_state = NOTIFY_INUSE;
11210 pidfstate = "busy";
11211 pidfnote = "On the phone";
11212 break;
11213 case AST_EXTENSION_BUSY:
11214 statestring = "confirmed";
11215 local_state = NOTIFY_CLOSED;
11216 pidfstate = "busy";
11217 pidfnote = "On the phone";
11218 break;
11219 case AST_EXTENSION_UNAVAILABLE:
11220 statestring = "terminated";
11221 local_state = NOTIFY_CLOSED;
11222 pidfstate = "away";
11223 pidfnote = "Unavailable";
11224 break;
11225 case AST_EXTENSION_ONHOLD:
11226 statestring = "confirmed";
11227 local_state = NOTIFY_CLOSED;
11228 pidfstate = "busy";
11229 pidfnote = "On hold";
11230 break;
11231 case AST_EXTENSION_NOT_INUSE:
11232 default:
11233
11234 break;
11235 }
11236
11237 subscriptiontype = find_subscription_type(p->subscribed);
11238
11239
11240 if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, p->exten)) {
11241 char *hint2 = hint, *individual_hint = NULL;
11242 int hint_count = 0, unavailable_count = 0;
11243
11244 while ((individual_hint = strsep(&hint2, "&"))) {
11245 hint_count++;
11246
11247 if (ast_device_state(individual_hint) == AST_DEVICE_UNAVAILABLE)
11248 unavailable_count++;
11249 }
11250
11251
11252
11253
11254 if (hint_count > 0 && hint_count == unavailable_count) {
11255 local_state = NOTIFY_CLOSED;
11256 pidfstate = "away";
11257 pidfnote = "Not online";
11258 }
11259 }
11260
11261 ast_copy_string(from, get_header(&p->initreq, "From"), sizeof(from));
11262 c = get_in_brackets(from);
11263 if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
11264 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
11265 return -1;
11266 }
11267
11268 mfrom = remove_uri_parameters(c);
11269
11270 ast_copy_string(to, get_header(&p->initreq, "To"), sizeof(to));
11271 c = get_in_brackets(to);
11272 if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
11273 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
11274 return -1;
11275 }
11276 mto = remove_uri_parameters(c);
11277
11278 reqprep(&req, p, SIP_NOTIFY, 0, 1);
11279
11280
11281 add_header(&req, "Event", subscriptiontype->event);
11282 add_header(&req, "Content-Type", subscriptiontype->mediatype);
11283 switch(state) {
11284 case AST_EXTENSION_DEACTIVATED:
11285 if (timeout)
11286 add_header(&req, "Subscription-State", "terminated;reason=timeout");
11287 else {
11288 add_header(&req, "Subscription-State", "terminated;reason=probation");
11289 add_header(&req, "Retry-After", "60");
11290 }
11291 break;
11292 case AST_EXTENSION_REMOVED:
11293 add_header(&req, "Subscription-State", "terminated;reason=noresource");
11294 break;
11295 default:
11296 if (p->expiry)
11297 add_header(&req, "Subscription-State", "active");
11298 else
11299 add_header(&req, "Subscription-State", "terminated;reason=timeout");
11300 }
11301 switch (p->subscribed) {
11302 case XPIDF_XML:
11303 case CPIM_PIDF_XML:
11304 ast_str_append(&tmp, 0,
11305 "<?xml version=\"1.0\"?>\n"
11306 "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n"
11307 "<presence>\n");
11308 ast_str_append(&tmp, 0, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
11309 ast_str_append(&tmp, 0, "<atom id=\"%s\">\n", p->exten);
11310 ast_str_append(&tmp, 0, "<address uri=\"%s;user=ip\" priority=\"0.800000\">\n", mto);
11311 ast_str_append(&tmp, 0, "<status status=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "open" : (local_state == NOTIFY_INUSE) ? "inuse" : "closed");
11312 ast_str_append(&tmp, 0, "<msnsubstatus substatus=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "online" : (local_state == NOTIFY_INUSE) ? "onthephone" : "offline");
11313 ast_str_append(&tmp, 0, "</address>\n</atom>\n</presence>\n");
11314 break;
11315 case PIDF_XML:
11316 ast_str_append(&tmp, 0,
11317 "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"
11318 "<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);
11319 ast_str_append(&tmp, 0, "<pp:person><status>\n");
11320 if (pidfstate[0] != '-')
11321 ast_str_append(&tmp, 0, "<ep:activities><ep:%s/></ep:activities>\n", pidfstate);
11322 ast_str_append(&tmp, 0, "</status></pp:person>\n");
11323 ast_str_append(&tmp, 0, "<note>%s</note>\n", pidfnote);
11324 ast_str_append(&tmp, 0, "<tuple id=\"%s\">\n", p->exten);
11325 ast_str_append(&tmp, 0, "<contact priority=\"1\">%s</contact>\n", mto);
11326 if (pidfstate[0] == 'b')
11327 ast_str_append(&tmp, 0, "<status><basic>open</basic></status>\n");
11328 else
11329 ast_str_append(&tmp, 0, "<status><basic>%s</basic></status>\n", (local_state != NOTIFY_CLOSED) ? "open" : "closed");
11330 ast_str_append(&tmp, 0, "</tuple>\n</presence>\n");
11331 break;
11332 case DIALOG_INFO_XML:
11333 ast_str_append(&tmp, 0, "<?xml version=\"1.0\"?>\n");
11334 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);
11335 if ((state & AST_EXTENSION_RINGING) && sip_cfg.notifyringing) {
11336 const char *local_display = p->exten;
11337 char *local_target = mto;
11338
11339
11340
11341
11342 if (sip_cfg.notifycid) {
11343 struct ast_channel *caller = ast_channel_search_locked(find_calling_channel, p);
11344
11345 if (caller) {
11346 int need = strlen(caller->cid.cid_num) + strlen(p->fromdomain) + sizeof("sip:@");
11347 local_target = alloca(need);
11348 snprintf(local_target, need, "sip:%s@%s", caller->cid.cid_num, p->fromdomain);
11349 if (!(ast_strlen_zero(caller->cid.cid_name))) {
11350 local_display = ast_strdupa(caller->cid.cid_name);
11351 }
11352 ast_channel_unlock(caller);
11353 caller = NULL;
11354 }
11355
11356
11357 ast_str_append(&tmp, 0,
11358 "<dialog id=\"%s\" call-id=\"pickup-%s\" direction=\"recipient\">\n"
11359 "<remote>\n"
11360
11361
11362 "<identity display=\"%s\">%s</identity>\n"
11363 "<target uri=\"%s\"/>\n"
11364 "</remote>\n"
11365 "<local>\n"
11366 "<identity>%s</identity>\n"
11367 "<target uri=\"%s\"/>\n"
11368 "</local>\n",
11369 p->exten, p->callid, local_display, local_target, local_target, mto, mto);
11370 } else {
11371 ast_str_append(&tmp, 0, "<dialog id=\"%s\" direction=\"recipient\">\n", p->exten);
11372 }
11373 } else {
11374 ast_str_append(&tmp, 0, "<dialog id=\"%s\">\n", p->exten);
11375 }
11376 ast_str_append(&tmp, 0, "<state>%s</state>\n", statestring);
11377 if (state == AST_EXTENSION_ONHOLD) {
11378 ast_str_append(&tmp, 0, "<local>\n<target uri=\"%s\">\n"
11379 "<param pname=\"+sip.rendering\" pvalue=\"no\"/>\n"
11380 "</target>\n</local>\n", mto);
11381 }
11382 ast_str_append(&tmp, 0, "</dialog>\n</dialog-info>\n");
11383 break;
11384 case NONE:
11385 default:
11386 break;
11387 }
11388
11389 add_content(&req, tmp->str);
11390
11391 p->pendinginvite = p->ocseq;
11392
11393 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11394 }
11395
11396
11397
11398
11399
11400
11401
11402 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten)
11403 {
11404 struct sip_request req;
11405 struct ast_str *out = ast_str_alloca(500);
11406 int ourport = ntohs(p->ourip.sin_port);
11407 const char *exten = S_OR(vmexten, default_vmexten);
11408
11409 initreqprep(&req, p, SIP_NOTIFY);
11410 add_header(&req, "Event", "message-summary");
11411 add_header(&req, "Content-Type", default_notifymime);
11412 ast_str_append(&out, 0, "Messages-Waiting: %s\r\n", newmsgs ? "yes" : "no");
11413
11414 if (!ast_strlen_zero(p->fromdomain)) {
11415 ast_str_append(&out, 0, "Message-Account: sip:%s@%s\r\n", exten, p->fromdomain);
11416 } else if (!sip_standard_port(p->socket.type, ourport)) {
11417 if (p->socket.type == SIP_TRANSPORT_UDP) {
11418 ast_str_append(&out, 0, "Message-Account: sip:%s@%s:%d\r\n", exten, ast_inet_ntoa(p->ourip.sin_addr), ourport);
11419 } else {
11420 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));
11421 }
11422 } else {
11423 if (p->socket.type == SIP_TRANSPORT_UDP) {
11424 ast_str_append(&out, 0, "Message-Account: sip:%s@%s\r\n", exten, ast_inet_ntoa(p->ourip.sin_addr));
11425 } else {
11426 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));
11427 }
11428 }
11429
11430
11431
11432 ast_str_append(&out, 0, "Voice-Message: %d/%d%s\r\n",
11433 newmsgs, oldmsgs, (ast_test_flag(&p->flags[1], SIP_PAGE2_BUGGY_MWI) ? "" : " (0/0)"));
11434
11435 if (p->subscribed) {
11436 if (p->expiry)
11437 add_header(&req, "Subscription-State", "active");
11438 else
11439 add_header(&req, "Subscription-State", "terminated;reason=timeout");
11440 }
11441
11442 add_content(&req, out->str);
11443
11444 if (!p->initreq.headers)
11445 initialize_initreq(p, &req);
11446 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11447 }
11448
11449
11450 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate)
11451 {
11452 struct sip_request req;
11453 char tmp[SIPBUFSIZE/2];
11454
11455 reqprep(&req, p, SIP_NOTIFY, 0, 1);
11456 snprintf(tmp, sizeof(tmp), "refer;id=%d", cseq);
11457 add_header(&req, "Event", tmp);
11458 add_header(&req, "Subscription-state", terminate ? "terminated;reason=noresource" : "active");
11459 add_header(&req, "Content-Type", "message/sipfrag;version=2.0");
11460 add_header(&req, "Allow", ALLOWED_METHODS);
11461 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
11462
11463 snprintf(tmp, sizeof(tmp), "SIP/2.0 %s\r\n", message);
11464 add_content(&req, tmp);
11465
11466 if (!p->initreq.headers)
11467 initialize_initreq(p, &req);
11468
11469 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11470 }
11471
11472
11473 static int transmit_notify_custom(struct sip_pvt *p, struct ast_variable *vars) {
11474 struct sip_request req;
11475 struct ast_variable *var, *newvar;
11476
11477 initreqprep(&req, p, SIP_NOTIFY);
11478
11479
11480 p->notify_headers = newvar = ast_variable_new("Subscription-State", "terminated", "");
11481 add_header(&req, newvar->name, newvar->value);
11482 for (var = vars; var; var = var->next) {
11483 char buf[512];
11484
11485 if (!strcasecmp(var->name, "Content-Length")) {
11486 ast_debug(2, "Ignoring pair %s=%s\n", var->name, var->value);
11487 continue;
11488 }
11489
11490 ast_debug(2, " Adding pair %s=%s\n", var->name, var->value);
11491 ast_copy_string(buf, var->value, sizeof(buf));
11492 add_header(&req, var->name, ast_unescape_semicolon(buf));
11493 newvar->next = ast_variable_new(var->name, var->value, "");
11494 newvar = newvar->next;
11495 }
11496
11497 if (!p->initreq.headers) {
11498 initialize_initreq(p, &req);
11499 }
11500
11501 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11502 }
11503
11504 static int manager_sipnotify(struct mansession *s, const struct message *m)
11505 {
11506 const char *channame = astman_get_header(m, "Channel");
11507 struct ast_variable *vars = astman_get_variables(m);
11508 struct sip_pvt *p;
11509
11510 if (ast_strlen_zero(channame)) {
11511 astman_send_error(s, m, "SIPNotify requires a channel name");
11512 return 0;
11513 }
11514
11515 if (!strncasecmp(channame, "sip/", 4)) {
11516 channame += 4;
11517 }
11518
11519 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
11520 astman_send_error(s, m, "Unable to build sip pvt data for notify (memory/socket error)");
11521 return 0;
11522 }
11523
11524 if (create_addr(p, channame, NULL, 0)) {
11525
11526 dialog_unlink_all(p, TRUE, TRUE);
11527 dialog_unref(p, "unref dialog inside for loop" );
11528
11529 astman_send_error(s, m, "Could not create address");
11530 return 0;
11531 }
11532
11533
11534 ast_set_flag(&p->flags[0], SIP_OUTGOING);
11535
11536
11537 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
11538 build_via(p);
11539 ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
11540 build_callid_pvt(p);
11541 ao2_t_link(dialogs, p, "Linking in new name");
11542 dialog_ref(p, "bump the count of p, which transmit_sip_request will decrement.");
11543 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
11544
11545 if (!transmit_notify_custom(p, vars)) {
11546 astman_send_ack(s, m, "Notify Sent");
11547 } else {
11548 astman_send_error(s, m, "Unable to send notify");
11549 }
11550 ast_variables_destroy(vars);
11551 return 0;
11552 }
11553
11554 static char mandescr_sipnotify[] =
11555 "Description: Sends a SIP Notify event\n"
11556 "All parameters for this event must be specified in the body of this request\n"
11557 "via multiple Variable: name=value sequences.\n"
11558 "Variables: \n"
11559 " *Channel: <peername> Peer to receive the notify. Required.\n"
11560 " *Variable: <name>=<value> At least one variable pair must be specified.\n"
11561 " ActionID: <id> Action ID for this transaction. Will be returned.\n";
11562
11563 static const struct _map_x_s regstatestrings[] = {
11564 { REG_STATE_FAILED, "Failed" },
11565 { REG_STATE_UNREGISTERED, "Unregistered"},
11566 { REG_STATE_REGSENT, "Request Sent"},
11567 { REG_STATE_AUTHSENT, "Auth. Sent"},
11568 { REG_STATE_REGISTERED, "Registered"},
11569 { REG_STATE_REJECTED, "Rejected"},
11570 { REG_STATE_TIMEOUT, "Timeout"},
11571 { REG_STATE_NOAUTH, "No Authentication"},
11572 { -1, NULL }
11573 };
11574
11575
11576 static const char *regstate2str(enum sipregistrystate regstate)
11577 {
11578 return map_x_s(regstatestrings, regstate, "Unknown");
11579 }
11580
11581
11582
11583
11584
11585
11586
11587 static int sip_reregister(const void *data)
11588 {
11589
11590 struct sip_registry *r= (struct sip_registry *) data;
11591
11592
11593 if (!r)
11594 return 0;
11595
11596 if (r->call && r->call->do_history)
11597 append_history(r->call, "RegistryRenew", "Account: %s@%s", r->username, r->hostname);
11598
11599
11600 if (sipdebug)
11601 ast_log(LOG_NOTICE, " -- Re-registration for %s@%s\n", r->username, r->hostname);
11602
11603 r->expire = -1;
11604 r->expiry = r->configured_expiry;
11605 __sip_do_register(r);
11606 registry_unref(r, "unref the re-register scheduled event");
11607 return 0;
11608 }
11609
11610
11611 static int __sip_do_register(struct sip_registry *r)
11612 {
11613 int res;
11614
11615 res = transmit_register(r, SIP_REGISTER, NULL, NULL);
11616 return res;
11617 }
11618
11619
11620
11621
11622
11623
11624
11625 static int sip_reg_timeout(const void *data)
11626 {
11627
11628
11629 struct sip_registry *r = (struct sip_registry *)data;
11630 struct sip_pvt *p;
11631 int res;
11632
11633
11634 if (!r)
11635 return 0;
11636
11637 if (r->dnsmgr) {
11638
11639 ast_dnsmgr_refresh(r->dnsmgr);
11640 }
11641
11642 ast_log(LOG_NOTICE, " -- Registration for '%s@%s' timed out, trying again (Attempt #%d)\n", r->username, r->hostname, r->regattempts);
11643
11644
11645
11646
11647 if (r->call) {
11648
11649
11650 p = r->call;
11651 sip_pvt_lock(p);
11652 pvt_set_needdestroy(p, "registration timeout");
11653
11654 __sip_pretend_ack(p);
11655 sip_pvt_unlock(p);
11656
11657
11658
11659 if (p->registry)
11660 p->registry = registry_unref(p->registry, "p->registry unreffed");
11661 r->call = dialog_unref(r->call, "unrefing r->call");
11662 }
11663
11664 r->timeout = -1;
11665 if (global_regattempts_max && r->regattempts > global_regattempts_max) {
11666
11667
11668
11669 ast_log(LOG_NOTICE, " -- Giving up forever trying to register '%s@%s'\n", r->username, r->hostname);
11670 r->regstate = REG_STATE_FAILED;
11671 } else {
11672 r->regstate = REG_STATE_UNREGISTERED;
11673 res=transmit_register(r, SIP_REGISTER, NULL, NULL);
11674 }
11675 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));
11676 registry_unref(r, "unreffing registry_unref r");
11677 return 0;
11678 }
11679
11680
11681
11682
11683 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader)
11684 {
11685 struct sip_request req;
11686 char from[256];
11687 char to[256];
11688 char tmp[80];
11689 char addr[80];
11690 struct sip_pvt *p;
11691 struct sip_peer *peer = NULL;
11692 int res;
11693 char *fromdomain;
11694 char *domainport = NULL;
11695
11696
11697 if (r == NULL || ((auth == NULL) && (r->regstate == REG_STATE_REGSENT || r->regstate == REG_STATE_AUTHSENT))) {
11698 if (r) {
11699 ast_log(LOG_NOTICE, "Strange, trying to register %s@%s when registration already pending\n", r->username, r->hostname);
11700 }
11701 return 0;
11702 }
11703
11704 if (r->dnsmgr == NULL) {
11705 char transport[MAXHOSTNAMELEN];
11706 peer = find_peer(r->hostname, NULL, TRUE, FINDPEERS, FALSE, 0);
11707 snprintf(transport, sizeof(transport), "_%s._%s",get_srv_service(r->transport), get_srv_protocol(r->transport));
11708 ast_dnsmgr_lookup(peer ? peer->tohost : r->hostname, &r->us, &r->dnsmgr, sip_cfg.srvlookup ? transport : NULL);
11709 if (peer) {
11710 peer = unref_peer(peer, "removing peer ref for dnsmgr_lookup");
11711 }
11712 }
11713
11714 if (r->call) {
11715 if (!auth) {
11716 ast_log(LOG_WARNING, "Already have a REGISTER going on to %s@%s?? \n", r->username, r->hostname);
11717 return 0;
11718 } else {
11719 p = dialog_ref(r->call, "getting a copy of the r->call dialog in transmit_register");
11720 make_our_tag(p->tag, sizeof(p->tag));
11721 ast_string_field_set(p, theirtag, NULL);
11722 }
11723 } else {
11724
11725 if (!r->callid_valid) {
11726 build_callid_registry(r, internip.sin_addr, default_fromdomain);
11727 r->callid_valid = TRUE;
11728 }
11729
11730 if (!(p = sip_alloc( r->callid, NULL, 0, SIP_REGISTER, NULL))) {
11731 ast_log(LOG_WARNING, "Unable to allocate registration transaction (memory or socket error)\n");
11732 return 0;
11733 }
11734
11735 if (p->do_history)
11736 append_history(p, "RegistryInit", "Account: %s@%s", r->username, r->hostname);
11737
11738
11739 if (!r->us.sin_port && r->portno)
11740 r->us.sin_port = htons(r->portno);
11741
11742
11743 if (create_addr(p, S_OR(r->peername, r->hostname), &r->us, 0)) {
11744
11745
11746 dialog_unlink_all(p, TRUE, TRUE);
11747 p = dialog_unref(p, "unref dialog after unlink_all");
11748 if (r->timeout > -1) {
11749 AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
11750 registry_unref(_data, "del for REPLACE of registry ptr"),
11751 registry_unref(r, "object ptr dec when SCHED_REPLACE add failed"),
11752 registry_addref(r,"add for REPLACE registry ptr"));
11753 ast_log(LOG_WARNING, "Still have a registration timeout for %s@%s (create_addr() error), %d\n", r->username, r->hostname, r->timeout);
11754 } else {
11755 r->timeout = ast_sched_add(sched, global_reg_timeout * 1000, sip_reg_timeout, registry_addref(r, "add for REPLACE registry ptr"));
11756 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);
11757 }
11758 r->regattempts++;
11759 return 0;
11760 }
11761
11762
11763 ast_string_field_set(r, callid, p->callid);
11764 if (!r->dnsmgr && r->portno) {
11765 p->sa.sin_port = htons(r->portno);
11766 p->recv.sin_port = htons(r->portno);
11767 } else {
11768 r->portno = ntohs(p->sa.sin_port);
11769 }
11770 ast_set_flag(&p->flags[0], SIP_OUTGOING);
11771 r->call = dialog_ref(p, "copying dialog into registry r->call");
11772 p->registry = registry_addref(r, "transmit_register: addref to p->registry in transmit_register");
11773 if (!ast_strlen_zero(r->secret)) {
11774 ast_string_field_set(p, peersecret, r->secret);
11775 }
11776 if (!ast_strlen_zero(r->md5secret))
11777 ast_string_field_set(p, peermd5secret, r->md5secret);
11778
11779
11780 if (!ast_strlen_zero(r->authuser)) {
11781 ast_string_field_set(p, peername, r->authuser);
11782 ast_string_field_set(p, authname, r->authuser);
11783 } else if (!ast_strlen_zero(r->username)) {
11784 ast_string_field_set(p, peername, r->username);
11785 ast_string_field_set(p, authname, r->username);
11786 ast_string_field_set(p, fromuser, r->username);
11787 }
11788 if (!ast_strlen_zero(r->username))
11789 ast_string_field_set(p, username, r->username);
11790
11791 if (!ast_strlen_zero(r->callback))
11792 ast_string_field_set(p, exten, r->callback);
11793
11794
11795 set_socket_transport(&p->socket, r->transport);
11796 if (r->transport == SIP_TRANSPORT_TLS || r->transport == SIP_TRANSPORT_TCP) {
11797 p->socket.port = sip_tcp_desc.local_address.sin_port;
11798 }
11799
11800
11801
11802
11803
11804
11805 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
11806 build_contact(p);
11807 }
11808
11809
11810 if (auth == NULL) {
11811 if (r->timeout > -1)
11812 ast_log(LOG_WARNING, "Still have a registration timeout, #%d - deleting it\n", r->timeout);
11813 AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
11814 registry_unref(_data,"reg ptr unrefed from del in SCHED_REPLACE"),
11815 registry_unref(r,"reg ptr unrefed from add failure in SCHED_REPLACE"),
11816 registry_addref(r,"reg ptr reffed from add in SCHED_REPLACE"));
11817 ast_debug(1, "Scheduled a registration timeout for %s id #%d \n", r->hostname, r->timeout);
11818 }
11819
11820 if ((fromdomain = strchr(r->username, '@'))) {
11821
11822 fromdomain++ ;
11823
11824 snprintf(from, sizeof(from), "<sip:%s>;tag=%s", r->username, p->tag);
11825 if (!ast_strlen_zero(p->theirtag))
11826 snprintf(to, sizeof(to), "<sip:%s>;tag=%s", r->username, p->theirtag);
11827 else
11828 snprintf(to, sizeof(to), "<sip:%s>", r->username);
11829
11830
11831
11832 if (ast_strlen_zero(p->fromdomain)) {
11833 ast_string_field_set(p, fromdomain, fromdomain);
11834 }
11835 } else {
11836 snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->tag);
11837 if (!ast_strlen_zero(p->theirtag))
11838 snprintf(to, sizeof(to), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->theirtag);
11839 else
11840 snprintf(to, sizeof(to), "<sip:%s@%s>", r->username, p->tohost);
11841 }
11842
11843
11844
11845 if (!ast_strlen_zero(p->fromdomain)) {
11846 domainport = strrchr(p->fromdomain, ':');
11847 if (domainport) {
11848 *domainport++ = '\0';
11849 if (ast_strlen_zero(domainport))
11850 domainport = NULL;
11851 }
11852 if (domainport) {
11853 if (atoi(domainport) != STANDARD_SIP_PORT)
11854 snprintf(addr, sizeof(addr), "sip:%s:%s", p->fromdomain, domainport);
11855 else
11856 snprintf(addr, sizeof(addr), "sip:%s", p->fromdomain);
11857 } else {
11858 if (r->portno && r->portno != STANDARD_SIP_PORT)
11859 snprintf(addr, sizeof(addr), "sip:%s:%d", p->fromdomain, r->portno);
11860 else
11861 snprintf(addr, sizeof(addr), "sip:%s", p->fromdomain);
11862 }
11863 } else {
11864 if (r->portno && r->portno != STANDARD_SIP_PORT)
11865 snprintf(addr, sizeof(addr), "sip:%s:%d", r->hostname, r->portno);
11866 else
11867 snprintf(addr, sizeof(addr), "sip:%s", r->hostname);
11868 }
11869 ast_string_field_set(p, uri, addr);
11870
11871 p->branch ^= ast_random();
11872
11873 init_req(&req, sipmethod, addr);
11874
11875
11876 snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, sip_methods[sipmethod].text);
11877 p->ocseq = r->ocseq;
11878
11879 build_via(p);
11880 add_header(&req, "Via", p->via);
11881 add_header(&req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
11882 add_header(&req, "From", from);
11883 add_header(&req, "To", to);
11884 add_header(&req, "Call-ID", p->callid);
11885 add_header(&req, "CSeq", tmp);
11886 if (!ast_strlen_zero(global_useragent))
11887 add_header(&req, "User-Agent", global_useragent);
11888
11889
11890 if (auth)
11891 add_header(&req, authheader, auth);
11892 else if (!ast_strlen_zero(r->nonce)) {
11893 char digest[1024];
11894
11895
11896
11897
11898
11899
11900 if (sipdebug)
11901 ast_debug(1, " >>> Re-using Auth data for %s@%s\n", r->username, r->hostname);
11902 ast_string_field_set(p, realm, r->realm);
11903 ast_string_field_set(p, nonce, r->nonce);
11904 ast_string_field_set(p, domain, r->domain);
11905 ast_string_field_set(p, opaque, r->opaque);
11906 ast_string_field_set(p, qop, r->qop);
11907 p->noncecount = ++r->noncecount;
11908
11909 memset(digest, 0, sizeof(digest));
11910 if(!build_reply_digest(p, sipmethod, digest, sizeof(digest)))
11911 add_header(&req, "Authorization", digest);
11912 else
11913 ast_log(LOG_NOTICE, "No authorization available for authentication of registration to %s@%s\n", r->username, r->hostname);
11914
11915 }
11916
11917 snprintf(tmp, sizeof(tmp), "%d", r->expiry);
11918 add_header(&req, "Expires", tmp);
11919 add_header(&req, "Contact", p->our_contact);
11920
11921 initialize_initreq(p, &req);
11922 if (sip_debug_test_pvt(p)) {
11923 ast_verbose("REGISTER %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
11924 }
11925 r->regstate = auth ? REG_STATE_AUTHSENT : REG_STATE_REGSENT;
11926 r->regattempts++;
11927 ast_debug(4, "REGISTER attempt %d to %s@%s\n", r->regattempts, r->username, r->hostname);
11928 res = send_request(p, &req, XMIT_CRITICAL, p->ocseq);
11929 dialog_unref(p, "p is finished here at the end of transmit_register");
11930 return res;
11931 }
11932
11933
11934 static int transmit_message_with_text(struct sip_pvt *p, const char *text)
11935 {
11936 struct sip_request req;
11937
11938 reqprep(&req, p, SIP_MESSAGE, 0, 1);
11939 add_text(&req, text);
11940 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11941 }
11942
11943
11944 static int sip_refer_allocate(struct sip_pvt *p)
11945 {
11946 p->refer = ast_calloc(1, sizeof(struct sip_refer));
11947 return p->refer ? 1 : 0;
11948 }
11949
11950
11951
11952
11953
11954
11955 static int transmit_refer(struct sip_pvt *p, const char *dest)
11956 {
11957 struct sip_request req = {
11958 .headers = 0,
11959 };
11960 char from[256];
11961 const char *of;
11962 char *c;
11963 char referto[256];
11964 char *ttag, *ftag;
11965 char *theirtag = ast_strdupa(p->theirtag);
11966 int use_tls=FALSE;
11967
11968 if (sipdebug)
11969 ast_debug(1, "SIP transfer of %s to %s\n", p->callid, dest);
11970
11971
11972 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
11973 of = get_header(&p->initreq, "To");
11974 ttag = theirtag;
11975 ftag = p->tag;
11976 } else {
11977 of = get_header(&p->initreq, "From");
11978 ftag = theirtag;
11979 ttag = p->tag;
11980 }
11981
11982 ast_copy_string(from, of, sizeof(from));
11983 of = get_in_brackets(from);
11984 ast_string_field_set(p, from, of);
11985 if (!strncasecmp(of, "sip:", 4)) {
11986 of += 4;
11987 }else if (!strncasecmp(of, "sips:", 5)) {
11988 of += 5;
11989 use_tls = TRUE;
11990 } else {
11991 ast_log(LOG_NOTICE, "From address missing 'sip(s):', assuming sip:\n");
11992 }
11993
11994 if ((c = strchr(dest, '@')))
11995 c = NULL;
11996 else if ((c = strchr(of, '@')))
11997 *c++ = '\0';
11998 if (c)
11999 snprintf(referto, sizeof(referto), "<sip%s:%s@%s>", use_tls ? "s" : "", dest, c);
12000 else
12001 snprintf(referto, sizeof(referto), "<sip%s:%s>", use_tls ? "s" : "", dest);
12002
12003
12004 sip_refer_allocate(p);
12005 ast_copy_string(p->refer->refer_to, referto, sizeof(p->refer->refer_to));
12006 ast_copy_string(p->refer->referred_by, p->our_contact, sizeof(p->refer->referred_by));
12007 p->refer->status = REFER_SENT;
12008
12009 reqprep(&req, p, SIP_REFER, 0, 1);
12010
12011 add_header(&req, "Refer-To", referto);
12012 add_header(&req, "Allow", ALLOWED_METHODS);
12013 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
12014 if (!ast_strlen_zero(p->our_contact))
12015 add_header(&req, "Referred-By", p->our_contact);
12016
12017 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027 }
12028
12029
12030
12031 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration)
12032 {
12033 struct sip_request req;
12034
12035 reqprep(&req, p, SIP_INFO, 0, 1);
12036 add_digit(&req, digit, duration, (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_SHORTINFO));
12037 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
12038 }
12039
12040
12041 static int transmit_info_with_vidupdate(struct sip_pvt *p)
12042 {
12043 struct sip_request req;
12044
12045 reqprep(&req, p, SIP_INFO, 0, 1);
12046 add_vidupdate(&req);
12047 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
12048 }
12049
12050
12051
12052
12053 static int transmit_request(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
12054 {
12055 struct sip_request resp;
12056
12057 if (sipmethod == SIP_ACK)
12058 p->invitestate = INV_CONFIRMED;
12059
12060 reqprep(&resp, p, sipmethod, seqno, newbranch);
12061 if (sipmethod == SIP_CANCEL && p->answered_elsewhere)
12062 add_header(&resp, "Reason", "SIP;cause=200;text=\"Call completed elsewhere\"");
12063
12064 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
12065 }
12066
12067
12068 static void auth_headers(enum sip_auth_type code, char **header, char **respheader)
12069 {
12070 if (code == WWW_AUTH) {
12071 *header = "WWW-Authenticate";
12072 *respheader = "Authorization";
12073 } else if (code == PROXY_AUTH) {
12074 *header = "Proxy-Authenticate";
12075 *respheader = "Proxy-Authorization";
12076 } else {
12077 ast_verbose("-- wrong response code %d\n", code);
12078 *header = *respheader = "Invalid";
12079 }
12080 }
12081
12082
12083 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
12084 {
12085 struct sip_request resp;
12086
12087 reqprep(&resp, p, sipmethod, seqno, newbranch);
12088 if (!ast_strlen_zero(p->realm)) {
12089 char digest[1024];
12090
12091 memset(digest, 0, sizeof(digest));
12092 if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
12093 char *dummy, *response;
12094 enum sip_auth_type code = p->options ? p->options->auth_type : PROXY_AUTH;
12095 auth_headers(code, &dummy, &response);
12096 add_header(&resp, response, digest);
12097 } else
12098 ast_log(LOG_WARNING, "No authentication available for call %s\n", p->callid);
12099 }
12100
12101
12102 if (sipmethod == SIP_BYE) {
12103 char buf[10];
12104
12105 add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->hangupcause));
12106 snprintf(buf, sizeof(buf), "%d", p->hangupcause);
12107 add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
12108 }
12109
12110 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
12111 }
12112
12113
12114 static void destroy_association(struct sip_peer *peer)
12115 {
12116 int realtimeregs = ast_check_realtime("sipregs");
12117 char *tablename = (realtimeregs) ? "sipregs" : "sippeers";
12118
12119 if (!sip_cfg.ignore_regexpire) {
12120 if (peer->rt_fromcontact && sip_cfg.peer_rtupdate) {
12121 ast_update_realtime(tablename, "name", peer->name, "fullcontact", "", "ipaddr", "", "port", "", "regseconds", "0", peer->deprecated_username ? "username" : "defaultuser", "", "regserver", "", "useragent", "", "lastms", "", SENTINEL);
12122 } else {
12123 ast_db_del("SIP/Registry", peer->name);
12124 }
12125 }
12126 }
12127
12128 static void set_socket_transport(struct sip_socket *socket, int transport)
12129 {
12130
12131 if (socket->type != transport) {
12132 socket->fd = -1;
12133 socket->type = transport;
12134 if (socket->tcptls_session) {
12135 ao2_ref(socket->tcptls_session, -1);
12136 socket->tcptls_session = NULL;
12137 }
12138 }
12139 }
12140
12141
12142 static int expire_register(const void *data)
12143 {
12144 struct sip_peer *peer = (struct sip_peer *)data;
12145
12146 if (!peer)
12147 return 0;
12148
12149 peer->expire = -1;
12150 peer->portinuri = 0;
12151
12152 destroy_association(peer);
12153 set_socket_transport(&peer->socket, peer->default_outbound_transport);
12154
12155 if (peer->socket.tcptls_session) {
12156 ao2_ref(peer->socket.tcptls_session, -1);
12157 peer->socket.tcptls_session = NULL;
12158 }
12159
12160 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
12161 register_peer_exten(peer, FALSE);
12162 ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
12163
12164
12165
12166
12167 if (peer->is_realtime)
12168 ast_debug(3, "-REALTIME- peer expired registration. Name: %s. Realtime peer objects now %d\n", peer->name, rpeerobjs);
12169
12170 if (peer->selfdestruct ||
12171 ast_test_flag(&peer->flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
12172 unlink_peer_from_tables(peer);
12173 }
12174
12175
12176
12177 memset(&peer->addr, 0, sizeof(peer->addr));
12178
12179 unref_peer(peer, "removing peer ref for expire_register");
12180
12181 return 0;
12182 }
12183
12184
12185 static int sip_poke_peer_s(const void *data)
12186 {
12187 struct sip_peer *peer = (struct sip_peer *)data;
12188
12189 peer->pokeexpire = -1;
12190
12191 sip_poke_peer(peer, 0);
12192
12193 unref_peer(peer, "removing poke peer ref");
12194
12195 return 0;
12196 }
12197
12198
12199 static void reg_source_db(struct sip_peer *peer)
12200 {
12201 char data[256];
12202 struct in_addr in;
12203 int expire;
12204 int port;
12205 char *scan, *addr, *port_str, *expiry_str, *username, *contact;
12206
12207 if (peer->rt_fromcontact)
12208 return;
12209 if (ast_db_get("SIP/Registry", peer->name, data, sizeof(data)))
12210 return;
12211
12212 scan = data;
12213 addr = strsep(&scan, ":");
12214 port_str = strsep(&scan, ":");
12215 expiry_str = strsep(&scan, ":");
12216 username = strsep(&scan, ":");
12217 contact = scan;
12218
12219 if (!inet_aton(addr, &in))
12220 return;
12221
12222 if (port_str)
12223 port = atoi(port_str);
12224 else
12225 return;
12226
12227 if (expiry_str)
12228 expire = atoi(expiry_str);
12229 else
12230 return;
12231
12232 if (username)
12233 ast_string_field_set(peer, username, username);
12234 if (contact)
12235 ast_string_field_set(peer, fullcontact, contact);
12236
12237 ast_debug(2, "SIP Seeding peer from astdb: '%s' at %s@%s:%d for %d\n",
12238 peer->name, peer->username, ast_inet_ntoa(in), port, expire);
12239
12240 memset(&peer->addr, 0, sizeof(peer->addr));
12241 peer->addr.sin_family = AF_INET;
12242 peer->addr.sin_addr = in;
12243 peer->addr.sin_port = htons(port);
12244 if (sipsock < 0) {
12245
12246 AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, ast_random() % 5000 + 1, sip_poke_peer_s, peer,
12247 unref_peer(_data, "removing poke peer ref"),
12248 unref_peer(peer, "removing poke peer ref"),
12249 ref_peer(peer, "adding poke peer ref"));
12250 } else {
12251 sip_poke_peer(peer, 0);
12252 }
12253 AST_SCHED_REPLACE_UNREF(peer->expire, sched, (expire + 10) * 1000, expire_register, peer,
12254 unref_peer(_data, "remove registration ref"),
12255 unref_peer(peer, "remove registration ref"),
12256 ref_peer(peer, "add registration ref"));
12257 register_peer_exten(peer, TRUE);
12258 }
12259
12260
12261 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req)
12262 {
12263 char contact[SIPBUFSIZE];
12264 char *c;
12265
12266
12267 ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
12268 c = get_in_brackets(contact);
12269
12270
12271 ast_string_field_set(pvt, fullcontact, c);
12272
12273
12274 ast_string_field_set(pvt, okcontacturi, c);
12275
12276
12277
12278 return TRUE;
12279 }
12280
12281 static int __set_address_from_contact(const char *fullcontact, struct sockaddr_in *sin, int tcp)
12282 {
12283 struct hostent *hp;
12284 struct ast_hostent ahp;
12285 int port = STANDARD_SIP_PORT;
12286 char *host, *pt, *transport;
12287 char contact_buf[256];
12288 char *contact;
12289
12290
12291 ast_copy_string(contact_buf, fullcontact, sizeof(contact_buf));
12292 contact = contact_buf;
12293
12294
12295
12296
12297
12298
12299
12300
12301 if (parse_uri(contact, "sip:,sips:", &contact, NULL, &host, &pt, NULL, &transport)) {
12302 ast_log(LOG_WARNING, "Invalid contact uri %s (missing sip: or sips:), attempting to use anyway\n", fullcontact);
12303 }
12304
12305
12306 if (((get_transport_str2enum(transport) == SIP_TRANSPORT_TLS)) || !(strncasecmp(fullcontact, "sips", 4))) {
12307 port = port_str2int(pt, STANDARD_TLS_PORT);
12308 } else {
12309 port = port_str2int(pt, STANDARD_SIP_PORT);
12310 }
12311
12312
12313
12314
12315
12316
12317
12318
12319 hp = ast_gethostbyname(host, &ahp);
12320 if (!hp) {
12321 ast_log(LOG_WARNING, "Invalid host name in Contact: (can't resolve in DNS) : '%s'\n", host);
12322 return -1;
12323 }
12324 sin->sin_family = AF_INET;
12325 memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
12326 sin->sin_port = htons(port);
12327
12328 return 0;
12329 }
12330
12331
12332 static int set_address_from_contact(struct sip_pvt *pvt)
12333 {
12334 if (ast_test_flag(&pvt->flags[0], SIP_NAT_ROUTE)) {
12335
12336
12337
12338 pvt->sa = pvt->recv;
12339 return 0;
12340 }
12341
12342 return __set_address_from_contact(pvt->fullcontact, &pvt->sa, pvt->socket.type == SIP_TRANSPORT_TLS ? 1 : 0);
12343 }
12344
12345
12346 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *peer, struct sip_request *req)
12347 {
12348 char contact[SIPBUFSIZE];
12349 char data[SIPBUFSIZE];
12350 const char *expires = get_header(req, "Expires");
12351 int expire = atoi(expires);
12352 char *curi, *host, *pt, *transport;
12353 int port;
12354 int transport_type;
12355 const char *useragent;
12356 struct hostent *hp;
12357 struct ast_hostent ahp;
12358 struct sockaddr_in oldsin, testsin;
12359
12360
12361 ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
12362
12363 if (ast_strlen_zero(expires)) {
12364 char *s = strcasestr(contact, ";expires=");
12365 if (s) {
12366 expires = strsep(&s, ";");
12367 if (sscanf(expires + 9, "%30d", &expire) != 1)
12368 expire = default_expiry;
12369 } else {
12370
12371 expire = default_expiry;
12372 }
12373 }
12374
12375 copy_socket_data(&pvt->socket, &req->socket);
12376
12377
12378 curi = contact;
12379 if (strchr(contact, '<') == NULL)
12380 strsep(&curi, ";");
12381 curi = get_in_brackets(contact);
12382
12383
12384
12385
12386
12387 if (ast_strlen_zero(curi) && ast_strlen_zero(expires)) {
12388
12389 if (peer->expire > -1 && !ast_strlen_zero(peer->fullcontact))
12390 pvt->expiry = ast_sched_when(sched, peer->expire);
12391 return PARSE_REGISTER_QUERY;
12392 } else if (!strcasecmp(curi, "*") || !expire) {
12393
12394 memset(&peer->addr, 0, sizeof(peer->addr));
12395 set_socket_transport(&peer->socket, peer->default_outbound_transport);
12396
12397 AST_SCHED_DEL_UNREF(sched, peer->expire,
12398 unref_peer(peer, "remove register expire ref"));
12399
12400 destroy_association(peer);
12401
12402 register_peer_exten(peer, FALSE);
12403 ast_string_field_set(peer, fullcontact, "");
12404 ast_string_field_set(peer, useragent, "");
12405 peer->sipoptions = 0;
12406 peer->lastms = 0;
12407 peer->portinuri = 0;
12408 pvt->expiry = 0;
12409
12410 ast_verb(3, "Unregistered SIP '%s'\n", peer->name);
12411
12412 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unregistered\r\n", peer->name);
12413 return PARSE_REGISTER_UPDATE;
12414 }
12415
12416
12417 ast_string_field_set(peer, fullcontact, curi);
12418
12419
12420 ast_string_field_build(pvt, our_contact, "<%s>", curi);
12421
12422
12423 if (parse_uri(curi, "sip:,sips:", &curi, NULL, &host, &pt, NULL, &transport)) {
12424 ast_log(LOG_NOTICE, "Not a valid SIP contact (missing sip:) trying to use anyway\n");
12425 }
12426
12427
12428
12429 peer->portinuri = !ast_strlen_zero(pt) ? TRUE : FALSE;
12430
12431
12432 if ((transport_type = get_transport_str2enum(transport))) {
12433
12434
12435
12436
12437 port = port_str2int(pt, (transport_type == SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT);
12438 } else {
12439 port = port_str2int(pt, STANDARD_SIP_PORT);
12440 transport_type = pvt->socket.type;
12441 }
12442
12443
12444
12445
12446 if ((peer->socket.type != transport_type) && (peer->transports & transport_type)) {
12447 set_socket_transport(&peer->socket, transport_type);
12448 }
12449
12450 oldsin = peer->addr;
12451
12452
12453 if (peer->addr.sin_addr.s_addr) {
12454 ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
12455 }
12456
12457 if (!ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE)) {
12458
12459 ast_debug(1, "Store REGISTER's Contact header for call routing.\n");
12460
12461
12462 hp = ast_gethostbyname(host, &ahp);
12463 if (!hp) {
12464 ast_log(LOG_WARNING, "Invalid host '%s'\n", host);
12465 ast_string_field_set(peer, fullcontact, "");
12466 ast_string_field_set(pvt, our_contact, "");
12467 return PARSE_REGISTER_FAILED;
12468 }
12469 peer->addr.sin_family = AF_INET;
12470 memcpy(&peer->addr.sin_addr, hp->h_addr, sizeof(peer->addr.sin_addr));
12471 peer->addr.sin_port = htons(port);
12472 } else {
12473
12474
12475 ast_debug(1, "Store REGISTER's src-IP:port for call routing.\n");
12476 peer->addr = pvt->recv;
12477 }
12478
12479
12480 memcpy(&testsin.sin_addr, &peer->addr.sin_addr, sizeof(testsin.sin_addr));
12481 if (ast_apply_ha(global_contact_ha, &testsin) != AST_SENSE_ALLOW ||
12482 ast_apply_ha(peer->contactha, &testsin) != AST_SENSE_ALLOW) {
12483 ast_log(LOG_WARNING, "Host '%s' disallowed by contact ACL (violating IP %s)\n", host, ast_inet_ntoa(testsin.sin_addr));
12484 ast_string_field_set(peer, fullcontact, "");
12485 ast_string_field_set(pvt, our_contact, "");
12486 return PARSE_REGISTER_DENIED;
12487 }
12488
12489
12490
12491
12492 if ((peer->socket.type == pvt->socket.type) &&
12493 (peer->addr.sin_addr.s_addr == pvt->recv.sin_addr.s_addr) &&
12494 (peer->addr.sin_port == pvt->recv.sin_port)){
12495
12496 copy_socket_data(&peer->socket, &pvt->socket);
12497 }
12498
12499
12500 ao2_t_link(peers_by_ip, peer, "ao2_link into peers_by_ip table");
12501
12502
12503 peer->sipoptions = pvt->sipoptions;
12504
12505 if (!ast_strlen_zero(curi) && ast_strlen_zero(peer->username))
12506 ast_string_field_set(peer, username, curi);
12507
12508 AST_SCHED_DEL_UNREF(sched, peer->expire,
12509 unref_peer(peer, "remove register expire ref"));
12510
12511 if (expire > max_expiry)
12512 expire = max_expiry;
12513 if (expire < min_expiry)
12514 expire = min_expiry;
12515 if (peer->is_realtime && !ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
12516 peer->expire = -1;
12517 } else {
12518 peer->expire = ast_sched_add(sched, (expire + 10) * 1000, expire_register,
12519 ref_peer(peer, "add registration ref"));
12520 if (peer->expire == -1) {
12521 unref_peer(peer, "remote registration ref");
12522 }
12523 }
12524 pvt->expiry = expire;
12525 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);
12526
12527
12528
12529
12530 if (!peer->rt_fromcontact && (peer->socket.type & SIP_TRANSPORT_UDP))
12531 ast_db_put("SIP/Registry", peer->name, data);
12532 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));
12533
12534
12535 if (VERBOSITY_ATLEAST(2) && inaddrcmp(&peer->addr, &oldsin)) {
12536 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));
12537 }
12538 sip_poke_peer(peer, 0);
12539 register_peer_exten(peer, 1);
12540
12541
12542 useragent = get_header(req, "User-Agent");
12543 if (strcasecmp(useragent, peer->useragent)) {
12544 ast_string_field_set(peer, useragent, useragent);
12545 ast_verb(4, "Saved useragent \"%s\" for peer %s\n", peer->useragent, peer->name);
12546 }
12547 return PARSE_REGISTER_UPDATE;
12548 }
12549
12550
12551 static void free_old_route(struct sip_route *route)
12552 {
12553 struct sip_route *next;
12554
12555 while (route) {
12556 next = route->next;
12557 ast_free(route);
12558 route = next;
12559 }
12560 }
12561
12562
12563 static void list_route(struct sip_route *route)
12564 {
12565 if (!route)
12566 ast_verbose("list_route: no route\n");
12567 else {
12568 for (;route; route = route->next)
12569 ast_verbose("list_route: hop: <%s>\n", route->hop);
12570 }
12571 }
12572
12573
12574 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards)
12575 {
12576 struct sip_route *thishop, *head, *tail;
12577 int start = 0;
12578 int len;
12579 const char *rr, *contact, *c;
12580
12581
12582 if (p->route && p->route_persistant) {
12583 ast_debug(1, "build_route: Retaining previous route: <%s>\n", p->route->hop);
12584 return;
12585 }
12586
12587 if (p->route) {
12588 free_old_route(p->route);
12589 p->route = NULL;
12590 }
12591
12592
12593 p->route_persistant = 1;
12594
12595
12596
12597
12598
12599
12600 head = NULL;
12601 tail = head;
12602
12603 for (;;) {
12604
12605 rr = __get_header(req, "Record-Route", &start);
12606 if (*rr == '\0')
12607 break;
12608 for (; (rr = strchr(rr, '<')) ; rr += len) {
12609 ++rr;
12610 len = strcspn(rr, ">") + 1;
12611
12612 if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
12613
12614 ast_copy_string(thishop->hop, rr, len);
12615 ast_debug(2, "build_route: Record-Route hop: <%s>\n", thishop->hop);
12616
12617 if (backwards) {
12618
12619 thishop->next = head;
12620 head = thishop;
12621
12622 if (!tail)
12623 tail = thishop;
12624 } else {
12625 thishop->next = NULL;
12626
12627 if (tail)
12628 tail->next = thishop;
12629 else
12630 head = thishop;
12631 tail = thishop;
12632 }
12633 }
12634 }
12635 }
12636
12637
12638 if (!head || (!ast_strlen_zero(head->hop) && strstr(head->hop, ";lr") == NULL) ) {
12639
12640
12641 contact = get_header(req, "Contact");
12642 if (!ast_strlen_zero(contact)) {
12643 ast_debug(2, "build_route: Contact hop: %s\n", contact);
12644
12645 c = strchr(contact, '<');
12646 if (c) {
12647
12648 ++c;
12649 len = strcspn(c, ">") + 1;
12650 } else {
12651
12652 c = contact;
12653 len = strlen(contact) + 1;
12654 }
12655 if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
12656
12657 ast_copy_string(thishop->hop, c, len);
12658 thishop->next = NULL;
12659
12660 if (tail)
12661 tail->next = thishop;
12662 else
12663 head = thishop;
12664 }
12665 }
12666 }
12667
12668
12669 p->route = head;
12670
12671
12672 if (sip_debug_test_pvt(p))
12673 list_route(p->route);
12674 }
12675
12676
12677
12678
12679
12680
12681
12682 static void set_nonce_randdata(struct sip_pvt *p, int forceupdate)
12683 {
12684 if (p->stalenonce || forceupdate || ast_strlen_zero(p->randdata)) {
12685 ast_string_field_build(p, randdata, "%08lx", ast_random());
12686 p->stalenonce = 0;
12687 }
12688 }
12689
12690 AST_THREADSTORAGE(check_auth_buf);
12691 #define CHECK_AUTH_BUF_INITLEN 256
12692
12693
12694
12695
12696
12697
12698 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
12699 const char *secret, const char *md5secret, int sipmethod,
12700 char *uri, enum xmittype reliable, int ignore)
12701 {
12702 const char *response;
12703 char *reqheader, *respheader;
12704 const char *authtoken;
12705 char a1_hash[256];
12706 char resp_hash[256]="";
12707 char *c;
12708 int wrongnonce = FALSE;
12709 int good_response;
12710 const char *usednonce = p->randdata;
12711 struct ast_str *buf;
12712 int res;
12713
12714
12715 enum keys { K_RESP, K_URI, K_USER, K_NONCE, K_LAST };
12716 struct x {
12717 const char *key;
12718 const char *s;
12719 } *i, keys[] = {
12720 [K_RESP] = { "response=", "" },
12721 [K_URI] = { "uri=", "" },
12722 [K_USER] = { "username=", "" },
12723 [K_NONCE] = { "nonce=", "" },
12724 [K_LAST] = { NULL, NULL}
12725 };
12726
12727
12728 if (ast_strlen_zero(secret) && ast_strlen_zero(md5secret))
12729 return AUTH_SUCCESSFUL;
12730
12731
12732
12733 response = "401 Unauthorized";
12734
12735
12736
12737
12738
12739 auth_headers(WWW_AUTH, &respheader, &reqheader);
12740
12741 authtoken = get_header(req, reqheader);
12742 if (ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
12743
12744
12745 if (!reliable) {
12746
12747
12748 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
12749
12750 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12751 }
12752 return AUTH_CHALLENGE_SENT;
12753 } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
12754
12755 set_nonce_randdata(p, 1);
12756 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
12757
12758 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12759 return AUTH_CHALLENGE_SENT;
12760 }
12761
12762
12763
12764
12765
12766
12767 if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN)))
12768 return AUTH_SECRET_FAILED;
12769
12770
12771 res = ast_str_set(&buf, 0, "%s", authtoken);
12772
12773 if (res == AST_DYNSTR_BUILD_FAILED)
12774 return AUTH_SECRET_FAILED;
12775
12776 c = buf->str;
12777
12778 while(c && *(c = ast_skip_blanks(c)) ) {
12779 for (i = keys; i->key != NULL; i++) {
12780 const char *separator = ",";
12781
12782 if (strncasecmp(c, i->key, strlen(i->key)) != 0)
12783 continue;
12784
12785 c += strlen(i->key);
12786 if (*c == '"') {
12787 c++;
12788 separator = "\"";
12789 }
12790 i->s = c;
12791 strsep(&c, separator);
12792 break;
12793 }
12794 if (i->key == NULL)
12795 strsep(&c, " ,");
12796 }
12797
12798
12799 if (strcmp(username, keys[K_USER].s)) {
12800 ast_log(LOG_WARNING, "username mismatch, have <%s>, digest has <%s>\n",
12801 username, keys[K_USER].s);
12802
12803 return AUTH_USERNAME_MISMATCH;
12804 }
12805
12806
12807
12808 if (strcasecmp(p->randdata, keys[K_NONCE].s) || p->stalenonce) {
12809 wrongnonce = TRUE;
12810 usednonce = keys[K_NONCE].s;
12811 } else {
12812 p->stalenonce = 1;
12813 }
12814
12815 if (!ast_strlen_zero(md5secret))
12816 ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
12817 else {
12818 char a1[256];
12819 snprintf(a1, sizeof(a1), "%s:%s:%s", username, sip_cfg.realm, secret);
12820 ast_md5_hash(a1_hash, a1);
12821 }
12822
12823
12824 {
12825 char a2[256];
12826 char a2_hash[256];
12827 char resp[256];
12828
12829 snprintf(a2, sizeof(a2), "%s:%s", sip_methods[sipmethod].text,
12830 S_OR(keys[K_URI].s, uri));
12831 ast_md5_hash(a2_hash, a2);
12832 snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, usednonce, a2_hash);
12833 ast_md5_hash(resp_hash, resp);
12834 }
12835
12836 good_response = keys[K_RESP].s &&
12837 !strncasecmp(keys[K_RESP].s, resp_hash, strlen(resp_hash));
12838 if (wrongnonce) {
12839 if (good_response) {
12840 if (sipdebug)
12841 ast_log(LOG_NOTICE, "Correct auth, but based on stale nonce received from '%s'\n", get_header(req, "From"));
12842
12843 set_nonce_randdata(p, 0);
12844 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, TRUE);
12845 } else {
12846
12847 if (!req->ignore) {
12848 if (sipdebug)
12849 ast_log(LOG_NOTICE, "Bad authentication received from '%s'\n", get_header(req, "To"));
12850 set_nonce_randdata(p, 1);
12851 } else {
12852 if (sipdebug)
12853 ast_log(LOG_NOTICE, "Duplicate authentication received from '%s'\n", get_header(req, "To"));
12854 }
12855 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
12856 }
12857
12858
12859 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12860 return AUTH_CHALLENGE_SENT;
12861 }
12862 if (good_response) {
12863 append_history(p, "AuthOK", "Auth challenge successful for %s", username);
12864 return AUTH_SUCCESSFUL;
12865 }
12866
12867
12868
12869
12870
12871
12872 return AUTH_SECRET_FAILED;
12873 }
12874
12875
12876 static void sip_peer_hold(struct sip_pvt *p, int hold)
12877 {
12878 struct sip_peer *peer = find_peer(p->peername, NULL, 1, FINDALLDEVICES, FALSE, 0);
12879
12880 if (!peer)
12881 return;
12882
12883
12884 ast_atomic_fetchadd_int(&peer->onHold, (hold ? +1 : -1));
12885
12886
12887 ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
12888 unref_peer(peer, "sip_peer_hold: from find_peer operation");
12889
12890 return;
12891 }
12892
12893
12894 static void mwi_event_cb(const struct ast_event *event, void *userdata)
12895 {
12896 struct sip_peer *peer = userdata;
12897
12898 ao2_lock(peer);
12899 sip_send_mwi_to_peer(peer, event, 0);
12900 ao2_unlock(peer);
12901 }
12902
12903
12904
12905
12906 static int cb_extensionstate(char *context, char* exten, int state, void *data)
12907 {
12908 struct sip_pvt *p = data;
12909
12910 sip_pvt_lock(p);
12911
12912 switch(state) {
12913 case AST_EXTENSION_DEACTIVATED:
12914 case AST_EXTENSION_REMOVED:
12915 if (p->autokillid > -1 && sip_cancel_destroy(p))
12916 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
12917 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12918 ast_verb(2, "Extension state: Watcher for hint %s %s. Notify User %s\n", exten, state == AST_EXTENSION_DEACTIVATED ? "deactivated" : "removed", p->username);
12919 p->stateid = -1;
12920 p->subscribed = NONE;
12921 append_history(p, "Subscribestatus", "%s", state == AST_EXTENSION_REMOVED ? "HintRemoved" : "Deactivated");
12922 break;
12923 default:
12924 p->laststate = state;
12925 break;
12926 }
12927 if (p->subscribed != NONE) {
12928 if (!p->pendinginvite) {
12929 transmit_state_notify(p, state, 1, FALSE);
12930 } else {
12931
12932
12933 ast_set_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
12934 }
12935 }
12936 ast_verb(2, "Extension Changed %s[%s] new state %s for Notify User %s %s\n", exten, context, ast_extension_state2str(state), p->username,
12937 ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE) ? "(queued)" : "");
12938
12939 sip_pvt_unlock(p);
12940
12941 return 0;
12942 }
12943
12944
12945
12946
12947 static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable)
12948 {
12949
12950
12951 const char *response = "407 Proxy Authentication Required";
12952 const char *reqheader = "Proxy-Authorization";
12953 const char *respheader = "Proxy-Authenticate";
12954 const char *authtoken;
12955 struct ast_str *buf;
12956 char *c;
12957
12958
12959 enum keys { K_NONCE, K_LAST };
12960 struct x {
12961 const char *key;
12962 const char *s;
12963 } *i, keys[] = {
12964 [K_NONCE] = { "nonce=", "" },
12965 [K_LAST] = { NULL, NULL}
12966 };
12967
12968 if (sipmethod == SIP_REGISTER || sipmethod == SIP_SUBSCRIBE) {
12969 response = "401 Unauthorized";
12970 reqheader = "Authorization";
12971 respheader = "WWW-Authenticate";
12972 }
12973 authtoken = get_header(req, reqheader);
12974 if (req->ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
12975
12976
12977 transmit_response_with_auth(p, response, req, p->randdata, 0, respheader, 0);
12978
12979 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12980 return;
12981 } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
12982
12983 set_nonce_randdata(p, 1);
12984 transmit_response_with_auth(p, response, req, p->randdata, 0, respheader, 0);
12985
12986 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12987 return;
12988 }
12989
12990 if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN))) {
12991 transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
12992 return;
12993 }
12994
12995
12996 if (ast_str_set(&buf, 0, "%s", authtoken) == AST_DYNSTR_BUILD_FAILED) {
12997 transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
12998 return;
12999 }
13000
13001 c = buf->str;
13002
13003 while (c && *(c = ast_skip_blanks(c))) {
13004 for (i = keys; i->key != NULL; i++) {
13005 const char *separator = ",";
13006
13007 if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
13008 continue;
13009 }
13010
13011 c += strlen(i->key);
13012 if (*c == '"') {
13013 c++;
13014 separator = "\"";
13015 }
13016 i->s = c;
13017 strsep(&c, separator);
13018 break;
13019 }
13020 if (i->key == NULL) {
13021 strsep(&c, " ,");
13022 }
13023 }
13024
13025
13026 if (strcasecmp(p->randdata, keys[K_NONCE].s)) {
13027 if (!req->ignore) {
13028 set_nonce_randdata(p, 1);
13029 }
13030 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
13031
13032
13033 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13034 } else {
13035 transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
13036 }
13037 }
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053 static char *terminate_uri(char *uri)
13054 {
13055 char *t = uri;
13056 while (*t && *t > ' ' && *t != ';')
13057 t++;
13058 *t = '\0';
13059 return uri;
13060 }
13061
13062
13063
13064
13065
13066
13067 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
13068 struct sip_request *req, char *uri)
13069 {
13070 enum check_auth_result res = AUTH_NOT_FOUND;
13071 struct sip_peer *peer;
13072 char tmp[256];
13073 char *name, *c;
13074 char *domain;
13075
13076 terminate_uri(uri);
13077
13078 ast_copy_string(tmp, get_header(req, "To"), sizeof(tmp));
13079 if (sip_cfg.pedanticsipchecking)
13080 ast_uri_decode(tmp);
13081
13082 c = get_in_brackets(tmp);
13083 c = remove_uri_parameters(c);
13084
13085 if (!strncasecmp(c, "sip:", 4)) {
13086 name = c + 4;
13087 } else if (!strncasecmp(c, "sips:", 5)) {
13088 name = c + 5;
13089 } else {
13090 name = c;
13091 ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, ast_inet_ntoa(sin->sin_addr));
13092 }
13093
13094
13095
13096
13097
13098 if ((c = strchr(name, '@'))) {
13099 *c++ = '\0';
13100 domain = c;
13101 if ((c = strchr(domain, ':')))
13102 *c = '\0';
13103 if (!AST_LIST_EMPTY(&domain_list)) {
13104 if (!check_sip_domain(domain, NULL, 0)) {
13105 transmit_response(p, "404 Not found (unknown domain)", &p->initreq);
13106 return AUTH_UNKNOWN_DOMAIN;
13107 }
13108 }
13109 }
13110 c = strchr(name, ';');
13111 if (c)
13112 *c = '\0';
13113
13114 ast_string_field_set(p, exten, name);
13115 build_contact(p);
13116 if (req->ignore) {
13117
13118 const char *expires = get_header(req, "Expires");
13119 int expire = atoi(expires);
13120
13121 if (ast_strlen_zero(expires)) {
13122 if ((expires = strcasestr(get_header(req, "Contact"), ";expires="))) {
13123 expire = atoi(expires + 9);
13124 }
13125 }
13126 if (!ast_strlen_zero(expires) && expire == 0) {
13127 transmit_response_with_date(p, "200 OK", req);
13128 return 0;
13129 }
13130 }
13131 peer = find_peer(name, NULL, TRUE, FINDPEERS, FALSE, 0);
13132 if (!(peer && ast_apply_ha(peer->ha, sin))) {
13133
13134 if (peer) {
13135 unref_peer(peer, "register_verify: unref_peer: from find_peer operation");
13136 peer = NULL;
13137 res = AUTH_ACL_FAILED;
13138 } else
13139 res = AUTH_NOT_FOUND;
13140 }
13141
13142 if (peer) {
13143
13144
13145 if (p->rtp) {
13146 ast_rtp_codec_setpref(p->rtp, &peer->prefs);
13147 p->autoframing = peer->autoframing;
13148 }
13149 if (!peer->host_dynamic) {
13150 ast_log(LOG_ERROR, "Peer '%s' is trying to register, but not configured as host=dynamic\n", peer->name);
13151 res = AUTH_PEER_NOT_DYNAMIC;
13152 } else {
13153 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_NAT);
13154 if (ast_test_flag(&p->flags[1], SIP_PAGE2_REGISTERTRYING))
13155 transmit_response(p, "100 Trying", req);
13156 if (!(res = check_auth(p, req, peer->name, peer->secret, peer->md5secret, SIP_REGISTER, uri, XMIT_UNRELIABLE, req->ignore))) {
13157 if (sip_cancel_destroy(p))
13158 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
13159
13160 if (check_request_transport(peer, req)) {
13161 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
13162 transmit_response_with_date(p, "403 Forbidden", req);
13163 res = AUTH_BAD_TRANSPORT;
13164 } else {
13165
13166
13167
13168 switch (parse_register_contact(p, peer, req)) {
13169 case PARSE_REGISTER_DENIED:
13170 ast_log(LOG_WARNING, "Registration denied because of contact ACL\n");
13171 transmit_response_with_date(p, "603 Denied", req);
13172 peer->lastmsgssent = -1;
13173 res = 0;
13174 break;
13175 case PARSE_REGISTER_FAILED:
13176 ast_log(LOG_WARNING, "Failed to parse contact info\n");
13177 transmit_response_with_date(p, "400 Bad Request", req);
13178 peer->lastmsgssent = -1;
13179 res = 0;
13180 break;
13181 case PARSE_REGISTER_QUERY:
13182 ast_string_field_set(p, fullcontact, peer->fullcontact);
13183 transmit_response_with_date(p, "200 OK", req);
13184 peer->lastmsgssent = -1;
13185 res = 0;
13186 break;
13187 case PARSE_REGISTER_UPDATE:
13188 ast_string_field_set(p, fullcontact, peer->fullcontact);
13189 update_peer(peer, p->expiry);
13190
13191 transmit_response_with_date(p, "200 OK", req);
13192 if (!ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY))
13193 peer->lastmsgssent = -1;
13194 res = 0;
13195 break;
13196 }
13197 }
13198
13199 }
13200 }
13201 }
13202 if (!peer && sip_cfg.autocreatepeer) {
13203
13204 peer = temp_peer(name);
13205 if (peer) {
13206 ao2_t_link(peers, peer, "link peer into peer table");
13207 if (peer->addr.sin_addr.s_addr) {
13208 ao2_t_link(peers_by_ip, peer, "link peer into peers-by-ip table");
13209 }
13210
13211 if (sip_cancel_destroy(p))
13212 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
13213 switch (parse_register_contact(p, peer, req)) {
13214 case PARSE_REGISTER_DENIED:
13215 ast_log(LOG_WARNING, "Registration denied because of contact ACL\n");
13216 transmit_response_with_date(p, "403 Forbidden (ACL)", req);
13217 peer->lastmsgssent = -1;
13218 res = 0;
13219 break;
13220 case PARSE_REGISTER_FAILED:
13221 ast_log(LOG_WARNING, "Failed to parse contact info\n");
13222 transmit_response_with_date(p, "400 Bad Request", req);
13223 peer->lastmsgssent = -1;
13224 res = 0;
13225 break;
13226 case PARSE_REGISTER_QUERY:
13227 ast_string_field_set(p, fullcontact, peer->fullcontact);
13228 transmit_response_with_date(p, "200 OK", req);
13229 peer->lastmsgssent = -1;
13230 res = 0;
13231 break;
13232 case PARSE_REGISTER_UPDATE:
13233 ast_string_field_set(p, fullcontact, peer->fullcontact);
13234
13235 transmit_response_with_date(p, "200 OK", req);
13236 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));
13237 peer->lastmsgssent = -1;
13238 res = 0;
13239 break;
13240 }
13241 }
13242 }
13243 if (!peer && sip_cfg.alwaysauthreject) {
13244
13245
13246
13247 transmit_response(p, "100 Trying", req);
13248
13249 sched_yield();
13250 }
13251 if (!res) {
13252 ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
13253 }
13254 if (res < 0) {
13255 switch (res) {
13256 case AUTH_SECRET_FAILED:
13257
13258 transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
13259 if (global_authfailureevents)
13260 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",
13261 name, ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
13262 break;
13263 case AUTH_USERNAME_MISMATCH:
13264
13265
13266
13267
13268 case AUTH_NOT_FOUND:
13269 case AUTH_PEER_NOT_DYNAMIC:
13270 case AUTH_ACL_FAILED:
13271 if (sip_cfg.alwaysauthreject) {
13272 transmit_fake_auth_response(p, SIP_REGISTER, &p->initreq, XMIT_UNRELIABLE);
13273 if (global_authfailureevents) {
13274 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",
13275 name, res == AUTH_PEER_NOT_DYNAMIC ? "AUTH_PEER_NOT_DYNAMIC" : "URI_NOT_FOUND",
13276 ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
13277 }
13278 } else {
13279
13280 if (res == AUTH_PEER_NOT_DYNAMIC) {
13281 transmit_response(p, "403 Forbidden", &p->initreq);
13282 if (global_authfailureevents) {
13283 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
13284 "ChannelType: SIP\r\n"
13285 "Peer: SIP/%s\r\n"
13286 "PeerStatus: Rejected\r\n"
13287 "Cause: AUTH_PEER_NOT_DYNAMIC\r\n"
13288 "Address: %s\r\n"
13289 "Port: %d\r\n",
13290 name, ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
13291 }
13292 } else {
13293 transmit_response(p, "404 Not found", &p->initreq);
13294 if (global_authfailureevents) {
13295 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
13296 "ChannelType: SIP\r\n"
13297 "Peer: SIP/%s\r\n"
13298 "PeerStatus: Rejected\r\n"
13299 "Cause: %s\r\n"
13300 "Address: %s\r\n"
13301 "Port: %d\r\n",
13302 name,
13303 (res == AUTH_USERNAME_MISMATCH) ? "AUTH_USERNAME_MISMATCH" : "URI_NOT_FOUND",
13304 ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
13305 }
13306 }
13307 }
13308 break;
13309 case AUTH_BAD_TRANSPORT:
13310 default:
13311 break;
13312 }
13313 }
13314 if (peer)
13315 unref_peer(peer, "register_verify: unref_peer: tossing stack peer pointer at end of func");
13316
13317 return res;
13318 }
13319
13320
13321 static void sip_set_redirstr(struct sip_pvt *p, char *reason) {
13322
13323 if (!strcmp(reason, "unknown")) {
13324 ast_string_field_set(p, redircause, "UNKNOWN");
13325 } else if (!strcmp(reason, "user-busy")) {
13326 ast_string_field_set(p, redircause, "BUSY");
13327 } else if (!strcmp(reason, "no-answer")) {
13328 ast_string_field_set(p, redircause, "NOANSWER");
13329 } else if (!strcmp(reason, "unavailable")) {
13330 ast_string_field_set(p, redircause, "UNREACHABLE");
13331 } else if (!strcmp(reason, "unconditional")) {
13332 ast_string_field_set(p, redircause, "UNCONDITIONAL");
13333 } else if (!strcmp(reason, "time-of-day")) {
13334 ast_string_field_set(p, redircause, "UNKNOWN");
13335 } else if (!strcmp(reason, "do-not-disturb")) {
13336 ast_string_field_set(p, redircause, "UNKNOWN");
13337 } else if (!strcmp(reason, "deflection")) {
13338 ast_string_field_set(p, redircause, "UNKNOWN");
13339 } else if (!strcmp(reason, "follow-me")) {
13340 ast_string_field_set(p, redircause, "UNKNOWN");
13341 } else if (!strcmp(reason, "out-of-service")) {
13342 ast_string_field_set(p, redircause, "UNREACHABLE");
13343 } else if (!strcmp(reason, "away")) {
13344 ast_string_field_set(p, redircause, "UNREACHABLE");
13345 } else {
13346 ast_string_field_set(p, redircause, "UNKNOWN");
13347 }
13348 }
13349
13350
13351 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq)
13352 {
13353 char tmp[256], *exten, *rexten, *rdomain;
13354 char *params, *reason = NULL;
13355 struct sip_request *req;
13356
13357 req = oreq ? oreq : &p->initreq;
13358
13359 ast_copy_string(tmp, get_header(req, "Diversion"), sizeof(tmp));
13360 if (ast_strlen_zero(tmp))
13361 return 0;
13362
13363
13364
13365
13366 params = strchr(tmp, ';');
13367
13368 exten = get_in_brackets(tmp);
13369 if (!strncasecmp(exten, "sip:", 4)) {
13370 exten += 4;
13371 } else if (!strncasecmp(exten, "sips:", 5)) {
13372 exten += 5;
13373 } else {
13374 ast_log(LOG_WARNING, "Huh? Not an RDNIS SIP header (%s)?\n", exten);
13375 return -1;
13376 }
13377
13378
13379 if (params) {
13380 *params = '\0';
13381 params++;
13382 while (*params == ';' || *params == ' ')
13383 params++;
13384
13385 if ((reason = strcasestr(params, "reason="))) {
13386 reason+=7;
13387
13388 if (*reason == '"')
13389 ast_strip_quoted(reason, "\"", "\"");
13390 if (!ast_strlen_zero(reason)) {
13391 sip_set_redirstr(p, reason);
13392 if (p->owner) {
13393 pbx_builtin_setvar_helper(p->owner, "__PRIREDIRECTREASON", p->redircause);
13394 pbx_builtin_setvar_helper(p->owner, "__SIPREDIRECTREASON", reason);
13395 }
13396 }
13397 }
13398 }
13399
13400 rdomain = exten;
13401 rexten = strsep(&rdomain, "@");
13402 if (p->owner)
13403 pbx_builtin_setvar_helper(p->owner, "__SIPRDNISDOMAIN", rdomain);
13404
13405 if (sip_debug_test_pvt(p))
13406 ast_verbose("RDNIS for this call is is %s (reason %s)\n", exten, reason ? reason : "");
13407
13408 ast_string_field_set(p, rdnis, rexten);
13409
13410 return 0;
13411 }
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425 static int get_destination(struct sip_pvt *p, struct sip_request *oreq)
13426 {
13427 char tmp[256] = "", *uri, *a;
13428 char tmpf[256] = "", *from = NULL;
13429 struct sip_request *req;
13430 char *colon;
13431 char *decoded_uri;
13432
13433 req = oreq;
13434 if (!req)
13435 req = &p->initreq;
13436
13437
13438 if (req->rlPart2)
13439 ast_copy_string(tmp, REQ_OFFSET_TO_STR(req, rlPart2), sizeof(tmp));
13440
13441 if (sip_cfg.pedanticsipchecking)
13442 ast_uri_decode(tmp);
13443
13444 uri = get_in_brackets(tmp);
13445
13446 if (!strncasecmp(uri, "sip:", 4)) {
13447 uri += 4;
13448 } else if (!strncasecmp(uri, "sips:", 5)) {
13449 uri += 5;
13450 } else {
13451 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", uri);
13452 return -1;
13453 }
13454
13455
13456
13457
13458
13459 ast_copy_string(tmpf, get_header(req, "From"), sizeof(tmpf));
13460 if (!ast_strlen_zero(tmpf)) {
13461 if (sip_cfg.pedanticsipchecking)
13462 ast_uri_decode(tmpf);
13463 from = get_in_brackets(tmpf);
13464 }
13465
13466 if (!ast_strlen_zero(from)) {
13467 if (!strncasecmp(from, "sip:", 4)) {
13468 from += 4;
13469 } else if (!strncasecmp(from, "sips:", 5)) {
13470 from += 5;
13471 } else {
13472 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", from);
13473 return -1;
13474 }
13475 if ((a = strchr(from, '@')))
13476 *a++ = '\0';
13477 else
13478 a = from;
13479 from = strsep(&from, ";");
13480 a = strsep(&a, ";");
13481 ast_string_field_set(p, fromdomain, a);
13482 }
13483
13484
13485
13486
13487 if ((a = strchr(uri, '@'))) {
13488 *a++ = '\0';
13489 } else {
13490 a = uri;
13491 uri = "s";
13492 }
13493 colon = strchr(a, ':');
13494 if (colon)
13495 *colon = '\0';
13496
13497 uri = strsep(&uri, ";");
13498 a = strsep(&a, ";");
13499
13500 ast_string_field_set(p, domain, a);
13501
13502 if (!AST_LIST_EMPTY(&domain_list)) {
13503 char domain_context[AST_MAX_EXTENSION];
13504
13505 domain_context[0] = '\0';
13506 if (!check_sip_domain(p->domain, domain_context, sizeof(domain_context))) {
13507 if (!sip_cfg.allow_external_domains && (req->method == SIP_INVITE || req->method == SIP_REFER)) {
13508 ast_debug(1, "Got SIP %s to non-local domain '%s'; refusing request.\n", sip_methods[req->method].text, p->domain);
13509 return -2;
13510 }
13511 }
13512
13513
13514 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_HAVEPEERCONTEXT) && !ast_strlen_zero(domain_context))
13515 ast_string_field_set(p, context, domain_context);
13516 }
13517
13518
13519 if (req->method == SIP_SUBSCRIBE && !ast_strlen_zero(p->subscribecontext))
13520 ast_string_field_set(p, context, p->subscribecontext);
13521
13522 if (sip_debug_test_pvt(p))
13523 ast_verbose("Looking for %s in %s (domain %s)\n", uri, p->context, p->domain);
13524
13525
13526 if (req->method == SIP_SUBSCRIBE) {
13527 char hint[AST_MAX_EXTENSION];
13528 return (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, p->exten) ? 0 : -1);
13529 } else {
13530 decoded_uri = ast_strdupa(uri);
13531 ast_uri_decode(decoded_uri);
13532
13533
13534
13535
13536
13537 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)) ||
13538 !strcmp(decoded_uri, ast_pickup_ext())) {
13539 if (!oreq)
13540 ast_string_field_set(p, exten, decoded_uri);
13541 return 0;
13542 }
13543 }
13544
13545
13546 if((ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP) &&
13547 ast_canmatch_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from))) ||
13548 !strncmp(decoded_uri, ast_pickup_ext(), strlen(decoded_uri))) {
13549 return 1;
13550 }
13551
13552 return -1;
13553 }
13554
13555
13556
13557
13558 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag)
13559 {
13560 struct sip_pvt *sip_pvt_ptr;
13561 struct sip_pvt tmp_dialog = {
13562 .callid = callid,
13563 };
13564
13565 if (totag)
13566 ast_debug(4, "Looking for callid %s (fromtag %s totag %s)\n", callid, fromtag ? fromtag : "<no fromtag>", totag ? totag : "<no totag>");
13567
13568
13569
13570 sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find of dialog in dialogs table");
13571 if (sip_pvt_ptr) {
13572
13573 sip_pvt_lock(sip_pvt_ptr);
13574 if (sip_cfg.pedanticsipchecking) {
13575 unsigned char frommismatch = 0, tomismatch = 0;
13576
13577 if (ast_strlen_zero(fromtag)) {
13578 sip_pvt_unlock(sip_pvt_ptr);
13579 ast_debug(4, "Matched %s call for callid=%s - no from tag specified, pedantic check fails\n",
13580 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
13581 return NULL;
13582 }
13583
13584 if (ast_strlen_zero(totag)) {
13585 sip_pvt_unlock(sip_pvt_ptr);
13586 ast_debug(4, "Matched %s call for callid=%s - no to tag specified, pedantic check fails\n",
13587 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
13588 return NULL;
13589 }
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604 frommismatch = !!strcmp(fromtag, sip_pvt_ptr->theirtag);
13605 tomismatch = !!strcmp(totag, sip_pvt_ptr->tag);
13606
13607 if (frommismatch || tomismatch) {
13608 sip_pvt_unlock(sip_pvt_ptr);
13609 if (frommismatch) {
13610 ast_debug(4, "Matched %s call for callid=%s - pedantic from tag check fails; their tag is %s our tag is %s\n",
13611 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid,
13612 fromtag, sip_pvt_ptr->theirtag);
13613 }
13614 if (tomismatch) {
13615 ast_debug(4, "Matched %s call for callid=%s - pedantic to tag check fails; their tag is %s our tag is %s\n",
13616 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid,
13617 totag, sip_pvt_ptr->tag);
13618 }
13619 return NULL;
13620 }
13621 }
13622
13623 if (totag)
13624 ast_debug(4, "Matched %s call - their tag is %s Our tag is %s\n",
13625 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING",
13626 sip_pvt_ptr->theirtag, sip_pvt_ptr->tag);
13627
13628
13629 while (sip_pvt_ptr->owner && ast_channel_trylock(sip_pvt_ptr->owner)) {
13630 sip_pvt_unlock(sip_pvt_ptr);
13631 usleep(1);
13632 sip_pvt_lock(sip_pvt_ptr);
13633 }
13634 }
13635
13636 return sip_pvt_ptr;
13637 }
13638
13639
13640
13641
13642
13643
13644
13645
13646 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req)
13647 {
13648
13649 const char *p_referred_by = NULL;
13650 char *h_refer_to = NULL;
13651 char *h_referred_by = NULL;
13652 char *refer_to;
13653 const char *p_refer_to;
13654 char *referred_by_uri = NULL;
13655 char *ptr;
13656 struct sip_request *req = NULL;
13657 const char *transfer_context = NULL;
13658 struct sip_refer *referdata;
13659
13660
13661 req = outgoing_req;
13662 referdata = transferer->refer;
13663
13664 if (!req)
13665 req = &transferer->initreq;
13666
13667 p_refer_to = get_header(req, "Refer-To");
13668 if (ast_strlen_zero(p_refer_to)) {
13669 ast_log(LOG_WARNING, "Refer-To Header missing. Skipping transfer.\n");
13670 return -2;
13671 }
13672 h_refer_to = ast_strdupa(p_refer_to);
13673 refer_to = get_in_brackets(h_refer_to);
13674 if (sip_cfg.pedanticsipchecking)
13675 ast_uri_decode(refer_to);
13676
13677 if (!strncasecmp(refer_to, "sip:", 4)) {
13678 refer_to += 4;
13679 } else if (!strncasecmp(refer_to, "sips:", 5)) {
13680 refer_to += 5;
13681 } else {
13682 ast_log(LOG_WARNING, "Can't transfer to non-sip: URI. (Refer-to: %s)?\n", refer_to);
13683 return -3;
13684 }
13685
13686
13687 p_referred_by = get_header(req, "Referred-By");
13688
13689
13690 if (transferer->owner) {
13691 struct ast_channel *peer = ast_bridged_channel(transferer->owner);
13692 if (peer) {
13693 pbx_builtin_setvar_helper(peer, "SIPREFERRINGCONTEXT", transferer->context);
13694 pbx_builtin_setvar_helper(peer, "SIPREFERREDBYHDR", p_referred_by);
13695 }
13696 }
13697
13698 if (!ast_strlen_zero(p_referred_by)) {
13699 char *lessthan;
13700 h_referred_by = ast_strdupa(p_referred_by);
13701 if (sip_cfg.pedanticsipchecking)
13702 ast_uri_decode(h_referred_by);
13703
13704
13705 ast_copy_string(referdata->referred_by_name, h_referred_by, sizeof(referdata->referred_by_name));
13706 if ((lessthan = strchr(referdata->referred_by_name, '<'))) {
13707 *(lessthan - 1) = '\0';
13708 }
13709
13710 referred_by_uri = get_in_brackets(h_referred_by);
13711 if (!strncasecmp(referred_by_uri, "sip:", 4)) {
13712 referred_by_uri += 4;
13713 } else if (!strncasecmp(referred_by_uri, "sips:", 5)) {
13714 referred_by_uri += 5;
13715 } else {
13716 ast_log(LOG_WARNING, "Huh? Not a sip: header (Referred-by: %s). Skipping.\n", referred_by_uri);
13717 referred_by_uri = NULL;
13718 }
13719 }
13720
13721
13722 if ((ptr = strcasestr(refer_to, "replaces="))) {
13723 char *to = NULL, *from = NULL;
13724
13725
13726 referdata->attendedtransfer = 1;
13727 ast_copy_string(referdata->replaces_callid, ptr+9, sizeof(referdata->replaces_callid));
13728 ast_uri_decode(referdata->replaces_callid);
13729 if ((ptr = strchr(referdata->replaces_callid, ';'))) {
13730 *ptr++ = '\0';
13731 }
13732
13733 if (ptr) {
13734
13735 to = strcasestr(ptr, "to-tag=");
13736 from = strcasestr(ptr, "from-tag=");
13737 }
13738
13739
13740 if (to) {
13741 ptr = to + 7;
13742 if ((to = strchr(ptr, '&')))
13743 *to = '\0';
13744 if ((to = strchr(ptr, ';')))
13745 *to = '\0';
13746 ast_copy_string(referdata->replaces_callid_totag, ptr, sizeof(referdata->replaces_callid_totag));
13747 }
13748
13749 if (from) {
13750 ptr = from + 9;
13751 if ((to = strchr(ptr, '&')))
13752 *to = '\0';
13753 if ((to = strchr(ptr, ';')))
13754 *to = '\0';
13755 ast_copy_string(referdata->replaces_callid_fromtag, ptr, sizeof(referdata->replaces_callid_fromtag));
13756 }
13757
13758 if (!sip_cfg.pedanticsipchecking)
13759 ast_debug(2, "Attended transfer: Will use Replace-Call-ID : %s (No check of from/to tags)\n", referdata->replaces_callid );
13760 else
13761 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>" );
13762 }
13763
13764 if ((ptr = strchr(refer_to, '@'))) {
13765 char *urioption = NULL, *domain;
13766 *ptr++ = '\0';
13767
13768 if ((urioption = strchr(ptr, ';')))
13769 *urioption++ = '\0';
13770
13771 domain = ptr;
13772 if ((ptr = strchr(domain, ':')))
13773 *ptr = '\0';
13774
13775
13776 ast_copy_string(referdata->refer_to_domain, domain, sizeof(referdata->refer_to_domain));
13777 if (urioption)
13778 ast_copy_string(referdata->refer_to_urioption, urioption, sizeof(referdata->refer_to_urioption));
13779 }
13780
13781 if ((ptr = strchr(refer_to, ';')))
13782 *ptr = '\0';
13783 ast_copy_string(referdata->refer_to, refer_to, sizeof(referdata->refer_to));
13784
13785 if (referred_by_uri) {
13786 if ((ptr = strchr(referred_by_uri, ';')))
13787 *ptr = '\0';
13788 ast_copy_string(referdata->referred_by, referred_by_uri, sizeof(referdata->referred_by));
13789 } else {
13790 referdata->referred_by[0] = '\0';
13791 }
13792
13793
13794 if (transferer->owner)
13795 transfer_context = pbx_builtin_getvar_helper(transferer->owner, "TRANSFER_CONTEXT");
13796
13797
13798 if (ast_strlen_zero(transfer_context)) {
13799 transfer_context = S_OR(transferer->owner->macrocontext,
13800 S_OR(transferer->context, sip_cfg.default_context));
13801 }
13802
13803 ast_copy_string(referdata->refer_to_context, transfer_context, sizeof(referdata->refer_to_context));
13804
13805
13806 if (referdata->attendedtransfer || ast_exists_extension(NULL, transfer_context, refer_to, 1, NULL) ) {
13807 if (sip_debug_test_pvt(transferer)) {
13808 ast_verbose("SIP transfer to extension %s@%s by %s\n", refer_to, transfer_context, referred_by_uri);
13809 }
13810
13811 return 0;
13812 }
13813 if (sip_debug_test_pvt(transferer))
13814 ast_verbose("Failed SIP Transfer to non-existing extension %s in context %s\n n", refer_to, transfer_context);
13815
13816
13817 return -1;
13818 }
13819
13820
13821
13822
13823
13824 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq)
13825 {
13826 char tmp[256] = "", *c, *a;
13827 struct sip_request *req = oreq ? oreq : &p->initreq;
13828 struct sip_refer *referdata = NULL;
13829 const char *transfer_context = NULL;
13830
13831 if (!p->refer && !sip_refer_allocate(p))
13832 return -1;
13833
13834 referdata = p->refer;
13835
13836 ast_copy_string(tmp, get_header(req, "Also"), sizeof(tmp));
13837 c = get_in_brackets(tmp);
13838
13839 if (sip_cfg.pedanticsipchecking)
13840 ast_uri_decode(c);
13841
13842 if (!strncasecmp(c, "sip:", 4)) {
13843 c += 4;
13844 } else if (!strncasecmp(c, "sips:", 5)) {
13845 c += 5;
13846 } else {
13847 ast_log(LOG_WARNING, "Huh? Not a SIP header in Also: transfer (%s)?\n", c);
13848 return -1;
13849 }
13850
13851 if ((a = strchr(c, ';')))
13852 *a = '\0';
13853
13854 if ((a = strchr(c, '@'))) {
13855 *a++ = '\0';
13856 ast_copy_string(referdata->refer_to_domain, a, sizeof(referdata->refer_to_domain));
13857 }
13858
13859 if (sip_debug_test_pvt(p))
13860 ast_verbose("Looking for %s in %s\n", c, p->context);
13861
13862 if (p->owner)
13863 transfer_context = pbx_builtin_getvar_helper(p->owner, "TRANSFER_CONTEXT");
13864
13865
13866 if (ast_strlen_zero(transfer_context)) {
13867 transfer_context = S_OR(p->owner->macrocontext,
13868 S_OR(p->context, sip_cfg.default_context));
13869 }
13870 if (ast_exists_extension(NULL, transfer_context, c, 1, NULL)) {
13871
13872 ast_debug(1, "SIP Bye-also transfer to Extension %s@%s \n", c, transfer_context);
13873 ast_copy_string(referdata->refer_to, c, sizeof(referdata->refer_to));
13874 ast_copy_string(referdata->referred_by, "", sizeof(referdata->referred_by));
13875 ast_copy_string(referdata->refer_contact, "", sizeof(referdata->refer_contact));
13876 referdata->refer_call = dialog_unref(referdata->refer_call, "unreffing referdata->refer_call");
13877
13878 ast_string_field_set(p, context, transfer_context);
13879 return 0;
13880 } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
13881 return 1;
13882 }
13883
13884 return -1;
13885 }
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897 static attribute_unused void check_via_response(struct sip_pvt *p, struct sip_request *req)
13898 {
13899 char via[256];
13900 char *cur, *opts;
13901
13902 ast_copy_string(via, get_header(req, "Via"), sizeof(via));
13903
13904
13905 opts = strchr(via, ',');
13906 if (opts)
13907 *opts = '\0';
13908
13909
13910 opts = strchr(via, ';');
13911 if (!opts)
13912 return;
13913 *opts++ = '\0';
13914 while ( (cur = strsep(&opts, ";")) ) {
13915 if (!strncmp(cur, "rport=", 6)) {
13916 int port = strtol(cur+6, NULL, 10);
13917
13918 p->ourip.sin_port = ntohs(port);
13919 } else if (!strncmp(cur, "received=", 9)) {
13920 if (ast_parse_arg(cur+9, PARSE_INADDR, &p->ourip))
13921 ;
13922 }
13923 }
13924 }
13925
13926
13927 static void check_via(struct sip_pvt *p, struct sip_request *req)
13928 {
13929 char via[512];
13930 char *c, *pt, *maddr;
13931 struct hostent *hp;
13932 struct ast_hostent ahp;
13933
13934 ast_copy_string(via, get_header(req, "Via"), sizeof(via));
13935
13936
13937 c = strchr(via, ',');
13938 if (c)
13939 *c = '\0';
13940
13941
13942 c = strstr(via, ";rport");
13943 if (c && (c[6] != '='))
13944 ast_set_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT);
13945
13946
13947 maddr = strstr(via, "maddr=");
13948 if (maddr) {
13949 maddr += 6;
13950 c = maddr + strspn(maddr, "0123456789.");
13951 *c = '\0';
13952 }
13953
13954 c = strchr(via, ';');
13955 if (c)
13956 *c = '\0';
13957
13958 c = strchr(via, ' ');
13959 if (c) {
13960 *c = '\0';
13961 c = ast_skip_blanks(c+1);
13962 if (strcasecmp(via, "SIP/2.0/UDP") && strcasecmp(via, "SIP/2.0/TCP") && strcasecmp(via, "SIP/2.0/TLS")) {
13963 ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
13964 return;
13965 }
13966 pt = strchr(c, ':');
13967 if (pt)
13968 *pt++ = '\0';
13969
13970 if (maddr)
13971 c = maddr;
13972 hp = ast_gethostbyname(c, &ahp);
13973 if (!hp) {
13974 ast_log(LOG_WARNING, "'%s' is not a valid host\n", c);
13975 return;
13976 }
13977 memset(&p->sa, 0, sizeof(p->sa));
13978 p->sa.sin_family = AF_INET;
13979 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
13980 p->sa.sin_port = htons(port_str2int(pt, STANDARD_SIP_PORT));
13981
13982 if (sip_debug_test_pvt(p)) {
13983 const struct sockaddr_in *dst = sip_real_dst(p);
13984 ast_verbose("Sending to %s : %d (%s)\n", ast_inet_ntoa(dst->sin_addr), ntohs(dst->sin_port), sip_nat_mode(p));
13985 }
13986 }
13987 }
13988
13989
13990 static char *get_calleridname(const char *input, char *output, size_t outputsize)
13991 {
13992 const char *end = strchr(input, '<');
13993 const char *tmp = strchr(input, '"');
13994 int bytes = 0;
13995 int maxbytes = outputsize - 1;
13996
13997 if (!end || end == input)
13998 return NULL;
13999
14000 end--;
14001
14002 if (tmp && tmp <= end) {
14003
14004
14005
14006 end = strchr(tmp+1, '"');
14007 if (!end)
14008 return NULL;
14009 bytes = (int) (end - tmp);
14010
14011 if (bytes > maxbytes)
14012 bytes = maxbytes;
14013 ast_copy_string(output, tmp + 1, bytes);
14014 } else {
14015
14016
14017 input = ast_skip_blanks(input);
14018
14019 while(*end && *end < 33 && end > input)
14020 end--;
14021 if (end >= input) {
14022 bytes = (int) (end - input) + 2;
14023
14024 if (bytes > maxbytes)
14025 bytes = maxbytes;
14026 ast_copy_string(output, input, bytes);
14027 } else
14028 return NULL;
14029 }
14030 return output;
14031 }
14032
14033
14034
14035
14036
14037 static int get_rpid_num(const char *input, char *output, int maxlen)
14038 {
14039 char *start;
14040 char *end;
14041
14042 start = strchr(input, ':');
14043 if (!start) {
14044 output[0] = '\0';
14045 return 0;
14046 }
14047 start++;
14048
14049
14050 ast_copy_string(output, start, maxlen);
14051 output[maxlen-1] = '\0';
14052
14053 end = strchr(output, '@');
14054 if (end)
14055 *end = '\0';
14056 else
14057 output[0] = '\0';
14058 if (strstr(input, "privacy=full") || strstr(input, "privacy=uri"))
14059 return AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
14060
14061 return 0;
14062 }
14063
14064
14065
14066 static void replace_cid(struct sip_pvt *p, const char *rpid_num, const char *calleridname)
14067 {
14068
14069 if (!ast_strlen_zero(rpid_num) && ast_test_flag(&p->flags[0], SIP_TRUSTRPID)) {
14070 char *tmp = ast_strdupa(rpid_num);
14071 if (!ast_strlen_zero(calleridname))
14072 ast_string_field_set(p, cid_name, calleridname);
14073 if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
14074 ast_shrink_phone_number(tmp);
14075 ast_string_field_set(p, cid_num, tmp);
14076 }
14077 }
14078
14079
14080 static enum check_auth_result check_peer_ok(struct sip_pvt *p, char *of,
14081 struct sip_request *req, int sipmethod, struct sockaddr_in *sin,
14082 struct sip_peer **authpeer,
14083 enum xmittype reliable,
14084 char *rpid_num, char *calleridname, char *uri2)
14085 {
14086 enum check_auth_result res;
14087 int debug=sip_debug_test_addr(sin);
14088 struct sip_peer *peer;
14089
14090 if (sipmethod == SIP_SUBSCRIBE) {
14091
14092
14093
14094 peer = find_peer(of, NULL, TRUE, FINDALLDEVICES, FALSE, 0);
14095 } else {
14096
14097 peer = find_peer(of, NULL, TRUE, FINDUSERS, FALSE, 0);
14098
14099
14100 if (!peer) {
14101 peer = find_peer(NULL, &p->recv, TRUE, FINDPEERS, FALSE, p->socket.type);
14102 }
14103 }
14104
14105 if (!peer) {
14106 if (debug)
14107 ast_verbose("No matching peer for '%s' from '%s:%d'\n",
14108 of, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
14109 return AUTH_DONT_KNOW;
14110 }
14111 if (!ast_apply_ha(peer->ha, sin)) {
14112 ast_debug(2, "Found peer '%s' for '%s', but fails host access\n", peer->name, of);
14113 unref_peer(peer, "unref_peer: check_peer_ok: from find_peer call, early return of AUTH_ACL_FAILED");
14114 return AUTH_ACL_FAILED;
14115 }
14116 if (debug)
14117 ast_verbose("Found peer '%s' for '%s' from %s:%d\n",
14118 peer->name, of, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
14119
14120
14121
14122 if (p->rtp) {
14123 ast_rtp_codec_setpref(p->rtp, &peer->prefs);
14124 p->autoframing = peer->autoframing;
14125 }
14126
14127
14128 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
14129 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
14130
14131 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) && p->udptl) {
14132 p->t38_maxdatagram = peer->t38_maxdatagram;
14133 set_t38_capabilities(p);
14134 }
14135
14136
14137
14138 if (p->sipoptions)
14139 peer->sipoptions = p->sipoptions;
14140
14141 replace_cid(p, rpid_num, calleridname);
14142 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT_ROUTE));
14143
14144 ast_string_field_set(p, peersecret, peer->secret);
14145 ast_string_field_set(p, peermd5secret, peer->md5secret);
14146 ast_string_field_set(p, subscribecontext, peer->subscribecontext);
14147 ast_string_field_set(p, mohinterpret, peer->mohinterpret);
14148 ast_string_field_set(p, mohsuggest, peer->mohsuggest);
14149 ast_string_field_set(p, parkinglot, peer->parkinglot);
14150 if (peer->callingpres)
14151 p->callingpres = peer->callingpres;
14152 if (peer->maxms && peer->lastms)
14153 p->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
14154 else
14155 p->timer_t1 = peer->timer_t1;
14156
14157
14158 if (peer->timer_b)
14159 p->timer_b = peer->timer_b;
14160 else
14161 p->timer_b = 64 * p->timer_t1;
14162
14163 if (ast_test_flag(&peer->flags[0], SIP_INSECURE_INVITE)) {
14164
14165 ast_string_field_set(p, peersecret, NULL);
14166 ast_string_field_set(p, peermd5secret, NULL);
14167 }
14168 if (!(res = check_auth(p, req, peer->name, p->peersecret, p->peermd5secret, sipmethod, uri2, reliable, req->ignore))) {
14169 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
14170 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
14171
14172 if (peer->call_limit)
14173 ast_set_flag(&p->flags[0], SIP_CALL_LIMIT);
14174 ast_string_field_set(p, peername, peer->name);
14175 ast_string_field_set(p, authname, peer->name);
14176
14177 if (sipmethod == SIP_INVITE) {
14178
14179 p->chanvars = copy_vars(peer->chanvars);
14180 }
14181
14182 if (authpeer) {
14183 ao2_t_ref(peer, 1, "copy pointer into (*authpeer)");
14184 (*authpeer) = peer;
14185 }
14186
14187 if (!ast_strlen_zero(peer->username)) {
14188 ast_string_field_set(p, username, peer->username);
14189
14190
14191 ast_string_field_set(p, authname, peer->username);
14192 }
14193 if (!ast_strlen_zero(peer->cid_num)) {
14194 char *tmp = ast_strdupa(peer->cid_num);
14195 if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
14196 ast_shrink_phone_number(tmp);
14197 ast_string_field_set(p, cid_num, tmp);
14198 }
14199 if (!ast_strlen_zero(peer->cid_name))
14200 ast_string_field_set(p, cid_name, peer->cid_name);
14201 ast_string_field_set(p, fullcontact, peer->fullcontact);
14202 if (!ast_strlen_zero(peer->context))
14203 ast_string_field_set(p, context, peer->context);
14204 ast_string_field_set(p, peersecret, peer->secret);
14205 ast_string_field_set(p, peermd5secret, peer->md5secret);
14206 ast_string_field_set(p, language, peer->language);
14207 ast_string_field_set(p, accountcode, peer->accountcode);
14208 p->amaflags = peer->amaflags;
14209 p->callgroup = peer->callgroup;
14210 p->pickupgroup = peer->pickupgroup;
14211 p->capability = peer->capability;
14212 p->prefs = peer->prefs;
14213 p->jointcapability = peer->capability;
14214 if (p->peercapability)
14215 p->jointcapability &= p->peercapability;
14216 p->maxcallbitrate = peer->maxcallbitrate;
14217 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS) &&
14218 (!ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) ||
14219 !(p->capability & AST_FORMAT_VIDEO_MASK)) &&
14220 p->vrtp) {
14221 ast_rtp_destroy(p->vrtp);
14222 p->vrtp = NULL;
14223 }
14224 if ((!ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT) || !(p->capability & AST_FORMAT_TEXT_MASK)) && p->trtp) {
14225 ast_rtp_destroy(p->trtp);
14226 p->trtp = NULL;
14227 }
14228 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
14229 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
14230 p->noncodeccapability |= AST_RTP_DTMF;
14231 else
14232 p->noncodeccapability &= ~AST_RTP_DTMF;
14233 p->jointnoncodeccapability = p->noncodeccapability;
14234 }
14235 unref_peer(peer, "check_peer_ok: unref_peer: tossing temp ptr to peer from find_peer");
14236 return res;
14237 }
14238
14239
14240
14241
14242
14243
14244
14245 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
14246 int sipmethod, char *uri, enum xmittype reliable,
14247 struct sockaddr_in *sin, struct sip_peer **authpeer)
14248 {
14249 char from[256];
14250 char *dummy;
14251 char *domain;
14252 char *of;
14253 char rpid_num[50];
14254 const char *rpid;
14255 enum check_auth_result res;
14256 char calleridname[50];
14257 char *uri2 = ast_strdupa(uri);
14258
14259 terminate_uri(uri2);
14260
14261 ast_copy_string(from, get_header(req, "From"), sizeof(from));
14262 if (sip_cfg.pedanticsipchecking)
14263 ast_uri_decode(from);
14264
14265 memset(calleridname, 0, sizeof(calleridname));
14266 get_calleridname(from, calleridname, sizeof(calleridname));
14267 if (calleridname[0])
14268 ast_string_field_set(p, cid_name, calleridname);
14269
14270 rpid = get_header(req, "Remote-Party-ID");
14271 memset(rpid_num, 0, sizeof(rpid_num));
14272 if (!ast_strlen_zero(rpid))
14273 p->callingpres = get_rpid_num(rpid, rpid_num, sizeof(rpid_num));
14274
14275 of = get_in_brackets(from);
14276 if (ast_strlen_zero(p->exten)) {
14277 char *t = uri2;
14278 if (!strncasecmp(t, "sip:", 4))
14279 t+= 4;
14280 else if (!strncasecmp(t, "sips:", 5))
14281 t += 5;
14282 ast_string_field_set(p, exten, t);
14283 t = strchr(p->exten, '@');
14284 if (t)
14285 *t = '\0';
14286 if (ast_strlen_zero(p->our_contact))
14287 build_contact(p);
14288 }
14289
14290 ast_string_field_set(p, from, of);
14291
14292
14293 if (parse_uri(of, "sip:,sips:", &of, &dummy, &domain, &dummy, &dummy, NULL)) {
14294 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
14295 }
14296
14297 if (ast_strlen_zero(of)) {
14298
14299
14300
14301
14302
14303
14304 of = domain;
14305 } else {
14306 char *tmp = ast_strdupa(of);
14307
14308
14309
14310 tmp = strsep(&tmp, ";");
14311 if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
14312 ast_shrink_phone_number(tmp);
14313 ast_string_field_set(p, cid_num, tmp);
14314 }
14315
14316 if (global_match_auth_username) {
14317
14318
14319
14320
14321
14322
14323
14324
14325 const char *hdr = get_header(req, "Authorization");
14326 if (ast_strlen_zero(hdr))
14327 hdr = get_header(req, "Proxy-Authorization");
14328
14329 if ( !ast_strlen_zero(hdr) && (hdr = strstr(hdr, "username=\"")) ) {
14330 ast_copy_string(from, hdr + strlen("username=\""), sizeof(from));
14331 of = from;
14332 of = strsep(&of, "\"");
14333 }
14334 }
14335
14336 res = check_peer_ok(p, of, req, sipmethod, sin,
14337 authpeer, reliable, rpid_num, calleridname, uri2);
14338 if (res != AUTH_DONT_KNOW)
14339 return res;
14340
14341
14342 if (sip_cfg.allowguest) {
14343 replace_cid(p, rpid_num, calleridname);
14344 res = AUTH_SUCCESSFUL;
14345 } else if (sip_cfg.alwaysauthreject)
14346 res = AUTH_FAKE_AUTH;
14347 else
14348 res = AUTH_SECRET_FAILED;
14349
14350
14351 if (ast_test_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT)) {
14352 ast_set_flag(&p->flags[0], SIP_NAT_ROUTE);
14353 }
14354
14355 return res;
14356 }
14357
14358
14359
14360
14361 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin)
14362 {
14363 return check_user_full(p, req, sipmethod, uri, reliable, sin, NULL);
14364 }
14365
14366
14367 static int get_msg_text(char *buf, int len, struct sip_request *req, int addnewline)
14368 {
14369 int x;
14370 int y;
14371
14372 buf[0] = '\0';
14373
14374 y = len - strlen(buf) - 5;
14375 if (y < 0)
14376 y = 0;
14377 for (x = 0; x < req->lines; x++) {
14378 char *line = REQ_OFFSET_TO_STR(req, line[x]);
14379 strncat(buf, line, y);
14380 y -= strlen(line) + 1;
14381 if (y < 0)
14382 y = 0;
14383 if (y != 0 && addnewline)
14384 strcat(buf, "\n");
14385 }
14386 return 0;
14387 }
14388
14389
14390
14391
14392
14393 static void receive_message(struct sip_pvt *p, struct sip_request *req)
14394 {
14395 char buf[1400];
14396 struct ast_frame f;
14397 const char *content_type = get_header(req, "Content-Type");
14398
14399 if (strncmp(content_type, "text/plain", strlen("text/plain"))) {
14400 transmit_response(p, "415 Unsupported Media Type", req);
14401 if (!p->owner)
14402 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14403 return;
14404 }
14405
14406 if (get_msg_text(buf, sizeof(buf), req, FALSE)) {
14407 ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
14408 transmit_response(p, "202 Accepted", req);
14409 if (!p->owner)
14410 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14411 return;
14412 }
14413
14414 if (p->owner) {
14415 if (sip_debug_test_pvt(p))
14416 ast_verbose("SIP Text message received: '%s'\n", buf);
14417 memset(&f, 0, sizeof(f));
14418 f.frametype = AST_FRAME_TEXT;
14419 f.subclass = 0;
14420 f.offset = 0;
14421 f.data.ptr = buf;
14422 f.datalen = strlen(buf);
14423 ast_queue_frame(p->owner, &f);
14424 transmit_response(p, "202 Accepted", req);
14425 return;
14426 }
14427
14428
14429 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);
14430 transmit_response(p, "405 Method Not Allowed", req);
14431 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14432 return;
14433 }
14434
14435
14436 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14437 {
14438 #define FORMAT "%-25.25s %-15.15s %-15.15s \n"
14439 #define FORMAT2 "%-25.25s %-15.15s %-15.15s \n"
14440 char ilimits[40];
14441 char iused[40];
14442 int showall = FALSE;
14443 struct ao2_iterator i;
14444 struct sip_peer *peer;
14445
14446 switch (cmd) {
14447 case CLI_INIT:
14448 e->command = "sip show inuse";
14449 e->usage =
14450 "Usage: sip show inuse [all]\n"
14451 " List all SIP devices usage counters and limits.\n"
14452 " Add option \"all\" to show all devices, not only those with a limit.\n";
14453 return NULL;
14454 case CLI_GENERATE:
14455 return NULL;
14456 }
14457
14458 if (a->argc < 3)
14459 return CLI_SHOWUSAGE;
14460
14461 if (a->argc == 4 && !strcmp(a->argv[3], "all"))
14462 showall = TRUE;
14463
14464 ast_cli(a->fd, FORMAT, "* Peer name", "In use", "Limit");
14465
14466 i = ao2_iterator_init(peers, 0);
14467 while ((peer = ao2_t_iterator_next(&i, "iterate thru peer table"))) {
14468 ao2_lock(peer);
14469 if (peer->call_limit)
14470 snprintf(ilimits, sizeof(ilimits), "%d", peer->call_limit);
14471 else
14472 ast_copy_string(ilimits, "N/A", sizeof(ilimits));
14473 snprintf(iused, sizeof(iused), "%d/%d/%d", peer->inUse, peer->inRinging, peer->onHold);
14474 if (showall || peer->call_limit)
14475 ast_cli(a->fd, FORMAT2, peer->name, iused, ilimits);
14476 ao2_unlock(peer);
14477 unref_peer(peer, "toss iterator pointer");
14478 }
14479 ao2_iterator_destroy(&i);
14480
14481 return CLI_SUCCESS;
14482 #undef FORMAT
14483 #undef FORMAT2
14484 }
14485
14486
14487
14488 static char *transfermode2str(enum transfermodes mode)
14489 {
14490 if (mode == TRANSFER_OPENFORALL)
14491 return "open";
14492 else if (mode == TRANSFER_CLOSED)
14493 return "closed";
14494 return "strict";
14495 }
14496
14497 static struct _map_x_s natmodes[] = {
14498 { SIP_NAT_NEVER, "No"},
14499 { SIP_NAT_ROUTE, "Route"},
14500 { SIP_NAT_ALWAYS, "Always"},
14501 { SIP_NAT_RFC3581, "RFC3581"},
14502 { -1, NULL},
14503 };
14504
14505
14506 static const char *nat2str(int nat)
14507 {
14508 return map_x_s(natmodes, nat, "Unknown");
14509 }
14510
14511 #ifdef NOTUSED
14512
14513
14514
14515
14516 static struct _map_x_s natcfgmodes[] = {
14517 { SIP_NAT_NEVER, "never"},
14518 { SIP_NAT_ROUTE, "route"},
14519 { SIP_NAT_ALWAYS, "yes"},
14520 { SIP_NAT_RFC3581, "no"},
14521 { -1, NULL},
14522 };
14523
14524
14525 static const char *nat2strconfig(int nat)
14526 {
14527 return map_x_s(natcfgmodes, nat, "Unknown");
14528 }
14529 #endif
14530
14531
14532
14533
14534
14535
14536
14537 static struct _map_x_s stmodes[] = {
14538 { SESSION_TIMER_MODE_ACCEPT, "Accept"},
14539 { SESSION_TIMER_MODE_ORIGINATE, "Originate"},
14540 { SESSION_TIMER_MODE_REFUSE, "Refuse"},
14541 { -1, NULL},
14542 };
14543
14544 static const char *stmode2str(enum st_mode m)
14545 {
14546 return map_x_s(stmodes, m, "Unknown");
14547 }
14548
14549 static enum st_mode str2stmode(const char *s)
14550 {
14551 return map_s_x(stmodes, s, -1);
14552 }
14553
14554
14555 static struct _map_x_s strefreshers[] = {
14556 { SESSION_TIMER_REFRESHER_AUTO, "auto"},
14557 { SESSION_TIMER_REFRESHER_UAC, "uac"},
14558 { SESSION_TIMER_REFRESHER_UAS, "uas"},
14559 { -1, NULL},
14560 };
14561
14562 static const char *strefresher2str(enum st_refresher r)
14563 {
14564 return map_x_s(strefreshers, r, "Unknown");
14565 }
14566
14567 static enum st_refresher str2strefresher(const char *s)
14568 {
14569 return map_s_x(strefreshers, s, -1);
14570 }
14571
14572
14573 static int peer_status(struct sip_peer *peer, char *status, int statuslen)
14574 {
14575 int res = 0;
14576 if (peer->maxms) {
14577 if (peer->lastms < 0) {
14578 ast_copy_string(status, "UNREACHABLE", statuslen);
14579 } else if (peer->lastms > peer->maxms) {
14580 snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
14581 res = 1;
14582 } else if (peer->lastms) {
14583 snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
14584 res = 1;
14585 } else {
14586 ast_copy_string(status, "UNKNOWN", statuslen);
14587 }
14588 } else {
14589 ast_copy_string(status, "Unmonitored", statuslen);
14590
14591 res = -1;
14592 }
14593 return res;
14594 }
14595
14596
14597
14598
14599
14600
14601 static const char *cli_yesno(int x)
14602 {
14603 return x ? "Yes" : "No";
14604 }
14605
14606
14607 static char *sip_show_tcp(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14608 {
14609 struct sip_threadinfo *th;
14610 struct ao2_iterator i;
14611
14612 #define FORMAT2 "%-30.30s %3.6s %9.9s %6.6s\n"
14613 #define FORMAT "%-30.30s %-6d %-9.9s %-6.6s\n"
14614
14615 switch (cmd) {
14616 case CLI_INIT:
14617 e->command = "sip show tcp";
14618 e->usage =
14619 "Usage: sip show tcp\n"
14620 " Lists all active TCP/TLS sessions.\n";
14621 return NULL;
14622 case CLI_GENERATE:
14623 return NULL;
14624 }
14625
14626 if (a->argc != 3)
14627 return CLI_SHOWUSAGE;
14628
14629 ast_cli(a->fd, FORMAT2, "Host", "Port", "Transport", "Type");
14630 i = ao2_iterator_init(threadt, 0);
14631 while ((th = ao2_t_iterator_next(&i, "iterate through tcp threads for 'sip show tcp'"))) {
14632 ast_cli(a->fd, FORMAT, ast_inet_ntoa(th->tcptls_session->remote_address.sin_addr),
14633 ntohs(th->tcptls_session->remote_address.sin_port),
14634 get_transport(th->type),
14635 (th->tcptls_session->client ? "Client" : "Server"));
14636 ao2_t_ref(th, -1, "decrement ref from iterator");
14637 }
14638 ao2_iterator_destroy(&i);
14639 return CLI_SUCCESS;
14640 #undef FORMAT
14641 #undef FORMAT2
14642 }
14643
14644
14645 static char *sip_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14646 {
14647 regex_t regexbuf;
14648 int havepattern = FALSE;
14649 struct ao2_iterator user_iter;
14650 struct sip_peer *user;
14651
14652 #define FORMAT "%-25.25s %-15.15s %-15.15s %-15.15s %-5.5s%-10.10s\n"
14653
14654 switch (cmd) {
14655 case CLI_INIT:
14656 e->command = "sip show users";
14657 e->usage =
14658 "Usage: sip show users [like <pattern>]\n"
14659 " Lists all known SIP users.\n"
14660 " Optional regular expression pattern is used to filter the user list.\n";
14661 return NULL;
14662 case CLI_GENERATE:
14663 return NULL;
14664 }
14665
14666 switch (a->argc) {
14667 case 5:
14668 if (!strcasecmp(a->argv[3], "like")) {
14669 if (regcomp(®exbuf, a->argv[4], REG_EXTENDED | REG_NOSUB))
14670 return CLI_SHOWUSAGE;
14671 havepattern = TRUE;
14672 } else
14673 return CLI_SHOWUSAGE;
14674 case 3:
14675 break;
14676 default:
14677 return CLI_SHOWUSAGE;
14678 }
14679
14680 ast_cli(a->fd, FORMAT, "Username", "Secret", "Accountcode", "Def.Context", "ACL", "NAT");
14681
14682 user_iter = ao2_iterator_init(peers, 0);
14683 while ((user = ao2_iterator_next(&user_iter))) {
14684 ao2_lock(user);
14685 if (!(user->type & SIP_TYPE_USER)) {
14686 ao2_unlock(user);
14687 unref_peer(user, "sip show users");
14688 continue;
14689 }
14690
14691 if (havepattern && regexec(®exbuf, user->name, 0, NULL, 0)) {
14692 ao2_unlock(user);
14693 unref_peer(user, "sip show users");
14694 continue;
14695 }
14696
14697 ast_cli(a->fd, FORMAT, user->name,
14698 user->secret,
14699 user->accountcode,
14700 user->context,
14701 cli_yesno(user->ha != NULL),
14702 nat2str(ast_test_flag(&user->flags[0], SIP_NAT)));
14703 ao2_unlock(user);
14704 unref_peer(user, "sip show users");
14705 }
14706 ao2_iterator_destroy(&user_iter);
14707
14708 if (havepattern)
14709 regfree(®exbuf);
14710
14711 return CLI_SUCCESS;
14712 #undef FORMAT
14713 }
14714
14715
14716 static char mandescr_show_registry[] =
14717 "Description: Lists all registration requests and status\n"
14718 "Registrations will follow as separate events. followed by a final event called\n"
14719 "RegistrationsComplete.\n"
14720 "Variables: \n"
14721 " ActionID: <id> Action ID for this transaction. Will be returned.\n";
14722
14723
14724 static int manager_show_registry(struct mansession *s, const struct message *m)
14725 {
14726 const char *id = astman_get_header(m, "ActionID");
14727 char idtext[256] = "";
14728 int total = 0;
14729
14730 if (!ast_strlen_zero(id))
14731 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
14732
14733 astman_send_listack(s, m, "Registrations will follow", "start");
14734
14735 ASTOBJ_CONTAINER_TRAVERSE(®l, 1, do {
14736 ASTOBJ_RDLOCK(iterator);
14737 astman_append(s,
14738 "Event: RegistryEntry\r\n"
14739 "%s"
14740 "Host: %s\r\n"
14741 "Port: %d\r\n"
14742 "Username: %s\r\n"
14743 "Refresh: %d\r\n"
14744 "State: %s\r\n"
14745 "RegistrationTime: %ld\r\n"
14746 "\r\n", idtext, iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT,
14747 iterator->username, iterator->refresh, regstate2str(iterator->regstate), (long) iterator->regtime.tv_sec);
14748 ASTOBJ_UNLOCK(iterator);
14749 total++;
14750 } while(0));
14751
14752 astman_append(s,
14753 "Event: RegistrationsComplete\r\n"
14754 "EventList: Complete\r\n"
14755 "ListItems: %d\r\n"
14756 "%s"
14757 "\r\n", total, idtext);
14758
14759 return 0;
14760 }
14761
14762 static char mandescr_show_peers[] =
14763 "Description: Lists SIP peers in text format with details on current status.\n"
14764 "Peerlist will follow as separate events, followed by a final event called\n"
14765 "PeerlistComplete.\n"
14766 "Variables: \n"
14767 " ActionID: <id> Action ID for this transaction. Will be returned.\n";
14768
14769
14770
14771 static int manager_sip_show_peers(struct mansession *s, const struct message *m)
14772 {
14773 const char *id = astman_get_header(m, "ActionID");
14774 const char *a[] = {"sip", "show", "peers"};
14775 char idtext[256] = "";
14776 int total = 0;
14777
14778 if (!ast_strlen_zero(id))
14779 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
14780
14781 astman_send_listack(s, m, "Peer status list will follow", "start");
14782
14783 _sip_show_peers(-1, &total, s, m, 3, a);
14784
14785 astman_append(s,
14786 "Event: PeerlistComplete\r\n"
14787 "EventList: Complete\r\n"
14788 "ListItems: %d\r\n"
14789 "%s"
14790 "\r\n", total, idtext);
14791 return 0;
14792 }
14793
14794
14795 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14796 {
14797 switch (cmd) {
14798 case CLI_INIT:
14799 e->command = "sip show peers";
14800 e->usage =
14801 "Usage: sip show peers [like <pattern>]\n"
14802 " Lists all known SIP peers.\n"
14803 " Optional regular expression pattern is used to filter the peer list.\n";
14804 return NULL;
14805 case CLI_GENERATE:
14806 return NULL;
14807 }
14808
14809 return _sip_show_peers(a->fd, NULL, NULL, NULL, a->argc, (const char **) a->argv);
14810 }
14811
14812 int peercomparefunc(const void *a, const void *b);
14813
14814 int peercomparefunc(const void *a, const void *b)
14815 {
14816 struct sip_peer **ap = (struct sip_peer **)a;
14817 struct sip_peer **bp = (struct sip_peer **)b;
14818 return strcmp((*ap)->name, (*bp)->name);
14819 }
14820
14821
14822
14823 static char *_sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[])
14824 {
14825 regex_t regexbuf;
14826 int havepattern = FALSE;
14827 struct sip_peer *peer;
14828 struct ao2_iterator i;
14829
14830
14831 #define FORMAT2 "%-25.25s %-15.15s %-3.3s %-3.3s %-3.3s %-8s %-10s %s\n"
14832 #define FORMAT "%-25.25s %-15.15s %-3.3s %-3.3s %-3.3s %-8d %-10s %s\n"
14833
14834 char name[256];
14835 int total_peers = 0;
14836 int peers_mon_online = 0;
14837 int peers_mon_offline = 0;
14838 int peers_unmon_offline = 0;
14839 int peers_unmon_online = 0;
14840 const char *id;
14841 char idtext[256] = "";
14842 int realtimepeers;
14843 int objcount = ao2_container_count(peers);
14844 struct sip_peer **peerarray;
14845 int k;
14846
14847
14848 realtimepeers = ast_check_realtime("sippeers");
14849 peerarray = ast_calloc(sizeof(struct sip_peer *), objcount);
14850
14851 if (s) {
14852 id = astman_get_header(m, "ActionID");
14853 if (!ast_strlen_zero(id))
14854 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
14855 }
14856
14857 switch (argc) {
14858 case 5:
14859 if (!strcasecmp(argv[3], "like")) {
14860 if (regcomp(®exbuf, argv[4], REG_EXTENDED | REG_NOSUB))
14861 return CLI_SHOWUSAGE;
14862 havepattern = TRUE;
14863 } else
14864 return CLI_SHOWUSAGE;
14865 case 3:
14866 break;
14867 default:
14868 return CLI_SHOWUSAGE;
14869 }
14870
14871 if (!s)
14872 ast_cli(fd, FORMAT2, "Name/username", "Host", "Dyn", "Nat", "ACL", "Port", "Status", (realtimepeers ? "Realtime" : ""));
14873
14874
14875 i = ao2_iterator_init(peers, 0);
14876 while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
14877 ao2_lock(peer);
14878
14879 if (!(peer->type & SIP_TYPE_PEER)) {
14880 ao2_unlock(peer);
14881 unref_peer(peer, "unref peer because it's actually a user");
14882 continue;
14883 }
14884
14885 if (havepattern && regexec(®exbuf, peer->name, 0, NULL, 0)) {
14886 objcount--;
14887 ao2_unlock(peer);
14888 unref_peer(peer, "toss iterator peer ptr before continue");
14889 continue;
14890 }
14891
14892 peerarray[total_peers++] = peer;
14893 ao2_unlock(peer);
14894 }
14895 ao2_iterator_destroy(&i);
14896
14897 qsort(peerarray, total_peers, sizeof(struct sip_peer *), peercomparefunc);
14898
14899 for(k=0; k < total_peers; k++) {
14900 char status[20] = "";
14901 char srch[2000];
14902 char pstatus;
14903 peer = peerarray[k];
14904
14905 ao2_lock(peer);
14906 if (havepattern && regexec(®exbuf, peer->name, 0, NULL, 0)) {
14907 ao2_unlock(peer);
14908 unref_peer(peer, "toss iterator peer ptr before continue");
14909 continue;
14910 }
14911
14912 if (!ast_strlen_zero(peer->username) && !s)
14913 snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
14914 else
14915 ast_copy_string(name, peer->name, sizeof(name));
14916
14917 pstatus = peer_status(peer, status, sizeof(status));
14918 if (pstatus == 1)
14919 peers_mon_online++;
14920 else if (pstatus == 0)
14921 peers_mon_offline++;
14922 else {
14923 if (peer->addr.sin_port == 0)
14924 peers_unmon_offline++;
14925 else
14926 peers_unmon_online++;
14927 }
14928
14929 snprintf(srch, sizeof(srch), FORMAT, name,
14930 peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
14931 peer->host_dynamic ? " D " : " ",
14932 ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) ? " N " : " ",
14933 peer->ha ? " A " : " ",
14934 ntohs(peer->addr.sin_port), status,
14935 realtimepeers ? (peer->is_realtime ? "Cached RT":"") : "");
14936
14937 if (!s) {
14938 ast_cli(fd, FORMAT, name,
14939 peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
14940 peer->host_dynamic ? " D " : " ",
14941 ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) ? " N " : " ",
14942 peer->ha ? " A " : " ",
14943
14944 ntohs(peer->addr.sin_port), status,
14945 realtimepeers ? (peer->is_realtime ? "Cached RT":"") : "");
14946 } else {
14947
14948 astman_append(s,
14949 "Event: PeerEntry\r\n%s"
14950 "Channeltype: SIP\r\n"
14951 "ObjectName: %s\r\n"
14952 "ChanObjectType: peer\r\n"
14953 "IPaddress: %s\r\n"
14954 "IPport: %d\r\n"
14955 "Dynamic: %s\r\n"
14956 "Natsupport: %s\r\n"
14957 "VideoSupport: %s\r\n"
14958 "TextSupport: %s\r\n"
14959 "ACL: %s\r\n"
14960 "Status: %s\r\n"
14961 "RealtimeDevice: %s\r\n\r\n",
14962 idtext,
14963 peer->name,
14964 peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "-none-",
14965 ntohs(peer->addr.sin_port),
14966 peer->host_dynamic ? "yes" : "no",
14967 ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) ? "yes" : "no",
14968 ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "yes" : "no",
14969 ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT) ? "yes" : "no",
14970 peer->ha ? "yes" : "no",
14971 status,
14972 realtimepeers ? (peer->is_realtime ? "yes":"no") : "no");
14973 }
14974 ao2_unlock(peer);
14975 unref_peer(peer, "toss iterator peer ptr");
14976 }
14977
14978 if (!s)
14979 ast_cli(fd, "%d sip peers [Monitored: %d online, %d offline Unmonitored: %d online, %d offline]\n",
14980 total_peers, peers_mon_online, peers_mon_offline, peers_unmon_online, peers_unmon_offline);
14981
14982 if (havepattern)
14983 regfree(®exbuf);
14984
14985 if (total)
14986 *total = total_peers;
14987
14988 ast_free(peerarray);
14989
14990 return CLI_SUCCESS;
14991 #undef FORMAT
14992 #undef FORMAT2
14993 }
14994
14995 static int peer_dump_func(void *userobj, void *arg, int flags)
14996 {
14997 struct sip_peer *peer = userobj;
14998 int refc = ao2_t_ref(userobj, 0, "");
14999 int *fd = arg;
15000
15001 ast_cli(*fd, "name: %s\ntype: peer\nobjflags: %d\nrefcount: %d\n\n",
15002 peer->name, 0, refc);
15003 return 0;
15004 }
15005
15006 static int dialog_dump_func(void *userobj, void *arg, int flags)
15007 {
15008 struct sip_pvt *pvt = userobj;
15009 int refc = ao2_t_ref(userobj, 0, "");
15010 int *fd = arg;
15011
15012 ast_cli(*fd, "name: %s\ntype: dialog\nobjflags: %d\nrefcount: %d\n\n",
15013 pvt->callid, 0, refc);
15014 return 0;
15015 }
15016
15017
15018
15019 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15020 {
15021 char tmp[256];
15022
15023 switch (cmd) {
15024 case CLI_INIT:
15025 e->command = "sip show objects";
15026 e->usage =
15027 "Usage: sip show objects\n"
15028 " Lists status of known SIP objects\n";
15029 return NULL;
15030 case CLI_GENERATE:
15031 return NULL;
15032 }
15033
15034 if (a->argc != 3)
15035 return CLI_SHOWUSAGE;
15036 ast_cli(a->fd, "-= Peer objects: %d static, %d realtime, %d autocreate =-\n\n", speerobjs, rpeerobjs, apeerobjs);
15037 ao2_t_callback(peers, OBJ_NODATA, peer_dump_func, &a->fd, "initiate ao2_callback to dump peers");
15038 ast_cli(a->fd, "-= Registry objects: %d =-\n\n", regobjs);
15039 ASTOBJ_CONTAINER_DUMP(a->fd, tmp, sizeof(tmp), ®l);
15040 ast_cli(a->fd, "-= Dialog objects:\n\n");
15041 ao2_t_callback(dialogs, OBJ_NODATA, dialog_dump_func, &a->fd, "initiate ao2_callback to dump dialogs");
15042 return CLI_SUCCESS;
15043 }
15044
15045 static void print_group(int fd, ast_group_t group, int crlf)
15046 {
15047 char buf[256];
15048 ast_cli(fd, crlf ? "%s\r\n" : "%s\n", ast_print_group(buf, sizeof(buf), group) );
15049 }
15050
15051
15052 static struct _map_x_s dtmfstr[] = {
15053 { SIP_DTMF_RFC2833, "rfc2833" },
15054 { SIP_DTMF_INFO, "info" },
15055 { SIP_DTMF_SHORTINFO, "shortinfo" },
15056 { SIP_DTMF_INBAND, "inband" },
15057 { SIP_DTMF_AUTO, "auto" },
15058 { -1, NULL },
15059 };
15060
15061
15062 static const char *dtmfmode2str(int mode)
15063 {
15064 return map_x_s(dtmfstr, mode, "<error>");
15065 }
15066
15067
15068 static int str2dtmfmode(const char *str)
15069 {
15070 return map_s_x(dtmfstr, str, -1);
15071 }
15072
15073 static struct _map_x_s insecurestr[] = {
15074 { SIP_INSECURE_PORT, "port" },
15075 { SIP_INSECURE_INVITE, "invite" },
15076 { SIP_INSECURE_PORT | SIP_INSECURE_INVITE, "port,invite" },
15077 { 0, "no" },
15078 { -1, NULL },
15079 };
15080
15081
15082 static const char *insecure2str(int mode)
15083 {
15084 return map_x_s(insecurestr, mode, "<error>");
15085 }
15086
15087
15088
15089
15090 static void cleanup_stale_contexts(char *new, char *old)
15091 {
15092 char *oldcontext, *newcontext, *stalecontext, *stringp, newlist[AST_MAX_CONTEXT];
15093
15094 while ((oldcontext = strsep(&old, "&"))) {
15095 stalecontext = '\0';
15096 ast_copy_string(newlist, new, sizeof(newlist));
15097 stringp = newlist;
15098 while ((newcontext = strsep(&stringp, "&"))) {
15099 if (!strcmp(newcontext, oldcontext)) {
15100
15101 stalecontext = '\0';
15102 break;
15103 } else if (strcmp(newcontext, oldcontext)) {
15104 stalecontext = oldcontext;
15105 }
15106
15107 }
15108 if (stalecontext)
15109 ast_context_destroy(ast_context_find(stalecontext), "SIP");
15110 }
15111 }
15112
15113
15114
15115
15116
15117
15118
15119
15120
15121
15122
15123
15124
15125 static int dialog_needdestroy(void *dialogobj, void *arg, int flags)
15126 {
15127 struct sip_pvt *dialog = dialogobj;
15128 time_t *t = arg;
15129
15130 if (sip_pvt_trylock(dialog)) {
15131
15132
15133 return 0;
15134 }
15135
15136
15137 check_rtp_timeout(dialog, *t);
15138
15139
15140
15141
15142 if (dialog->needdestroy && !dialog->packets && !dialog->owner) {
15143
15144 if (dialog->rtp && ast_rtp_get_bridged(dialog->rtp)) {
15145 ast_debug(2, "Bridge still active. Delaying destruction of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
15146 sip_pvt_unlock(dialog);
15147 return 0;
15148 }
15149
15150 if (dialog->vrtp && ast_rtp_get_bridged(dialog->vrtp)) {
15151 ast_debug(2, "Bridge still active. Delaying destroy of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
15152 sip_pvt_unlock(dialog);
15153 return 0;
15154 }
15155
15156 sip_pvt_unlock(dialog);
15157
15158
15159 dialog_unlink_all(dialog, TRUE, FALSE);
15160 return 0;
15161 }
15162
15163 sip_pvt_unlock(dialog);
15164
15165 return 0;
15166 }
15167
15168
15169
15170 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15171 {
15172 struct sip_peer *peer, *pi;
15173 int prunepeer = FALSE;
15174 int multi = FALSE;
15175 char *name = NULL;
15176 regex_t regexbuf;
15177 struct ao2_iterator i;
15178 static char *choices[] = { "all", "like", NULL };
15179 char *cmplt;
15180
15181 if (cmd == CLI_INIT) {
15182 e->command = "sip prune realtime [peer|all]";
15183 e->usage =
15184 "Usage: sip prune realtime [peer [<name>|all|like <pattern>]|all]\n"
15185 " Prunes object(s) from the cache.\n"
15186 " Optional regular expression pattern is used to filter the objects.\n";
15187 return NULL;
15188 } else if (cmd == CLI_GENERATE) {
15189 if (a->pos == 4 && !strcasecmp(a->argv[3], "peer")) {
15190 cmplt = ast_cli_complete(a->word, choices, a->n);
15191 if (!cmplt)
15192 cmplt = complete_sip_peer(a->word, a->n - sizeof(choices), SIP_PAGE2_RTCACHEFRIENDS);
15193 return cmplt;
15194 }
15195 if (a->pos == 5 && !strcasecmp(a->argv[4], "like"))
15196 return complete_sip_peer(a->word, a->n, SIP_PAGE2_RTCACHEFRIENDS);
15197 return NULL;
15198 }
15199 switch (a->argc) {
15200 case 4:
15201 name = a->argv[3];
15202
15203 if (!strcasecmp(name, "peer") || !strcasecmp(name, "like"))
15204 return CLI_SHOWUSAGE;
15205 prunepeer = TRUE;
15206 if (!strcasecmp(name, "all")) {
15207 multi = TRUE;
15208 name = NULL;
15209 }
15210
15211 break;
15212 case 5:
15213
15214 name = a->argv[4];
15215 if (!strcasecmp(a->argv[3], "peer"))
15216 prunepeer = TRUE;
15217 else if (!strcasecmp(a->argv[3], "like")) {
15218 prunepeer = TRUE;
15219 multi = TRUE;
15220 } else
15221 return CLI_SHOWUSAGE;
15222 if (!strcasecmp(name, "like"))
15223 return CLI_SHOWUSAGE;
15224 if (!multi && !strcasecmp(name, "all")) {
15225 multi = TRUE;
15226 name = NULL;
15227 }
15228 break;
15229 case 6:
15230 name = a->argv[5];
15231 multi = TRUE;
15232
15233 if (strcasecmp(a->argv[4], "like"))
15234 return CLI_SHOWUSAGE;
15235 if (!strcasecmp(a->argv[3], "peer")) {
15236 prunepeer = TRUE;
15237 } else
15238 return CLI_SHOWUSAGE;
15239 break;
15240 default:
15241 return CLI_SHOWUSAGE;
15242 }
15243
15244 if (multi && name) {
15245 if (regcomp(®exbuf, name, REG_EXTENDED | REG_NOSUB))
15246 return CLI_SHOWUSAGE;
15247 }
15248
15249 if (multi) {
15250 if (prunepeer) {
15251 int pruned = 0;
15252
15253 i = ao2_iterator_init(peers, 0);
15254 while ((pi = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
15255 ao2_lock(pi);
15256 if (name && regexec(®exbuf, pi->name, 0, NULL, 0)) {
15257 unref_peer(pi, "toss iterator peer ptr before continue");
15258 ao2_unlock(pi);
15259 continue;
15260 };
15261 if (ast_test_flag(&pi->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
15262 pi->the_mark = 1;
15263 pruned++;
15264 }
15265 ao2_unlock(pi);
15266 unref_peer(pi, "toss iterator peer ptr");
15267 }
15268 ao2_iterator_destroy(&i);
15269 if (pruned) {
15270 unlink_marked_peers_from_tables();
15271 ast_cli(a->fd, "%d peers pruned.\n", pruned);
15272 } else
15273 ast_cli(a->fd, "No peers found to prune.\n");
15274 }
15275 } else {
15276 if (prunepeer) {
15277 struct sip_peer tmp;
15278 ast_copy_string(tmp.name, name, sizeof(tmp.name));
15279 if ((peer = ao2_t_find(peers, &tmp, OBJ_POINTER | OBJ_UNLINK, "finding to unlink from peers"))) {
15280 if (peer->addr.sin_addr.s_addr) {
15281 ao2_t_unlink(peers_by_ip, peer, "unlinking peer from peers_by_ip also");
15282 }
15283 if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
15284 ast_cli(a->fd, "Peer '%s' is not a Realtime peer, cannot be pruned.\n", name);
15285
15286 ao2_t_link(peers, peer, "link peer into peer table");
15287 if (peer->addr.sin_addr.s_addr) {
15288 ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
15289 }
15290
15291 } else
15292 ast_cli(a->fd, "Peer '%s' pruned.\n", name);
15293 unref_peer(peer, "sip_prune_realtime: unref_peer: tossing temp peer ptr");
15294 } else
15295 ast_cli(a->fd, "Peer '%s' not found.\n", name);
15296 }
15297 }
15298
15299 return CLI_SUCCESS;
15300 }
15301
15302
15303 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref)
15304 {
15305 int x, codec;
15306
15307 for(x = 0; x < 32 ; x++) {
15308 codec = ast_codec_pref_index(pref, x);
15309 if (!codec)
15310 break;
15311 ast_cli(fd, "%s", ast_getformatname(codec));
15312 ast_cli(fd, ":%d", pref->framing[x]);
15313 if (x < 31 && ast_codec_pref_index(pref, x + 1))
15314 ast_cli(fd, ",");
15315 }
15316 if (!x)
15317 ast_cli(fd, "none");
15318 }
15319
15320
15321 static const char *domain_mode_to_text(const enum domain_mode mode)
15322 {
15323 switch (mode) {
15324 case SIP_DOMAIN_AUTO:
15325 return "[Automatic]";
15326 case SIP_DOMAIN_CONFIG:
15327 return "[Configured]";
15328 }
15329
15330 return "";
15331 }
15332
15333
15334 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15335 {
15336 struct domain *d;
15337 #define FORMAT "%-40.40s %-20.20s %-16.16s\n"
15338
15339 switch (cmd) {
15340 case CLI_INIT:
15341 e->command = "sip show domains";
15342 e->usage =
15343 "Usage: sip show domains\n"
15344 " Lists all configured SIP local domains.\n"
15345 " Asterisk only responds to SIP messages to local domains.\n";
15346 return NULL;
15347 case CLI_GENERATE:
15348 return NULL;
15349 }
15350
15351 if (AST_LIST_EMPTY(&domain_list)) {
15352 ast_cli(a->fd, "SIP Domain support not enabled.\n\n");
15353 return CLI_SUCCESS;
15354 } else {
15355 ast_cli(a->fd, FORMAT, "Our local SIP domains:", "Context", "Set by");
15356 AST_LIST_LOCK(&domain_list);
15357 AST_LIST_TRAVERSE(&domain_list, d, list)
15358 ast_cli(a->fd, FORMAT, d->domain, S_OR(d->context, "(default)"),
15359 domain_mode_to_text(d->mode));
15360 AST_LIST_UNLOCK(&domain_list);
15361 ast_cli(a->fd, "\n");
15362 return CLI_SUCCESS;
15363 }
15364 }
15365 #undef FORMAT
15366
15367 static char mandescr_show_peer[] =
15368 "Description: Show one SIP peer with details on current status.\n"
15369 "Variables: \n"
15370 " Peer: <name> The peer name you want to check.\n"
15371 " ActionID: <id> Optional action ID for this AMI transaction.\n";
15372
15373
15374 static int manager_sip_show_peer(struct mansession *s, const struct message *m)
15375 {
15376 const char *a[4];
15377 const char *peer;
15378
15379 peer = astman_get_header(m, "Peer");
15380 if (ast_strlen_zero(peer)) {
15381 astman_send_error(s, m, "Peer: <name> missing.");
15382 return 0;
15383 }
15384 a[0] = "sip";
15385 a[1] = "show";
15386 a[2] = "peer";
15387 a[3] = peer;
15388
15389 _sip_show_peer(1, -1, s, m, 4, a);
15390 astman_append(s, "\r\n\r\n" );
15391 return 0;
15392 }
15393
15394
15395 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15396 {
15397 switch (cmd) {
15398 case CLI_INIT:
15399 e->command = "sip show peer";
15400 e->usage =
15401 "Usage: sip show peer <name> [load]\n"
15402 " Shows all details on one SIP peer and the current status.\n"
15403 " Option \"load\" forces lookup of peer in realtime storage.\n";
15404 return NULL;
15405 case CLI_GENERATE:
15406 return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
15407 }
15408 return _sip_show_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
15409 }
15410
15411
15412 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
15413 {
15414 struct sip_peer *peer;
15415 int load_realtime;
15416
15417 if (argc < 4)
15418 return CLI_SHOWUSAGE;
15419
15420 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
15421 if ((peer = find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0))) {
15422 sip_poke_peer(peer, 1);
15423 unref_peer(peer, "qualify: done with peer");
15424 } else if (type == 0) {
15425 ast_cli(fd, "Peer '%s' not found\n", argv[3]);
15426 } else {
15427 astman_send_error(s, m, "Peer not found");
15428 }
15429 return CLI_SUCCESS;
15430 }
15431
15432
15433 static int manager_sip_qualify_peer(struct mansession *s, const struct message *m)
15434 {
15435 const char *a[4];
15436 const char *peer;
15437
15438 peer = astman_get_header(m, "Peer");
15439 if (ast_strlen_zero(peer)) {
15440 astman_send_error(s, m, "Peer: <name> missing.");
15441 return 0;
15442 }
15443 a[0] = "sip";
15444 a[1] = "qualify";
15445 a[2] = "peer";
15446 a[3] = peer;
15447
15448 _sip_qualify_peer(1, -1, s, m, 4, a);
15449 astman_append(s, "\r\n\r\n" );
15450 return 0;
15451 }
15452
15453
15454 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15455 {
15456 switch (cmd) {
15457 case CLI_INIT:
15458 e->command = "sip qualify peer";
15459 e->usage =
15460 "Usage: sip qualify peer <name> [load]\n"
15461 " Requests a response from one SIP peer and the current status.\n"
15462 " Option \"load\" forces lookup of peer in realtime storage.\n";
15463 return NULL;
15464 case CLI_GENERATE:
15465 return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
15466 }
15467 return _sip_qualify_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
15468 }
15469
15470
15471 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer)
15472 {
15473 struct sip_mailbox *mailbox;
15474
15475 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
15476 ast_str_append(mailbox_str, 0, "%s%s%s%s",
15477 mailbox->mailbox,
15478 ast_strlen_zero(mailbox->context) ? "" : "@",
15479 S_OR(mailbox->context, ""),
15480 AST_LIST_NEXT(mailbox, entry) ? "," : "");
15481 }
15482 }
15483
15484 static struct _map_x_s faxecmodes[] = {
15485 { SIP_PAGE2_T38SUPPORT_UDPTL, "None"},
15486 { SIP_PAGE2_T38SUPPORT_UDPTL_FEC, "FEC"},
15487 { SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY, "Redundancy"},
15488 { -1, NULL},
15489 };
15490
15491 static const char *faxec2str(int faxec)
15492 {
15493 return map_x_s(faxecmodes, faxec, "Unknown");
15494 }
15495
15496
15497 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
15498 {
15499 char status[30] = "";
15500 char cbuf[256];
15501 struct sip_peer *peer;
15502 char codec_buf[512];
15503 struct ast_codec_pref *pref;
15504 struct ast_variable *v;
15505 struct sip_auth *auth;
15506 int x = 0, codec = 0, load_realtime;
15507 int realtimepeers;
15508
15509 realtimepeers = ast_check_realtime("sippeers");
15510
15511 if (argc < 4)
15512 return CLI_SHOWUSAGE;
15513
15514 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
15515 peer = find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0);
15516
15517 if (s) {
15518 if (peer) {
15519 const char *id = astman_get_header(m, "ActionID");
15520
15521 astman_append(s, "Response: Success\r\n");
15522 if (!ast_strlen_zero(id))
15523 astman_append(s, "ActionID: %s\r\n", id);
15524 } else {
15525 snprintf (cbuf, sizeof(cbuf), "Peer %s not found.", argv[3]);
15526 astman_send_error(s, m, cbuf);
15527 return CLI_SUCCESS;
15528 }
15529 }
15530 if (peer && type==0 ) {
15531 struct ast_str *mailbox_str = ast_str_alloca(512);
15532 ast_cli(fd, "\n\n");
15533 ast_cli(fd, " * Name : %s\n", peer->name);
15534 if (realtimepeers) {
15535 ast_cli(fd, " Realtime peer: %s\n", peer->is_realtime ? "Yes, cached" : "No");
15536 }
15537 ast_cli(fd, " Secret : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
15538 ast_cli(fd, " MD5Secret : %s\n", ast_strlen_zero(peer->md5secret)?"<Not set>":"<Set>");
15539 ast_cli(fd, " Remote Secret: %s\n", ast_strlen_zero(peer->remotesecret)?"<Not set>":"<Set>");
15540 for (auth = peer->auth; auth; auth = auth->next) {
15541 ast_cli(fd, " Realm-auth : Realm %-15.15s User %-10.20s ", auth->realm, auth->username);
15542 ast_cli(fd, "%s\n", !ast_strlen_zero(auth->secret)?"<Secret set>":(!ast_strlen_zero(auth->md5secret)?"<MD5secret set>" : "<Not set>"));
15543 }
15544 ast_cli(fd, " Context : %s\n", peer->context);
15545 ast_cli(fd, " Subscr.Cont. : %s\n", S_OR(peer->subscribecontext, "<Not set>") );
15546 ast_cli(fd, " Language : %s\n", peer->language);
15547 if (!ast_strlen_zero(peer->accountcode))
15548 ast_cli(fd, " Accountcode : %s\n", peer->accountcode);
15549 ast_cli(fd, " AMA flags : %s\n", ast_cdr_flags2str(peer->amaflags));
15550 ast_cli(fd, " Transfer mode: %s\n", transfermode2str(peer->allowtransfer));
15551 ast_cli(fd, " CallingPres : %s\n", ast_describe_caller_presentation(peer->callingpres));
15552 if (!ast_strlen_zero(peer->fromuser))
15553 ast_cli(fd, " FromUser : %s\n", peer->fromuser);
15554 if (!ast_strlen_zero(peer->fromdomain))
15555 ast_cli(fd, " FromDomain : %s\n", peer->fromdomain);
15556 ast_cli(fd, " Callgroup : ");
15557 print_group(fd, peer->callgroup, 0);
15558 ast_cli(fd, " Pickupgroup : ");
15559 print_group(fd, peer->pickupgroup, 0);
15560 peer_mailboxes_to_str(&mailbox_str, peer);
15561 ast_cli(fd, " Mailbox : %s\n", mailbox_str->str);
15562 ast_cli(fd, " VM Extension : %s\n", peer->vmexten);
15563 ast_cli(fd, " LastMsgsSent : %d/%d\n", (peer->lastmsgssent & 0x7fff0000) >> 16, peer->lastmsgssent & 0xffff);
15564 ast_cli(fd, " Call limit : %d\n", peer->call_limit);
15565 if (peer->busy_level)
15566 ast_cli(fd, " Busy level : %d\n", peer->busy_level);
15567 ast_cli(fd, " Dynamic : %s\n", cli_yesno(peer->host_dynamic));
15568 ast_cli(fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
15569 ast_cli(fd, " MaxCallBR : %d kbps\n", peer->maxcallbitrate);
15570 ast_cli(fd, " Expire : %ld\n", ast_sched_when(sched, peer->expire));
15571 ast_cli(fd, " Insecure : %s\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
15572 ast_cli(fd, " Nat : %s\n", nat2str(ast_test_flag(&peer->flags[0], SIP_NAT)));
15573 ast_cli(fd, " ACL : %s\n", cli_yesno(peer->ha != NULL));
15574 ast_cli(fd, " T.38 support : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
15575 ast_cli(fd, " T.38 EC mode : %s\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
15576 ast_cli(fd, " T.38 MaxDtgrm: %d\n", peer->t38_maxdatagram);
15577 ast_cli(fd, " DirectMedia : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)));
15578 ast_cli(fd, " PromiscRedir : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)));
15579 ast_cli(fd, " User=Phone : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)));
15580 ast_cli(fd, " Video Support: %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT) || ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS)));
15581 ast_cli(fd, " Text Support : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)));
15582 ast_cli(fd, " Ign SDP ver : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_IGNORESDPVERSION)));
15583 ast_cli(fd, " Trust RPID : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_TRUSTRPID)));
15584 ast_cli(fd, " Send RPID : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_SENDRPID)));
15585 ast_cli(fd, " Subscriptions: %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
15586 ast_cli(fd, " Overlap dial : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWOVERLAP)));
15587 ast_cli(fd, " Forward Loop : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_FORWARD_LOOP_DETECTED)));
15588 if (peer->outboundproxy)
15589 ast_cli(fd, " Outb. proxy : %s %s\n", ast_strlen_zero(peer->outboundproxy->name) ? "<not set>" : peer->outboundproxy->name,
15590 peer->outboundproxy->force ? "(forced)" : "");
15591
15592
15593 ast_cli(fd, " DTMFmode : %s\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
15594 ast_cli(fd, " Timer T1 : %d\n", peer->timer_t1);
15595 ast_cli(fd, " Timer B : %d\n", peer->timer_b);
15596 ast_cli(fd, " ToHost : %s\n", peer->tohost);
15597 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));
15598 ast_cli(fd, " Defaddr->IP : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
15599 ast_cli(fd, " Prim.Transp. : %s\n", get_transport(peer->socket.type));
15600 ast_cli(fd, " Allowed.Trsp : %s\n", get_transport_list(peer->transports));
15601 if (!ast_strlen_zero(global_regcontext))
15602 ast_cli(fd, " Reg. exten : %s\n", peer->regexten);
15603 ast_cli(fd, " Def. Username: %s\n", peer->username);
15604 ast_cli(fd, " SIP Options : ");
15605 if (peer->sipoptions) {
15606 int lastoption = -1;
15607 for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
15608 if (sip_options[x].id != lastoption) {
15609 if (peer->sipoptions & sip_options[x].id)
15610 ast_cli(fd, "%s ", sip_options[x].text);
15611 lastoption = x;
15612 }
15613 }
15614 } else
15615 ast_cli(fd, "(none)");
15616
15617 ast_cli(fd, "\n");
15618 ast_cli(fd, " Codecs : ");
15619 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
15620 ast_cli(fd, "%s\n", codec_buf);
15621 ast_cli(fd, " Codec Order : (");
15622 print_codec_to_cli(fd, &peer->prefs);
15623 ast_cli(fd, ")\n");
15624
15625 ast_cli(fd, " Auto-Framing : %s \n", cli_yesno(peer->autoframing));
15626 ast_cli(fd, " 100 on REG : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_REGISTERTRYING) ? "Yes" : "No");
15627 ast_cli(fd, " Status : ");
15628 peer_status(peer, status, sizeof(status));
15629 ast_cli(fd, "%s\n", status);
15630 ast_cli(fd, " Useragent : %s\n", peer->useragent);
15631 ast_cli(fd, " Reg. Contact : %s\n", peer->fullcontact);
15632 ast_cli(fd, " Qualify Freq : %d ms\n", peer->qualifyfreq);
15633 if (peer->chanvars) {
15634 ast_cli(fd, " Variables :\n");
15635 for (v = peer->chanvars ; v ; v = v->next)
15636 ast_cli(fd, " %s = %s\n", v->name, v->value);
15637 }
15638
15639 ast_cli(fd, " Sess-Timers : %s\n", stmode2str(peer->stimer.st_mode_oper));
15640 ast_cli(fd, " Sess-Refresh : %s\n", strefresher2str(peer->stimer.st_ref));
15641 ast_cli(fd, " Sess-Expires : %d secs\n", peer->stimer.st_max_se);
15642 ast_cli(fd, " Min-Sess : %d secs\n", peer->stimer.st_min_se);
15643 ast_cli(fd, " Parkinglot : %s\n", peer->parkinglot);
15644 ast_cli(fd, "\n");
15645 peer = unref_peer(peer, "sip_show_peer: unref_peer: done with peer ptr");
15646 } else if (peer && type == 1) {
15647 char buffer[256];
15648 struct ast_str *mailbox_str = ast_str_alloca(512);
15649 astman_append(s, "Channeltype: SIP\r\n");
15650 astman_append(s, "ObjectName: %s\r\n", peer->name);
15651 astman_append(s, "ChanObjectType: peer\r\n");
15652 astman_append(s, "SecretExist: %s\r\n", ast_strlen_zero(peer->secret)?"N":"Y");
15653 astman_append(s, "RemoteSecretExist: %s\r\n", ast_strlen_zero(peer->remotesecret)?"N":"Y");
15654 astman_append(s, "MD5SecretExist: %s\r\n", ast_strlen_zero(peer->md5secret)?"N":"Y");
15655 astman_append(s, "Context: %s\r\n", peer->context);
15656 astman_append(s, "Language: %s\r\n", peer->language);
15657 if (!ast_strlen_zero(peer->accountcode))
15658 astman_append(s, "Accountcode: %s\r\n", peer->accountcode);
15659 astman_append(s, "AMAflags: %s\r\n", ast_cdr_flags2str(peer->amaflags));
15660 astman_append(s, "CID-CallingPres: %s\r\n", ast_describe_caller_presentation(peer->callingpres));
15661 if (!ast_strlen_zero(peer->fromuser))
15662 astman_append(s, "SIP-FromUser: %s\r\n", peer->fromuser);
15663 if (!ast_strlen_zero(peer->fromdomain))
15664 astman_append(s, "SIP-FromDomain: %s\r\n", peer->fromdomain);
15665 astman_append(s, "Callgroup: ");
15666 astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->callgroup));
15667 astman_append(s, "Pickupgroup: ");
15668 astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->pickupgroup));
15669 peer_mailboxes_to_str(&mailbox_str, peer);
15670 astman_append(s, "VoiceMailbox: %s\r\n", mailbox_str->str);
15671 astman_append(s, "TransferMode: %s\r\n", transfermode2str(peer->allowtransfer));
15672 astman_append(s, "LastMsgsSent: %d\r\n", peer->lastmsgssent);
15673 astman_append(s, "Call-limit: %d\r\n", peer->call_limit);
15674 astman_append(s, "Busy-level: %d\r\n", peer->busy_level);
15675 astman_append(s, "MaxCallBR: %d kbps\r\n", peer->maxcallbitrate);
15676 astman_append(s, "Dynamic: %s\r\n", peer->host_dynamic?"Y":"N");
15677 astman_append(s, "Callerid: %s\r\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, ""));
15678 astman_append(s, "RegExpire: %ld seconds\r\n", ast_sched_when(sched, peer->expire));
15679 astman_append(s, "SIP-AuthInsecure: %s\r\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
15680 astman_append(s, "SIP-NatSupport: %s\r\n", nat2str(ast_test_flag(&peer->flags[0], SIP_NAT)));
15681 astman_append(s, "ACL: %s\r\n", (peer->ha?"Y":"N"));
15682 astman_append(s, "SIP-CanReinvite: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)?"Y":"N"));
15683 astman_append(s, "SIP-DirectMedia: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)?"Y":"N"));
15684 astman_append(s, "SIP-PromiscRedir: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)?"Y":"N"));
15685 astman_append(s, "SIP-UserPhone: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)?"Y":"N"));
15686 astman_append(s, "SIP-VideoSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)?"Y":"N"));
15687 astman_append(s, "SIP-TextSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)?"Y":"N"));
15688 astman_append(s, "SIP-T.38Support: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)?"Y":"N"));
15689 astman_append(s, "SIP-T.38EC: %s\r\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
15690 astman_append(s, "SIP-T.38MaxDtgrm: %d\r\n", peer->t38_maxdatagram);
15691 astman_append(s, "SIP-Sess-Timers: %s\r\n", stmode2str(peer->stimer.st_mode_oper));
15692 astman_append(s, "SIP-Sess-Refresh: %s\r\n", strefresher2str(peer->stimer.st_ref));
15693 astman_append(s, "SIP-Sess-Expires: %d\r\n", peer->stimer.st_max_se);
15694 astman_append(s, "SIP-Sess-Min: %d\r\n", peer->stimer.st_min_se);
15695
15696
15697 astman_append(s, "SIP-DTMFmode: %s\r\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
15698 astman_append(s, "ToHost: %s\r\n", peer->tohost);
15699 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));
15700 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));
15701 astman_append(s, "Default-Username: %s\r\n", peer->username);
15702 if (!ast_strlen_zero(global_regcontext))
15703 astman_append(s, "RegExtension: %s\r\n", peer->regexten);
15704 astman_append(s, "Codecs: ");
15705 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
15706 astman_append(s, "%s\r\n", codec_buf);
15707 astman_append(s, "CodecOrder: ");
15708 pref = &peer->prefs;
15709 for(x = 0; x < 32 ; x++) {
15710 codec = ast_codec_pref_index(pref, x);
15711 if (!codec)
15712 break;
15713 astman_append(s, "%s", ast_getformatname(codec));
15714 if (x < 31 && ast_codec_pref_index(pref, x+1))
15715 astman_append(s, ",");
15716 }
15717
15718 astman_append(s, "\r\n");
15719 astman_append(s, "Status: ");
15720 peer_status(peer, status, sizeof(status));
15721 astman_append(s, "%s\r\n", status);
15722 astman_append(s, "SIP-Useragent: %s\r\n", peer->useragent);
15723 astman_append(s, "Reg-Contact: %s\r\n", peer->fullcontact);
15724 astman_append(s, "QualifyFreq: %d ms\r\n", peer->qualifyfreq);
15725 astman_append(s, "Parkinglot: %s\r\n", peer->parkinglot);
15726 if (peer->chanvars) {
15727 for (v = peer->chanvars ; v ; v = v->next) {
15728 astman_append(s, "ChanVariable: %s=%s\r\n", v->name, v->value);
15729 }
15730 }
15731
15732 peer = unref_peer(peer, "sip_show_peer: unref_peer: done with peer");
15733
15734 } else {
15735 ast_cli(fd, "Peer %s not found.\n", argv[3]);
15736 ast_cli(fd, "\n");
15737 }
15738
15739 return CLI_SUCCESS;
15740 }
15741
15742
15743 static char *complete_sip_user(const char *word, int state)
15744 {
15745 char *result = NULL;
15746 int wordlen = strlen(word);
15747 int which = 0;
15748 struct ao2_iterator user_iter;
15749 struct sip_peer *user;
15750
15751 user_iter = ao2_iterator_init(peers, 0);
15752 while ((user = ao2_iterator_next(&user_iter))) {
15753 ao2_lock(user);
15754 if (!(user->type & SIP_TYPE_USER)) {
15755 ao2_unlock(user);
15756 unref_peer(user, "complete sip user");
15757 continue;
15758 }
15759
15760 if (!strncasecmp(word, user->name, wordlen) && ++which > state) {
15761 result = ast_strdup(user->name);
15762 }
15763 ao2_unlock(user);
15764 unref_peer(user, "complete sip user");
15765 }
15766 ao2_iterator_destroy(&user_iter);
15767 return result;
15768 }
15769
15770 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state)
15771 {
15772 if (pos == 3)
15773 return complete_sip_user(word, state);
15774
15775 return NULL;
15776 }
15777
15778
15779 static char *sip_show_user(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15780 {
15781 char cbuf[256];
15782 struct sip_peer *user;
15783 struct ast_variable *v;
15784 int load_realtime;
15785
15786 switch (cmd) {
15787 case CLI_INIT:
15788 e->command = "sip show user";
15789 e->usage =
15790 "Usage: sip show user <name> [load]\n"
15791 " Shows all details on one SIP user and the current status.\n"
15792 " Option \"load\" forces lookup of peer in realtime storage.\n";
15793 return NULL;
15794 case CLI_GENERATE:
15795 return complete_sip_show_user(a->line, a->word, a->pos, a->n);
15796 }
15797
15798 if (a->argc < 4)
15799 return CLI_SHOWUSAGE;
15800
15801
15802 load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? TRUE : FALSE;
15803
15804 if ((user = find_peer(a->argv[3], NULL, load_realtime, FINDUSERS, FALSE, 0))) {
15805 ao2_lock(user);
15806 ast_cli(a->fd, "\n\n");
15807 ast_cli(a->fd, " * Name : %s\n", user->name);
15808 ast_cli(a->fd, " Secret : %s\n", ast_strlen_zero(user->secret)?"<Not set>":"<Set>");
15809 ast_cli(a->fd, " MD5Secret : %s\n", ast_strlen_zero(user->md5secret)?"<Not set>":"<Set>");
15810 ast_cli(a->fd, " Context : %s\n", user->context);
15811 ast_cli(a->fd, " Language : %s\n", user->language);
15812 if (!ast_strlen_zero(user->accountcode))
15813 ast_cli(a->fd, " Accountcode : %s\n", user->accountcode);
15814 ast_cli(a->fd, " AMA flags : %s\n", ast_cdr_flags2str(user->amaflags));
15815 ast_cli(a->fd, " Transfer mode: %s\n", transfermode2str(user->allowtransfer));
15816 ast_cli(a->fd, " MaxCallBR : %d kbps\n", user->maxcallbitrate);
15817 ast_cli(a->fd, " CallingPres : %s\n", ast_describe_caller_presentation(user->callingpres));
15818 ast_cli(a->fd, " Call limit : %d\n", user->call_limit);
15819 ast_cli(a->fd, " Callgroup : ");
15820 print_group(a->fd, user->callgroup, 0);
15821 ast_cli(a->fd, " Pickupgroup : ");
15822 print_group(a->fd, user->pickupgroup, 0);
15823 ast_cli(a->fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), user->cid_name, user->cid_num, "<unspecified>"));
15824 ast_cli(a->fd, " ACL : %s\n", cli_yesno(user->ha != NULL));
15825 ast_cli(a->fd, " Sess-Timers : %s\n", stmode2str(user->stimer.st_mode_oper));
15826 ast_cli(a->fd, " Sess-Refresh : %s\n", strefresher2str(user->stimer.st_ref));
15827 ast_cli(a->fd, " Sess-Expires : %d secs\n", user->stimer.st_max_se);
15828 ast_cli(a->fd, " Sess-Min-SE : %d secs\n", user->stimer.st_min_se);
15829
15830 ast_cli(a->fd, " Codec Order : (");
15831 print_codec_to_cli(a->fd, &user->prefs);
15832 ast_cli(a->fd, ")\n");
15833
15834 ast_cli(a->fd, " Auto-Framing: %s \n", cli_yesno(user->autoframing));
15835 if (user->chanvars) {
15836 ast_cli(a->fd, " Variables :\n");
15837 for (v = user->chanvars ; v ; v = v->next)
15838 ast_cli(a->fd, " %s = %s\n", v->name, v->value);
15839 }
15840
15841 ast_cli(a->fd, "\n");
15842
15843 ao2_unlock(user);
15844 unref_peer(user, "sip show user");
15845 } else {
15846 ast_cli(a->fd, "User %s not found.\n", a->argv[3]);
15847 ast_cli(a->fd, "\n");
15848 }
15849
15850 return CLI_SUCCESS;
15851 }
15852
15853
15854 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15855 {
15856 struct ast_str *cbuf;
15857 struct ast_cb_names cbnames = {9, { "retrans_pkt",
15858 "__sip_autodestruct",
15859 "expire_register",
15860 "auto_congest",
15861 "sip_reg_timeout",
15862 "sip_poke_peer_s",
15863 "sip_poke_noanswer",
15864 "sip_reregister",
15865 "sip_reinvite_retry"},
15866 { retrans_pkt,
15867 __sip_autodestruct,
15868 expire_register,
15869 auto_congest,
15870 sip_reg_timeout,
15871 sip_poke_peer_s,
15872 sip_poke_noanswer,
15873 sip_reregister,
15874 sip_reinvite_retry}};
15875
15876 switch (cmd) {
15877 case CLI_INIT:
15878 e->command = "sip show sched";
15879 e->usage =
15880 "Usage: sip show sched\n"
15881 " Shows stats on what's in the sched queue at the moment\n";
15882 return NULL;
15883 case CLI_GENERATE:
15884 return NULL;
15885 }
15886
15887 cbuf = ast_str_alloca(2048);
15888
15889 ast_cli(a->fd, "\n");
15890 ast_sched_report(sched, &cbuf, &cbnames);
15891 ast_cli(a->fd, "%s", cbuf->str);
15892
15893 return CLI_SUCCESS;
15894 }
15895
15896
15897 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15898 {
15899 #define FORMAT2 "%-30.30s %-6.6s %-12.12s %8.8s %-20.20s %-25.25s\n"
15900 #define FORMAT "%-30.30s %-6.6s %-12.12s %8d %-20.20s %-25.25s\n"
15901 char host[80];
15902 char tmpdat[256];
15903 struct ast_tm tm;
15904 int counter = 0;
15905
15906 switch (cmd) {
15907 case CLI_INIT:
15908 e->command = "sip show registry";
15909 e->usage =
15910 "Usage: sip show registry\n"
15911 " Lists all registration requests and status.\n";
15912 return NULL;
15913 case CLI_GENERATE:
15914 return NULL;
15915 }
15916
15917 if (a->argc != 3)
15918 return CLI_SHOWUSAGE;
15919 ast_cli(a->fd, FORMAT2, "Host", "dnsmgr", "Username", "Refresh", "State", "Reg.Time");
15920
15921 ASTOBJ_CONTAINER_TRAVERSE(®l, 1, do {
15922 ASTOBJ_RDLOCK(iterator);
15923 snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
15924 if (iterator->regtime.tv_sec) {
15925 ast_localtime(&iterator->regtime, &tm, NULL);
15926 ast_strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T", &tm);
15927 } else
15928 tmpdat[0] = '\0';
15929 ast_cli(a->fd, FORMAT, host, (iterator->dnsmgr) ? "Y" : "N", iterator->username, iterator->refresh, regstate2str(iterator->regstate), tmpdat);
15930 ASTOBJ_UNLOCK(iterator);
15931 counter++;
15932 } while(0));
15933 ast_cli(a->fd, "%d SIP registrations.\n", counter);
15934 return CLI_SUCCESS;
15935 #undef FORMAT
15936 #undef FORMAT2
15937 }
15938
15939
15940
15941
15942
15943 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15944 {
15945 struct sip_peer *peer;
15946 int load_realtime = 0;
15947
15948 switch (cmd) {
15949 case CLI_INIT:
15950 e->command = "sip unregister";
15951 e->usage =
15952 "Usage: sip unregister <peer>\n"
15953 " Unregister (force expiration) a SIP peer from the registry\n";
15954 return NULL;
15955 case CLI_GENERATE:
15956 return complete_sip_unregister(a->line, a->word, a->pos, a->n);
15957 }
15958
15959 if (a->argc != 3)
15960 return CLI_SHOWUSAGE;
15961
15962 if ((peer = find_peer(a->argv[2], NULL, load_realtime, FINDPEERS, TRUE, 0))) {
15963 if (peer->expire > 0) {
15964 AST_SCHED_DEL_UNREF(sched, peer->expire,
15965 unref_peer(peer, "remove register expire ref"));
15966 expire_register(ref_peer(peer, "ref for expire_register"));
15967 ast_cli(a->fd, "Unregistered peer \'%s\'\n\n", a->argv[2]);
15968 } else {
15969 ast_cli(a->fd, "Peer %s not registered\n", a->argv[2]);
15970 }
15971 unref_peer(peer, "sip_unregister: unref_peer via sip_unregister: done with peer from find_peer call");
15972 } else {
15973 ast_cli(a->fd, "Peer unknown: \'%s\'. Not unregistered.\n", a->argv[2]);
15974 }
15975
15976 return CLI_SUCCESS;
15977 }
15978
15979
15980 static int show_chanstats_cb(void *__cur, void *__arg, int flags)
15981 {
15982 #define FORMAT2 "%-15.15s %-11.11s %-8.8s %-10.10s %-10.10s ( %%) %-6.6s %-10.10s %-10.10s ( %%) %-6.6s\n"
15983 #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"
15984 struct sip_pvt *cur = __cur;
15985 unsigned int rxcount, txcount, rxploss, txploss;
15986 char durbuf[10];
15987 int duration;
15988 int durh, durm, durs;
15989 struct ast_channel *c = cur->owner;
15990 struct __show_chan_arg *arg = __arg;
15991 int fd = arg->fd;
15992
15993
15994 if (cur->subscribed != NONE)
15995 return 0;
15996
15997 if (!cur->rtp) {
15998 if (sipdebug)
15999 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");
16000 return 0;
16001 }
16002 rxcount = ast_rtp_get_qosvalue(cur->rtp, AST_RTP_RXCOUNT);
16003 txcount = ast_rtp_get_qosvalue(cur->rtp, AST_RTP_TXCOUNT);
16004 rxploss = ast_rtp_get_qosvalue(cur->rtp, AST_RTP_RXPLOSS);
16005 txploss = ast_rtp_get_qosvalue(cur->rtp, AST_RTP_TXPLOSS);
16006
16007
16008 if (c && c->cdr && !ast_tvzero(c->cdr->start)) {
16009 duration = (int)(ast_tvdiff_ms(ast_tvnow(), c->cdr->start) / 1000);
16010 durh = duration / 3600;
16011 durm = (duration % 3600) / 60;
16012 durs = duration % 60;
16013 snprintf(durbuf, sizeof(durbuf), "%02d:%02d:%02d", durh, durm, durs);
16014 } else {
16015 durbuf[0] = '\0';
16016 }
16017
16018 ast_cli(fd, FORMAT,
16019 ast_inet_ntoa(cur->sa.sin_addr),
16020 cur->callid,
16021 durbuf,
16022 rxcount > (unsigned int) 100000 ? (unsigned int) (rxcount)/(unsigned int) 1000 : rxcount,
16023 rxcount > (unsigned int) 100000 ? "K":" ",
16024 rxploss,
16025 (rxcount + rxploss) > 0 ? (double) rxploss / (rxcount + rxploss) * 100 : 0,
16026 ast_rtp_get_qosvalue(cur->rtp, AST_RTP_RXJITTER),
16027 txcount > (unsigned int) 100000 ? (unsigned int) (txcount)/(unsigned int) 1000 : txcount,
16028 txcount > (unsigned int) 100000 ? "K":" ",
16029 txploss,
16030 txcount > 0 ? (double) txploss / txcount * 100 : 0,
16031 ast_rtp_get_qosvalue(cur->rtp, AST_RTP_TXJITTER)
16032 );
16033 arg->numchans++;
16034
16035 return 0;
16036 }
16037
16038
16039 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16040 {
16041 struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
16042
16043 switch (cmd) {
16044 case CLI_INIT:
16045 e->command = "sip show channelstats";
16046 e->usage =
16047 "Usage: sip show channelstats\n"
16048 " Lists all currently active SIP channel's RTCP statistics.\n"
16049 " Note that calls in the much optimized RTP P2P bridge mode will not show any packets here.";
16050 return NULL;
16051 case CLI_GENERATE:
16052 return NULL;
16053 }
16054
16055 if (a->argc != 3)
16056 return CLI_SHOWUSAGE;
16057
16058 ast_cli(a->fd, FORMAT2, "Peer", "Call ID", "Duration", "Recv: Pack", "Lost", "Jitter", "Send: Pack", "Lost", "Jitter");
16059
16060 ao2_t_callback(dialogs, OBJ_NODATA, show_chanstats_cb, &arg, "callback to sip show chanstats");
16061 ast_cli(a->fd, "%d active SIP channel%s\n", arg.numchans, (arg.numchans != 1) ? "s" : "");
16062 return CLI_SUCCESS;
16063 }
16064 #undef FORMAT
16065 #undef FORMAT2
16066
16067
16068 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16069 {
16070 int realtimepeers;
16071 int realtimeregs;
16072 char codec_buf[SIPBUFSIZE];
16073 const char *msg;
16074
16075 switch (cmd) {
16076 case CLI_INIT:
16077 e->command = "sip show settings";
16078 e->usage =
16079 "Usage: sip show settings\n"
16080 " Provides detailed list of the configuration of the SIP channel.\n";
16081 return NULL;
16082 case CLI_GENERATE:
16083 return NULL;
16084 }
16085
16086
16087 realtimepeers = ast_check_realtime("sippeers");
16088 realtimeregs = ast_check_realtime("sipregs");
16089
16090 if (a->argc != 3)
16091 return CLI_SHOWUSAGE;
16092 ast_cli(a->fd, "\n\nGlobal Settings:\n");
16093 ast_cli(a->fd, "----------------\n");
16094 ast_cli(a->fd, " UDP SIP Port: %d\n", ntohs(bindaddr.sin_port));
16095 ast_cli(a->fd, " UDP Bindaddress: %s\n", ast_inet_ntoa(bindaddr.sin_addr));
16096 ast_cli(a->fd, " TCP SIP Port: ");
16097 if (sip_tcp_desc.local_address.sin_family == AF_INET) {
16098 ast_cli(a->fd, "%d\n", ntohs(sip_tcp_desc.local_address.sin_port));
16099 ast_cli(a->fd, " TCP Bindaddress: %s\n", ast_inet_ntoa(sip_tcp_desc.local_address.sin_addr));
16100 } else {
16101 ast_cli(a->fd, "Disabled\n");
16102 }
16103 ast_cli(a->fd, " TLS SIP Port: ");
16104 if (default_tls_cfg.enabled != FALSE) {
16105 ast_cli(a->fd, "%d\n", ntohs(sip_tls_desc.local_address.sin_port));
16106 ast_cli(a->fd, " TLS Bindaddress: %s\n", ast_inet_ntoa(sip_tls_desc.local_address.sin_addr));
16107 } else {
16108 ast_cli(a->fd, "Disabled\n");
16109 }
16110 ast_cli(a->fd, " Videosupport: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT)));
16111 ast_cli(a->fd, " Textsupport: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT)));
16112 ast_cli(a->fd, " Ignore SDP sess. ver.: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION)));
16113 ast_cli(a->fd, " AutoCreate Peer: %s\n", cli_yesno(sip_cfg.autocreatepeer));
16114 ast_cli(a->fd, " Match Auth Username: %s\n", cli_yesno(global_match_auth_username));
16115 ast_cli(a->fd, " Allow unknown access: %s\n", cli_yesno(sip_cfg.allowguest));
16116 ast_cli(a->fd, " Allow subscriptions: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
16117 ast_cli(a->fd, " Allow overlap dialing: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP)));
16118 ast_cli(a->fd, " Allow promsic. redir: %s\n", cli_yesno(ast_test_flag(&global_flags[0], SIP_PROMISCREDIR)));
16119 ast_cli(a->fd, " Enable call counters: %s\n", cli_yesno(global_callcounter));
16120 ast_cli(a->fd, " SIP domain support: %s\n", cli_yesno(!AST_LIST_EMPTY(&domain_list)));
16121 ast_cli(a->fd, " Realm. auth: %s\n", cli_yesno(authl != NULL));
16122 ast_cli(a->fd, " Our auth realm %s\n", sip_cfg.realm);
16123 ast_cli(a->fd, " Call to non-local dom.: %s\n", cli_yesno(sip_cfg.allow_external_domains));
16124 ast_cli(a->fd, " URI user is phone no: %s\n", cli_yesno(ast_test_flag(&global_flags[0], SIP_USEREQPHONE)));
16125 ast_cli(a->fd, " Always auth rejects: %s\n", cli_yesno(sip_cfg.alwaysauthreject));
16126 ast_cli(a->fd, " Direct RTP setup: %s\n", cli_yesno(sip_cfg.directrtpsetup));
16127 ast_cli(a->fd, " User Agent: %s\n", global_useragent);
16128 ast_cli(a->fd, " SDP Session Name: %s\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
16129 ast_cli(a->fd, " SDP Owner Name: %s\n", ast_strlen_zero(global_sdpowner) ? "-" : global_sdpowner);
16130 ast_cli(a->fd, " Reg. context: %s\n", S_OR(global_regcontext, "(not set)"));
16131 ast_cli(a->fd, " Regexten on Qualify: %s\n", cli_yesno(sip_cfg.regextenonqualify));
16132 ast_cli(a->fd, " Caller ID: %s\n", default_callerid);
16133 ast_cli(a->fd, " From: Domain: %s\n", default_fromdomain);
16134 ast_cli(a->fd, " Record SIP history: %s\n", recordhistory ? "On" : "Off");
16135 ast_cli(a->fd, " Call Events: %s\n", sip_cfg.callevents ? "On" : "Off");
16136 ast_cli(a->fd, " Auth. Failure Events: %s\n", global_authfailureevents ? "On" : "Off");
16137
16138 ast_cli(a->fd, " T.38 support: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
16139 ast_cli(a->fd, " T.38 EC mode: %s\n", faxec2str(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
16140 ast_cli(a->fd, " T.38 MaxDtgrm: %d\n", global_t38_maxdatagram);
16141
16142 if (!realtimepeers && !realtimeregs)
16143 ast_cli(a->fd, " SIP realtime: Disabled\n" );
16144 else
16145 ast_cli(a->fd, " SIP realtime: Enabled\n" );
16146 ast_cli(a->fd, " Qualify Freq : %d ms\n", global_qualifyfreq);
16147 ast_cli(a->fd, "\nNetwork QoS Settings:\n");
16148 ast_cli(a->fd, "---------------------------\n");
16149 ast_cli(a->fd, " IP ToS SIP: %s\n", ast_tos2str(global_tos_sip));
16150 ast_cli(a->fd, " IP ToS RTP audio: %s\n", ast_tos2str(global_tos_audio));
16151 ast_cli(a->fd, " IP ToS RTP video: %s\n", ast_tos2str(global_tos_video));
16152 ast_cli(a->fd, " IP ToS RTP text: %s\n", ast_tos2str(global_tos_text));
16153 ast_cli(a->fd, " 802.1p CoS SIP: %d\n", global_cos_sip);
16154 ast_cli(a->fd, " 802.1p CoS RTP audio: %d\n", global_cos_audio);
16155 ast_cli(a->fd, " 802.1p CoS RTP video: %d\n", global_cos_video);
16156 ast_cli(a->fd, " 802.1p CoS RTP text: %d\n", global_cos_text);
16157 ast_cli(a->fd, " Jitterbuffer enabled: %s\n", cli_yesno(ast_test_flag(&global_jbconf, AST_JB_ENABLED)));
16158 ast_cli(a->fd, " Jitterbuffer forced: %s\n", cli_yesno(ast_test_flag(&global_jbconf, AST_JB_FORCED)));
16159 ast_cli(a->fd, " Jitterbuffer max size: %ld\n", global_jbconf.max_size);
16160 ast_cli(a->fd, " Jitterbuffer resync: %ld\n", global_jbconf.resync_threshold);
16161 ast_cli(a->fd, " Jitterbuffer impl: %s\n", global_jbconf.impl);
16162 ast_cli(a->fd, " Jitterbuffer log: %s\n", cli_yesno(ast_test_flag(&global_jbconf, AST_JB_LOG)));
16163
16164 ast_cli(a->fd, "\nNetwork Settings:\n");
16165 ast_cli(a->fd, "---------------------------\n");
16166
16167 if (localaddr == NULL)
16168 msg = "Disabled, no localnet list";
16169 else if (externip.sin_addr.s_addr == 0)
16170 msg = "Disabled, externip is 0.0.0.0";
16171 else if (stunaddr.sin_addr.s_addr != 0)
16172 msg = "Enabled using STUN";
16173 else if (!ast_strlen_zero(externhost))
16174 msg = "Enabled using externhost";
16175 else
16176 msg = "Enabled using externip";
16177 ast_cli(a->fd, " SIP address remapping: %s\n", msg);
16178 ast_cli(a->fd, " Externhost: %s\n", S_OR(externhost, "<none>"));
16179 ast_cli(a->fd, " Externip: %s:%d\n", ast_inet_ntoa(externip.sin_addr), ntohs(externip.sin_port));
16180 ast_cli(a->fd, " Externrefresh: %d\n", externrefresh);
16181 ast_cli(a->fd, " Internal IP: %s:%d\n", ast_inet_ntoa(internip.sin_addr), ntohs(internip.sin_port));
16182 {
16183 struct ast_ha *d;
16184 const char *prefix = "Localnet:";
16185 char buf[INET_ADDRSTRLEN];
16186
16187 for (d = localaddr; d ; prefix = "", d = d->next) {
16188 ast_cli(a->fd, " %-24s%s/%s\n",
16189 prefix, ast_inet_ntoa(d->netaddr),
16190 inet_ntop(AF_INET, &d->netmask, buf, sizeof(buf)) );
16191 }
16192 }
16193 ast_cli(a->fd, " STUN server: %s:%d\n", ast_inet_ntoa(stunaddr.sin_addr), ntohs(stunaddr.sin_port));
16194
16195 ast_cli(a->fd, "\nGlobal Signalling Settings:\n");
16196 ast_cli(a->fd, "---------------------------\n");
16197 ast_cli(a->fd, " Codecs: ");
16198 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, global_capability);
16199 ast_cli(a->fd, "%s\n", codec_buf);
16200 ast_cli(a->fd, " Codec Order: ");
16201 print_codec_to_cli(a->fd, &default_prefs);
16202 ast_cli(a->fd, "\n");
16203 ast_cli(a->fd, " Relax DTMF: %s\n", cli_yesno(global_relaxdtmf));
16204 ast_cli(a->fd, " RFC2833 Compensation: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_RFC2833_COMPENSATE)));
16205 ast_cli(a->fd, " Compact SIP headers: %s\n", cli_yesno(sip_cfg.compactheaders));
16206 ast_cli(a->fd, " RTP Keepalive: %d %s\n", global_rtpkeepalive, global_rtpkeepalive ? "" : "(Disabled)" );
16207 ast_cli(a->fd, " RTP Timeout: %d %s\n", global_rtptimeout, global_rtptimeout ? "" : "(Disabled)" );
16208 ast_cli(a->fd, " RTP Hold Timeout: %d %s\n", global_rtpholdtimeout, global_rtpholdtimeout ? "" : "(Disabled)");
16209 ast_cli(a->fd, " MWI NOTIFY mime type: %s\n", default_notifymime);
16210 ast_cli(a->fd, " DNS SRV lookup: %s\n", cli_yesno(sip_cfg.srvlookup));
16211 ast_cli(a->fd, " Pedantic SIP support: %s\n", cli_yesno(sip_cfg.pedanticsipchecking));
16212 ast_cli(a->fd, " Reg. min duration %d secs\n", min_expiry);
16213 ast_cli(a->fd, " Reg. max duration: %d secs\n", max_expiry);
16214 ast_cli(a->fd, " Reg. default duration: %d secs\n", default_expiry);
16215 ast_cli(a->fd, " Outbound reg. timeout: %d secs\n", global_reg_timeout);
16216 ast_cli(a->fd, " Outbound reg. attempts: %d\n", global_regattempts_max);
16217 ast_cli(a->fd, " Notify ringing state: %s\n", cli_yesno(sip_cfg.notifyringing));
16218 if (sip_cfg.notifyringing) {
16219 ast_cli(a->fd, " Include CID: %s%s\n",
16220 cli_yesno(sip_cfg.notifycid),
16221 sip_cfg.notifycid == IGNORE_CONTEXT ? " (Ignoring context)" : "");
16222 }
16223 ast_cli(a->fd, " Notify hold state: %s\n", cli_yesno(sip_cfg.notifyhold));
16224 ast_cli(a->fd, " SIP Transfer mode: %s\n", transfermode2str(sip_cfg.allowtransfer));
16225 ast_cli(a->fd, " Max Call Bitrate: %d kbps\n", default_maxcallbitrate);
16226 ast_cli(a->fd, " Auto-Framing: %s\n", cli_yesno(global_autoframing));
16227 ast_cli(a->fd, " Outb. proxy: %s %s\n", ast_strlen_zero(sip_cfg.outboundproxy.name) ? "<not set>" : sip_cfg.outboundproxy.name,
16228 sip_cfg.outboundproxy.force ? "(forced)" : "");
16229 ast_cli(a->fd, " Session Timers: %s\n", stmode2str(global_st_mode));
16230 ast_cli(a->fd, " Session Refresher: %s\n", strefresher2str (global_st_refresher));
16231 ast_cli(a->fd, " Session Expires: %d secs\n", global_max_se);
16232 ast_cli(a->fd, " Session Min-SE: %d secs\n", global_min_se);
16233 ast_cli(a->fd, " Timer T1: %d\n", global_t1);
16234 ast_cli(a->fd, " Timer T1 minimum: %d\n", global_t1min);
16235 ast_cli(a->fd, " Timer B: %d\n", global_timer_b);
16236 ast_cli(a->fd, " No premature media: %s\n", global_prematuremediafilter ? "Yes" : "No");
16237
16238 ast_cli(a->fd, "\nDefault Settings:\n");
16239 ast_cli(a->fd, "-----------------\n");
16240 ast_cli(a->fd, " Allowed transports: %s\n", get_transport_list(default_transports));
16241 ast_cli(a->fd, " Outbound transport: %s\n", get_transport(default_primary_transport));
16242 ast_cli(a->fd, " Context: %s\n", sip_cfg.default_context);
16243 ast_cli(a->fd, " Nat: %s\n", nat2str(ast_test_flag(&global_flags[0], SIP_NAT)));
16244 ast_cli(a->fd, " DTMF: %s\n", dtmfmode2str(ast_test_flag(&global_flags[0], SIP_DTMF)));
16245 ast_cli(a->fd, " Qualify: %d\n", default_qualify);
16246 ast_cli(a->fd, " Use ClientCode: %s\n", cli_yesno(ast_test_flag(&global_flags[0], SIP_USECLIENTCODE)));
16247 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" );
16248 ast_cli(a->fd, " Language: %s\n", default_language);
16249 ast_cli(a->fd, " MOH Interpret: %s\n", default_mohinterpret);
16250 ast_cli(a->fd, " MOH Suggest: %s\n", default_mohsuggest);
16251 ast_cli(a->fd, " Voice Mail Extension: %s\n", default_vmexten);
16252 ast_cli(a->fd, " Forward Detected Loops: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_FORWARD_LOOP_DETECTED)));
16253
16254 if (realtimepeers || realtimeregs) {
16255 ast_cli(a->fd, "\nRealtime SIP Settings:\n");
16256 ast_cli(a->fd, "----------------------\n");
16257 ast_cli(a->fd, " Realtime Peers: %s\n", cli_yesno(realtimepeers));
16258 ast_cli(a->fd, " Realtime Regs: %s\n", cli_yesno(realtimeregs));
16259 ast_cli(a->fd, " Cache Friends: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)));
16260 ast_cli(a->fd, " Update: %s\n", cli_yesno(sip_cfg.peer_rtupdate));
16261 ast_cli(a->fd, " Ignore Reg. Expire: %s\n", cli_yesno(sip_cfg.ignore_regexpire));
16262 ast_cli(a->fd, " Save sys. name: %s\n", cli_yesno(sip_cfg.rtsave_sysname));
16263 ast_cli(a->fd, " Auto Clear: %d\n", sip_cfg.rtautoclear);
16264 }
16265 ast_cli(a->fd, "\n----\n");
16266 return CLI_SUCCESS;
16267 }
16268
16269 static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16270 {
16271 #define FORMAT "%-30.30s %-12.12s %-10.10s %-10.10s\n"
16272 char host[80];
16273
16274 switch (cmd) {
16275 case CLI_INIT:
16276 e->command = "sip show mwi";
16277 e->usage =
16278 "Usage: sip show mwi\n"
16279 " Provides a list of MWI subscriptions and status.\n";
16280 return NULL;
16281 case CLI_GENERATE:
16282 return NULL;
16283 }
16284
16285 ast_cli(a->fd, FORMAT, "Host", "Username", "Mailbox", "Subscribed");
16286
16287 ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
16288 ASTOBJ_RDLOCK(iterator);
16289 snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
16290 ast_cli(a->fd, FORMAT, host, iterator->username, iterator->mailbox, iterator->subscribed ? "Yes" : "No");
16291 ASTOBJ_UNLOCK(iterator);
16292 } while(0));
16293
16294 return CLI_SUCCESS;
16295 #undef FORMAT
16296 }
16297
16298
16299
16300 static const char *subscription_type2str(enum subscriptiontype subtype)
16301 {
16302 int i;
16303
16304 for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
16305 if (subscription_types[i].type == subtype) {
16306 return subscription_types[i].text;
16307 }
16308 }
16309 return subscription_types[0].text;
16310 }
16311
16312
16313 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype)
16314 {
16315 int i;
16316
16317 for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
16318 if (subscription_types[i].type == subtype) {
16319 return &subscription_types[i];
16320 }
16321 }
16322 return &subscription_types[0];
16323 }
16324
16325
16326
16327
16328
16329
16330
16331
16332 #define FORMAT4 "%-15.15s %-15.15s %-15.15s %-15.15s %-13.13s %-15.15s %-10.10s %-6.6d\n"
16333 #define FORMAT3 "%-15.15s %-15.15s %-15.15s %-15.15s %-13.13s %-15.15s %-10.10s %-6.6s\n"
16334 #define FORMAT2 "%-15.15s %-15.15s %-15.15s %-15.15s %-7.7s %-15.15s %-6.6s\n"
16335 #define FORMAT "%-15.15s %-15.15s %-15.15s %-15.15s %-3.3s %-3.3s %-15.15s %-10.10s\n"
16336
16337
16338 static int show_channels_cb(void *__cur, void *__arg, int flags)
16339 {
16340 struct sip_pvt *cur = __cur;
16341 struct __show_chan_arg *arg = __arg;
16342 const struct sockaddr_in *dst = sip_real_dst(cur);
16343
16344
16345 if (cur->subscribed == NONE && !arg->subscriptions) {
16346
16347 const char *referstatus = cur->refer ? referstatus2str(cur->refer->status) : "";
16348 char formatbuf[SIPBUFSIZE/2];
16349
16350 ast_cli(arg->fd, FORMAT, ast_inet_ntoa(dst->sin_addr),
16351 S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
16352 cur->callid,
16353 ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0),
16354 cli_yesno(ast_test_flag(&cur->flags[1], SIP_PAGE2_CALL_ONHOLD)),
16355 cur->needdestroy ? "(d)" : "",
16356 cur->lastmsg ,
16357 referstatus
16358 );
16359 arg->numchans++;
16360 }
16361 if (cur->subscribed != NONE && arg->subscriptions) {
16362 struct ast_str *mailbox_str = ast_str_alloca(512);
16363 if (cur->subscribed == MWI_NOTIFICATION && cur->relatedpeer)
16364 peer_mailboxes_to_str(&mailbox_str, cur->relatedpeer);
16365 ast_cli(arg->fd, FORMAT4, ast_inet_ntoa(dst->sin_addr),
16366 S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
16367 cur->callid,
16368
16369 cur->subscribed == MWI_NOTIFICATION ? "--" : cur->subscribeuri,
16370 cur->subscribed == MWI_NOTIFICATION ? "<none>" : ast_extension_state2str(cur->laststate),
16371 subscription_type2str(cur->subscribed),
16372 cur->subscribed == MWI_NOTIFICATION ? S_OR(mailbox_str->str, "<none>") : "<none>",
16373 cur->expiry
16374 );
16375 arg->numchans++;
16376 }
16377 return 0;
16378 }
16379
16380
16381
16382
16383
16384
16385 static char *sip_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16386 {
16387 struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
16388
16389
16390 if (cmd == CLI_INIT) {
16391 e->command = "sip show {channels|subscriptions}";
16392 e->usage =
16393 "Usage: sip show channels\n"
16394 " Lists all currently active SIP calls (dialogs).\n"
16395 "Usage: sip show subscriptions\n"
16396 " Lists active SIP subscriptions.\n";
16397 return NULL;
16398 } else if (cmd == CLI_GENERATE)
16399 return NULL;
16400
16401 if (a->argc != e->args)
16402 return CLI_SHOWUSAGE;
16403 arg.subscriptions = !strcasecmp(a->argv[e->args - 1], "subscriptions");
16404 if (!arg.subscriptions)
16405 ast_cli(arg.fd, FORMAT2, "Peer", "User/ANR", "Call ID", "Format", "Hold", "Last Message", "Expiry");
16406 else
16407 ast_cli(arg.fd, FORMAT3, "Peer", "User", "Call ID", "Extension", "Last state", "Type", "Mailbox", "Expiry");
16408
16409
16410 ao2_t_callback(dialogs, OBJ_NODATA, show_channels_cb, &arg, "callback to show channels");
16411
16412
16413 ast_cli(arg.fd, "%d active SIP %s%s\n", arg.numchans,
16414 (arg.subscriptions ? "subscription" : "dialog"),
16415 ESS(arg.numchans));
16416 return CLI_SUCCESS;
16417 #undef FORMAT
16418 #undef FORMAT2
16419 #undef FORMAT3
16420 }
16421
16422
16423
16424
16425
16426
16427 static char *complete_sipch(const char *line, const char *word, int pos, int state)
16428 {
16429 int which=0;
16430 struct sip_pvt *cur;
16431 char *c = NULL;
16432 int wordlen = strlen(word);
16433 struct ao2_iterator i;
16434
16435 if (pos != 3) {
16436 return NULL;
16437 }
16438
16439 i = ao2_iterator_init(dialogs, 0);
16440 while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
16441 sip_pvt_lock(cur);
16442 if (!strncasecmp(word, cur->callid, wordlen) && ++which > state) {
16443 c = ast_strdup(cur->callid);
16444 sip_pvt_unlock(cur);
16445 dialog_unref(cur, "drop ref in iterator loop break");
16446 break;
16447 }
16448 sip_pvt_unlock(cur);
16449 dialog_unref(cur, "drop ref in iterator loop");
16450 }
16451 ao2_iterator_destroy(&i);
16452 return c;
16453 }
16454
16455
16456
16457 static char *complete_sip_peer(const char *word, int state, int flags2)
16458 {
16459 char *result = NULL;
16460 int wordlen = strlen(word);
16461 int which = 0;
16462 struct ao2_iterator i = ao2_iterator_init(peers, 0);
16463 struct sip_peer *peer;
16464
16465 while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
16466
16467 if (!strncasecmp(word, peer->name, wordlen) &&
16468 (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
16469 ++which > state)
16470 result = ast_strdup(peer->name);
16471 unref_peer(peer, "toss iterator peer ptr before break");
16472 if (result) {
16473 break;
16474 }
16475 }
16476 ao2_iterator_destroy(&i);
16477 return result;
16478 }
16479
16480
16481 static char *complete_sip_registered_peer(const char *word, int state, int flags2)
16482 {
16483 char *result = NULL;
16484 int wordlen = strlen(word);
16485 int which = 0;
16486 struct ao2_iterator i;
16487 struct sip_peer *peer;
16488
16489 i = ao2_iterator_init(peers, 0);
16490 while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
16491 if (!strncasecmp(word, peer->name, wordlen) &&
16492 (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
16493 ++which > state && peer->expire > 0)
16494 result = ast_strdup(peer->name);
16495 if (result) {
16496 unref_peer(peer, "toss iterator peer ptr before break");
16497 break;
16498 }
16499 unref_peer(peer, "toss iterator peer ptr");
16500 }
16501 ao2_iterator_destroy(&i);
16502 return result;
16503 }
16504
16505
16506 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state)
16507 {
16508 if (pos == 3)
16509 return complete_sipch(line, word, pos, state);
16510
16511 return NULL;
16512 }
16513
16514
16515 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state)
16516 {
16517 if (pos == 3) {
16518 return complete_sip_peer(word, state, 0);
16519 }
16520
16521 return NULL;
16522 }
16523
16524
16525 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state)
16526 {
16527 if (pos == 2)
16528 return complete_sip_registered_peer(word, state, 0);
16529
16530 return NULL;
16531 }
16532
16533
16534 static char *complete_sipnotify(const char *line, const char *word, int pos, int state)
16535 {
16536 char *c = NULL;
16537
16538 if (pos == 2) {
16539 int which = 0;
16540 char *cat = NULL;
16541 int wordlen = strlen(word);
16542
16543
16544
16545 if (!notify_types)
16546 return NULL;
16547
16548 while ( (cat = ast_category_browse(notify_types, cat)) ) {
16549 if (!strncasecmp(word, cat, wordlen) && ++which > state) {
16550 c = ast_strdup(cat);
16551 break;
16552 }
16553 }
16554 return c;
16555 }
16556
16557 if (pos > 2)
16558 return complete_sip_peer(word, state, 0);
16559
16560 return NULL;
16561 }
16562
16563
16564 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16565 {
16566 struct sip_pvt *cur;
16567 size_t len;
16568 int found = 0;
16569 struct ao2_iterator i;
16570
16571 switch (cmd) {
16572 case CLI_INIT:
16573 e->command = "sip show channel";
16574 e->usage =
16575 "Usage: sip show channel <call-id>\n"
16576 " Provides detailed status on a given SIP dialog (identified by SIP call-id).\n";
16577 return NULL;
16578 case CLI_GENERATE:
16579 return complete_sipch(a->line, a->word, a->pos, a->n);
16580 }
16581
16582 if (a->argc != 4)
16583 return CLI_SHOWUSAGE;
16584 len = strlen(a->argv[3]);
16585
16586 i = ao2_iterator_init(dialogs, 0);
16587 while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
16588 sip_pvt_lock(cur);
16589
16590 if (!strncasecmp(cur->callid, a->argv[3], len)) {
16591 char formatbuf[SIPBUFSIZE/2];
16592 ast_cli(a->fd, "\n");
16593 if (cur->subscribed != NONE)
16594 ast_cli(a->fd, " * Subscription (type: %s)\n", subscription_type2str(cur->subscribed));
16595 else
16596 ast_cli(a->fd, " * SIP Call\n");
16597 ast_cli(a->fd, " Curr. trans. direction: %s\n", ast_test_flag(&cur->flags[0], SIP_OUTGOING) ? "Outgoing" : "Incoming");
16598 ast_cli(a->fd, " Call-ID: %s\n", cur->callid);
16599 ast_cli(a->fd, " Owner channel ID: %s\n", cur->owner ? cur->owner->name : "<none>");
16600 ast_cli(a->fd, " Our Codec Capability: %d\n", cur->capability);
16601 ast_cli(a->fd, " Non-Codec Capability (DTMF): %d\n", cur->noncodeccapability);
16602 ast_cli(a->fd, " Their Codec Capability: %d\n", cur->peercapability);
16603 ast_cli(a->fd, " Joint Codec Capability: %d\n", cur->jointcapability);
16604 ast_cli(a->fd, " Format: %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0) );
16605 ast_cli(a->fd, " T.38 support %s\n", cli_yesno(cur->udptl != NULL));
16606 ast_cli(a->fd, " Video support %s\n", cli_yesno(cur->vrtp != NULL));
16607 ast_cli(a->fd, " MaxCallBR: %d kbps\n", cur->maxcallbitrate);
16608 ast_cli(a->fd, " Theoretical Address: %s:%d\n", ast_inet_ntoa(cur->sa.sin_addr), ntohs(cur->sa.sin_port));
16609 ast_cli(a->fd, " Received Address: %s:%d\n", ast_inet_ntoa(cur->recv.sin_addr), ntohs(cur->recv.sin_port));
16610 ast_cli(a->fd, " SIP Transfer mode: %s\n", transfermode2str(cur->allowtransfer));
16611 ast_cli(a->fd, " NAT Support: %s\n", nat2str(ast_test_flag(&cur->flags[0], SIP_NAT)));
16612 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)" );
16613 ast_cli(a->fd, " Our Tag: %s\n", cur->tag);
16614 ast_cli(a->fd, " Their Tag: %s\n", cur->theirtag);
16615 ast_cli(a->fd, " SIP User agent: %s\n", cur->useragent);
16616 if (!ast_strlen_zero(cur->username))
16617 ast_cli(a->fd, " Username: %s\n", cur->username);
16618 if (!ast_strlen_zero(cur->peername))
16619 ast_cli(a->fd, " Peername: %s\n", cur->peername);
16620 if (!ast_strlen_zero(cur->uri))
16621 ast_cli(a->fd, " Original uri: %s\n", cur->uri);
16622 if (!ast_strlen_zero(cur->cid_num))
16623 ast_cli(a->fd, " Caller-ID: %s\n", cur->cid_num);
16624 ast_cli(a->fd, " Need Destroy: %s\n", cli_yesno(cur->needdestroy));
16625 ast_cli(a->fd, " Last Message: %s\n", cur->lastmsg);
16626 ast_cli(a->fd, " Promiscuous Redir: %s\n", cli_yesno(ast_test_flag(&cur->flags[0], SIP_PROMISCREDIR)));
16627 ast_cli(a->fd, " Route: %s\n", cur->route ? cur->route->hop : "N/A");
16628 ast_cli(a->fd, " DTMF Mode: %s\n", dtmfmode2str(ast_test_flag(&cur->flags[0], SIP_DTMF)));
16629 ast_cli(a->fd, " SIP Options: ");
16630 if (cur->sipoptions) {
16631 int x;
16632 for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
16633 if (cur->sipoptions & sip_options[x].id)
16634 ast_cli(a->fd, "%s ", sip_options[x].text);
16635 }
16636 ast_cli(a->fd, "\n");
16637 } else
16638 ast_cli(a->fd, "(none)\n");
16639
16640 if (!cur->stimer)
16641 ast_cli(a->fd, " Session-Timer: Uninitiallized\n");
16642 else {
16643 ast_cli(a->fd, " Session-Timer: %s\n", cur->stimer->st_active ? "Active" : "Inactive");
16644 if (cur->stimer->st_active == TRUE) {
16645 ast_cli(a->fd, " S-Timer Interval: %d\n", cur->stimer->st_interval);
16646 ast_cli(a->fd, " S-Timer Refresher: %s\n", strefresher2str(cur->stimer->st_ref));
16647 ast_cli(a->fd, " S-Timer Expirys: %d\n", cur->stimer->st_expirys);
16648 ast_cli(a->fd, " S-Timer Sched Id: %d\n", cur->stimer->st_schedid);
16649 ast_cli(a->fd, " S-Timer Peer Sts: %s\n", cur->stimer->st_active_peer_ua ? "Active" : "Inactive");
16650 ast_cli(a->fd, " S-Timer Cached Min-SE: %d\n", cur->stimer->st_cached_min_se);
16651 ast_cli(a->fd, " S-Timer Cached SE: %d\n", cur->stimer->st_cached_max_se);
16652 ast_cli(a->fd, " S-Timer Cached Ref: %s\n", strefresher2str(cur->stimer->st_cached_ref));
16653 ast_cli(a->fd, " S-Timer Cached Mode: %s\n", stmode2str(cur->stimer->st_cached_mode));
16654 }
16655 }
16656
16657 ast_cli(a->fd, "\n\n");
16658
16659 found++;
16660 }
16661
16662 sip_pvt_unlock(cur);
16663
16664 ao2_t_ref(cur, -1, "toss dialog ptr set by iterator_next");
16665 }
16666 ao2_iterator_destroy(&i);
16667
16668 if (!found)
16669 ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
16670
16671 return CLI_SUCCESS;
16672 }
16673
16674
16675 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16676 {
16677 struct sip_pvt *cur;
16678 size_t len;
16679 int found = 0;
16680 struct ao2_iterator i;
16681
16682 switch (cmd) {
16683 case CLI_INIT:
16684 e->command = "sip show history";
16685 e->usage =
16686 "Usage: sip show history <call-id>\n"
16687 " Provides detailed dialog history on a given SIP call (specified by call-id).\n";
16688 return NULL;
16689 case CLI_GENERATE:
16690 return complete_sip_show_history(a->line, a->word, a->pos, a->n);
16691 }
16692
16693 if (a->argc != 4)
16694 return CLI_SHOWUSAGE;
16695
16696 if (!recordhistory)
16697 ast_cli(a->fd, "\n***Note: History recording is currently DISABLED. Use 'sip set history on' to ENABLE.\n");
16698
16699 len = strlen(a->argv[3]);
16700
16701 i = ao2_iterator_init(dialogs, 0);
16702 while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
16703 sip_pvt_lock(cur);
16704 if (!strncasecmp(cur->callid, a->argv[3], len)) {
16705 struct sip_history *hist;
16706 int x = 0;
16707
16708 ast_cli(a->fd, "\n");
16709 if (cur->subscribed != NONE)
16710 ast_cli(a->fd, " * Subscription\n");
16711 else
16712 ast_cli(a->fd, " * SIP Call\n");
16713 if (cur->history)
16714 AST_LIST_TRAVERSE(cur->history, hist, list)
16715 ast_cli(a->fd, "%d. %s\n", ++x, hist->event);
16716 if (x == 0)
16717 ast_cli(a->fd, "Call '%s' has no history\n", cur->callid);
16718 found++;
16719 }
16720 sip_pvt_unlock(cur);
16721 ao2_t_ref(cur, -1, "toss dialog ptr from iterator_next");
16722 }
16723 ao2_iterator_destroy(&i);
16724
16725 if (!found)
16726 ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
16727
16728 return CLI_SUCCESS;
16729 }
16730
16731
16732 static void sip_dump_history(struct sip_pvt *dialog)
16733 {
16734 int x = 0;
16735 struct sip_history *hist;
16736 static int errmsg = 0;
16737
16738 if (!dialog)
16739 return;
16740
16741 if (!option_debug && !sipdebug) {
16742 if (!errmsg) {
16743 ast_log(LOG_NOTICE, "You must have debugging enabled (SIP or Asterisk) in order to dump SIP history.\n");
16744 errmsg = 1;
16745 }
16746 return;
16747 }
16748
16749 ast_debug(1, "\n---------- SIP HISTORY for '%s' \n", dialog->callid);
16750 if (dialog->subscribed)
16751 ast_debug(1, " * Subscription\n");
16752 else
16753 ast_debug(1, " * SIP Call\n");
16754 if (dialog->history)
16755 AST_LIST_TRAVERSE(dialog->history, hist, list)
16756 ast_debug(1, " %-3.3d. %s\n", ++x, hist->event);
16757 if (!x)
16758 ast_debug(1, "Call '%s' has no history\n", dialog->callid);
16759 ast_debug(1, "\n---------- END SIP HISTORY for '%s' \n", dialog->callid);
16760 }
16761
16762
16763
16764 static void handle_request_info(struct sip_pvt *p, struct sip_request *req)
16765 {
16766 char buf[1024];
16767 unsigned int event;
16768 const char *c = get_header(req, "Content-Type");
16769
16770
16771 if (!strcasecmp(c, "application/dtmf-relay") ||
16772 !strcasecmp(c, "application/vnd.nortelnetworks.digits")) {
16773 unsigned int duration = 0;
16774
16775 if (!p->owner) {
16776 transmit_response(p, "481 Call leg/transaction does not exist", req);
16777 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16778 return;
16779 }
16780
16781
16782 if (ast_strlen_zero(c = get_body(req, "Signal", '=')) && ast_strlen_zero(c = get_body(req, "d", '='))) {
16783 ast_log(LOG_WARNING, "Unable to retrieve DTMF signal from INFO message from %s\n", p->callid);
16784 transmit_response(p, "200 OK", req);
16785 return;
16786 } else {
16787 ast_copy_string(buf, c, sizeof(buf));
16788 }
16789
16790 if (!ast_strlen_zero((c = get_body(req, "Duration", '='))))
16791 duration = atoi(c);
16792 if (!duration)
16793 duration = 100;
16794
16795
16796 if (ast_strlen_zero(buf)) {
16797 transmit_response(p, "200 OK", req);
16798 return;
16799 }
16800
16801 if (buf[0] == '*')
16802 event = 10;
16803 else if (buf[0] == '#')
16804 event = 11;
16805 else if ((buf[0] >= 'A') && (buf[0] <= 'D'))
16806 event = 12 + buf[0] - 'A';
16807 else if (buf[0] == '!')
16808 event = 16;
16809 else
16810 event = atoi(buf);
16811 if (event == 16) {
16812
16813 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_FLASH, };
16814 ast_queue_frame(p->owner, &f);
16815 if (sipdebug)
16816 ast_verbose("* DTMF-relay event received: FLASH\n");
16817 } else {
16818
16819 struct ast_frame f = { AST_FRAME_DTMF, };
16820 if (event < 10) {
16821 f.subclass = '0' + event;
16822 } else if (event < 11) {
16823 f.subclass = '*';
16824 } else if (event < 12) {
16825 f.subclass = '#';
16826 } else if (event < 16) {
16827 f.subclass = 'A' + (event - 12);
16828 }
16829 f.len = duration;
16830 ast_queue_frame(p->owner, &f);
16831 if (sipdebug)
16832 ast_verbose("* DTMF-relay event received: %c\n", f.subclass);
16833 }
16834 transmit_response(p, "200 OK", req);
16835 return;
16836 } else if (!strcasecmp(c, "application/dtmf")) {
16837
16838 unsigned int duration = 0;
16839
16840 if (!p->owner) {
16841 transmit_response(p, "481 Call leg/transaction does not exist", req);
16842 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16843 return;
16844 }
16845
16846 get_msg_text(buf, sizeof(buf), req, TRUE);
16847 duration = 100;
16848
16849 if (ast_strlen_zero(buf)) {
16850 transmit_response(p, "200 OK", req);
16851 return;
16852 }
16853 event = atoi(buf);
16854 if (event == 16) {
16855
16856 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_FLASH, };
16857 ast_queue_frame(p->owner, &f);
16858 if (sipdebug)
16859 ast_verbose("* DTMF-relay event received: FLASH\n");
16860 } else {
16861
16862 struct ast_frame f = { AST_FRAME_DTMF, };
16863 if (event < 10) {
16864 f.subclass = '0' + event;
16865 } else if (event < 11) {
16866 f.subclass = '*';
16867 } else if (event < 12) {
16868 f.subclass = '#';
16869 } else if (event < 16) {
16870 f.subclass = 'A' + (event - 12);
16871 }
16872 f.len = duration;
16873 ast_queue_frame(p->owner, &f);
16874 if (sipdebug)
16875 ast_verbose("* DTMF-relay event received: %c\n", f.subclass);
16876 }
16877 transmit_response(p, "200 OK", req);
16878 return;
16879
16880 } else if (!strcasecmp(c, "application/media_control+xml")) {
16881
16882 if (p->owner)
16883 ast_queue_control(p->owner, AST_CONTROL_VIDUPDATE);
16884 transmit_response(p, "200 OK", req);
16885 return;
16886 } else if (!ast_strlen_zero(c = get_header(req, "X-ClientCode"))) {
16887
16888 if (ast_test_flag(&p->flags[0], SIP_USECLIENTCODE)) {
16889 if (p->owner && p->owner->cdr)
16890 ast_cdr_setuserfield(p->owner, c);
16891 if (p->owner && ast_bridged_channel(p->owner) && ast_bridged_channel(p->owner)->cdr)
16892 ast_cdr_setuserfield(ast_bridged_channel(p->owner), c);
16893 transmit_response(p, "200 OK", req);
16894 } else {
16895 transmit_response(p, "403 Forbidden", req);
16896 }
16897 return;
16898 } else if (!ast_strlen_zero(c = get_header(req, "Record"))) {
16899
16900
16901
16902
16903
16904
16905
16906 struct ast_call_feature *feat;
16907 int j;
16908 struct ast_frame f = { AST_FRAME_DTMF, };
16909
16910 ast_rdlock_call_features();
16911 feat = ast_find_call_feature("automon");
16912 if (!feat || ast_strlen_zero(feat->exten)) {
16913 ast_log(LOG_WARNING, "Recording requested, but no One Touch Monitor registered. (See features.conf)\n");
16914
16915 transmit_response(p, "403 Forbidden", req);
16916 ast_unlock_call_features();
16917 return;
16918 }
16919
16920 f.len = 100;
16921 for (j=0; j < strlen(feat->exten); j++) {
16922 f.subclass = feat->exten[j];
16923 ast_queue_frame(p->owner, &f);
16924 if (sipdebug)
16925 ast_verbose("* DTMF-relay event faked: %c\n", f.subclass);
16926 }
16927 ast_unlock_call_features();
16928
16929 ast_debug(1, "Got a Request to Record the channel, state %s\n", c);
16930 transmit_response(p, "200 OK", req);
16931 return;
16932 } else if (ast_strlen_zero(c = get_header(req, "Content-Length")) || !strcasecmp(c, "0")) {
16933
16934 transmit_response(p, "200 OK", req);
16935 return;
16936 }
16937
16938
16939
16940
16941 ast_log(LOG_WARNING, "Unable to parse INFO message from %s. Content %s\n", p->callid, buf);
16942 transmit_response(p, "415 Unsupported media type", req);
16943 return;
16944 }
16945
16946
16947 static char *sip_do_debug_ip(int fd, char *arg)
16948 {
16949 struct hostent *hp;
16950 struct ast_hostent ahp;
16951 int port = 0;
16952 char *p;
16953
16954 p = arg;
16955 strsep(&p, ":");
16956 if (p)
16957 port = atoi(p);
16958 hp = ast_gethostbyname(arg, &ahp);
16959 if (hp == NULL)
16960 return CLI_SHOWUSAGE;
16961
16962 debugaddr.sin_family = AF_INET;
16963 memcpy(&debugaddr.sin_addr, hp->h_addr, sizeof(debugaddr.sin_addr));
16964 debugaddr.sin_port = htons(port);
16965 if (port == 0)
16966 ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_inet_ntoa(debugaddr.sin_addr));
16967 else
16968 ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(debugaddr.sin_addr), port);
16969
16970 sipdebug |= sip_debug_console;
16971
16972 return CLI_SUCCESS;
16973 }
16974
16975
16976 static char *sip_do_debug_peer(int fd, char *arg)
16977 {
16978 struct sip_peer *peer = find_peer(arg, NULL, TRUE, FINDPEERS, FALSE, 0);
16979 if (!peer)
16980 ast_cli(fd, "No such peer '%s'\n", arg);
16981 else if (peer->addr.sin_addr.s_addr == 0)
16982 ast_cli(fd, "Unable to get IP address of peer '%s'\n", arg);
16983 else {
16984 debugaddr.sin_family = AF_INET;
16985 debugaddr.sin_addr = peer->addr.sin_addr;
16986 debugaddr.sin_port = peer->addr.sin_port;
16987 ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n",
16988 ast_inet_ntoa(debugaddr.sin_addr), ntohs(debugaddr.sin_port));
16989 sipdebug |= sip_debug_console;
16990 }
16991 if (peer)
16992 unref_peer(peer, "sip_do_debug_peer: unref_peer, from find_peer call");
16993 return CLI_SUCCESS;
16994 }
16995
16996
16997 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16998 {
16999 int oldsipdebug = sipdebug & sip_debug_console;
17000 char *what;
17001
17002 if (cmd == CLI_INIT) {
17003 e->command = "sip set debug {on|off|ip|peer}";
17004 e->usage =
17005 "Usage: sip set debug {off|on|ip addr[:port]|peer peername}\n"
17006 " Globally disables dumping of SIP packets,\n"
17007 " or enables it either globally or for a (single)\n"
17008 " IP address or registered peer.\n";
17009 return NULL;
17010 } else if (cmd == CLI_GENERATE) {
17011 if (a->pos == 4 && !strcasecmp(a->argv[3], "peer"))
17012 return complete_sip_peer(a->word, a->n, 0);
17013 return NULL;
17014 }
17015
17016 what = a->argv[e->args-1];
17017 if (a->argc == e->args) {
17018 if (!strcasecmp(what, "on")) {
17019 sipdebug |= sip_debug_console;
17020 sipdebug_text = 1;
17021 memset(&debugaddr, 0, sizeof(debugaddr));
17022 ast_cli(a->fd, "SIP Debugging %senabled\n", oldsipdebug ? "re-" : "");
17023 return CLI_SUCCESS;
17024 } else if (!strcasecmp(what, "off")) {
17025 sipdebug &= ~sip_debug_console;
17026 sipdebug_text = 0;
17027 ast_cli(a->fd, "SIP Debugging Disabled\n");
17028 return CLI_SUCCESS;
17029 }
17030 } else if (a->argc == e->args +1) {
17031 if (!strcasecmp(what, "ip"))
17032 return sip_do_debug_ip(a->fd, a->argv[e->args]);
17033 else if (!strcasecmp(what, "peer"))
17034 return sip_do_debug_peer(a->fd, a->argv[e->args]);
17035 }
17036 return CLI_SHOWUSAGE;
17037 }
17038
17039
17040 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17041 {
17042 struct ast_variable *varlist;
17043 int i;
17044
17045 switch (cmd) {
17046 case CLI_INIT:
17047 e->command = "sip notify";
17048 e->usage =
17049 "Usage: sip notify <type> <peer> [<peer>...]\n"
17050 " Send a NOTIFY message to a SIP peer or peers\n"
17051 " Message types are defined in sip_notify.conf\n";
17052 return NULL;
17053 case CLI_GENERATE:
17054 return complete_sipnotify(a->line, a->word, a->pos, a->n);
17055 }
17056
17057 if (a->argc < 4)
17058 return CLI_SHOWUSAGE;
17059
17060 if (!notify_types) {
17061 ast_cli(a->fd, "No %s file found, or no types listed there\n", notify_config);
17062 return CLI_FAILURE;
17063 }
17064
17065 varlist = ast_variable_browse(notify_types, a->argv[2]);
17066
17067 if (!varlist) {
17068 ast_cli(a->fd, "Unable to find notify type '%s'\n", a->argv[2]);
17069 return CLI_FAILURE;
17070 }
17071
17072 for (i = 3; i < a->argc; i++) {
17073 struct sip_pvt *p;
17074
17075 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
17076 ast_log(LOG_WARNING, "Unable to build sip pvt data for notify (memory/socket error)\n");
17077 return CLI_FAILURE;
17078 }
17079
17080 if (create_addr(p, a->argv[i], NULL, 1)) {
17081
17082 dialog_unlink_all(p, TRUE, TRUE);
17083 dialog_unref(p, "unref dialog inside for loop" );
17084
17085 ast_cli(a->fd, "Could not create address for '%s'\n", a->argv[i]);
17086 continue;
17087 }
17088
17089
17090 ast_set_flag(&p->flags[0], SIP_OUTGOING);
17091
17092
17093 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
17094 build_via(p);
17095 ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
17096 build_callid_pvt(p);
17097 ao2_t_link(dialogs, p, "Linking in new name");
17098 ast_cli(a->fd, "Sending NOTIFY of type '%s' to '%s'\n", a->argv[2], a->argv[i]);
17099 dialog_ref(p, "bump the count of p, which transmit_sip_request will decrement.");
17100 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
17101 transmit_notify_custom(p, varlist);
17102 }
17103
17104 return CLI_SUCCESS;
17105 }
17106
17107
17108 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17109 {
17110 switch (cmd) {
17111 case CLI_INIT:
17112 e->command = "sip set history {on|off}";
17113 e->usage =
17114 "Usage: sip set history {on|off}\n"
17115 " Enables/Disables recording of SIP dialog history for debugging purposes.\n"
17116 " Use 'sip show history' to view the history of a call number.\n";
17117 return NULL;
17118 case CLI_GENERATE:
17119 return NULL;
17120 }
17121
17122 if (a->argc != e->args)
17123 return CLI_SHOWUSAGE;
17124
17125 if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
17126 recordhistory = TRUE;
17127 ast_cli(a->fd, "SIP History Recording Enabled (use 'sip show history')\n");
17128 } else if (!strncasecmp(a->argv[e->args - 1], "off", 3)) {
17129 recordhistory = FALSE;
17130 ast_cli(a->fd, "SIP History Recording Disabled\n");
17131 } else {
17132 return CLI_SHOWUSAGE;
17133 }
17134 return CLI_SUCCESS;
17135 }
17136
17137
17138 static int do_register_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code)
17139 {
17140 char *header, *respheader;
17141 char digest[1024];
17142
17143 p->authtries++;
17144 auth_headers(code, &header, &respheader);
17145 memset(digest, 0, sizeof(digest));
17146 if (reply_digest(p, req, header, SIP_REGISTER, digest, sizeof(digest))) {
17147
17148
17149 if (sip_debug_test_pvt(p) && p->registry)
17150 ast_verbose("No authentication challenge, sending blank registration to domain/host name %s\n", p->registry->hostname);
17151
17152 return -1;
17153 }
17154 if (p->do_history)
17155 append_history(p, "RegistryAuth", "Try: %d", p->authtries);
17156 if (sip_debug_test_pvt(p) && p->registry)
17157 ast_verbose("Responding to challenge, registration to domain/host name %s\n", p->registry->hostname);
17158 return transmit_register(p->registry, SIP_REGISTER, digest, respheader);
17159 }
17160
17161
17162 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code, int sipmethod, int init)
17163 {
17164 char *header, *respheader;
17165 char digest[1024];
17166
17167 if (!p->options && !(p->options = ast_calloc(1, sizeof(*p->options))))
17168 return -2;
17169
17170 p->authtries++;
17171 auth_headers(code, &header, &respheader);
17172 ast_debug(2, "Auth attempt %d on %s\n", p->authtries, sip_methods[sipmethod].text);
17173 memset(digest, 0, sizeof(digest));
17174 if (reply_digest(p, req, header, sipmethod, digest, sizeof(digest) )) {
17175
17176 return -1;
17177 }
17178
17179 p->options->auth = digest;
17180 p->options->authheader = respheader;
17181 return transmit_invite(p, sipmethod, sipmethod == SIP_INVITE, init);
17182 }
17183
17184
17185
17186
17187
17188 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len)
17189 {
17190 char tmp[512];
17191 char *c;
17192 char oldnonce[256];
17193
17194
17195 const struct x {
17196 const char *key;
17197 const ast_string_field *field;
17198 } *i, keys[] = {
17199 { "realm=", &p->realm },
17200 { "nonce=", &p->nonce },
17201 { "opaque=", &p->opaque },
17202 { "qop=", &p->qop },
17203 { "domain=", &p->domain },
17204 { NULL, 0 },
17205 };
17206
17207 ast_copy_string(tmp, get_header(req, header), sizeof(tmp));
17208 if (ast_strlen_zero(tmp))
17209 return -1;
17210 if (strncasecmp(tmp, "Digest ", strlen("Digest "))) {
17211 ast_log(LOG_WARNING, "missing Digest.\n");
17212 return -1;
17213 }
17214 c = tmp + strlen("Digest ");
17215 ast_copy_string(oldnonce, p->nonce, sizeof(oldnonce));
17216 while (c && *(c = ast_skip_blanks(c))) {
17217 for (i = keys; i->key != NULL; i++) {
17218 char *src, *separator;
17219 if (strncasecmp(c, i->key, strlen(i->key)) != 0)
17220 continue;
17221
17222 c += strlen(i->key);
17223 if (*c == '"') {
17224 src = ++c;
17225 separator = "\"";
17226 } else {
17227 src = c;
17228 separator = ",";
17229 }
17230 strsep(&c, separator);
17231 ast_string_field_ptr_set(p, i->field, src);
17232 break;
17233 }
17234 if (i->key == NULL)
17235 strsep(&c, ",");
17236 }
17237
17238 if (strcmp(p->nonce, oldnonce))
17239 p->noncecount = 0;
17240
17241
17242 if (p->registry) {
17243 struct sip_registry *r = p->registry;
17244
17245 if (strcmp(r->nonce, p->nonce)) {
17246 ast_string_field_set(r, realm, p->realm);
17247 ast_string_field_set(r, nonce, p->nonce);
17248 ast_string_field_set(r, domain, p->domain);
17249 ast_string_field_set(r, opaque, p->opaque);
17250 ast_string_field_set(r, qop, p->qop);
17251 r->noncecount = 0;
17252 }
17253 }
17254 return build_reply_digest(p, sipmethod, digest, digest_len);
17255 }
17256
17257
17258
17259
17260
17261
17262 static int build_reply_digest(struct sip_pvt *p, int method, char* digest, int digest_len)
17263 {
17264 char a1[256];
17265 char a2[256];
17266 char a1_hash[256];
17267 char a2_hash[256];
17268 char resp[256];
17269 char resp_hash[256];
17270 char uri[256];
17271 char opaque[256] = "";
17272 char cnonce[80];
17273 const char *username;
17274 const char *secret;
17275 const char *md5secret;
17276 struct sip_auth *auth = NULL;
17277
17278 if (!ast_strlen_zero(p->domain))
17279 ast_copy_string(uri, p->domain, sizeof(uri));
17280 else if (!ast_strlen_zero(p->uri))
17281 ast_copy_string(uri, p->uri, sizeof(uri));
17282 else
17283 snprintf(uri, sizeof(uri), "sip:%s@%s", p->username, ast_inet_ntoa(p->sa.sin_addr));
17284
17285 snprintf(cnonce, sizeof(cnonce), "%08lx", ast_random());
17286
17287
17288 if(!(auth = find_realm_authentication(p->peerauth, p->realm)))
17289 auth = find_realm_authentication(authl, p->realm);
17290
17291 if (auth) {
17292 ast_debug(3, "use realm [%s] from peer [%s][%s]\n", auth->username, p->peername, p->username);
17293 username = auth->username;
17294 secret = auth->secret;
17295 md5secret = auth->md5secret;
17296 if (sipdebug)
17297 ast_debug(1, "Using realm %s authentication for call %s\n", p->realm, p->callid);
17298 } else {
17299
17300 username = p->authname;
17301 secret = p->peersecret;
17302 md5secret = p->peermd5secret;
17303 }
17304 if (ast_strlen_zero(username))
17305 return -1;
17306
17307
17308 snprintf(a1, sizeof(a1), "%s:%s:%s", username, p->realm, secret);
17309 snprintf(a2, sizeof(a2), "%s:%s", sip_methods[method].text, uri);
17310 if (!ast_strlen_zero(md5secret))
17311 ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
17312 else
17313 ast_md5_hash(a1_hash, a1);
17314 ast_md5_hash(a2_hash, a2);
17315
17316 p->noncecount++;
17317 if (!ast_strlen_zero(p->qop))
17318 snprintf(resp, sizeof(resp), "%s:%s:%08x:%s:%s:%s", a1_hash, p->nonce, p->noncecount, cnonce, "auth", a2_hash);
17319 else
17320 snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, p->nonce, a2_hash);
17321 ast_md5_hash(resp_hash, resp);
17322
17323
17324 if (!ast_strlen_zero(p->opaque)) {
17325 snprintf(opaque, sizeof(opaque), ", opaque=\"%s\"", p->opaque);
17326 }
17327
17328
17329 if (!ast_strlen_zero(p->qop))
17330 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);
17331 else
17332 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);
17333
17334 append_history(p, "AuthResp", "Auth response sent for %s in realm %s - nc %d", username, p->realm, p->noncecount);
17335
17336 return 0;
17337 }
17338
17339
17340 static int func_header_read(struct ast_channel *chan, const char *function, char *data, char *buf, size_t len)
17341 {
17342 struct sip_pvt *p;
17343 const char *content = NULL;
17344 AST_DECLARE_APP_ARGS(args,
17345 AST_APP_ARG(header);
17346 AST_APP_ARG(number);
17347 );
17348 int i, number, start = 0;
17349
17350 if (ast_strlen_zero(data)) {
17351 ast_log(LOG_WARNING, "This function requires a header name.\n");
17352 return -1;
17353 }
17354
17355 ast_channel_lock(chan);
17356 if (!IS_SIP_TECH(chan->tech)) {
17357 ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
17358 ast_channel_unlock(chan);
17359 return -1;
17360 }
17361
17362 AST_STANDARD_APP_ARGS(args, data);
17363 if (!args.number) {
17364 number = 1;
17365 } else {
17366 sscanf(args.number, "%30d", &number);
17367 if (number < 1)
17368 number = 1;
17369 }
17370
17371 p = chan->tech_pvt;
17372
17373
17374 if (!p) {
17375 ast_channel_unlock(chan);
17376 return -1;
17377 }
17378
17379 for (i = 0; i < number; i++)
17380 content = __get_header(&p->initreq, args.header, &start);
17381
17382 if (ast_strlen_zero(content)) {
17383 ast_channel_unlock(chan);
17384 return -1;
17385 }
17386
17387 ast_copy_string(buf, content, len);
17388 ast_channel_unlock(chan);
17389
17390 return 0;
17391 }
17392
17393 static struct ast_custom_function sip_header_function = {
17394 .name = "SIP_HEADER",
17395 .read = func_header_read,
17396 };
17397
17398
17399 static int func_check_sipdomain(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
17400 {
17401 if (ast_strlen_zero(data)) {
17402 ast_log(LOG_WARNING, "CHECKSIPDOMAIN requires an argument - A domain name\n");
17403 return -1;
17404 }
17405 if (check_sip_domain(data, NULL, 0))
17406 ast_copy_string(buf, data, len);
17407 else
17408 buf[0] = '\0';
17409 return 0;
17410 }
17411
17412 static struct ast_custom_function checksipdomain_function = {
17413 .name = "CHECKSIPDOMAIN",
17414 .read = func_check_sipdomain,
17415 };
17416
17417
17418 static int function_sippeer(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
17419 {
17420 struct sip_peer *peer;
17421 char *colname;
17422
17423 if ((colname = strchr(data, ':'))) {
17424 static int deprecation_warning = 0;
17425 *colname++ = '\0';
17426 if (deprecation_warning++ % 10 == 0)
17427 ast_log(LOG_WARNING, "SIPPEER(): usage of ':' to separate arguments is deprecated. Please use ',' instead.\n");
17428 } else if ((colname = strchr(data, ',')))
17429 *colname++ = '\0';
17430 else
17431 colname = "ip";
17432
17433 if (!(peer = find_peer(data, NULL, TRUE, FINDPEERS, FALSE, 0)))
17434 return -1;
17435
17436 if (!strcasecmp(colname, "ip")) {
17437 ast_copy_string(buf, peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "", len);
17438 } else if (!strcasecmp(colname, "port")) {
17439 snprintf(buf, len, "%d", ntohs(peer->addr.sin_port));
17440 } else if (!strcasecmp(colname, "status")) {
17441 peer_status(peer, buf, len);
17442 } else if (!strcasecmp(colname, "language")) {
17443 ast_copy_string(buf, peer->language, len);
17444 } else if (!strcasecmp(colname, "regexten")) {
17445 ast_copy_string(buf, peer->regexten, len);
17446 } else if (!strcasecmp(colname, "limit")) {
17447 snprintf(buf, len, "%d", peer->call_limit);
17448 } else if (!strcasecmp(colname, "busylevel")) {
17449 snprintf(buf, len, "%d", peer->busy_level);
17450 } else if (!strcasecmp(colname, "curcalls")) {
17451 snprintf(buf, len, "%d", peer->inUse);
17452 } else if (!strcasecmp(colname, "accountcode")) {
17453 ast_copy_string(buf, peer->accountcode, len);
17454 } else if (!strcasecmp(colname, "callgroup")) {
17455 ast_print_group(buf, len, peer->callgroup);
17456 } else if (!strcasecmp(colname, "pickupgroup")) {
17457 ast_print_group(buf, len, peer->pickupgroup);
17458 } else if (!strcasecmp(colname, "useragent")) {
17459 ast_copy_string(buf, peer->useragent, len);
17460 } else if (!strcasecmp(colname, "mailbox")) {
17461 struct ast_str *mailbox_str = ast_str_alloca(512);
17462 peer_mailboxes_to_str(&mailbox_str, peer);
17463 ast_copy_string(buf, mailbox_str->str, len);
17464 } else if (!strcasecmp(colname, "context")) {
17465 ast_copy_string(buf, peer->context, len);
17466 } else if (!strcasecmp(colname, "expire")) {
17467 snprintf(buf, len, "%d", peer->expire);
17468 } else if (!strcasecmp(colname, "dynamic")) {
17469 ast_copy_string(buf, peer->host_dynamic ? "yes" : "no", len);
17470 } else if (!strcasecmp(colname, "callerid_name")) {
17471 ast_copy_string(buf, peer->cid_name, len);
17472 } else if (!strcasecmp(colname, "callerid_num")) {
17473 ast_copy_string(buf, peer->cid_num, len);
17474 } else if (!strcasecmp(colname, "codecs")) {
17475 ast_getformatname_multiple(buf, len -1, peer->capability);
17476 } else if (!strncasecmp(colname, "chanvar[", 8)) {
17477 char *chanvar=colname + 8;
17478 struct ast_variable *v;
17479
17480 chanvar = strsep(&chanvar, "]");
17481 for (v = peer->chanvars ; v ; v = v->next) {
17482 if (!strcasecmp(v->name, chanvar)) {
17483 ast_copy_string(buf, v->value, len);
17484 }
17485 }
17486 } else if (!strncasecmp(colname, "codec[", 6)) {
17487 char *codecnum;
17488 int codec = 0;
17489
17490 codecnum = colname + 6;
17491 codecnum = strsep(&codecnum, "]");
17492 if((codec = ast_codec_pref_index(&peer->prefs, atoi(codecnum)))) {
17493 ast_copy_string(buf, ast_getformatname(codec), len);
17494 } else {
17495 buf[0] = '\0';
17496 }
17497 } else {
17498 buf[0] = '\0';
17499 }
17500
17501 unref_peer(peer, "unref_peer from function_sippeer, just before return");
17502
17503 return 0;
17504 }
17505
17506
17507 static struct ast_custom_function sippeer_function = {
17508 .name = "SIPPEER",
17509 .read = function_sippeer,
17510 };
17511
17512
17513 static int function_sipchaninfo_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
17514 {
17515 struct sip_pvt *p;
17516 static int deprecated = 0;
17517
17518 *buf = 0;
17519
17520 if (!data) {
17521 ast_log(LOG_WARNING, "This function requires a parameter name.\n");
17522 return -1;
17523 }
17524
17525 ast_channel_lock(chan);
17526 if (!IS_SIP_TECH(chan->tech)) {
17527 ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
17528 ast_channel_unlock(chan);
17529 return -1;
17530 }
17531
17532 if (deprecated++ % 20 == 0) {
17533
17534 ast_log(LOG_WARNING, "SIPCHANINFO() is deprecated. Please transition to using CHANNEL().\n");
17535 }
17536
17537 p = chan->tech_pvt;
17538
17539
17540 if (!p) {
17541 ast_channel_unlock(chan);
17542 return -1;
17543 }
17544
17545 if (!strcasecmp(data, "peerip")) {
17546 ast_copy_string(buf, p->sa.sin_addr.s_addr ? ast_inet_ntoa(p->sa.sin_addr) : "", len);
17547 } else if (!strcasecmp(data, "recvip")) {
17548 ast_copy_string(buf, p->recv.sin_addr.s_addr ? ast_inet_ntoa(p->recv.sin_addr) : "", len);
17549 } else if (!strcasecmp(data, "from")) {
17550 ast_copy_string(buf, p->from, len);
17551 } else if (!strcasecmp(data, "uri")) {
17552 ast_copy_string(buf, p->uri, len);
17553 } else if (!strcasecmp(data, "useragent")) {
17554 ast_copy_string(buf, p->useragent, len);
17555 } else if (!strcasecmp(data, "peername")) {
17556 ast_copy_string(buf, p->peername, len);
17557 } else if (!strcasecmp(data, "t38passthrough")) {
17558 if (p->t38.state == T38_DISABLED) {
17559 ast_copy_string(buf, "0", len);
17560 } else {
17561 ast_copy_string(buf, "1", len);
17562 }
17563 } else {
17564 ast_channel_unlock(chan);
17565 return -1;
17566 }
17567 ast_channel_unlock(chan);
17568
17569 return 0;
17570 }
17571
17572
17573 static struct ast_custom_function sipchaninfo_function = {
17574 .name = "SIPCHANINFO",
17575 .read = function_sipchaninfo_read,
17576 };
17577
17578
17579
17580
17581
17582
17583
17584 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req)
17585 {
17586 char tmp[SIPBUFSIZE];
17587 char *s, *e, *t, *trans;
17588 char *domain;
17589 enum sip_transport transport = SIP_TRANSPORT_UDP;
17590
17591 ast_copy_string(tmp, get_header(req, "Contact"), sizeof(tmp));
17592 if ((t = strchr(tmp, ',')))
17593 *t = '\0';
17594
17595 s = get_in_brackets(tmp);
17596 if ((trans = strcasestr(s, ";transport="))) do {
17597 trans += 11;
17598
17599 if ((e = strchr(trans, ';')))
17600 *e = '\0';
17601
17602 if (!strncasecmp(trans, "tcp", 3))
17603 transport = SIP_TRANSPORT_TCP;
17604 else if (!strncasecmp(trans, "tls", 3))
17605 transport = SIP_TRANSPORT_TLS;
17606 else {
17607 if (strncasecmp(trans, "udp", 3))
17608 ast_debug(1, "received contact with an invalid transport, '%s'\n", s);
17609
17610 transport = SIP_TRANSPORT_UDP;
17611 }
17612 } while(0);
17613 s = remove_uri_parameters(s);
17614
17615 if (p->socket.tcptls_session) {
17616 ao2_ref(p->socket.tcptls_session, -1);
17617 p->socket.tcptls_session = NULL;
17618 }
17619
17620 set_socket_transport(&p->socket, transport);
17621
17622 if (ast_test_flag(&p->flags[0], SIP_PROMISCREDIR)) {
17623 char *host = NULL;
17624 if (!strncasecmp(s, "sip:", 4))
17625 s += 4;
17626 else if (!strncasecmp(s, "sips:", 5))
17627 s += 5;
17628 e = strchr(s, '/');
17629 if (e)
17630 *e = '\0';
17631 if ((host = strchr(s, '@'))) {
17632 *host++ = '\0';
17633 ast_debug(2, "Found promiscuous redirection to 'SIP/%s::::%s@%s'\n", s, get_transport(transport), host);
17634 if (p->owner)
17635 ast_string_field_build(p->owner, call_forward, "SIP/%s::::%s@%s", s, get_transport(transport), host);
17636 } else {
17637 ast_debug(2, "Found promiscuous redirection to 'SIP/::::%s@%s'\n", get_transport(transport), s);
17638 if (p->owner)
17639 ast_string_field_build(p->owner, call_forward, "SIP/::::%s@%s", get_transport(transport), s);
17640 }
17641 } else {
17642 e = strchr(tmp, '@');
17643 if (e) {
17644 *e++ = '\0';
17645 domain = e;
17646 } else {
17647
17648 domain = tmp;
17649 }
17650 e = strchr(tmp, '/');
17651 if (e)
17652 *e = '\0';
17653
17654 if (!strncasecmp(s, "sip:", 4))
17655 s += 4;
17656 else if (!strncasecmp(s, "sips:", 5))
17657 s += 5;
17658 e = strchr(s, ';');
17659 if (e)
17660 *e = '\0';
17661 ast_uri_decode(s);
17662 ast_debug(2, "Received 302 Redirect to extension '%s' (domain %s)\n", s, domain);
17663 if (p->owner) {
17664 pbx_builtin_setvar_helper(p->owner, "SIPDOMAIN", domain);
17665 ast_string_field_set(p->owner, call_forward, s);
17666 }
17667 }
17668 }
17669
17670
17671 static void check_pendings(struct sip_pvt *p)
17672 {
17673 if (ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
17674
17675 if (p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA)
17676 transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
17677
17678
17679 else {
17680
17681
17682 if (p->pendinginvite)
17683 return;
17684
17685
17686 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, TRUE);
17687 }
17688 ast_clear_flag(&p->flags[0], SIP_PENDINGBYE);
17689 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17690 } else if (ast_test_flag(&p->flags[0], SIP_NEEDREINVITE)) {
17691
17692 if (p->pendinginvite || p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA || p->waitid > 0) {
17693 ast_debug(2, "NOT Sending pending reinvite (yet) on '%s'\n", p->callid);
17694 } else {
17695 ast_debug(2, "Sending pending reinvite on '%s'\n", p->callid);
17696
17697 transmit_reinvite_with_sdp(p, (p->t38.state == T38_LOCAL_REINVITE ? TRUE : FALSE), FALSE);
17698 ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);
17699 }
17700 }
17701 }
17702
17703
17704
17705
17706
17707 static int sip_reinvite_retry(const void *data)
17708 {
17709 struct sip_pvt *p = (struct sip_pvt *) data;
17710
17711 sip_pvt_lock(p);
17712 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
17713 p->waitid = -1;
17714 check_pendings(p);
17715 sip_pvt_unlock(p);
17716 dialog_unref(p, "unref the dialog ptr from sip_reinvite_retry, because it held a dialog ptr");
17717 return 0;
17718 }
17719
17720
17721
17722 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
17723 {
17724 int outgoing = ast_test_flag(&p->flags[0], SIP_OUTGOING);
17725 int res = 0;
17726 int xmitres = 0;
17727 int reinvite = (p->owner && p->owner->_state == AST_STATE_UP);
17728 char *p_hdrval;
17729 int rtn;
17730
17731 if (reinvite)
17732 ast_debug(4, "SIP response %d to RE-invite on %s call %s\n", resp, outgoing ? "outgoing" : "incoming", p->callid);
17733 else
17734 ast_debug(4, "SIP response %d to standard invite\n", resp);
17735
17736 if (p->alreadygone) {
17737 ast_debug(1, "Got response on call that is already terminated: %s (ignoring)\n", p->callid);
17738 return;
17739 }
17740
17741
17742
17743 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"));
17744
17745
17746
17747
17748 if (resp > 100 && resp < 200 && resp!=101 && resp != 180 && resp != 182 && resp != 183)
17749 resp = 183;
17750
17751
17752 if (resp >= 100 && resp < 200 && p->invitestate == INV_CALLING)
17753 p->invitestate = INV_PROCEEDING;
17754
17755
17756 if (resp >= 300 && (p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA ))
17757 p->invitestate = INV_COMPLETED;
17758
17759
17760 if ((resp == 200 || resp >= 300) && p->pendinginvite && seqno == p->pendinginvite)
17761 p->pendinginvite = 0;
17762
17763 switch (resp) {
17764 case 100:
17765 case 101:
17766 if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p))
17767 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
17768 check_pendings(p);
17769 break;
17770
17771 case 180:
17772 case 182:
17773 if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p))
17774 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
17775 if (!req->ignore && p->owner) {
17776 ast_queue_control(p->owner, AST_CONTROL_RINGING);
17777 if (p->owner->_state != AST_STATE_UP) {
17778 ast_setstate(p->owner, AST_STATE_RINGING);
17779 }
17780 }
17781 if (find_sdp(req)) {
17782 if (p->invitestate != INV_CANCELLED)
17783 p->invitestate = INV_EARLY_MEDIA;
17784 res = process_sdp(p, req, SDP_T38_NONE);
17785 if (!req->ignore && p->owner) {
17786
17787 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
17788 }
17789 }
17790 check_pendings(p);
17791 break;
17792
17793 case 183:
17794 if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
17795 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
17796 if (find_sdp(req)) {
17797 if (p->invitestate != INV_CANCELLED)
17798 p->invitestate = INV_EARLY_MEDIA;
17799 res = process_sdp(p, req, SDP_T38_NONE);
17800 if (!req->ignore && p->owner) {
17801
17802 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
17803 }
17804 } else {
17805
17806
17807
17808
17809 if (!req->ignore && p->owner) {
17810 ast_queue_control(p->owner, AST_CONTROL_RINGING);
17811 }
17812 }
17813 check_pendings(p);
17814 break;
17815
17816 case 200:
17817 if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
17818 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
17819 p->authtries = 0;
17820 if (find_sdp(req)) {
17821 if ((res = process_sdp(p, req, SDP_T38_ACCEPT)) && !req->ignore)
17822 if (!reinvite)
17823
17824
17825 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
17826 }
17827
17828
17829
17830
17831 if (outgoing) {
17832 update_call_counter(p, DEC_CALL_RINGING);
17833 parse_ok_contact(p, req);
17834
17835 if (!reinvite)
17836 build_route(p, req, 1);
17837
17838 if(set_address_from_contact(p)) {
17839
17840
17841 if (!p->route && !req->ignore)
17842 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
17843 }
17844
17845 }
17846
17847 if (!req->ignore && p->owner) {
17848 if (!reinvite) {
17849 ast_queue_control(p->owner, AST_CONTROL_ANSWER);
17850 if (sip_cfg.callevents)
17851 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
17852 "Channel: %s\r\nChanneltype: %s\r\nUniqueid: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
17853 p->owner->name, "SIP", p->owner->uniqueid, p->callid, p->fullcontact, p->peername);
17854 } else {
17855 ast_queue_frame(p->owner, &ast_null_frame);
17856 }
17857 } else {
17858
17859
17860
17861 if (!req->ignore)
17862 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
17863 }
17864
17865
17866 if (st_get_mode(p) != SESSION_TIMER_MODE_REFUSE && p->outgoing_call == TRUE && !reinvite) {
17867 p_hdrval = (char*)get_header(req, "Session-Expires");
17868 if (!ast_strlen_zero(p_hdrval)) {
17869
17870 enum st_refresher tmp_st_ref = SESSION_TIMER_REFRESHER_AUTO;
17871 int tmp_st_interval = 0;
17872 rtn = parse_session_expires(p_hdrval, &tmp_st_interval, &tmp_st_ref);
17873 if (rtn != 0) {
17874 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
17875 }
17876 if (tmp_st_ref == SESSION_TIMER_REFRESHER_UAC ||
17877 tmp_st_ref == SESSION_TIMER_REFRESHER_UAS) {
17878 p->stimer->st_ref = tmp_st_ref;
17879 }
17880 if (tmp_st_interval) {
17881 p->stimer->st_interval = tmp_st_interval;
17882 }
17883 p->stimer->st_active = TRUE;
17884 p->stimer->st_active_peer_ua = TRUE;
17885 start_session_timer(p);
17886 } else {
17887
17888 if (st_get_mode(p) == SESSION_TIMER_MODE_ORIGINATE) {
17889 p->stimer->st_ref = SESSION_TIMER_REFRESHER_UAC;
17890 p->stimer->st_active_peer_ua = FALSE;
17891 start_session_timer(p);
17892 }
17893 }
17894 }
17895
17896
17897
17898 p->invitestate = INV_TERMINATED;
17899 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
17900 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, TRUE);
17901 check_pendings(p);
17902 break;
17903
17904 case 407:
17905 case 401:
17906
17907 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17908 if (p->options)
17909 p->options->auth_type = resp;
17910
17911
17912 ast_string_field_set(p, theirtag, NULL);
17913 if (!req->ignore) {
17914 if (p->authtries < MAX_AUTHTRIES)
17915 p->invitestate = INV_CALLING;
17916 if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, SIP_INVITE, 1)) {
17917 ast_log(LOG_NOTICE, "Failed to authenticate on INVITE to '%s'\n", get_header(&p->initreq, "From"));
17918 pvt_set_needdestroy(p, "failed to authenticate on INVITE");
17919 sip_alreadygone(p);
17920 if (p->owner)
17921 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17922 }
17923 }
17924 break;
17925
17926 case 403:
17927
17928 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17929 ast_log(LOG_WARNING, "Received response: \"Forbidden\" from '%s'\n", get_header(&p->initreq, "From"));
17930 if (!req->ignore && p->owner)
17931 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17932 pvt_set_needdestroy(p, "received 403 response");
17933 sip_alreadygone(p);
17934 break;
17935
17936 case 404:
17937 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17938 if (p->owner && !req->ignore)
17939 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17940 sip_alreadygone(p);
17941 break;
17942
17943 case 408:
17944 case 481:
17945
17946 ast_log(LOG_WARNING, "Re-invite to non-existing call leg on other UA. SIP dialog '%s'. Giving up.\n", p->callid);
17947 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17948 if (p->owner)
17949 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17950 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17951 break;
17952
17953 case 422:
17954 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17955 ast_string_field_set(p, theirtag, NULL);
17956 proc_422_rsp(p, req);
17957 break;
17958
17959 case 428:
17960 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17961 append_history(p, "Identity", "SIP identity is required. Not supported by Asterisk.");
17962 ast_log(LOG_WARNING, "SIP identity required by proxy. SIP dialog '%s'. Giving up.\n", p->callid);
17963 if (p->owner)
17964 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17965 break;
17966
17967
17968
17969 case 487:
17970
17971
17972
17973 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17974 if (p->owner && !req->ignore) {
17975 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_NORMAL_CLEARING);
17976 append_history(p, "Hangup", "Got 487 on CANCEL request from us. Queued AST hangup request");
17977 } else if (!req->ignore) {
17978 update_call_counter(p, DEC_CALL_LIMIT);
17979 append_history(p, "Hangup", "Got 487 on CANCEL request from us on call without owner. Killing this dialog.");
17980 pvt_set_needdestroy(p, "received 487 response");
17981 sip_alreadygone(p);
17982 }
17983 break;
17984 case 415:
17985 case 488:
17986 case 606:
17987 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17988 if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
17989 change_t38_state(p, T38_DISABLED);
17990
17991 ast_rtp_set_rtptimers_onhold(p->rtp);
17992
17993
17994 transmit_reinvite_with_sdp(p, FALSE, FALSE);
17995 } else {
17996
17997 if (p->owner && !req->ignore)
17998 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17999 pvt_set_needdestroy(p, "received 488 response");
18000
18001 if (!reinvite)
18002 sip_alreadygone(p);
18003 }
18004 break;
18005 case 491:
18006 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
18007 if (p->owner && !req->ignore) {
18008 if (p->owner->_state != AST_STATE_UP) {
18009 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18010 pvt_set_needdestroy(p, "received 491 response");
18011 } else {
18012
18013
18014
18015 int wait;
18016
18017
18018 if (p->outgoing_call) {
18019 wait = 2100 + ast_random() % 2000;
18020 } else {
18021 wait = ast_random() % 2000;
18022 }
18023 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."));
18024 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);
18025 ast_debug(2, "Reinvite race. Waiting %d secs before retry\n", wait);
18026 }
18027 }
18028 break;
18029
18030 case 501:
18031 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
18032 if (p->owner)
18033 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18034 break;
18035 }
18036 if (xmitres == XMIT_ERROR)
18037 ast_log(LOG_WARNING, "Could not transmit message in dialog %s\n", p->callid);
18038 }
18039
18040
18041
18042
18043 static void handle_response_notify(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
18044 {
18045 switch (resp) {
18046 case 200:
18047
18048 if (p->owner) {
18049 if (!p->refer) {
18050 ast_log(LOG_WARNING, "Notify answer on an owned channel? - %s\n", p->owner->name);
18051 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_NORMAL_UNSPECIFIED);
18052 } else {
18053 ast_debug(4, "Got OK on REFER Notify message\n");
18054 }
18055 } else {
18056 if (p->subscribed == NONE) {
18057 ast_debug(4, "Got 200 accepted on NOTIFY\n");
18058 pvt_set_needdestroy(p, "received 200 response");
18059 }
18060 if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
18061
18062 ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
18063 cb_extensionstate((char *)p->context, (char *)p->exten, p->laststate, (void *) p);
18064 }
18065 }
18066 break;
18067 case 401:
18068 case 407:
18069 if (!p->notify_headers) {
18070 break;
18071 }
18072 ast_string_field_set(p, theirtag, NULL);
18073 if (ast_strlen_zero(p->authname)) {
18074 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));
18075 pvt_set_needdestroy(p, "unable to authenticate NOTIFY");
18076 }
18077 if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_NOTIFY, 0)) {
18078 ast_log(LOG_NOTICE, "Failed to authenticate on NOTIFY to '%s'\n", get_header(&p->initreq, "From"));
18079 pvt_set_needdestroy(p, "failed to authenticate NOTIFY");
18080 }
18081 break;
18082 }
18083 }
18084
18085
18086 static void handle_response_subscribe(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
18087 {
18088 if (!p->mwi) {
18089 return;
18090 }
18091
18092 switch (resp) {
18093 case 200:
18094 ast_debug(3, "Got 200 OK on subscription for MWI\n");
18095 if (p->options) {
18096 ast_free(p->options);
18097 p->options = NULL;
18098 }
18099 p->mwi->subscribed = 1;
18100 if ((p->mwi->resub = ast_sched_add(sched, mwi_expiry * 1000, sip_subscribe_mwi_do, ASTOBJ_REF(p->mwi))) < 0) {
18101 ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18102 }
18103 break;
18104 case 401:
18105 case 407:
18106 ast_string_field_set(p, theirtag, NULL);
18107 if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_SUBSCRIBE, 0)) {
18108 ast_log(LOG_NOTICE, "Failed to authenticate on SUBSCRIBE to '%s'\n", get_header(&p->initreq, "From"));
18109 p->mwi->call = NULL;
18110 ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18111 pvt_set_needdestroy(p, "failed to authenticate SUBSCRIBE");
18112 }
18113 break;
18114 case 403:
18115 transmit_response_with_date(p, "200 OK", req);
18116 ast_log(LOG_WARNING, "Authentication failed while trying to subscribe for MWI.\n");
18117 p->mwi->call = NULL;
18118 ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18119 pvt_set_needdestroy(p, "received 403 response");
18120 sip_alreadygone(p);
18121 break;
18122 case 404:
18123 ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side said that a mailbox may not have been configured.\n");
18124 p->mwi->call = NULL;
18125 ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18126 pvt_set_needdestroy(p, "received 404 response");
18127 break;
18128 case 481:
18129 ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side said that our dialog did not exist.\n");
18130 p->mwi->call = NULL;
18131 ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18132 pvt_set_needdestroy(p, "received 481 response");
18133 break;
18134 case 500:
18135 case 501:
18136 ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side may have suffered a heart attack.\n");
18137 p->mwi->call = NULL;
18138 ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18139 pvt_set_needdestroy(p, "received 500/501 response");
18140 break;
18141 }
18142 }
18143
18144
18145
18146
18147 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
18148 {
18149
18150 if (!p->refer)
18151 return;
18152
18153 switch (resp) {
18154 case 202:
18155
18156
18157 p->refer->status = REFER_ACCEPTED;
18158
18159 ast_debug(3, "Got 202 accepted on transfer\n");
18160
18161 break;
18162
18163 case 401:
18164 case 407:
18165 if (ast_strlen_zero(p->authname)) {
18166 ast_log(LOG_WARNING, "Asked to authenticate REFER to %s:%d but we have no matching peer or realm auth!\n",
18167 ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
18168 pvt_set_needdestroy(p, "unable to authenticate REFER");
18169 }
18170 if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_REFER, 0)) {
18171 ast_log(LOG_NOTICE, "Failed to authenticate on REFER to '%s'\n", get_header(&p->initreq, "From"));
18172 p->refer->status = REFER_NOAUTH;
18173 pvt_set_needdestroy(p, "failed to authenticat REFER");
18174 }
18175 break;
18176 case 481:
18177
18178
18179
18180
18181 ast_log(LOG_WARNING, "Remote host can't match REFER request to call '%s'. Giving up.\n", p->callid);
18182 if (p->owner)
18183 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18184 pvt_set_needdestroy(p, "received 481 response");
18185 break;
18186
18187 case 500:
18188 case 501:
18189
18190
18191 ast_log(LOG_NOTICE, "SIP transfer to %s failed, call miserably fails. \n", p->refer->refer_to);
18192 pvt_set_needdestroy(p, "received 500/501 response");
18193 p->refer->status = REFER_FAILED;
18194 break;
18195 case 603:
18196 ast_log(LOG_NOTICE, "SIP transfer to %s declined, call miserably fails. \n", p->refer->refer_to);
18197 p->refer->status = REFER_FAILED;
18198 pvt_set_needdestroy(p, "received 603 response");
18199 break;
18200 }
18201 }
18202
18203
18204 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
18205 {
18206 int expires, expires_ms;
18207 struct sip_registry *r;
18208 r=p->registry;
18209
18210 switch (resp) {
18211 case 401:
18212 if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
18213 ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s@%s' (Tries %d)\n", p->registry->username, p->registry->hostname, p->authtries);
18214 pvt_set_needdestroy(p, "failed to authenticate REGISTER");
18215 }
18216 break;
18217 case 403:
18218 ast_log(LOG_WARNING, "Forbidden - wrong password on authentication for REGISTER for '%s' to '%s'\n", p->registry->username, p->registry->hostname);
18219 AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 403"));
18220 r->regstate = REG_STATE_NOAUTH;
18221 pvt_set_needdestroy(p, "received 403 response");
18222 break;
18223 case 404:
18224 ast_log(LOG_WARNING, "Got 404 Not found on SIP register to service %s@%s, giving up\n", p->registry->username, p->registry->hostname);
18225 pvt_set_needdestroy(p, "received 404 response");
18226 if (r->call)
18227 r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 404");
18228 r->regstate = REG_STATE_REJECTED;
18229 AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 404"));
18230 break;
18231 case 407:
18232 if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
18233 ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s' (tries '%d')\n", get_header(&p->initreq, "From"), p->authtries);
18234 pvt_set_needdestroy(p, "failed to authenticate REGISTER");
18235 }
18236 break;
18237 case 408:
18238
18239 if (r) {
18240 r->regattempts = 0;
18241 } else {
18242 ast_log(LOG_WARNING, "Got a 408 response to our REGISTER on call %s after we had destroyed the registry object\n", p->callid);
18243 }
18244 break;
18245 case 423:
18246 r->expiry = atoi(get_header(req, "Min-Expires"));
18247 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);
18248 AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 423"));
18249 if (r->call) {
18250 r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 423");
18251 pvt_set_needdestroy(p, "received 423 response");
18252 }
18253 if (r->expiry > max_expiry) {
18254 ast_log(LOG_WARNING, "Required expiration time from %s@%s is too high, giving up\n", p->registry->username, p->registry->hostname);
18255 r->expiry = r->configured_expiry;
18256 r->regstate = REG_STATE_REJECTED;
18257 } else {
18258 r->regstate = REG_STATE_UNREGISTERED;
18259 transmit_register(r, SIP_REGISTER, NULL, NULL);
18260 }
18261 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));
18262 break;
18263 case 479:
18264 ast_log(LOG_WARNING, "Got error 479 on register to %s@%s, giving up (check config)\n", p->registry->username, p->registry->hostname);
18265 pvt_set_needdestroy(p, "received 479 response");
18266 if (r->call)
18267 r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 479");
18268 r->regstate = REG_STATE_REJECTED;
18269 AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 479"));
18270 break;
18271 case 200:
18272 if (!r) {
18273 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));
18274 pvt_set_needdestroy(p, "received erroneous 200 response");
18275 return 0;
18276 }
18277
18278 r->regstate = REG_STATE_REGISTERED;
18279 r->regtime = ast_tvnow();
18280 manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelType: SIP\r\nDomain: %s\r\nStatus: %s\r\n", r->hostname, regstate2str(r->regstate));
18281 r->regattempts = 0;
18282 ast_debug(1, "Registration successful\n");
18283 if (r->timeout > -1) {
18284 ast_debug(1, "Cancelling timeout %d\n", r->timeout);
18285 }
18286 AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 200"));
18287 if (r->call)
18288 r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 200");
18289 p->registry = registry_unref(p->registry, "unref registry entry p->registry");
18290
18291 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18292
18293
18294
18295
18296
18297
18298 expires = 0;
18299
18300
18301 if (!ast_strlen_zero(get_header(req, "Contact"))) {
18302 const char *contact = NULL;
18303 const char *tmptmp = NULL;
18304 int start = 0;
18305 for(;;) {
18306 contact = __get_header(req, "Contact", &start);
18307
18308 if(!ast_strlen_zero(contact)) {
18309 if( (tmptmp=strstr(contact, p->our_contact))) {
18310 contact=tmptmp;
18311 break;
18312 }
18313 } else
18314 break;
18315 }
18316 tmptmp = strcasestr(contact, "expires=");
18317 if (tmptmp) {
18318 if (sscanf(tmptmp + 8, "%30d;", &expires) != 1)
18319 expires = 0;
18320 }
18321
18322 }
18323 if (!expires)
18324 expires=atoi(get_header(req, "expires"));
18325 if (!expires)
18326 expires=default_expiry;
18327
18328 expires_ms = expires * 1000;
18329 if (expires <= EXPIRY_GUARD_LIMIT)
18330 expires_ms -= MAX((expires_ms * EXPIRY_GUARD_PCT), EXPIRY_GUARD_MIN);
18331 else
18332 expires_ms -= EXPIRY_GUARD_SECS * 1000;
18333 if (sipdebug)
18334 ast_log(LOG_NOTICE, "Outbound Registration: Expiry for %s is %d sec (Scheduling reregistration in %d s)\n", r->hostname, expires, expires_ms/1000);
18335
18336 r->refresh= (int) expires_ms / 1000;
18337
18338
18339 AST_SCHED_REPLACE_UNREF(r->expire, sched, expires_ms, sip_reregister, r,
18340 registry_unref(_data,"unref in REPLACE del fail"),
18341 registry_unref(r,"unref in REPLACE add fail"),
18342 registry_addref(r,"The Addition side of REPLACE"));
18343 }
18344 return 1;
18345 }
18346
18347
18348 static void handle_response_peerpoke(struct sip_pvt *p, int resp, struct sip_request *req)
18349 {
18350 struct sip_peer *peer = p->relatedpeer ;
18351 int statechanged, is_reachable, was_reachable;
18352 int pingtime = ast_tvdiff_ms(ast_tvnow(), peer->ps);
18353
18354
18355
18356
18357
18358
18359 if (pingtime < 1)
18360 pingtime = 1;
18361
18362
18363
18364
18365
18366 was_reachable = peer->lastms > 0 && peer->lastms <= peer->maxms;
18367 is_reachable = pingtime <= peer->maxms;
18368 statechanged = peer->lastms == 0
18369 || was_reachable != is_reachable;
18370
18371 peer->lastms = pingtime;
18372 peer->call = dialog_unref(peer->call, "unref dialog peer->call");
18373 if (statechanged) {
18374 const char *s = is_reachable ? "Reachable" : "Lagged";
18375 char str_lastms[20];
18376 snprintf(str_lastms, sizeof(str_lastms), "%d", pingtime);
18377
18378 ast_log(LOG_NOTICE, "Peer '%s' is now %s. (%dms / %dms)\n",
18379 peer->name, s, pingtime, peer->maxms);
18380 ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
18381 if (sip_cfg.peer_rtupdate) {
18382 ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", str_lastms, SENTINEL);
18383 }
18384 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
18385 "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: %s\r\nTime: %d\r\n",
18386 peer->name, s, pingtime);
18387 if (is_reachable && sip_cfg.regextenonqualify)
18388 register_peer_exten(peer, TRUE);
18389 }
18390
18391 pvt_set_needdestroy(p, "got OPTIONS response");
18392
18393
18394 AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
18395 is_reachable ? peer->qualifyfreq : DEFAULT_FREQ_NOTOK,
18396 sip_poke_peer_s, peer,
18397 unref_peer(_data, "removing poke peer ref"),
18398 unref_peer(peer, "removing poke peer ref"),
18399 ref_peer(peer, "adding poke peer ref"));
18400 }
18401
18402
18403 static void stop_media_flows(struct sip_pvt *p)
18404 {
18405
18406 if (p->rtp)
18407 ast_rtp_stop(p->rtp);
18408 if (p->vrtp)
18409 ast_rtp_stop(p->vrtp);
18410 if (p->trtp)
18411 ast_rtp_stop(p->trtp);
18412 if (p->udptl)
18413 ast_udptl_stop(p->udptl);
18414 }
18415
18416
18417
18418 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
18419 {
18420 struct ast_channel *owner;
18421 int sipmethod;
18422 int res = 1;
18423 const char *c = get_header(req, "Cseq");
18424
18425 char *c_copy = ast_strdupa(c);
18426
18427 const char *msg = ast_skip_blanks(ast_skip_nonblanks(c_copy));
18428
18429 if (!msg)
18430 msg = "";
18431
18432 sipmethod = find_sip_method(msg);
18433
18434 owner = p->owner;
18435 if (owner)
18436 owner->hangupcause = hangup_sip2cause(resp);
18437
18438 if (p->socket.type == SIP_TRANSPORT_UDP) {
18439 int ack_res;
18440
18441
18442 if ((resp >= 100) && (resp <= 199)) {
18443 ack_res = __sip_semi_ack(p, seqno, 0, sipmethod);
18444 } else {
18445 ack_res = __sip_ack(p, seqno, 0, sipmethod);
18446 }
18447
18448 if (ack_res == FALSE) {
18449 append_history(p, "Ignore", "Ignoring this retransmit\n");
18450 return;
18451 }
18452 }
18453
18454
18455 if (!p->owner && sipmethod == SIP_NOTIFY && p->pendinginvite)
18456 p->pendinginvite = 0;
18457
18458
18459 if (ast_strlen_zero(p->theirtag) || (resp >= 200)) {
18460 char tag[128];
18461
18462 gettag(req, "To", tag, sizeof(tag));
18463 ast_string_field_set(p, theirtag, tag);
18464 }
18465
18466
18467
18468
18469
18470
18471
18472
18473
18474
18475
18476
18477
18478
18479
18480 if ((resp == 404 || resp == 408 || resp == 481) && sipmethod == SIP_BYE) {
18481 pvt_set_needdestroy(p, "received 4XX response to a BYE");
18482 return;
18483 }
18484
18485 if (p->relatedpeer && p->method == SIP_OPTIONS) {
18486
18487
18488
18489 if (resp != 100)
18490 handle_response_peerpoke(p, resp, req);
18491 } else if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
18492 switch(resp) {
18493 case 100:
18494 case 101:
18495 case 183:
18496 case 180:
18497 case 182:
18498 if (sipmethod == SIP_INVITE)
18499 handle_response_invite(p, resp, rest, req, seqno);
18500 break;
18501 case 200:
18502 p->authtries = 0;
18503 if (sipmethod == SIP_MESSAGE || sipmethod == SIP_INFO) {
18504
18505
18506
18507 } else if (sipmethod == SIP_INVITE) {
18508 handle_response_invite(p, resp, rest, req, seqno);
18509 } else if (sipmethod == SIP_NOTIFY) {
18510 handle_response_notify(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_SUBSCRIBE) {
18514 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
18515 handle_response_subscribe(p, resp, rest, req, seqno);
18516 } else if (sipmethod == SIP_BYE) {
18517 pvt_set_needdestroy(p, "received 200 response");
18518 ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
18519 }
18520 break;
18521 case 202:
18522 if (sipmethod == SIP_REFER)
18523 handle_response_refer(p, resp, rest, req, seqno);
18524 break;
18525 case 401:
18526 case 407:
18527 if (sipmethod == SIP_INVITE)
18528 handle_response_invite(p, resp, rest, req, seqno);
18529 else if (sipmethod == SIP_NOTIFY)
18530 handle_response_notify(p, resp, rest, req, seqno);
18531 else if (sipmethod == SIP_REFER)
18532 handle_response_refer(p, resp, rest, req, seqno);
18533 else if (sipmethod == SIP_SUBSCRIBE)
18534 handle_response_subscribe(p, resp, rest, req, seqno);
18535 else if (p->registry && sipmethod == SIP_REGISTER)
18536 res = handle_response_register(p, resp, rest, req, seqno);
18537 else if (sipmethod == SIP_BYE) {
18538 if (p->options)
18539 p->options->auth_type = resp;
18540 if (ast_strlen_zero(p->authname)) {
18541 ast_log(LOG_WARNING, "Asked to authenticate %s, to %s:%d but we have no matching peer!\n",
18542 msg, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
18543 pvt_set_needdestroy(p, "unable to authenticate BYE");
18544 } else if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp, sipmethod, 0)) {
18545 ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
18546 pvt_set_needdestroy(p, "failed to authenticate BYE");
18547 }
18548 } else {
18549 ast_log(LOG_WARNING, "Got authentication request (%d) on %s to '%s'\n", resp, sip_methods[sipmethod].text, get_header(req, "To"));
18550 pvt_set_needdestroy(p, "received 407 response");
18551 }
18552 break;
18553 case 403:
18554 if (sipmethod == SIP_INVITE)
18555 handle_response_invite(p, resp, rest, req, seqno);
18556 else if (sipmethod == SIP_SUBSCRIBE)
18557 handle_response_subscribe(p, resp, rest, req, seqno);
18558 else if (p->registry && sipmethod == SIP_REGISTER)
18559 res = handle_response_register(p, resp, rest, req, seqno);
18560 else {
18561 ast_log(LOG_WARNING, "Forbidden - maybe wrong password on authentication for %s\n", msg);
18562 pvt_set_needdestroy(p, "received 403 response");
18563 }
18564 break;
18565 case 404:
18566 if (p->registry && sipmethod == SIP_REGISTER)
18567 res = handle_response_register(p, resp, rest, req, seqno);
18568 else if (sipmethod == SIP_INVITE)
18569 handle_response_invite(p, resp, rest, req, seqno);
18570 else if (sipmethod == SIP_SUBSCRIBE)
18571 handle_response_subscribe(p, resp, rest, req, seqno);
18572 else if (owner)
18573 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18574 break;
18575 case 423:
18576 if (sipmethod == SIP_REGISTER)
18577 res = handle_response_register(p, resp, rest, req, seqno);
18578 break;
18579 case 408:
18580 if (sipmethod == SIP_INVITE)
18581 handle_response_invite(p, resp, rest, req, seqno);
18582 else if (sipmethod == SIP_REGISTER)
18583 res = handle_response_register(p, resp, rest, req, seqno);
18584 else if (sipmethod == SIP_BYE) {
18585 pvt_set_needdestroy(p, "received 408 response");
18586 ast_debug(4, "Got timeout on bye. Thanks for the answer. Now, kill this call\n");
18587 } else {
18588 if (owner)
18589 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18590 pvt_set_needdestroy(p, "received 408 response");
18591 }
18592 break;
18593
18594 case 422:
18595 if (sipmethod == SIP_INVITE) {
18596 handle_response_invite(p, resp, rest, req, seqno);
18597 }
18598 break;
18599
18600 case 481:
18601 if (sipmethod == SIP_INVITE) {
18602 handle_response_invite(p, resp, rest, req, seqno);
18603 } else if (sipmethod == SIP_REFER) {
18604 handle_response_refer(p, resp, rest, req, seqno);
18605 } else if (sipmethod == SIP_SUBSCRIBE) {
18606 handle_response_subscribe(p, resp, rest, req, seqno);
18607 } else if (sipmethod == SIP_BYE) {
18608
18609
18610 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
18611 } else if (sipmethod == SIP_CANCEL) {
18612
18613
18614 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
18615 } else {
18616 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
18617
18618 }
18619 break;
18620 case 487:
18621 if (sipmethod == SIP_INVITE)
18622 handle_response_invite(p, resp, rest, req, seqno);
18623 break;
18624 case 415:
18625 case 488:
18626 case 606:
18627 if (sipmethod == SIP_INVITE)
18628 handle_response_invite(p, resp, rest, req, seqno);
18629 break;
18630 case 491:
18631 if (sipmethod == SIP_INVITE)
18632 handle_response_invite(p, resp, rest, req, seqno);
18633 else {
18634 ast_debug(1, "Got 491 on %s, unsupported. Call ID %s\n", sip_methods[sipmethod].text, p->callid);
18635 pvt_set_needdestroy(p, "received 491 response");
18636 }
18637 break;
18638 case 501:
18639 if (sipmethod == SIP_INVITE)
18640 handle_response_invite(p, resp, rest, req, seqno);
18641 else if (sipmethod == SIP_REFER)
18642 handle_response_refer(p, resp, rest, req, seqno);
18643 else
18644 ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n", ast_inet_ntoa(p->sa.sin_addr), msg);
18645 break;
18646 case 603:
18647 if (sipmethod == SIP_REFER) {
18648 handle_response_refer(p, resp, rest, req, seqno);
18649 break;
18650 }
18651
18652 default:
18653 if ((resp >= 300) && (resp < 700)) {
18654
18655 if ((resp != 487))
18656 ast_verb(3, "Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_inet_ntoa(p->sa.sin_addr));
18657
18658 if (sipmethod == SIP_INVITE)
18659 stop_media_flows(p);
18660
18661
18662 switch(resp) {
18663 case 300:
18664 case 301:
18665 case 302:
18666 case 305:
18667 parse_moved_contact(p, req);
18668
18669 case 486:
18670 case 600:
18671 case 603:
18672 if (p->owner)
18673 ast_queue_control(p->owner, AST_CONTROL_BUSY);
18674 break;
18675 case 482:
18676
18677
18678
18679
18680
18681 if (p->owner && ast_test_flag(&p->flags[1], SIP_PAGE2_FORWARD_LOOP_DETECTED)) {
18682 ast_debug(1, "Hairpin detected, setting up call forward for what it's worth\n");
18683 ast_string_field_build(p->owner, call_forward,
18684 "Local/%s@%s", p->username, p->context);
18685 }
18686
18687 case 480:
18688 case 404:
18689 case 410:
18690 case 400:
18691 case 500:
18692 if (sipmethod == SIP_REFER) {
18693 handle_response_refer(p, resp, rest, req, seqno);
18694 break;
18695 } else if (sipmethod == SIP_SUBSCRIBE) {
18696 handle_response_subscribe(p, resp, rest, req, seqno);
18697 break;
18698 }
18699
18700 case 502:
18701 case 503:
18702 case 504:
18703 if (owner)
18704 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18705 break;
18706 default:
18707
18708 if (owner && sipmethod != SIP_MESSAGE && sipmethod != SIP_INFO && sipmethod != SIP_BYE)
18709 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
18710 break;
18711 }
18712
18713 if (sipmethod == SIP_INVITE)
18714 transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
18715 if (sipmethod != SIP_MESSAGE && sipmethod != SIP_INFO)
18716 sip_alreadygone(p);
18717 if (!p->owner) {
18718 pvt_set_needdestroy(p, "transaction completed");
18719 }
18720 } else if ((resp >= 100) && (resp < 200)) {
18721 if (sipmethod == SIP_INVITE) {
18722 if (!req->ignore && sip_cancel_destroy(p))
18723 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
18724 if (find_sdp(req))
18725 process_sdp(p, req, SDP_T38_NONE);
18726 if (p->owner) {
18727
18728 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
18729 }
18730 }
18731 } else
18732 ast_log(LOG_NOTICE, "Don't know how to handle a %d %s response from %s\n", resp, rest, p->owner ? p->owner->name : ast_inet_ntoa(p->sa.sin_addr));
18733 }
18734 } else {
18735
18736
18737 if (req->debug)
18738 ast_verbose("SIP Response message for INCOMING dialog %s arrived\n", msg);
18739
18740 if (sipmethod == SIP_INVITE && resp == 200) {
18741
18742
18743 char tag[128];
18744
18745 gettag(req, "To", tag, sizeof(tag));
18746 ast_string_field_set(p, theirtag, tag);
18747 }
18748
18749 switch(resp) {
18750 case 200:
18751 if (sipmethod == SIP_INVITE) {
18752 handle_response_invite(p, resp, rest, req, seqno);
18753 } else if (sipmethod == SIP_CANCEL) {
18754 ast_debug(1, "Got 200 OK on CANCEL\n");
18755
18756
18757 } else if (sipmethod == SIP_NOTIFY) {
18758
18759 if (p->owner) {
18760 if (p->refer) {
18761 ast_debug(1, "Got 200 OK on NOTIFY for transfer\n");
18762 } else
18763 ast_log(LOG_WARNING, "Notify answer on an owned channel?\n");
18764
18765 } else {
18766 if (!p->subscribed && !p->refer) {
18767 pvt_set_needdestroy(p, "transaction completed");
18768 }
18769 if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
18770
18771 ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
18772 cb_extensionstate((char *)p->context, (char *)p->exten, p->laststate, (void *) p);
18773 }
18774 }
18775 } else if (sipmethod == SIP_BYE) {
18776 pvt_set_needdestroy(p, "transaction completed");
18777 } else if (sipmethod == SIP_MESSAGE || sipmethod == SIP_INFO) {
18778
18779
18780 ;
18781 }
18782 break;
18783 case 202:
18784 if (sipmethod == SIP_REFER)
18785 handle_response_refer(p, resp, rest, req, seqno);
18786 break;
18787 case 401:
18788 case 407:
18789 if (sipmethod == SIP_REFER)
18790 handle_response_refer(p, resp, rest, req, seqno);
18791 else if (sipmethod == SIP_INVITE)
18792 handle_response_invite(p, resp, rest, req, seqno);
18793 else if (sipmethod == SIP_BYE) {
18794 if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, sipmethod, 0)) {
18795 ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
18796 pvt_set_needdestroy(p, "failed to authenticate BYE");
18797 }
18798 }
18799 break;
18800 case 481:
18801 if (sipmethod == SIP_INVITE) {
18802
18803 handle_response_invite(p, resp, rest, req, seqno);
18804 } else if (sipmethod == SIP_BYE) {
18805 pvt_set_needdestroy(p, "received 481 response");
18806 } else if (sipdebug) {
18807 ast_debug(1, "Remote host can't match request %s to call '%s'. Giving up\n", sip_methods[sipmethod].text, p->callid);
18808 }
18809 break;
18810 case 501:
18811 if (sipmethod == SIP_INVITE)
18812 handle_response_invite(p, resp, rest, req, seqno);
18813 else if (sipmethod == SIP_REFER)
18814 handle_response_refer(p, resp, rest, req, seqno);
18815 break;
18816 case 603:
18817 if (sipmethod == SIP_REFER) {
18818 handle_response_refer(p, resp, rest, req, seqno);
18819 break;
18820 }
18821
18822 default:
18823 if ((resp >= 100) && (resp < 200)) {
18824 if (sipmethod == SIP_INVITE) {
18825 if (!req->ignore && sip_cancel_destroy(p))
18826 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
18827 }
18828 }
18829 if ((resp >= 300) && (resp < 700)) {
18830 if ((resp != 487))
18831 ast_verb(3, "Incoming call: Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_inet_ntoa(p->sa.sin_addr));
18832 switch(resp) {
18833 case 415:
18834 case 488:
18835 case 603:
18836 case 500:
18837 case 502:
18838 case 503:
18839 case 504:
18840
18841
18842 if (sipmethod == SIP_INVITE && sip_cancel_destroy(p))
18843 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
18844 break;
18845 }
18846 }
18847 break;
18848 }
18849 }
18850 }
18851
18852
18853
18854
18855
18856
18857
18858 static void *sip_park_thread(void *stuff)
18859 {
18860 struct ast_channel *transferee, *transferer;
18861 struct sip_dual *d;
18862 struct sip_request req = {0,};
18863 int ext;
18864 int res;
18865
18866 d = stuff;
18867 transferee = d->chan1;
18868 transferer = d->chan2;
18869 copy_request(&req, &d->req);
18870
18871 if (!transferee || !transferer) {
18872 ast_log(LOG_ERROR, "Missing channels for parking! Transferer %s Transferee %s\n", transferer ? "<available>" : "<missing>", transferee ? "<available>" : "<missing>" );
18873 deinit_req(&d->req);
18874 free(d);
18875 return NULL;
18876 }
18877 ast_debug(4, "SIP Park: Transferer channel %s, Transferee %s\n", transferer->name, transferee->name);
18878
18879 ast_channel_lock(transferee);
18880 if (ast_do_masquerade(transferee)) {
18881 ast_log(LOG_WARNING, "Masquerade failed.\n");
18882 transmit_response(transferer->tech_pvt, "503 Internal error", &req);
18883 ast_channel_unlock(transferee);
18884 deinit_req(&d->req);
18885 free(d);
18886 return NULL;
18887 }
18888 ast_channel_unlock(transferee);
18889
18890 res = ast_park_call(transferee, transferer, 0, &ext);
18891
18892
18893 #ifdef WHEN_WE_KNOW_THAT_THE_CLIENT_SUPPORTS_MESSAGE
18894 if (!res) {
18895 transmit_message_with_text(transferer->tech_pvt, "Unable to park call.\n");
18896 } else {
18897
18898 sprintf(buf, "Call parked on extension '%d'", ext);
18899 transmit_message_with_text(transferer->tech_pvt, buf);
18900 }
18901 #endif
18902
18903
18904
18905 transmit_response(transferer->tech_pvt, "202 Accepted", &req);
18906 if (!res) {
18907
18908 append_history(transferer->tech_pvt, "SIPpark", "Parked call on %d", ext);
18909 transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "200 OK", TRUE);
18910 transferer->hangupcause = AST_CAUSE_NORMAL_CLEARING;
18911 ast_hangup(transferer);
18912 ast_debug(1, "SIP Call parked on extension '%d'\n", ext);
18913 } else {
18914 transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "503 Service Unavailable", TRUE);
18915 append_history(transferer->tech_pvt, "SIPpark", "Parking failed\n");
18916 ast_debug(1, "SIP Call parked failed \n");
18917
18918 }
18919 deinit_req(&d->req);
18920 free(d);
18921 return NULL;
18922 }
18923
18924
18925
18926
18927 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno)
18928 {
18929 struct sip_dual *d;
18930 struct ast_channel *transferee, *transferer;
18931
18932 pthread_t th;
18933
18934 transferee = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan1->accountcode, chan1->exten, chan1->context, chan1->amaflags, "Parking/%s", chan1->name);
18935 transferer = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan2->accountcode, chan2->exten, chan2->context, chan2->amaflags, "SIPPeer/%s", chan2->name);
18936 if ((!transferer) || (!transferee)) {
18937 if (transferee) {
18938 transferee->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
18939 ast_hangup(transferee);
18940 }
18941 if (transferer) {
18942 transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
18943 ast_hangup(transferer);
18944 }
18945 return -1;
18946 }
18947
18948
18949 transferee->readformat = chan1->readformat;
18950 transferee->writeformat = chan1->writeformat;
18951
18952
18953 ast_channel_masquerade(transferee, chan1);
18954
18955
18956 ast_copy_string(transferee->context, chan1->context, sizeof(transferee->context));
18957 ast_copy_string(transferee->exten, chan1->exten, sizeof(transferee->exten));
18958 transferee->priority = chan1->priority;
18959
18960
18961
18962
18963
18964 transferer->readformat = chan2->readformat;
18965 transferer->writeformat = chan2->writeformat;
18966 if (!ast_strlen_zero(chan2->parkinglot))
18967 ast_string_field_set(transferer, parkinglot, chan2->parkinglot);
18968
18969
18970
18971
18972 while (ast_channel_trylock(chan2)) {
18973 struct sip_pvt *pvt = chan2->tech_pvt;
18974 sip_pvt_unlock(pvt);
18975 usleep(1);
18976 sip_pvt_lock(pvt);
18977 }
18978 ast_channel_masquerade(transferer, chan2);
18979 ast_channel_unlock(chan2);
18980
18981
18982 ast_copy_string(transferer->context, chan2->context, sizeof(transferer->context));
18983 ast_copy_string(transferer->exten, chan2->exten, sizeof(transferer->exten));
18984 transferer->priority = chan2->priority;
18985
18986 ast_channel_lock(transferer);
18987 if (ast_do_masquerade(transferer)) {
18988 ast_log(LOG_WARNING, "Masquerade failed :(\n");
18989 ast_channel_unlock(transferer);
18990 transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
18991 ast_hangup(transferer);
18992 return -1;
18993 }
18994 ast_channel_unlock(transferer);
18995 if (!transferer || !transferee) {
18996 if (!transferer) {
18997 ast_debug(1, "No transferer channel, giving up parking\n");
18998 }
18999 if (!transferee) {
19000 ast_debug(1, "No transferee channel, giving up parking\n");
19001 }
19002 return -1;
19003 }
19004 if ((d = ast_calloc(1, sizeof(*d)))) {
19005
19006
19007 copy_request(&d->req, req);
19008 d->chan1 = transferee;
19009 d->chan2 = transferer;
19010 d->seqno = seqno;
19011 if (ast_pthread_create_detached_background(&th, NULL, sip_park_thread, d) < 0) {
19012
19013 deinit_req(&d->req);
19014 ast_free(d);
19015
19016 return 0;
19017 }
19018 }
19019 return -1;
19020 }
19021
19022
19023
19024
19025 static void ast_quiet_chan(struct ast_channel *chan)
19026 {
19027 if (chan && chan->_state == AST_STATE_UP) {
19028 if (ast_test_flag(chan, AST_FLAG_MOH))
19029 ast_moh_stop(chan);
19030 else if (chan->generatordata)
19031 ast_deactivate_generator(chan);
19032 }
19033 }
19034
19035
19036
19037 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target)
19038 {
19039 int res = 0;
19040 struct ast_channel *peera = NULL,
19041 *peerb = NULL,
19042 *peerc = NULL,
19043 *peerd = NULL;
19044
19045
19046
19047
19048 ast_debug(4, "Sip transfer:--------------------\n");
19049 if (transferer->chan1)
19050 ast_debug(4, "-- Transferer to PBX channel: %s State %s\n", transferer->chan1->name, ast_state2str(transferer->chan1->_state));
19051 else
19052 ast_debug(4, "-- No transferer first channel - odd??? \n");
19053 if (target->chan1)
19054 ast_debug(4, "-- Transferer to PBX second channel (target): %s State %s\n", target->chan1->name, ast_state2str(target->chan1->_state));
19055 else
19056 ast_debug(4, "-- No target first channel ---\n");
19057 if (transferer->chan2)
19058 ast_debug(4, "-- Bridged call to transferee: %s State %s\n", transferer->chan2->name, ast_state2str(transferer->chan2->_state));
19059 else
19060 ast_debug(4, "-- No bridged call to transferee\n");
19061 if (target->chan2)
19062 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)");
19063 else
19064 ast_debug(4, "-- No target second channel ---\n");
19065 ast_debug(4, "-- END Sip transfer:--------------------\n");
19066 if (transferer->chan2) {
19067 peera = transferer->chan1;
19068 peerb = target->chan1;
19069 peerc = transferer->chan2;
19070 peerd = target->chan2;
19071 ast_debug(3, "SIP transfer: Four channels to handle\n");
19072 } else if (target->chan2) {
19073 peera = target->chan1;
19074 peerb = transferer->chan1;
19075 peerc = target->chan2;
19076 peerd = transferer->chan2;
19077 ast_debug(3, "SIP transfer: Three channels to handle\n");
19078 }
19079
19080 if (peera && peerb && peerc && (peerb != peerc)) {
19081 ast_quiet_chan(peera);
19082 ast_quiet_chan(peerb);
19083 ast_quiet_chan(peerc);
19084 if (peerd)
19085 ast_quiet_chan(peerd);
19086
19087 ast_debug(4, "SIP transfer: trying to masquerade %s into %s\n", peerc->name, peerb->name);
19088 if (ast_channel_masquerade(peerb, peerc)) {
19089 ast_log(LOG_WARNING, "Failed to masquerade %s into %s\n", peerb->name, peerc->name);
19090 res = -1;
19091 } else
19092 ast_debug(4, "SIP transfer: Succeeded to masquerade channels.\n");
19093 return res;
19094 } else {
19095 ast_log(LOG_NOTICE, "SIP Transfer attempted with no appropriate bridged calls to transfer\n");
19096 if (transferer->chan1)
19097 ast_softhangup_nolock(transferer->chan1, AST_SOFTHANGUP_DEV);
19098 if (target->chan1)
19099 ast_softhangup_nolock(target->chan1, AST_SOFTHANGUP_DEV);
19100 return -1;
19101 }
19102 return 0;
19103 }
19104
19105
19106
19107
19108
19109
19110 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize)
19111 {
19112 const char *thetag;
19113
19114 if (!tagbuf)
19115 return NULL;
19116 tagbuf[0] = '\0';
19117 thetag = get_header(req, header);
19118 thetag = strcasestr(thetag, ";tag=");
19119 if (thetag) {
19120 thetag += 5;
19121 ast_copy_string(tagbuf, thetag, tagbufsize);
19122 return strsep(&tagbuf, ";");
19123 }
19124 return NULL;
19125 }
19126
19127
19128 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e)
19129 {
19130
19131
19132 int res = 0;
19133 const char *event = get_header(req, "Event");
19134 char *eventid = NULL;
19135 char *sep;
19136
19137 if( (sep = strchr(event, ';')) ) {
19138 *sep++ = '\0';
19139 eventid = sep;
19140 }
19141
19142 if (sipdebug)
19143 ast_debug(2, "Got NOTIFY Event: %s\n", event);
19144
19145 if (!strcmp(event, "refer")) {
19146
19147
19148
19149
19150
19151 char buf[1024];
19152 char *cmd, *code;
19153 int respcode;
19154 int success = TRUE;
19155
19156
19157
19158
19159
19160
19161
19162
19163 if (strncasecmp(get_header(req, "Content-Type"), "message/sipfrag", strlen("message/sipfrag"))) {
19164
19165 transmit_response(p, "400 Bad request", req);
19166 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19167 return -1;
19168 }
19169
19170
19171 if (get_msg_text(buf, sizeof(buf), req, TRUE)) {
19172 ast_log(LOG_WARNING, "Unable to retrieve attachment from NOTIFY %s\n", p->callid);
19173 transmit_response(p, "400 Bad request", req);
19174 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19175 return -1;
19176 }
19177
19178
19179
19180
19181
19182
19183
19184
19185
19186
19187
19188
19189
19190
19191
19192
19193
19194
19195
19196
19197
19198 ast_debug(3, "* SIP Transfer NOTIFY Attachment: \n---%s\n---\n", buf);
19199 cmd = ast_skip_blanks(buf);
19200 code = cmd;
19201
19202 while(*code && (*code > 32)) {
19203 code++;
19204 }
19205 *code++ = '\0';
19206 code = ast_skip_blanks(code);
19207 sep = code;
19208 sep++;
19209 while(*sep && (*sep > 32)) {
19210 sep++;
19211 }
19212 *sep++ = '\0';
19213 respcode = atoi(code);
19214 switch (respcode) {
19215 case 100:
19216 case 101:
19217
19218 break;
19219 case 183:
19220
19221 break;
19222 case 200:
19223
19224 break;
19225 case 301:
19226 case 302:
19227
19228 success = FALSE;
19229 break;
19230 case 503:
19231
19232 success = FALSE;
19233 break;
19234 case 603:
19235
19236 success = FALSE;
19237 break;
19238 }
19239 if (!success) {
19240 ast_log(LOG_NOTICE, "Transfer failed. Sorry. Nothing further to do with this call\n");
19241 }
19242
19243
19244 transmit_response(p, "200 OK", req);
19245 } else if (p->mwi && !strcmp(event, "message-summary")) {
19246 char *c = ast_strdupa(get_body(req, "Voice-Message", ':'));
19247
19248 if (!ast_strlen_zero(c)) {
19249 char *old = strsep(&c, " ");
19250 char *new = strsep(&old, "/");
19251 struct ast_event *event;
19252
19253 if ((event = ast_event_new(AST_EVENT_MWI,
19254 AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, p->mwi->mailbox,
19255 AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, "SIP_Remote",
19256 AST_EVENT_IE_NEWMSGS, AST_EVENT_IE_PLTYPE_UINT, atoi(new),
19257 AST_EVENT_IE_OLDMSGS, AST_EVENT_IE_PLTYPE_UINT, atoi(old),
19258 AST_EVENT_IE_END))) {
19259 ast_event_queue_and_cache(event);
19260 }
19261 }
19262
19263 transmit_response(p, "200 OK", req);
19264 } else if (!strcmp(event, "keep-alive")) {
19265
19266
19267 transmit_response(p, "200 OK", req);
19268 } else {
19269
19270 transmit_response(p, "489 Bad event", req);
19271 res = -1;
19272 }
19273
19274 if (!p->lastinvite)
19275 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19276
19277 return res;
19278 }
19279
19280
19281
19282
19283 static int handle_request_options(struct sip_pvt *p, struct sip_request *req)
19284 {
19285 int res;
19286
19287
19288
19289
19290
19291
19292
19293
19294
19295
19296
19297 if (p->lastinvite) {
19298
19299 transmit_response_with_allow(p, "200 OK", req, 0);
19300 return 0;
19301 }
19302
19303 res = get_destination(p, req);
19304 build_contact(p);
19305
19306 if (ast_strlen_zero(p->context))
19307 ast_string_field_set(p, context, sip_cfg.default_context);
19308
19309 if (ast_shutting_down())
19310 transmit_response_with_allow(p, "503 Unavailable", req, 0);
19311 else if (res < 0)
19312 transmit_response_with_allow(p, "404 Not Found", req, 0);
19313 else
19314 transmit_response_with_allow(p, "200 OK", req, 0);
19315
19316
19317
19318 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19319
19320 return res;
19321 }
19322
19323
19324
19325
19326
19327
19328
19329
19330
19331
19332 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin, int *nounlock)
19333 {
19334 int earlyreplace = 0;
19335 int oneleggedreplace = 0;
19336 struct ast_channel *c = p->owner;
19337 struct ast_channel *replacecall = p->refer->refer_call->owner;
19338 struct ast_channel *targetcall;
19339
19340 struct ast_channel *test;
19341
19342
19343 if (replacecall->_state == AST_STATE_RING)
19344 earlyreplace = 1;
19345
19346
19347 if (!(targetcall = ast_bridged_channel(replacecall))) {
19348
19349 if (!earlyreplace) {
19350 ast_debug(2, " Attended transfer attempted to replace call with no bridge (maybe ringing). Channel %s!\n", replacecall->name);
19351 oneleggedreplace = 1;
19352 }
19353 }
19354 if (targetcall && targetcall->_state == AST_STATE_RINGING)
19355 ast_debug(4, "SIP transfer: Target channel is in ringing state\n");
19356
19357 if (targetcall)
19358 ast_debug(4, "SIP transfer: Invite Replace incoming channel should bridge to channel %s while hanging up channel %s\n", targetcall->name, replacecall->name);
19359 else
19360 ast_debug(4, "SIP transfer: Invite Replace incoming channel should replace and hang up channel %s (one call leg)\n", replacecall->name);
19361
19362 if (req->ignore) {
19363 ast_log(LOG_NOTICE, "Ignoring this INVITE with replaces in a stupid way.\n");
19364
19365
19366
19367 transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE);
19368
19369 if (c) {
19370 *nounlock = 1;
19371 ast_channel_unlock(c);
19372 }
19373 ast_channel_unlock(replacecall);
19374 sip_pvt_unlock(p->refer->refer_call);
19375 return 1;
19376 }
19377 if (!c) {
19378
19379 ast_log(LOG_ERROR, "Unable to create new channel. Invite/replace failed.\n");
19380 transmit_response_reliable(p, "503 Service Unavailable", req);
19381 append_history(p, "Xfer", "INVITE/Replace Failed. No new channel.");
19382 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19383 ast_channel_unlock(replacecall);
19384 sip_pvt_unlock(p->refer->refer_call);
19385 return 1;
19386 }
19387 append_history(p, "Xfer", "INVITE/Replace received");
19388
19389
19390
19391
19392
19393
19394
19395
19396
19397
19398
19399 transmit_response(p, "100 Trying", req);
19400 ast_setstate(c, AST_STATE_RING);
19401
19402
19403
19404
19405
19406 transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE);
19407
19408 ast_setstate(c, AST_STATE_UP);
19409
19410
19411 ast_quiet_chan(replacecall);
19412 ast_quiet_chan(targetcall);
19413 ast_debug(4, "Invite/Replaces: preparing to masquerade %s into %s\n", c->name, replacecall->name);
19414
19415
19416 if (! earlyreplace && ! oneleggedreplace )
19417 ast_set_flag(&p->refer->refer_call->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
19418
19419
19420 if(ast_channel_masquerade(replacecall, c))
19421 ast_log(LOG_ERROR, "Failed to masquerade C into Replacecall\n");
19422 else
19423 ast_debug(4, "Invite/Replaces: Going to masquerade %s into %s\n", c->name, replacecall->name);
19424
19425
19426 if (ast_do_masquerade(replacecall)) {
19427 ast_log(LOG_WARNING, "Failed to perform masquerade with INVITE replaces\n");
19428 }
19429
19430 if (earlyreplace || oneleggedreplace ) {
19431 c->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
19432 }
19433
19434 ast_setstate(c, AST_STATE_DOWN);
19435 ast_debug(4, "After transfer:----------------------------\n");
19436 ast_debug(4, " -- C: %s State %s\n", c->name, ast_state2str(c->_state));
19437 if (replacecall)
19438 ast_debug(4, " -- replacecall: %s State %s\n", replacecall->name, ast_state2str(replacecall->_state));
19439 if (p->owner) {
19440 ast_debug(4, " -- P->owner: %s State %s\n", p->owner->name, ast_state2str(p->owner->_state));
19441 test = ast_bridged_channel(p->owner);
19442 if (test)
19443 ast_debug(4, " -- Call bridged to P->owner: %s State %s\n", test->name, ast_state2str(test->_state));
19444 else
19445 ast_debug(4, " -- No call bridged to C->owner \n");
19446 } else
19447 ast_debug(4, " -- No channel yet \n");
19448 ast_debug(4, "End After transfer:----------------------------\n");
19449
19450
19451 ast_channel_unlock(replacecall);
19452 ast_channel_unlock(c);
19453 sip_pvt_unlock(p->refer->refer_call);
19454 sip_pvt_unlock(p);
19455 *nounlock = 1;
19456
19457
19458 c->tech_pvt = dialog_unref(c->tech_pvt, "unref dialog c->tech_pvt");
19459 ast_hangup(c);
19460 sip_pvt_lock(p);
19461
19462 return 0;
19463 }
19464
19465
19466
19467
19468
19469
19470
19471
19472
19473
19474
19475
19476
19477
19478
19479
19480
19481
19482 static int sip_uri_params_cmp(const char *input1, const char *input2)
19483 {
19484 char *params1 = NULL;
19485 char *params2 = NULL;
19486 char *pos1;
19487 char *pos2;
19488 int zerolength1 = 0;
19489 int zerolength2 = 0;
19490 int maddrmatch = 0;
19491 int ttlmatch = 0;
19492 int usermatch = 0;
19493 int methodmatch = 0;
19494
19495 if (ast_strlen_zero(input1)) {
19496 zerolength1 = 1;
19497 } else {
19498 params1 = ast_strdupa(input1);
19499 }
19500 if (ast_strlen_zero(input2)) {
19501 zerolength2 = 1;
19502 } else {
19503 params2 = ast_strdupa(input2);
19504 }
19505
19506
19507
19508
19509 if (zerolength1 && zerolength2) {
19510 return 0;
19511 }
19512
19513 for (pos1 = strsep(¶ms1, ";"); pos1; pos1 = strsep(¶ms1, ";")) {
19514 char *value1 = pos1;
19515 char *name1 = strsep(&value1, "=");
19516 char *params2dup = NULL;
19517 int matched = 0;
19518 if (!value1) {
19519 value1 = "";
19520 }
19521
19522
19523
19524
19525 if (!zerolength2) {
19526 params2dup = ast_strdupa(params2);
19527 }
19528 for (pos2 = strsep(¶ms2dup, ";"); pos2; pos2 = strsep(¶ms2dup, ";")) {
19529 char *name2 = pos2;
19530 char *value2 = strchr(pos2, '=');
19531 if (!value2) {
19532 value2 = "";
19533 } else {
19534 *value2++ = '\0';
19535 }
19536 if (!strcasecmp(name1, name2)) {
19537 if (strcasecmp(value1, value2)) {
19538 goto fail;
19539 } else {
19540 matched = 1;
19541 break;
19542 }
19543 }
19544 }
19545
19546 if (!strcasecmp(name1, "maddr")) {
19547 if (matched) {
19548 maddrmatch = 1;
19549 } else {
19550 goto fail;
19551 }
19552 } else if (!strcasecmp(name1, "ttl")) {
19553 if (matched) {
19554 ttlmatch = 1;
19555 } else {
19556 goto fail;
19557 }
19558 } else if (!strcasecmp(name1, "user")) {
19559 if (matched) {
19560 usermatch = 1;
19561 } else {
19562 goto fail;
19563 }
19564 } else if (!strcasecmp(name1, "method")) {
19565 if (matched) {
19566 methodmatch = 1;
19567 } else {
19568 goto fail;
19569 }
19570 }
19571 }
19572
19573
19574
19575
19576
19577 for (pos2 = strsep(¶ms2, ";"); pos2; pos2 = strsep(¶ms2, ";")) {
19578 char *value2 = pos2;
19579 char *name2 = strsep(&value2, "=");
19580 if (!value2) {
19581 value2 = "";
19582 }
19583 if ((!strcasecmp(name2, "maddr") && !maddrmatch) ||
19584 (!strcasecmp(name2, "ttl") && !ttlmatch) ||
19585 (!strcasecmp(name2, "user") && !usermatch) ||
19586 (!strcasecmp(name2, "method") && !methodmatch)) {
19587 goto fail;
19588 }
19589 }
19590 return 0;
19591
19592 fail:
19593 return 1;
19594 }
19595
19596
19597
19598
19599
19600
19601
19602
19603
19604
19605
19606
19607 static int sip_uri_headers_cmp(const char *input1, const char *input2)
19608 {
19609 char *headers1 = NULL;
19610 char *headers2 = NULL;
19611 int zerolength1 = 0;
19612 int zerolength2 = 0;
19613 int different = 0;
19614 char *header1;
19615
19616 if (ast_strlen_zero(input1)) {
19617 zerolength1 = 1;
19618 } else {
19619 headers1 = ast_strdupa(input1);
19620 }
19621
19622 if (ast_strlen_zero(input2)) {
19623 zerolength2 = 1;
19624 } else {
19625 headers2 = ast_strdupa(input2);
19626 }
19627
19628 if ((zerolength1 && !zerolength2) ||
19629 (zerolength2 && !zerolength1))
19630 return 1;
19631
19632 if (zerolength1 && zerolength2)
19633 return 0;
19634
19635
19636
19637
19638
19639 if (strlen(headers1) != strlen(headers2)) {
19640 return 1;
19641 }
19642
19643 for (header1 = strsep(&headers1, "&"); header1; header1 = strsep(&headers1, "&")) {
19644 if (!strcasestr(headers2, header1)) {
19645 different = 1;
19646 break;
19647 }
19648 }
19649
19650 return different;
19651 }
19652
19653 static int sip_uri_cmp(const char *input1, const char *input2)
19654 {
19655 char *uri1 = ast_strdupa(input1);
19656 char *uri2 = ast_strdupa(input2);
19657 char *host1;
19658 char *host2;
19659 char *params1;
19660 char *params2;
19661 char *headers1;
19662 char *headers2;
19663
19664
19665
19666
19667 strsep(&uri1, ":");
19668 strsep(&uri2, ":");
19669
19670 if ((host1 = strchr(uri1, '@'))) {
19671 *host1++ = '\0';
19672 }
19673 if ((host2 = strchr(uri2, '@'))) {
19674 *host2++ = '\0';
19675 }
19676
19677
19678
19679
19680 if ((host1 && !host2) ||
19681 (host2 && !host1) ||
19682 (host1 && host2 && strcmp(uri1, uri2))) {
19683 return 1;
19684 }
19685
19686 if (!host1)
19687 host1 = uri1;
19688 if (!host2)
19689 host2 = uri2;
19690
19691
19692
19693
19694
19695 if ((params1 = strchr(host1, ';'))) {
19696 *params1++ = '\0';
19697 }
19698 if ((params2 = strchr(host2, ';'))) {
19699 *params2++ = '\0';
19700 }
19701
19702
19703
19704
19705 if ((headers1 = strchr(S_OR(params1, host1), '?'))) {
19706 *headers1++ = '\0';
19707 }
19708 if ((headers2 = strchr(S_OR(params2, host2), '?'))) {
19709 *headers2++ = '\0';
19710 }
19711
19712
19713
19714
19715
19716
19717
19718
19719
19720
19721
19722 if (strcasecmp(host1, host2)) {
19723 return 1;
19724 }
19725
19726
19727 if (sip_uri_headers_cmp(headers1, headers2)) {
19728 return 1;
19729 }
19730
19731
19732 return sip_uri_params_cmp(params1, params2);
19733 }
19734
19735 static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context)
19736 {
19737 struct ast_str *str = ast_str_alloca(AST_MAX_EXTENSION + AST_MAX_CONTEXT + 2);
19738 struct ast_app *pickup = pbx_findapp("Pickup");
19739
19740 if (!pickup) {
19741 ast_log(LOG_ERROR, "Unable to perform pickup: Application 'Pickup' not loaded (app_directed_pickup.so).\n");
19742 return -1;
19743 }
19744
19745 ast_str_set(&str, 0, "%s@%s", extension, sip_cfg.notifycid == IGNORE_CONTEXT ? "PICKUPMARK" : context);
19746
19747 ast_debug(2, "About to call Pickup(%s)\n", str->str);
19748
19749
19750
19751
19752 pbx_exec(channel, pickup, str->str);
19753
19754 return 0;
19755 }
19756
19757
19758 static int sip_t38_abort(const void *data)
19759 {
19760 struct sip_pvt *p = (struct sip_pvt *) data;
19761
19762 sip_pvt_lock(p);
19763
19764
19765
19766
19767
19768 if (p->t38id != -1) {
19769 change_t38_state(p, T38_DISABLED);
19770 transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
19771 p->t38id = -1;
19772 dialog_unref(p, "unref the dialog ptr from sip_t38_abort, because it held a dialog ptr");
19773 }
19774 sip_pvt_unlock(p);
19775 return 0;
19776 }
19777
19778
19779
19780
19781
19782
19783
19784 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)
19785 {
19786 int res = 1;
19787 int gotdest;
19788 const char *p_replaces;
19789 char *replace_id = NULL;
19790 int refer_locked = 0;
19791 const char *required;
19792 unsigned int required_profile = 0;
19793 struct ast_channel *c = NULL;
19794 int reinvite = 0;
19795 int rtn;
19796
19797 const char *p_uac_se_hdr;
19798 const char *p_uac_min_se;
19799 int uac_max_se = -1;
19800 int uac_min_se = -1;
19801 int st_active = FALSE;
19802 int st_interval = 0;
19803 enum st_refresher st_ref;
19804 int dlg_min_se = -1;
19805 struct {
19806 char exten[AST_MAX_EXTENSION];
19807 char context[AST_MAX_CONTEXT];
19808 } pickup = {
19809 .exten = "",
19810 };
19811 st_ref = SESSION_TIMER_REFRESHER_AUTO;
19812
19813
19814 if (!p->sipoptions) {
19815 const char *supported = get_header(req, "Supported");
19816 if (!ast_strlen_zero(supported))
19817 parse_sip_options(p, supported);
19818 }
19819
19820
19821 required = get_header(req, "Require");
19822 if (!ast_strlen_zero(required)) {
19823 required_profile = parse_sip_options(NULL, required);
19824 if (required_profile && !(required_profile & (SIP_OPT_REPLACES | SIP_OPT_TIMER))) {
19825
19826 transmit_response_with_unsupported(p, "420 Bad extension (unsupported)", req, required);
19827 ast_log(LOG_WARNING, "Received SIP INVITE with unsupported required extension: %s\n", required);
19828 p->invitestate = INV_COMPLETED;
19829 if (!p->lastinvite)
19830 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19831 res = -1;
19832 goto request_invite_cleanup;
19833 }
19834 }
19835
19836
19837
19838 p->sipoptions |= required_profile;
19839 p->reqsipoptions = required_profile;
19840
19841
19842 if (ast_test_flag(&p->flags[0], SIP_OUTGOING) && p->owner && (p->invitestate != INV_TERMINATED && p->invitestate != INV_CONFIRMED)) {
19843
19844
19845
19846
19847
19848 int different;
19849 char *initial_rlPart2 = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
19850 char *this_rlPart2 = REQ_OFFSET_TO_STR(req, rlPart2);
19851 if (sip_cfg.pedanticsipchecking)
19852 different = sip_uri_cmp(initial_rlPart2, this_rlPart2);
19853 else
19854 different = strcmp(initial_rlPart2, this_rlPart2);
19855 if (!different) {
19856 transmit_response(p, "482 Loop Detected", req);
19857 p->invitestate = INV_COMPLETED;
19858 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19859 res = 0;
19860 goto request_invite_cleanup;
19861 } else {
19862
19863
19864
19865
19866
19867
19868
19869 char *uri = ast_strdupa(this_rlPart2);
19870 char *at = strchr(uri, '@');
19871 char *peerorhost;
19872 ast_debug(2, "Potential spiral detected. Original RURI was %s, new RURI is %s\n", initial_rlPart2, this_rlPart2);
19873 transmit_response(p, "100 Trying", req);
19874 if (at) {
19875 *at = '\0';
19876 }
19877
19878 if ((peerorhost = strchr(uri, ':'))) {
19879 *peerorhost++ = '\0';
19880 }
19881 ast_string_field_set(p, theirtag, NULL);
19882
19883
19884 ast_string_field_set(p->owner, call_forward, peerorhost);
19885 ast_queue_control(p->owner, AST_CONTROL_BUSY);
19886 res = 0;
19887 goto request_invite_cleanup;
19888 }
19889 }
19890
19891 if (!req->ignore && p->pendinginvite) {
19892 if (!ast_test_flag(&p->flags[0], SIP_OUTGOING) && (p->invitestate == INV_COMPLETED || p->invitestate == INV_TERMINATED)) {
19893
19894
19895
19896
19897
19898
19899
19900
19901
19902
19903 __sip_ack(p, p->pendinginvite, 1, 0);
19904 } else {
19905
19906 p->glareinvite = seqno;
19907 if (p->rtp && find_sdp(req)) {
19908 struct sockaddr_in sin;
19909 if (get_ip_and_port_from_sdp(req, SDP_AUDIO, &sin)) {
19910 ast_log(LOG_WARNING, "Failed to set an alternate media source on glared reinvite. Audio may not work properly on this call.\n");
19911 } else {
19912 ast_rtp_set_alt_peer(p->rtp, &sin);
19913 }
19914 if (p->vrtp) {
19915 if (get_ip_and_port_from_sdp(req, SDP_VIDEO, &sin)) {
19916 ast_log(LOG_WARNING, "Failed to set an alternate media source on glared reinvite. Video may not work properly on this call.\n");
19917 } else {
19918 ast_rtp_set_alt_peer(p->vrtp, &sin);
19919 }
19920 }
19921 }
19922 transmit_response_reliable(p, "491 Request Pending", req);
19923 ast_debug(1, "Got INVITE on call where we already have pending INVITE, deferring that - %s\n", p->callid);
19924
19925 res = 0;
19926 goto request_invite_cleanup;
19927 }
19928 }
19929
19930 p_replaces = get_header(req, "Replaces");
19931 if (!ast_strlen_zero(p_replaces)) {
19932
19933 char *ptr;
19934 char *fromtag = NULL;
19935 char *totag = NULL;
19936 char *start, *to;
19937 int error = 0;
19938
19939 if (p->owner) {
19940 ast_debug(3, "INVITE w Replaces on existing call? Refusing action. [%s]\n", p->callid);
19941 transmit_response_reliable(p, "400 Bad request", req);
19942
19943 res = -1;
19944 goto request_invite_cleanup;
19945 }
19946
19947 if (sipdebug)
19948 ast_debug(3, "INVITE part of call transfer. Replaces [%s]\n", p_replaces);
19949
19950 replace_id = ast_strdupa(p_replaces);
19951 ast_uri_decode(replace_id);
19952
19953 if (!p->refer && !sip_refer_allocate(p)) {
19954 transmit_response_reliable(p, "500 Server Internal Error", req);
19955 append_history(p, "Xfer", "INVITE/Replace Failed. Out of memory.");
19956 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19957 p->invitestate = INV_COMPLETED;
19958 res = -1;
19959 goto request_invite_cleanup;
19960 }
19961
19962
19963
19964
19965
19966
19967
19968
19969
19970
19971 replace_id = ast_skip_blanks(replace_id);
19972
19973 start = replace_id;
19974 while ( (ptr = strsep(&start, ";")) ) {
19975 ptr = ast_skip_blanks(ptr);
19976 if ( (to = strcasestr(ptr, "to-tag=") ) )
19977 totag = to + 7;
19978 else if ( (to = strcasestr(ptr, "from-tag=") ) ) {
19979 fromtag = to + 9;
19980 fromtag = strsep(&fromtag, "&");
19981 }
19982 }
19983
19984 if (sipdebug)
19985 ast_debug(4, "Invite/replaces: Will use Replace-Call-ID : %s Fromtag: %s Totag: %s\n",
19986 replace_id,
19987 fromtag ? fromtag : "<no from tag>",
19988 totag ? totag : "<no to tag>");
19989
19990
19991
19992
19993
19994 if (strncmp(replace_id, "pickup-", 7) == 0) {
19995 struct sip_pvt *subscription = NULL;
19996 replace_id += 7;
19997
19998 if ((subscription = get_sip_pvt_byid_locked(replace_id, NULL, NULL)) == NULL) {
19999 ast_log(LOG_NOTICE, "Unable to find subscription with call-id: %s\n", replace_id);
20000 transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
20001 error = 1;
20002 } else {
20003 ast_log(LOG_NOTICE, "Trying to pick up %s@%s\n", subscription->exten, subscription->context);
20004 ast_copy_string(pickup.exten, subscription->exten, sizeof(pickup.exten));
20005 ast_copy_string(pickup.context, subscription->context, sizeof(pickup.context));
20006 sip_pvt_unlock(subscription);
20007 if (subscription->owner) {
20008 ast_channel_unlock(subscription->owner);
20009 }
20010 }
20011 }
20012
20013
20014 if (!error && ast_strlen_zero(pickup.exten) && (p->refer->refer_call = get_sip_pvt_byid_locked(replace_id, totag, fromtag)) == NULL) {
20015 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existent call id (%s)!\n", replace_id);
20016 transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
20017 error = 1;
20018 } else {
20019 refer_locked = 1;
20020 }
20021
20022
20023
20024
20025
20026 if (p->refer->refer_call == p) {
20027 ast_log(LOG_NOTICE, "INVITE with replaces into it's own call id (%s == %s)!\n", replace_id, p->callid);
20028 p->refer->refer_call = dialog_unref(p->refer->refer_call, "unref dialog p->refer->refer_call");
20029 transmit_response_reliable(p, "400 Bad request", req);
20030 error = 1;
20031 }
20032
20033 if (!error && ast_strlen_zero(pickup.exten) && !p->refer->refer_call->owner) {
20034
20035 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existing call id (%s)!\n", replace_id);
20036
20037 transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replace)", req);
20038 error = 1;
20039 }
20040
20041 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) {
20042 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-ringing or active call id (%s)!\n", replace_id);
20043 transmit_response_reliable(p, "603 Declined (Replaces)", req);
20044 error = 1;
20045 }
20046
20047 if (error) {
20048 append_history(p, "Xfer", "INVITE/Replace Failed.");
20049 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20050 sip_pvt_unlock(p);
20051 if (p->refer->refer_call) {
20052 sip_pvt_unlock(p->refer->refer_call);
20053 if (p->refer->refer_call->owner) {
20054 ast_channel_unlock(p->refer->refer_call->owner);
20055 }
20056 }
20057 refer_locked = 0;
20058 p->invitestate = INV_COMPLETED;
20059 res = -1;
20060 goto request_invite_cleanup;
20061 }
20062 }
20063
20064
20065
20066
20067 if (!req->ignore) {
20068 int newcall = (p->initreq.headers ? TRUE : FALSE);
20069
20070 if (sip_cancel_destroy(p))
20071 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
20072
20073 p->pendinginvite = seqno;
20074 check_via(p, req);
20075
20076 copy_request(&p->initreq, req);
20077 if (sipdebug)
20078 ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
20079 if (!p->owner) {
20080 if (debug)
20081 ast_verbose("Using INVITE request as basis request - %s\n", p->callid);
20082 if (newcall)
20083 append_history(p, "Invite", "New call: %s", p->callid);
20084 parse_ok_contact(p, req);
20085 } else {
20086 ast_clear_flag(&p->flags[0], SIP_OUTGOING);
20087
20088 if (find_sdp(req)) {
20089 if (process_sdp(p, req, SDP_T38_INITIATE)) {
20090 transmit_response_reliable(p, "488 Not acceptable here", req);
20091 if (!p->lastinvite)
20092 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20093 res = -1;
20094 goto request_invite_cleanup;
20095 }
20096 ast_queue_control(p->owner, AST_CONTROL_SRCUPDATE);
20097 } else {
20098 p->jointcapability = p->capability;
20099 ast_debug(1, "Hm.... No sdp for the moment\n");
20100 }
20101 if (p->do_history)
20102 append_history(p, "ReInv", "Re-invite received");
20103 }
20104 } else if (debug)
20105 ast_verbose("Ignoring this INVITE request\n");
20106
20107 if (!p->lastinvite && !req->ignore && !p->owner) {
20108
20109
20110 res = check_user(p, req, SIP_INVITE, e, XMIT_RELIABLE, sin);
20111 if (res == AUTH_CHALLENGE_SENT) {
20112 p->invitestate = INV_COMPLETED;
20113 res = 0;
20114 goto request_invite_cleanup;
20115 }
20116 if (res < 0) {
20117 if (res == AUTH_FAKE_AUTH) {
20118 ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", get_header(req, "From"));
20119 transmit_fake_auth_response(p, SIP_INVITE, req, XMIT_RELIABLE);
20120 } else {
20121 ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", get_header(req, "From"));
20122 transmit_response_reliable(p, "403 Forbidden", req);
20123 }
20124 p->invitestate = INV_COMPLETED;
20125 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20126 ast_string_field_set(p, theirtag, NULL);
20127 res = 0;
20128 goto request_invite_cleanup;
20129 }
20130
20131
20132 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) && !p->udptl) {
20133 if ((p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr))) {
20134 p->t38_maxdatagram = global_t38_maxdatagram;
20135 set_t38_capabilities(p);
20136 } else {
20137
20138 ast_debug(1, "UDPTL creation failed on dialog.\n");
20139 ast_clear_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT);
20140 }
20141 }
20142
20143
20144 if (find_sdp(req)) {
20145 if (process_sdp(p, req, SDP_T38_INITIATE)) {
20146
20147 transmit_response_reliable(p, "488 Not acceptable here", req);
20148 p->invitestate = INV_COMPLETED;
20149 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20150 ast_debug(1, "No compatible codecs for this SIP call.\n");
20151 res = -1;
20152 goto request_invite_cleanup;
20153 }
20154 } else {
20155 p->jointcapability = p->capability;
20156 ast_debug(2, "No SDP in Invite, third party call control\n");
20157 }
20158
20159
20160
20161 if (p->owner)
20162 ast_queue_frame(p->owner, &ast_null_frame);
20163
20164
20165
20166 if (ast_strlen_zero(p->context))
20167 ast_string_field_set(p, context, sip_cfg.default_context);
20168
20169
20170
20171 ast_debug(1, "Checking SIP call limits for device %s\n", p->username);
20172 if ((res = update_call_counter(p, INC_CALL_LIMIT))) {
20173 if (res < 0) {
20174 ast_log(LOG_NOTICE, "Failed to place call for device %s, too many calls\n", p->username);
20175 transmit_response_reliable(p, "480 Temporarily Unavailable (Call limit) ", req);
20176 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20177 p->invitestate = INV_COMPLETED;
20178 }
20179 res = 0;
20180 goto request_invite_cleanup;
20181 }
20182 gotdest = get_destination(p, NULL);
20183 get_rdnis(p, NULL);
20184 extract_uri(p, req);
20185 build_contact(p);
20186
20187 if (p->rtp) {
20188 ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
20189 ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
20190 }
20191
20192 if (!replace_id && gotdest) {
20193 if (gotdest == 1 && ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP))
20194 transmit_response_reliable(p, "484 Address Incomplete", req);
20195 else {
20196 char *decoded_exten = ast_strdupa(p->exten);
20197
20198 transmit_response_reliable(p, "404 Not Found", req);
20199 ast_uri_decode(decoded_exten);
20200 ast_log(LOG_NOTICE, "Call from '%s' to extension"
20201 " '%s' rejected because extension not found in context '%s'.\n",
20202 S_OR(p->username, p->peername), decoded_exten, p->context);
20203 }
20204 p->invitestate = INV_COMPLETED;
20205 update_call_counter(p, DEC_CALL_LIMIT);
20206 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20207 res = 0;
20208 goto request_invite_cleanup;
20209 } else {
20210
20211
20212
20213 if (ast_strlen_zero(p->exten))
20214 ast_string_field_set(p, exten, "s");
20215
20216
20217 make_our_tag(p->tag, sizeof(p->tag));
20218
20219 c = sip_new(p, AST_STATE_DOWN, S_OR(p->peername, NULL));
20220 *recount = 1;
20221
20222
20223 build_route(p, req, 0);
20224
20225 if (c) {
20226
20227 ast_channel_lock(c);
20228 }
20229 }
20230 } else {
20231 if (sipdebug) {
20232 if (!req->ignore)
20233 ast_debug(2, "Got a SIP re-invite for call %s\n", p->callid);
20234 else
20235 ast_debug(2, "Got a SIP re-transmit of INVITE for call %s\n", p->callid);
20236 }
20237 if (!req->ignore)
20238 reinvite = 1;
20239 c = p->owner;
20240 }
20241
20242
20243 if (p->sipoptions & SIP_OPT_TIMER) {
20244
20245
20246 ast_debug(2, "Incoming INVITE with 'timer' option enabled\n");
20247
20248
20249 if (!p->stimer)
20250 sip_st_alloc(p);
20251
20252
20253 p_uac_se_hdr = get_header(req, "Session-Expires");
20254 if (!ast_strlen_zero(p_uac_se_hdr)) {
20255 rtn = parse_session_expires(p_uac_se_hdr, &uac_max_se, &st_ref);
20256 if (rtn != 0) {
20257 transmit_response_reliable(p, "400 Session-Expires Invalid Syntax", req);
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 }
20266
20267
20268 p_uac_min_se = get_header(req, "Min-SE");
20269 if (!ast_strlen_zero(p_uac_min_se)) {
20270 rtn = parse_minse(p_uac_min_se, &uac_min_se);
20271 if (rtn != 0) {
20272 transmit_response_reliable(p, "400 Min-SE Invalid Syntax", req);
20273 p->invitestate = INV_COMPLETED;
20274 if (!p->lastinvite) {
20275 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20276 }
20277 res = -1;
20278 goto request_invite_cleanup;
20279 }
20280 }
20281
20282 dlg_min_se = st_get_se(p, FALSE);
20283 switch (st_get_mode(p)) {
20284 case SESSION_TIMER_MODE_ACCEPT:
20285 case SESSION_TIMER_MODE_ORIGINATE:
20286 if (uac_max_se > 0 && uac_max_se < dlg_min_se) {
20287 transmit_response_with_minse(p, "422 Session Interval Too Small", req, dlg_min_se);
20288 p->invitestate = INV_COMPLETED;
20289 if (!p->lastinvite) {
20290 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20291 }
20292 res = -1;
20293 goto request_invite_cleanup;
20294 }
20295
20296 p->stimer->st_active_peer_ua = TRUE;
20297 st_active = TRUE;
20298 if (st_ref == SESSION_TIMER_REFRESHER_AUTO) {
20299 st_ref = st_get_refresher(p);
20300 }
20301
20302 if (uac_max_se > 0) {
20303 int dlg_max_se = st_get_se(p, TRUE);
20304 if (dlg_max_se >= uac_min_se) {
20305 st_interval = (uac_max_se < dlg_max_se) ? uac_max_se : dlg_max_se;
20306 } else {
20307 st_interval = uac_max_se;
20308 }
20309 } else {
20310
20311 st_interval = global_max_se;
20312 }
20313 break;
20314
20315 case SESSION_TIMER_MODE_REFUSE:
20316 if (p->reqsipoptions & SIP_OPT_TIMER) {
20317 transmit_response_with_unsupported(p, "420 Option Disabled", req, required);
20318 ast_log(LOG_WARNING, "Received SIP INVITE with supported but disabled option: %s\n", required);
20319 p->invitestate = INV_COMPLETED;
20320 if (!p->lastinvite) {
20321 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20322 }
20323 res = -1;
20324 goto request_invite_cleanup;
20325 }
20326 break;
20327
20328 default:
20329 ast_log(LOG_ERROR, "Internal Error %d at %s:%d\n", st_get_mode(p), __FILE__, __LINE__);
20330 break;
20331 }
20332 } else {
20333
20334
20335
20336 switch (st_get_mode(p)) {
20337 case SESSION_TIMER_MODE_ORIGINATE:
20338 st_active = TRUE;
20339 st_interval = st_get_se(p, TRUE);
20340 st_ref = SESSION_TIMER_REFRESHER_UAS;
20341 p->stimer->st_active_peer_ua = FALSE;
20342 break;
20343
20344 default:
20345 break;
20346 }
20347 }
20348
20349 if (reinvite == 0) {
20350
20351 if (st_active == TRUE) {
20352 p->stimer->st_active = TRUE;
20353 p->stimer->st_interval = st_interval;
20354 p->stimer->st_ref = st_ref;
20355 start_session_timer(p);
20356 }
20357 } else {
20358 if (p->stimer->st_active == TRUE) {
20359
20360
20361
20362 ast_debug (2, "Restarting session-timers on a refresh - %s\n", p->callid);
20363
20364
20365 if (st_interval > 0) {
20366 p->stimer->st_interval = st_interval;
20367 p->stimer->st_ref = st_ref;
20368 }
20369
20370 restart_session_timer(p);
20371 if (p->stimer->st_expirys > 0) {
20372 p->stimer->st_expirys--;
20373 }
20374 }
20375 }
20376
20377 if (!req->ignore && p)
20378 p->lastinvite = seqno;
20379
20380 if (replace_id) {
20381 if (!ast_strlen_zero(pickup.exten)) {
20382 append_history(p, "Xfer", "INVITE/Replace received");
20383
20384
20385 transmit_response(p, "100 Trying", req);
20386 p->invitestate = INV_PROCEEDING;
20387 ast_setstate(c, AST_STATE_RING);
20388
20389
20390 ast_channel_unlock(c);
20391 *nounlock = 1;
20392 do_magic_pickup(c, pickup.exten, pickup.context);
20393
20394
20395 sip_pvt_unlock(p);
20396 ast_hangup(c);
20397 sip_pvt_lock(p);
20398
20399 res = 0;
20400 goto request_invite_cleanup;
20401 } else {
20402
20403 if (sipdebug)
20404 ast_debug(4, "Sending this call to the invite/replcaes handler %s\n", p->callid);
20405 res = handle_invite_replaces(p, req, debug, seqno, sin, nounlock);
20406 refer_locked = 0;
20407 goto request_invite_cleanup;
20408 }
20409 }
20410
20411
20412 if (c) {
20413 enum ast_channel_state c_state = c->_state;
20414
20415 if (c_state != AST_STATE_UP && reinvite &&
20416 (p->invitestate == INV_TERMINATED || p->invitestate == INV_CONFIRMED)) {
20417
20418
20419
20420
20421
20422
20423
20424
20425
20426 c_state = AST_STATE_UP;
20427 }
20428
20429 switch(c_state) {
20430 case AST_STATE_DOWN:
20431 ast_debug(2, "%s: New call is still down.... Trying... \n", c->name);
20432 transmit_provisional_response(p, "100 Trying", req, 0);
20433 p->invitestate = INV_PROCEEDING;
20434 ast_setstate(c, AST_STATE_RING);
20435 if (strcmp(p->exten, ast_pickup_ext())) {
20436 enum ast_pbx_result result;
20437
20438 result = ast_pbx_start(c);
20439
20440 switch(result) {
20441 case AST_PBX_FAILED:
20442 ast_log(LOG_WARNING, "Failed to start PBX :(\n");
20443 p->invitestate = INV_COMPLETED;
20444 transmit_response_reliable(p, "503 Unavailable", req);
20445 break;
20446 case AST_PBX_CALL_LIMIT:
20447 ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
20448 p->invitestate = INV_COMPLETED;
20449 transmit_response_reliable(p, "480 Temporarily Unavailable", req);
20450 break;
20451 case AST_PBX_SUCCESS:
20452
20453 break;
20454 }
20455
20456 if (result) {
20457
20458
20459 ast_channel_unlock(c);
20460 sip_pvt_unlock(p);
20461 ast_hangup(c);
20462 sip_pvt_lock(p);
20463 c = NULL;
20464 }
20465 } else {
20466 ast_channel_unlock(c);
20467 *nounlock = 1;
20468 if (ast_pickup_call(c)) {
20469 ast_log(LOG_NOTICE, "Nothing to pick up for %s\n", p->callid);
20470 transmit_response_reliable(p, "503 Unavailable", req);
20471 sip_alreadygone(p);
20472
20473 sip_pvt_unlock(p);
20474 c->hangupcause = AST_CAUSE_CALL_REJECTED;
20475 } else {
20476 sip_pvt_unlock(p);
20477 ast_setstate(c, AST_STATE_DOWN);
20478 c->hangupcause = AST_CAUSE_NORMAL_CLEARING;
20479 }
20480 p->invitestate = INV_COMPLETED;
20481 ast_hangup(c);
20482 sip_pvt_lock(p);
20483 c = NULL;
20484 }
20485 break;
20486 case AST_STATE_RING:
20487 transmit_provisional_response(p, "100 Trying", req, 0);
20488 p->invitestate = INV_PROCEEDING;
20489 break;
20490 case AST_STATE_RINGING:
20491 transmit_provisional_response(p, "180 Ringing", req, 0);
20492 p->invitestate = INV_PROCEEDING;
20493 break;
20494 case AST_STATE_UP:
20495 ast_debug(2, "%s: This call is UP.... \n", c->name);
20496
20497 transmit_response(p, "100 Trying", req);
20498
20499 if (p->t38.state == T38_PEER_REINVITE) {
20500 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."));
20501 } else if (p->t38.state == T38_ENABLED) {
20502 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
20503 transmit_response_with_t38_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL)));
20504 } else if (p->t38.state == T38_DISABLED) {
20505
20506 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
20507 transmit_response_with_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL)), p->session_modify == TRUE ? FALSE:TRUE);
20508 }
20509
20510 p->invitestate = INV_TERMINATED;
20511 break;
20512 default:
20513 ast_log(LOG_WARNING, "Don't know how to handle INVITE in state %d\n", c->_state);
20514 transmit_response(p, "100 Trying", req);
20515 break;
20516 }
20517 } else {
20518 if (p && (p->autokillid == -1)) {
20519 const char *msg;
20520
20521 if (!p->jointcapability)
20522 msg = "488 Not Acceptable Here (codec error)";
20523 else {
20524 ast_log(LOG_NOTICE, "Unable to create/find SIP channel for this INVITE\n");
20525 msg = "503 Unavailable";
20526 }
20527 transmit_response_reliable(p, msg, req);
20528 p->invitestate = INV_COMPLETED;
20529 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20530 }
20531 }
20532
20533 request_invite_cleanup:
20534
20535 if (refer_locked && p->refer && p->refer->refer_call) {
20536 sip_pvt_unlock(p->refer->refer_call);
20537 if (p->refer->refer_call->owner) {
20538 ast_channel_unlock(p->refer->refer_call->owner);
20539 }
20540 }
20541
20542 return res;
20543 }
20544
20545
20546
20547 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno)
20548 {
20549 struct sip_dual target;
20550
20551 int res = 0;
20552 struct sip_pvt *targetcall_pvt;
20553
20554
20555 if (!(targetcall_pvt = get_sip_pvt_byid_locked(transferer->refer->replaces_callid, transferer->refer->replaces_callid_totag,
20556 transferer->refer->replaces_callid_fromtag))) {
20557 if (transferer->refer->localtransfer) {
20558
20559 transmit_response(transferer, "202 Accepted", req);
20560
20561
20562 transmit_notify_with_sipfrag(transferer, seqno, "481 Call leg/transaction does not exist", TRUE);
20563 append_history(transferer, "Xfer", "Refer failed");
20564 ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
20565 transferer->refer->status = REFER_FAILED;
20566 return -1;
20567 }
20568
20569 ast_debug(3, "SIP attended transfer: Not our call - generating INVITE with replaces\n");
20570 return 0;
20571 }
20572
20573
20574 transmit_response(transferer, "202 Accepted", req);
20575 append_history(transferer, "Xfer", "Refer accepted");
20576 if (!targetcall_pvt->owner) {
20577 ast_debug(4, "SIP attended transfer: Error: No owner of target call\n");
20578
20579 transmit_notify_with_sipfrag(transferer, seqno, "503 Service Unavailable", TRUE);
20580 append_history(transferer, "Xfer", "Refer failed");
20581 ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
20582 transferer->refer->status = REFER_FAILED;
20583 sip_pvt_unlock(targetcall_pvt);
20584 if (targetcall_pvt)
20585 ao2_t_ref(targetcall_pvt, -1, "Drop targetcall_pvt pointer");
20586 return -1;
20587 }
20588
20589
20590 target.chan1 = targetcall_pvt->owner;
20591 target.chan2 = ast_bridged_channel(targetcall_pvt->owner);
20592
20593 if (!target.chan2 || !(target.chan2->_state == AST_STATE_UP || target.chan2->_state == AST_STATE_RINGING) ) {
20594
20595 if (target.chan2)
20596 ast_debug(4, "SIP attended transfer: Error: Wrong state of target call: %s\n", ast_state2str(target.chan2->_state));
20597 else if (target.chan1->_state != AST_STATE_RING)
20598 ast_debug(4, "SIP attended transfer: Error: No target channel\n");
20599 else
20600 ast_debug(4, "SIP attended transfer: Attempting transfer in ringing state\n");
20601 }
20602
20603
20604 if (sipdebug) {
20605 if (current->chan2)
20606 ast_debug(4, "SIP attended transfer: trying to bridge %s and %s\n", target.chan1->name, current->chan2->name);
20607 else
20608 ast_debug(4, "SIP attended transfer: trying to make %s take over (masq) %s\n", target.chan1->name, current->chan1->name);
20609 }
20610
20611 ast_set_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
20612
20613
20614 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",
20615 transferer->owner->name,
20616 transferer->owner->uniqueid,
20617 transferer->callid,
20618 target.chan1->name,
20619 target.chan1->uniqueid);
20620 res = attempt_transfer(current, &target);
20621 sip_pvt_unlock(targetcall_pvt);
20622 if (res) {
20623
20624 transmit_notify_with_sipfrag(transferer, seqno, "486 Busy Here", TRUE);
20625 append_history(transferer, "Xfer", "Refer failed");
20626 if (targetcall_pvt->owner)
20627 ast_channel_unlock(targetcall_pvt->owner);
20628 ast_clear_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
20629 } else {
20630
20631 const char *xfersound = pbx_builtin_getvar_helper(target.chan1, "ATTENDED_TRANSFER_COMPLETE_SOUND");
20632
20633
20634 transmit_notify_with_sipfrag(transferer, seqno, "200 OK", TRUE);
20635 append_history(transferer, "Xfer", "Refer succeeded");
20636 transferer->refer->status = REFER_200OK;
20637 if (target.chan2 && !ast_strlen_zero(xfersound) && ast_streamfile(target.chan2, xfersound, target.chan2->language) >= 0) {
20638 ast_waitstream(target.chan2, "");
20639 }
20640 if (targetcall_pvt->owner) {
20641 ast_debug(1, "SIP attended transfer: Unlocking channel %s\n", targetcall_pvt->owner->name);
20642 ast_channel_unlock(targetcall_pvt->owner);
20643 }
20644 }
20645 if (targetcall_pvt)
20646 ao2_t_ref(targetcall_pvt, -1, "drop targetcall_pvt");
20647 return 1;
20648 }
20649
20650
20651
20652
20653
20654
20655
20656
20657
20658
20659
20660
20661
20662
20663
20664
20665
20666
20667
20668
20669
20670
20671
20672
20673
20674
20675
20676
20677
20678
20679
20680
20681
20682
20683
20684
20685
20686
20687
20688
20689
20690
20691
20692
20693
20694
20695
20696
20697
20698
20699
20700
20701
20702
20703
20704
20705
20706
20707
20708
20709
20710
20711
20712
20713
20714 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock)
20715 {
20716 struct sip_dual current;
20717
20718
20719 int res = 0;
20720 current.req.data = NULL;
20721
20722 if (req->debug)
20723 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");
20724
20725 if (!p->owner) {
20726
20727
20728 ast_debug(3, "Call %s: Declined REFER, outside of dialog...\n", p->callid);
20729 transmit_response(p, "603 Declined (No dialog)", req);
20730 if (!req->ignore) {
20731 append_history(p, "Xfer", "Refer failed. Outside of dialog.");
20732 sip_alreadygone(p);
20733 pvt_set_needdestroy(p, "outside of dialog");
20734 }
20735 return 0;
20736 }
20737
20738
20739
20740 if (p->allowtransfer == TRANSFER_CLOSED ) {
20741
20742 transmit_response(p, "603 Declined (policy)", req);
20743 append_history(p, "Xfer", "Refer failed. Allowtransfer == closed.");
20744
20745 return 0;
20746 }
20747
20748 if (!req->ignore && ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
20749
20750 transmit_response(p, "491 Request pending", req);
20751 append_history(p, "Xfer", "Refer failed. Request pending.");
20752 return 0;
20753 }
20754
20755
20756 if (!p->refer && !sip_refer_allocate(p)) {
20757 transmit_response(p, "500 Internal Server Error", req);
20758 append_history(p, "Xfer", "Refer failed. Memory allocation error.");
20759 return -3;
20760 }
20761
20762 res = get_refer_info(p, req);
20763
20764 p->refer->status = REFER_SENT;
20765
20766 if (res != 0) {
20767 switch (res) {
20768 case -2:
20769 transmit_response(p, "400 Bad Request (Refer-to missing)", req);
20770 append_history(p, "Xfer", "Refer failed. Refer-to missing.");
20771 if (req->debug)
20772 ast_debug(1, "SIP transfer to black hole can't be handled (no refer-to: )\n");
20773 break;
20774 case -3:
20775 transmit_response(p, "603 Declined (Non sip: uri)", req);
20776 append_history(p, "Xfer", "Refer failed. Non SIP uri");
20777 if (req->debug)
20778 ast_debug(1, "SIP transfer to non-SIP uri denied\n");
20779 break;
20780 default:
20781
20782 transmit_response(p, "202 Accepted", req);
20783 append_history(p, "Xfer", "Refer failed. Bad extension.");
20784 transmit_notify_with_sipfrag(p, seqno, "404 Not found", TRUE);
20785 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
20786 if (req->debug)
20787 ast_debug(1, "SIP transfer to bad extension: %s\n", p->refer->refer_to);
20788 break;
20789 }
20790 return 0;
20791 }
20792 if (ast_strlen_zero(p->context))
20793 ast_string_field_set(p, context, sip_cfg.default_context);
20794
20795
20796 if (sip_cfg.allow_external_domains && check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
20797 p->refer->localtransfer = 1;
20798 if (sipdebug)
20799 ast_debug(3, "This SIP transfer is local : %s\n", p->refer->refer_to_domain);
20800 } else if (AST_LIST_EMPTY(&domain_list) || check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
20801
20802 p->refer->localtransfer = 1;
20803 } else if (sipdebug)
20804 ast_debug(3, "This SIP transfer is to a remote SIP extension (remote domain %s)\n", p->refer->refer_to_domain);
20805
20806
20807
20808 if (req->ignore)
20809 return res;
20810
20811
20812
20813
20814
20815
20816
20817
20818
20819
20820
20821
20822
20823
20824
20825
20826
20827
20828
20829
20830
20831
20832
20833
20834
20835
20836
20837 current.chan1 = p->owner;
20838
20839
20840 current.chan2 = ast_bridged_channel(current.chan1);
20841
20842 if (sipdebug)
20843 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>");
20844
20845 if (!current.chan2 && !p->refer->attendedtransfer) {
20846
20847
20848
20849 if (sipdebug)
20850 ast_debug(3, "Refused SIP transfer on non-bridged channel.\n");
20851 p->refer->status = REFER_FAILED;
20852 append_history(p, "Xfer", "Refer failed. Non-bridged channel.");
20853 transmit_response(p, "603 Declined", req);
20854 return -1;
20855 }
20856
20857 if (current.chan2) {
20858 if (sipdebug)
20859 ast_debug(4, "Got SIP transfer, applying to bridged peer '%s'\n", current.chan2->name);
20860
20861 ast_queue_control(current.chan1, AST_CONTROL_UNHOLD);
20862 }
20863
20864 ast_set_flag(&p->flags[0], SIP_GOTREFER);
20865
20866
20867 if (p->refer->attendedtransfer) {
20868 if ((res = local_attended_transfer(p, ¤t, req, seqno)))
20869 return res;
20870
20871 if (sipdebug)
20872 ast_debug(4, "SIP attended transfer: Still not our call - generating INVITE with replaces\n");
20873
20874 }
20875
20876
20877
20878 if (p->refer->localtransfer && !strcmp(p->refer->refer_to, ast_parking_ext())) {
20879
20880 *nounlock = 1;
20881 ast_channel_unlock(current.chan1);
20882 copy_request(¤t.req, req);
20883 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
20884 p->refer->status = REFER_200OK;
20885 append_history(p, "Xfer", "REFER to call parking.");
20886 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",
20887 current.chan1->name,
20888 current.chan1->uniqueid,
20889 p->callid,
20890 current.chan2->name,
20891 current.chan2->uniqueid,
20892 p->refer->refer_to);
20893 if (sipdebug)
20894 ast_debug(4, "SIP transfer to parking: trying to park %s. Parked by %s\n", current.chan2->name, current.chan1->name);
20895 sip_park(current.chan2, current.chan1, req, seqno);
20896 return res;
20897 }
20898
20899
20900 transmit_response(p, "202 Accepted", req);
20901
20902 if (current.chan1 && current.chan2) {
20903 ast_debug(3, "chan1->name: %s\n", current.chan1->name);
20904 pbx_builtin_setvar_helper(current.chan1, "BLINDTRANSFER", current.chan2->name);
20905 }
20906 if (current.chan2) {
20907 pbx_builtin_setvar_helper(current.chan2, "BLINDTRANSFER", current.chan1->name);
20908 pbx_builtin_setvar_helper(current.chan2, "SIPDOMAIN", p->refer->refer_to_domain);
20909 pbx_builtin_setvar_helper(current.chan2, "SIPTRANSFER", "yes");
20910
20911 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER", "yes");
20912
20913 if (p->refer->referred_by)
20914 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REFERER", p->refer->referred_by);
20915 }
20916
20917 if (!ast_strlen_zero(p->refer->replaces_callid)) {
20918 char tempheader[SIPBUFSIZE];
20919 snprintf(tempheader, sizeof(tempheader), "%s%s%s%s%s", p->refer->replaces_callid,
20920 p->refer->replaces_callid_totag ? ";to-tag=" : "",
20921 p->refer->replaces_callid_totag,
20922 p->refer->replaces_callid_fromtag ? ";from-tag=" : "",
20923 p->refer->replaces_callid_fromtag);
20924 if (current.chan2)
20925 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REPLACES", tempheader);
20926 }
20927
20928
20929 *nounlock = 1;
20930 ast_channel_unlock(current.chan1);
20931
20932
20933
20934
20935 if (!p->refer->attendedtransfer)
20936 transmit_notify_with_sipfrag(p, seqno, "183 Ringing", FALSE);
20937
20938
20939
20940
20941
20942 if (!current.chan2) {
20943
20944
20945
20946
20947
20948
20949
20950 p->refer->status = REFER_FAILED;
20951 transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable (can't handle one-legged xfers)", TRUE);
20952 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
20953 append_history(p, "Xfer", "Refer failed (only bridged calls).");
20954 return -1;
20955 }
20956 ast_set_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
20957
20958
20959
20960
20961 res = ast_async_goto(current.chan2, p->refer->refer_to_context, p->refer->refer_to, 1);
20962
20963 if (!res) {
20964 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",
20965 current.chan1->name,
20966 current.chan1->uniqueid,
20967 p->callid,
20968 current.chan2->name,
20969 current.chan2->uniqueid,
20970 p->refer->refer_to, p->refer->refer_to_context);
20971
20972 ast_debug(3, "%s transfer succeeded. Telling transferer.\n", p->refer->attendedtransfer? "Attended" : "Blind");
20973 transmit_notify_with_sipfrag(p, seqno, "200 Ok", TRUE);
20974 if (p->refer->localtransfer)
20975 p->refer->status = REFER_200OK;
20976 if (p->owner)
20977 p->owner->hangupcause = AST_CAUSE_NORMAL_CLEARING;
20978 append_history(p, "Xfer", "Refer succeeded.");
20979 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
20980
20981
20982 res = 0;
20983 } else {
20984 ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
20985 ast_debug(3, "%s transfer failed. Resuming original call.\n", p->refer->attendedtransfer? "Attended" : "Blind");
20986 append_history(p, "Xfer", "Refer failed.");
20987
20988 p->refer->status = REFER_FAILED;
20989 transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable", TRUE);
20990 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
20991 res = -1;
20992 }
20993 return res;
20994 }
20995
20996
20997 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req)
20998 {
20999
21000 check_via(p, req);
21001 sip_alreadygone(p);
21002
21003
21004
21005
21006
21007
21008 if (p->invitestate == INV_TERMINATED)
21009 __sip_pretend_ack(p);
21010 else
21011 p->invitestate = INV_CANCELLED;
21012
21013 if (p->owner && p->owner->_state == AST_STATE_UP) {
21014
21015 transmit_response(p, "200 OK", req);
21016 ast_debug(1, "Got CANCEL on an answered call. Ignoring... \n");
21017 return 0;
21018 }
21019
21020 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD))
21021 update_call_counter(p, DEC_CALL_LIMIT);
21022
21023 stop_media_flows(p);
21024 if (p->owner)
21025 ast_queue_hangup(p->owner);
21026 else
21027 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21028 if (p->initreq.len > 0) {
21029 struct sip_pkt *pkt, *prev_pkt;
21030
21031
21032
21033
21034
21035
21036
21037
21038
21039
21040
21041 for (pkt = p->packets, prev_pkt = NULL; pkt; prev_pkt = pkt, pkt = pkt->next) {
21042 if (pkt->seqno == p->lastinvite && pkt->response_code == 487) {
21043 AST_SCHED_DEL(sched, pkt->retransid);
21044 UNLINK(pkt, p->packets, prev_pkt);
21045 ast_free(pkt);
21046 break;
21047 }
21048 }
21049 transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
21050 transmit_response(p, "200 OK", req);
21051 return 1;
21052 } else {
21053 transmit_response(p, "481 Call Leg Does Not Exist", req);
21054 return 0;
21055 }
21056 }
21057
21058 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen)
21059 {
21060 struct sip_pvt *p = chan->tech_pvt;
21061 char *all = "", *parse = ast_strdupa(preparse);
21062 int res = 0;
21063 AST_DECLARE_APP_ARGS(args,
21064 AST_APP_ARG(param);
21065 AST_APP_ARG(type);
21066 AST_APP_ARG(field);
21067 );
21068 AST_STANDARD_APP_ARGS(args, parse);
21069
21070
21071 if (!IS_SIP_TECH(chan->tech)) {
21072 ast_log(LOG_ERROR, "Cannot call %s on a non-SIP channel\n", funcname);
21073 return 0;
21074 }
21075
21076 memset(buf, 0, buflen);
21077
21078 if (p == NULL) {
21079 return -1;
21080 }
21081
21082 if (!strcasecmp(args.param, "peerip")) {
21083 ast_copy_string(buf, p->sa.sin_addr.s_addr ? ast_inet_ntoa(p->sa.sin_addr) : "", buflen);
21084 } else if (!strcasecmp(args.param, "recvip")) {
21085 ast_copy_string(buf, p->recv.sin_addr.s_addr ? ast_inet_ntoa(p->recv.sin_addr) : "", buflen);
21086 } else if (!strcasecmp(args.param, "from")) {
21087 ast_copy_string(buf, p->from, buflen);
21088 } else if (!strcasecmp(args.param, "uri")) {
21089 ast_copy_string(buf, p->uri, buflen);
21090 } else if (!strcasecmp(args.param, "useragent")) {
21091 ast_copy_string(buf, p->useragent, buflen);
21092 } else if (!strcasecmp(args.param, "peername")) {
21093 ast_copy_string(buf, p->peername, buflen);
21094 } else if (!strcasecmp(args.param, "t38passthrough")) {
21095 ast_copy_string(buf, (p->t38.state == T38_DISABLED) ? "0" : "1", buflen);
21096 } else if (!strcasecmp(args.param, "rtpdest")) {
21097 struct sockaddr_in sin;
21098 struct ast_rtp *stream = NULL;
21099
21100 if (ast_strlen_zero(args.type))
21101 args.type = "audio";
21102
21103 if (!strcasecmp(args.type, "audio")) {
21104 stream = p->rtp;
21105 } else if (!strcasecmp(args.type, "video")) {
21106 stream = p->vrtp;
21107 } else if (!strcasecmp(args.type, "text")) {
21108 stream = p->trtp;
21109 } else {
21110 return -1;
21111 }
21112
21113 if (!stream) {
21114 return -1;
21115 }
21116
21117 ast_rtp_get_peer(stream, &sin);
21118 snprintf(buf, buflen, "%s:%d", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
21119 } else if (!strcasecmp(args.param, "rtpqos")) {
21120 struct ast_rtp_quality qos;
21121 struct ast_rtp *rtp = p->rtp;
21122
21123 memset(&qos, 0, sizeof(qos));
21124
21125 if (ast_strlen_zero(args.type))
21126 args.type = "audio";
21127 if (ast_strlen_zero(args.field))
21128 args.field = "all";
21129
21130 if (!strcasecmp(args.type, "AUDIO")) {
21131 all = ast_rtp_get_quality(rtp = p->rtp, &qos, RTPQOS_SUMMARY);
21132 } else if (!strcasecmp(args.type, "VIDEO")) {
21133 all = ast_rtp_get_quality(rtp = p->vrtp, &qos, RTPQOS_SUMMARY);
21134 } else if (!strcasecmp(args.type, "TEXT")) {
21135 all = ast_rtp_get_quality(rtp = p->trtp, &qos, RTPQOS_SUMMARY);
21136 } else {
21137 return -1;
21138 }
21139
21140 if (!strcasecmp(args.field, "local_ssrc"))
21141 snprintf(buf, buflen, "%u", qos.local_ssrc);
21142 else if (!strcasecmp(args.field, "local_lostpackets"))
21143 snprintf(buf, buflen, "%u", qos.local_lostpackets);
21144 else if (!strcasecmp(args.field, "local_jitter"))
21145 snprintf(buf, buflen, "%.0f", qos.local_jitter * 1000.0);
21146 else if (!strcasecmp(args.field, "local_count"))
21147 snprintf(buf, buflen, "%u", qos.local_count);
21148 else if (!strcasecmp(args.field, "remote_ssrc"))
21149 snprintf(buf, buflen, "%u", qos.remote_ssrc);
21150 else if (!strcasecmp(args.field, "remote_lostpackets"))
21151 snprintf(buf, buflen, "%u", qos.remote_lostpackets);
21152 else if (!strcasecmp(args.field, "remote_jitter"))
21153 snprintf(buf, buflen, "%.0f", qos.remote_jitter * 1000.0);
21154 else if (!strcasecmp(args.field, "remote_count"))
21155 snprintf(buf, buflen, "%u", qos.remote_count);
21156 else if (!strcasecmp(args.field, "rtt"))
21157 snprintf(buf, buflen, "%.0f", qos.rtt * 1000.0);
21158 else if (!strcasecmp(args.field, "all"))
21159 ast_copy_string(buf, all, buflen);
21160 else if (!ast_rtp_get_qos(rtp, args.field, buf, buflen))
21161 ;
21162 else {
21163 ast_log(LOG_WARNING, "Unrecognized argument '%s' to %s\n", preparse, funcname);
21164 return -1;
21165 }
21166 } else {
21167 res = -1;
21168 }
21169 return res;
21170 }
21171
21172
21173 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req)
21174 {
21175 struct ast_channel *c=NULL;
21176 int res;
21177 struct ast_channel *bridged_to;
21178
21179
21180 if (p->pendinginvite && !ast_test_flag(&p->flags[0], SIP_OUTGOING) && !req->ignore) {
21181 transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
21182 }
21183
21184 __sip_pretend_ack(p);
21185
21186 p->invitestate = INV_TERMINATED;
21187
21188 copy_request(&p->initreq, req);
21189 if (sipdebug)
21190 ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
21191 check_via(p, req);
21192 sip_alreadygone(p);
21193
21194
21195 if (p->do_history || p->owner) {
21196 struct ast_channel *bridge = p->owner ? ast_bridged_channel(p->owner) : NULL;
21197 char *videoqos, *textqos;
21198
21199
21200
21201
21202 while (bridge && ast_channel_trylock(bridge)) {
21203 ast_channel_unlock(p->owner);
21204 do {
21205
21206 sip_pvt_unlock(p);
21207 usleep(1);
21208 sip_pvt_lock(p);
21209 } while (p->owner && ast_channel_trylock(p->owner));
21210 bridge = p->owner ? ast_bridged_channel(p->owner) : NULL;
21211 }
21212
21213 if (p->rtp) {
21214 if (p->do_history) {
21215 char *audioqos,
21216 *audioqos_jitter,
21217 *audioqos_loss,
21218 *audioqos_rtt;
21219
21220 audioqos = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_SUMMARY);
21221 audioqos_jitter = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_JITTER);
21222 audioqos_loss = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_LOSS);
21223 audioqos_rtt = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_RTT);
21224
21225 append_history(p, "RTCPaudio", "Quality:%s", audioqos);
21226 append_history(p, "RTCPaudioJitter", "Quality:%s", audioqos_jitter);
21227 append_history(p, "RTCPaudioLoss", "Quality:%s", audioqos_loss);
21228 append_history(p, "RTCPaudioRTT", "Quality:%s", audioqos_rtt);
21229 }
21230
21231 if (p->owner) {
21232 ast_rtp_set_vars(p->owner, p->rtp);
21233 }
21234 }
21235
21236 if (bridge) {
21237 struct sip_pvt *q = bridge->tech_pvt;
21238
21239 if (IS_SIP_TECH(bridge->tech) && q && q->rtp)
21240 ast_rtp_set_vars(bridge, q->rtp);
21241 ast_channel_unlock(bridge);
21242 }
21243
21244 if (p->vrtp) {
21245 videoqos = ast_rtp_get_quality(p->vrtp, NULL, RTPQOS_SUMMARY);
21246 if (p->do_history)
21247 append_history(p, "RTCPvideo", "Quality:%s", videoqos);
21248 if (p->owner)
21249 pbx_builtin_setvar_helper(p->owner, "RTPVIDEOQOS", videoqos);
21250 }
21251
21252 if (p->trtp) {
21253 textqos = ast_rtp_get_quality(p->trtp, NULL, RTPQOS_SUMMARY);
21254 if (p->do_history)
21255 append_history(p, "RTCPtext", "Quality:%s", textqos);
21256 if (p->owner)
21257 pbx_builtin_setvar_helper(p->owner, "RTPTEXTQOS", textqos);
21258 }
21259 }
21260
21261 stop_media_flows(p);
21262 stop_session_timer(p);
21263
21264 if (!ast_strlen_zero(get_header(req, "Also"))) {
21265 ast_log(LOG_NOTICE, "Client '%s' using deprecated BYE/Also transfer method. Ask vendor to support REFER instead\n",
21266 ast_inet_ntoa(p->recv.sin_addr));
21267 if (ast_strlen_zero(p->context))
21268 ast_string_field_set(p, context, sip_cfg.default_context);
21269 res = get_also_info(p, req);
21270 if (!res) {
21271 c = p->owner;
21272 if (c) {
21273 bridged_to = ast_bridged_channel(c);
21274 if (bridged_to) {
21275
21276 ast_queue_control(c, AST_CONTROL_UNHOLD);
21277 ast_async_goto(bridged_to, p->context, p->refer->refer_to, 1);
21278 } else
21279 ast_queue_hangup(p->owner);
21280 }
21281 } else {
21282 ast_log(LOG_WARNING, "Invalid transfer information from '%s'\n", ast_inet_ntoa(p->recv.sin_addr));
21283 if (p->owner)
21284 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
21285 }
21286 } else if (p->owner) {
21287 ast_queue_hangup(p->owner);
21288 ast_debug(3, "Received bye, issuing owner hangup\n");
21289 } else {
21290 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21291 ast_debug(3, "Received bye, no owner, selfdestruct soon.\n");
21292 }
21293 ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
21294 transmit_response(p, "200 OK", req);
21295
21296 return 1;
21297 }
21298
21299
21300 static int handle_request_message(struct sip_pvt *p, struct sip_request *req)
21301 {
21302 if (!req->ignore) {
21303 if (req->debug)
21304 ast_verbose("Receiving message!\n");
21305 receive_message(p, req);
21306 } else
21307 transmit_response(p, "202 Accepted", req);
21308 return 1;
21309 }
21310
21311 static void add_peer_mwi_subs(struct sip_peer *peer)
21312 {
21313 struct sip_mailbox *mailbox;
21314
21315 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
21316 mailbox->event_sub = ast_event_subscribe(AST_EVENT_MWI, mwi_event_cb, peer,
21317 AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox->mailbox,
21318 AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, S_OR(mailbox->context, "default"),
21319 AST_EVENT_IE_END);
21320 }
21321 }
21322
21323
21324 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e)
21325 {
21326 int gotdest = 0;
21327 int res = 0;
21328 int firststate = AST_EXTENSION_REMOVED;
21329 struct sip_peer *authpeer = NULL;
21330 const char *eventheader = get_header(req, "Event");
21331 const char *acceptheader = get_header(req, "Accept");
21332 int resubscribe = (p->subscribed != NONE);
21333 char *temp, *event;
21334 struct ao2_iterator i;
21335
21336 if (p->initreq.headers) {
21337
21338 if (p->initreq.method != SIP_SUBSCRIBE) {
21339
21340
21341 transmit_response(p, "403 Forbidden (within dialog)", req);
21342
21343 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);
21344 return 0;
21345 } else if (req->debug) {
21346 if (resubscribe)
21347 ast_debug(1, "Got a re-subscribe on existing subscription %s\n", p->callid);
21348 else
21349 ast_debug(1, "Got a new subscription %s (possibly with auth)\n", p->callid);
21350 }
21351 }
21352
21353
21354
21355
21356 if (!sip_cfg.allowsubscribe) {
21357 transmit_response(p, "403 Forbidden (policy)", req);
21358 pvt_set_needdestroy(p, "forbidden");
21359 return 0;
21360 }
21361
21362 if (!req->ignore && !resubscribe) {
21363 const char *to = get_header(req, "To");
21364 char totag[128];
21365
21366
21367 if (!ast_strlen_zero(to) && gettag(req, "To", totag, sizeof(totag))) {
21368 if (req->debug)
21369 ast_verbose("Received resubscription for a dialog we no longer know about. Telling remote side to subscribe again.\n");
21370 transmit_response(p, "481 Subscription does not exist", req);
21371 pvt_set_needdestroy(p, "subscription does not exist");
21372 return 0;
21373 }
21374
21375
21376 if (req->debug)
21377 ast_verbose("Creating new subscription\n");
21378
21379 copy_request(&p->initreq, req);
21380 if (sipdebug)
21381 ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
21382 check_via(p, req);
21383 build_route(p, req, 0);
21384 } else if (req->debug && req->ignore)
21385 ast_verbose("Ignoring this SUBSCRIBE request\n");
21386
21387
21388 if (ast_strlen_zero(eventheader)) {
21389 transmit_response(p, "489 Bad Event", req);
21390 ast_debug(2, "Received SIP subscribe for unknown event package: <none>\n");
21391 pvt_set_needdestroy(p, "unknown event package in subscribe");
21392 return 0;
21393 }
21394
21395 if ( (strchr(eventheader, ';'))) {
21396 event = ast_strdupa(eventheader);
21397 temp = strchr(event, ';');
21398 *temp = '\0';
21399
21400 } else
21401 event = (char *) eventheader;
21402
21403
21404 res = check_user_full(p, req, SIP_SUBSCRIBE, e, 0, sin, &authpeer);
21405
21406 if (res == AUTH_CHALLENGE_SENT)
21407 return 0;
21408 if (res < 0) {
21409 if (res == AUTH_FAKE_AUTH) {
21410 ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", get_header(req, "From"));
21411 transmit_fake_auth_response(p, SIP_SUBSCRIBE, req, XMIT_UNRELIABLE);
21412 } else {
21413 ast_log(LOG_NOTICE, "Failed to authenticate device %s for SUBSCRIBE\n", get_header(req, "From"));
21414 transmit_response_reliable(p, "403 Forbidden", req);
21415 }
21416 pvt_set_needdestroy(p, "authentication failed");
21417 return 0;
21418 }
21419
21420
21421
21422
21423
21424
21425
21426 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
21427 transmit_response(p, "403 Forbidden (policy)", req);
21428 pvt_set_needdestroy(p, "subscription not allowed");
21429 if (authpeer)
21430 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 1)");
21431 return 0;
21432 }
21433
21434 if (strcmp(event, "message-summary")) {
21435
21436 gotdest = get_destination(p, NULL);
21437 }
21438
21439
21440 parse_ok_contact(p, req);
21441
21442 build_contact(p);
21443 if (gotdest) {
21444 transmit_response(p, "404 Not Found", req);
21445 pvt_set_needdestroy(p, "subscription target not found");
21446 if (authpeer)
21447 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
21448 return 0;
21449 }
21450
21451
21452 if (ast_strlen_zero(p->tag))
21453 make_our_tag(p->tag, sizeof(p->tag));
21454
21455 if (!strcmp(event, "presence") || !strcmp(event, "dialog")) {
21456 unsigned int pidf_xml;
21457
21458 if (authpeer)
21459 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
21460
21461
21462
21463 pidf_xml = strstr(acceptheader, "application/pidf+xml") ? 1 : 0;
21464
21465
21466
21467 if (pidf_xml && strstr(p->useragent, "Polycom")) {
21468 p->subscribed = XPIDF_XML;
21469 } else if (pidf_xml) {
21470 p->subscribed = PIDF_XML;
21471 } else if (strstr(acceptheader, "application/dialog-info+xml")) {
21472 p->subscribed = DIALOG_INFO_XML;
21473
21474 } else if (strstr(acceptheader, "application/cpim-pidf+xml")) {
21475 p->subscribed = CPIM_PIDF_XML;
21476 } else if (strstr(acceptheader, "application/xpidf+xml")) {
21477 p->subscribed = XPIDF_XML;
21478 } else if (ast_strlen_zero(acceptheader)) {
21479 if (p->subscribed == NONE) {
21480 transmit_response(p, "489 Bad Event", req);
21481
21482 ast_log(LOG_WARNING, "SUBSCRIBE failure: no Accept header: pvt: stateid: %d, laststate: %d, dialogver: %d, subscribecont: '%s', subscribeuri: '%s'\n",
21483 p->stateid, p->laststate, p->dialogver, p->subscribecontext, p->subscribeuri);
21484 pvt_set_needdestroy(p, "no Accept header");
21485 return 0;
21486 }
21487
21488
21489 } else {
21490
21491 char mybuf[200];
21492 snprintf(mybuf, sizeof(mybuf), "489 Bad Event (format %s)", acceptheader);
21493 transmit_response(p, mybuf, req);
21494
21495 ast_log(LOG_WARNING, "SUBSCRIBE failure: unrecognized format: '%s' pvt: subscribed: %d, stateid: %d, laststate: %d, dialogver: %d, subscribecont: '%s', subscribeuri: '%s'\n",
21496 acceptheader, (int)p->subscribed, p->stateid, p->laststate, p->dialogver, p->subscribecontext, p->subscribeuri);
21497 pvt_set_needdestroy(p, "unrecognized format");
21498 return 0;
21499 }
21500 } else if (!strcmp(event, "message-summary")) {
21501 if (!ast_strlen_zero(acceptheader) && strcmp(acceptheader, "application/simple-message-summary")) {
21502
21503 transmit_response(p, "406 Not Acceptable", req);
21504 ast_debug(2, "Received SIP mailbox subscription for unknown format: %s\n", acceptheader);
21505 pvt_set_needdestroy(p, "unknown format");
21506 if (authpeer)
21507 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 3)");
21508 return 0;
21509 }
21510
21511
21512
21513
21514
21515 if (!authpeer || AST_LIST_EMPTY(&authpeer->mailboxes)) {
21516 transmit_response(p, "404 Not found (no mailbox)", req);
21517 pvt_set_needdestroy(p, "received 404 response");
21518 ast_log(LOG_NOTICE, "Received SIP subscribe for peer without mailbox: %s\n", authpeer->name);
21519 if (authpeer)
21520 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 4)");
21521 return 0;
21522 }
21523
21524 p->subscribed = MWI_NOTIFICATION;
21525 if (ast_test_flag(&authpeer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY)) {
21526 add_peer_mwi_subs(authpeer);
21527 }
21528 if (authpeer->mwipvt && authpeer->mwipvt != p) {
21529
21530 dialog_unlink_all(authpeer->mwipvt, TRUE, TRUE);
21531 authpeer->mwipvt = dialog_unref(authpeer->mwipvt, "unref dialog authpeer->mwipvt");
21532
21533 }
21534 if (authpeer->mwipvt)
21535 dialog_unref(authpeer->mwipvt, "Unref previously stored mwipvt dialog pointer");
21536 authpeer->mwipvt = dialog_ref(p, "setting peers' mwipvt to p");
21537 if (p->relatedpeer)
21538 unref_peer(p->relatedpeer, "Unref previously stored relatedpeer ptr");
21539 p->relatedpeer = ref_peer(authpeer, "setting dialog's relatedpeer pointer");
21540
21541 } else {
21542 transmit_response(p, "489 Bad Event", req);
21543 ast_debug(2, "Received SIP subscribe for unknown event package: %s\n", event);
21544 pvt_set_needdestroy(p, "unknown event package");
21545 if (authpeer)
21546 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 5)");
21547 return 0;
21548 }
21549
21550
21551 if (p->subscribed != MWI_NOTIFICATION && !resubscribe) {
21552 if (p->stateid > -1) {
21553 ast_extension_state_del(p->stateid, cb_extensionstate);
21554
21555 dialog_unref(p, "the extensionstate containing this dialog ptr was deleted");
21556 }
21557 p->stateid = ast_extension_state_add(p->context, p->exten, cb_extensionstate, dialog_ref(p,"copying dialog ptr into extension state struct"));
21558 }
21559
21560 if (!req->ignore && p)
21561 p->lastinvite = seqno;
21562 if (p && !p->needdestroy) {
21563 p->expiry = atoi(get_header(req, "Expires"));
21564
21565
21566 if (p->expiry > max_expiry)
21567 p->expiry = max_expiry;
21568 if (p->expiry < min_expiry && p->expiry > 0)
21569 p->expiry = min_expiry;
21570
21571 if (sipdebug) {
21572 if (p->subscribed == MWI_NOTIFICATION && p->relatedpeer)
21573 ast_debug(2, "Adding subscription for mailbox notification - peer %s\n", p->relatedpeer->name);
21574 else
21575 ast_debug(2, "Adding subscription for extension %s context %s for peer %s\n", p->exten, p->context, p->username);
21576 }
21577 if (p->autokillid > -1 && sip_cancel_destroy(p))
21578 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
21579 if (p->expiry > 0)
21580 sip_scheddestroy(p, (p->expiry + 10) * 1000);
21581
21582 if (p->subscribed == MWI_NOTIFICATION) {
21583 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
21584 transmit_response(p, "200 OK", req);
21585 if (p->relatedpeer) {
21586 ao2_lock(p->relatedpeer);
21587 sip_send_mwi_to_peer(p->relatedpeer, NULL, 0);
21588 ao2_unlock(p->relatedpeer);
21589 }
21590 } else {
21591 struct sip_pvt *p_old;
21592
21593 if ((firststate = ast_extension_state(NULL, p->context, p->exten)) < 0) {
21594
21595 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));
21596 transmit_response(p, "404 Not found", req);
21597 pvt_set_needdestroy(p, "no extension for SUBSCRIBE");
21598 return 0;
21599 }
21600 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
21601 transmit_response(p, "200 OK", req);
21602 transmit_state_notify(p, firststate, 1, FALSE);
21603 append_history(p, "Subscribestatus", "%s", ast_extension_state2str(firststate));
21604
21605 ast_string_field_build(p, subscribeuri, "%s@%s", p->exten, p->context);
21606
21607
21608
21609
21610
21611
21612 i = ao2_iterator_init(dialogs, 0);
21613 while ((p_old = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
21614 if (p_old == p) {
21615 ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next before continue");
21616 continue;
21617 }
21618 if (p_old->initreq.method != SIP_SUBSCRIBE) {
21619 ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next before continue");
21620 continue;
21621 }
21622 if (p_old->subscribed == NONE) {
21623 ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next before continue");
21624 continue;
21625 }
21626 sip_pvt_lock(p_old);
21627 if (!strcmp(p_old->username, p->username)) {
21628 if (!strcmp(p_old->exten, p->exten) &&
21629 !strcmp(p_old->context, p->context)) {
21630 pvt_set_needdestroy(p_old, "replacing subscription");
21631 sip_pvt_unlock(p_old);
21632 ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next before break");
21633 break;
21634 }
21635 }
21636 sip_pvt_unlock(p_old);
21637 ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next");
21638 }
21639 ao2_iterator_destroy(&i);
21640 }
21641 if (!p->expiry) {
21642 pvt_set_needdestroy(p, "forcing expiration");
21643 }
21644 }
21645 return 1;
21646 }
21647
21648
21649 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e)
21650 {
21651 enum check_auth_result res;
21652
21653
21654 copy_request(&p->initreq, req);
21655 if (sipdebug)
21656 ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
21657 check_via(p, req);
21658 if ((res = register_verify(p, sin, req, e)) < 0) {
21659 const char *reason;
21660
21661 switch (res) {
21662 case AUTH_SECRET_FAILED:
21663 reason = "Wrong password";
21664 break;
21665 case AUTH_USERNAME_MISMATCH:
21666 reason = "Username/auth name mismatch";
21667 break;
21668 case AUTH_NOT_FOUND:
21669 reason = "No matching peer found";
21670 break;
21671 case AUTH_UNKNOWN_DOMAIN:
21672 reason = "Not a local domain";
21673 break;
21674 case AUTH_PEER_NOT_DYNAMIC:
21675 reason = "Peer is not supposed to register";
21676 break;
21677 case AUTH_ACL_FAILED:
21678 reason = "Device does not match ACL";
21679 break;
21680 case AUTH_BAD_TRANSPORT:
21681 reason = "Device not configured to use this transport type";
21682 break;
21683 default:
21684 reason = "Unknown failure";
21685 break;
21686 }
21687 ast_log(LOG_NOTICE, "Registration from '%s' failed for '%s' - %s\n",
21688 get_header(req, "To"), ast_inet_ntoa(sin->sin_addr),
21689 reason);
21690 append_history(p, "RegRequest", "Failed : Account %s : %s", get_header(req, "To"), reason);
21691 } else
21692 append_history(p, "RegRequest", "Succeeded : Account %s", get_header(req, "To"));
21693
21694 if (res < 1) {
21695
21696
21697 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21698 }
21699 return res;
21700 }
21701
21702
21703
21704
21705 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock)
21706 {
21707
21708
21709 const char *cmd;
21710 const char *cseq;
21711 const char *useragent;
21712 int seqno;
21713 int len;
21714 int respid;
21715 int res = 0;
21716 int debug = sip_debug_test_pvt(p);
21717 char *e;
21718 int error = 0;
21719 int oldmethod = p->method;
21720 int acked = 0;
21721
21722
21723 cseq = get_header(req, "Cseq");
21724 cmd = REQ_OFFSET_TO_STR(req, header[0]);
21725
21726
21727 if (ast_strlen_zero(cmd) || ast_strlen_zero(cseq)) {
21728 ast_log(LOG_ERROR, "Missing Cseq. Dropping this SIP message, it's incomplete.\n");
21729 error = 1;
21730 }
21731 if (!error && sscanf(cseq, "%30d%n", &seqno, &len) != 1) {
21732 ast_log(LOG_ERROR, "No seqno in '%s'. Dropping incomplete message.\n", cmd);
21733 error = 1;
21734 }
21735 if (error) {
21736 if (!p->initreq.headers) {
21737 pvt_set_needdestroy(p, "no headers");
21738 }
21739 return -1;
21740 }
21741
21742
21743 cmd = REQ_OFFSET_TO_STR(req, rlPart1);
21744 e = ast_skip_blanks(REQ_OFFSET_TO_STR(req, rlPart2));
21745
21746
21747 useragent = get_header(req, "User-Agent");
21748 if (!ast_strlen_zero(useragent))
21749 ast_string_field_set(p, useragent, useragent);
21750
21751
21752 if (req->method == SIP_RESPONSE) {
21753
21754
21755
21756
21757
21758
21759 if (ast_strlen_zero(e)) {
21760 return 0;
21761 }
21762 if (sscanf(e, "%30d %n", &respid, &len) != 1) {
21763 ast_log(LOG_WARNING, "Invalid response: '%s'\n", e);
21764 return 0;
21765 }
21766 if (respid <= 0) {
21767 ast_log(LOG_WARNING, "Invalid SIP response code: '%d'\n", respid);
21768 return 0;
21769 }
21770 if (p->ocseq && (p->ocseq < seqno)) {
21771 if (option_debug)
21772 ast_log(LOG_DEBUG, "Ignoring out of order response %d (expecting %d)\n", seqno, p->ocseq);
21773 return -1;
21774 } else {
21775 if ((respid == 200) || ((respid >= 300) && (respid <= 399))) {
21776 extract_uri(p, req);
21777 }
21778 handle_response(p, respid, e + len, req, seqno);
21779 }
21780 return 0;
21781 }
21782
21783
21784
21785
21786
21787 p->method = req->method;
21788 ast_debug(4, "**** Received %s (%d) - Command in SIP %s\n", sip_methods[p->method].text, sip_methods[p->method].id, cmd);
21789
21790 if (p->icseq && (p->icseq > seqno) ) {
21791 if (p->pendinginvite && seqno == p->pendinginvite && (req->method == SIP_ACK || req->method == SIP_CANCEL)) {
21792 ast_debug(2, "Got CANCEL or ACK on INVITE with transactions in between.\n");
21793 } else {
21794 ast_debug(1, "Ignoring too old SIP packet packet %d (expecting >= %d)\n", seqno, p->icseq);
21795 if (req->method != SIP_ACK)
21796 transmit_response(p, "503 Server error", req);
21797 return -1;
21798 }
21799 } else if (p->icseq &&
21800 p->icseq == seqno &&
21801 req->method != SIP_ACK &&
21802 (p->method != SIP_CANCEL || p->alreadygone)) {
21803
21804
21805
21806 req->ignore = 1;
21807 ast_debug(3, "Ignoring SIP message because of retransmit (%s Seqno %d, ours %d)\n", sip_methods[p->method].text, p->icseq, seqno);
21808 }
21809
21810 if (seqno >= p->icseq)
21811
21812
21813
21814 p->icseq = seqno;
21815
21816
21817 if (ast_strlen_zero(p->theirtag)) {
21818 char tag[128];
21819
21820 gettag(req, "From", tag, sizeof(tag));
21821 ast_string_field_set(p, theirtag, tag);
21822 }
21823 snprintf(p->lastmsg, sizeof(p->lastmsg), "Rx: %s", cmd);
21824
21825 if (sip_cfg.pedanticsipchecking) {
21826
21827
21828
21829
21830 if (!p->initreq.headers && req->has_to_tag) {
21831
21832 if (!req->ignore && req->method == SIP_INVITE) {
21833 transmit_response_reliable(p, "481 Call/Transaction Does Not Exist", req);
21834
21835 } else if (req->method != SIP_ACK) {
21836 transmit_response(p, "481 Call/Transaction Does Not Exist", req);
21837 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21838 } else {
21839 ast_debug(1, "Got ACK for unknown dialog... strange.\n");
21840 }
21841 return res;
21842 }
21843 }
21844
21845 if (!e && (p->method == SIP_INVITE || p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER || p->method == SIP_NOTIFY)) {
21846 transmit_response(p, "400 Bad request", req);
21847 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21848 return -1;
21849 }
21850
21851
21852 switch (p->method) {
21853 case SIP_OPTIONS:
21854 res = handle_request_options(p, req);
21855 break;
21856 case SIP_INVITE:
21857 res = handle_request_invite(p, req, debug, seqno, sin, recount, e, nounlock);
21858 break;
21859 case SIP_REFER:
21860 res = handle_request_refer(p, req, debug, seqno, nounlock);
21861 break;
21862 case SIP_CANCEL:
21863 res = handle_request_cancel(p, req);
21864 break;
21865 case SIP_BYE:
21866 res = handle_request_bye(p, req);
21867 break;
21868 case SIP_MESSAGE:
21869 res = handle_request_message(p, req);
21870 break;
21871 case SIP_SUBSCRIBE:
21872 res = handle_request_subscribe(p, req, sin, seqno, e);
21873 break;
21874 case SIP_REGISTER:
21875 res = handle_request_register(p, req, sin, e);
21876 break;
21877 case SIP_INFO:
21878 if (req->debug)
21879 ast_verbose("Receiving INFO!\n");
21880 if (!req->ignore)
21881 handle_request_info(p, req);
21882 else
21883 transmit_response(p, "200 OK", req);
21884 break;
21885 case SIP_NOTIFY:
21886 res = handle_request_notify(p, req, sin, seqno, e);
21887 break;
21888 case SIP_ACK:
21889
21890 if (seqno == p->pendinginvite) {
21891 p->invitestate = INV_TERMINATED;
21892 p->pendinginvite = 0;
21893 acked = __sip_ack(p, seqno, 1 , 0);
21894 if (find_sdp(req)) {
21895 if (process_sdp(p, req, SDP_T38_NONE))
21896 return -1;
21897 }
21898 check_pendings(p);
21899 } else if (p->glareinvite == seqno) {
21900
21901 p->glareinvite = 0;
21902 acked = __sip_ack(p, seqno, 1, 0);
21903 }
21904 if (!acked) {
21905
21906
21907 p->method = oldmethod;
21908 }
21909 if (!p->lastinvite && ast_strlen_zero(p->randdata)) {
21910 pvt_set_needdestroy(p, "unmatched ACK");
21911 }
21912 break;
21913 default:
21914 transmit_response_with_allow(p, "501 Method Not Implemented", req, 0);
21915 ast_log(LOG_NOTICE, "Unknown SIP command '%s' from '%s'\n",
21916 cmd, ast_inet_ntoa(p->sa.sin_addr));
21917
21918 if (!p->initreq.headers) {
21919 pvt_set_needdestroy(p, "unimplemented method");
21920 }
21921 break;
21922 }
21923 return res;
21924 }
21925
21926 static void process_request_queue(struct sip_pvt *p, int *recount, int *nounlock)
21927 {
21928 struct sip_request *req;
21929
21930 while ((req = AST_LIST_REMOVE_HEAD(&p->request_queue, next))) {
21931 if (handle_incoming(p, req, &p->recv, recount, nounlock) == -1) {
21932
21933 if (option_debug) {
21934 ast_log(LOG_DEBUG, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
21935 }
21936 }
21937 ast_free(req);
21938 }
21939 }
21940
21941 static int scheduler_process_request_queue(const void *data)
21942 {
21943 struct sip_pvt *p = (struct sip_pvt *) data;
21944 int recount = 0;
21945 int nounlock = 0;
21946 int lockretry;
21947
21948 for (lockretry = 10; lockretry > 0; lockretry--) {
21949 sip_pvt_lock(p);
21950
21951
21952
21953 if (!p->owner || !ast_channel_trylock(p->owner)) {
21954 break;
21955 }
21956
21957 if (lockretry != 1) {
21958 sip_pvt_unlock(p);
21959
21960 usleep(1);
21961 }
21962 }
21963
21964 if (!lockretry) {
21965 int retry = !AST_LIST_EMPTY(&p->request_queue);
21966
21967
21968
21969
21970
21971
21972 sip_pvt_unlock(p);
21973 if (!retry) {
21974 dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
21975 }
21976 return retry;
21977 };
21978
21979 process_request_queue(p, &recount, &nounlock);
21980 p->request_queue_sched_id = -1;
21981
21982 if (p->owner && !nounlock) {
21983 ast_channel_unlock(p->owner);
21984 }
21985 sip_pvt_unlock(p);
21986
21987 if (recount) {
21988 ast_update_use_count();
21989 }
21990
21991 dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
21992
21993 return 0;
21994 }
21995
21996 static int queue_request(struct sip_pvt *p, const struct sip_request *req)
21997 {
21998 struct sip_request *newreq;
21999
22000 if (!(newreq = ast_calloc(1, sizeof(*newreq)))) {
22001 return -1;
22002 }
22003
22004 copy_request(newreq, req);
22005 AST_LIST_INSERT_TAIL(&p->request_queue, newreq, next);
22006 if (p->request_queue_sched_id == -1) {
22007 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) {
22008 dialog_unref(p, "Decrement refcount due to sched_add failure");
22009 }
22010 }
22011
22012 return 0;
22013 }
22014
22015
22016
22017
22018
22019
22020 static int sipsock_read(int *id, int fd, short events, void *ignore)
22021 {
22022 struct sip_request req;
22023 struct sockaddr_in sin = { 0, };
22024 int res;
22025 socklen_t len = sizeof(sin);
22026 static char readbuf[65535];
22027
22028 memset(&req, 0, sizeof(req));
22029 res = recvfrom(fd, readbuf, sizeof(readbuf) - 1, 0, (struct sockaddr *)&sin, &len);
22030 if (res < 0) {
22031 #if !defined(__FreeBSD__)
22032 if (errno == EAGAIN)
22033 ast_log(LOG_NOTICE, "SIP: Received packet with bad UDP checksum\n");
22034 else
22035 #endif
22036 if (errno != ECONNREFUSED)
22037 ast_log(LOG_WARNING, "Recv error: %s\n", strerror(errno));
22038 return 1;
22039 }
22040
22041 readbuf[res] = '\0';
22042
22043 if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
22044 return 1;
22045 }
22046
22047 if (ast_str_set(&req.data, 0, "%s", readbuf) == AST_DYNSTR_BUILD_FAILED) {
22048 return -1;
22049 }
22050
22051 req.len = res;
22052 req.socket.fd = sipsock;
22053 set_socket_transport(&req.socket, SIP_TRANSPORT_UDP);
22054 req.socket.tcptls_session = NULL;
22055 req.socket.port = bindaddr.sin_port;
22056
22057 handle_request_do(&req, &sin);
22058 deinit_req(&req);
22059
22060 return 1;
22061 }
22062
22063
22064
22065
22066
22067 static int handle_request_do(struct sip_request *req, struct sockaddr_in *sin)
22068 {
22069 struct sip_pvt *p;
22070 int recount = 0;
22071 int nounlock = 0;
22072 int lockretry;
22073
22074 if (sip_debug_test_addr(sin))
22075 req->debug = 1;
22076 if (sip_cfg.pedanticsipchecking)
22077 req->len = lws2sws(req->data->str, req->len);
22078 if (req->debug) {
22079 ast_verbose("\n<--- SIP read from %s:%s:%d --->\n%s\n<------------->\n",
22080 get_transport(req->socket.type), ast_inet_ntoa(sin->sin_addr),
22081 ntohs(sin->sin_port), req->data->str);
22082 }
22083
22084 if (parse_request(req) == -1) {
22085 ast_str_reset(req->data);
22086 return 1;
22087 }
22088 req->method = find_sip_method(REQ_OFFSET_TO_STR(req, rlPart1));
22089
22090 if (req->debug)
22091 ast_verbose("--- (%d headers %d lines)%s ---\n", req->headers, req->lines, (req->headers + req->lines == 0) ? " Nat keepalive" : "");
22092
22093 if (req->headers < 2) {
22094 ast_str_reset(req->data);
22095 return 1;
22096 }
22097
22098
22099 for (lockretry = 10; lockretry > 0; lockretry--) {
22100 ast_mutex_lock(&netlock);
22101
22102
22103 p = find_call(req, sin, req->method);
22104 if (p == NULL) {
22105 ast_debug(1, "Invalid SIP message - rejected , no callid, len %d\n", req->len);
22106 ast_mutex_unlock(&netlock);
22107 return 1;
22108 }
22109
22110 copy_socket_data(&p->socket, &req->socket);
22111
22112
22113
22114 if (!p->owner || !ast_channel_trylock(p->owner))
22115 break;
22116
22117 if (lockretry != 1) {
22118 sip_pvt_unlock(p);
22119 ao2_t_ref(p, -1, "release p (from find_call) inside lockretry loop");
22120 ast_mutex_unlock(&netlock);
22121
22122 usleep(1);
22123 }
22124 }
22125 p->recv = *sin;
22126
22127 if (p->do_history)
22128 append_history(p, "Rx", "%s / %s / %s", req->data->str, get_header(req, "CSeq"), REQ_OFFSET_TO_STR(req, rlPart2));
22129
22130 if (!lockretry) {
22131 if (!queue_request(p, req)) {
22132
22133 sip_pvt_unlock(p);
22134 ao2_t_ref(p, -1, "release p (from find_call) after queueing request");
22135 ast_mutex_unlock(&netlock);
22136 return 1;
22137 }
22138
22139 if (p->owner)
22140 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 ??? - "));
22141 ast_log(LOG_ERROR, "SIP transaction failed: %s \n", p->callid);
22142 if (req->method != SIP_ACK)
22143 transmit_response(p, "503 Server error", req);
22144
22145 append_history(p, "LockFail", "Owner lock failed, transaction failed.");
22146 sip_pvt_unlock(p);
22147 ao2_t_ref(p, -1, "release p (from find_call) at end of lockretry");
22148 ast_mutex_unlock(&netlock);
22149 return 1;
22150 }
22151
22152
22153
22154
22155 if (!AST_LIST_EMPTY(&p->request_queue)) {
22156 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"));
22157 process_request_queue(p, &recount, &nounlock);
22158 }
22159
22160 if (handle_incoming(p, req, sin, &recount, &nounlock) == -1) {
22161
22162 ast_debug(1, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
22163 }
22164
22165 if (recount)
22166 ast_update_use_count();
22167
22168 if (p->owner && !nounlock)
22169 ast_channel_unlock(p->owner);
22170 sip_pvt_unlock(p);
22171 ast_mutex_unlock(&netlock);
22172 ao2_t_ref(p, -1, "throw away dialog ptr from find_call at end of routine");
22173 return 1;
22174 }
22175
22176
22177
22178
22179
22180
22181
22182 static int sip_standard_port(enum sip_transport type, int port)
22183 {
22184 if (type & SIP_TRANSPORT_TLS)
22185 return port == STANDARD_TLS_PORT;
22186 else
22187 return port == STANDARD_SIP_PORT;
22188 }
22189
22190 static int threadinfo_locate_cb(void *obj, void *arg, int flags)
22191 {
22192 struct sip_threadinfo *th = obj;
22193 struct sockaddr_in *s = arg;
22194
22195 if (!inaddrcmp(&th->tcptls_session->remote_address, s)) {
22196 return CMP_MATCH | CMP_STOP;
22197 }
22198
22199 return 0;
22200 }
22201
22202
22203
22204
22205
22206
22207 static struct ast_tcptls_session_instance *sip_tcp_locate(struct sockaddr_in *s)
22208 {
22209 struct sip_threadinfo *th;
22210 struct ast_tcptls_session_instance *tcptls_instance = NULL;
22211
22212 if ((th = ao2_callback(threadt, 0, threadinfo_locate_cb, s))) {
22213 tcptls_instance = (ao2_ref(th->tcptls_session, +1), th->tcptls_session);
22214 ao2_t_ref(th, -1, "decrement ref from callback");
22215 }
22216 return tcptls_instance;
22217 }
22218
22219
22220 static int sip_prepare_socket(struct sip_pvt *p)
22221 {
22222 struct sip_socket *s = &p->socket;
22223 static const char name[] = "SIP socket";
22224 struct sip_threadinfo *th = NULL;
22225 struct ast_tcptls_session_instance *tcptls_session;
22226 struct ast_tcptls_session_args tmp_ca = {
22227 .name = name,
22228 .accept_fd = -1,
22229 };
22230 struct ast_tcptls_session_args *ca;
22231
22232
22233 if ((s->fd != -1) && (s->type == SIP_TRANSPORT_UDP)) {
22234 return s->fd;
22235 }
22236 if ((s->type & (SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS)) &&
22237 (s->tcptls_session) &&
22238 (s->tcptls_session->fd != -1)) {
22239 return s->tcptls_session->fd;
22240 }
22241
22242
22243
22244
22245 if (p->outboundproxy && p->outboundproxy->transport) {
22246 s->type = p->outboundproxy->transport;
22247 }
22248
22249 if (s->type == SIP_TRANSPORT_UDP) {
22250 s->fd = sipsock;
22251 return s->fd;
22252 }
22253
22254
22255
22256
22257
22258
22259
22260
22261
22262
22263
22264 tmp_ca.remote_address = *(sip_real_dst(p));
22265 if ((tcptls_session = sip_tcp_locate(&tmp_ca.remote_address))) {
22266 s->fd = tcptls_session->fd;
22267 if (s->tcptls_session) {
22268 ao2_ref(s->tcptls_session, -1);
22269 s->tcptls_session = NULL;
22270 }
22271 s->tcptls_session = tcptls_session;
22272 return s->fd;
22273
22274 } else if (s->tcptls_session) {
22275 return s->fd;
22276 }
22277
22278
22279
22280 if (!(ca = ao2_alloc(sizeof(*ca), sip_tcptls_client_args_destructor)) ||
22281 !(ca->name = ast_strdup(name))) {
22282 goto create_tcptls_session_fail;
22283 }
22284 ca->accept_fd = -1;
22285 ca->remote_address = *(sip_real_dst(p));
22286
22287 if (s->type == SIP_TRANSPORT_TLS) {
22288 if (!(ca->tls_cfg = ast_calloc(1, sizeof(*ca->tls_cfg)))) {
22289 goto create_tcptls_session_fail;
22290 }
22291 memcpy(ca->tls_cfg, &default_tls_cfg, sizeof(*ca->tls_cfg));
22292
22293 if (!(ca->tls_cfg->certfile = ast_strdup(default_tls_cfg.certfile)) ||
22294 !(ca->tls_cfg->cipher = ast_strdup(default_tls_cfg.cipher)) ||
22295 !(ca->tls_cfg->cafile = ast_strdup(default_tls_cfg.cafile)) ||
22296 !(ca->tls_cfg->capath = ast_strdup(default_tls_cfg.capath))) {
22297
22298 goto create_tcptls_session_fail;
22299 }
22300
22301
22302 if (!ast_strlen_zero(p->tohost)) {
22303 ast_copy_string(ca->hostname, p->tohost, sizeof(ca->hostname));
22304 }
22305 }
22306
22307 if (!(s->tcptls_session = ast_tcptls_client_create(ca))) {
22308 goto create_tcptls_session_fail;
22309 }
22310
22311 s->fd = s->tcptls_session->fd;
22312
22313
22314
22315
22316
22317 if (!(th = sip_threadinfo_create(s->tcptls_session, s->type))) {
22318 goto create_tcptls_session_fail;
22319
22320 }
22321
22322
22323 ao2_ref(s->tcptls_session, +1);
22324
22325 if (ast_pthread_create_background(&ca->master, NULL, sip_tcp_worker_fn, s->tcptls_session)) {
22326 ast_debug(1, "Unable to launch '%s'.", ca->name);
22327 ao2_ref(s->tcptls_session, -1);
22328 goto create_tcptls_session_fail;
22329 }
22330
22331 return s->fd;
22332
22333 create_tcptls_session_fail:
22334 if (ca) {
22335 ao2_t_ref(ca, -1, "failed to create client, getting rid of client tcptls_session arguments");
22336 }
22337 if (s->tcptls_session) {
22338 close(tcptls_session->fd);
22339 s->fd = tcptls_session->fd = -1;
22340 ao2_ref(s->tcptls_session, -1);
22341 s->tcptls_session = NULL;
22342 }
22343 if (th) {
22344 ao2_t_unlink(threadt, th, "Removing tcptls thread info object, thread failed to open");
22345 }
22346
22347 return -1;
22348 }
22349
22350
22351
22352
22353
22354 static int sip_parse_host(char *line, int lineno, char **hostname, int *portnum, enum sip_transport *transport)
22355 {
22356 char *port;
22357
22358 if ((*hostname = strstr(line, "://"))) {
22359 *hostname += 3;
22360
22361 if (!strncasecmp(line, "tcp", 3))
22362 *transport = SIP_TRANSPORT_TCP;
22363 else if (!strncasecmp(line, "tls", 3))
22364 *transport = SIP_TRANSPORT_TLS;
22365 else if (!strncasecmp(line, "udp", 3))
22366 *transport = SIP_TRANSPORT_UDP;
22367 else
22368 ast_log(LOG_NOTICE, "'%.3s' is not a valid transport type on line %d of sip.conf. defaulting to udp.\n", line, lineno);
22369 } else {
22370 *hostname = line;
22371 *transport = SIP_TRANSPORT_UDP;
22372 }
22373
22374 if ((line = strrchr(*hostname, '@')))
22375 line++;
22376 else
22377 line = *hostname;
22378
22379 if ((port = strrchr(line, ':'))) {
22380 *port++ = '\0';
22381
22382 if (!sscanf(port, "%5u", portnum)) {
22383 ast_log(LOG_NOTICE, "'%s' is not a valid port number on line %d of sip.conf. using default.\n", port, lineno);
22384 port = NULL;
22385 }
22386 }
22387
22388 if (!port) {
22389 if (*transport & SIP_TRANSPORT_TLS) {
22390 *portnum = STANDARD_TLS_PORT;
22391 } else {
22392 *portnum = STANDARD_SIP_PORT;
22393 }
22394 }
22395
22396 return 0;
22397 }
22398
22399
22400
22401
22402
22403
22404 static int get_cached_mwi(struct sip_peer *peer, int *new, int *old)
22405 {
22406 struct sip_mailbox *mailbox;
22407
22408 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
22409 struct ast_event *event;
22410 event = ast_event_get_cached(AST_EVENT_MWI,
22411 AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox->mailbox,
22412 AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, S_OR(mailbox->context, "default"),
22413 AST_EVENT_IE_END);
22414 if (!event)
22415 continue;
22416 *new += ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
22417 *old += ast_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS);
22418 ast_event_destroy(event);
22419 }
22420
22421 return (*new || *old) ? 0 : 1;
22422 }
22423
22424
22425 static int sip_send_mwi_to_peer(struct sip_peer *peer, const struct ast_event *event, int cache_only)
22426 {
22427
22428 struct sip_pvt *p;
22429 int newmsgs = 0, oldmsgs = 0;
22430
22431 if (ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY) && !peer->mwipvt)
22432 return 0;
22433
22434
22435 if (!peer->addr.sin_addr.s_addr && !peer->defaddr.sin_addr.s_addr)
22436 return 0;
22437
22438 if (event) {
22439 newmsgs = ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
22440 oldmsgs = ast_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS);
22441 } else if (!cache_only) {
22442 struct ast_str *mailbox_str = ast_str_alloca(512);
22443 peer_mailboxes_to_str(&mailbox_str, peer);
22444 ast_app_inboxcount(mailbox_str->str, &newmsgs, &oldmsgs);
22445 } else {
22446 get_cached_mwi(peer, &newmsgs, &oldmsgs);
22447 }
22448
22449 if (peer->mwipvt) {
22450
22451 p = dialog_ref(peer->mwipvt, "sip_send_mwi_to_peer: Setting dialog ptr p from peer->mwipvt-- should this be done?");
22452 } else {
22453
22454 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL)))
22455 return -1;
22456
22457
22458
22459
22460 set_socket_transport(&p->socket, 0);
22461 if (create_addr_from_peer(p, peer)) {
22462
22463 dialog_unlink_all(p, TRUE, TRUE);
22464 dialog_unref(p, "unref dialog p just created via sip_alloc");
22465
22466 return 0;
22467 }
22468
22469 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
22470 build_via(p);
22471 ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
22472 build_callid_pvt(p);
22473 ao2_t_link(dialogs, p, "Linking in under new name");
22474
22475 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22476 }
22477
22478
22479 ast_set_flag(&p->flags[0], SIP_OUTGOING);
22480
22481 transmit_notify_with_mwi(p, newmsgs, oldmsgs, peer->vmexten);
22482 dialog_unref(p, "unref dialog ptr p just before it goes out of scope at the end of sip_send_mwi_to_peer.");
22483 return 0;
22484 }
22485
22486
22487 static void check_rtp_timeout(struct sip_pvt *dialog, time_t t)
22488 {
22489
22490 if (!dialog->rtp || !dialog->owner)
22491 return;
22492
22493
22494 if (dialog->owner->_state != AST_STATE_UP || dialog->redirip.sin_addr.s_addr)
22495 return;
22496
22497
22498 if (dialog->t38.state == T38_ENABLED)
22499 return;
22500
22501
22502 if ((ast_rtp_get_rtpkeepalive(dialog->rtp) == 0) && (ast_rtp_get_rtptimeout(dialog->rtp) == 0) && (ast_rtp_get_rtpholdtimeout(dialog->rtp) == 0))
22503 return;
22504
22505
22506 if (dialog->lastrtptx && ast_rtp_get_rtpkeepalive(dialog->rtp) &&
22507 (t > dialog->lastrtptx + ast_rtp_get_rtpkeepalive(dialog->rtp))) {
22508
22509 dialog->lastrtptx = time(NULL);
22510 ast_rtp_sendcng(dialog->rtp, 0);
22511 }
22512
22513
22514
22515
22516
22517
22518
22519
22520 if (dialog->lastrtprx && (ast_rtp_get_rtptimeout(dialog->rtp) || ast_rtp_get_rtpholdtimeout(dialog->rtp)) &&
22521 (t > dialog->lastrtprx + ast_rtp_get_rtptimeout(dialog->rtp))) {
22522
22523
22524 struct sockaddr_in sin;
22525 ast_rtp_get_peer(dialog->rtp, &sin);
22526 if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD) || (ast_rtp_get_rtpholdtimeout(dialog->rtp) &&
22527 (t > dialog->lastrtprx + ast_rtp_get_rtpholdtimeout(dialog->rtp)))) {
22528
22529 if (ast_rtp_get_rtptimeout(dialog->rtp)) {
22530 while (dialog->owner && ast_channel_trylock(dialog->owner)) {
22531 sip_pvt_unlock(dialog);
22532 usleep(1);
22533 sip_pvt_lock(dialog);
22534 }
22535 if (!dialog->owner) {
22536 return;
22537 }
22538 ast_log(LOG_NOTICE, "Disconnecting call '%s' for lack of RTP activity in %ld seconds\n",
22539 dialog->owner->name, (long) (t - dialog->lastrtprx));
22540
22541 ast_softhangup_nolock(dialog->owner, AST_SOFTHANGUP_DEV);
22542 ast_channel_unlock(dialog->owner);
22543
22544
22545
22546
22547 ast_rtp_set_rtptimeout(dialog->rtp, 0);
22548 ast_rtp_set_rtpholdtimeout(dialog->rtp, 0);
22549 if (dialog->vrtp) {
22550 ast_rtp_set_rtptimeout(dialog->vrtp, 0);
22551 ast_rtp_set_rtpholdtimeout(dialog->vrtp, 0);
22552 }
22553 }
22554 }
22555 }
22556 }
22557
22558
22559
22560
22561
22562 static void *do_monitor(void *data)
22563 {
22564 int res;
22565 time_t t;
22566 int reloading;
22567
22568
22569 if (sipsock > -1)
22570 sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
22571
22572
22573 for(;;) {
22574
22575 ast_mutex_lock(&sip_reload_lock);
22576 reloading = sip_reloading;
22577 sip_reloading = FALSE;
22578 ast_mutex_unlock(&sip_reload_lock);
22579 if (reloading) {
22580 ast_verb(1, "Reloading SIP\n");
22581 sip_do_reload(sip_reloadreason);
22582
22583
22584 if (sipsock > -1) {
22585 if (sipsock_read_id)
22586 sipsock_read_id = ast_io_change(io, sipsock_read_id, sipsock, NULL, 0, NULL);
22587 else
22588 sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
22589 } else if (sipsock_read_id) {
22590 ast_io_remove(io, sipsock_read_id);
22591 sipsock_read_id = NULL;
22592 }
22593 }
22594
22595
22596 t = time(NULL);
22597
22598
22599
22600
22601 ao2_t_callback(dialogs, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, dialog_needdestroy, &t,
22602 "callback to remove dialogs w/needdestroy");
22603
22604
22605
22606
22607
22608
22609
22610
22611
22612
22613
22614 pthread_testcancel();
22615
22616 res = ast_sched_wait(sched);
22617 if ((res < 0) || (res > 1000))
22618 res = 1000;
22619 res = ast_io_wait(io, res);
22620 if (res > 20)
22621 ast_debug(1, "chan_sip: ast_io_wait ran %d all at once\n", res);
22622 ast_mutex_lock(&monlock);
22623 res = ast_sched_runq(sched);
22624 if (res >= 20)
22625 ast_debug(1, "chan_sip: ast_sched_runq ran %d all at once\n", res);
22626 ast_mutex_unlock(&monlock);
22627 }
22628
22629
22630 return NULL;
22631 }
22632
22633
22634 static int restart_monitor(void)
22635 {
22636
22637 if (monitor_thread == AST_PTHREADT_STOP)
22638 return 0;
22639 ast_mutex_lock(&monlock);
22640 if (monitor_thread == pthread_self()) {
22641 ast_mutex_unlock(&monlock);
22642 ast_log(LOG_WARNING, "Cannot kill myself\n");
22643 return -1;
22644 }
22645 if (monitor_thread != AST_PTHREADT_NULL) {
22646
22647 pthread_kill(monitor_thread, SIGURG);
22648 } else {
22649
22650 if (ast_pthread_create_background(&monitor_thread, NULL, do_monitor, NULL) < 0) {
22651 ast_mutex_unlock(&monlock);
22652 ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
22653 return -1;
22654 }
22655 }
22656 ast_mutex_unlock(&monlock);
22657 return 0;
22658 }
22659
22660
22661
22662 static void restart_session_timer(struct sip_pvt *p)
22663 {
22664 if (!p->stimer) {
22665 ast_log(LOG_WARNING, "Null stimer in restart_session_timer - %s\n", p->callid);
22666 return;
22667 }
22668
22669 if (p->stimer->st_active == TRUE) {
22670 AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
22671 dialog_unref(p, "Removing session timer ref"));
22672 ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
22673 start_session_timer(p);
22674 }
22675 }
22676
22677
22678
22679 static void stop_session_timer(struct sip_pvt *p)
22680 {
22681 if (!p->stimer) {
22682 ast_log(LOG_WARNING, "Null stimer in stop_session_timer - %s\n", p->callid);
22683 return;
22684 }
22685
22686 if (p->stimer->st_active == TRUE) {
22687 p->stimer->st_active = FALSE;
22688 AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
22689 dialog_unref(p, "removing session timer ref"));
22690 ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
22691 }
22692 }
22693
22694
22695
22696 static void start_session_timer(struct sip_pvt *p)
22697 {
22698 if (!p->stimer) {
22699 ast_log(LOG_WARNING, "Null stimer in start_session_timer - %s\n", p->callid);
22700 return;
22701 }
22702
22703 p->stimer->st_schedid = ast_sched_add(sched, p->stimer->st_interval * 1000 / 2, proc_session_timer,
22704 dialog_ref(p, "adding session timer ref"));
22705 if (p->stimer->st_schedid < 0) {
22706 dialog_unref(p, "removing session timer ref");
22707 ast_log(LOG_ERROR, "ast_sched_add failed.\n");
22708 }
22709 ast_debug(2, "Session timer started: %d - %s\n", p->stimer->st_schedid, p->callid);
22710 }
22711
22712
22713
22714 static int proc_session_timer(const void *vp)
22715 {
22716 struct sip_pvt *p = (struct sip_pvt *) vp;
22717 int sendreinv = FALSE;
22718 int res = 0;
22719
22720 if (!p->stimer) {
22721 ast_log(LOG_WARNING, "Null stimer in proc_session_timer - %s\n", p->callid);
22722 goto return_unref;
22723 }
22724
22725 ast_debug(2, "Session timer expired: %d - %s\n", p->stimer->st_schedid, p->callid);
22726
22727 if (!p->owner) {
22728 goto return_unref;
22729 }
22730
22731 if ((p->stimer->st_active != TRUE) || (p->owner->_state != AST_STATE_UP)) {
22732 goto return_unref;
22733 }
22734
22735 switch (p->stimer->st_ref) {
22736 case SESSION_TIMER_REFRESHER_UAC:
22737 if (p->outgoing_call == TRUE) {
22738 sendreinv = TRUE;
22739 }
22740 break;
22741 case SESSION_TIMER_REFRESHER_UAS:
22742 if (p->outgoing_call != TRUE) {
22743 sendreinv = TRUE;
22744 }
22745 break;
22746 default:
22747 ast_log(LOG_ERROR, "Unknown session refresher %d\n", p->stimer->st_ref);
22748 goto return_unref;
22749 }
22750
22751 if (sendreinv == TRUE) {
22752 res = 1;
22753 transmit_reinvite_with_sdp(p, FALSE, TRUE);
22754 } else {
22755 p->stimer->st_expirys++;
22756 if (p->stimer->st_expirys >= 2) {
22757 if (p->stimer->quit_flag) {
22758 goto return_unref;
22759 }
22760 ast_log(LOG_WARNING, "Session-Timer expired - %s\n", p->callid);
22761 sip_pvt_lock(p);
22762 while (p->owner && ast_channel_trylock(p->owner)) {
22763 sip_pvt_unlock(p);
22764 usleep(1);
22765 if (p->stimer && p->stimer->quit_flag) {
22766 goto return_unref;
22767 }
22768 sip_pvt_lock(p);
22769 }
22770
22771 ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
22772 ast_channel_unlock(p->owner);
22773 sip_pvt_unlock(p);
22774 }
22775 }
22776
22777 return_unref:
22778 if (!res) {
22779
22780 if (p->stimer) {
22781 p->stimer->st_schedid = -1;
22782 stop_session_timer(p);
22783 }
22784
22785
22786
22787 dialog_unref(p, "removing session timer ref");
22788 }
22789
22790 return res;
22791 }
22792
22793
22794
22795 int parse_minse (const char *p_hdrval, int *const p_interval)
22796 {
22797 if (ast_strlen_zero(p_hdrval)) {
22798 ast_log(LOG_WARNING, "Null Min-SE header\n");
22799 return -1;
22800 }
22801
22802 *p_interval = 0;
22803 p_hdrval = ast_skip_blanks(p_hdrval);
22804 if (!sscanf(p_hdrval, "%30d", p_interval)) {
22805 ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
22806 return -1;
22807 }
22808
22809 ast_debug(2, "Received Min-SE: %d\n", *p_interval);
22810 return 0;
22811 }
22812
22813
22814
22815 int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref)
22816 {
22817 char *p_token;
22818 int ref_idx;
22819 char *p_se_hdr;
22820
22821 if (ast_strlen_zero(p_hdrval)) {
22822 ast_log(LOG_WARNING, "Null Session-Expires header\n");
22823 return -1;
22824 }
22825
22826 *p_ref = SESSION_TIMER_REFRESHER_AUTO;
22827 *p_interval = 0;
22828
22829 p_se_hdr = ast_strdupa(p_hdrval);
22830 p_se_hdr = ast_skip_blanks(p_se_hdr);
22831
22832 while ((p_token = strsep(&p_se_hdr, ";"))) {
22833 p_token = ast_skip_blanks(p_token);
22834 if (!sscanf(p_token, "%30d", p_interval)) {
22835 ast_log(LOG_WARNING, "Parsing of Session-Expires failed\n");
22836 return -1;
22837 }
22838
22839 ast_debug(2, "Session-Expires: %d\n", *p_interval);
22840
22841 if (!p_se_hdr)
22842 continue;
22843
22844 p_se_hdr = ast_skip_blanks(p_se_hdr);
22845 ref_idx = strlen("refresher=");
22846 if (!strncasecmp(p_se_hdr, "refresher=", ref_idx)) {
22847 p_se_hdr += ref_idx;
22848 p_se_hdr = ast_skip_blanks(p_se_hdr);
22849
22850 if (!strncasecmp(p_se_hdr, "uac", strlen("uac"))) {
22851 *p_ref = SESSION_TIMER_REFRESHER_UAC;
22852 ast_debug(2, "Refresher: UAC\n");
22853 } else if (!strncasecmp(p_se_hdr, "uas", strlen("uas"))) {
22854 *p_ref = SESSION_TIMER_REFRESHER_UAS;
22855 ast_debug(2, "Refresher: UAS\n");
22856 } else {
22857 ast_log(LOG_WARNING, "Invalid refresher value %s\n", p_se_hdr);
22858 return -1;
22859 }
22860 break;
22861 }
22862 }
22863 return 0;
22864 }
22865
22866
22867
22868
22869
22870
22871
22872
22873
22874 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp)
22875 {
22876 int rtn;
22877 const char *p_hdrval;
22878 int minse;
22879
22880 p_hdrval = get_header(rsp, "Min-SE");
22881 if (ast_strlen_zero(p_hdrval)) {
22882 ast_log(LOG_WARNING, "422 response without a Min-SE header %s\n", p_hdrval);
22883 return;
22884 }
22885 rtn = parse_minse(p_hdrval, &minse);
22886 if (rtn != 0) {
22887 ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
22888 return;
22889 }
22890 p->stimer->st_interval = minse;
22891 transmit_invite(p, SIP_INVITE, 1, 2);
22892 }
22893
22894
22895
22896
22897
22898
22899 int st_get_se(struct sip_pvt *p, int max)
22900 {
22901 if (max == TRUE) {
22902 if (p->stimer->st_cached_max_se) {
22903 return p->stimer->st_cached_max_se;
22904 } else 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_max_se = pp->stimer.st_max_se;
22908 unref_peer(pp, "unref peer pointer from find_peer call in st_get_se");
22909 return (p->stimer->st_cached_max_se);
22910 }
22911 }
22912 p->stimer->st_cached_max_se = global_max_se;
22913 return (p->stimer->st_cached_max_se);
22914 } else {
22915 if (p->stimer->st_cached_min_se) {
22916 return p->stimer->st_cached_min_se;
22917 } else if (p->peername) {
22918 struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE, 0);
22919 if (pp) {
22920 p->stimer->st_cached_min_se = pp->stimer.st_min_se;
22921 unref_peer(pp, "unref peer pointer from find_peer call in st_get_se (2)");
22922 return (p->stimer->st_cached_min_se);
22923 }
22924 }
22925 p->stimer->st_cached_min_se = global_min_se;
22926 return (p->stimer->st_cached_min_se);
22927 }
22928 }
22929
22930
22931
22932
22933
22934 enum st_refresher st_get_refresher(struct sip_pvt *p)
22935 {
22936 if (p->stimer->st_cached_ref != SESSION_TIMER_REFRESHER_AUTO)
22937 return p->stimer->st_cached_ref;
22938
22939 if (p->peername) {
22940 struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE, 0);
22941 if (pp) {
22942 p->stimer->st_cached_ref = pp->stimer.st_ref;
22943 unref_peer(pp, "unref peer pointer from find_peer call in st_get_refresher");
22944 return pp->stimer.st_ref;
22945 }
22946 }
22947
22948 p->stimer->st_cached_ref = global_st_refresher;
22949 return global_st_refresher;
22950 }
22951
22952
22953
22954
22955
22956 enum st_mode st_get_mode(struct sip_pvt *p)
22957 {
22958 if (!p->stimer)
22959 sip_st_alloc(p);
22960
22961 if (p->stimer->st_cached_mode != SESSION_TIMER_MODE_INVALID)
22962 return p->stimer->st_cached_mode;
22963
22964 if (p->peername) {
22965 struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE, 0);
22966 if (pp) {
22967 p->stimer->st_cached_mode = pp->stimer.st_mode_oper;
22968 unref_peer(pp, "unref peer pointer from find_peer call in st_get_mode");
22969 return pp->stimer.st_mode_oper;
22970 }
22971 }
22972
22973 p->stimer->st_cached_mode = global_st_mode;
22974 return global_st_mode;
22975 }
22976
22977
22978
22979 static int sip_poke_noanswer(const void *data)
22980 {
22981 struct sip_peer *peer = (struct sip_peer *)data;
22982
22983 peer->pokeexpire = -1;
22984
22985 if (peer->lastms > -1) {
22986 ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE! Last qualify: %d\n", peer->name, peer->lastms);
22987 if (sip_cfg.peer_rtupdate) {
22988 ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", "-1", SENTINEL);
22989 }
22990 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer->name, -1);
22991 if (sip_cfg.regextenonqualify) {
22992 register_peer_exten(peer, FALSE);
22993 }
22994 }
22995
22996 if (peer->call) {
22997 dialog_unlink_all(peer->call, TRUE, TRUE);
22998 peer->call = dialog_unref(peer->call, "unref dialog peer->call");
22999
23000 }
23001
23002 peer->lastms = -1;
23003 ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
23004
23005
23006 AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
23007 DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer,
23008 unref_peer(_data, "removing poke peer ref"),
23009 unref_peer(peer, "removing poke peer ref"),
23010 ref_peer(peer, "adding poke peer ref"));
23011
23012
23013 unref_peer(peer, "release peer poke noanswer ref");
23014
23015 return 0;
23016 }
23017
23018
23019
23020
23021
23022
23023 static int sip_poke_peer(struct sip_peer *peer, int force)
23024 {
23025 struct sip_pvt *p;
23026 int xmitres = 0;
23027
23028 if ((!peer->maxms && !force) || !peer->addr.sin_addr.s_addr) {
23029
23030
23031 AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
23032 unref_peer(peer, "removing poke peer ref"));
23033
23034 peer->lastms = 0;
23035 if (peer->call) {
23036 peer->call = dialog_unref(peer->call, "unref dialog peer->call");
23037 }
23038 return 0;
23039 }
23040 if (peer->call) {
23041 if (sipdebug) {
23042 ast_log(LOG_NOTICE, "Still have a QUALIFY dialog active, deleting\n");
23043 }
23044 dialog_unlink_all(peer->call, TRUE, TRUE);
23045 peer->call = dialog_unref(peer->call, "unref dialog peer->call");
23046
23047 }
23048 if (!(p = sip_alloc(NULL, NULL, 0, SIP_OPTIONS, NULL))) {
23049 return -1;
23050 }
23051 peer->call = dialog_ref(p, "copy sip alloc from p to peer->call");
23052
23053 p->sa = peer->addr;
23054 p->recv = peer->addr;
23055 copy_socket_data(&p->socket, &peer->socket);
23056 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
23057 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
23058
23059
23060 if (!ast_strlen_zero(peer->fullcontact))
23061 ast_string_field_set(p, fullcontact, peer->fullcontact);
23062
23063 if (!ast_strlen_zero(peer->tohost))
23064 ast_string_field_set(p, tohost, peer->tohost);
23065 else
23066 ast_string_field_set(p, tohost, ast_inet_ntoa(peer->addr.sin_addr));
23067
23068
23069 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
23070 build_via(p);
23071 ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
23072 build_callid_pvt(p);
23073 ao2_t_link(dialogs, p, "Linking in under new name");
23074
23075 AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
23076 unref_peer(peer, "removing poke peer ref"));
23077
23078 if (p->relatedpeer)
23079 p->relatedpeer = unref_peer(p->relatedpeer,"unsetting the relatedpeer field in the dialog, before it is set to something else.");
23080 p->relatedpeer = ref_peer(peer, "setting the relatedpeer field in the dialog");
23081 ast_set_flag(&p->flags[0], SIP_OUTGOING);
23082 #ifdef VOCAL_DATA_HACK
23083 ast_copy_string(p->username, "__VOCAL_DATA_SHOULD_READ_THE_SIP_SPEC__", sizeof(p->username));
23084 xmitres = transmit_invite(p, SIP_INVITE, 0, 2);
23085 #else
23086 xmitres = transmit_invite(p, SIP_OPTIONS, 0, 2);
23087 #endif
23088 peer->ps = ast_tvnow();
23089 if (xmitres == XMIT_ERROR) {
23090 sip_poke_noanswer(peer);
23091 } else if (!force) {
23092 AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, peer->maxms * 2, sip_poke_noanswer, peer,
23093 unref_peer(_data, "removing poke peer ref"),
23094 unref_peer(peer, "removing poke peer ref"),
23095 ref_peer(peer, "adding poke peer ref"));
23096 }
23097 dialog_unref(p, "unref dialog at end of sip_poke_peer, obtained from sip_alloc, just before it goes out of scope");
23098 return 0;
23099 }
23100
23101
23102
23103
23104
23105
23106
23107
23108
23109
23110
23111
23112
23113
23114
23115
23116
23117
23118
23119
23120
23121
23122
23123
23124
23125
23126
23127
23128
23129
23130
23131
23132
23133
23134 static int sip_devicestate(void *data)
23135 {
23136 char *host;
23137 char *tmp;
23138 struct sip_peer *p;
23139
23140 int res = AST_DEVICE_INVALID;
23141
23142
23143 host = ast_strdupa(data ? data : "");
23144 if ((tmp = strchr(host, '@')))
23145 host = tmp + 1;
23146
23147 ast_debug(3, "Checking device state for peer %s\n", host);
23148
23149
23150
23151
23152
23153
23154
23155
23156 if ((p = find_peer(host, NULL, FALSE, FINDALLDEVICES, TRUE, 0))) {
23157 if (p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) {
23158
23159
23160
23161
23162
23163
23164
23165
23166
23167
23168
23169 if (p->onHold)
23170
23171 res = AST_DEVICE_ONHOLD;
23172 else if (p->inRinging) {
23173 if (p->inRinging == p->inUse)
23174 res = AST_DEVICE_RINGING;
23175 else
23176 res = AST_DEVICE_RINGINUSE;
23177 } else if (p->call_limit && (p->inUse == p->call_limit))
23178
23179 res = AST_DEVICE_BUSY;
23180 else if (p->call_limit && p->busy_level && p->inUse >= p->busy_level)
23181
23182 res = AST_DEVICE_BUSY;
23183 else if (p->call_limit && p->inUse)
23184
23185 res = AST_DEVICE_INUSE;
23186 else if (p->maxms && ((p->lastms > p->maxms) || (p->lastms < 0)))
23187
23188 res = AST_DEVICE_UNAVAILABLE;
23189 else
23190 res = AST_DEVICE_NOT_INUSE;
23191 } else {
23192
23193 res = AST_DEVICE_UNAVAILABLE;
23194 }
23195 unref_peer(p, "unref_peer, from sip_devicestate, release ref from find_peer");
23196 } else {
23197 res = AST_DEVICE_UNKNOWN;
23198 }
23199
23200 return res;
23201 }
23202
23203
23204
23205
23206
23207
23208
23209
23210
23211
23212
23213 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause)
23214 {
23215 struct sip_pvt *p;
23216 struct ast_channel *tmpc = NULL;
23217 char *ext = NULL, *host;
23218 char tmp[256];
23219 char *dest = data;
23220 char *dnid;
23221 char *secret = NULL;
23222 char *md5secret = NULL;
23223 char *authname = NULL;
23224 char *trans = NULL;
23225 enum sip_transport transport = 0;
23226 int oldformat = format;
23227
23228
23229
23230
23231
23232
23233
23234
23235 format &= AST_FORMAT_AUDIO_MASK;
23236 if (!format) {
23237 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));
23238 *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
23239 return NULL;
23240 }
23241 ast_debug(1, "Asked to create a SIP channel with formats: %s\n", ast_getformatname_multiple(tmp, sizeof(tmp), oldformat));
23242
23243 if (!(p = sip_alloc(NULL, NULL, 0, SIP_INVITE, NULL))) {
23244 ast_log(LOG_ERROR, "Unable to build sip pvt data for '%s' (Out of memory or socket error)\n", dest);
23245 *cause = AST_CAUSE_SWITCH_CONGESTION;
23246 return NULL;
23247 }
23248
23249 p->outgoing_call = TRUE;
23250
23251 if (!(p->options = ast_calloc(1, sizeof(*p->options)))) {
23252 dialog_unlink_all(p, TRUE, TRUE);
23253 dialog_unref(p, "unref dialog p from mem fail");
23254
23255 ast_log(LOG_ERROR, "Unable to build option SIP data structure - Out of memory\n");
23256 *cause = AST_CAUSE_SWITCH_CONGESTION;
23257 return NULL;
23258 }
23259
23260
23261 ast_copy_string(tmp, dest, sizeof(tmp));
23262
23263
23264
23265 dnid = strchr(tmp, '!');
23266 if (dnid != NULL) {
23267 *dnid++ = '\0';
23268 ast_string_field_set(p, todnid, dnid);
23269 }
23270
23271
23272 host = strchr(tmp, '@');
23273 if (host) {
23274 *host++ = '\0';
23275 ext = tmp;
23276 secret = strchr(ext, ':');
23277 }
23278 if (secret) {
23279 *secret++ = '\0';
23280 md5secret = strchr(secret, ':');
23281 }
23282 if (md5secret) {
23283 *md5secret++ = '\0';
23284 authname = strchr(md5secret, ':');
23285 }
23286 if (authname) {
23287 *authname++ = '\0';
23288 trans = strchr(authname, ':');
23289 }
23290 if (trans) {
23291 *trans++ = '\0';
23292 if (!strcasecmp(trans, "tcp"))
23293 transport = SIP_TRANSPORT_TCP;
23294 else if (!strcasecmp(trans, "tls"))
23295 transport = SIP_TRANSPORT_TLS;
23296 else {
23297 if (strcasecmp(trans, "udp"))
23298 ast_log(LOG_WARNING, "'%s' is not a valid transport option to Dial() for SIP calls, using udp by default.\n", trans);
23299 transport = SIP_TRANSPORT_UDP;
23300 }
23301 } else {
23302 transport = SIP_TRANSPORT_UDP;
23303 }
23304
23305 if (!host) {
23306 ext = strchr(tmp, '/');
23307 if (ext)
23308 *ext++ = '\0';
23309 host = tmp;
23310 }
23311
23312 set_socket_transport(&p->socket, transport);
23313
23314
23315
23316
23317
23318
23319 if (create_addr(p, host, NULL, 1)) {
23320 *cause = AST_CAUSE_UNREGISTERED;
23321 ast_debug(3, "Cant create SIP call - target device not registered\n");
23322 dialog_unlink_all(p, TRUE, TRUE);
23323 dialog_unref(p, "unref dialog p UNREGISTERED");
23324
23325 return NULL;
23326 }
23327 if (ast_strlen_zero(p->peername) && ext)
23328 ast_string_field_set(p, peername, ext);
23329
23330 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
23331 build_via(p);
23332 ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
23333 build_callid_pvt(p);
23334 ao2_t_link(dialogs, p, "Linking in under new name");
23335
23336
23337
23338
23339
23340
23341 if (ext) {
23342 ast_string_field_set(p, username, ext);
23343 ast_string_field_set(p, fullcontact, NULL);
23344 }
23345 if (secret && !ast_strlen_zero(secret))
23346 ast_string_field_set(p, peersecret, secret);
23347
23348 if (md5secret && !ast_strlen_zero(md5secret))
23349 ast_string_field_set(p, peermd5secret, md5secret);
23350
23351 if (authname && !ast_strlen_zero(authname))
23352 ast_string_field_set(p, authname, authname);
23353 #if 0
23354 printf("Setting up to call extension '%s' at '%s'\n", ext ? ext : "<none>", host);
23355 #endif
23356 p->prefcodec = oldformat;
23357 p->jointcapability = oldformat & p->capability;
23358 sip_pvt_lock(p);
23359 tmpc = sip_new(p, AST_STATE_DOWN, host);
23360 if (sip_cfg.callevents)
23361 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
23362 "Channel: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
23363 p->owner? p->owner->name : "", "SIP", p->callid, p->fullcontact, p->peername);
23364 sip_pvt_unlock(p);
23365 if (!tmpc) {
23366 dialog_unlink_all(p, TRUE, TRUE);
23367
23368 }
23369 dialog_unref(p, "toss pvt ptr at end of sip_request_call");
23370 ast_update_use_count();
23371 restart_monitor();
23372 return tmpc;
23373 }
23374
23375
23376 static void set_insecure_flags (struct ast_flags *flags, const char *value, int lineno)
23377 {
23378 if (ast_strlen_zero(value))
23379 return;
23380
23381 if (!ast_false(value)) {
23382 char buf[64];
23383 char *word, *next;
23384
23385 ast_copy_string(buf, value, sizeof(buf));
23386 next = buf;
23387 while ((word = strsep(&next, ","))) {
23388 if (!strcasecmp(word, "port"))
23389 ast_set_flag(&flags[0], SIP_INSECURE_PORT);
23390 else if (!strcasecmp(word, "invite"))
23391 ast_set_flag(&flags[0], SIP_INSECURE_INVITE);
23392 else
23393 ast_log(LOG_WARNING, "Unknown insecure mode '%s' on line %d\n", value, lineno);
23394 }
23395 }
23396 }
23397
23398
23399
23400
23401
23402 static int handle_t38_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v,
23403 int *maxdatagram)
23404 {
23405 int res = 1;
23406
23407 if (!strcasecmp(v->name, "t38pt_udptl")) {
23408 char *buf = ast_strdupa(v->value);
23409 char *word, *next = buf;
23410
23411 ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT);
23412
23413 while ((word = strsep(&next, ","))) {
23414 if (ast_true(word) || !strcasecmp(word, "fec")) {
23415 ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
23416 ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_FEC);
23417 } else if (!strcasecmp(word, "redundancy")) {
23418 ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
23419 ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY);
23420 } else if (!strcasecmp(word, "none")) {
23421 ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
23422 ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL);
23423 } else if (!strncasecmp(word, "maxdatagram=", 12)) {
23424 if (sscanf(&word[12], "%30u", maxdatagram) != 1) {
23425 ast_log(LOG_WARNING, "Invalid maxdatagram '%s' at line %d of %s\n", v->value, v->lineno, config);
23426 *maxdatagram = global_t38_maxdatagram;
23427 }
23428 }
23429 }
23430 } else if (!strcasecmp(v->name, "t38pt_usertpsource")) {
23431 ast_set_flag(&mask[1], SIP_PAGE2_UDPTL_DESTINATION);
23432 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_UDPTL_DESTINATION);
23433 } else if (!strcasecmp(v->name, "forwardloopdetected")) {
23434 ast_set_flag(&mask[1], SIP_PAGE2_FORWARD_LOOP_DETECTED);
23435 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_FORWARD_LOOP_DETECTED);
23436 } else {
23437 res = 0;
23438 }
23439
23440 return res;
23441 }
23442
23443
23444
23445
23446
23447
23448
23449
23450 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v)
23451 {
23452 int res = 1;
23453
23454 if (!strcasecmp(v->name, "trustrpid")) {
23455 ast_set_flag(&mask[0], SIP_TRUSTRPID);
23456 ast_set2_flag(&flags[0], ast_true(v->value), SIP_TRUSTRPID);
23457 } else if (!strcasecmp(v->name, "sendrpid")) {
23458 ast_set_flag(&mask[0], SIP_SENDRPID);
23459 ast_set2_flag(&flags[0], ast_true(v->value), SIP_SENDRPID);
23460 } else if (!strcasecmp(v->name, "g726nonstandard")) {
23461 ast_set_flag(&mask[0], SIP_G726_NONSTANDARD);
23462 ast_set2_flag(&flags[0], ast_true(v->value), SIP_G726_NONSTANDARD);
23463 } else if (!strcasecmp(v->name, "useclientcode")) {
23464 ast_set_flag(&mask[0], SIP_USECLIENTCODE);
23465 ast_set2_flag(&flags[0], ast_true(v->value), SIP_USECLIENTCODE);
23466 } else if (!strcasecmp(v->name, "dtmfmode")) {
23467 ast_set_flag(&mask[0], SIP_DTMF);
23468 ast_clear_flag(&flags[0], SIP_DTMF);
23469 if (!strcasecmp(v->value, "inband"))
23470 ast_set_flag(&flags[0], SIP_DTMF_INBAND);
23471 else if (!strcasecmp(v->value, "rfc2833"))
23472 ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
23473 else if (!strcasecmp(v->value, "info"))
23474 ast_set_flag(&flags[0], SIP_DTMF_INFO);
23475 else if (!strcasecmp(v->value, "shortinfo"))
23476 ast_set_flag(&flags[0], SIP_DTMF_SHORTINFO);
23477 else if (!strcasecmp(v->value, "auto"))
23478 ast_set_flag(&flags[0], SIP_DTMF_AUTO);
23479 else {
23480 ast_log(LOG_WARNING, "Unknown dtmf mode '%s' on line %d, using rfc2833\n", v->value, v->lineno);
23481 ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
23482 }
23483 } else if (!strcasecmp(v->name, "nat")) {
23484 ast_set_flag(&mask[0], SIP_NAT);
23485 ast_clear_flag(&flags[0], SIP_NAT);
23486 if (!strcasecmp(v->value, "never"))
23487 ast_set_flag(&flags[0], SIP_NAT_NEVER);
23488 else if (!strcasecmp(v->value, "route"))
23489 ast_set_flag(&flags[0], SIP_NAT_ROUTE);
23490 else if (ast_true(v->value))
23491 ast_set_flag(&flags[0], SIP_NAT_ALWAYS);
23492 else
23493 ast_set_flag(&flags[0], SIP_NAT_RFC3581);
23494 } else if (!strcasecmp(v->name, "directmedia") || !strcasecmp(v->name, "canreinvite")) {
23495 ast_set_flag(&mask[0], SIP_REINVITE);
23496 ast_clear_flag(&flags[0], SIP_REINVITE);
23497 if (ast_true(v->value)) {
23498 ast_set_flag(&flags[0], SIP_DIRECT_MEDIA | SIP_DIRECT_MEDIA_NAT);
23499 } else if (!ast_false(v->value)) {
23500 char buf[64];
23501 char *word, *next = buf;
23502
23503 ast_copy_string(buf, v->value, sizeof(buf));
23504 while ((word = strsep(&next, ","))) {
23505 if (!strcasecmp(word, "update")) {
23506 ast_set_flag(&flags[0], SIP_REINVITE_UPDATE | SIP_DIRECT_MEDIA);
23507 } else if (!strcasecmp(word, "nonat")) {
23508 ast_set_flag(&flags[0], SIP_DIRECT_MEDIA);
23509 ast_clear_flag(&flags[0], SIP_DIRECT_MEDIA_NAT);
23510 } else {
23511 ast_log(LOG_WARNING, "Unknown directmedia mode '%s' on line %d\n", v->value, v->lineno);
23512 }
23513 }
23514 }
23515 } else if (!strcasecmp(v->name, "insecure")) {
23516 ast_set_flag(&mask[0], SIP_INSECURE);
23517 ast_clear_flag(&flags[0], SIP_INSECURE);
23518 set_insecure_flags(&flags[0], v->value, v->lineno);
23519 } else if (!strcasecmp(v->name, "progressinband")) {
23520 ast_set_flag(&mask[0], SIP_PROG_INBAND);
23521 ast_clear_flag(&flags[0], SIP_PROG_INBAND);
23522 if (ast_true(v->value))
23523 ast_set_flag(&flags[0], SIP_PROG_INBAND_YES);
23524 else if (strcasecmp(v->value, "never"))
23525 ast_set_flag(&flags[0], SIP_PROG_INBAND_NO);
23526 } else if (!strcasecmp(v->name, "promiscredir")) {
23527 ast_set_flag(&mask[0], SIP_PROMISCREDIR);
23528 ast_set2_flag(&flags[0], ast_true(v->value), SIP_PROMISCREDIR);
23529 } else if (!strcasecmp(v->name, "videosupport")) {
23530 if (!strcasecmp(v->value, "always")) {
23531 ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
23532 ast_set_flag(&flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
23533 } else {
23534 ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT);
23535 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_VIDEOSUPPORT);
23536 }
23537 } else if (!strcasecmp(v->name, "textsupport")) {
23538 ast_set_flag(&mask[1], SIP_PAGE2_TEXTSUPPORT);
23539 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_TEXTSUPPORT);
23540 res = 1;
23541 } else if (!strcasecmp(v->name, "allowoverlap")) {
23542 ast_set_flag(&mask[1], SIP_PAGE2_ALLOWOVERLAP);
23543 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWOVERLAP);
23544 } else if (!strcasecmp(v->name, "allowsubscribe")) {
23545 ast_set_flag(&mask[1], SIP_PAGE2_ALLOWSUBSCRIBE);
23546 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWSUBSCRIBE);
23547 } else if (!strcasecmp(v->name, "ignoresdpversion")) {
23548 ast_set_flag(&mask[1], SIP_PAGE2_IGNORESDPVERSION);
23549 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_IGNORESDPVERSION);
23550 } else if (!strcasecmp(v->name, "faxdetect")) {
23551 ast_set_flag(&mask[1], SIP_PAGE2_FAX_DETECT);
23552 if (ast_true(v->value)) {
23553 ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_BOTH);
23554 } else if (ast_false(v->value)) {
23555 ast_clear_flag(&flags[1], SIP_PAGE2_FAX_DETECT_BOTH);
23556 } else {
23557 char *buf = ast_strdupa(v->value);
23558 char *word, *next = buf;
23559
23560 while ((word = strsep(&next, ","))) {
23561 if (!strcasecmp(word, "cng")) {
23562 ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_CNG);
23563 } else if (!strcasecmp(word, "t38")) {
23564 ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_T38);
23565 } else {
23566 ast_log(LOG_WARNING, "Unknown faxdetect mode '%s' on line %d.\n", word, v->lineno);
23567 }
23568 }
23569 }
23570 } else if (!strcasecmp(v->name, "rfc2833compensate")) {
23571 ast_set_flag(&mask[1], SIP_PAGE2_RFC2833_COMPENSATE);
23572 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RFC2833_COMPENSATE);
23573 } else if (!strcasecmp(v->name, "buggymwi")) {
23574 ast_set_flag(&mask[1], SIP_PAGE2_BUGGY_MWI);
23575 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_BUGGY_MWI);
23576 } else
23577 res = 0;
23578
23579 return res;
23580 }
23581
23582
23583 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context)
23584 {
23585 struct domain *d;
23586
23587 if (ast_strlen_zero(domain)) {
23588 ast_log(LOG_WARNING, "Zero length domain.\n");
23589 return 1;
23590 }
23591
23592 if (!(d = ast_calloc(1, sizeof(*d))))
23593 return 0;
23594
23595 ast_copy_string(d->domain, domain, sizeof(d->domain));
23596
23597 if (!ast_strlen_zero(context))
23598 ast_copy_string(d->context, context, sizeof(d->context));
23599
23600 d->mode = mode;
23601
23602 AST_LIST_LOCK(&domain_list);
23603 AST_LIST_INSERT_TAIL(&domain_list, d, list);
23604 AST_LIST_UNLOCK(&domain_list);
23605
23606 if (sipdebug)
23607 ast_debug(1, "Added local SIP domain '%s'\n", domain);
23608
23609 return 1;
23610 }
23611
23612
23613 static int check_sip_domain(const char *domain, char *context, size_t len)
23614 {
23615 struct domain *d;
23616 int result = 0;
23617
23618 AST_LIST_LOCK(&domain_list);
23619 AST_LIST_TRAVERSE(&domain_list, d, list) {
23620 if (strcasecmp(d->domain, domain))
23621 continue;
23622
23623 if (len && !ast_strlen_zero(d->context))
23624 ast_copy_string(context, d->context, len);
23625
23626 result = 1;
23627 break;
23628 }
23629 AST_LIST_UNLOCK(&domain_list);
23630
23631 return result;
23632 }
23633
23634
23635 static void clear_sip_domains(void)
23636 {
23637 struct domain *d;
23638
23639 AST_LIST_LOCK(&domain_list);
23640 while ((d = AST_LIST_REMOVE_HEAD(&domain_list, list)))
23641 ast_free(d);
23642 AST_LIST_UNLOCK(&domain_list);
23643 }
23644
23645
23646
23647 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, const char *configuration, int lineno)
23648 {
23649 char authcopy[256];
23650 char *username=NULL, *realm=NULL, *secret=NULL, *md5secret=NULL;
23651 struct sip_auth *a, *b, *auth;
23652
23653 if (ast_strlen_zero(configuration))
23654 return authlist;
23655
23656 ast_debug(1, "Auth config :: %s\n", configuration);
23657
23658 ast_copy_string(authcopy, configuration, sizeof(authcopy));
23659 username = authcopy;
23660
23661
23662 realm = strrchr(username, '@');
23663 if (realm)
23664 *realm++ = '\0';
23665 if (ast_strlen_zero(username) || ast_strlen_zero(realm)) {
23666 ast_log(LOG_WARNING, "Format for authentication entry is user[:secret]@realm at line %d\n", lineno);
23667 return authlist;
23668 }
23669
23670
23671 if ((secret = strchr(username, ':'))) {
23672 *secret++ = '\0';
23673 } else if ((md5secret = strchr(username, '#'))) {
23674 *md5secret++ = '\0';
23675 }
23676
23677 if (!(auth = ast_calloc(1, sizeof(*auth))))
23678 return authlist;
23679
23680 ast_copy_string(auth->realm, realm, sizeof(auth->realm));
23681 ast_copy_string(auth->username, username, sizeof(auth->username));
23682 if (secret)
23683 ast_copy_string(auth->secret, secret, sizeof(auth->secret));
23684 if (md5secret)
23685 ast_copy_string(auth->md5secret, md5secret, sizeof(auth->md5secret));
23686
23687
23688 for (b = NULL, a = authlist; a ; b = a, a = a->next)
23689 ;
23690 if (b)
23691 b->next = auth;
23692 else
23693 authlist = auth;
23694
23695 ast_verb(3, "Added authentication for realm %s\n", realm);
23696
23697 return authlist;
23698
23699 }
23700
23701
23702 static int clear_realm_authentication(struct sip_auth *authlist)
23703 {
23704 struct sip_auth *a = authlist;
23705 struct sip_auth *b;
23706
23707 while (a) {
23708 b = a;
23709 a = a->next;
23710 ast_free(b);
23711 }
23712
23713 return 1;
23714 }
23715
23716
23717 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm)
23718 {
23719 struct sip_auth *a;
23720
23721 for (a = authlist; a; a = a->next) {
23722 if (!strcasecmp(a->realm, realm))
23723 break;
23724 }
23725
23726 return a;
23727 }
23728
23729
23730
23731
23732 static struct ast_variable *add_var(const char *buf, struct ast_variable *list)
23733 {
23734 struct ast_variable *tmpvar = NULL;
23735 char *varname = ast_strdupa(buf), *varval = NULL;
23736
23737 if ((varval = strchr(varname, '='))) {
23738 *varval++ = '\0';
23739 if ((tmpvar = ast_variable_new(varname, varval, ""))) {
23740 tmpvar->next = list;
23741 list = tmpvar;
23742 }
23743 }
23744 return list;
23745 }
23746
23747
23748 static void set_peer_defaults(struct sip_peer *peer)
23749 {
23750 if (peer->expire == 0) {
23751
23752
23753
23754 peer->expire = -1;
23755 peer->pokeexpire = -1;
23756 peer->addr.sin_port = htons(STANDARD_SIP_PORT);
23757 set_socket_transport(&peer->socket, SIP_TRANSPORT_UDP);
23758 }
23759 peer->type = SIP_TYPE_PEER;
23760 ast_copy_flags(&peer->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
23761 ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
23762 ast_string_field_set(peer, context, sip_cfg.default_context);
23763 ast_string_field_set(peer, subscribecontext, sip_cfg.default_subscribecontext);
23764 ast_string_field_set(peer, language, default_language);
23765 ast_string_field_set(peer, mohinterpret, default_mohinterpret);
23766 ast_string_field_set(peer, mohsuggest, default_mohsuggest);
23767 peer->addr.sin_family = AF_INET;
23768 peer->defaddr.sin_family = AF_INET;
23769 peer->capability = global_capability;
23770 peer->maxcallbitrate = default_maxcallbitrate;
23771 peer->rtptimeout = global_rtptimeout;
23772 peer->rtpholdtimeout = global_rtpholdtimeout;
23773 peer->rtpkeepalive = global_rtpkeepalive;
23774 peer->allowtransfer = sip_cfg.allowtransfer;
23775 peer->autoframing = global_autoframing;
23776 peer->t38_maxdatagram = global_t38_maxdatagram;
23777 peer->qualifyfreq = global_qualifyfreq;
23778 if (global_callcounter)
23779 peer->call_limit=INT_MAX;
23780 ast_string_field_set(peer, vmexten, default_vmexten);
23781 ast_string_field_set(peer, secret, "");
23782 ast_string_field_set(peer, remotesecret, "");
23783 ast_string_field_set(peer, md5secret, "");
23784 ast_string_field_set(peer, cid_num, "");
23785 ast_string_field_set(peer, cid_name, "");
23786 ast_string_field_set(peer, fromdomain, "");
23787 ast_string_field_set(peer, fromuser, "");
23788 ast_string_field_set(peer, regexten, "");
23789 peer->callgroup = 0;
23790 peer->pickupgroup = 0;
23791 peer->maxms = default_qualify;
23792 peer->prefs = default_prefs;
23793 peer->stimer.st_mode_oper = global_st_mode;
23794 peer->stimer.st_ref = global_st_refresher;
23795 peer->stimer.st_min_se = global_min_se;
23796 peer->stimer.st_max_se = global_max_se;
23797 peer->timer_t1 = global_t1;
23798 peer->timer_b = global_timer_b;
23799 clear_peer_mailboxes(peer);
23800 peer->transports = default_transports;
23801 peer->default_outbound_transport = default_primary_transport;
23802 }
23803
23804
23805 static struct sip_peer *temp_peer(const char *name)
23806 {
23807 struct sip_peer *peer;
23808
23809 if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct")))
23810 return NULL;
23811
23812 if (ast_string_field_init(peer, 512)) {
23813 ao2_t_ref(peer, -1, "failed to string_field_init, drop peer");
23814 return NULL;
23815 }
23816
23817 ast_atomic_fetchadd_int(&apeerobjs, 1);
23818 set_peer_defaults(peer);
23819
23820 ast_copy_string(peer->name, name, sizeof(peer->name));
23821
23822 peer->selfdestruct = TRUE;
23823 peer->host_dynamic = TRUE;
23824 peer->prefs = default_prefs;
23825 reg_source_db(peer);
23826
23827 return peer;
23828 }
23829
23830
23831 static void add_peer_mailboxes(struct sip_peer *peer, const char *value)
23832 {
23833 char *next, *mbox, *context;
23834
23835 next = ast_strdupa(value);
23836
23837 while ((mbox = context = strsep(&next, ","))) {
23838 struct sip_mailbox *mailbox;
23839 int duplicate = 0;
23840
23841 strsep(&context, "@");
23842
23843 if (ast_strlen_zero(mbox)) {
23844 continue;
23845 }
23846
23847
23848 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
23849 if (!strcmp(mailbox->mailbox, mbox) && !strcmp(S_OR(mailbox->context, ""), S_OR(context, ""))) {
23850 duplicate = 1;
23851 mailbox->delme = 1;
23852 break;
23853 }
23854 }
23855 if (duplicate) {
23856 continue;
23857 }
23858
23859 if (!(mailbox = ast_calloc(1, sizeof(*mailbox)))) {
23860 continue;
23861 }
23862
23863 mailbox->mailbox = ast_strdup(mbox);
23864 mailbox->context = ast_strdup(context);
23865
23866 AST_LIST_INSERT_TAIL(&peer->mailboxes, mailbox, entry);
23867 }
23868 }
23869
23870
23871 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only)
23872 {
23873 struct sip_peer *peer = NULL;
23874 struct ast_ha *oldha = NULL;
23875 int found = 0;
23876 int firstpass = 1;
23877 uint16_t port = 0;
23878 int format = 0;
23879 time_t regseconds = 0;
23880 struct ast_flags peerflags[2] = {{(0)}};
23881 struct ast_flags mask[2] = {{(0)}};
23882 char callback[256] = "";
23883 struct sip_peer tmp_peer;
23884 const char *srvlookup = NULL;
23885 static int deprecation_warning = 1;
23886 int alt_fullcontact = alt ? 1 : 0;
23887 struct ast_str *fullcontact = ast_str_alloca(512);
23888
23889 if (!realtime || ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
23890
23891
23892
23893
23894
23895 ast_copy_string(tmp_peer.name, name, sizeof(tmp_peer.name));
23896 peer = ao2_t_find(peers, &tmp_peer, OBJ_POINTER | OBJ_UNLINK, "find and unlink peer from peers table");
23897 }
23898
23899 if (peer) {
23900
23901 found++;
23902 if (!(peer->the_mark))
23903 firstpass = 0;
23904 } else {
23905 if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct")))
23906 return NULL;
23907
23908 if (ast_string_field_init(peer, 512)) {
23909 ao2_t_ref(peer, -1, "failed to string_field_init, drop peer");
23910 return NULL;
23911 }
23912
23913 if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
23914 ast_atomic_fetchadd_int(&rpeerobjs, 1);
23915 ast_debug(3, "-REALTIME- peer built. Name: %s. Peer objects: %d\n", name, rpeerobjs);
23916 } else
23917 ast_atomic_fetchadd_int(&speerobjs, 1);
23918 }
23919
23920
23921 if (firstpass) {
23922 peer->lastmsgssent = -1;
23923 oldha = peer->ha;
23924 peer->ha = NULL;
23925 set_peer_defaults(peer);
23926 peer->type = 0;
23927 }
23928 if (!found && name)
23929 ast_copy_string(peer->name, name, sizeof(peer->name));
23930
23931
23932 if (peer->chanvars) {
23933 ast_variables_destroy(peer->chanvars);
23934 peer->chanvars = NULL;
23935
23936 }
23937
23938 if (found)
23939 peer->portinuri = 0;
23940
23941
23942 clear_realm_authentication(peer->auth);
23943 peer->auth = NULL;
23944
23945 peer->default_outbound_transport = 0;
23946 peer->transports = 0;
23947
23948 if (!devstate_only) {
23949 struct sip_mailbox *mailbox;
23950 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
23951 mailbox->delme = 1;
23952 }
23953 }
23954
23955 for (; v || ((v = alt) && !(alt=NULL)); v = v->next) {
23956 if (!devstate_only) {
23957 if (handle_common_options(&peerflags[0], &mask[0], v)) {
23958 continue;
23959 }
23960 if (handle_t38_options(&peerflags[0], &mask[0], v, &peer->t38_maxdatagram)) {
23961 continue;
23962 }
23963 if (!strcasecmp(v->name, "transport") && !ast_strlen_zero(v->value)) {
23964 char *val = ast_strdupa(v->value);
23965 char *trans;
23966
23967 while ((trans = strsep(&val, ","))) {
23968 trans = ast_skip_blanks(trans);
23969
23970 if (!strncasecmp(trans, "udp", 3)) {
23971 peer->transports |= SIP_TRANSPORT_UDP;
23972 } else if (!strncasecmp(trans, "tcp", 3)) {
23973 peer->transports |= SIP_TRANSPORT_TCP;
23974 } else if (!strncasecmp(trans, "tls", 3)) {
23975 peer->transports |= SIP_TRANSPORT_TLS;
23976 } else {
23977 ast_log(LOG_NOTICE, "'%s' is not a valid transport type. if no other is specified, udp will be used.\n", trans);
23978 }
23979
23980 if (!peer->default_outbound_transport) {
23981 peer->default_outbound_transport = peer->transports;
23982 }
23983 }
23984 } else if (realtime && !strcasecmp(v->name, "regseconds")) {
23985 ast_get_time_t(v->value, ®seconds, 0, NULL);
23986 } else if (realtime && !strcasecmp(v->name, "name")) {
23987 ast_copy_string(peer->name, v->value, sizeof(peer->name));
23988 } else if (realtime && !strcasecmp(v->name, "useragent")) {
23989 ast_string_field_set(peer, useragent, v->value);
23990 } else if (!strcasecmp(v->name, "type")) {
23991 if (!strcasecmp(v->value, "peer")) {
23992 peer->type |= SIP_TYPE_PEER;
23993 } else if (!strcasecmp(v->value, "user")) {
23994 peer->type |= SIP_TYPE_USER;
23995 } else if (!strcasecmp(v->value, "friend")) {
23996 peer->type = SIP_TYPE_USER | SIP_TYPE_PEER;
23997 }
23998 } else if (!strcasecmp(v->name, "remotesecret")) {
23999 ast_string_field_set(peer, remotesecret, v->value);
24000 } else if (!strcasecmp(v->name, "secret")) {
24001 ast_string_field_set(peer, secret, v->value);
24002 } else if (!strcasecmp(v->name, "md5secret")) {
24003 ast_string_field_set(peer, md5secret, v->value);
24004 } else if (!strcasecmp(v->name, "auth")) {
24005 peer->auth = add_realm_authentication(peer->auth, v->value, v->lineno);
24006 } else if (!strcasecmp(v->name, "callerid")) {
24007 char cid_name[80] = { '\0' }, cid_num[80] = { '\0' };
24008
24009 ast_callerid_split(v->value, cid_name, sizeof(cid_name), cid_num, sizeof(cid_num));
24010 ast_string_field_set(peer, cid_name, cid_name);
24011 ast_string_field_set(peer, cid_num, cid_num);
24012 } else if (!strcasecmp(v->name, "fullname")) {
24013 ast_string_field_set(peer, cid_name, v->value);
24014 } else if (!strcasecmp(v->name, "trunkname")) {
24015
24016 ast_string_field_set(peer, cid_name, "");
24017 } else if (!strcasecmp(v->name, "cid_number")) {
24018 ast_string_field_set(peer, cid_num, v->value);
24019 } else if (!strcasecmp(v->name, "context")) {
24020 ast_string_field_set(peer, context, v->value);
24021 ast_set_flag(&peer->flags[1], SIP_PAGE2_HAVEPEERCONTEXT);
24022 } else if (!strcasecmp(v->name, "subscribecontext")) {
24023 ast_string_field_set(peer, subscribecontext, v->value);
24024 } else if (!strcasecmp(v->name, "fromdomain")) {
24025 ast_string_field_set(peer, fromdomain, v->value);
24026 } else if (!strcasecmp(v->name, "usereqphone")) {
24027 ast_set2_flag(&peer->flags[0], ast_true(v->value), SIP_USEREQPHONE);
24028 } else if (!strcasecmp(v->name, "fromuser")) {
24029 ast_string_field_set(peer, fromuser, v->value);
24030 } else if (!strcasecmp(v->name, "outboundproxy")) {
24031 char *port, *next, *force, *proxyname;
24032 int forceopt = FALSE;
24033
24034 next = proxyname = ast_strdupa(v->value);
24035 if ((port = strchr(proxyname, ':'))) {
24036 *port++ = '\0';
24037 next = port;
24038 }
24039 if ((force = strchr(next, ','))) {
24040 *force++ = '\0';
24041 forceopt = strcmp(force, "force");
24042 }
24043
24044 peer->outboundproxy = proxy_allocate(proxyname, port, forceopt);
24045 } else if (!strcasecmp(v->name, "host")) {
24046 if (!strcasecmp(v->value, "dynamic")) {
24047
24048 if (!found || !peer->host_dynamic) {
24049
24050
24051 memset(&peer->addr.sin_addr, 0, 4);
24052 peer->addr.sin_port = 0;
24053 }
24054 peer->host_dynamic = TRUE;
24055 } else {
24056
24057 AST_SCHED_DEL_UNREF(sched, peer->expire,
24058 unref_peer(peer, "removing register expire ref"));
24059
24060 peer->addr.sin_port = 0;
24061 peer->host_dynamic = FALSE;
24062 srvlookup = v->value;
24063 }
24064 } else if (!strcasecmp(v->name, "defaultip")) {
24065 if (!ast_strlen_zero(v->value) && ast_get_ip(&peer->defaddr, v->value)) {
24066 unref_peer(peer, "unref_peer: from build_peer defaultip");
24067 return NULL;
24068 }
24069 } else if (!strcasecmp(v->name, "permit") || !strcasecmp(v->name, "deny")) {
24070 int ha_error = 0;
24071 if (!ast_strlen_zero(v->value)) {
24072 peer->ha = ast_append_ha(v->name, v->value, peer->ha, &ha_error);
24073 }
24074 if (ha_error) {
24075 ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
24076 }
24077 } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny")) {
24078 int ha_error = 0;
24079 if (!ast_strlen_zero(v->value)) {
24080 peer->contactha = ast_append_ha(v->name + 7, v->value, peer->contactha, &ha_error);
24081 }
24082 if (ha_error) {
24083 ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
24084 }
24085 } else if (!strcasecmp(v->name, "port")) {
24086 peer->portinuri = 1;
24087 if (!(port = port_str2int(v->value, 0))) {
24088 if (realtime) {
24089
24090 peer->portinuri = 0;
24091 } else {
24092 ast_log(LOG_WARNING, "Invalid peer port configuration at line %d : %s\n", v->lineno, v->value);
24093 }
24094 }
24095 } else if (!strcasecmp(v->name, "callingpres")) {
24096 peer->callingpres = ast_parse_caller_presentation(v->value);
24097 if (peer->callingpres == -1) {
24098 peer->callingpres = atoi(v->value);
24099 }
24100 } else if (!strcasecmp(v->name, "username") || !strcmp(v->name, "defaultuser")) {
24101 ast_string_field_set(peer, username, v->value);
24102 if (!strcasecmp(v->name, "username")) {
24103 if (deprecation_warning) {
24104 ast_log(LOG_NOTICE, "The 'username' field for sip peers has been deprecated in favor of the term 'defaultuser'\n");
24105 deprecation_warning = 0;
24106 }
24107 peer->deprecated_username = 1;
24108 }
24109 } else if (!strcasecmp(v->name, "language")) {
24110 ast_string_field_set(peer, language, v->value);
24111 } else if (!strcasecmp(v->name, "regexten")) {
24112 ast_string_field_set(peer, regexten, v->value);
24113 } else if (!strcasecmp(v->name, "callbackextension")) {
24114 ast_copy_string(callback, v->value, sizeof(callback));
24115 } else if (!strcasecmp(v->name, "amaflags")) {
24116 format = ast_cdr_amaflags2int(v->value);
24117 if (format < 0) {
24118 ast_log(LOG_WARNING, "Invalid AMA Flags for peer: %s at line %d\n", v->value, v->lineno);
24119 } else {
24120 peer->amaflags = format;
24121 }
24122 } else if (!strcasecmp(v->name, "accountcode")) {
24123 ast_string_field_set(peer, accountcode, v->value);
24124 } else if (!strcasecmp(v->name, "mohinterpret")) {
24125 ast_string_field_set(peer, mohinterpret, v->value);
24126 } else if (!strcasecmp(v->name, "mohsuggest")) {
24127 ast_string_field_set(peer, mohsuggest, v->value);
24128 } else if (!strcasecmp(v->name, "parkinglot")) {
24129 ast_string_field_set(peer, parkinglot, v->value);
24130 } else if (!strcasecmp(v->name, "mailbox")) {
24131 add_peer_mailboxes(peer, v->value);
24132 } else if (!strcasecmp(v->name, "hasvoicemail")) {
24133
24134
24135 if (ast_true(v->value) && AST_LIST_EMPTY(&peer->mailboxes)) {
24136 add_peer_mailboxes(peer, name);
24137 }
24138 } else if (!strcasecmp(v->name, "subscribemwi")) {
24139 ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_SUBSCRIBEMWIONLY);
24140 } else if (!strcasecmp(v->name, "vmexten")) {
24141 ast_string_field_set(peer, vmexten, v->value);
24142 } else if (!strcasecmp(v->name, "callgroup")) {
24143 peer->callgroup = ast_get_group(v->value);
24144 } else if (!strcasecmp(v->name, "allowtransfer")) {
24145 peer->allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
24146 } else if (!strcasecmp(v->name, "pickupgroup")) {
24147 peer->pickupgroup = ast_get_group(v->value);
24148 } else if (!strcasecmp(v->name, "allow")) {
24149 int error = ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, TRUE);
24150 if (error) {
24151 ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
24152 }
24153 } else if (!strcasecmp(v->name, "disallow")) {
24154 int error = ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, FALSE);
24155 if (error) {
24156 ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
24157 }
24158 } else if (!strcasecmp(v->name, "registertrying")) {
24159 ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_REGISTERTRYING);
24160 } else if (!strcasecmp(v->name, "autoframing")) {
24161 peer->autoframing = ast_true(v->value);
24162 } else if (!strcasecmp(v->name, "rtptimeout")) {
24163 if ((sscanf(v->value, "%30d", &peer->rtptimeout) != 1) || (peer->rtptimeout < 0)) {
24164 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
24165 peer->rtptimeout = global_rtptimeout;
24166 }
24167 } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
24168 if ((sscanf(v->value, "%30d", &peer->rtpholdtimeout) != 1) || (peer->rtpholdtimeout < 0)) {
24169 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
24170 peer->rtpholdtimeout = global_rtpholdtimeout;
24171 }
24172 } else if (!strcasecmp(v->name, "rtpkeepalive")) {
24173 if ((sscanf(v->value, "%30d", &peer->rtpkeepalive) != 1) || (peer->rtpkeepalive < 0)) {
24174 ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d. Using default.\n", v->value, v->lineno);
24175 peer->rtpkeepalive = global_rtpkeepalive;
24176 }
24177 } else if (!strcasecmp(v->name, "timert1")) {
24178 if ((sscanf(v->value, "%30d", &peer->timer_t1) != 1) || (peer->timer_t1 < 0)) {
24179 ast_log(LOG_WARNING, "'%s' is not a valid T1 time at line %d. Using default.\n", v->value, v->lineno);
24180 peer->timer_t1 = global_t1;
24181 }
24182
24183
24184 if (peer->timer_b < peer->timer_t1 * 64) {
24185 peer->timer_b = peer->timer_t1 * 64;
24186 }
24187 } else if (!strcasecmp(v->name, "timerb")) {
24188 if ((sscanf(v->value, "%30d", &peer->timer_b) != 1) || (peer->timer_b < 0)) {
24189 ast_log(LOG_WARNING, "'%s' is not a valid Timer B time at line %d. Using default.\n", v->value, v->lineno);
24190 peer->timer_b = global_timer_b;
24191 }
24192 if (peer->timer_b < peer->timer_t1 * 64) {
24193 static int warning = 0;
24194 if (warning++ % 20 == 0) {
24195 ast_log(LOG_WARNING, "Timer B has been set lower than recommended. (RFC 3261, 17.1.1.2)\n");
24196 }
24197 }
24198 } else if (!strcasecmp(v->name, "setvar")) {
24199 peer->chanvars = add_var(v->value, peer->chanvars);
24200 } else if (!strcasecmp(v->name, "qualifyfreq")) {
24201 int i;
24202 if (sscanf(v->value, "%30d", &i) == 1) {
24203 peer->qualifyfreq = i * 1000;
24204 } else {
24205 ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
24206 peer->qualifyfreq = global_qualifyfreq;
24207 }
24208 } else if (!strcasecmp(v->name, "maxcallbitrate")) {
24209 peer->maxcallbitrate = atoi(v->value);
24210 if (peer->maxcallbitrate < 0) {
24211 peer->maxcallbitrate = default_maxcallbitrate;
24212 }
24213 } else if (!strcasecmp(v->name, "session-timers")) {
24214 int i = (int) str2stmode(v->value);
24215 if (i < 0) {
24216 ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
24217 peer->stimer.st_mode_oper = global_st_mode;
24218 } else {
24219 peer->stimer.st_mode_oper = i;
24220 }
24221 } else if (!strcasecmp(v->name, "session-expires")) {
24222 if (sscanf(v->value, "%30d", &peer->stimer.st_max_se) != 1) {
24223 ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
24224 peer->stimer.st_max_se = global_max_se;
24225 }
24226 } else if (!strcasecmp(v->name, "session-minse")) {
24227 if (sscanf(v->value, "%30d", &peer->stimer.st_min_se) != 1) {
24228 ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
24229 peer->stimer.st_min_se = global_min_se;
24230 }
24231 if (peer->stimer.st_min_se < 90) {
24232 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);
24233 peer->stimer.st_min_se = global_min_se;
24234 }
24235 } else if (!strcasecmp(v->name, "session-refresher")) {
24236 int i = (int) str2strefresher(v->value);
24237 if (i < 0) {
24238 ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
24239 peer->stimer.st_ref = global_st_refresher;
24240 } else {
24241 peer->stimer.st_ref = i;
24242 }
24243 }
24244 }
24245
24246
24247 if (realtime && !strcasecmp(v->name, "lastms")) {
24248 sscanf(v->value, "%30d", &peer->lastms);
24249 } else if (realtime && !strcasecmp(v->name, "ipaddr") && !ast_strlen_zero(v->value) ) {
24250 inet_aton(v->value, &(peer->addr.sin_addr));
24251 } else if (realtime && !strcasecmp(v->name, "fullcontact")) {
24252 if (alt_fullcontact && !alt) {
24253
24254
24255
24256
24257
24258 alt_fullcontact = 0;
24259 ast_str_reset(fullcontact);
24260 }
24261
24262 if (fullcontact->used > 0) {
24263 ast_str_append(&fullcontact, 0, ";%s", v->value);
24264 } else {
24265 ast_str_set(&fullcontact, 0, "%s", v->value);
24266 }
24267 } else if (!strcasecmp(v->name, "qualify")) {
24268 if (!strcasecmp(v->value, "no")) {
24269 peer->maxms = 0;
24270 } else if (!strcasecmp(v->value, "yes")) {
24271 peer->maxms = default_qualify ? default_qualify : DEFAULT_MAXMS;
24272 } else if (sscanf(v->value, "%30d", &peer->maxms) != 1) {
24273 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);
24274 peer->maxms = 0;
24275 }
24276 if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && peer->maxms > 0) {
24277
24278
24279
24280
24281 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);
24282 peer->maxms = 0;
24283 }
24284 } else if (!strcasecmp(v->name, "callcounter")) {
24285 peer->call_limit = ast_true(v->value) ? INT_MAX : 0;
24286 } else if (!strcasecmp(v->name, "call-limit")) {
24287 peer->call_limit = atoi(v->value);
24288 if (peer->call_limit < 0) {
24289 peer->call_limit = 0;
24290 }
24291 } else if (!strcasecmp(v->name, "busylevel")) {
24292 peer->busy_level = atoi(v->value);
24293 if (peer->busy_level < 0) {
24294 peer->busy_level = 0;
24295 }
24296 }
24297 }
24298
24299 if (!devstate_only) {
24300 struct sip_mailbox *mailbox;
24301 AST_LIST_TRAVERSE_SAFE_BEGIN(&peer->mailboxes, mailbox, entry) {
24302 if (mailbox->delme) {
24303 AST_LIST_REMOVE_CURRENT(entry);
24304 destroy_mailbox(mailbox);
24305 }
24306 }
24307 AST_LIST_TRAVERSE_SAFE_END;
24308 }
24309
24310 if (!peer->default_outbound_transport) {
24311
24312 peer->transports = default_transports;
24313
24314 peer->default_outbound_transport = default_primary_transport;
24315 }
24316
24317
24318
24319
24320
24321 if (((peer->socket.type != peer->default_outbound_transport) && (peer->expire == -1)) ||
24322 !(peer->socket.type & peer->transports) || !(peer->socket.type)) {
24323
24324 set_socket_transport(&peer->socket, peer->default_outbound_transport);
24325 }
24326
24327 if (port && !realtime && peer->host_dynamic) {
24328 peer->defaddr.sin_port = htons(port);
24329 } else if (port) {
24330 peer->addr.sin_port = htons(port);
24331 }
24332
24333 if (ast_str_strlen(fullcontact)) {
24334 ast_string_field_set(peer, fullcontact, ast_str_buffer(fullcontact));
24335 peer->rt_fromcontact = TRUE;
24336
24337
24338
24339
24340
24341
24342
24343
24344 if (!ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) || !peer->addr.sin_addr.s_addr) {
24345 __set_address_from_contact(fullcontact->str, &peer->addr, 0);
24346 }
24347 }
24348
24349 if (srvlookup && peer->dnsmgr == NULL) {
24350 char transport[MAXHOSTNAMELEN];
24351 char _srvlookup[MAXHOSTNAMELEN];
24352 char *params;
24353
24354 ast_copy_string(_srvlookup, srvlookup, sizeof(_srvlookup));
24355 if ((params = strchr(_srvlookup, ';'))) {
24356 *params++ = '\0';
24357 }
24358
24359 snprintf(transport, sizeof(transport), "_%s._%s", get_srv_service(peer->socket.type), get_srv_protocol(peer->socket.type));
24360
24361 if (ast_dnsmgr_lookup(_srvlookup, &peer->addr, &peer->dnsmgr, sip_cfg.srvlookup && !peer->portinuri ? transport : NULL)) {
24362 ast_log(LOG_ERROR, "srvlookup failed for host: %s, on peer %s, removing peer\n", _srvlookup, peer->name);
24363 unref_peer(peer, "getting rid of a peer pointer");
24364 return NULL;
24365 }
24366
24367 ast_string_field_set(peer, tohost, srvlookup);
24368 if (global_dynamic_exclude_static) {
24369 int err = 0;
24370 global_contact_ha = ast_append_ha("deny", (char *)ast_inet_ntoa(peer->addr.sin_addr), global_contact_ha, &err);
24371 if (err) {
24372 ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
24373 }
24374 }
24375 }
24376
24377 if (!peer->addr.sin_port) {
24378 peer->addr.sin_port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
24379 }
24380 if (!peer->defaddr.sin_port) {
24381 peer->defaddr.sin_port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
24382 }
24383 if (!peer->socket.port) {
24384 peer->socket.port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
24385 }
24386
24387 if (!sip_cfg.ignore_regexpire && peer->host_dynamic && realtime) {
24388 time_t nowtime = time(NULL);
24389
24390 if ((nowtime - regseconds) > 0) {
24391 destroy_association(peer);
24392 memset(&peer->addr, 0, sizeof(peer->addr));
24393 peer->lastms = -1;
24394 ast_debug(1, "Bah, we're expired (%d/%d/%d)!\n", (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
24395 }
24396 }
24397
24398
24399 if (!devstate_only && realtime && peer->lastms > 0) {
24400 ref_peer(peer, "schedule qualify");
24401 sip_poke_peer(peer, 0);
24402 }
24403
24404 ast_copy_flags(&peer->flags[0], &peerflags[0], mask[0].flags);
24405 ast_copy_flags(&peer->flags[1], &peerflags[1], mask[1].flags);
24406 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
24407 sip_cfg.allowsubscribe = TRUE;
24408 }
24409 if (peer->host_dynamic && !peer->is_realtime) {
24410 reg_source_db(peer);
24411 }
24412
24413
24414
24415 if (!devstate_only && !ast_test_flag(&peer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY) &&
24416 !AST_LIST_EMPTY(&peer->mailboxes)) {
24417 add_peer_mwi_subs(peer);
24418
24419
24420
24421 sip_send_mwi_to_peer(peer, NULL, 1);
24422 }
24423
24424 peer->the_mark = 0;
24425
24426 ast_free_ha(oldha);
24427 if (!ast_strlen_zero(callback)) {
24428 char *reg_string;
24429 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) {
24430 ast_log(LOG_WARNING, "asprintf() failed: %s\n", strerror(errno));
24431 } else if (reg_string) {
24432 sip_register(reg_string, 0);
24433 ast_free(reg_string);
24434 }
24435 }
24436 return peer;
24437 }
24438
24439 static int peer_markall_func(void *device, void *arg, int flags)
24440 {
24441 struct sip_peer *peer = device;
24442 peer->the_mark = 1;
24443 return 0;
24444 }
24445
24446
24447
24448
24449
24450
24451
24452 static int reload_config(enum channelreloadreason reason)
24453 {
24454 struct ast_config *cfg, *ucfg;
24455 struct ast_variable *v;
24456 struct sip_peer *peer;
24457 char *cat, *stringp, *context, *oldregcontext;
24458 char newcontexts[AST_MAX_CONTEXT], oldcontexts[AST_MAX_CONTEXT];
24459 struct ast_flags dummy[2];
24460 struct ast_flags config_flags = { reason == CHANNEL_MODULE_LOAD ? 0 : ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) ? 0 : CONFIG_FLAG_FILEUNCHANGED };
24461 int auto_sip_domains = FALSE;
24462 struct sockaddr_in old_bindaddr = bindaddr;
24463 int registry_count = 0, peer_count = 0;
24464 time_t run_start, run_end;
24465
24466 run_start = time(0);
24467 ast_unload_realtime("sipregs");
24468 ast_unload_realtime("sippeers");
24469 cfg = ast_config_load(config, config_flags);
24470
24471
24472 if (!cfg) {
24473 ast_log(LOG_NOTICE, "Unable to load config %s\n", config);
24474 return -1;
24475 } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
24476 ucfg = ast_config_load("users.conf", config_flags);
24477 if (ucfg == CONFIG_STATUS_FILEUNCHANGED) {
24478 return 1;
24479 } else if (ucfg == CONFIG_STATUS_FILEINVALID) {
24480 ast_log(LOG_ERROR, "Contents of users.conf are invalid and cannot be parsed\n");
24481 return 1;
24482 }
24483
24484 ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
24485 if ((cfg = ast_config_load(config, config_flags)) == CONFIG_STATUS_FILEINVALID) {
24486 ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed\n", config);
24487 ast_config_destroy(ucfg);
24488 return 1;
24489 }
24490 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
24491 ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed\n", config);
24492 return 1;
24493 } else {
24494 ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
24495 if ((ucfg = ast_config_load("users.conf", config_flags)) == CONFIG_STATUS_FILEINVALID) {
24496 ast_log(LOG_ERROR, "Contents of users.conf are invalid and cannot be parsed\n");
24497 ast_config_destroy(cfg);
24498 return 1;
24499 }
24500 }
24501
24502
24503 memset(&sip_tcp_desc.local_address, 0, sizeof(sip_tcp_desc.local_address));
24504 memset(&sip_tls_desc.local_address, 0, sizeof(sip_tls_desc.local_address));
24505
24506 ast_free_ha(global_contact_ha);
24507 global_contact_ha = NULL;
24508
24509 default_tls_cfg.enabled = FALSE;
24510
24511 sip_tcp_desc.local_address.sin_port = htons(STANDARD_SIP_PORT);
24512 sip_tls_desc.local_address.sin_port = htons(STANDARD_TLS_PORT);
24513
24514 if (reason != CHANNEL_MODULE_LOAD) {
24515 ast_debug(4, "--------------- SIP reload started\n");
24516
24517 clear_realm_authentication(authl);
24518 clear_sip_domains();
24519 authl = NULL;
24520
24521
24522
24523 ASTOBJ_CONTAINER_TRAVERSE(®l, 1, do {
24524
24525 ASTOBJ_RDLOCK(iterator);
24526 if (iterator->call) {
24527 ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", iterator->username, iterator->hostname);
24528
24529 dialog_unlink_all(iterator->call, TRUE, TRUE);
24530 iterator->call = dialog_unref(iterator->call, "remove iterator->call from registry traversal");
24531 }
24532 if (iterator->expire > -1) {
24533 AST_SCHED_DEL_UNREF(sched, iterator->expire, registry_unref(iterator, "reg ptr unref from reload config"));
24534 }
24535 if (iterator->timeout > -1) {
24536 AST_SCHED_DEL_UNREF(sched, iterator->timeout, registry_unref(iterator, "reg ptr unref from reload config"));
24537 }
24538 ASTOBJ_UNLOCK(iterator);
24539
24540 } while(0));
24541
24542
24543 ASTOBJ_CONTAINER_DESTROYALL(®l, sip_registry_destroy);
24544 ast_debug(4, "--------------- Done destroying registry list\n");
24545 ao2_t_callback(peers, OBJ_NODATA, peer_markall_func, NULL, "callback to mark all peers");
24546 }
24547
24548
24549 if (reason != CHANNEL_MODULE_LOAD) {
24550 ast_free(default_tls_cfg.certfile);
24551 ast_free(default_tls_cfg.cipher);
24552 ast_free(default_tls_cfg.cafile);
24553 ast_free(default_tls_cfg.capath);
24554 }
24555 default_tls_cfg.certfile = ast_strdup(AST_CERTFILE);
24556 default_tls_cfg.cipher = ast_strdup("");
24557 default_tls_cfg.cafile = ast_strdup("");
24558 default_tls_cfg.capath = ast_strdup("");
24559
24560
24561
24562 ast_copy_string(oldcontexts, global_regcontext, sizeof(oldcontexts));
24563 oldregcontext = oldcontexts;
24564
24565
24566
24567 sipdebug &= sip_debug_console;
24568 ast_clear_flag(&global_flags[0], AST_FLAGS_ALL);
24569 ast_clear_flag(&global_flags[1], AST_FLAGS_ALL);
24570
24571
24572 memset(&bindaddr, 0, sizeof(bindaddr));
24573 memset(&stunaddr, 0, sizeof(stunaddr));
24574 memset(&internip, 0, sizeof(internip));
24575
24576
24577 ast_free_ha(localaddr);
24578 memset(&localaddr, 0, sizeof(localaddr));
24579 memset(&externip, 0, sizeof(externip));
24580 memset(&default_prefs, 0 , sizeof(default_prefs));
24581 memset(&sip_cfg.outboundproxy, 0, sizeof(struct sip_proxy));
24582 sip_cfg.outboundproxy.ip.sin_port = htons(STANDARD_SIP_PORT);
24583 sip_cfg.outboundproxy.ip.sin_family = AF_INET;
24584 sip_cfg.outboundproxy.force = FALSE;
24585 default_transports = 0;
24586 default_primary_transport = 0;
24587 ourport_tcp = STANDARD_SIP_PORT;
24588 ourport_tls = STANDARD_TLS_PORT;
24589 bindaddr.sin_port = htons(STANDARD_SIP_PORT);
24590 sip_cfg.srvlookup = DEFAULT_SRVLOOKUP;
24591 global_tos_sip = DEFAULT_TOS_SIP;
24592 global_tos_audio = DEFAULT_TOS_AUDIO;
24593 global_tos_video = DEFAULT_TOS_VIDEO;
24594 global_tos_text = DEFAULT_TOS_TEXT;
24595 global_cos_sip = DEFAULT_COS_SIP;
24596 global_cos_audio = DEFAULT_COS_AUDIO;
24597 global_cos_video = DEFAULT_COS_VIDEO;
24598 global_cos_text = DEFAULT_COS_TEXT;
24599
24600 externhost[0] = '\0';
24601 externexpire = 0;
24602 externrefresh = 10;
24603
24604
24605 sip_cfg.allow_external_domains = DEFAULT_ALLOW_EXT_DOM;
24606 global_regcontext[0] = '\0';
24607 sip_cfg.regextenonqualify = DEFAULT_REGEXTENONQUALIFY;
24608 sip_cfg.notifyringing = DEFAULT_NOTIFYRINGING;
24609 sip_cfg.notifycid = DEFAULT_NOTIFYCID;
24610 sip_cfg.notifyhold = FALSE;
24611 sip_cfg.directrtpsetup = FALSE;
24612 sip_cfg.alwaysauthreject = DEFAULT_ALWAYSAUTHREJECT;
24613 sip_cfg.allowsubscribe = FALSE;
24614 snprintf(global_useragent, sizeof(global_useragent), "%s %s", DEFAULT_USERAGENT, ast_get_version());
24615 snprintf(global_sdpsession, sizeof(global_sdpsession), "%s %s", DEFAULT_SDPSESSION, ast_get_version());
24616 snprintf(global_sdpowner, sizeof(global_sdpowner), "%s", DEFAULT_SDPOWNER);
24617 global_prematuremediafilter = TRUE;
24618 ast_copy_string(default_notifymime, DEFAULT_NOTIFYMIME, sizeof(default_notifymime));
24619 ast_copy_string(sip_cfg.realm, S_OR(ast_config_AST_SYSTEM_NAME, DEFAULT_REALM), sizeof(sip_cfg.realm));
24620 ast_copy_string(default_callerid, DEFAULT_CALLERID, sizeof(default_callerid));
24621 sip_cfg.compactheaders = DEFAULT_COMPACTHEADERS;
24622 global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
24623 global_regattempts_max = 0;
24624 sip_cfg.pedanticsipchecking = DEFAULT_PEDANTIC;
24625 sip_cfg.autocreatepeer = DEFAULT_AUTOCREATEPEER;
24626 global_autoframing = 0;
24627 sip_cfg.allowguest = DEFAULT_ALLOWGUEST;
24628 global_callcounter = DEFAULT_CALLCOUNTER;
24629 global_match_auth_username = FALSE;
24630 global_rtptimeout = 0;
24631 global_rtpholdtimeout = 0;
24632 global_rtpkeepalive = DEFAULT_RTPKEEPALIVE;
24633 sip_cfg.allowtransfer = TRANSFER_OPENFORALL;
24634 sip_cfg.rtautoclear = 120;
24635 ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE);
24636 ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP);
24637 sip_cfg.peer_rtupdate = TRUE;
24638 global_dynamic_exclude_static = 0;
24639
24640
24641 global_st_mode = SESSION_TIMER_MODE_ACCEPT;
24642 global_st_refresher = SESSION_TIMER_REFRESHER_UAS;
24643 global_min_se = DEFAULT_MIN_SE;
24644 global_max_se = DEFAULT_MAX_SE;
24645
24646
24647 global_qualify_gap = DEFAULT_QUALIFY_GAP;
24648 global_qualify_peers = DEFAULT_QUALIFY_PEERS;
24649
24650
24651 ast_copy_string(sip_cfg.default_context, DEFAULT_CONTEXT, sizeof(sip_cfg.default_context));
24652 sip_cfg.default_subscribecontext[0] = '\0';
24653 default_language[0] = '\0';
24654 default_fromdomain[0] = '\0';
24655 default_qualify = DEFAULT_QUALIFY;
24656 default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
24657 ast_copy_string(default_mohinterpret, DEFAULT_MOHINTERPRET, sizeof(default_mohinterpret));
24658 ast_copy_string(default_mohsuggest, DEFAULT_MOHSUGGEST, sizeof(default_mohsuggest));
24659 ast_copy_string(default_vmexten, DEFAULT_VMEXTEN, sizeof(default_vmexten));
24660 ast_set_flag(&global_flags[0], SIP_DTMF_RFC2833);
24661 ast_set_flag(&global_flags[0], SIP_NAT_RFC3581);
24662 ast_set_flag(&global_flags[0], SIP_DIRECT_MEDIA);
24663 ast_set_flag(&global_flags[1], SIP_PAGE2_FORWARD_LOOP_DETECTED);
24664
24665
24666 dumphistory = FALSE;
24667 recordhistory = FALSE;
24668 sipdebug &= ~sip_debug_config;
24669
24670
24671 global_relaxdtmf = FALSE;
24672 sip_cfg.callevents = DEFAULT_CALLEVENTS;
24673 global_authfailureevents = FALSE;
24674 global_t1 = DEFAULT_TIMER_T1;
24675 global_timer_b = 64 * DEFAULT_TIMER_T1;
24676 global_t1min = DEFAULT_T1MIN;
24677 global_qualifyfreq = DEFAULT_QUALIFYFREQ;
24678 global_t38_maxdatagram = -1;
24679 global_shrinkcallerid = 1;
24680
24681 sip_cfg.matchexterniplocally = DEFAULT_MATCHEXTERNIPLOCALLY;
24682
24683
24684 memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
24685
24686 ast_clear_flag(&global_flags[1], SIP_PAGE2_FAX_DETECT);
24687 ast_clear_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT | SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
24688 ast_clear_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT);
24689 ast_clear_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION);
24690
24691
24692
24693 for (v = ast_variable_browse(cfg, "general"); v; v = v->next) {
24694 if (handle_common_options(&global_flags[0], &dummy[0], v))
24695 continue;
24696 if (handle_t38_options(&global_flags[0], &dummy[0], v, &global_t38_maxdatagram)) {
24697 continue;
24698 }
24699
24700 if (!ast_jb_read_conf(&global_jbconf, v->name, v->value))
24701 continue;
24702
24703 if (!strcasecmp(v->name, "context")) {
24704 ast_copy_string(sip_cfg.default_context, v->value, sizeof(sip_cfg.default_context));
24705 } else if (!strcasecmp(v->name, "subscribecontext")) {
24706 ast_copy_string(sip_cfg.default_subscribecontext, v->value, sizeof(sip_cfg.default_subscribecontext));
24707 } else if (!strcasecmp(v->name, "callcounter")) {
24708 global_callcounter = ast_true(v->value) ? 1 : 0;
24709 } else if (!strcasecmp(v->name, "allowguest")) {
24710 sip_cfg.allowguest = ast_true(v->value) ? 1 : 0;
24711 } else if (!strcasecmp(v->name, "realm")) {
24712 ast_copy_string(sip_cfg.realm, v->value, sizeof(sip_cfg.realm));
24713 } else if (!strcasecmp(v->name, "useragent")) {
24714 ast_copy_string(global_useragent, v->value, sizeof(global_useragent));
24715 ast_debug(1, "Setting SIP channel User-Agent Name to %s\n", global_useragent);
24716 } else if (!strcasecmp(v->name, "sdpsession")) {
24717 ast_copy_string(global_sdpsession, v->value, sizeof(global_sdpsession));
24718 } else if (!strcasecmp(v->name, "sdpowner")) {
24719
24720 if (!strstr(v->value, " "))
24721 ast_copy_string(global_sdpowner, v->value, sizeof(global_sdpowner));
24722 else
24723 ast_log(LOG_WARNING, "'%s' must not contain spaces at line %d. Using default.\n", v->value, v->lineno);
24724 } else if (!strcasecmp(v->name, "allowtransfer")) {
24725 sip_cfg.allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
24726 } else if (!strcasecmp(v->name, "rtcachefriends")) {
24727 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTCACHEFRIENDS);
24728 } else if (!strcasecmp(v->name, "rtsavesysname")) {
24729 sip_cfg.rtsave_sysname = ast_true(v->value);
24730 } else if (!strcasecmp(v->name, "rtupdate")) {
24731 sip_cfg.peer_rtupdate = ast_true(v->value);
24732 } else if (!strcasecmp(v->name, "ignoreregexpire")) {
24733 sip_cfg.ignore_regexpire = ast_true(v->value);
24734 } else if (!strcasecmp(v->name, "timert1")) {
24735
24736
24737
24738 global_t1 = atoi(v->value);
24739
24740 global_timer_b = global_t1 * 64;
24741 } else if (!strcasecmp(v->name, "t1min")) {
24742 global_t1min = atoi(v->value);
24743 } else if (!strcasecmp(v->name, "transport") && !ast_strlen_zero(v->value)) {
24744 char *val = ast_strdupa(v->value);
24745 char *trans;
24746
24747 while ((trans = strsep(&val, ","))) {
24748 trans = ast_skip_blanks(trans);
24749
24750 if (!strncasecmp(trans, "udp", 3))
24751 default_transports |= SIP_TRANSPORT_UDP;
24752 else if (!strncasecmp(trans, "tcp", 3))
24753 default_transports |= SIP_TRANSPORT_TCP;
24754 else if (!strncasecmp(trans, "tls", 3))
24755 default_transports |= SIP_TRANSPORT_TLS;
24756 else
24757 ast_log(LOG_NOTICE, "'%s' is not a valid transport type. if no other is specified, udp will be used.\n", trans);
24758 if (default_primary_transport == 0) {
24759 default_primary_transport = default_transports;
24760 }
24761 }
24762 } else if (!strcasecmp(v->name, "tcpenable")) {
24763 sip_tcp_desc.local_address.sin_family = ast_false(v->value) ? 0 : AF_INET;
24764 ast_debug(2, "Enabling TCP socket for listening\n");
24765 } else if (!strcasecmp(v->name, "tcpbindaddr")) {
24766 int family = sip_tcp_desc.local_address.sin_family;
24767 if (ast_parse_arg(v->value, PARSE_INADDR, &sip_tcp_desc.local_address))
24768 ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n", v->name, v->value, v->lineno, config);
24769 sip_tcp_desc.local_address.sin_family = family;
24770 ast_debug(2, "Setting TCP socket address to %s\n", v->value);
24771 } else if (!strcasecmp(v->name, "tlsenable")) {
24772 default_tls_cfg.enabled = ast_true(v->value) ? TRUE : FALSE;
24773 sip_tls_desc.local_address.sin_family = AF_INET;
24774 } else if (!strcasecmp(v->name, "tlscertfile")) {
24775 ast_free(default_tls_cfg.certfile);
24776 default_tls_cfg.certfile = ast_strdup(v->value);
24777 } else if (!strcasecmp(v->name, "tlscipher")) {
24778 ast_free(default_tls_cfg.cipher);
24779 default_tls_cfg.cipher = ast_strdup(v->value);
24780 } else if (!strcasecmp(v->name, "tlscafile")) {
24781 ast_free(default_tls_cfg.cafile);
24782 default_tls_cfg.cafile = ast_strdup(v->value);
24783 } else if (!strcasecmp(v->name, "tlscapath")) {
24784 ast_free(default_tls_cfg.capath);
24785 default_tls_cfg.capath = ast_strdup(v->value);
24786 } else if (!strcasecmp(v->name, "tlsverifyclient")) {
24787 ast_set2_flag(&default_tls_cfg.flags, ast_true(v->value), AST_SSL_VERIFY_CLIENT);
24788 } else if (!strcasecmp(v->name, "tlsdontverifyserver")) {
24789 ast_set2_flag(&default_tls_cfg.flags, ast_true(v->value), AST_SSL_DONT_VERIFY_SERVER);
24790 } else if (!strcasecmp(v->name, "tlsbindaddr")) {
24791 if (ast_parse_arg(v->value, PARSE_INADDR, &sip_tls_desc.local_address))
24792 ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n", v->name, v->value, v->lineno, config);
24793 } else if (!strcasecmp(v->name, "dynamic_exclude_static") || !strcasecmp(v->name, "dynamic_excludes_static")) {
24794 global_dynamic_exclude_static = ast_true(v->value);
24795 } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny")) {
24796 int ha_error = 0;
24797 global_contact_ha = ast_append_ha(v->name + 7, v->value, global_contact_ha, &ha_error);
24798 if (ha_error) {
24799 ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
24800 }
24801 } else if (!strcasecmp(v->name, "rtautoclear")) {
24802 int i = atoi(v->value);
24803 if (i > 0)
24804 sip_cfg.rtautoclear = i;
24805 else
24806 i = 0;
24807 ast_set2_flag(&global_flags[1], i || ast_true(v->value), SIP_PAGE2_RTAUTOCLEAR);
24808 } else if (!strcasecmp(v->name, "usereqphone")) {
24809 ast_set2_flag(&global_flags[0], ast_true(v->value), SIP_USEREQPHONE);
24810 } else if (!strcasecmp(v->name, "prematuremedia")) {
24811 global_prematuremediafilter = ast_true(v->value);
24812 } else if (!strcasecmp(v->name, "relaxdtmf")) {
24813 global_relaxdtmf = ast_true(v->value);
24814 } else if (!strcasecmp(v->name, "vmexten")) {
24815 ast_copy_string(default_vmexten, v->value, sizeof(default_vmexten));
24816 } else if (!strcasecmp(v->name, "rtptimeout")) {
24817 if ((sscanf(v->value, "%30d", &global_rtptimeout) != 1) || (global_rtptimeout < 0)) {
24818 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
24819 global_rtptimeout = 0;
24820 }
24821 } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
24822 if ((sscanf(v->value, "%30d", &global_rtpholdtimeout) != 1) || (global_rtpholdtimeout < 0)) {
24823 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
24824 global_rtpholdtimeout = 0;
24825 }
24826 } else if (!strcasecmp(v->name, "rtpkeepalive")) {
24827 if ((sscanf(v->value, "%30d", &global_rtpkeepalive) != 1) || (global_rtpkeepalive < 0)) {
24828 ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d. Using default.\n", v->value, v->lineno);
24829 global_rtpkeepalive = DEFAULT_RTPKEEPALIVE;
24830 }
24831 } else if (!strcasecmp(v->name, "compactheaders")) {
24832 sip_cfg.compactheaders = ast_true(v->value);
24833 } else if (!strcasecmp(v->name, "notifymimetype")) {
24834 ast_copy_string(default_notifymime, v->value, sizeof(default_notifymime));
24835 } else if (!strcasecmp(v->name, "directrtpsetup")) {
24836 sip_cfg.directrtpsetup = ast_true(v->value);
24837 } else if (!strcasecmp(v->name, "notifyringing")) {
24838 sip_cfg.notifyringing = ast_true(v->value);
24839 } else if (!strcasecmp(v->name, "notifyhold")) {
24840 sip_cfg.notifyhold = ast_true(v->value);
24841 } else if (!strcasecmp(v->name, "notifycid")) {
24842 if (!strcasecmp(v->value, "ignore-context")) {
24843 sip_cfg.notifycid = IGNORE_CONTEXT;
24844 } else {
24845 sip_cfg.notifycid = ast_true(v->value);
24846 }
24847 } else if (!strcasecmp(v->name, "alwaysauthreject")) {
24848 sip_cfg.alwaysauthreject = ast_true(v->value);
24849 } else if (!strcasecmp(v->name, "mohinterpret")) {
24850 ast_copy_string(default_mohinterpret, v->value, sizeof(default_mohinterpret));
24851 } else if (!strcasecmp(v->name, "mohsuggest")) {
24852 ast_copy_string(default_mohsuggest, v->value, sizeof(default_mohsuggest));
24853 } else if (!strcasecmp(v->name, "language")) {
24854 ast_copy_string(default_language, v->value, sizeof(default_language));
24855 } else if (!strcasecmp(v->name, "regcontext")) {
24856 ast_copy_string(newcontexts, v->value, sizeof(newcontexts));
24857 stringp = newcontexts;
24858
24859 cleanup_stale_contexts(stringp, oldregcontext);
24860
24861 while ((context = strsep(&stringp, "&"))) {
24862 ast_copy_string(used_context, context, sizeof(used_context));
24863 ast_context_find_or_create(NULL, NULL, context, "SIP");
24864 }
24865 ast_copy_string(global_regcontext, v->value, sizeof(global_regcontext));
24866 } else if (!strcasecmp(v->name, "regextenonqualify")) {
24867 sip_cfg.regextenonqualify = ast_true(v->value);
24868 } else if (!strcasecmp(v->name, "callerid")) {
24869 ast_copy_string(default_callerid, v->value, sizeof(default_callerid));
24870 } else if (!strcasecmp(v->name, "fromdomain")) {
24871 ast_copy_string(default_fromdomain, v->value, sizeof(default_fromdomain));
24872 } else if (!strcasecmp(v->name, "outboundproxy")) {
24873 int portnum;
24874 char *tok, *proxyname;
24875
24876 if (ast_strlen_zero(v->value)) {
24877 ast_log(LOG_WARNING, "no value given for outbound proxy on line %d of sip.conf.", v->lineno);
24878 continue;
24879 }
24880
24881 tok = ast_skip_blanks(strtok(ast_strdupa(v->value), ","));
24882
24883 sip_parse_host(tok, v->lineno, &proxyname, &portnum, &sip_cfg.outboundproxy.transport);
24884
24885 sip_cfg.outboundproxy.ip.sin_port = htons(portnum);
24886
24887 if ((tok = strtok(NULL, ","))) {
24888 sip_cfg.outboundproxy.force = !strncasecmp(ast_skip_blanks(tok), "force", 5);
24889 } else {
24890 sip_cfg.outboundproxy.force = FALSE;
24891 }
24892
24893 if (ast_strlen_zero(proxyname)) {
24894 ast_log(LOG_WARNING, "you must specify a name for the outboundproxy on line %d of sip.conf.", v->lineno);
24895 sip_cfg.outboundproxy.name[0] = '\0';
24896 continue;
24897 }
24898
24899 ast_copy_string(sip_cfg.outboundproxy.name, proxyname, sizeof(sip_cfg.outboundproxy.name));
24900
24901 proxy_update(&sip_cfg.outboundproxy);
24902 } else if (!strcasecmp(v->name, "autocreatepeer")) {
24903 sip_cfg.autocreatepeer = ast_true(v->value);
24904 } else if (!strcasecmp(v->name, "match_auth_username")) {
24905 global_match_auth_username = ast_true(v->value);
24906 } else if (!strcasecmp(v->name, "srvlookup")) {
24907 sip_cfg.srvlookup = ast_true(v->value);
24908 } else if (!strcasecmp(v->name, "pedantic")) {
24909 sip_cfg.pedanticsipchecking = ast_true(v->value);
24910 } else if (!strcasecmp(v->name, "maxexpirey") || !strcasecmp(v->name, "maxexpiry")) {
24911 max_expiry = atoi(v->value);
24912 if (max_expiry < 1)
24913 max_expiry = DEFAULT_MAX_EXPIRY;
24914 } else if (!strcasecmp(v->name, "minexpirey") || !strcasecmp(v->name, "minexpiry")) {
24915 min_expiry = atoi(v->value);
24916 if (min_expiry < 1)
24917 min_expiry = DEFAULT_MIN_EXPIRY;
24918 } else if (!strcasecmp(v->name, "defaultexpiry") || !strcasecmp(v->name, "defaultexpirey")) {
24919 default_expiry = atoi(v->value);
24920 if (default_expiry < 1)
24921 default_expiry = DEFAULT_DEFAULT_EXPIRY;
24922 } else if (!strcasecmp(v->name, "mwiexpiry") || !strcasecmp(v->name, "mwiexpirey")) {
24923 mwi_expiry = atoi(v->value);
24924 if (mwi_expiry < 1)
24925 mwi_expiry = DEFAULT_MWI_EXPIRY;
24926 } else if (!strcasecmp(v->name, "sipdebug")) {
24927 if (ast_true(v->value))
24928 sipdebug |= sip_debug_config;
24929 } else if (!strcasecmp(v->name, "dumphistory")) {
24930 dumphistory = ast_true(v->value);
24931 } else if (!strcasecmp(v->name, "recordhistory")) {
24932 recordhistory = ast_true(v->value);
24933 } else if (!strcasecmp(v->name, "registertimeout")) {
24934 global_reg_timeout = atoi(v->value);
24935 if (global_reg_timeout < 1)
24936 global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
24937 } else if (!strcasecmp(v->name, "registerattempts")) {
24938 global_regattempts_max = atoi(v->value);
24939 } else if (!strcasecmp(v->name, "stunaddr")) {
24940 stunaddr.sin_port = htons(3478);
24941 if (ast_parse_arg(v->value, PARSE_INADDR, &stunaddr))
24942 ast_log(LOG_WARNING, "Invalid STUN server address: %s\n", v->value);
24943 externexpire = time(NULL);
24944 } else if (!strcasecmp(v->name, "bindaddr") || !strcasecmp(v->name, "udpbindaddr")) {
24945 if (ast_parse_arg(v->value, PARSE_INADDR, &bindaddr))
24946 ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
24947 } else if (!strcasecmp(v->name, "localnet")) {
24948 struct ast_ha *na;
24949 int ha_error = 0;
24950
24951 if (!(na = ast_append_ha("d", v->value, localaddr, &ha_error)))
24952 ast_log(LOG_WARNING, "Invalid localnet value: %s\n", v->value);
24953 else
24954 localaddr = na;
24955 if (ha_error)
24956 ast_log(LOG_ERROR, "Bad localnet configuration value line %d : %s\n", v->lineno, v->value);
24957 } else if (!strcasecmp(v->name, "externip")) {
24958 if (ast_parse_arg(v->value, PARSE_INADDR, &externip))
24959 ast_log(LOG_WARNING, "Invalid address for externip keyword: %s\n", v->value);
24960 externexpire = 0;
24961
24962 if (!externip.sin_port)
24963 externip.sin_port = bindaddr.sin_port;
24964 } else if (!strcasecmp(v->name, "externhost")) {
24965 ast_copy_string(externhost, v->value, sizeof(externhost));
24966 if (ast_parse_arg(externhost, PARSE_INADDR, &externip))
24967 ast_log(LOG_WARNING, "Invalid address for externhost keyword: %s\n", externhost);
24968 externexpire = time(NULL);
24969
24970 if (!externip.sin_port)
24971 externip.sin_port = bindaddr.sin_port;
24972 } else if (!strcasecmp(v->name, "externrefresh")) {
24973 if (sscanf(v->value, "%30d", &externrefresh) != 1) {
24974 ast_log(LOG_WARNING, "Invalid externrefresh value '%s', must be an integer >0 at line %d\n", v->value, v->lineno);
24975 externrefresh = 10;
24976 }
24977 } else if (!strcasecmp(v->name, "allow")) {
24978 int error = ast_parse_allow_disallow(&default_prefs, &global_capability, v->value, TRUE);
24979 if (error)
24980 ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
24981 } else if (!strcasecmp(v->name, "disallow")) {
24982 int error = ast_parse_allow_disallow(&default_prefs, &global_capability, v->value, FALSE);
24983 if (error)
24984 ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
24985 } else if (!strcasecmp(v->name, "autoframing")) {
24986 global_autoframing = ast_true(v->value);
24987 } else if (!strcasecmp(v->name, "allowexternaldomains")) {
24988 sip_cfg.allow_external_domains = ast_true(v->value);
24989 } else if (!strcasecmp(v->name, "autodomain")) {
24990 auto_sip_domains = ast_true(v->value);
24991 } else if (!strcasecmp(v->name, "domain")) {
24992 char *domain = ast_strdupa(v->value);
24993 char *cntx = strchr(domain, ',');
24994
24995 if (cntx)
24996 *cntx++ = '\0';
24997
24998 if (ast_strlen_zero(cntx))
24999 ast_debug(1, "No context specified at line %d for domain '%s'\n", v->lineno, domain);
25000 if (ast_strlen_zero(domain))
25001 ast_log(LOG_WARNING, "Empty domain specified at line %d\n", v->lineno);
25002 else
25003 add_sip_domain(ast_strip(domain), SIP_DOMAIN_CONFIG, cntx ? ast_strip(cntx) : "");
25004 } else if (!strcasecmp(v->name, "register")) {
25005 if (sip_register(v->value, v->lineno) == 0)
25006 registry_count++;
25007 } else if (!strcasecmp(v->name, "mwi")) {
25008 sip_subscribe_mwi(v->value, v->lineno);
25009 } else if (!strcasecmp(v->name, "tos_sip")) {
25010 if (ast_str2tos(v->value, &global_tos_sip))
25011 ast_log(LOG_WARNING, "Invalid tos_sip value at line %d, refer to QoS documentation\n", v->lineno);
25012 } else if (!strcasecmp(v->name, "tos_audio")) {
25013 if (ast_str2tos(v->value, &global_tos_audio))
25014 ast_log(LOG_WARNING, "Invalid tos_audio value at line %d, refer to QoS documentation\n", v->lineno);
25015 } else if (!strcasecmp(v->name, "tos_video")) {
25016 if (ast_str2tos(v->value, &global_tos_video))
25017 ast_log(LOG_WARNING, "Invalid tos_video value at line %d, refer to QoS documentation\n", v->lineno);
25018 } else if (!strcasecmp(v->name, "tos_text")) {
25019 if (ast_str2tos(v->value, &global_tos_text))
25020 ast_log(LOG_WARNING, "Invalid tos_text value at line %d, refer to QoS documentation\n", v->lineno);
25021 } else if (!strcasecmp(v->name, "cos_sip")) {
25022 if (ast_str2cos(v->value, &global_cos_sip))
25023 ast_log(LOG_WARNING, "Invalid cos_sip value at line %d, refer to QoS documentation\n", v->lineno);
25024 } else if (!strcasecmp(v->name, "cos_audio")) {
25025 if (ast_str2cos(v->value, &global_cos_audio))
25026 ast_log(LOG_WARNING, "Invalid cos_audio value at line %d, refer to QoS documentation\n", v->lineno);
25027 } else if (!strcasecmp(v->name, "cos_video")) {
25028 if (ast_str2cos(v->value, &global_cos_video))
25029 ast_log(LOG_WARNING, "Invalid cos_video value at line %d, refer to QoS documentation\n", v->lineno);
25030 } else if (!strcasecmp(v->name, "cos_text")) {
25031 if (ast_str2cos(v->value, &global_cos_text))
25032 ast_log(LOG_WARNING, "Invalid cos_text value at line %d, refer to QoS documentation\n", v->lineno);
25033 } else if (!strcasecmp(v->name, "bindport")) {
25034 int i;
25035 if (sscanf(v->value, "%5d", &i) == 1) {
25036 bindaddr.sin_port = htons(i);
25037 } else {
25038 ast_log(LOG_WARNING, "Invalid port number '%s' at line %d of %s\n", v->value, v->lineno, config);
25039 }
25040 } else if (!strcasecmp(v->name, "qualify")) {
25041 if (!strcasecmp(v->value, "no")) {
25042 default_qualify = 0;
25043 } else if (!strcasecmp(v->value, "yes")) {
25044 default_qualify = DEFAULT_MAXMS;
25045 } else if (sscanf(v->value, "%30d", &default_qualify) != 1) {
25046 ast_log(LOG_WARNING, "Qualification default should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", v->lineno);
25047 default_qualify = 0;
25048 }
25049 } else if (!strcasecmp(v->name, "qualifyfreq")) {
25050 int i;
25051 if (sscanf(v->value, "%30d", &i) == 1)
25052 global_qualifyfreq = i * 1000;
25053 else {
25054 ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
25055 global_qualifyfreq = DEFAULT_QUALIFYFREQ;
25056 }
25057 } else if (!strcasecmp(v->name, "callevents")) {
25058 sip_cfg.callevents = ast_true(v->value);
25059 } else if (!strcasecmp(v->name, "authfailureevents")) {
25060 global_authfailureevents = ast_true(v->value);
25061 } else if (!strcasecmp(v->name, "maxcallbitrate")) {
25062 default_maxcallbitrate = atoi(v->value);
25063 if (default_maxcallbitrate < 0)
25064 default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
25065 } else if (!strcasecmp(v->name, "matchexterniplocally")) {
25066 sip_cfg.matchexterniplocally = ast_true(v->value);
25067 } else if (!strcasecmp(v->name, "session-timers")) {
25068 int i = (int) str2stmode(v->value);
25069 if (i < 0) {
25070 ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
25071 global_st_mode = SESSION_TIMER_MODE_ACCEPT;
25072 } else {
25073 global_st_mode = i;
25074 }
25075 } else if (!strcasecmp(v->name, "session-expires")) {
25076 if (sscanf(v->value, "%30d", &global_max_se) != 1) {
25077 ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
25078 global_max_se = DEFAULT_MAX_SE;
25079 }
25080 } else if (!strcasecmp(v->name, "session-minse")) {
25081 if (sscanf(v->value, "%30d", &global_min_se) != 1) {
25082 ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
25083 global_min_se = DEFAULT_MIN_SE;
25084 }
25085 if (global_min_se < 90) {
25086 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);
25087 global_min_se = DEFAULT_MIN_SE;
25088 }
25089 } else if (!strcasecmp(v->name, "session-refresher")) {
25090 int i = (int) str2strefresher(v->value);
25091 if (i < 0) {
25092 ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
25093 global_st_refresher = SESSION_TIMER_REFRESHER_UAS;
25094 } else {
25095 global_st_refresher = i;
25096 }
25097 } else if (!strcasecmp(v->name, "qualifygap")) {
25098 if (sscanf(v->value, "%30d", &global_qualify_gap) != 1) {
25099 ast_log(LOG_WARNING, "Invalid qualifygap '%s' at line %d of %s\n", v->value, v->lineno, config);
25100 global_qualify_gap = DEFAULT_QUALIFY_GAP;
25101 }
25102 } else if (!strcasecmp(v->name, "qualifypeers")) {
25103 if (sscanf(v->value, "%30d", &global_qualify_peers) != 1) {
25104 ast_log(LOG_WARNING, "Invalid pokepeers '%s' at line %d of %s\n", v->value, v->lineno, config);
25105 global_qualify_peers = DEFAULT_QUALIFY_PEERS;
25106 }
25107 } else if (!strcasecmp(v->name, "shrinkcallerid")) {
25108 if (ast_true(v->value)) {
25109 global_shrinkcallerid = 1;
25110 } else if (ast_false(v->value)) {
25111 global_shrinkcallerid = 0;
25112 } else {
25113 ast_log(LOG_WARNING, "shrinkcallerid value %s is not valid at line %d.\n", v->value, v->lineno);
25114 }
25115 }
25116 }
25117
25118 if (!sip_cfg.allow_external_domains && AST_LIST_EMPTY(&domain_list)) {
25119 ast_log(LOG_WARNING, "To disallow external domains, you need to configure local SIP domains.\n");
25120 sip_cfg.allow_external_domains = 1;
25121 }
25122
25123 if (default_transports == 0) {
25124 default_transports = default_primary_transport = SIP_TRANSPORT_UDP;
25125 }
25126
25127
25128 for (v = ast_variable_browse(cfg, "authentication"); v ; v = v->next) {
25129
25130 if (!strcasecmp(v->name, "auth"))
25131 authl = add_realm_authentication(authl, v->value, v->lineno);
25132 }
25133
25134
25135 bindaddr.sin_family = AF_INET;
25136 internip = bindaddr;
25137 if (ast_find_ourip(&internip.sin_addr, bindaddr)) {
25138 ast_log(LOG_WARNING, "Unable to get own IP address, SIP disabled\n");
25139 ast_config_destroy(cfg);
25140 return 0;
25141 }
25142
25143 ast_mutex_lock(&netlock);
25144 if ((sipsock > -1) && (memcmp(&old_bindaddr, &bindaddr, sizeof(struct sockaddr_in)))) {
25145 close(sipsock);
25146 sipsock = -1;
25147 }
25148 if (sipsock < 0) {
25149 sipsock = socket(AF_INET, SOCK_DGRAM, 0);
25150 if (sipsock < 0) {
25151 ast_log(LOG_WARNING, "Unable to create SIP socket: %s\n", strerror(errno));
25152 ast_config_destroy(cfg);
25153 return -1;
25154 } else {
25155
25156 const int reuseFlag = 1;
25157
25158 setsockopt(sipsock, SOL_SOCKET, SO_REUSEADDR,
25159 (const char*)&reuseFlag,
25160 sizeof reuseFlag);
25161
25162 ast_enable_packet_fragmentation(sipsock);
25163
25164 if (bind(sipsock, (struct sockaddr *)&bindaddr, sizeof(bindaddr)) < 0) {
25165 ast_log(LOG_WARNING, "Failed to bind to %s:%d: %s\n",
25166 ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port),
25167 strerror(errno));
25168 close(sipsock);
25169 sipsock = -1;
25170 } else {
25171 ast_verb(2, "SIP Listening on %s:%d\n",
25172 ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port));
25173 ast_netsock_set_qos(sipsock, global_tos_sip, global_cos_sip, "SIP");
25174 }
25175 }
25176 } else {
25177 ast_netsock_set_qos(sipsock, global_tos_sip, global_cos_sip, "SIP");
25178 }
25179 if (stunaddr.sin_addr.s_addr != 0) {
25180 ast_debug(1, "stun to %s:%d\n",
25181 ast_inet_ntoa(stunaddr.sin_addr) , ntohs(stunaddr.sin_port));
25182 ast_stun_request(sipsock, &stunaddr,
25183 NULL, &externip);
25184 ast_debug(1, "STUN sees us at %s:%d\n",
25185 ast_inet_ntoa(externip.sin_addr) , ntohs(externip.sin_port));
25186 }
25187 ast_mutex_unlock(&netlock);
25188
25189
25190 ast_tcptls_server_start(&sip_tcp_desc);
25191 if (sip_tcp_desc.accept_fd == -1 && sip_tcp_desc.local_address.sin_family == AF_INET) {
25192
25193 ast_log(LOG_ERROR, "SIP TCP Server start failed. Not listening on TCP socket.\n");
25194 sip_tcp_desc.local_address.sin_family = 0;
25195 } else {
25196 ast_debug(2, "SIP TCP server started\n");
25197 }
25198
25199
25200 memcpy(sip_tls_desc.tls_cfg, &default_tls_cfg, sizeof(default_tls_cfg));
25201
25202 if (ast_ssl_setup(sip_tls_desc.tls_cfg)) {
25203 ast_tcptls_server_start(&sip_tls_desc);
25204 if (default_tls_cfg.enabled && sip_tls_desc.accept_fd == -1) {
25205 ast_log(LOG_ERROR, "TLS Server start failed. Not listening on TLS socket.\n");
25206 sip_tls_desc.tls_cfg = NULL;
25207 }
25208 } else if (sip_tls_desc.tls_cfg->enabled) {
25209 sip_tls_desc.tls_cfg = NULL;
25210 ast_log(LOG_WARNING, "SIP TLS server did not load because of errors.\n");
25211 }
25212
25213 if (ucfg) {
25214 struct ast_variable *gen;
25215 int genhassip, genregistersip;
25216 const char *hassip, *registersip;
25217
25218 genhassip = ast_true(ast_variable_retrieve(ucfg, "general", "hassip"));
25219 genregistersip = ast_true(ast_variable_retrieve(ucfg, "general", "registersip"));
25220 gen = ast_variable_browse(ucfg, "general");
25221 cat = ast_category_browse(ucfg, NULL);
25222 while (cat) {
25223 if (strcasecmp(cat, "general")) {
25224 hassip = ast_variable_retrieve(ucfg, cat, "hassip");
25225 registersip = ast_variable_retrieve(ucfg, cat, "registersip");
25226 if (ast_true(hassip) || (!hassip && genhassip)) {
25227 peer = build_peer(cat, gen, ast_variable_browse(ucfg, cat), 0, 0);
25228 if (peer) {
25229
25230 peer->type = SIP_TYPE_USER | SIP_TYPE_PEER;
25231 ao2_t_link(peers, peer, "link peer into peer table");
25232 if ((peer->type & SIP_TYPE_PEER) && peer->addr.sin_addr.s_addr) {
25233 ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
25234 }
25235
25236 unref_peer(peer, "unref_peer: from reload_config");
25237 peer_count++;
25238 }
25239 }
25240 if (ast_true(registersip) || (!registersip && genregistersip)) {
25241 char tmp[256];
25242 const char *host = ast_variable_retrieve(ucfg, cat, "host");
25243 const char *username = ast_variable_retrieve(ucfg, cat, "username");
25244 const char *secret = ast_variable_retrieve(ucfg, cat, "secret");
25245 const char *contact = ast_variable_retrieve(ucfg, cat, "contact");
25246 const char *authuser = ast_variable_retrieve(ucfg, cat, "authuser");
25247 if (!host)
25248 host = ast_variable_retrieve(ucfg, "general", "host");
25249 if (!username)
25250 username = ast_variable_retrieve(ucfg, "general", "username");
25251 if (!secret)
25252 secret = ast_variable_retrieve(ucfg, "general", "secret");
25253 if (!contact)
25254 contact = "s";
25255 if (!ast_strlen_zero(username) && !ast_strlen_zero(host)) {
25256 if (!ast_strlen_zero(secret)) {
25257 if (!ast_strlen_zero(authuser)) {
25258 snprintf(tmp, sizeof(tmp), "%s?%s:%s:%s@%s/%s", cat, username, secret, authuser, host, contact);
25259 } else {
25260 snprintf(tmp, sizeof(tmp), "%s?%s:%s@%s/%s", cat, username, secret, host, contact);
25261 }
25262 } else if (!ast_strlen_zero(authuser)) {
25263 snprintf(tmp, sizeof(tmp), "%s?%s::%s@%s/%s", cat, username, authuser, host, contact);
25264 } else {
25265 snprintf(tmp, sizeof(tmp), "%s?%s@%s/%s", cat, username, host, contact);
25266 }
25267 if (sip_register(tmp, 0) == 0)
25268 registry_count++;
25269 }
25270 }
25271 }
25272 cat = ast_category_browse(ucfg, cat);
25273 }
25274 ast_config_destroy(ucfg);
25275 }
25276
25277
25278 cat = NULL;
25279 while ( (cat = ast_category_browse(cfg, cat)) ) {
25280 const char *utype;
25281 if (!strcasecmp(cat, "general") || !strcasecmp(cat, "authentication"))
25282 continue;
25283 utype = ast_variable_retrieve(cfg, cat, "type");
25284 if (!utype) {
25285 ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
25286 continue;
25287 } else {
25288 if (!strcasecmp(utype, "user")) {
25289 ;
25290 } else if (!strcasecmp(utype, "friend")) {
25291 ;
25292 } else if (!strcasecmp(utype, "peer")) {
25293 ;
25294 } else {
25295 ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, "sip.conf");
25296 continue;
25297 }
25298 peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0, 0);
25299 if (peer) {
25300 ao2_t_link(peers, peer, "link peer into peers table");
25301 if ((peer->type & SIP_TYPE_PEER) && peer->addr.sin_addr.s_addr) {
25302 ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
25303 }
25304 unref_peer(peer, "unref the result of the build_peer call. Now, the links from the tables are the only ones left.");
25305 peer_count++;
25306 }
25307 }
25308 }
25309
25310
25311
25312
25313
25314
25315 if (auto_sip_domains) {
25316 char temp[MAXHOSTNAMELEN];
25317
25318
25319 if (bindaddr.sin_addr.s_addr) {
25320 add_sip_domain(ast_inet_ntoa(bindaddr.sin_addr), SIP_DOMAIN_AUTO, NULL);
25321 } else if (internip.sin_addr.s_addr) {
25322
25323 add_sip_domain(ast_inet_ntoa(internip.sin_addr), SIP_DOMAIN_AUTO, NULL);
25324 } else {
25325 ast_log(LOG_NOTICE, "Can't add wildcard IP address to domain list, please add IP address to domain manually.\n");
25326 }
25327
25328
25329 if (sip_tcp_desc.local_address.sin_addr.s_addr && !inaddrcmp(&bindaddr, &sip_tcp_desc.local_address))
25330 add_sip_domain(ast_inet_ntoa(sip_tcp_desc.local_address.sin_addr), SIP_DOMAIN_AUTO, NULL);
25331
25332
25333 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))
25334 add_sip_domain(ast_inet_ntoa(sip_tls_desc.local_address.sin_addr), SIP_DOMAIN_AUTO, NULL);
25335
25336
25337 if (externip.sin_addr.s_addr)
25338 add_sip_domain(ast_inet_ntoa(externip.sin_addr), SIP_DOMAIN_AUTO, NULL);
25339
25340
25341 if (!ast_strlen_zero(externhost))
25342 add_sip_domain(externhost, SIP_DOMAIN_AUTO, NULL);
25343
25344
25345 if (!gethostname(temp, sizeof(temp)))
25346 add_sip_domain(temp, SIP_DOMAIN_AUTO, NULL);
25347 }
25348
25349
25350 ast_config_destroy(cfg);
25351
25352
25353 if (notify_types)
25354 ast_config_destroy(notify_types);
25355 if ((notify_types = ast_config_load(notify_config, config_flags)) == CONFIG_STATUS_FILEINVALID) {
25356 ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed.\n", notify_config);
25357 notify_types = NULL;
25358 }
25359
25360
25361 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);
25362 run_end = time(0);
25363 ast_debug(4, "SIP reload_config done...Runtime= %d sec\n", (int)(run_end-run_start));
25364
25365 return 0;
25366 }
25367
25368 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan)
25369 {
25370 struct sip_pvt *p;
25371 struct ast_udptl *udptl = NULL;
25372
25373 p = chan->tech_pvt;
25374 if (!p)
25375 return NULL;
25376
25377 sip_pvt_lock(p);
25378 if (p->udptl && ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA))
25379 udptl = p->udptl;
25380 sip_pvt_unlock(p);
25381 return udptl;
25382 }
25383
25384 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl)
25385 {
25386 struct sip_pvt *p;
25387
25388 p = chan->tech_pvt;
25389 if (!p)
25390 return -1;
25391 sip_pvt_lock(p);
25392 if (udptl)
25393 ast_udptl_get_peer(udptl, &p->udptlredirip);
25394 else
25395 memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
25396 if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
25397 if (!p->pendinginvite) {
25398 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);
25399 transmit_reinvite_with_sdp(p, TRUE, FALSE);
25400 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
25401 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);
25402 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
25403 }
25404 }
25405
25406 p->lastrtprx = p->lastrtptx = time(NULL);
25407 sip_pvt_unlock(p);
25408 return 0;
25409 }
25410
25411
25412 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
25413 {
25414 struct sip_pvt *p = NULL;
25415 enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
25416
25417 if (!(p = chan->tech_pvt))
25418 return AST_RTP_GET_FAILED;
25419
25420 sip_pvt_lock(p);
25421 if (!(p->rtp)) {
25422 sip_pvt_unlock(p);
25423 return AST_RTP_GET_FAILED;
25424 }
25425
25426 *rtp = p->rtp;
25427
25428 if (ast_rtp_getnat(*rtp) && !ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA_NAT))
25429 res = AST_RTP_TRY_PARTIAL;
25430 else if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA))
25431 res = AST_RTP_TRY_NATIVE;
25432 else if (ast_test_flag(&global_jbconf, AST_JB_FORCED))
25433 res = AST_RTP_GET_FAILED;
25434
25435 sip_pvt_unlock(p);
25436
25437 return res;
25438 }
25439
25440
25441 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
25442 {
25443 struct sip_pvt *p = NULL;
25444 enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
25445
25446 if (!(p = chan->tech_pvt))
25447 return AST_RTP_GET_FAILED;
25448
25449 sip_pvt_lock(p);
25450 if (!(p->vrtp)) {
25451 sip_pvt_unlock(p);
25452 return AST_RTP_GET_FAILED;
25453 }
25454
25455 *rtp = p->vrtp;
25456
25457 if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA))
25458 res = AST_RTP_TRY_NATIVE;
25459
25460 sip_pvt_unlock(p);
25461
25462 return res;
25463 }
25464
25465
25466 static enum ast_rtp_get_result sip_get_trtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
25467 {
25468 struct sip_pvt *p = NULL;
25469 enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
25470
25471 if (!(p = chan->tech_pvt))
25472 return AST_RTP_GET_FAILED;
25473
25474 sip_pvt_lock(p);
25475 if (!(p->trtp)) {
25476 sip_pvt_unlock(p);
25477 return AST_RTP_GET_FAILED;
25478 }
25479
25480 *rtp = p->trtp;
25481
25482 if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA))
25483 res = AST_RTP_TRY_NATIVE;
25484
25485 sip_pvt_unlock(p);
25486
25487 return res;
25488 }
25489
25490
25491 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)
25492 {
25493 struct sip_pvt *p;
25494 int changed = 0;
25495
25496 p = chan->tech_pvt;
25497 if (!p)
25498 return -1;
25499
25500
25501 if (!ast_bridged_channel(chan) && !sip_cfg.directrtpsetup)
25502 return 0;
25503
25504 sip_pvt_lock(p);
25505 if (p->alreadygone) {
25506
25507 sip_pvt_unlock(p);
25508 return 0;
25509 }
25510
25511
25512
25513
25514 if (nat_active && !ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA_NAT)) {
25515 sip_pvt_unlock(p);
25516 return 0;
25517 }
25518
25519 if (rtp) {
25520 changed |= ast_rtp_get_peer(rtp, &p->redirip);
25521 } else if (p->redirip.sin_addr.s_addr || ntohs(p->redirip.sin_port) != 0) {
25522 memset(&p->redirip, 0, sizeof(p->redirip));
25523 changed = 1;
25524 }
25525 if (vrtp) {
25526 changed |= ast_rtp_get_peer(vrtp, &p->vredirip);
25527 } else if (p->vredirip.sin_addr.s_addr || ntohs(p->vredirip.sin_port) != 0) {
25528 memset(&p->vredirip, 0, sizeof(p->vredirip));
25529 changed = 1;
25530 }
25531 if (trtp) {
25532 changed |= ast_rtp_get_peer(trtp, &p->tredirip);
25533 } else if (p->tredirip.sin_addr.s_addr || ntohs(p->tredirip.sin_port) != 0) {
25534 memset(&p->tredirip, 0, sizeof(p->tredirip));
25535 changed = 1;
25536 }
25537 if (codecs && (p->redircodecs != codecs)) {
25538 p->redircodecs = codecs;
25539 changed = 1;
25540 }
25541 if (changed && !ast_test_flag(&p->flags[0], SIP_GOTREFER) && !ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
25542 if (chan->_state != AST_STATE_UP) {
25543 if (p->do_history)
25544 append_history(p, "ExtInv", "Initial invite sent with remote bridge proposal.");
25545 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));
25546 } else if (!p->pendinginvite) {
25547 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));
25548 transmit_reinvite_with_sdp(p, FALSE, FALSE);
25549 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
25550 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));
25551
25552 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
25553 }
25554 }
25555
25556 p->lastrtprx = p->lastrtptx = time(NULL);
25557 sip_pvt_unlock(p);
25558 return 0;
25559 }
25560
25561 static char *app_dtmfmode = "SIPDtmfMode";
25562 static char *app_sipaddheader = "SIPAddHeader";
25563 static char *app_sipremoveheader = "SIPRemoveHeader";
25564
25565
25566 static int sip_dtmfmode(struct ast_channel *chan, void *data)
25567 {
25568 struct sip_pvt *p;
25569 char *mode = data;
25570
25571 if (!data) {
25572 ast_log(LOG_WARNING, "This application requires the argument: info, inband, rfc2833\n");
25573 return 0;
25574 }
25575 ast_channel_lock(chan);
25576 if (!IS_SIP_TECH(chan->tech)) {
25577 ast_log(LOG_WARNING, "Call this application only on SIP incoming calls\n");
25578 ast_channel_unlock(chan);
25579 return 0;
25580 }
25581 p = chan->tech_pvt;
25582 if (!p) {
25583 ast_channel_unlock(chan);
25584 return 0;
25585 }
25586 sip_pvt_lock(p);
25587 if (!strcasecmp(mode, "info")) {
25588 ast_clear_flag(&p->flags[0], SIP_DTMF);
25589 ast_set_flag(&p->flags[0], SIP_DTMF_INFO);
25590 p->jointnoncodeccapability &= ~AST_RTP_DTMF;
25591 } else if (!strcasecmp(mode, "shortinfo")) {
25592 ast_clear_flag(&p->flags[0], SIP_DTMF);
25593 ast_set_flag(&p->flags[0], SIP_DTMF_SHORTINFO);
25594 p->jointnoncodeccapability &= ~AST_RTP_DTMF;
25595 } else if (!strcasecmp(mode, "rfc2833")) {
25596 ast_clear_flag(&p->flags[0], SIP_DTMF);
25597 ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
25598 p->jointnoncodeccapability |= AST_RTP_DTMF;
25599 } else if (!strcasecmp(mode, "inband")) {
25600 ast_clear_flag(&p->flags[0], SIP_DTMF);
25601 ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
25602 p->jointnoncodeccapability &= ~AST_RTP_DTMF;
25603 } else
25604 ast_log(LOG_WARNING, "I don't know about this dtmf mode: %s\n", mode);
25605 if (p->rtp)
25606 ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
25607 if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
25608 if (!p->dsp) {
25609 p->dsp = ast_dsp_new();
25610 ast_dsp_set_features(p->dsp, DSP_FEATURE_DIGIT_DETECT);
25611 }
25612 } else {
25613 if (p->dsp) {
25614 ast_dsp_free(p->dsp);
25615 p->dsp = NULL;
25616 }
25617 }
25618 sip_pvt_unlock(p);
25619 ast_channel_unlock(chan);
25620 return 0;
25621 }
25622
25623
25624 static int sip_addheader(struct ast_channel *chan, void *data)
25625 {
25626 int no = 0;
25627 int ok = FALSE;
25628 char varbuf[30];
25629 char *inbuf = data, *subbuf;
25630
25631 if (ast_strlen_zero(inbuf)) {
25632 ast_log(LOG_WARNING, "This application requires the argument: Header\n");
25633 return 0;
25634 }
25635 ast_channel_lock(chan);
25636
25637
25638 while (!ok && no <= 50) {
25639 no++;
25640 snprintf(varbuf, sizeof(varbuf), "__SIPADDHEADER%.2d", no);
25641
25642
25643 if ((pbx_builtin_getvar_helper(chan, (const char *) varbuf + 2) == (const char *) NULL)) {
25644 ok = TRUE;
25645 }
25646 }
25647 if (ok) {
25648 size_t len = strlen(inbuf);
25649 subbuf = alloca(len + 1);
25650 ast_get_encoded_str(inbuf, subbuf, len + 1);
25651 pbx_builtin_setvar_helper(chan, varbuf, subbuf);
25652 if (sipdebug) {
25653 ast_debug(1, "SIP Header added \"%s\" as %s\n", inbuf, varbuf);
25654 }
25655 } else {
25656 ast_log(LOG_WARNING, "Too many SIP headers added, max 50\n");
25657 }
25658 ast_channel_unlock(chan);
25659 return 0;
25660 }
25661
25662
25663 static int sip_removeheader(struct ast_channel *chan, void *data)
25664 {
25665 struct ast_var_t *newvariable;
25666 struct varshead *headp;
25667 int removeall = 0;
25668 char *inbuf = (char *) data;
25669
25670 if (ast_strlen_zero(inbuf)) {
25671 removeall = 1;
25672 }
25673 ast_channel_lock(chan);
25674
25675 headp=&chan->varshead;
25676 AST_LIST_TRAVERSE_SAFE_BEGIN (headp, newvariable, entries) {
25677 if (strncasecmp(ast_var_name(newvariable), "SIPADDHEADER", strlen("SIPADDHEADER")) == 0) {
25678 if (removeall || (!strncasecmp(ast_var_value(newvariable),inbuf,strlen(inbuf)))) {
25679 if (sipdebug)
25680 ast_log(LOG_DEBUG,"removing SIP Header \"%s\" as %s\n",
25681 ast_var_value(newvariable),
25682 ast_var_name(newvariable));
25683 AST_LIST_REMOVE_CURRENT(entries);
25684 ast_var_delete(newvariable);
25685 }
25686 }
25687 }
25688 AST_LIST_TRAVERSE_SAFE_END;
25689
25690 ast_channel_unlock(chan);
25691 return 0;
25692 }
25693
25694
25695
25696
25697
25698
25699
25700 static int sip_sipredirect(struct sip_pvt *p, const char *dest)
25701 {
25702 char *cdest;
25703 char *extension, *host, *port;
25704 char tmp[80];
25705
25706 cdest = ast_strdupa(dest);
25707
25708 extension = strsep(&cdest, "@");
25709 host = strsep(&cdest, ":");
25710 port = strsep(&cdest, ":");
25711 if (ast_strlen_zero(extension)) {
25712 ast_log(LOG_ERROR, "Missing mandatory argument: extension\n");
25713 return 0;
25714 }
25715
25716
25717 if (!host) {
25718 char *localtmp;
25719
25720 ast_copy_string(tmp, get_header(&p->initreq, "To"), sizeof(tmp));
25721 if (ast_strlen_zero(tmp)) {
25722 ast_log(LOG_ERROR, "Cannot retrieve the 'To' header from the original SIP request!\n");
25723 return 0;
25724 }
25725 if ( ( (localtmp = strcasestr(tmp, "sip:")) || (localtmp = strcasestr(tmp, "sips:")) )
25726 && (localtmp = strchr(localtmp, '@'))) {
25727 char lhost[80], lport[80];
25728
25729 memset(lhost, 0, sizeof(lhost));
25730 memset(lport, 0, sizeof(lport));
25731 localtmp++;
25732
25733 sscanf(localtmp, "%80[^<>:; ]:%80[^<>:; ]", lhost, lport);
25734 if (ast_strlen_zero(lhost)) {
25735 ast_log(LOG_ERROR, "Can't find the host address\n");
25736 return 0;
25737 }
25738 host = ast_strdupa(lhost);
25739 if (!ast_strlen_zero(lport)) {
25740 port = ast_strdupa(lport);
25741 }
25742 }
25743 }
25744
25745 ast_string_field_build(p, our_contact, "Transfer <sip:%s@%s%s%s>", extension, host, port ? ":" : "", port ? port : "");
25746 transmit_response_reliable(p, "302 Moved Temporarily", &p->initreq);
25747
25748 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
25749 sip_alreadygone(p);
25750
25751 return 0;
25752 }
25753
25754
25755 static int sip_get_codec(struct ast_channel *chan)
25756 {
25757 struct sip_pvt *p = chan->tech_pvt;
25758 return p->jointcapability ? p->jointcapability : p->capability;
25759 }
25760
25761
25762 static void sip_poke_all_peers(void)
25763 {
25764 int ms = 0, num = 0;
25765 struct ao2_iterator i;
25766 struct sip_peer *peer;
25767
25768 if (!speerobjs)
25769 return;
25770
25771 i = ao2_iterator_init(peers, 0);
25772 while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
25773 ao2_lock(peer);
25774 if (num == global_qualify_peers) {
25775 ms += global_qualify_gap;
25776 num = 0;
25777 } else {
25778 num++;
25779 }
25780 AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, ms, sip_poke_peer_s, peer,
25781 unref_peer(_data, "removing poke peer ref"),
25782 unref_peer(peer, "removing poke peer ref"),
25783 ref_peer(peer, "adding poke peer ref"));
25784 ao2_unlock(peer);
25785 unref_peer(peer, "toss iterator peer ptr");
25786 }
25787 ao2_iterator_destroy(&i);
25788 }
25789
25790
25791 static void sip_send_all_registers(void)
25792 {
25793 int ms;
25794 int regspacing;
25795 if (!regobjs)
25796 return;
25797 regspacing = default_expiry * 1000/regobjs;
25798 if (regspacing > 100)
25799 regspacing = 100;
25800 ms = regspacing;
25801 ASTOBJ_CONTAINER_TRAVERSE(®l, 1, do {
25802 ASTOBJ_WRLOCK(iterator);
25803 ms += regspacing;
25804 AST_SCHED_REPLACE_UNREF(iterator->expire, sched, ms, sip_reregister, iterator,
25805 registry_unref(_data, "REPLACE sched del decs the refcount"),
25806 registry_unref(iterator, "REPLACE sched add failure decs the refcount"),
25807 registry_addref(iterator, "REPLACE sched add incs the refcount"));
25808 ASTOBJ_UNLOCK(iterator);
25809 } while (0)
25810 );
25811 }
25812
25813
25814 static void sip_send_all_mwi_subscriptions(void)
25815 {
25816 ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
25817 ASTOBJ_WRLOCK(iterator);
25818 AST_SCHED_DEL(sched, iterator->resub);
25819 if ((iterator->resub = ast_sched_add(sched, 1, sip_subscribe_mwi_do, ASTOBJ_REF(iterator))) < 0) {
25820 ASTOBJ_UNREF(iterator, sip_subscribe_mwi_destroy);
25821 }
25822 ASTOBJ_UNLOCK(iterator);
25823 } while (0));
25824 }
25825
25826
25827 static int sip_do_reload(enum channelreloadreason reason)
25828 {
25829 time_t start_poke, end_poke;
25830
25831 reload_config(reason);
25832 ast_sched_dump(sched);
25833
25834 start_poke = time(0);
25835
25836 unlink_marked_peers_from_tables();
25837
25838 ast_debug(4, "--------------- Done destroying pruned peers\n");
25839
25840
25841 sip_poke_all_peers();
25842
25843
25844 sip_send_all_registers();
25845
25846 sip_send_all_mwi_subscriptions();
25847
25848 end_poke = time(0);
25849
25850 ast_debug(4, "do_reload finished. peer poke/prune reg contact time = %d sec.\n", (int)(end_poke-start_poke));
25851
25852 ast_debug(4, "--------------- SIP reload done\n");
25853
25854 return 0;
25855 }
25856
25857
25858 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
25859 {
25860
25861 switch (cmd) {
25862 case CLI_INIT:
25863 e->command = "sip reload";
25864 e->usage =
25865 "Usage: sip reload\n"
25866 " Reloads SIP configuration from sip.conf\n";
25867 return NULL;
25868 case CLI_GENERATE:
25869 return NULL;
25870 }
25871
25872 ast_mutex_lock(&sip_reload_lock);
25873 if (sip_reloading)
25874 ast_verbose("Previous SIP reload not yet done\n");
25875 else {
25876 sip_reloading = TRUE;
25877 sip_reloadreason = (a && a->fd) ? CHANNEL_CLI_RELOAD : CHANNEL_MODULE_RELOAD;
25878 }
25879 ast_mutex_unlock(&sip_reload_lock);
25880 restart_monitor();
25881
25882 return CLI_SUCCESS;
25883 }
25884
25885
25886 static int reload(void)
25887 {
25888 if (sip_reload(0, 0, NULL))
25889 return 0;
25890 return 1;
25891 }
25892
25893
25894 static struct ast_cli_entry cli_sip[] = {
25895 AST_CLI_DEFINE(sip_show_channels, "List active SIP channels or subscriptions"),
25896 AST_CLI_DEFINE(sip_show_channelstats, "List statistics for active SIP channels"),
25897 AST_CLI_DEFINE(sip_show_domains, "List our local SIP domains"),
25898 AST_CLI_DEFINE(sip_show_inuse, "List all inuse/limits"),
25899 AST_CLI_DEFINE(sip_show_objects, "List all SIP object allocations"),
25900 AST_CLI_DEFINE(sip_show_peers, "List defined SIP peers"),
25901 AST_CLI_DEFINE(sip_show_registry, "List SIP registration status"),
25902 AST_CLI_DEFINE(sip_unregister, "Unregister (force expiration) a SIP peer from the registry"),
25903 AST_CLI_DEFINE(sip_show_settings, "Show SIP global settings"),
25904 AST_CLI_DEFINE(sip_show_mwi, "Show MWI subscriptions"),
25905 AST_CLI_DEFINE(sip_cli_notify, "Send a notify packet to a SIP peer"),
25906 AST_CLI_DEFINE(sip_show_channel, "Show detailed SIP channel info"),
25907 AST_CLI_DEFINE(sip_show_history, "Show SIP dialog history"),
25908 AST_CLI_DEFINE(sip_show_peer, "Show details on specific SIP peer"),
25909 AST_CLI_DEFINE(sip_show_users, "List defined SIP users"),
25910 AST_CLI_DEFINE(sip_show_user, "Show details on specific SIP user"),
25911 AST_CLI_DEFINE(sip_qualify_peer, "Send an OPTIONS packet to a peer"),
25912 AST_CLI_DEFINE(sip_show_sched, "Present a report on the status of the sched queue"),
25913 AST_CLI_DEFINE(sip_prune_realtime, "Prune cached Realtime users/peers"),
25914 AST_CLI_DEFINE(sip_do_debug, "Enable/Disable SIP debugging"),
25915 AST_CLI_DEFINE(sip_set_history, "Enable/Disable SIP history"),
25916 AST_CLI_DEFINE(sip_reload, "Reload SIP configuration"),
25917 AST_CLI_DEFINE(sip_show_tcp, "List TCP Connections")
25918 };
25919
25920
25921 static int load_module(void)
25922 {
25923 ast_verbose("SIP channel loading...\n");
25924
25925
25926 peers = ao2_t_container_alloc(HASH_PEER_SIZE, peer_hash_cb, peer_cmp_cb, "allocate peers");
25927 peers_by_ip = ao2_t_container_alloc(HASH_PEER_SIZE, peer_iphash_cb, peer_ipcmp_cb, "allocate peers_by_ip");
25928 dialogs = ao2_t_container_alloc(HASH_DIALOG_SIZE, dialog_hash_cb, dialog_cmp_cb, "allocate dialogs");
25929 threadt = ao2_t_container_alloc(HASH_DIALOG_SIZE, threadt_hash_cb, threadt_cmp_cb, "allocate threadt table");
25930
25931 ASTOBJ_CONTAINER_INIT(®l);
25932 ASTOBJ_CONTAINER_INIT(&submwil);
25933
25934 if (!(sched = sched_context_create())) {
25935 ast_log(LOG_ERROR, "Unable to create scheduler context\n");
25936 return AST_MODULE_LOAD_FAILURE;
25937 }
25938
25939 if (!(io = io_context_create())) {
25940 ast_log(LOG_ERROR, "Unable to create I/O context\n");
25941 sched_context_destroy(sched);
25942 return AST_MODULE_LOAD_FAILURE;
25943 }
25944
25945 sip_reloadreason = CHANNEL_MODULE_LOAD;
25946
25947 if(reload_config(sip_reloadreason))
25948 return AST_MODULE_LOAD_DECLINE;
25949
25950
25951
25952
25953
25954 memcpy(&sip_tech_info, &sip_tech, sizeof(sip_tech));
25955 memset((void *) &sip_tech_info.send_digit_begin, 0, sizeof(sip_tech_info.send_digit_begin));
25956
25957
25958 if (ast_channel_register(&sip_tech)) {
25959 ast_log(LOG_ERROR, "Unable to register channel type 'SIP'\n");
25960 io_context_destroy(io);
25961 sched_context_destroy(sched);
25962 return AST_MODULE_LOAD_FAILURE;
25963 }
25964
25965
25966 ast_cli_register_multiple(cli_sip, ARRAY_LEN(cli_sip));
25967
25968
25969 ast_rtp_proto_register(&sip_rtp);
25970
25971
25972 ast_udptl_proto_register(&sip_udptl);
25973
25974
25975 ast_register_application_xml(app_dtmfmode, sip_dtmfmode);
25976 ast_register_application_xml(app_sipaddheader, sip_addheader);
25977 ast_register_application_xml(app_sipremoveheader, sip_removeheader);
25978
25979
25980 ast_custom_function_register(&sip_header_function);
25981 ast_custom_function_register(&sippeer_function);
25982 ast_custom_function_register(&sipchaninfo_function);
25983 ast_custom_function_register(&checksipdomain_function);
25984
25985
25986 ast_manager_register2("SIPpeers", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peers,
25987 "List SIP peers (text format)", mandescr_show_peers);
25988 ast_manager_register2("SIPshowpeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peer,
25989 "Show SIP peer (text format)", mandescr_show_peer);
25990 ast_manager_register2("SIPqualifypeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_qualify_peer,
25991 "Show SIP peer (text format)", mandescr_show_peer);
25992 ast_manager_register2("SIPshowregistry", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_show_registry,
25993 "Show SIP registrations (text format)", mandescr_show_registry);
25994 ast_manager_register2("SIPnotify", EVENT_FLAG_SYSTEM, manager_sipnotify,
25995 "Send a SIP notify", mandescr_sipnotify);
25996 sip_poke_all_peers();
25997 sip_send_all_registers();
25998 sip_send_all_mwi_subscriptions();
25999
26000
26001 restart_monitor();
26002
26003 ast_realtime_require_field(ast_check_realtime("sipregs") ? "sipregs" : "sippeers",
26004 "name", RQ_CHAR, 10,
26005 "ipaddr", RQ_CHAR, 15,
26006 "port", RQ_UINTEGER2, 5,
26007 "regseconds", RQ_INTEGER4, 11,
26008 "defaultuser", RQ_CHAR, 10,
26009 "fullcontact", RQ_CHAR, 35,
26010 "regserver", RQ_CHAR, 20,
26011 "useragent", RQ_CHAR, 20,
26012 "lastms", RQ_INTEGER4, 11,
26013 SENTINEL);
26014
26015 return AST_MODULE_LOAD_SUCCESS;
26016 }
26017
26018
26019 static int unload_module(void)
26020 {
26021 struct sip_pvt *p;
26022 struct sip_threadinfo *th;
26023 struct ast_context *con;
26024 struct ao2_iterator i;
26025
26026 ast_sched_dump(sched);
26027
26028
26029 ast_channel_unregister(&sip_tech);
26030
26031
26032 ast_custom_function_unregister(&sipchaninfo_function);
26033 ast_custom_function_unregister(&sippeer_function);
26034 ast_custom_function_unregister(&sip_header_function);
26035 ast_custom_function_unregister(&checksipdomain_function);
26036
26037
26038 ast_unregister_application(app_dtmfmode);
26039 ast_unregister_application(app_sipaddheader);
26040 ast_unregister_application(app_sipremoveheader);
26041
26042
26043 ast_cli_unregister_multiple(cli_sip, ARRAY_LEN(cli_sip));
26044
26045
26046 ast_rtp_proto_unregister(&sip_rtp);
26047
26048
26049 ast_udptl_proto_unregister(&sip_udptl);
26050
26051
26052 ast_manager_unregister("SIPpeers");
26053 ast_manager_unregister("SIPshowpeer");
26054 ast_manager_unregister("SIPqualifypeer");
26055 ast_manager_unregister("SIPshowregistry");
26056 ast_manager_unregister("SIPnotify");
26057
26058
26059 if (sip_tcp_desc.master)
26060 ast_tcptls_server_stop(&sip_tcp_desc);
26061 if (sip_tls_desc.master)
26062 ast_tcptls_server_stop(&sip_tls_desc);
26063
26064
26065 i = ao2_iterator_init(threadt, 0);
26066 while ((th = ao2_t_iterator_next(&i, "iterate through tcp threads for 'sip show tcp'"))) {
26067 pthread_t thread = th->threadid;
26068 th->stop = 1;
26069 pthread_kill(thread, SIGURG);
26070 pthread_join(thread, NULL);
26071 ao2_t_ref(th, -1, "decrement ref from iterator");
26072 }
26073 ao2_iterator_destroy(&i);
26074
26075
26076 i = ao2_iterator_init(dialogs, 0);
26077 while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
26078 if (p->owner)
26079 ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
26080 ao2_t_ref(p, -1, "toss dialog ptr from iterator_next");
26081 }
26082 ao2_iterator_destroy(&i);
26083
26084 ast_mutex_lock(&monlock);
26085 if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP) && (monitor_thread != AST_PTHREADT_NULL)) {
26086 pthread_cancel(monitor_thread);
26087 pthread_kill(monitor_thread, SIGURG);
26088 pthread_join(monitor_thread, NULL);
26089 }
26090 monitor_thread = AST_PTHREADT_STOP;
26091 ast_mutex_unlock(&monlock);
26092
26093
26094 i = ao2_iterator_init(dialogs, 0);
26095 while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
26096 dialog_unlink_all(p, TRUE, TRUE);
26097 ao2_t_ref(p, -1, "throw away iterator result");
26098 }
26099 ao2_iterator_destroy(&i);
26100
26101
26102 ast_free_ha(localaddr);
26103
26104 clear_realm_authentication(authl);
26105
26106
26107 if (default_tls_cfg.certfile)
26108 ast_free(default_tls_cfg.certfile);
26109 if (default_tls_cfg.cipher)
26110 ast_free(default_tls_cfg.cipher);
26111 if (default_tls_cfg.cafile)
26112 ast_free(default_tls_cfg.cafile);
26113 if (default_tls_cfg.capath)
26114 ast_free(default_tls_cfg.capath);
26115
26116 ASTOBJ_CONTAINER_DESTROYALL(®l, sip_registry_destroy);
26117 ASTOBJ_CONTAINER_DESTROY(®l);
26118 ASTOBJ_CONTAINER_DESTROYALL(&submwil, sip_subscribe_mwi_destroy);
26119 ASTOBJ_CONTAINER_DESTROY(&submwil);
26120
26121 ao2_t_ref(peers, -1, "unref the peers table");
26122 ao2_t_ref(peers_by_ip, -1, "unref the peers_by_ip table");
26123 ao2_t_ref(dialogs, -1, "unref the dialogs table");
26124 ao2_t_ref(threadt, -1, "unref the thread table");
26125
26126 clear_sip_domains();
26127 ast_free_ha(global_contact_ha);
26128 close(sipsock);
26129 sched_context_destroy(sched);
26130 con = ast_context_find(used_context);
26131 if (con)
26132 ast_context_destroy(con, "SIP");
26133 ast_unload_realtime("sipregs");
26134 ast_unload_realtime("sippeers");
26135
26136 return 0;
26137 }
26138
26139 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Session Initiation Protocol (SIP)",
26140 .load = load_module,
26141 .unload = unload_module,
26142 .reload = reload,
26143 );