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: 277563 $")
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
03110
03111
03112
03113 static void *unref_peer(struct sip_peer *peer, char *tag)
03114 {
03115 ao2_t_ref(peer, -1, tag);
03116 return NULL;
03117 }
03118
03119 static struct sip_peer *ref_peer(struct sip_peer *peer, char *tag)
03120 {
03121 ao2_t_ref(peer, 1, tag);
03122 return peer;
03123 }
03124
03125
03126
03127
03128
03129
03130
03131
03132
03133
03134
03135
03136 static void ref_proxy(struct sip_pvt *pvt, struct sip_proxy *proxy)
03137 {
03138 struct sip_proxy *old_obproxy = pvt->outboundproxy;
03139
03140
03141
03142 if (proxy && proxy != &sip_cfg.outboundproxy) {
03143 ao2_ref(proxy, +1);
03144 }
03145 pvt->outboundproxy = proxy;
03146 if (old_obproxy && old_obproxy != &sip_cfg.outboundproxy) {
03147 ao2_ref(old_obproxy, -1);
03148 }
03149 }
03150
03151
03152
03153
03154
03155
03156
03157
03158 static void *dialog_unlink_all(struct sip_pvt *dialog, int lockowner, int lockdialoglist)
03159 {
03160 struct sip_pkt *cp;
03161
03162 dialog_ref(dialog, "Let's bump the count in the unlink so it doesn't accidentally become dead before we are done");
03163
03164 ao2_t_unlink(dialogs, dialog, "unlinking dialog via ao2_unlink");
03165
03166
03167 if (dialog->owner) {
03168 if (lockowner)
03169 ast_channel_lock(dialog->owner);
03170 ast_debug(1, "Detaching from channel %s\n", dialog->owner->name);
03171 dialog->owner->tech_pvt = dialog_unref(dialog->owner->tech_pvt, "resetting channel dialog ptr in unlink_all");
03172 if (lockowner)
03173 ast_channel_unlock(dialog->owner);
03174 }
03175 if (dialog->registry) {
03176 if (dialog->registry->call == dialog)
03177 dialog->registry->call = dialog_unref(dialog->registry->call, "nulling out the registry's call dialog field in unlink_all");
03178 dialog->registry = registry_unref(dialog->registry, "delete dialog->registry");
03179 }
03180 if (dialog->stateid > -1) {
03181 ast_extension_state_del(dialog->stateid, NULL);
03182 dialog_unref(dialog, "removing extension_state, should unref the associated dialog ptr that was stored there.");
03183 dialog->stateid = -1;
03184 }
03185
03186 if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog)
03187 dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
03188 if (dialog->relatedpeer && dialog->relatedpeer->call == dialog)
03189 dialog->relatedpeer->call = dialog_unref(dialog->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
03190
03191
03192 while((cp = dialog->packets)) {
03193 dialog->packets = dialog->packets->next;
03194 AST_SCHED_DEL(sched, cp->retransid);
03195 dialog_unref(cp->owner, "remove all current packets in this dialog, and the pointer to the dialog too as part of __sip_destroy");
03196 if (cp->data) {
03197 ast_free(cp->data);
03198 }
03199 ast_free(cp);
03200 }
03201
03202 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"));
03203
03204 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"));
03205
03206 if (dialog->autokillid > -1)
03207 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"));
03208
03209 if (dialog->request_queue_sched_id > -1) {
03210 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"));
03211 }
03212
03213 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"));
03214
03215 if (dialog->t38id > -1) {
03216 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"));
03217 }
03218
03219 dialog_unref(dialog, "Let's unbump the count in the unlink so the poor pvt can disappear if it is time");
03220 return NULL;
03221 }
03222
03223 static void *registry_unref(struct sip_registry *reg, char *tag)
03224 {
03225 ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount - 1);
03226 ASTOBJ_UNREF(reg, sip_registry_destroy);
03227 return NULL;
03228 }
03229
03230
03231 static struct sip_registry *registry_addref(struct sip_registry *reg, char *tag)
03232 {
03233 ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount + 1);
03234 return ASTOBJ_REF(reg);
03235 }
03236
03237
03238 static struct ast_udptl_protocol sip_udptl = {
03239 type: "SIP",
03240 get_udptl_info: sip_get_udptl_peer,
03241 set_udptl_peer: sip_set_udptl_peer,
03242 };
03243
03244 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
03245 __attribute__((format(printf, 2, 3)));
03246
03247
03248
03249 static const char *referstatus2str(enum referstatus rstatus)
03250 {
03251 return map_x_s(referstatusstrings, rstatus, "");
03252 }
03253
03254 static inline void pvt_set_needdestroy(struct sip_pvt *pvt, const char *reason)
03255 {
03256 append_history(pvt, "NeedDestroy", "Setting needdestroy because %s", reason);
03257 pvt->needdestroy = 1;
03258 }
03259
03260
03261
03262
03263 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
03264 {
03265 if (p->initreq.headers)
03266 ast_debug(1, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
03267 else
03268 ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
03269
03270 copy_request(&p->initreq, req);
03271 parse_request(&p->initreq);
03272 if (req->debug)
03273 ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
03274 }
03275
03276
03277 static void sip_alreadygone(struct sip_pvt *dialog)
03278 {
03279 ast_debug(3, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
03280 dialog->alreadygone = 1;
03281 }
03282
03283
03284 static int proxy_update(struct sip_proxy *proxy)
03285 {
03286
03287
03288 if (!inet_aton(proxy->name, &proxy->ip.sin_addr)) {
03289
03290
03291 if (ast_get_ip_or_srv(&proxy->ip, proxy->name, sip_cfg.srvlookup ? "_sip._udp" : NULL) < 0) {
03292 ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
03293 return FALSE;
03294 }
03295 }
03296 proxy->last_dnsupdate = time(NULL);
03297 return TRUE;
03298 }
03299
03300
03301
03302
03303
03304 static int port_str2int(const char *pt, unsigned int standard)
03305 {
03306 int port = standard;
03307 if (ast_strlen_zero(pt) || (sscanf(pt, "%30d", &port) != 1) || (port < 1) || (port > 65535)) {
03308 port = standard;
03309 }
03310
03311 return port;
03312 }
03313
03314
03315 static struct sip_proxy *proxy_allocate(char *name, char *port, int force)
03316 {
03317 struct sip_proxy *proxy;
03318
03319 if (ast_strlen_zero(name)) {
03320 return NULL;
03321 }
03322
03323 proxy = ao2_alloc(sizeof(*proxy), NULL);
03324 if (!proxy)
03325 return NULL;
03326 proxy->force = force;
03327 ast_copy_string(proxy->name, name, sizeof(proxy->name));
03328 proxy->ip.sin_port = htons(port_str2int(port, STANDARD_SIP_PORT));
03329 proxy->ip.sin_family = AF_INET;
03330 proxy_update(proxy);
03331 return proxy;
03332 }
03333
03334
03335 static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
03336 {
03337 if (peer && peer->outboundproxy) {
03338 if (sipdebug)
03339 ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
03340 append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
03341 return peer->outboundproxy;
03342 }
03343 if (sip_cfg.outboundproxy.name[0]) {
03344 if (sipdebug)
03345 ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
03346 append_history(dialog, "OBproxy", "Using global obproxy %s", sip_cfg.outboundproxy.name);
03347 return &sip_cfg.outboundproxy;
03348 }
03349 if (sipdebug)
03350 ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
03351 return NULL;
03352 }
03353
03354
03355
03356
03357
03358
03359
03360 static int method_match(enum sipmethod id, const char *name)
03361 {
03362 int len = strlen(sip_methods[id].text);
03363 int l_name = name ? strlen(name) : 0;
03364
03365 return (l_name >= len && name[len] < 33 &&
03366 !strncasecmp(sip_methods[id].text, name, len));
03367 }
03368
03369
03370 static int find_sip_method(const char *msg)
03371 {
03372 int i, res = 0;
03373
03374 if (ast_strlen_zero(msg))
03375 return 0;
03376 for (i = 1; i < ARRAY_LEN(sip_methods) && !res; i++) {
03377 if (method_match(i, msg))
03378 res = sip_methods[i].id;
03379 }
03380 return res;
03381 }
03382
03383
03384 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported)
03385 {
03386 char *next, *sep;
03387 char *temp;
03388 unsigned int profile = 0;
03389 int i, found;
03390
03391 if (ast_strlen_zero(supported) )
03392 return 0;
03393 temp = ast_strdupa(supported);
03394
03395 if (sipdebug)
03396 ast_debug(3, "Begin: parsing SIP \"Supported: %s\"\n", supported);
03397
03398 for (next = temp; next; next = sep) {
03399 found = FALSE;
03400 if ( (sep = strchr(next, ',')) != NULL)
03401 *sep++ = '\0';
03402 next = ast_skip_blanks(next);
03403 if (sipdebug)
03404 ast_debug(3, "Found SIP option: -%s-\n", next);
03405 for (i = 0; i < ARRAY_LEN(sip_options); i++) {
03406 if (!strcasecmp(next, sip_options[i].text)) {
03407 profile |= sip_options[i].id;
03408 found = TRUE;
03409 if (sipdebug)
03410 ast_debug(3, "Matched SIP option: %s\n", next);
03411 break;
03412 }
03413 }
03414
03415
03416
03417
03418
03419 if (!found)
03420 profile |= SIP_OPT_UNKNOWN;
03421
03422 if (!found && sipdebug) {
03423 if (!strncasecmp(next, "x-", 2))
03424 ast_debug(3, "Found private SIP option, not supported: %s\n", next);
03425 else
03426 ast_debug(3, "Found no match for SIP option: %s (Please file bug report!)\n", next);
03427 }
03428 }
03429
03430 if (pvt)
03431 pvt->sipoptions = profile;
03432 return profile;
03433 }
03434
03435
03436 static inline int sip_debug_test_addr(const struct sockaddr_in *addr)
03437 {
03438 if (!sipdebug)
03439 return 0;
03440 if (debugaddr.sin_addr.s_addr) {
03441 if (((ntohs(debugaddr.sin_port) != 0)
03442 && (debugaddr.sin_port != addr->sin_port))
03443 || (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
03444 return 0;
03445 }
03446 return 1;
03447 }
03448
03449
03450 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p)
03451 {
03452 if (p->outboundproxy)
03453 return &p->outboundproxy->ip;
03454
03455 return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? &p->recv : &p->sa;
03456 }
03457
03458
03459 static const char *sip_nat_mode(const struct sip_pvt *p)
03460 {
03461 return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? "NAT" : "no NAT";
03462 }
03463
03464
03465 static inline int sip_debug_test_pvt(struct sip_pvt *p)
03466 {
03467 if (!sipdebug)
03468 return 0;
03469 return sip_debug_test_addr(sip_real_dst(p));
03470 }
03471
03472
03473 static int get_transport_str2enum(const char *transport)
03474 {
03475 int res = 0;
03476
03477 if (ast_strlen_zero(transport)) {
03478 return res;
03479 }
03480
03481 if (!strcasecmp(transport, "udp")) {
03482 res |= SIP_TRANSPORT_UDP;
03483 }
03484 if (!strcasecmp(transport, "tcp")) {
03485 res |= SIP_TRANSPORT_TCP;
03486 }
03487 if (!strcasecmp(transport, "tls")) {
03488 res |= SIP_TRANSPORT_TLS;
03489 }
03490
03491 return res;
03492 }
03493
03494
03495 static inline const char *get_transport_list(unsigned int transports) {
03496 switch (transports) {
03497 case SIP_TRANSPORT_UDP:
03498 return "UDP";
03499 case SIP_TRANSPORT_TCP:
03500 return "TCP";
03501 case SIP_TRANSPORT_TLS:
03502 return "TLS";
03503 case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TCP:
03504 return "TCP,UDP";
03505 case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TLS:
03506 return "TLS,UDP";
03507 case SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS:
03508 return "TLS,TCP";
03509 default:
03510 return transports ?
03511 "TLS,TCP,UDP" : "UNKNOWN";
03512 }
03513 }
03514
03515
03516 static inline const char *get_transport(enum sip_transport t)
03517 {
03518 switch (t) {
03519 case SIP_TRANSPORT_UDP:
03520 return "UDP";
03521 case SIP_TRANSPORT_TCP:
03522 return "TCP";
03523 case SIP_TRANSPORT_TLS:
03524 return "TLS";
03525 }
03526
03527 return "UNKNOWN";
03528 }
03529
03530
03531
03532
03533
03534
03535
03536 static inline const char *get_transport_pvt(struct sip_pvt *p)
03537 {
03538 if (p->outboundproxy && p->outboundproxy->transport) {
03539 set_socket_transport(&p->socket, p->outboundproxy->transport);
03540 }
03541
03542 return get_transport(p->socket.type);
03543 }
03544
03545
03546
03547
03548
03549
03550 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len)
03551 {
03552 int res = 0;
03553 const struct sockaddr_in *dst = sip_real_dst(p);
03554
03555 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));
03556
03557 if (sip_prepare_socket(p) < 0)
03558 return XMIT_ERROR;
03559
03560 if (p->socket.type == SIP_TRANSPORT_UDP) {
03561 res = sendto(p->socket.fd, data->str, len, 0, (const struct sockaddr *)dst, sizeof(struct sockaddr_in));
03562 } else if (p->socket.tcptls_session) {
03563 res = sip_tcptls_write(p->socket.tcptls_session, data->str, len);
03564 } else {
03565 ast_debug(2, "Socket type is TCP but no tcptls_session is present to write to\n");
03566 return XMIT_ERROR;
03567 }
03568
03569 if (res == -1) {
03570 switch (errno) {
03571 case EBADF:
03572 case EHOSTUNREACH:
03573 case ENETDOWN:
03574 case ENETUNREACH:
03575 case ECONNREFUSED:
03576 res = XMIT_ERROR;
03577 }
03578 }
03579 if (res != len)
03580 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));
03581
03582 return res;
03583 }
03584
03585
03586 static void build_via(struct sip_pvt *p)
03587 {
03588
03589 const char *rport = ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_RFC3581 ? ";rport" : "";
03590
03591
03592 snprintf(p->via, sizeof(p->via), "SIP/2.0/%s %s:%d;branch=z9hG4bK%08x%s",
03593 get_transport_pvt(p),
03594 ast_inet_ntoa(p->ourip.sin_addr),
03595 ntohs(p->ourip.sin_port), (int) p->branch, rport);
03596 }
03597
03598
03599
03600
03601
03602
03603
03604
03605 static void ast_sip_ouraddrfor(struct in_addr *them, struct sockaddr_in *us, struct sip_pvt *p)
03606 {
03607 struct sockaddr_in theirs;
03608
03609
03610
03611
03612
03613
03614
03615
03616
03617
03618
03619
03620 int want_remap;
03621
03622 *us = internip;
03623
03624 ast_ouraddrfor(them, &us->sin_addr);
03625 theirs.sin_addr = *them;
03626
03627 want_remap = localaddr &&
03628 (externip.sin_addr.s_addr || stunaddr.sin_addr.s_addr) &&
03629 ast_apply_ha(localaddr, &theirs) == AST_SENSE_ALLOW ;
03630
03631 if (want_remap &&
03632 (!sip_cfg.matchexterniplocally || !ast_apply_ha(localaddr, us)) ) {
03633
03634 if (externexpire && time(NULL) >= externexpire) {
03635 if (stunaddr.sin_addr.s_addr) {
03636 ast_stun_request(sipsock, &stunaddr, NULL, &externip);
03637 } else {
03638 if (ast_parse_arg(externhost, PARSE_INADDR, &externip))
03639 ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
03640 }
03641 externexpire = time(NULL) + externrefresh;
03642 }
03643 if (externip.sin_addr.s_addr)
03644 *us = externip;
03645 else
03646 ast_log(LOG_WARNING, "stun failed\n");
03647 ast_debug(1, "Target address %s is not local, substituting externip\n",
03648 ast_inet_ntoa(*(struct in_addr *)&them->s_addr));
03649 } else if (p) {
03650
03651 switch (p->socket.type) {
03652 case SIP_TRANSPORT_TCP:
03653 if (sip_tcp_desc.local_address.sin_addr.s_addr) {
03654 *us = sip_tcp_desc.local_address;
03655 } else {
03656 us->sin_port = sip_tcp_desc.local_address.sin_port;
03657 }
03658 break;
03659 case SIP_TRANSPORT_TLS:
03660 if (sip_tls_desc.local_address.sin_addr.s_addr) {
03661 *us = sip_tls_desc.local_address;
03662 } else {
03663 us->sin_port = sip_tls_desc.local_address.sin_port;
03664 }
03665 break;
03666 case SIP_TRANSPORT_UDP:
03667
03668 default:
03669 if (bindaddr.sin_addr.s_addr) {
03670 *us = bindaddr;
03671 }
03672 }
03673 } else if (bindaddr.sin_addr.s_addr) {
03674 *us = bindaddr;
03675 }
03676 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));
03677 }
03678
03679
03680 static __attribute__((format(printf, 2, 0))) void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
03681 {
03682 char buf[80], *c = buf;
03683 struct sip_history *hist;
03684 int l;
03685
03686 vsnprintf(buf, sizeof(buf), fmt, ap);
03687 strsep(&c, "\r\n");
03688 l = strlen(buf) + 1;
03689 if (!(hist = ast_calloc(1, sizeof(*hist) + l)))
03690 return;
03691 if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
03692 ast_free(hist);
03693 return;
03694 }
03695 memcpy(hist->event, buf, l);
03696 if (p->history_entries == MAX_HISTORY_ENTRIES) {
03697 struct sip_history *oldest;
03698 oldest = AST_LIST_REMOVE_HEAD(p->history, list);
03699 p->history_entries--;
03700 ast_free(oldest);
03701 }
03702 AST_LIST_INSERT_TAIL(p->history, hist, list);
03703 p->history_entries++;
03704 }
03705
03706
03707 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
03708 {
03709 va_list ap;
03710
03711 if (!p)
03712 return;
03713
03714 if (!p->do_history && !recordhistory && !dumphistory)
03715 return;
03716
03717 va_start(ap, fmt);
03718 append_history_va(p, fmt, ap);
03719 va_end(ap);
03720
03721 return;
03722 }
03723
03724
03725 static int retrans_pkt(const void *data)
03726 {
03727 struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
03728 int reschedule = DEFAULT_RETRANS;
03729 int xmitres = 0;
03730
03731
03732 sip_pvt_lock(pkt->owner);
03733
03734 if (pkt->retrans < MAX_RETRANS) {
03735 pkt->retrans++;
03736 if (!pkt->timer_t1) {
03737 if (sipdebug)
03738 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);
03739 } else {
03740 int siptimer_a;
03741
03742 if (sipdebug)
03743 ast_debug(4, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n", pkt->retransid, pkt->retrans, sip_methods[pkt->method].text, pkt->method);
03744 if (!pkt->timer_a)
03745 pkt->timer_a = 2 ;
03746 else
03747 pkt->timer_a = 2 * pkt->timer_a;
03748
03749
03750 siptimer_a = pkt->timer_t1 * pkt->timer_a;
03751 if (pkt->method != SIP_INVITE && siptimer_a > 4000)
03752 siptimer_a = 4000;
03753
03754
03755 reschedule = siptimer_a;
03756 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);
03757 }
03758
03759 if (sip_debug_test_pvt(pkt->owner)) {
03760 const struct sockaddr_in *dst = sip_real_dst(pkt->owner);
03761 ast_verbose("Retransmitting #%d (%s) to %s:%d:\n%s\n---\n",
03762 pkt->retrans, sip_nat_mode(pkt->owner),
03763 ast_inet_ntoa(dst->sin_addr),
03764 ntohs(dst->sin_port), pkt->data->str);
03765 }
03766
03767 append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data->str);
03768 xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
03769 sip_pvt_unlock(pkt->owner);
03770 if (xmitres == XMIT_ERROR)
03771 ast_log(LOG_WARNING, "Network error on retransmit in dialog %s\n", pkt->owner->callid);
03772 else
03773 return reschedule;
03774 }
03775
03776 if (pkt->owner && pkt->method != SIP_OPTIONS && xmitres == 0) {
03777 if (pkt->is_fatal || sipdebug)
03778 ast_log(LOG_WARNING, "Maximum retries exceeded on transmission %s for seqno %d (%s %s) -- See doc/sip-retransmit.txt.\n",
03779 pkt->owner->callid, pkt->seqno,
03780 pkt->is_fatal ? "Critical" : "Non-critical", pkt->is_resp ? "Response" : "Request");
03781 } else if (pkt->method == SIP_OPTIONS && sipdebug) {
03782 ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s) -- See doc/sip-retransmit.txt.\n", pkt->owner->callid);
03783
03784 }
03785 if (xmitres == XMIT_ERROR) {
03786 ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission on Call ID %s\n", pkt->owner->callid);
03787 append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03788 } else
03789 append_history(pkt->owner, "MaxRetries", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03790
03791 pkt->retransid = -1;
03792
03793 if (pkt->is_fatal) {
03794 while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
03795 sip_pvt_unlock(pkt->owner);
03796 usleep(1);
03797 sip_pvt_lock(pkt->owner);
03798 }
03799
03800 if (pkt->owner->owner && !pkt->owner->owner->hangupcause)
03801 pkt->owner->owner->hangupcause = AST_CAUSE_NO_USER_RESPONSE;
03802
03803 if (pkt->owner->owner) {
03804 sip_alreadygone(pkt->owner);
03805 ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet (see doc/sip-retransmit.txt).\n", pkt->owner->callid);
03806 ast_queue_hangup_with_cause(pkt->owner->owner, AST_CAUSE_PROTOCOL_ERROR);
03807 ast_channel_unlock(pkt->owner->owner);
03808 } else {
03809
03810
03811
03812 if (pkt->method != SIP_OPTIONS && pkt->method != SIP_REGISTER) {
03813 pvt_set_needdestroy(pkt->owner, "no response to critical packet");
03814 sip_alreadygone(pkt->owner);
03815 append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
03816 }
03817 }
03818 }
03819
03820 if (pkt->method == SIP_BYE) {
03821
03822 if (pkt->owner->owner)
03823 ast_channel_unlock(pkt->owner->owner);
03824 append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
03825 pvt_set_needdestroy(pkt->owner, "no response to BYE");
03826 }
03827
03828
03829 for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
03830 if (cur == pkt) {
03831 UNLINK(cur, pkt->owner->packets, prev);
03832 sip_pvt_unlock(pkt->owner);
03833 if (pkt->owner)
03834 pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
03835 if (pkt->data)
03836 ast_free(pkt->data);
03837 pkt->data = NULL;
03838 ast_free(pkt);
03839 return 0;
03840 }
03841 }
03842
03843 ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
03844 sip_pvt_unlock(pkt->owner);
03845 return 0;
03846 }
03847
03848
03849
03850
03851 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)
03852 {
03853 struct sip_pkt *pkt = NULL;
03854 int siptimer_a = DEFAULT_RETRANS;
03855 int xmitres = 0;
03856 int respid;
03857
03858 if (sipmethod == SIP_INVITE) {
03859
03860 p->pendinginvite = seqno;
03861 }
03862
03863
03864
03865
03866 if (!(p->socket.type & SIP_TRANSPORT_UDP)) {
03867 xmitres = __sip_xmit(p, data, len);
03868 if (xmitres == XMIT_ERROR) {
03869 append_history(p, "XmitErr", "%s", fatal ? "(Critical)" : "(Non-critical)");
03870 return AST_FAILURE;
03871 } else {
03872 return AST_SUCCESS;
03873 }
03874 }
03875
03876 if (!(pkt = ast_calloc(1, sizeof(*pkt) + len + 1)))
03877 return AST_FAILURE;
03878
03879 if (!(pkt->data = ast_str_create(len))) {
03880 ast_free(pkt);
03881 return AST_FAILURE;
03882 }
03883 ast_str_set(&pkt->data, 0, "%s%s", data->str, "\0");
03884 pkt->packetlen = len;
03885
03886 pkt->method = sipmethod;
03887 pkt->seqno = seqno;
03888 pkt->is_resp = resp;
03889 pkt->is_fatal = fatal;
03890 pkt->owner = dialog_ref(p, "__sip_reliable_xmit: setting pkt->owner");
03891 pkt->next = p->packets;
03892 p->packets = pkt;
03893 if (resp) {
03894
03895 if (sscanf(ast_str_buffer(pkt->data), "SIP/2.0 %30u", &respid) == 1) {
03896 pkt->response_code = respid;
03897 }
03898 }
03899 pkt->timer_t1 = p->timer_t1;
03900 pkt->retransid = -1;
03901 if (pkt->timer_t1)
03902 siptimer_a = pkt->timer_t1 * 2;
03903
03904
03905 AST_SCHED_REPLACE_VARIABLE(pkt->retransid, sched, siptimer_a, retrans_pkt, pkt, 1);
03906 if (sipdebug)
03907 ast_debug(4, "*** SIP TIMER: Initializing retransmit timer on packet: Id #%d\n", pkt->retransid);
03908
03909 xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
03910
03911 if (xmitres == XMIT_ERROR) {
03912 append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03913 ast_log(LOG_ERROR, "Serious Network Trouble; __sip_xmit returns error for pkt data\n");
03914 AST_SCHED_DEL(sched, pkt->retransid);
03915 p->packets = pkt->next;
03916 pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
03917 ast_free(pkt->data);
03918 ast_free(pkt);
03919 return AST_FAILURE;
03920 } else {
03921 return AST_SUCCESS;
03922 }
03923 }
03924
03925
03926
03927
03928
03929
03930 static int __sip_autodestruct(const void *data)
03931 {
03932 struct sip_pvt *p = (struct sip_pvt *)data;
03933
03934
03935 if (p->subscribed) {
03936 transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE);
03937 p->subscribed = NONE;
03938 append_history(p, "Subscribestatus", "timeout");
03939 ast_debug(3, "Re-scheduled destruction of SIP subscription %s\n", p->callid ? p->callid : "<unknown>");
03940 return 10000;
03941 }
03942
03943
03944 if (p->packets) {
03945 if (!p->needdestroy) {
03946 char method_str[31];
03947 ast_debug(3, "Re-scheduled destruction of SIP call %s\n", p->callid ? p->callid : "<unknown>");
03948 append_history(p, "ReliableXmit", "timeout");
03949 if (sscanf(p->lastmsg, "Tx: %30s", method_str) == 1 || sscanf(p->lastmsg, "Rx: %30s", method_str) == 1) {
03950 if (method_match(SIP_CANCEL, method_str) || method_match(SIP_BYE, method_str)) {
03951 pvt_set_needdestroy(p, "autodestruct");
03952 }
03953 }
03954 return 10000;
03955 } else {
03956
03957 __sip_pretend_ack(p);
03958 }
03959 }
03960
03961 if (p->subscribed == MWI_NOTIFICATION)
03962 if (p->relatedpeer)
03963 p->relatedpeer = unref_peer(p->relatedpeer, "__sip_autodestruct: unref peer p->relatedpeer");
03964
03965
03966 p->autokillid = -1;
03967
03968 if (p->owner) {
03969 ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
03970 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
03971 } else if (p->refer && !p->alreadygone) {
03972 ast_debug(3, "Finally hanging up channel after transfer: %s\n", p->callid);
03973 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
03974 append_history(p, "ReferBYE", "Sending BYE on transferer call leg %s", p->callid);
03975 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
03976 } else {
03977 append_history(p, "AutoDestroy", "%s", p->callid);
03978 ast_debug(3, "Auto destroying SIP dialog '%s'\n", p->callid);
03979 dialog_unlink_all(p, TRUE, TRUE);
03980
03981
03982
03983 }
03984 dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
03985 return 0;
03986 }
03987
03988
03989 static void sip_scheddestroy(struct sip_pvt *p, int ms)
03990 {
03991 if (ms < 0) {
03992 if (p->timer_t1 == 0) {
03993 p->timer_t1 = global_t1;
03994 p->timer_b = global_timer_b;
03995 }
03996 ms = p->timer_t1 * 64;
03997 }
03998 if (sip_debug_test_pvt(p))
03999 ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
04000 if (sip_cancel_destroy(p))
04001 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
04002
04003 if (p->do_history)
04004 append_history(p, "SchedDestroy", "%d ms", ms);
04005 p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, dialog_ref(p, "setting ref as passing into ast_sched_add for __sip_autodestruct"));
04006
04007 if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_schedid > 0)
04008 stop_session_timer(p);
04009 }
04010
04011
04012
04013
04014
04015 static int sip_cancel_destroy(struct sip_pvt *p)
04016 {
04017 int res = 0;
04018 if (p->autokillid > -1) {
04019 int res3;
04020
04021 if (!(res3 = ast_sched_del(sched, p->autokillid))) {
04022 append_history(p, "CancelDestroy", "");
04023 p->autokillid = -1;
04024 dialog_unref(p, "dialog unrefd because autokillid is de-sched'd");
04025 }
04026 }
04027 return res;
04028 }
04029
04030
04031
04032 static int __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
04033 {
04034 struct sip_pkt *cur, *prev = NULL;
04035 const char *msg = "Not Found";
04036 int res = FALSE;
04037
04038
04039
04040
04041
04042
04043 if (p->outboundproxy && !p->outboundproxy->force){
04044 ref_proxy(p, NULL);
04045 }
04046
04047 for (cur = p->packets; cur; prev = cur, cur = cur->next) {
04048 if (cur->seqno != seqno || cur->is_resp != resp)
04049 continue;
04050 if (cur->is_resp || cur->method == sipmethod) {
04051 res = TRUE;
04052 msg = "Found";
04053 if (!resp && (seqno == p->pendinginvite)) {
04054 ast_debug(1, "Acked pending invite %d\n", p->pendinginvite);
04055 p->pendinginvite = 0;
04056 }
04057 if (cur->retransid > -1) {
04058 if (sipdebug)
04059 ast_debug(4, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
04060 }
04061
04062
04063
04064
04065
04066
04067
04068
04069
04070
04071
04072
04073
04074
04075
04076
04077 while (cur->retransid > -1 && ast_sched_del(sched, cur->retransid)) {
04078 sip_pvt_unlock(p);
04079 usleep(1);
04080 sip_pvt_lock(p);
04081 }
04082 UNLINK(cur, p->packets, prev);
04083 dialog_unref(cur->owner, "unref pkt cur->owner dialog from sip ack before freeing pkt");
04084 if (cur->data)
04085 ast_free(cur->data);
04086 ast_free(cur);
04087 break;
04088 }
04089 }
04090 ast_debug(1, "Stopping retransmission on '%s' of %s %d: Match %s\n",
04091 p->callid, resp ? "Response" : "Request", seqno, msg);
04092 return res;
04093 }
04094
04095
04096
04097 static void __sip_pretend_ack(struct sip_pvt *p)
04098 {
04099 struct sip_pkt *cur = NULL;
04100
04101 while (p->packets) {
04102 int method;
04103 if (cur == p->packets) {
04104 ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
04105 return;
04106 }
04107 cur = p->packets;
04108 method = (cur->method) ? cur->method : find_sip_method(cur->data->str);
04109 __sip_ack(p, cur->seqno, cur->is_resp, method);
04110 }
04111 }
04112
04113
04114 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
04115 {
04116 struct sip_pkt *cur;
04117 int res = FALSE;
04118
04119 for (cur = p->packets; cur; cur = cur->next) {
04120 if (cur->seqno == seqno && cur->is_resp == resp &&
04121 (cur->is_resp || method_match(sipmethod, cur->data->str))) {
04122
04123 if (cur->retransid > -1) {
04124 if (sipdebug)
04125 ast_debug(4, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
04126 }
04127 AST_SCHED_DEL(sched, cur->retransid);
04128 res = TRUE;
04129 break;
04130 }
04131 }
04132 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");
04133 return res;
04134 }
04135
04136
04137
04138 static void parse_copy(struct sip_request *dst, const struct sip_request *src)
04139 {
04140 copy_request(dst, src);
04141 parse_request(dst);
04142 }
04143
04144
04145 static void add_blank(struct sip_request *req)
04146 {
04147 if (!req->lines) {
04148
04149 ast_str_append(&req->data, 0, "\r\n");
04150 req->len = ast_str_strlen(req->data);
04151 }
04152 }
04153
04154 static int send_provisional_keepalive_full(struct sip_pvt *pvt, int with_sdp)
04155 {
04156 const char *msg = NULL;
04157
04158 if (!pvt->last_provisional || !strncasecmp(pvt->last_provisional, "100", 3)) {
04159 msg = "183 Session Progress";
04160 }
04161
04162 if (pvt->invitestate < INV_COMPLETED) {
04163 if (with_sdp) {
04164 transmit_response_with_sdp(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq, XMIT_UNRELIABLE, FALSE);
04165 } else {
04166 transmit_response(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq);
04167 }
04168 return PROVIS_KEEPALIVE_TIMEOUT;
04169 }
04170
04171 return 0;
04172 }
04173
04174 static int send_provisional_keepalive(const void *data) {
04175 struct sip_pvt *pvt = (struct sip_pvt *) data;
04176
04177 return send_provisional_keepalive_full(pvt, 0);
04178 }
04179
04180 static int send_provisional_keepalive_with_sdp(const void *data) {
04181 struct sip_pvt *pvt = (void *)data;
04182
04183 return send_provisional_keepalive_full(pvt, 1);
04184 }
04185
04186 static void update_provisional_keepalive(struct sip_pvt *pvt, int with_sdp)
04187 {
04188 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"));
04189
04190 pvt->provisional_keepalive_sched_id = ast_sched_add(sched, PROVIS_KEEPALIVE_TIMEOUT,
04191 with_sdp ? send_provisional_keepalive_with_sdp : send_provisional_keepalive, dialog_ref(pvt, "Increment refcount to pass dialog pointer to sched callback"));
04192 }
04193
04194
04195 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
04196 {
04197 int res;
04198
04199 finalize_content(req);
04200 add_blank(req);
04201 if (sip_debug_test_pvt(p)) {
04202 const struct sockaddr_in *dst = sip_real_dst(p);
04203
04204 ast_verbose("\n<--- %sTransmitting (%s) to %s:%d --->\n%s\n<------------>\n",
04205 reliable ? "Reliably " : "", sip_nat_mode(p),
04206 ast_inet_ntoa(dst->sin_addr),
04207 ntohs(dst->sin_port), req->data->str);
04208 }
04209 if (p->do_history) {
04210 struct sip_request tmp = { .rlPart1 = 0, };
04211 parse_copy(&tmp, req);
04212 append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", tmp.data->str, get_header(&tmp, "CSeq"),
04213 (tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? REQ_OFFSET_TO_STR(&tmp, rlPart2) : sip_methods[tmp.method].text);
04214 deinit_req(&tmp);
04215 }
04216
04217
04218 if (p->initreq.method == SIP_INVITE && reliable == XMIT_CRITICAL) {
04219 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"));
04220 }
04221
04222 res = (reliable) ?
04223 __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
04224 __sip_xmit(p, req->data, req->len);
04225 deinit_req(req);
04226 if (res > 0)
04227 return 0;
04228 return res;
04229 }
04230
04231
04232 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
04233 {
04234 int res;
04235
04236
04237
04238
04239 if (p->outboundproxy) {
04240 p->sa = p->outboundproxy->ip;
04241 }
04242
04243 finalize_content(req);
04244 add_blank(req);
04245 if (sip_debug_test_pvt(p)) {
04246 if (ast_test_flag(&p->flags[0], SIP_NAT_ROUTE))
04247 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);
04248 else
04249 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);
04250 }
04251 if (p->do_history) {
04252 struct sip_request tmp = { .rlPart1 = 0, };
04253 parse_copy(&tmp, req);
04254 append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", tmp.data->str, get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
04255 deinit_req(&tmp);
04256 }
04257 res = (reliable) ?
04258 __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
04259 __sip_xmit(p, req->data, req->len);
04260 deinit_req(req);
04261 return res;
04262 }
04263
04264
04265 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen)
04266 {
04267 int res = -1;
04268 enum ast_t38_state state = T38_STATE_UNAVAILABLE;
04269 struct sip_pvt *p = (struct sip_pvt *) chan->tech_pvt;
04270
04271 switch (option) {
04272 case AST_OPTION_T38_STATE:
04273
04274 if (*datalen != sizeof(enum ast_t38_state)) {
04275 ast_log(LOG_ERROR, "Invalid datalen for AST_OPTION_T38_STATE option. Expected %d, got %d\n", (int)sizeof(enum ast_t38_state), *datalen);
04276 return -1;
04277 }
04278
04279 sip_pvt_lock(p);
04280
04281
04282 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
04283 switch (p->t38.state) {
04284 case T38_LOCAL_REINVITE:
04285 case T38_PEER_REINVITE:
04286 state = T38_STATE_NEGOTIATING;
04287 break;
04288 case T38_ENABLED:
04289 state = T38_STATE_NEGOTIATED;
04290 break;
04291 default:
04292 state = T38_STATE_UNKNOWN;
04293 }
04294 }
04295
04296 sip_pvt_unlock(p);
04297
04298 *((enum ast_t38_state *) data) = state;
04299 res = 0;
04300
04301 break;
04302 default:
04303 break;
04304 }
04305
04306 return res;
04307 }
04308
04309
04310
04311
04312
04313 static const char *find_closing_quote(const char *start, const char *lim)
04314 {
04315 char last_char = '\0';
04316 const char *s;
04317 for (s = start; *s && s != lim; last_char = *s++) {
04318 if (*s == '"' && last_char != '\\')
04319 break;
04320 }
04321 return s;
04322 }
04323
04324
04325
04326
04327
04328
04329
04330
04331
04332
04333
04334
04335
04336 static char *get_in_brackets(char *tmp)
04337 {
04338 const char *parse = tmp;
04339 char *first_bracket;
04340
04341
04342
04343
04344
04345 while ( (first_bracket = strchr(parse, '<')) ) {
04346 char *first_quote = strchr(parse, '"');
04347
04348 if (!first_quote || first_quote > first_bracket)
04349 break;
04350
04351 parse = find_closing_quote(first_quote + 1, NULL);
04352 if (!*parse) {
04353
04354 ast_log(LOG_WARNING, "No closing quote found in '%s'\n", tmp);
04355 break;
04356 }
04357 parse++;
04358 }
04359 if (first_bracket) {
04360 char *second_bracket = strchr(first_bracket + 1, '>');
04361 if (second_bracket) {
04362 *second_bracket = '\0';
04363 tmp = first_bracket + 1;
04364 } else {
04365 ast_log(LOG_WARNING, "No closing bracket found in '%s'\n", tmp);
04366 }
04367 }
04368
04369 return tmp;
04370 }
04371
04372
04373
04374
04375
04376
04377
04378
04379
04380
04381
04382
04383
04384
04385
04386
04387
04388
04389
04390
04391 static int parse_uri(char *uri, const char *scheme,
04392 char **ret_name, char **pass, char **domain, char **port, char **options, char **transport)
04393 {
04394 char *name = NULL;
04395 int error = 0;
04396
04397
04398 if (pass)
04399 *pass = "";
04400 if (port)
04401 *port = "";
04402 if (scheme) {
04403 int l;
04404 char *scheme2 = ast_strdupa(scheme);
04405 char *cur = strsep(&scheme2, ",");
04406 for (; !ast_strlen_zero(cur); cur = strsep(&scheme2, ",")) {
04407 l = strlen(cur);
04408 if (!strncasecmp(uri, cur, l)) {
04409 uri += l;
04410 break;
04411 }
04412 }
04413 if (ast_strlen_zero(cur)) {
04414 ast_debug(1, "No supported scheme found in '%s' using the scheme[s] %s\n", uri, scheme);
04415 error = -1;
04416 }
04417 }
04418 if (transport) {
04419 char *t, *type = "";
04420 *transport = "";
04421 if ((t = strstr(uri, "transport="))) {
04422 strsep(&t, "=");
04423 if ((type = strsep(&t, ";"))) {
04424 *transport = type;
04425 }
04426 }
04427 }
04428
04429 if (!domain) {
04430
04431
04432
04433 } else {
04434
04435
04436
04437 char *c, *dom = "";
04438
04439 if ((c = strchr(uri, '@')) == NULL) {
04440
04441 dom = uri;
04442 name = "";
04443 } else {
04444 *c++ = '\0';
04445 dom = c;
04446 name = uri;
04447 }
04448
04449
04450 dom = strsep(&dom, ";");
04451 name = strsep(&name, ";");
04452
04453 if (port && (c = strchr(dom, ':'))) {
04454 *c++ = '\0';
04455 *port = c;
04456 }
04457 if (pass && (c = strchr(name, ':'))) {
04458 *c++ = '\0';
04459 *pass = c;
04460 }
04461 *domain = dom;
04462 }
04463 if (ret_name)
04464 *ret_name = name;
04465 if (options)
04466 *options = uri ? uri : "";
04467
04468 return error;
04469 }
04470
04471
04472 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
04473 {
04474 struct sip_pvt *p = chan->tech_pvt;
04475
04476 if (subclass != AST_HTML_URL)
04477 return -1;
04478
04479 ast_string_field_build(p, url, "<%s>;mode=active", data);
04480
04481 if (sip_debug_test_pvt(p))
04482 ast_debug(1, "Send URL %s, state = %d!\n", data, chan->_state);
04483
04484 switch (chan->_state) {
04485 case AST_STATE_RING:
04486 transmit_response(p, "100 Trying", &p->initreq);
04487 break;
04488 case AST_STATE_RINGING:
04489 transmit_response(p, "180 Ringing", &p->initreq);
04490 break;
04491 case AST_STATE_UP:
04492 if (!p->pendinginvite) {
04493 transmit_reinvite_with_sdp(p, FALSE, FALSE);
04494 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
04495 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
04496 }
04497 break;
04498 default:
04499 ast_log(LOG_WARNING, "Don't know how to send URI when state is %d!\n", chan->_state);
04500 }
04501
04502 return 0;
04503 }
04504
04505
04506 static const char *sip_get_callid(struct ast_channel *chan)
04507 {
04508 return chan->tech_pvt ? ((struct sip_pvt *) chan->tech_pvt)->callid : "";
04509 }
04510
04511
04512
04513 static int sip_sendtext(struct ast_channel *ast, const char *text)
04514 {
04515 struct sip_pvt *p = ast->tech_pvt;
04516 int debug = sip_debug_test_pvt(p);
04517
04518 if (debug)
04519 ast_verbose("Sending text %s on %s\n", text, ast->name);
04520 if (!p)
04521 return -1;
04522
04523
04524 if (!text)
04525 return 0;
04526 if (debug)
04527 ast_verbose("Really sending text %s on %s\n", text, ast->name);
04528 transmit_message_with_text(p, text);
04529 return 0;
04530 }
04531
04532
04533
04534
04535
04536
04537 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)
04538 {
04539 char port[10];
04540 char ipaddr[INET_ADDRSTRLEN];
04541 char regseconds[20];
04542 char *tablename = NULL;
04543 char str_lastms[20];
04544
04545 const char *sysname = ast_config_AST_SYSTEM_NAME;
04546 char *syslabel = NULL;
04547
04548 time_t nowtime = time(NULL) + expirey;
04549 const char *fc = fullcontact ? "fullcontact" : NULL;
04550
04551 int realtimeregs = ast_check_realtime("sipregs");
04552
04553 tablename = realtimeregs ? "sipregs" : "sippeers";
04554
04555
04556 snprintf(str_lastms, sizeof(str_lastms), "%d", lastms);
04557 snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime);
04558 ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
04559 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
04560
04561 if (ast_strlen_zero(sysname))
04562 sysname = NULL;
04563 else if (sip_cfg.rtsave_sysname)
04564 syslabel = "regserver";
04565
04566 if (fc) {
04567 ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
04568 "port", port, "regseconds", regseconds,
04569 deprecated_username ? "username" : "defaultuser", defaultuser,
04570 "useragent", useragent, "lastms", str_lastms,
04571 fc, fullcontact, syslabel, sysname, SENTINEL);
04572 } else {
04573 ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
04574 "port", port, "regseconds", regseconds,
04575 "useragent", useragent, "lastms", str_lastms,
04576 deprecated_username ? "username" : "defaultuser", defaultuser,
04577 syslabel, sysname, SENTINEL);
04578 }
04579 }
04580
04581
04582 static void register_peer_exten(struct sip_peer *peer, int onoff)
04583 {
04584 char multi[256];
04585 char *stringp, *ext, *context;
04586 struct pbx_find_info q = { .stacklen = 0 };
04587
04588
04589
04590
04591
04592 if (ast_strlen_zero(global_regcontext))
04593 return;
04594
04595 ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
04596 stringp = multi;
04597 while ((ext = strsep(&stringp, "&"))) {
04598 if ((context = strchr(ext, '@'))) {
04599 *context++ = '\0';
04600 if (!ast_context_find(context)) {
04601 ast_log(LOG_WARNING, "Context %s must exist in regcontext= in sip.conf!\n", context);
04602 continue;
04603 }
04604 } else {
04605 context = global_regcontext;
04606 }
04607 if (onoff) {
04608 if (!ast_exists_extension(NULL, context, ext, 1, NULL)) {
04609 ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
04610 ast_strdup(peer->name), ast_free_ptr, "SIP");
04611 }
04612 } else if (pbx_find_extension(NULL, NULL, &q, context, ext, 1, NULL, "", E_MATCH)) {
04613 ast_context_remove_extension(context, ext, 1, NULL);
04614 }
04615 }
04616 }
04617
04618
04619 static void destroy_mailbox(struct sip_mailbox *mailbox)
04620 {
04621 if (mailbox->mailbox)
04622 ast_free(mailbox->mailbox);
04623 if (mailbox->context)
04624 ast_free(mailbox->context);
04625 if (mailbox->event_sub)
04626 ast_event_unsubscribe(mailbox->event_sub);
04627 ast_free(mailbox);
04628 }
04629
04630
04631 static void clear_peer_mailboxes(struct sip_peer *peer)
04632 {
04633 struct sip_mailbox *mailbox;
04634
04635 while ((mailbox = AST_LIST_REMOVE_HEAD(&peer->mailboxes, entry)))
04636 destroy_mailbox(mailbox);
04637 }
04638
04639 static void sip_destroy_peer_fn(void *peer)
04640 {
04641 sip_destroy_peer(peer);
04642 }
04643
04644
04645 static void sip_destroy_peer(struct sip_peer *peer)
04646 {
04647 ast_debug(3, "Destroying SIP peer %s\n", peer->name);
04648 if (peer->outboundproxy)
04649 ao2_ref(peer->outboundproxy, -1);
04650 peer->outboundproxy = NULL;
04651
04652
04653 if (peer->call) {
04654 dialog_unlink_all(peer->call, TRUE, TRUE);
04655 peer->call = dialog_unref(peer->call, "peer->call is being unset");
04656 }
04657
04658
04659 if (peer->mwipvt) {
04660 dialog_unlink_all(peer->mwipvt, TRUE, TRUE);
04661 peer->mwipvt = dialog_unref(peer->mwipvt, "unreffing peer->mwipvt");
04662 }
04663
04664 if (peer->chanvars) {
04665 ast_variables_destroy(peer->chanvars);
04666 peer->chanvars = NULL;
04667 }
04668
04669 register_peer_exten(peer, FALSE);
04670 ast_free_ha(peer->ha);
04671 if (peer->selfdestruct)
04672 ast_atomic_fetchadd_int(&apeerobjs, -1);
04673 else if (peer->is_realtime) {
04674 ast_atomic_fetchadd_int(&rpeerobjs, -1);
04675 ast_debug(3, "-REALTIME- peer Destroyed. Name: %s. Realtime Peer objects: %d\n", peer->name, rpeerobjs);
04676 } else
04677 ast_atomic_fetchadd_int(&speerobjs, -1);
04678 clear_realm_authentication(peer->auth);
04679 peer->auth = NULL;
04680 if (peer->dnsmgr)
04681 ast_dnsmgr_release(peer->dnsmgr);
04682 clear_peer_mailboxes(peer);
04683
04684 if (peer->socket.tcptls_session) {
04685 ao2_ref(peer->socket.tcptls_session, -1);
04686 peer->socket.tcptls_session = NULL;
04687 }
04688
04689 ast_string_field_free_memory(peer);
04690 }
04691
04692
04693 static void update_peer(struct sip_peer *p, int expire)
04694 {
04695 int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
04696 if (sip_cfg.peer_rtupdate &&
04697 (p->is_realtime || rtcachefriends)) {
04698 realtime_update_peer(p->name, &p->addr, p->username, rtcachefriends ? p->fullcontact : NULL, p->useragent, expire, p->deprecated_username, p->lastms);
04699 }
04700 }
04701
04702 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *cfg)
04703 {
04704 struct ast_variable *var = NULL;
04705 struct ast_flags flags = {0};
04706 char *cat = NULL;
04707 const char *insecure;
04708 while ((cat = ast_category_browse(cfg, cat))) {
04709 insecure = ast_variable_retrieve(cfg, cat, "insecure");
04710 set_insecure_flags(&flags, insecure, -1);
04711 if (ast_test_flag(&flags, SIP_INSECURE_PORT)) {
04712 var = ast_category_root(cfg, cat);
04713 break;
04714 }
04715 }
04716 return var;
04717 }
04718
04719 static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername)
04720 {
04721 struct ast_variable *tmp;
04722 for (tmp = var; tmp; tmp = tmp->next) {
04723 if (!newpeername && !strcasecmp(tmp->name, "name"))
04724 newpeername = tmp->value;
04725 }
04726 return newpeername;
04727 }
04728
04729
04730
04731
04732
04733
04734
04735 static struct sip_peer *realtime_peer(const char *newpeername, struct sockaddr_in *sin, int devstate_only)
04736 {
04737 struct sip_peer *peer;
04738 struct ast_variable *var = NULL;
04739 struct ast_variable *varregs = NULL;
04740 struct ast_variable *tmp;
04741 struct ast_config *peerlist = NULL;
04742 char ipaddr[INET_ADDRSTRLEN];
04743 char portstring[6];
04744 char *cat = NULL;
04745 unsigned short portnum;
04746 int realtimeregs = ast_check_realtime("sipregs");
04747
04748
04749 if (newpeername) {
04750 if (realtimeregs)
04751 varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04752
04753 var = ast_load_realtime("sippeers", "name", newpeername, "host", "dynamic", SENTINEL);
04754 if (!var && sin)
04755 var = ast_load_realtime("sippeers", "name", newpeername, "host", ast_inet_ntoa(sin->sin_addr), SENTINEL);
04756 if (!var) {
04757 var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
04758
04759
04760
04761
04762
04763
04764 if (var && sin) {
04765 for (tmp = var; tmp; tmp = tmp->next) {
04766 if (!strcasecmp(tmp->name, "host")) {
04767 struct hostent *hp;
04768 struct ast_hostent ahp;
04769 if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || (memcmp(hp->h_addr, &sin->sin_addr, sizeof(hp->h_addr)))) {
04770
04771 ast_variables_destroy(var);
04772 var = NULL;
04773 }
04774 break;
04775 }
04776 }
04777 }
04778 }
04779 }
04780
04781 if (!var && sin) {
04782 ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
04783 portnum = ntohs(sin->sin_port);
04784 sprintf(portstring, "%u", portnum);
04785 var = ast_load_realtime("sippeers", "host", ipaddr, "port", portstring, SENTINEL);
04786 if (var) {
04787 if (realtimeregs) {
04788 newpeername = get_name_from_variable(var, newpeername);
04789 varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04790 }
04791 } else {
04792 if (realtimeregs)
04793 varregs = ast_load_realtime("sipregs", "ipaddr", ipaddr, "port", portstring, SENTINEL);
04794 else
04795 var = ast_load_realtime("sippeers", "ipaddr", ipaddr, "port", portstring, SENTINEL);
04796 if (varregs) {
04797 newpeername = get_name_from_variable(varregs, newpeername);
04798 var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
04799 }
04800 }
04801 if (!var) {
04802 peerlist = ast_load_realtime_multientry("sippeers", "host", ipaddr, SENTINEL);
04803 if (peerlist) {
04804 var = get_insecure_variable_from_config(peerlist);
04805 if(var) {
04806 if (realtimeregs) {
04807 newpeername = get_name_from_variable(var, newpeername);
04808 varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04809 }
04810 } else {
04811 peerlist = NULL;
04812 cat = NULL;
04813 peerlist = ast_load_realtime_multientry("sippeers", "ipaddr", ipaddr, SENTINEL);
04814 if(peerlist) {
04815 var = get_insecure_variable_from_config(peerlist);
04816 if(var) {
04817 if (realtimeregs) {
04818 newpeername = get_name_from_variable(var, newpeername);
04819 varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04820 }
04821 }
04822 }
04823 }
04824 } else {
04825 if (realtimeregs) {
04826 peerlist = ast_load_realtime_multientry("sipregs", "ipaddr", ipaddr, SENTINEL);
04827 if (peerlist) {
04828 varregs = get_insecure_variable_from_config(peerlist);
04829 if (varregs) {
04830 newpeername = get_name_from_variable(varregs, newpeername);
04831 var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
04832 }
04833 }
04834 } else {
04835 peerlist = ast_load_realtime_multientry("sippeers", "ipaddr", ipaddr, SENTINEL);
04836 if (peerlist) {
04837 var = get_insecure_variable_from_config(peerlist);
04838 if (var) {
04839 newpeername = get_name_from_variable(var, newpeername);
04840 varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04841 }
04842 }
04843 }
04844 }
04845 }
04846 }
04847
04848 if (!var) {
04849 if (peerlist)
04850 ast_config_destroy(peerlist);
04851 return NULL;
04852 }
04853
04854 for (tmp = var; tmp; tmp = tmp->next) {
04855 if (!newpeername && !strcasecmp(tmp->name, "name")) {
04856 newpeername = tmp->value;
04857 }
04858 }
04859
04860 if (!newpeername) {
04861 ast_log(LOG_WARNING, "Cannot Determine peer name ip=%s\n", ipaddr);
04862 if(peerlist)
04863 ast_config_destroy(peerlist);
04864 else
04865 ast_variables_destroy(var);
04866 return NULL;
04867 }
04868
04869
04870
04871 peer = build_peer(newpeername, var, varregs, TRUE, devstate_only);
04872 if (!peer) {
04873 if(peerlist)
04874 ast_config_destroy(peerlist);
04875 else {
04876 ast_variables_destroy(var);
04877 ast_variables_destroy(varregs);
04878 }
04879 return NULL;
04880 }
04881
04882 ast_debug(3, "-REALTIME- loading peer from database to memory. Name: %s. Peer objects: %d\n", peer->name, rpeerobjs);
04883
04884 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && !devstate_only) {
04885
04886 ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
04887 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
04888 AST_SCHED_REPLACE_UNREF(peer->expire, sched, sip_cfg.rtautoclear * 1000, expire_register, peer,
04889 unref_peer(_data, "remove registration ref"),
04890 unref_peer(peer, "remove registration ref"),
04891 ref_peer(peer, "add registration ref"));
04892 }
04893 ao2_t_link(peers, peer, "link peer into peers table");
04894 if (peer->addr.sin_addr.s_addr) {
04895 ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
04896 }
04897 }
04898 peer->is_realtime = 1;
04899 if (peerlist)
04900 ast_config_destroy(peerlist);
04901 else {
04902 ast_variables_destroy(var);
04903 ast_variables_destroy(varregs);
04904 }
04905
04906 return peer;
04907 }
04908
04909
04910 static int find_by_name(void *obj, void *arg, void *data, int flags)
04911 {
04912 struct sip_peer *search = obj, *match = arg;
04913 int *which_objects = data;
04914
04915
04916 if (strcmp(search->name, match->name)) {
04917 return 0;
04918 }
04919
04920 switch (*which_objects) {
04921 case FINDUSERS:
04922 if (!(search->type & SIP_TYPE_USER)) {
04923 return 0;
04924 }
04925 break;
04926 case FINDPEERS:
04927 if (!(search->type & SIP_TYPE_PEER)) {
04928 return 0;
04929 }
04930 break;
04931 case FINDALLDEVICES:
04932 break;
04933 }
04934
04935 return CMP_MATCH | CMP_STOP;
04936 }
04937
04938
04939
04940
04941
04942
04943
04944
04945
04946
04947
04948
04949
04950
04951 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime, int which_objects, int devstate_only, int transport)
04952 {
04953 struct sip_peer *p = NULL;
04954 struct sip_peer tmp_peer;
04955
04956 if (peer) {
04957 ast_copy_string(tmp_peer.name, peer, sizeof(tmp_peer.name));
04958 p = ao2_t_callback_data(peers, OBJ_POINTER, find_by_name, &tmp_peer, &which_objects, "ao2_find in peers table");
04959 } else if (sin) {
04960 tmp_peer.addr.sin_addr.s_addr = sin->sin_addr.s_addr;
04961 tmp_peer.addr.sin_port = sin->sin_port;
04962 tmp_peer.flags[0].flags = 0;
04963 tmp_peer.transports = transport;
04964 p = ao2_t_find(peers_by_ip, &tmp_peer, OBJ_POINTER, "ao2_find in peers_by_ip table");
04965 if (!p) {
04966 ast_set_flag(&tmp_peer.flags[0], SIP_INSECURE_PORT);
04967 p = ao2_t_find(peers_by_ip, &tmp_peer, OBJ_POINTER, "ao2_find in peers_by_ip table 2");
04968 if (p) {
04969 return p;
04970 }
04971 }
04972 }
04973
04974 if (!p && (realtime || devstate_only)) {
04975 p = realtime_peer(peer, sin, devstate_only);
04976 if (p) {
04977 switch (which_objects) {
04978 case FINDUSERS:
04979 if (!(p->type & SIP_TYPE_USER)) {
04980 unref_peer(p, "Wrong type of realtime SIP endpoint");
04981 return NULL;
04982 }
04983 break;
04984 case FINDPEERS:
04985 if (!(p->type & SIP_TYPE_PEER)) {
04986 unref_peer(p, "Wrong type of realtime SIP endpoint");
04987 return NULL;
04988 }
04989 break;
04990 case FINDALLDEVICES:
04991 break;
04992 }
04993 }
04994 }
04995
04996 return p;
04997 }
04998
04999
05000 static void do_setnat(struct sip_pvt *p, int natflags)
05001 {
05002 const char *mode = natflags ? "On" : "Off";
05003
05004 if (p->rtp) {
05005 ast_debug(1, "Setting NAT on RTP to %s\n", mode);
05006 ast_rtp_setnat(p->rtp, natflags);
05007 }
05008 if (p->vrtp) {
05009 ast_debug(1, "Setting NAT on VRTP to %s\n", mode);
05010 ast_rtp_setnat(p->vrtp, natflags);
05011 }
05012 if (p->udptl) {
05013 ast_debug(1, "Setting NAT on UDPTL to %s\n", mode);
05014 ast_udptl_setnat(p->udptl, natflags);
05015 }
05016 if (p->trtp) {
05017 ast_debug(1, "Setting NAT on TRTP to %s\n", mode);
05018 ast_rtp_setnat(p->trtp, natflags);
05019 }
05020 }
05021
05022
05023 static void change_t38_state(struct sip_pvt *p, int state)
05024 {
05025 int old = p->t38.state;
05026 struct ast_channel *chan = p->owner;
05027 struct ast_control_t38_parameters parameters = { .request_response = 0 };
05028
05029
05030 if (old == state)
05031 return;
05032
05033 p->t38.state = state;
05034 ast_debug(2, "T38 state changed to %d on channel %s\n", p->t38.state, chan ? chan->name : "<none>");
05035
05036
05037 if (!chan)
05038 return;
05039
05040
05041 switch (state) {
05042 case T38_PEER_REINVITE:
05043 parameters = p->t38.their_parms;
05044 parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
05045 parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
05046 ast_udptl_set_tag(p->udptl, "SIP/%s", p->username);
05047 break;
05048 case T38_ENABLED:
05049 parameters = p->t38.their_parms;
05050 parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
05051 parameters.request_response = AST_T38_NEGOTIATED;
05052 ast_udptl_set_tag(p->udptl, "SIP/%s", p->username);
05053 break;
05054 case T38_DISABLED:
05055 if (old == T38_ENABLED) {
05056 parameters.request_response = AST_T38_TERMINATED;
05057 } else if (old == T38_LOCAL_REINVITE) {
05058 parameters.request_response = AST_T38_REFUSED;
05059 }
05060 break;
05061 case T38_LOCAL_REINVITE:
05062
05063 break;
05064 }
05065
05066
05067 if (parameters.request_response)
05068 ast_queue_control_data(chan, AST_CONTROL_T38_PARAMETERS, ¶meters, sizeof(parameters));
05069 }
05070
05071
05072 static void set_t38_capabilities(struct sip_pvt *p)
05073 {
05074 if (p->udptl) {
05075 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY) {
05076 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
05077 } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_FEC) {
05078 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
05079 } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL) {
05080 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
05081 }
05082 }
05083 }
05084
05085 static void copy_socket_data(struct sip_socket *to_sock, const struct sip_socket *from_sock)
05086 {
05087 if (to_sock->tcptls_session) {
05088 ao2_ref(to_sock->tcptls_session, -1);
05089 to_sock->tcptls_session = NULL;
05090 }
05091
05092 if (from_sock->tcptls_session) {
05093 ao2_ref(from_sock->tcptls_session, +1);
05094 }
05095
05096 *to_sock = *from_sock;
05097 }
05098
05099
05100
05101
05102
05103
05104
05105
05106 static int create_addr_from_peer(struct sip_pvt *dialog, struct sip_peer *peer)
05107 {
05108
05109
05110
05111
05112 if (dialog->socket.type && check_request_transport(peer, dialog))
05113 return -1;
05114 copy_socket_data(&dialog->socket, &peer->socket);
05115
05116 if ((peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr) &&
05117 (!peer->maxms || ((peer->lastms >= 0) && (peer->lastms <= peer->maxms)))) {
05118 dialog->sa = (peer->addr.sin_addr.s_addr) ? peer->addr : peer->defaddr;
05119 dialog->recv = dialog->sa;
05120 } else
05121 return -1;
05122
05123 ast_copy_flags(&dialog->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
05124 ast_copy_flags(&dialog->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
05125 dialog->capability = peer->capability;
05126 if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS) &&
05127 (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT) ||
05128 !(dialog->capability & AST_FORMAT_VIDEO_MASK)) &&
05129 dialog->vrtp) {
05130 ast_rtp_destroy(dialog->vrtp);
05131 dialog->vrtp = NULL;
05132 }
05133 if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_TEXTSUPPORT) && dialog->trtp) {
05134 ast_rtp_destroy(dialog->trtp);
05135 dialog->trtp = NULL;
05136 }
05137 dialog->prefs = peer->prefs;
05138 if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_T38SUPPORT)) {
05139
05140 if (dialog->udptl || (!dialog->udptl && (dialog->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr)))) {
05141 dialog->t38_maxdatagram = peer->t38_maxdatagram;
05142 set_t38_capabilities(dialog);
05143 } else {
05144
05145 ast_debug(1, "UDPTL creation failed on dialog.\n");
05146 ast_clear_flag(&dialog->flags[1], SIP_PAGE2_T38SUPPORT);
05147 }
05148 } else if (dialog->udptl) {
05149 ast_udptl_destroy(dialog->udptl);
05150 dialog->udptl = NULL;
05151 }
05152 do_setnat(dialog, ast_test_flag(&dialog->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
05153
05154 if (dialog->rtp) {
05155 ast_rtp_setdtmf(dialog->rtp, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
05156 ast_rtp_setdtmfcompensate(dialog->rtp, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
05157 ast_rtp_set_rtptimeout(dialog->rtp, peer->rtptimeout);
05158 ast_rtp_set_rtpholdtimeout(dialog->rtp, peer->rtpholdtimeout);
05159 ast_rtp_set_rtpkeepalive(dialog->rtp, peer->rtpkeepalive);
05160
05161 ast_rtp_codec_setpref(dialog->rtp, &dialog->prefs);
05162 dialog->autoframing = peer->autoframing;
05163 }
05164 if (dialog->vrtp) {
05165 ast_rtp_setdtmf(dialog->vrtp, 0);
05166 ast_rtp_setdtmfcompensate(dialog->vrtp, 0);
05167 ast_rtp_set_rtptimeout(dialog->vrtp, peer->rtptimeout);
05168 ast_rtp_set_rtpholdtimeout(dialog->vrtp, peer->rtpholdtimeout);
05169 ast_rtp_set_rtpkeepalive(dialog->vrtp, peer->rtpkeepalive);
05170 }
05171 if (dialog->trtp) {
05172 ast_rtp_setdtmf(dialog->trtp, 0);
05173 ast_rtp_setdtmfcompensate(dialog->trtp, 0);
05174 ast_rtp_set_rtptimeout(dialog->trtp, peer->rtptimeout);
05175 ast_rtp_set_rtpholdtimeout(dialog->trtp, peer->rtpholdtimeout);
05176 ast_rtp_set_rtpkeepalive(dialog->trtp, peer->rtpkeepalive);
05177 }
05178
05179 ast_string_field_set(dialog, peername, peer->name);
05180 ast_string_field_set(dialog, authname, peer->username);
05181 ast_string_field_set(dialog, username, peer->username);
05182 ast_string_field_set(dialog, peersecret, peer->secret);
05183 ast_string_field_set(dialog, peermd5secret, peer->md5secret);
05184 ast_string_field_set(dialog, mohsuggest, peer->mohsuggest);
05185 ast_string_field_set(dialog, mohinterpret, peer->mohinterpret);
05186 ast_string_field_set(dialog, tohost, peer->tohost);
05187 ast_string_field_set(dialog, fullcontact, peer->fullcontact);
05188 ast_string_field_set(dialog, context, peer->context);
05189 ast_string_field_set(dialog, parkinglot, peer->parkinglot);
05190 ref_proxy(dialog, obproxy_get(dialog, peer));
05191 dialog->callgroup = peer->callgroup;
05192 dialog->pickupgroup = peer->pickupgroup;
05193 dialog->allowtransfer = peer->allowtransfer;
05194 dialog->jointnoncodeccapability = dialog->noncodeccapability;
05195 dialog->rtptimeout = peer->rtptimeout;
05196 dialog->peerauth = peer->auth;
05197 dialog->maxcallbitrate = peer->maxcallbitrate;
05198 if (ast_strlen_zero(dialog->tohost))
05199 ast_string_field_set(dialog, tohost, ast_inet_ntoa(dialog->sa.sin_addr));
05200 if (!ast_strlen_zero(peer->fromdomain)) {
05201 ast_string_field_set(dialog, fromdomain, peer->fromdomain);
05202 if (!dialog->initreq.headers) {
05203 char *c;
05204 char *tmpcall = ast_strdupa(dialog->callid);
05205
05206 c = strchr(tmpcall, '@');
05207 if (c) {
05208 *c = '\0';
05209 ao2_t_unlink(dialogs, dialog, "About to change the callid -- remove the old name");
05210 ast_string_field_build(dialog, callid, "%s@%s", tmpcall, peer->fromdomain);
05211 ao2_t_link(dialogs, dialog, "New dialog callid -- inserted back into table");
05212 }
05213 }
05214 }
05215 if (!ast_strlen_zero(peer->fromuser))
05216 ast_string_field_set(dialog, fromuser, peer->fromuser);
05217 if (!ast_strlen_zero(peer->language))
05218 ast_string_field_set(dialog, language, peer->language);
05219
05220
05221
05222
05223 if (peer->maxms && peer->lastms)
05224 dialog->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
05225 else
05226 dialog->timer_t1 = peer->timer_t1;
05227
05228
05229
05230 if (peer->timer_b)
05231 dialog->timer_b = peer->timer_b;
05232 else
05233 dialog->timer_b = 64 * dialog->timer_t1;
05234
05235 if ((ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
05236 (ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
05237 dialog->noncodeccapability |= AST_RTP_DTMF;
05238 else
05239 dialog->noncodeccapability &= ~AST_RTP_DTMF;
05240 if (peer->call_limit)
05241 ast_set_flag(&dialog->flags[0], SIP_CALL_LIMIT);
05242 if (!dialog->portinuri)
05243 dialog->portinuri = peer->portinuri;
05244
05245 dialog->chanvars = copy_vars(peer->chanvars);
05246
05247 return 0;
05248 }
05249
05250
05251
05252
05253 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct sockaddr_in *sin, int newdialog)
05254 {
05255 struct hostent *hp;
05256 struct ast_hostent ahp;
05257 struct sip_peer *peer;
05258 char *port;
05259 int portno = 0;
05260 char host[MAXHOSTNAMELEN], *hostn;
05261 char peername[256];
05262 int srv_ret = 0;
05263
05264 ast_copy_string(peername, opeer, sizeof(peername));
05265 port = strchr(peername, ':');
05266 if (port) {
05267 *port++ = '\0';
05268 dialog->portinuri = 1;
05269 }
05270 dialog->sa.sin_family = AF_INET;
05271 dialog->timer_t1 = global_t1;
05272 dialog->timer_b = global_timer_b;
05273 peer = find_peer(peername, NULL, TRUE, FINDPEERS, FALSE, 0);
05274
05275 if (peer) {
05276 int res;
05277 if (newdialog) {
05278 set_socket_transport(&dialog->socket, 0);
05279 }
05280 res = create_addr_from_peer(dialog, peer);
05281 if (!ast_strlen_zero(port)) {
05282 if ((portno = atoi(port))) {
05283 dialog->sa.sin_port = dialog->recv.sin_port = htons(portno);
05284 }
05285 }
05286 unref_peer(peer, "create_addr: unref peer from find_peer hashtab lookup");
05287 return res;
05288 }
05289
05290 do_setnat(dialog, ast_test_flag(&dialog->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
05291
05292 ast_string_field_set(dialog, tohost, peername);
05293
05294
05295 ref_proxy(dialog, obproxy_get(dialog, NULL));
05296
05297 if (sin) {
05298
05299 memcpy(&dialog->sa.sin_addr, &sin->sin_addr, sizeof(dialog->sa.sin_addr));
05300 if (!sin->sin_port) {
05301 portno = port_str2int(port, (dialog->socket.type == SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT);
05302 } else {
05303 portno = ntohs(sin->sin_port);
05304 }
05305 } else {
05306
05307
05308
05309
05310
05311
05312 hostn = peername;
05313
05314
05315
05316 if (!port && sip_cfg.srvlookup) {
05317 char service[MAXHOSTNAMELEN];
05318 int tportno;
05319
05320 snprintf(service, sizeof(service), "_sip._%s.%s", get_transport(dialog->socket.type), peername);
05321 srv_ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
05322 if (srv_ret > 0) {
05323 hostn = host;
05324 portno = tportno;
05325 }
05326 }
05327 if (!portno)
05328 portno = port_str2int(port, (dialog->socket.type == SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT);
05329 hp = ast_gethostbyname(hostn, &ahp);
05330 if (!hp) {
05331 ast_log(LOG_WARNING, "No such host: %s\n", peername);
05332 return -1;
05333 }
05334 memcpy(&dialog->sa.sin_addr, hp->h_addr, sizeof(dialog->sa.sin_addr));
05335 }
05336
05337 if (!dialog->socket.type)
05338 set_socket_transport(&dialog->socket, SIP_TRANSPORT_UDP);
05339 if (!dialog->socket.port)
05340 dialog->socket.port = bindaddr.sin_port;
05341 dialog->sa.sin_port = htons(portno);
05342 dialog->recv = dialog->sa;
05343 return 0;
05344 }
05345
05346
05347
05348
05349 static int auto_congest(const void *arg)
05350 {
05351 struct sip_pvt *p = (struct sip_pvt *)arg;
05352
05353 sip_pvt_lock(p);
05354 p->initid = -1;
05355 if (p->owner) {
05356
05357 if (!ast_channel_trylock(p->owner)) {
05358 append_history(p, "Cong", "Auto-congesting (timer)");
05359 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
05360 ast_channel_unlock(p->owner);
05361 }
05362
05363
05364 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
05365 }
05366 sip_pvt_unlock(p);
05367 dialog_unref(p, "unreffing arg passed into auto_congest callback (p->initid)");
05368 return 0;
05369 }
05370
05371
05372
05373
05374 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
05375 {
05376 int res;
05377 struct sip_pvt *p = ast->tech_pvt;
05378 struct varshead *headp;
05379 struct ast_var_t *current;
05380 const char *referer = NULL;
05381
05382 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
05383 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
05384 return -1;
05385 }
05386
05387
05388 headp=&ast->varshead;
05389 AST_LIST_TRAVERSE(headp, current, entries) {
05390
05391 if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
05392 p->options->vxml_url = ast_var_value(current);
05393 } else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
05394 p->options->uri_options = ast_var_value(current);
05395 } else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
05396
05397 p->options->addsipheaders = 1;
05398 } else if (!strcasecmp(ast_var_name(current), "SIPFROMDOMAIN")) {
05399 ast_string_field_set(p, fromdomain, ast_var_value(current));
05400 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER")) {
05401
05402 p->options->transfer = 1;
05403 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REFERER")) {
05404
05405 referer = ast_var_value(current);
05406 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REPLACES")) {
05407
05408 p->options->replaces = ast_var_value(current);
05409 }
05410 }
05411
05412 res = 0;
05413 ast_set_flag(&p->flags[0], SIP_OUTGOING);
05414
05415
05416
05417
05418 ast_clear_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_T38);
05419
05420 if (p->options->transfer) {
05421 char buf[SIPBUFSIZE/2];
05422
05423 if (referer) {
05424 if (sipdebug)
05425 ast_debug(3, "Call for %s transfered by %s\n", p->username, referer);
05426 snprintf(buf, sizeof(buf)-1, "-> %s (via %s)", p->cid_name, referer);
05427 } else
05428 snprintf(buf, sizeof(buf)-1, "-> %s", p->cid_name);
05429 ast_string_field_set(p, cid_name, buf);
05430 }
05431 ast_debug(1, "Outgoing Call for %s\n", p->username);
05432
05433 res = update_call_counter(p, INC_CALL_RINGING);
05434
05435 if (res == -1) {
05436 ast->hangupcause = AST_CAUSE_USER_BUSY;
05437 return res;
05438 }
05439 p->callingpres = ast->cid.cid_pres;
05440 p->jointcapability = ast_translate_available_formats(p->capability, p->prefcodec);
05441 p->jointnoncodeccapability = p->noncodeccapability;
05442
05443
05444 if (!(p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
05445 ast_log(LOG_WARNING, "No audio format found to offer. Cancelling call to %s\n", p->username);
05446 res = -1;
05447 } else {
05448 int xmitres;
05449
05450 xmitres = transmit_invite(p, SIP_INVITE, 1, 2);
05451 if (xmitres == XMIT_ERROR)
05452 return -1;
05453 p->invitestate = INV_CALLING;
05454
05455
05456 AST_SCHED_REPLACE_UNREF(p->initid, sched, p->timer_b, auto_congest, p,
05457 dialog_unref(_data, "dialog ptr dec when SCHED_REPLACE del op succeeded"),
05458 dialog_unref(p, "dialog ptr dec when SCHED_REPLACE add failed"),
05459 dialog_ref(p, "dialog ptr inc when SCHED_REPLACE add succeeded") );
05460 }
05461 return res;
05462 }
05463
05464
05465
05466 static void sip_registry_destroy(struct sip_registry *reg)
05467 {
05468
05469 ast_debug(3, "Destroying registry entry for %s@%s\n", reg->username, reg->hostname);
05470
05471 if (reg->call) {
05472
05473
05474 reg->call->registry = registry_unref(reg->call->registry, "destroy reg->call->registry");
05475 ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", reg->username, reg->hostname);
05476 dialog_unlink_all(reg->call, TRUE, TRUE);
05477 reg->call = dialog_unref(reg->call, "unref reg->call");
05478
05479 }
05480 AST_SCHED_DEL(sched, reg->expire);
05481 AST_SCHED_DEL(sched, reg->timeout);
05482
05483 ast_string_field_free_memory(reg);
05484 ast_atomic_fetchadd_int(®objs, -1);
05485 ast_dnsmgr_release(reg->dnsmgr);
05486 ast_free(reg);
05487 }
05488
05489
05490 static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi)
05491 {
05492 if (mwi->call) {
05493 mwi->call->mwi = NULL;
05494 sip_destroy(mwi->call);
05495 }
05496
05497 AST_SCHED_DEL(sched, mwi->resub);
05498 ast_string_field_free_memory(mwi);
05499 ast_dnsmgr_release(mwi->dnsmgr);
05500 ast_free(mwi);
05501 }
05502
05503
05504 static void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist)
05505 {
05506 struct sip_request *req;
05507
05508 if (p->stimer) {
05509 ast_free(p->stimer);
05510 p->stimer = NULL;
05511 }
05512
05513 if (sip_debug_test_pvt(p))
05514 ast_verbose("Really destroying SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
05515
05516 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
05517 update_call_counter(p, DEC_CALL_LIMIT);
05518 ast_debug(2, "This call did not properly clean up call limits. Call ID %s\n", p->callid);
05519 }
05520
05521
05522 if (p->owner) {
05523 if (lockowner)
05524 ast_channel_lock(p->owner);
05525 if (option_debug)
05526 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
05527 p->owner->tech_pvt = NULL;
05528
05529 p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
05530 if (lockowner)
05531 ast_channel_unlock(p->owner);
05532
05533 usleep(1);
05534 }
05535
05536
05537 if (p->relatedpeer && p->relatedpeer->mwipvt)
05538 p->relatedpeer->mwipvt = dialog_unref(p->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
05539 if (p->relatedpeer && p->relatedpeer->call == p)
05540 p->relatedpeer->call = dialog_unref(p->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
05541
05542 if (p->relatedpeer)
05543 p->relatedpeer = unref_peer(p->relatedpeer,"unsetting a dialog relatedpeer field in sip_destroy");
05544
05545 if (p->registry) {
05546 if (p->registry->call == p)
05547 p->registry->call = dialog_unref(p->registry->call, "nulling out the registry's call dialog field in unlink_all");
05548 p->registry = registry_unref(p->registry, "delete p->registry");
05549 }
05550
05551 if (p->mwi) {
05552 p->mwi->call = NULL;
05553 }
05554
05555 if (dumphistory)
05556 sip_dump_history(p);
05557
05558 if (p->options)
05559 ast_free(p->options);
05560
05561 if (p->notify_headers) {
05562 ast_variables_destroy(p->notify_headers);
05563 p->notify_headers = NULL;
05564 }
05565 if (p->rtp) {
05566 ast_rtp_destroy(p->rtp);
05567 }
05568 if (p->vrtp) {
05569 ast_rtp_destroy(p->vrtp);
05570 }
05571 if (p->trtp) {
05572 while (ast_rtp_get_bridged(p->trtp))
05573 usleep(1);
05574 ast_rtp_destroy(p->trtp);
05575 }
05576 if (p->udptl)
05577 ast_udptl_destroy(p->udptl);
05578 if (p->refer)
05579 ast_free(p->refer);
05580 if (p->route) {
05581 free_old_route(p->route);
05582 p->route = NULL;
05583 }
05584 deinit_req(&p->initreq);
05585
05586
05587 if (p->stimer) {
05588 p->stimer->quit_flag = 1;
05589 if (p->stimer->st_active == TRUE && p->stimer->st_schedid > -1) {
05590 AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
05591 dialog_unref(p, "removing session timer ref"));
05592 }
05593 ast_free(p->stimer);
05594 p->stimer = NULL;
05595 }
05596
05597
05598 if (p->history) {
05599 struct sip_history *hist;
05600 while ( (hist = AST_LIST_REMOVE_HEAD(p->history, list)) ) {
05601 ast_free(hist);
05602 p->history_entries--;
05603 }
05604 ast_free(p->history);
05605 p->history = NULL;
05606 }
05607
05608 while ((req = AST_LIST_REMOVE_HEAD(&p->request_queue, next))) {
05609 ast_free(req);
05610 }
05611
05612 if (p->chanvars) {
05613 ast_variables_destroy(p->chanvars);
05614 p->chanvars = NULL;
05615 }
05616
05617 ast_string_field_free_memory(p);
05618
05619 if (p->socket.tcptls_session) {
05620 ao2_ref(p->socket.tcptls_session, -1);
05621 p->socket.tcptls_session = NULL;
05622 }
05623 }
05624
05625
05626
05627
05628
05629
05630
05631
05632
05633
05634
05635
05636
05637
05638
05639 static int update_call_counter(struct sip_pvt *fup, int event)
05640 {
05641 char name[256];
05642 int *inuse = NULL, *call_limit = NULL, *inringing = NULL;
05643 int outgoing = fup->outgoing_call;
05644 struct sip_peer *p = NULL;
05645
05646 ast_debug(3, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
05647
05648
05649
05650
05651 if (!ast_test_flag(&fup->flags[0], SIP_CALL_LIMIT) && !ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD))
05652 return 0;
05653
05654 ast_copy_string(name, fup->username, sizeof(name));
05655
05656
05657 if ((p = find_peer(ast_strlen_zero(fup->peername) ? name : fup->peername, NULL, TRUE, FINDALLDEVICES, FALSE, 0))) {
05658 inuse = &p->inUse;
05659 call_limit = &p->call_limit;
05660 inringing = &p->inRinging;
05661 ast_copy_string(name, fup->peername, sizeof(name));
05662 }
05663 if (!p) {
05664 ast_debug(2, "%s is not a local device, no call limit\n", name);
05665 return 0;
05666 }
05667
05668 switch(event) {
05669
05670 case DEC_CALL_LIMIT:
05671
05672 if (inuse) {
05673 sip_pvt_lock(fup);
05674 ao2_lock(p);
05675 if (*inuse > 0) {
05676 if (ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
05677 (*inuse)--;
05678 ast_clear_flag(&fup->flags[0], SIP_INC_COUNT);
05679 }
05680 } else {
05681 *inuse = 0;
05682 }
05683 ao2_unlock(p);
05684 sip_pvt_unlock(fup);
05685 }
05686
05687
05688 if (inringing) {
05689 sip_pvt_lock(fup);
05690 ao2_lock(p);
05691 if (*inringing > 0) {
05692 if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
05693 (*inringing)--;
05694 ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
05695 }
05696 } else {
05697 *inringing = 0;
05698 }
05699 ao2_unlock(p);
05700 sip_pvt_unlock(fup);
05701 }
05702
05703
05704 sip_pvt_lock(fup);
05705 ao2_lock(p);
05706 if (ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD) && sip_cfg.notifyhold) {
05707 ast_clear_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD);
05708 ao2_unlock(p);
05709 sip_pvt_unlock(fup);
05710 sip_peer_hold(fup, FALSE);
05711 } else {
05712 ao2_unlock(p);
05713 sip_pvt_unlock(fup);
05714 }
05715 if (sipdebug)
05716 ast_debug(2, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
05717 break;
05718
05719 case INC_CALL_RINGING:
05720 case INC_CALL_LIMIT:
05721
05722 if (*call_limit > 0 ) {
05723 if (*inuse >= *call_limit) {
05724 ast_log(LOG_NOTICE, "Call %s %s '%s' rejected due to usage limit of %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
05725 unref_peer(p, "update_call_counter: unref peer p, call limit exceeded");
05726 return -1;
05727 }
05728 }
05729 if (inringing && (event == INC_CALL_RINGING)) {
05730 sip_pvt_lock(fup);
05731 ao2_lock(p);
05732 if (!ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
05733 (*inringing)++;
05734 ast_set_flag(&fup->flags[0], SIP_INC_RINGING);
05735 }
05736 ao2_unlock(p);
05737 sip_pvt_unlock(fup);
05738 }
05739 if (inuse) {
05740 sip_pvt_lock(fup);
05741 ao2_lock(p);
05742 if (!ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
05743 (*inuse)++;
05744 ast_set_flag(&fup->flags[0], SIP_INC_COUNT);
05745 }
05746 ao2_unlock(p);
05747 sip_pvt_unlock(fup);
05748 }
05749 if (sipdebug) {
05750 ast_debug(2, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", "peer", name, *inuse, *call_limit);
05751 }
05752 break;
05753
05754 case DEC_CALL_RINGING:
05755 if (inringing) {
05756 sip_pvt_lock(fup);
05757 ao2_lock(p);
05758 if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
05759 if (*inringing > 0) {
05760 (*inringing)--;
05761 }
05762 ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
05763 }
05764 ao2_unlock(p);
05765 sip_pvt_unlock(fup);
05766 }
05767 break;
05768
05769 default:
05770 ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
05771 }
05772
05773 if (p) {
05774 ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", p->name);
05775 unref_peer(p, "update_call_counter: unref_peer from call counter");
05776 }
05777 return 0;
05778 }
05779
05780
05781 static void sip_destroy_fn(void *p)
05782 {
05783 sip_destroy(p);
05784 }
05785
05786
05787
05788
05789
05790
05791 static struct sip_pvt * sip_destroy(struct sip_pvt *p)
05792 {
05793 ast_debug(3, "Destroying SIP dialog %s\n", p->callid);
05794 __sip_destroy(p, TRUE, TRUE);
05795 return NULL;
05796 }
05797
05798
05799 static int hangup_sip2cause(int cause)
05800 {
05801
05802
05803 switch(cause) {
05804 case 401:
05805 return AST_CAUSE_CALL_REJECTED;
05806 case 403:
05807 return AST_CAUSE_CALL_REJECTED;
05808 case 404:
05809 return AST_CAUSE_UNALLOCATED;
05810 case 405:
05811 return AST_CAUSE_INTERWORKING;
05812 case 407:
05813 return AST_CAUSE_CALL_REJECTED;
05814 case 408:
05815 return AST_CAUSE_NO_USER_RESPONSE;
05816 case 409:
05817 return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
05818 case 410:
05819 return AST_CAUSE_NUMBER_CHANGED;
05820 case 411:
05821 return AST_CAUSE_INTERWORKING;
05822 case 413:
05823 return AST_CAUSE_INTERWORKING;
05824 case 414:
05825 return AST_CAUSE_INTERWORKING;
05826 case 415:
05827 return AST_CAUSE_INTERWORKING;
05828 case 420:
05829 return AST_CAUSE_NO_ROUTE_DESTINATION;
05830 case 480:
05831 return AST_CAUSE_NO_ANSWER;
05832 case 481:
05833 return AST_CAUSE_INTERWORKING;
05834 case 482:
05835 return AST_CAUSE_INTERWORKING;
05836 case 483:
05837 return AST_CAUSE_NO_ANSWER;
05838 case 484:
05839 return AST_CAUSE_INVALID_NUMBER_FORMAT;
05840 case 485:
05841 return AST_CAUSE_UNALLOCATED;
05842 case 486:
05843 return AST_CAUSE_BUSY;
05844 case 487:
05845 return AST_CAUSE_INTERWORKING;
05846 case 488:
05847 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
05848 case 491:
05849 return AST_CAUSE_INTERWORKING;
05850 case 493:
05851 return AST_CAUSE_INTERWORKING;
05852 case 500:
05853 return AST_CAUSE_FAILURE;
05854 case 501:
05855 return AST_CAUSE_FACILITY_REJECTED;
05856 case 502:
05857 return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
05858 case 503:
05859 return AST_CAUSE_CONGESTION;
05860 case 504:
05861 return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
05862 case 505:
05863 return AST_CAUSE_INTERWORKING;
05864 case 600:
05865 return AST_CAUSE_USER_BUSY;
05866 case 603:
05867 return AST_CAUSE_CALL_REJECTED;
05868 case 604:
05869 return AST_CAUSE_UNALLOCATED;
05870 case 606:
05871 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
05872 default:
05873 return AST_CAUSE_NORMAL;
05874 }
05875
05876 return 0;
05877 }
05878
05879
05880
05881
05882
05883
05884
05885
05886
05887
05888
05889
05890
05891
05892
05893
05894
05895
05896
05897
05898
05899
05900
05901
05902
05903
05904
05905
05906
05907
05908
05909
05910
05911 static const char *hangup_cause2sip(int cause)
05912 {
05913 switch (cause) {
05914 case AST_CAUSE_UNALLOCATED:
05915 case AST_CAUSE_NO_ROUTE_DESTINATION:
05916 case AST_CAUSE_NO_ROUTE_TRANSIT_NET:
05917 return "404 Not Found";
05918 case AST_CAUSE_CONGESTION:
05919 case AST_CAUSE_SWITCH_CONGESTION:
05920 return "503 Service Unavailable";
05921 case AST_CAUSE_NO_USER_RESPONSE:
05922 return "408 Request Timeout";
05923 case AST_CAUSE_NO_ANSWER:
05924 case AST_CAUSE_UNREGISTERED:
05925 return "480 Temporarily unavailable";
05926 case AST_CAUSE_CALL_REJECTED:
05927 return "403 Forbidden";
05928 case AST_CAUSE_NUMBER_CHANGED:
05929 return "410 Gone";
05930 case AST_CAUSE_NORMAL_UNSPECIFIED:
05931 return "480 Temporarily unavailable";
05932 case AST_CAUSE_INVALID_NUMBER_FORMAT:
05933 return "484 Address incomplete";
05934 case AST_CAUSE_USER_BUSY:
05935 return "486 Busy here";
05936 case AST_CAUSE_FAILURE:
05937 return "500 Server internal failure";
05938 case AST_CAUSE_FACILITY_REJECTED:
05939 return "501 Not Implemented";
05940 case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
05941 return "503 Service Unavailable";
05942
05943 case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
05944 return "502 Bad Gateway";
05945 case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL:
05946 return "488 Not Acceptable Here";
05947
05948 case AST_CAUSE_NOTDEFINED:
05949 default:
05950 ast_debug(1, "AST hangup cause %d (no match found in SIP)\n", cause);
05951 return NULL;
05952 }
05953
05954
05955 return 0;
05956 }
05957
05958
05959
05960
05961 static int sip_hangup(struct ast_channel *ast)
05962 {
05963 struct sip_pvt *p = ast->tech_pvt;
05964 int needcancel = FALSE;
05965 int needdestroy = 0;
05966 struct ast_channel *oldowner = ast;
05967
05968 if (!p) {
05969 ast_debug(1, "Asked to hangup channel that was not connected\n");
05970 return 0;
05971 }
05972 if (ast_test_flag(ast, AST_FLAG_ANSWERED_ELSEWHERE) || ast->hangupcause == AST_CAUSE_ANSWERED_ELSEWHERE) {
05973 ast_debug(1, "This call was answered elsewhere");
05974 if (ast->hangupcause == AST_CAUSE_ANSWERED_ELSEWHERE) {
05975 ast_debug(1, "####### It's the cause code, buddy. The cause code!!!\n");
05976 }
05977 append_history(p, "Cancel", "Call answered elsewhere");
05978 p->answered_elsewhere = TRUE;
05979 }
05980
05981
05982 if (p->owner)
05983 p->hangupcause = p->owner->hangupcause;
05984
05985 if (ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
05986 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
05987 if (sipdebug)
05988 ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
05989 update_call_counter(p, DEC_CALL_LIMIT);
05990 }
05991 ast_debug(4, "SIP Transfer: Not hanging up right now... Rescheduling hangup for %s.\n", p->callid);
05992 if (p->autokillid > -1 && sip_cancel_destroy(p))
05993 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
05994 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
05995 ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
05996 p->needdestroy = 0;
05997 p->owner->tech_pvt = dialog_unref(p->owner->tech_pvt, "unref p->owner->tech_pvt");
05998 sip_pvt_lock(p);
05999 p->owner = NULL;
06000 sip_pvt_unlock(p);
06001 ast_module_unref(ast_module_info->self);
06002 return 0;
06003 }
06004
06005 if (ast_test_flag(ast, AST_FLAG_ZOMBIE)) {
06006 if (p->refer)
06007 ast_debug(1, "SIP Transfer: Hanging up Zombie channel %s after transfer ... Call-ID: %s\n", ast->name, p->callid);
06008 else
06009 ast_debug(1, "Hanging up zombie call. Be scared.\n");
06010 } else
06011 ast_debug(1, "Hangup call %s, SIP callid %s\n", ast->name, p->callid);
06012
06013 sip_pvt_lock(p);
06014 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
06015 if (sipdebug)
06016 ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
06017 update_call_counter(p, DEC_CALL_LIMIT);
06018 }
06019
06020
06021 if (p->owner != ast) {
06022 ast_log(LOG_WARNING, "Huh? We aren't the owner? Can't hangup call.\n");
06023 sip_pvt_unlock(p);
06024 return 0;
06025 }
06026
06027
06028 if (p->invitestate < INV_COMPLETED && p->owner->_state != AST_STATE_UP) {
06029 needcancel = TRUE;
06030 ast_debug(4, "Hanging up channel in state %s (not UP)\n", ast_state2str(ast->_state));
06031 }
06032
06033 stop_media_flows(p);
06034
06035 append_history(p, needcancel ? "Cancel" : "Hangup", "Cause %s", p->owner ? ast_cause2str(p->hangupcause) : "Unknown");
06036
06037
06038 if (p->dsp)
06039 ast_dsp_free(p->dsp);
06040
06041 p->owner = NULL;
06042 ast->tech_pvt = dialog_unref(ast->tech_pvt, "unref ast->tech_pvt");
06043
06044 ast_module_unref(ast_module_info->self);
06045
06046
06047
06048
06049
06050
06051 if (p->alreadygone)
06052 needdestroy = 1;
06053 else if (p->invitestate != INV_CALLING)
06054 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06055
06056
06057 if (!p->alreadygone && p->initreq.data && !ast_strlen_zero(p->initreq.data->str)) {
06058 if (needcancel) {
06059 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06060
06061
06062 if (p->invitestate == INV_CALLING) {
06063
06064 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
06065 __sip_pretend_ack(p);
06066
06067 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06068 append_history(p, "DELAY", "Not sending cancel, waiting for timeout");
06069 } else {
06070 struct sip_pkt *cur;
06071
06072 for (cur = p->packets; cur; cur = cur->next) {
06073 __sip_semi_ack(p, cur->seqno, cur->is_resp, cur->method ? cur->method : find_sip_method(cur->data->str));
06074 }
06075 p->invitestate = INV_CANCELLED;
06076
06077 transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
06078
06079
06080 needdestroy = 0;
06081 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06082 }
06083 } else {
06084 const char *res;
06085 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"));
06086 if (p->hangupcause && (res = hangup_cause2sip(p->hangupcause)))
06087 transmit_response_reliable(p, res, &p->initreq);
06088 else
06089 transmit_response_reliable(p, "603 Declined", &p->initreq);
06090 p->invitestate = INV_TERMINATED;
06091 }
06092 } else {
06093 if (p->stimer->st_active == TRUE) {
06094 stop_session_timer(p);
06095 }
06096
06097 if (!p->pendinginvite) {
06098 struct ast_channel *bridge = ast_bridged_channel(oldowner);
06099 char *audioqos = "";
06100 char *videoqos = "";
06101 char *textqos = "";
06102
06103
06104
06105
06106 while (bridge && ast_channel_trylock(bridge)) {
06107 sip_pvt_unlock(p);
06108 do {
06109
06110 CHANNEL_DEADLOCK_AVOIDANCE(oldowner);
06111 } while (sip_pvt_trylock(p));
06112 bridge = ast_bridged_channel(oldowner);
06113 }
06114
06115 if (p->rtp)
06116 ast_rtp_set_vars(oldowner, p->rtp);
06117
06118 if (bridge) {
06119 struct sip_pvt *q = bridge->tech_pvt;
06120
06121 if (IS_SIP_TECH(bridge->tech) && q && q->rtp)
06122 ast_rtp_set_vars(bridge, q->rtp);
06123 ast_channel_unlock(bridge);
06124 }
06125
06126 if (p->vrtp)
06127 videoqos = ast_rtp_get_quality(p->vrtp, NULL, RTPQOS_SUMMARY);
06128 if (p->trtp)
06129 textqos = ast_rtp_get_quality(p->trtp, NULL, RTPQOS_SUMMARY);
06130
06131 if (oldowner->_state == AST_STATE_UP) {
06132 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
06133 }
06134
06135
06136 if (p->do_history) {
06137 if (p->rtp)
06138 append_history(p, "RTCPaudio", "Quality:%s", audioqos);
06139 if (p->vrtp)
06140 append_history(p, "RTCPvideo", "Quality:%s", videoqos);
06141 if (p->trtp)
06142 append_history(p, "RTCPtext", "Quality:%s", textqos);
06143 }
06144 if (p->rtp && oldowner)
06145 pbx_builtin_setvar_helper(oldowner, "RTPAUDIOQOS", audioqos);
06146 if (p->vrtp && oldowner)
06147 pbx_builtin_setvar_helper(oldowner, "RTPVIDEOQOS", videoqos);
06148 if (p->trtp && oldowner)
06149 pbx_builtin_setvar_helper(oldowner, "RTPTEXTQOS", textqos);
06150 } else {
06151
06152
06153 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
06154 ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);
06155 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"));
06156 if (sip_cancel_destroy(p))
06157 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
06158 }
06159 }
06160 }
06161 if (needdestroy) {
06162 pvt_set_needdestroy(p, "hangup");
06163 }
06164 sip_pvt_unlock(p);
06165 return 0;
06166 }
06167
06168
06169 static void try_suggested_sip_codec(struct sip_pvt *p)
06170 {
06171 int fmt;
06172 const char *codec;
06173
06174 codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC");
06175 if (!codec)
06176 return;
06177
06178 fmt = ast_getformatbyname(codec);
06179 if (fmt) {
06180 ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC} variable\n", codec);
06181 if (p->jointcapability & fmt) {
06182 p->jointcapability &= fmt;
06183 p->capability &= fmt;
06184 } else
06185 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
06186 } else
06187 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n", codec);
06188 return;
06189 }
06190
06191
06192
06193 static int sip_answer(struct ast_channel *ast)
06194 {
06195 int res = 0;
06196 struct sip_pvt *p = ast->tech_pvt;
06197
06198 sip_pvt_lock(p);
06199 if (ast->_state != AST_STATE_UP) {
06200 try_suggested_sip_codec(p);
06201
06202 ast_setstate(ast, AST_STATE_UP);
06203 ast_debug(1, "SIP answering channel: %s\n", ast->name);
06204 ast_rtp_new_source(p->rtp);
06205 res = transmit_response_with_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL, FALSE);
06206 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
06207 }
06208 sip_pvt_unlock(p);
06209 return res;
06210 }
06211
06212
06213 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
06214 {
06215 struct sip_pvt *p = ast->tech_pvt;
06216 int res = 0;
06217
06218 switch (frame->frametype) {
06219 case AST_FRAME_VOICE:
06220 if (!(frame->subclass & ast->nativeformats)) {
06221 char s1[512], s2[512], s3[512];
06222 ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %s(%d) read/write = %s(%d)/%s(%d)\n",
06223 frame->subclass,
06224 ast_getformatname_multiple(s1, sizeof(s1) - 1, ast->nativeformats & AST_FORMAT_AUDIO_MASK),
06225 ast->nativeformats & AST_FORMAT_AUDIO_MASK,
06226 ast_getformatname_multiple(s2, sizeof(s2) - 1, ast->readformat),
06227 ast->readformat,
06228 ast_getformatname_multiple(s3, sizeof(s3) - 1, ast->writeformat),
06229 ast->writeformat);
06230 return 0;
06231 }
06232 if (p) {
06233 sip_pvt_lock(p);
06234 if (p->rtp) {
06235
06236 if ((ast->_state != AST_STATE_UP) &&
06237 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06238 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06239 ast_rtp_new_source(p->rtp);
06240 if (!global_prematuremediafilter) {
06241 p->invitestate = INV_EARLY_MEDIA;
06242 transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06243 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06244 }
06245 } else if (p->t38.state == T38_ENABLED) {
06246
06247 } else {
06248 p->lastrtptx = time(NULL);
06249 res = ast_rtp_write(p->rtp, frame);
06250 }
06251 }
06252 sip_pvt_unlock(p);
06253 }
06254 break;
06255 case AST_FRAME_VIDEO:
06256 if (p) {
06257 sip_pvt_lock(p);
06258 if (p->vrtp) {
06259
06260 if ((ast->_state != AST_STATE_UP) &&
06261 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06262 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06263 p->invitestate = INV_EARLY_MEDIA;
06264 transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06265 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06266 }
06267 p->lastrtptx = time(NULL);
06268 res = ast_rtp_write(p->vrtp, frame);
06269 }
06270 sip_pvt_unlock(p);
06271 }
06272 break;
06273 case AST_FRAME_TEXT:
06274 if (p) {
06275 sip_pvt_lock(p);
06276 if (p->red) {
06277 red_buffer_t140(p->trtp, frame);
06278 } else {
06279 if (p->trtp) {
06280
06281 if ((ast->_state != AST_STATE_UP) &&
06282 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06283 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06284 p->invitestate = INV_EARLY_MEDIA;
06285 transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06286 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06287 }
06288 p->lastrtptx = time(NULL);
06289 res = ast_rtp_write(p->trtp, frame);
06290 }
06291 }
06292 sip_pvt_unlock(p);
06293 }
06294 break;
06295 case AST_FRAME_IMAGE:
06296 return 0;
06297 break;
06298 case AST_FRAME_MODEM:
06299 if (p) {
06300 sip_pvt_lock(p);
06301
06302
06303
06304
06305 if ((ast->_state == AST_STATE_UP) &&
06306 p->udptl &&
06307 (p->t38.state == T38_ENABLED)) {
06308 res = ast_udptl_write(p->udptl, frame);
06309 }
06310 sip_pvt_unlock(p);
06311 }
06312 break;
06313 default:
06314 ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
06315 return 0;
06316 }
06317
06318 return res;
06319 }
06320
06321
06322
06323 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
06324 {
06325 int ret = -1;
06326 struct sip_pvt *p;
06327
06328 if (newchan && ast_test_flag(newchan, AST_FLAG_ZOMBIE))
06329 ast_debug(1, "New channel is zombie\n");
06330 if (oldchan && ast_test_flag(oldchan, AST_FLAG_ZOMBIE))
06331 ast_debug(1, "Old channel is zombie\n");
06332
06333 if (!newchan || !newchan->tech_pvt) {
06334 if (!newchan)
06335 ast_log(LOG_WARNING, "No new channel! Fixup of %s failed.\n", oldchan->name);
06336 else
06337 ast_log(LOG_WARNING, "No SIP tech_pvt! Fixup of %s failed.\n", oldchan->name);
06338 return -1;
06339 }
06340 p = newchan->tech_pvt;
06341
06342 sip_pvt_lock(p);
06343 append_history(p, "Masq", "Old channel: %s\n", oldchan->name);
06344 append_history(p, "Masq (cont)", "...new owner: %s\n", newchan->name);
06345 if (p->owner != oldchan)
06346 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
06347 else {
06348 p->owner = newchan;
06349
06350
06351
06352
06353
06354
06355 sip_set_rtp_peer(newchan, NULL, NULL, 0, 0, 0);
06356 ret = 0;
06357 }
06358 ast_debug(3, "SIP Fixup: New owner for dialogue %s: %s (Old parent: %s)\n", p->callid, p->owner->name, oldchan->name);
06359
06360 sip_pvt_unlock(p);
06361 return ret;
06362 }
06363
06364 static int sip_senddigit_begin(struct ast_channel *ast, char digit)
06365 {
06366 struct sip_pvt *p = ast->tech_pvt;
06367 int res = 0;
06368
06369 sip_pvt_lock(p);
06370 switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
06371 case SIP_DTMF_INBAND:
06372 res = -1;
06373 break;
06374 case SIP_DTMF_RFC2833:
06375 if (p->rtp)
06376 ast_rtp_senddigit_begin(p->rtp, digit);
06377 break;
06378 default:
06379 break;
06380 }
06381 sip_pvt_unlock(p);
06382
06383 return res;
06384 }
06385
06386
06387
06388 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration)
06389 {
06390 struct sip_pvt *p = ast->tech_pvt;
06391 int res = 0;
06392
06393 sip_pvt_lock(p);
06394 switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
06395 case SIP_DTMF_INFO:
06396 case SIP_DTMF_SHORTINFO:
06397 transmit_info_with_digit(p, digit, duration);
06398 break;
06399 case SIP_DTMF_RFC2833:
06400 if (p->rtp)
06401 ast_rtp_senddigit_end(p->rtp, digit);
06402 break;
06403 case SIP_DTMF_INBAND:
06404 res = -1;
06405 break;
06406 }
06407 sip_pvt_unlock(p);
06408
06409 return res;
06410 }
06411
06412
06413 static int sip_transfer(struct ast_channel *ast, const char *dest)
06414 {
06415 struct sip_pvt *p = ast->tech_pvt;
06416 int res;
06417
06418 if (dest == NULL)
06419 dest = "";
06420 sip_pvt_lock(p);
06421 if (ast->_state == AST_STATE_RING)
06422 res = sip_sipredirect(p, dest);
06423 else
06424 res = transmit_refer(p, dest);
06425 sip_pvt_unlock(p);
06426 return res;
06427 }
06428
06429
06430 static int interpret_t38_parameters(struct sip_pvt *p, const struct ast_control_t38_parameters *parameters)
06431 {
06432 int res = 0;
06433
06434 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) || !p->udptl) {
06435 return -1;
06436 }
06437 switch (parameters->request_response) {
06438 case AST_T38_NEGOTIATED:
06439 case AST_T38_REQUEST_NEGOTIATE:
06440
06441 if (!parameters->max_ifp) {
06442 change_t38_state(p, T38_DISABLED);
06443 if (p->t38.state == T38_PEER_REINVITE) {
06444 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"));
06445 transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
06446 }
06447 break;
06448 } else if (p->t38.state == T38_PEER_REINVITE) {
06449 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"));
06450 p->t38.our_parms = *parameters;
06451
06452
06453
06454 if (!p->t38.their_parms.fill_bit_removal) {
06455 p->t38.our_parms.fill_bit_removal = FALSE;
06456 }
06457 if (!p->t38.their_parms.transcoding_mmr) {
06458 p->t38.our_parms.transcoding_mmr = FALSE;
06459 }
06460 if (!p->t38.their_parms.transcoding_jbig) {
06461 p->t38.our_parms.transcoding_jbig = FALSE;
06462 }
06463 p->t38.our_parms.version = MIN(p->t38.our_parms.version, p->t38.their_parms.version);
06464 p->t38.our_parms.rate_management = p->t38.their_parms.rate_management;
06465 ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
06466 change_t38_state(p, T38_ENABLED);
06467 transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
06468 } else if (p->t38.state != T38_ENABLED) {
06469 p->t38.our_parms = *parameters;
06470 ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
06471 change_t38_state(p, T38_LOCAL_REINVITE);
06472 if (!p->pendinginvite) {
06473 transmit_reinvite_with_sdp(p, TRUE, FALSE);
06474 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
06475 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
06476 }
06477 }
06478 break;
06479 case AST_T38_TERMINATED:
06480 case AST_T38_REFUSED:
06481 case AST_T38_REQUEST_TERMINATE:
06482 if (p->t38.state == T38_PEER_REINVITE) {
06483 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"));
06484 change_t38_state(p, T38_DISABLED);
06485 transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
06486 } else if (p->t38.state == T38_ENABLED)
06487 transmit_reinvite_with_sdp(p, FALSE, FALSE);
06488 break;
06489 case AST_T38_REQUEST_PARMS: {
06490 struct ast_control_t38_parameters parameters = p->t38.their_parms;
06491
06492 if (p->t38.state == T38_PEER_REINVITE) {
06493 AST_SCHED_DEL(sched, p->t38id);
06494 parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
06495 parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
06496 ast_queue_control_data(p->owner, AST_CONTROL_T38_PARAMETERS, ¶meters, sizeof(parameters));
06497
06498
06499
06500
06501 res = AST_T38_REQUEST_PARMS;
06502 }
06503 break;
06504 }
06505 default:
06506 res = -1;
06507 break;
06508 }
06509
06510 return res;
06511 }
06512
06513
06514
06515
06516
06517
06518 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
06519 {
06520 struct sip_pvt *p = ast->tech_pvt;
06521 int res = 0;
06522
06523 sip_pvt_lock(p);
06524 switch(condition) {
06525 case AST_CONTROL_RINGING:
06526 if (ast->_state == AST_STATE_RING) {
06527 p->invitestate = INV_EARLY_MEDIA;
06528 if (!ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) ||
06529 (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) {
06530
06531 transmit_provisional_response(p, "180 Ringing", &p->initreq, 0);
06532 ast_set_flag(&p->flags[0], SIP_RINGING);
06533 if (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) != SIP_PROG_INBAND_YES)
06534 break;
06535 } else {
06536
06537 }
06538 }
06539 res = -1;
06540 break;
06541 case AST_CONTROL_BUSY:
06542 if (ast->_state != AST_STATE_UP) {
06543 transmit_response_reliable(p, "486 Busy Here", &p->initreq);
06544 p->invitestate = INV_COMPLETED;
06545 sip_alreadygone(p);
06546 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
06547 break;
06548 }
06549 res = -1;
06550 break;
06551 case AST_CONTROL_CONGESTION:
06552 if (ast->_state != AST_STATE_UP) {
06553 transmit_response_reliable(p, "503 Service Unavailable", &p->initreq);
06554 p->invitestate = INV_COMPLETED;
06555 sip_alreadygone(p);
06556 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
06557 break;
06558 }
06559 res = -1;
06560 break;
06561 case AST_CONTROL_PROCEEDING:
06562 if ((ast->_state != AST_STATE_UP) &&
06563 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06564 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06565 transmit_response(p, "100 Trying", &p->initreq);
06566 p->invitestate = INV_PROCEEDING;
06567 break;
06568 }
06569 res = -1;
06570 break;
06571 case AST_CONTROL_PROGRESS:
06572 if ((ast->_state != AST_STATE_UP) &&
06573 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06574 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06575 p->invitestate = INV_EARLY_MEDIA;
06576 transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06577 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06578 break;
06579 }
06580 res = -1;
06581 break;
06582 case AST_CONTROL_HOLD:
06583 ast_rtp_new_source(p->rtp);
06584 ast_moh_start(ast, data, p->mohinterpret);
06585 break;
06586 case AST_CONTROL_UNHOLD:
06587 ast_rtp_new_source(p->rtp);
06588 ast_moh_stop(ast);
06589 break;
06590 case AST_CONTROL_VIDUPDATE:
06591 if (p->vrtp && !p->novideo) {
06592 transmit_info_with_vidupdate(p);
06593
06594 } else
06595 res = -1;
06596 break;
06597 case AST_CONTROL_T38_PARAMETERS:
06598 if (datalen != sizeof(struct ast_control_t38_parameters)) {
06599 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);
06600 res = -1;
06601 } else {
06602 const struct ast_control_t38_parameters *parameters = data;
06603 res = interpret_t38_parameters(p, parameters);
06604 }
06605 break;
06606 case AST_CONTROL_SRCUPDATE:
06607 ast_rtp_new_source(p->rtp);
06608 break;
06609 case AST_CONTROL_SRCCHANGE:
06610 ast_rtp_change_source(p->rtp);
06611 break;
06612 case -1:
06613 res = -1;
06614 break;
06615 default:
06616 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
06617 res = -1;
06618 break;
06619 }
06620 sip_pvt_unlock(p);
06621 return res;
06622 }
06623
06624
06625
06626
06627
06628
06629
06630 static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title)
06631 {
06632 struct ast_channel *tmp;
06633 struct ast_variable *v = NULL;
06634 int fmt;
06635 int what;
06636 int video;
06637 int text;
06638 int needvideo = 0;
06639 int needtext = 0;
06640 char buf[SIPBUFSIZE];
06641 char *decoded_exten;
06642
06643 {
06644 const char *my_name;
06645
06646 if (title) {
06647 my_name = title;
06648 } else {
06649 char *port = NULL;
06650 my_name = ast_strdupa(i->fromdomain);
06651 if ((port = strchr(i->fromdomain, ':'))) {
06652 *port = '\0';
06653 }
06654 }
06655
06656 sip_pvt_unlock(i);
06657
06658 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));
06659
06660 }
06661 if (!tmp) {
06662 ast_log(LOG_WARNING, "Unable to allocate AST channel structure for SIP channel\n");
06663 sip_pvt_lock(i);
06664 return NULL;
06665 }
06666 sip_pvt_lock(i);
06667
06668 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;
06669
06670
06671
06672 if (i->jointcapability) {
06673 what = i->jointcapability;
06674 video = i->jointcapability & AST_FORMAT_VIDEO_MASK;
06675 text = i->jointcapability & AST_FORMAT_TEXT_MASK;
06676 } else if (i->capability) {
06677 what = i->capability;
06678 video = i->capability & AST_FORMAT_VIDEO_MASK;
06679 text = i->capability & AST_FORMAT_TEXT_MASK;
06680 } else {
06681 what = global_capability;
06682 video = global_capability & AST_FORMAT_VIDEO_MASK;
06683 text = global_capability & AST_FORMAT_TEXT_MASK;
06684 }
06685
06686
06687 tmp->nativeformats = ast_codec_choose(&i->prefs, what, 1) | video | text;
06688 ast_debug(3, "*** Our native formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, tmp->nativeformats));
06689 ast_debug(3, "*** Joint capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->jointcapability));
06690 ast_debug(3, "*** Our capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->capability));
06691 ast_debug(3, "*** AST_CODEC_CHOOSE formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, ast_codec_choose(&i->prefs, what, 1)));
06692 if (i->prefcodec)
06693 ast_debug(3, "*** Our preferred formats from the incoming channel are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->prefcodec));
06694
06695
06696 fmt = ast_best_codec(tmp->nativeformats);
06697
06698
06699
06700
06701
06702 if (i->vrtp) {
06703 if (ast_test_flag(&i->flags[1], SIP_PAGE2_VIDEOSUPPORT))
06704 needvideo = AST_FORMAT_VIDEO_MASK;
06705 else if (i->prefcodec)
06706 needvideo = i->prefcodec & AST_FORMAT_VIDEO_MASK;
06707 else
06708 needvideo = i->jointcapability & AST_FORMAT_VIDEO_MASK;
06709 }
06710
06711 if (i->trtp) {
06712 if (i->prefcodec)
06713 needtext = i->prefcodec & AST_FORMAT_TEXT_MASK;
06714 else
06715 needtext = i->jointcapability & AST_FORMAT_TEXT_MASK;
06716 }
06717
06718 if (needvideo)
06719 ast_debug(3, "This channel can handle video! HOLLYWOOD next!\n");
06720 else
06721 ast_debug(3, "This channel will not be able to handle video.\n");
06722
06723 if ((ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) || (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) ||
06724 (ast_test_flag(&i->flags[1], SIP_PAGE2_FAX_DETECT))) {
06725 int features = 0;
06726
06727 if ((ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) || (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
06728 features |= DSP_FEATURE_DIGIT_DETECT;
06729 }
06730
06731 if (ast_test_flag(&i->flags[1], SIP_PAGE2_FAX_DETECT)) {
06732 features |= DSP_FEATURE_FAX_DETECT;
06733 }
06734
06735 i->dsp = ast_dsp_new();
06736 ast_dsp_set_features(i->dsp, features);
06737 if (global_relaxdtmf)
06738 ast_dsp_set_digitmode(i->dsp, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
06739 }
06740
06741
06742 if (i->rtp) {
06743 ast_channel_set_fd(tmp, 0, ast_rtp_fd(i->rtp));
06744 ast_channel_set_fd(tmp, 1, ast_rtcp_fd(i->rtp));
06745 }
06746 if (needvideo && i->vrtp) {
06747 ast_channel_set_fd(tmp, 2, ast_rtp_fd(i->vrtp));
06748 ast_channel_set_fd(tmp, 3, ast_rtcp_fd(i->vrtp));
06749 }
06750 if (needtext && i->trtp)
06751 ast_channel_set_fd(tmp, 4, ast_rtp_fd(i->trtp));
06752 if (i->udptl)
06753 ast_channel_set_fd(tmp, 5, ast_udptl_fd(i->udptl));
06754
06755 if (state == AST_STATE_RING)
06756 tmp->rings = 1;
06757 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
06758 tmp->writeformat = fmt;
06759 tmp->rawwriteformat = fmt;
06760 tmp->readformat = fmt;
06761 tmp->rawreadformat = fmt;
06762 tmp->tech_pvt = dialog_ref(i, "sip_new: set chan->tech_pvt to i");
06763
06764 tmp->callgroup = i->callgroup;
06765 tmp->pickupgroup = i->pickupgroup;
06766 tmp->cid.cid_pres = i->callingpres;
06767 if (!ast_strlen_zero(i->parkinglot))
06768 ast_string_field_set(tmp, parkinglot, i->parkinglot);
06769 if (!ast_strlen_zero(i->accountcode))
06770 ast_string_field_set(tmp, accountcode, i->accountcode);
06771 if (i->amaflags)
06772 tmp->amaflags = i->amaflags;
06773 if (!ast_strlen_zero(i->language))
06774 ast_string_field_set(tmp, language, i->language);
06775 i->owner = tmp;
06776 ast_module_ref(ast_module_info->self);
06777 ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
06778
06779
06780
06781
06782 decoded_exten = ast_strdupa(i->exten);
06783 ast_uri_decode(decoded_exten);
06784 ast_copy_string(tmp->exten, decoded_exten, sizeof(tmp->exten));
06785
06786
06787
06788 tmp->cid.cid_ani = ast_strdup(i->cid_num);
06789 if (!ast_strlen_zero(i->rdnis))
06790 tmp->cid.cid_rdnis = ast_strdup(i->rdnis);
06791
06792 if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s"))
06793 tmp->cid.cid_dnid = ast_strdup(i->exten);
06794
06795 tmp->priority = 1;
06796 if (!ast_strlen_zero(i->uri))
06797 pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
06798 if (!ast_strlen_zero(i->domain))
06799 pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
06800 if (!ast_strlen_zero(i->callid))
06801 pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
06802 if (i->rtp)
06803 ast_jb_configure(tmp, &global_jbconf);
06804
06805
06806 for (v = i->chanvars ; v ; v = v->next) {
06807 char valuebuf[1024];
06808 pbx_builtin_setvar_helper(tmp, v->name, ast_get_encoded_str(v->value, valuebuf, sizeof(valuebuf)));
06809 }
06810
06811 if (state != AST_STATE_DOWN && ast_pbx_start(tmp)) {
06812 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
06813 tmp->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
06814 ast_hangup(tmp);
06815 tmp = NULL;
06816 }
06817
06818 if (i->do_history)
06819 append_history(i, "NewChan", "Channel %s - from %s", tmp->name, i->callid);
06820
06821
06822 if (sip_cfg.callevents)
06823 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
06824 "Channel: %s\r\nUniqueid: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\n",
06825 tmp->name, tmp->uniqueid, "SIP", i->callid, i->fullcontact);
06826
06827 return tmp;
06828 }
06829
06830
06831 static char *get_body_by_line(const char *line, const char *name, int nameLen, char delimiter)
06832 {
06833 if (!strncasecmp(line, name, nameLen) && line[nameLen] == delimiter)
06834 return ast_skip_blanks(line + nameLen + 1);
06835
06836 return "";
06837 }
06838
06839
06840
06841
06842
06843 static const char *get_sdp_iterate(int *start, struct sip_request *req, const char *name)
06844 {
06845 int len = strlen(name);
06846
06847 while (*start < (req->sdp_start + req->sdp_count)) {
06848 const char *r = get_body_by_line(REQ_OFFSET_TO_STR(req, line[(*start)++]), name, len, '=');
06849 if (r[0] != '\0')
06850 return r;
06851 }
06852
06853
06854 (*start)++;
06855
06856 return "";
06857 }
06858
06859
06860
06861
06862
06863
06864 static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value)
06865 {
06866 char type = '\0';
06867 const char *line = NULL;
06868
06869 if (stop > (req->sdp_start + req->sdp_count)) {
06870 stop = req->sdp_start + req->sdp_count;
06871 }
06872
06873 while (*start < stop) {
06874 line = REQ_OFFSET_TO_STR(req, line[(*start)++]);
06875 if (line[1] == '=') {
06876 type = line[0];
06877 *value = ast_skip_blanks(line + 2);
06878 break;
06879 }
06880 }
06881
06882 return type;
06883 }
06884
06885
06886 static char *get_body(struct sip_request *req, char *name, char delimiter)
06887 {
06888 int x;
06889 int len = strlen(name);
06890 char *r;
06891
06892 for (x = 0; x < req->lines; x++) {
06893 r = get_body_by_line(REQ_OFFSET_TO_STR(req, line[x]), name, len, delimiter);
06894 if (r[0] != '\0')
06895 return r;
06896 }
06897
06898 return "";
06899 }
06900
06901
06902 static const char *find_alias(const char *name, const char *_default)
06903 {
06904
06905 static const struct cfalias {
06906 char * const fullname;
06907 char * const shortname;
06908 } aliases[] = {
06909 { "Content-Type", "c" },
06910 { "Content-Encoding", "e" },
06911 { "From", "f" },
06912 { "Call-ID", "i" },
06913 { "Contact", "m" },
06914 { "Content-Length", "l" },
06915 { "Subject", "s" },
06916 { "To", "t" },
06917 { "Supported", "k" },
06918 { "Refer-To", "r" },
06919 { "Referred-By", "b" },
06920 { "Allow-Events", "u" },
06921 { "Event", "o" },
06922 { "Via", "v" },
06923 { "Accept-Contact", "a" },
06924 { "Reject-Contact", "j" },
06925 { "Request-Disposition", "d" },
06926 { "Session-Expires", "x" },
06927 { "Identity", "y" },
06928 { "Identity-Info", "n" },
06929 };
06930 int x;
06931
06932 for (x = 0; x < ARRAY_LEN(aliases); x++) {
06933 if (!strcasecmp(aliases[x].fullname, name))
06934 return aliases[x].shortname;
06935 }
06936
06937 return _default;
06938 }
06939
06940 static const char *__get_header(const struct sip_request *req, const char *name, int *start)
06941 {
06942 int pass;
06943
06944
06945
06946
06947
06948
06949
06950
06951
06952
06953 for (pass = 0; name && pass < 2;pass++) {
06954 int x, len = strlen(name);
06955 for (x = *start; x < req->headers; x++) {
06956 char *header = REQ_OFFSET_TO_STR(req, header[x]);
06957 if (!strncasecmp(header, name, len)) {
06958 char *r = header + len;
06959 if (sip_cfg.pedanticsipchecking)
06960 r = ast_skip_blanks(r);
06961
06962 if (*r == ':') {
06963 *start = x+1;
06964 return ast_skip_blanks(r+1);
06965 }
06966 }
06967 }
06968 if (pass == 0)
06969 name = find_alias(name, NULL);
06970 }
06971
06972
06973 return "";
06974 }
06975
06976
06977
06978
06979 static const char *get_header(const struct sip_request *req, const char *name)
06980 {
06981 int start = 0;
06982 return __get_header(req, name, &start);
06983 }
06984
06985
06986 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect)
06987 {
06988
06989 struct ast_frame *f;
06990
06991 if (!p->rtp) {
06992
06993 return &ast_null_frame;
06994 }
06995
06996 switch(ast->fdno) {
06997 case 0:
06998 f = ast_rtp_read(p->rtp);
06999 break;
07000 case 1:
07001 f = ast_rtcp_read(p->rtp);
07002 break;
07003 case 2:
07004 f = ast_rtp_read(p->vrtp);
07005 break;
07006 case 3:
07007 f = ast_rtcp_read(p->vrtp);
07008 break;
07009 case 4:
07010 f = ast_rtp_read(p->trtp);
07011 if (sipdebug_text) {
07012 int i;
07013 unsigned char* arr = f->data.ptr;
07014 for (i=0; i < f->datalen; i++)
07015 ast_verbose("%c", (arr[i] > ' ' && arr[i] < '}') ? arr[i] : '.');
07016 ast_verbose(" -> ");
07017 for (i=0; i < f->datalen; i++)
07018 ast_verbose("%02X ", arr[i]);
07019 ast_verbose("\n");
07020 }
07021 break;
07022 case 5:
07023 f = ast_udptl_read(p->udptl);
07024 break;
07025 default:
07026 f = &ast_null_frame;
07027 }
07028
07029 if (f && (f->frametype == AST_FRAME_DTMF_BEGIN || f->frametype == AST_FRAME_DTMF_END) &&
07030 (ast_test_flag(&p->flags[0], SIP_DTMF) != SIP_DTMF_RFC2833)) {
07031 ast_debug(1, "Ignoring DTMF (%c) RTP frame because dtmfmode is not RFC2833\n", f->subclass);
07032 return &ast_null_frame;
07033 }
07034
07035
07036 if (!p->owner || (f && f->frametype != AST_FRAME_VOICE))
07037 return f;
07038
07039 if (f && f->subclass != (p->owner->nativeformats & AST_FORMAT_AUDIO_MASK)) {
07040 if (!(f->subclass & p->jointcapability)) {
07041 ast_debug(1, "Bogus frame of format '%s' received from '%s'!\n",
07042 ast_getformatname(f->subclass), p->owner->name);
07043 return &ast_null_frame;
07044 }
07045 ast_debug(1, "Oooh, format changed to %d %s\n",
07046 f->subclass, ast_getformatname(f->subclass));
07047 p->owner->nativeformats = (p->owner->nativeformats & (AST_FORMAT_VIDEO_MASK | AST_FORMAT_TEXT_MASK)) | f->subclass;
07048 ast_set_read_format(p->owner, p->owner->readformat);
07049 ast_set_write_format(p->owner, p->owner->writeformat);
07050 }
07051
07052 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) {
07053 f = ast_dsp_process(p->owner, p->dsp, f);
07054 if (f && f->frametype == AST_FRAME_DTMF) {
07055 if (f->subclass == 'f') {
07056 if (option_debug)
07057 ast_log(LOG_DEBUG, "Fax CNG detected on %s\n", ast->name);
07058 *faxdetect = 1;
07059
07060 if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
07061 ast_dsp_set_features(p->dsp, DSP_FEATURE_DIGIT_DETECT);
07062 } else {
07063 ast_dsp_free(p->dsp);
07064 p->dsp = NULL;
07065 }
07066 } else {
07067 ast_debug(1, "* Detected inband DTMF '%c'\n", f->subclass);
07068 }
07069 }
07070 }
07071
07072 return f;
07073 }
07074
07075
07076 static struct ast_frame *sip_read(struct ast_channel *ast)
07077 {
07078 struct ast_frame *fr;
07079 struct sip_pvt *p = ast->tech_pvt;
07080 int faxdetected = FALSE;
07081
07082 sip_pvt_lock(p);
07083 fr = sip_rtp_read(ast, p, &faxdetected);
07084 p->lastrtprx = time(NULL);
07085
07086
07087 if (faxdetected && ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_CNG)) {
07088 ast_channel_lock(ast);
07089 if (strcmp(ast->exten, "fax")) {
07090 const char *target_context = S_OR(ast->macrocontext, ast->context);
07091 ast_channel_unlock(ast);
07092 if (ast_exists_extension(ast, target_context, "fax", 1, ast->cid.cid_num)) {
07093 ast_verbose(VERBOSE_PREFIX_2 "Redirecting '%s' to fax extension due to CNG detection\n", ast->name);
07094 pbx_builtin_setvar_helper(ast, "FAXEXTEN", ast->exten);
07095 if (ast_async_goto(ast, target_context, "fax", 1)) {
07096 ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", ast->name, target_context);
07097 }
07098 fr = &ast_null_frame;
07099 } else {
07100 ast_log(LOG_NOTICE, "FAX CNG detected but no fax extension\n");
07101 }
07102 } else {
07103 ast_channel_unlock(ast);
07104 }
07105 }
07106
07107
07108 if (fr && fr->frametype == AST_FRAME_VOICE && p->invitestate != INV_EARLY_MEDIA && ast->_state != AST_STATE_UP) {
07109 fr = &ast_null_frame;
07110 }
07111
07112 sip_pvt_unlock(p);
07113
07114 return fr;
07115 }
07116
07117
07118
07119 static char *generate_random_string(char *buf, size_t size)
07120 {
07121 long val[4];
07122 int x;
07123
07124 for (x=0; x<4; x++)
07125 val[x] = ast_random();
07126 snprintf(buf, size, "%08lx%08lx%08lx%08lx", val[0], val[1], val[2], val[3]);
07127
07128 return buf;
07129 }
07130
07131
07132 static void build_callid_pvt(struct sip_pvt *pvt)
07133 {
07134 char buf[33];
07135
07136 const char *host = S_OR(pvt->fromdomain, ast_inet_ntoa(pvt->ourip.sin_addr));
07137
07138 ast_string_field_build(pvt, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
07139
07140 }
07141
07142
07143 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain)
07144 {
07145 char buf[33];
07146
07147 const char *host = S_OR(fromdomain, ast_inet_ntoa(ourip));
07148
07149 ast_string_field_build(reg, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
07150 }
07151
07152
07153 static void make_our_tag(char *tagbuf, size_t len)
07154 {
07155 snprintf(tagbuf, len, "as%08lx", ast_random());
07156 }
07157
07158
07159 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p)
07160 {
07161 struct sip_st_dlg *stp;
07162
07163 if (p->stimer) {
07164 ast_log(LOG_ERROR, "Session-Timer struct already allocated\n");
07165 return p->stimer;
07166 }
07167
07168 if (!(stp = ast_calloc(1, sizeof(struct sip_st_dlg))))
07169 return NULL;
07170
07171 p->stimer = stp;
07172
07173 stp->st_schedid = -1;
07174
07175 return p->stimer;
07176 }
07177
07178
07179
07180
07181
07182 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
07183 int useglobal_nat, const int intended_method, struct sip_request *req)
07184 {
07185 struct sip_pvt *p;
07186
07187 if (!(p = ao2_t_alloc(sizeof(*p), sip_destroy_fn, "allocate a dialog(pvt) struct")))
07188 return NULL;
07189
07190 if (ast_string_field_init(p, 512)) {
07191 ao2_t_ref(p, -1, "failed to string_field_init, drop p");
07192 return NULL;
07193 }
07194
07195 if (req) {
07196 set_socket_transport(&p->socket, req->socket.type);
07197 } else {
07198 set_socket_transport(&p->socket, SIP_TRANSPORT_UDP);
07199 }
07200
07201 p->socket.fd = -1;
07202 p->method = intended_method;
07203 p->initid = -1;
07204 p->waitid = -1;
07205 p->autokillid = -1;
07206 p->request_queue_sched_id = -1;
07207 p->provisional_keepalive_sched_id = -1;
07208 p->t38id = -1;
07209 p->subscribed = NONE;
07210 p->stateid = -1;
07211 p->sessionversion_remote = -1;
07212 p->session_modify = TRUE;
07213 p->stimer = NULL;
07214 p->prefs = default_prefs;
07215
07216 if (intended_method != SIP_OPTIONS) {
07217 p->timer_t1 = global_t1;
07218 p->timer_b = global_timer_b;
07219 }
07220
07221 if (!sin)
07222 p->ourip = internip;
07223 else {
07224 p->sa = *sin;
07225 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
07226 }
07227
07228
07229 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
07230 ast_copy_flags(&p->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
07231
07232 p->do_history = recordhistory;
07233
07234 p->branch = ast_random();
07235 make_our_tag(p->tag, sizeof(p->tag));
07236 p->ocseq = INITIAL_CSEQ;
07237
07238 if (sip_methods[intended_method].need_rtp) {
07239 p->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
07240
07241 if (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) ||
07242 ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS))
07243 p->vrtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
07244 if (ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT))
07245 p->trtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
07246 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
07247 if (!(p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr))) {
07248
07249 ast_log(LOG_ERROR, "UDPTL creation failed\n");
07250 ast_clear_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT);
07251 }
07252 }
07253 if (!p->rtp|| (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) && !p->vrtp)
07254 || (ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT) && !p->trtp)) {
07255 ast_log(LOG_WARNING, "Unable to create RTP audio %s%ssession: %s\n",
07256 ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "and video " : "",
07257 ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT) ? "and text " : "", strerror(errno));
07258 if (p->chanvars) {
07259 ast_variables_destroy(p->chanvars);
07260 p->chanvars = NULL;
07261 }
07262 ao2_t_ref(p, -1, "failed to create RTP audio session, drop p");
07263 return NULL;
07264 p->t38_maxdatagram = global_t38_maxdatagram;
07265 }
07266 ast_rtp_setqos(p->rtp, global_tos_audio, global_cos_audio, "SIP RTP");
07267 ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
07268 ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
07269 ast_rtp_set_rtptimeout(p->rtp, global_rtptimeout);
07270 ast_rtp_set_rtpholdtimeout(p->rtp, global_rtpholdtimeout);
07271 ast_rtp_set_rtpkeepalive(p->rtp, global_rtpkeepalive);
07272 if (p->vrtp) {
07273 ast_rtp_setqos(p->vrtp, global_tos_video, global_cos_video, "SIP VRTP");
07274 ast_rtp_setdtmf(p->vrtp, 0);
07275 ast_rtp_setdtmfcompensate(p->vrtp, 0);
07276 ast_rtp_set_rtptimeout(p->vrtp, global_rtptimeout);
07277 ast_rtp_set_rtpholdtimeout(p->vrtp, global_rtpholdtimeout);
07278 ast_rtp_set_rtpkeepalive(p->vrtp, global_rtpkeepalive);
07279 }
07280 if (p->trtp) {
07281 ast_rtp_setqos(p->trtp, global_tos_text, global_cos_text, "SIP TRTP");
07282 ast_rtp_setdtmf(p->trtp, 0);
07283 ast_rtp_setdtmfcompensate(p->trtp, 0);
07284 }
07285 if (p->udptl)
07286 ast_udptl_setqos(p->udptl, global_tos_audio, global_cos_audio);
07287 p->maxcallbitrate = default_maxcallbitrate;
07288 p->autoframing = global_autoframing;
07289 ast_rtp_codec_setpref(p->rtp, &p->prefs);
07290 }
07291
07292 if (useglobal_nat && sin) {
07293
07294 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT);
07295 p->recv = *sin;
07296 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
07297 }
07298
07299 if (p->method != SIP_REGISTER)
07300 ast_string_field_set(p, fromdomain, default_fromdomain);
07301 build_via(p);
07302 if (!callid)
07303 build_callid_pvt(p);
07304 else
07305 ast_string_field_set(p, callid, callid);
07306
07307 ast_string_field_set(p, mohinterpret, default_mohinterpret);
07308 ast_string_field_set(p, mohsuggest, default_mohsuggest);
07309 p->capability = global_capability;
07310 p->allowtransfer = sip_cfg.allowtransfer;
07311 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
07312 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
07313 p->noncodeccapability |= AST_RTP_DTMF;
07314 if (p->udptl) {
07315 p->t38_maxdatagram = global_t38_maxdatagram;
07316 set_t38_capabilities(p);
07317 }
07318 ast_string_field_set(p, context, sip_cfg.default_context);
07319 ast_string_field_set(p, parkinglot, default_parkinglot);
07320
07321 AST_LIST_HEAD_INIT_NOLOCK(&p->request_queue);
07322
07323
07324
07325 ao2_t_link(dialogs, p, "link pvt into dialogs table");
07326
07327 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");
07328 return p;
07329 }
07330
07331
07332 struct find_call_cb_arg {
07333 enum sipmethod method;
07334 const char *callid;
07335 const char *fromtag;
07336 const char *totag;
07337 const char *tag;
07338 };
07339
07340
07341
07342
07343
07344 static int find_call_cb(void *__pvt, void *__arg, int flags)
07345 {
07346 struct sip_pvt *p = __pvt;
07347 struct find_call_cb_arg *arg = __arg;
07348
07349 int found = FALSE;
07350
07351 if (!ast_strlen_zero(p->callid)) {
07352 if (arg->method == SIP_REGISTER)
07353 found = (!strcmp(p->callid, arg->callid));
07354 else {
07355 found = !strcmp(p->callid, arg->callid);
07356 if (sip_cfg.pedanticsipchecking && found) {
07357 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);
07358 }
07359 }
07360
07361 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);
07362
07363
07364 if (sip_cfg.pedanticsipchecking && found && arg->method != SIP_RESPONSE) {
07365 if (p->tag[0] == '\0' && arg->totag[0]) {
07366
07367 found = FALSE;
07368 } else if (arg->totag[0]) {
07369 if (strcmp(arg->totag, p->tag)) {
07370 found = FALSE;
07371 }
07372 }
07373 if (!found)
07374 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);
07375 }
07376 }
07377 return found;
07378 }
07379
07380
07381
07382
07383
07384
07385 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method)
07386 {
07387 struct sip_pvt *p = NULL;
07388 char *tag = "";
07389 char totag[128];
07390 char fromtag[128];
07391 struct find_call_cb_arg arg;
07392 const char *callid = get_header(req, "Call-ID");
07393 const char *from = get_header(req, "From");
07394 const char *to = get_header(req, "To");
07395 const char *cseq = get_header(req, "Cseq");
07396 struct sip_pvt *sip_pvt_ptr;
07397
07398
07399
07400 if (ast_strlen_zero(callid) || ast_strlen_zero(to) ||
07401 ast_strlen_zero(from) || ast_strlen_zero(cseq))
07402 return NULL;
07403
07404 arg.method = req->method;
07405 arg.callid = callid;
07406 arg.fromtag = fromtag;
07407 arg.totag = totag;
07408 arg.tag = "";
07409
07410 if (sip_cfg.pedanticsipchecking) {
07411
07412
07413
07414
07415
07416
07417 if (gettag(req, "To", totag, sizeof(totag)))
07418 req->has_to_tag = 1;
07419 gettag(req, "From", fromtag, sizeof(fromtag));
07420
07421 tag = (req->method == SIP_RESPONSE) ? totag : fromtag;
07422
07423 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);
07424
07425
07426 if (ast_strlen_zero(fromtag)) {
07427 ast_debug(5, "%s request has no from tag, dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
07428 return NULL;
07429 }
07430
07431 if (ast_strlen_zero(totag) && (req->method == SIP_ACK || req->method == SIP_BYE || req->method == SIP_INFO )) {
07432 ast_debug(5, "%s must have a to tag. dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
07433 return NULL;
07434 }
07435 }
07436
07437 restartsearch:
07438 if (!sip_cfg.pedanticsipchecking) {
07439 struct sip_pvt tmp_dialog = {
07440 .callid = callid,
07441 };
07442 sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find in dialogs");
07443 if (sip_pvt_ptr) {
07444
07445 sip_pvt_lock(sip_pvt_ptr);
07446 return sip_pvt_ptr;
07447 }
07448 } else {
07449 ao2_lock(dialogs);
07450 p = ao2_t_callback(dialogs, 0 , find_call_cb, &arg, "pedantic linear search for dialog");
07451 if (p) {
07452 if (sip_pvt_trylock(p)) {
07453 ao2_unlock(dialogs);
07454 usleep(1);
07455 goto restartsearch;
07456 }
07457 ao2_unlock(dialogs);
07458 return p;
07459 }
07460 ao2_unlock(dialogs);
07461 }
07462
07463
07464 if (sip_methods[intended_method].can_create == CAN_CREATE_DIALOG) {
07465 if (intended_method == SIP_REFER) {
07466
07467 transmit_response_using_temp(callid, sin, 1, intended_method, req, "603 Declined (no dialog)");
07468 } else if (intended_method == SIP_NOTIFY) {
07469
07470
07471 transmit_response_using_temp(callid, sin, 1, intended_method, req, "489 Bad event");
07472 } else {
07473
07474 if ((p = sip_alloc(callid, sin, 1, intended_method, req))) {
07475
07476 sip_pvt_lock(p);
07477 } else {
07478
07479
07480
07481
07482
07483
07484
07485
07486 transmit_response_using_temp(callid, sin, 1, intended_method, req, "500 Server internal error");
07487 ast_debug(4, "Failed allocating SIP dialog, sending 500 Server internal error and giving up\n");
07488 }
07489 }
07490 return p;
07491 } else if( sip_methods[intended_method].can_create == CAN_CREATE_DIALOG_UNSUPPORTED_METHOD) {
07492
07493 transmit_response_using_temp(callid, sin, 1, intended_method, req, "501 Method Not Implemented");
07494 ast_debug(2, "Got a request with unsupported SIP method.\n");
07495 } else if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
07496
07497 transmit_response_using_temp(callid, sin, 1, intended_method, req, "481 Call leg/transaction does not exist");
07498 ast_debug(2, "That's odd... Got a request in unknown dialog. Callid %s\n", callid ? callid : "<unknown>");
07499 }
07500
07501
07502 if (intended_method == SIP_RESPONSE)
07503 ast_debug(2, "That's odd... Got a response on a call we don't know about. Callid %s\n", callid ? callid : "<unknown>");
07504
07505 return NULL;
07506 }
07507
07508
07509 static int sip_register(const char *value, int lineno)
07510 {
07511 struct sip_registry *reg;
07512 int portnum = 0;
07513 enum sip_transport transport = SIP_TRANSPORT_UDP;
07514 char buf[256] = "";
07515 char *userpart = NULL, *hostpart = NULL;
07516
07517 AST_DECLARE_APP_ARGS(pre1,
07518 AST_APP_ARG(peer);
07519 AST_APP_ARG(userpart);
07520 );
07521 AST_DECLARE_APP_ARGS(pre2,
07522 AST_APP_ARG(transport);
07523 AST_APP_ARG(blank);
07524 AST_APP_ARG(userpart);
07525 );
07526 AST_DECLARE_APP_ARGS(user1,
07527 AST_APP_ARG(userpart);
07528 AST_APP_ARG(secret);
07529 AST_APP_ARG(authuser);
07530 );
07531 AST_DECLARE_APP_ARGS(host1,
07532 AST_APP_ARG(hostpart);
07533 AST_APP_ARG(expiry);
07534 );
07535 AST_DECLARE_APP_ARGS(host2,
07536 AST_APP_ARG(hostpart);
07537 AST_APP_ARG(extension);
07538 );
07539 AST_DECLARE_APP_ARGS(host3,
07540 AST_APP_ARG(host);
07541 AST_APP_ARG(port);
07542 );
07543
07544 if (!value)
07545 return -1;
07546 ast_copy_string(buf, value, sizeof(buf));
07547
07548
07549
07550
07551
07552
07553 if ((hostpart = strrchr(buf, '@'))) {
07554 *hostpart++ = '\0';
07555 userpart = buf;
07556 }
07557
07558 if (ast_strlen_zero(userpart) || ast_strlen_zero(hostpart)) {
07559 ast_log(LOG_WARNING, "Format for registration is [peer?][transport://]user[@domain][:secret[:authuser]]@host[:port][/extension][~expiry] at line %d\n", lineno);
07560 return -1;
07561 }
07562
07563
07564
07565
07566
07567
07568 AST_NONSTANDARD_RAW_ARGS(pre1, userpart, '?');
07569 if (ast_strlen_zero(pre1.userpart)) {
07570 pre1.userpart = pre1.peer;
07571 pre1.peer = NULL;
07572 }
07573
07574
07575
07576
07577
07578
07579
07580 AST_NONSTANDARD_RAW_ARGS(pre2, pre1.userpart, '/');
07581 if (ast_strlen_zero(pre2.userpart)) {
07582 pre2.userpart = pre2.transport;
07583 pre2.transport = NULL;
07584 } else {
07585 pre2.transport[strlen(pre2.transport) - 1] = '\0';
07586 }
07587
07588 if (!ast_strlen_zero(pre2.blank)) {
07589 ast_log(LOG_WARNING, "Format for registration is [peer?][transport://]user[@domain][:secret[:authuser]]@host[:port][/extension][~expiry] at line %d\n", lineno);
07590 return -1;
07591 }
07592
07593
07594
07595
07596
07597
07598
07599
07600
07601 AST_NONSTANDARD_RAW_ARGS(user1, pre2.userpart, ':');
07602
07603
07604
07605
07606
07607
07608
07609
07610
07611
07612 AST_NONSTANDARD_RAW_ARGS(host1, hostpart, '~');
07613
07614
07615
07616
07617
07618
07619
07620
07621
07622
07623
07624 AST_NONSTANDARD_RAW_ARGS(host2, host1.hostpart, '/');
07625
07626
07627
07628
07629
07630
07631
07632
07633
07634
07635
07636
07637 AST_NONSTANDARD_RAW_ARGS(host3, host2.hostpart, ':');
07638
07639 if (host3.port) {
07640 if (!(portnum = port_str2int(host3.port, 0))) {
07641 ast_log(LOG_NOTICE, "'%s' is not a valid port number on line %d of sip.conf. using default.\n", host3.port, lineno);
07642 }
07643 }
07644
07645
07646 if (!pre2.transport) {
07647 transport = SIP_TRANSPORT_UDP;
07648 } else if (!strncasecmp(pre2.transport, "tcp", 3)) {
07649 transport = SIP_TRANSPORT_TCP;
07650 } else if (!strncasecmp(pre2.transport, "tls", 3)) {
07651 transport = SIP_TRANSPORT_TLS;
07652 } else if (!strncasecmp(pre2.transport, "udp", 3)) {
07653 transport = SIP_TRANSPORT_UDP;
07654 } else {
07655 transport = SIP_TRANSPORT_UDP;
07656 ast_log(LOG_NOTICE, "'%.3s' is not a valid transport type on line %d of sip.conf. defaulting to udp.\n", pre2.transport, lineno);
07657 }
07658
07659
07660 if (!portnum) {
07661 if (transport == SIP_TRANSPORT_TLS) {
07662 portnum = STANDARD_TLS_PORT;
07663 } else {
07664 portnum = STANDARD_SIP_PORT;
07665 }
07666 }
07667
07668 if (!(reg = ast_calloc(1, sizeof(*reg)))) {
07669 ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry entry\n");
07670 return -1;
07671 }
07672
07673 if (ast_string_field_init(reg, 256)) {
07674 ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry strings\n");
07675 ast_free(reg);
07676 return -1;
07677 }
07678
07679 ast_atomic_fetchadd_int(®objs, 1);
07680 ASTOBJ_INIT(reg);
07681 ast_string_field_set(reg, callback, ast_strip_quoted(S_OR(host2.extension, "s"), "\"", "\""));
07682 ast_string_field_set(reg, username, ast_strip_quoted(S_OR(user1.userpart, ""), "\"", "\""));
07683 ast_string_field_set(reg, hostname, ast_strip_quoted(S_OR(host3.host, ""), "\"", "\""));
07684 ast_string_field_set(reg, authuser, ast_strip_quoted(S_OR(user1.authuser, ""), "\"", "\""));
07685 ast_string_field_set(reg, secret, ast_strip_quoted(S_OR(user1.secret, ""), "\"", "\""));
07686 ast_string_field_set(reg, peername, ast_strip_quoted(S_OR(pre1.peer, ""), "\"", "\""));
07687
07688 reg->transport = transport;
07689 reg->timeout = reg->expire = -1;
07690 reg->refresh = reg->expiry = reg->configured_expiry = (host1.expiry ? atoi(ast_strip_quoted(host1.expiry, "\"", "\"")) : default_expiry);
07691 reg->portno = portnum;
07692 reg->callid_valid = FALSE;
07693 reg->ocseq = INITIAL_CSEQ;
07694 ASTOBJ_CONTAINER_LINK(®l, reg);
07695 registry_unref(reg, "unref the reg pointer");
07696 return 0;
07697 }
07698
07699
07700 static int sip_subscribe_mwi(const char *value, int lineno)
07701 {
07702 struct sip_subscription_mwi *mwi;
07703 int portnum = 0;
07704 enum sip_transport transport = SIP_TRANSPORT_UDP;
07705 char buf[256] = "";
07706 char *username = NULL, *hostname = NULL, *secret = NULL, *authuser = NULL, *porta = NULL, *mailbox = NULL;
07707
07708 if (!value) {
07709 return -1;
07710 }
07711
07712 ast_copy_string(buf, value, sizeof(buf));
07713
07714 sip_parse_host(buf, lineno, &username, &portnum, &transport);
07715
07716 if ((hostname = strrchr(username, '@'))) {
07717 *hostname++ = '\0';
07718 }
07719
07720 if ((secret = strchr(username, ':'))) {
07721 *secret++ = '\0';
07722 if ((authuser = strchr(secret, ':'))) {
07723 *authuser++ = '\0';
07724 }
07725 }
07726
07727 if ((mailbox = strchr(hostname, '/'))) {
07728 *mailbox++ = '\0';
07729 }
07730
07731 if (ast_strlen_zero(username) || ast_strlen_zero(hostname) || ast_strlen_zero(mailbox)) {
07732 ast_log(LOG_WARNING, "Format for MWI subscription is user[:secret[:authuser]]@host[:port][/mailbox] at line %d\n", lineno);
07733 return -1;
07734 }
07735
07736 if ((porta = strchr(hostname, ':'))) {
07737 *porta++ = '\0';
07738 if (!(portnum = atoi(porta))) {
07739 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
07740 return -1;
07741 }
07742 }
07743
07744 if (!(mwi = ast_calloc(1, sizeof(*mwi)))) {
07745 return -1;
07746 }
07747
07748 if (ast_string_field_init(mwi, 256)) {
07749 ast_free(mwi);
07750 return -1;
07751 }
07752
07753 ASTOBJ_INIT(mwi);
07754 ast_string_field_set(mwi, username, username);
07755 if (secret) {
07756 ast_string_field_set(mwi, secret, secret);
07757 }
07758 if (authuser) {
07759 ast_string_field_set(mwi, authuser, authuser);
07760 }
07761 ast_string_field_set(mwi, hostname, hostname);
07762 ast_string_field_set(mwi, mailbox, mailbox);
07763 mwi->resub = -1;
07764 mwi->portno = portnum;
07765 mwi->transport = transport;
07766
07767 ASTOBJ_CONTAINER_LINK(&submwil, mwi);
07768 ASTOBJ_UNREF(mwi, sip_subscribe_mwi_destroy);
07769
07770 return 0;
07771 }
07772
07773
07774
07775 static int lws2sws(char *msgbuf, int len)
07776 {
07777 int h = 0, t = 0;
07778 int lws = 0;
07779
07780 for (; h < len;) {
07781
07782 if (msgbuf[h] == '\r') {
07783 h++;
07784 continue;
07785 }
07786
07787 if (msgbuf[h] == '\n') {
07788
07789 if (h + 1 == len)
07790 break;
07791
07792 if (msgbuf[h + 1] == ' ' || msgbuf[h + 1] == '\t') {
07793
07794 h++;
07795 continue;
07796 }
07797
07798 msgbuf[t++] = msgbuf[h++];
07799 lws = 0;
07800 continue;
07801 }
07802 if (msgbuf[h] == ' ' || msgbuf[h] == '\t') {
07803 if (lws) {
07804 h++;
07805 continue;
07806 }
07807 msgbuf[t++] = msgbuf[h++];
07808 lws = 1;
07809 continue;
07810 }
07811 msgbuf[t++] = msgbuf[h++];
07812 if (lws)
07813 lws = 0;
07814 }
07815 msgbuf[t] = '\0';
07816 return t;
07817 }
07818
07819
07820
07821
07822 static int parse_request(struct sip_request *req)
07823 {
07824 char *c = req->data->str;
07825 ptrdiff_t *dst = req->header;
07826 int i = 0, lim = SIP_MAX_HEADERS - 1;
07827 unsigned int skipping_headers = 0;
07828 ptrdiff_t current_header_offset = 0;
07829 char *previous_header = "";
07830
07831 req->header[0] = 0;
07832 req->headers = -1;
07833 for (; *c; c++) {
07834 if (*c == '\r') {
07835 *c = '\0';
07836 } else if (*c == '\n') {
07837 *c = '\0';
07838 current_header_offset = (c + 1) - req->data->str;
07839 previous_header = req->data->str + dst[i];
07840 if (skipping_headers) {
07841
07842
07843
07844 if (ast_strlen_zero(previous_header)) {
07845 skipping_headers = 0;
07846 }
07847 dst[i] = current_header_offset;
07848 continue;
07849 }
07850 if (sipdebug) {
07851 ast_debug(4, "%7s %2d [%3d]: %s\n",
07852 req->headers < 0 ? "Header" : "Body",
07853 i, (int) strlen(previous_header), previous_header);
07854 }
07855 if (ast_strlen_zero(previous_header) && req->headers < 0) {
07856 req->headers = i;
07857 dst = req->line;
07858 i = 0;
07859 lim = SIP_MAX_LINES - 1;
07860 } else {
07861 if (i++ == lim) {
07862
07863
07864
07865 if (req->headers != -1) {
07866 break;
07867 } else {
07868 req->headers = i;
07869 dst = req->line;
07870 i = 0;
07871 lim = SIP_MAX_LINES - 1;
07872 skipping_headers = 1;
07873 }
07874 }
07875 }
07876 dst[i] = current_header_offset;
07877 }
07878 }
07879
07880
07881
07882
07883
07884
07885 previous_header = req->data->str + dst[i];
07886 if ((i < lim) && !ast_strlen_zero(previous_header)) {
07887 if (sipdebug) {
07888 ast_debug(4, "%7s %2d [%3d]: %s\n",
07889 req->headers < 0 ? "Header" : "Body",
07890 i, (int) strlen(previous_header), previous_header );
07891 }
07892 i++;
07893 }
07894
07895
07896 if (req->headers >= 0) {
07897 req->lines = i;
07898 } else {
07899 req->headers = i;
07900 req->lines = 0;
07901
07902 req->line[0] = ast_str_strlen(req->data);
07903 }
07904
07905 if (*c) {
07906 ast_log(LOG_WARNING, "Too many lines, skipping <%s>\n", c);
07907 }
07908
07909
07910 return determine_firstline_parts(req);
07911 }
07912
07913
07914
07915
07916
07917
07918
07919
07920
07921 static int find_sdp(struct sip_request *req)
07922 {
07923 const char *content_type;
07924 const char *content_length;
07925 const char *search;
07926 char *boundary;
07927 unsigned int x;
07928 int boundaryisquoted = FALSE;
07929 int found_application_sdp = FALSE;
07930 int found_end_of_headers = FALSE;
07931
07932 content_length = get_header(req, "Content-Length");
07933
07934 if (!ast_strlen_zero(content_length)) {
07935 if (sscanf(content_length, "%30u", &x) != 1) {
07936 ast_log(LOG_WARNING, "Invalid Content-Length: %s\n", content_length);
07937 return 0;
07938 }
07939
07940
07941
07942 if (x == 0)
07943 return 0;
07944 }
07945
07946 content_type = get_header(req, "Content-Type");
07947
07948
07949 if (!strncasecmp(content_type, "application/sdp", 15)) {
07950 req->sdp_start = 0;
07951 req->sdp_count = req->lines;
07952 return req->lines ? 1 : 0;
07953 }
07954
07955
07956 if (strncasecmp(content_type, "multipart/mixed", 15))
07957 return 0;
07958
07959
07960 if ((search = strcasestr(content_type, ";boundary=")))
07961 search += 10;
07962 else if ((search = strcasestr(content_type, "; boundary=")))
07963 search += 11;
07964 else
07965 return 0;
07966
07967 if (ast_strlen_zero(search))
07968 return 0;
07969
07970
07971 if (*search == '\"') {
07972 search++;
07973 boundaryisquoted = TRUE;
07974 }
07975
07976
07977
07978 boundary = ast_strdupa(search - 2);
07979 boundary[0] = boundary[1] = '-';
07980
07981 if (boundaryisquoted)
07982 boundary[strlen(boundary) - 1] = '\0';
07983
07984
07985
07986
07987 for (x = 0; x < (req->lines); x++) {
07988 char *line = REQ_OFFSET_TO_STR(req, line[x]);
07989 if (!strncasecmp(line, boundary, strlen(boundary))){
07990 if (found_application_sdp && found_end_of_headers) {
07991 req->sdp_count = (x - 1) - req->sdp_start;
07992 return 1;
07993 }
07994 found_application_sdp = FALSE;
07995 }
07996 if (!strcasecmp(line, "Content-Type: application/sdp"))
07997 found_application_sdp = TRUE;
07998
07999 if (ast_strlen_zero(line)) {
08000 if (found_application_sdp && !found_end_of_headers){
08001 req->sdp_start = x;
08002 found_end_of_headers = TRUE;
08003 }
08004 }
08005 }
08006 if (found_application_sdp && found_end_of_headers) {
08007 req->sdp_count = x - req->sdp_start;
08008 return TRUE;
08009 }
08010 return FALSE;
08011 }
08012
08013 enum media_type {
08014 SDP_AUDIO,
08015 SDP_VIDEO,
08016 SDP_IMAGE,
08017 SDP_TEXT,
08018 };
08019
08020 static int get_ip_and_port_from_sdp(struct sip_request *req, const enum media_type media, struct sockaddr_in *sin)
08021 {
08022 const char *m;
08023 const char *c;
08024 int miterator = req->sdp_start;
08025 int citerator = req->sdp_start;
08026 int x = 0;
08027 int numberofports;
08028 int len;
08029 char host[258] = "";
08030 struct ast_hostent audiohp;
08031 struct hostent *hp;
08032
08033 c = get_sdp_iterate(&citerator, req, "c");
08034 if (sscanf(c, "IN IP4 %256s", host) != 1) {
08035 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
08036
08037 }
08038
08039 for (m = get_sdp_iterate(&miterator, req, "m"); !ast_strlen_zero(m); m = get_sdp_iterate(&miterator, req, "m")) {
08040 if ((media == SDP_AUDIO && ((sscanf(m, "audio %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08041 (sscanf(m, "audio %30u RTP/AVP %n", &x, &len) == 1 && len > 0))) ||
08042 (media == SDP_VIDEO && ((sscanf(m, "video %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08043 (sscanf(m, "video %30u RTP/AVP %n", &x, &len) == 1 && len > 0)))) {
08044
08045
08046
08047
08048 c = get_sdp_iterate(&citerator, req, "c");
08049 if (!ast_strlen_zero(c)) {
08050 sscanf(c, "IN IP4 %256s", host);
08051 }
08052 break;
08053 }
08054 }
08055
08056 if (ast_strlen_zero(host) || x == 0) {
08057 ast_log(LOG_WARNING, "Failed to read an alternate host or port in SDP. Expect %s problems\n", media == SDP_AUDIO ? "audio" : "video");
08058 return -1;
08059 }
08060
08061 hp = ast_gethostbyname(host, &audiohp);
08062 if (!hp) {
08063 ast_log(LOG_WARNING, "Could not look up IP address of alternate hostname. Expect %s problems\n", media == SDP_AUDIO? "audio" : "video");
08064 return -1;
08065 }
08066
08067 memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
08068 sin->sin_port = htons(x);
08069 return 0;
08070 }
08071
08072
08073
08074
08075
08076
08077 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action)
08078 {
08079
08080 int start = req->sdp_start;
08081 int next = start;
08082 int iterator = start;
08083
08084
08085 char type = '\0';
08086 const char *value = NULL;
08087 const char *m = NULL;
08088 const char *nextm = NULL;
08089 int len = -1;
08090
08091
08092 struct ast_hostent sessionhp;
08093 struct ast_hostent audiohp;
08094 struct ast_hostent videohp;
08095 struct ast_hostent texthp;
08096 struct ast_hostent imagehp;
08097 struct hostent *hp = NULL;
08098 struct hostent *vhp = NULL;
08099 struct hostent *thp = NULL;
08100 struct hostent *ihp = NULL;
08101 int portno = -1;
08102 int vportno = -1;
08103 int tportno = -1;
08104 int udptlportno = -1;
08105 struct sockaddr_in sin;
08106 struct sockaddr_in vsin;
08107 struct sockaddr_in isin;
08108 struct sockaddr_in tsin;
08109
08110
08111 int peercapability = 0, peernoncodeccapability = 0;
08112 int vpeercapability = 0, vpeernoncodeccapability = 0;
08113 int tpeercapability = 0, tpeernoncodeccapability = 0;
08114
08115 struct ast_rtp *newaudiortp, *newvideortp, *newtextrtp;
08116 int newjointcapability;
08117 int newpeercapability;
08118 int newnoncodeccapability;
08119
08120 const char *codecs;
08121 int codec;
08122
08123
08124 int sendonly = -1;
08125 int vsendonly = -1;
08126 int numberofports;
08127 int numberofmediastreams = 0;
08128 int last_rtpmap_codec = 0;
08129 int red_data_pt[10];
08130 int red_num_gen = 0;
08131 char red_fmtp[100] = "empty";
08132 int debug = sip_debug_test_pvt(p);
08133
08134
08135 char buf[SIPBUFSIZE];
08136
08137
08138
08139 if (!p->rtp) {
08140 ast_log(LOG_ERROR, "Got SDP but have no RTP session allocated.\n");
08141 return -1;
08142 }
08143
08144
08145 #ifdef LOW_MEMORY
08146 newaudiortp = ast_threadstorage_get(&ts_audio_rtp, ast_rtp_alloc_size());
08147 #else
08148 newaudiortp = alloca(ast_rtp_alloc_size());
08149 #endif
08150 memset(newaudiortp, 0, ast_rtp_alloc_size());
08151 ast_rtp_new_init(newaudiortp);
08152 ast_rtp_pt_clear(newaudiortp);
08153
08154 #ifdef LOW_MEMORY
08155 newvideortp = ast_threadstorage_get(&ts_video_rtp, ast_rtp_alloc_size());
08156 #else
08157 newvideortp = alloca(ast_rtp_alloc_size());
08158 #endif
08159 memset(newvideortp, 0, ast_rtp_alloc_size());
08160 ast_rtp_new_init(newvideortp);
08161 ast_rtp_pt_clear(newvideortp);
08162
08163 #ifdef LOW_MEMORY
08164 newtextrtp = ast_threadstorage_get(&ts_text_rtp, ast_rtp_alloc_size());
08165 #else
08166 newtextrtp = alloca(ast_rtp_alloc_size());
08167 #endif
08168 memset(newtextrtp, 0, ast_rtp_alloc_size());
08169 ast_rtp_new_init(newtextrtp);
08170 ast_rtp_pt_clear(newtextrtp);
08171
08172
08173 p->lastrtprx = p->lastrtptx = time(NULL);
08174
08175 memset(p->offered_media, 0, sizeof(p->offered_media));
08176
08177
08178
08179 p->novideo = TRUE;
08180 p->notext = TRUE;
08181
08182 if (p->vrtp)
08183 ast_rtp_pt_clear(newvideortp);
08184
08185 if (p->trtp)
08186 ast_rtp_pt_clear(newtextrtp);
08187
08188
08189 nextm = get_sdp_iterate(&next, req, "m");
08190 if (ast_strlen_zero(nextm)) {
08191 ast_log(LOG_WARNING, "Insufficient information for SDP (m= not found)\n");
08192 return -1;
08193 }
08194
08195
08196 while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
08197 int processed = FALSE;
08198 switch (type) {
08199 case 'o':
08200
08201
08202
08203 if (!process_sdp_o(value, p))
08204 return (p->session_modify == FALSE) ? 0 : -1;
08205 break;
08206 case 'c':
08207 if (process_sdp_c(value, &sessionhp)) {
08208 processed = TRUE;
08209 hp = &sessionhp.hp;
08210 vhp = hp;
08211 thp = hp;
08212 ihp = hp;
08213 }
08214 break;
08215 case 'a':
08216 if (process_sdp_a_sendonly(value, &sendonly)) {
08217 processed = TRUE;
08218 vsendonly = sendonly;
08219 }
08220 else if (process_sdp_a_audio(value, p, newaudiortp, &last_rtpmap_codec))
08221 processed = TRUE;
08222 else if (process_sdp_a_video(value, p, newvideortp, &last_rtpmap_codec))
08223 processed = TRUE;
08224 else if (process_sdp_a_text(value, p, newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec))
08225 processed = TRUE;
08226 else if (process_sdp_a_image(value, p))
08227 processed = TRUE;
08228 break;
08229 }
08230
08231 if (option_debug > 2)
08232 ast_log(LOG_DEBUG, "Processing session-level SDP %c=%s... %s\n", type, value, (processed == TRUE)? "OK." : "UNSUPPORTED.");
08233 }
08234
08235
08236
08237
08238 while (!ast_strlen_zero(nextm)) {
08239 int audio = FALSE;
08240 int video = FALSE;
08241 int image = FALSE;
08242 int text = FALSE;
08243 int x;
08244
08245 numberofports = 1;
08246 len = -1;
08247 start = next;
08248 m = nextm;
08249 iterator = next;
08250 nextm = get_sdp_iterate(&next, req, "m");
08251
08252
08253 if ((sscanf(m, "audio %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08254 (sscanf(m, "audio %30u RTP/AVP %n", &x, &len) == 1 && len > 0)) {
08255 audio = TRUE;
08256 p->offered_media[SDP_AUDIO].offered = TRUE;
08257 numberofmediastreams++;
08258 portno = x;
08259
08260
08261 codecs = m + len;
08262 ast_copy_string(p->offered_media[SDP_AUDIO].text, codecs, sizeof(p->offered_media[SDP_AUDIO].text));
08263 for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
08264 if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
08265 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
08266 return -1;
08267 }
08268 if (debug)
08269 ast_verbose("Found RTP audio format %d\n", codec);
08270
08271 ast_rtp_set_m_type(newaudiortp, codec);
08272 }
08273
08274 } else if ((sscanf(m, "video %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08275 (sscanf(m, "video %30u RTP/AVP %n", &x, &len) == 1 && len >= 0)) {
08276 video = TRUE;
08277 p->novideo = FALSE;
08278 p->offered_media[SDP_VIDEO].offered = TRUE;
08279 numberofmediastreams++;
08280 vportno = x;
08281
08282
08283 codecs = m + len;
08284 ast_copy_string(p->offered_media[SDP_VIDEO].text, codecs, sizeof(p->offered_media[SDP_VIDEO].text));
08285 for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
08286 if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
08287 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
08288 return -1;
08289 }
08290 if (debug)
08291 ast_verbose("Found RTP video format %d\n", codec);
08292 ast_rtp_set_m_type(newvideortp, codec);
08293 }
08294
08295 } else if ((sscanf(m, "text %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08296 (sscanf(m, "text %30u RTP/AVP %n", &x, &len) == 1 && len > 0)) {
08297 text = TRUE;
08298 p->notext = FALSE;
08299 p->offered_media[SDP_TEXT].offered = TRUE;
08300 numberofmediastreams++;
08301 tportno = x;
08302
08303
08304 codecs = m + len;
08305 ast_copy_string(p->offered_media[SDP_TEXT].text, codecs, sizeof(p->offered_media[SDP_TEXT].text));
08306 for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
08307 if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
08308 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
08309 return -1;
08310 }
08311 if (debug)
08312 ast_verbose("Found RTP text format %d\n", codec);
08313 ast_rtp_set_m_type(newtextrtp, codec);
08314 }
08315
08316 } else if (p->udptl && ((sscanf(m, "image %30u udptl t38%n", &x, &len) == 1 && len > 0) ||
08317 (sscanf(m, "image %30u UDPTL t38%n", &x, &len) == 1 && len > 0) )) {
08318 image = TRUE;
08319 if (debug)
08320 ast_verbose("Got T.38 offer in SDP in dialog %s\n", p->callid);
08321 p->offered_media[SDP_IMAGE].offered = TRUE;
08322 udptlportno = x;
08323 numberofmediastreams++;
08324
08325 if (p->t38.state != T38_ENABLED) {
08326 memset(&p->t38.their_parms, 0, sizeof(p->t38.their_parms));
08327
08328
08329
08330 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
08331 }
08332 } else {
08333 ast_log(LOG_WARNING, "Unsupported SDP media type in offer: %s\n", m);
08334 continue;
08335 }
08336
08337
08338 if (numberofports > 1)
08339 ast_log(LOG_WARNING, "SDP offered %d ports for media, not supported by Asterisk. Will try anyway...\n", numberofports);
08340
08341
08342
08343
08344 while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
08345 int processed = FALSE;
08346
08347 switch (type) {
08348 case 'c':
08349 if (audio) {
08350 if (process_sdp_c(value, &audiohp)) {
08351 processed = TRUE;
08352 hp = &audiohp.hp;
08353 }
08354 } else if (video) {
08355 if (process_sdp_c(value, &videohp)) {
08356 processed = TRUE;
08357 vhp = &videohp.hp;
08358 }
08359 } else if (text) {
08360 if (process_sdp_c(value, &texthp)) {
08361 processed = TRUE;
08362 thp = &texthp.hp;
08363 }
08364 } else if (image) {
08365 if (process_sdp_c(value, &imagehp)) {
08366 processed = TRUE;
08367 ihp = &imagehp.hp;
08368 }
08369 }
08370 break;
08371 case 'a':
08372
08373 if (audio) {
08374 if (process_sdp_a_sendonly(value, &sendonly))
08375 processed = TRUE;
08376 else if (process_sdp_a_audio(value, p, newaudiortp, &last_rtpmap_codec))
08377 processed = TRUE;
08378 }
08379
08380 else if (video) {
08381 if (process_sdp_a_sendonly(value, &vsendonly))
08382 processed = TRUE;
08383 else if (process_sdp_a_video(value, p, newvideortp, &last_rtpmap_codec))
08384 processed = TRUE;
08385 }
08386
08387 else if (text) {
08388 if (process_sdp_a_text(value, p, newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec))
08389 processed = TRUE;
08390 }
08391
08392 else if (image) {
08393 if (process_sdp_a_image(value, p))
08394 processed = TRUE;
08395 }
08396 break;
08397 }
08398
08399 if (option_debug > 2)
08400 ast_log(LOG_DEBUG, "Processing media-level (%s) SDP %c=%s... %s\n",
08401 (audio == TRUE)? "audio" : (video == TRUE)? "video" : "image",
08402 type, value,
08403 (processed == TRUE)? "OK." : "UNSUPPORTED.");
08404 }
08405 }
08406
08407
08408
08409 if (!hp && !vhp && !thp && !ihp) {
08410 ast_log(LOG_WARNING, "Insufficient information in SDP (c=)...\n");
08411 return -1;
08412 }
08413
08414 if (portno == -1 && vportno == -1 && udptlportno == -1 && tportno == -1)
08415
08416
08417 return -2;
08418
08419 if (numberofmediastreams > 3)
08420
08421 return -3;
08422
08423 if (udptlportno == -1) {
08424 change_t38_state(p, T38_DISABLED);
08425 }
08426
08427
08428
08429 ast_rtp_get_current_formats(newaudiortp, &peercapability, &peernoncodeccapability);
08430 ast_rtp_get_current_formats(newvideortp, &vpeercapability, &vpeernoncodeccapability);
08431 ast_rtp_get_current_formats(newtextrtp, &tpeercapability, &tpeernoncodeccapability);
08432
08433 newjointcapability = p->capability & (peercapability | vpeercapability | tpeercapability);
08434 newpeercapability = (peercapability | vpeercapability | tpeercapability);
08435 newnoncodeccapability = p->noncodeccapability & peernoncodeccapability;
08436
08437 if (debug) {
08438
08439 char s1[SIPBUFSIZE], s2[SIPBUFSIZE], s3[SIPBUFSIZE], s4[SIPBUFSIZE], s5[SIPBUFSIZE];
08440
08441 ast_verbose("Capabilities: us - %s, peer - audio=%s/video=%s/text=%s, combined - %s\n",
08442 ast_getformatname_multiple(s1, SIPBUFSIZE, p->capability),
08443 ast_getformatname_multiple(s2, SIPBUFSIZE, peercapability),
08444 ast_getformatname_multiple(s3, SIPBUFSIZE, vpeercapability),
08445 ast_getformatname_multiple(s4, SIPBUFSIZE, tpeercapability),
08446 ast_getformatname_multiple(s5, SIPBUFSIZE, newjointcapability));
08447
08448 ast_verbose("Non-codec capabilities (dtmf): us - %s, peer - %s, combined - %s\n",
08449 ast_rtp_lookup_mime_multiple(s1, SIPBUFSIZE, p->noncodeccapability, 0, 0),
08450 ast_rtp_lookup_mime_multiple(s2, SIPBUFSIZE, peernoncodeccapability, 0, 0),
08451 ast_rtp_lookup_mime_multiple(s3, SIPBUFSIZE, newnoncodeccapability, 0, 0));
08452 }
08453 if (!newjointcapability && (portno != -1)) {
08454 ast_log(LOG_NOTICE, "No compatible codecs, not accepting this offer!\n");
08455
08456 return -1;
08457 }
08458
08459
08460 if (p->rtp) {
08461 if (portno > 0) {
08462 sin.sin_family = AF_INET;
08463 sin.sin_port = htons(portno);
08464 memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
08465 ast_rtp_set_peer(p->rtp, &sin);
08466 if (debug)
08467 ast_verbose("Peer audio RTP is at port %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
08468
08469
08470 p->jointcapability = newjointcapability;
08471 p->peercapability = newpeercapability;
08472 p->jointnoncodeccapability = newnoncodeccapability;
08473
08474 ast_rtp_pt_copy(p->rtp, newaudiortp);
08475
08476 if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) {
08477 ast_clear_flag(&p->flags[0], SIP_DTMF);
08478 if (newnoncodeccapability & AST_RTP_DTMF) {
08479
08480 ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
08481
08482 ast_rtp_setdtmf(p->rtp, 1);
08483 ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
08484 } else {
08485 ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
08486 }
08487 }
08488 } else if (udptlportno > 0) {
08489 if (debug)
08490 ast_verbose("Got T.38 Re-invite without audio. Keeping RTP active during T.38 session.\n");
08491 } else {
08492 ast_rtp_stop(p->rtp);
08493 if (debug)
08494 ast_verbose("Peer doesn't provide audio\n");
08495 }
08496 }
08497
08498
08499 if (p->vrtp) {
08500 if (vportno > 0) {
08501 vsin.sin_family = AF_INET;
08502 vsin.sin_port = htons(vportno);
08503 memcpy(&vsin.sin_addr, vhp->h_addr, sizeof(vsin.sin_addr));
08504 ast_rtp_set_peer(p->vrtp, &vsin);
08505 if (debug)
08506 ast_verbose("Peer video RTP is at port %s:%d\n", ast_inet_ntoa(vsin.sin_addr), ntohs(vsin.sin_port));
08507 ast_rtp_pt_copy(p->vrtp, newvideortp);
08508 } else {
08509 ast_rtp_stop(p->vrtp);
08510 if (debug)
08511 ast_verbose("Peer doesn't provide video\n");
08512 }
08513 }
08514
08515
08516 if (p->trtp) {
08517 if (tportno > 0) {
08518 tsin.sin_family = AF_INET;
08519 tsin.sin_port = htons(tportno);
08520 memcpy(&tsin.sin_addr, thp->h_addr, sizeof(tsin.sin_addr));
08521 ast_rtp_set_peer(p->trtp, &tsin);
08522 if (debug)
08523 ast_verbose("Peer T.140 RTP is at port %s:%d\n", ast_inet_ntoa(tsin.sin_addr), ntohs(tsin.sin_port));
08524 if ((p->jointcapability & AST_FORMAT_T140RED)) {
08525 p->red = 1;
08526 rtp_red_init(p->trtp, 300, red_data_pt, 2);
08527 } else {
08528 p->red = 0;
08529 }
08530 ast_rtp_pt_copy(p->trtp, newtextrtp);
08531 } else {
08532 ast_rtp_stop(p->trtp);
08533 if (debug)
08534 ast_verbose("Peer doesn't provide T.140\n");
08535 }
08536 }
08537
08538 if (p->udptl) {
08539 if (udptlportno > 0) {
08540 isin.sin_family = AF_INET;
08541 isin.sin_port = htons(udptlportno);
08542 if (ast_test_flag(&p->flags[0], SIP_NAT) && ast_test_flag(&p->flags[1], SIP_PAGE2_UDPTL_DESTINATION)) {
08543 struct sockaddr_in remote_address = { 0, };
08544 ast_rtp_get_peer(p->rtp, &remote_address);
08545 if (remote_address.sin_addr.s_addr) {
08546 memcpy(&isin, &remote_address, sizeof(isin));
08547 if (debug) {
08548 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));
08549 }
08550 }
08551 } else {
08552 memcpy(&isin.sin_addr, ihp->h_addr, sizeof(isin.sin_addr));
08553 }
08554 ast_udptl_set_peer(p->udptl, &isin);
08555 if (debug)
08556 ast_debug(1,"Peer T.38 UDPTL is at port %s:%d\n", ast_inet_ntoa(isin.sin_addr), ntohs(isin.sin_port));
08557
08558
08559 if (!ast_udptl_get_far_max_datagram(p->udptl)) {
08560
08561 ast_udptl_set_far_max_datagram(p->udptl, 0);
08562 }
08563
08564
08565 if ((t38action == SDP_T38_ACCEPT) &&
08566 (p->t38.state == T38_LOCAL_REINVITE)) {
08567 change_t38_state(p, T38_ENABLED);
08568 } else if ((t38action == SDP_T38_INITIATE) &&
08569 p->owner && p->lastinvite) {
08570 change_t38_state(p, T38_PEER_REINVITE);
08571
08572 if (ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_T38)) {
08573 ast_channel_lock(p->owner);
08574 if (strcmp(p->owner->exten, "fax")) {
08575 const char *target_context = S_OR(p->owner->macrocontext, p->owner->context);
08576 ast_channel_unlock(p->owner);
08577 if (ast_exists_extension(p->owner, target_context, "fax", 1, p->owner->cid.cid_num)) {
08578 ast_verbose(VERBOSE_PREFIX_2 "Redirecting '%s' to fax extension due to peer T.38 re-INVITE\n", p->owner->name);
08579 pbx_builtin_setvar_helper(p->owner, "FAXEXTEN", p->owner->exten);
08580 if (ast_async_goto(p->owner, target_context, "fax", 1)) {
08581 ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", p->owner->name, target_context);
08582 }
08583 } else {
08584 ast_log(LOG_NOTICE, "T.38 re-INVITE detected but no fax extension\n");
08585 }
08586 } else {
08587 ast_channel_unlock(p->owner);
08588 }
08589 }
08590 }
08591 } else {
08592 ast_udptl_stop(p->udptl);
08593 if (debug)
08594 ast_debug(1, "Peer doesn't provide T.38 UDPTL\n");
08595 }
08596 }
08597
08598 if ((portno == -1) && (p->t38.state != T38_DISABLED)) {
08599 ast_debug(3, "Have T.38 but no audio, accepting offer anyway\n");
08600 return 0;
08601 }
08602
08603
08604 ast_debug(2, "We're settling with these formats: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, p->jointcapability));
08605
08606 if (!p->owner)
08607 return 0;
08608
08609 ast_debug(4, "We have an owner, now see if we need to change this call\n");
08610
08611 if (!(p->owner->nativeformats & p->jointcapability) && (p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
08612 if (debug) {
08613 char s1[SIPBUFSIZE], s2[SIPBUFSIZE];
08614 ast_debug(1, "Oooh, we need to change our audio formats since our peer supports only %s and not %s\n",
08615 ast_getformatname_multiple(s1, SIPBUFSIZE, p->jointcapability),
08616 ast_getformatname_multiple(s2, SIPBUFSIZE, p->owner->nativeformats));
08617 }
08618 p->owner->nativeformats = ast_codec_choose(&p->prefs, p->jointcapability, 1) | (p->capability & vpeercapability) | (p->capability & tpeercapability);
08619 ast_set_read_format(p->owner, p->owner->readformat);
08620 ast_set_write_format(p->owner, p->owner->writeformat);
08621 }
08622
08623 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) && sin.sin_addr.s_addr && (!sendonly || sendonly == -1)) {
08624 ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
08625
08626 ast_queue_frame(p->owner, &ast_null_frame);
08627
08628 append_history(p, "Unhold", "%s", req->data->str);
08629 if (sip_cfg.callevents)
08630 manager_event(EVENT_FLAG_CALL, "Hold",
08631 "Status: Off\r\n"
08632 "Channel: %s\r\n"
08633 "Uniqueid: %s\r\n",
08634 p->owner->name,
08635 p->owner->uniqueid);
08636 if (sip_cfg.notifyhold)
08637 sip_peer_hold(p, FALSE);
08638 ast_clear_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD);
08639 } else if (!sin.sin_addr.s_addr || (sendonly && sendonly != -1)) {
08640 int already_on_hold = ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD);
08641 ast_queue_control_data(p->owner, AST_CONTROL_HOLD,
08642 S_OR(p->mohsuggest, NULL),
08643 !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
08644 if (sendonly)
08645 ast_rtp_stop(p->rtp);
08646
08647
08648 ast_queue_frame(p->owner, &ast_null_frame);
08649
08650 append_history(p, "Hold", "%s", req->data->str);
08651 if (sip_cfg.callevents && !ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
08652 manager_event(EVENT_FLAG_CALL, "Hold",
08653 "Status: On\r\n"
08654 "Channel: %s\r\n"
08655 "Uniqueid: %s\r\n",
08656 p->owner->name,
08657 p->owner->uniqueid);
08658 }
08659 if (sendonly == 1)
08660 ast_set_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD_ONEDIR);
08661 else if (sendonly == 2)
08662 ast_set_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD_INACTIVE);
08663 else
08664 ast_set_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD_ACTIVE);
08665 if (sip_cfg.notifyhold && !already_on_hold)
08666 sip_peer_hold(p, TRUE);
08667 }
08668
08669 return 0;
08670 }
08671
08672 static int process_sdp_o(const char *o, struct sip_pvt *p)
08673 {
08674 char *o_copy;
08675 char *token;
08676 int64_t rua_version;
08677
08678
08679
08680
08681
08682
08683
08684
08685
08686
08687 p->session_modify = TRUE;
08688
08689 if (ast_strlen_zero(o)) {
08690 ast_log(LOG_WARNING, "SDP syntax error. SDP without an o= line\n");
08691 return FALSE;
08692 }
08693
08694 o_copy = ast_strdupa(o);
08695 token = strsep(&o_copy, " ");
08696 if (!o_copy) {
08697 ast_log(LOG_WARNING, "SDP syntax error in o= line username\n");
08698 return FALSE;
08699 }
08700 token = strsep(&o_copy, " ");
08701 if (!o_copy) {
08702 ast_log(LOG_WARNING, "SDP syntax error in o= line session-id\n");
08703 return FALSE;
08704 }
08705 token = strsep(&o_copy, " ");
08706 if (!o_copy) {
08707 ast_log(LOG_WARNING, "SDP syntax error in o= line\n");
08708 return FALSE;
08709 }
08710 if (!sscanf(token, "%30" SCNd64, &rua_version)) {
08711 ast_log(LOG_WARNING, "SDP syntax error in o= line version\n");
08712 return FALSE;
08713 }
08714
08715
08716
08717
08718
08719
08720
08721
08722
08723
08724
08725
08726
08727
08728
08729
08730
08731
08732
08733 if (ast_test_flag(&p->flags[1], SIP_PAGE2_IGNORESDPVERSION) ||
08734 (p->sessionversion_remote < 0) ||
08735 (p->sessionversion_remote < rua_version)) {
08736 p->sessionversion_remote = rua_version;
08737 } else {
08738 if (p->t38.state == T38_LOCAL_REINVITE) {
08739 p->sessionversion_remote = rua_version;
08740 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);
08741 } else {
08742 p->session_modify = FALSE;
08743 ast_debug(2, "Call %s responded to our reinvite without changing SDP version; ignoring SDP.\n", p->callid);
08744 return FALSE;
08745 }
08746 }
08747
08748 return TRUE;
08749 }
08750
08751 static int process_sdp_c(const char *c, struct ast_hostent *ast_hp)
08752 {
08753 char host[258];
08754 struct hostent *hp;
08755
08756
08757 if (sscanf(c, "IN IP4 %255s", host) != 1) {
08758 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
08759 return FALSE;
08760 } else {
08761 if (!(hp = ast_gethostbyname(host, ast_hp))) {
08762 ast_log(LOG_WARNING, "Unable to lookup RTP Audio host in c= line, '%s'\n", c);
08763 return FALSE;
08764 }
08765 return TRUE;
08766 }
08767 return FALSE;
08768 }
08769
08770 static int process_sdp_a_sendonly(const char *a, int *sendonly)
08771 {
08772 int found = FALSE;
08773
08774 if (!strcasecmp(a, "sendonly")) {
08775 if (*sendonly == -1)
08776 *sendonly = 1;
08777 found = TRUE;
08778 } else if (!strcasecmp(a, "inactive")) {
08779 if (*sendonly == -1)
08780 *sendonly = 2;
08781 found = TRUE;
08782 } else if (!strcasecmp(a, "sendrecv")) {
08783 if (*sendonly == -1)
08784 *sendonly = 0;
08785 found = TRUE;
08786 }
08787 return found;
08788 }
08789
08790 static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp *newaudiortp, int *last_rtpmap_codec)
08791 {
08792 int found = FALSE;
08793 int codec;
08794 char mimeSubtype[128];
08795 char fmtp_string[64];
08796 unsigned int sample_rate;
08797 int debug = sip_debug_test_pvt(p);
08798
08799 if (!strncasecmp(a, "ptime", 5)) {
08800 char *tmp = strrchr(a, ':');
08801 long int framing = 0;
08802 if (tmp) {
08803 tmp++;
08804 framing = strtol(tmp, NULL, 10);
08805 if (framing == LONG_MIN || framing == LONG_MAX) {
08806 framing = 0;
08807 ast_debug(1, "Can't read framing from SDP: %s\n", a);
08808 }
08809 }
08810 if (framing && p->autoframing) {
08811 struct ast_codec_pref *pref = ast_rtp_codec_getpref(p->rtp);
08812 int codec_n;
08813 int format = 0;
08814 for (codec_n = 0; codec_n < MAX_RTP_PT; codec_n++) {
08815 format = ast_rtp_codec_getformat(codec_n);
08816 if (!format)
08817 continue;
08818 if (option_debug)
08819 ast_log(LOG_DEBUG, "Setting framing for %d to %ld\n", format, framing);
08820 ast_codec_pref_setsize(pref, format, framing);
08821 }
08822 ast_rtp_codec_setpref(p->rtp, pref);
08823 }
08824 found = TRUE;
08825 } else if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
08826
08827 if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
08828 if (ast_rtp_set_rtpmap_type_rate(newaudiortp, codec, "audio", mimeSubtype,
08829 ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0, sample_rate) != -1) {
08830 if (debug)
08831 ast_verbose("Found audio description format %s for ID %d\n", mimeSubtype, codec);
08832
08833 (*last_rtpmap_codec)++;
08834 found = TRUE;
08835 } else {
08836 ast_rtp_unset_m_type(newaudiortp, codec);
08837 if (debug)
08838 ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
08839 }
08840 } else {
08841 if (debug)
08842 ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
08843 }
08844 } else if (sscanf(a, "fmtp: %30u %63s", &codec, fmtp_string) == 2) {
08845 struct rtpPayloadType payload;
08846
08847 payload = ast_rtp_lookup_pt(newaudiortp, codec);
08848 if (payload.code && payload.isAstFormat) {
08849 unsigned int bit_rate;
08850
08851 switch (payload.code) {
08852 case AST_FORMAT_SIREN7:
08853 if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
08854 if (bit_rate != 32000) {
08855 ast_log(LOG_WARNING, "Got Siren7 offer at %d bps, but only 32000 bps supported; ignoring.\n", bit_rate);
08856 ast_rtp_unset_m_type(newaudiortp, codec);
08857 } else {
08858 found = TRUE;
08859 }
08860 }
08861 break;
08862 case AST_FORMAT_SIREN14:
08863 if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
08864 if (bit_rate != 48000) {
08865 ast_log(LOG_WARNING, "Got Siren14 offer at %d bps, but only 48000 bps supported; ignoring.\n", bit_rate);
08866 ast_rtp_unset_m_type(newaudiortp, codec);
08867 } else {
08868 found = TRUE;
08869 }
08870 }
08871 break;
08872 }
08873 }
08874 }
08875
08876 return found;
08877 }
08878
08879 static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp *newvideortp, int *last_rtpmap_codec)
08880 {
08881 int found = FALSE;
08882 int codec;
08883 char mimeSubtype[128];
08884 unsigned int sample_rate;
08885 int debug = sip_debug_test_pvt(p);
08886
08887 if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
08888
08889 if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
08890
08891 if (!strncasecmp(mimeSubtype, "H26", 3) || !strncasecmp(mimeSubtype, "MP4", 3)) {
08892 if (ast_rtp_set_rtpmap_type_rate(newvideortp, codec, "video", mimeSubtype, 0, sample_rate) != -1) {
08893 if (debug)
08894 ast_verbose("Found video description format %s for ID %d\n", mimeSubtype, codec);
08895
08896 (*last_rtpmap_codec)++;
08897 found = TRUE;
08898 } else {
08899 ast_rtp_unset_m_type(newvideortp, codec);
08900 if (debug)
08901 ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
08902 }
08903 }
08904 } else {
08905 if (debug)
08906 ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
08907 }
08908 }
08909
08910 return found;
08911 }
08912
08913 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)
08914 {
08915 int found = FALSE;
08916 int codec;
08917 char mimeSubtype[128];
08918 unsigned int sample_rate;
08919 char *red_cp;
08920 int debug = sip_debug_test_pvt(p);
08921
08922 if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
08923
08924 if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
08925 if (!strncasecmp(mimeSubtype, "T140", 4)) {
08926 if (p->trtp) {
08927
08928 ast_rtp_set_rtpmap_type(newtextrtp, codec, "text", mimeSubtype, 0);
08929 found = TRUE;
08930 }
08931 } else if (!strncasecmp(mimeSubtype, "RED", 3)) {
08932 if (p->trtp) {
08933 ast_rtp_set_rtpmap_type(newtextrtp, codec, "text", mimeSubtype, 0);
08934 sprintf(red_fmtp, "fmtp:%d ", codec);
08935 if (debug)
08936 ast_verbose("RED submimetype has payload type: %d\n", codec);
08937 found = TRUE;
08938 }
08939 }
08940 } else {
08941 if (debug)
08942 ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
08943 }
08944 } else if (!strncmp(a, red_fmtp, strlen(red_fmtp))) {
08945
08946 red_cp = &red_fmtp[strlen(red_fmtp)];
08947 strncpy(red_fmtp, a, 100);
08948
08949 sscanf(red_cp, "%30u", &red_data_pt[*red_num_gen]);
08950 red_cp = strtok(red_cp, "/");
08951 while (red_cp && (*red_num_gen)++ < RED_MAX_GENERATION) {
08952 sscanf(red_cp, "%30u", &red_data_pt[*red_num_gen]);
08953 red_cp = strtok(NULL, "/");
08954 }
08955 red_cp = red_fmtp;
08956 found = TRUE;
08957 }
08958
08959 return found;
08960 }
08961
08962 static int process_sdp_a_image(const char *a, struct sip_pvt *p)
08963 {
08964 int found = FALSE;
08965 char s[256];
08966 unsigned int x;
08967
08968 if ((sscanf(a, "T38FaxMaxBuffer:%30u", &x) == 1)) {
08969 ast_debug(3, "MaxBufferSize:%d\n", x);
08970 found = TRUE;
08971 } else if ((sscanf(a, "T38MaxBitRate:%30u", &x) == 1) || (sscanf(a, "T38FaxMaxRate:%30u", &x) == 1)) {
08972 ast_debug(3, "T38MaxBitRate: %d\n", x);
08973 switch (x) {
08974 case 14400:
08975 p->t38.their_parms.rate = AST_T38_RATE_14400;
08976 break;
08977 case 12000:
08978 p->t38.their_parms.rate = AST_T38_RATE_12000;
08979 break;
08980 case 9600:
08981 p->t38.their_parms.rate = AST_T38_RATE_9600;
08982 break;
08983 case 7200:
08984 p->t38.their_parms.rate = AST_T38_RATE_7200;
08985 break;
08986 case 4800:
08987 p->t38.their_parms.rate = AST_T38_RATE_4800;
08988 break;
08989 case 2400:
08990 p->t38.their_parms.rate = AST_T38_RATE_2400;
08991 break;
08992 }
08993 found = TRUE;
08994 } else if ((sscanf(a, "T38FaxVersion:%30u", &x) == 1)) {
08995 ast_debug(3, "FaxVersion: %u\n", x);
08996 p->t38.their_parms.version = x;
08997 found = TRUE;
08998 } else if ((sscanf(a, "T38FaxMaxDatagram:%30u", &x) == 1) || (sscanf(a, "T38MaxDatagram:%30u", &x) == 1)) {
08999
09000 if (((signed int) p->t38_maxdatagram >= 0) && ((unsigned int) p->t38_maxdatagram > x)) {
09001 ast_debug(1, "Overriding T38FaxMaxDatagram '%d' with '%d'\n", x, p->t38_maxdatagram);
09002 x = p->t38_maxdatagram;
09003 }
09004 ast_debug(3, "FaxMaxDatagram: %u\n", x);
09005 ast_udptl_set_far_max_datagram(p->udptl, x);
09006 found = TRUE;
09007 } else if ((strncmp(a, "T38FaxFillBitRemoval", 20) == 0)) {
09008 if (sscanf(a, "T38FaxFillBitRemoval:%30u", &x) == 1) {
09009 ast_debug(3, "FillBitRemoval: %d\n", x);
09010 if (x == 1) {
09011 p->t38.their_parms.fill_bit_removal = TRUE;
09012 }
09013 } else {
09014 ast_debug(3, "FillBitRemoval\n");
09015 p->t38.their_parms.fill_bit_removal = TRUE;
09016 }
09017 found = TRUE;
09018 } else if ((strncmp(a, "T38FaxTranscodingMMR", 20) == 0)) {
09019 if (sscanf(a, "T38FaxTranscodingMMR:%30u", &x) == 1) {
09020 ast_debug(3, "Transcoding MMR: %d\n", x);
09021 if (x == 1) {
09022 p->t38.their_parms.transcoding_mmr = TRUE;
09023 }
09024 } else {
09025 ast_debug(3, "Transcoding MMR\n");
09026 p->t38.their_parms.transcoding_mmr = TRUE;
09027 }
09028 found = TRUE;
09029 } else if ((strncmp(a, "T38FaxTranscodingJBIG", 21) == 0)) {
09030 if (sscanf(a, "T38FaxTranscodingJBIG:%30u", &x) == 1) {
09031 ast_debug(3, "Transcoding JBIG: %d\n", x);
09032 if (x == 1) {
09033 p->t38.their_parms.transcoding_jbig = TRUE;
09034 }
09035 } else {
09036 ast_debug(3, "Transcoding JBIG\n");
09037 p->t38.their_parms.transcoding_jbig = TRUE;
09038 }
09039 found = TRUE;
09040 } else if ((sscanf(a, "T38FaxRateManagement:%255s", s) == 1)) {
09041 ast_debug(3, "RateManagement: %s\n", s);
09042 if (!strcasecmp(s, "localTCF"))
09043 p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_LOCAL_TCF;
09044 else if (!strcasecmp(s, "transferredTCF"))
09045 p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF;
09046 found = TRUE;
09047 } else if ((sscanf(a, "T38FaxUdpEC:%255s", s) == 1)) {
09048 ast_debug(3, "UDP EC: %s\n", s);
09049 if (!strcasecmp(s, "t38UDPRedundancy")) {
09050 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
09051 } else if (!strcasecmp(s, "t38UDPFEC")) {
09052 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
09053 } else {
09054 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
09055 }
09056 found = TRUE;
09057 }
09058
09059 return found;
09060 }
09061
09062
09063 #ifdef LOW_MEMORY
09064 static void ts_ast_rtp_destroy(void *data)
09065 {
09066 struct ast_rtp *tmp = data;
09067 ast_rtp_destroy(tmp);
09068 }
09069 #endif
09070
09071
09072 static int add_header(struct sip_request *req, const char *var, const char *value)
09073 {
09074 if (req->headers == SIP_MAX_HEADERS) {
09075 ast_log(LOG_WARNING, "Out of SIP header space\n");
09076 return -1;
09077 }
09078
09079 if (req->lines) {
09080 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
09081 return -1;
09082 }
09083
09084 if (sip_cfg.compactheaders) {
09085 var = find_alias(var, var);
09086 }
09087
09088 ast_str_append(&req->data, 0, "%s: %s\r\n", var, value);
09089 req->header[req->headers] = req->len;
09090
09091 req->len = ast_str_strlen(req->data);
09092 req->headers++;
09093
09094 return 0;
09095 }
09096
09097
09098 static int finalize_content(struct sip_request *req)
09099 {
09100 char clen[10];
09101
09102 if (req->lines) {
09103 ast_log(LOG_WARNING, "finalize_content() called on a message that has already been finalized\n");
09104 return -1;
09105 }
09106
09107 snprintf(clen, sizeof(clen), "%zd", ast_str_strlen(req->content));
09108 add_header(req, "Content-Length", clen);
09109
09110 if (ast_str_strlen(req->content)) {
09111 ast_str_append(&req->data, 0, "\r\n%s", ast_str_buffer(req->content));
09112 req->len = ast_str_strlen(req->data);
09113 }
09114 req->lines = ast_str_strlen(req->content) ? 1 : 0;
09115 return 0;
09116 }
09117
09118
09119 static int add_content(struct sip_request *req, const char *line)
09120 {
09121 if (req->lines) {
09122 ast_log(LOG_WARNING, "Can't add more content when the content has been finalized\n");
09123 return -1;
09124 }
09125
09126 ast_str_append(&req->content, 0, "%s", line);
09127 return 0;
09128 }
09129
09130
09131 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field)
09132 {
09133 const char *tmp = get_header(orig, field);
09134
09135 if (!ast_strlen_zero(tmp))
09136 return add_header(req, field, tmp);
09137 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
09138 return -1;
09139 }
09140
09141
09142 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field)
09143 {
09144 int start = 0;
09145 int copied = 0;
09146 for (;;) {
09147 const char *tmp = __get_header(orig, field, &start);
09148
09149 if (ast_strlen_zero(tmp))
09150 break;
09151
09152 add_header(req, field, tmp);
09153 copied++;
09154 }
09155 return copied ? 0 : -1;
09156 }
09157
09158
09159
09160
09161
09162
09163
09164
09165
09166 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field)
09167 {
09168 int copied = 0;
09169 int start = 0;
09170
09171 for (;;) {
09172 char new[512];
09173 const char *oh = __get_header(orig, field, &start);
09174
09175 if (ast_strlen_zero(oh))
09176 break;
09177
09178 if (!copied) {
09179 char leftmost[512], *others, *rport;
09180
09181
09182 ast_copy_string(leftmost, oh, sizeof(leftmost));
09183 others = strchr(leftmost, ',');
09184 if (others)
09185 *others++ = '\0';
09186
09187
09188 rport = strstr(leftmost, ";rport");
09189 if (rport && *(rport+6) == '=')
09190 rport = NULL;
09191
09192
09193 if (rport && ((ast_test_flag(&p->flags[0], SIP_NAT) == SIP_NAT_ALWAYS) || (ast_test_flag(&p->flags[0], SIP_NAT) == SIP_NAT_RFC3581))) {
09194
09195 char *end;
09196
09197 rport = strstr(leftmost, ";rport");
09198
09199 if (rport) {
09200 end = strchr(rport + 1, ';');
09201 if (end)
09202 memmove(rport, end, strlen(end) + 1);
09203 else
09204 *rport = '\0';
09205 }
09206
09207
09208 snprintf(new, sizeof(new), "%s;received=%s;rport=%d%s%s",
09209 leftmost, ast_inet_ntoa(p->recv.sin_addr),
09210 ntohs(p->recv.sin_port),
09211 others ? "," : "", others ? others : "");
09212 } else {
09213
09214 snprintf(new, sizeof(new), "%s;received=%s%s%s",
09215 leftmost, ast_inet_ntoa(p->recv.sin_addr),
09216 others ? "," : "", others ? others : "");
09217 }
09218 oh = new;
09219 }
09220 add_header(req, field, oh);
09221 copied++;
09222 }
09223 if (!copied) {
09224 ast_log(LOG_NOTICE, "No header field '%s' present to copy\n", field);
09225 return -1;
09226 }
09227 return 0;
09228 }
09229
09230
09231 static void add_route(struct sip_request *req, struct sip_route *route)
09232 {
09233 char r[SIPBUFSIZE*2], *p;
09234 int n, rem = sizeof(r);
09235
09236 if (!route)
09237 return;
09238
09239 p = r;
09240 for (;route ; route = route->next) {
09241 n = strlen(route->hop);
09242 if (rem < n+3)
09243 break;
09244 if (p != r) {
09245 *p++ = ',';
09246 --rem;
09247 }
09248 *p++ = '<';
09249 ast_copy_string(p, route->hop, rem);
09250 p += n;
09251 *p++ = '>';
09252 rem -= (n+2);
09253 }
09254 *p = '\0';
09255 add_header(req, "Route", r);
09256 }
09257
09258
09259
09260
09261
09262
09263
09264
09265
09266
09267 static void set_destination(struct sip_pvt *p, char *uri)
09268 {
09269 char *h, *maddr, hostname[256];
09270 int port, hn;
09271 struct hostent *hp;
09272 struct ast_hostent ahp;
09273 int debug=sip_debug_test_pvt(p);
09274 int tls_on = FALSE;
09275 int use_dns = sip_cfg.srvlookup;
09276
09277 if (debug)
09278 ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
09279
09280
09281 h = strchr(uri, '@');
09282 if (h)
09283 ++h;
09284 else {
09285 h = uri;
09286 if (!strncasecmp(h, "sip:", 4)) {
09287 h += 4;
09288 } else if (!strncasecmp(h, "sips:", 5)) {
09289 h += 5;
09290 tls_on = TRUE;
09291 }
09292 }
09293 hn = strcspn(h, ":;>") + 1;
09294 if (hn > sizeof(hostname))
09295 hn = sizeof(hostname);
09296 ast_copy_string(hostname, h, hn);
09297
09298 h += hn - 1;
09299
09300
09301 if (*h == ':') {
09302
09303 ++h;
09304 port = strtol(h, &h, 10);
09305 use_dns = FALSE;
09306 } else
09307 port = tls_on ? STANDARD_TLS_PORT : STANDARD_SIP_PORT;
09308
09309
09310 maddr = strstr(h, "maddr=");
09311 if (maddr) {
09312 maddr += 6;
09313 hn = strspn(maddr, "0123456789.") + 1;
09314 if (hn > sizeof(hostname))
09315 hn = sizeof(hostname);
09316 ast_copy_string(hostname, maddr, hn);
09317 }
09318
09319
09320
09321 hp = ast_gethostbyname(hostname, &ahp);
09322 if (hp == NULL) {
09323 ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
09324 return;
09325 }
09326 p->sa.sin_family = AF_INET;
09327 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
09328 p->sa.sin_port = htons(port);
09329 if (debug)
09330 ast_verbose("set_destination: set destination to %s, port %d\n", ast_inet_ntoa(p->sa.sin_addr), port);
09331 }
09332
09333
09334 static int init_resp(struct sip_request *resp, const char *msg)
09335 {
09336
09337 memset(resp, 0, sizeof(*resp));
09338 resp->method = SIP_RESPONSE;
09339 if (!(resp->data = ast_str_create(SIP_MIN_PACKET)))
09340 goto e_return;
09341 if (!(resp->content = ast_str_create(SIP_MIN_PACKET)))
09342 goto e_free_data;
09343 resp->header[0] = 0;
09344 ast_str_set(&resp->data, 0, "SIP/2.0 %s\r\n", msg);
09345 resp->len = resp->data->used;
09346 resp->headers++;
09347 return 0;
09348
09349 e_free_data:
09350 ast_free(resp->data);
09351 resp->data = NULL;
09352 e_return:
09353 return -1;
09354 }
09355
09356
09357 static int init_req(struct sip_request *req, int sipmethod, const char *recip)
09358 {
09359
09360 memset(req, 0, sizeof(*req));
09361 if (!(req->data = ast_str_create(SIP_MIN_PACKET)))
09362 goto e_return;
09363 if (!(req->content = ast_str_create(SIP_MIN_PACKET)))
09364 goto e_free_data;
09365 req->method = sipmethod;
09366 req->header[0] = 0;
09367 ast_str_set(&req->data, 0, "%s %s SIP/2.0\r\n", sip_methods[sipmethod].text, recip);
09368 req->len = ast_str_strlen(req->data);
09369 req->headers++;
09370 return 0;
09371
09372 e_free_data:
09373 ast_free(req->data);
09374 req->data = NULL;
09375 e_return:
09376 return -1;
09377 }
09378
09379
09380 static void deinit_req(struct sip_request *req)
09381 {
09382 if (req->data) {
09383 ast_free(req->data);
09384 req->data = NULL;
09385 }
09386 if (req->content) {
09387 ast_free(req->content);
09388 req->content = NULL;
09389 }
09390 }
09391
09392
09393
09394 static inline int resp_needs_contact(const char *msg, enum sipmethod method) {
09395
09396
09397
09398
09399
09400
09401
09402
09403
09404
09405
09406
09407
09408
09409
09410 switch (method) {
09411
09412 case SIP_INVITE:
09413 case SIP_UPDATE:
09414 case SIP_SUBSCRIBE:
09415 case SIP_NOTIFY:
09416 if ((msg[0] >= '1' && msg[0] <= '3') || !strncmp(msg, "485", 3))
09417 return 1;
09418 break;
09419
09420
09421 case SIP_REGISTER:
09422 case SIP_OPTIONS:
09423 if (msg[0] == '2' || msg[0] == '3' || !strncmp(msg, "485", 3))
09424 return 1;
09425 break;
09426
09427
09428 case SIP_BYE:
09429 case SIP_PRACK:
09430 case SIP_MESSAGE:
09431 case SIP_PUBLISH:
09432 if (msg[0] == '3' || !strncmp(msg, "485", 3))
09433 return 1;
09434 break;
09435
09436
09437 case SIP_REFER:
09438 if (msg[0] >= '2' && msg[0] <= '6')
09439 return 1;
09440 break;
09441
09442
09443 case SIP_ACK:
09444 case SIP_CANCEL:
09445 case SIP_INFO:
09446 case SIP_PING:
09447 default:
09448 return 0;
09449 }
09450 return 0;
09451 }
09452
09453
09454 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req)
09455 {
09456 char newto[256];
09457 const char *ot;
09458
09459 init_resp(resp, msg);
09460 copy_via_headers(p, resp, req, "Via");
09461 if (msg[0] == '1' || msg[0] == '2')
09462 copy_all_header(resp, req, "Record-Route");
09463 copy_header(resp, req, "From");
09464 ot = get_header(req, "To");
09465 if (!strcasestr(ot, "tag=") && strncmp(msg, "100", 3)) {
09466
09467
09468 if (!ast_strlen_zero(p->theirtag) && ast_test_flag(&p->flags[0], SIP_OUTGOING))
09469 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
09470 else if (p->tag && !ast_test_flag(&p->flags[0], SIP_OUTGOING))
09471 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
09472 else
09473 ast_copy_string(newto, ot, sizeof(newto));
09474 ot = newto;
09475 }
09476 add_header(resp, "To", ot);
09477 copy_header(resp, req, "Call-ID");
09478 copy_header(resp, req, "CSeq");
09479 if (!ast_strlen_zero(global_useragent))
09480 add_header(resp, "Server", global_useragent);
09481 add_header(resp, "Allow", ALLOWED_METHODS);
09482 add_header(resp, "Supported", SUPPORTED_EXTENSIONS);
09483
09484
09485 if (p->method == SIP_INVITE && p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE) {
09486 char se_hdr[256];
09487 snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval,
09488 strefresher2str(p->stimer->st_ref));
09489 add_header(resp, "Require", "timer");
09490 add_header(resp, "Session-Expires", se_hdr);
09491 }
09492
09493 if (msg[0] == '2' && (p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER)) {
09494
09495
09496 char tmp[256];
09497
09498 snprintf(tmp, sizeof(tmp), "%d", p->expiry);
09499 add_header(resp, "Expires", tmp);
09500 if (p->expiry) {
09501 char contact[SIPBUFSIZE];
09502 const char *contact_uri = p->method == SIP_SUBSCRIBE ? p->our_contact : p->fullcontact;
09503 char *brackets = strchr(contact_uri, '<');
09504 snprintf(contact, sizeof(contact), "%s%s%s;expires=%d", brackets ? "" : "<", contact_uri, brackets ? "" : ">", p->expiry);
09505 add_header(resp, "Contact", contact);
09506 }
09507 } else if (!ast_strlen_zero(p->our_contact) && resp_needs_contact(msg, p->method)) {
09508 add_header(resp, "Contact", p->our_contact);
09509 }
09510
09511 if (!ast_strlen_zero(p->url)) {
09512 add_header(resp, "Access-URL", p->url);
09513 ast_string_field_set(p, url, NULL);
09514 }
09515
09516 return 0;
09517 }
09518
09519
09520 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch)
09521 {
09522 struct sip_request *orig = &p->initreq;
09523 char stripped[80];
09524 char tmp[80];
09525 char newto[256];
09526 const char *c;
09527 const char *ot, *of;
09528 int is_strict = FALSE;
09529 int is_outbound = ast_test_flag(&p->flags[0], SIP_OUTGOING);
09530
09531 memset(req, 0, sizeof(struct sip_request));
09532
09533 snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", sip_methods[sipmethod].text);
09534
09535 if (!seqno) {
09536 p->ocseq++;
09537 seqno = p->ocseq;
09538 }
09539
09540
09541 if (sipmethod == SIP_CANCEL) {
09542 p->branch = p->invite_branch;
09543 build_via(p);
09544 } else if (newbranch && (sipmethod == SIP_INVITE)) {
09545 p->branch ^= ast_random();
09546 p->invite_branch = p->branch;
09547 build_via(p);
09548 } else if (newbranch) {
09549 p->branch ^= ast_random();
09550 build_via(p);
09551 }
09552
09553
09554 if (p->route && !ast_strlen_zero(p->route->hop) && strstr(p->route->hop, ";lr") == NULL) {
09555 is_strict = TRUE;
09556 if (sipdebug)
09557 ast_debug(1, "Strict routing enforced for session %s\n", p->callid);
09558 }
09559
09560 if (sipmethod == SIP_CANCEL)
09561 c = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
09562 else if (sipmethod == SIP_ACK) {
09563
09564
09565 if (!ast_strlen_zero(p->okcontacturi))
09566 c = is_strict ? p->route->hop : p->okcontacturi;
09567 else
09568 c = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
09569 } else if (!ast_strlen_zero(p->okcontacturi))
09570 c = is_strict ? p->route->hop : p->okcontacturi;
09571 else if (!ast_strlen_zero(p->uri))
09572 c = p->uri;
09573 else {
09574 char *n;
09575
09576 ast_copy_string(stripped, get_header(orig, is_outbound ? "To" : "From"),
09577 sizeof(stripped));
09578 n = get_in_brackets(stripped);
09579 c = remove_uri_parameters(n);
09580 }
09581 init_req(req, sipmethod, c);
09582
09583 snprintf(tmp, sizeof(tmp), "%d %s", seqno, sip_methods[sipmethod].text);
09584
09585 add_header(req, "Via", p->via);
09586 if (p->route) {
09587 set_destination(p, p->route->hop);
09588 add_route(req, is_strict ? p->route->next : p->route);
09589 }
09590 add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
09591
09592 ot = get_header(orig, "To");
09593 of = get_header(orig, "From");
09594
09595
09596
09597 if (!strcasestr(ot, "tag=") && sipmethod != SIP_CANCEL) {
09598
09599
09600 if (is_outbound && !ast_strlen_zero(p->theirtag))
09601 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
09602 else if (!is_outbound)
09603 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
09604 else
09605 snprintf(newto, sizeof(newto), "%s", ot);
09606 ot = newto;
09607 }
09608
09609 if (is_outbound) {
09610 add_header(req, "From", of);
09611 add_header(req, "To", ot);
09612 } else {
09613 add_header(req, "From", ot);
09614 add_header(req, "To", of);
09615 }
09616
09617 if (sipmethod != SIP_BYE && sipmethod != SIP_CANCEL && sipmethod != SIP_MESSAGE)
09618 add_header(req, "Contact", p->our_contact);
09619
09620 copy_header(req, orig, "Call-ID");
09621 add_header(req, "CSeq", tmp);
09622
09623 if (!ast_strlen_zero(global_useragent))
09624 add_header(req, "User-Agent", global_useragent);
09625
09626 if (!ast_strlen_zero(p->rpid))
09627 add_header(req, "Remote-Party-ID", p->rpid);
09628
09629 if (!ast_strlen_zero(p->url)) {
09630 add_header(req, "Access-URL", p->url);
09631 ast_string_field_set(p, url, NULL);
09632 }
09633
09634
09635
09636
09637
09638
09639
09640
09641 if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE
09642 && sipmethod == SIP_INVITE) {
09643 char se_hdr[256];
09644 snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval,
09645 strefresher2str(p->stimer->st_ref));
09646 add_header(req, "Require", "timer");
09647 add_header(req, "Session-Expires", se_hdr);
09648 snprintf(se_hdr, sizeof(se_hdr), "%d", st_get_se(p, FALSE));
09649 add_header(req, "Min-SE", se_hdr);
09650 }
09651
09652 return 0;
09653 }
09654
09655
09656 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
09657 {
09658 struct sip_request resp;
09659 int seqno = 0;
09660
09661 if (reliable && (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1)) {
09662 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
09663 return -1;
09664 }
09665 respprep(&resp, p, msg, req);
09666
09667
09668 if (p->method == SIP_INVITE && msg[0] != '1' && p->owner && p->owner->hangupcause) {
09669 char buf[10];
09670
09671 add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->owner->hangupcause));
09672 snprintf(buf, sizeof(buf), "%d", p->owner->hangupcause);
09673 add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
09674 }
09675 return send_response(p, &resp, reliable, seqno);
09676 }
09677
09678 static int temp_pvt_init(void *data)
09679 {
09680 struct sip_pvt *p = data;
09681
09682 p->do_history = 0;
09683 return ast_string_field_init(p, 512);
09684 }
09685
09686 static void temp_pvt_cleanup(void *data)
09687 {
09688 struct sip_pvt *p = data;
09689
09690 ast_string_field_free_memory(p);
09691
09692 ast_free(data);
09693 }
09694
09695
09696 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)
09697 {
09698 struct sip_pvt *p = NULL;
09699
09700 if (!(p = ast_threadstorage_get(&ts_temp_pvt, sizeof(*p)))) {
09701 ast_log(LOG_ERROR, "Failed to get temporary pvt\n");
09702 return -1;
09703 }
09704
09705
09706
09707
09708
09709
09710
09711
09712
09713 p->method = intended_method;
09714
09715 if (!sin)
09716 p->ourip = internip;
09717 else {
09718 p->sa = *sin;
09719 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
09720 }
09721
09722 p->branch = ast_random();
09723 make_our_tag(p->tag, sizeof(p->tag));
09724 p->ocseq = INITIAL_CSEQ;
09725
09726 if (useglobal_nat && sin) {
09727 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT);
09728 p->recv = *sin;
09729 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
09730 }
09731
09732 ast_string_field_set(p, fromdomain, default_fromdomain);
09733 build_via(p);
09734 ast_string_field_set(p, callid, callid);
09735
09736 copy_socket_data(&p->socket, &req->socket);
09737
09738
09739 __transmit_response(p, msg, req, XMIT_UNRELIABLE);
09740
09741
09742 ast_string_field_init(p, 0);
09743
09744 return 0;
09745 }
09746
09747
09748 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req)
09749 {
09750 return __transmit_response(p, msg, req, XMIT_UNRELIABLE);
09751 }
09752
09753
09754 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported)
09755 {
09756 struct sip_request resp;
09757 respprep(&resp, p, msg, req);
09758 append_date(&resp);
09759 add_header(&resp, "Unsupported", unsupported);
09760 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
09761 }
09762
09763
09764 static int transmit_response_with_minse(struct sip_pvt *p, const char *msg, const struct sip_request *req, int minse_int)
09765 {
09766 struct sip_request resp;
09767 char minse_str[20];
09768
09769 respprep(&resp, p, msg, req);
09770 append_date(&resp);
09771
09772 snprintf(minse_str, sizeof(minse_str), "%d", minse_int);
09773 add_header(&resp, "Min-SE", minse_str);
09774 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
09775 }
09776
09777
09778
09779
09780
09781 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req)
09782 {
09783 return __transmit_response(p, msg, req, req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL);
09784 }
09785
09786
09787 static void append_date(struct sip_request *req)
09788 {
09789 char tmpdat[256];
09790 struct tm tm;
09791 time_t t = time(NULL);
09792
09793 gmtime_r(&t, &tm);
09794 strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
09795 add_header(req, "Date", tmpdat);
09796 }
09797
09798
09799 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req)
09800 {
09801 struct sip_request resp;
09802 respprep(&resp, p, msg, req);
09803 append_date(&resp);
09804 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
09805 }
09806
09807
09808 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
09809 {
09810 struct sip_request resp;
09811 respprep(&resp, p, msg, req);
09812 add_header(&resp, "Accept", "application/sdp");
09813 return send_response(p, &resp, reliable, 0);
09814 }
09815
09816
09817 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)
09818 {
09819 struct sip_request resp;
09820 char tmp[512];
09821 int seqno = 0;
09822
09823 if (reliable && (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1)) {
09824 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
09825 return -1;
09826 }
09827
09828
09829 snprintf(tmp, sizeof(tmp), "Digest algorithm=MD5, realm=\"%s\", nonce=\"%s\"%s", sip_cfg.realm, randdata, stale ? ", stale=true" : "");
09830 respprep(&resp, p, msg, req);
09831 add_header(&resp, header, tmp);
09832 append_history(p, "AuthChal", "Auth challenge sent for %s - nc %d", p->username, p->noncecount);
09833 return send_response(p, &resp, reliable, seqno);
09834 }
09835
09836
09837 static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp)
09838 {
09839 int res;
09840
09841 if (!(res = with_sdp ? transmit_response_with_sdp(p, msg, req, XMIT_UNRELIABLE, FALSE) : transmit_response(p, msg, req))) {
09842 p->last_provisional = msg;
09843 update_provisional_keepalive(p, with_sdp);
09844 }
09845
09846 return res;
09847 }
09848
09849
09850 static int add_text(struct sip_request *req, const char *text)
09851 {
09852
09853 add_header(req, "Content-Type", "text/plain;charset=UTF-8");
09854 add_content(req, text);
09855 return 0;
09856 }
09857
09858
09859
09860
09861
09862 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode)
09863 {
09864 char tmp[256];
09865 int event;
09866 if (mode) {
09867
09868 if (digit == '*')
09869 event = 10;
09870 else if (digit == '#')
09871 event = 11;
09872 else if ((digit >= 'A') && (digit <= 'D'))
09873 event = 12 + digit - 'A';
09874 else
09875 event = atoi(&digit);
09876 snprintf(tmp, sizeof(tmp), "%d\r\n", event);
09877 add_header(req, "Content-Type", "application/dtmf");
09878 add_content(req, tmp);
09879 } else {
09880
09881 snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=%u\r\n", digit, duration);
09882 add_header(req, "Content-Type", "application/dtmf-relay");
09883 add_content(req, tmp);
09884 }
09885 return 0;
09886 }
09887
09888
09889
09890 static int add_vidupdate(struct sip_request *req)
09891 {
09892 const char *xml_is_a_huge_waste_of_space =
09893 "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
09894 " <media_control>\r\n"
09895 " <vc_primitive>\r\n"
09896 " <to_encoder>\r\n"
09897 " <picture_fast_update>\r\n"
09898 " </picture_fast_update>\r\n"
09899 " </to_encoder>\r\n"
09900 " </vc_primitive>\r\n"
09901 " </media_control>\r\n";
09902 add_header(req, "Content-Type", "application/media_control+xml");
09903 add_content(req, xml_is_a_huge_waste_of_space);
09904 return 0;
09905 }
09906
09907
09908 static void add_codec_to_sdp(const struct sip_pvt *p, int codec,
09909 struct ast_str **m_buf, struct ast_str **a_buf,
09910 int debug, int *min_packet_size)
09911 {
09912 int rtp_code;
09913 struct ast_format_list fmt;
09914
09915
09916 if (debug)
09917 ast_verbose("Adding codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
09918 if ((rtp_code = ast_rtp_lookup_code(p->rtp, 1, codec)) == -1)
09919 return;
09920
09921 if (p->rtp) {
09922 struct ast_codec_pref *pref = ast_rtp_codec_getpref(p->rtp);
09923 fmt = ast_codec_pref_getsize(pref, codec);
09924 } else
09925 return;
09926 ast_str_append(m_buf, 0, " %d", rtp_code);
09927 ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
09928 ast_rtp_lookup_mime_subtype(1, codec,
09929 ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0),
09930 ast_rtp_lookup_sample_rate(1, codec));
09931
09932 switch (codec) {
09933 case AST_FORMAT_G729A:
09934
09935 ast_str_append(a_buf, 0, "a=fmtp:%d annexb=no\r\n", rtp_code);
09936 break;
09937 case AST_FORMAT_G723_1:
09938
09939 ast_str_append(a_buf, 0, "a=fmtp:%d annexa=no\r\n", rtp_code);
09940 break;
09941 case AST_FORMAT_ILBC:
09942
09943 ast_str_append(a_buf, 0, "a=fmtp:%d mode=%d\r\n", rtp_code, fmt.cur_ms);
09944 break;
09945 case AST_FORMAT_SIREN7:
09946
09947 ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=32000\r\n", rtp_code);
09948 break;
09949 case AST_FORMAT_SIREN14:
09950
09951 ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=48000\r\n", rtp_code);
09952 break;
09953 }
09954
09955 if (fmt.cur_ms && (fmt.cur_ms < *min_packet_size))
09956 *min_packet_size = fmt.cur_ms;
09957
09958
09959 if ((*min_packet_size)==0 && fmt.cur_ms)
09960 *min_packet_size = fmt.cur_ms;
09961 }
09962
09963
09964
09965 static void add_vcodec_to_sdp(const struct sip_pvt *p, int codec,
09966 struct ast_str **m_buf, struct ast_str **a_buf,
09967 int debug, int *min_packet_size)
09968 {
09969 int rtp_code;
09970
09971 if (!p->vrtp)
09972 return;
09973
09974 if (debug)
09975 ast_verbose("Adding video codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
09976
09977 if ((rtp_code = ast_rtp_lookup_code(p->vrtp, 1, codec)) == -1)
09978 return;
09979
09980 ast_str_append(m_buf, 0, " %d", rtp_code);
09981 ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
09982 ast_rtp_lookup_mime_subtype(1, codec, 0),
09983 ast_rtp_lookup_sample_rate(1, codec));
09984
09985 }
09986
09987
09988 static void add_tcodec_to_sdp(const struct sip_pvt *p, int codec,
09989 struct ast_str **m_buf, struct ast_str **a_buf,
09990 int debug, int *min_packet_size)
09991 {
09992 int rtp_code;
09993
09994 if (!p->trtp)
09995 return;
09996
09997 if (debug)
09998 ast_verbose("Adding text codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
09999
10000 if ((rtp_code = ast_rtp_lookup_code(p->trtp, 1, codec)) == -1)
10001 return;
10002
10003 ast_str_append(m_buf, 0, " %d", rtp_code);
10004 ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
10005 ast_rtp_lookup_mime_subtype(1, codec, 0),
10006 ast_rtp_lookup_sample_rate(1, codec));
10007
10008
10009 if (codec == AST_FORMAT_T140RED) {
10010 ast_str_append(a_buf, 0, "a=fmtp:%d %d/%d/%d\r\n", rtp_code,
10011 ast_rtp_lookup_code(p->trtp, 1, AST_FORMAT_T140),
10012 ast_rtp_lookup_code(p->trtp, 1, AST_FORMAT_T140),
10013 ast_rtp_lookup_code(p->trtp, 1, AST_FORMAT_T140));
10014
10015 }
10016 }
10017
10018
10019
10020 static unsigned int t38_get_rate(enum ast_control_t38_rate rate)
10021 {
10022 switch (rate) {
10023 case AST_T38_RATE_2400:
10024 return 2400;
10025 case AST_T38_RATE_4800:
10026 return 4800;
10027 case AST_T38_RATE_7200:
10028 return 7200;
10029 case AST_T38_RATE_9600:
10030 return 9600;
10031 case AST_T38_RATE_12000:
10032 return 12000;
10033 case AST_T38_RATE_14400:
10034 return 14400;
10035 default:
10036 return 0;
10037 }
10038 }
10039
10040
10041 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
10042 struct ast_str **m_buf, struct ast_str **a_buf,
10043 int debug)
10044 {
10045 int rtp_code;
10046
10047 if (debug)
10048 ast_verbose("Adding non-codec 0x%x (%s) to SDP\n", format, ast_rtp_lookup_mime_subtype(0, format, 0));
10049 if ((rtp_code = ast_rtp_lookup_code(p->rtp, 0, format)) == -1)
10050 return;
10051
10052 ast_str_append(m_buf, 0, " %d", rtp_code);
10053 ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
10054 ast_rtp_lookup_mime_subtype(0, format, 0),
10055 ast_rtp_lookup_sample_rate(0, format));
10056 if (format == AST_RTP_DTMF)
10057 ast_str_append(a_buf, 0, "a=fmtp:%d 0-16\r\n", rtp_code);
10058 }
10059
10060
10061
10062
10063 static void get_our_media_address(struct sip_pvt *p, int needvideo,
10064 struct sockaddr_in *sin, struct sockaddr_in *vsin, struct sockaddr_in *tsin,
10065 struct sockaddr_in *dest, struct sockaddr_in *vdest)
10066 {
10067
10068 ast_rtp_get_us(p->rtp, sin);
10069 if (p->vrtp)
10070 ast_rtp_get_us(p->vrtp, vsin);
10071 if (p->trtp)
10072 ast_rtp_get_us(p->trtp, tsin);
10073
10074
10075
10076 if (p->redirip.sin_addr.s_addr) {
10077 dest->sin_port = p->redirip.sin_port;
10078 dest->sin_addr = p->redirip.sin_addr;
10079 } else {
10080 dest->sin_addr = p->ourip.sin_addr;
10081 dest->sin_port = sin->sin_port;
10082 }
10083 if (needvideo) {
10084
10085 if (p->vredirip.sin_addr.s_addr) {
10086 vdest->sin_addr = p->vredirip.sin_addr;
10087 vdest->sin_port = p->vredirip.sin_port;
10088 } else {
10089 vdest->sin_addr = p->ourip.sin_addr;
10090 vdest->sin_port = vsin->sin_port;
10091 }
10092 }
10093
10094 }
10095
10096
10097
10098
10099
10100
10101
10102 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38)
10103 {
10104 int alreadysent = 0;
10105
10106 struct sockaddr_in sin;
10107 struct sockaddr_in vsin;
10108 struct sockaddr_in tsin;
10109 struct sockaddr_in dest;
10110 struct sockaddr_in udptlsin;
10111 struct sockaddr_in vdest = { 0, };
10112 struct sockaddr_in tdest = { 0, };
10113 struct sockaddr_in udptldest = { 0, };
10114
10115
10116 char *version = "v=0\r\n";
10117 char subject[256];
10118 char owner[256];
10119 char connection[256];
10120 char *session_time = "t=0 0\r\n";
10121 char bandwidth[256] = "";
10122 char *hold = "";
10123 struct ast_str *m_audio = ast_str_alloca(256);
10124 struct ast_str *m_video = ast_str_alloca(256);
10125 struct ast_str *m_text = ast_str_alloca(256);
10126 struct ast_str *m_modem = ast_str_alloca(256);
10127 struct ast_str *a_audio = ast_str_alloca(1024);
10128 struct ast_str *a_video = ast_str_alloca(1024);
10129 struct ast_str *a_text = ast_str_alloca(1024);
10130 struct ast_str *a_modem = ast_str_alloca(1024);
10131
10132 int x;
10133 int capability = 0;
10134 int needaudio = FALSE;
10135 int needvideo = FALSE;
10136 int needtext = FALSE;
10137 int debug = sip_debug_test_pvt(p);
10138 int min_audio_packet_size = 0;
10139 int min_video_packet_size = 0;
10140 int min_text_packet_size = 0;
10141
10142 char codecbuf[SIPBUFSIZE];
10143 char buf[SIPBUFSIZE];
10144 char dummy_answer[256];
10145
10146
10147 snprintf(subject, sizeof(subject), "s=%s\r\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
10148
10149 if (!p->rtp) {
10150 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
10151 return AST_FAILURE;
10152 }
10153
10154
10155
10156
10157 if (!p->sessionid) {
10158 p->sessionid = (int)ast_random();
10159 p->sessionversion = p->sessionid;
10160 } else {
10161 if (oldsdp == FALSE)
10162 p->sessionversion++;
10163 }
10164
10165 if (add_audio) {
10166
10167 if ((p->jointcapability & AST_FORMAT_VIDEO_MASK) && !p->novideo) {
10168 if (p->vrtp) {
10169 needvideo = TRUE;
10170 ast_debug(2, "This call needs video offers!\n");
10171 } else
10172 ast_debug(2, "This call needs video offers, but there's no video support enabled!\n");
10173 }
10174
10175 if ((p->jointcapability & AST_FORMAT_TEXT_MASK) && !p->notext) {
10176 if (sipdebug_text)
10177 ast_verbose("We think we can do text\n");
10178 if (p->trtp) {
10179 if (sipdebug_text) {
10180 ast_verbose("And we have a text rtp object\n");
10181 }
10182 needtext = TRUE;
10183 ast_debug(2, "This call needs text offers! \n");
10184 } else {
10185 ast_debug(2, "This call needs text offers, but there's no text support enabled ! \n");
10186 }
10187 }
10188 }
10189
10190 get_our_media_address(p, needvideo, &sin, &vsin, &tsin, &dest, &vdest);
10191
10192 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));
10193 snprintf(connection, sizeof(connection), "c=IN IP4 %s\r\n", ast_inet_ntoa(dest.sin_addr));
10194
10195 if (add_audio) {
10196 capability = p->jointcapability;
10197
10198
10199 ast_debug(1, "** Our capability: %s Video flag: %s Text flag: %s\n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), capability),
10200 p->novideo ? "True" : "False", p->notext ? "True" : "False");
10201 ast_debug(1, "** Our prefcodec: %s \n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), p->prefcodec));
10202
10203
10204 if (capability & AST_FORMAT_AUDIO_MASK)
10205 needaudio = TRUE;
10206
10207 if (debug)
10208 ast_verbose("Audio is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(sin.sin_port));
10209
10210
10211
10212 if (needvideo) {
10213 ast_str_append(&m_video, 0, "m=video %d RTP/AVP", ntohs(vdest.sin_port));
10214
10215
10216 if (p->maxcallbitrate)
10217 snprintf(bandwidth, sizeof(bandwidth), "b=CT:%d\r\n", p->maxcallbitrate);
10218 if (debug)
10219 ast_verbose("Video is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(vdest.sin_port));
10220 }
10221
10222
10223
10224 if (needtext) {
10225 if (sipdebug_text)
10226 ast_verbose("Lets set up the text sdp\n");
10227
10228 if (p->tredirip.sin_addr.s_addr) {
10229 tdest.sin_addr = p->tredirip.sin_addr;
10230 tdest.sin_port = p->tredirip.sin_port;
10231 } else {
10232 tdest.sin_addr = p->ourip.sin_addr;
10233 tdest.sin_port = tsin.sin_port;
10234 }
10235 ast_str_append(&m_text, 0, "m=text %d RTP/AVP", ntohs(tdest.sin_port));
10236 if (debug)
10237 ast_verbose("Text is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(tsin.sin_port));
10238
10239 }
10240
10241
10242
10243
10244
10245
10246 ast_str_append(&m_audio, 0, "m=audio %d RTP/AVP", ntohs(dest.sin_port));
10247
10248 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_ONEDIR)
10249 hold = "a=recvonly\r\n";
10250 else if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_INACTIVE)
10251 hold = "a=inactive\r\n";
10252 else
10253 hold = "a=sendrecv\r\n";
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264 if (capability & p->prefcodec) {
10265 int codec = p->prefcodec & AST_FORMAT_AUDIO_MASK;
10266
10267 add_codec_to_sdp(p, codec, &m_audio, &a_audio, debug, &min_audio_packet_size);
10268 alreadysent |= codec;
10269 }
10270
10271
10272 for (x = 0; x < 32; x++) {
10273 int codec;
10274
10275 if (!(codec = ast_codec_pref_index(&p->prefs, x)))
10276 break;
10277
10278 if (!(capability & codec))
10279 continue;
10280
10281 if (alreadysent & codec)
10282 continue;
10283
10284 add_codec_to_sdp(p, codec, &m_audio, &a_audio, debug, &min_audio_packet_size);
10285 alreadysent |= codec;
10286 }
10287
10288
10289 for (x = 1; x <= (needtext ? AST_FORMAT_TEXT_MASK : (needvideo ? AST_FORMAT_VIDEO_MASK : AST_FORMAT_AUDIO_MASK)); x <<= 1) {
10290 if (!(capability & x))
10291 continue;
10292
10293 if (alreadysent & x)
10294 continue;
10295
10296 if (x & AST_FORMAT_AUDIO_MASK)
10297 add_codec_to_sdp(p, x, &m_audio, &a_audio, debug, &min_audio_packet_size);
10298 else if (x & AST_FORMAT_VIDEO_MASK)
10299 add_vcodec_to_sdp(p, x, &m_video, &a_video, debug, &min_video_packet_size);
10300 else if (x & AST_FORMAT_TEXT_MASK)
10301 add_tcodec_to_sdp(p, x, &m_text, &a_text, debug, &min_text_packet_size);
10302 }
10303
10304
10305 for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
10306 if (!(p->jointnoncodeccapability & x))
10307 continue;
10308
10309 add_noncodec_to_sdp(p, x, &m_audio, &a_audio, debug);
10310 }
10311
10312 ast_debug(3, "-- Done with adding codecs to SDP\n");
10313
10314 if (!p->owner || !ast_internal_timing_enabled(p->owner))
10315 ast_str_append(&a_audio, 0, "a=silenceSupp:off - - - -\r\n");
10316
10317 if (min_audio_packet_size)
10318 ast_str_append(&a_audio, 0, "a=ptime:%d\r\n", min_audio_packet_size);
10319
10320
10321 if (min_video_packet_size)
10322 ast_str_append(&a_video, 0, "a=ptime:%d\r\n", min_video_packet_size);
10323
10324
10325 if (min_text_packet_size)
10326 ast_str_append(&a_text, 0, "a=ptime:%d\r\n", min_text_packet_size);
10327
10328 if (m_audio->len - m_audio->used < 2 || m_video->len - m_video->used < 2 ||
10329 m_text->len - m_text->used < 2 || a_text->len - a_text->used < 2 ||
10330 a_audio->len - a_audio->used < 2 || a_video->len - a_video->used < 2)
10331 ast_log(LOG_WARNING, "SIP SDP may be truncated due to undersized buffer!!\n");
10332 }
10333
10334 if (add_t38) {
10335
10336 ast_udptl_get_us(p->udptl, &udptlsin);
10337
10338
10339 if (p->udptlredirip.sin_addr.s_addr) {
10340 udptldest.sin_port = p->udptlredirip.sin_port;
10341 udptldest.sin_addr = p->udptlredirip.sin_addr;
10342 } else {
10343 udptldest.sin_addr = p->ourip.sin_addr;
10344 udptldest.sin_port = udptlsin.sin_port;
10345 }
10346
10347 if (debug)
10348 ast_debug(1, "T.38 UDPTL is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(udptlsin.sin_port));
10349
10350
10351
10352
10353 ast_str_append(&m_modem, 0, "m=image %d udptl t38\r\n", ntohs(udptldest.sin_port));
10354
10355 ast_str_append(&a_modem, 0, "a=T38FaxVersion:%d\r\n", p->t38.our_parms.version);
10356 ast_str_append(&a_modem, 0, "a=T38MaxBitRate:%d\r\n", t38_get_rate(p->t38.our_parms.rate));
10357 if (p->t38.our_parms.fill_bit_removal) {
10358 ast_str_append(&a_modem, 0, "a=T38FaxFillBitRemoval\r\n");
10359 }
10360 if (p->t38.our_parms.transcoding_mmr) {
10361 ast_str_append(&a_modem, 0, "a=T38FaxTranscodingMMR\r\n");
10362 }
10363 if (p->t38.our_parms.transcoding_jbig) {
10364 ast_str_append(&a_modem, 0, "a=T38FaxTranscodingJBIG\r\n");
10365 }
10366 switch (p->t38.our_parms.rate_management) {
10367 case AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF:
10368 ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:transferredTCF\r\n");
10369 break;
10370 case AST_T38_RATE_MANAGEMENT_LOCAL_TCF:
10371 ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:localTCF\r\n");
10372 break;
10373 }
10374 ast_str_append(&a_modem, 0, "a=T38FaxMaxDatagram:%u\r\n", ast_udptl_get_local_max_datagram(p->udptl));
10375 switch (ast_udptl_get_error_correction_scheme(p->udptl)) {
10376 case UDPTL_ERROR_CORRECTION_NONE:
10377 break;
10378 case UDPTL_ERROR_CORRECTION_FEC:
10379 ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPFEC\r\n");
10380 break;
10381 case UDPTL_ERROR_CORRECTION_REDUNDANCY:
10382 ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPRedundancy\r\n");
10383 break;
10384 }
10385 }
10386
10387 if (needaudio)
10388 ast_str_append(&m_audio, 0, "\r\n");
10389 if (needvideo)
10390 ast_str_append(&m_video, 0, "\r\n");
10391 if (needtext)
10392 ast_str_append(&m_text, 0, "\r\n");
10393
10394 add_header(resp, "Content-Type", "application/sdp");
10395 add_content(resp, version);
10396 add_content(resp, owner);
10397 add_content(resp, subject);
10398 add_content(resp, connection);
10399 if (needvideo)
10400 add_content(resp, bandwidth);
10401 add_content(resp, session_time);
10402 if (needaudio) {
10403 add_content(resp, m_audio->str);
10404 add_content(resp, a_audio->str);
10405 add_content(resp, hold);
10406 } else if (p->offered_media[SDP_AUDIO].offered) {
10407 snprintf(dummy_answer, sizeof(dummy_answer), "m=audio 0 RTP/AVP %s\r\n", p->offered_media[SDP_AUDIO].text);
10408 add_content(resp, dummy_answer);
10409 }
10410 if (needvideo) {
10411 add_content(resp, m_video->str);
10412 add_content(resp, a_video->str);
10413 add_content(resp, hold);
10414 } else if (p->offered_media[SDP_VIDEO].offered) {
10415 snprintf(dummy_answer, sizeof(dummy_answer), "m=video 0 RTP/AVP %s\r\n", p->offered_media[SDP_VIDEO].text);
10416 add_content(resp, dummy_answer);
10417 }
10418 if (needtext) {
10419 add_content(resp, m_text->str);
10420 add_content(resp, a_text->str);
10421 add_content(resp, hold);
10422 } else if (p->offered_media[SDP_TEXT].offered) {
10423 snprintf(dummy_answer, sizeof(dummy_answer), "m=text 0 RTP/AVP %s\r\n", p->offered_media[SDP_TEXT].text);
10424 add_content(resp, dummy_answer);
10425 }
10426 if (add_t38) {
10427 add_content(resp, m_modem->str);
10428 add_content(resp, a_modem->str);
10429 } else if (p->offered_media[SDP_IMAGE].offered) {
10430 add_content(resp, "m=image 0 udptl t38\r\n");
10431 }
10432
10433
10434 p->lastrtprx = p->lastrtptx = time(NULL);
10435
10436 ast_debug(3, "Done building SDP. Settling with this capability: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, capability));
10437
10438 return AST_SUCCESS;
10439 }
10440
10441
10442 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
10443 {
10444 struct sip_request resp;
10445 int seqno;
10446
10447 if (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1) {
10448 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
10449 return -1;
10450 }
10451 respprep(&resp, p, msg, req);
10452 if (p->udptl) {
10453 add_sdp(&resp, p, 0, 0, 1);
10454 } else
10455 ast_log(LOG_ERROR, "Can't add SDP to response, since we have no UDPTL session allocated. Call-ID %s\n", p->callid);
10456 if (retrans && !p->pendinginvite)
10457 p->pendinginvite = seqno;
10458 return send_response(p, &resp, retrans, seqno);
10459 }
10460
10461
10462 static void copy_request(struct sip_request *dst, const struct sip_request *src)
10463 {
10464
10465
10466
10467 struct ast_str *duplicate = dst->data;
10468 struct ast_str *duplicate_content = dst->content;
10469
10470
10471
10472 memcpy(dst, src, sizeof(*dst));
10473 dst->data = duplicate;
10474 dst->content = duplicate_content;
10475
10476
10477 if (!dst->data && !(dst->data = ast_str_create(ast_str_strlen(src->data) + 1)))
10478 return;
10479 ast_str_copy_string(&dst->data, src->data);
10480
10481
10482 if (src->content) {
10483 if (!dst->content && !(dst->content = ast_str_create(ast_str_strlen(src->content) + 1)))
10484 return;
10485 ast_str_copy_string(&dst->content, src->content);
10486 }
10487 }
10488
10489
10490
10491
10492 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable, int oldsdp)
10493 {
10494 struct sip_request resp;
10495 int seqno;
10496 if (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1) {
10497 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
10498 return -1;
10499 }
10500 respprep(&resp, p, msg, req);
10501 if (p->rtp) {
10502 if (!p->autoframing && !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
10503 ast_debug(1, "Setting framing from config on incoming call\n");
10504 ast_rtp_codec_setpref(p->rtp, &p->prefs);
10505 }
10506 try_suggested_sip_codec(p);
10507 if (p->t38.state == T38_ENABLED) {
10508 add_sdp(&resp, p, oldsdp, TRUE, TRUE);
10509 } else {
10510 add_sdp(&resp, p, oldsdp, TRUE, FALSE);
10511 }
10512 } else
10513 ast_log(LOG_ERROR, "Can't add SDP to response, since we have no RTP session allocated. Call-ID %s\n", p->callid);
10514 if (reliable && !p->pendinginvite)
10515 p->pendinginvite = seqno;
10516 return send_response(p, &resp, reliable, seqno);
10517 }
10518
10519
10520 static int determine_firstline_parts(struct sip_request *req)
10521 {
10522 char *e = ast_skip_blanks(req->data->str);
10523 char *local_rlPart1;
10524
10525 if (!*e)
10526 return -1;
10527 req->rlPart1 = e - req->data->str;
10528 local_rlPart1 = e;
10529 e = ast_skip_nonblanks(e);
10530 if (*e)
10531 *e++ = '\0';
10532
10533 e = ast_skip_blanks(e);
10534 if ( !*e )
10535 return -1;
10536 ast_trim_blanks(e);
10537
10538 if (!strcasecmp(local_rlPart1, "SIP/2.0") ) {
10539 if (strlen(e) < 3)
10540 return -1;
10541 req->rlPart2 = e - req->data->str;
10542 } else {
10543 if ( *e == '<' ) {
10544 ast_debug(3, "Oops. Bogus uri in <> %s\n", e);
10545 e++;
10546 if (!*e)
10547 return -1;
10548 }
10549 req->rlPart2 = e - req->data->str;
10550 e = ast_skip_nonblanks(e);
10551 if (*e)
10552 *e++ = '\0';
10553 e = ast_skip_blanks(e);
10554 if (strcasecmp(e, "SIP/2.0") ) {
10555 ast_debug(3, "Skipping packet - Bad request protocol %s\n", e);
10556 return -1;
10557 }
10558 }
10559 return 1;
10560 }
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp)
10576 {
10577 struct sip_request req;
10578
10579 reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ? SIP_UPDATE : SIP_INVITE, 0, 1);
10580
10581 add_header(&req, "Allow", ALLOWED_METHODS);
10582 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
10583 if (sipdebug) {
10584 if (oldsdp == TRUE)
10585 add_header(&req, "X-asterisk-Info", "SIP re-invite (Session-Timers)");
10586 else
10587 add_header(&req, "X-asterisk-Info", "SIP re-invite (External RTP bridge)");
10588 }
10589
10590 if (p->do_history)
10591 append_history(p, "ReInv", "Re-invite sent");
10592 memset(p->offered_media, 0, sizeof(p->offered_media));
10593
10594 if (t38version)
10595 add_sdp(&req, p, oldsdp, FALSE, TRUE);
10596 else
10597 add_sdp(&req, p, oldsdp, TRUE, FALSE);
10598
10599
10600 initialize_initreq(p, &req);
10601 p->lastinvite = p->ocseq;
10602 ast_set_flag(&p->flags[0], SIP_OUTGOING);
10603
10604 return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
10605 }
10606
10607
10608 static char *remove_uri_parameters(char *uri)
10609 {
10610 char *atsign;
10611 atsign = strchr(uri, '@');
10612 if (!atsign)
10613 atsign = uri;
10614 atsign = strchr(atsign, ';');
10615 if (atsign)
10616 *atsign = '\0';
10617 return uri;
10618 }
10619
10620
10621 static void extract_uri(struct sip_pvt *p, struct sip_request *req)
10622 {
10623 char stripped[SIPBUFSIZE];
10624 char *c;
10625
10626 ast_copy_string(stripped, get_header(req, "Contact"), sizeof(stripped));
10627 c = get_in_brackets(stripped);
10628
10629 c = remove_uri_parameters(c);
10630 if (!ast_strlen_zero(c))
10631 ast_string_field_set(p, uri, c);
10632
10633 }
10634
10635
10636 static void build_contact(struct sip_pvt *p)
10637 {
10638
10639 int ourport = ntohs(p->ourip.sin_port);
10640
10641 if (!sip_standard_port(p->socket.type, ourport)) {
10642 if (p->socket.type == SIP_TRANSPORT_UDP)
10643 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);
10644 else
10645 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));
10646 } else {
10647 if (p->socket.type == SIP_TRANSPORT_UDP)
10648 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));
10649 else
10650 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));
10651 }
10652 }
10653
10654
10655 static void build_rpid(struct sip_pvt *p)
10656 {
10657 int send_pres_tags = TRUE;
10658 const char *privacy=NULL;
10659 const char *screen=NULL;
10660 char buf[256];
10661 const char *clid = default_callerid;
10662 const char *clin = NULL;
10663 const char *fromdomain;
10664
10665 if (!ast_strlen_zero(p->rpid) || !ast_strlen_zero(p->rpid_from))
10666 return;
10667
10668 if (p->owner && !ast_strlen_zero(p->owner->cid.cid_num))
10669 clid = p->owner->cid.cid_num;
10670 if (p->owner && p->owner->cid.cid_name)
10671 clin = p->owner->cid.cid_name;
10672 if (ast_strlen_zero(clin))
10673 clin = clid;
10674
10675 switch (p->callingpres) {
10676 case AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED:
10677 privacy = "off";
10678 screen = "no";
10679 break;
10680 case AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN:
10681 privacy = "off";
10682 screen = "yes";
10683 break;
10684 case AST_PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN:
10685 privacy = "off";
10686 screen = "no";
10687 break;
10688 case AST_PRES_ALLOWED_NETWORK_NUMBER:
10689 privacy = "off";
10690 screen = "yes";
10691 break;
10692 case AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED:
10693 privacy = "full";
10694 screen = "no";
10695 break;
10696 case AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN:
10697 privacy = "full";
10698 screen = "yes";
10699 break;
10700 case AST_PRES_PROHIB_USER_NUMBER_FAILED_SCREEN:
10701 privacy = "full";
10702 screen = "no";
10703 break;
10704 case AST_PRES_PROHIB_NETWORK_NUMBER:
10705 privacy = "full";
10706 screen = "yes";
10707 break;
10708 case AST_PRES_NUMBER_NOT_AVAILABLE:
10709 send_pres_tags = FALSE;
10710 break;
10711 default:
10712 ast_log(LOG_WARNING, "Unsupported callingpres (%d)\n", p->callingpres);
10713 if ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)
10714 privacy = "full";
10715 else
10716 privacy = "off";
10717 screen = "no";
10718 break;
10719 }
10720
10721 fromdomain = S_OR(p->fromdomain, ast_inet_ntoa(p->ourip.sin_addr));
10722
10723 snprintf(buf, sizeof(buf), "\"%s\" <sip:%s@%s>", clin, clid, fromdomain);
10724 if (send_pres_tags)
10725 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ";privacy=%s;screen=%s", privacy, screen);
10726 ast_string_field_set(p, rpid, buf);
10727
10728 ast_string_field_build(p, rpid_from, "\"%s\" <sip:%s@%s>;tag=%s", clin,
10729 S_OR(p->fromuser, clid),
10730 fromdomain, p->tag);
10731 }
10732
10733
10734 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod)
10735 {
10736 struct ast_str *invite = ast_str_alloca(256);
10737 char from[256];
10738 char to[256];
10739 char tmp_n[SIPBUFSIZE/2];
10740 char tmp_l[SIPBUFSIZE/2];
10741 const char *l = NULL;
10742 const char *n = NULL;
10743 const char *d = NULL;
10744 const char *urioptions = "";
10745 int ourport;
10746
10747 if (ast_test_flag(&p->flags[0], SIP_USEREQPHONE)) {
10748 const char *s = p->username;
10749
10750
10751
10752
10753
10754
10755 if (*s == '+')
10756 s++;
10757 for (; *s; s++) {
10758 if (!strchr(AST_DIGIT_ANYNUM, *s) )
10759 break;
10760 }
10761
10762 if (!*s)
10763 urioptions = ";user=phone";
10764 }
10765
10766
10767 snprintf(p->lastmsg, sizeof(p->lastmsg), "Init: %s", sip_methods[sipmethod].text);
10768
10769 d = S_OR(p->fromdomain, ast_inet_ntoa(p->ourip.sin_addr));
10770 if (p->owner) {
10771 l = p->owner->cid.cid_num;
10772 n = p->owner->cid.cid_name;
10773 }
10774
10775 if (!ast_test_flag(&p->flags[0], SIP_SENDRPID) &&
10776 ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)) {
10777 l = CALLERID_UNKNOWN;
10778 n = l;
10779 d = FROMDOMAIN_INVALID;
10780 }
10781 if (ast_strlen_zero(l))
10782 l = default_callerid;
10783 if (ast_strlen_zero(n))
10784 n = l;
10785
10786 if (!ast_strlen_zero(p->fromuser))
10787 l = p->fromuser;
10788 else
10789 ast_string_field_set(p, fromuser, l);
10790
10791
10792 if (!ast_strlen_zero(p->fromname))
10793 n = p->fromname;
10794 else
10795 ast_string_field_set(p, fromname, n);
10796
10797 if (sip_cfg.pedanticsipchecking) {
10798 ast_uri_encode(n, tmp_n, sizeof(tmp_n), 0);
10799 n = tmp_n;
10800 ast_uri_encode(l, tmp_l, sizeof(tmp_l), 0);
10801 l = tmp_l;
10802 }
10803
10804 ourport = ntohs(p->ourip.sin_port);
10805 if (!sip_standard_port(p->socket.type, ourport) && ast_strlen_zero(p->fromdomain))
10806 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s:%d>;tag=%s", n, l, d, ourport, p->tag);
10807 else
10808 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=%s", n, l, d, p->tag);
10809
10810
10811 if (!ast_strlen_zero(p->fullcontact)) {
10812
10813 ast_str_append(&invite, 0, "%s", p->fullcontact);
10814 } else {
10815
10816 ast_str_append(&invite, 0, "sip:");
10817 if (!ast_strlen_zero(p->username)) {
10818 n = p->username;
10819 if (sip_cfg.pedanticsipchecking) {
10820 ast_uri_encode(n, tmp_n, sizeof(tmp_n), 0);
10821 n = tmp_n;
10822 }
10823 ast_str_append(&invite, 0, "%s@", n);
10824 }
10825 ast_str_append(&invite, 0, "%s", p->tohost);
10826 if (p->portinuri)
10827 ast_str_append(&invite, 0, ":%d", ntohs(p->sa.sin_port));
10828 ast_str_append(&invite, 0, "%s", urioptions);
10829 }
10830
10831
10832 if (p->options && !ast_strlen_zero(p->options->uri_options))
10833 ast_str_append(&invite, 0, ";%s", p->options->uri_options);
10834
10835
10836
10837
10838 ast_string_field_set(p, uri, invite->str);
10839
10840 if (!ast_strlen_zero(p->todnid)) {
10841
10842 if (!strchr(p->todnid, '@')) {
10843
10844 snprintf(to, sizeof(to), "<sip:%s@%s>%s%s", p->todnid, p->tohost, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
10845 } else {
10846 snprintf(to, sizeof(to), "<sip:%s>%s%s", p->todnid, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
10847 }
10848 } else {
10849 if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->theirtag)) {
10850
10851 snprintf(to, sizeof(to), "<%s%s>;tag=%s", (strncasecmp(p->uri, "sip:", 4) ? "sip:" : ""), p->uri, p->theirtag);
10852 } else if (p->options && p->options->vxml_url) {
10853
10854 snprintf(to, sizeof(to), "<%s>;%s", p->uri, p->options->vxml_url);
10855 } else
10856 snprintf(to, sizeof(to), "<%s>", p->uri);
10857 }
10858
10859 init_req(req, sipmethod, p->uri);
10860
10861 snprintf(tmp_n, sizeof(tmp_n), "%d %s", ++p->ocseq, sip_methods[sipmethod].text);
10862
10863 add_header(req, "Via", p->via);
10864 add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
10865
10866
10867
10868
10869 add_route(req, p->route);
10870
10871
10872 if (ast_test_flag(&p->flags[0], SIP_SENDRPID) && (sipmethod == SIP_INVITE)) {
10873 build_rpid(p);
10874 add_header(req, "From", p->rpid_from);
10875 } else
10876 add_header(req, "From", from);
10877 add_header(req, "To", to);
10878 ast_string_field_set(p, exten, l);
10879 build_contact(p);
10880 add_header(req, "Contact", p->our_contact);
10881 add_header(req, "Call-ID", p->callid);
10882 add_header(req, "CSeq", tmp_n);
10883 if (!ast_strlen_zero(global_useragent))
10884 add_header(req, "User-Agent", global_useragent);
10885 if (!ast_strlen_zero(p->rpid))
10886 add_header(req, "Remote-Party-ID", p->rpid);
10887 }
10888
10889
10890
10891
10892
10893
10894
10895
10896 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init)
10897 {
10898 struct sip_request req;
10899 struct ast_variable *var;
10900
10901 req.method = sipmethod;
10902 if (init) {
10903 p->branch ^= ast_random();
10904 p->invite_branch = p->branch;
10905 build_via(p);
10906 }
10907 if (init > 1)
10908 initreqprep(&req, p, sipmethod);
10909 else
10910
10911 reqprep(&req, p, sipmethod, 0, init ? 0 : 1);
10912
10913 if (p->options && p->options->auth)
10914 add_header(&req, p->options->authheader, p->options->auth);
10915 append_date(&req);
10916 if (sipmethod == SIP_REFER) {
10917 if (p->refer) {
10918 char buf[SIPBUFSIZE];
10919 if (!ast_strlen_zero(p->refer->refer_to))
10920 add_header(&req, "Refer-To", p->refer->refer_to);
10921 if (!ast_strlen_zero(p->refer->referred_by)) {
10922 snprintf(buf, sizeof(buf), "%s <%s>", p->refer->referred_by_name, p->refer->referred_by);
10923 add_header(&req, "Referred-By", buf);
10924 }
10925 }
10926 } else if (sipmethod == SIP_SUBSCRIBE) {
10927 char buf[SIPBUFSIZE];
10928
10929 add_header(&req, "Event", "message-summary");
10930 add_header(&req, "Accept", "application/simple-message-summary");
10931 snprintf(buf, sizeof(buf), "%d", mwi_expiry);
10932 add_header(&req, "Expires", buf);
10933 }
10934
10935
10936
10937 if (p->options && !ast_strlen_zero(p->options->replaces)) {
10938 add_header(&req, "Replaces", p->options->replaces);
10939 add_header(&req, "Require", "replaces");
10940 }
10941
10942
10943 if (st_get_mode(p) == SESSION_TIMER_MODE_ORIGINATE) {
10944 char i2astr[10];
10945
10946 if (!p->stimer->st_interval)
10947 p->stimer->st_interval = st_get_se(p, TRUE);
10948
10949 p->stimer->st_active = TRUE;
10950
10951 snprintf(i2astr, sizeof(i2astr), "%d", p->stimer->st_interval);
10952 add_header(&req, "Session-Expires", i2astr);
10953 snprintf(i2astr, sizeof(i2astr), "%d", st_get_se(p, FALSE));
10954 add_header(&req, "Min-SE", i2astr);
10955 }
10956
10957 add_header(&req, "Allow", ALLOWED_METHODS);
10958 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
10959
10960 if(p->notify_headers) {
10961 char buf[512];
10962 for (var = p->notify_headers; var; var = var->next) {
10963 ast_copy_string(buf, var->value, sizeof(buf));
10964 add_header(&req, var->name, ast_unescape_semicolon(buf));
10965 }
10966 }
10967 if (p->options && p->options->addsipheaders && p->owner) {
10968 struct ast_channel *chan = p->owner;
10969 struct varshead *headp;
10970
10971 ast_channel_lock(chan);
10972
10973 headp = &chan->varshead;
10974
10975 if (!headp)
10976 ast_log(LOG_WARNING, "No Headp for the channel...ooops!\n");
10977 else {
10978 const struct ast_var_t *current;
10979 AST_LIST_TRAVERSE(headp, current, entries) {
10980
10981 if (!strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
10982 char *content, *end;
10983 const char *header = ast_var_value(current);
10984 char *headdup = ast_strdupa(header);
10985
10986
10987 if (*headdup == '"')
10988 headdup++;
10989 if ((content = strchr(headdup, ':'))) {
10990 *content++ = '\0';
10991 content = ast_skip_blanks(content);
10992
10993 end = content + strlen(content) -1;
10994 if (*end == '"')
10995 *end = '\0';
10996
10997 add_header(&req, headdup, content);
10998 if (sipdebug)
10999 ast_debug(1, "Adding SIP Header \"%s\" with content :%s: \n", headdup, content);
11000 }
11001 }
11002 }
11003 }
11004
11005 ast_channel_unlock(chan);
11006 }
11007 if (sdp) {
11008 memset(p->offered_media, 0, sizeof(p->offered_media));
11009 if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
11010 ast_debug(1, "T38 is in state %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
11011 add_sdp(&req, p, FALSE, FALSE, TRUE);
11012 } else if (p->rtp)
11013 add_sdp(&req, p, FALSE, TRUE, FALSE);
11014 }
11015
11016 if (!p->initreq.headers || init > 2)
11017 initialize_initreq(p, &req);
11018 p->lastinvite = p->ocseq;
11019 return send_request(p, &req, init ? XMIT_CRITICAL : XMIT_RELIABLE, p->ocseq);
11020 }
11021
11022
11023 static int sip_subscribe_mwi_do(const void *data)
11024 {
11025 struct sip_subscription_mwi *mwi = (struct sip_subscription_mwi*)data;
11026
11027 if (!mwi) {
11028 return -1;
11029 }
11030
11031 mwi->resub = -1;
11032 __sip_subscribe_mwi_do(mwi);
11033 ASTOBJ_UNREF(mwi, sip_subscribe_mwi_destroy);
11034
11035 return 0;
11036 }
11037
11038
11039 static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi)
11040 {
11041
11042 if (!mwi->dnsmgr) {
11043 char transport[MAXHOSTNAMELEN];
11044 snprintf(transport, sizeof(transport), "_sip._%s", get_transport(mwi->transport));
11045 ast_dnsmgr_lookup(mwi->hostname, &mwi->us, &mwi->dnsmgr, sip_cfg.srvlookup ? transport : NULL);
11046 }
11047
11048
11049 if (mwi->call) {
11050 transmit_invite(mwi->call, SIP_SUBSCRIBE, 0, 0);
11051 return 0;
11052 }
11053
11054
11055 if (!(mwi->call = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL))) {
11056 return -1;
11057 }
11058
11059 ref_proxy(mwi->call, obproxy_get(mwi->call, NULL));
11060
11061 if (!mwi->us.sin_port && mwi->portno) {
11062 mwi->us.sin_port = htons(mwi->portno);
11063 }
11064
11065
11066 if (create_addr(mwi->call, mwi->hostname, &mwi->us, 0)) {
11067 dialog_unlink_all(mwi->call, TRUE, TRUE);
11068 mwi->call = dialog_unref(mwi->call, "unref dialog after unlink_all");
11069 return 0;
11070 }
11071
11072 if (!mwi->dnsmgr && mwi->portno) {
11073 mwi->call->sa.sin_port = htons(mwi->portno);
11074 mwi->call->recv.sin_port = htons(mwi->portno);
11075 } else {
11076 mwi->portno = ntohs(mwi->call->sa.sin_port);
11077 }
11078
11079
11080 if (!ast_strlen_zero(mwi->authuser)) {
11081 ast_string_field_set(mwi->call, peername, mwi->authuser);
11082 ast_string_field_set(mwi->call, authname, mwi->authuser);
11083 ast_string_field_set(mwi->call, fromuser, mwi->authuser);
11084 } else {
11085 ast_string_field_set(mwi->call, peername, mwi->username);
11086 ast_string_field_set(mwi->call, authname, mwi->username);
11087 ast_string_field_set(mwi->call, fromuser, mwi->username);
11088 }
11089 ast_string_field_set(mwi->call, username, mwi->username);
11090 if (!ast_strlen_zero(mwi->secret)) {
11091 ast_string_field_set(mwi->call, peersecret, mwi->secret);
11092 }
11093 set_socket_transport(&mwi->call->socket, mwi->transport);
11094 mwi->call->socket.port = htons(mwi->portno);
11095 ast_sip_ouraddrfor(&mwi->call->sa.sin_addr, &mwi->call->ourip, mwi->call);
11096 build_contact(mwi->call);
11097 build_via(mwi->call);
11098 build_callid_pvt(mwi->call);
11099 ast_set_flag(&mwi->call->flags[0], SIP_OUTGOING);
11100
11101
11102 mwi->call->mwi = ASTOBJ_REF(mwi);
11103
11104
11105 transmit_invite(mwi->call, SIP_SUBSCRIBE, 0, 2);
11106
11107 return 0;
11108 }
11109
11110 static int find_calling_channel(struct ast_channel *c, void *data) {
11111 struct sip_pvt *p = data;
11112
11113 return (c->pbx &&
11114 (!strcasecmp(c->macroexten, p->exten) || !strcasecmp(c->exten, p->exten)) &&
11115 (sip_cfg.notifycid == IGNORE_CONTEXT || !strcasecmp(c->context, p->context)));
11116 }
11117
11118
11119 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout)
11120 {
11121 struct ast_str *tmp = ast_str_alloca(4000);
11122 char from[256], to[256];
11123 char *c, *mfrom, *mto;
11124 struct sip_request req;
11125 char hint[AST_MAX_EXTENSION];
11126 char *statestring = "terminated";
11127 const struct cfsubscription_types *subscriptiontype;
11128 enum state { NOTIFY_OPEN, NOTIFY_INUSE, NOTIFY_CLOSED } local_state = NOTIFY_OPEN;
11129 char *pidfstate = "--";
11130 char *pidfnote= "Ready";
11131
11132 memset(from, 0, sizeof(from));
11133 memset(to, 0, sizeof(to));
11134
11135 switch (state) {
11136 case (AST_EXTENSION_RINGING | AST_EXTENSION_INUSE):
11137 statestring = (sip_cfg.notifyringing) ? "early" : "confirmed";
11138 local_state = NOTIFY_INUSE;
11139 pidfstate = "busy";
11140 pidfnote = "Ringing";
11141 break;
11142 case AST_EXTENSION_RINGING:
11143 statestring = "early";
11144 local_state = NOTIFY_INUSE;
11145 pidfstate = "busy";
11146 pidfnote = "Ringing";
11147 break;
11148 case AST_EXTENSION_INUSE:
11149 statestring = "confirmed";
11150 local_state = NOTIFY_INUSE;
11151 pidfstate = "busy";
11152 pidfnote = "On the phone";
11153 break;
11154 case AST_EXTENSION_BUSY:
11155 statestring = "confirmed";
11156 local_state = NOTIFY_CLOSED;
11157 pidfstate = "busy";
11158 pidfnote = "On the phone";
11159 break;
11160 case AST_EXTENSION_UNAVAILABLE:
11161 statestring = "terminated";
11162 local_state = NOTIFY_CLOSED;
11163 pidfstate = "away";
11164 pidfnote = "Unavailable";
11165 break;
11166 case AST_EXTENSION_ONHOLD:
11167 statestring = "confirmed";
11168 local_state = NOTIFY_CLOSED;
11169 pidfstate = "busy";
11170 pidfnote = "On hold";
11171 break;
11172 case AST_EXTENSION_NOT_INUSE:
11173 default:
11174
11175 break;
11176 }
11177
11178 subscriptiontype = find_subscription_type(p->subscribed);
11179
11180
11181 if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, p->exten)) {
11182 char *hint2 = hint, *individual_hint = NULL;
11183 int hint_count = 0, unavailable_count = 0;
11184
11185 while ((individual_hint = strsep(&hint2, "&"))) {
11186 hint_count++;
11187
11188 if (ast_device_state(individual_hint) == AST_DEVICE_UNAVAILABLE)
11189 unavailable_count++;
11190 }
11191
11192
11193
11194
11195 if (hint_count > 0 && hint_count == unavailable_count) {
11196 local_state = NOTIFY_CLOSED;
11197 pidfstate = "away";
11198 pidfnote = "Not online";
11199 }
11200 }
11201
11202 ast_copy_string(from, get_header(&p->initreq, "From"), sizeof(from));
11203 c = get_in_brackets(from);
11204 if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
11205 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
11206 return -1;
11207 }
11208
11209 mfrom = remove_uri_parameters(c);
11210
11211 ast_copy_string(to, get_header(&p->initreq, "To"), sizeof(to));
11212 c = get_in_brackets(to);
11213 if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
11214 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
11215 return -1;
11216 }
11217 mto = remove_uri_parameters(c);
11218
11219 reqprep(&req, p, SIP_NOTIFY, 0, 1);
11220
11221
11222 add_header(&req, "Event", subscriptiontype->event);
11223 add_header(&req, "Content-Type", subscriptiontype->mediatype);
11224 switch(state) {
11225 case AST_EXTENSION_DEACTIVATED:
11226 if (timeout)
11227 add_header(&req, "Subscription-State", "terminated;reason=timeout");
11228 else {
11229 add_header(&req, "Subscription-State", "terminated;reason=probation");
11230 add_header(&req, "Retry-After", "60");
11231 }
11232 break;
11233 case AST_EXTENSION_REMOVED:
11234 add_header(&req, "Subscription-State", "terminated;reason=noresource");
11235 break;
11236 default:
11237 if (p->expiry)
11238 add_header(&req, "Subscription-State", "active");
11239 else
11240 add_header(&req, "Subscription-State", "terminated;reason=timeout");
11241 }
11242 switch (p->subscribed) {
11243 case XPIDF_XML:
11244 case CPIM_PIDF_XML:
11245 ast_str_append(&tmp, 0,
11246 "<?xml version=\"1.0\"?>\n"
11247 "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n"
11248 "<presence>\n");
11249 ast_str_append(&tmp, 0, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
11250 ast_str_append(&tmp, 0, "<atom id=\"%s\">\n", p->exten);
11251 ast_str_append(&tmp, 0, "<address uri=\"%s;user=ip\" priority=\"0.800000\">\n", mto);
11252 ast_str_append(&tmp, 0, "<status status=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "open" : (local_state == NOTIFY_INUSE) ? "inuse" : "closed");
11253 ast_str_append(&tmp, 0, "<msnsubstatus substatus=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "online" : (local_state == NOTIFY_INUSE) ? "onthephone" : "offline");
11254 ast_str_append(&tmp, 0, "</address>\n</atom>\n</presence>\n");
11255 break;
11256 case PIDF_XML:
11257 ast_str_append(&tmp, 0,
11258 "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"
11259 "<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);
11260 ast_str_append(&tmp, 0, "<pp:person><status>\n");
11261 if (pidfstate[0] != '-')
11262 ast_str_append(&tmp, 0, "<ep:activities><ep:%s/></ep:activities>\n", pidfstate);
11263 ast_str_append(&tmp, 0, "</status></pp:person>\n");
11264 ast_str_append(&tmp, 0, "<note>%s</note>\n", pidfnote);
11265 ast_str_append(&tmp, 0, "<tuple id=\"%s\">\n", p->exten);
11266 ast_str_append(&tmp, 0, "<contact priority=\"1\">%s</contact>\n", mto);
11267 if (pidfstate[0] == 'b')
11268 ast_str_append(&tmp, 0, "<status><basic>open</basic></status>\n");
11269 else
11270 ast_str_append(&tmp, 0, "<status><basic>%s</basic></status>\n", (local_state != NOTIFY_CLOSED) ? "open" : "closed");
11271 ast_str_append(&tmp, 0, "</tuple>\n</presence>\n");
11272 break;
11273 case DIALOG_INFO_XML:
11274 ast_str_append(&tmp, 0, "<?xml version=\"1.0\"?>\n");
11275 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);
11276 if ((state & AST_EXTENSION_RINGING) && sip_cfg.notifyringing) {
11277 const char *local_display = p->exten;
11278 char *local_target = mto;
11279
11280
11281
11282
11283 if (sip_cfg.notifycid) {
11284 struct ast_channel *caller = ast_channel_search_locked(find_calling_channel, p);
11285
11286 if (caller) {
11287 int need = strlen(caller->cid.cid_num) + strlen(p->fromdomain) + sizeof("sip:@");
11288 local_target = alloca(need);
11289 snprintf(local_target, need, "sip:%s@%s", caller->cid.cid_num, p->fromdomain);
11290 local_display = ast_strdupa(caller->cid.cid_name);
11291 ast_channel_unlock(caller);
11292 caller = NULL;
11293 }
11294 }
11295
11296
11297
11298 ast_str_append(&tmp, 0,
11299 "<dialog id=\"%s\" call-id=\"pickup-%s\" direction=\"recipient\">\n"
11300 "<remote>\n"
11301
11302
11303 "<identity display=\"%s\">%s</identity>\n"
11304 "<target uri=\"%s\"/>\n"
11305 "</remote>\n"
11306 "<local>\n"
11307 "<identity>%s</identity>\n"
11308 "<target uri=\"%s\"/>\n"
11309 "</local>\n",
11310 p->exten, p->callid, local_display, local_target, local_target, mto, mto);
11311 } else {
11312 ast_str_append(&tmp, 0, "<dialog id=\"%s\">\n", p->exten);
11313 }
11314 ast_str_append(&tmp, 0, "<state>%s</state>\n", statestring);
11315 if (state == AST_EXTENSION_ONHOLD) {
11316 ast_str_append(&tmp, 0, "<local>\n<target uri=\"%s\">\n"
11317 "<param pname=\"+sip.rendering\" pvalue=\"no\"/>\n"
11318 "</target>\n</local>\n", mto);
11319 }
11320 ast_str_append(&tmp, 0, "</dialog>\n</dialog-info>\n");
11321 break;
11322 case NONE:
11323 default:
11324 break;
11325 }
11326
11327 add_content(&req, tmp->str);
11328
11329 p->pendinginvite = p->ocseq;
11330
11331 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11332 }
11333
11334
11335
11336
11337
11338
11339
11340 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten)
11341 {
11342 struct sip_request req;
11343 struct ast_str *out = ast_str_alloca(500);
11344 int ourport = ntohs(p->ourip.sin_port);
11345 const char *exten = S_OR(vmexten, default_vmexten);
11346
11347 initreqprep(&req, p, SIP_NOTIFY);
11348 add_header(&req, "Event", "message-summary");
11349 add_header(&req, "Content-Type", default_notifymime);
11350 ast_str_append(&out, 0, "Messages-Waiting: %s\r\n", newmsgs ? "yes" : "no");
11351
11352 if (!ast_strlen_zero(p->fromdomain)) {
11353 ast_str_append(&out, 0, "Message-Account: sip:%s@%s\r\n", exten, p->fromdomain);
11354 } else if (!sip_standard_port(p->socket.type, ourport)) {
11355 if (p->socket.type == SIP_TRANSPORT_UDP) {
11356 ast_str_append(&out, 0, "Message-Account: sip:%s@%s:%d\r\n", exten, ast_inet_ntoa(p->ourip.sin_addr), ourport);
11357 } else {
11358 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));
11359 }
11360 } else {
11361 if (p->socket.type == SIP_TRANSPORT_UDP) {
11362 ast_str_append(&out, 0, "Message-Account: sip:%s@%s\r\n", exten, ast_inet_ntoa(p->ourip.sin_addr));
11363 } else {
11364 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));
11365 }
11366 }
11367
11368
11369
11370 ast_str_append(&out, 0, "Voice-Message: %d/%d%s\r\n",
11371 newmsgs, oldmsgs, (ast_test_flag(&p->flags[1], SIP_PAGE2_BUGGY_MWI) ? "" : " (0/0)"));
11372
11373 if (p->subscribed) {
11374 if (p->expiry)
11375 add_header(&req, "Subscription-State", "active");
11376 else
11377 add_header(&req, "Subscription-State", "terminated;reason=timeout");
11378 }
11379
11380 add_content(&req, out->str);
11381
11382 if (!p->initreq.headers)
11383 initialize_initreq(p, &req);
11384 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11385 }
11386
11387
11388 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate)
11389 {
11390 struct sip_request req;
11391 char tmp[SIPBUFSIZE/2];
11392
11393 reqprep(&req, p, SIP_NOTIFY, 0, 1);
11394 snprintf(tmp, sizeof(tmp), "refer;id=%d", cseq);
11395 add_header(&req, "Event", tmp);
11396 add_header(&req, "Subscription-state", terminate ? "terminated;reason=noresource" : "active");
11397 add_header(&req, "Content-Type", "message/sipfrag;version=2.0");
11398 add_header(&req, "Allow", ALLOWED_METHODS);
11399 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
11400
11401 snprintf(tmp, sizeof(tmp), "SIP/2.0 %s\r\n", message);
11402 add_content(&req, tmp);
11403
11404 if (!p->initreq.headers)
11405 initialize_initreq(p, &req);
11406
11407 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11408 }
11409
11410
11411 static int transmit_notify_custom(struct sip_pvt *p, struct ast_variable *vars) {
11412 struct sip_request req;
11413 struct ast_variable *var, *newvar;
11414
11415 initreqprep(&req, p, SIP_NOTIFY);
11416
11417
11418 p->notify_headers = newvar = ast_variable_new("Subscription-State", "terminated", "");
11419 add_header(&req, newvar->name, newvar->value);
11420 for (var = vars; var; var = var->next) {
11421 char buf[512];
11422
11423 if (!strcasecmp(var->name, "Content-Length")) {
11424 ast_debug(2, "Ignoring pair %s=%s\n", var->name, var->value);
11425 continue;
11426 }
11427
11428 ast_debug(2, " Adding pair %s=%s\n", var->name, var->value);
11429 ast_copy_string(buf, var->value, sizeof(buf));
11430 add_header(&req, var->name, ast_unescape_semicolon(buf));
11431 newvar->next = ast_variable_new(var->name, var->value, "");
11432 newvar = newvar->next;
11433 }
11434
11435 if (!p->initreq.headers) {
11436 initialize_initreq(p, &req);
11437 }
11438
11439 return send_request(p, &req, XMIT_UNRELIABLE, p->ocseq);
11440 }
11441
11442 static int manager_sipnotify(struct mansession *s, const struct message *m)
11443 {
11444 const char *channame = astman_get_header(m, "Channel");
11445 struct ast_variable *vars = astman_get_variables(m);
11446 struct sip_pvt *p;
11447
11448 if (ast_strlen_zero(channame)) {
11449 astman_send_error(s, m, "SIPNotify requires a channel name");
11450 return 0;
11451 }
11452
11453 if (!strncasecmp(channame, "sip/", 4)) {
11454 channame += 4;
11455 }
11456
11457 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
11458 astman_send_error(s, m, "Unable to build sip pvt data for notify (memory/socket error)");
11459 return 0;
11460 }
11461
11462 if (create_addr(p, channame, NULL, 0)) {
11463
11464 dialog_unlink_all(p, TRUE, TRUE);
11465 dialog_unref(p, "unref dialog inside for loop" );
11466
11467 astman_send_error(s, m, "Could not create address");
11468 return 0;
11469 }
11470
11471
11472 ast_set_flag(&p->flags[0], SIP_OUTGOING);
11473
11474
11475 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
11476 build_via(p);
11477 ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
11478 build_callid_pvt(p);
11479 ao2_t_link(dialogs, p, "Linking in new name");
11480 dialog_ref(p, "bump the count of p, which transmit_sip_request will decrement.");
11481 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
11482
11483 if (!transmit_notify_custom(p, vars)) {
11484 astman_send_ack(s, m, "Notify Sent");
11485 } else {
11486 astman_send_error(s, m, "Unable to send notify");
11487 }
11488 ast_variables_destroy(vars);
11489 return 0;
11490 }
11491
11492 static char mandescr_sipnotify[] =
11493 "Description: Sends a SIP Notify event\n"
11494 "All parameters for this event must be specified in the body of this request\n"
11495 "via multiple Variable: name=value sequences.\n"
11496 "Variables: \n"
11497 " *Channel: <peername> Peer to receive the notify. Required.\n"
11498 " *Variable: <name>=<value> At least one variable pair must be specified.\n"
11499 " ActionID: <id> Action ID for this transaction. Will be returned.\n";
11500
11501 static const struct _map_x_s regstatestrings[] = {
11502 { REG_STATE_FAILED, "Failed" },
11503 { REG_STATE_UNREGISTERED, "Unregistered"},
11504 { REG_STATE_REGSENT, "Request Sent"},
11505 { REG_STATE_AUTHSENT, "Auth. Sent"},
11506 { REG_STATE_REGISTERED, "Registered"},
11507 { REG_STATE_REJECTED, "Rejected"},
11508 { REG_STATE_TIMEOUT, "Timeout"},
11509 { REG_STATE_NOAUTH, "No Authentication"},
11510 { -1, NULL }
11511 };
11512
11513
11514 static const char *regstate2str(enum sipregistrystate regstate)
11515 {
11516 return map_x_s(regstatestrings, regstate, "Unknown");
11517 }
11518
11519
11520
11521
11522
11523
11524
11525 static int sip_reregister(const void *data)
11526 {
11527
11528 struct sip_registry *r= (struct sip_registry *) data;
11529
11530
11531 if (!r)
11532 return 0;
11533
11534 if (r->call && r->call->do_history)
11535 append_history(r->call, "RegistryRenew", "Account: %s@%s", r->username, r->hostname);
11536
11537
11538 if (sipdebug)
11539 ast_log(LOG_NOTICE, " -- Re-registration for %s@%s\n", r->username, r->hostname);
11540
11541 r->expire = -1;
11542 r->expiry = r->configured_expiry;
11543 __sip_do_register(r);
11544 registry_unref(r, "unref the re-register scheduled event");
11545 return 0;
11546 }
11547
11548
11549 static int __sip_do_register(struct sip_registry *r)
11550 {
11551 int res;
11552
11553 res = transmit_register(r, SIP_REGISTER, NULL, NULL);
11554 return res;
11555 }
11556
11557
11558
11559
11560
11561
11562
11563 static int sip_reg_timeout(const void *data)
11564 {
11565
11566
11567 struct sip_registry *r = (struct sip_registry *)data;
11568 struct sip_pvt *p;
11569 int res;
11570
11571
11572 if (!r)
11573 return 0;
11574
11575 if (r->dnsmgr) {
11576
11577 ast_dnsmgr_refresh(r->dnsmgr);
11578 }
11579
11580 ast_log(LOG_NOTICE, " -- Registration for '%s@%s' timed out, trying again (Attempt #%d)\n", r->username, r->hostname, r->regattempts);
11581
11582
11583
11584
11585 if (r->call) {
11586
11587
11588 p = r->call;
11589 sip_pvt_lock(p);
11590 pvt_set_needdestroy(p, "registration timeout");
11591
11592 __sip_pretend_ack(p);
11593 sip_pvt_unlock(p);
11594
11595
11596
11597 if (p->registry)
11598 p->registry = registry_unref(p->registry, "p->registry unreffed");
11599 r->call = dialog_unref(r->call, "unrefing r->call");
11600 }
11601
11602 r->timeout = -1;
11603 if (global_regattempts_max && r->regattempts > global_regattempts_max) {
11604
11605
11606
11607 ast_log(LOG_NOTICE, " -- Giving up forever trying to register '%s@%s'\n", r->username, r->hostname);
11608 r->regstate = REG_STATE_FAILED;
11609 } else {
11610 r->regstate = REG_STATE_UNREGISTERED;
11611 res=transmit_register(r, SIP_REGISTER, NULL, NULL);
11612 }
11613 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));
11614 registry_unref(r, "unreffing registry_unref r");
11615 return 0;
11616 }
11617
11618
11619
11620
11621 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader)
11622 {
11623 struct sip_request req;
11624 char from[256];
11625 char to[256];
11626 char tmp[80];
11627 char addr[80];
11628 struct sip_pvt *p;
11629 struct sip_peer *peer = NULL;
11630 int res;
11631 char *fromdomain;
11632 char *domainport = NULL;
11633
11634
11635 if (r == NULL || ((auth == NULL) && (r->regstate == REG_STATE_REGSENT || r->regstate == REG_STATE_AUTHSENT))) {
11636 if (r) {
11637 ast_log(LOG_NOTICE, "Strange, trying to register %s@%s when registration already pending\n", r->username, r->hostname);
11638 }
11639 return 0;
11640 }
11641
11642 if (r->dnsmgr == NULL) {
11643 char transport[MAXHOSTNAMELEN];
11644 peer = find_peer(r->hostname, NULL, TRUE, FINDPEERS, FALSE, 0);
11645 snprintf(transport, sizeof(transport), "_sip._%s", get_transport(r->transport));
11646 ast_dnsmgr_lookup(peer ? peer->tohost : r->hostname, &r->us, &r->dnsmgr, sip_cfg.srvlookup ? transport : NULL);
11647 if (peer) {
11648 peer = unref_peer(peer, "removing peer ref for dnsmgr_lookup");
11649 }
11650 }
11651
11652 if (r->call) {
11653 if (!auth) {
11654 ast_log(LOG_WARNING, "Already have a REGISTER going on to %s@%s?? \n", r->username, r->hostname);
11655 return 0;
11656 } else {
11657 p = dialog_ref(r->call, "getting a copy of the r->call dialog in transmit_register");
11658 make_our_tag(p->tag, sizeof(p->tag));
11659 ast_string_field_set(p, theirtag, NULL);
11660 }
11661 } else {
11662
11663 if (!r->callid_valid) {
11664 build_callid_registry(r, internip.sin_addr, default_fromdomain);
11665 r->callid_valid = TRUE;
11666 }
11667
11668 if (!(p = sip_alloc( r->callid, NULL, 0, SIP_REGISTER, NULL))) {
11669 ast_log(LOG_WARNING, "Unable to allocate registration transaction (memory or socket error)\n");
11670 return 0;
11671 }
11672
11673 if (p->do_history)
11674 append_history(p, "RegistryInit", "Account: %s@%s", r->username, r->hostname);
11675
11676
11677 if (!r->us.sin_port && r->portno)
11678 r->us.sin_port = htons(r->portno);
11679
11680
11681 if (create_addr(p, S_OR(r->peername, r->hostname), &r->us, 0)) {
11682
11683
11684 dialog_unlink_all(p, TRUE, TRUE);
11685 p = dialog_unref(p, "unref dialog after unlink_all");
11686 if (r->timeout > -1) {
11687 AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
11688 registry_unref(_data, "del for REPLACE of registry ptr"),
11689 registry_unref(r, "object ptr dec when SCHED_REPLACE add failed"),
11690 registry_addref(r,"add for REPLACE registry ptr"));
11691 ast_log(LOG_WARNING, "Still have a registration timeout for %s@%s (create_addr() error), %d\n", r->username, r->hostname, r->timeout);
11692 } else {
11693 r->timeout = ast_sched_add(sched, global_reg_timeout * 1000, sip_reg_timeout, registry_addref(r, "add for REPLACE registry ptr"));
11694 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);
11695 }
11696 r->regattempts++;
11697 return 0;
11698 }
11699
11700
11701 ast_string_field_set(r, callid, p->callid);
11702 if (!r->dnsmgr && r->portno) {
11703 p->sa.sin_port = htons(r->portno);
11704 p->recv.sin_port = htons(r->portno);
11705 } else {
11706 r->portno = ntohs(p->sa.sin_port);
11707 }
11708 ast_set_flag(&p->flags[0], SIP_OUTGOING);
11709 r->call = dialog_ref(p, "copying dialog into registry r->call");
11710 p->registry = registry_addref(r, "transmit_register: addref to p->registry in transmit_register");
11711 if (!ast_strlen_zero(r->secret)) {
11712 ast_string_field_set(p, peersecret, r->secret);
11713 }
11714 if (!ast_strlen_zero(r->md5secret))
11715 ast_string_field_set(p, peermd5secret, r->md5secret);
11716
11717
11718 if (!ast_strlen_zero(r->authuser)) {
11719 ast_string_field_set(p, peername, r->authuser);
11720 ast_string_field_set(p, authname, r->authuser);
11721 } else if (!ast_strlen_zero(r->username)) {
11722 ast_string_field_set(p, peername, r->username);
11723 ast_string_field_set(p, authname, r->username);
11724 ast_string_field_set(p, fromuser, r->username);
11725 }
11726 if (!ast_strlen_zero(r->username))
11727 ast_string_field_set(p, username, r->username);
11728
11729 if (!ast_strlen_zero(r->callback))
11730 ast_string_field_set(p, exten, r->callback);
11731
11732
11733 set_socket_transport(&p->socket, r->transport);
11734 if (r->transport == SIP_TRANSPORT_TLS || r->transport == SIP_TRANSPORT_TCP) {
11735 p->socket.port = sip_tcp_desc.local_address.sin_port;
11736 }
11737
11738
11739
11740
11741
11742
11743 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
11744 build_contact(p);
11745 }
11746
11747
11748 if (auth == NULL) {
11749 if (r->timeout > -1)
11750 ast_log(LOG_WARNING, "Still have a registration timeout, #%d - deleting it\n", r->timeout);
11751 AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
11752 registry_unref(_data,"reg ptr unrefed from del in SCHED_REPLACE"),
11753 registry_unref(r,"reg ptr unrefed from add failure in SCHED_REPLACE"),
11754 registry_addref(r,"reg ptr reffed from add in SCHED_REPLACE"));
11755 ast_debug(1, "Scheduled a registration timeout for %s id #%d \n", r->hostname, r->timeout);
11756 }
11757
11758 if ((fromdomain = strchr(r->username, '@'))) {
11759
11760 fromdomain++ ;
11761
11762 snprintf(from, sizeof(from), "<sip:%s>;tag=%s", r->username, p->tag);
11763 if (!ast_strlen_zero(p->theirtag))
11764 snprintf(to, sizeof(to), "<sip:%s>;tag=%s", r->username, p->theirtag);
11765 else
11766 snprintf(to, sizeof(to), "<sip:%s>", r->username);
11767
11768
11769
11770 if (ast_strlen_zero(p->fromdomain)) {
11771 ast_string_field_set(p, fromdomain, fromdomain);
11772 }
11773 } else {
11774 snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->tag);
11775 if (!ast_strlen_zero(p->theirtag))
11776 snprintf(to, sizeof(to), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->theirtag);
11777 else
11778 snprintf(to, sizeof(to), "<sip:%s@%s>", r->username, p->tohost);
11779 }
11780
11781
11782
11783 if (!ast_strlen_zero(p->fromdomain)) {
11784 domainport = strrchr(p->fromdomain, ':');
11785 if (domainport) {
11786 *domainport++ = '\0';
11787 if (ast_strlen_zero(domainport))
11788 domainport = NULL;
11789 }
11790 if (domainport) {
11791 if (atoi(domainport) != STANDARD_SIP_PORT)
11792 snprintf(addr, sizeof(addr), "sip:%s:%s", p->fromdomain, domainport);
11793 else
11794 snprintf(addr, sizeof(addr), "sip:%s", p->fromdomain);
11795 } else {
11796 if (r->portno && r->portno != STANDARD_SIP_PORT)
11797 snprintf(addr, sizeof(addr), "sip:%s:%d", p->fromdomain, r->portno);
11798 else
11799 snprintf(addr, sizeof(addr), "sip:%s", p->fromdomain);
11800 }
11801 } else {
11802 if (r->portno && r->portno != STANDARD_SIP_PORT)
11803 snprintf(addr, sizeof(addr), "sip:%s:%d", r->hostname, r->portno);
11804 else
11805 snprintf(addr, sizeof(addr), "sip:%s", r->hostname);
11806 }
11807 ast_string_field_set(p, uri, addr);
11808
11809 p->branch ^= ast_random();
11810
11811 init_req(&req, sipmethod, addr);
11812
11813
11814 snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, sip_methods[sipmethod].text);
11815 p->ocseq = r->ocseq;
11816
11817 build_via(p);
11818 add_header(&req, "Via", p->via);
11819 add_header(&req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
11820 add_header(&req, "From", from);
11821 add_header(&req, "To", to);
11822 add_header(&req, "Call-ID", p->callid);
11823 add_header(&req, "CSeq", tmp);
11824 if (!ast_strlen_zero(global_useragent))
11825 add_header(&req, "User-Agent", global_useragent);
11826
11827
11828 if (auth)
11829 add_header(&req, authheader, auth);
11830 else if (!ast_strlen_zero(r->nonce)) {
11831 char digest[1024];
11832
11833
11834
11835
11836
11837
11838 if (sipdebug)
11839 ast_debug(1, " >>> Re-using Auth data for %s@%s\n", r->username, r->hostname);
11840 ast_string_field_set(p, realm, r->realm);
11841 ast_string_field_set(p, nonce, r->nonce);
11842 ast_string_field_set(p, domain, r->domain);
11843 ast_string_field_set(p, opaque, r->opaque);
11844 ast_string_field_set(p, qop, r->qop);
11845 p->noncecount = ++r->noncecount;
11846
11847 memset(digest, 0, sizeof(digest));
11848 if(!build_reply_digest(p, sipmethod, digest, sizeof(digest)))
11849 add_header(&req, "Authorization", digest);
11850 else
11851 ast_log(LOG_NOTICE, "No authorization available for authentication of registration to %s@%s\n", r->username, r->hostname);
11852
11853 }
11854
11855 snprintf(tmp, sizeof(tmp), "%d", r->expiry);
11856 add_header(&req, "Expires", tmp);
11857 add_header(&req, "Contact", p->our_contact);
11858
11859 initialize_initreq(p, &req);
11860 if (sip_debug_test_pvt(p)) {
11861 ast_verbose("REGISTER %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
11862 }
11863 r->regstate = auth ? REG_STATE_AUTHSENT : REG_STATE_REGSENT;
11864 r->regattempts++;
11865 ast_debug(4, "REGISTER attempt %d to %s@%s\n", r->regattempts, r->username, r->hostname);
11866 res = send_request(p, &req, XMIT_CRITICAL, p->ocseq);
11867 dialog_unref(p, "p is finished here at the end of transmit_register");
11868 return res;
11869 }
11870
11871
11872 static int transmit_message_with_text(struct sip_pvt *p, const char *text)
11873 {
11874 struct sip_request req;
11875
11876 reqprep(&req, p, SIP_MESSAGE, 0, 1);
11877 add_text(&req, text);
11878 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11879 }
11880
11881
11882 static int sip_refer_allocate(struct sip_pvt *p)
11883 {
11884 p->refer = ast_calloc(1, sizeof(struct sip_refer));
11885 return p->refer ? 1 : 0;
11886 }
11887
11888
11889
11890
11891
11892
11893 static int transmit_refer(struct sip_pvt *p, const char *dest)
11894 {
11895 struct sip_request req = {
11896 .headers = 0,
11897 };
11898 char from[256];
11899 const char *of;
11900 char *c;
11901 char referto[256];
11902 char *ttag, *ftag;
11903 char *theirtag = ast_strdupa(p->theirtag);
11904 int use_tls=FALSE;
11905
11906 if (sipdebug)
11907 ast_debug(1, "SIP transfer of %s to %s\n", p->callid, dest);
11908
11909
11910 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
11911 of = get_header(&p->initreq, "To");
11912 ttag = theirtag;
11913 ftag = p->tag;
11914 } else {
11915 of = get_header(&p->initreq, "From");
11916 ftag = theirtag;
11917 ttag = p->tag;
11918 }
11919
11920 ast_copy_string(from, of, sizeof(from));
11921 of = get_in_brackets(from);
11922 ast_string_field_set(p, from, of);
11923 if (!strncasecmp(of, "sip:", 4)) {
11924 of += 4;
11925 }else if (!strncasecmp(of, "sips:", 5)) {
11926 of += 5;
11927 use_tls = TRUE;
11928 } else {
11929 ast_log(LOG_NOTICE, "From address missing 'sip(s):', assuming sip:\n");
11930 }
11931
11932 if ((c = strchr(dest, '@')))
11933 c = NULL;
11934 else if ((c = strchr(of, '@')))
11935 *c++ = '\0';
11936 if (c)
11937 snprintf(referto, sizeof(referto), "<sip%s:%s@%s>", use_tls ? "s" : "", dest, c);
11938 else
11939 snprintf(referto, sizeof(referto), "<sip%s:%s>", use_tls ? "s" : "", dest);
11940
11941
11942 sip_refer_allocate(p);
11943 ast_copy_string(p->refer->refer_to, referto, sizeof(p->refer->refer_to));
11944 ast_copy_string(p->refer->referred_by, p->our_contact, sizeof(p->refer->referred_by));
11945 p->refer->status = REFER_SENT;
11946
11947 reqprep(&req, p, SIP_REFER, 0, 1);
11948
11949 add_header(&req, "Refer-To", referto);
11950 add_header(&req, "Allow", ALLOWED_METHODS);
11951 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
11952 if (!ast_strlen_zero(p->our_contact))
11953 add_header(&req, "Referred-By", p->our_contact);
11954
11955 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965 }
11966
11967
11968
11969 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration)
11970 {
11971 struct sip_request req;
11972
11973 reqprep(&req, p, SIP_INFO, 0, 1);
11974 add_digit(&req, digit, duration, (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_SHORTINFO));
11975 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11976 }
11977
11978
11979 static int transmit_info_with_vidupdate(struct sip_pvt *p)
11980 {
11981 struct sip_request req;
11982
11983 reqprep(&req, p, SIP_INFO, 0, 1);
11984 add_vidupdate(&req);
11985 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11986 }
11987
11988
11989
11990
11991 static int transmit_request(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
11992 {
11993 struct sip_request resp;
11994
11995 if (sipmethod == SIP_ACK)
11996 p->invitestate = INV_CONFIRMED;
11997
11998 reqprep(&resp, p, sipmethod, seqno, newbranch);
11999 if (sipmethod == SIP_CANCEL && p->answered_elsewhere)
12000 add_header(&resp, "Reason", "SIP;cause=200;text=\"Call completed elsewhere\"");
12001
12002 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
12003 }
12004
12005
12006 static void auth_headers(enum sip_auth_type code, char **header, char **respheader)
12007 {
12008 if (code == WWW_AUTH) {
12009 *header = "WWW-Authenticate";
12010 *respheader = "Authorization";
12011 } else if (code == PROXY_AUTH) {
12012 *header = "Proxy-Authenticate";
12013 *respheader = "Proxy-Authorization";
12014 } else {
12015 ast_verbose("-- wrong response code %d\n", code);
12016 *header = *respheader = "Invalid";
12017 }
12018 }
12019
12020
12021 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
12022 {
12023 struct sip_request resp;
12024
12025 reqprep(&resp, p, sipmethod, seqno, newbranch);
12026 if (!ast_strlen_zero(p->realm)) {
12027 char digest[1024];
12028
12029 memset(digest, 0, sizeof(digest));
12030 if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
12031 char *dummy, *response;
12032 enum sip_auth_type code = p->options ? p->options->auth_type : PROXY_AUTH;
12033 auth_headers(code, &dummy, &response);
12034 add_header(&resp, response, digest);
12035 } else
12036 ast_log(LOG_WARNING, "No authentication available for call %s\n", p->callid);
12037 }
12038
12039
12040 if (sipmethod == SIP_BYE) {
12041 char buf[10];
12042
12043 add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->hangupcause));
12044 snprintf(buf, sizeof(buf), "%d", p->hangupcause);
12045 add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
12046 }
12047
12048 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
12049 }
12050
12051
12052 static void destroy_association(struct sip_peer *peer)
12053 {
12054 int realtimeregs = ast_check_realtime("sipregs");
12055 char *tablename = (realtimeregs) ? "sipregs" : "sippeers";
12056
12057 if (!sip_cfg.ignore_regexpire) {
12058 if (peer->rt_fromcontact && sip_cfg.peer_rtupdate) {
12059 ast_update_realtime(tablename, "name", peer->name, "fullcontact", "", "ipaddr", "", "port", "", "regseconds", "0", peer->deprecated_username ? "username" : "defaultuser", "", "regserver", "", "useragent", "", "lastms", "", SENTINEL);
12060 } else {
12061 ast_db_del("SIP/Registry", peer->name);
12062 }
12063 }
12064 }
12065
12066 static void set_socket_transport(struct sip_socket *socket, int transport)
12067 {
12068
12069 if (socket->type != transport) {
12070 socket->fd = -1;
12071 socket->type = transport;
12072 if (socket->tcptls_session) {
12073 ao2_ref(socket->tcptls_session, -1);
12074 socket->tcptls_session = NULL;
12075 }
12076 }
12077 }
12078
12079
12080 static int expire_register(const void *data)
12081 {
12082 struct sip_peer *peer = (struct sip_peer *)data;
12083
12084 if (!peer)
12085 return 0;
12086
12087 peer->expire = -1;
12088 peer->portinuri = 0;
12089 memset(&peer->addr, 0, sizeof(peer->addr));
12090
12091 destroy_association(peer);
12092 set_socket_transport(&peer->socket, peer->default_outbound_transport);
12093
12094 if (peer->socket.tcptls_session) {
12095 ao2_ref(peer->socket.tcptls_session, -1);
12096 peer->socket.tcptls_session = NULL;
12097 }
12098
12099 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
12100 register_peer_exten(peer, FALSE);
12101 ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
12102
12103
12104
12105
12106 if (peer->is_realtime)
12107 ast_debug(3, "-REALTIME- peer expired registration. Name: %s. Realtime peer objects now %d\n", peer->name, rpeerobjs);
12108
12109 if (peer->selfdestruct ||
12110 ast_test_flag(&peer->flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
12111 ao2_t_unlink(peers, peer, "ao2_unlink of peer from peers table");
12112 if (peer->addr.sin_addr.s_addr) {
12113 ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
12114 }
12115 }
12116
12117 unref_peer(peer, "removing peer ref for expire_register");
12118
12119 return 0;
12120 }
12121
12122
12123 static int sip_poke_peer_s(const void *data)
12124 {
12125 struct sip_peer *peer = (struct sip_peer *)data;
12126
12127 peer->pokeexpire = -1;
12128
12129 sip_poke_peer(peer, 0);
12130
12131 unref_peer(peer, "removing poke peer ref");
12132
12133 return 0;
12134 }
12135
12136
12137 static void reg_source_db(struct sip_peer *peer)
12138 {
12139 char data[256];
12140 struct in_addr in;
12141 int expire;
12142 int port;
12143 char *scan, *addr, *port_str, *expiry_str, *username, *contact;
12144
12145 if (peer->rt_fromcontact)
12146 return;
12147 if (ast_db_get("SIP/Registry", peer->name, data, sizeof(data)))
12148 return;
12149
12150 scan = data;
12151 addr = strsep(&scan, ":");
12152 port_str = strsep(&scan, ":");
12153 expiry_str = strsep(&scan, ":");
12154 username = strsep(&scan, ":");
12155 contact = scan;
12156
12157 if (!inet_aton(addr, &in))
12158 return;
12159
12160 if (port_str)
12161 port = atoi(port_str);
12162 else
12163 return;
12164
12165 if (expiry_str)
12166 expire = atoi(expiry_str);
12167 else
12168 return;
12169
12170 if (username)
12171 ast_string_field_set(peer, username, username);
12172 if (contact)
12173 ast_string_field_set(peer, fullcontact, contact);
12174
12175 ast_debug(2, "SIP Seeding peer from astdb: '%s' at %s@%s:%d for %d\n",
12176 peer->name, peer->username, ast_inet_ntoa(in), port, expire);
12177
12178 memset(&peer->addr, 0, sizeof(peer->addr));
12179 peer->addr.sin_family = AF_INET;
12180 peer->addr.sin_addr = in;
12181 peer->addr.sin_port = htons(port);
12182 if (sipsock < 0) {
12183
12184 AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, ast_random() % 5000 + 1, sip_poke_peer_s, peer,
12185 unref_peer(_data, "removing poke peer ref"),
12186 unref_peer(peer, "removing poke peer ref"),
12187 ref_peer(peer, "adding poke peer ref"));
12188 } else {
12189 sip_poke_peer(peer, 0);
12190 }
12191 AST_SCHED_REPLACE_UNREF(peer->expire, sched, (expire + 10) * 1000, expire_register, peer,
12192 unref_peer(_data, "remove registration ref"),
12193 unref_peer(peer, "remove registration ref"),
12194 ref_peer(peer, "add registration ref"));
12195 register_peer_exten(peer, TRUE);
12196 }
12197
12198
12199 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req)
12200 {
12201 char contact[SIPBUFSIZE];
12202 char *c;
12203
12204
12205 ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
12206 c = get_in_brackets(contact);
12207
12208
12209 ast_string_field_set(pvt, fullcontact, c);
12210
12211
12212 ast_string_field_set(pvt, okcontacturi, c);
12213
12214
12215
12216 return TRUE;
12217 }
12218
12219 static int __set_address_from_contact(const char *fullcontact, struct sockaddr_in *sin, int tcp)
12220 {
12221 struct hostent *hp;
12222 struct ast_hostent ahp;
12223 int port = STANDARD_SIP_PORT;
12224 char *host, *pt, *transport;
12225 char contact_buf[256];
12226 char *contact;
12227
12228
12229 ast_copy_string(contact_buf, fullcontact, sizeof(contact_buf));
12230 contact = contact_buf;
12231
12232
12233
12234
12235
12236
12237
12238
12239 if (parse_uri(contact, "sip:,sips:", &contact, NULL, &host, &pt, NULL, &transport)) {
12240 ast_log(LOG_WARNING, "Invalid contact uri %s (missing sip: or sips:), attempting to use anyway\n", fullcontact);
12241 }
12242
12243
12244 if (((get_transport_str2enum(transport) == SIP_TRANSPORT_TLS)) || !(strncasecmp(fullcontact, "sips", 4))) {
12245 port = port_str2int(pt, STANDARD_TLS_PORT);
12246 } else {
12247 port = port_str2int(pt, STANDARD_SIP_PORT);
12248 }
12249
12250
12251
12252
12253
12254
12255
12256
12257 hp = ast_gethostbyname(host, &ahp);
12258 if (!hp) {
12259 ast_log(LOG_WARNING, "Invalid host name in Contact: (can't resolve in DNS) : '%s'\n", host);
12260 return -1;
12261 }
12262 sin->sin_family = AF_INET;
12263 memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
12264 sin->sin_port = htons(port);
12265
12266 return 0;
12267 }
12268
12269
12270 static int set_address_from_contact(struct sip_pvt *pvt)
12271 {
12272 if (ast_test_flag(&pvt->flags[0], SIP_NAT_ROUTE)) {
12273
12274
12275
12276 pvt->sa = pvt->recv;
12277 return 0;
12278 }
12279
12280 return __set_address_from_contact(pvt->fullcontact, &pvt->sa, pvt->socket.type == SIP_TRANSPORT_TLS ? 1 : 0);
12281 }
12282
12283
12284 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *peer, struct sip_request *req)
12285 {
12286 char contact[SIPBUFSIZE];
12287 char data[SIPBUFSIZE];
12288 const char *expires = get_header(req, "Expires");
12289 int expire = atoi(expires);
12290 char *curi, *host, *pt, *transport;
12291 int port;
12292 int transport_type;
12293 const char *useragent;
12294 struct hostent *hp;
12295 struct ast_hostent ahp;
12296 struct sockaddr_in oldsin, testsin;
12297
12298
12299 ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
12300
12301 if (ast_strlen_zero(expires)) {
12302 char *s = strcasestr(contact, ";expires=");
12303 if (s) {
12304 expires = strsep(&s, ";");
12305 if (sscanf(expires + 9, "%30d", &expire) != 1)
12306 expire = default_expiry;
12307 } else {
12308
12309 expire = default_expiry;
12310 }
12311 }
12312
12313 copy_socket_data(&pvt->socket, &req->socket);
12314
12315
12316 curi = contact;
12317 if (strchr(contact, '<') == NULL)
12318 strsep(&curi, ";");
12319 curi = get_in_brackets(contact);
12320
12321
12322
12323
12324
12325 if (ast_strlen_zero(curi) && ast_strlen_zero(expires)) {
12326
12327 if (peer->expire > -1 && !ast_strlen_zero(peer->fullcontact))
12328 pvt->expiry = ast_sched_when(sched, peer->expire);
12329 return PARSE_REGISTER_QUERY;
12330 } else if (!strcasecmp(curi, "*") || !expire) {
12331
12332 memset(&peer->addr, 0, sizeof(peer->addr));
12333 set_socket_transport(&peer->socket, peer->default_outbound_transport);
12334
12335 AST_SCHED_DEL_UNREF(sched, peer->expire,
12336 unref_peer(peer, "remove register expire ref"));
12337
12338 destroy_association(peer);
12339
12340 register_peer_exten(peer, FALSE);
12341 ast_string_field_set(peer, fullcontact, "");
12342 ast_string_field_set(peer, useragent, "");
12343 peer->sipoptions = 0;
12344 peer->lastms = 0;
12345 peer->portinuri = 0;
12346 pvt->expiry = 0;
12347
12348 ast_verb(3, "Unregistered SIP '%s'\n", peer->name);
12349
12350 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unregistered\r\n", peer->name);
12351 return PARSE_REGISTER_UPDATE;
12352 }
12353
12354
12355 ast_string_field_set(peer, fullcontact, curi);
12356
12357
12358 ast_string_field_build(pvt, our_contact, "<%s>", curi);
12359
12360
12361 if (parse_uri(curi, "sip:,sips:", &curi, NULL, &host, &pt, NULL, &transport)) {
12362 ast_log(LOG_NOTICE, "Not a valid SIP contact (missing sip:) trying to use anyway\n");
12363 }
12364
12365
12366
12367 peer->portinuri = !ast_strlen_zero(pt) ? TRUE : FALSE;
12368
12369
12370 if ((transport_type = get_transport_str2enum(transport))) {
12371
12372
12373
12374
12375 port = port_str2int(pt, (transport_type == SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT);
12376 } else {
12377 port = port_str2int(pt, STANDARD_SIP_PORT);
12378 transport_type = pvt->socket.type;
12379 }
12380
12381
12382
12383
12384 if ((peer->socket.type != transport_type) && (peer->transports & transport_type)) {
12385 set_socket_transport(&peer->socket, transport_type);
12386 }
12387
12388 oldsin = peer->addr;
12389
12390
12391 if (peer->addr.sin_addr.s_addr) {
12392 ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
12393 }
12394
12395 if (!ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE)) {
12396
12397 ast_debug(1, "Store REGISTER's Contact header for call routing.\n");
12398
12399
12400 hp = ast_gethostbyname(host, &ahp);
12401 if (!hp) {
12402 ast_log(LOG_WARNING, "Invalid host '%s'\n", host);
12403 ast_string_field_set(peer, fullcontact, "");
12404 ast_string_field_set(pvt, our_contact, "");
12405 return PARSE_REGISTER_FAILED;
12406 }
12407 peer->addr.sin_family = AF_INET;
12408 memcpy(&peer->addr.sin_addr, hp->h_addr, sizeof(peer->addr.sin_addr));
12409 peer->addr.sin_port = htons(port);
12410 } else {
12411
12412
12413 ast_debug(1, "Store REGISTER's src-IP:port for call routing.\n");
12414 peer->addr = pvt->recv;
12415 }
12416
12417
12418 memcpy(&testsin.sin_addr, &peer->addr.sin_addr, sizeof(testsin.sin_addr));
12419 if (ast_apply_ha(global_contact_ha, &testsin) != AST_SENSE_ALLOW ||
12420 ast_apply_ha(peer->contactha, &testsin) != AST_SENSE_ALLOW) {
12421 ast_log(LOG_WARNING, "Host '%s' disallowed by contact ACL (violating IP %s)\n", host, ast_inet_ntoa(testsin.sin_addr));
12422 ast_string_field_set(peer, fullcontact, "");
12423 ast_string_field_set(pvt, our_contact, "");
12424 return PARSE_REGISTER_DENIED;
12425 }
12426
12427
12428
12429
12430 if ((peer->socket.type == pvt->socket.type) &&
12431 (peer->addr.sin_addr.s_addr == pvt->recv.sin_addr.s_addr) &&
12432 (peer->addr.sin_port == pvt->recv.sin_port)){
12433
12434 copy_socket_data(&peer->socket, &pvt->socket);
12435 }
12436
12437
12438 ao2_t_link(peers_by_ip, peer, "ao2_link into peers_by_ip table");
12439
12440
12441 peer->sipoptions = pvt->sipoptions;
12442
12443 if (!ast_strlen_zero(curi) && ast_strlen_zero(peer->username))
12444 ast_string_field_set(peer, username, curi);
12445
12446 AST_SCHED_DEL_UNREF(sched, peer->expire,
12447 unref_peer(peer, "remove register expire ref"));
12448
12449 if (expire > max_expiry)
12450 expire = max_expiry;
12451 if (expire < min_expiry)
12452 expire = min_expiry;
12453 if (peer->is_realtime && !ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
12454 peer->expire = -1;
12455 } else {
12456 peer->expire = ast_sched_add(sched, (expire + 10) * 1000, expire_register,
12457 ref_peer(peer, "add registration ref"));
12458 if (peer->expire == -1) {
12459 unref_peer(peer, "remote registration ref");
12460 }
12461 }
12462 pvt->expiry = expire;
12463 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);
12464
12465
12466
12467
12468 if (!peer->rt_fromcontact && (peer->socket.type & SIP_TRANSPORT_UDP))
12469 ast_db_put("SIP/Registry", peer->name, data);
12470 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));
12471
12472
12473 if (VERBOSITY_ATLEAST(2) && inaddrcmp(&peer->addr, &oldsin)) {
12474 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));
12475 }
12476 sip_poke_peer(peer, 0);
12477 register_peer_exten(peer, 1);
12478
12479
12480 useragent = get_header(req, "User-Agent");
12481 if (strcasecmp(useragent, peer->useragent)) {
12482 ast_string_field_set(peer, useragent, useragent);
12483 ast_verb(4, "Saved useragent \"%s\" for peer %s\n", peer->useragent, peer->name);
12484 }
12485 return PARSE_REGISTER_UPDATE;
12486 }
12487
12488
12489 static void free_old_route(struct sip_route *route)
12490 {
12491 struct sip_route *next;
12492
12493 while (route) {
12494 next = route->next;
12495 ast_free(route);
12496 route = next;
12497 }
12498 }
12499
12500
12501 static void list_route(struct sip_route *route)
12502 {
12503 if (!route)
12504 ast_verbose("list_route: no route\n");
12505 else {
12506 for (;route; route = route->next)
12507 ast_verbose("list_route: hop: <%s>\n", route->hop);
12508 }
12509 }
12510
12511
12512 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards)
12513 {
12514 struct sip_route *thishop, *head, *tail;
12515 int start = 0;
12516 int len;
12517 const char *rr, *contact, *c;
12518
12519
12520 if (p->route && p->route_persistant) {
12521 ast_debug(1, "build_route: Retaining previous route: <%s>\n", p->route->hop);
12522 return;
12523 }
12524
12525 if (p->route) {
12526 free_old_route(p->route);
12527 p->route = NULL;
12528 }
12529
12530
12531 p->route_persistant = 1;
12532
12533
12534
12535
12536
12537
12538 head = NULL;
12539 tail = head;
12540
12541 for (;;) {
12542
12543 rr = __get_header(req, "Record-Route", &start);
12544 if (*rr == '\0')
12545 break;
12546 for (; (rr = strchr(rr, '<')) ; rr += len) {
12547 ++rr;
12548 len = strcspn(rr, ">") + 1;
12549
12550 if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
12551
12552 ast_copy_string(thishop->hop, rr, len);
12553 ast_debug(2, "build_route: Record-Route hop: <%s>\n", thishop->hop);
12554
12555 if (backwards) {
12556
12557 thishop->next = head;
12558 head = thishop;
12559
12560 if (!tail)
12561 tail = thishop;
12562 } else {
12563 thishop->next = NULL;
12564
12565 if (tail)
12566 tail->next = thishop;
12567 else
12568 head = thishop;
12569 tail = thishop;
12570 }
12571 }
12572 }
12573 }
12574
12575
12576 if (!head || (!ast_strlen_zero(head->hop) && strstr(head->hop, ";lr") == NULL) ) {
12577
12578
12579 contact = get_header(req, "Contact");
12580 if (!ast_strlen_zero(contact)) {
12581 ast_debug(2, "build_route: Contact hop: %s\n", contact);
12582
12583 c = strchr(contact, '<');
12584 if (c) {
12585
12586 ++c;
12587 len = strcspn(c, ">") + 1;
12588 } else {
12589
12590 c = contact;
12591 len = strlen(contact) + 1;
12592 }
12593 if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
12594
12595 ast_copy_string(thishop->hop, c, len);
12596 thishop->next = NULL;
12597
12598 if (tail)
12599 tail->next = thishop;
12600 else
12601 head = thishop;
12602 }
12603 }
12604 }
12605
12606
12607 p->route = head;
12608
12609
12610 if (sip_debug_test_pvt(p))
12611 list_route(p->route);
12612 }
12613
12614
12615
12616
12617
12618
12619
12620 static void set_nonce_randdata(struct sip_pvt *p, int forceupdate)
12621 {
12622 if (p->stalenonce || forceupdate || ast_strlen_zero(p->randdata)) {
12623 ast_string_field_build(p, randdata, "%08lx", ast_random());
12624 p->stalenonce = 0;
12625 }
12626 }
12627
12628 AST_THREADSTORAGE(check_auth_buf);
12629 #define CHECK_AUTH_BUF_INITLEN 256
12630
12631
12632
12633
12634
12635
12636 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
12637 const char *secret, const char *md5secret, int sipmethod,
12638 char *uri, enum xmittype reliable, int ignore)
12639 {
12640 const char *response;
12641 char *reqheader, *respheader;
12642 const char *authtoken;
12643 char a1_hash[256];
12644 char resp_hash[256]="";
12645 char *c;
12646 int wrongnonce = FALSE;
12647 int good_response;
12648 const char *usednonce = p->randdata;
12649 struct ast_str *buf;
12650 int res;
12651
12652
12653 enum keys { K_RESP, K_URI, K_USER, K_NONCE, K_LAST };
12654 struct x {
12655 const char *key;
12656 const char *s;
12657 } *i, keys[] = {
12658 [K_RESP] = { "response=", "" },
12659 [K_URI] = { "uri=", "" },
12660 [K_USER] = { "username=", "" },
12661 [K_NONCE] = { "nonce=", "" },
12662 [K_LAST] = { NULL, NULL}
12663 };
12664
12665
12666 if (ast_strlen_zero(secret) && ast_strlen_zero(md5secret))
12667 return AUTH_SUCCESSFUL;
12668
12669
12670
12671 response = "401 Unauthorized";
12672
12673
12674
12675
12676
12677 auth_headers(WWW_AUTH, &respheader, &reqheader);
12678
12679 authtoken = get_header(req, reqheader);
12680 if (ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
12681
12682
12683 if (!reliable) {
12684
12685
12686 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
12687
12688 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12689 }
12690 return AUTH_CHALLENGE_SENT;
12691 } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
12692
12693 set_nonce_randdata(p, 1);
12694 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
12695
12696 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12697 return AUTH_CHALLENGE_SENT;
12698 }
12699
12700
12701
12702
12703
12704
12705 if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN)))
12706 return AUTH_SECRET_FAILED;
12707
12708
12709 res = ast_str_set(&buf, 0, "%s", authtoken);
12710
12711 if (res == AST_DYNSTR_BUILD_FAILED)
12712 return AUTH_SECRET_FAILED;
12713
12714 c = buf->str;
12715
12716 while(c && *(c = ast_skip_blanks(c)) ) {
12717 for (i = keys; i->key != NULL; i++) {
12718 const char *separator = ",";
12719
12720 if (strncasecmp(c, i->key, strlen(i->key)) != 0)
12721 continue;
12722
12723 c += strlen(i->key);
12724 if (*c == '"') {
12725 c++;
12726 separator = "\"";
12727 }
12728 i->s = c;
12729 strsep(&c, separator);
12730 break;
12731 }
12732 if (i->key == NULL)
12733 strsep(&c, " ,");
12734 }
12735
12736
12737 if (strcmp(username, keys[K_USER].s)) {
12738 ast_log(LOG_WARNING, "username mismatch, have <%s>, digest has <%s>\n",
12739 username, keys[K_USER].s);
12740
12741 return AUTH_USERNAME_MISMATCH;
12742 }
12743
12744
12745
12746 if (strcasecmp(p->randdata, keys[K_NONCE].s) || p->stalenonce) {
12747 wrongnonce = TRUE;
12748 usednonce = keys[K_NONCE].s;
12749 } else {
12750 p->stalenonce = 1;
12751 }
12752
12753 if (!ast_strlen_zero(md5secret))
12754 ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
12755 else {
12756 char a1[256];
12757 snprintf(a1, sizeof(a1), "%s:%s:%s", username, sip_cfg.realm, secret);
12758 ast_md5_hash(a1_hash, a1);
12759 }
12760
12761
12762 {
12763 char a2[256];
12764 char a2_hash[256];
12765 char resp[256];
12766
12767 snprintf(a2, sizeof(a2), "%s:%s", sip_methods[sipmethod].text,
12768 S_OR(keys[K_URI].s, uri));
12769 ast_md5_hash(a2_hash, a2);
12770 snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, usednonce, a2_hash);
12771 ast_md5_hash(resp_hash, resp);
12772 }
12773
12774 good_response = keys[K_RESP].s &&
12775 !strncasecmp(keys[K_RESP].s, resp_hash, strlen(resp_hash));
12776 if (wrongnonce) {
12777 if (good_response) {
12778 if (sipdebug)
12779 ast_log(LOG_NOTICE, "Correct auth, but based on stale nonce received from '%s'\n", get_header(req, "From"));
12780
12781 set_nonce_randdata(p, 0);
12782 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, TRUE);
12783 } else {
12784
12785 if (!req->ignore) {
12786 if (sipdebug)
12787 ast_log(LOG_NOTICE, "Bad authentication received from '%s'\n", get_header(req, "To"));
12788 set_nonce_randdata(p, 1);
12789 } else {
12790 if (sipdebug)
12791 ast_log(LOG_NOTICE, "Duplicate authentication received from '%s'\n", get_header(req, "To"));
12792 }
12793 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
12794 }
12795
12796
12797 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12798 return AUTH_CHALLENGE_SENT;
12799 }
12800 if (good_response) {
12801 append_history(p, "AuthOK", "Auth challenge successful for %s", username);
12802 return AUTH_SUCCESSFUL;
12803 }
12804
12805
12806
12807
12808
12809
12810 return AUTH_SECRET_FAILED;
12811 }
12812
12813
12814 static void sip_peer_hold(struct sip_pvt *p, int hold)
12815 {
12816 struct sip_peer *peer = find_peer(p->peername, NULL, 1, FINDALLDEVICES, FALSE, 0);
12817
12818 if (!peer)
12819 return;
12820
12821
12822 ast_atomic_fetchadd_int(&peer->onHold, (hold ? +1 : -1));
12823
12824
12825 ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
12826 unref_peer(peer, "sip_peer_hold: from find_peer operation");
12827
12828 return;
12829 }
12830
12831
12832 static void mwi_event_cb(const struct ast_event *event, void *userdata)
12833 {
12834 struct sip_peer *peer = userdata;
12835
12836 ao2_lock(peer);
12837 sip_send_mwi_to_peer(peer, event, 0);
12838 ao2_unlock(peer);
12839 }
12840
12841
12842
12843
12844 static int cb_extensionstate(char *context, char* exten, int state, void *data)
12845 {
12846 struct sip_pvt *p = data;
12847
12848 sip_pvt_lock(p);
12849
12850 switch(state) {
12851 case AST_EXTENSION_DEACTIVATED:
12852 case AST_EXTENSION_REMOVED:
12853 if (p->autokillid > -1 && sip_cancel_destroy(p))
12854 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
12855 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12856 ast_verb(2, "Extension state: Watcher for hint %s %s. Notify User %s\n", exten, state == AST_EXTENSION_DEACTIVATED ? "deactivated" : "removed", p->username);
12857 p->stateid = -1;
12858 p->subscribed = NONE;
12859 append_history(p, "Subscribestatus", "%s", state == AST_EXTENSION_REMOVED ? "HintRemoved" : "Deactivated");
12860 break;
12861 default:
12862 p->laststate = state;
12863 break;
12864 }
12865 if (p->subscribed != NONE) {
12866 if (!p->pendinginvite) {
12867 transmit_state_notify(p, state, 1, FALSE);
12868 } else {
12869
12870
12871 ast_set_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
12872 }
12873 }
12874 ast_verb(2, "Extension Changed %s[%s] new state %s for Notify User %s %s\n", exten, context, ast_extension_state2str(state), p->username,
12875 ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE) ? "(queued)" : "");
12876
12877 sip_pvt_unlock(p);
12878
12879 return 0;
12880 }
12881
12882
12883
12884
12885 static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable)
12886 {
12887
12888
12889 const char *response = "407 Proxy Authentication Required";
12890 const char *reqheader = "Proxy-Authorization";
12891 const char *respheader = "Proxy-Authenticate";
12892 const char *authtoken;
12893 struct ast_str *buf;
12894 char *c;
12895
12896
12897 enum keys { K_NONCE, K_LAST };
12898 struct x {
12899 const char *key;
12900 const char *s;
12901 } *i, keys[] = {
12902 [K_NONCE] = { "nonce=", "" },
12903 [K_LAST] = { NULL, NULL}
12904 };
12905
12906 if (sipmethod == SIP_REGISTER || sipmethod == SIP_SUBSCRIBE) {
12907 response = "401 Unauthorized";
12908 reqheader = "Authorization";
12909 respheader = "WWW-Authenticate";
12910 }
12911 authtoken = get_header(req, reqheader);
12912 if (req->ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
12913
12914
12915 transmit_response_with_auth(p, response, req, p->randdata, 0, respheader, 0);
12916
12917 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12918 return;
12919 } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
12920
12921 set_nonce_randdata(p, 1);
12922 transmit_response_with_auth(p, response, req, p->randdata, 0, respheader, 0);
12923
12924 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12925 return;
12926 }
12927
12928 if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN))) {
12929 transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
12930 return;
12931 }
12932
12933
12934 if (ast_str_set(&buf, 0, "%s", authtoken) == AST_DYNSTR_BUILD_FAILED) {
12935 transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
12936 return;
12937 }
12938
12939 c = buf->str;
12940
12941 while (c && *(c = ast_skip_blanks(c))) {
12942 for (i = keys; i->key != NULL; i++) {
12943 const char *separator = ",";
12944
12945 if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
12946 continue;
12947 }
12948
12949 c += strlen(i->key);
12950 if (*c == '"') {
12951 c++;
12952 separator = "\"";
12953 }
12954 i->s = c;
12955 strsep(&c, separator);
12956 break;
12957 }
12958 if (i->key == NULL) {
12959 strsep(&c, " ,");
12960 }
12961 }
12962
12963
12964 if (strcasecmp(p->randdata, keys[K_NONCE].s)) {
12965 if (!req->ignore) {
12966 set_nonce_randdata(p, 1);
12967 }
12968 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
12969
12970
12971 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12972 } else {
12973 transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
12974 }
12975 }
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991 static char *terminate_uri(char *uri)
12992 {
12993 char *t = uri;
12994 while (*t && *t > ' ' && *t != ';')
12995 t++;
12996 *t = '\0';
12997 return uri;
12998 }
12999
13000
13001
13002
13003
13004
13005 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
13006 struct sip_request *req, char *uri)
13007 {
13008 enum check_auth_result res = AUTH_NOT_FOUND;
13009 struct sip_peer *peer;
13010 char tmp[256];
13011 char *name, *c;
13012 char *domain;
13013
13014 terminate_uri(uri);
13015
13016 ast_copy_string(tmp, get_header(req, "To"), sizeof(tmp));
13017 if (sip_cfg.pedanticsipchecking)
13018 ast_uri_decode(tmp);
13019
13020 c = get_in_brackets(tmp);
13021 c = remove_uri_parameters(c);
13022
13023 if (!strncasecmp(c, "sip:", 4)) {
13024 name = c + 4;
13025 } else if (!strncasecmp(c, "sips:", 5)) {
13026 name = c + 5;
13027 } else {
13028 name = c;
13029 ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, ast_inet_ntoa(sin->sin_addr));
13030 }
13031
13032
13033
13034
13035
13036 if ((c = strchr(name, '@'))) {
13037 *c++ = '\0';
13038 domain = c;
13039 if ((c = strchr(domain, ':')))
13040 *c = '\0';
13041 if (!AST_LIST_EMPTY(&domain_list)) {
13042 if (!check_sip_domain(domain, NULL, 0)) {
13043 transmit_response(p, "404 Not found (unknown domain)", &p->initreq);
13044 return AUTH_UNKNOWN_DOMAIN;
13045 }
13046 }
13047 }
13048 c = strchr(name, ';');
13049 if (c)
13050 *c = '\0';
13051
13052 ast_string_field_set(p, exten, name);
13053 build_contact(p);
13054 if (req->ignore) {
13055
13056 const char *expires = get_header(req, "Expires");
13057 int expire = atoi(expires);
13058
13059 if (ast_strlen_zero(expires)) {
13060 if ((expires = strcasestr(get_header(req, "Contact"), ";expires="))) {
13061 expire = atoi(expires + 9);
13062 }
13063 }
13064 if (!ast_strlen_zero(expires) && expire == 0) {
13065 transmit_response_with_date(p, "200 OK", req);
13066 return 0;
13067 }
13068 }
13069 peer = find_peer(name, NULL, TRUE, FINDPEERS, FALSE, 0);
13070 if (!(peer && ast_apply_ha(peer->ha, sin))) {
13071
13072 if (peer) {
13073 unref_peer(peer, "register_verify: unref_peer: from find_peer operation");
13074 peer = NULL;
13075 res = AUTH_ACL_FAILED;
13076 } else
13077 res = AUTH_NOT_FOUND;
13078 }
13079
13080 if (peer) {
13081
13082
13083 if (p->rtp) {
13084 ast_rtp_codec_setpref(p->rtp, &peer->prefs);
13085 p->autoframing = peer->autoframing;
13086 }
13087 if (!peer->host_dynamic) {
13088 ast_log(LOG_ERROR, "Peer '%s' is trying to register, but not configured as host=dynamic\n", peer->name);
13089 res = AUTH_PEER_NOT_DYNAMIC;
13090 } else {
13091 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_NAT);
13092 if (ast_test_flag(&p->flags[1], SIP_PAGE2_REGISTERTRYING))
13093 transmit_response(p, "100 Trying", req);
13094 if (!(res = check_auth(p, req, peer->name, peer->secret, peer->md5secret, SIP_REGISTER, uri, XMIT_UNRELIABLE, req->ignore))) {
13095 if (sip_cancel_destroy(p))
13096 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
13097
13098 if (check_request_transport(peer, req)) {
13099 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
13100 transmit_response_with_date(p, "403 Forbidden", req);
13101 res = AUTH_BAD_TRANSPORT;
13102 } else {
13103
13104
13105
13106 switch (parse_register_contact(p, peer, req)) {
13107 case PARSE_REGISTER_DENIED:
13108 ast_log(LOG_WARNING, "Registration denied because of contact ACL\n");
13109 transmit_response_with_date(p, "603 Denied", req);
13110 peer->lastmsgssent = -1;
13111 res = 0;
13112 break;
13113 case PARSE_REGISTER_FAILED:
13114 ast_log(LOG_WARNING, "Failed to parse contact info\n");
13115 transmit_response_with_date(p, "400 Bad Request", req);
13116 peer->lastmsgssent = -1;
13117 res = 0;
13118 break;
13119 case PARSE_REGISTER_QUERY:
13120 ast_string_field_set(p, fullcontact, peer->fullcontact);
13121 transmit_response_with_date(p, "200 OK", req);
13122 peer->lastmsgssent = -1;
13123 res = 0;
13124 break;
13125 case PARSE_REGISTER_UPDATE:
13126 ast_string_field_set(p, fullcontact, peer->fullcontact);
13127 update_peer(peer, p->expiry);
13128
13129 transmit_response_with_date(p, "200 OK", req);
13130 if (!ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY))
13131 peer->lastmsgssent = -1;
13132 res = 0;
13133 break;
13134 }
13135 }
13136
13137 }
13138 }
13139 }
13140 if (!peer && sip_cfg.autocreatepeer) {
13141
13142 peer = temp_peer(name);
13143 if (peer) {
13144 ao2_t_link(peers, peer, "link peer into peer table");
13145 if (peer->addr.sin_addr.s_addr) {
13146 ao2_t_link(peers_by_ip, peer, "link peer into peers-by-ip table");
13147 }
13148
13149 if (sip_cancel_destroy(p))
13150 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
13151 switch (parse_register_contact(p, peer, req)) {
13152 case PARSE_REGISTER_DENIED:
13153 ast_log(LOG_WARNING, "Registration denied because of contact ACL\n");
13154 transmit_response_with_date(p, "403 Forbidden (ACL)", req);
13155 peer->lastmsgssent = -1;
13156 res = 0;
13157 break;
13158 case PARSE_REGISTER_FAILED:
13159 ast_log(LOG_WARNING, "Failed to parse contact info\n");
13160 transmit_response_with_date(p, "400 Bad Request", req);
13161 peer->lastmsgssent = -1;
13162 res = 0;
13163 break;
13164 case PARSE_REGISTER_QUERY:
13165 ast_string_field_set(p, fullcontact, peer->fullcontact);
13166 transmit_response_with_date(p, "200 OK", req);
13167 peer->lastmsgssent = -1;
13168 res = 0;
13169 break;
13170 case PARSE_REGISTER_UPDATE:
13171 ast_string_field_set(p, fullcontact, peer->fullcontact);
13172
13173 transmit_response_with_date(p, "200 OK", req);
13174 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));
13175 peer->lastmsgssent = -1;
13176 res = 0;
13177 break;
13178 }
13179 }
13180 }
13181 if (!peer && sip_cfg.alwaysauthreject) {
13182
13183
13184
13185 transmit_response(p, "100 Trying", req);
13186
13187 sched_yield();
13188 }
13189 if (!res) {
13190 ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
13191 }
13192 if (res < 0) {
13193 switch (res) {
13194 case AUTH_SECRET_FAILED:
13195
13196 transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
13197 if (global_authfailureevents)
13198 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",
13199 name, ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
13200 break;
13201 case AUTH_USERNAME_MISMATCH:
13202
13203
13204
13205
13206 case AUTH_NOT_FOUND:
13207 case AUTH_PEER_NOT_DYNAMIC:
13208 case AUTH_ACL_FAILED:
13209 if (sip_cfg.alwaysauthreject) {
13210 transmit_fake_auth_response(p, SIP_REGISTER, &p->initreq, XMIT_UNRELIABLE);
13211 if (global_authfailureevents) {
13212 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",
13213 name, res == AUTH_PEER_NOT_DYNAMIC ? "AUTH_PEER_NOT_DYNAMIC" : "URI_NOT_FOUND",
13214 ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
13215 }
13216 } else {
13217
13218 if (res == AUTH_PEER_NOT_DYNAMIC) {
13219 transmit_response(p, "403 Forbidden", &p->initreq);
13220 if (global_authfailureevents) {
13221 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
13222 "ChannelType: SIP\r\n"
13223 "Peer: SIP/%s\r\n"
13224 "PeerStatus: Rejected\r\n"
13225 "Cause: AUTH_PEER_NOT_DYNAMIC\r\n"
13226 "Address: %s\r\n"
13227 "Port: %d\r\n",
13228 name, ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
13229 }
13230 } else {
13231 transmit_response(p, "404 Not found", &p->initreq);
13232 if (global_authfailureevents) {
13233 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
13234 "ChannelType: SIP\r\n"
13235 "Peer: SIP/%s\r\n"
13236 "PeerStatus: Rejected\r\n"
13237 "Cause: %s\r\n"
13238 "Address: %s\r\n"
13239 "Port: %d\r\n",
13240 name,
13241 (res == AUTH_USERNAME_MISMATCH) ? "AUTH_USERNAME_MISMATCH" : "URI_NOT_FOUND",
13242 ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
13243 }
13244 }
13245 }
13246 break;
13247 case AUTH_BAD_TRANSPORT:
13248 default:
13249 break;
13250 }
13251 }
13252 if (peer)
13253 unref_peer(peer, "register_verify: unref_peer: tossing stack peer pointer at end of func");
13254
13255 return res;
13256 }
13257
13258
13259 static void sip_set_redirstr(struct sip_pvt *p, char *reason) {
13260
13261 if (!strcmp(reason, "unknown")) {
13262 ast_string_field_set(p, redircause, "UNKNOWN");
13263 } else if (!strcmp(reason, "user-busy")) {
13264 ast_string_field_set(p, redircause, "BUSY");
13265 } else if (!strcmp(reason, "no-answer")) {
13266 ast_string_field_set(p, redircause, "NOANSWER");
13267 } else if (!strcmp(reason, "unavailable")) {
13268 ast_string_field_set(p, redircause, "UNREACHABLE");
13269 } else if (!strcmp(reason, "unconditional")) {
13270 ast_string_field_set(p, redircause, "UNCONDITIONAL");
13271 } else if (!strcmp(reason, "time-of-day")) {
13272 ast_string_field_set(p, redircause, "UNKNOWN");
13273 } else if (!strcmp(reason, "do-not-disturb")) {
13274 ast_string_field_set(p, redircause, "UNKNOWN");
13275 } else if (!strcmp(reason, "deflection")) {
13276 ast_string_field_set(p, redircause, "UNKNOWN");
13277 } else if (!strcmp(reason, "follow-me")) {
13278 ast_string_field_set(p, redircause, "UNKNOWN");
13279 } else if (!strcmp(reason, "out-of-service")) {
13280 ast_string_field_set(p, redircause, "UNREACHABLE");
13281 } else if (!strcmp(reason, "away")) {
13282 ast_string_field_set(p, redircause, "UNREACHABLE");
13283 } else {
13284 ast_string_field_set(p, redircause, "UNKNOWN");
13285 }
13286 }
13287
13288
13289 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq)
13290 {
13291 char tmp[256], *exten, *rexten, *rdomain;
13292 char *params, *reason = NULL;
13293 struct sip_request *req;
13294
13295 req = oreq ? oreq : &p->initreq;
13296
13297 ast_copy_string(tmp, get_header(req, "Diversion"), sizeof(tmp));
13298 if (ast_strlen_zero(tmp))
13299 return 0;
13300
13301
13302
13303
13304 params = strchr(tmp, ';');
13305
13306 exten = get_in_brackets(tmp);
13307 if (!strncasecmp(exten, "sip:", 4)) {
13308 exten += 4;
13309 } else if (!strncasecmp(exten, "sips:", 5)) {
13310 exten += 5;
13311 } else {
13312 ast_log(LOG_WARNING, "Huh? Not an RDNIS SIP header (%s)?\n", exten);
13313 return -1;
13314 }
13315
13316
13317 if (params) {
13318 *params = '\0';
13319 params++;
13320 while (*params == ';' || *params == ' ')
13321 params++;
13322
13323 if ((reason = strcasestr(params, "reason="))) {
13324 reason+=7;
13325
13326 if (*reason == '"')
13327 ast_strip_quoted(reason, "\"", "\"");
13328 if (!ast_strlen_zero(reason)) {
13329 sip_set_redirstr(p, reason);
13330 if (p->owner) {
13331 pbx_builtin_setvar_helper(p->owner, "__PRIREDIRECTREASON", p->redircause);
13332 pbx_builtin_setvar_helper(p->owner, "__SIPREDIRECTREASON", reason);
13333 }
13334 }
13335 }
13336 }
13337
13338 rdomain = exten;
13339 rexten = strsep(&rdomain, "@");
13340 if (p->owner)
13341 pbx_builtin_setvar_helper(p->owner, "__SIPRDNISDOMAIN", rdomain);
13342
13343 if (sip_debug_test_pvt(p))
13344 ast_verbose("RDNIS for this call is is %s (reason %s)\n", exten, reason ? reason : "");
13345
13346 ast_string_field_set(p, rdnis, rexten);
13347
13348 return 0;
13349 }
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363 static int get_destination(struct sip_pvt *p, struct sip_request *oreq)
13364 {
13365 char tmp[256] = "", *uri, *a;
13366 char tmpf[256] = "", *from = NULL;
13367 struct sip_request *req;
13368 char *colon;
13369 char *decoded_uri;
13370
13371 req = oreq;
13372 if (!req)
13373 req = &p->initreq;
13374
13375
13376 if (req->rlPart2)
13377 ast_copy_string(tmp, REQ_OFFSET_TO_STR(req, rlPart2), sizeof(tmp));
13378
13379 if (sip_cfg.pedanticsipchecking)
13380 ast_uri_decode(tmp);
13381
13382 uri = get_in_brackets(tmp);
13383
13384 if (!strncasecmp(uri, "sip:", 4)) {
13385 uri += 4;
13386 } else if (!strncasecmp(uri, "sips:", 5)) {
13387 uri += 5;
13388 } else {
13389 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", uri);
13390 return -1;
13391 }
13392
13393
13394
13395
13396
13397 ast_copy_string(tmpf, get_header(req, "From"), sizeof(tmpf));
13398 if (!ast_strlen_zero(tmpf)) {
13399 if (sip_cfg.pedanticsipchecking)
13400 ast_uri_decode(tmpf);
13401 from = get_in_brackets(tmpf);
13402 }
13403
13404 if (!ast_strlen_zero(from)) {
13405 if (!strncasecmp(from, "sip:", 4)) {
13406 from += 4;
13407 } else if (!strncasecmp(from, "sips:", 5)) {
13408 from += 5;
13409 } else {
13410 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", from);
13411 return -1;
13412 }
13413 if ((a = strchr(from, '@')))
13414 *a++ = '\0';
13415 else
13416 a = from;
13417 from = strsep(&from, ";");
13418 a = strsep(&a, ";");
13419 ast_string_field_set(p, fromdomain, a);
13420 }
13421
13422
13423
13424
13425 if ((a = strchr(uri, '@'))) {
13426 *a++ = '\0';
13427 } else {
13428 a = uri;
13429 uri = "s";
13430 }
13431 colon = strchr(a, ':');
13432 if (colon)
13433 *colon = '\0';
13434
13435 uri = strsep(&uri, ";");
13436 a = strsep(&a, ";");
13437
13438 ast_string_field_set(p, domain, a);
13439
13440 if (!AST_LIST_EMPTY(&domain_list)) {
13441 char domain_context[AST_MAX_EXTENSION];
13442
13443 domain_context[0] = '\0';
13444 if (!check_sip_domain(p->domain, domain_context, sizeof(domain_context))) {
13445 if (!sip_cfg.allow_external_domains && (req->method == SIP_INVITE || req->method == SIP_REFER)) {
13446 ast_debug(1, "Got SIP %s to non-local domain '%s'; refusing request.\n", sip_methods[req->method].text, p->domain);
13447 return -2;
13448 }
13449 }
13450
13451
13452 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_HAVEPEERCONTEXT) && !ast_strlen_zero(domain_context))
13453 ast_string_field_set(p, context, domain_context);
13454 }
13455
13456
13457 if (req->method == SIP_SUBSCRIBE && !ast_strlen_zero(p->subscribecontext))
13458 ast_string_field_set(p, context, p->subscribecontext);
13459
13460 if (sip_debug_test_pvt(p))
13461 ast_verbose("Looking for %s in %s (domain %s)\n", uri, p->context, p->domain);
13462
13463
13464 if (req->method == SIP_SUBSCRIBE) {
13465 char hint[AST_MAX_EXTENSION];
13466 return (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, p->exten) ? 0 : -1);
13467 } else {
13468 decoded_uri = ast_strdupa(uri);
13469 ast_uri_decode(decoded_uri);
13470
13471
13472
13473
13474
13475 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)) ||
13476 !strcmp(decoded_uri, ast_pickup_ext())) {
13477 if (!oreq)
13478 ast_string_field_set(p, exten, decoded_uri);
13479 return 0;
13480 }
13481 }
13482
13483
13484 if((ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP) &&
13485 ast_canmatch_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from))) ||
13486 !strncmp(decoded_uri, ast_pickup_ext(), strlen(decoded_uri))) {
13487 return 1;
13488 }
13489
13490 return -1;
13491 }
13492
13493
13494
13495
13496 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag)
13497 {
13498 struct sip_pvt *sip_pvt_ptr;
13499 struct sip_pvt tmp_dialog = {
13500 .callid = callid,
13501 };
13502
13503 if (totag)
13504 ast_debug(4, "Looking for callid %s (fromtag %s totag %s)\n", callid, fromtag ? fromtag : "<no fromtag>", totag ? totag : "<no totag>");
13505
13506
13507
13508 sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find of dialog in dialogs table");
13509 if (sip_pvt_ptr) {
13510
13511 sip_pvt_lock(sip_pvt_ptr);
13512 if (sip_cfg.pedanticsipchecking) {
13513 unsigned char frommismatch = 0, tomismatch = 0;
13514
13515 if (ast_strlen_zero(fromtag)) {
13516 sip_pvt_unlock(sip_pvt_ptr);
13517 ast_debug(4, "Matched %s call for callid=%s - no from tag specified, pedantic check fails\n",
13518 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
13519 return NULL;
13520 }
13521
13522 if (ast_strlen_zero(totag)) {
13523 sip_pvt_unlock(sip_pvt_ptr);
13524 ast_debug(4, "Matched %s call for callid=%s - no to tag specified, pedantic check fails\n",
13525 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
13526 return NULL;
13527 }
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542 frommismatch = !!strcmp(fromtag, sip_pvt_ptr->theirtag);
13543 tomismatch = !!strcmp(totag, sip_pvt_ptr->tag);
13544
13545 if (frommismatch || tomismatch) {
13546 sip_pvt_unlock(sip_pvt_ptr);
13547 if (frommismatch) {
13548 ast_debug(4, "Matched %s call for callid=%s - pedantic from tag check fails; their tag is %s our tag is %s\n",
13549 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid,
13550 fromtag, sip_pvt_ptr->theirtag);
13551 }
13552 if (tomismatch) {
13553 ast_debug(4, "Matched %s call for callid=%s - pedantic to tag check fails; their tag is %s our tag is %s\n",
13554 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid,
13555 totag, sip_pvt_ptr->tag);
13556 }
13557 return NULL;
13558 }
13559 }
13560
13561 if (totag)
13562 ast_debug(4, "Matched %s call - their tag is %s Our tag is %s\n",
13563 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING",
13564 sip_pvt_ptr->theirtag, sip_pvt_ptr->tag);
13565
13566
13567 while (sip_pvt_ptr->owner && ast_channel_trylock(sip_pvt_ptr->owner)) {
13568 sip_pvt_unlock(sip_pvt_ptr);
13569 usleep(1);
13570 sip_pvt_lock(sip_pvt_ptr);
13571 }
13572 }
13573
13574 return sip_pvt_ptr;
13575 }
13576
13577
13578
13579
13580
13581
13582
13583
13584 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req)
13585 {
13586
13587 const char *p_referred_by = NULL;
13588 char *h_refer_to = NULL;
13589 char *h_referred_by = NULL;
13590 char *refer_to;
13591 const char *p_refer_to;
13592 char *referred_by_uri = NULL;
13593 char *ptr;
13594 struct sip_request *req = NULL;
13595 const char *transfer_context = NULL;
13596 struct sip_refer *referdata;
13597
13598
13599 req = outgoing_req;
13600 referdata = transferer->refer;
13601
13602 if (!req)
13603 req = &transferer->initreq;
13604
13605 p_refer_to = get_header(req, "Refer-To");
13606 if (ast_strlen_zero(p_refer_to)) {
13607 ast_log(LOG_WARNING, "Refer-To Header missing. Skipping transfer.\n");
13608 return -2;
13609 }
13610 h_refer_to = ast_strdupa(p_refer_to);
13611 refer_to = get_in_brackets(h_refer_to);
13612 if (sip_cfg.pedanticsipchecking)
13613 ast_uri_decode(refer_to);
13614
13615 if (!strncasecmp(refer_to, "sip:", 4)) {
13616 refer_to += 4;
13617 } else if (!strncasecmp(refer_to, "sips:", 5)) {
13618 refer_to += 5;
13619 } else {
13620 ast_log(LOG_WARNING, "Can't transfer to non-sip: URI. (Refer-to: %s)?\n", refer_to);
13621 return -3;
13622 }
13623
13624
13625 p_referred_by = get_header(req, "Referred-By");
13626
13627
13628 if (transferer->owner) {
13629 struct ast_channel *peer = ast_bridged_channel(transferer->owner);
13630 if (peer) {
13631 pbx_builtin_setvar_helper(peer, "SIPREFERRINGCONTEXT", transferer->context);
13632 pbx_builtin_setvar_helper(peer, "SIPREFERREDBYHDR", p_referred_by);
13633 }
13634 }
13635
13636 if (!ast_strlen_zero(p_referred_by)) {
13637 char *lessthan;
13638 h_referred_by = ast_strdupa(p_referred_by);
13639 if (sip_cfg.pedanticsipchecking)
13640 ast_uri_decode(h_referred_by);
13641
13642
13643 ast_copy_string(referdata->referred_by_name, h_referred_by, sizeof(referdata->referred_by_name));
13644 if ((lessthan = strchr(referdata->referred_by_name, '<'))) {
13645 *(lessthan - 1) = '\0';
13646 }
13647
13648 referred_by_uri = get_in_brackets(h_referred_by);
13649 if (!strncasecmp(referred_by_uri, "sip:", 4)) {
13650 referred_by_uri += 4;
13651 } else if (!strncasecmp(referred_by_uri, "sips:", 5)) {
13652 referred_by_uri += 5;
13653 } else {
13654 ast_log(LOG_WARNING, "Huh? Not a sip: header (Referred-by: %s). Skipping.\n", referred_by_uri);
13655 referred_by_uri = NULL;
13656 }
13657 }
13658
13659
13660 if ((ptr = strcasestr(refer_to, "replaces="))) {
13661 char *to = NULL, *from = NULL;
13662
13663
13664 referdata->attendedtransfer = 1;
13665 ast_copy_string(referdata->replaces_callid, ptr+9, sizeof(referdata->replaces_callid));
13666 ast_uri_decode(referdata->replaces_callid);
13667 if ((ptr = strchr(referdata->replaces_callid, ';'))) {
13668 *ptr++ = '\0';
13669 }
13670
13671 if (ptr) {
13672
13673 to = strcasestr(ptr, "to-tag=");
13674 from = strcasestr(ptr, "from-tag=");
13675 }
13676
13677
13678 if (to) {
13679 ptr = to + 7;
13680 if ((to = strchr(ptr, '&')))
13681 *to = '\0';
13682 if ((to = strchr(ptr, ';')))
13683 *to = '\0';
13684 ast_copy_string(referdata->replaces_callid_totag, ptr, sizeof(referdata->replaces_callid_totag));
13685 }
13686
13687 if (from) {
13688 ptr = from + 9;
13689 if ((to = strchr(ptr, '&')))
13690 *to = '\0';
13691 if ((to = strchr(ptr, ';')))
13692 *to = '\0';
13693 ast_copy_string(referdata->replaces_callid_fromtag, ptr, sizeof(referdata->replaces_callid_fromtag));
13694 }
13695
13696 if (!sip_cfg.pedanticsipchecking)
13697 ast_debug(2, "Attended transfer: Will use Replace-Call-ID : %s (No check of from/to tags)\n", referdata->replaces_callid );
13698 else
13699 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>" );
13700 }
13701
13702 if ((ptr = strchr(refer_to, '@'))) {
13703 char *urioption = NULL, *domain;
13704 *ptr++ = '\0';
13705
13706 if ((urioption = strchr(ptr, ';')))
13707 *urioption++ = '\0';
13708
13709 domain = ptr;
13710 if ((ptr = strchr(domain, ':')))
13711 *ptr = '\0';
13712
13713
13714 ast_copy_string(referdata->refer_to_domain, domain, sizeof(referdata->refer_to_domain));
13715 if (urioption)
13716 ast_copy_string(referdata->refer_to_urioption, urioption, sizeof(referdata->refer_to_urioption));
13717 }
13718
13719 if ((ptr = strchr(refer_to, ';')))
13720 *ptr = '\0';
13721 ast_copy_string(referdata->refer_to, refer_to, sizeof(referdata->refer_to));
13722
13723 if (referred_by_uri) {
13724 if ((ptr = strchr(referred_by_uri, ';')))
13725 *ptr = '\0';
13726 ast_copy_string(referdata->referred_by, referred_by_uri, sizeof(referdata->referred_by));
13727 } else {
13728 referdata->referred_by[0] = '\0';
13729 }
13730
13731
13732 if (transferer->owner)
13733 transfer_context = pbx_builtin_getvar_helper(transferer->owner, "TRANSFER_CONTEXT");
13734
13735
13736 if (ast_strlen_zero(transfer_context)) {
13737 transfer_context = S_OR(transferer->owner->macrocontext,
13738 S_OR(transferer->context, sip_cfg.default_context));
13739 }
13740
13741 ast_copy_string(referdata->refer_to_context, transfer_context, sizeof(referdata->refer_to_context));
13742
13743
13744 if (referdata->attendedtransfer || ast_exists_extension(NULL, transfer_context, refer_to, 1, NULL) ) {
13745 if (sip_debug_test_pvt(transferer)) {
13746 ast_verbose("SIP transfer to extension %s@%s by %s\n", refer_to, transfer_context, referred_by_uri);
13747 }
13748
13749 return 0;
13750 }
13751 if (sip_debug_test_pvt(transferer))
13752 ast_verbose("Failed SIP Transfer to non-existing extension %s in context %s\n n", refer_to, transfer_context);
13753
13754
13755 return -1;
13756 }
13757
13758
13759
13760
13761
13762 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq)
13763 {
13764 char tmp[256] = "", *c, *a;
13765 struct sip_request *req = oreq ? oreq : &p->initreq;
13766 struct sip_refer *referdata = NULL;
13767 const char *transfer_context = NULL;
13768
13769 if (!p->refer && !sip_refer_allocate(p))
13770 return -1;
13771
13772 referdata = p->refer;
13773
13774 ast_copy_string(tmp, get_header(req, "Also"), sizeof(tmp));
13775 c = get_in_brackets(tmp);
13776
13777 if (sip_cfg.pedanticsipchecking)
13778 ast_uri_decode(c);
13779
13780 if (!strncasecmp(c, "sip:", 4)) {
13781 c += 4;
13782 } else if (!strncasecmp(c, "sips:", 5)) {
13783 c += 5;
13784 } else {
13785 ast_log(LOG_WARNING, "Huh? Not a SIP header in Also: transfer (%s)?\n", c);
13786 return -1;
13787 }
13788
13789 if ((a = strchr(c, ';')))
13790 *a = '\0';
13791
13792 if ((a = strchr(c, '@'))) {
13793 *a++ = '\0';
13794 ast_copy_string(referdata->refer_to_domain, a, sizeof(referdata->refer_to_domain));
13795 }
13796
13797 if (sip_debug_test_pvt(p))
13798 ast_verbose("Looking for %s in %s\n", c, p->context);
13799
13800 if (p->owner)
13801 transfer_context = pbx_builtin_getvar_helper(p->owner, "TRANSFER_CONTEXT");
13802
13803
13804 if (ast_strlen_zero(transfer_context)) {
13805 transfer_context = S_OR(p->owner->macrocontext,
13806 S_OR(p->context, sip_cfg.default_context));
13807 }
13808 if (ast_exists_extension(NULL, transfer_context, c, 1, NULL)) {
13809
13810 ast_debug(1, "SIP Bye-also transfer to Extension %s@%s \n", c, transfer_context);
13811 ast_copy_string(referdata->refer_to, c, sizeof(referdata->refer_to));
13812 ast_copy_string(referdata->referred_by, "", sizeof(referdata->referred_by));
13813 ast_copy_string(referdata->refer_contact, "", sizeof(referdata->refer_contact));
13814 referdata->refer_call = dialog_unref(referdata->refer_call, "unreffing referdata->refer_call");
13815
13816 ast_string_field_set(p, context, transfer_context);
13817 return 0;
13818 } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
13819 return 1;
13820 }
13821
13822 return -1;
13823 }
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835 static attribute_unused void check_via_response(struct sip_pvt *p, struct sip_request *req)
13836 {
13837 char via[256];
13838 char *cur, *opts;
13839
13840 ast_copy_string(via, get_header(req, "Via"), sizeof(via));
13841
13842
13843 opts = strchr(via, ',');
13844 if (opts)
13845 *opts = '\0';
13846
13847
13848 opts = strchr(via, ';');
13849 if (!opts)
13850 return;
13851 *opts++ = '\0';
13852 while ( (cur = strsep(&opts, ";")) ) {
13853 if (!strncmp(cur, "rport=", 6)) {
13854 int port = strtol(cur+6, NULL, 10);
13855
13856 p->ourip.sin_port = ntohs(port);
13857 } else if (!strncmp(cur, "received=", 9)) {
13858 if (ast_parse_arg(cur+9, PARSE_INADDR, &p->ourip))
13859 ;
13860 }
13861 }
13862 }
13863
13864
13865 static void check_via(struct sip_pvt *p, struct sip_request *req)
13866 {
13867 char via[512];
13868 char *c, *pt, *maddr;
13869 struct hostent *hp;
13870 struct ast_hostent ahp;
13871
13872 ast_copy_string(via, get_header(req, "Via"), sizeof(via));
13873
13874
13875 c = strchr(via, ',');
13876 if (c)
13877 *c = '\0';
13878
13879
13880 c = strstr(via, ";rport");
13881 if (c && (c[6] != '='))
13882 ast_set_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT);
13883
13884
13885 maddr = strstr(via, "maddr=");
13886 if (maddr) {
13887 maddr += 6;
13888 c = maddr + strspn(maddr, "0123456789.");
13889 *c = '\0';
13890 }
13891
13892 c = strchr(via, ';');
13893 if (c)
13894 *c = '\0';
13895
13896 c = strchr(via, ' ');
13897 if (c) {
13898 *c = '\0';
13899 c = ast_skip_blanks(c+1);
13900 if (strcasecmp(via, "SIP/2.0/UDP") && strcasecmp(via, "SIP/2.0/TCP") && strcasecmp(via, "SIP/2.0/TLS")) {
13901 ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
13902 return;
13903 }
13904 pt = strchr(c, ':');
13905 if (pt)
13906 *pt++ = '\0';
13907
13908 if (maddr)
13909 c = maddr;
13910 hp = ast_gethostbyname(c, &ahp);
13911 if (!hp) {
13912 ast_log(LOG_WARNING, "'%s' is not a valid host\n", c);
13913 return;
13914 }
13915 memset(&p->sa, 0, sizeof(p->sa));
13916 p->sa.sin_family = AF_INET;
13917 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
13918 p->sa.sin_port = htons(port_str2int(pt, STANDARD_SIP_PORT));
13919
13920 if (sip_debug_test_pvt(p)) {
13921 const struct sockaddr_in *dst = sip_real_dst(p);
13922 ast_verbose("Sending to %s : %d (%s)\n", ast_inet_ntoa(dst->sin_addr), ntohs(dst->sin_port), sip_nat_mode(p));
13923 }
13924 }
13925 }
13926
13927
13928 static char *get_calleridname(const char *input, char *output, size_t outputsize)
13929 {
13930 const char *end = strchr(input, '<');
13931 const char *tmp = strchr(input, '"');
13932 int bytes = 0;
13933 int maxbytes = outputsize - 1;
13934
13935 if (!end || end == input)
13936 return NULL;
13937
13938 end--;
13939
13940 if (tmp && tmp <= end) {
13941
13942
13943
13944 end = strchr(tmp+1, '"');
13945 if (!end)
13946 return NULL;
13947 bytes = (int) (end - tmp);
13948
13949 if (bytes > maxbytes)
13950 bytes = maxbytes;
13951 ast_copy_string(output, tmp + 1, bytes);
13952 } else {
13953
13954
13955 input = ast_skip_blanks(input);
13956
13957 while(*end && *end < 33 && end > input)
13958 end--;
13959 if (end >= input) {
13960 bytes = (int) (end - input) + 2;
13961
13962 if (bytes > maxbytes)
13963 bytes = maxbytes;
13964 ast_copy_string(output, input, bytes);
13965 } else
13966 return NULL;
13967 }
13968 return output;
13969 }
13970
13971
13972
13973
13974
13975 static int get_rpid_num(const char *input, char *output, int maxlen)
13976 {
13977 char *start;
13978 char *end;
13979
13980 start = strchr(input, ':');
13981 if (!start) {
13982 output[0] = '\0';
13983 return 0;
13984 }
13985 start++;
13986
13987
13988 ast_copy_string(output, start, maxlen);
13989 output[maxlen-1] = '\0';
13990
13991 end = strchr(output, '@');
13992 if (end)
13993 *end = '\0';
13994 else
13995 output[0] = '\0';
13996 if (strstr(input, "privacy=full") || strstr(input, "privacy=uri"))
13997 return AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
13998
13999 return 0;
14000 }
14001
14002
14003
14004 static void replace_cid(struct sip_pvt *p, const char *rpid_num, const char *calleridname)
14005 {
14006
14007 if (!ast_strlen_zero(rpid_num) && ast_test_flag(&p->flags[0], SIP_TRUSTRPID)) {
14008 char *tmp = ast_strdupa(rpid_num);
14009 if (!ast_strlen_zero(calleridname))
14010 ast_string_field_set(p, cid_name, calleridname);
14011 if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
14012 ast_shrink_phone_number(tmp);
14013 ast_string_field_set(p, cid_num, tmp);
14014 }
14015 }
14016
14017
14018 static enum check_auth_result check_peer_ok(struct sip_pvt *p, char *of,
14019 struct sip_request *req, int sipmethod, struct sockaddr_in *sin,
14020 struct sip_peer **authpeer,
14021 enum xmittype reliable,
14022 char *rpid_num, char *calleridname, char *uri2)
14023 {
14024 enum check_auth_result res;
14025 int debug=sip_debug_test_addr(sin);
14026 struct sip_peer *peer;
14027
14028 if (sipmethod == SIP_SUBSCRIBE) {
14029
14030
14031
14032 peer = find_peer(of, NULL, TRUE, FINDALLDEVICES, FALSE, 0);
14033 } else {
14034
14035 peer = find_peer(of, NULL, TRUE, FINDUSERS, FALSE, 0);
14036
14037
14038 if (!peer) {
14039 peer = find_peer(NULL, &p->recv, TRUE, FINDPEERS, FALSE, p->socket.type);
14040 }
14041 }
14042
14043 if (!peer) {
14044 if (debug)
14045 ast_verbose("No matching peer for '%s' from '%s:%d'\n",
14046 of, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
14047 return AUTH_DONT_KNOW;
14048 }
14049 if (!ast_apply_ha(peer->ha, sin)) {
14050 ast_debug(2, "Found peer '%s' for '%s', but fails host access\n", peer->name, of);
14051 unref_peer(peer, "unref_peer: check_peer_ok: from find_peer call, early return of AUTH_ACL_FAILED");
14052 return AUTH_ACL_FAILED;
14053 }
14054 if (debug)
14055 ast_verbose("Found peer '%s' for '%s' from %s:%d\n",
14056 peer->name, of, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
14057
14058
14059
14060 if (p->rtp) {
14061 ast_rtp_codec_setpref(p->rtp, &peer->prefs);
14062 p->autoframing = peer->autoframing;
14063 }
14064
14065
14066 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
14067 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
14068
14069 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) && p->udptl) {
14070 p->t38_maxdatagram = peer->t38_maxdatagram;
14071 set_t38_capabilities(p);
14072 }
14073
14074
14075
14076 if (p->sipoptions)
14077 peer->sipoptions = p->sipoptions;
14078
14079 replace_cid(p, rpid_num, calleridname);
14080 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT_ROUTE));
14081
14082 ast_string_field_set(p, peersecret, peer->secret);
14083 ast_string_field_set(p, peermd5secret, peer->md5secret);
14084 ast_string_field_set(p, subscribecontext, peer->subscribecontext);
14085 ast_string_field_set(p, mohinterpret, peer->mohinterpret);
14086 ast_string_field_set(p, mohsuggest, peer->mohsuggest);
14087 ast_string_field_set(p, parkinglot, peer->parkinglot);
14088 if (peer->callingpres)
14089 p->callingpres = peer->callingpres;
14090 if (peer->maxms && peer->lastms)
14091 p->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
14092 else
14093 p->timer_t1 = peer->timer_t1;
14094
14095
14096 if (peer->timer_b)
14097 p->timer_b = peer->timer_b;
14098 else
14099 p->timer_b = 64 * p->timer_t1;
14100
14101 if (ast_test_flag(&peer->flags[0], SIP_INSECURE_INVITE)) {
14102
14103 ast_string_field_set(p, peersecret, NULL);
14104 ast_string_field_set(p, peermd5secret, NULL);
14105 }
14106 if (!(res = check_auth(p, req, peer->name, p->peersecret, p->peermd5secret, sipmethod, uri2, reliable, req->ignore))) {
14107 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
14108 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
14109
14110 if (peer->call_limit)
14111 ast_set_flag(&p->flags[0], SIP_CALL_LIMIT);
14112 ast_string_field_set(p, peername, peer->name);
14113 ast_string_field_set(p, authname, peer->name);
14114
14115 if (sipmethod == SIP_INVITE) {
14116
14117 p->chanvars = copy_vars(peer->chanvars);
14118 }
14119
14120 if (authpeer) {
14121 ao2_t_ref(peer, 1, "copy pointer into (*authpeer)");
14122 (*authpeer) = peer;
14123 }
14124
14125 if (!ast_strlen_zero(peer->username)) {
14126 ast_string_field_set(p, username, peer->username);
14127
14128
14129 ast_string_field_set(p, authname, peer->username);
14130 }
14131 if (!ast_strlen_zero(peer->cid_num)) {
14132 char *tmp = ast_strdupa(peer->cid_num);
14133 if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
14134 ast_shrink_phone_number(tmp);
14135 ast_string_field_set(p, cid_num, tmp);
14136 }
14137 if (!ast_strlen_zero(peer->cid_name))
14138 ast_string_field_set(p, cid_name, peer->cid_name);
14139 ast_string_field_set(p, fullcontact, peer->fullcontact);
14140 if (!ast_strlen_zero(peer->context))
14141 ast_string_field_set(p, context, peer->context);
14142 ast_string_field_set(p, peersecret, peer->secret);
14143 ast_string_field_set(p, peermd5secret, peer->md5secret);
14144 ast_string_field_set(p, language, peer->language);
14145 ast_string_field_set(p, accountcode, peer->accountcode);
14146 p->amaflags = peer->amaflags;
14147 p->callgroup = peer->callgroup;
14148 p->pickupgroup = peer->pickupgroup;
14149 p->capability = peer->capability;
14150 p->prefs = peer->prefs;
14151 p->jointcapability = peer->capability;
14152 if (p->peercapability)
14153 p->jointcapability &= p->peercapability;
14154 p->maxcallbitrate = peer->maxcallbitrate;
14155 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS) &&
14156 (!ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) ||
14157 !(p->capability & AST_FORMAT_VIDEO_MASK)) &&
14158 p->vrtp) {
14159 ast_rtp_destroy(p->vrtp);
14160 p->vrtp = NULL;
14161 }
14162 if ((!ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT) || !(p->capability & AST_FORMAT_TEXT_MASK)) && p->trtp) {
14163 ast_rtp_destroy(p->trtp);
14164 p->trtp = NULL;
14165 }
14166 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
14167 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
14168 p->noncodeccapability |= AST_RTP_DTMF;
14169 else
14170 p->noncodeccapability &= ~AST_RTP_DTMF;
14171 p->jointnoncodeccapability = p->noncodeccapability;
14172 }
14173 unref_peer(peer, "check_peer_ok: unref_peer: tossing temp ptr to peer from find_peer");
14174 return res;
14175 }
14176
14177
14178
14179
14180
14181
14182
14183 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
14184 int sipmethod, char *uri, enum xmittype reliable,
14185 struct sockaddr_in *sin, struct sip_peer **authpeer)
14186 {
14187 char from[256];
14188 char *dummy;
14189 char *domain;
14190 char *of;
14191 char rpid_num[50];
14192 const char *rpid;
14193 enum check_auth_result res;
14194 char calleridname[50];
14195 char *uri2 = ast_strdupa(uri);
14196
14197 terminate_uri(uri2);
14198
14199 ast_copy_string(from, get_header(req, "From"), sizeof(from));
14200 if (sip_cfg.pedanticsipchecking)
14201 ast_uri_decode(from);
14202
14203 memset(calleridname, 0, sizeof(calleridname));
14204 get_calleridname(from, calleridname, sizeof(calleridname));
14205 if (calleridname[0])
14206 ast_string_field_set(p, cid_name, calleridname);
14207
14208 rpid = get_header(req, "Remote-Party-ID");
14209 memset(rpid_num, 0, sizeof(rpid_num));
14210 if (!ast_strlen_zero(rpid))
14211 p->callingpres = get_rpid_num(rpid, rpid_num, sizeof(rpid_num));
14212
14213 of = get_in_brackets(from);
14214 if (ast_strlen_zero(p->exten)) {
14215 char *t = uri2;
14216 if (!strncasecmp(t, "sip:", 4))
14217 t+= 4;
14218 else if (!strncasecmp(t, "sips:", 5))
14219 t += 5;
14220 ast_string_field_set(p, exten, t);
14221 t = strchr(p->exten, '@');
14222 if (t)
14223 *t = '\0';
14224 if (ast_strlen_zero(p->our_contact))
14225 build_contact(p);
14226 }
14227
14228 ast_string_field_set(p, from, of);
14229
14230
14231 if (parse_uri(of, "sip:,sips:", &of, &dummy, &domain, &dummy, &dummy, NULL)) {
14232 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
14233 }
14234
14235 if (ast_strlen_zero(of)) {
14236
14237
14238
14239
14240
14241
14242 of = domain;
14243 } else {
14244 char *tmp = ast_strdupa(of);
14245
14246
14247
14248 tmp = strsep(&tmp, ";");
14249 if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
14250 ast_shrink_phone_number(tmp);
14251 ast_string_field_set(p, cid_num, tmp);
14252 }
14253
14254 if (global_match_auth_username) {
14255
14256
14257
14258
14259
14260
14261
14262
14263 const char *hdr = get_header(req, "Authorization");
14264 if (ast_strlen_zero(hdr))
14265 hdr = get_header(req, "Proxy-Authorization");
14266
14267 if ( !ast_strlen_zero(hdr) && (hdr = strstr(hdr, "username=\"")) ) {
14268 ast_copy_string(from, hdr + strlen("username=\""), sizeof(from));
14269 of = from;
14270 of = strsep(&of, "\"");
14271 }
14272 }
14273
14274 res = check_peer_ok(p, of, req, sipmethod, sin,
14275 authpeer, reliable, rpid_num, calleridname, uri2);
14276 if (res != AUTH_DONT_KNOW)
14277 return res;
14278
14279
14280 if (sip_cfg.allowguest) {
14281 replace_cid(p, rpid_num, calleridname);
14282 res = AUTH_SUCCESSFUL;
14283 } else if (sip_cfg.alwaysauthreject)
14284 res = AUTH_FAKE_AUTH;
14285 else
14286 res = AUTH_SECRET_FAILED;
14287
14288
14289 if (ast_test_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT)) {
14290 ast_set_flag(&p->flags[0], SIP_NAT_ROUTE);
14291 }
14292
14293 return res;
14294 }
14295
14296
14297
14298
14299 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin)
14300 {
14301 return check_user_full(p, req, sipmethod, uri, reliable, sin, NULL);
14302 }
14303
14304
14305 static int get_msg_text(char *buf, int len, struct sip_request *req, int addnewline)
14306 {
14307 int x;
14308 int y;
14309
14310 buf[0] = '\0';
14311
14312 y = len - strlen(buf) - 5;
14313 if (y < 0)
14314 y = 0;
14315 for (x = 0; x < req->lines; x++) {
14316 char *line = REQ_OFFSET_TO_STR(req, line[x]);
14317 strncat(buf, line, y);
14318 y -= strlen(line) + 1;
14319 if (y < 0)
14320 y = 0;
14321 if (y != 0 && addnewline)
14322 strcat(buf, "\n");
14323 }
14324 return 0;
14325 }
14326
14327
14328
14329
14330
14331 static void receive_message(struct sip_pvt *p, struct sip_request *req)
14332 {
14333 char buf[1400];
14334 struct ast_frame f;
14335 const char *content_type = get_header(req, "Content-Type");
14336
14337 if (strncmp(content_type, "text/plain", strlen("text/plain"))) {
14338 transmit_response(p, "415 Unsupported Media Type", req);
14339 if (!p->owner)
14340 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14341 return;
14342 }
14343
14344 if (get_msg_text(buf, sizeof(buf), req, FALSE)) {
14345 ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
14346 transmit_response(p, "202 Accepted", req);
14347 if (!p->owner)
14348 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14349 return;
14350 }
14351
14352 if (p->owner) {
14353 if (sip_debug_test_pvt(p))
14354 ast_verbose("SIP Text message received: '%s'\n", buf);
14355 memset(&f, 0, sizeof(f));
14356 f.frametype = AST_FRAME_TEXT;
14357 f.subclass = 0;
14358 f.offset = 0;
14359 f.data.ptr = buf;
14360 f.datalen = strlen(buf);
14361 ast_queue_frame(p->owner, &f);
14362 transmit_response(p, "202 Accepted", req);
14363 return;
14364 }
14365
14366
14367 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);
14368 transmit_response(p, "405 Method Not Allowed", req);
14369 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14370 return;
14371 }
14372
14373
14374 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14375 {
14376 #define FORMAT "%-25.25s %-15.15s %-15.15s \n"
14377 #define FORMAT2 "%-25.25s %-15.15s %-15.15s \n"
14378 char ilimits[40];
14379 char iused[40];
14380 int showall = FALSE;
14381 struct ao2_iterator i;
14382 struct sip_peer *peer;
14383
14384 switch (cmd) {
14385 case CLI_INIT:
14386 e->command = "sip show inuse";
14387 e->usage =
14388 "Usage: sip show inuse [all]\n"
14389 " List all SIP devices usage counters and limits.\n"
14390 " Add option \"all\" to show all devices, not only those with a limit.\n";
14391 return NULL;
14392 case CLI_GENERATE:
14393 return NULL;
14394 }
14395
14396 if (a->argc < 3)
14397 return CLI_SHOWUSAGE;
14398
14399 if (a->argc == 4 && !strcmp(a->argv[3], "all"))
14400 showall = TRUE;
14401
14402 ast_cli(a->fd, FORMAT, "* Peer name", "In use", "Limit");
14403
14404 i = ao2_iterator_init(peers, 0);
14405 while ((peer = ao2_t_iterator_next(&i, "iterate thru peer table"))) {
14406 ao2_lock(peer);
14407 if (peer->call_limit)
14408 snprintf(ilimits, sizeof(ilimits), "%d", peer->call_limit);
14409 else
14410 ast_copy_string(ilimits, "N/A", sizeof(ilimits));
14411 snprintf(iused, sizeof(iused), "%d/%d/%d", peer->inUse, peer->inRinging, peer->onHold);
14412 if (showall || peer->call_limit)
14413 ast_cli(a->fd, FORMAT2, peer->name, iused, ilimits);
14414 ao2_unlock(peer);
14415 unref_peer(peer, "toss iterator pointer");
14416 }
14417 ao2_iterator_destroy(&i);
14418
14419 return CLI_SUCCESS;
14420 #undef FORMAT
14421 #undef FORMAT2
14422 }
14423
14424
14425
14426 static char *transfermode2str(enum transfermodes mode)
14427 {
14428 if (mode == TRANSFER_OPENFORALL)
14429 return "open";
14430 else if (mode == TRANSFER_CLOSED)
14431 return "closed";
14432 return "strict";
14433 }
14434
14435 static struct _map_x_s natmodes[] = {
14436 { SIP_NAT_NEVER, "No"},
14437 { SIP_NAT_ROUTE, "Route"},
14438 { SIP_NAT_ALWAYS, "Always"},
14439 { SIP_NAT_RFC3581, "RFC3581"},
14440 { -1, NULL},
14441 };
14442
14443
14444 static const char *nat2str(int nat)
14445 {
14446 return map_x_s(natmodes, nat, "Unknown");
14447 }
14448
14449 #ifdef NOTUSED
14450
14451
14452
14453
14454 static struct _map_x_s natcfgmodes[] = {
14455 { SIP_NAT_NEVER, "never"},
14456 { SIP_NAT_ROUTE, "route"},
14457 { SIP_NAT_ALWAYS, "yes"},
14458 { SIP_NAT_RFC3581, "no"},
14459 { -1, NULL},
14460 };
14461
14462
14463 static const char *nat2strconfig(int nat)
14464 {
14465 return map_x_s(natcfgmodes, nat, "Unknown");
14466 }
14467 #endif
14468
14469
14470
14471
14472
14473
14474
14475 static struct _map_x_s stmodes[] = {
14476 { SESSION_TIMER_MODE_ACCEPT, "Accept"},
14477 { SESSION_TIMER_MODE_ORIGINATE, "Originate"},
14478 { SESSION_TIMER_MODE_REFUSE, "Refuse"},
14479 { -1, NULL},
14480 };
14481
14482 static const char *stmode2str(enum st_mode m)
14483 {
14484 return map_x_s(stmodes, m, "Unknown");
14485 }
14486
14487 static enum st_mode str2stmode(const char *s)
14488 {
14489 return map_s_x(stmodes, s, -1);
14490 }
14491
14492
14493 static struct _map_x_s strefreshers[] = {
14494 { SESSION_TIMER_REFRESHER_AUTO, "auto"},
14495 { SESSION_TIMER_REFRESHER_UAC, "uac"},
14496 { SESSION_TIMER_REFRESHER_UAS, "uas"},
14497 { -1, NULL},
14498 };
14499
14500 static const char *strefresher2str(enum st_refresher r)
14501 {
14502 return map_x_s(strefreshers, r, "Unknown");
14503 }
14504
14505 static enum st_refresher str2strefresher(const char *s)
14506 {
14507 return map_s_x(strefreshers, s, -1);
14508 }
14509
14510
14511 static int peer_status(struct sip_peer *peer, char *status, int statuslen)
14512 {
14513 int res = 0;
14514 if (peer->maxms) {
14515 if (peer->lastms < 0) {
14516 ast_copy_string(status, "UNREACHABLE", statuslen);
14517 } else if (peer->lastms > peer->maxms) {
14518 snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
14519 res = 1;
14520 } else if (peer->lastms) {
14521 snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
14522 res = 1;
14523 } else {
14524 ast_copy_string(status, "UNKNOWN", statuslen);
14525 }
14526 } else {
14527 ast_copy_string(status, "Unmonitored", statuslen);
14528
14529 res = -1;
14530 }
14531 return res;
14532 }
14533
14534
14535
14536
14537
14538
14539 static const char *cli_yesno(int x)
14540 {
14541 return x ? "Yes" : "No";
14542 }
14543
14544
14545 static char *sip_show_tcp(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14546 {
14547 struct sip_threadinfo *th;
14548 struct ao2_iterator i;
14549
14550 #define FORMAT2 "%-30.30s %3.6s %9.9s %6.6s\n"
14551 #define FORMAT "%-30.30s %-6d %-9.9s %-6.6s\n"
14552
14553 switch (cmd) {
14554 case CLI_INIT:
14555 e->command = "sip show tcp";
14556 e->usage =
14557 "Usage: sip show tcp\n"
14558 " Lists all active TCP/TLS sessions.\n";
14559 return NULL;
14560 case CLI_GENERATE:
14561 return NULL;
14562 }
14563
14564 if (a->argc != 3)
14565 return CLI_SHOWUSAGE;
14566
14567 ast_cli(a->fd, FORMAT2, "Host", "Port", "Transport", "Type");
14568 i = ao2_iterator_init(threadt, 0);
14569 while ((th = ao2_t_iterator_next(&i, "iterate through tcp threads for 'sip show tcp'"))) {
14570 ast_cli(a->fd, FORMAT, ast_inet_ntoa(th->tcptls_session->remote_address.sin_addr),
14571 ntohs(th->tcptls_session->remote_address.sin_port),
14572 get_transport(th->type),
14573 (th->tcptls_session->client ? "Client" : "Server"));
14574 ao2_t_ref(th, -1, "decrement ref from iterator");
14575 }
14576 ao2_iterator_destroy(&i);
14577 return CLI_SUCCESS;
14578 #undef FORMAT
14579 #undef FORMAT2
14580 }
14581
14582
14583 static char *sip_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14584 {
14585 regex_t regexbuf;
14586 int havepattern = FALSE;
14587 struct ao2_iterator user_iter;
14588 struct sip_peer *user;
14589
14590 #define FORMAT "%-25.25s %-15.15s %-15.15s %-15.15s %-5.5s%-10.10s\n"
14591
14592 switch (cmd) {
14593 case CLI_INIT:
14594 e->command = "sip show users";
14595 e->usage =
14596 "Usage: sip show users [like <pattern>]\n"
14597 " Lists all known SIP users.\n"
14598 " Optional regular expression pattern is used to filter the user list.\n";
14599 return NULL;
14600 case CLI_GENERATE:
14601 return NULL;
14602 }
14603
14604 switch (a->argc) {
14605 case 5:
14606 if (!strcasecmp(a->argv[3], "like")) {
14607 if (regcomp(®exbuf, a->argv[4], REG_EXTENDED | REG_NOSUB))
14608 return CLI_SHOWUSAGE;
14609 havepattern = TRUE;
14610 } else
14611 return CLI_SHOWUSAGE;
14612 case 3:
14613 break;
14614 default:
14615 return CLI_SHOWUSAGE;
14616 }
14617
14618 ast_cli(a->fd, FORMAT, "Username", "Secret", "Accountcode", "Def.Context", "ACL", "NAT");
14619
14620 user_iter = ao2_iterator_init(peers, 0);
14621 while ((user = ao2_iterator_next(&user_iter))) {
14622 ao2_lock(user);
14623 if (!(user->type & SIP_TYPE_USER)) {
14624 ao2_unlock(user);
14625 unref_peer(user, "sip show users");
14626 continue;
14627 }
14628
14629 if (havepattern && regexec(®exbuf, user->name, 0, NULL, 0)) {
14630 ao2_unlock(user);
14631 unref_peer(user, "sip show users");
14632 continue;
14633 }
14634
14635 ast_cli(a->fd, FORMAT, user->name,
14636 user->secret,
14637 user->accountcode,
14638 user->context,
14639 cli_yesno(user->ha != NULL),
14640 nat2str(ast_test_flag(&user->flags[0], SIP_NAT)));
14641 ao2_unlock(user);
14642 unref_peer(user, "sip show users");
14643 }
14644 ao2_iterator_destroy(&user_iter);
14645
14646 if (havepattern)
14647 regfree(®exbuf);
14648
14649 return CLI_SUCCESS;
14650 #undef FORMAT
14651 }
14652
14653
14654 static char mandescr_show_registry[] =
14655 "Description: Lists all registration requests and status\n"
14656 "Registrations will follow as separate events. followed by a final event called\n"
14657 "RegistrationsComplete.\n"
14658 "Variables: \n"
14659 " ActionID: <id> Action ID for this transaction. Will be returned.\n";
14660
14661
14662 static int manager_show_registry(struct mansession *s, const struct message *m)
14663 {
14664 const char *id = astman_get_header(m, "ActionID");
14665 char idtext[256] = "";
14666 int total = 0;
14667
14668 if (!ast_strlen_zero(id))
14669 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
14670
14671 astman_send_listack(s, m, "Registrations will follow", "start");
14672
14673 ASTOBJ_CONTAINER_TRAVERSE(®l, 1, do {
14674 ASTOBJ_RDLOCK(iterator);
14675 astman_append(s,
14676 "Event: RegistryEntry\r\n"
14677 "%s"
14678 "Host: %s\r\n"
14679 "Port: %d\r\n"
14680 "Username: %s\r\n"
14681 "Refresh: %d\r\n"
14682 "State: %s\r\n"
14683 "RegistrationTime: %ld\r\n"
14684 "\r\n", idtext, iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT,
14685 iterator->username, iterator->refresh, regstate2str(iterator->regstate), (long) iterator->regtime.tv_sec);
14686 ASTOBJ_UNLOCK(iterator);
14687 total++;
14688 } while(0));
14689
14690 astman_append(s,
14691 "Event: RegistrationsComplete\r\n"
14692 "EventList: Complete\r\n"
14693 "ListItems: %d\r\n"
14694 "%s"
14695 "\r\n", total, idtext);
14696
14697 return 0;
14698 }
14699
14700 static char mandescr_show_peers[] =
14701 "Description: Lists SIP peers in text format with details on current status.\n"
14702 "Peerlist will follow as separate events, followed by a final event called\n"
14703 "PeerlistComplete.\n"
14704 "Variables: \n"
14705 " ActionID: <id> Action ID for this transaction. Will be returned.\n";
14706
14707
14708
14709 static int manager_sip_show_peers(struct mansession *s, const struct message *m)
14710 {
14711 const char *id = astman_get_header(m, "ActionID");
14712 const char *a[] = {"sip", "show", "peers"};
14713 char idtext[256] = "";
14714 int total = 0;
14715
14716 if (!ast_strlen_zero(id))
14717 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
14718
14719 astman_send_listack(s, m, "Peer status list will follow", "start");
14720
14721 _sip_show_peers(-1, &total, s, m, 3, a);
14722
14723 astman_append(s,
14724 "Event: PeerlistComplete\r\n"
14725 "EventList: Complete\r\n"
14726 "ListItems: %d\r\n"
14727 "%s"
14728 "\r\n", total, idtext);
14729 return 0;
14730 }
14731
14732
14733 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14734 {
14735 switch (cmd) {
14736 case CLI_INIT:
14737 e->command = "sip show peers";
14738 e->usage =
14739 "Usage: sip show peers [like <pattern>]\n"
14740 " Lists all known SIP peers.\n"
14741 " Optional regular expression pattern is used to filter the peer list.\n";
14742 return NULL;
14743 case CLI_GENERATE:
14744 return NULL;
14745 }
14746
14747 return _sip_show_peers(a->fd, NULL, NULL, NULL, a->argc, (const char **) a->argv);
14748 }
14749
14750 int peercomparefunc(const void *a, const void *b);
14751
14752 int peercomparefunc(const void *a, const void *b)
14753 {
14754 struct sip_peer **ap = (struct sip_peer **)a;
14755 struct sip_peer **bp = (struct sip_peer **)b;
14756 return strcmp((*ap)->name, (*bp)->name);
14757 }
14758
14759
14760
14761 static char *_sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[])
14762 {
14763 regex_t regexbuf;
14764 int havepattern = FALSE;
14765 struct sip_peer *peer;
14766 struct ao2_iterator i;
14767
14768
14769 #define FORMAT2 "%-25.25s %-15.15s %-3.3s %-3.3s %-3.3s %-8s %-10s %s\n"
14770 #define FORMAT "%-25.25s %-15.15s %-3.3s %-3.3s %-3.3s %-8d %-10s %s\n"
14771
14772 char name[256];
14773 int total_peers = 0;
14774 int peers_mon_online = 0;
14775 int peers_mon_offline = 0;
14776 int peers_unmon_offline = 0;
14777 int peers_unmon_online = 0;
14778 const char *id;
14779 char idtext[256] = "";
14780 int realtimepeers;
14781 int objcount = ao2_container_count(peers);
14782 struct sip_peer **peerarray;
14783 int k;
14784
14785
14786 realtimepeers = ast_check_realtime("sippeers");
14787 peerarray = ast_calloc(sizeof(struct sip_peer *), objcount);
14788
14789 if (s) {
14790 id = astman_get_header(m, "ActionID");
14791 if (!ast_strlen_zero(id))
14792 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
14793 }
14794
14795 switch (argc) {
14796 case 5:
14797 if (!strcasecmp(argv[3], "like")) {
14798 if (regcomp(®exbuf, argv[4], REG_EXTENDED | REG_NOSUB))
14799 return CLI_SHOWUSAGE;
14800 havepattern = TRUE;
14801 } else
14802 return CLI_SHOWUSAGE;
14803 case 3:
14804 break;
14805 default:
14806 return CLI_SHOWUSAGE;
14807 }
14808
14809 if (!s)
14810 ast_cli(fd, FORMAT2, "Name/username", "Host", "Dyn", "Nat", "ACL", "Port", "Status", (realtimepeers ? "Realtime" : ""));
14811
14812
14813 i = ao2_iterator_init(peers, 0);
14814 while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
14815 ao2_lock(peer);
14816
14817 if (!(peer->type & SIP_TYPE_PEER)) {
14818 ao2_unlock(peer);
14819 unref_peer(peer, "unref peer because it's actually a user");
14820 continue;
14821 }
14822
14823 if (havepattern && regexec(®exbuf, peer->name, 0, NULL, 0)) {
14824 objcount--;
14825 ao2_unlock(peer);
14826 unref_peer(peer, "toss iterator peer ptr before continue");
14827 continue;
14828 }
14829
14830 peerarray[total_peers++] = peer;
14831 ao2_unlock(peer);
14832 }
14833 ao2_iterator_destroy(&i);
14834
14835 qsort(peerarray, total_peers, sizeof(struct sip_peer *), peercomparefunc);
14836
14837 for(k=0; k < total_peers; k++) {
14838 char status[20] = "";
14839 char srch[2000];
14840 char pstatus;
14841 peer = peerarray[k];
14842
14843 ao2_lock(peer);
14844 if (havepattern && regexec(®exbuf, peer->name, 0, NULL, 0)) {
14845 ao2_unlock(peer);
14846 unref_peer(peer, "toss iterator peer ptr before continue");
14847 continue;
14848 }
14849
14850 if (!ast_strlen_zero(peer->username) && !s)
14851 snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
14852 else
14853 ast_copy_string(name, peer->name, sizeof(name));
14854
14855 pstatus = peer_status(peer, status, sizeof(status));
14856 if (pstatus == 1)
14857 peers_mon_online++;
14858 else if (pstatus == 0)
14859 peers_mon_offline++;
14860 else {
14861 if (peer->addr.sin_port == 0)
14862 peers_unmon_offline++;
14863 else
14864 peers_unmon_online++;
14865 }
14866
14867 snprintf(srch, sizeof(srch), FORMAT, name,
14868 peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
14869 peer->host_dynamic ? " D " : " ",
14870 ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) ? " N " : " ",
14871 peer->ha ? " A " : " ",
14872 ntohs(peer->addr.sin_port), status,
14873 realtimepeers ? (peer->is_realtime ? "Cached RT":"") : "");
14874
14875 if (!s) {
14876 ast_cli(fd, FORMAT, name,
14877 peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
14878 peer->host_dynamic ? " D " : " ",
14879 ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) ? " N " : " ",
14880 peer->ha ? " A " : " ",
14881
14882 ntohs(peer->addr.sin_port), status,
14883 realtimepeers ? (peer->is_realtime ? "Cached RT":"") : "");
14884 } else {
14885
14886 astman_append(s,
14887 "Event: PeerEntry\r\n%s"
14888 "Channeltype: SIP\r\n"
14889 "ObjectName: %s\r\n"
14890 "ChanObjectType: peer\r\n"
14891 "IPaddress: %s\r\n"
14892 "IPport: %d\r\n"
14893 "Dynamic: %s\r\n"
14894 "Natsupport: %s\r\n"
14895 "VideoSupport: %s\r\n"
14896 "TextSupport: %s\r\n"
14897 "ACL: %s\r\n"
14898 "Status: %s\r\n"
14899 "RealtimeDevice: %s\r\n\r\n",
14900 idtext,
14901 peer->name,
14902 peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "-none-",
14903 ntohs(peer->addr.sin_port),
14904 peer->host_dynamic ? "yes" : "no",
14905 ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) ? "yes" : "no",
14906 ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "yes" : "no",
14907 ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT) ? "yes" : "no",
14908 peer->ha ? "yes" : "no",
14909 status,
14910 realtimepeers ? (peer->is_realtime ? "yes":"no") : "no");
14911 }
14912 ao2_unlock(peer);
14913 unref_peer(peer, "toss iterator peer ptr");
14914 }
14915
14916 if (!s)
14917 ast_cli(fd, "%d sip peers [Monitored: %d online, %d offline Unmonitored: %d online, %d offline]\n",
14918 total_peers, peers_mon_online, peers_mon_offline, peers_unmon_online, peers_unmon_offline);
14919
14920 if (havepattern)
14921 regfree(®exbuf);
14922
14923 if (total)
14924 *total = total_peers;
14925
14926 ast_free(peerarray);
14927
14928 return CLI_SUCCESS;
14929 #undef FORMAT
14930 #undef FORMAT2
14931 }
14932
14933 static int peer_dump_func(void *userobj, void *arg, int flags)
14934 {
14935 struct sip_peer *peer = userobj;
14936 int refc = ao2_t_ref(userobj, 0, "");
14937 int *fd = arg;
14938
14939 ast_cli(*fd, "name: %s\ntype: peer\nobjflags: %d\nrefcount: %d\n\n",
14940 peer->name, 0, refc);
14941 return 0;
14942 }
14943
14944 static int dialog_dump_func(void *userobj, void *arg, int flags)
14945 {
14946 struct sip_pvt *pvt = userobj;
14947 int refc = ao2_t_ref(userobj, 0, "");
14948 int *fd = arg;
14949
14950 ast_cli(*fd, "name: %s\ntype: dialog\nobjflags: %d\nrefcount: %d\n\n",
14951 pvt->callid, 0, refc);
14952 return 0;
14953 }
14954
14955
14956
14957 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14958 {
14959 char tmp[256];
14960
14961 switch (cmd) {
14962 case CLI_INIT:
14963 e->command = "sip show objects";
14964 e->usage =
14965 "Usage: sip show objects\n"
14966 " Lists status of known SIP objects\n";
14967 return NULL;
14968 case CLI_GENERATE:
14969 return NULL;
14970 }
14971
14972 if (a->argc != 3)
14973 return CLI_SHOWUSAGE;
14974 ast_cli(a->fd, "-= Peer objects: %d static, %d realtime, %d autocreate =-\n\n", speerobjs, rpeerobjs, apeerobjs);
14975 ao2_t_callback(peers, OBJ_NODATA, peer_dump_func, &a->fd, "initiate ao2_callback to dump peers");
14976 ast_cli(a->fd, "-= Registry objects: %d =-\n\n", regobjs);
14977 ASTOBJ_CONTAINER_DUMP(a->fd, tmp, sizeof(tmp), ®l);
14978 ast_cli(a->fd, "-= Dialog objects:\n\n");
14979 ao2_t_callback(dialogs, OBJ_NODATA, dialog_dump_func, &a->fd, "initiate ao2_callback to dump dialogs");
14980 return CLI_SUCCESS;
14981 }
14982
14983 static void print_group(int fd, ast_group_t group, int crlf)
14984 {
14985 char buf[256];
14986 ast_cli(fd, crlf ? "%s\r\n" : "%s\n", ast_print_group(buf, sizeof(buf), group) );
14987 }
14988
14989
14990 static struct _map_x_s dtmfstr[] = {
14991 { SIP_DTMF_RFC2833, "rfc2833" },
14992 { SIP_DTMF_INFO, "info" },
14993 { SIP_DTMF_SHORTINFO, "shortinfo" },
14994 { SIP_DTMF_INBAND, "inband" },
14995 { SIP_DTMF_AUTO, "auto" },
14996 { -1, NULL },
14997 };
14998
14999
15000 static const char *dtmfmode2str(int mode)
15001 {
15002 return map_x_s(dtmfstr, mode, "<error>");
15003 }
15004
15005
15006 static int str2dtmfmode(const char *str)
15007 {
15008 return map_s_x(dtmfstr, str, -1);
15009 }
15010
15011 static struct _map_x_s insecurestr[] = {
15012 { SIP_INSECURE_PORT, "port" },
15013 { SIP_INSECURE_INVITE, "invite" },
15014 { SIP_INSECURE_PORT | SIP_INSECURE_INVITE, "port,invite" },
15015 { 0, "no" },
15016 { -1, NULL },
15017 };
15018
15019
15020 static const char *insecure2str(int mode)
15021 {
15022 return map_x_s(insecurestr, mode, "<error>");
15023 }
15024
15025
15026
15027
15028 static void cleanup_stale_contexts(char *new, char *old)
15029 {
15030 char *oldcontext, *newcontext, *stalecontext, *stringp, newlist[AST_MAX_CONTEXT];
15031
15032 while ((oldcontext = strsep(&old, "&"))) {
15033 stalecontext = '\0';
15034 ast_copy_string(newlist, new, sizeof(newlist));
15035 stringp = newlist;
15036 while ((newcontext = strsep(&stringp, "&"))) {
15037 if (!strcmp(newcontext, oldcontext)) {
15038
15039 stalecontext = '\0';
15040 break;
15041 } else if (strcmp(newcontext, oldcontext)) {
15042 stalecontext = oldcontext;
15043 }
15044
15045 }
15046 if (stalecontext)
15047 ast_context_destroy(ast_context_find(stalecontext), "SIP");
15048 }
15049 }
15050
15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063 static int dialog_needdestroy(void *dialogobj, void *arg, int flags)
15064 {
15065 struct sip_pvt *dialog = dialogobj;
15066 time_t *t = arg;
15067
15068 if (sip_pvt_trylock(dialog)) {
15069
15070
15071 return 0;
15072 }
15073
15074
15075 check_rtp_timeout(dialog, *t);
15076
15077
15078
15079
15080 if (dialog->needdestroy && !dialog->packets && !dialog->owner) {
15081
15082 if (dialog->rtp && ast_rtp_get_bridged(dialog->rtp)) {
15083 ast_debug(2, "Bridge still active. Delaying destruction of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
15084 sip_pvt_unlock(dialog);
15085 return 0;
15086 }
15087
15088 if (dialog->vrtp && ast_rtp_get_bridged(dialog->vrtp)) {
15089 ast_debug(2, "Bridge still active. Delaying destroy of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
15090 sip_pvt_unlock(dialog);
15091 return 0;
15092 }
15093
15094 sip_pvt_unlock(dialog);
15095
15096
15097 dialog_unlink_all(dialog, TRUE, FALSE);
15098 return 0;
15099 }
15100
15101 sip_pvt_unlock(dialog);
15102
15103 return 0;
15104 }
15105
15106
15107
15108 static int peer_is_marked(void *peerobj, void *arg, int flags)
15109 {
15110 struct sip_peer *peer = peerobj;
15111 return peer->the_mark ? CMP_MATCH : 0;
15112 }
15113
15114
15115
15116 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15117 {
15118 struct sip_peer *peer, *pi;
15119 int prunepeer = FALSE;
15120 int multi = FALSE;
15121 char *name = NULL;
15122 regex_t regexbuf;
15123 struct ao2_iterator i;
15124 static char *choices[] = { "all", "like", NULL };
15125 char *cmplt;
15126
15127 if (cmd == CLI_INIT) {
15128 e->command = "sip prune realtime [peer|all]";
15129 e->usage =
15130 "Usage: sip prune realtime [peer [<name>|all|like <pattern>]|all]\n"
15131 " Prunes object(s) from the cache.\n"
15132 " Optional regular expression pattern is used to filter the objects.\n";
15133 return NULL;
15134 } else if (cmd == CLI_GENERATE) {
15135 if (a->pos == 4 && !strcasecmp(a->argv[3], "peer")) {
15136 cmplt = ast_cli_complete(a->word, choices, a->n);
15137 if (!cmplt)
15138 cmplt = complete_sip_peer(a->word, a->n - sizeof(choices), SIP_PAGE2_RTCACHEFRIENDS);
15139 return cmplt;
15140 }
15141 if (a->pos == 5 && !strcasecmp(a->argv[4], "like"))
15142 return complete_sip_peer(a->word, a->n, SIP_PAGE2_RTCACHEFRIENDS);
15143 return NULL;
15144 }
15145 switch (a->argc) {
15146 case 4:
15147 name = a->argv[3];
15148
15149 if (!strcasecmp(name, "peer") || !strcasecmp(name, "like"))
15150 return CLI_SHOWUSAGE;
15151 prunepeer = TRUE;
15152 if (!strcasecmp(name, "all")) {
15153 multi = TRUE;
15154 name = NULL;
15155 }
15156
15157 break;
15158 case 5:
15159
15160 name = a->argv[4];
15161 if (!strcasecmp(a->argv[3], "peer"))
15162 prunepeer = TRUE;
15163 else if (!strcasecmp(a->argv[3], "like")) {
15164 prunepeer = TRUE;
15165 multi = TRUE;
15166 } else
15167 return CLI_SHOWUSAGE;
15168 if (!strcasecmp(name, "like"))
15169 return CLI_SHOWUSAGE;
15170 if (!multi && !strcasecmp(name, "all")) {
15171 multi = TRUE;
15172 name = NULL;
15173 }
15174 break;
15175 case 6:
15176 name = a->argv[5];
15177 multi = TRUE;
15178
15179 if (strcasecmp(a->argv[4], "like"))
15180 return CLI_SHOWUSAGE;
15181 if (!strcasecmp(a->argv[3], "peer")) {
15182 prunepeer = TRUE;
15183 } else
15184 return CLI_SHOWUSAGE;
15185 break;
15186 default:
15187 return CLI_SHOWUSAGE;
15188 }
15189
15190 if (multi && name) {
15191 if (regcomp(®exbuf, name, REG_EXTENDED | REG_NOSUB))
15192 return CLI_SHOWUSAGE;
15193 }
15194
15195 if (multi) {
15196 if (prunepeer) {
15197 int pruned = 0;
15198
15199 i = ao2_iterator_init(peers, 0);
15200 while ((pi = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
15201 ao2_lock(pi);
15202 if (name && regexec(®exbuf, pi->name, 0, NULL, 0)) {
15203 unref_peer(pi, "toss iterator peer ptr before continue");
15204 ao2_unlock(pi);
15205 continue;
15206 };
15207 if (ast_test_flag(&pi->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
15208 pi->the_mark = 1;
15209 pruned++;
15210 }
15211 ao2_unlock(pi);
15212 unref_peer(pi, "toss iterator peer ptr");
15213 }
15214 ao2_iterator_destroy(&i);
15215 if (pruned) {
15216 ao2_t_callback(peers, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, peer_is_marked, NULL,
15217 "initiating callback to remove marked peers");
15218 ast_cli(a->fd, "%d peers pruned.\n", pruned);
15219 } else
15220 ast_cli(a->fd, "No peers found to prune.\n");
15221 }
15222 } else {
15223 if (prunepeer) {
15224 struct sip_peer tmp;
15225 ast_copy_string(tmp.name, name, sizeof(tmp.name));
15226 if ((peer = ao2_t_find(peers, &tmp, OBJ_POINTER | OBJ_UNLINK, "finding to unlink from peers"))) {
15227 if (peer->addr.sin_addr.s_addr) {
15228 ao2_t_unlink(peers_by_ip, peer, "unlinking peer from peers_by_ip also");
15229 }
15230 if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
15231 ast_cli(a->fd, "Peer '%s' is not a Realtime peer, cannot be pruned.\n", name);
15232
15233 ao2_t_link(peers, peer, "link peer into peer table");
15234 if (peer->addr.sin_addr.s_addr) {
15235 ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
15236 }
15237
15238 } else
15239 ast_cli(a->fd, "Peer '%s' pruned.\n", name);
15240 unref_peer(peer, "sip_prune_realtime: unref_peer: tossing temp peer ptr");
15241 } else
15242 ast_cli(a->fd, "Peer '%s' not found.\n", name);
15243 }
15244 }
15245
15246 return CLI_SUCCESS;
15247 }
15248
15249
15250 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref)
15251 {
15252 int x, codec;
15253
15254 for(x = 0; x < 32 ; x++) {
15255 codec = ast_codec_pref_index(pref, x);
15256 if (!codec)
15257 break;
15258 ast_cli(fd, "%s", ast_getformatname(codec));
15259 ast_cli(fd, ":%d", pref->framing[x]);
15260 if (x < 31 && ast_codec_pref_index(pref, x + 1))
15261 ast_cli(fd, ",");
15262 }
15263 if (!x)
15264 ast_cli(fd, "none");
15265 }
15266
15267
15268 static const char *domain_mode_to_text(const enum domain_mode mode)
15269 {
15270 switch (mode) {
15271 case SIP_DOMAIN_AUTO:
15272 return "[Automatic]";
15273 case SIP_DOMAIN_CONFIG:
15274 return "[Configured]";
15275 }
15276
15277 return "";
15278 }
15279
15280
15281 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15282 {
15283 struct domain *d;
15284 #define FORMAT "%-40.40s %-20.20s %-16.16s\n"
15285
15286 switch (cmd) {
15287 case CLI_INIT:
15288 e->command = "sip show domains";
15289 e->usage =
15290 "Usage: sip show domains\n"
15291 " Lists all configured SIP local domains.\n"
15292 " Asterisk only responds to SIP messages to local domains.\n";
15293 return NULL;
15294 case CLI_GENERATE:
15295 return NULL;
15296 }
15297
15298 if (AST_LIST_EMPTY(&domain_list)) {
15299 ast_cli(a->fd, "SIP Domain support not enabled.\n\n");
15300 return CLI_SUCCESS;
15301 } else {
15302 ast_cli(a->fd, FORMAT, "Our local SIP domains:", "Context", "Set by");
15303 AST_LIST_LOCK(&domain_list);
15304 AST_LIST_TRAVERSE(&domain_list, d, list)
15305 ast_cli(a->fd, FORMAT, d->domain, S_OR(d->context, "(default)"),
15306 domain_mode_to_text(d->mode));
15307 AST_LIST_UNLOCK(&domain_list);
15308 ast_cli(a->fd, "\n");
15309 return CLI_SUCCESS;
15310 }
15311 }
15312 #undef FORMAT
15313
15314 static char mandescr_show_peer[] =
15315 "Description: Show one SIP peer with details on current status.\n"
15316 "Variables: \n"
15317 " Peer: <name> The peer name you want to check.\n"
15318 " ActionID: <id> Optional action ID for this AMI transaction.\n";
15319
15320
15321 static int manager_sip_show_peer(struct mansession *s, const struct message *m)
15322 {
15323 const char *a[4];
15324 const char *peer;
15325
15326 peer = astman_get_header(m, "Peer");
15327 if (ast_strlen_zero(peer)) {
15328 astman_send_error(s, m, "Peer: <name> missing.");
15329 return 0;
15330 }
15331 a[0] = "sip";
15332 a[1] = "show";
15333 a[2] = "peer";
15334 a[3] = peer;
15335
15336 _sip_show_peer(1, -1, s, m, 4, a);
15337 astman_append(s, "\r\n\r\n" );
15338 return 0;
15339 }
15340
15341
15342 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15343 {
15344 switch (cmd) {
15345 case CLI_INIT:
15346 e->command = "sip show peer";
15347 e->usage =
15348 "Usage: sip show peer <name> [load]\n"
15349 " Shows all details on one SIP peer and the current status.\n"
15350 " Option \"load\" forces lookup of peer in realtime storage.\n";
15351 return NULL;
15352 case CLI_GENERATE:
15353 return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
15354 }
15355 return _sip_show_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
15356 }
15357
15358
15359 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
15360 {
15361 struct sip_peer *peer;
15362 int load_realtime;
15363
15364 if (argc < 4)
15365 return CLI_SHOWUSAGE;
15366
15367 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
15368 if ((peer = find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0))) {
15369 sip_poke_peer(peer, 1);
15370 unref_peer(peer, "qualify: done with peer");
15371 } else if (type == 0) {
15372 ast_cli(fd, "Peer '%s' not found\n", argv[3]);
15373 } else {
15374 astman_send_error(s, m, "Peer not found");
15375 }
15376 return CLI_SUCCESS;
15377 }
15378
15379
15380 static int manager_sip_qualify_peer(struct mansession *s, const struct message *m)
15381 {
15382 const char *a[4];
15383 const char *peer;
15384
15385 peer = astman_get_header(m, "Peer");
15386 if (ast_strlen_zero(peer)) {
15387 astman_send_error(s, m, "Peer: <name> missing.");
15388 return 0;
15389 }
15390 a[0] = "sip";
15391 a[1] = "qualify";
15392 a[2] = "peer";
15393 a[3] = peer;
15394
15395 _sip_qualify_peer(1, -1, s, m, 4, a);
15396 astman_append(s, "\r\n\r\n" );
15397 return 0;
15398 }
15399
15400
15401 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15402 {
15403 switch (cmd) {
15404 case CLI_INIT:
15405 e->command = "sip qualify peer";
15406 e->usage =
15407 "Usage: sip qualify peer <name> [load]\n"
15408 " Requests a response from one SIP peer and the current status.\n"
15409 " Option \"load\" forces lookup of peer in realtime storage.\n";
15410 return NULL;
15411 case CLI_GENERATE:
15412 return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
15413 }
15414 return _sip_qualify_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
15415 }
15416
15417
15418 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer)
15419 {
15420 struct sip_mailbox *mailbox;
15421
15422 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
15423 ast_str_append(mailbox_str, 0, "%s%s%s%s",
15424 mailbox->mailbox,
15425 ast_strlen_zero(mailbox->context) ? "" : "@",
15426 S_OR(mailbox->context, ""),
15427 AST_LIST_NEXT(mailbox, entry) ? "," : "");
15428 }
15429 }
15430
15431 static struct _map_x_s faxecmodes[] = {
15432 { SIP_PAGE2_T38SUPPORT_UDPTL, "None"},
15433 { SIP_PAGE2_T38SUPPORT_UDPTL_FEC, "FEC"},
15434 { SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY, "Redundancy"},
15435 { -1, NULL},
15436 };
15437
15438 static const char *faxec2str(int faxec)
15439 {
15440 return map_x_s(faxecmodes, faxec, "Unknown");
15441 }
15442
15443
15444 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
15445 {
15446 char status[30] = "";
15447 char cbuf[256];
15448 struct sip_peer *peer;
15449 char codec_buf[512];
15450 struct ast_codec_pref *pref;
15451 struct ast_variable *v;
15452 struct sip_auth *auth;
15453 int x = 0, codec = 0, load_realtime;
15454 int realtimepeers;
15455
15456 realtimepeers = ast_check_realtime("sippeers");
15457
15458 if (argc < 4)
15459 return CLI_SHOWUSAGE;
15460
15461 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
15462 peer = find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0);
15463
15464 if (s) {
15465 if (peer) {
15466 const char *id = astman_get_header(m, "ActionID");
15467
15468 astman_append(s, "Response: Success\r\n");
15469 if (!ast_strlen_zero(id))
15470 astman_append(s, "ActionID: %s\r\n", id);
15471 } else {
15472 snprintf (cbuf, sizeof(cbuf), "Peer %s not found.", argv[3]);
15473 astman_send_error(s, m, cbuf);
15474 return CLI_SUCCESS;
15475 }
15476 }
15477 if (peer && type==0 ) {
15478 struct ast_str *mailbox_str = ast_str_alloca(512);
15479 ast_cli(fd, "\n\n");
15480 ast_cli(fd, " * Name : %s\n", peer->name);
15481 if (realtimepeers) {
15482 ast_cli(fd, " Realtime peer: %s\n", peer->is_realtime ? "Yes, cached" : "No");
15483 }
15484 ast_cli(fd, " Secret : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
15485 ast_cli(fd, " MD5Secret : %s\n", ast_strlen_zero(peer->md5secret)?"<Not set>":"<Set>");
15486 ast_cli(fd, " Remote Secret: %s\n", ast_strlen_zero(peer->remotesecret)?"<Not set>":"<Set>");
15487 for (auth = peer->auth; auth; auth = auth->next) {
15488 ast_cli(fd, " Realm-auth : Realm %-15.15s User %-10.20s ", auth->realm, auth->username);
15489 ast_cli(fd, "%s\n", !ast_strlen_zero(auth->secret)?"<Secret set>":(!ast_strlen_zero(auth->md5secret)?"<MD5secret set>" : "<Not set>"));
15490 }
15491 ast_cli(fd, " Context : %s\n", peer->context);
15492 ast_cli(fd, " Subscr.Cont. : %s\n", S_OR(peer->subscribecontext, "<Not set>") );
15493 ast_cli(fd, " Language : %s\n", peer->language);
15494 if (!ast_strlen_zero(peer->accountcode))
15495 ast_cli(fd, " Accountcode : %s\n", peer->accountcode);
15496 ast_cli(fd, " AMA flags : %s\n", ast_cdr_flags2str(peer->amaflags));
15497 ast_cli(fd, " Transfer mode: %s\n", transfermode2str(peer->allowtransfer));
15498 ast_cli(fd, " CallingPres : %s\n", ast_describe_caller_presentation(peer->callingpres));
15499 if (!ast_strlen_zero(peer->fromuser))
15500 ast_cli(fd, " FromUser : %s\n", peer->fromuser);
15501 if (!ast_strlen_zero(peer->fromdomain))
15502 ast_cli(fd, " FromDomain : %s\n", peer->fromdomain);
15503 ast_cli(fd, " Callgroup : ");
15504 print_group(fd, peer->callgroup, 0);
15505 ast_cli(fd, " Pickupgroup : ");
15506 print_group(fd, peer->pickupgroup, 0);
15507 peer_mailboxes_to_str(&mailbox_str, peer);
15508 ast_cli(fd, " Mailbox : %s\n", mailbox_str->str);
15509 ast_cli(fd, " VM Extension : %s\n", peer->vmexten);
15510 ast_cli(fd, " LastMsgsSent : %d/%d\n", (peer->lastmsgssent & 0x7fff0000) >> 16, peer->lastmsgssent & 0xffff);
15511 ast_cli(fd, " Call limit : %d\n", peer->call_limit);
15512 if (peer->busy_level)
15513 ast_cli(fd, " Busy level : %d\n", peer->busy_level);
15514 ast_cli(fd, " Dynamic : %s\n", cli_yesno(peer->host_dynamic));
15515 ast_cli(fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
15516 ast_cli(fd, " MaxCallBR : %d kbps\n", peer->maxcallbitrate);
15517 ast_cli(fd, " Expire : %ld\n", ast_sched_when(sched, peer->expire));
15518 ast_cli(fd, " Insecure : %s\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
15519 ast_cli(fd, " Nat : %s\n", nat2str(ast_test_flag(&peer->flags[0], SIP_NAT)));
15520 ast_cli(fd, " ACL : %s\n", cli_yesno(peer->ha != NULL));
15521 ast_cli(fd, " T.38 support : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
15522 ast_cli(fd, " T.38 EC mode : %s\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
15523 ast_cli(fd, " T.38 MaxDtgrm: %d\n", peer->t38_maxdatagram);
15524 ast_cli(fd, " DirectMedia : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)));
15525 ast_cli(fd, " PromiscRedir : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)));
15526 ast_cli(fd, " User=Phone : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)));
15527 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)));
15528 ast_cli(fd, " Text Support : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)));
15529 ast_cli(fd, " Ign SDP ver : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_IGNORESDPVERSION)));
15530 ast_cli(fd, " Trust RPID : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_TRUSTRPID)));
15531 ast_cli(fd, " Send RPID : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_SENDRPID)));
15532 ast_cli(fd, " Subscriptions: %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
15533 ast_cli(fd, " Overlap dial : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWOVERLAP)));
15534 ast_cli(fd, " Forward Loop : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_FORWARD_LOOP_DETECTED)));
15535 if (peer->outboundproxy)
15536 ast_cli(fd, " Outb. proxy : %s %s\n", ast_strlen_zero(peer->outboundproxy->name) ? "<not set>" : peer->outboundproxy->name,
15537 peer->outboundproxy->force ? "(forced)" : "");
15538
15539
15540 ast_cli(fd, " DTMFmode : %s\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
15541 ast_cli(fd, " Timer T1 : %d\n", peer->timer_t1);
15542 ast_cli(fd, " Timer B : %d\n", peer->timer_b);
15543 ast_cli(fd, " ToHost : %s\n", peer->tohost);
15544 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));
15545 ast_cli(fd, " Defaddr->IP : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
15546 ast_cli(fd, " Prim.Transp. : %s\n", get_transport(peer->socket.type));
15547 ast_cli(fd, " Allowed.Trsp : %s\n", get_transport_list(peer->transports));
15548 if (!ast_strlen_zero(global_regcontext))
15549 ast_cli(fd, " Reg. exten : %s\n", peer->regexten);
15550 ast_cli(fd, " Def. Username: %s\n", peer->username);
15551 ast_cli(fd, " SIP Options : ");
15552 if (peer->sipoptions) {
15553 int lastoption = -1;
15554 for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
15555 if (sip_options[x].id != lastoption) {
15556 if (peer->sipoptions & sip_options[x].id)
15557 ast_cli(fd, "%s ", sip_options[x].text);
15558 lastoption = x;
15559 }
15560 }
15561 } else
15562 ast_cli(fd, "(none)");
15563
15564 ast_cli(fd, "\n");
15565 ast_cli(fd, " Codecs : ");
15566 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
15567 ast_cli(fd, "%s\n", codec_buf);
15568 ast_cli(fd, " Codec Order : (");
15569 print_codec_to_cli(fd, &peer->prefs);
15570 ast_cli(fd, ")\n");
15571
15572 ast_cli(fd, " Auto-Framing : %s \n", cli_yesno(peer->autoframing));
15573 ast_cli(fd, " 100 on REG : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_REGISTERTRYING) ? "Yes" : "No");
15574 ast_cli(fd, " Status : ");
15575 peer_status(peer, status, sizeof(status));
15576 ast_cli(fd, "%s\n", status);
15577 ast_cli(fd, " Useragent : %s\n", peer->useragent);
15578 ast_cli(fd, " Reg. Contact : %s\n", peer->fullcontact);
15579 ast_cli(fd, " Qualify Freq : %d ms\n", peer->qualifyfreq);
15580 if (peer->chanvars) {
15581 ast_cli(fd, " Variables :\n");
15582 for (v = peer->chanvars ; v ; v = v->next)
15583 ast_cli(fd, " %s = %s\n", v->name, v->value);
15584 }
15585
15586 ast_cli(fd, " Sess-Timers : %s\n", stmode2str(peer->stimer.st_mode_oper));
15587 ast_cli(fd, " Sess-Refresh : %s\n", strefresher2str(peer->stimer.st_ref));
15588 ast_cli(fd, " Sess-Expires : %d secs\n", peer->stimer.st_max_se);
15589 ast_cli(fd, " Min-Sess : %d secs\n", peer->stimer.st_min_se);
15590 ast_cli(fd, " Parkinglot : %s\n", peer->parkinglot);
15591 ast_cli(fd, "\n");
15592 peer = unref_peer(peer, "sip_show_peer: unref_peer: done with peer ptr");
15593 } else if (peer && type == 1) {
15594 char buffer[256];
15595 struct ast_str *mailbox_str = ast_str_alloca(512);
15596 astman_append(s, "Channeltype: SIP\r\n");
15597 astman_append(s, "ObjectName: %s\r\n", peer->name);
15598 astman_append(s, "ChanObjectType: peer\r\n");
15599 astman_append(s, "SecretExist: %s\r\n", ast_strlen_zero(peer->secret)?"N":"Y");
15600 astman_append(s, "RemoteSecretExist: %s\r\n", ast_strlen_zero(peer->remotesecret)?"N":"Y");
15601 astman_append(s, "MD5SecretExist: %s\r\n", ast_strlen_zero(peer->md5secret)?"N":"Y");
15602 astman_append(s, "Context: %s\r\n", peer->context);
15603 astman_append(s, "Language: %s\r\n", peer->language);
15604 if (!ast_strlen_zero(peer->accountcode))
15605 astman_append(s, "Accountcode: %s\r\n", peer->accountcode);
15606 astman_append(s, "AMAflags: %s\r\n", ast_cdr_flags2str(peer->amaflags));
15607 astman_append(s, "CID-CallingPres: %s\r\n", ast_describe_caller_presentation(peer->callingpres));
15608 if (!ast_strlen_zero(peer->fromuser))
15609 astman_append(s, "SIP-FromUser: %s\r\n", peer->fromuser);
15610 if (!ast_strlen_zero(peer->fromdomain))
15611 astman_append(s, "SIP-FromDomain: %s\r\n", peer->fromdomain);
15612 astman_append(s, "Callgroup: ");
15613 astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->callgroup));
15614 astman_append(s, "Pickupgroup: ");
15615 astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->pickupgroup));
15616 peer_mailboxes_to_str(&mailbox_str, peer);
15617 astman_append(s, "VoiceMailbox: %s\r\n", mailbox_str->str);
15618 astman_append(s, "TransferMode: %s\r\n", transfermode2str(peer->allowtransfer));
15619 astman_append(s, "LastMsgsSent: %d\r\n", peer->lastmsgssent);
15620 astman_append(s, "Call-limit: %d\r\n", peer->call_limit);
15621 astman_append(s, "Busy-level: %d\r\n", peer->busy_level);
15622 astman_append(s, "MaxCallBR: %d kbps\r\n", peer->maxcallbitrate);
15623 astman_append(s, "Dynamic: %s\r\n", peer->host_dynamic?"Y":"N");
15624 astman_append(s, "Callerid: %s\r\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, ""));
15625 astman_append(s, "RegExpire: %ld seconds\r\n", ast_sched_when(sched, peer->expire));
15626 astman_append(s, "SIP-AuthInsecure: %s\r\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
15627 astman_append(s, "SIP-NatSupport: %s\r\n", nat2str(ast_test_flag(&peer->flags[0], SIP_NAT)));
15628 astman_append(s, "ACL: %s\r\n", (peer->ha?"Y":"N"));
15629 astman_append(s, "SIP-CanReinvite: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)?"Y":"N"));
15630 astman_append(s, "SIP-DirectMedia: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)?"Y":"N"));
15631 astman_append(s, "SIP-PromiscRedir: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)?"Y":"N"));
15632 astman_append(s, "SIP-UserPhone: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)?"Y":"N"));
15633 astman_append(s, "SIP-VideoSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)?"Y":"N"));
15634 astman_append(s, "SIP-TextSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)?"Y":"N"));
15635 astman_append(s, "SIP-T.38Support: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)?"Y":"N"));
15636 astman_append(s, "SIP-T.38EC: %s\r\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
15637 astman_append(s, "SIP-T.38MaxDtgrm: %d\r\n", peer->t38_maxdatagram);
15638 astman_append(s, "SIP-Sess-Timers: %s\r\n", stmode2str(peer->stimer.st_mode_oper));
15639 astman_append(s, "SIP-Sess-Refresh: %s\r\n", strefresher2str(peer->stimer.st_ref));
15640 astman_append(s, "SIP-Sess-Expires: %d\r\n", peer->stimer.st_max_se);
15641 astman_append(s, "SIP-Sess-Min: %d\r\n", peer->stimer.st_min_se);
15642
15643
15644 astman_append(s, "SIP-DTMFmode: %s\r\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
15645 astman_append(s, "ToHost: %s\r\n", peer->tohost);
15646 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));
15647 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));
15648 astman_append(s, "Default-Username: %s\r\n", peer->username);
15649 if (!ast_strlen_zero(global_regcontext))
15650 astman_append(s, "RegExtension: %s\r\n", peer->regexten);
15651 astman_append(s, "Codecs: ");
15652 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
15653 astman_append(s, "%s\r\n", codec_buf);
15654 astman_append(s, "CodecOrder: ");
15655 pref = &peer->prefs;
15656 for(x = 0; x < 32 ; x++) {
15657 codec = ast_codec_pref_index(pref, x);
15658 if (!codec)
15659 break;
15660 astman_append(s, "%s", ast_getformatname(codec));
15661 if (x < 31 && ast_codec_pref_index(pref, x+1))
15662 astman_append(s, ",");
15663 }
15664
15665 astman_append(s, "\r\n");
15666 astman_append(s, "Status: ");
15667 peer_status(peer, status, sizeof(status));
15668 astman_append(s, "%s\r\n", status);
15669 astman_append(s, "SIP-Useragent: %s\r\n", peer->useragent);
15670 astman_append(s, "Reg-Contact: %s\r\n", peer->fullcontact);
15671 astman_append(s, "QualifyFreq: %d ms\r\n", peer->qualifyfreq);
15672 astman_append(s, "Parkinglot: %s\r\n", peer->parkinglot);
15673 if (peer->chanvars) {
15674 for (v = peer->chanvars ; v ; v = v->next) {
15675 astman_append(s, "ChanVariable: %s=%s\r\n", v->name, v->value);
15676 }
15677 }
15678
15679 peer = unref_peer(peer, "sip_show_peer: unref_peer: done with peer");
15680
15681 } else {
15682 ast_cli(fd, "Peer %s not found.\n", argv[3]);
15683 ast_cli(fd, "\n");
15684 }
15685
15686 return CLI_SUCCESS;
15687 }
15688
15689
15690 static char *complete_sip_user(const char *word, int state)
15691 {
15692 char *result = NULL;
15693 int wordlen = strlen(word);
15694 int which = 0;
15695 struct ao2_iterator user_iter;
15696 struct sip_peer *user;
15697
15698 user_iter = ao2_iterator_init(peers, 0);
15699 while ((user = ao2_iterator_next(&user_iter))) {
15700 ao2_lock(user);
15701 if (!(user->type & SIP_TYPE_USER)) {
15702 ao2_unlock(user);
15703 unref_peer(user, "complete sip user");
15704 continue;
15705 }
15706
15707 if (!strncasecmp(word, user->name, wordlen) && ++which > state) {
15708 result = ast_strdup(user->name);
15709 }
15710 ao2_unlock(user);
15711 unref_peer(user, "complete sip user");
15712 }
15713 ao2_iterator_destroy(&user_iter);
15714 return result;
15715 }
15716
15717 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state)
15718 {
15719 if (pos == 3)
15720 return complete_sip_user(word, state);
15721
15722 return NULL;
15723 }
15724
15725
15726 static char *sip_show_user(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15727 {
15728 char cbuf[256];
15729 struct sip_peer *user;
15730 struct ast_variable *v;
15731 int load_realtime;
15732
15733 switch (cmd) {
15734 case CLI_INIT:
15735 e->command = "sip show user";
15736 e->usage =
15737 "Usage: sip show user <name> [load]\n"
15738 " Shows all details on one SIP user and the current status.\n"
15739 " Option \"load\" forces lookup of peer in realtime storage.\n";
15740 return NULL;
15741 case CLI_GENERATE:
15742 return complete_sip_show_user(a->line, a->word, a->pos, a->n);
15743 }
15744
15745 if (a->argc < 4)
15746 return CLI_SHOWUSAGE;
15747
15748
15749 load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? TRUE : FALSE;
15750
15751 if ((user = find_peer(a->argv[3], NULL, load_realtime, FINDUSERS, FALSE, 0))) {
15752 ao2_lock(user);
15753 ast_cli(a->fd, "\n\n");
15754 ast_cli(a->fd, " * Name : %s\n", user->name);
15755 ast_cli(a->fd, " Secret : %s\n", ast_strlen_zero(user->secret)?"<Not set>":"<Set>");
15756 ast_cli(a->fd, " MD5Secret : %s\n", ast_strlen_zero(user->md5secret)?"<Not set>":"<Set>");
15757 ast_cli(a->fd, " Context : %s\n", user->context);
15758 ast_cli(a->fd, " Language : %s\n", user->language);
15759 if (!ast_strlen_zero(user->accountcode))
15760 ast_cli(a->fd, " Accountcode : %s\n", user->accountcode);
15761 ast_cli(a->fd, " AMA flags : %s\n", ast_cdr_flags2str(user->amaflags));
15762 ast_cli(a->fd, " Transfer mode: %s\n", transfermode2str(user->allowtransfer));
15763 ast_cli(a->fd, " MaxCallBR : %d kbps\n", user->maxcallbitrate);
15764 ast_cli(a->fd, " CallingPres : %s\n", ast_describe_caller_presentation(user->callingpres));
15765 ast_cli(a->fd, " Call limit : %d\n", user->call_limit);
15766 ast_cli(a->fd, " Callgroup : ");
15767 print_group(a->fd, user->callgroup, 0);
15768 ast_cli(a->fd, " Pickupgroup : ");
15769 print_group(a->fd, user->pickupgroup, 0);
15770 ast_cli(a->fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), user->cid_name, user->cid_num, "<unspecified>"));
15771 ast_cli(a->fd, " ACL : %s\n", cli_yesno(user->ha != NULL));
15772 ast_cli(a->fd, " Sess-Timers : %s\n", stmode2str(user->stimer.st_mode_oper));
15773 ast_cli(a->fd, " Sess-Refresh : %s\n", strefresher2str(user->stimer.st_ref));
15774 ast_cli(a->fd, " Sess-Expires : %d secs\n", user->stimer.st_max_se);
15775 ast_cli(a->fd, " Sess-Min-SE : %d secs\n", user->stimer.st_min_se);
15776
15777 ast_cli(a->fd, " Codec Order : (");
15778 print_codec_to_cli(a->fd, &user->prefs);
15779 ast_cli(a->fd, ")\n");
15780
15781 ast_cli(a->fd, " Auto-Framing: %s \n", cli_yesno(user->autoframing));
15782 if (user->chanvars) {
15783 ast_cli(a->fd, " Variables :\n");
15784 for (v = user->chanvars ; v ; v = v->next)
15785 ast_cli(a->fd, " %s = %s\n", v->name, v->value);
15786 }
15787
15788 ast_cli(a->fd, "\n");
15789
15790 ao2_unlock(user);
15791 unref_peer(user, "sip show user");
15792 } else {
15793 ast_cli(a->fd, "User %s not found.\n", a->argv[3]);
15794 ast_cli(a->fd, "\n");
15795 }
15796
15797 return CLI_SUCCESS;
15798 }
15799
15800
15801 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15802 {
15803 struct ast_str *cbuf;
15804 struct ast_cb_names cbnames = {9, { "retrans_pkt",
15805 "__sip_autodestruct",
15806 "expire_register",
15807 "auto_congest",
15808 "sip_reg_timeout",
15809 "sip_poke_peer_s",
15810 "sip_poke_noanswer",
15811 "sip_reregister",
15812 "sip_reinvite_retry"},
15813 { retrans_pkt,
15814 __sip_autodestruct,
15815 expire_register,
15816 auto_congest,
15817 sip_reg_timeout,
15818 sip_poke_peer_s,
15819 sip_poke_noanswer,
15820 sip_reregister,
15821 sip_reinvite_retry}};
15822
15823 switch (cmd) {
15824 case CLI_INIT:
15825 e->command = "sip show sched";
15826 e->usage =
15827 "Usage: sip show sched\n"
15828 " Shows stats on what's in the sched queue at the moment\n";
15829 return NULL;
15830 case CLI_GENERATE:
15831 return NULL;
15832 }
15833
15834 cbuf = ast_str_alloca(2048);
15835
15836 ast_cli(a->fd, "\n");
15837 ast_sched_report(sched, &cbuf, &cbnames);
15838 ast_cli(a->fd, "%s", cbuf->str);
15839
15840 return CLI_SUCCESS;
15841 }
15842
15843
15844 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15845 {
15846 #define FORMAT2 "%-30.30s %-6.6s %-12.12s %8.8s %-20.20s %-25.25s\n"
15847 #define FORMAT "%-30.30s %-6.6s %-12.12s %8d %-20.20s %-25.25s\n"
15848 char host[80];
15849 char tmpdat[256];
15850 struct ast_tm tm;
15851 int counter = 0;
15852
15853 switch (cmd) {
15854 case CLI_INIT:
15855 e->command = "sip show registry";
15856 e->usage =
15857 "Usage: sip show registry\n"
15858 " Lists all registration requests and status.\n";
15859 return NULL;
15860 case CLI_GENERATE:
15861 return NULL;
15862 }
15863
15864 if (a->argc != 3)
15865 return CLI_SHOWUSAGE;
15866 ast_cli(a->fd, FORMAT2, "Host", "dnsmgr", "Username", "Refresh", "State", "Reg.Time");
15867
15868 ASTOBJ_CONTAINER_TRAVERSE(®l, 1, do {
15869 ASTOBJ_RDLOCK(iterator);
15870 snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
15871 if (iterator->regtime.tv_sec) {
15872 ast_localtime(&iterator->regtime, &tm, NULL);
15873 ast_strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T", &tm);
15874 } else
15875 tmpdat[0] = '\0';
15876 ast_cli(a->fd, FORMAT, host, (iterator->dnsmgr) ? "Y" : "N", iterator->username, iterator->refresh, regstate2str(iterator->regstate), tmpdat);
15877 ASTOBJ_UNLOCK(iterator);
15878 counter++;
15879 } while(0));
15880 ast_cli(a->fd, "%d SIP registrations.\n", counter);
15881 return CLI_SUCCESS;
15882 #undef FORMAT
15883 #undef FORMAT2
15884 }
15885
15886
15887
15888
15889
15890 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15891 {
15892 struct sip_peer *peer;
15893 int load_realtime = 0;
15894
15895 switch (cmd) {
15896 case CLI_INIT:
15897 e->command = "sip unregister";
15898 e->usage =
15899 "Usage: sip unregister <peer>\n"
15900 " Unregister (force expiration) a SIP peer from the registry\n";
15901 return NULL;
15902 case CLI_GENERATE:
15903 return complete_sip_unregister(a->line, a->word, a->pos, a->n);
15904 }
15905
15906 if (a->argc != 3)
15907 return CLI_SHOWUSAGE;
15908
15909 if ((peer = find_peer(a->argv[2], NULL, load_realtime, FINDPEERS, TRUE, 0))) {
15910 if (peer->expire > 0) {
15911 AST_SCHED_DEL_UNREF(sched, peer->expire,
15912 unref_peer(peer, "remove register expire ref"));
15913 expire_register(ref_peer(peer, "ref for expire_register"));
15914 ast_cli(a->fd, "Unregistered peer \'%s\'\n\n", a->argv[2]);
15915 } else {
15916 ast_cli(a->fd, "Peer %s not registered\n", a->argv[2]);
15917 }
15918 unref_peer(peer, "sip_unregister: unref_peer via sip_unregister: done with peer from find_peer call");
15919 } else {
15920 ast_cli(a->fd, "Peer unknown: \'%s\'. Not unregistered.\n", a->argv[2]);
15921 }
15922
15923 return CLI_SUCCESS;
15924 }
15925
15926
15927 static int show_chanstats_cb(void *__cur, void *__arg, int flags)
15928 {
15929 #define FORMAT2 "%-15.15s %-11.11s %-8.8s %-10.10s %-10.10s ( %%) %-6.6s %-10.10s %-10.10s ( %%) %-6.6s\n"
15930 #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"
15931 struct sip_pvt *cur = __cur;
15932 unsigned int rxcount, txcount, rxploss, txploss;
15933 char durbuf[10];
15934 int duration;
15935 int durh, durm, durs;
15936 struct ast_channel *c = cur->owner;
15937 struct __show_chan_arg *arg = __arg;
15938 int fd = arg->fd;
15939
15940
15941 if (cur->subscribed != NONE)
15942 return 0;
15943
15944 if (!cur->rtp) {
15945 if (sipdebug)
15946 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");
15947 return 0;
15948 }
15949 rxcount = ast_rtp_get_qosvalue(cur->rtp, AST_RTP_RXCOUNT);
15950 txcount = ast_rtp_get_qosvalue(cur->rtp, AST_RTP_TXCOUNT);
15951 rxploss = ast_rtp_get_qosvalue(cur->rtp, AST_RTP_RXPLOSS);
15952 txploss = ast_rtp_get_qosvalue(cur->rtp, AST_RTP_TXPLOSS);
15953
15954
15955 if (c && c->cdr && !ast_tvzero(c->cdr->start)) {
15956 duration = (int)(ast_tvdiff_ms(ast_tvnow(), c->cdr->start) / 1000);
15957 durh = duration / 3600;
15958 durm = (duration % 3600) / 60;
15959 durs = duration % 60;
15960 snprintf(durbuf, sizeof(durbuf), "%02d:%02d:%02d", durh, durm, durs);
15961 } else {
15962 durbuf[0] = '\0';
15963 }
15964
15965 ast_cli(fd, FORMAT,
15966 ast_inet_ntoa(cur->sa.sin_addr),
15967 cur->callid,
15968 durbuf,
15969 rxcount > (unsigned int) 100000 ? (unsigned int) (rxcount)/(unsigned int) 1000 : rxcount,
15970 rxcount > (unsigned int) 100000 ? "K":" ",
15971 rxploss,
15972 (rxcount + rxploss) > 0 ? (double) rxploss / (rxcount + rxploss) * 100 : 0,
15973 ast_rtp_get_qosvalue(cur->rtp, AST_RTP_RXJITTER),
15974 txcount > (unsigned int) 100000 ? (unsigned int) (txcount)/(unsigned int) 1000 : txcount,
15975 txcount > (unsigned int) 100000 ? "K":" ",
15976 txploss,
15977 txcount > 0 ? (double) txploss / txcount * 100 : 0,
15978 ast_rtp_get_qosvalue(cur->rtp, AST_RTP_TXJITTER)
15979 );
15980 arg->numchans++;
15981
15982 return 0;
15983 }
15984
15985
15986 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15987 {
15988 struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
15989
15990 switch (cmd) {
15991 case CLI_INIT:
15992 e->command = "sip show channelstats";
15993 e->usage =
15994 "Usage: sip show channelstats\n"
15995 " Lists all currently active SIP channel's RTCP statistics.\n"
15996 " Note that calls in the much optimized RTP P2P bridge mode will not show any packets here.";
15997 return NULL;
15998 case CLI_GENERATE:
15999 return NULL;
16000 }
16001
16002 if (a->argc != 3)
16003 return CLI_SHOWUSAGE;
16004
16005 ast_cli(a->fd, FORMAT2, "Peer", "Call ID", "Duration", "Recv: Pack", "Lost", "Jitter", "Send: Pack", "Lost", "Jitter");
16006
16007 ao2_t_callback(dialogs, OBJ_NODATA, show_chanstats_cb, &arg, "callback to sip show chanstats");
16008 ast_cli(a->fd, "%d active SIP channel%s\n", arg.numchans, (arg.numchans != 1) ? "s" : "");
16009 return CLI_SUCCESS;
16010 }
16011 #undef FORMAT
16012 #undef FORMAT2
16013
16014
16015 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16016 {
16017 int realtimepeers;
16018 int realtimeregs;
16019 char codec_buf[SIPBUFSIZE];
16020 const char *msg;
16021
16022 switch (cmd) {
16023 case CLI_INIT:
16024 e->command = "sip show settings";
16025 e->usage =
16026 "Usage: sip show settings\n"
16027 " Provides detailed list of the configuration of the SIP channel.\n";
16028 return NULL;
16029 case CLI_GENERATE:
16030 return NULL;
16031 }
16032
16033
16034 realtimepeers = ast_check_realtime("sippeers");
16035 realtimeregs = ast_check_realtime("sipregs");
16036
16037 if (a->argc != 3)
16038 return CLI_SHOWUSAGE;
16039 ast_cli(a->fd, "\n\nGlobal Settings:\n");
16040 ast_cli(a->fd, "----------------\n");
16041 ast_cli(a->fd, " UDP SIP Port: %d\n", ntohs(bindaddr.sin_port));
16042 ast_cli(a->fd, " UDP Bindaddress: %s\n", ast_inet_ntoa(bindaddr.sin_addr));
16043 ast_cli(a->fd, " TCP SIP Port: ");
16044 if (sip_tcp_desc.local_address.sin_family == AF_INET) {
16045 ast_cli(a->fd, "%d\n", ntohs(sip_tcp_desc.local_address.sin_port));
16046 ast_cli(a->fd, " TCP Bindaddress: %s\n", ast_inet_ntoa(sip_tcp_desc.local_address.sin_addr));
16047 } else {
16048 ast_cli(a->fd, "Disabled\n");
16049 }
16050 ast_cli(a->fd, " TLS SIP Port: ");
16051 if (default_tls_cfg.enabled != FALSE) {
16052 ast_cli(a->fd, "%d\n", ntohs(sip_tls_desc.local_address.sin_port));
16053 ast_cli(a->fd, " TLS Bindaddress: %s\n", ast_inet_ntoa(sip_tls_desc.local_address.sin_addr));
16054 } else {
16055 ast_cli(a->fd, "Disabled\n");
16056 }
16057 ast_cli(a->fd, " Videosupport: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT)));
16058 ast_cli(a->fd, " Textsupport: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT)));
16059 ast_cli(a->fd, " Ignore SDP sess. ver.: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION)));
16060 ast_cli(a->fd, " AutoCreate Peer: %s\n", cli_yesno(sip_cfg.autocreatepeer));
16061 ast_cli(a->fd, " Match Auth Username: %s\n", cli_yesno(global_match_auth_username));
16062 ast_cli(a->fd, " Allow unknown access: %s\n", cli_yesno(sip_cfg.allowguest));
16063 ast_cli(a->fd, " Allow subscriptions: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
16064 ast_cli(a->fd, " Allow overlap dialing: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP)));
16065 ast_cli(a->fd, " Allow promsic. redir: %s\n", cli_yesno(ast_test_flag(&global_flags[0], SIP_PROMISCREDIR)));
16066 ast_cli(a->fd, " Enable call counters: %s\n", cli_yesno(global_callcounter));
16067 ast_cli(a->fd, " SIP domain support: %s\n", cli_yesno(!AST_LIST_EMPTY(&domain_list)));
16068 ast_cli(a->fd, " Realm. auth: %s\n", cli_yesno(authl != NULL));
16069 ast_cli(a->fd, " Our auth realm %s\n", sip_cfg.realm);
16070 ast_cli(a->fd, " Call to non-local dom.: %s\n", cli_yesno(sip_cfg.allow_external_domains));
16071 ast_cli(a->fd, " URI user is phone no: %s\n", cli_yesno(ast_test_flag(&global_flags[0], SIP_USEREQPHONE)));
16072 ast_cli(a->fd, " Always auth rejects: %s\n", cli_yesno(sip_cfg.alwaysauthreject));
16073 ast_cli(a->fd, " Direct RTP setup: %s\n", cli_yesno(sip_cfg.directrtpsetup));
16074 ast_cli(a->fd, " User Agent: %s\n", global_useragent);
16075 ast_cli(a->fd, " SDP Session Name: %s\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
16076 ast_cli(a->fd, " SDP Owner Name: %s\n", ast_strlen_zero(global_sdpowner) ? "-" : global_sdpowner);
16077 ast_cli(a->fd, " Reg. context: %s\n", S_OR(global_regcontext, "(not set)"));
16078 ast_cli(a->fd, " Regexten on Qualify: %s\n", cli_yesno(sip_cfg.regextenonqualify));
16079 ast_cli(a->fd, " Caller ID: %s\n", default_callerid);
16080 ast_cli(a->fd, " From: Domain: %s\n", default_fromdomain);
16081 ast_cli(a->fd, " Record SIP history: %s\n", recordhistory ? "On" : "Off");
16082 ast_cli(a->fd, " Call Events: %s\n", sip_cfg.callevents ? "On" : "Off");
16083 ast_cli(a->fd, " Auth. Failure Events: %s\n", global_authfailureevents ? "On" : "Off");
16084
16085 ast_cli(a->fd, " T.38 support: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
16086 ast_cli(a->fd, " T.38 EC mode: %s\n", faxec2str(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
16087 ast_cli(a->fd, " T.38 MaxDtgrm: %d\n", global_t38_maxdatagram);
16088
16089 if (!realtimepeers && !realtimeregs)
16090 ast_cli(a->fd, " SIP realtime: Disabled\n" );
16091 else
16092 ast_cli(a->fd, " SIP realtime: Enabled\n" );
16093 ast_cli(a->fd, " Qualify Freq : %d ms\n", global_qualifyfreq);
16094 ast_cli(a->fd, "\nNetwork QoS Settings:\n");
16095 ast_cli(a->fd, "---------------------------\n");
16096 ast_cli(a->fd, " IP ToS SIP: %s\n", ast_tos2str(global_tos_sip));
16097 ast_cli(a->fd, " IP ToS RTP audio: %s\n", ast_tos2str(global_tos_audio));
16098 ast_cli(a->fd, " IP ToS RTP video: %s\n", ast_tos2str(global_tos_video));
16099 ast_cli(a->fd, " IP ToS RTP text: %s\n", ast_tos2str(global_tos_text));
16100 ast_cli(a->fd, " 802.1p CoS SIP: %d\n", global_cos_sip);
16101 ast_cli(a->fd, " 802.1p CoS RTP audio: %d\n", global_cos_audio);
16102 ast_cli(a->fd, " 802.1p CoS RTP video: %d\n", global_cos_video);
16103 ast_cli(a->fd, " 802.1p CoS RTP text: %d\n", global_cos_text);
16104 ast_cli(a->fd, " Jitterbuffer enabled: %s\n", cli_yesno(ast_test_flag(&global_jbconf, AST_JB_ENABLED)));
16105 ast_cli(a->fd, " Jitterbuffer forced: %s\n", cli_yesno(ast_test_flag(&global_jbconf, AST_JB_FORCED)));
16106 ast_cli(a->fd, " Jitterbuffer max size: %ld\n", global_jbconf.max_size);
16107 ast_cli(a->fd, " Jitterbuffer resync: %ld\n", global_jbconf.resync_threshold);
16108 ast_cli(a->fd, " Jitterbuffer impl: %s\n", global_jbconf.impl);
16109 ast_cli(a->fd, " Jitterbuffer log: %s\n", cli_yesno(ast_test_flag(&global_jbconf, AST_JB_LOG)));
16110
16111 ast_cli(a->fd, "\nNetwork Settings:\n");
16112 ast_cli(a->fd, "---------------------------\n");
16113
16114 if (localaddr == NULL)
16115 msg = "Disabled, no localnet list";
16116 else if (externip.sin_addr.s_addr == 0)
16117 msg = "Disabled, externip is 0.0.0.0";
16118 else if (stunaddr.sin_addr.s_addr != 0)
16119 msg = "Enabled using STUN";
16120 else if (!ast_strlen_zero(externhost))
16121 msg = "Enabled using externhost";
16122 else
16123 msg = "Enabled using externip";
16124 ast_cli(a->fd, " SIP address remapping: %s\n", msg);
16125 ast_cli(a->fd, " Externhost: %s\n", S_OR(externhost, "<none>"));
16126 ast_cli(a->fd, " Externip: %s:%d\n", ast_inet_ntoa(externip.sin_addr), ntohs(externip.sin_port));
16127 ast_cli(a->fd, " Externrefresh: %d\n", externrefresh);
16128 ast_cli(a->fd, " Internal IP: %s:%d\n", ast_inet_ntoa(internip.sin_addr), ntohs(internip.sin_port));
16129 {
16130 struct ast_ha *d;
16131 const char *prefix = "Localnet:";
16132 char buf[INET_ADDRSTRLEN];
16133
16134 for (d = localaddr; d ; prefix = "", d = d->next) {
16135 ast_cli(a->fd, " %-24s%s/%s\n",
16136 prefix, ast_inet_ntoa(d->netaddr),
16137 inet_ntop(AF_INET, &d->netmask, buf, sizeof(buf)) );
16138 }
16139 }
16140 ast_cli(a->fd, " STUN server: %s:%d\n", ast_inet_ntoa(stunaddr.sin_addr), ntohs(stunaddr.sin_port));
16141
16142 ast_cli(a->fd, "\nGlobal Signalling Settings:\n");
16143 ast_cli(a->fd, "---------------------------\n");
16144 ast_cli(a->fd, " Codecs: ");
16145 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, global_capability);
16146 ast_cli(a->fd, "%s\n", codec_buf);
16147 ast_cli(a->fd, " Codec Order: ");
16148 print_codec_to_cli(a->fd, &default_prefs);
16149 ast_cli(a->fd, "\n");
16150 ast_cli(a->fd, " Relax DTMF: %s\n", cli_yesno(global_relaxdtmf));
16151 ast_cli(a->fd, " RFC2833 Compensation: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_RFC2833_COMPENSATE)));
16152 ast_cli(a->fd, " Compact SIP headers: %s\n", cli_yesno(sip_cfg.compactheaders));
16153 ast_cli(a->fd, " RTP Keepalive: %d %s\n", global_rtpkeepalive, global_rtpkeepalive ? "" : "(Disabled)" );
16154 ast_cli(a->fd, " RTP Timeout: %d %s\n", global_rtptimeout, global_rtptimeout ? "" : "(Disabled)" );
16155 ast_cli(a->fd, " RTP Hold Timeout: %d %s\n", global_rtpholdtimeout, global_rtpholdtimeout ? "" : "(Disabled)");
16156 ast_cli(a->fd, " MWI NOTIFY mime type: %s\n", default_notifymime);
16157 ast_cli(a->fd, " DNS SRV lookup: %s\n", cli_yesno(sip_cfg.srvlookup));
16158 ast_cli(a->fd, " Pedantic SIP support: %s\n", cli_yesno(sip_cfg.pedanticsipchecking));
16159 ast_cli(a->fd, " Reg. min duration %d secs\n", min_expiry);
16160 ast_cli(a->fd, " Reg. max duration: %d secs\n", max_expiry);
16161 ast_cli(a->fd, " Reg. default duration: %d secs\n", default_expiry);
16162 ast_cli(a->fd, " Outbound reg. timeout: %d secs\n", global_reg_timeout);
16163 ast_cli(a->fd, " Outbound reg. attempts: %d\n", global_regattempts_max);
16164 ast_cli(a->fd, " Notify ringing state: %s\n", cli_yesno(sip_cfg.notifyringing));
16165 if (sip_cfg.notifyringing) {
16166 ast_cli(a->fd, " Include CID: %s%s\n",
16167 cli_yesno(sip_cfg.notifycid),
16168 sip_cfg.notifycid == IGNORE_CONTEXT ? " (Ignoring context)" : "");
16169 }
16170 ast_cli(a->fd, " Notify hold state: %s\n", cli_yesno(sip_cfg.notifyhold));
16171 ast_cli(a->fd, " SIP Transfer mode: %s\n", transfermode2str(sip_cfg.allowtransfer));
16172 ast_cli(a->fd, " Max Call Bitrate: %d kbps\n", default_maxcallbitrate);
16173 ast_cli(a->fd, " Auto-Framing: %s\n", cli_yesno(global_autoframing));
16174 ast_cli(a->fd, " Outb. proxy: %s %s\n", ast_strlen_zero(sip_cfg.outboundproxy.name) ? "<not set>" : sip_cfg.outboundproxy.name,
16175 sip_cfg.outboundproxy.force ? "(forced)" : "");
16176 ast_cli(a->fd, " Session Timers: %s\n", stmode2str(global_st_mode));
16177 ast_cli(a->fd, " Session Refresher: %s\n", strefresher2str (global_st_refresher));
16178 ast_cli(a->fd, " Session Expires: %d secs\n", global_max_se);
16179 ast_cli(a->fd, " Session Min-SE: %d secs\n", global_min_se);
16180 ast_cli(a->fd, " Timer T1: %d\n", global_t1);
16181 ast_cli(a->fd, " Timer T1 minimum: %d\n", global_t1min);
16182 ast_cli(a->fd, " Timer B: %d\n", global_timer_b);
16183 ast_cli(a->fd, " No premature media: %s\n", global_prematuremediafilter ? "Yes" : "No");
16184
16185 ast_cli(a->fd, "\nDefault Settings:\n");
16186 ast_cli(a->fd, "-----------------\n");
16187 ast_cli(a->fd, " Allowed transports: %s\n", get_transport_list(default_transports));
16188 ast_cli(a->fd, " Outbound transport: %s\n", get_transport(default_primary_transport));
16189 ast_cli(a->fd, " Context: %s\n", sip_cfg.default_context);
16190 ast_cli(a->fd, " Nat: %s\n", nat2str(ast_test_flag(&global_flags[0], SIP_NAT)));
16191 ast_cli(a->fd, " DTMF: %s\n", dtmfmode2str(ast_test_flag(&global_flags[0], SIP_DTMF)));
16192 ast_cli(a->fd, " Qualify: %d\n", default_qualify);
16193 ast_cli(a->fd, " Use ClientCode: %s\n", cli_yesno(ast_test_flag(&global_flags[0], SIP_USECLIENTCODE)));
16194 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" );
16195 ast_cli(a->fd, " Language: %s\n", default_language);
16196 ast_cli(a->fd, " MOH Interpret: %s\n", default_mohinterpret);
16197 ast_cli(a->fd, " MOH Suggest: %s\n", default_mohsuggest);
16198 ast_cli(a->fd, " Voice Mail Extension: %s\n", default_vmexten);
16199 ast_cli(a->fd, " Forward Detected Loops: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_FORWARD_LOOP_DETECTED)));
16200
16201 if (realtimepeers || realtimeregs) {
16202 ast_cli(a->fd, "\nRealtime SIP Settings:\n");
16203 ast_cli(a->fd, "----------------------\n");
16204 ast_cli(a->fd, " Realtime Peers: %s\n", cli_yesno(realtimepeers));
16205 ast_cli(a->fd, " Realtime Regs: %s\n", cli_yesno(realtimeregs));
16206 ast_cli(a->fd, " Cache Friends: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)));
16207 ast_cli(a->fd, " Update: %s\n", cli_yesno(sip_cfg.peer_rtupdate));
16208 ast_cli(a->fd, " Ignore Reg. Expire: %s\n", cli_yesno(sip_cfg.ignore_regexpire));
16209 ast_cli(a->fd, " Save sys. name: %s\n", cli_yesno(sip_cfg.rtsave_sysname));
16210 ast_cli(a->fd, " Auto Clear: %d\n", sip_cfg.rtautoclear);
16211 }
16212 ast_cli(a->fd, "\n----\n");
16213 return CLI_SUCCESS;
16214 }
16215
16216 static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16217 {
16218 #define FORMAT "%-30.30s %-12.12s %-10.10s %-10.10s\n"
16219 char host[80];
16220
16221 switch (cmd) {
16222 case CLI_INIT:
16223 e->command = "sip show mwi";
16224 e->usage =
16225 "Usage: sip show mwi\n"
16226 " Provides a list of MWI subscriptions and status.\n";
16227 return NULL;
16228 case CLI_GENERATE:
16229 return NULL;
16230 }
16231
16232 ast_cli(a->fd, FORMAT, "Host", "Username", "Mailbox", "Subscribed");
16233
16234 ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
16235 ASTOBJ_RDLOCK(iterator);
16236 snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
16237 ast_cli(a->fd, FORMAT, host, iterator->username, iterator->mailbox, iterator->subscribed ? "Yes" : "No");
16238 ASTOBJ_UNLOCK(iterator);
16239 } while(0));
16240
16241 return CLI_SUCCESS;
16242 #undef FORMAT
16243 }
16244
16245
16246
16247 static const char *subscription_type2str(enum subscriptiontype subtype)
16248 {
16249 int i;
16250
16251 for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
16252 if (subscription_types[i].type == subtype) {
16253 return subscription_types[i].text;
16254 }
16255 }
16256 return subscription_types[0].text;
16257 }
16258
16259
16260 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype)
16261 {
16262 int i;
16263
16264 for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
16265 if (subscription_types[i].type == subtype) {
16266 return &subscription_types[i];
16267 }
16268 }
16269 return &subscription_types[0];
16270 }
16271
16272
16273
16274
16275
16276
16277
16278
16279 #define FORMAT4 "%-15.15s %-15.15s %-15.15s %-15.15s %-13.13s %-15.15s %-10.10s %-6.6d\n"
16280 #define FORMAT3 "%-15.15s %-15.15s %-15.15s %-15.15s %-13.13s %-15.15s %-10.10s %-6.6s\n"
16281 #define FORMAT2 "%-15.15s %-15.15s %-15.15s %-15.15s %-7.7s %-15.15s %-6.6s\n"
16282 #define FORMAT "%-15.15s %-15.15s %-15.15s %-15.15s %-3.3s %-3.3s %-15.15s %-10.10s\n"
16283
16284
16285 static int show_channels_cb(void *__cur, void *__arg, int flags)
16286 {
16287 struct sip_pvt *cur = __cur;
16288 struct __show_chan_arg *arg = __arg;
16289 const struct sockaddr_in *dst = sip_real_dst(cur);
16290
16291
16292 if (cur->subscribed == NONE && !arg->subscriptions) {
16293
16294 const char *referstatus = cur->refer ? referstatus2str(cur->refer->status) : "";
16295 char formatbuf[SIPBUFSIZE/2];
16296
16297 ast_cli(arg->fd, FORMAT, ast_inet_ntoa(dst->sin_addr),
16298 S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
16299 cur->callid,
16300 ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0),
16301 cli_yesno(ast_test_flag(&cur->flags[1], SIP_PAGE2_CALL_ONHOLD)),
16302 cur->needdestroy ? "(d)" : "",
16303 cur->lastmsg ,
16304 referstatus
16305 );
16306 arg->numchans++;
16307 }
16308 if (cur->subscribed != NONE && arg->subscriptions) {
16309 struct ast_str *mailbox_str = ast_str_alloca(512);
16310 if (cur->subscribed == MWI_NOTIFICATION && cur->relatedpeer)
16311 peer_mailboxes_to_str(&mailbox_str, cur->relatedpeer);
16312 ast_cli(arg->fd, FORMAT4, ast_inet_ntoa(dst->sin_addr),
16313 S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
16314 cur->callid,
16315
16316 cur->subscribed == MWI_NOTIFICATION ? "--" : cur->subscribeuri,
16317 cur->subscribed == MWI_NOTIFICATION ? "<none>" : ast_extension_state2str(cur->laststate),
16318 subscription_type2str(cur->subscribed),
16319 cur->subscribed == MWI_NOTIFICATION ? S_OR(mailbox_str->str, "<none>") : "<none>",
16320 cur->expiry
16321 );
16322 arg->numchans++;
16323 }
16324 return 0;
16325 }
16326
16327
16328
16329
16330
16331
16332 static char *sip_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16333 {
16334 struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
16335
16336
16337 if (cmd == CLI_INIT) {
16338 e->command = "sip show {channels|subscriptions}";
16339 e->usage =
16340 "Usage: sip show channels\n"
16341 " Lists all currently active SIP calls (dialogs).\n"
16342 "Usage: sip show subscriptions\n"
16343 " Lists active SIP subscriptions.\n";
16344 return NULL;
16345 } else if (cmd == CLI_GENERATE)
16346 return NULL;
16347
16348 if (a->argc != e->args)
16349 return CLI_SHOWUSAGE;
16350 arg.subscriptions = !strcasecmp(a->argv[e->args - 1], "subscriptions");
16351 if (!arg.subscriptions)
16352 ast_cli(arg.fd, FORMAT2, "Peer", "User/ANR", "Call ID", "Format", "Hold", "Last Message", "Expiry");
16353 else
16354 ast_cli(arg.fd, FORMAT3, "Peer", "User", "Call ID", "Extension", "Last state", "Type", "Mailbox", "Expiry");
16355
16356
16357 ao2_t_callback(dialogs, OBJ_NODATA, show_channels_cb, &arg, "callback to show channels");
16358
16359
16360 ast_cli(arg.fd, "%d active SIP %s%s\n", arg.numchans,
16361 (arg.subscriptions ? "subscription" : "dialog"),
16362 ESS(arg.numchans));
16363 return CLI_SUCCESS;
16364 #undef FORMAT
16365 #undef FORMAT2
16366 #undef FORMAT3
16367 }
16368
16369
16370
16371
16372
16373
16374 static char *complete_sipch(const char *line, const char *word, int pos, int state)
16375 {
16376 int which=0;
16377 struct sip_pvt *cur;
16378 char *c = NULL;
16379 int wordlen = strlen(word);
16380 struct ao2_iterator i;
16381
16382 if (pos != 3) {
16383 return NULL;
16384 }
16385
16386 i = ao2_iterator_init(dialogs, 0);
16387 while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
16388 sip_pvt_lock(cur);
16389 if (!strncasecmp(word, cur->callid, wordlen) && ++which > state) {
16390 c = ast_strdup(cur->callid);
16391 sip_pvt_unlock(cur);
16392 dialog_unref(cur, "drop ref in iterator loop break");
16393 break;
16394 }
16395 sip_pvt_unlock(cur);
16396 dialog_unref(cur, "drop ref in iterator loop");
16397 }
16398 ao2_iterator_destroy(&i);
16399 return c;
16400 }
16401
16402
16403
16404 static char *complete_sip_peer(const char *word, int state, int flags2)
16405 {
16406 char *result = NULL;
16407 int wordlen = strlen(word);
16408 int which = 0;
16409 struct ao2_iterator i = ao2_iterator_init(peers, 0);
16410 struct sip_peer *peer;
16411
16412 while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
16413
16414 if (!strncasecmp(word, peer->name, wordlen) &&
16415 (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
16416 ++which > state)
16417 result = ast_strdup(peer->name);
16418 unref_peer(peer, "toss iterator peer ptr before break");
16419 if (result) {
16420 break;
16421 }
16422 }
16423 ao2_iterator_destroy(&i);
16424 return result;
16425 }
16426
16427
16428 static char *complete_sip_registered_peer(const char *word, int state, int flags2)
16429 {
16430 char *result = NULL;
16431 int wordlen = strlen(word);
16432 int which = 0;
16433 struct ao2_iterator i;
16434 struct sip_peer *peer;
16435
16436 i = ao2_iterator_init(peers, 0);
16437 while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
16438 if (!strncasecmp(word, peer->name, wordlen) &&
16439 (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
16440 ++which > state && peer->expire > 0)
16441 result = ast_strdup(peer->name);
16442 if (result) {
16443 unref_peer(peer, "toss iterator peer ptr before break");
16444 break;
16445 }
16446 unref_peer(peer, "toss iterator peer ptr");
16447 }
16448 ao2_iterator_destroy(&i);
16449 return result;
16450 }
16451
16452
16453 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state)
16454 {
16455 if (pos == 3)
16456 return complete_sipch(line, word, pos, state);
16457
16458 return NULL;
16459 }
16460
16461
16462 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state)
16463 {
16464 if (pos == 3) {
16465 return complete_sip_peer(word, state, 0);
16466 }
16467
16468 return NULL;
16469 }
16470
16471
16472 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state)
16473 {
16474 if (pos == 2)
16475 return complete_sip_registered_peer(word, state, 0);
16476
16477 return NULL;
16478 }
16479
16480
16481 static char *complete_sipnotify(const char *line, const char *word, int pos, int state)
16482 {
16483 char *c = NULL;
16484
16485 if (pos == 2) {
16486 int which = 0;
16487 char *cat = NULL;
16488 int wordlen = strlen(word);
16489
16490
16491
16492 if (!notify_types)
16493 return NULL;
16494
16495 while ( (cat = ast_category_browse(notify_types, cat)) ) {
16496 if (!strncasecmp(word, cat, wordlen) && ++which > state) {
16497 c = ast_strdup(cat);
16498 break;
16499 }
16500 }
16501 return c;
16502 }
16503
16504 if (pos > 2)
16505 return complete_sip_peer(word, state, 0);
16506
16507 return NULL;
16508 }
16509
16510
16511 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16512 {
16513 struct sip_pvt *cur;
16514 size_t len;
16515 int found = 0;
16516 struct ao2_iterator i;
16517
16518 switch (cmd) {
16519 case CLI_INIT:
16520 e->command = "sip show channel";
16521 e->usage =
16522 "Usage: sip show channel <call-id>\n"
16523 " Provides detailed status on a given SIP dialog (identified by SIP call-id).\n";
16524 return NULL;
16525 case CLI_GENERATE:
16526 return complete_sipch(a->line, a->word, a->pos, a->n);
16527 }
16528
16529 if (a->argc != 4)
16530 return CLI_SHOWUSAGE;
16531 len = strlen(a->argv[3]);
16532
16533 i = ao2_iterator_init(dialogs, 0);
16534 while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
16535 sip_pvt_lock(cur);
16536
16537 if (!strncasecmp(cur->callid, a->argv[3], len)) {
16538 char formatbuf[SIPBUFSIZE/2];
16539 ast_cli(a->fd, "\n");
16540 if (cur->subscribed != NONE)
16541 ast_cli(a->fd, " * Subscription (type: %s)\n", subscription_type2str(cur->subscribed));
16542 else
16543 ast_cli(a->fd, " * SIP Call\n");
16544 ast_cli(a->fd, " Curr. trans. direction: %s\n", ast_test_flag(&cur->flags[0], SIP_OUTGOING) ? "Outgoing" : "Incoming");
16545 ast_cli(a->fd, " Call-ID: %s\n", cur->callid);
16546 ast_cli(a->fd, " Owner channel ID: %s\n", cur->owner ? cur->owner->name : "<none>");
16547 ast_cli(a->fd, " Our Codec Capability: %d\n", cur->capability);
16548 ast_cli(a->fd, " Non-Codec Capability (DTMF): %d\n", cur->noncodeccapability);
16549 ast_cli(a->fd, " Their Codec Capability: %d\n", cur->peercapability);
16550 ast_cli(a->fd, " Joint Codec Capability: %d\n", cur->jointcapability);
16551 ast_cli(a->fd, " Format: %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0) );
16552 ast_cli(a->fd, " T.38 support %s\n", cli_yesno(cur->udptl != NULL));
16553 ast_cli(a->fd, " Video support %s\n", cli_yesno(cur->vrtp != NULL));
16554 ast_cli(a->fd, " MaxCallBR: %d kbps\n", cur->maxcallbitrate);
16555 ast_cli(a->fd, " Theoretical Address: %s:%d\n", ast_inet_ntoa(cur->sa.sin_addr), ntohs(cur->sa.sin_port));
16556 ast_cli(a->fd, " Received Address: %s:%d\n", ast_inet_ntoa(cur->recv.sin_addr), ntohs(cur->recv.sin_port));
16557 ast_cli(a->fd, " SIP Transfer mode: %s\n", transfermode2str(cur->allowtransfer));
16558 ast_cli(a->fd, " NAT Support: %s\n", nat2str(ast_test_flag(&cur->flags[0], SIP_NAT)));
16559 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)" );
16560 ast_cli(a->fd, " Our Tag: %s\n", cur->tag);
16561 ast_cli(a->fd, " Their Tag: %s\n", cur->theirtag);
16562 ast_cli(a->fd, " SIP User agent: %s\n", cur->useragent);
16563 if (!ast_strlen_zero(cur->username))
16564 ast_cli(a->fd, " Username: %s\n", cur->username);
16565 if (!ast_strlen_zero(cur->peername))
16566 ast_cli(a->fd, " Peername: %s\n", cur->peername);
16567 if (!ast_strlen_zero(cur->uri))
16568 ast_cli(a->fd, " Original uri: %s\n", cur->uri);
16569 if (!ast_strlen_zero(cur->cid_num))
16570 ast_cli(a->fd, " Caller-ID: %s\n", cur->cid_num);
16571 ast_cli(a->fd, " Need Destroy: %s\n", cli_yesno(cur->needdestroy));
16572 ast_cli(a->fd, " Last Message: %s\n", cur->lastmsg);
16573 ast_cli(a->fd, " Promiscuous Redir: %s\n", cli_yesno(ast_test_flag(&cur->flags[0], SIP_PROMISCREDIR)));
16574 ast_cli(a->fd, " Route: %s\n", cur->route ? cur->route->hop : "N/A");
16575 ast_cli(a->fd, " DTMF Mode: %s\n", dtmfmode2str(ast_test_flag(&cur->flags[0], SIP_DTMF)));
16576 ast_cli(a->fd, " SIP Options: ");
16577 if (cur->sipoptions) {
16578 int x;
16579 for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
16580 if (cur->sipoptions & sip_options[x].id)
16581 ast_cli(a->fd, "%s ", sip_options[x].text);
16582 }
16583 ast_cli(a->fd, "\n");
16584 } else
16585 ast_cli(a->fd, "(none)\n");
16586
16587 if (!cur->stimer)
16588 ast_cli(a->fd, " Session-Timer: Uninitiallized\n");
16589 else {
16590 ast_cli(a->fd, " Session-Timer: %s\n", cur->stimer->st_active ? "Active" : "Inactive");
16591 if (cur->stimer->st_active == TRUE) {
16592 ast_cli(a->fd, " S-Timer Interval: %d\n", cur->stimer->st_interval);
16593 ast_cli(a->fd, " S-Timer Refresher: %s\n", strefresher2str(cur->stimer->st_ref));
16594 ast_cli(a->fd, " S-Timer Expirys: %d\n", cur->stimer->st_expirys);
16595 ast_cli(a->fd, " S-Timer Sched Id: %d\n", cur->stimer->st_schedid);
16596 ast_cli(a->fd, " S-Timer Peer Sts: %s\n", cur->stimer->st_active_peer_ua ? "Active" : "Inactive");
16597 ast_cli(a->fd, " S-Timer Cached Min-SE: %d\n", cur->stimer->st_cached_min_se);
16598 ast_cli(a->fd, " S-Timer Cached SE: %d\n", cur->stimer->st_cached_max_se);
16599 ast_cli(a->fd, " S-Timer Cached Ref: %s\n", strefresher2str(cur->stimer->st_cached_ref));
16600 ast_cli(a->fd, " S-Timer Cached Mode: %s\n", stmode2str(cur->stimer->st_cached_mode));
16601 }
16602 }
16603
16604 ast_cli(a->fd, "\n\n");
16605
16606 found++;
16607 }
16608
16609 sip_pvt_unlock(cur);
16610
16611 ao2_t_ref(cur, -1, "toss dialog ptr set by iterator_next");
16612 }
16613 ao2_iterator_destroy(&i);
16614
16615 if (!found)
16616 ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
16617
16618 return CLI_SUCCESS;
16619 }
16620
16621
16622 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16623 {
16624 struct sip_pvt *cur;
16625 size_t len;
16626 int found = 0;
16627 struct ao2_iterator i;
16628
16629 switch (cmd) {
16630 case CLI_INIT:
16631 e->command = "sip show history";
16632 e->usage =
16633 "Usage: sip show history <call-id>\n"
16634 " Provides detailed dialog history on a given SIP call (specified by call-id).\n";
16635 return NULL;
16636 case CLI_GENERATE:
16637 return complete_sip_show_history(a->line, a->word, a->pos, a->n);
16638 }
16639
16640 if (a->argc != 4)
16641 return CLI_SHOWUSAGE;
16642
16643 if (!recordhistory)
16644 ast_cli(a->fd, "\n***Note: History recording is currently DISABLED. Use 'sip set history on' to ENABLE.\n");
16645
16646 len = strlen(a->argv[3]);
16647
16648 i = ao2_iterator_init(dialogs, 0);
16649 while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
16650 sip_pvt_lock(cur);
16651 if (!strncasecmp(cur->callid, a->argv[3], len)) {
16652 struct sip_history *hist;
16653 int x = 0;
16654
16655 ast_cli(a->fd, "\n");
16656 if (cur->subscribed != NONE)
16657 ast_cli(a->fd, " * Subscription\n");
16658 else
16659 ast_cli(a->fd, " * SIP Call\n");
16660 if (cur->history)
16661 AST_LIST_TRAVERSE(cur->history, hist, list)
16662 ast_cli(a->fd, "%d. %s\n", ++x, hist->event);
16663 if (x == 0)
16664 ast_cli(a->fd, "Call '%s' has no history\n", cur->callid);
16665 found++;
16666 }
16667 sip_pvt_unlock(cur);
16668 ao2_t_ref(cur, -1, "toss dialog ptr from iterator_next");
16669 }
16670 ao2_iterator_destroy(&i);
16671
16672 if (!found)
16673 ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
16674
16675 return CLI_SUCCESS;
16676 }
16677
16678
16679 static void sip_dump_history(struct sip_pvt *dialog)
16680 {
16681 int x = 0;
16682 struct sip_history *hist;
16683 static int errmsg = 0;
16684
16685 if (!dialog)
16686 return;
16687
16688 if (!option_debug && !sipdebug) {
16689 if (!errmsg) {
16690 ast_log(LOG_NOTICE, "You must have debugging enabled (SIP or Asterisk) in order to dump SIP history.\n");
16691 errmsg = 1;
16692 }
16693 return;
16694 }
16695
16696 ast_debug(1, "\n---------- SIP HISTORY for '%s' \n", dialog->callid);
16697 if (dialog->subscribed)
16698 ast_debug(1, " * Subscription\n");
16699 else
16700 ast_debug(1, " * SIP Call\n");
16701 if (dialog->history)
16702 AST_LIST_TRAVERSE(dialog->history, hist, list)
16703 ast_debug(1, " %-3.3d. %s\n", ++x, hist->event);
16704 if (!x)
16705 ast_debug(1, "Call '%s' has no history\n", dialog->callid);
16706 ast_debug(1, "\n---------- END SIP HISTORY for '%s' \n", dialog->callid);
16707 }
16708
16709
16710
16711 static void handle_request_info(struct sip_pvt *p, struct sip_request *req)
16712 {
16713 char buf[1024];
16714 unsigned int event;
16715 const char *c = get_header(req, "Content-Type");
16716
16717
16718 if (!strcasecmp(c, "application/dtmf-relay") ||
16719 !strcasecmp(c, "application/vnd.nortelnetworks.digits")) {
16720 unsigned int duration = 0;
16721
16722 if (!p->owner) {
16723 transmit_response(p, "481 Call leg/transaction does not exist", req);
16724 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16725 return;
16726 }
16727
16728
16729 if (ast_strlen_zero(c = get_body(req, "Signal", '=')) && ast_strlen_zero(c = get_body(req, "d", '='))) {
16730 ast_log(LOG_WARNING, "Unable to retrieve DTMF signal from INFO message from %s\n", p->callid);
16731 transmit_response(p, "200 OK", req);
16732 return;
16733 } else {
16734 ast_copy_string(buf, c, sizeof(buf));
16735 }
16736
16737 if (!ast_strlen_zero((c = get_body(req, "Duration", '='))))
16738 duration = atoi(c);
16739 if (!duration)
16740 duration = 100;
16741
16742
16743 if (ast_strlen_zero(buf)) {
16744 transmit_response(p, "200 OK", req);
16745 return;
16746 }
16747
16748 if (buf[0] == '*')
16749 event = 10;
16750 else if (buf[0] == '#')
16751 event = 11;
16752 else if ((buf[0] >= 'A') && (buf[0] <= 'D'))
16753 event = 12 + buf[0] - 'A';
16754 else if (buf[0] == '!')
16755 event = 16;
16756 else
16757 event = atoi(buf);
16758 if (event == 16) {
16759
16760 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_FLASH, };
16761 ast_queue_frame(p->owner, &f);
16762 if (sipdebug)
16763 ast_verbose("* DTMF-relay event received: FLASH\n");
16764 } else {
16765
16766 struct ast_frame f = { AST_FRAME_DTMF, };
16767 if (event < 10) {
16768 f.subclass = '0' + event;
16769 } else if (event < 11) {
16770 f.subclass = '*';
16771 } else if (event < 12) {
16772 f.subclass = '#';
16773 } else if (event < 16) {
16774 f.subclass = 'A' + (event - 12);
16775 }
16776 f.len = duration;
16777 ast_queue_frame(p->owner, &f);
16778 if (sipdebug)
16779 ast_verbose("* DTMF-relay event received: %c\n", f.subclass);
16780 }
16781 transmit_response(p, "200 OK", req);
16782 return;
16783 } else if (!strcasecmp(c, "application/dtmf")) {
16784
16785 unsigned int duration = 0;
16786
16787 if (!p->owner) {
16788 transmit_response(p, "481 Call leg/transaction does not exist", req);
16789 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16790 return;
16791 }
16792
16793 get_msg_text(buf, sizeof(buf), req, TRUE);
16794 duration = 100;
16795
16796 if (ast_strlen_zero(buf)) {
16797 transmit_response(p, "200 OK", req);
16798 return;
16799 }
16800 event = atoi(buf);
16801 if (event == 16) {
16802
16803 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_FLASH, };
16804 ast_queue_frame(p->owner, &f);
16805 if (sipdebug)
16806 ast_verbose("* DTMF-relay event received: FLASH\n");
16807 } else {
16808
16809 struct ast_frame f = { AST_FRAME_DTMF, };
16810 if (event < 10) {
16811 f.subclass = '0' + event;
16812 } else if (event < 11) {
16813 f.subclass = '*';
16814 } else if (event < 12) {
16815 f.subclass = '#';
16816 } else if (event < 16) {
16817 f.subclass = 'A' + (event - 12);
16818 }
16819 f.len = duration;
16820 ast_queue_frame(p->owner, &f);
16821 if (sipdebug)
16822 ast_verbose("* DTMF-relay event received: %c\n", f.subclass);
16823 }
16824 transmit_response(p, "200 OK", req);
16825 return;
16826
16827 } else if (!strcasecmp(c, "application/media_control+xml")) {
16828
16829 if (p->owner)
16830 ast_queue_control(p->owner, AST_CONTROL_VIDUPDATE);
16831 transmit_response(p, "200 OK", req);
16832 return;
16833 } else if (!ast_strlen_zero(c = get_header(req, "X-ClientCode"))) {
16834
16835 if (ast_test_flag(&p->flags[0], SIP_USECLIENTCODE)) {
16836 if (p->owner && p->owner->cdr)
16837 ast_cdr_setuserfield(p->owner, c);
16838 if (p->owner && ast_bridged_channel(p->owner) && ast_bridged_channel(p->owner)->cdr)
16839 ast_cdr_setuserfield(ast_bridged_channel(p->owner), c);
16840 transmit_response(p, "200 OK", req);
16841 } else {
16842 transmit_response(p, "403 Forbidden", req);
16843 }
16844 return;
16845 } else if (!ast_strlen_zero(c = get_header(req, "Record"))) {
16846
16847
16848
16849
16850
16851
16852
16853 struct ast_call_feature *feat;
16854 int j;
16855 struct ast_frame f = { AST_FRAME_DTMF, };
16856
16857 ast_rdlock_call_features();
16858 feat = ast_find_call_feature("automon");
16859 if (!feat || ast_strlen_zero(feat->exten)) {
16860 ast_log(LOG_WARNING, "Recording requested, but no One Touch Monitor registered. (See features.conf)\n");
16861
16862 transmit_response(p, "403 Forbidden", req);
16863 ast_unlock_call_features();
16864 return;
16865 }
16866
16867 f.len = 100;
16868 for (j=0; j < strlen(feat->exten); j++) {
16869 f.subclass = feat->exten[j];
16870 ast_queue_frame(p->owner, &f);
16871 if (sipdebug)
16872 ast_verbose("* DTMF-relay event faked: %c\n", f.subclass);
16873 }
16874 ast_unlock_call_features();
16875
16876 ast_debug(1, "Got a Request to Record the channel, state %s\n", c);
16877 transmit_response(p, "200 OK", req);
16878 return;
16879 } else if (ast_strlen_zero(c = get_header(req, "Content-Length")) || !strcasecmp(c, "0")) {
16880
16881 transmit_response(p, "200 OK", req);
16882 return;
16883 }
16884
16885
16886
16887
16888 ast_log(LOG_WARNING, "Unable to parse INFO message from %s. Content %s\n", p->callid, buf);
16889 transmit_response(p, "415 Unsupported media type", req);
16890 return;
16891 }
16892
16893
16894 static char *sip_do_debug_ip(int fd, char *arg)
16895 {
16896 struct hostent *hp;
16897 struct ast_hostent ahp;
16898 int port = 0;
16899 char *p;
16900
16901 p = arg;
16902 strsep(&p, ":");
16903 if (p)
16904 port = atoi(p);
16905 hp = ast_gethostbyname(arg, &ahp);
16906 if (hp == NULL)
16907 return CLI_SHOWUSAGE;
16908
16909 debugaddr.sin_family = AF_INET;
16910 memcpy(&debugaddr.sin_addr, hp->h_addr, sizeof(debugaddr.sin_addr));
16911 debugaddr.sin_port = htons(port);
16912 if (port == 0)
16913 ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_inet_ntoa(debugaddr.sin_addr));
16914 else
16915 ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(debugaddr.sin_addr), port);
16916
16917 sipdebug |= sip_debug_console;
16918
16919 return CLI_SUCCESS;
16920 }
16921
16922
16923 static char *sip_do_debug_peer(int fd, char *arg)
16924 {
16925 struct sip_peer *peer = find_peer(arg, NULL, TRUE, FINDPEERS, FALSE, 0);
16926 if (!peer)
16927 ast_cli(fd, "No such peer '%s'\n", arg);
16928 else if (peer->addr.sin_addr.s_addr == 0)
16929 ast_cli(fd, "Unable to get IP address of peer '%s'\n", arg);
16930 else {
16931 debugaddr.sin_family = AF_INET;
16932 debugaddr.sin_addr = peer->addr.sin_addr;
16933 debugaddr.sin_port = peer->addr.sin_port;
16934 ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n",
16935 ast_inet_ntoa(debugaddr.sin_addr), ntohs(debugaddr.sin_port));
16936 sipdebug |= sip_debug_console;
16937 }
16938 if (peer)
16939 unref_peer(peer, "sip_do_debug_peer: unref_peer, from find_peer call");
16940 return CLI_SUCCESS;
16941 }
16942
16943
16944 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16945 {
16946 int oldsipdebug = sipdebug & sip_debug_console;
16947 char *what;
16948
16949 if (cmd == CLI_INIT) {
16950 e->command = "sip set debug {on|off|ip|peer}";
16951 e->usage =
16952 "Usage: sip set debug {off|on|ip addr[:port]|peer peername}\n"
16953 " Globally disables dumping of SIP packets,\n"
16954 " or enables it either globally or for a (single)\n"
16955 " IP address or registered peer.\n";
16956 return NULL;
16957 } else if (cmd == CLI_GENERATE) {
16958 if (a->pos == 4 && !strcasecmp(a->argv[3], "peer"))
16959 return complete_sip_peer(a->word, a->n, 0);
16960 return NULL;
16961 }
16962
16963 what = a->argv[e->args-1];
16964 if (a->argc == e->args) {
16965 if (!strcasecmp(what, "on")) {
16966 sipdebug |= sip_debug_console;
16967 sipdebug_text = 1;
16968 memset(&debugaddr, 0, sizeof(debugaddr));
16969 ast_cli(a->fd, "SIP Debugging %senabled\n", oldsipdebug ? "re-" : "");
16970 return CLI_SUCCESS;
16971 } else if (!strcasecmp(what, "off")) {
16972 sipdebug &= ~sip_debug_console;
16973 sipdebug_text = 0;
16974 ast_cli(a->fd, "SIP Debugging Disabled\n");
16975 return CLI_SUCCESS;
16976 }
16977 } else if (a->argc == e->args +1) {
16978 if (!strcasecmp(what, "ip"))
16979 return sip_do_debug_ip(a->fd, a->argv[e->args]);
16980 else if (!strcasecmp(what, "peer"))
16981 return sip_do_debug_peer(a->fd, a->argv[e->args]);
16982 }
16983 return CLI_SHOWUSAGE;
16984 }
16985
16986
16987 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16988 {
16989 struct ast_variable *varlist;
16990 int i;
16991
16992 switch (cmd) {
16993 case CLI_INIT:
16994 e->command = "sip notify";
16995 e->usage =
16996 "Usage: sip notify <type> <peer> [<peer>...]\n"
16997 " Send a NOTIFY message to a SIP peer or peers\n"
16998 " Message types are defined in sip_notify.conf\n";
16999 return NULL;
17000 case CLI_GENERATE:
17001 return complete_sipnotify(a->line, a->word, a->pos, a->n);
17002 }
17003
17004 if (a->argc < 4)
17005 return CLI_SHOWUSAGE;
17006
17007 if (!notify_types) {
17008 ast_cli(a->fd, "No %s file found, or no types listed there\n", notify_config);
17009 return CLI_FAILURE;
17010 }
17011
17012 varlist = ast_variable_browse(notify_types, a->argv[2]);
17013
17014 if (!varlist) {
17015 ast_cli(a->fd, "Unable to find notify type '%s'\n", a->argv[2]);
17016 return CLI_FAILURE;
17017 }
17018
17019 for (i = 3; i < a->argc; i++) {
17020 struct sip_pvt *p;
17021
17022 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
17023 ast_log(LOG_WARNING, "Unable to build sip pvt data for notify (memory/socket error)\n");
17024 return CLI_FAILURE;
17025 }
17026
17027 if (create_addr(p, a->argv[i], NULL, 1)) {
17028
17029 dialog_unlink_all(p, TRUE, TRUE);
17030 dialog_unref(p, "unref dialog inside for loop" );
17031
17032 ast_cli(a->fd, "Could not create address for '%s'\n", a->argv[i]);
17033 continue;
17034 }
17035
17036
17037 ast_set_flag(&p->flags[0], SIP_OUTGOING);
17038
17039
17040 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
17041 build_via(p);
17042 ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
17043 build_callid_pvt(p);
17044 ao2_t_link(dialogs, p, "Linking in new name");
17045 ast_cli(a->fd, "Sending NOTIFY of type '%s' to '%s'\n", a->argv[2], a->argv[i]);
17046 dialog_ref(p, "bump the count of p, which transmit_sip_request will decrement.");
17047 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
17048 transmit_notify_custom(p, varlist);
17049 }
17050
17051 return CLI_SUCCESS;
17052 }
17053
17054
17055 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17056 {
17057 switch (cmd) {
17058 case CLI_INIT:
17059 e->command = "sip set history {on|off}";
17060 e->usage =
17061 "Usage: sip set history {on|off}\n"
17062 " Enables/Disables recording of SIP dialog history for debugging purposes.\n"
17063 " Use 'sip show history' to view the history of a call number.\n";
17064 return NULL;
17065 case CLI_GENERATE:
17066 return NULL;
17067 }
17068
17069 if (a->argc != e->args)
17070 return CLI_SHOWUSAGE;
17071
17072 if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
17073 recordhistory = TRUE;
17074 ast_cli(a->fd, "SIP History Recording Enabled (use 'sip show history')\n");
17075 } else if (!strncasecmp(a->argv[e->args - 1], "off", 3)) {
17076 recordhistory = FALSE;
17077 ast_cli(a->fd, "SIP History Recording Disabled\n");
17078 } else {
17079 return CLI_SHOWUSAGE;
17080 }
17081 return CLI_SUCCESS;
17082 }
17083
17084
17085 static int do_register_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code)
17086 {
17087 char *header, *respheader;
17088 char digest[1024];
17089
17090 p->authtries++;
17091 auth_headers(code, &header, &respheader);
17092 memset(digest, 0, sizeof(digest));
17093 if (reply_digest(p, req, header, SIP_REGISTER, digest, sizeof(digest))) {
17094
17095
17096 if (sip_debug_test_pvt(p) && p->registry)
17097 ast_verbose("No authentication challenge, sending blank registration to domain/host name %s\n", p->registry->hostname);
17098
17099 return -1;
17100 }
17101 if (p->do_history)
17102 append_history(p, "RegistryAuth", "Try: %d", p->authtries);
17103 if (sip_debug_test_pvt(p) && p->registry)
17104 ast_verbose("Responding to challenge, registration to domain/host name %s\n", p->registry->hostname);
17105 return transmit_register(p->registry, SIP_REGISTER, digest, respheader);
17106 }
17107
17108
17109 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code, int sipmethod, int init)
17110 {
17111 char *header, *respheader;
17112 char digest[1024];
17113
17114 if (!p->options && !(p->options = ast_calloc(1, sizeof(*p->options))))
17115 return -2;
17116
17117 p->authtries++;
17118 auth_headers(code, &header, &respheader);
17119 ast_debug(2, "Auth attempt %d on %s\n", p->authtries, sip_methods[sipmethod].text);
17120 memset(digest, 0, sizeof(digest));
17121 if (reply_digest(p, req, header, sipmethod, digest, sizeof(digest) )) {
17122
17123 return -1;
17124 }
17125
17126 p->options->auth = digest;
17127 p->options->authheader = respheader;
17128 return transmit_invite(p, sipmethod, sipmethod == SIP_INVITE, init);
17129 }
17130
17131
17132
17133
17134
17135 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len)
17136 {
17137 char tmp[512];
17138 char *c;
17139 char oldnonce[256];
17140
17141
17142 const struct x {
17143 const char *key;
17144 const ast_string_field *field;
17145 } *i, keys[] = {
17146 { "realm=", &p->realm },
17147 { "nonce=", &p->nonce },
17148 { "opaque=", &p->opaque },
17149 { "qop=", &p->qop },
17150 { "domain=", &p->domain },
17151 { NULL, 0 },
17152 };
17153
17154 ast_copy_string(tmp, get_header(req, header), sizeof(tmp));
17155 if (ast_strlen_zero(tmp))
17156 return -1;
17157 if (strncasecmp(tmp, "Digest ", strlen("Digest "))) {
17158 ast_log(LOG_WARNING, "missing Digest.\n");
17159 return -1;
17160 }
17161 c = tmp + strlen("Digest ");
17162 ast_copy_string(oldnonce, p->nonce, sizeof(oldnonce));
17163 while (c && *(c = ast_skip_blanks(c))) {
17164 for (i = keys; i->key != NULL; i++) {
17165 char *src, *separator;
17166 if (strncasecmp(c, i->key, strlen(i->key)) != 0)
17167 continue;
17168
17169 c += strlen(i->key);
17170 if (*c == '"') {
17171 src = ++c;
17172 separator = "\"";
17173 } else {
17174 src = c;
17175 separator = ",";
17176 }
17177 strsep(&c, separator);
17178 ast_string_field_ptr_set(p, i->field, src);
17179 break;
17180 }
17181 if (i->key == NULL)
17182 strsep(&c, ",");
17183 }
17184
17185 if (strcmp(p->nonce, oldnonce))
17186 p->noncecount = 0;
17187
17188
17189 if (p->registry) {
17190 struct sip_registry *r = p->registry;
17191
17192 if (strcmp(r->nonce, p->nonce)) {
17193 ast_string_field_set(r, realm, p->realm);
17194 ast_string_field_set(r, nonce, p->nonce);
17195 ast_string_field_set(r, domain, p->domain);
17196 ast_string_field_set(r, opaque, p->opaque);
17197 ast_string_field_set(r, qop, p->qop);
17198 r->noncecount = 0;
17199 }
17200 }
17201 return build_reply_digest(p, sipmethod, digest, digest_len);
17202 }
17203
17204
17205
17206
17207
17208
17209 static int build_reply_digest(struct sip_pvt *p, int method, char* digest, int digest_len)
17210 {
17211 char a1[256];
17212 char a2[256];
17213 char a1_hash[256];
17214 char a2_hash[256];
17215 char resp[256];
17216 char resp_hash[256];
17217 char uri[256];
17218 char opaque[256] = "";
17219 char cnonce[80];
17220 const char *username;
17221 const char *secret;
17222 const char *md5secret;
17223 struct sip_auth *auth = NULL;
17224
17225 if (!ast_strlen_zero(p->domain))
17226 ast_copy_string(uri, p->domain, sizeof(uri));
17227 else if (!ast_strlen_zero(p->uri))
17228 ast_copy_string(uri, p->uri, sizeof(uri));
17229 else
17230 snprintf(uri, sizeof(uri), "sip:%s@%s", p->username, ast_inet_ntoa(p->sa.sin_addr));
17231
17232 snprintf(cnonce, sizeof(cnonce), "%08lx", ast_random());
17233
17234
17235 if(!(auth = find_realm_authentication(p->peerauth, p->realm)))
17236 auth = find_realm_authentication(authl, p->realm);
17237
17238 if (auth) {
17239 ast_debug(3, "use realm [%s] from peer [%s][%s]\n", auth->username, p->peername, p->username);
17240 username = auth->username;
17241 secret = auth->secret;
17242 md5secret = auth->md5secret;
17243 if (sipdebug)
17244 ast_debug(1, "Using realm %s authentication for call %s\n", p->realm, p->callid);
17245 } else {
17246
17247 username = p->authname;
17248 secret = p->peersecret;
17249 md5secret = p->peermd5secret;
17250 }
17251 if (ast_strlen_zero(username))
17252 return -1;
17253
17254
17255 snprintf(a1, sizeof(a1), "%s:%s:%s", username, p->realm, secret);
17256 snprintf(a2, sizeof(a2), "%s:%s", sip_methods[method].text, uri);
17257 if (!ast_strlen_zero(md5secret))
17258 ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
17259 else
17260 ast_md5_hash(a1_hash, a1);
17261 ast_md5_hash(a2_hash, a2);
17262
17263 p->noncecount++;
17264 if (!ast_strlen_zero(p->qop))
17265 snprintf(resp, sizeof(resp), "%s:%s:%08x:%s:%s:%s", a1_hash, p->nonce, p->noncecount, cnonce, "auth", a2_hash);
17266 else
17267 snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, p->nonce, a2_hash);
17268 ast_md5_hash(resp_hash, resp);
17269
17270
17271 if (!ast_strlen_zero(p->opaque)) {
17272 snprintf(opaque, sizeof(opaque), ", opaque=\"%s\"", p->opaque);
17273 }
17274
17275
17276 if (!ast_strlen_zero(p->qop))
17277 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);
17278 else
17279 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);
17280
17281 append_history(p, "AuthResp", "Auth response sent for %s in realm %s - nc %d", username, p->realm, p->noncecount);
17282
17283 return 0;
17284 }
17285
17286
17287 static int func_header_read(struct ast_channel *chan, const char *function, char *data, char *buf, size_t len)
17288 {
17289 struct sip_pvt *p;
17290 const char *content = NULL;
17291 AST_DECLARE_APP_ARGS(args,
17292 AST_APP_ARG(header);
17293 AST_APP_ARG(number);
17294 );
17295 int i, number, start = 0;
17296
17297 if (ast_strlen_zero(data)) {
17298 ast_log(LOG_WARNING, "This function requires a header name.\n");
17299 return -1;
17300 }
17301
17302 ast_channel_lock(chan);
17303 if (!IS_SIP_TECH(chan->tech)) {
17304 ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
17305 ast_channel_unlock(chan);
17306 return -1;
17307 }
17308
17309 AST_STANDARD_APP_ARGS(args, data);
17310 if (!args.number) {
17311 number = 1;
17312 } else {
17313 sscanf(args.number, "%30d", &number);
17314 if (number < 1)
17315 number = 1;
17316 }
17317
17318 p = chan->tech_pvt;
17319
17320
17321 if (!p) {
17322 ast_channel_unlock(chan);
17323 return -1;
17324 }
17325
17326 for (i = 0; i < number; i++)
17327 content = __get_header(&p->initreq, args.header, &start);
17328
17329 if (ast_strlen_zero(content)) {
17330 ast_channel_unlock(chan);
17331 return -1;
17332 }
17333
17334 ast_copy_string(buf, content, len);
17335 ast_channel_unlock(chan);
17336
17337 return 0;
17338 }
17339
17340 static struct ast_custom_function sip_header_function = {
17341 .name = "SIP_HEADER",
17342 .read = func_header_read,
17343 };
17344
17345
17346 static int func_check_sipdomain(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
17347 {
17348 if (ast_strlen_zero(data)) {
17349 ast_log(LOG_WARNING, "CHECKSIPDOMAIN requires an argument - A domain name\n");
17350 return -1;
17351 }
17352 if (check_sip_domain(data, NULL, 0))
17353 ast_copy_string(buf, data, len);
17354 else
17355 buf[0] = '\0';
17356 return 0;
17357 }
17358
17359 static struct ast_custom_function checksipdomain_function = {
17360 .name = "CHECKSIPDOMAIN",
17361 .read = func_check_sipdomain,
17362 };
17363
17364
17365 static int function_sippeer(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
17366 {
17367 struct sip_peer *peer;
17368 char *colname;
17369
17370 if ((colname = strchr(data, ':'))) {
17371 static int deprecation_warning = 0;
17372 *colname++ = '\0';
17373 if (deprecation_warning++ % 10 == 0)
17374 ast_log(LOG_WARNING, "SIPPEER(): usage of ':' to separate arguments is deprecated. Please use ',' instead.\n");
17375 } else if ((colname = strchr(data, ',')))
17376 *colname++ = '\0';
17377 else
17378 colname = "ip";
17379
17380 if (!(peer = find_peer(data, NULL, TRUE, FINDPEERS, FALSE, 0)))
17381 return -1;
17382
17383 if (!strcasecmp(colname, "ip")) {
17384 ast_copy_string(buf, peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "", len);
17385 } else if (!strcasecmp(colname, "port")) {
17386 snprintf(buf, len, "%d", ntohs(peer->addr.sin_port));
17387 } else if (!strcasecmp(colname, "status")) {
17388 peer_status(peer, buf, len);
17389 } else if (!strcasecmp(colname, "language")) {
17390 ast_copy_string(buf, peer->language, len);
17391 } else if (!strcasecmp(colname, "regexten")) {
17392 ast_copy_string(buf, peer->regexten, len);
17393 } else if (!strcasecmp(colname, "limit")) {
17394 snprintf(buf, len, "%d", peer->call_limit);
17395 } else if (!strcasecmp(colname, "busylevel")) {
17396 snprintf(buf, len, "%d", peer->busy_level);
17397 } else if (!strcasecmp(colname, "curcalls")) {
17398 snprintf(buf, len, "%d", peer->inUse);
17399 } else if (!strcasecmp(colname, "accountcode")) {
17400 ast_copy_string(buf, peer->accountcode, len);
17401 } else if (!strcasecmp(colname, "callgroup")) {
17402 ast_print_group(buf, len, peer->callgroup);
17403 } else if (!strcasecmp(colname, "pickupgroup")) {
17404 ast_print_group(buf, len, peer->pickupgroup);
17405 } else if (!strcasecmp(colname, "useragent")) {
17406 ast_copy_string(buf, peer->useragent, len);
17407 } else if (!strcasecmp(colname, "mailbox")) {
17408 struct ast_str *mailbox_str = ast_str_alloca(512);
17409 peer_mailboxes_to_str(&mailbox_str, peer);
17410 ast_copy_string(buf, mailbox_str->str, len);
17411 } else if (!strcasecmp(colname, "context")) {
17412 ast_copy_string(buf, peer->context, len);
17413 } else if (!strcasecmp(colname, "expire")) {
17414 snprintf(buf, len, "%d", peer->expire);
17415 } else if (!strcasecmp(colname, "dynamic")) {
17416 ast_copy_string(buf, peer->host_dynamic ? "yes" : "no", len);
17417 } else if (!strcasecmp(colname, "callerid_name")) {
17418 ast_copy_string(buf, peer->cid_name, len);
17419 } else if (!strcasecmp(colname, "callerid_num")) {
17420 ast_copy_string(buf, peer->cid_num, len);
17421 } else if (!strcasecmp(colname, "codecs")) {
17422 ast_getformatname_multiple(buf, len -1, peer->capability);
17423 } else if (!strncasecmp(colname, "chanvar[", 8)) {
17424 char *chanvar=colname + 8;
17425 struct ast_variable *v;
17426
17427 chanvar = strsep(&chanvar, "]");
17428 for (v = peer->chanvars ; v ; v = v->next) {
17429 if (!strcasecmp(v->name, chanvar)) {
17430 ast_copy_string(buf, v->value, len);
17431 }
17432 }
17433 } else if (!strncasecmp(colname, "codec[", 6)) {
17434 char *codecnum;
17435 int codec = 0;
17436
17437 codecnum = colname + 6;
17438 codecnum = strsep(&codecnum, "]");
17439 if((codec = ast_codec_pref_index(&peer->prefs, atoi(codecnum)))) {
17440 ast_copy_string(buf, ast_getformatname(codec), len);
17441 } else {
17442 buf[0] = '\0';
17443 }
17444 } else {
17445 buf[0] = '\0';
17446 }
17447
17448 unref_peer(peer, "unref_peer from function_sippeer, just before return");
17449
17450 return 0;
17451 }
17452
17453
17454 static struct ast_custom_function sippeer_function = {
17455 .name = "SIPPEER",
17456 .read = function_sippeer,
17457 };
17458
17459
17460 static int function_sipchaninfo_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
17461 {
17462 struct sip_pvt *p;
17463 static int deprecated = 0;
17464
17465 *buf = 0;
17466
17467 if (!data) {
17468 ast_log(LOG_WARNING, "This function requires a parameter name.\n");
17469 return -1;
17470 }
17471
17472 ast_channel_lock(chan);
17473 if (!IS_SIP_TECH(chan->tech)) {
17474 ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
17475 ast_channel_unlock(chan);
17476 return -1;
17477 }
17478
17479 if (deprecated++ % 20 == 0) {
17480
17481 ast_log(LOG_WARNING, "SIPCHANINFO() is deprecated. Please transition to using CHANNEL().\n");
17482 }
17483
17484 p = chan->tech_pvt;
17485
17486
17487 if (!p) {
17488 ast_channel_unlock(chan);
17489 return -1;
17490 }
17491
17492 if (!strcasecmp(data, "peerip")) {
17493 ast_copy_string(buf, p->sa.sin_addr.s_addr ? ast_inet_ntoa(p->sa.sin_addr) : "", len);
17494 } else if (!strcasecmp(data, "recvip")) {
17495 ast_copy_string(buf, p->recv.sin_addr.s_addr ? ast_inet_ntoa(p->recv.sin_addr) : "", len);
17496 } else if (!strcasecmp(data, "from")) {
17497 ast_copy_string(buf, p->from, len);
17498 } else if (!strcasecmp(data, "uri")) {
17499 ast_copy_string(buf, p->uri, len);
17500 } else if (!strcasecmp(data, "useragent")) {
17501 ast_copy_string(buf, p->useragent, len);
17502 } else if (!strcasecmp(data, "peername")) {
17503 ast_copy_string(buf, p->peername, len);
17504 } else if (!strcasecmp(data, "t38passthrough")) {
17505 if (p->t38.state == T38_DISABLED) {
17506 ast_copy_string(buf, "0", len);
17507 } else {
17508 ast_copy_string(buf, "1", len);
17509 }
17510 } else {
17511 ast_channel_unlock(chan);
17512 return -1;
17513 }
17514 ast_channel_unlock(chan);
17515
17516 return 0;
17517 }
17518
17519
17520 static struct ast_custom_function sipchaninfo_function = {
17521 .name = "SIPCHANINFO",
17522 .read = function_sipchaninfo_read,
17523 };
17524
17525
17526
17527
17528
17529
17530
17531 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req)
17532 {
17533 char tmp[SIPBUFSIZE];
17534 char *s, *e, *t, *trans;
17535 char *domain;
17536 enum sip_transport transport = SIP_TRANSPORT_UDP;
17537
17538 ast_copy_string(tmp, get_header(req, "Contact"), sizeof(tmp));
17539 if ((t = strchr(tmp, ',')))
17540 *t = '\0';
17541
17542 s = get_in_brackets(tmp);
17543 if ((trans = strcasestr(s, ";transport="))) do {
17544 trans += 11;
17545
17546 if ((e = strchr(trans, ';')))
17547 *e = '\0';
17548
17549 if (!strncasecmp(trans, "tcp", 3))
17550 transport = SIP_TRANSPORT_TCP;
17551 else if (!strncasecmp(trans, "tls", 3))
17552 transport = SIP_TRANSPORT_TLS;
17553 else {
17554 if (strncasecmp(trans, "udp", 3))
17555 ast_debug(1, "received contact with an invalid transport, '%s'\n", s);
17556
17557 transport = SIP_TRANSPORT_UDP;
17558 }
17559 } while(0);
17560 s = remove_uri_parameters(s);
17561
17562 if (p->socket.tcptls_session) {
17563 ao2_ref(p->socket.tcptls_session, -1);
17564 p->socket.tcptls_session = NULL;
17565 }
17566
17567 set_socket_transport(&p->socket, transport);
17568
17569 if (ast_test_flag(&p->flags[0], SIP_PROMISCREDIR)) {
17570 char *host = NULL;
17571 if (!strncasecmp(s, "sip:", 4))
17572 s += 4;
17573 else if (!strncasecmp(s, "sips:", 5))
17574 s += 5;
17575 e = strchr(s, '/');
17576 if (e)
17577 *e = '\0';
17578 if ((host = strchr(s, '@'))) {
17579 *host++ = '\0';
17580 ast_debug(2, "Found promiscuous redirection to 'SIP/%s::::%s@%s'\n", s, get_transport(transport), host);
17581 if (p->owner)
17582 ast_string_field_build(p->owner, call_forward, "SIP/%s::::%s@%s", s, get_transport(transport), host);
17583 } else {
17584 ast_debug(2, "Found promiscuous redirection to 'SIP/::::%s@%s'\n", get_transport(transport), s);
17585 if (p->owner)
17586 ast_string_field_build(p->owner, call_forward, "SIP/::::%s@%s", get_transport(transport), s);
17587 }
17588 } else {
17589 e = strchr(tmp, '@');
17590 if (e) {
17591 *e++ = '\0';
17592 domain = e;
17593 } else {
17594
17595 domain = tmp;
17596 }
17597 e = strchr(tmp, '/');
17598 if (e)
17599 *e = '\0';
17600
17601 if (!strncasecmp(s, "sip:", 4))
17602 s += 4;
17603 else if (!strncasecmp(s, "sips:", 5))
17604 s += 5;
17605 e = strchr(s, ';');
17606 if (e)
17607 *e = '\0';
17608 ast_uri_decode(s);
17609 ast_debug(2, "Received 302 Redirect to extension '%s' (domain %s)\n", s, domain);
17610 if (p->owner) {
17611 pbx_builtin_setvar_helper(p->owner, "SIPDOMAIN", domain);
17612 ast_string_field_set(p->owner, call_forward, s);
17613 }
17614 }
17615 }
17616
17617
17618 static void check_pendings(struct sip_pvt *p)
17619 {
17620 if (ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
17621
17622 if (p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA)
17623 transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
17624
17625
17626 else {
17627
17628
17629 if (p->pendinginvite)
17630 return;
17631
17632
17633 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, TRUE);
17634 }
17635 ast_clear_flag(&p->flags[0], SIP_PENDINGBYE);
17636 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17637 } else if (ast_test_flag(&p->flags[0], SIP_NEEDREINVITE)) {
17638
17639 if (p->pendinginvite || p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA || p->waitid > 0) {
17640 ast_debug(2, "NOT Sending pending reinvite (yet) on '%s'\n", p->callid);
17641 } else {
17642 ast_debug(2, "Sending pending reinvite on '%s'\n", p->callid);
17643
17644 transmit_reinvite_with_sdp(p, (p->t38.state == T38_LOCAL_REINVITE ? TRUE : FALSE), FALSE);
17645 ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);
17646 }
17647 }
17648 }
17649
17650
17651
17652
17653
17654 static int sip_reinvite_retry(const void *data)
17655 {
17656 struct sip_pvt *p = (struct sip_pvt *) data;
17657
17658 sip_pvt_lock(p);
17659 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
17660 p->waitid = -1;
17661 check_pendings(p);
17662 sip_pvt_unlock(p);
17663 dialog_unref(p, "unref the dialog ptr from sip_reinvite_retry, because it held a dialog ptr");
17664 return 0;
17665 }
17666
17667
17668
17669 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
17670 {
17671 int outgoing = ast_test_flag(&p->flags[0], SIP_OUTGOING);
17672 int res = 0;
17673 int xmitres = 0;
17674 int reinvite = (p->owner && p->owner->_state == AST_STATE_UP);
17675 char *p_hdrval;
17676 int rtn;
17677
17678 if (reinvite)
17679 ast_debug(4, "SIP response %d to RE-invite on %s call %s\n", resp, outgoing ? "outgoing" : "incoming", p->callid);
17680 else
17681 ast_debug(4, "SIP response %d to standard invite\n", resp);
17682
17683 if (p->alreadygone) {
17684 ast_debug(1, "Got response on call that is already terminated: %s (ignoring)\n", p->callid);
17685 return;
17686 }
17687
17688
17689
17690 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"));
17691
17692
17693
17694
17695 if (resp > 100 && resp < 200 && resp!=101 && resp != 180 && resp != 182 && resp != 183)
17696 resp = 183;
17697
17698
17699 if (resp >= 100 && resp < 200 && p->invitestate == INV_CALLING)
17700 p->invitestate = INV_PROCEEDING;
17701
17702
17703 if (resp >= 300 && (p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA ))
17704 p->invitestate = INV_COMPLETED;
17705
17706
17707 if ((resp == 200 || resp >= 300) && p->pendinginvite && seqno == p->pendinginvite)
17708 p->pendinginvite = 0;
17709
17710 switch (resp) {
17711 case 100:
17712 case 101:
17713 if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p))
17714 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
17715 check_pendings(p);
17716 break;
17717
17718 case 180:
17719 case 182:
17720 if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p))
17721 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
17722 if (!req->ignore && p->owner) {
17723 ast_queue_control(p->owner, AST_CONTROL_RINGING);
17724 if (p->owner->_state != AST_STATE_UP) {
17725 ast_setstate(p->owner, AST_STATE_RINGING);
17726 }
17727 }
17728 if (find_sdp(req)) {
17729 if (p->invitestate != INV_CANCELLED)
17730 p->invitestate = INV_EARLY_MEDIA;
17731 res = process_sdp(p, req, SDP_T38_NONE);
17732 if (!req->ignore && p->owner) {
17733
17734 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
17735 }
17736 }
17737 check_pendings(p);
17738 break;
17739
17740 case 183:
17741 if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
17742 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
17743 if (find_sdp(req)) {
17744 if (p->invitestate != INV_CANCELLED)
17745 p->invitestate = INV_EARLY_MEDIA;
17746 res = process_sdp(p, req, SDP_T38_NONE);
17747 if (!req->ignore && p->owner) {
17748
17749 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
17750 }
17751 } else {
17752
17753
17754
17755
17756 if (!req->ignore && p->owner) {
17757 ast_queue_control(p->owner, AST_CONTROL_RINGING);
17758 }
17759 }
17760 check_pendings(p);
17761 break;
17762
17763 case 200:
17764 if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
17765 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
17766 p->authtries = 0;
17767 if (find_sdp(req)) {
17768 if ((res = process_sdp(p, req, SDP_T38_ACCEPT)) && !req->ignore)
17769 if (!reinvite)
17770
17771
17772 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
17773 }
17774
17775
17776
17777
17778 if (outgoing) {
17779 update_call_counter(p, DEC_CALL_RINGING);
17780 parse_ok_contact(p, req);
17781
17782 if (!reinvite)
17783 build_route(p, req, 1);
17784
17785 if(set_address_from_contact(p)) {
17786
17787
17788 if (!p->route && !req->ignore)
17789 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
17790 }
17791
17792 }
17793
17794 if (!req->ignore && p->owner) {
17795 if (!reinvite) {
17796 ast_queue_control(p->owner, AST_CONTROL_ANSWER);
17797 if (sip_cfg.callevents)
17798 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
17799 "Channel: %s\r\nChanneltype: %s\r\nUniqueid: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
17800 p->owner->name, "SIP", p->owner->uniqueid, p->callid, p->fullcontact, p->peername);
17801 } else {
17802 ast_queue_frame(p->owner, &ast_null_frame);
17803 }
17804 } else {
17805
17806
17807
17808 if (!req->ignore)
17809 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
17810 }
17811
17812
17813 if (st_get_mode(p) != SESSION_TIMER_MODE_REFUSE && p->outgoing_call == TRUE && !reinvite) {
17814 p_hdrval = (char*)get_header(req, "Session-Expires");
17815 if (!ast_strlen_zero(p_hdrval)) {
17816
17817 enum st_refresher tmp_st_ref = SESSION_TIMER_REFRESHER_AUTO;
17818 int tmp_st_interval = 0;
17819 rtn = parse_session_expires(p_hdrval, &tmp_st_interval, &tmp_st_ref);
17820 if (rtn != 0) {
17821 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
17822 }
17823 if (tmp_st_ref == SESSION_TIMER_REFRESHER_UAC ||
17824 tmp_st_ref == SESSION_TIMER_REFRESHER_UAS) {
17825 p->stimer->st_ref = tmp_st_ref;
17826 }
17827 if (tmp_st_interval) {
17828 p->stimer->st_interval = tmp_st_interval;
17829 }
17830 p->stimer->st_active = TRUE;
17831 p->stimer->st_active_peer_ua = TRUE;
17832 start_session_timer(p);
17833 } else {
17834
17835 if (st_get_mode(p) == SESSION_TIMER_MODE_ORIGINATE) {
17836 p->stimer->st_ref = SESSION_TIMER_REFRESHER_UAC;
17837 p->stimer->st_active_peer_ua = FALSE;
17838 start_session_timer(p);
17839 }
17840 }
17841 }
17842
17843
17844
17845 p->invitestate = INV_TERMINATED;
17846 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
17847 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, TRUE);
17848 check_pendings(p);
17849 break;
17850
17851 case 407:
17852 case 401:
17853
17854 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17855 if (p->options)
17856 p->options->auth_type = resp;
17857
17858
17859 ast_string_field_set(p, theirtag, NULL);
17860 if (!req->ignore) {
17861 if (p->authtries < MAX_AUTHTRIES)
17862 p->invitestate = INV_CALLING;
17863 if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, SIP_INVITE, 1)) {
17864 ast_log(LOG_NOTICE, "Failed to authenticate on INVITE to '%s'\n", get_header(&p->initreq, "From"));
17865 pvt_set_needdestroy(p, "failed to authenticate on INVITE");
17866 sip_alreadygone(p);
17867 if (p->owner)
17868 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17869 }
17870 }
17871 break;
17872
17873 case 403:
17874
17875 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17876 ast_log(LOG_WARNING, "Received response: \"Forbidden\" from '%s'\n", get_header(&p->initreq, "From"));
17877 if (!req->ignore && p->owner)
17878 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17879 pvt_set_needdestroy(p, "received 403 response");
17880 sip_alreadygone(p);
17881 break;
17882
17883 case 404:
17884 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17885 if (p->owner && !req->ignore)
17886 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17887 sip_alreadygone(p);
17888 break;
17889
17890 case 408:
17891 case 481:
17892
17893 ast_log(LOG_WARNING, "Re-invite to non-existing call leg on other UA. SIP dialog '%s'. Giving up.\n", p->callid);
17894 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17895 if (p->owner)
17896 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17897 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17898 break;
17899
17900 case 422:
17901 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17902 ast_string_field_set(p, theirtag, NULL);
17903 proc_422_rsp(p, req);
17904 break;
17905
17906 case 428:
17907 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17908 append_history(p, "Identity", "SIP identity is required. Not supported by Asterisk.");
17909 ast_log(LOG_WARNING, "SIP identity required by proxy. SIP dialog '%s'. Giving up.\n", p->callid);
17910 if (p->owner)
17911 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17912 break;
17913
17914
17915
17916 case 487:
17917
17918
17919
17920 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17921 if (p->owner && !req->ignore) {
17922 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_NORMAL_CLEARING);
17923 append_history(p, "Hangup", "Got 487 on CANCEL request from us. Queued AST hangup request");
17924 } else if (!req->ignore) {
17925 update_call_counter(p, DEC_CALL_LIMIT);
17926 append_history(p, "Hangup", "Got 487 on CANCEL request from us on call without owner. Killing this dialog.");
17927 pvt_set_needdestroy(p, "received 487 response");
17928 sip_alreadygone(p);
17929 }
17930 break;
17931 case 415:
17932 case 488:
17933 case 606:
17934 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17935 if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
17936 change_t38_state(p, T38_DISABLED);
17937
17938 ast_rtp_set_rtptimers_onhold(p->rtp);
17939
17940
17941 transmit_reinvite_with_sdp(p, FALSE, FALSE);
17942 } else {
17943
17944 if (p->owner && !req->ignore)
17945 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17946 pvt_set_needdestroy(p, "received 488 response");
17947
17948 if (!reinvite)
17949 sip_alreadygone(p);
17950 }
17951 break;
17952 case 491:
17953 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17954 if (p->owner && !req->ignore) {
17955 if (p->owner->_state != AST_STATE_UP) {
17956 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17957 pvt_set_needdestroy(p, "received 491 response");
17958 } else {
17959
17960
17961
17962 int wait;
17963
17964
17965 if (p->outgoing_call) {
17966 wait = 2100 + ast_random() % 2000;
17967 } else {
17968 wait = ast_random() % 2000;
17969 }
17970 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."));
17971 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);
17972 ast_debug(2, "Reinvite race. Waiting %d secs before retry\n", wait);
17973 }
17974 }
17975 break;
17976
17977 case 501:
17978 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17979 if (p->owner)
17980 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17981 break;
17982 }
17983 if (xmitres == XMIT_ERROR)
17984 ast_log(LOG_WARNING, "Could not transmit message in dialog %s\n", p->callid);
17985 }
17986
17987
17988
17989
17990 static void handle_response_notify(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
17991 {
17992 switch (resp) {
17993 case 200:
17994
17995 if (p->owner) {
17996 if (!p->refer) {
17997 ast_log(LOG_WARNING, "Notify answer on an owned channel? - %s\n", p->owner->name);
17998 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_NORMAL_UNSPECIFIED);
17999 } else {
18000 ast_debug(4, "Got OK on REFER Notify message\n");
18001 }
18002 } else {
18003 if (p->subscribed == NONE) {
18004 ast_debug(4, "Got 200 accepted on NOTIFY\n");
18005 pvt_set_needdestroy(p, "received 200 response");
18006 }
18007 if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
18008
18009 ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
18010 cb_extensionstate((char *)p->context, (char *)p->exten, p->laststate, (void *) p);
18011 }
18012 }
18013 break;
18014 case 401:
18015 case 407:
18016 if (!p->notify_headers) {
18017 break;
18018 }
18019 ast_string_field_set(p, theirtag, NULL);
18020 if (ast_strlen_zero(p->authname)) {
18021 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));
18022 pvt_set_needdestroy(p, "unable to authenticate NOTIFY");
18023 }
18024 if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_NOTIFY, 0)) {
18025 ast_log(LOG_NOTICE, "Failed to authenticate on NOTIFY to '%s'\n", get_header(&p->initreq, "From"));
18026 pvt_set_needdestroy(p, "failed to authenticate NOTIFY");
18027 }
18028 break;
18029 }
18030 }
18031
18032
18033 static void handle_response_subscribe(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
18034 {
18035 if (!p->mwi) {
18036 return;
18037 }
18038
18039 switch (resp) {
18040 case 200:
18041 ast_debug(3, "Got 200 OK on subscription for MWI\n");
18042 if (p->options) {
18043 ast_free(p->options);
18044 p->options = NULL;
18045 }
18046 p->mwi->subscribed = 1;
18047 if ((p->mwi->resub = ast_sched_add(sched, mwi_expiry * 1000, sip_subscribe_mwi_do, ASTOBJ_REF(p->mwi))) < 0) {
18048 ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18049 }
18050 break;
18051 case 401:
18052 case 407:
18053 ast_string_field_set(p, theirtag, NULL);
18054 if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_SUBSCRIBE, 0)) {
18055 ast_log(LOG_NOTICE, "Failed to authenticate on SUBSCRIBE to '%s'\n", get_header(&p->initreq, "From"));
18056 p->mwi->call = NULL;
18057 ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18058 pvt_set_needdestroy(p, "failed to authenticate SUBSCRIBE");
18059 }
18060 break;
18061 case 403:
18062 transmit_response_with_date(p, "200 OK", req);
18063 ast_log(LOG_WARNING, "Authentication failed while trying to subscribe for MWI.\n");
18064 p->mwi->call = NULL;
18065 ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18066 pvt_set_needdestroy(p, "received 403 response");
18067 sip_alreadygone(p);
18068 break;
18069 case 404:
18070 ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side said that a mailbox may not have been configured.\n");
18071 p->mwi->call = NULL;
18072 ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18073 pvt_set_needdestroy(p, "received 404 response");
18074 break;
18075 case 481:
18076 ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side said that our dialog did not exist.\n");
18077 p->mwi->call = NULL;
18078 ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18079 pvt_set_needdestroy(p, "received 481 response");
18080 break;
18081 case 500:
18082 case 501:
18083 ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side may have suffered a heart attack.\n");
18084 p->mwi->call = NULL;
18085 ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
18086 pvt_set_needdestroy(p, "received 500/501 response");
18087 break;
18088 }
18089 }
18090
18091
18092
18093
18094 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
18095 {
18096
18097 if (!p->refer)
18098 return;
18099
18100 switch (resp) {
18101 case 202:
18102
18103
18104 p->refer->status = REFER_ACCEPTED;
18105
18106 ast_debug(3, "Got 202 accepted on transfer\n");
18107
18108 break;
18109
18110 case 401:
18111 case 407:
18112 if (ast_strlen_zero(p->authname)) {
18113 ast_log(LOG_WARNING, "Asked to authenticate REFER to %s:%d but we have no matching peer or realm auth!\n",
18114 ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
18115 pvt_set_needdestroy(p, "unable to authenticate REFER");
18116 }
18117 if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_REFER, 0)) {
18118 ast_log(LOG_NOTICE, "Failed to authenticate on REFER to '%s'\n", get_header(&p->initreq, "From"));
18119 p->refer->status = REFER_NOAUTH;
18120 pvt_set_needdestroy(p, "failed to authenticat REFER");
18121 }
18122 break;
18123 case 481:
18124
18125
18126
18127
18128 ast_log(LOG_WARNING, "Remote host can't match REFER request to call '%s'. Giving up.\n", p->callid);
18129 if (p->owner)
18130 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18131 pvt_set_needdestroy(p, "received 481 response");
18132 break;
18133
18134 case 500:
18135 case 501:
18136
18137
18138 ast_log(LOG_NOTICE, "SIP transfer to %s failed, call miserably fails. \n", p->refer->refer_to);
18139 pvt_set_needdestroy(p, "received 500/501 response");
18140 p->refer->status = REFER_FAILED;
18141 break;
18142 case 603:
18143 ast_log(LOG_NOTICE, "SIP transfer to %s declined, call miserably fails. \n", p->refer->refer_to);
18144 p->refer->status = REFER_FAILED;
18145 pvt_set_needdestroy(p, "received 603 response");
18146 break;
18147 }
18148 }
18149
18150
18151 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
18152 {
18153 int expires, expires_ms;
18154 struct sip_registry *r;
18155 r=p->registry;
18156
18157 switch (resp) {
18158 case 401:
18159 if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
18160 ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s@%s' (Tries %d)\n", p->registry->username, p->registry->hostname, p->authtries);
18161 pvt_set_needdestroy(p, "failed to authenticate REGISTER");
18162 }
18163 break;
18164 case 403:
18165 ast_log(LOG_WARNING, "Forbidden - wrong password on authentication for REGISTER for '%s' to '%s'\n", p->registry->username, p->registry->hostname);
18166 AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 403"));
18167 r->regstate = REG_STATE_NOAUTH;
18168 pvt_set_needdestroy(p, "received 403 response");
18169 break;
18170 case 404:
18171 ast_log(LOG_WARNING, "Got 404 Not found on SIP register to service %s@%s, giving up\n", p->registry->username, p->registry->hostname);
18172 pvt_set_needdestroy(p, "received 404 response");
18173 if (r->call)
18174 r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 404");
18175 r->regstate = REG_STATE_REJECTED;
18176 AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 404"));
18177 break;
18178 case 407:
18179 if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
18180 ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s' (tries '%d')\n", get_header(&p->initreq, "From"), p->authtries);
18181 pvt_set_needdestroy(p, "failed to authenticate REGISTER");
18182 }
18183 break;
18184 case 408:
18185
18186 if (r) {
18187 r->regattempts = 0;
18188 } else {
18189 ast_log(LOG_WARNING, "Got a 408 response to our REGISTER on call %s after we had destroyed the registry object\n", p->callid);
18190 }
18191 break;
18192 case 423:
18193 r->expiry = atoi(get_header(req, "Min-Expires"));
18194 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);
18195 AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 423"));
18196 if (r->call) {
18197 r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 423");
18198 pvt_set_needdestroy(p, "received 423 response");
18199 }
18200 if (r->expiry > max_expiry) {
18201 ast_log(LOG_WARNING, "Required expiration time from %s@%s is too high, giving up\n", p->registry->username, p->registry->hostname);
18202 r->expiry = r->configured_expiry;
18203 r->regstate = REG_STATE_REJECTED;
18204 } else {
18205 r->regstate = REG_STATE_UNREGISTERED;
18206 transmit_register(r, SIP_REGISTER, NULL, NULL);
18207 }
18208 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));
18209 break;
18210 case 479:
18211 ast_log(LOG_WARNING, "Got error 479 on register to %s@%s, giving up (check config)\n", p->registry->username, p->registry->hostname);
18212 pvt_set_needdestroy(p, "received 479 response");
18213 if (r->call)
18214 r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 479");
18215 r->regstate = REG_STATE_REJECTED;
18216 AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 479"));
18217 break;
18218 case 200:
18219 if (!r) {
18220 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));
18221 pvt_set_needdestroy(p, "received erroneous 200 response");
18222 return 0;
18223 }
18224
18225 r->regstate = REG_STATE_REGISTERED;
18226 r->regtime = ast_tvnow();
18227 manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelType: SIP\r\nDomain: %s\r\nStatus: %s\r\n", r->hostname, regstate2str(r->regstate));
18228 r->regattempts = 0;
18229 ast_debug(1, "Registration successful\n");
18230 if (r->timeout > -1) {
18231 ast_debug(1, "Cancelling timeout %d\n", r->timeout);
18232 }
18233 AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 200"));
18234 if (r->call)
18235 r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 200");
18236 p->registry = registry_unref(p->registry, "unref registry entry p->registry");
18237
18238 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18239
18240
18241
18242
18243
18244
18245 expires = 0;
18246
18247
18248 if (!ast_strlen_zero(get_header(req, "Contact"))) {
18249 const char *contact = NULL;
18250 const char *tmptmp = NULL;
18251 int start = 0;
18252 for(;;) {
18253 contact = __get_header(req, "Contact", &start);
18254
18255 if(!ast_strlen_zero(contact)) {
18256 if( (tmptmp=strstr(contact, p->our_contact))) {
18257 contact=tmptmp;
18258 break;
18259 }
18260 } else
18261 break;
18262 }
18263 tmptmp = strcasestr(contact, "expires=");
18264 if (tmptmp) {
18265 if (sscanf(tmptmp + 8, "%30d;", &expires) != 1)
18266 expires = 0;
18267 }
18268
18269 }
18270 if (!expires)
18271 expires=atoi(get_header(req, "expires"));
18272 if (!expires)
18273 expires=default_expiry;
18274
18275 expires_ms = expires * 1000;
18276 if (expires <= EXPIRY_GUARD_LIMIT)
18277 expires_ms -= MAX((expires_ms * EXPIRY_GUARD_PCT), EXPIRY_GUARD_MIN);
18278 else
18279 expires_ms -= EXPIRY_GUARD_SECS * 1000;
18280 if (sipdebug)
18281 ast_log(LOG_NOTICE, "Outbound Registration: Expiry for %s is %d sec (Scheduling reregistration in %d s)\n", r->hostname, expires, expires_ms/1000);
18282
18283 r->refresh= (int) expires_ms / 1000;
18284
18285
18286 AST_SCHED_REPLACE_UNREF(r->expire, sched, expires_ms, sip_reregister, r,
18287 registry_unref(_data,"unref in REPLACE del fail"),
18288 registry_unref(r,"unref in REPLACE add fail"),
18289 registry_addref(r,"The Addition side of REPLACE"));
18290 }
18291 return 1;
18292 }
18293
18294
18295 static void handle_response_peerpoke(struct sip_pvt *p, int resp, struct sip_request *req)
18296 {
18297 struct sip_peer *peer = p->relatedpeer ;
18298 int statechanged, is_reachable, was_reachable;
18299 int pingtime = ast_tvdiff_ms(ast_tvnow(), peer->ps);
18300
18301
18302
18303
18304
18305
18306 if (pingtime < 1)
18307 pingtime = 1;
18308
18309
18310
18311
18312
18313 was_reachable = peer->lastms > 0 && peer->lastms <= peer->maxms;
18314 is_reachable = pingtime <= peer->maxms;
18315 statechanged = peer->lastms == 0
18316 || was_reachable != is_reachable;
18317
18318 peer->lastms = pingtime;
18319 peer->call = dialog_unref(peer->call, "unref dialog peer->call");
18320 if (statechanged) {
18321 const char *s = is_reachable ? "Reachable" : "Lagged";
18322 char str_lastms[20];
18323 snprintf(str_lastms, sizeof(str_lastms), "%d", pingtime);
18324
18325 ast_log(LOG_NOTICE, "Peer '%s' is now %s. (%dms / %dms)\n",
18326 peer->name, s, pingtime, peer->maxms);
18327 ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
18328 if (sip_cfg.peer_rtupdate) {
18329 ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", str_lastms, SENTINEL);
18330 }
18331 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
18332 "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: %s\r\nTime: %d\r\n",
18333 peer->name, s, pingtime);
18334 if (is_reachable && sip_cfg.regextenonqualify)
18335 register_peer_exten(peer, TRUE);
18336 }
18337
18338 pvt_set_needdestroy(p, "got OPTIONS response");
18339
18340
18341 AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
18342 is_reachable ? peer->qualifyfreq : DEFAULT_FREQ_NOTOK,
18343 sip_poke_peer_s, peer,
18344 unref_peer(_data, "removing poke peer ref"),
18345 unref_peer(peer, "removing poke peer ref"),
18346 ref_peer(peer, "adding poke peer ref"));
18347 }
18348
18349
18350 static void stop_media_flows(struct sip_pvt *p)
18351 {
18352
18353 if (p->rtp)
18354 ast_rtp_stop(p->rtp);
18355 if (p->vrtp)
18356 ast_rtp_stop(p->vrtp);
18357 if (p->trtp)
18358 ast_rtp_stop(p->trtp);
18359 if (p->udptl)
18360 ast_udptl_stop(p->udptl);
18361 }
18362
18363
18364
18365 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
18366 {
18367 struct ast_channel *owner;
18368 int sipmethod;
18369 int res = 1;
18370 const char *c = get_header(req, "Cseq");
18371
18372 char *c_copy = ast_strdupa(c);
18373
18374 const char *msg = ast_skip_blanks(ast_skip_nonblanks(c_copy));
18375
18376 if (!msg)
18377 msg = "";
18378
18379 sipmethod = find_sip_method(msg);
18380
18381 owner = p->owner;
18382 if (owner)
18383 owner->hangupcause = hangup_sip2cause(resp);
18384
18385 if (p->socket.type == SIP_TRANSPORT_UDP) {
18386 int ack_res;
18387
18388
18389 if ((resp >= 100) && (resp <= 199)) {
18390 ack_res = __sip_semi_ack(p, seqno, 0, sipmethod);
18391 } else {
18392 ack_res = __sip_ack(p, seqno, 0, sipmethod);
18393 }
18394
18395 if (ack_res == FALSE) {
18396 append_history(p, "Ignore", "Ignoring this retransmit\n");
18397 return;
18398 }
18399 }
18400
18401
18402 if (!p->owner && sipmethod == SIP_NOTIFY && p->pendinginvite)
18403 p->pendinginvite = 0;
18404
18405
18406 if (ast_strlen_zero(p->theirtag) || (resp >= 200)) {
18407 char tag[128];
18408
18409 gettag(req, "To", tag, sizeof(tag));
18410 ast_string_field_set(p, theirtag, tag);
18411 }
18412
18413
18414
18415
18416
18417
18418
18419
18420
18421
18422
18423
18424
18425
18426
18427 if ((resp == 404 || resp == 408 || resp == 481) && sipmethod == SIP_BYE) {
18428 pvt_set_needdestroy(p, "received 4XX response to a BYE");
18429 return;
18430 }
18431
18432 if (p->relatedpeer && p->method == SIP_OPTIONS) {
18433
18434
18435
18436 if (resp != 100)
18437 handle_response_peerpoke(p, resp, req);
18438 } else if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
18439 switch(resp) {
18440 case 100:
18441 case 101:
18442 case 183:
18443 case 180:
18444 case 182:
18445 if (sipmethod == SIP_INVITE)
18446 handle_response_invite(p, resp, rest, req, seqno);
18447 break;
18448 case 200:
18449 p->authtries = 0;
18450 if (sipmethod == SIP_MESSAGE || sipmethod == SIP_INFO) {
18451
18452
18453
18454 } else if (sipmethod == SIP_INVITE) {
18455 handle_response_invite(p, resp, rest, req, seqno);
18456 } else if (sipmethod == SIP_NOTIFY) {
18457 handle_response_notify(p, resp, rest, req, seqno);
18458 } else if (sipmethod == SIP_REGISTER) {
18459 res = handle_response_register(p, resp, rest, req, seqno);
18460 } else if (sipmethod == SIP_SUBSCRIBE) {
18461 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
18462 handle_response_subscribe(p, resp, rest, req, seqno);
18463 } else if (sipmethod == SIP_BYE) {
18464 pvt_set_needdestroy(p, "received 200 response");
18465 ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
18466 }
18467 break;
18468 case 202:
18469 if (sipmethod == SIP_REFER)
18470 handle_response_refer(p, resp, rest, req, seqno);
18471 break;
18472 case 401:
18473 case 407:
18474 if (sipmethod == SIP_INVITE)
18475 handle_response_invite(p, resp, rest, req, seqno);
18476 else if (sipmethod == SIP_NOTIFY)
18477 handle_response_notify(p, resp, rest, req, seqno);
18478 else if (sipmethod == SIP_REFER)
18479 handle_response_refer(p, resp, rest, req, seqno);
18480 else if (sipmethod == SIP_SUBSCRIBE)
18481 handle_response_subscribe(p, resp, rest, req, seqno);
18482 else if (p->registry && sipmethod == SIP_REGISTER)
18483 res = handle_response_register(p, resp, rest, req, seqno);
18484 else if (sipmethod == SIP_BYE) {
18485 if (p->options)
18486 p->options->auth_type = resp;
18487 if (ast_strlen_zero(p->authname)) {
18488 ast_log(LOG_WARNING, "Asked to authenticate %s, to %s:%d but we have no matching peer!\n",
18489 msg, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
18490 pvt_set_needdestroy(p, "unable to authenticate BYE");
18491 } else if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp, sipmethod, 0)) {
18492 ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
18493 pvt_set_needdestroy(p, "failed to authenticate BYE");
18494 }
18495 } else {
18496 ast_log(LOG_WARNING, "Got authentication request (%d) on %s to '%s'\n", resp, sip_methods[sipmethod].text, get_header(req, "To"));
18497 pvt_set_needdestroy(p, "received 407 response");
18498 }
18499 break;
18500 case 403:
18501 if (sipmethod == SIP_INVITE)
18502 handle_response_invite(p, resp, rest, req, seqno);
18503 else if (sipmethod == SIP_SUBSCRIBE)
18504 handle_response_subscribe(p, resp, rest, req, seqno);
18505 else if (p->registry && sipmethod == SIP_REGISTER)
18506 res = handle_response_register(p, resp, rest, req, seqno);
18507 else {
18508 ast_log(LOG_WARNING, "Forbidden - maybe wrong password on authentication for %s\n", msg);
18509 pvt_set_needdestroy(p, "received 403 response");
18510 }
18511 break;
18512 case 404:
18513 if (p->registry && sipmethod == SIP_REGISTER)
18514 res = handle_response_register(p, resp, rest, req, seqno);
18515 else if (sipmethod == SIP_INVITE)
18516 handle_response_invite(p, resp, rest, req, seqno);
18517 else if (sipmethod == SIP_SUBSCRIBE)
18518 handle_response_subscribe(p, resp, rest, req, seqno);
18519 else if (owner)
18520 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18521 break;
18522 case 423:
18523 if (sipmethod == SIP_REGISTER)
18524 res = handle_response_register(p, resp, rest, req, seqno);
18525 break;
18526 case 408:
18527 if (sipmethod == SIP_INVITE)
18528 handle_response_invite(p, resp, rest, req, seqno);
18529 else if (sipmethod == SIP_REGISTER)
18530 res = handle_response_register(p, resp, rest, req, seqno);
18531 else if (sipmethod == SIP_BYE) {
18532 pvt_set_needdestroy(p, "received 408 response");
18533 ast_debug(4, "Got timeout on bye. Thanks for the answer. Now, kill this call\n");
18534 } else {
18535 if (owner)
18536 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18537 pvt_set_needdestroy(p, "received 408 response");
18538 }
18539 break;
18540
18541 case 422:
18542 if (sipmethod == SIP_INVITE) {
18543 handle_response_invite(p, resp, rest, req, seqno);
18544 }
18545 break;
18546
18547 case 481:
18548 if (sipmethod == SIP_INVITE) {
18549 handle_response_invite(p, resp, rest, req, seqno);
18550 } else if (sipmethod == SIP_REFER) {
18551 handle_response_refer(p, resp, rest, req, seqno);
18552 } else if (sipmethod == SIP_SUBSCRIBE) {
18553 handle_response_subscribe(p, resp, rest, req, seqno);
18554 } else if (sipmethod == SIP_BYE) {
18555
18556
18557 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
18558 } else if (sipmethod == SIP_CANCEL) {
18559
18560
18561 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
18562 } else {
18563 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
18564
18565 }
18566 break;
18567 case 487:
18568 if (sipmethod == SIP_INVITE)
18569 handle_response_invite(p, resp, rest, req, seqno);
18570 break;
18571 case 415:
18572 case 488:
18573 case 606:
18574 if (sipmethod == SIP_INVITE)
18575 handle_response_invite(p, resp, rest, req, seqno);
18576 break;
18577 case 491:
18578 if (sipmethod == SIP_INVITE)
18579 handle_response_invite(p, resp, rest, req, seqno);
18580 else {
18581 ast_debug(1, "Got 491 on %s, unsupported. Call ID %s\n", sip_methods[sipmethod].text, p->callid);
18582 pvt_set_needdestroy(p, "received 491 response");
18583 }
18584 break;
18585 case 501:
18586 if (sipmethod == SIP_INVITE)
18587 handle_response_invite(p, resp, rest, req, seqno);
18588 else if (sipmethod == SIP_REFER)
18589 handle_response_refer(p, resp, rest, req, seqno);
18590 else
18591 ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n", ast_inet_ntoa(p->sa.sin_addr), msg);
18592 break;
18593 case 603:
18594 if (sipmethod == SIP_REFER) {
18595 handle_response_refer(p, resp, rest, req, seqno);
18596 break;
18597 }
18598
18599 default:
18600 if ((resp >= 300) && (resp < 700)) {
18601
18602 if ((resp != 487))
18603 ast_verb(3, "Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_inet_ntoa(p->sa.sin_addr));
18604
18605 if (sipmethod == SIP_INVITE)
18606 stop_media_flows(p);
18607
18608
18609 switch(resp) {
18610 case 300:
18611 case 301:
18612 case 302:
18613 case 305:
18614 parse_moved_contact(p, req);
18615
18616 case 486:
18617 case 600:
18618 case 603:
18619 if (p->owner)
18620 ast_queue_control(p->owner, AST_CONTROL_BUSY);
18621 break;
18622 case 482:
18623
18624
18625
18626
18627
18628 if (p->owner && ast_test_flag(&p->flags[1], SIP_PAGE2_FORWARD_LOOP_DETECTED)) {
18629 ast_debug(1, "Hairpin detected, setting up call forward for what it's worth\n");
18630 ast_string_field_build(p->owner, call_forward,
18631 "Local/%s@%s", p->username, p->context);
18632 }
18633
18634 case 480:
18635 case 404:
18636 case 410:
18637 case 400:
18638 case 500:
18639 if (sipmethod == SIP_REFER) {
18640 handle_response_refer(p, resp, rest, req, seqno);
18641 break;
18642 } else if (sipmethod == SIP_SUBSCRIBE) {
18643 handle_response_subscribe(p, resp, rest, req, seqno);
18644 break;
18645 }
18646
18647 case 502:
18648 case 503:
18649 case 504:
18650 if (owner)
18651 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18652 break;
18653 default:
18654
18655 if (owner && sipmethod != SIP_MESSAGE && sipmethod != SIP_INFO && sipmethod != SIP_BYE)
18656 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
18657 break;
18658 }
18659
18660 if (sipmethod == SIP_INVITE)
18661 transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
18662 if (sipmethod != SIP_MESSAGE && sipmethod != SIP_INFO)
18663 sip_alreadygone(p);
18664 if (!p->owner) {
18665 pvt_set_needdestroy(p, "transaction completed");
18666 }
18667 } else if ((resp >= 100) && (resp < 200)) {
18668 if (sipmethod == SIP_INVITE) {
18669 if (!req->ignore && sip_cancel_destroy(p))
18670 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
18671 if (find_sdp(req))
18672 process_sdp(p, req, SDP_T38_NONE);
18673 if (p->owner) {
18674
18675 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
18676 }
18677 }
18678 } else
18679 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));
18680 }
18681 } else {
18682
18683
18684 if (req->debug)
18685 ast_verbose("SIP Response message for INCOMING dialog %s arrived\n", msg);
18686
18687 if (sipmethod == SIP_INVITE && resp == 200) {
18688
18689
18690 char tag[128];
18691
18692 gettag(req, "To", tag, sizeof(tag));
18693 ast_string_field_set(p, theirtag, tag);
18694 }
18695
18696 switch(resp) {
18697 case 200:
18698 if (sipmethod == SIP_INVITE) {
18699 handle_response_invite(p, resp, rest, req, seqno);
18700 } else if (sipmethod == SIP_CANCEL) {
18701 ast_debug(1, "Got 200 OK on CANCEL\n");
18702
18703
18704 } else if (sipmethod == SIP_NOTIFY) {
18705
18706 if (p->owner) {
18707 if (p->refer) {
18708 ast_debug(1, "Got 200 OK on NOTIFY for transfer\n");
18709 } else
18710 ast_log(LOG_WARNING, "Notify answer on an owned channel?\n");
18711
18712 } else {
18713 if (!p->subscribed && !p->refer) {
18714 pvt_set_needdestroy(p, "transaction completed");
18715 }
18716 if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
18717
18718 ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
18719 cb_extensionstate((char *)p->context, (char *)p->exten, p->laststate, (void *) p);
18720 }
18721 }
18722 } else if (sipmethod == SIP_BYE) {
18723 pvt_set_needdestroy(p, "transaction completed");
18724 } else if (sipmethod == SIP_MESSAGE || sipmethod == SIP_INFO) {
18725
18726
18727 ;
18728 }
18729 break;
18730 case 202:
18731 if (sipmethod == SIP_REFER)
18732 handle_response_refer(p, resp, rest, req, seqno);
18733 break;
18734 case 401:
18735 case 407:
18736 if (sipmethod == SIP_REFER)
18737 handle_response_refer(p, resp, rest, req, seqno);
18738 else if (sipmethod == SIP_INVITE)
18739 handle_response_invite(p, resp, rest, req, seqno);
18740 else if (sipmethod == SIP_BYE) {
18741 if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, sipmethod, 0)) {
18742 ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
18743 pvt_set_needdestroy(p, "failed to authenticate BYE");
18744 }
18745 }
18746 break;
18747 case 481:
18748 if (sipmethod == SIP_INVITE) {
18749
18750 handle_response_invite(p, resp, rest, req, seqno);
18751 } else if (sipmethod == SIP_BYE) {
18752 pvt_set_needdestroy(p, "received 481 response");
18753 } else if (sipdebug) {
18754 ast_debug(1, "Remote host can't match request %s to call '%s'. Giving up\n", sip_methods[sipmethod].text, p->callid);
18755 }
18756 break;
18757 case 501:
18758 if (sipmethod == SIP_INVITE)
18759 handle_response_invite(p, resp, rest, req, seqno);
18760 else if (sipmethod == SIP_REFER)
18761 handle_response_refer(p, resp, rest, req, seqno);
18762 break;
18763 case 603:
18764 if (sipmethod == SIP_REFER) {
18765 handle_response_refer(p, resp, rest, req, seqno);
18766 break;
18767 }
18768
18769 default:
18770 if ((resp >= 100) && (resp < 200)) {
18771 if (sipmethod == SIP_INVITE) {
18772 if (!req->ignore && sip_cancel_destroy(p))
18773 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
18774 }
18775 }
18776 if ((resp >= 300) && (resp < 700)) {
18777 if ((resp != 487))
18778 ast_verb(3, "Incoming call: Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_inet_ntoa(p->sa.sin_addr));
18779 switch(resp) {
18780 case 415:
18781 case 488:
18782 case 603:
18783 case 500:
18784 case 502:
18785 case 503:
18786 case 504:
18787
18788
18789 if (sipmethod == SIP_INVITE && sip_cancel_destroy(p))
18790 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
18791 break;
18792 }
18793 }
18794 break;
18795 }
18796 }
18797 }
18798
18799
18800
18801
18802
18803
18804
18805 static void *sip_park_thread(void *stuff)
18806 {
18807 struct ast_channel *transferee, *transferer;
18808 struct sip_dual *d;
18809 struct sip_request req = {0,};
18810 int ext;
18811 int res;
18812
18813 d = stuff;
18814 transferee = d->chan1;
18815 transferer = d->chan2;
18816 copy_request(&req, &d->req);
18817
18818 if (!transferee || !transferer) {
18819 ast_log(LOG_ERROR, "Missing channels for parking! Transferer %s Transferee %s\n", transferer ? "<available>" : "<missing>", transferee ? "<available>" : "<missing>" );
18820 deinit_req(&d->req);
18821 free(d);
18822 return NULL;
18823 }
18824 ast_debug(4, "SIP Park: Transferer channel %s, Transferee %s\n", transferer->name, transferee->name);
18825
18826 ast_channel_lock(transferee);
18827 if (ast_do_masquerade(transferee)) {
18828 ast_log(LOG_WARNING, "Masquerade failed.\n");
18829 transmit_response(transferer->tech_pvt, "503 Internal error", &req);
18830 ast_channel_unlock(transferee);
18831 deinit_req(&d->req);
18832 free(d);
18833 return NULL;
18834 }
18835 ast_channel_unlock(transferee);
18836
18837 res = ast_park_call(transferee, transferer, 0, &ext);
18838
18839
18840 #ifdef WHEN_WE_KNOW_THAT_THE_CLIENT_SUPPORTS_MESSAGE
18841 if (!res) {
18842 transmit_message_with_text(transferer->tech_pvt, "Unable to park call.\n");
18843 } else {
18844
18845 sprintf(buf, "Call parked on extension '%d'", ext);
18846 transmit_message_with_text(transferer->tech_pvt, buf);
18847 }
18848 #endif
18849
18850
18851
18852 transmit_response(transferer->tech_pvt, "202 Accepted", &req);
18853 if (!res) {
18854
18855 append_history(transferer->tech_pvt, "SIPpark", "Parked call on %d", ext);
18856 transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "200 OK", TRUE);
18857 transferer->hangupcause = AST_CAUSE_NORMAL_CLEARING;
18858 ast_hangup(transferer);
18859 ast_debug(1, "SIP Call parked on extension '%d'\n", ext);
18860 } else {
18861 transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "503 Service Unavailable", TRUE);
18862 append_history(transferer->tech_pvt, "SIPpark", "Parking failed\n");
18863 ast_debug(1, "SIP Call parked failed \n");
18864
18865 }
18866 deinit_req(&d->req);
18867 free(d);
18868 return NULL;
18869 }
18870
18871
18872
18873
18874 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno)
18875 {
18876 struct sip_dual *d;
18877 struct ast_channel *transferee, *transferer;
18878
18879 pthread_t th;
18880
18881 transferee = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan1->accountcode, chan1->exten, chan1->context, chan1->amaflags, "Parking/%s", chan1->name);
18882 transferer = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan2->accountcode, chan2->exten, chan2->context, chan2->amaflags, "SIPPeer/%s", chan2->name);
18883 if ((!transferer) || (!transferee)) {
18884 if (transferee) {
18885 transferee->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
18886 ast_hangup(transferee);
18887 }
18888 if (transferer) {
18889 transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
18890 ast_hangup(transferer);
18891 }
18892 return -1;
18893 }
18894
18895
18896 transferee->readformat = chan1->readformat;
18897 transferee->writeformat = chan1->writeformat;
18898
18899
18900 ast_channel_masquerade(transferee, chan1);
18901
18902
18903 ast_copy_string(transferee->context, chan1->context, sizeof(transferee->context));
18904 ast_copy_string(transferee->exten, chan1->exten, sizeof(transferee->exten));
18905 transferee->priority = chan1->priority;
18906
18907
18908
18909
18910
18911 transferer->readformat = chan2->readformat;
18912 transferer->writeformat = chan2->writeformat;
18913 if (!ast_strlen_zero(chan2->parkinglot))
18914 ast_string_field_set(transferer, parkinglot, chan2->parkinglot);
18915
18916
18917
18918
18919 while (ast_channel_trylock(chan2)) {
18920 struct sip_pvt *pvt = chan2->tech_pvt;
18921 sip_pvt_unlock(pvt);
18922 usleep(1);
18923 sip_pvt_lock(pvt);
18924 }
18925 ast_channel_masquerade(transferer, chan2);
18926 ast_channel_unlock(chan2);
18927
18928
18929 ast_copy_string(transferer->context, chan2->context, sizeof(transferer->context));
18930 ast_copy_string(transferer->exten, chan2->exten, sizeof(transferer->exten));
18931 transferer->priority = chan2->priority;
18932
18933 ast_channel_lock(transferer);
18934 if (ast_do_masquerade(transferer)) {
18935 ast_log(LOG_WARNING, "Masquerade failed :(\n");
18936 ast_channel_unlock(transferer);
18937 transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
18938 ast_hangup(transferer);
18939 return -1;
18940 }
18941 ast_channel_unlock(transferer);
18942 if (!transferer || !transferee) {
18943 if (!transferer) {
18944 ast_debug(1, "No transferer channel, giving up parking\n");
18945 }
18946 if (!transferee) {
18947 ast_debug(1, "No transferee channel, giving up parking\n");
18948 }
18949 return -1;
18950 }
18951 if ((d = ast_calloc(1, sizeof(*d)))) {
18952
18953
18954 copy_request(&d->req, req);
18955 d->chan1 = transferee;
18956 d->chan2 = transferer;
18957 d->seqno = seqno;
18958 if (ast_pthread_create_detached_background(&th, NULL, sip_park_thread, d) < 0) {
18959
18960 deinit_req(&d->req);
18961 ast_free(d);
18962
18963 return 0;
18964 }
18965 }
18966 return -1;
18967 }
18968
18969
18970
18971
18972 static void ast_quiet_chan(struct ast_channel *chan)
18973 {
18974 if (chan && chan->_state == AST_STATE_UP) {
18975 if (ast_test_flag(chan, AST_FLAG_MOH))
18976 ast_moh_stop(chan);
18977 else if (chan->generatordata)
18978 ast_deactivate_generator(chan);
18979 }
18980 }
18981
18982
18983
18984 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target)
18985 {
18986 int res = 0;
18987 struct ast_channel *peera = NULL,
18988 *peerb = NULL,
18989 *peerc = NULL,
18990 *peerd = NULL;
18991
18992
18993
18994
18995 ast_debug(4, "Sip transfer:--------------------\n");
18996 if (transferer->chan1)
18997 ast_debug(4, "-- Transferer to PBX channel: %s State %s\n", transferer->chan1->name, ast_state2str(transferer->chan1->_state));
18998 else
18999 ast_debug(4, "-- No transferer first channel - odd??? \n");
19000 if (target->chan1)
19001 ast_debug(4, "-- Transferer to PBX second channel (target): %s State %s\n", target->chan1->name, ast_state2str(target->chan1->_state));
19002 else
19003 ast_debug(4, "-- No target first channel ---\n");
19004 if (transferer->chan2)
19005 ast_debug(4, "-- Bridged call to transferee: %s State %s\n", transferer->chan2->name, ast_state2str(transferer->chan2->_state));
19006 else
19007 ast_debug(4, "-- No bridged call to transferee\n");
19008 if (target->chan2)
19009 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)");
19010 else
19011 ast_debug(4, "-- No target second channel ---\n");
19012 ast_debug(4, "-- END Sip transfer:--------------------\n");
19013 if (transferer->chan2) {
19014 peera = transferer->chan1;
19015 peerb = target->chan1;
19016 peerc = transferer->chan2;
19017 peerd = target->chan2;
19018 ast_debug(3, "SIP transfer: Four channels to handle\n");
19019 } else if (target->chan2) {
19020 peera = target->chan1;
19021 peerb = transferer->chan1;
19022 peerc = target->chan2;
19023 peerd = transferer->chan2;
19024 ast_debug(3, "SIP transfer: Three channels to handle\n");
19025 }
19026
19027 if (peera && peerb && peerc && (peerb != peerc)) {
19028 ast_quiet_chan(peera);
19029 ast_quiet_chan(peerb);
19030 ast_quiet_chan(peerc);
19031 if (peerd)
19032 ast_quiet_chan(peerd);
19033
19034 ast_debug(4, "SIP transfer: trying to masquerade %s into %s\n", peerc->name, peerb->name);
19035 if (ast_channel_masquerade(peerb, peerc)) {
19036 ast_log(LOG_WARNING, "Failed to masquerade %s into %s\n", peerb->name, peerc->name);
19037 res = -1;
19038 } else
19039 ast_debug(4, "SIP transfer: Succeeded to masquerade channels.\n");
19040 return res;
19041 } else {
19042 ast_log(LOG_NOTICE, "SIP Transfer attempted with no appropriate bridged calls to transfer\n");
19043 if (transferer->chan1)
19044 ast_softhangup_nolock(transferer->chan1, AST_SOFTHANGUP_DEV);
19045 if (target->chan1)
19046 ast_softhangup_nolock(target->chan1, AST_SOFTHANGUP_DEV);
19047 return -1;
19048 }
19049 return 0;
19050 }
19051
19052
19053
19054
19055
19056
19057 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize)
19058 {
19059 const char *thetag;
19060
19061 if (!tagbuf)
19062 return NULL;
19063 tagbuf[0] = '\0';
19064 thetag = get_header(req, header);
19065 thetag = strcasestr(thetag, ";tag=");
19066 if (thetag) {
19067 thetag += 5;
19068 ast_copy_string(tagbuf, thetag, tagbufsize);
19069 return strsep(&tagbuf, ";");
19070 }
19071 return NULL;
19072 }
19073
19074
19075 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e)
19076 {
19077
19078
19079 int res = 0;
19080 const char *event = get_header(req, "Event");
19081 char *eventid = NULL;
19082 char *sep;
19083
19084 if( (sep = strchr(event, ';')) ) {
19085 *sep++ = '\0';
19086 eventid = sep;
19087 }
19088
19089 if (sipdebug)
19090 ast_debug(2, "Got NOTIFY Event: %s\n", event);
19091
19092 if (!strcmp(event, "refer")) {
19093
19094
19095
19096
19097
19098 char buf[1024];
19099 char *cmd, *code;
19100 int respcode;
19101 int success = TRUE;
19102
19103
19104
19105
19106
19107
19108
19109
19110 if (strncasecmp(get_header(req, "Content-Type"), "message/sipfrag", strlen("message/sipfrag"))) {
19111
19112 transmit_response(p, "400 Bad request", req);
19113 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19114 return -1;
19115 }
19116
19117
19118 if (get_msg_text(buf, sizeof(buf), req, TRUE)) {
19119 ast_log(LOG_WARNING, "Unable to retrieve attachment from NOTIFY %s\n", p->callid);
19120 transmit_response(p, "400 Bad request", req);
19121 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19122 return -1;
19123 }
19124
19125
19126
19127
19128
19129
19130
19131
19132
19133
19134
19135
19136
19137
19138
19139
19140
19141
19142
19143
19144
19145 ast_debug(3, "* SIP Transfer NOTIFY Attachment: \n---%s\n---\n", buf);
19146 cmd = ast_skip_blanks(buf);
19147 code = cmd;
19148
19149 while(*code && (*code > 32)) {
19150 code++;
19151 }
19152 *code++ = '\0';
19153 code = ast_skip_blanks(code);
19154 sep = code;
19155 sep++;
19156 while(*sep && (*sep > 32)) {
19157 sep++;
19158 }
19159 *sep++ = '\0';
19160 respcode = atoi(code);
19161 switch (respcode) {
19162 case 100:
19163 case 101:
19164
19165 break;
19166 case 183:
19167
19168 break;
19169 case 200:
19170
19171 break;
19172 case 301:
19173 case 302:
19174
19175 success = FALSE;
19176 break;
19177 case 503:
19178
19179 success = FALSE;
19180 break;
19181 case 603:
19182
19183 success = FALSE;
19184 break;
19185 }
19186 if (!success) {
19187 ast_log(LOG_NOTICE, "Transfer failed. Sorry. Nothing further to do with this call\n");
19188 }
19189
19190
19191 transmit_response(p, "200 OK", req);
19192 } else if (p->mwi && !strcmp(event, "message-summary")) {
19193 char *c = ast_strdupa(get_body(req, "Voice-Message", ':'));
19194
19195 if (!ast_strlen_zero(c)) {
19196 char *old = strsep(&c, " ");
19197 char *new = strsep(&old, "/");
19198 struct ast_event *event;
19199
19200 if ((event = ast_event_new(AST_EVENT_MWI,
19201 AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, p->mwi->mailbox,
19202 AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, "SIP_Remote",
19203 AST_EVENT_IE_NEWMSGS, AST_EVENT_IE_PLTYPE_UINT, atoi(new),
19204 AST_EVENT_IE_OLDMSGS, AST_EVENT_IE_PLTYPE_UINT, atoi(old),
19205 AST_EVENT_IE_END))) {
19206 ast_event_queue_and_cache(event);
19207 }
19208 }
19209
19210 transmit_response(p, "200 OK", req);
19211 } else if (!strcmp(event, "keep-alive")) {
19212
19213
19214 transmit_response(p, "200 OK", req);
19215 } else {
19216
19217 transmit_response(p, "489 Bad event", req);
19218 res = -1;
19219 }
19220
19221 if (!p->lastinvite)
19222 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19223
19224 return res;
19225 }
19226
19227
19228
19229
19230 static int handle_request_options(struct sip_pvt *p, struct sip_request *req)
19231 {
19232 int res;
19233
19234
19235
19236
19237
19238
19239
19240
19241
19242
19243
19244 if (p->lastinvite) {
19245
19246 transmit_response_with_allow(p, "200 OK", req, 0);
19247 return 0;
19248 }
19249
19250 res = get_destination(p, req);
19251 build_contact(p);
19252
19253 if (ast_strlen_zero(p->context))
19254 ast_string_field_set(p, context, sip_cfg.default_context);
19255
19256 if (ast_shutting_down())
19257 transmit_response_with_allow(p, "503 Unavailable", req, 0);
19258 else if (res < 0)
19259 transmit_response_with_allow(p, "404 Not Found", req, 0);
19260 else
19261 transmit_response_with_allow(p, "200 OK", req, 0);
19262
19263
19264
19265 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19266
19267 return res;
19268 }
19269
19270
19271
19272
19273
19274
19275
19276
19277
19278
19279 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin, int *nounlock)
19280 {
19281 int earlyreplace = 0;
19282 int oneleggedreplace = 0;
19283 struct ast_channel *c = p->owner;
19284 struct ast_channel *replacecall = p->refer->refer_call->owner;
19285 struct ast_channel *targetcall;
19286
19287 struct ast_channel *test;
19288
19289
19290 if (replacecall->_state == AST_STATE_RING)
19291 earlyreplace = 1;
19292
19293
19294 if (!(targetcall = ast_bridged_channel(replacecall))) {
19295
19296 if (!earlyreplace) {
19297 ast_debug(2, " Attended transfer attempted to replace call with no bridge (maybe ringing). Channel %s!\n", replacecall->name);
19298 oneleggedreplace = 1;
19299 }
19300 }
19301 if (targetcall && targetcall->_state == AST_STATE_RINGING)
19302 ast_debug(4, "SIP transfer: Target channel is in ringing state\n");
19303
19304 if (targetcall)
19305 ast_debug(4, "SIP transfer: Invite Replace incoming channel should bridge to channel %s while hanging up channel %s\n", targetcall->name, replacecall->name);
19306 else
19307 ast_debug(4, "SIP transfer: Invite Replace incoming channel should replace and hang up channel %s (one call leg)\n", replacecall->name);
19308
19309 if (req->ignore) {
19310 ast_log(LOG_NOTICE, "Ignoring this INVITE with replaces in a stupid way.\n");
19311
19312
19313
19314 transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE);
19315
19316 if (c) {
19317 *nounlock = 1;
19318 ast_channel_unlock(c);
19319 }
19320 ast_channel_unlock(replacecall);
19321 sip_pvt_unlock(p->refer->refer_call);
19322 return 1;
19323 }
19324 if (!c) {
19325
19326 ast_log(LOG_ERROR, "Unable to create new channel. Invite/replace failed.\n");
19327 transmit_response_reliable(p, "503 Service Unavailable", req);
19328 append_history(p, "Xfer", "INVITE/Replace Failed. No new channel.");
19329 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19330 ast_channel_unlock(replacecall);
19331 sip_pvt_unlock(p->refer->refer_call);
19332 return 1;
19333 }
19334 append_history(p, "Xfer", "INVITE/Replace received");
19335
19336
19337
19338
19339
19340
19341
19342
19343
19344
19345
19346 transmit_response(p, "100 Trying", req);
19347 ast_setstate(c, AST_STATE_RING);
19348
19349
19350
19351
19352
19353 transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE);
19354
19355 ast_setstate(c, AST_STATE_UP);
19356
19357
19358 ast_quiet_chan(replacecall);
19359 ast_quiet_chan(targetcall);
19360 ast_debug(4, "Invite/Replaces: preparing to masquerade %s into %s\n", c->name, replacecall->name);
19361
19362
19363 if (! earlyreplace && ! oneleggedreplace )
19364 ast_set_flag(&p->refer->refer_call->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
19365
19366
19367 if(ast_channel_masquerade(replacecall, c))
19368 ast_log(LOG_ERROR, "Failed to masquerade C into Replacecall\n");
19369 else
19370 ast_debug(4, "Invite/Replaces: Going to masquerade %s into %s\n", c->name, replacecall->name);
19371
19372
19373 if (ast_do_masquerade(replacecall)) {
19374 ast_log(LOG_WARNING, "Failed to perform masquerade with INVITE replaces\n");
19375 }
19376
19377 if (earlyreplace || oneleggedreplace ) {
19378 c->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
19379 }
19380
19381 ast_setstate(c, AST_STATE_DOWN);
19382 ast_debug(4, "After transfer:----------------------------\n");
19383 ast_debug(4, " -- C: %s State %s\n", c->name, ast_state2str(c->_state));
19384 if (replacecall)
19385 ast_debug(4, " -- replacecall: %s State %s\n", replacecall->name, ast_state2str(replacecall->_state));
19386 if (p->owner) {
19387 ast_debug(4, " -- P->owner: %s State %s\n", p->owner->name, ast_state2str(p->owner->_state));
19388 test = ast_bridged_channel(p->owner);
19389 if (test)
19390 ast_debug(4, " -- Call bridged to P->owner: %s State %s\n", test->name, ast_state2str(test->_state));
19391 else
19392 ast_debug(4, " -- No call bridged to C->owner \n");
19393 } else
19394 ast_debug(4, " -- No channel yet \n");
19395 ast_debug(4, "End After transfer:----------------------------\n");
19396
19397
19398 ast_channel_unlock(replacecall);
19399 ast_channel_unlock(c);
19400 sip_pvt_unlock(p->refer->refer_call);
19401 sip_pvt_unlock(p);
19402 *nounlock = 1;
19403
19404
19405 c->tech_pvt = dialog_unref(c->tech_pvt, "unref dialog c->tech_pvt");
19406 ast_hangup(c);
19407 sip_pvt_lock(p);
19408
19409 return 0;
19410 }
19411
19412
19413
19414
19415
19416
19417
19418
19419
19420
19421
19422
19423
19424
19425
19426
19427
19428 static int sip_uri_params_cmp(const char *input1, const char *input2)
19429 {
19430 char *params1 = NULL;
19431 char *params2 = NULL;
19432 char *pos1;
19433 char *pos2;
19434 int zerolength1 = 0;
19435 int zerolength2 = 0;
19436 int maddrmatch = 0;
19437 int ttlmatch = 0;
19438 int usermatch = 0;
19439 int methodmatch = 0;
19440
19441 if (ast_strlen_zero(input1)) {
19442 zerolength1 = 1;
19443 } else {
19444 params1 = ast_strdupa(input1);
19445 }
19446 if (ast_strlen_zero(input2)) {
19447 zerolength2 = 1;
19448 } else {
19449 params2 = ast_strdupa(input2);
19450 }
19451
19452
19453
19454
19455 if (zerolength1 && zerolength2) {
19456 return 0;
19457 }
19458
19459 pos1 = params1;
19460 while (!ast_strlen_zero(pos1)) {
19461 char *name1 = pos1;
19462 char *value1 = strchr(pos1, '=');
19463 char *semicolon1 = strchr(pos1, ';');
19464 int matched = 0;
19465 if (semicolon1) {
19466 *semicolon1++ = '\0';
19467 }
19468 if (!value1) {
19469 goto fail;
19470 }
19471 *value1++ = '\0';
19472
19473
19474
19475
19476
19477 pos2 = ast_strdupa(params2);
19478 while (!ast_strlen_zero(pos2)) {
19479 char *name2 = pos2;
19480 char *value2 = strchr(pos2, '=');
19481 char *semicolon2 = strchr(pos2, ';');
19482 if (semicolon2) {
19483 *semicolon2++ = '\0';
19484 }
19485 if (!value2) {
19486 goto fail;
19487 }
19488 *value2++ = '\0';
19489 if (!strcasecmp(name1, name2)) {
19490 if (strcasecmp(value1, value2)) {
19491 goto fail;
19492 } else {
19493 matched = 1;
19494 break;
19495 }
19496 }
19497 pos2 = semicolon2;
19498 }
19499
19500 if (!strcasecmp(name1, "maddr")) {
19501 if (matched) {
19502 maddrmatch = 1;
19503 } else {
19504 goto fail;
19505 }
19506 } else if (!strcasecmp(name1, "ttl")) {
19507 if (matched) {
19508 ttlmatch = 1;
19509 } else {
19510 goto fail;
19511 }
19512 } else if (!strcasecmp(name1, "user")) {
19513 if (matched) {
19514 usermatch = 1;
19515 } else {
19516 goto fail;
19517 }
19518 } else if (!strcasecmp(name1, "method")) {
19519 if (matched) {
19520 methodmatch = 1;
19521 } else {
19522 goto fail;
19523 }
19524 }
19525 pos1 = semicolon1;
19526 }
19527
19528
19529
19530
19531
19532 pos2 = params2;
19533 while (!ast_strlen_zero(pos2)) {
19534 char *name2 = pos2;
19535 char *value2 = strchr(pos2, '=');
19536 char *semicolon2 = strchr(pos2, ';');
19537 if (semicolon2) {
19538 *semicolon2++ = '\0';
19539 }
19540 if (!value2) {
19541 goto fail;
19542 }
19543 *value2++ = '\0';
19544 if ((!strcasecmp(name2, "maddr") && !maddrmatch) ||
19545 (!strcasecmp(name2, "ttl") && !ttlmatch) ||
19546 (!strcasecmp(name2, "user") && !usermatch) ||
19547 (!strcasecmp(name2, "method") && !methodmatch)) {
19548 goto fail;
19549 }
19550 }
19551 return 0;
19552
19553 fail:
19554 return 1;
19555 }
19556
19557
19558
19559
19560
19561
19562
19563
19564
19565
19566
19567
19568 static int sip_uri_headers_cmp(const char *input1, const char *input2)
19569 {
19570 char *headers1 = NULL;
19571 char *headers2 = NULL;
19572 int zerolength1 = 0;
19573 int zerolength2 = 0;
19574 int different = 0;
19575 char *header1;
19576
19577 if (ast_strlen_zero(input1)) {
19578 zerolength1 = 1;
19579 } else {
19580 headers1 = ast_strdupa(input1);
19581 }
19582
19583 if (ast_strlen_zero(input2)) {
19584 zerolength2 = 1;
19585 } else {
19586 headers2 = ast_strdupa(input2);
19587 }
19588
19589 if ((zerolength1 && !zerolength2) ||
19590 (zerolength2 && !zerolength1))
19591 return 1;
19592
19593 if (zerolength1 && zerolength2)
19594 return 0;
19595
19596
19597
19598
19599
19600 if (strlen(headers1) != strlen(headers2)) {
19601 return 1;
19602 }
19603
19604 for (header1 = strsep(&headers1, "&"); header1; header1 = strsep(&headers1, "&")) {
19605 if (!strcasestr(headers2, header1)) {
19606 different = 1;
19607 break;
19608 }
19609 }
19610
19611 return different;
19612 }
19613
19614 static int sip_uri_cmp(const char *input1, const char *input2)
19615 {
19616 char *uri1 = ast_strdupa(input1);
19617 char *uri2 = ast_strdupa(input2);
19618 char *host1;
19619 char *host2;
19620 char *params1;
19621 char *params2;
19622 char *headers1;
19623 char *headers2;
19624
19625
19626
19627
19628 strsep(&uri1, ":");
19629 strsep(&uri2, ":");
19630
19631 if ((host1 = strchr(uri1, '@'))) {
19632 *host1++ = '\0';
19633 }
19634 if ((host2 = strchr(uri2, '@'))) {
19635 *host2++ = '\0';
19636 }
19637
19638
19639
19640
19641 if ((host1 && !host2) ||
19642 (host2 && !host1) ||
19643 (host1 && host2 && strcmp(uri1, uri2))) {
19644 return 1;
19645 }
19646
19647 if (!host1)
19648 host1 = uri1;
19649 if (!host2)
19650 host2 = uri2;
19651
19652
19653
19654
19655
19656 if ((params1 = strchr(host1, ';'))) {
19657 *params1++ = '\0';
19658 }
19659 if ((params2 = strchr(host2, ';'))) {
19660 *params2++ = '\0';
19661 }
19662
19663
19664
19665
19666 if ((headers1 = strchr(S_OR(params1, host1), '?'))) {
19667 *headers1++ = '\0';
19668 }
19669 if ((headers2 = strchr(S_OR(params2, host2), '?'))) {
19670 *headers2++ = '\0';
19671 }
19672
19673
19674
19675
19676
19677
19678
19679
19680
19681
19682
19683 if (strcasecmp(host1, host2)) {
19684 return 1;
19685 }
19686
19687
19688 if (sip_uri_headers_cmp(headers1, headers2)) {
19689 return 1;
19690 }
19691
19692
19693 return sip_uri_params_cmp(params1, params2);
19694 }
19695
19696 static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context)
19697 {
19698 struct ast_str *str = ast_str_alloca(AST_MAX_EXTENSION + AST_MAX_CONTEXT + 2);
19699 struct ast_app *pickup = pbx_findapp("Pickup");
19700
19701 if (!pickup) {
19702 ast_log(LOG_ERROR, "Unable to perform pickup: Application 'Pickup' not loaded (app_directed_pickup.so).\n");
19703 return -1;
19704 }
19705
19706 ast_str_set(&str, 0, "%s@%s", extension, sip_cfg.notifycid == IGNORE_CONTEXT ? "PICKUPMARK" : context);
19707
19708 ast_debug(2, "About to call Pickup(%s)\n", str->str);
19709
19710
19711
19712
19713 pbx_exec(channel, pickup, str->str);
19714
19715 return 0;
19716 }
19717
19718
19719 static int sip_t38_abort(const void *data)
19720 {
19721 struct sip_pvt *p = (struct sip_pvt *) data;
19722
19723 sip_pvt_lock(p);
19724
19725
19726
19727
19728
19729 if (p->t38id != -1) {
19730 change_t38_state(p, T38_DISABLED);
19731 transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
19732 p->t38id = -1;
19733 dialog_unref(p, "unref the dialog ptr from sip_t38_abort, because it held a dialog ptr");
19734 }
19735 sip_pvt_unlock(p);
19736 return 0;
19737 }
19738
19739
19740
19741
19742
19743
19744
19745 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)
19746 {
19747 int res = 1;
19748 int gotdest;
19749 const char *p_replaces;
19750 char *replace_id = NULL;
19751 int refer_locked = 0;
19752 const char *required;
19753 unsigned int required_profile = 0;
19754 struct ast_channel *c = NULL;
19755 int reinvite = 0;
19756 int rtn;
19757
19758 const char *p_uac_se_hdr;
19759 const char *p_uac_min_se;
19760 int uac_max_se = -1;
19761 int uac_min_se = -1;
19762 int st_active = FALSE;
19763 int st_interval = 0;
19764 enum st_refresher st_ref;
19765 int dlg_min_se = -1;
19766 struct {
19767 char exten[AST_MAX_EXTENSION];
19768 char context[AST_MAX_CONTEXT];
19769 } pickup = {
19770 .exten = "",
19771 };
19772 st_ref = SESSION_TIMER_REFRESHER_AUTO;
19773
19774
19775 if (!p->sipoptions) {
19776 const char *supported = get_header(req, "Supported");
19777 if (!ast_strlen_zero(supported))
19778 parse_sip_options(p, supported);
19779 }
19780
19781
19782 required = get_header(req, "Require");
19783 if (!ast_strlen_zero(required)) {
19784 required_profile = parse_sip_options(NULL, required);
19785 if (required_profile && !(required_profile & (SIP_OPT_REPLACES | SIP_OPT_TIMER))) {
19786
19787 transmit_response_with_unsupported(p, "420 Bad extension (unsupported)", req, required);
19788 ast_log(LOG_WARNING, "Received SIP INVITE with unsupported required extension: %s\n", required);
19789 p->invitestate = INV_COMPLETED;
19790 if (!p->lastinvite)
19791 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19792 res = -1;
19793 goto request_invite_cleanup;
19794 }
19795 }
19796
19797
19798
19799 p->sipoptions |= required_profile;
19800 p->reqsipoptions = required_profile;
19801
19802
19803 if (ast_test_flag(&p->flags[0], SIP_OUTGOING) && p->owner && (p->invitestate != INV_TERMINATED && p->invitestate != INV_CONFIRMED)) {
19804
19805
19806
19807
19808
19809 int different;
19810 char *initial_rlPart2 = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
19811 char *this_rlPart2 = REQ_OFFSET_TO_STR(req, rlPart2);
19812 if (sip_cfg.pedanticsipchecking)
19813 different = sip_uri_cmp(initial_rlPart2, this_rlPart2);
19814 else
19815 different = strcmp(initial_rlPart2, this_rlPart2);
19816 if (!different) {
19817 transmit_response(p, "482 Loop Detected", req);
19818 p->invitestate = INV_COMPLETED;
19819 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19820 res = 0;
19821 goto request_invite_cleanup;
19822 } else {
19823
19824
19825
19826
19827
19828
19829
19830 char *uri = ast_strdupa(this_rlPart2);
19831 char *at = strchr(uri, '@');
19832 char *peerorhost;
19833 ast_debug(2, "Potential spiral detected. Original RURI was %s, new RURI is %s\n", initial_rlPart2, this_rlPart2);
19834 transmit_response(p, "100 Trying", req);
19835 if (at) {
19836 *at = '\0';
19837 }
19838
19839 if ((peerorhost = strchr(uri, ':'))) {
19840 *peerorhost++ = '\0';
19841 }
19842 ast_string_field_set(p, theirtag, NULL);
19843
19844
19845 ast_string_field_set(p->owner, call_forward, peerorhost);
19846 ast_queue_control(p->owner, AST_CONTROL_BUSY);
19847 res = 0;
19848 goto request_invite_cleanup;
19849 }
19850 }
19851
19852 if (!req->ignore && p->pendinginvite) {
19853 if (!ast_test_flag(&p->flags[0], SIP_OUTGOING) && (p->invitestate == INV_COMPLETED || p->invitestate == INV_TERMINATED)) {
19854
19855
19856
19857
19858
19859
19860
19861
19862
19863
19864 __sip_ack(p, p->pendinginvite, 1, 0);
19865 } else {
19866
19867 p->glareinvite = seqno;
19868 if (p->rtp && find_sdp(req)) {
19869 struct sockaddr_in sin;
19870 if (get_ip_and_port_from_sdp(req, SDP_AUDIO, &sin)) {
19871 ast_log(LOG_WARNING, "Failed to set an alternate media source on glared reinvite. Audio may not work properly on this call.\n");
19872 } else {
19873 ast_rtp_set_alt_peer(p->rtp, &sin);
19874 }
19875 if (p->vrtp) {
19876 if (get_ip_and_port_from_sdp(req, SDP_VIDEO, &sin)) {
19877 ast_log(LOG_WARNING, "Failed to set an alternate media source on glared reinvite. Video may not work properly on this call.\n");
19878 } else {
19879 ast_rtp_set_alt_peer(p->vrtp, &sin);
19880 }
19881 }
19882 }
19883 transmit_response_reliable(p, "491 Request Pending", req);
19884 ast_debug(1, "Got INVITE on call where we already have pending INVITE, deferring that - %s\n", p->callid);
19885
19886 res = 0;
19887 goto request_invite_cleanup;
19888 }
19889 }
19890
19891 p_replaces = get_header(req, "Replaces");
19892 if (!ast_strlen_zero(p_replaces)) {
19893
19894 char *ptr;
19895 char *fromtag = NULL;
19896 char *totag = NULL;
19897 char *start, *to;
19898 int error = 0;
19899
19900 if (p->owner) {
19901 ast_debug(3, "INVITE w Replaces on existing call? Refusing action. [%s]\n", p->callid);
19902 transmit_response_reliable(p, "400 Bad request", req);
19903
19904 res = -1;
19905 goto request_invite_cleanup;
19906 }
19907
19908 if (sipdebug)
19909 ast_debug(3, "INVITE part of call transfer. Replaces [%s]\n", p_replaces);
19910
19911 replace_id = ast_strdupa(p_replaces);
19912 ast_uri_decode(replace_id);
19913
19914 if (!p->refer && !sip_refer_allocate(p)) {
19915 transmit_response_reliable(p, "500 Server Internal Error", req);
19916 append_history(p, "Xfer", "INVITE/Replace Failed. Out of memory.");
19917 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19918 p->invitestate = INV_COMPLETED;
19919 res = -1;
19920 goto request_invite_cleanup;
19921 }
19922
19923
19924
19925
19926
19927
19928
19929
19930
19931
19932 replace_id = ast_skip_blanks(replace_id);
19933
19934 start = replace_id;
19935 while ( (ptr = strsep(&start, ";")) ) {
19936 ptr = ast_skip_blanks(ptr);
19937 if ( (to = strcasestr(ptr, "to-tag=") ) )
19938 totag = to + 7;
19939 else if ( (to = strcasestr(ptr, "from-tag=") ) ) {
19940 fromtag = to + 9;
19941 fromtag = strsep(&fromtag, "&");
19942 }
19943 }
19944
19945 if (sipdebug)
19946 ast_debug(4, "Invite/replaces: Will use Replace-Call-ID : %s Fromtag: %s Totag: %s\n",
19947 replace_id,
19948 fromtag ? fromtag : "<no from tag>",
19949 totag ? totag : "<no to tag>");
19950
19951
19952
19953
19954
19955 if (strncmp(replace_id, "pickup-", 7) == 0) {
19956 struct sip_pvt *subscription = NULL;
19957 replace_id += 7;
19958
19959 if ((subscription = get_sip_pvt_byid_locked(replace_id, NULL, NULL)) == NULL) {
19960 ast_log(LOG_NOTICE, "Unable to find subscription with call-id: %s\n", replace_id);
19961 transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
19962 error = 1;
19963 } else {
19964 ast_log(LOG_NOTICE, "Trying to pick up %s@%s\n", subscription->exten, subscription->context);
19965 ast_copy_string(pickup.exten, subscription->exten, sizeof(pickup.exten));
19966 ast_copy_string(pickup.context, subscription->context, sizeof(pickup.context));
19967 sip_pvt_unlock(subscription);
19968 if (subscription->owner) {
19969 ast_channel_unlock(subscription->owner);
19970 }
19971 }
19972 }
19973
19974
19975 if (!error && ast_strlen_zero(pickup.exten) && (p->refer->refer_call = get_sip_pvt_byid_locked(replace_id, totag, fromtag)) == NULL) {
19976 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existent call id (%s)!\n", replace_id);
19977 transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
19978 error = 1;
19979 } else {
19980 refer_locked = 1;
19981 }
19982
19983
19984
19985
19986
19987 if (p->refer->refer_call == p) {
19988 ast_log(LOG_NOTICE, "INVITE with replaces into it's own call id (%s == %s)!\n", replace_id, p->callid);
19989 p->refer->refer_call = dialog_unref(p->refer->refer_call, "unref dialog p->refer->refer_call");
19990 transmit_response_reliable(p, "400 Bad request", req);
19991 error = 1;
19992 }
19993
19994 if (!error && ast_strlen_zero(pickup.exten) && !p->refer->refer_call->owner) {
19995
19996 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existing call id (%s)!\n", replace_id);
19997
19998 transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replace)", req);
19999 error = 1;
20000 }
20001
20002 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) {
20003 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-ringing or active call id (%s)!\n", replace_id);
20004 transmit_response_reliable(p, "603 Declined (Replaces)", req);
20005 error = 1;
20006 }
20007
20008 if (error) {
20009 append_history(p, "Xfer", "INVITE/Replace Failed.");
20010 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20011 sip_pvt_unlock(p);
20012 if (p->refer->refer_call) {
20013 sip_pvt_unlock(p->refer->refer_call);
20014 if (p->refer->refer_call->owner) {
20015 ast_channel_unlock(p->refer->refer_call->owner);
20016 }
20017 }
20018 refer_locked = 0;
20019 p->invitestate = INV_COMPLETED;
20020 res = -1;
20021 goto request_invite_cleanup;
20022 }
20023 }
20024
20025
20026
20027
20028 if (!req->ignore) {
20029 int newcall = (p->initreq.headers ? TRUE : FALSE);
20030
20031 if (sip_cancel_destroy(p))
20032 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
20033
20034 p->pendinginvite = seqno;
20035 check_via(p, req);
20036
20037 copy_request(&p->initreq, req);
20038 if (sipdebug)
20039 ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
20040 if (!p->owner) {
20041 if (debug)
20042 ast_verbose("Using INVITE request as basis request - %s\n", p->callid);
20043 if (newcall)
20044 append_history(p, "Invite", "New call: %s", p->callid);
20045 parse_ok_contact(p, req);
20046 } else {
20047 ast_clear_flag(&p->flags[0], SIP_OUTGOING);
20048
20049 if (find_sdp(req)) {
20050 if (process_sdp(p, req, SDP_T38_INITIATE)) {
20051 transmit_response_reliable(p, "488 Not acceptable here", req);
20052 if (!p->lastinvite)
20053 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20054 res = -1;
20055 goto request_invite_cleanup;
20056 }
20057 ast_queue_control(p->owner, AST_CONTROL_SRCUPDATE);
20058 } else {
20059 p->jointcapability = p->capability;
20060 ast_debug(1, "Hm.... No sdp for the moment\n");
20061 }
20062 if (p->do_history)
20063 append_history(p, "ReInv", "Re-invite received");
20064 }
20065 } else if (debug)
20066 ast_verbose("Ignoring this INVITE request\n");
20067
20068 if (!p->lastinvite && !req->ignore && !p->owner) {
20069
20070
20071 res = check_user(p, req, SIP_INVITE, e, XMIT_RELIABLE, sin);
20072 if (res == AUTH_CHALLENGE_SENT) {
20073 p->invitestate = INV_COMPLETED;
20074 res = 0;
20075 goto request_invite_cleanup;
20076 }
20077 if (res < 0) {
20078 if (res == AUTH_FAKE_AUTH) {
20079 ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", get_header(req, "From"));
20080 transmit_fake_auth_response(p, SIP_INVITE, req, XMIT_RELIABLE);
20081 } else {
20082 ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", get_header(req, "From"));
20083 transmit_response_reliable(p, "403 Forbidden", req);
20084 }
20085 p->invitestate = INV_COMPLETED;
20086 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20087 ast_string_field_set(p, theirtag, NULL);
20088 res = 0;
20089 goto request_invite_cleanup;
20090 }
20091
20092
20093 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) && !p->udptl) {
20094 if ((p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr))) {
20095 p->t38_maxdatagram = global_t38_maxdatagram;
20096 set_t38_capabilities(p);
20097 } else {
20098
20099 ast_debug(1, "UDPTL creation failed on dialog.\n");
20100 ast_clear_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT);
20101 }
20102 }
20103
20104
20105 if (find_sdp(req)) {
20106 if (process_sdp(p, req, SDP_T38_INITIATE)) {
20107
20108 transmit_response_reliable(p, "488 Not acceptable here", req);
20109 p->invitestate = INV_COMPLETED;
20110 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20111 ast_debug(1, "No compatible codecs for this SIP call.\n");
20112 res = -1;
20113 goto request_invite_cleanup;
20114 }
20115 } else {
20116 p->jointcapability = p->capability;
20117 ast_debug(2, "No SDP in Invite, third party call control\n");
20118 }
20119
20120
20121
20122 if (p->owner)
20123 ast_queue_frame(p->owner, &ast_null_frame);
20124
20125
20126
20127 if (ast_strlen_zero(p->context))
20128 ast_string_field_set(p, context, sip_cfg.default_context);
20129
20130
20131
20132 ast_debug(1, "Checking SIP call limits for device %s\n", p->username);
20133 if ((res = update_call_counter(p, INC_CALL_LIMIT))) {
20134 if (res < 0) {
20135 ast_log(LOG_NOTICE, "Failed to place call for device %s, too many calls\n", p->username);
20136 transmit_response_reliable(p, "480 Temporarily Unavailable (Call limit) ", req);
20137 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20138 p->invitestate = INV_COMPLETED;
20139 }
20140 res = 0;
20141 goto request_invite_cleanup;
20142 }
20143 gotdest = get_destination(p, NULL);
20144 get_rdnis(p, NULL);
20145 extract_uri(p, req);
20146 build_contact(p);
20147
20148 if (p->rtp) {
20149 ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
20150 ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
20151 }
20152
20153 if (!replace_id && gotdest) {
20154 if (gotdest == 1 && ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP))
20155 transmit_response_reliable(p, "484 Address Incomplete", req);
20156 else {
20157 char *decoded_exten = ast_strdupa(p->exten);
20158
20159 transmit_response_reliable(p, "404 Not Found", req);
20160 ast_uri_decode(decoded_exten);
20161 ast_log(LOG_NOTICE, "Call from '%s' to extension"
20162 " '%s' rejected because extension not found in context '%s'.\n",
20163 S_OR(p->username, p->peername), decoded_exten, p->context);
20164 }
20165 p->invitestate = INV_COMPLETED;
20166 update_call_counter(p, DEC_CALL_LIMIT);
20167 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20168 res = 0;
20169 goto request_invite_cleanup;
20170 } else {
20171
20172
20173
20174 if (ast_strlen_zero(p->exten))
20175 ast_string_field_set(p, exten, "s");
20176
20177
20178 make_our_tag(p->tag, sizeof(p->tag));
20179
20180 c = sip_new(p, AST_STATE_DOWN, S_OR(p->peername, NULL));
20181 *recount = 1;
20182
20183
20184 build_route(p, req, 0);
20185
20186 if (c) {
20187
20188 ast_channel_lock(c);
20189 }
20190 }
20191 } else {
20192 if (sipdebug) {
20193 if (!req->ignore)
20194 ast_debug(2, "Got a SIP re-invite for call %s\n", p->callid);
20195 else
20196 ast_debug(2, "Got a SIP re-transmit of INVITE for call %s\n", p->callid);
20197 }
20198 if (!req->ignore)
20199 reinvite = 1;
20200 c = p->owner;
20201 }
20202
20203
20204 if (p->sipoptions & SIP_OPT_TIMER) {
20205
20206
20207 ast_debug(2, "Incoming INVITE with 'timer' option enabled\n");
20208
20209
20210 if (!p->stimer)
20211 sip_st_alloc(p);
20212
20213
20214 p_uac_se_hdr = get_header(req, "Session-Expires");
20215 if (!ast_strlen_zero(p_uac_se_hdr)) {
20216 rtn = parse_session_expires(p_uac_se_hdr, &uac_max_se, &st_ref);
20217 if (rtn != 0) {
20218 transmit_response_reliable(p, "400 Session-Expires Invalid Syntax", req);
20219 p->invitestate = INV_COMPLETED;
20220 if (!p->lastinvite) {
20221 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20222 }
20223 res = -1;
20224 goto request_invite_cleanup;
20225 }
20226 }
20227
20228
20229 p_uac_min_se = get_header(req, "Min-SE");
20230 if (!ast_strlen_zero(p_uac_min_se)) {
20231 rtn = parse_minse(p_uac_min_se, &uac_min_se);
20232 if (rtn != 0) {
20233 transmit_response_reliable(p, "400 Min-SE Invalid Syntax", req);
20234 p->invitestate = INV_COMPLETED;
20235 if (!p->lastinvite) {
20236 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20237 }
20238 res = -1;
20239 goto request_invite_cleanup;
20240 }
20241 }
20242
20243 dlg_min_se = st_get_se(p, FALSE);
20244 switch (st_get_mode(p)) {
20245 case SESSION_TIMER_MODE_ACCEPT:
20246 case SESSION_TIMER_MODE_ORIGINATE:
20247 if (uac_max_se > 0 && uac_max_se < dlg_min_se) {
20248 transmit_response_with_minse(p, "422 Session Interval Too Small", req, dlg_min_se);
20249 p->invitestate = INV_COMPLETED;
20250 if (!p->lastinvite) {
20251 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20252 }
20253 res = -1;
20254 goto request_invite_cleanup;
20255 }
20256
20257 p->stimer->st_active_peer_ua = TRUE;
20258 st_active = TRUE;
20259 if (st_ref == SESSION_TIMER_REFRESHER_AUTO) {
20260 st_ref = st_get_refresher(p);
20261 }
20262
20263 if (uac_max_se > 0) {
20264 int dlg_max_se = st_get_se(p, TRUE);
20265 if (dlg_max_se >= uac_min_se) {
20266 st_interval = (uac_max_se < dlg_max_se) ? uac_max_se : dlg_max_se;
20267 } else {
20268 st_interval = uac_max_se;
20269 }
20270 } else {
20271
20272 st_interval = global_max_se;
20273 }
20274 break;
20275
20276 case SESSION_TIMER_MODE_REFUSE:
20277 if (p->reqsipoptions & SIP_OPT_TIMER) {
20278 transmit_response_with_unsupported(p, "420 Option Disabled", req, required);
20279 ast_log(LOG_WARNING, "Received SIP INVITE with supported but disabled option: %s\n", required);
20280 p->invitestate = INV_COMPLETED;
20281 if (!p->lastinvite) {
20282 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20283 }
20284 res = -1;
20285 goto request_invite_cleanup;
20286 }
20287 break;
20288
20289 default:
20290 ast_log(LOG_ERROR, "Internal Error %d at %s:%d\n", st_get_mode(p), __FILE__, __LINE__);
20291 break;
20292 }
20293 } else {
20294
20295
20296
20297 switch (st_get_mode(p)) {
20298 case SESSION_TIMER_MODE_ORIGINATE:
20299 st_active = TRUE;
20300 st_interval = st_get_se(p, TRUE);
20301 st_ref = SESSION_TIMER_REFRESHER_UAS;
20302 p->stimer->st_active_peer_ua = FALSE;
20303 break;
20304
20305 default:
20306 break;
20307 }
20308 }
20309
20310 if (reinvite == 0) {
20311
20312 if (st_active == TRUE) {
20313 p->stimer->st_active = TRUE;
20314 p->stimer->st_interval = st_interval;
20315 p->stimer->st_ref = st_ref;
20316 start_session_timer(p);
20317 }
20318 } else {
20319 if (p->stimer->st_active == TRUE) {
20320
20321
20322
20323 ast_debug (2, "Restarting session-timers on a refresh - %s\n", p->callid);
20324
20325
20326 if (st_interval > 0) {
20327 p->stimer->st_interval = st_interval;
20328 p->stimer->st_ref = st_ref;
20329 }
20330
20331 restart_session_timer(p);
20332 if (p->stimer->st_expirys > 0) {
20333 p->stimer->st_expirys--;
20334 }
20335 }
20336 }
20337
20338 if (!req->ignore && p)
20339 p->lastinvite = seqno;
20340
20341 if (replace_id) {
20342 if (!ast_strlen_zero(pickup.exten)) {
20343 append_history(p, "Xfer", "INVITE/Replace received");
20344
20345
20346 transmit_response(p, "100 Trying", req);
20347 p->invitestate = INV_PROCEEDING;
20348 ast_setstate(c, AST_STATE_RING);
20349
20350
20351 ast_channel_unlock(c);
20352 *nounlock = 1;
20353 do_magic_pickup(c, pickup.exten, pickup.context);
20354
20355
20356 sip_pvt_unlock(p);
20357 ast_hangup(c);
20358 sip_pvt_lock(p);
20359
20360 res = 0;
20361 goto request_invite_cleanup;
20362 } else {
20363
20364 if (sipdebug)
20365 ast_debug(4, "Sending this call to the invite/replcaes handler %s\n", p->callid);
20366 res = handle_invite_replaces(p, req, debug, seqno, sin, nounlock);
20367 refer_locked = 0;
20368 goto request_invite_cleanup;
20369 }
20370 }
20371
20372
20373 if (c) {
20374 enum ast_channel_state c_state = c->_state;
20375
20376 if (c_state != AST_STATE_UP && reinvite &&
20377 (p->invitestate == INV_TERMINATED || p->invitestate == INV_CONFIRMED)) {
20378
20379
20380
20381
20382
20383
20384
20385
20386
20387 c_state = AST_STATE_UP;
20388 }
20389
20390 switch(c_state) {
20391 case AST_STATE_DOWN:
20392 ast_debug(2, "%s: New call is still down.... Trying... \n", c->name);
20393 transmit_provisional_response(p, "100 Trying", req, 0);
20394 p->invitestate = INV_PROCEEDING;
20395 ast_setstate(c, AST_STATE_RING);
20396 if (strcmp(p->exten, ast_pickup_ext())) {
20397 enum ast_pbx_result result;
20398
20399 result = ast_pbx_start(c);
20400
20401 switch(result) {
20402 case AST_PBX_FAILED:
20403 ast_log(LOG_WARNING, "Failed to start PBX :(\n");
20404 p->invitestate = INV_COMPLETED;
20405 transmit_response_reliable(p, "503 Unavailable", req);
20406 break;
20407 case AST_PBX_CALL_LIMIT:
20408 ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
20409 p->invitestate = INV_COMPLETED;
20410 transmit_response_reliable(p, "480 Temporarily Unavailable", req);
20411 break;
20412 case AST_PBX_SUCCESS:
20413
20414 break;
20415 }
20416
20417 if (result) {
20418
20419
20420 ast_channel_unlock(c);
20421 sip_pvt_unlock(p);
20422 ast_hangup(c);
20423 sip_pvt_lock(p);
20424 c = NULL;
20425 }
20426 } else {
20427 ast_channel_unlock(c);
20428 *nounlock = 1;
20429 if (ast_pickup_call(c)) {
20430 ast_log(LOG_NOTICE, "Nothing to pick up for %s\n", p->callid);
20431 transmit_response_reliable(p, "503 Unavailable", req);
20432 sip_alreadygone(p);
20433
20434 sip_pvt_unlock(p);
20435 c->hangupcause = AST_CAUSE_CALL_REJECTED;
20436 } else {
20437 sip_pvt_unlock(p);
20438 ast_setstate(c, AST_STATE_DOWN);
20439 c->hangupcause = AST_CAUSE_NORMAL_CLEARING;
20440 }
20441 p->invitestate = INV_COMPLETED;
20442 ast_hangup(c);
20443 sip_pvt_lock(p);
20444 c = NULL;
20445 }
20446 break;
20447 case AST_STATE_RING:
20448 transmit_provisional_response(p, "100 Trying", req, 0);
20449 p->invitestate = INV_PROCEEDING;
20450 break;
20451 case AST_STATE_RINGING:
20452 transmit_provisional_response(p, "180 Ringing", req, 0);
20453 p->invitestate = INV_PROCEEDING;
20454 break;
20455 case AST_STATE_UP:
20456 ast_debug(2, "%s: This call is UP.... \n", c->name);
20457
20458 transmit_response(p, "100 Trying", req);
20459
20460 if (p->t38.state == T38_PEER_REINVITE) {
20461 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."));
20462 } else if (p->t38.state == T38_ENABLED) {
20463 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
20464 transmit_response_with_t38_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL)));
20465 } else if (p->t38.state == T38_DISABLED) {
20466
20467 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
20468 transmit_response_with_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL)), p->session_modify == TRUE ? FALSE:TRUE);
20469 }
20470
20471 p->invitestate = INV_TERMINATED;
20472 break;
20473 default:
20474 ast_log(LOG_WARNING, "Don't know how to handle INVITE in state %d\n", c->_state);
20475 transmit_response(p, "100 Trying", req);
20476 break;
20477 }
20478 } else {
20479 if (p && (p->autokillid == -1)) {
20480 const char *msg;
20481
20482 if (!p->jointcapability)
20483 msg = "488 Not Acceptable Here (codec error)";
20484 else {
20485 ast_log(LOG_NOTICE, "Unable to create/find SIP channel for this INVITE\n");
20486 msg = "503 Unavailable";
20487 }
20488 transmit_response_reliable(p, msg, req);
20489 p->invitestate = INV_COMPLETED;
20490 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20491 }
20492 }
20493
20494 request_invite_cleanup:
20495
20496 if (refer_locked && p->refer && p->refer->refer_call) {
20497 sip_pvt_unlock(p->refer->refer_call);
20498 if (p->refer->refer_call->owner) {
20499 ast_channel_unlock(p->refer->refer_call->owner);
20500 }
20501 }
20502
20503 return res;
20504 }
20505
20506
20507
20508 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno)
20509 {
20510 struct sip_dual target;
20511
20512 int res = 0;
20513 struct sip_pvt *targetcall_pvt;
20514
20515
20516 if (!(targetcall_pvt = get_sip_pvt_byid_locked(transferer->refer->replaces_callid, transferer->refer->replaces_callid_totag,
20517 transferer->refer->replaces_callid_fromtag))) {
20518 if (transferer->refer->localtransfer) {
20519
20520 transmit_response(transferer, "202 Accepted", req);
20521
20522
20523 transmit_notify_with_sipfrag(transferer, seqno, "481 Call leg/transaction does not exist", TRUE);
20524 append_history(transferer, "Xfer", "Refer failed");
20525 ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
20526 transferer->refer->status = REFER_FAILED;
20527 return -1;
20528 }
20529
20530 ast_debug(3, "SIP attended transfer: Not our call - generating INVITE with replaces\n");
20531 return 0;
20532 }
20533
20534
20535 transmit_response(transferer, "202 Accepted", req);
20536 append_history(transferer, "Xfer", "Refer accepted");
20537 if (!targetcall_pvt->owner) {
20538 ast_debug(4, "SIP attended transfer: Error: No owner of target call\n");
20539
20540 transmit_notify_with_sipfrag(transferer, seqno, "503 Service Unavailable", TRUE);
20541 append_history(transferer, "Xfer", "Refer failed");
20542 ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
20543 transferer->refer->status = REFER_FAILED;
20544 sip_pvt_unlock(targetcall_pvt);
20545 if (targetcall_pvt)
20546 ao2_t_ref(targetcall_pvt, -1, "Drop targetcall_pvt pointer");
20547 return -1;
20548 }
20549
20550
20551 target.chan1 = targetcall_pvt->owner;
20552 target.chan2 = ast_bridged_channel(targetcall_pvt->owner);
20553
20554 if (!target.chan2 || !(target.chan2->_state == AST_STATE_UP || target.chan2->_state == AST_STATE_RINGING) ) {
20555
20556 if (target.chan2)
20557 ast_debug(4, "SIP attended transfer: Error: Wrong state of target call: %s\n", ast_state2str(target.chan2->_state));
20558 else if (target.chan1->_state != AST_STATE_RING)
20559 ast_debug(4, "SIP attended transfer: Error: No target channel\n");
20560 else
20561 ast_debug(4, "SIP attended transfer: Attempting transfer in ringing state\n");
20562 }
20563
20564
20565 if (sipdebug) {
20566 if (current->chan2)
20567 ast_debug(4, "SIP attended transfer: trying to bridge %s and %s\n", target.chan1->name, current->chan2->name);
20568 else
20569 ast_debug(4, "SIP attended transfer: trying to make %s take over (masq) %s\n", target.chan1->name, current->chan1->name);
20570 }
20571
20572 ast_set_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
20573
20574
20575 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",
20576 transferer->owner->name,
20577 transferer->owner->uniqueid,
20578 transferer->callid,
20579 target.chan1->name,
20580 target.chan1->uniqueid);
20581 res = attempt_transfer(current, &target);
20582 sip_pvt_unlock(targetcall_pvt);
20583 if (res) {
20584
20585 transmit_notify_with_sipfrag(transferer, seqno, "486 Busy Here", TRUE);
20586 append_history(transferer, "Xfer", "Refer failed");
20587 if (targetcall_pvt->owner)
20588 ast_channel_unlock(targetcall_pvt->owner);
20589 ast_clear_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
20590 } else {
20591
20592 const char *xfersound = pbx_builtin_getvar_helper(target.chan1, "ATTENDED_TRANSFER_COMPLETE_SOUND");
20593
20594
20595 transmit_notify_with_sipfrag(transferer, seqno, "200 OK", TRUE);
20596 append_history(transferer, "Xfer", "Refer succeeded");
20597 transferer->refer->status = REFER_200OK;
20598 if (target.chan2 && !ast_strlen_zero(xfersound) && ast_streamfile(target.chan2, xfersound, target.chan2->language) >= 0) {
20599 ast_waitstream(target.chan2, "");
20600 }
20601 if (targetcall_pvt->owner) {
20602 ast_debug(1, "SIP attended transfer: Unlocking channel %s\n", targetcall_pvt->owner->name);
20603 ast_channel_unlock(targetcall_pvt->owner);
20604 }
20605 }
20606 if (targetcall_pvt)
20607 ao2_t_ref(targetcall_pvt, -1, "drop targetcall_pvt");
20608 return 1;
20609 }
20610
20611
20612
20613
20614
20615
20616
20617
20618
20619
20620
20621
20622
20623
20624
20625
20626
20627
20628
20629
20630
20631
20632
20633
20634
20635
20636
20637
20638
20639
20640
20641
20642
20643
20644
20645
20646
20647
20648
20649
20650
20651
20652
20653
20654
20655
20656
20657
20658
20659
20660
20661
20662
20663
20664
20665
20666
20667
20668
20669
20670
20671
20672
20673
20674
20675 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock)
20676 {
20677 struct sip_dual current;
20678
20679
20680 int res = 0;
20681 current.req.data = NULL;
20682
20683 if (req->debug)
20684 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");
20685
20686 if (!p->owner) {
20687
20688
20689 ast_debug(3, "Call %s: Declined REFER, outside of dialog...\n", p->callid);
20690 transmit_response(p, "603 Declined (No dialog)", req);
20691 if (!req->ignore) {
20692 append_history(p, "Xfer", "Refer failed. Outside of dialog.");
20693 sip_alreadygone(p);
20694 pvt_set_needdestroy(p, "outside of dialog");
20695 }
20696 return 0;
20697 }
20698
20699
20700
20701 if (p->allowtransfer == TRANSFER_CLOSED ) {
20702
20703 transmit_response(p, "603 Declined (policy)", req);
20704 append_history(p, "Xfer", "Refer failed. Allowtransfer == closed.");
20705
20706 return 0;
20707 }
20708
20709 if (!req->ignore && ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
20710
20711 transmit_response(p, "491 Request pending", req);
20712 append_history(p, "Xfer", "Refer failed. Request pending.");
20713 return 0;
20714 }
20715
20716
20717 if (!p->refer && !sip_refer_allocate(p)) {
20718 transmit_response(p, "500 Internal Server Error", req);
20719 append_history(p, "Xfer", "Refer failed. Memory allocation error.");
20720 return -3;
20721 }
20722
20723 res = get_refer_info(p, req);
20724
20725 p->refer->status = REFER_SENT;
20726
20727 if (res != 0) {
20728 switch (res) {
20729 case -2:
20730 transmit_response(p, "400 Bad Request (Refer-to missing)", req);
20731 append_history(p, "Xfer", "Refer failed. Refer-to missing.");
20732 if (req->debug)
20733 ast_debug(1, "SIP transfer to black hole can't be handled (no refer-to: )\n");
20734 break;
20735 case -3:
20736 transmit_response(p, "603 Declined (Non sip: uri)", req);
20737 append_history(p, "Xfer", "Refer failed. Non SIP uri");
20738 if (req->debug)
20739 ast_debug(1, "SIP transfer to non-SIP uri denied\n");
20740 break;
20741 default:
20742
20743 transmit_response(p, "202 Accepted", req);
20744 append_history(p, "Xfer", "Refer failed. Bad extension.");
20745 transmit_notify_with_sipfrag(p, seqno, "404 Not found", TRUE);
20746 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
20747 if (req->debug)
20748 ast_debug(1, "SIP transfer to bad extension: %s\n", p->refer->refer_to);
20749 break;
20750 }
20751 return 0;
20752 }
20753 if (ast_strlen_zero(p->context))
20754 ast_string_field_set(p, context, sip_cfg.default_context);
20755
20756
20757 if (sip_cfg.allow_external_domains && check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
20758 p->refer->localtransfer = 1;
20759 if (sipdebug)
20760 ast_debug(3, "This SIP transfer is local : %s\n", p->refer->refer_to_domain);
20761 } else if (AST_LIST_EMPTY(&domain_list) || check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
20762
20763 p->refer->localtransfer = 1;
20764 } else if (sipdebug)
20765 ast_debug(3, "This SIP transfer is to a remote SIP extension (remote domain %s)\n", p->refer->refer_to_domain);
20766
20767
20768
20769 if (req->ignore)
20770 return res;
20771
20772
20773
20774
20775
20776
20777
20778
20779
20780
20781
20782
20783
20784
20785
20786
20787
20788
20789
20790
20791
20792
20793
20794
20795
20796
20797
20798 current.chan1 = p->owner;
20799
20800
20801 current.chan2 = ast_bridged_channel(current.chan1);
20802
20803 if (sipdebug)
20804 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>");
20805
20806 if (!current.chan2 && !p->refer->attendedtransfer) {
20807
20808
20809
20810 if (sipdebug)
20811 ast_debug(3, "Refused SIP transfer on non-bridged channel.\n");
20812 p->refer->status = REFER_FAILED;
20813 append_history(p, "Xfer", "Refer failed. Non-bridged channel.");
20814 transmit_response(p, "603 Declined", req);
20815 return -1;
20816 }
20817
20818 if (current.chan2) {
20819 if (sipdebug)
20820 ast_debug(4, "Got SIP transfer, applying to bridged peer '%s'\n", current.chan2->name);
20821
20822 ast_queue_control(current.chan1, AST_CONTROL_UNHOLD);
20823 }
20824
20825 ast_set_flag(&p->flags[0], SIP_GOTREFER);
20826
20827
20828 if (p->refer->attendedtransfer) {
20829 if ((res = local_attended_transfer(p, ¤t, req, seqno)))
20830 return res;
20831
20832 if (sipdebug)
20833 ast_debug(4, "SIP attended transfer: Still not our call - generating INVITE with replaces\n");
20834
20835 }
20836
20837
20838
20839 if (p->refer->localtransfer && !strcmp(p->refer->refer_to, ast_parking_ext())) {
20840
20841 *nounlock = 1;
20842 ast_channel_unlock(current.chan1);
20843 copy_request(¤t.req, req);
20844 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
20845 p->refer->status = REFER_200OK;
20846 append_history(p, "Xfer", "REFER to call parking.");
20847 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",
20848 current.chan1->name,
20849 current.chan1->uniqueid,
20850 p->callid,
20851 current.chan2->name,
20852 current.chan2->uniqueid,
20853 p->refer->refer_to);
20854 if (sipdebug)
20855 ast_debug(4, "SIP transfer to parking: trying to park %s. Parked by %s\n", current.chan2->name, current.chan1->name);
20856 sip_park(current.chan2, current.chan1, req, seqno);
20857 return res;
20858 }
20859
20860
20861 transmit_response(p, "202 Accepted", req);
20862
20863 if (current.chan1 && current.chan2) {
20864 ast_debug(3, "chan1->name: %s\n", current.chan1->name);
20865 pbx_builtin_setvar_helper(current.chan1, "BLINDTRANSFER", current.chan2->name);
20866 }
20867 if (current.chan2) {
20868 pbx_builtin_setvar_helper(current.chan2, "BLINDTRANSFER", current.chan1->name);
20869 pbx_builtin_setvar_helper(current.chan2, "SIPDOMAIN", p->refer->refer_to_domain);
20870 pbx_builtin_setvar_helper(current.chan2, "SIPTRANSFER", "yes");
20871
20872 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER", "yes");
20873
20874 if (p->refer->referred_by)
20875 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REFERER", p->refer->referred_by);
20876 }
20877
20878 if (!ast_strlen_zero(p->refer->replaces_callid)) {
20879 char tempheader[SIPBUFSIZE];
20880 snprintf(tempheader, sizeof(tempheader), "%s%s%s%s%s", p->refer->replaces_callid,
20881 p->refer->replaces_callid_totag ? ";to-tag=" : "",
20882 p->refer->replaces_callid_totag,
20883 p->refer->replaces_callid_fromtag ? ";from-tag=" : "",
20884 p->refer->replaces_callid_fromtag);
20885 if (current.chan2)
20886 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REPLACES", tempheader);
20887 }
20888
20889
20890 *nounlock = 1;
20891 ast_channel_unlock(current.chan1);
20892
20893
20894
20895
20896 if (!p->refer->attendedtransfer)
20897 transmit_notify_with_sipfrag(p, seqno, "183 Ringing", FALSE);
20898
20899
20900
20901
20902
20903 if (!current.chan2) {
20904
20905
20906
20907
20908
20909
20910
20911 p->refer->status = REFER_FAILED;
20912 transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable (can't handle one-legged xfers)", TRUE);
20913 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
20914 append_history(p, "Xfer", "Refer failed (only bridged calls).");
20915 return -1;
20916 }
20917 ast_set_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
20918
20919
20920
20921
20922 res = ast_async_goto(current.chan2, p->refer->refer_to_context, p->refer->refer_to, 1);
20923
20924 if (!res) {
20925 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",
20926 current.chan1->name,
20927 current.chan1->uniqueid,
20928 p->callid,
20929 current.chan2->name,
20930 current.chan2->uniqueid,
20931 p->refer->refer_to, p->refer->refer_to_context);
20932
20933 ast_debug(3, "%s transfer succeeded. Telling transferer.\n", p->refer->attendedtransfer? "Attended" : "Blind");
20934 transmit_notify_with_sipfrag(p, seqno, "200 Ok", TRUE);
20935 if (p->refer->localtransfer)
20936 p->refer->status = REFER_200OK;
20937 if (p->owner)
20938 p->owner->hangupcause = AST_CAUSE_NORMAL_CLEARING;
20939 append_history(p, "Xfer", "Refer succeeded.");
20940 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
20941
20942
20943 res = 0;
20944 } else {
20945 ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
20946 ast_debug(3, "%s transfer failed. Resuming original call.\n", p->refer->attendedtransfer? "Attended" : "Blind");
20947 append_history(p, "Xfer", "Refer failed.");
20948
20949 p->refer->status = REFER_FAILED;
20950 transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable", TRUE);
20951 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
20952 res = -1;
20953 }
20954 return res;
20955 }
20956
20957
20958 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req)
20959 {
20960
20961 check_via(p, req);
20962 sip_alreadygone(p);
20963
20964
20965
20966
20967
20968
20969 if (p->invitestate == INV_TERMINATED)
20970 __sip_pretend_ack(p);
20971 else
20972 p->invitestate = INV_CANCELLED;
20973
20974 if (p->owner && p->owner->_state == AST_STATE_UP) {
20975
20976 transmit_response(p, "200 OK", req);
20977 ast_debug(1, "Got CANCEL on an answered call. Ignoring... \n");
20978 return 0;
20979 }
20980
20981 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD))
20982 update_call_counter(p, DEC_CALL_LIMIT);
20983
20984 stop_media_flows(p);
20985 if (p->owner)
20986 ast_queue_hangup(p->owner);
20987 else
20988 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20989 if (p->initreq.len > 0) {
20990 struct sip_pkt *pkt, *prev_pkt;
20991
20992
20993
20994
20995
20996
20997
20998
20999
21000
21001
21002 for (pkt = p->packets, prev_pkt = NULL; pkt; prev_pkt = pkt, pkt = pkt->next) {
21003 if (pkt->seqno == p->lastinvite && pkt->response_code == 487) {
21004 AST_SCHED_DEL(sched, pkt->retransid);
21005 UNLINK(pkt, p->packets, prev_pkt);
21006 ast_free(pkt);
21007 break;
21008 }
21009 }
21010 transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
21011 transmit_response(p, "200 OK", req);
21012 return 1;
21013 } else {
21014 transmit_response(p, "481 Call Leg Does Not Exist", req);
21015 return 0;
21016 }
21017 }
21018
21019 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen)
21020 {
21021 struct sip_pvt *p = chan->tech_pvt;
21022 char *all = "", *parse = ast_strdupa(preparse);
21023 int res = 0;
21024 AST_DECLARE_APP_ARGS(args,
21025 AST_APP_ARG(param);
21026 AST_APP_ARG(type);
21027 AST_APP_ARG(field);
21028 );
21029 AST_STANDARD_APP_ARGS(args, parse);
21030
21031
21032 if (!IS_SIP_TECH(chan->tech)) {
21033 ast_log(LOG_ERROR, "Cannot call %s on a non-SIP channel\n", funcname);
21034 return 0;
21035 }
21036
21037 memset(buf, 0, buflen);
21038
21039 if (p == NULL) {
21040 return -1;
21041 }
21042
21043 if (!strcasecmp(args.param, "peerip")) {
21044 ast_copy_string(buf, p->sa.sin_addr.s_addr ? ast_inet_ntoa(p->sa.sin_addr) : "", buflen);
21045 } else if (!strcasecmp(args.param, "recvip")) {
21046 ast_copy_string(buf, p->recv.sin_addr.s_addr ? ast_inet_ntoa(p->recv.sin_addr) : "", buflen);
21047 } else if (!strcasecmp(args.param, "from")) {
21048 ast_copy_string(buf, p->from, buflen);
21049 } else if (!strcasecmp(args.param, "uri")) {
21050 ast_copy_string(buf, p->uri, buflen);
21051 } else if (!strcasecmp(args.param, "useragent")) {
21052 ast_copy_string(buf, p->useragent, buflen);
21053 } else if (!strcasecmp(args.param, "peername")) {
21054 ast_copy_string(buf, p->peername, buflen);
21055 } else if (!strcasecmp(args.param, "t38passthrough")) {
21056 ast_copy_string(buf, (p->t38.state == T38_DISABLED) ? "0" : "1", buflen);
21057 } else if (!strcasecmp(args.param, "rtpdest")) {
21058 struct sockaddr_in sin;
21059 struct ast_rtp *stream = NULL;
21060
21061 if (ast_strlen_zero(args.type))
21062 args.type = "audio";
21063
21064 if (!strcasecmp(args.type, "audio")) {
21065 stream = p->rtp;
21066 } else if (!strcasecmp(args.type, "video")) {
21067 stream = p->vrtp;
21068 } else if (!strcasecmp(args.type, "text")) {
21069 stream = p->trtp;
21070 } else {
21071 return -1;
21072 }
21073
21074 if (!stream) {
21075 return -1;
21076 }
21077
21078 ast_rtp_get_peer(stream, &sin);
21079 snprintf(buf, buflen, "%s:%d", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
21080 } else if (!strcasecmp(args.param, "rtpqos")) {
21081 struct ast_rtp_quality qos;
21082 struct ast_rtp *rtp = p->rtp;
21083
21084 memset(&qos, 0, sizeof(qos));
21085
21086 if (ast_strlen_zero(args.type))
21087 args.type = "audio";
21088 if (ast_strlen_zero(args.field))
21089 args.field = "all";
21090
21091 if (!strcasecmp(args.type, "AUDIO")) {
21092 all = ast_rtp_get_quality(rtp = p->rtp, &qos, RTPQOS_SUMMARY);
21093 } else if (!strcasecmp(args.type, "VIDEO")) {
21094 all = ast_rtp_get_quality(rtp = p->vrtp, &qos, RTPQOS_SUMMARY);
21095 } else if (!strcasecmp(args.type, "TEXT")) {
21096 all = ast_rtp_get_quality(rtp = p->trtp, &qos, RTPQOS_SUMMARY);
21097 } else {
21098 return -1;
21099 }
21100
21101 if (!strcasecmp(args.field, "local_ssrc"))
21102 snprintf(buf, buflen, "%u", qos.local_ssrc);
21103 else if (!strcasecmp(args.field, "local_lostpackets"))
21104 snprintf(buf, buflen, "%u", qos.local_lostpackets);
21105 else if (!strcasecmp(args.field, "local_jitter"))
21106 snprintf(buf, buflen, "%.0f", qos.local_jitter * 1000.0);
21107 else if (!strcasecmp(args.field, "local_count"))
21108 snprintf(buf, buflen, "%u", qos.local_count);
21109 else if (!strcasecmp(args.field, "remote_ssrc"))
21110 snprintf(buf, buflen, "%u", qos.remote_ssrc);
21111 else if (!strcasecmp(args.field, "remote_lostpackets"))
21112 snprintf(buf, buflen, "%u", qos.remote_lostpackets);
21113 else if (!strcasecmp(args.field, "remote_jitter"))
21114 snprintf(buf, buflen, "%.0f", qos.remote_jitter * 1000.0);
21115 else if (!strcasecmp(args.field, "remote_count"))
21116 snprintf(buf, buflen, "%u", qos.remote_count);
21117 else if (!strcasecmp(args.field, "rtt"))
21118 snprintf(buf, buflen, "%.0f", qos.rtt * 1000.0);
21119 else if (!strcasecmp(args.field, "all"))
21120 ast_copy_string(buf, all, buflen);
21121 else if (!ast_rtp_get_qos(rtp, args.field, buf, buflen))
21122 ;
21123 else {
21124 ast_log(LOG_WARNING, "Unrecognized argument '%s' to %s\n", preparse, funcname);
21125 return -1;
21126 }
21127 } else {
21128 res = -1;
21129 }
21130 return res;
21131 }
21132
21133
21134 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req)
21135 {
21136 struct ast_channel *c=NULL;
21137 int res;
21138 struct ast_channel *bridged_to;
21139
21140
21141 if (p->pendinginvite && !ast_test_flag(&p->flags[0], SIP_OUTGOING) && !req->ignore) {
21142 transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
21143 }
21144
21145 __sip_pretend_ack(p);
21146
21147 p->invitestate = INV_TERMINATED;
21148
21149 copy_request(&p->initreq, req);
21150 if (sipdebug)
21151 ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
21152 check_via(p, req);
21153 sip_alreadygone(p);
21154
21155
21156 if (p->do_history || p->owner) {
21157 struct ast_channel *bridge = p->owner ? ast_bridged_channel(p->owner) : NULL;
21158 char *videoqos, *textqos;
21159
21160
21161
21162
21163 while (bridge && ast_channel_trylock(bridge)) {
21164 ast_channel_unlock(p->owner);
21165 do {
21166
21167 sip_pvt_unlock(p);
21168 usleep(1);
21169 sip_pvt_lock(p);
21170 } while (p->owner && ast_channel_trylock(p->owner));
21171 bridge = p->owner ? ast_bridged_channel(p->owner) : NULL;
21172 }
21173
21174 if (p->rtp) {
21175 if (p->do_history) {
21176 char *audioqos,
21177 *audioqos_jitter,
21178 *audioqos_loss,
21179 *audioqos_rtt;
21180
21181 audioqos = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_SUMMARY);
21182 audioqos_jitter = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_JITTER);
21183 audioqos_loss = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_LOSS);
21184 audioqos_rtt = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_RTT);
21185
21186 append_history(p, "RTCPaudio", "Quality:%s", audioqos);
21187 append_history(p, "RTCPaudioJitter", "Quality:%s", audioqos_jitter);
21188 append_history(p, "RTCPaudioLoss", "Quality:%s", audioqos_loss);
21189 append_history(p, "RTCPaudioRTT", "Quality:%s", audioqos_rtt);
21190 }
21191
21192 if (p->owner) {
21193 ast_rtp_set_vars(p->owner, p->rtp);
21194 }
21195 }
21196
21197 if (bridge) {
21198 struct sip_pvt *q = bridge->tech_pvt;
21199
21200 if (IS_SIP_TECH(bridge->tech) && q && q->rtp)
21201 ast_rtp_set_vars(bridge, q->rtp);
21202 ast_channel_unlock(bridge);
21203 }
21204
21205 if (p->vrtp) {
21206 videoqos = ast_rtp_get_quality(p->vrtp, NULL, RTPQOS_SUMMARY);
21207 if (p->do_history)
21208 append_history(p, "RTCPvideo", "Quality:%s", videoqos);
21209 if (p->owner)
21210 pbx_builtin_setvar_helper(p->owner, "RTPVIDEOQOS", videoqos);
21211 }
21212
21213 if (p->trtp) {
21214 textqos = ast_rtp_get_quality(p->trtp, NULL, RTPQOS_SUMMARY);
21215 if (p->do_history)
21216 append_history(p, "RTCPtext", "Quality:%s", textqos);
21217 if (p->owner)
21218 pbx_builtin_setvar_helper(p->owner, "RTPTEXTQOS", textqos);
21219 }
21220 }
21221
21222 stop_media_flows(p);
21223 stop_session_timer(p);
21224
21225 if (!ast_strlen_zero(get_header(req, "Also"))) {
21226 ast_log(LOG_NOTICE, "Client '%s' using deprecated BYE/Also transfer method. Ask vendor to support REFER instead\n",
21227 ast_inet_ntoa(p->recv.sin_addr));
21228 if (ast_strlen_zero(p->context))
21229 ast_string_field_set(p, context, sip_cfg.default_context);
21230 res = get_also_info(p, req);
21231 if (!res) {
21232 c = p->owner;
21233 if (c) {
21234 bridged_to = ast_bridged_channel(c);
21235 if (bridged_to) {
21236
21237 ast_queue_control(c, AST_CONTROL_UNHOLD);
21238 ast_async_goto(bridged_to, p->context, p->refer->refer_to, 1);
21239 } else
21240 ast_queue_hangup(p->owner);
21241 }
21242 } else {
21243 ast_log(LOG_WARNING, "Invalid transfer information from '%s'\n", ast_inet_ntoa(p->recv.sin_addr));
21244 if (p->owner)
21245 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
21246 }
21247 } else if (p->owner) {
21248 ast_queue_hangup(p->owner);
21249 ast_debug(3, "Received bye, issuing owner hangup\n");
21250 } else {
21251 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21252 ast_debug(3, "Received bye, no owner, selfdestruct soon.\n");
21253 }
21254 ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
21255 transmit_response(p, "200 OK", req);
21256
21257 return 1;
21258 }
21259
21260
21261 static int handle_request_message(struct sip_pvt *p, struct sip_request *req)
21262 {
21263 if (!req->ignore) {
21264 if (req->debug)
21265 ast_verbose("Receiving message!\n");
21266 receive_message(p, req);
21267 } else
21268 transmit_response(p, "202 Accepted", req);
21269 return 1;
21270 }
21271
21272 static void add_peer_mwi_subs(struct sip_peer *peer)
21273 {
21274 struct sip_mailbox *mailbox;
21275
21276 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
21277 mailbox->event_sub = ast_event_subscribe(AST_EVENT_MWI, mwi_event_cb, peer,
21278 AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox->mailbox,
21279 AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, S_OR(mailbox->context, "default"),
21280 AST_EVENT_IE_END);
21281 }
21282 }
21283
21284
21285 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e)
21286 {
21287 int gotdest = 0;
21288 int res = 0;
21289 int firststate = AST_EXTENSION_REMOVED;
21290 struct sip_peer *authpeer = NULL;
21291 const char *eventheader = get_header(req, "Event");
21292 const char *acceptheader = get_header(req, "Accept");
21293 int resubscribe = (p->subscribed != NONE);
21294 char *temp, *event;
21295 struct ao2_iterator i;
21296
21297 if (p->initreq.headers) {
21298
21299 if (p->initreq.method != SIP_SUBSCRIBE) {
21300
21301
21302 transmit_response(p, "403 Forbidden (within dialog)", req);
21303
21304 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);
21305 return 0;
21306 } else if (req->debug) {
21307 if (resubscribe)
21308 ast_debug(1, "Got a re-subscribe on existing subscription %s\n", p->callid);
21309 else
21310 ast_debug(1, "Got a new subscription %s (possibly with auth)\n", p->callid);
21311 }
21312 }
21313
21314
21315
21316
21317 if (!sip_cfg.allowsubscribe) {
21318 transmit_response(p, "403 Forbidden (policy)", req);
21319 pvt_set_needdestroy(p, "forbidden");
21320 return 0;
21321 }
21322
21323 if (!req->ignore && !resubscribe) {
21324 const char *to = get_header(req, "To");
21325 char totag[128];
21326
21327
21328 if (!ast_strlen_zero(to) && gettag(req, "To", totag, sizeof(totag))) {
21329 if (req->debug)
21330 ast_verbose("Received resubscription for a dialog we no longer know about. Telling remote side to subscribe again.\n");
21331 transmit_response(p, "481 Subscription does not exist", req);
21332 pvt_set_needdestroy(p, "subscription does not exist");
21333 return 0;
21334 }
21335
21336
21337 if (req->debug)
21338 ast_verbose("Creating new subscription\n");
21339
21340 copy_request(&p->initreq, req);
21341 if (sipdebug)
21342 ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
21343 check_via(p, req);
21344 build_route(p, req, 0);
21345 } else if (req->debug && req->ignore)
21346 ast_verbose("Ignoring this SUBSCRIBE request\n");
21347
21348
21349 if (ast_strlen_zero(eventheader)) {
21350 transmit_response(p, "489 Bad Event", req);
21351 ast_debug(2, "Received SIP subscribe for unknown event package: <none>\n");
21352 pvt_set_needdestroy(p, "unknown event package in subscribe");
21353 return 0;
21354 }
21355
21356 if ( (strchr(eventheader, ';'))) {
21357 event = ast_strdupa(eventheader);
21358 temp = strchr(event, ';');
21359 *temp = '\0';
21360
21361 } else
21362 event = (char *) eventheader;
21363
21364
21365 res = check_user_full(p, req, SIP_SUBSCRIBE, e, 0, sin, &authpeer);
21366
21367 if (res == AUTH_CHALLENGE_SENT)
21368 return 0;
21369 if (res < 0) {
21370 if (res == AUTH_FAKE_AUTH) {
21371 ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", get_header(req, "From"));
21372 transmit_fake_auth_response(p, SIP_SUBSCRIBE, req, XMIT_UNRELIABLE);
21373 } else {
21374 ast_log(LOG_NOTICE, "Failed to authenticate device %s for SUBSCRIBE\n", get_header(req, "From"));
21375 transmit_response_reliable(p, "403 Forbidden", req);
21376 }
21377 pvt_set_needdestroy(p, "authentication failed");
21378 return 0;
21379 }
21380
21381
21382
21383
21384
21385
21386
21387 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
21388 transmit_response(p, "403 Forbidden (policy)", req);
21389 pvt_set_needdestroy(p, "subscription not allowed");
21390 if (authpeer)
21391 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 1)");
21392 return 0;
21393 }
21394
21395 if (strcmp(event, "message-summary")) {
21396
21397 gotdest = get_destination(p, NULL);
21398 }
21399
21400
21401 parse_ok_contact(p, req);
21402
21403 build_contact(p);
21404 if (gotdest) {
21405 transmit_response(p, "404 Not Found", req);
21406 pvt_set_needdestroy(p, "subscription target not found");
21407 if (authpeer)
21408 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
21409 return 0;
21410 }
21411
21412
21413 if (ast_strlen_zero(p->tag))
21414 make_our_tag(p->tag, sizeof(p->tag));
21415
21416 if (!strcmp(event, "presence") || !strcmp(event, "dialog")) {
21417 unsigned int pidf_xml;
21418
21419 if (authpeer)
21420 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
21421
21422
21423
21424 pidf_xml = strstr(acceptheader, "application/pidf+xml") ? 1 : 0;
21425
21426
21427
21428 if (pidf_xml && strstr(p->useragent, "Polycom")) {
21429 p->subscribed = XPIDF_XML;
21430 } else if (pidf_xml) {
21431 p->subscribed = PIDF_XML;
21432 } else if (strstr(acceptheader, "application/dialog-info+xml")) {
21433 p->subscribed = DIALOG_INFO_XML;
21434
21435 } else if (strstr(acceptheader, "application/cpim-pidf+xml")) {
21436 p->subscribed = CPIM_PIDF_XML;
21437 } else if (strstr(acceptheader, "application/xpidf+xml")) {
21438 p->subscribed = XPIDF_XML;
21439 } else if (ast_strlen_zero(acceptheader)) {
21440 if (p->subscribed == NONE) {
21441 transmit_response(p, "489 Bad Event", req);
21442
21443 ast_log(LOG_WARNING, "SUBSCRIBE failure: no Accept header: pvt: stateid: %d, laststate: %d, dialogver: %d, subscribecont: '%s', subscribeuri: '%s'\n",
21444 p->stateid, p->laststate, p->dialogver, p->subscribecontext, p->subscribeuri);
21445 pvt_set_needdestroy(p, "no Accept header");
21446 return 0;
21447 }
21448
21449
21450 } else {
21451
21452 char mybuf[200];
21453 snprintf(mybuf, sizeof(mybuf), "489 Bad Event (format %s)", acceptheader);
21454 transmit_response(p, mybuf, req);
21455
21456 ast_log(LOG_WARNING, "SUBSCRIBE failure: unrecognized format: '%s' pvt: subscribed: %d, stateid: %d, laststate: %d, dialogver: %d, subscribecont: '%s', subscribeuri: '%s'\n",
21457 acceptheader, (int)p->subscribed, p->stateid, p->laststate, p->dialogver, p->subscribecontext, p->subscribeuri);
21458 pvt_set_needdestroy(p, "unrecognized format");
21459 return 0;
21460 }
21461 } else if (!strcmp(event, "message-summary")) {
21462 if (!ast_strlen_zero(acceptheader) && strcmp(acceptheader, "application/simple-message-summary")) {
21463
21464 transmit_response(p, "406 Not Acceptable", req);
21465 ast_debug(2, "Received SIP mailbox subscription for unknown format: %s\n", acceptheader);
21466 pvt_set_needdestroy(p, "unknown format");
21467 if (authpeer)
21468 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 3)");
21469 return 0;
21470 }
21471
21472
21473
21474
21475
21476 if (!authpeer || AST_LIST_EMPTY(&authpeer->mailboxes)) {
21477 transmit_response(p, "404 Not found (no mailbox)", req);
21478 pvt_set_needdestroy(p, "received 404 response");
21479 ast_log(LOG_NOTICE, "Received SIP subscribe for peer without mailbox: %s\n", authpeer->name);
21480 if (authpeer)
21481 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 4)");
21482 return 0;
21483 }
21484
21485 p->subscribed = MWI_NOTIFICATION;
21486 if (ast_test_flag(&authpeer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY)) {
21487 add_peer_mwi_subs(authpeer);
21488 }
21489 if (authpeer->mwipvt && authpeer->mwipvt != p) {
21490
21491 dialog_unlink_all(authpeer->mwipvt, TRUE, TRUE);
21492 authpeer->mwipvt = dialog_unref(authpeer->mwipvt, "unref dialog authpeer->mwipvt");
21493
21494 }
21495 if (authpeer->mwipvt)
21496 dialog_unref(authpeer->mwipvt, "Unref previously stored mwipvt dialog pointer");
21497 authpeer->mwipvt = dialog_ref(p, "setting peers' mwipvt to p");
21498 if (p->relatedpeer)
21499 unref_peer(p->relatedpeer, "Unref previously stored relatedpeer ptr");
21500 p->relatedpeer = ref_peer(authpeer, "setting dialog's relatedpeer pointer");
21501
21502 } else {
21503 transmit_response(p, "489 Bad Event", req);
21504 ast_debug(2, "Received SIP subscribe for unknown event package: %s\n", event);
21505 pvt_set_needdestroy(p, "unknown event package");
21506 if (authpeer)
21507 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 5)");
21508 return 0;
21509 }
21510
21511
21512 if (p->subscribed != MWI_NOTIFICATION && !resubscribe) {
21513 if (p->stateid > -1) {
21514 ast_extension_state_del(p->stateid, cb_extensionstate);
21515
21516 dialog_unref(p, "the extensionstate containing this dialog ptr was deleted");
21517 }
21518 p->stateid = ast_extension_state_add(p->context, p->exten, cb_extensionstate, dialog_ref(p,"copying dialog ptr into extension state struct"));
21519 }
21520
21521 if (!req->ignore && p)
21522 p->lastinvite = seqno;
21523 if (p && !p->needdestroy) {
21524 p->expiry = atoi(get_header(req, "Expires"));
21525
21526
21527 if (p->expiry > max_expiry)
21528 p->expiry = max_expiry;
21529 if (p->expiry < min_expiry && p->expiry > 0)
21530 p->expiry = min_expiry;
21531
21532 if (sipdebug) {
21533 if (p->subscribed == MWI_NOTIFICATION && p->relatedpeer)
21534 ast_debug(2, "Adding subscription for mailbox notification - peer %s\n", p->relatedpeer->name);
21535 else
21536 ast_debug(2, "Adding subscription for extension %s context %s for peer %s\n", p->exten, p->context, p->username);
21537 }
21538 if (p->autokillid > -1 && sip_cancel_destroy(p))
21539 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
21540 if (p->expiry > 0)
21541 sip_scheddestroy(p, (p->expiry + 10) * 1000);
21542
21543 if (p->subscribed == MWI_NOTIFICATION) {
21544 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
21545 transmit_response(p, "200 OK", req);
21546 if (p->relatedpeer) {
21547 ao2_lock(p->relatedpeer);
21548 sip_send_mwi_to_peer(p->relatedpeer, NULL, 0);
21549 ao2_unlock(p->relatedpeer);
21550 }
21551 } else {
21552 struct sip_pvt *p_old;
21553
21554 if ((firststate = ast_extension_state(NULL, p->context, p->exten)) < 0) {
21555
21556 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));
21557 transmit_response(p, "404 Not found", req);
21558 pvt_set_needdestroy(p, "no extension for SUBSCRIBE");
21559 return 0;
21560 }
21561 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
21562 transmit_response(p, "200 OK", req);
21563 transmit_state_notify(p, firststate, 1, FALSE);
21564 append_history(p, "Subscribestatus", "%s", ast_extension_state2str(firststate));
21565
21566 ast_string_field_build(p, subscribeuri, "%s@%s", p->exten, p->context);
21567
21568
21569
21570
21571
21572
21573 i = ao2_iterator_init(dialogs, 0);
21574 while ((p_old = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
21575 if (p_old == p) {
21576 ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next before continue");
21577 continue;
21578 }
21579 if (p_old->initreq.method != SIP_SUBSCRIBE) {
21580 ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next before continue");
21581 continue;
21582 }
21583 if (p_old->subscribed == NONE) {
21584 ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next before continue");
21585 continue;
21586 }
21587 sip_pvt_lock(p_old);
21588 if (!strcmp(p_old->username, p->username)) {
21589 if (!strcmp(p_old->exten, p->exten) &&
21590 !strcmp(p_old->context, p->context)) {
21591 pvt_set_needdestroy(p_old, "replacing subscription");
21592 sip_pvt_unlock(p_old);
21593 ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next before break");
21594 break;
21595 }
21596 }
21597 sip_pvt_unlock(p_old);
21598 ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next");
21599 }
21600 ao2_iterator_destroy(&i);
21601 }
21602 if (!p->expiry) {
21603 pvt_set_needdestroy(p, "forcing expiration");
21604 }
21605 }
21606 return 1;
21607 }
21608
21609
21610 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e)
21611 {
21612 enum check_auth_result res;
21613
21614
21615 copy_request(&p->initreq, req);
21616 if (sipdebug)
21617 ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
21618 check_via(p, req);
21619 if ((res = register_verify(p, sin, req, e)) < 0) {
21620 const char *reason;
21621
21622 switch (res) {
21623 case AUTH_SECRET_FAILED:
21624 reason = "Wrong password";
21625 break;
21626 case AUTH_USERNAME_MISMATCH:
21627 reason = "Username/auth name mismatch";
21628 break;
21629 case AUTH_NOT_FOUND:
21630 reason = "No matching peer found";
21631 break;
21632 case AUTH_UNKNOWN_DOMAIN:
21633 reason = "Not a local domain";
21634 break;
21635 case AUTH_PEER_NOT_DYNAMIC:
21636 reason = "Peer is not supposed to register";
21637 break;
21638 case AUTH_ACL_FAILED:
21639 reason = "Device does not match ACL";
21640 break;
21641 case AUTH_BAD_TRANSPORT:
21642 reason = "Device not configured to use this transport type";
21643 break;
21644 default:
21645 reason = "Unknown failure";
21646 break;
21647 }
21648 ast_log(LOG_NOTICE, "Registration from '%s' failed for '%s' - %s\n",
21649 get_header(req, "To"), ast_inet_ntoa(sin->sin_addr),
21650 reason);
21651 append_history(p, "RegRequest", "Failed : Account %s : %s", get_header(req, "To"), reason);
21652 } else
21653 append_history(p, "RegRequest", "Succeeded : Account %s", get_header(req, "To"));
21654
21655 if (res < 1) {
21656
21657
21658 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21659 }
21660 return res;
21661 }
21662
21663
21664
21665
21666 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock)
21667 {
21668
21669
21670 const char *cmd;
21671 const char *cseq;
21672 const char *useragent;
21673 int seqno;
21674 int len;
21675 int respid;
21676 int res = 0;
21677 int debug = sip_debug_test_pvt(p);
21678 char *e;
21679 int error = 0;
21680 int oldmethod = p->method;
21681 int acked = 0;
21682
21683
21684 cseq = get_header(req, "Cseq");
21685 cmd = REQ_OFFSET_TO_STR(req, header[0]);
21686
21687
21688 if (ast_strlen_zero(cmd) || ast_strlen_zero(cseq)) {
21689 ast_log(LOG_ERROR, "Missing Cseq. Dropping this SIP message, it's incomplete.\n");
21690 error = 1;
21691 }
21692 if (!error && sscanf(cseq, "%30d%n", &seqno, &len) != 1) {
21693 ast_log(LOG_ERROR, "No seqno in '%s'. Dropping incomplete message.\n", cmd);
21694 error = 1;
21695 }
21696 if (error) {
21697 if (!p->initreq.headers) {
21698 pvt_set_needdestroy(p, "no headers");
21699 }
21700 return -1;
21701 }
21702
21703
21704 cmd = REQ_OFFSET_TO_STR(req, rlPart1);
21705 e = ast_skip_blanks(REQ_OFFSET_TO_STR(req, rlPart2));
21706
21707
21708 useragent = get_header(req, "User-Agent");
21709 if (!ast_strlen_zero(useragent))
21710 ast_string_field_set(p, useragent, useragent);
21711
21712
21713 if (req->method == SIP_RESPONSE) {
21714
21715
21716
21717
21718
21719
21720 if (ast_strlen_zero(e)) {
21721 return 0;
21722 }
21723 if (sscanf(e, "%30d %n", &respid, &len) != 1) {
21724 ast_log(LOG_WARNING, "Invalid response: '%s'\n", e);
21725 return 0;
21726 }
21727 if (respid <= 0) {
21728 ast_log(LOG_WARNING, "Invalid SIP response code: '%d'\n", respid);
21729 return 0;
21730 }
21731 if (p->ocseq && (p->ocseq < seqno)) {
21732 if (option_debug)
21733 ast_log(LOG_DEBUG, "Ignoring out of order response %d (expecting %d)\n", seqno, p->ocseq);
21734 return -1;
21735 } else {
21736 if ((respid == 200) || ((respid >= 300) && (respid <= 399))) {
21737 extract_uri(p, req);
21738 }
21739 handle_response(p, respid, e + len, req, seqno);
21740 }
21741 return 0;
21742 }
21743
21744
21745
21746
21747
21748 p->method = req->method;
21749 ast_debug(4, "**** Received %s (%d) - Command in SIP %s\n", sip_methods[p->method].text, sip_methods[p->method].id, cmd);
21750
21751 if (p->icseq && (p->icseq > seqno) ) {
21752 if (p->pendinginvite && seqno == p->pendinginvite && (req->method == SIP_ACK || req->method == SIP_CANCEL)) {
21753 ast_debug(2, "Got CANCEL or ACK on INVITE with transactions in between.\n");
21754 } else {
21755 ast_debug(1, "Ignoring too old SIP packet packet %d (expecting >= %d)\n", seqno, p->icseq);
21756 if (req->method != SIP_ACK)
21757 transmit_response(p, "503 Server error", req);
21758 return -1;
21759 }
21760 } else if (p->icseq &&
21761 p->icseq == seqno &&
21762 req->method != SIP_ACK &&
21763 (p->method != SIP_CANCEL || p->alreadygone)) {
21764
21765
21766
21767 req->ignore = 1;
21768 ast_debug(3, "Ignoring SIP message because of retransmit (%s Seqno %d, ours %d)\n", sip_methods[p->method].text, p->icseq, seqno);
21769 }
21770
21771 if (seqno >= p->icseq)
21772
21773
21774
21775 p->icseq = seqno;
21776
21777
21778 if (ast_strlen_zero(p->theirtag)) {
21779 char tag[128];
21780
21781 gettag(req, "From", tag, sizeof(tag));
21782 ast_string_field_set(p, theirtag, tag);
21783 }
21784 snprintf(p->lastmsg, sizeof(p->lastmsg), "Rx: %s", cmd);
21785
21786 if (sip_cfg.pedanticsipchecking) {
21787
21788
21789
21790
21791 if (!p->initreq.headers && req->has_to_tag) {
21792
21793 if (!req->ignore && req->method == SIP_INVITE) {
21794 transmit_response_reliable(p, "481 Call/Transaction Does Not Exist", req);
21795
21796 } else if (req->method != SIP_ACK) {
21797 transmit_response(p, "481 Call/Transaction Does Not Exist", req);
21798 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21799 } else {
21800 ast_debug(1, "Got ACK for unknown dialog... strange.\n");
21801 }
21802 return res;
21803 }
21804 }
21805
21806 if (!e && (p->method == SIP_INVITE || p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER || p->method == SIP_NOTIFY)) {
21807 transmit_response(p, "400 Bad request", req);
21808 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21809 return -1;
21810 }
21811
21812
21813 switch (p->method) {
21814 case SIP_OPTIONS:
21815 res = handle_request_options(p, req);
21816 break;
21817 case SIP_INVITE:
21818 res = handle_request_invite(p, req, debug, seqno, sin, recount, e, nounlock);
21819 break;
21820 case SIP_REFER:
21821 res = handle_request_refer(p, req, debug, seqno, nounlock);
21822 break;
21823 case SIP_CANCEL:
21824 res = handle_request_cancel(p, req);
21825 break;
21826 case SIP_BYE:
21827 res = handle_request_bye(p, req);
21828 break;
21829 case SIP_MESSAGE:
21830 res = handle_request_message(p, req);
21831 break;
21832 case SIP_SUBSCRIBE:
21833 res = handle_request_subscribe(p, req, sin, seqno, e);
21834 break;
21835 case SIP_REGISTER:
21836 res = handle_request_register(p, req, sin, e);
21837 break;
21838 case SIP_INFO:
21839 if (req->debug)
21840 ast_verbose("Receiving INFO!\n");
21841 if (!req->ignore)
21842 handle_request_info(p, req);
21843 else
21844 transmit_response(p, "200 OK", req);
21845 break;
21846 case SIP_NOTIFY:
21847 res = handle_request_notify(p, req, sin, seqno, e);
21848 break;
21849 case SIP_ACK:
21850
21851 if (seqno == p->pendinginvite) {
21852 p->invitestate = INV_TERMINATED;
21853 p->pendinginvite = 0;
21854 acked = __sip_ack(p, seqno, 1 , 0);
21855 if (find_sdp(req)) {
21856 if (process_sdp(p, req, SDP_T38_NONE))
21857 return -1;
21858 }
21859 check_pendings(p);
21860 } else if (p->glareinvite == seqno) {
21861
21862 p->glareinvite = 0;
21863 acked = __sip_ack(p, seqno, 1, 0);
21864 }
21865 if (!acked) {
21866
21867
21868 p->method = oldmethod;
21869 }
21870 if (!p->lastinvite && ast_strlen_zero(p->randdata)) {
21871 pvt_set_needdestroy(p, "unmatched ACK");
21872 }
21873 break;
21874 default:
21875 transmit_response_with_allow(p, "501 Method Not Implemented", req, 0);
21876 ast_log(LOG_NOTICE, "Unknown SIP command '%s' from '%s'\n",
21877 cmd, ast_inet_ntoa(p->sa.sin_addr));
21878
21879 if (!p->initreq.headers) {
21880 pvt_set_needdestroy(p, "unimplemented method");
21881 }
21882 break;
21883 }
21884 return res;
21885 }
21886
21887 static void process_request_queue(struct sip_pvt *p, int *recount, int *nounlock)
21888 {
21889 struct sip_request *req;
21890
21891 while ((req = AST_LIST_REMOVE_HEAD(&p->request_queue, next))) {
21892 if (handle_incoming(p, req, &p->recv, recount, nounlock) == -1) {
21893
21894 if (option_debug) {
21895 ast_log(LOG_DEBUG, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
21896 }
21897 }
21898 ast_free(req);
21899 }
21900 }
21901
21902 static int scheduler_process_request_queue(const void *data)
21903 {
21904 struct sip_pvt *p = (struct sip_pvt *) data;
21905 int recount = 0;
21906 int nounlock = 0;
21907 int lockretry;
21908
21909 for (lockretry = 10; lockretry > 0; lockretry--) {
21910 sip_pvt_lock(p);
21911
21912
21913
21914 if (!p->owner || !ast_channel_trylock(p->owner)) {
21915 break;
21916 }
21917
21918 if (lockretry != 1) {
21919 sip_pvt_unlock(p);
21920
21921 usleep(1);
21922 }
21923 }
21924
21925 if (!lockretry) {
21926 int retry = !AST_LIST_EMPTY(&p->request_queue);
21927
21928
21929
21930
21931
21932
21933 sip_pvt_unlock(p);
21934 if (!retry) {
21935 dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
21936 }
21937 return retry;
21938 };
21939
21940 process_request_queue(p, &recount, &nounlock);
21941 p->request_queue_sched_id = -1;
21942
21943 if (p->owner && !nounlock) {
21944 ast_channel_unlock(p->owner);
21945 }
21946 sip_pvt_unlock(p);
21947
21948 if (recount) {
21949 ast_update_use_count();
21950 }
21951
21952 dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
21953
21954 return 0;
21955 }
21956
21957 static int queue_request(struct sip_pvt *p, const struct sip_request *req)
21958 {
21959 struct sip_request *newreq;
21960
21961 if (!(newreq = ast_calloc(1, sizeof(*newreq)))) {
21962 return -1;
21963 }
21964
21965 copy_request(newreq, req);
21966 AST_LIST_INSERT_TAIL(&p->request_queue, newreq, next);
21967 if (p->request_queue_sched_id == -1) {
21968 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) {
21969 dialog_unref(p, "Decrement refcount due to sched_add failure");
21970 }
21971 }
21972
21973 return 0;
21974 }
21975
21976
21977
21978
21979
21980
21981 static int sipsock_read(int *id, int fd, short events, void *ignore)
21982 {
21983 struct sip_request req;
21984 struct sockaddr_in sin = { 0, };
21985 int res;
21986 socklen_t len = sizeof(sin);
21987 static char readbuf[65535];
21988
21989 memset(&req, 0, sizeof(req));
21990 res = recvfrom(fd, readbuf, sizeof(readbuf) - 1, 0, (struct sockaddr *)&sin, &len);
21991 if (res < 0) {
21992 #if !defined(__FreeBSD__)
21993 if (errno == EAGAIN)
21994 ast_log(LOG_NOTICE, "SIP: Received packet with bad UDP checksum\n");
21995 else
21996 #endif
21997 if (errno != ECONNREFUSED)
21998 ast_log(LOG_WARNING, "Recv error: %s\n", strerror(errno));
21999 return 1;
22000 }
22001
22002 readbuf[res] = '\0';
22003
22004 if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
22005 return 1;
22006 }
22007
22008 if (ast_str_set(&req.data, 0, "%s", readbuf) == AST_DYNSTR_BUILD_FAILED) {
22009 return -1;
22010 }
22011
22012 req.len = res;
22013 req.socket.fd = sipsock;
22014 set_socket_transport(&req.socket, SIP_TRANSPORT_UDP);
22015 req.socket.tcptls_session = NULL;
22016 req.socket.port = bindaddr.sin_port;
22017
22018 handle_request_do(&req, &sin);
22019 deinit_req(&req);
22020
22021 return 1;
22022 }
22023
22024
22025
22026
22027
22028 static int handle_request_do(struct sip_request *req, struct sockaddr_in *sin)
22029 {
22030 struct sip_pvt *p;
22031 int recount = 0;
22032 int nounlock = 0;
22033 int lockretry;
22034
22035 if (sip_debug_test_addr(sin))
22036 req->debug = 1;
22037 if (sip_cfg.pedanticsipchecking)
22038 req->len = lws2sws(req->data->str, req->len);
22039 if (req->debug) {
22040 ast_verbose("\n<--- SIP read from %s:%s:%d --->\n%s\n<------------->\n",
22041 get_transport(req->socket.type), ast_inet_ntoa(sin->sin_addr),
22042 ntohs(sin->sin_port), req->data->str);
22043 }
22044
22045 if (parse_request(req) == -1) {
22046 ast_str_reset(req->data);
22047 return 1;
22048 }
22049 req->method = find_sip_method(REQ_OFFSET_TO_STR(req, rlPart1));
22050
22051 if (req->debug)
22052 ast_verbose("--- (%d headers %d lines)%s ---\n", req->headers, req->lines, (req->headers + req->lines == 0) ? " Nat keepalive" : "");
22053
22054 if (req->headers < 2) {
22055 ast_str_reset(req->data);
22056 return 1;
22057 }
22058
22059
22060 for (lockretry = 10; lockretry > 0; lockretry--) {
22061 ast_mutex_lock(&netlock);
22062
22063
22064 p = find_call(req, sin, req->method);
22065 if (p == NULL) {
22066 ast_debug(1, "Invalid SIP message - rejected , no callid, len %d\n", req->len);
22067 ast_mutex_unlock(&netlock);
22068 return 1;
22069 }
22070
22071 copy_socket_data(&p->socket, &req->socket);
22072
22073
22074
22075 if (!p->owner || !ast_channel_trylock(p->owner))
22076 break;
22077
22078 if (lockretry != 1) {
22079 sip_pvt_unlock(p);
22080 ao2_t_ref(p, -1, "release p (from find_call) inside lockretry loop");
22081 ast_mutex_unlock(&netlock);
22082
22083 usleep(1);
22084 }
22085 }
22086 p->recv = *sin;
22087
22088 if (p->do_history)
22089 append_history(p, "Rx", "%s / %s / %s", req->data->str, get_header(req, "CSeq"), REQ_OFFSET_TO_STR(req, rlPart2));
22090
22091 if (!lockretry) {
22092 if (!queue_request(p, req)) {
22093
22094 sip_pvt_unlock(p);
22095 ao2_t_ref(p, -1, "release p (from find_call) after queueing request");
22096 ast_mutex_unlock(&netlock);
22097 return 1;
22098 }
22099
22100 if (p->owner)
22101 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 ??? - "));
22102 ast_log(LOG_ERROR, "SIP transaction failed: %s \n", p->callid);
22103 if (req->method != SIP_ACK)
22104 transmit_response(p, "503 Server error", req);
22105
22106 append_history(p, "LockFail", "Owner lock failed, transaction failed.");
22107 sip_pvt_unlock(p);
22108 ao2_t_ref(p, -1, "release p (from find_call) at end of lockretry");
22109 ast_mutex_unlock(&netlock);
22110 return 1;
22111 }
22112
22113
22114
22115
22116 if (!AST_LIST_EMPTY(&p->request_queue)) {
22117 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"));
22118 process_request_queue(p, &recount, &nounlock);
22119 }
22120
22121 if (handle_incoming(p, req, sin, &recount, &nounlock) == -1) {
22122
22123 ast_debug(1, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
22124 }
22125
22126 if (recount)
22127 ast_update_use_count();
22128
22129 if (p->owner && !nounlock)
22130 ast_channel_unlock(p->owner);
22131 sip_pvt_unlock(p);
22132 ast_mutex_unlock(&netlock);
22133 ao2_t_ref(p, -1, "throw away dialog ptr from find_call at end of routine");
22134 return 1;
22135 }
22136
22137
22138
22139
22140
22141
22142
22143 static int sip_standard_port(enum sip_transport type, int port)
22144 {
22145 if (type & SIP_TRANSPORT_TLS)
22146 return port == STANDARD_TLS_PORT;
22147 else
22148 return port == STANDARD_SIP_PORT;
22149 }
22150
22151 static int threadinfo_locate_cb(void *obj, void *arg, int flags)
22152 {
22153 struct sip_threadinfo *th = obj;
22154 struct sockaddr_in *s = arg;
22155
22156 if (!inaddrcmp(&th->tcptls_session->remote_address, s)) {
22157 return CMP_MATCH | CMP_STOP;
22158 }
22159
22160 return 0;
22161 }
22162
22163
22164
22165
22166
22167
22168 static struct ast_tcptls_session_instance *sip_tcp_locate(struct sockaddr_in *s)
22169 {
22170 struct sip_threadinfo *th;
22171 struct ast_tcptls_session_instance *tcptls_instance = NULL;
22172
22173 if ((th = ao2_callback(threadt, 0, threadinfo_locate_cb, s))) {
22174 tcptls_instance = (ao2_ref(th->tcptls_session, +1), th->tcptls_session);
22175 ao2_t_ref(th, -1, "decrement ref from callback");
22176 }
22177 return tcptls_instance;
22178 }
22179
22180
22181 static int sip_prepare_socket(struct sip_pvt *p)
22182 {
22183 struct sip_socket *s = &p->socket;
22184 static const char name[] = "SIP socket";
22185 struct sip_threadinfo *th = NULL;
22186 struct ast_tcptls_session_instance *tcptls_session;
22187 struct ast_tcptls_session_args tmp_ca = {
22188 .name = name,
22189 .accept_fd = -1,
22190 };
22191 struct ast_tcptls_session_args *ca;
22192
22193
22194 if ((s->fd != -1) && (s->type == SIP_TRANSPORT_UDP)) {
22195 return s->fd;
22196 }
22197 if ((s->type & (SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS)) &&
22198 (s->tcptls_session) &&
22199 (s->tcptls_session->fd != -1)) {
22200 return s->tcptls_session->fd;
22201 }
22202
22203
22204
22205
22206 if (p->outboundproxy && p->outboundproxy->transport) {
22207 s->type = p->outboundproxy->transport;
22208 }
22209
22210 if (s->type == SIP_TRANSPORT_UDP) {
22211 s->fd = sipsock;
22212 return s->fd;
22213 }
22214
22215
22216
22217
22218
22219
22220
22221
22222
22223
22224
22225 tmp_ca.remote_address = *(sip_real_dst(p));
22226 if ((tcptls_session = sip_tcp_locate(&tmp_ca.remote_address))) {
22227 s->fd = tcptls_session->fd;
22228 if (s->tcptls_session) {
22229 ao2_ref(s->tcptls_session, -1);
22230 s->tcptls_session = NULL;
22231 }
22232 s->tcptls_session = tcptls_session;
22233 return s->fd;
22234
22235 } else if (s->tcptls_session) {
22236 return s->fd;
22237 }
22238
22239
22240
22241 if (!(ca = ao2_alloc(sizeof(*ca), sip_tcptls_client_args_destructor)) ||
22242 !(ca->name = ast_strdup(name))) {
22243 goto create_tcptls_session_fail;
22244 }
22245 ca->accept_fd = -1;
22246 ca->remote_address = *(sip_real_dst(p));
22247
22248 if (s->type == SIP_TRANSPORT_TLS) {
22249 if (!(ca->tls_cfg = ast_calloc(1, sizeof(*ca->tls_cfg)))) {
22250 goto create_tcptls_session_fail;
22251 }
22252 memcpy(ca->tls_cfg, &default_tls_cfg, sizeof(*ca->tls_cfg));
22253
22254 if (!(ca->tls_cfg->certfile = ast_strdup(default_tls_cfg.certfile)) ||
22255 !(ca->tls_cfg->cipher = ast_strdup(default_tls_cfg.cipher)) ||
22256 !(ca->tls_cfg->cafile = ast_strdup(default_tls_cfg.cafile)) ||
22257 !(ca->tls_cfg->capath = ast_strdup(default_tls_cfg.capath))) {
22258
22259 goto create_tcptls_session_fail;
22260 }
22261
22262
22263 if (!ast_strlen_zero(p->tohost)) {
22264 ast_copy_string(ca->hostname, p->tohost, sizeof(ca->hostname));
22265 }
22266 }
22267
22268 if (!(s->tcptls_session = ast_tcptls_client_create(ca))) {
22269 goto create_tcptls_session_fail;
22270 }
22271
22272 s->fd = s->tcptls_session->fd;
22273
22274
22275
22276
22277
22278 if (!(th = sip_threadinfo_create(s->tcptls_session, s->type))) {
22279 goto create_tcptls_session_fail;
22280
22281 }
22282
22283
22284 ao2_ref(s->tcptls_session, +1);
22285
22286 if (ast_pthread_create_background(&ca->master, NULL, sip_tcp_worker_fn, s->tcptls_session)) {
22287 ast_debug(1, "Unable to launch '%s'.", ca->name);
22288 ao2_ref(s->tcptls_session, -1);
22289 goto create_tcptls_session_fail;
22290 }
22291
22292 return s->fd;
22293
22294 create_tcptls_session_fail:
22295 if (ca) {
22296 ao2_t_ref(ca, -1, "failed to create client, getting rid of client tcptls_session arguments");
22297 }
22298 if (s->tcptls_session) {
22299 close(tcptls_session->fd);
22300 s->fd = tcptls_session->fd = -1;
22301 ao2_ref(s->tcptls_session, -1);
22302 s->tcptls_session = NULL;
22303 }
22304 if (th) {
22305 ao2_t_unlink(threadt, th, "Removing tcptls thread info object, thread failed to open");
22306 }
22307
22308 return -1;
22309 }
22310
22311
22312
22313
22314
22315 static int sip_parse_host(char *line, int lineno, char **hostname, int *portnum, enum sip_transport *transport)
22316 {
22317 char *port;
22318
22319 if ((*hostname = strstr(line, "://"))) {
22320 *hostname += 3;
22321
22322 if (!strncasecmp(line, "tcp", 3))
22323 *transport = SIP_TRANSPORT_TCP;
22324 else if (!strncasecmp(line, "tls", 3))
22325 *transport = SIP_TRANSPORT_TLS;
22326 else if (!strncasecmp(line, "udp", 3))
22327 *transport = SIP_TRANSPORT_UDP;
22328 else
22329 ast_log(LOG_NOTICE, "'%.3s' is not a valid transport type on line %d of sip.conf. defaulting to udp.\n", line, lineno);
22330 } else {
22331 *hostname = line;
22332 *transport = SIP_TRANSPORT_UDP;
22333 }
22334
22335 if ((line = strrchr(*hostname, '@')))
22336 line++;
22337 else
22338 line = *hostname;
22339
22340 if ((port = strrchr(line, ':'))) {
22341 *port++ = '\0';
22342
22343 if (!sscanf(port, "%5u", portnum)) {
22344 ast_log(LOG_NOTICE, "'%s' is not a valid port number on line %d of sip.conf. using default.\n", port, lineno);
22345 port = NULL;
22346 }
22347 }
22348
22349 if (!port) {
22350 if (*transport & SIP_TRANSPORT_TLS) {
22351 *portnum = STANDARD_TLS_PORT;
22352 } else {
22353 *portnum = STANDARD_SIP_PORT;
22354 }
22355 }
22356
22357 return 0;
22358 }
22359
22360
22361
22362
22363
22364
22365 static int get_cached_mwi(struct sip_peer *peer, int *new, int *old)
22366 {
22367 struct sip_mailbox *mailbox;
22368
22369 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
22370 struct ast_event *event;
22371 event = ast_event_get_cached(AST_EVENT_MWI,
22372 AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox->mailbox,
22373 AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, S_OR(mailbox->context, "default"),
22374 AST_EVENT_IE_END);
22375 if (!event)
22376 continue;
22377 *new += ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
22378 *old += ast_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS);
22379 ast_event_destroy(event);
22380 }
22381
22382 return (*new || *old) ? 0 : 1;
22383 }
22384
22385
22386 static int sip_send_mwi_to_peer(struct sip_peer *peer, const struct ast_event *event, int cache_only)
22387 {
22388
22389 struct sip_pvt *p;
22390 int newmsgs = 0, oldmsgs = 0;
22391
22392 if (ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY) && !peer->mwipvt)
22393 return 0;
22394
22395
22396 if (!peer->addr.sin_addr.s_addr && !peer->defaddr.sin_addr.s_addr)
22397 return 0;
22398
22399 if (event) {
22400 newmsgs = ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
22401 oldmsgs = ast_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS);
22402 } else if (!cache_only) {
22403 struct ast_str *mailbox_str = ast_str_alloca(512);
22404 peer_mailboxes_to_str(&mailbox_str, peer);
22405 ast_app_inboxcount(mailbox_str->str, &newmsgs, &oldmsgs);
22406 } else {
22407 get_cached_mwi(peer, &newmsgs, &oldmsgs);
22408 }
22409
22410 if (peer->mwipvt) {
22411
22412 p = dialog_ref(peer->mwipvt, "sip_send_mwi_to_peer: Setting dialog ptr p from peer->mwipvt-- should this be done?");
22413 } else {
22414
22415 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL)))
22416 return -1;
22417
22418
22419
22420
22421 set_socket_transport(&p->socket, 0);
22422 if (create_addr_from_peer(p, peer)) {
22423
22424 dialog_unlink_all(p, TRUE, TRUE);
22425 dialog_unref(p, "unref dialog p just created via sip_alloc");
22426
22427 return 0;
22428 }
22429
22430 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
22431 build_via(p);
22432 ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
22433 build_callid_pvt(p);
22434 ao2_t_link(dialogs, p, "Linking in under new name");
22435
22436 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22437 }
22438
22439
22440 ast_set_flag(&p->flags[0], SIP_OUTGOING);
22441
22442 transmit_notify_with_mwi(p, newmsgs, oldmsgs, peer->vmexten);
22443 dialog_unref(p, "unref dialog ptr p just before it goes out of scope at the end of sip_send_mwi_to_peer.");
22444 return 0;
22445 }
22446
22447
22448 static void check_rtp_timeout(struct sip_pvt *dialog, time_t t)
22449 {
22450
22451 if (!dialog->rtp || !dialog->owner)
22452 return;
22453
22454
22455 if (dialog->owner->_state != AST_STATE_UP || dialog->redirip.sin_addr.s_addr)
22456 return;
22457
22458
22459 if (dialog->t38.state == T38_ENABLED)
22460 return;
22461
22462
22463 if ((ast_rtp_get_rtpkeepalive(dialog->rtp) == 0) && (ast_rtp_get_rtptimeout(dialog->rtp) == 0) && (ast_rtp_get_rtpholdtimeout(dialog->rtp) == 0))
22464 return;
22465
22466
22467 if (dialog->lastrtptx && ast_rtp_get_rtpkeepalive(dialog->rtp) &&
22468 (t > dialog->lastrtptx + ast_rtp_get_rtpkeepalive(dialog->rtp))) {
22469
22470 dialog->lastrtptx = time(NULL);
22471 ast_rtp_sendcng(dialog->rtp, 0);
22472 }
22473
22474
22475
22476
22477
22478
22479
22480
22481 if (dialog->lastrtprx && (ast_rtp_get_rtptimeout(dialog->rtp) || ast_rtp_get_rtpholdtimeout(dialog->rtp)) &&
22482 (t > dialog->lastrtprx + ast_rtp_get_rtptimeout(dialog->rtp))) {
22483
22484
22485 struct sockaddr_in sin;
22486 ast_rtp_get_peer(dialog->rtp, &sin);
22487 if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD) || (ast_rtp_get_rtpholdtimeout(dialog->rtp) &&
22488 (t > dialog->lastrtprx + ast_rtp_get_rtpholdtimeout(dialog->rtp)))) {
22489
22490 if (ast_rtp_get_rtptimeout(dialog->rtp)) {
22491 while (dialog->owner && ast_channel_trylock(dialog->owner)) {
22492 sip_pvt_unlock(dialog);
22493 usleep(1);
22494 sip_pvt_lock(dialog);
22495 }
22496 if (!dialog->owner) {
22497 return;
22498 }
22499 ast_log(LOG_NOTICE, "Disconnecting call '%s' for lack of RTP activity in %ld seconds\n",
22500 dialog->owner->name, (long) (t - dialog->lastrtprx));
22501
22502 ast_softhangup_nolock(dialog->owner, AST_SOFTHANGUP_DEV);
22503 ast_channel_unlock(dialog->owner);
22504
22505
22506
22507
22508 ast_rtp_set_rtptimeout(dialog->rtp, 0);
22509 ast_rtp_set_rtpholdtimeout(dialog->rtp, 0);
22510 if (dialog->vrtp) {
22511 ast_rtp_set_rtptimeout(dialog->vrtp, 0);
22512 ast_rtp_set_rtpholdtimeout(dialog->vrtp, 0);
22513 }
22514 }
22515 }
22516 }
22517 }
22518
22519
22520
22521
22522
22523 static void *do_monitor(void *data)
22524 {
22525 int res;
22526 time_t t;
22527 int reloading;
22528
22529
22530 if (sipsock > -1)
22531 sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
22532
22533
22534 for(;;) {
22535
22536 ast_mutex_lock(&sip_reload_lock);
22537 reloading = sip_reloading;
22538 sip_reloading = FALSE;
22539 ast_mutex_unlock(&sip_reload_lock);
22540 if (reloading) {
22541 ast_verb(1, "Reloading SIP\n");
22542 sip_do_reload(sip_reloadreason);
22543
22544
22545 if (sipsock > -1) {
22546 if (sipsock_read_id)
22547 sipsock_read_id = ast_io_change(io, sipsock_read_id, sipsock, NULL, 0, NULL);
22548 else
22549 sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
22550 } else if (sipsock_read_id) {
22551 ast_io_remove(io, sipsock_read_id);
22552 sipsock_read_id = NULL;
22553 }
22554 }
22555
22556
22557 t = time(NULL);
22558
22559
22560
22561
22562 ao2_t_callback(dialogs, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, dialog_needdestroy, &t,
22563 "callback to remove dialogs w/needdestroy");
22564
22565
22566
22567
22568
22569
22570
22571
22572
22573
22574
22575 pthread_testcancel();
22576
22577 res = ast_sched_wait(sched);
22578 if ((res < 0) || (res > 1000))
22579 res = 1000;
22580 res = ast_io_wait(io, res);
22581 if (res > 20)
22582 ast_debug(1, "chan_sip: ast_io_wait ran %d all at once\n", res);
22583 ast_mutex_lock(&monlock);
22584 res = ast_sched_runq(sched);
22585 if (res >= 20)
22586 ast_debug(1, "chan_sip: ast_sched_runq ran %d all at once\n", res);
22587 ast_mutex_unlock(&monlock);
22588 }
22589
22590
22591 return NULL;
22592 }
22593
22594
22595 static int restart_monitor(void)
22596 {
22597
22598 if (monitor_thread == AST_PTHREADT_STOP)
22599 return 0;
22600 ast_mutex_lock(&monlock);
22601 if (monitor_thread == pthread_self()) {
22602 ast_mutex_unlock(&monlock);
22603 ast_log(LOG_WARNING, "Cannot kill myself\n");
22604 return -1;
22605 }
22606 if (monitor_thread != AST_PTHREADT_NULL) {
22607
22608 pthread_kill(monitor_thread, SIGURG);
22609 } else {
22610
22611 if (ast_pthread_create_background(&monitor_thread, NULL, do_monitor, NULL) < 0) {
22612 ast_mutex_unlock(&monlock);
22613 ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
22614 return -1;
22615 }
22616 }
22617 ast_mutex_unlock(&monlock);
22618 return 0;
22619 }
22620
22621
22622
22623 static void restart_session_timer(struct sip_pvt *p)
22624 {
22625 if (!p->stimer) {
22626 ast_log(LOG_WARNING, "Null stimer in restart_session_timer - %s\n", p->callid);
22627 return;
22628 }
22629
22630 if (p->stimer->st_active == TRUE) {
22631 AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
22632 dialog_unref(p, "Removing session timer ref"));
22633 ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
22634 start_session_timer(p);
22635 }
22636 }
22637
22638
22639
22640 static void stop_session_timer(struct sip_pvt *p)
22641 {
22642 if (!p->stimer) {
22643 ast_log(LOG_WARNING, "Null stimer in stop_session_timer - %s\n", p->callid);
22644 return;
22645 }
22646
22647 if (p->stimer->st_active == TRUE) {
22648 p->stimer->st_active = FALSE;
22649 AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
22650 dialog_unref(p, "removing session timer ref"));
22651 ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
22652 }
22653 }
22654
22655
22656
22657 static void start_session_timer(struct sip_pvt *p)
22658 {
22659 if (!p->stimer) {
22660 ast_log(LOG_WARNING, "Null stimer in start_session_timer - %s\n", p->callid);
22661 return;
22662 }
22663
22664 p->stimer->st_schedid = ast_sched_add(sched, p->stimer->st_interval * 1000 / 2, proc_session_timer,
22665 dialog_ref(p, "adding session timer ref"));
22666 if (p->stimer->st_schedid < 0) {
22667 dialog_unref(p, "removing session timer ref");
22668 ast_log(LOG_ERROR, "ast_sched_add failed.\n");
22669 }
22670 ast_debug(2, "Session timer started: %d - %s\n", p->stimer->st_schedid, p->callid);
22671 }
22672
22673
22674
22675 static int proc_session_timer(const void *vp)
22676 {
22677 struct sip_pvt *p = (struct sip_pvt *) vp;
22678 int sendreinv = FALSE;
22679 int res = 0;
22680
22681 if (!p->stimer) {
22682 ast_log(LOG_WARNING, "Null stimer in proc_session_timer - %s\n", p->callid);
22683 goto return_unref;
22684 }
22685
22686 ast_debug(2, "Session timer expired: %d - %s\n", p->stimer->st_schedid, p->callid);
22687
22688 if (!p->owner) {
22689 goto return_unref;
22690 }
22691
22692 if ((p->stimer->st_active != TRUE) || (p->owner->_state != AST_STATE_UP)) {
22693 goto return_unref;
22694 }
22695
22696 switch (p->stimer->st_ref) {
22697 case SESSION_TIMER_REFRESHER_UAC:
22698 if (p->outgoing_call == TRUE) {
22699 sendreinv = TRUE;
22700 }
22701 break;
22702 case SESSION_TIMER_REFRESHER_UAS:
22703 if (p->outgoing_call != TRUE) {
22704 sendreinv = TRUE;
22705 }
22706 break;
22707 default:
22708 ast_log(LOG_ERROR, "Unknown session refresher %d\n", p->stimer->st_ref);
22709 goto return_unref;
22710 }
22711
22712 if (sendreinv == TRUE) {
22713 res = 1;
22714 transmit_reinvite_with_sdp(p, FALSE, TRUE);
22715 } else {
22716 p->stimer->st_expirys++;
22717 if (p->stimer->st_expirys >= 2) {
22718 if (p->stimer->quit_flag) {
22719 goto return_unref;
22720 }
22721 ast_log(LOG_WARNING, "Session-Timer expired - %s\n", p->callid);
22722 sip_pvt_lock(p);
22723 while (p->owner && ast_channel_trylock(p->owner)) {
22724 sip_pvt_unlock(p);
22725 usleep(1);
22726 if (p->stimer && p->stimer->quit_flag) {
22727 goto return_unref;
22728 }
22729 sip_pvt_lock(p);
22730 }
22731
22732 ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
22733 ast_channel_unlock(p->owner);
22734 sip_pvt_unlock(p);
22735 }
22736 }
22737
22738 return_unref:
22739 if (!res) {
22740
22741 if (p->stimer) {
22742 p->stimer->st_schedid = -1;
22743 stop_session_timer(p);
22744 }
22745
22746
22747
22748 dialog_unref(p, "removing session timer ref");
22749 }
22750
22751 return res;
22752 }
22753
22754
22755
22756 int parse_minse (const char *p_hdrval, int *const p_interval)
22757 {
22758 if (ast_strlen_zero(p_hdrval)) {
22759 ast_log(LOG_WARNING, "Null Min-SE header\n");
22760 return -1;
22761 }
22762
22763 *p_interval = 0;
22764 p_hdrval = ast_skip_blanks(p_hdrval);
22765 if (!sscanf(p_hdrval, "%30d", p_interval)) {
22766 ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
22767 return -1;
22768 }
22769
22770 ast_debug(2, "Received Min-SE: %d\n", *p_interval);
22771 return 0;
22772 }
22773
22774
22775
22776 int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref)
22777 {
22778 char *p_token;
22779 int ref_idx;
22780 char *p_se_hdr;
22781
22782 if (ast_strlen_zero(p_hdrval)) {
22783 ast_log(LOG_WARNING, "Null Session-Expires header\n");
22784 return -1;
22785 }
22786
22787 *p_ref = SESSION_TIMER_REFRESHER_AUTO;
22788 *p_interval = 0;
22789
22790 p_se_hdr = ast_strdupa(p_hdrval);
22791 p_se_hdr = ast_skip_blanks(p_se_hdr);
22792
22793 while ((p_token = strsep(&p_se_hdr, ";"))) {
22794 p_token = ast_skip_blanks(p_token);
22795 if (!sscanf(p_token, "%30d", p_interval)) {
22796 ast_log(LOG_WARNING, "Parsing of Session-Expires failed\n");
22797 return -1;
22798 }
22799
22800 ast_debug(2, "Session-Expires: %d\n", *p_interval);
22801
22802 if (!p_se_hdr)
22803 continue;
22804
22805 p_se_hdr = ast_skip_blanks(p_se_hdr);
22806 ref_idx = strlen("refresher=");
22807 if (!strncasecmp(p_se_hdr, "refresher=", ref_idx)) {
22808 p_se_hdr += ref_idx;
22809 p_se_hdr = ast_skip_blanks(p_se_hdr);
22810
22811 if (!strncasecmp(p_se_hdr, "uac", strlen("uac"))) {
22812 *p_ref = SESSION_TIMER_REFRESHER_UAC;
22813 ast_debug(2, "Refresher: UAC\n");
22814 } else if (!strncasecmp(p_se_hdr, "uas", strlen("uas"))) {
22815 *p_ref = SESSION_TIMER_REFRESHER_UAS;
22816 ast_debug(2, "Refresher: UAS\n");
22817 } else {
22818 ast_log(LOG_WARNING, "Invalid refresher value %s\n", p_se_hdr);
22819 return -1;
22820 }
22821 break;
22822 }
22823 }
22824 return 0;
22825 }
22826
22827
22828
22829
22830
22831
22832
22833
22834
22835 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp)
22836 {
22837 int rtn;
22838 const char *p_hdrval;
22839 int minse;
22840
22841 p_hdrval = get_header(rsp, "Min-SE");
22842 if (ast_strlen_zero(p_hdrval)) {
22843 ast_log(LOG_WARNING, "422 response without a Min-SE header %s\n", p_hdrval);
22844 return;
22845 }
22846 rtn = parse_minse(p_hdrval, &minse);
22847 if (rtn != 0) {
22848 ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
22849 return;
22850 }
22851 p->stimer->st_interval = minse;
22852 transmit_invite(p, SIP_INVITE, 1, 2);
22853 }
22854
22855
22856
22857
22858
22859
22860 int st_get_se(struct sip_pvt *p, int max)
22861 {
22862 if (max == TRUE) {
22863 if (p->stimer->st_cached_max_se) {
22864 return p->stimer->st_cached_max_se;
22865 } else if (p->peername) {
22866 struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE, 0);
22867 if (pp) {
22868 p->stimer->st_cached_max_se = pp->stimer.st_max_se;
22869 unref_peer(pp, "unref peer pointer from find_peer call in st_get_se");
22870 return (p->stimer->st_cached_max_se);
22871 }
22872 }
22873 p->stimer->st_cached_max_se = global_max_se;
22874 return (p->stimer->st_cached_max_se);
22875 } else {
22876 if (p->stimer->st_cached_min_se) {
22877 return p->stimer->st_cached_min_se;
22878 } else if (p->peername) {
22879 struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE, 0);
22880 if (pp) {
22881 p->stimer->st_cached_min_se = pp->stimer.st_min_se;
22882 unref_peer(pp, "unref peer pointer from find_peer call in st_get_se (2)");
22883 return (p->stimer->st_cached_min_se);
22884 }
22885 }
22886 p->stimer->st_cached_min_se = global_min_se;
22887 return (p->stimer->st_cached_min_se);
22888 }
22889 }
22890
22891
22892
22893
22894
22895 enum st_refresher st_get_refresher(struct sip_pvt *p)
22896 {
22897 if (p->stimer->st_cached_ref != SESSION_TIMER_REFRESHER_AUTO)
22898 return p->stimer->st_cached_ref;
22899
22900 if (p->peername) {
22901 struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE, 0);
22902 if (pp) {
22903 p->stimer->st_cached_ref = pp->stimer.st_ref;
22904 unref_peer(pp, "unref peer pointer from find_peer call in st_get_refresher");
22905 return pp->stimer.st_ref;
22906 }
22907 }
22908
22909 p->stimer->st_cached_ref = global_st_refresher;
22910 return global_st_refresher;
22911 }
22912
22913
22914
22915
22916
22917 enum st_mode st_get_mode(struct sip_pvt *p)
22918 {
22919 if (!p->stimer)
22920 sip_st_alloc(p);
22921
22922 if (p->stimer->st_cached_mode != SESSION_TIMER_MODE_INVALID)
22923 return p->stimer->st_cached_mode;
22924
22925 if (p->peername) {
22926 struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE, 0);
22927 if (pp) {
22928 p->stimer->st_cached_mode = pp->stimer.st_mode_oper;
22929 unref_peer(pp, "unref peer pointer from find_peer call in st_get_mode");
22930 return pp->stimer.st_mode_oper;
22931 }
22932 }
22933
22934 p->stimer->st_cached_mode = global_st_mode;
22935 return global_st_mode;
22936 }
22937
22938
22939
22940 static int sip_poke_noanswer(const void *data)
22941 {
22942 struct sip_peer *peer = (struct sip_peer *)data;
22943
22944 peer->pokeexpire = -1;
22945
22946 if (peer->lastms > -1) {
22947 ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE! Last qualify: %d\n", peer->name, peer->lastms);
22948 if (sip_cfg.peer_rtupdate) {
22949 ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", "-1", SENTINEL);
22950 }
22951 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer->name, -1);
22952 if (sip_cfg.regextenonqualify) {
22953 register_peer_exten(peer, FALSE);
22954 }
22955 }
22956
22957 if (peer->call) {
22958 dialog_unlink_all(peer->call, TRUE, TRUE);
22959 peer->call = dialog_unref(peer->call, "unref dialog peer->call");
22960
22961 }
22962
22963 peer->lastms = -1;
22964 ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
22965
22966
22967 AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
22968 DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer,
22969 unref_peer(_data, "removing poke peer ref"),
22970 unref_peer(peer, "removing poke peer ref"),
22971 ref_peer(peer, "adding poke peer ref"));
22972
22973
22974 unref_peer(peer, "release peer poke noanswer ref");
22975
22976 return 0;
22977 }
22978
22979
22980
22981
22982
22983
22984 static int sip_poke_peer(struct sip_peer *peer, int force)
22985 {
22986 struct sip_pvt *p;
22987 int xmitres = 0;
22988
22989 if ((!peer->maxms && !force) || !peer->addr.sin_addr.s_addr) {
22990
22991
22992 AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
22993 unref_peer(peer, "removing poke peer ref"));
22994
22995 peer->lastms = 0;
22996 if (peer->call) {
22997 peer->call = dialog_unref(peer->call, "unref dialog peer->call");
22998 }
22999 return 0;
23000 }
23001 if (peer->call) {
23002 if (sipdebug) {
23003 ast_log(LOG_NOTICE, "Still have a QUALIFY dialog active, deleting\n");
23004 }
23005 dialog_unlink_all(peer->call, TRUE, TRUE);
23006 peer->call = dialog_unref(peer->call, "unref dialog peer->call");
23007
23008 }
23009 if (!(p = sip_alloc(NULL, NULL, 0, SIP_OPTIONS, NULL))) {
23010 return -1;
23011 }
23012 peer->call = dialog_ref(p, "copy sip alloc from p to peer->call");
23013
23014 p->sa = peer->addr;
23015 p->recv = peer->addr;
23016 copy_socket_data(&p->socket, &peer->socket);
23017 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
23018 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
23019
23020
23021 if (!ast_strlen_zero(peer->fullcontact))
23022 ast_string_field_set(p, fullcontact, peer->fullcontact);
23023
23024 if (!ast_strlen_zero(peer->tohost))
23025 ast_string_field_set(p, tohost, peer->tohost);
23026 else
23027 ast_string_field_set(p, tohost, ast_inet_ntoa(peer->addr.sin_addr));
23028
23029
23030 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
23031 build_via(p);
23032 ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
23033 build_callid_pvt(p);
23034 ao2_t_link(dialogs, p, "Linking in under new name");
23035
23036 AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
23037 unref_peer(peer, "removing poke peer ref"));
23038
23039 if (p->relatedpeer)
23040 p->relatedpeer = unref_peer(p->relatedpeer,"unsetting the relatedpeer field in the dialog, before it is set to something else.");
23041 p->relatedpeer = ref_peer(peer, "setting the relatedpeer field in the dialog");
23042 ast_set_flag(&p->flags[0], SIP_OUTGOING);
23043 #ifdef VOCAL_DATA_HACK
23044 ast_copy_string(p->username, "__VOCAL_DATA_SHOULD_READ_THE_SIP_SPEC__", sizeof(p->username));
23045 xmitres = transmit_invite(p, SIP_INVITE, 0, 2);
23046 #else
23047 xmitres = transmit_invite(p, SIP_OPTIONS, 0, 2);
23048 #endif
23049 peer->ps = ast_tvnow();
23050 if (xmitres == XMIT_ERROR) {
23051 sip_poke_noanswer(peer);
23052 } else if (!force) {
23053 AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, peer->maxms * 2, sip_poke_noanswer, peer,
23054 unref_peer(_data, "removing poke peer ref"),
23055 unref_peer(peer, "removing poke peer ref"),
23056 ref_peer(peer, "adding poke peer ref"));
23057 }
23058 dialog_unref(p, "unref dialog at end of sip_poke_peer, obtained from sip_alloc, just before it goes out of scope");
23059 return 0;
23060 }
23061
23062
23063
23064
23065
23066
23067
23068
23069
23070
23071
23072
23073
23074
23075
23076
23077
23078
23079
23080
23081
23082
23083
23084
23085
23086
23087
23088
23089
23090
23091
23092
23093
23094
23095 static int sip_devicestate(void *data)
23096 {
23097 char *host;
23098 char *tmp;
23099 struct sip_peer *p;
23100
23101 int res = AST_DEVICE_INVALID;
23102
23103
23104 host = ast_strdupa(data ? data : "");
23105 if ((tmp = strchr(host, '@')))
23106 host = tmp + 1;
23107
23108 ast_debug(3, "Checking device state for peer %s\n", host);
23109
23110
23111
23112
23113
23114
23115
23116
23117 if ((p = find_peer(host, NULL, FALSE, FINDALLDEVICES, TRUE, 0))) {
23118 if (p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) {
23119
23120
23121
23122
23123
23124
23125
23126
23127
23128
23129
23130 if (p->onHold)
23131
23132 res = AST_DEVICE_ONHOLD;
23133 else if (p->inRinging) {
23134 if (p->inRinging == p->inUse)
23135 res = AST_DEVICE_RINGING;
23136 else
23137 res = AST_DEVICE_RINGINUSE;
23138 } else if (p->call_limit && (p->inUse == p->call_limit))
23139
23140 res = AST_DEVICE_BUSY;
23141 else if (p->call_limit && p->busy_level && p->inUse >= p->busy_level)
23142
23143 res = AST_DEVICE_BUSY;
23144 else if (p->call_limit && p->inUse)
23145
23146 res = AST_DEVICE_INUSE;
23147 else if (p->maxms && ((p->lastms > p->maxms) || (p->lastms < 0)))
23148
23149 res = AST_DEVICE_UNAVAILABLE;
23150 else
23151 res = AST_DEVICE_NOT_INUSE;
23152 } else {
23153
23154 res = AST_DEVICE_UNAVAILABLE;
23155 }
23156 unref_peer(p, "unref_peer, from sip_devicestate, release ref from find_peer");
23157 } else {
23158 res = AST_DEVICE_UNKNOWN;
23159 }
23160
23161 return res;
23162 }
23163
23164
23165
23166
23167
23168
23169
23170
23171
23172
23173
23174 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause)
23175 {
23176 struct sip_pvt *p;
23177 struct ast_channel *tmpc = NULL;
23178 char *ext = NULL, *host;
23179 char tmp[256];
23180 char *dest = data;
23181 char *dnid;
23182 char *secret = NULL;
23183 char *md5secret = NULL;
23184 char *authname = NULL;
23185 char *trans = NULL;
23186 enum sip_transport transport = 0;
23187 int oldformat = format;
23188
23189
23190
23191
23192
23193
23194
23195
23196 format &= AST_FORMAT_AUDIO_MASK;
23197 if (!format) {
23198 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));
23199 *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
23200 return NULL;
23201 }
23202 ast_debug(1, "Asked to create a SIP channel with formats: %s\n", ast_getformatname_multiple(tmp, sizeof(tmp), oldformat));
23203
23204 if (!(p = sip_alloc(NULL, NULL, 0, SIP_INVITE, NULL))) {
23205 ast_log(LOG_ERROR, "Unable to build sip pvt data for '%s' (Out of memory or socket error)\n", dest);
23206 *cause = AST_CAUSE_SWITCH_CONGESTION;
23207 return NULL;
23208 }
23209
23210 p->outgoing_call = TRUE;
23211
23212 if (!(p->options = ast_calloc(1, sizeof(*p->options)))) {
23213 dialog_unlink_all(p, TRUE, TRUE);
23214 dialog_unref(p, "unref dialog p from mem fail");
23215
23216 ast_log(LOG_ERROR, "Unable to build option SIP data structure - Out of memory\n");
23217 *cause = AST_CAUSE_SWITCH_CONGESTION;
23218 return NULL;
23219 }
23220
23221
23222 ast_copy_string(tmp, dest, sizeof(tmp));
23223
23224
23225
23226 dnid = strchr(tmp, '!');
23227 if (dnid != NULL) {
23228 *dnid++ = '\0';
23229 ast_string_field_set(p, todnid, dnid);
23230 }
23231
23232
23233 host = strchr(tmp, '@');
23234 if (host) {
23235 *host++ = '\0';
23236 ext = tmp;
23237 secret = strchr(ext, ':');
23238 }
23239 if (secret) {
23240 *secret++ = '\0';
23241 md5secret = strchr(secret, ':');
23242 }
23243 if (md5secret) {
23244 *md5secret++ = '\0';
23245 authname = strchr(md5secret, ':');
23246 }
23247 if (authname) {
23248 *authname++ = '\0';
23249 trans = strchr(authname, ':');
23250 }
23251 if (trans) {
23252 *trans++ = '\0';
23253 if (!strcasecmp(trans, "tcp"))
23254 transport = SIP_TRANSPORT_TCP;
23255 else if (!strcasecmp(trans, "tls"))
23256 transport = SIP_TRANSPORT_TLS;
23257 else {
23258 if (strcasecmp(trans, "udp"))
23259 ast_log(LOG_WARNING, "'%s' is not a valid transport option to Dial() for SIP calls, using udp by default.\n", trans);
23260 transport = SIP_TRANSPORT_UDP;
23261 }
23262 } else {
23263 transport = SIP_TRANSPORT_UDP;
23264 }
23265
23266 if (!host) {
23267 ext = strchr(tmp, '/');
23268 if (ext)
23269 *ext++ = '\0';
23270 host = tmp;
23271 }
23272
23273 set_socket_transport(&p->socket, transport);
23274
23275
23276
23277
23278
23279
23280 if (create_addr(p, host, NULL, 1)) {
23281 *cause = AST_CAUSE_UNREGISTERED;
23282 ast_debug(3, "Cant create SIP call - target device not registered\n");
23283 dialog_unlink_all(p, TRUE, TRUE);
23284 dialog_unref(p, "unref dialog p UNREGISTERED");
23285
23286 return NULL;
23287 }
23288 if (ast_strlen_zero(p->peername) && ext)
23289 ast_string_field_set(p, peername, ext);
23290
23291 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
23292 build_via(p);
23293 ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
23294 build_callid_pvt(p);
23295 ao2_t_link(dialogs, p, "Linking in under new name");
23296
23297
23298
23299
23300
23301
23302 if (ext) {
23303 ast_string_field_set(p, username, ext);
23304 ast_string_field_set(p, fullcontact, NULL);
23305 }
23306 if (secret && !ast_strlen_zero(secret))
23307 ast_string_field_set(p, peersecret, secret);
23308
23309 if (md5secret && !ast_strlen_zero(md5secret))
23310 ast_string_field_set(p, peermd5secret, md5secret);
23311
23312 if (authname && !ast_strlen_zero(authname))
23313 ast_string_field_set(p, authname, authname);
23314 #if 0
23315 printf("Setting up to call extension '%s' at '%s'\n", ext ? ext : "<none>", host);
23316 #endif
23317 p->prefcodec = oldformat;
23318 p->jointcapability = oldformat & p->capability;
23319 sip_pvt_lock(p);
23320 tmpc = sip_new(p, AST_STATE_DOWN, host);
23321 if (sip_cfg.callevents)
23322 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
23323 "Channel: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
23324 p->owner? p->owner->name : "", "SIP", p->callid, p->fullcontact, p->peername);
23325 sip_pvt_unlock(p);
23326 if (!tmpc) {
23327 dialog_unlink_all(p, TRUE, TRUE);
23328
23329 }
23330 dialog_unref(p, "toss pvt ptr at end of sip_request_call");
23331 ast_update_use_count();
23332 restart_monitor();
23333 return tmpc;
23334 }
23335
23336
23337 static void set_insecure_flags (struct ast_flags *flags, const char *value, int lineno)
23338 {
23339 if (ast_strlen_zero(value))
23340 return;
23341
23342 if (!ast_false(value)) {
23343 char buf[64];
23344 char *word, *next;
23345
23346 ast_copy_string(buf, value, sizeof(buf));
23347 next = buf;
23348 while ((word = strsep(&next, ","))) {
23349 if (!strcasecmp(word, "port"))
23350 ast_set_flag(&flags[0], SIP_INSECURE_PORT);
23351 else if (!strcasecmp(word, "invite"))
23352 ast_set_flag(&flags[0], SIP_INSECURE_INVITE);
23353 else
23354 ast_log(LOG_WARNING, "Unknown insecure mode '%s' on line %d\n", value, lineno);
23355 }
23356 }
23357 }
23358
23359
23360
23361
23362
23363 static int handle_t38_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v,
23364 int *maxdatagram)
23365 {
23366 int res = 1;
23367
23368 if (!strcasecmp(v->name, "t38pt_udptl")) {
23369 char *buf = ast_strdupa(v->value);
23370 char *word, *next = buf;
23371
23372 ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT);
23373
23374 while ((word = strsep(&next, ","))) {
23375 if (ast_true(word) || !strcasecmp(word, "fec")) {
23376 ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
23377 ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_FEC);
23378 } else if (!strcasecmp(word, "redundancy")) {
23379 ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
23380 ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY);
23381 } else if (!strcasecmp(word, "none")) {
23382 ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
23383 ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL);
23384 } else if (!strncasecmp(word, "maxdatagram=", 12)) {
23385 if (sscanf(&word[12], "%30u", maxdatagram) != 1) {
23386 ast_log(LOG_WARNING, "Invalid maxdatagram '%s' at line %d of %s\n", v->value, v->lineno, config);
23387 *maxdatagram = global_t38_maxdatagram;
23388 }
23389 }
23390 }
23391 } else if (!strcasecmp(v->name, "t38pt_usertpsource")) {
23392 ast_set_flag(&mask[1], SIP_PAGE2_UDPTL_DESTINATION);
23393 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_UDPTL_DESTINATION);
23394 } else if (!strcasecmp(v->name, "forwardloopdetected")) {
23395 ast_set_flag(&mask[1], SIP_PAGE2_FORWARD_LOOP_DETECTED);
23396 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_FORWARD_LOOP_DETECTED);
23397 } else {
23398 res = 0;
23399 }
23400
23401 return res;
23402 }
23403
23404
23405
23406
23407
23408
23409
23410
23411 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v)
23412 {
23413 int res = 1;
23414
23415 if (!strcasecmp(v->name, "trustrpid")) {
23416 ast_set_flag(&mask[0], SIP_TRUSTRPID);
23417 ast_set2_flag(&flags[0], ast_true(v->value), SIP_TRUSTRPID);
23418 } else if (!strcasecmp(v->name, "sendrpid")) {
23419 ast_set_flag(&mask[0], SIP_SENDRPID);
23420 ast_set2_flag(&flags[0], ast_true(v->value), SIP_SENDRPID);
23421 } else if (!strcasecmp(v->name, "g726nonstandard")) {
23422 ast_set_flag(&mask[0], SIP_G726_NONSTANDARD);
23423 ast_set2_flag(&flags[0], ast_true(v->value), SIP_G726_NONSTANDARD);
23424 } else if (!strcasecmp(v->name, "useclientcode")) {
23425 ast_set_flag(&mask[0], SIP_USECLIENTCODE);
23426 ast_set2_flag(&flags[0], ast_true(v->value), SIP_USECLIENTCODE);
23427 } else if (!strcasecmp(v->name, "dtmfmode")) {
23428 ast_set_flag(&mask[0], SIP_DTMF);
23429 ast_clear_flag(&flags[0], SIP_DTMF);
23430 if (!strcasecmp(v->value, "inband"))
23431 ast_set_flag(&flags[0], SIP_DTMF_INBAND);
23432 else if (!strcasecmp(v->value, "rfc2833"))
23433 ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
23434 else if (!strcasecmp(v->value, "info"))
23435 ast_set_flag(&flags[0], SIP_DTMF_INFO);
23436 else if (!strcasecmp(v->value, "shortinfo"))
23437 ast_set_flag(&flags[0], SIP_DTMF_SHORTINFO);
23438 else if (!strcasecmp(v->value, "auto"))
23439 ast_set_flag(&flags[0], SIP_DTMF_AUTO);
23440 else {
23441 ast_log(LOG_WARNING, "Unknown dtmf mode '%s' on line %d, using rfc2833\n", v->value, v->lineno);
23442 ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
23443 }
23444 } else if (!strcasecmp(v->name, "nat")) {
23445 ast_set_flag(&mask[0], SIP_NAT);
23446 ast_clear_flag(&flags[0], SIP_NAT);
23447 if (!strcasecmp(v->value, "never"))
23448 ast_set_flag(&flags[0], SIP_NAT_NEVER);
23449 else if (!strcasecmp(v->value, "route"))
23450 ast_set_flag(&flags[0], SIP_NAT_ROUTE);
23451 else if (ast_true(v->value))
23452 ast_set_flag(&flags[0], SIP_NAT_ALWAYS);
23453 else
23454 ast_set_flag(&flags[0], SIP_NAT_RFC3581);
23455 } else if (!strcasecmp(v->name, "directmedia") || !strcasecmp(v->name, "canreinvite")) {
23456 ast_set_flag(&mask[0], SIP_REINVITE);
23457 ast_clear_flag(&flags[0], SIP_REINVITE);
23458 if (ast_true(v->value)) {
23459 ast_set_flag(&flags[0], SIP_DIRECT_MEDIA | SIP_DIRECT_MEDIA_NAT);
23460 } else if (!ast_false(v->value)) {
23461 char buf[64];
23462 char *word, *next = buf;
23463
23464 ast_copy_string(buf, v->value, sizeof(buf));
23465 while ((word = strsep(&next, ","))) {
23466 if (!strcasecmp(word, "update")) {
23467 ast_set_flag(&flags[0], SIP_REINVITE_UPDATE | SIP_DIRECT_MEDIA);
23468 } else if (!strcasecmp(word, "nonat")) {
23469 ast_set_flag(&flags[0], SIP_DIRECT_MEDIA);
23470 ast_clear_flag(&flags[0], SIP_DIRECT_MEDIA_NAT);
23471 } else {
23472 ast_log(LOG_WARNING, "Unknown directmedia mode '%s' on line %d\n", v->value, v->lineno);
23473 }
23474 }
23475 }
23476 } else if (!strcasecmp(v->name, "insecure")) {
23477 ast_set_flag(&mask[0], SIP_INSECURE);
23478 ast_clear_flag(&flags[0], SIP_INSECURE);
23479 set_insecure_flags(&flags[0], v->value, v->lineno);
23480 } else if (!strcasecmp(v->name, "progressinband")) {
23481 ast_set_flag(&mask[0], SIP_PROG_INBAND);
23482 ast_clear_flag(&flags[0], SIP_PROG_INBAND);
23483 if (ast_true(v->value))
23484 ast_set_flag(&flags[0], SIP_PROG_INBAND_YES);
23485 else if (strcasecmp(v->value, "never"))
23486 ast_set_flag(&flags[0], SIP_PROG_INBAND_NO);
23487 } else if (!strcasecmp(v->name, "promiscredir")) {
23488 ast_set_flag(&mask[0], SIP_PROMISCREDIR);
23489 ast_set2_flag(&flags[0], ast_true(v->value), SIP_PROMISCREDIR);
23490 } else if (!strcasecmp(v->name, "videosupport")) {
23491 if (!strcasecmp(v->value, "always")) {
23492 ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
23493 ast_set_flag(&flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
23494 } else {
23495 ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT);
23496 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_VIDEOSUPPORT);
23497 }
23498 } else if (!strcasecmp(v->name, "textsupport")) {
23499 ast_set_flag(&mask[1], SIP_PAGE2_TEXTSUPPORT);
23500 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_TEXTSUPPORT);
23501 res = 1;
23502 } else if (!strcasecmp(v->name, "allowoverlap")) {
23503 ast_set_flag(&mask[1], SIP_PAGE2_ALLOWOVERLAP);
23504 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWOVERLAP);
23505 } else if (!strcasecmp(v->name, "allowsubscribe")) {
23506 ast_set_flag(&mask[1], SIP_PAGE2_ALLOWSUBSCRIBE);
23507 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWSUBSCRIBE);
23508 } else if (!strcasecmp(v->name, "ignoresdpversion")) {
23509 ast_set_flag(&mask[1], SIP_PAGE2_IGNORESDPVERSION);
23510 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_IGNORESDPVERSION);
23511 } else if (!strcasecmp(v->name, "faxdetect")) {
23512 ast_set_flag(&mask[1], SIP_PAGE2_FAX_DETECT);
23513 if (ast_true(v->value)) {
23514 ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_BOTH);
23515 } else if (ast_false(v->value)) {
23516 ast_clear_flag(&flags[1], SIP_PAGE2_FAX_DETECT_BOTH);
23517 } else {
23518 char *buf = ast_strdupa(v->value);
23519 char *word, *next = buf;
23520
23521 while ((word = strsep(&next, ","))) {
23522 if (!strcasecmp(word, "cng")) {
23523 ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_CNG);
23524 } else if (!strcasecmp(word, "t38")) {
23525 ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_T38);
23526 } else {
23527 ast_log(LOG_WARNING, "Unknown faxdetect mode '%s' on line %d.\n", word, v->lineno);
23528 }
23529 }
23530 }
23531 } else if (!strcasecmp(v->name, "rfc2833compensate")) {
23532 ast_set_flag(&mask[1], SIP_PAGE2_RFC2833_COMPENSATE);
23533 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RFC2833_COMPENSATE);
23534 } else if (!strcasecmp(v->name, "buggymwi")) {
23535 ast_set_flag(&mask[1], SIP_PAGE2_BUGGY_MWI);
23536 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_BUGGY_MWI);
23537 } else
23538 res = 0;
23539
23540 return res;
23541 }
23542
23543
23544 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context)
23545 {
23546 struct domain *d;
23547
23548 if (ast_strlen_zero(domain)) {
23549 ast_log(LOG_WARNING, "Zero length domain.\n");
23550 return 1;
23551 }
23552
23553 if (!(d = ast_calloc(1, sizeof(*d))))
23554 return 0;
23555
23556 ast_copy_string(d->domain, domain, sizeof(d->domain));
23557
23558 if (!ast_strlen_zero(context))
23559 ast_copy_string(d->context, context, sizeof(d->context));
23560
23561 d->mode = mode;
23562
23563 AST_LIST_LOCK(&domain_list);
23564 AST_LIST_INSERT_TAIL(&domain_list, d, list);
23565 AST_LIST_UNLOCK(&domain_list);
23566
23567 if (sipdebug)
23568 ast_debug(1, "Added local SIP domain '%s'\n", domain);
23569
23570 return 1;
23571 }
23572
23573
23574 static int check_sip_domain(const char *domain, char *context, size_t len)
23575 {
23576 struct domain *d;
23577 int result = 0;
23578
23579 AST_LIST_LOCK(&domain_list);
23580 AST_LIST_TRAVERSE(&domain_list, d, list) {
23581 if (strcasecmp(d->domain, domain))
23582 continue;
23583
23584 if (len && !ast_strlen_zero(d->context))
23585 ast_copy_string(context, d->context, len);
23586
23587 result = 1;
23588 break;
23589 }
23590 AST_LIST_UNLOCK(&domain_list);
23591
23592 return result;
23593 }
23594
23595
23596 static void clear_sip_domains(void)
23597 {
23598 struct domain *d;
23599
23600 AST_LIST_LOCK(&domain_list);
23601 while ((d = AST_LIST_REMOVE_HEAD(&domain_list, list)))
23602 ast_free(d);
23603 AST_LIST_UNLOCK(&domain_list);
23604 }
23605
23606
23607
23608 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, const char *configuration, int lineno)
23609 {
23610 char authcopy[256];
23611 char *username=NULL, *realm=NULL, *secret=NULL, *md5secret=NULL;
23612 struct sip_auth *a, *b, *auth;
23613
23614 if (ast_strlen_zero(configuration))
23615 return authlist;
23616
23617 ast_debug(1, "Auth config :: %s\n", configuration);
23618
23619 ast_copy_string(authcopy, configuration, sizeof(authcopy));
23620 username = authcopy;
23621
23622
23623 realm = strrchr(username, '@');
23624 if (realm)
23625 *realm++ = '\0';
23626 if (ast_strlen_zero(username) || ast_strlen_zero(realm)) {
23627 ast_log(LOG_WARNING, "Format for authentication entry is user[:secret]@realm at line %d\n", lineno);
23628 return authlist;
23629 }
23630
23631
23632 if ((secret = strchr(username, ':'))) {
23633 *secret++ = '\0';
23634 } else if ((md5secret = strchr(username, '#'))) {
23635 *md5secret++ = '\0';
23636 }
23637
23638 if (!(auth = ast_calloc(1, sizeof(*auth))))
23639 return authlist;
23640
23641 ast_copy_string(auth->realm, realm, sizeof(auth->realm));
23642 ast_copy_string(auth->username, username, sizeof(auth->username));
23643 if (secret)
23644 ast_copy_string(auth->secret, secret, sizeof(auth->secret));
23645 if (md5secret)
23646 ast_copy_string(auth->md5secret, md5secret, sizeof(auth->md5secret));
23647
23648
23649 for (b = NULL, a = authlist; a ; b = a, a = a->next)
23650 ;
23651 if (b)
23652 b->next = auth;
23653 else
23654 authlist = auth;
23655
23656 ast_verb(3, "Added authentication for realm %s\n", realm);
23657
23658 return authlist;
23659
23660 }
23661
23662
23663 static int clear_realm_authentication(struct sip_auth *authlist)
23664 {
23665 struct sip_auth *a = authlist;
23666 struct sip_auth *b;
23667
23668 while (a) {
23669 b = a;
23670 a = a->next;
23671 ast_free(b);
23672 }
23673
23674 return 1;
23675 }
23676
23677
23678 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm)
23679 {
23680 struct sip_auth *a;
23681
23682 for (a = authlist; a; a = a->next) {
23683 if (!strcasecmp(a->realm, realm))
23684 break;
23685 }
23686
23687 return a;
23688 }
23689
23690
23691
23692
23693 static struct ast_variable *add_var(const char *buf, struct ast_variable *list)
23694 {
23695 struct ast_variable *tmpvar = NULL;
23696 char *varname = ast_strdupa(buf), *varval = NULL;
23697
23698 if ((varval = strchr(varname, '='))) {
23699 *varval++ = '\0';
23700 if ((tmpvar = ast_variable_new(varname, varval, ""))) {
23701 tmpvar->next = list;
23702 list = tmpvar;
23703 }
23704 }
23705 return list;
23706 }
23707
23708
23709 static void set_peer_defaults(struct sip_peer *peer)
23710 {
23711 if (peer->expire == 0) {
23712
23713
23714
23715 peer->expire = -1;
23716 peer->pokeexpire = -1;
23717 peer->addr.sin_port = htons(STANDARD_SIP_PORT);
23718 set_socket_transport(&peer->socket, SIP_TRANSPORT_UDP);
23719 }
23720 peer->type = SIP_TYPE_PEER;
23721 ast_copy_flags(&peer->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
23722 ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
23723 ast_string_field_set(peer, context, sip_cfg.default_context);
23724 ast_string_field_set(peer, subscribecontext, sip_cfg.default_subscribecontext);
23725 ast_string_field_set(peer, language, default_language);
23726 ast_string_field_set(peer, mohinterpret, default_mohinterpret);
23727 ast_string_field_set(peer, mohsuggest, default_mohsuggest);
23728 peer->addr.sin_family = AF_INET;
23729 peer->defaddr.sin_family = AF_INET;
23730 peer->capability = global_capability;
23731 peer->maxcallbitrate = default_maxcallbitrate;
23732 peer->rtptimeout = global_rtptimeout;
23733 peer->rtpholdtimeout = global_rtpholdtimeout;
23734 peer->rtpkeepalive = global_rtpkeepalive;
23735 peer->allowtransfer = sip_cfg.allowtransfer;
23736 peer->autoframing = global_autoframing;
23737 peer->t38_maxdatagram = global_t38_maxdatagram;
23738 peer->qualifyfreq = global_qualifyfreq;
23739 if (global_callcounter)
23740 peer->call_limit=INT_MAX;
23741 ast_string_field_set(peer, vmexten, default_vmexten);
23742 ast_string_field_set(peer, secret, "");
23743 ast_string_field_set(peer, remotesecret, "");
23744 ast_string_field_set(peer, md5secret, "");
23745 ast_string_field_set(peer, cid_num, "");
23746 ast_string_field_set(peer, cid_name, "");
23747 ast_string_field_set(peer, fromdomain, "");
23748 ast_string_field_set(peer, fromuser, "");
23749 ast_string_field_set(peer, regexten, "");
23750 peer->callgroup = 0;
23751 peer->pickupgroup = 0;
23752 peer->maxms = default_qualify;
23753 peer->prefs = default_prefs;
23754 peer->stimer.st_mode_oper = global_st_mode;
23755 peer->stimer.st_ref = global_st_refresher;
23756 peer->stimer.st_min_se = global_min_se;
23757 peer->stimer.st_max_se = global_max_se;
23758 peer->timer_t1 = global_t1;
23759 peer->timer_b = global_timer_b;
23760 clear_peer_mailboxes(peer);
23761 }
23762
23763
23764 static struct sip_peer *temp_peer(const char *name)
23765 {
23766 struct sip_peer *peer;
23767
23768 if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct")))
23769 return NULL;
23770
23771 if (ast_string_field_init(peer, 512)) {
23772 ao2_t_ref(peer, -1, "failed to string_field_init, drop peer");
23773 return NULL;
23774 }
23775
23776 ast_atomic_fetchadd_int(&apeerobjs, 1);
23777 set_peer_defaults(peer);
23778
23779 ast_copy_string(peer->name, name, sizeof(peer->name));
23780
23781 peer->selfdestruct = TRUE;
23782 peer->host_dynamic = TRUE;
23783 peer->prefs = default_prefs;
23784 reg_source_db(peer);
23785
23786 return peer;
23787 }
23788
23789
23790 static void add_peer_mailboxes(struct sip_peer *peer, const char *value)
23791 {
23792 char *next, *mbox, *context;
23793
23794 next = ast_strdupa(value);
23795
23796 while ((mbox = context = strsep(&next, ","))) {
23797 struct sip_mailbox *mailbox;
23798 int duplicate = 0;
23799
23800 strsep(&context, "@");
23801
23802 if (ast_strlen_zero(mbox)) {
23803 continue;
23804 }
23805
23806
23807 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
23808 if (!strcmp(mailbox->mailbox, mbox) && !strcmp(S_OR(mailbox->context, ""), S_OR(context, ""))) {
23809 duplicate = 1;
23810 mailbox->delme = 1;
23811 break;
23812 }
23813 }
23814 if (duplicate) {
23815 continue;
23816 }
23817
23818 if (!(mailbox = ast_calloc(1, sizeof(*mailbox)))) {
23819 continue;
23820 }
23821
23822 mailbox->mailbox = ast_strdup(mbox);
23823 mailbox->context = ast_strdup(context);
23824
23825 AST_LIST_INSERT_TAIL(&peer->mailboxes, mailbox, entry);
23826 }
23827 }
23828
23829
23830 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only)
23831 {
23832 struct sip_peer *peer = NULL;
23833 struct ast_ha *oldha = NULL;
23834 int found = 0;
23835 int firstpass = 1;
23836 uint16_t port = 0;
23837 int format = 0;
23838 time_t regseconds = 0;
23839 struct ast_flags peerflags[2] = {{(0)}};
23840 struct ast_flags mask[2] = {{(0)}};
23841 char callback[256] = "";
23842 struct sip_peer tmp_peer;
23843 const char *srvlookup = NULL;
23844 static int deprecation_warning = 1;
23845 int alt_fullcontact = alt ? 1 : 0;
23846 struct ast_str *fullcontact = ast_str_alloca(512);
23847
23848 if (!realtime || ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
23849
23850
23851
23852
23853
23854 ast_copy_string(tmp_peer.name, name, sizeof(tmp_peer.name));
23855 peer = ao2_t_find(peers, &tmp_peer, OBJ_POINTER | OBJ_UNLINK, "find and unlink peer from peers table");
23856 }
23857
23858 if (peer) {
23859
23860 found++;
23861 if (!(peer->the_mark))
23862 firstpass = 0;
23863 } else {
23864 if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct")))
23865 return NULL;
23866
23867 if (ast_string_field_init(peer, 512)) {
23868 ao2_t_ref(peer, -1, "failed to string_field_init, drop peer");
23869 return NULL;
23870 }
23871
23872 if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
23873 ast_atomic_fetchadd_int(&rpeerobjs, 1);
23874 ast_debug(3, "-REALTIME- peer built. Name: %s. Peer objects: %d\n", name, rpeerobjs);
23875 } else
23876 ast_atomic_fetchadd_int(&speerobjs, 1);
23877 }
23878
23879
23880 if (firstpass) {
23881 peer->lastmsgssent = -1;
23882 oldha = peer->ha;
23883 peer->ha = NULL;
23884 set_peer_defaults(peer);
23885 peer->type = 0;
23886 }
23887 if (!found && name)
23888 ast_copy_string(peer->name, name, sizeof(peer->name));
23889
23890
23891 if (peer->chanvars) {
23892 ast_variables_destroy(peer->chanvars);
23893 peer->chanvars = NULL;
23894
23895 }
23896
23897 if (found)
23898 peer->portinuri = 0;
23899
23900
23901 clear_realm_authentication(peer->auth);
23902 peer->auth = NULL;
23903 peer->default_outbound_transport = 0;
23904 peer->transports = 0;
23905
23906 if (!devstate_only) {
23907 struct sip_mailbox *mailbox;
23908 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
23909 mailbox->delme = 1;
23910 }
23911 }
23912
23913 for (; v || ((v = alt) && !(alt=NULL)); v = v->next) {
23914 if (!devstate_only) {
23915 if (handle_common_options(&peerflags[0], &mask[0], v)) {
23916 continue;
23917 }
23918 if (handle_t38_options(&peerflags[0], &mask[0], v, &peer->t38_maxdatagram)) {
23919 continue;
23920 }
23921 if (!strcasecmp(v->name, "transport") && !ast_strlen_zero(v->value)) {
23922 char *val = ast_strdupa(v->value);
23923 char *trans;
23924
23925 while ((trans = strsep(&val, ","))) {
23926 trans = ast_skip_blanks(trans);
23927
23928 if (!strncasecmp(trans, "udp", 3)) {
23929 peer->transports |= SIP_TRANSPORT_UDP;
23930 } else if (!strncasecmp(trans, "tcp", 3)) {
23931 peer->transports |= SIP_TRANSPORT_TCP;
23932 } else if (!strncasecmp(trans, "tls", 3)) {
23933 peer->transports |= SIP_TRANSPORT_TLS;
23934 } else {
23935 ast_log(LOG_NOTICE, "'%s' is not a valid transport type. if no other is specified, udp will be used.\n", trans);
23936 }
23937
23938 if (!peer->default_outbound_transport) {
23939 peer->default_outbound_transport = peer->transports;
23940 }
23941 }
23942 } else if (realtime && !strcasecmp(v->name, "regseconds")) {
23943 ast_get_time_t(v->value, ®seconds, 0, NULL);
23944 } else if (realtime && !strcasecmp(v->name, "name")) {
23945 ast_copy_string(peer->name, v->value, sizeof(peer->name));
23946 } else if (realtime && !strcasecmp(v->name, "useragent")) {
23947 ast_string_field_set(peer, useragent, v->value);
23948 } else if (!strcasecmp(v->name, "type")) {
23949 if (!strcasecmp(v->value, "peer")) {
23950 peer->type |= SIP_TYPE_PEER;
23951 } else if (!strcasecmp(v->value, "user")) {
23952 peer->type |= SIP_TYPE_USER;
23953 } else if (!strcasecmp(v->value, "friend")) {
23954 peer->type = SIP_TYPE_USER | SIP_TYPE_PEER;
23955 }
23956 } else if (!strcasecmp(v->name, "remotesecret")) {
23957 ast_string_field_set(peer, remotesecret, v->value);
23958 } else if (!strcasecmp(v->name, "secret")) {
23959 ast_string_field_set(peer, secret, v->value);
23960 } else if (!strcasecmp(v->name, "md5secret")) {
23961 ast_string_field_set(peer, md5secret, v->value);
23962 } else if (!strcasecmp(v->name, "auth")) {
23963 peer->auth = add_realm_authentication(peer->auth, v->value, v->lineno);
23964 } else if (!strcasecmp(v->name, "callerid")) {
23965 char cid_name[80] = { '\0' }, cid_num[80] = { '\0' };
23966
23967 ast_callerid_split(v->value, cid_name, sizeof(cid_name), cid_num, sizeof(cid_num));
23968 ast_string_field_set(peer, cid_name, cid_name);
23969 ast_string_field_set(peer, cid_num, cid_num);
23970 } else if (!strcasecmp(v->name, "fullname")) {
23971 ast_string_field_set(peer, cid_name, v->value);
23972 } else if (!strcasecmp(v->name, "trunkname")) {
23973
23974 ast_string_field_set(peer, cid_name, "");
23975 } else if (!strcasecmp(v->name, "cid_number")) {
23976 ast_string_field_set(peer, cid_num, v->value);
23977 } else if (!strcasecmp(v->name, "context")) {
23978 ast_string_field_set(peer, context, v->value);
23979 ast_set_flag(&peer->flags[1], SIP_PAGE2_HAVEPEERCONTEXT);
23980 } else if (!strcasecmp(v->name, "subscribecontext")) {
23981 ast_string_field_set(peer, subscribecontext, v->value);
23982 } else if (!strcasecmp(v->name, "fromdomain")) {
23983 ast_string_field_set(peer, fromdomain, v->value);
23984 } else if (!strcasecmp(v->name, "usereqphone")) {
23985 ast_set2_flag(&peer->flags[0], ast_true(v->value), SIP_USEREQPHONE);
23986 } else if (!strcasecmp(v->name, "fromuser")) {
23987 ast_string_field_set(peer, fromuser, v->value);
23988 } else if (!strcasecmp(v->name, "outboundproxy")) {
23989 char *port, *next, *force, *proxyname;
23990 int forceopt = FALSE;
23991
23992 next = proxyname = ast_strdupa(v->value);
23993 if ((port = strchr(proxyname, ':'))) {
23994 *port++ = '\0';
23995 next = port;
23996 }
23997 if ((force = strchr(next, ','))) {
23998 *force++ = '\0';
23999 forceopt = strcmp(force, "force");
24000 }
24001
24002 peer->outboundproxy = proxy_allocate(proxyname, port, forceopt);
24003 } else if (!strcasecmp(v->name, "host")) {
24004 if (!strcasecmp(v->value, "dynamic")) {
24005
24006 if (!found || !peer->host_dynamic) {
24007
24008
24009 memset(&peer->addr.sin_addr, 0, 4);
24010 peer->addr.sin_port = 0;
24011 }
24012 peer->host_dynamic = TRUE;
24013 } else {
24014
24015 AST_SCHED_DEL_UNREF(sched, peer->expire,
24016 unref_peer(peer, "removing register expire ref"));
24017
24018 peer->addr.sin_port = 0;
24019 peer->host_dynamic = FALSE;
24020 srvlookup = v->value;
24021 if (global_dynamic_exclude_static) {
24022 int err = 0;
24023 global_contact_ha = ast_append_ha("deny", (char *)ast_inet_ntoa(peer->addr.sin_addr), global_contact_ha, &err);
24024 if (err) {
24025 ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
24026 }
24027 }
24028 }
24029 } else if (!strcasecmp(v->name, "defaultip")) {
24030 if (!ast_strlen_zero(v->value) && ast_get_ip(&peer->defaddr, v->value)) {
24031 unref_peer(peer, "unref_peer: from build_peer defaultip");
24032 return NULL;
24033 }
24034 } else if (!strcasecmp(v->name, "permit") || !strcasecmp(v->name, "deny")) {
24035 int ha_error = 0;
24036 if (!ast_strlen_zero(v->value)) {
24037 peer->ha = ast_append_ha(v->name, v->value, peer->ha, &ha_error);
24038 }
24039 if (ha_error) {
24040 ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
24041 }
24042 } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny")) {
24043 int ha_error = 0;
24044 if (!ast_strlen_zero(v->value)) {
24045 peer->contactha = ast_append_ha(v->name + 7, v->value, peer->contactha, &ha_error);
24046 }
24047 if (ha_error) {
24048 ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
24049 }
24050 } else if (!strcasecmp(v->name, "port")) {
24051 peer->portinuri = 1;
24052 if (!(port = port_str2int(v->value, 0))) {
24053 if (realtime) {
24054
24055 peer->portinuri = 0;
24056 } else {
24057 ast_log(LOG_WARNING, "Invalid peer port configuration at line %d : %s\n", v->lineno, v->value);
24058 }
24059 }
24060 } else if (!strcasecmp(v->name, "callingpres")) {
24061 peer->callingpres = ast_parse_caller_presentation(v->value);
24062 if (peer->callingpres == -1) {
24063 peer->callingpres = atoi(v->value);
24064 }
24065 } else if (!strcasecmp(v->name, "username") || !strcmp(v->name, "defaultuser")) {
24066 ast_string_field_set(peer, username, v->value);
24067 if (!strcasecmp(v->name, "username")) {
24068 if (deprecation_warning) {
24069 ast_log(LOG_NOTICE, "The 'username' field for sip peers has been deprecated in favor of the term 'defaultuser'\n");
24070 deprecation_warning = 0;
24071 }
24072 peer->deprecated_username = 1;
24073 }
24074 } else if (!strcasecmp(v->name, "language")) {
24075 ast_string_field_set(peer, language, v->value);
24076 } else if (!strcasecmp(v->name, "regexten")) {
24077 ast_string_field_set(peer, regexten, v->value);
24078 } else if (!strcasecmp(v->name, "callbackextension")) {
24079 ast_copy_string(callback, v->value, sizeof(callback));
24080 } else if (!strcasecmp(v->name, "amaflags")) {
24081 format = ast_cdr_amaflags2int(v->value);
24082 if (format < 0) {
24083 ast_log(LOG_WARNING, "Invalid AMA Flags for peer: %s at line %d\n", v->value, v->lineno);
24084 } else {
24085 peer->amaflags = format;
24086 }
24087 } else if (!strcasecmp(v->name, "accountcode")) {
24088 ast_string_field_set(peer, accountcode, v->value);
24089 } else if (!strcasecmp(v->name, "mohinterpret")) {
24090 ast_string_field_set(peer, mohinterpret, v->value);
24091 } else if (!strcasecmp(v->name, "mohsuggest")) {
24092 ast_string_field_set(peer, mohsuggest, v->value);
24093 } else if (!strcasecmp(v->name, "parkinglot")) {
24094 ast_string_field_set(peer, parkinglot, v->value);
24095 } else if (!strcasecmp(v->name, "mailbox")) {
24096 add_peer_mailboxes(peer, v->value);
24097 } else if (!strcasecmp(v->name, "hasvoicemail")) {
24098
24099
24100 if (ast_true(v->value) && AST_LIST_EMPTY(&peer->mailboxes)) {
24101 add_peer_mailboxes(peer, name);
24102 }
24103 } else if (!strcasecmp(v->name, "subscribemwi")) {
24104 ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_SUBSCRIBEMWIONLY);
24105 } else if (!strcasecmp(v->name, "vmexten")) {
24106 ast_string_field_set(peer, vmexten, v->value);
24107 } else if (!strcasecmp(v->name, "callgroup")) {
24108 peer->callgroup = ast_get_group(v->value);
24109 } else if (!strcasecmp(v->name, "allowtransfer")) {
24110 peer->allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
24111 } else if (!strcasecmp(v->name, "pickupgroup")) {
24112 peer->pickupgroup = ast_get_group(v->value);
24113 } else if (!strcasecmp(v->name, "allow")) {
24114 int error = ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, TRUE);
24115 if (error) {
24116 ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
24117 }
24118 } else if (!strcasecmp(v->name, "disallow")) {
24119 int error = ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, FALSE);
24120 if (error) {
24121 ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
24122 }
24123 } else if (!strcasecmp(v->name, "registertrying")) {
24124 ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_REGISTERTRYING);
24125 } else if (!strcasecmp(v->name, "autoframing")) {
24126 peer->autoframing = ast_true(v->value);
24127 } else if (!strcasecmp(v->name, "rtptimeout")) {
24128 if ((sscanf(v->value, "%30d", &peer->rtptimeout) != 1) || (peer->rtptimeout < 0)) {
24129 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
24130 peer->rtptimeout = global_rtptimeout;
24131 }
24132 } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
24133 if ((sscanf(v->value, "%30d", &peer->rtpholdtimeout) != 1) || (peer->rtpholdtimeout < 0)) {
24134 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
24135 peer->rtpholdtimeout = global_rtpholdtimeout;
24136 }
24137 } else if (!strcasecmp(v->name, "rtpkeepalive")) {
24138 if ((sscanf(v->value, "%30d", &peer->rtpkeepalive) != 1) || (peer->rtpkeepalive < 0)) {
24139 ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d. Using default.\n", v->value, v->lineno);
24140 peer->rtpkeepalive = global_rtpkeepalive;
24141 }
24142 } else if (!strcasecmp(v->name, "timert1")) {
24143 if ((sscanf(v->value, "%30d", &peer->timer_t1) != 1) || (peer->timer_t1 < 0)) {
24144 ast_log(LOG_WARNING, "'%s' is not a valid T1 time at line %d. Using default.\n", v->value, v->lineno);
24145 peer->timer_t1 = global_t1;
24146 }
24147
24148
24149 if (peer->timer_b < peer->timer_t1 * 64) {
24150 peer->timer_b = peer->timer_t1 * 64;
24151 }
24152 } else if (!strcasecmp(v->name, "timerb")) {
24153 if ((sscanf(v->value, "%30d", &peer->timer_b) != 1) || (peer->timer_b < 0)) {
24154 ast_log(LOG_WARNING, "'%s' is not a valid Timer B time at line %d. Using default.\n", v->value, v->lineno);
24155 peer->timer_b = global_timer_b;
24156 }
24157 if (peer->timer_b < peer->timer_t1 * 64) {
24158 static int warning = 0;
24159 if (warning++ % 20 == 0) {
24160 ast_log(LOG_WARNING, "Timer B has been set lower than recommended. (RFC 3261, 17.1.1.2)\n");
24161 }
24162 }
24163 } else if (!strcasecmp(v->name, "setvar")) {
24164 peer->chanvars = add_var(v->value, peer->chanvars);
24165 } else if (!strcasecmp(v->name, "qualifyfreq")) {
24166 int i;
24167 if (sscanf(v->value, "%30d", &i) == 1) {
24168 peer->qualifyfreq = i * 1000;
24169 } else {
24170 ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
24171 peer->qualifyfreq = global_qualifyfreq;
24172 }
24173 } else if (!strcasecmp(v->name, "maxcallbitrate")) {
24174 peer->maxcallbitrate = atoi(v->value);
24175 if (peer->maxcallbitrate < 0) {
24176 peer->maxcallbitrate = default_maxcallbitrate;
24177 }
24178 } else if (!strcasecmp(v->name, "session-timers")) {
24179 int i = (int) str2stmode(v->value);
24180 if (i < 0) {
24181 ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
24182 peer->stimer.st_mode_oper = global_st_mode;
24183 } else {
24184 peer->stimer.st_mode_oper = i;
24185 }
24186 } else if (!strcasecmp(v->name, "session-expires")) {
24187 if (sscanf(v->value, "%30d", &peer->stimer.st_max_se) != 1) {
24188 ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
24189 peer->stimer.st_max_se = global_max_se;
24190 }
24191 } else if (!strcasecmp(v->name, "session-minse")) {
24192 if (sscanf(v->value, "%30d", &peer->stimer.st_min_se) != 1) {
24193 ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
24194 peer->stimer.st_min_se = global_min_se;
24195 }
24196 if (peer->stimer.st_min_se < 90) {
24197 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);
24198 peer->stimer.st_min_se = global_min_se;
24199 }
24200 } else if (!strcasecmp(v->name, "session-refresher")) {
24201 int i = (int) str2strefresher(v->value);
24202 if (i < 0) {
24203 ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
24204 peer->stimer.st_ref = global_st_refresher;
24205 } else {
24206 peer->stimer.st_ref = i;
24207 }
24208 }
24209 }
24210
24211
24212 if (realtime && !strcasecmp(v->name, "lastms")) {
24213 sscanf(v->value, "%30d", &peer->lastms);
24214 } else if (realtime && !strcasecmp(v->name, "ipaddr") && !ast_strlen_zero(v->value) ) {
24215 inet_aton(v->value, &(peer->addr.sin_addr));
24216 } else if (realtime && !strcasecmp(v->name, "fullcontact")) {
24217 if (alt_fullcontact && !alt) {
24218
24219
24220
24221
24222
24223 alt_fullcontact = 0;
24224 ast_str_reset(fullcontact);
24225 }
24226
24227 if (fullcontact->used > 0) {
24228 ast_str_append(&fullcontact, 0, ";%s", v->value);
24229 } else {
24230 ast_str_set(&fullcontact, 0, "%s", v->value);
24231 }
24232 } else if (!strcasecmp(v->name, "qualify")) {
24233 if (!strcasecmp(v->value, "no")) {
24234 peer->maxms = 0;
24235 } else if (!strcasecmp(v->value, "yes")) {
24236 peer->maxms = default_qualify ? default_qualify : DEFAULT_MAXMS;
24237 } else if (sscanf(v->value, "%30d", &peer->maxms) != 1) {
24238 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);
24239 peer->maxms = 0;
24240 }
24241 if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && peer->maxms > 0) {
24242
24243
24244
24245
24246 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);
24247 peer->maxms = 0;
24248 }
24249 } else if (!strcasecmp(v->name, "callcounter")) {
24250 peer->call_limit = ast_true(v->value) ? INT_MAX : 0;
24251 } else if (!strcasecmp(v->name, "call-limit")) {
24252 peer->call_limit = atoi(v->value);
24253 if (peer->call_limit < 0) {
24254 peer->call_limit = 0;
24255 }
24256 } else if (!strcasecmp(v->name, "busylevel")) {
24257 peer->busy_level = atoi(v->value);
24258 if (peer->busy_level < 0) {
24259 peer->busy_level = 0;
24260 }
24261 }
24262 }
24263
24264 if (!devstate_only) {
24265 struct sip_mailbox *mailbox;
24266 AST_LIST_TRAVERSE_SAFE_BEGIN(&peer->mailboxes, mailbox, entry) {
24267 if (mailbox->delme) {
24268 AST_LIST_REMOVE_CURRENT(entry);
24269 destroy_mailbox(mailbox);
24270 }
24271 }
24272 AST_LIST_TRAVERSE_SAFE_END;
24273 }
24274
24275 if (!peer->default_outbound_transport) {
24276
24277 peer->transports = default_transports;
24278
24279 peer->default_outbound_transport = default_primary_transport;
24280 }
24281
24282
24283
24284
24285
24286 if (((peer->socket.type != peer->default_outbound_transport) && (peer->expire == -1)) ||
24287 !(peer->socket.type & peer->transports) || !(peer->socket.type)) {
24288
24289 set_socket_transport(&peer->socket, peer->default_outbound_transport);
24290 }
24291
24292 if (port && !realtime && peer->host_dynamic) {
24293 peer->defaddr.sin_port = htons(port);
24294 } else if (port) {
24295 peer->addr.sin_port = htons(port);
24296 }
24297
24298 if (ast_str_strlen(fullcontact)) {
24299 ast_string_field_set(peer, fullcontact, ast_str_buffer(fullcontact));
24300 peer->rt_fromcontact = TRUE;
24301
24302
24303
24304
24305
24306
24307
24308
24309 if (!ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) || !peer->addr.sin_addr.s_addr) {
24310 __set_address_from_contact(fullcontact->str, &peer->addr, 0);
24311 }
24312 }
24313
24314 if (srvlookup && peer->dnsmgr == NULL) {
24315 char transport[MAXHOSTNAMELEN];
24316 char _srvlookup[MAXHOSTNAMELEN];
24317 char *params;
24318
24319 ast_copy_string(_srvlookup, srvlookup, sizeof(_srvlookup));
24320 if ((params = strchr(_srvlookup, ';'))) {
24321 *params++ = '\0';
24322 }
24323
24324 snprintf(transport, sizeof(transport), "_sip._%s", get_transport(peer->socket.type));
24325
24326 if (ast_dnsmgr_lookup(_srvlookup, &peer->addr, &peer->dnsmgr, sip_cfg.srvlookup && !peer->portinuri ? transport : NULL)) {
24327 ast_log(LOG_ERROR, "srvlookup failed for host: %s, on peer %s, removing peer\n", _srvlookup, peer->name);
24328 unref_peer(peer, "getting rid of a peer pointer");
24329 return NULL;
24330 }
24331
24332 ast_string_field_set(peer, tohost, srvlookup);
24333 }
24334
24335 if (!peer->addr.sin_port) {
24336 peer->addr.sin_port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
24337 }
24338 if (!peer->defaddr.sin_port) {
24339 peer->defaddr.sin_port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
24340 }
24341 if (!peer->socket.port) {
24342 peer->socket.port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
24343 }
24344
24345 if (!sip_cfg.ignore_regexpire && peer->host_dynamic && realtime) {
24346 time_t nowtime = time(NULL);
24347
24348 if ((nowtime - regseconds) > 0) {
24349 destroy_association(peer);
24350 memset(&peer->addr, 0, sizeof(peer->addr));
24351 peer->lastms = -1;
24352 ast_debug(1, "Bah, we're expired (%d/%d/%d)!\n", (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
24353 }
24354 }
24355
24356
24357 if (!devstate_only && realtime && peer->lastms > 0) {
24358 ref_peer(peer, "schedule qualify");
24359 sip_poke_peer(peer, 0);
24360 }
24361
24362 ast_copy_flags(&peer->flags[0], &peerflags[0], mask[0].flags);
24363 ast_copy_flags(&peer->flags[1], &peerflags[1], mask[1].flags);
24364 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
24365 sip_cfg.allowsubscribe = TRUE;
24366 }
24367 if (peer->host_dynamic && !peer->is_realtime) {
24368 reg_source_db(peer);
24369 }
24370
24371
24372
24373 if (!devstate_only && !ast_test_flag(&peer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY) &&
24374 !AST_LIST_EMPTY(&peer->mailboxes)) {
24375 add_peer_mwi_subs(peer);
24376
24377
24378
24379 sip_send_mwi_to_peer(peer, NULL, 1);
24380 }
24381
24382 peer->the_mark = 0;
24383
24384 ast_free_ha(oldha);
24385 if (!ast_strlen_zero(callback)) {
24386 char *reg_string;
24387 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) {
24388 ast_log(LOG_WARNING, "asprintf() failed: %s\n", strerror(errno));
24389 } else if (reg_string) {
24390 sip_register(reg_string, 0);
24391 ast_free(reg_string);
24392 }
24393 }
24394 return peer;
24395 }
24396
24397 static int peer_markall_func(void *device, void *arg, int flags)
24398 {
24399 struct sip_peer *peer = device;
24400 peer->the_mark = 1;
24401 return 0;
24402 }
24403
24404
24405
24406
24407
24408
24409
24410 static int reload_config(enum channelreloadreason reason)
24411 {
24412 struct ast_config *cfg, *ucfg;
24413 struct ast_variable *v;
24414 struct sip_peer *peer;
24415 char *cat, *stringp, *context, *oldregcontext;
24416 char newcontexts[AST_MAX_CONTEXT], oldcontexts[AST_MAX_CONTEXT];
24417 struct ast_flags dummy[2];
24418 struct ast_flags config_flags = { reason == CHANNEL_MODULE_LOAD ? 0 : ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) ? 0 : CONFIG_FLAG_FILEUNCHANGED };
24419 int auto_sip_domains = FALSE;
24420 struct sockaddr_in old_bindaddr = bindaddr;
24421 int registry_count = 0, peer_count = 0;
24422 time_t run_start, run_end;
24423
24424 run_start = time(0);
24425 ast_unload_realtime("sipregs");
24426 ast_unload_realtime("sippeers");
24427 cfg = ast_config_load(config, config_flags);
24428
24429
24430 if (!cfg) {
24431 ast_log(LOG_NOTICE, "Unable to load config %s\n", config);
24432 return -1;
24433 } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
24434 ucfg = ast_config_load("users.conf", config_flags);
24435 if (ucfg == CONFIG_STATUS_FILEUNCHANGED) {
24436 return 1;
24437 } else if (ucfg == CONFIG_STATUS_FILEINVALID) {
24438 ast_log(LOG_ERROR, "Contents of users.conf are invalid and cannot be parsed\n");
24439 return 1;
24440 }
24441
24442 ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
24443 if ((cfg = ast_config_load(config, config_flags)) == CONFIG_STATUS_FILEINVALID) {
24444 ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed\n", config);
24445 ast_config_destroy(ucfg);
24446 return 1;
24447 }
24448 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
24449 ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed\n", config);
24450 return 1;
24451 } else {
24452 ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
24453 if ((ucfg = ast_config_load("users.conf", config_flags)) == CONFIG_STATUS_FILEINVALID) {
24454 ast_log(LOG_ERROR, "Contents of users.conf are invalid and cannot be parsed\n");
24455 ast_config_destroy(cfg);
24456 return 1;
24457 }
24458 }
24459
24460
24461 memset(&sip_tcp_desc.local_address, 0, sizeof(sip_tcp_desc.local_address));
24462 memset(&sip_tls_desc.local_address, 0, sizeof(sip_tls_desc.local_address));
24463
24464 ast_free_ha(global_contact_ha);
24465 global_contact_ha = NULL;
24466
24467 default_tls_cfg.enabled = FALSE;
24468
24469 sip_tcp_desc.local_address.sin_port = htons(STANDARD_SIP_PORT);
24470 sip_tls_desc.local_address.sin_port = htons(STANDARD_TLS_PORT);
24471
24472 if (reason != CHANNEL_MODULE_LOAD) {
24473 ast_debug(4, "--------------- SIP reload started\n");
24474
24475 clear_realm_authentication(authl);
24476 clear_sip_domains();
24477 authl = NULL;
24478
24479
24480
24481 ASTOBJ_CONTAINER_TRAVERSE(®l, 1, do {
24482
24483 ASTOBJ_RDLOCK(iterator);
24484 if (iterator->call) {
24485 ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", iterator->username, iterator->hostname);
24486
24487 dialog_unlink_all(iterator->call, TRUE, TRUE);
24488 iterator->call = dialog_unref(iterator->call, "remove iterator->call from registry traversal");
24489 }
24490 if (iterator->expire > -1) {
24491 AST_SCHED_DEL_UNREF(sched, iterator->expire, registry_unref(iterator, "reg ptr unref from reload config"));
24492 }
24493 if (iterator->timeout > -1) {
24494 AST_SCHED_DEL_UNREF(sched, iterator->timeout, registry_unref(iterator, "reg ptr unref from reload config"));
24495 }
24496 ASTOBJ_UNLOCK(iterator);
24497
24498 } while(0));
24499
24500
24501 ASTOBJ_CONTAINER_DESTROYALL(®l, sip_registry_destroy);
24502 ast_debug(4, "--------------- Done destroying registry list\n");
24503 ao2_t_callback(peers, OBJ_NODATA, peer_markall_func, NULL, "callback to mark all peers");
24504 }
24505
24506
24507 if (reason != CHANNEL_MODULE_LOAD) {
24508 ast_free(default_tls_cfg.certfile);
24509 ast_free(default_tls_cfg.cipher);
24510 ast_free(default_tls_cfg.cafile);
24511 ast_free(default_tls_cfg.capath);
24512 }
24513 default_tls_cfg.certfile = ast_strdup(AST_CERTFILE);
24514 default_tls_cfg.cipher = ast_strdup("");
24515 default_tls_cfg.cafile = ast_strdup("");
24516 default_tls_cfg.capath = ast_strdup("");
24517
24518
24519
24520 ast_copy_string(oldcontexts, global_regcontext, sizeof(oldcontexts));
24521 oldregcontext = oldcontexts;
24522
24523
24524
24525 sipdebug &= sip_debug_console;
24526 ast_clear_flag(&global_flags[0], AST_FLAGS_ALL);
24527 ast_clear_flag(&global_flags[1], AST_FLAGS_ALL);
24528
24529
24530 memset(&bindaddr, 0, sizeof(bindaddr));
24531 memset(&stunaddr, 0, sizeof(stunaddr));
24532 memset(&internip, 0, sizeof(internip));
24533
24534
24535 ast_free_ha(localaddr);
24536 memset(&localaddr, 0, sizeof(localaddr));
24537 memset(&externip, 0, sizeof(externip));
24538 memset(&default_prefs, 0 , sizeof(default_prefs));
24539 memset(&sip_cfg.outboundproxy, 0, sizeof(struct sip_proxy));
24540 sip_cfg.outboundproxy.ip.sin_port = htons(STANDARD_SIP_PORT);
24541 sip_cfg.outboundproxy.ip.sin_family = AF_INET;
24542 sip_cfg.outboundproxy.force = FALSE;
24543 default_transports = 0;
24544 default_primary_transport = 0;
24545 ourport_tcp = STANDARD_SIP_PORT;
24546 ourport_tls = STANDARD_TLS_PORT;
24547 bindaddr.sin_port = htons(STANDARD_SIP_PORT);
24548 sip_cfg.srvlookup = DEFAULT_SRVLOOKUP;
24549 global_tos_sip = DEFAULT_TOS_SIP;
24550 global_tos_audio = DEFAULT_TOS_AUDIO;
24551 global_tos_video = DEFAULT_TOS_VIDEO;
24552 global_tos_text = DEFAULT_TOS_TEXT;
24553 global_cos_sip = DEFAULT_COS_SIP;
24554 global_cos_audio = DEFAULT_COS_AUDIO;
24555 global_cos_video = DEFAULT_COS_VIDEO;
24556 global_cos_text = DEFAULT_COS_TEXT;
24557
24558 externhost[0] = '\0';
24559 externexpire = 0;
24560 externrefresh = 10;
24561
24562
24563 sip_cfg.allow_external_domains = DEFAULT_ALLOW_EXT_DOM;
24564 global_regcontext[0] = '\0';
24565 sip_cfg.regextenonqualify = DEFAULT_REGEXTENONQUALIFY;
24566 sip_cfg.notifyringing = DEFAULT_NOTIFYRINGING;
24567 sip_cfg.notifycid = DEFAULT_NOTIFYCID;
24568 sip_cfg.notifyhold = FALSE;
24569 sip_cfg.directrtpsetup = FALSE;
24570 sip_cfg.alwaysauthreject = DEFAULT_ALWAYSAUTHREJECT;
24571 sip_cfg.allowsubscribe = FALSE;
24572 snprintf(global_useragent, sizeof(global_useragent), "%s %s", DEFAULT_USERAGENT, ast_get_version());
24573 snprintf(global_sdpsession, sizeof(global_sdpsession), "%s %s", DEFAULT_SDPSESSION, ast_get_version());
24574 snprintf(global_sdpowner, sizeof(global_sdpowner), "%s", DEFAULT_SDPOWNER);
24575 global_prematuremediafilter = TRUE;
24576 ast_copy_string(default_notifymime, DEFAULT_NOTIFYMIME, sizeof(default_notifymime));
24577 ast_copy_string(sip_cfg.realm, S_OR(ast_config_AST_SYSTEM_NAME, DEFAULT_REALM), sizeof(sip_cfg.realm));
24578 ast_copy_string(default_callerid, DEFAULT_CALLERID, sizeof(default_callerid));
24579 sip_cfg.compactheaders = DEFAULT_COMPACTHEADERS;
24580 global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
24581 global_regattempts_max = 0;
24582 sip_cfg.pedanticsipchecking = DEFAULT_PEDANTIC;
24583 sip_cfg.autocreatepeer = DEFAULT_AUTOCREATEPEER;
24584 global_autoframing = 0;
24585 sip_cfg.allowguest = DEFAULT_ALLOWGUEST;
24586 global_callcounter = DEFAULT_CALLCOUNTER;
24587 global_match_auth_username = FALSE;
24588 global_rtptimeout = 0;
24589 global_rtpholdtimeout = 0;
24590 global_rtpkeepalive = DEFAULT_RTPKEEPALIVE;
24591 sip_cfg.allowtransfer = TRANSFER_OPENFORALL;
24592 sip_cfg.rtautoclear = 120;
24593 ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE);
24594 ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP);
24595 sip_cfg.peer_rtupdate = TRUE;
24596 global_dynamic_exclude_static = 0;
24597
24598
24599 global_st_mode = SESSION_TIMER_MODE_ACCEPT;
24600 global_st_refresher = SESSION_TIMER_REFRESHER_UAS;
24601 global_min_se = DEFAULT_MIN_SE;
24602 global_max_se = DEFAULT_MAX_SE;
24603
24604
24605 global_qualify_gap = DEFAULT_QUALIFY_GAP;
24606 global_qualify_peers = DEFAULT_QUALIFY_PEERS;
24607
24608
24609 ast_copy_string(sip_cfg.default_context, DEFAULT_CONTEXT, sizeof(sip_cfg.default_context));
24610 sip_cfg.default_subscribecontext[0] = '\0';
24611 default_language[0] = '\0';
24612 default_fromdomain[0] = '\0';
24613 default_qualify = DEFAULT_QUALIFY;
24614 default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
24615 ast_copy_string(default_mohinterpret, DEFAULT_MOHINTERPRET, sizeof(default_mohinterpret));
24616 ast_copy_string(default_mohsuggest, DEFAULT_MOHSUGGEST, sizeof(default_mohsuggest));
24617 ast_copy_string(default_vmexten, DEFAULT_VMEXTEN, sizeof(default_vmexten));
24618 ast_set_flag(&global_flags[0], SIP_DTMF_RFC2833);
24619 ast_set_flag(&global_flags[0], SIP_NAT_RFC3581);
24620 ast_set_flag(&global_flags[0], SIP_DIRECT_MEDIA);
24621 ast_set_flag(&global_flags[1], SIP_PAGE2_FORWARD_LOOP_DETECTED);
24622
24623
24624 dumphistory = FALSE;
24625 recordhistory = FALSE;
24626 sipdebug &= ~sip_debug_config;
24627
24628
24629 global_relaxdtmf = FALSE;
24630 sip_cfg.callevents = DEFAULT_CALLEVENTS;
24631 global_authfailureevents = FALSE;
24632 global_t1 = DEFAULT_TIMER_T1;
24633 global_timer_b = 64 * DEFAULT_TIMER_T1;
24634 global_t1min = DEFAULT_T1MIN;
24635 global_qualifyfreq = DEFAULT_QUALIFYFREQ;
24636 global_t38_maxdatagram = -1;
24637 global_shrinkcallerid = 1;
24638
24639 sip_cfg.matchexterniplocally = DEFAULT_MATCHEXTERNIPLOCALLY;
24640
24641
24642 memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
24643
24644 ast_clear_flag(&global_flags[1], SIP_PAGE2_FAX_DETECT);
24645 ast_clear_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT | SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
24646 ast_clear_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT);
24647 ast_clear_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION);
24648
24649
24650
24651 for (v = ast_variable_browse(cfg, "general"); v; v = v->next) {
24652 if (handle_common_options(&global_flags[0], &dummy[0], v))
24653 continue;
24654 if (handle_t38_options(&global_flags[0], &dummy[0], v, &global_t38_maxdatagram)) {
24655 continue;
24656 }
24657
24658 if (!ast_jb_read_conf(&global_jbconf, v->name, v->value))
24659 continue;
24660
24661 if (!strcasecmp(v->name, "context")) {
24662 ast_copy_string(sip_cfg.default_context, v->value, sizeof(sip_cfg.default_context));
24663 } else if (!strcasecmp(v->name, "subscribecontext")) {
24664 ast_copy_string(sip_cfg.default_subscribecontext, v->value, sizeof(sip_cfg.default_subscribecontext));
24665 } else if (!strcasecmp(v->name, "callcounter")) {
24666 global_callcounter = ast_true(v->value) ? 1 : 0;
24667 } else if (!strcasecmp(v->name, "allowguest")) {
24668 sip_cfg.allowguest = ast_true(v->value) ? 1 : 0;
24669 } else if (!strcasecmp(v->name, "realm")) {
24670 ast_copy_string(sip_cfg.realm, v->value, sizeof(sip_cfg.realm));
24671 } else if (!strcasecmp(v->name, "useragent")) {
24672 ast_copy_string(global_useragent, v->value, sizeof(global_useragent));
24673 ast_debug(1, "Setting SIP channel User-Agent Name to %s\n", global_useragent);
24674 } else if (!strcasecmp(v->name, "sdpsession")) {
24675 ast_copy_string(global_sdpsession, v->value, sizeof(global_sdpsession));
24676 } else if (!strcasecmp(v->name, "sdpowner")) {
24677
24678 if (!strstr(v->value, " "))
24679 ast_copy_string(global_sdpowner, v->value, sizeof(global_sdpowner));
24680 else
24681 ast_log(LOG_WARNING, "'%s' must not contain spaces at line %d. Using default.\n", v->value, v->lineno);
24682 } else if (!strcasecmp(v->name, "allowtransfer")) {
24683 sip_cfg.allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
24684 } else if (!strcasecmp(v->name, "rtcachefriends")) {
24685 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTCACHEFRIENDS);
24686 } else if (!strcasecmp(v->name, "rtsavesysname")) {
24687 sip_cfg.rtsave_sysname = ast_true(v->value);
24688 } else if (!strcasecmp(v->name, "rtupdate")) {
24689 sip_cfg.peer_rtupdate = ast_true(v->value);
24690 } else if (!strcasecmp(v->name, "ignoreregexpire")) {
24691 sip_cfg.ignore_regexpire = ast_true(v->value);
24692 } else if (!strcasecmp(v->name, "timert1")) {
24693
24694
24695
24696 global_t1 = atoi(v->value);
24697
24698 global_timer_b = global_t1 * 64;
24699 } else if (!strcasecmp(v->name, "t1min")) {
24700 global_t1min = atoi(v->value);
24701 } else if (!strcasecmp(v->name, "transport") && !ast_strlen_zero(v->value)) {
24702 char *val = ast_strdupa(v->value);
24703 char *trans;
24704
24705 while ((trans = strsep(&val, ","))) {
24706 trans = ast_skip_blanks(trans);
24707
24708 if (!strncasecmp(trans, "udp", 3))
24709 default_transports |= SIP_TRANSPORT_UDP;
24710 else if (!strncasecmp(trans, "tcp", 3))
24711 default_transports |= SIP_TRANSPORT_TCP;
24712 else if (!strncasecmp(trans, "tls", 3))
24713 default_transports |= SIP_TRANSPORT_TLS;
24714 else
24715 ast_log(LOG_NOTICE, "'%s' is not a valid transport type. if no other is specified, udp will be used.\n", trans);
24716 if (default_primary_transport == 0) {
24717 default_primary_transport = default_transports;
24718 }
24719 }
24720 } else if (!strcasecmp(v->name, "tcpenable")) {
24721 sip_tcp_desc.local_address.sin_family = ast_false(v->value) ? 0 : AF_INET;
24722 ast_debug(2, "Enabling TCP socket for listening\n");
24723 } else if (!strcasecmp(v->name, "tcpbindaddr")) {
24724 int family = sip_tcp_desc.local_address.sin_family;
24725 if (ast_parse_arg(v->value, PARSE_INADDR, &sip_tcp_desc.local_address))
24726 ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n", v->name, v->value, v->lineno, config);
24727 sip_tcp_desc.local_address.sin_family = family;
24728 ast_debug(2, "Setting TCP socket address to %s\n", v->value);
24729 } else if (!strcasecmp(v->name, "tlsenable")) {
24730 default_tls_cfg.enabled = ast_true(v->value) ? TRUE : FALSE;
24731 sip_tls_desc.local_address.sin_family = AF_INET;
24732 } else if (!strcasecmp(v->name, "tlscertfile")) {
24733 ast_free(default_tls_cfg.certfile);
24734 default_tls_cfg.certfile = ast_strdup(v->value);
24735 } else if (!strcasecmp(v->name, "tlscipher")) {
24736 ast_free(default_tls_cfg.cipher);
24737 default_tls_cfg.cipher = ast_strdup(v->value);
24738 } else if (!strcasecmp(v->name, "tlscafile")) {
24739 ast_free(default_tls_cfg.cafile);
24740 default_tls_cfg.cafile = ast_strdup(v->value);
24741 } else if (!strcasecmp(v->name, "tlscapath")) {
24742 ast_free(default_tls_cfg.capath);
24743 default_tls_cfg.capath = ast_strdup(v->value);
24744 } else if (!strcasecmp(v->name, "tlsverifyclient")) {
24745 ast_set2_flag(&default_tls_cfg.flags, ast_true(v->value), AST_SSL_VERIFY_CLIENT);
24746 } else if (!strcasecmp(v->name, "tlsdontverifyserver")) {
24747 ast_set2_flag(&default_tls_cfg.flags, ast_true(v->value), AST_SSL_DONT_VERIFY_SERVER);
24748 } else if (!strcasecmp(v->name, "tlsbindaddr")) {
24749 if (ast_parse_arg(v->value, PARSE_INADDR, &sip_tls_desc.local_address))
24750 ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n", v->name, v->value, v->lineno, config);
24751 } else if (!strcasecmp(v->name, "dynamic_exclude_static") || !strcasecmp(v->name, "dynamic_excludes_static")) {
24752 global_dynamic_exclude_static = ast_true(v->value);
24753 } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny")) {
24754 int ha_error = 0;
24755 global_contact_ha = ast_append_ha(v->name + 7, v->value, global_contact_ha, &ha_error);
24756 if (ha_error) {
24757 ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
24758 }
24759 } else if (!strcasecmp(v->name, "rtautoclear")) {
24760 int i = atoi(v->value);
24761 if (i > 0)
24762 sip_cfg.rtautoclear = i;
24763 else
24764 i = 0;
24765 ast_set2_flag(&global_flags[1], i || ast_true(v->value), SIP_PAGE2_RTAUTOCLEAR);
24766 } else if (!strcasecmp(v->name, "usereqphone")) {
24767 ast_set2_flag(&global_flags[0], ast_true(v->value), SIP_USEREQPHONE);
24768 } else if (!strcasecmp(v->name, "prematuremedia")) {
24769 global_prematuremediafilter = ast_true(v->value);
24770 } else if (!strcasecmp(v->name, "relaxdtmf")) {
24771 global_relaxdtmf = ast_true(v->value);
24772 } else if (!strcasecmp(v->name, "vmexten")) {
24773 ast_copy_string(default_vmexten, v->value, sizeof(default_vmexten));
24774 } else if (!strcasecmp(v->name, "rtptimeout")) {
24775 if ((sscanf(v->value, "%30d", &global_rtptimeout) != 1) || (global_rtptimeout < 0)) {
24776 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
24777 global_rtptimeout = 0;
24778 }
24779 } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
24780 if ((sscanf(v->value, "%30d", &global_rtpholdtimeout) != 1) || (global_rtpholdtimeout < 0)) {
24781 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
24782 global_rtpholdtimeout = 0;
24783 }
24784 } else if (!strcasecmp(v->name, "rtpkeepalive")) {
24785 if ((sscanf(v->value, "%30d", &global_rtpkeepalive) != 1) || (global_rtpkeepalive < 0)) {
24786 ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d. Using default.\n", v->value, v->lineno);
24787 global_rtpkeepalive = DEFAULT_RTPKEEPALIVE;
24788 }
24789 } else if (!strcasecmp(v->name, "compactheaders")) {
24790 sip_cfg.compactheaders = ast_true(v->value);
24791 } else if (!strcasecmp(v->name, "notifymimetype")) {
24792 ast_copy_string(default_notifymime, v->value, sizeof(default_notifymime));
24793 } else if (!strcasecmp(v->name, "directrtpsetup")) {
24794 sip_cfg.directrtpsetup = ast_true(v->value);
24795 } else if (!strcasecmp(v->name, "notifyringing")) {
24796 sip_cfg.notifyringing = ast_true(v->value);
24797 } else if (!strcasecmp(v->name, "notifyhold")) {
24798 sip_cfg.notifyhold = ast_true(v->value);
24799 } else if (!strcasecmp(v->name, "notifycid")) {
24800 if (!strcasecmp(v->value, "ignore-context")) {
24801 sip_cfg.notifycid = IGNORE_CONTEXT;
24802 } else {
24803 sip_cfg.notifycid = ast_true(v->value);
24804 }
24805 } else if (!strcasecmp(v->name, "alwaysauthreject")) {
24806 sip_cfg.alwaysauthreject = ast_true(v->value);
24807 } else if (!strcasecmp(v->name, "mohinterpret")) {
24808 ast_copy_string(default_mohinterpret, v->value, sizeof(default_mohinterpret));
24809 } else if (!strcasecmp(v->name, "mohsuggest")) {
24810 ast_copy_string(default_mohsuggest, v->value, sizeof(default_mohsuggest));
24811 } else if (!strcasecmp(v->name, "language")) {
24812 ast_copy_string(default_language, v->value, sizeof(default_language));
24813 } else if (!strcasecmp(v->name, "regcontext")) {
24814 ast_copy_string(newcontexts, v->value, sizeof(newcontexts));
24815 stringp = newcontexts;
24816
24817 cleanup_stale_contexts(stringp, oldregcontext);
24818
24819 while ((context = strsep(&stringp, "&"))) {
24820 ast_copy_string(used_context, context, sizeof(used_context));
24821 ast_context_find_or_create(NULL, NULL, context, "SIP");
24822 }
24823 ast_copy_string(global_regcontext, v->value, sizeof(global_regcontext));
24824 } else if (!strcasecmp(v->name, "regextenonqualify")) {
24825 sip_cfg.regextenonqualify = ast_true(v->value);
24826 } else if (!strcasecmp(v->name, "callerid")) {
24827 ast_copy_string(default_callerid, v->value, sizeof(default_callerid));
24828 } else if (!strcasecmp(v->name, "fromdomain")) {
24829 ast_copy_string(default_fromdomain, v->value, sizeof(default_fromdomain));
24830 } else if (!strcasecmp(v->name, "outboundproxy")) {
24831 int portnum;
24832 char *tok, *proxyname;
24833
24834 if (ast_strlen_zero(v->value)) {
24835 ast_log(LOG_WARNING, "no value given for outbound proxy on line %d of sip.conf.", v->lineno);
24836 continue;
24837 }
24838
24839 tok = ast_skip_blanks(strtok(ast_strdupa(v->value), ","));
24840
24841 sip_parse_host(tok, v->lineno, &proxyname, &portnum, &sip_cfg.outboundproxy.transport);
24842
24843 sip_cfg.outboundproxy.ip.sin_port = htons(portnum);
24844
24845 if ((tok = strtok(NULL, ","))) {
24846 sip_cfg.outboundproxy.force = !strncasecmp(ast_skip_blanks(tok), "force", 5);
24847 } else {
24848 sip_cfg.outboundproxy.force = FALSE;
24849 }
24850
24851 if (ast_strlen_zero(proxyname)) {
24852 ast_log(LOG_WARNING, "you must specify a name for the outboundproxy on line %d of sip.conf.", v->lineno);
24853 sip_cfg.outboundproxy.name[0] = '\0';
24854 continue;
24855 }
24856
24857 ast_copy_string(sip_cfg.outboundproxy.name, proxyname, sizeof(sip_cfg.outboundproxy.name));
24858
24859 proxy_update(&sip_cfg.outboundproxy);
24860 } else if (!strcasecmp(v->name, "autocreatepeer")) {
24861 sip_cfg.autocreatepeer = ast_true(v->value);
24862 } else if (!strcasecmp(v->name, "match_auth_username")) {
24863 global_match_auth_username = ast_true(v->value);
24864 } else if (!strcasecmp(v->name, "srvlookup")) {
24865 sip_cfg.srvlookup = ast_true(v->value);
24866 } else if (!strcasecmp(v->name, "pedantic")) {
24867 sip_cfg.pedanticsipchecking = ast_true(v->value);
24868 } else if (!strcasecmp(v->name, "maxexpirey") || !strcasecmp(v->name, "maxexpiry")) {
24869 max_expiry = atoi(v->value);
24870 if (max_expiry < 1)
24871 max_expiry = DEFAULT_MAX_EXPIRY;
24872 } else if (!strcasecmp(v->name, "minexpirey") || !strcasecmp(v->name, "minexpiry")) {
24873 min_expiry = atoi(v->value);
24874 if (min_expiry < 1)
24875 min_expiry = DEFAULT_MIN_EXPIRY;
24876 } else if (!strcasecmp(v->name, "defaultexpiry") || !strcasecmp(v->name, "defaultexpirey")) {
24877 default_expiry = atoi(v->value);
24878 if (default_expiry < 1)
24879 default_expiry = DEFAULT_DEFAULT_EXPIRY;
24880 } else if (!strcasecmp(v->name, "mwiexpiry") || !strcasecmp(v->name, "mwiexpirey")) {
24881 mwi_expiry = atoi(v->value);
24882 if (mwi_expiry < 1)
24883 mwi_expiry = DEFAULT_MWI_EXPIRY;
24884 } else if (!strcasecmp(v->name, "sipdebug")) {
24885 if (ast_true(v->value))
24886 sipdebug |= sip_debug_config;
24887 } else if (!strcasecmp(v->name, "dumphistory")) {
24888 dumphistory = ast_true(v->value);
24889 } else if (!strcasecmp(v->name, "recordhistory")) {
24890 recordhistory = ast_true(v->value);
24891 } else if (!strcasecmp(v->name, "registertimeout")) {
24892 global_reg_timeout = atoi(v->value);
24893 if (global_reg_timeout < 1)
24894 global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
24895 } else if (!strcasecmp(v->name, "registerattempts")) {
24896 global_regattempts_max = atoi(v->value);
24897 } else if (!strcasecmp(v->name, "stunaddr")) {
24898 stunaddr.sin_port = htons(3478);
24899 if (ast_parse_arg(v->value, PARSE_INADDR, &stunaddr))
24900 ast_log(LOG_WARNING, "Invalid STUN server address: %s\n", v->value);
24901 externexpire = time(NULL);
24902 } else if (!strcasecmp(v->name, "bindaddr") || !strcasecmp(v->name, "udpbindaddr")) {
24903 if (ast_parse_arg(v->value, PARSE_INADDR, &bindaddr))
24904 ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
24905 } else if (!strcasecmp(v->name, "localnet")) {
24906 struct ast_ha *na;
24907 int ha_error = 0;
24908
24909 if (!(na = ast_append_ha("d", v->value, localaddr, &ha_error)))
24910 ast_log(LOG_WARNING, "Invalid localnet value: %s\n", v->value);
24911 else
24912 localaddr = na;
24913 if (ha_error)
24914 ast_log(LOG_ERROR, "Bad localnet configuration value line %d : %s\n", v->lineno, v->value);
24915 } else if (!strcasecmp(v->name, "externip")) {
24916 if (ast_parse_arg(v->value, PARSE_INADDR, &externip))
24917 ast_log(LOG_WARNING, "Invalid address for externip keyword: %s\n", v->value);
24918 externexpire = 0;
24919
24920 if (!externip.sin_port)
24921 externip.sin_port = bindaddr.sin_port;
24922 } else if (!strcasecmp(v->name, "externhost")) {
24923 ast_copy_string(externhost, v->value, sizeof(externhost));
24924 if (ast_parse_arg(externhost, PARSE_INADDR, &externip))
24925 ast_log(LOG_WARNING, "Invalid address for externhost keyword: %s\n", externhost);
24926 externexpire = time(NULL);
24927
24928 if (!externip.sin_port)
24929 externip.sin_port = bindaddr.sin_port;
24930 } else if (!strcasecmp(v->name, "externrefresh")) {
24931 if (sscanf(v->value, "%30d", &externrefresh) != 1) {
24932 ast_log(LOG_WARNING, "Invalid externrefresh value '%s', must be an integer >0 at line %d\n", v->value, v->lineno);
24933 externrefresh = 10;
24934 }
24935 } else if (!strcasecmp(v->name, "allow")) {
24936 int error = ast_parse_allow_disallow(&default_prefs, &global_capability, v->value, TRUE);
24937 if (error)
24938 ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
24939 } else if (!strcasecmp(v->name, "disallow")) {
24940 int error = ast_parse_allow_disallow(&default_prefs, &global_capability, v->value, FALSE);
24941 if (error)
24942 ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
24943 } else if (!strcasecmp(v->name, "autoframing")) {
24944 global_autoframing = ast_true(v->value);
24945 } else if (!strcasecmp(v->name, "allowexternaldomains")) {
24946 sip_cfg.allow_external_domains = ast_true(v->value);
24947 } else if (!strcasecmp(v->name, "autodomain")) {
24948 auto_sip_domains = ast_true(v->value);
24949 } else if (!strcasecmp(v->name, "domain")) {
24950 char *domain = ast_strdupa(v->value);
24951 char *cntx = strchr(domain, ',');
24952
24953 if (cntx)
24954 *cntx++ = '\0';
24955
24956 if (ast_strlen_zero(cntx))
24957 ast_debug(1, "No context specified at line %d for domain '%s'\n", v->lineno, domain);
24958 if (ast_strlen_zero(domain))
24959 ast_log(LOG_WARNING, "Empty domain specified at line %d\n", v->lineno);
24960 else
24961 add_sip_domain(ast_strip(domain), SIP_DOMAIN_CONFIG, cntx ? ast_strip(cntx) : "");
24962 } else if (!strcasecmp(v->name, "register")) {
24963 if (sip_register(v->value, v->lineno) == 0)
24964 registry_count++;
24965 } else if (!strcasecmp(v->name, "mwi")) {
24966 sip_subscribe_mwi(v->value, v->lineno);
24967 } else if (!strcasecmp(v->name, "tos_sip")) {
24968 if (ast_str2tos(v->value, &global_tos_sip))
24969 ast_log(LOG_WARNING, "Invalid tos_sip value at line %d, refer to QoS documentation\n", v->lineno);
24970 } else if (!strcasecmp(v->name, "tos_audio")) {
24971 if (ast_str2tos(v->value, &global_tos_audio))
24972 ast_log(LOG_WARNING, "Invalid tos_audio value at line %d, refer to QoS documentation\n", v->lineno);
24973 } else if (!strcasecmp(v->name, "tos_video")) {
24974 if (ast_str2tos(v->value, &global_tos_video))
24975 ast_log(LOG_WARNING, "Invalid tos_video value at line %d, refer to QoS documentation\n", v->lineno);
24976 } else if (!strcasecmp(v->name, "tos_text")) {
24977 if (ast_str2tos(v->value, &global_tos_text))
24978 ast_log(LOG_WARNING, "Invalid tos_text value at line %d, refer to QoS documentation\n", v->lineno);
24979 } else if (!strcasecmp(v->name, "cos_sip")) {
24980 if (ast_str2cos(v->value, &global_cos_sip))
24981 ast_log(LOG_WARNING, "Invalid cos_sip value at line %d, refer to QoS documentation\n", v->lineno);
24982 } else if (!strcasecmp(v->name, "cos_audio")) {
24983 if (ast_str2cos(v->value, &global_cos_audio))
24984 ast_log(LOG_WARNING, "Invalid cos_audio value at line %d, refer to QoS documentation\n", v->lineno);
24985 } else if (!strcasecmp(v->name, "cos_video")) {
24986 if (ast_str2cos(v->value, &global_cos_video))
24987 ast_log(LOG_WARNING, "Invalid cos_video value at line %d, refer to QoS documentation\n", v->lineno);
24988 } else if (!strcasecmp(v->name, "cos_text")) {
24989 if (ast_str2cos(v->value, &global_cos_text))
24990 ast_log(LOG_WARNING, "Invalid cos_text value at line %d, refer to QoS documentation\n", v->lineno);
24991 } else if (!strcasecmp(v->name, "bindport")) {
24992 int i;
24993 if (sscanf(v->value, "%5d", &i) == 1) {
24994 bindaddr.sin_port = htons(i);
24995 } else {
24996 ast_log(LOG_WARNING, "Invalid port number '%s' at line %d of %s\n", v->value, v->lineno, config);
24997 }
24998 } else if (!strcasecmp(v->name, "qualify")) {
24999 if (!strcasecmp(v->value, "no")) {
25000 default_qualify = 0;
25001 } else if (!strcasecmp(v->value, "yes")) {
25002 default_qualify = DEFAULT_MAXMS;
25003 } else if (sscanf(v->value, "%30d", &default_qualify) != 1) {
25004 ast_log(LOG_WARNING, "Qualification default should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", v->lineno);
25005 default_qualify = 0;
25006 }
25007 } else if (!strcasecmp(v->name, "qualifyfreq")) {
25008 int i;
25009 if (sscanf(v->value, "%30d", &i) == 1)
25010 global_qualifyfreq = i * 1000;
25011 else {
25012 ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
25013 global_qualifyfreq = DEFAULT_QUALIFYFREQ;
25014 }
25015 } else if (!strcasecmp(v->name, "callevents")) {
25016 sip_cfg.callevents = ast_true(v->value);
25017 } else if (!strcasecmp(v->name, "authfailureevents")) {
25018 global_authfailureevents = ast_true(v->value);
25019 } else if (!strcasecmp(v->name, "maxcallbitrate")) {
25020 default_maxcallbitrate = atoi(v->value);
25021 if (default_maxcallbitrate < 0)
25022 default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
25023 } else if (!strcasecmp(v->name, "matchexterniplocally")) {
25024 sip_cfg.matchexterniplocally = ast_true(v->value);
25025 } else if (!strcasecmp(v->name, "session-timers")) {
25026 int i = (int) str2stmode(v->value);
25027 if (i < 0) {
25028 ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
25029 global_st_mode = SESSION_TIMER_MODE_ACCEPT;
25030 } else {
25031 global_st_mode = i;
25032 }
25033 } else if (!strcasecmp(v->name, "session-expires")) {
25034 if (sscanf(v->value, "%30d", &global_max_se) != 1) {
25035 ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
25036 global_max_se = DEFAULT_MAX_SE;
25037 }
25038 } else if (!strcasecmp(v->name, "session-minse")) {
25039 if (sscanf(v->value, "%30d", &global_min_se) != 1) {
25040 ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
25041 global_min_se = DEFAULT_MIN_SE;
25042 }
25043 if (global_min_se < 90) {
25044 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);
25045 global_min_se = DEFAULT_MIN_SE;
25046 }
25047 } else if (!strcasecmp(v->name, "session-refresher")) {
25048 int i = (int) str2strefresher(v->value);
25049 if (i < 0) {
25050 ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
25051 global_st_refresher = SESSION_TIMER_REFRESHER_UAS;
25052 } else {
25053 global_st_refresher = i;
25054 }
25055 } else if (!strcasecmp(v->name, "qualifygap")) {
25056 if (sscanf(v->value, "%30d", &global_qualify_gap) != 1) {
25057 ast_log(LOG_WARNING, "Invalid qualifygap '%s' at line %d of %s\n", v->value, v->lineno, config);
25058 global_qualify_gap = DEFAULT_QUALIFY_GAP;
25059 }
25060 } else if (!strcasecmp(v->name, "qualifypeers")) {
25061 if (sscanf(v->value, "%30d", &global_qualify_peers) != 1) {
25062 ast_log(LOG_WARNING, "Invalid pokepeers '%s' at line %d of %s\n", v->value, v->lineno, config);
25063 global_qualify_peers = DEFAULT_QUALIFY_PEERS;
25064 }
25065 } else if (!strcasecmp(v->name, "shrinkcallerid")) {
25066 if (ast_true(v->value)) {
25067 global_shrinkcallerid = 1;
25068 } else if (ast_false(v->value)) {
25069 global_shrinkcallerid = 0;
25070 } else {
25071 ast_log(LOG_WARNING, "shrinkcallerid value %s is not valid at line %d.\n", v->value, v->lineno);
25072 }
25073 }
25074 }
25075
25076 if (!sip_cfg.allow_external_domains && AST_LIST_EMPTY(&domain_list)) {
25077 ast_log(LOG_WARNING, "To disallow external domains, you need to configure local SIP domains.\n");
25078 sip_cfg.allow_external_domains = 1;
25079 }
25080
25081 if (default_transports == 0) {
25082 default_transports = default_primary_transport = SIP_TRANSPORT_UDP;
25083 }
25084
25085
25086 for (v = ast_variable_browse(cfg, "authentication"); v ; v = v->next) {
25087
25088 if (!strcasecmp(v->name, "auth"))
25089 authl = add_realm_authentication(authl, v->value, v->lineno);
25090 }
25091
25092
25093 bindaddr.sin_family = AF_INET;
25094 internip = bindaddr;
25095 if (ast_find_ourip(&internip.sin_addr, bindaddr)) {
25096 ast_log(LOG_WARNING, "Unable to get own IP address, SIP disabled\n");
25097 ast_config_destroy(cfg);
25098 return 0;
25099 }
25100
25101 ast_mutex_lock(&netlock);
25102 if ((sipsock > -1) && (memcmp(&old_bindaddr, &bindaddr, sizeof(struct sockaddr_in)))) {
25103 close(sipsock);
25104 sipsock = -1;
25105 }
25106 if (sipsock < 0) {
25107 sipsock = socket(AF_INET, SOCK_DGRAM, 0);
25108 if (sipsock < 0) {
25109 ast_log(LOG_WARNING, "Unable to create SIP socket: %s\n", strerror(errno));
25110 ast_config_destroy(cfg);
25111 return -1;
25112 } else {
25113
25114 const int reuseFlag = 1;
25115
25116 setsockopt(sipsock, SOL_SOCKET, SO_REUSEADDR,
25117 (const char*)&reuseFlag,
25118 sizeof reuseFlag);
25119
25120 ast_enable_packet_fragmentation(sipsock);
25121
25122 if (bind(sipsock, (struct sockaddr *)&bindaddr, sizeof(bindaddr)) < 0) {
25123 ast_log(LOG_WARNING, "Failed to bind to %s:%d: %s\n",
25124 ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port),
25125 strerror(errno));
25126 close(sipsock);
25127 sipsock = -1;
25128 } else {
25129 ast_verb(2, "SIP Listening on %s:%d\n",
25130 ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port));
25131 ast_netsock_set_qos(sipsock, global_tos_sip, global_cos_sip, "SIP");
25132 }
25133 }
25134 }
25135 if (stunaddr.sin_addr.s_addr != 0) {
25136 ast_debug(1, "stun to %s:%d\n",
25137 ast_inet_ntoa(stunaddr.sin_addr) , ntohs(stunaddr.sin_port));
25138 ast_stun_request(sipsock, &stunaddr,
25139 NULL, &externip);
25140 ast_debug(1, "STUN sees us at %s:%d\n",
25141 ast_inet_ntoa(externip.sin_addr) , ntohs(externip.sin_port));
25142 }
25143 ast_mutex_unlock(&netlock);
25144
25145
25146 ast_tcptls_server_start(&sip_tcp_desc);
25147 if (sip_tcp_desc.accept_fd == -1 && sip_tcp_desc.local_address.sin_family == AF_INET) {
25148
25149 ast_log(LOG_ERROR, "SIP TCP Server start failed. Not listening on TCP socket.\n");
25150 sip_tcp_desc.local_address.sin_family = 0;
25151 } else {
25152 ast_debug(2, "SIP TCP server started\n");
25153 }
25154
25155
25156 memcpy(sip_tls_desc.tls_cfg, &default_tls_cfg, sizeof(default_tls_cfg));
25157
25158 if (ast_ssl_setup(sip_tls_desc.tls_cfg)) {
25159 ast_tcptls_server_start(&sip_tls_desc);
25160 if (default_tls_cfg.enabled && sip_tls_desc.accept_fd == -1) {
25161 ast_log(LOG_ERROR, "TLS Server start failed. Not listening on TLS socket.\n");
25162 sip_tls_desc.tls_cfg = NULL;
25163 }
25164 } else if (sip_tls_desc.tls_cfg->enabled) {
25165 sip_tls_desc.tls_cfg = NULL;
25166 ast_log(LOG_WARNING, "SIP TLS server did not load because of errors.\n");
25167 }
25168
25169 if (ucfg) {
25170 struct ast_variable *gen;
25171 int genhassip, genregistersip;
25172 const char *hassip, *registersip;
25173
25174 genhassip = ast_true(ast_variable_retrieve(ucfg, "general", "hassip"));
25175 genregistersip = ast_true(ast_variable_retrieve(ucfg, "general", "registersip"));
25176 gen = ast_variable_browse(ucfg, "general");
25177 cat = ast_category_browse(ucfg, NULL);
25178 while (cat) {
25179 if (strcasecmp(cat, "general")) {
25180 hassip = ast_variable_retrieve(ucfg, cat, "hassip");
25181 registersip = ast_variable_retrieve(ucfg, cat, "registersip");
25182 if (ast_true(hassip) || (!hassip && genhassip)) {
25183 peer = build_peer(cat, gen, ast_variable_browse(ucfg, cat), 0, 0);
25184 if (peer) {
25185
25186 peer->type = SIP_TYPE_USER | SIP_TYPE_PEER;
25187 ao2_t_link(peers, peer, "link peer into peer table");
25188 if ((peer->type & SIP_TYPE_PEER) && peer->addr.sin_addr.s_addr) {
25189 ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
25190 }
25191
25192 unref_peer(peer, "unref_peer: from reload_config");
25193 peer_count++;
25194 }
25195 }
25196 if (ast_true(registersip) || (!registersip && genregistersip)) {
25197 char tmp[256];
25198 const char *host = ast_variable_retrieve(ucfg, cat, "host");
25199 const char *username = ast_variable_retrieve(ucfg, cat, "username");
25200 const char *secret = ast_variable_retrieve(ucfg, cat, "secret");
25201 const char *contact = ast_variable_retrieve(ucfg, cat, "contact");
25202 const char *authuser = ast_variable_retrieve(ucfg, cat, "authuser");
25203 if (!host)
25204 host = ast_variable_retrieve(ucfg, "general", "host");
25205 if (!username)
25206 username = ast_variable_retrieve(ucfg, "general", "username");
25207 if (!secret)
25208 secret = ast_variable_retrieve(ucfg, "general", "secret");
25209 if (!contact)
25210 contact = "s";
25211 if (!ast_strlen_zero(username) && !ast_strlen_zero(host)) {
25212 if (!ast_strlen_zero(secret)) {
25213 if (!ast_strlen_zero(authuser)) {
25214 snprintf(tmp, sizeof(tmp), "%s?%s:%s:%s@%s/%s", cat, username, secret, authuser, host, contact);
25215 } else {
25216 snprintf(tmp, sizeof(tmp), "%s?%s:%s@%s/%s", cat, username, secret, host, contact);
25217 }
25218 } else if (!ast_strlen_zero(authuser)) {
25219 snprintf(tmp, sizeof(tmp), "%s?%s::%s@%s/%s", cat, username, authuser, host, contact);
25220 } else {
25221 snprintf(tmp, sizeof(tmp), "%s?%s@%s/%s", cat, username, host, contact);
25222 }
25223 if (sip_register(tmp, 0) == 0)
25224 registry_count++;
25225 }
25226 }
25227 }
25228 cat = ast_category_browse(ucfg, cat);
25229 }
25230 ast_config_destroy(ucfg);
25231 }
25232
25233
25234 cat = NULL;
25235 while ( (cat = ast_category_browse(cfg, cat)) ) {
25236 const char *utype;
25237 if (!strcasecmp(cat, "general") || !strcasecmp(cat, "authentication"))
25238 continue;
25239 utype = ast_variable_retrieve(cfg, cat, "type");
25240 if (!utype) {
25241 ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
25242 continue;
25243 } else {
25244 if (!strcasecmp(utype, "user")) {
25245 ;
25246 } else if (!strcasecmp(utype, "friend")) {
25247 ;
25248 } else if (!strcasecmp(utype, "peer")) {
25249 ;
25250 } else {
25251 ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, "sip.conf");
25252 continue;
25253 }
25254 peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0, 0);
25255 if (peer) {
25256 ao2_t_link(peers, peer, "link peer into peers table");
25257 if ((peer->type & SIP_TYPE_PEER) && peer->addr.sin_addr.s_addr) {
25258 ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
25259 }
25260 unref_peer(peer, "unref the result of the build_peer call. Now, the links from the tables are the only ones left.");
25261 peer_count++;
25262 }
25263 }
25264 }
25265
25266
25267
25268
25269
25270
25271 if (auto_sip_domains) {
25272 char temp[MAXHOSTNAMELEN];
25273
25274
25275 if (bindaddr.sin_addr.s_addr) {
25276 add_sip_domain(ast_inet_ntoa(bindaddr.sin_addr), SIP_DOMAIN_AUTO, NULL);
25277 } else if (internip.sin_addr.s_addr) {
25278
25279 add_sip_domain(ast_inet_ntoa(internip.sin_addr), SIP_DOMAIN_AUTO, NULL);
25280 } else {
25281 ast_log(LOG_NOTICE, "Can't add wildcard IP address to domain list, please add IP address to domain manually.\n");
25282 }
25283
25284
25285 if (sip_tcp_desc.local_address.sin_addr.s_addr && !inaddrcmp(&bindaddr, &sip_tcp_desc.local_address))
25286 add_sip_domain(ast_inet_ntoa(sip_tcp_desc.local_address.sin_addr), SIP_DOMAIN_AUTO, NULL);
25287
25288
25289 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))
25290 add_sip_domain(ast_inet_ntoa(sip_tls_desc.local_address.sin_addr), SIP_DOMAIN_AUTO, NULL);
25291
25292
25293 if (externip.sin_addr.s_addr)
25294 add_sip_domain(ast_inet_ntoa(externip.sin_addr), SIP_DOMAIN_AUTO, NULL);
25295
25296
25297 if (!ast_strlen_zero(externhost))
25298 add_sip_domain(externhost, SIP_DOMAIN_AUTO, NULL);
25299
25300
25301 if (!gethostname(temp, sizeof(temp)))
25302 add_sip_domain(temp, SIP_DOMAIN_AUTO, NULL);
25303 }
25304
25305
25306 ast_config_destroy(cfg);
25307
25308
25309 if (notify_types)
25310 ast_config_destroy(notify_types);
25311 if ((notify_types = ast_config_load(notify_config, config_flags)) == CONFIG_STATUS_FILEINVALID) {
25312 ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed.\n", notify_config);
25313 notify_types = NULL;
25314 }
25315
25316
25317 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);
25318 run_end = time(0);
25319 ast_debug(4, "SIP reload_config done...Runtime= %d sec\n", (int)(run_end-run_start));
25320
25321 return 0;
25322 }
25323
25324 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan)
25325 {
25326 struct sip_pvt *p;
25327 struct ast_udptl *udptl = NULL;
25328
25329 p = chan->tech_pvt;
25330 if (!p)
25331 return NULL;
25332
25333 sip_pvt_lock(p);
25334 if (p->udptl && ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA))
25335 udptl = p->udptl;
25336 sip_pvt_unlock(p);
25337 return udptl;
25338 }
25339
25340 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl)
25341 {
25342 struct sip_pvt *p;
25343
25344 p = chan->tech_pvt;
25345 if (!p)
25346 return -1;
25347 sip_pvt_lock(p);
25348 if (udptl)
25349 ast_udptl_get_peer(udptl, &p->udptlredirip);
25350 else
25351 memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
25352 if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
25353 if (!p->pendinginvite) {
25354 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);
25355 transmit_reinvite_with_sdp(p, TRUE, FALSE);
25356 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
25357 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);
25358 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
25359 }
25360 }
25361
25362 p->lastrtprx = p->lastrtptx = time(NULL);
25363 sip_pvt_unlock(p);
25364 return 0;
25365 }
25366
25367
25368 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
25369 {
25370 struct sip_pvt *p = NULL;
25371 enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
25372
25373 if (!(p = chan->tech_pvt))
25374 return AST_RTP_GET_FAILED;
25375
25376 sip_pvt_lock(p);
25377 if (!(p->rtp)) {
25378 sip_pvt_unlock(p);
25379 return AST_RTP_GET_FAILED;
25380 }
25381
25382 *rtp = p->rtp;
25383
25384 if (ast_rtp_getnat(*rtp) && !ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA_NAT))
25385 res = AST_RTP_TRY_PARTIAL;
25386 else if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA))
25387 res = AST_RTP_TRY_NATIVE;
25388 else if (ast_test_flag(&global_jbconf, AST_JB_FORCED))
25389 res = AST_RTP_GET_FAILED;
25390
25391 sip_pvt_unlock(p);
25392
25393 return res;
25394 }
25395
25396
25397 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
25398 {
25399 struct sip_pvt *p = NULL;
25400 enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
25401
25402 if (!(p = chan->tech_pvt))
25403 return AST_RTP_GET_FAILED;
25404
25405 sip_pvt_lock(p);
25406 if (!(p->vrtp)) {
25407 sip_pvt_unlock(p);
25408 return AST_RTP_GET_FAILED;
25409 }
25410
25411 *rtp = p->vrtp;
25412
25413 if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA))
25414 res = AST_RTP_TRY_NATIVE;
25415
25416 sip_pvt_unlock(p);
25417
25418 return res;
25419 }
25420
25421
25422 static enum ast_rtp_get_result sip_get_trtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
25423 {
25424 struct sip_pvt *p = NULL;
25425 enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
25426
25427 if (!(p = chan->tech_pvt))
25428 return AST_RTP_GET_FAILED;
25429
25430 sip_pvt_lock(p);
25431 if (!(p->trtp)) {
25432 sip_pvt_unlock(p);
25433 return AST_RTP_GET_FAILED;
25434 }
25435
25436 *rtp = p->trtp;
25437
25438 if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA))
25439 res = AST_RTP_TRY_NATIVE;
25440
25441 sip_pvt_unlock(p);
25442
25443 return res;
25444 }
25445
25446
25447 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)
25448 {
25449 struct sip_pvt *p;
25450 int changed = 0;
25451
25452 p = chan->tech_pvt;
25453 if (!p)
25454 return -1;
25455
25456
25457 if (!ast_bridged_channel(chan) && !sip_cfg.directrtpsetup)
25458 return 0;
25459
25460 sip_pvt_lock(p);
25461 if (p->alreadygone) {
25462
25463 sip_pvt_unlock(p);
25464 return 0;
25465 }
25466
25467
25468
25469
25470 if (nat_active && !ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA_NAT)) {
25471 sip_pvt_unlock(p);
25472 return 0;
25473 }
25474
25475 if (rtp) {
25476 changed |= ast_rtp_get_peer(rtp, &p->redirip);
25477 } else if (p->redirip.sin_addr.s_addr || ntohs(p->redirip.sin_port) != 0) {
25478 memset(&p->redirip, 0, sizeof(p->redirip));
25479 changed = 1;
25480 }
25481 if (vrtp) {
25482 changed |= ast_rtp_get_peer(vrtp, &p->vredirip);
25483 } else if (p->vredirip.sin_addr.s_addr || ntohs(p->vredirip.sin_port) != 0) {
25484 memset(&p->vredirip, 0, sizeof(p->vredirip));
25485 changed = 1;
25486 }
25487 if (trtp) {
25488 changed |= ast_rtp_get_peer(trtp, &p->tredirip);
25489 } else if (p->tredirip.sin_addr.s_addr || ntohs(p->tredirip.sin_port) != 0) {
25490 memset(&p->tredirip, 0, sizeof(p->tredirip));
25491 changed = 1;
25492 }
25493 if (codecs && (p->redircodecs != codecs)) {
25494 p->redircodecs = codecs;
25495 changed = 1;
25496 }
25497 if (changed && !ast_test_flag(&p->flags[0], SIP_GOTREFER) && !ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
25498 if (chan->_state != AST_STATE_UP) {
25499 if (p->do_history)
25500 append_history(p, "ExtInv", "Initial invite sent with remote bridge proposal.");
25501 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));
25502 } else if (!p->pendinginvite) {
25503 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));
25504 transmit_reinvite_with_sdp(p, FALSE, FALSE);
25505 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
25506 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));
25507
25508 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
25509 }
25510 }
25511
25512 p->lastrtprx = p->lastrtptx = time(NULL);
25513 sip_pvt_unlock(p);
25514 return 0;
25515 }
25516
25517 static char *app_dtmfmode = "SIPDtmfMode";
25518 static char *app_sipaddheader = "SIPAddHeader";
25519 static char *app_sipremoveheader = "SIPRemoveHeader";
25520
25521
25522 static int sip_dtmfmode(struct ast_channel *chan, void *data)
25523 {
25524 struct sip_pvt *p;
25525 char *mode = data;
25526
25527 if (!data) {
25528 ast_log(LOG_WARNING, "This application requires the argument: info, inband, rfc2833\n");
25529 return 0;
25530 }
25531 ast_channel_lock(chan);
25532 if (!IS_SIP_TECH(chan->tech)) {
25533 ast_log(LOG_WARNING, "Call this application only on SIP incoming calls\n");
25534 ast_channel_unlock(chan);
25535 return 0;
25536 }
25537 p = chan->tech_pvt;
25538 if (!p) {
25539 ast_channel_unlock(chan);
25540 return 0;
25541 }
25542 sip_pvt_lock(p);
25543 if (!strcasecmp(mode, "info")) {
25544 ast_clear_flag(&p->flags[0], SIP_DTMF);
25545 ast_set_flag(&p->flags[0], SIP_DTMF_INFO);
25546 p->jointnoncodeccapability &= ~AST_RTP_DTMF;
25547 } else if (!strcasecmp(mode, "shortinfo")) {
25548 ast_clear_flag(&p->flags[0], SIP_DTMF);
25549 ast_set_flag(&p->flags[0], SIP_DTMF_SHORTINFO);
25550 p->jointnoncodeccapability &= ~AST_RTP_DTMF;
25551 } else if (!strcasecmp(mode, "rfc2833")) {
25552 ast_clear_flag(&p->flags[0], SIP_DTMF);
25553 ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
25554 p->jointnoncodeccapability |= AST_RTP_DTMF;
25555 } else if (!strcasecmp(mode, "inband")) {
25556 ast_clear_flag(&p->flags[0], SIP_DTMF);
25557 ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
25558 p->jointnoncodeccapability &= ~AST_RTP_DTMF;
25559 } else
25560 ast_log(LOG_WARNING, "I don't know about this dtmf mode: %s\n", mode);
25561 if (p->rtp)
25562 ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
25563 if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
25564 if (!p->dsp) {
25565 p->dsp = ast_dsp_new();
25566 ast_dsp_set_features(p->dsp, DSP_FEATURE_DIGIT_DETECT);
25567 }
25568 } else {
25569 if (p->dsp) {
25570 ast_dsp_free(p->dsp);
25571 p->dsp = NULL;
25572 }
25573 }
25574 sip_pvt_unlock(p);
25575 ast_channel_unlock(chan);
25576 return 0;
25577 }
25578
25579
25580 static int sip_addheader(struct ast_channel *chan, void *data)
25581 {
25582 int no = 0;
25583 int ok = FALSE;
25584 char varbuf[30];
25585 char *inbuf = data, *subbuf;
25586
25587 if (ast_strlen_zero(inbuf)) {
25588 ast_log(LOG_WARNING, "This application requires the argument: Header\n");
25589 return 0;
25590 }
25591 ast_channel_lock(chan);
25592
25593
25594 while (!ok && no <= 50) {
25595 no++;
25596 snprintf(varbuf, sizeof(varbuf), "__SIPADDHEADER%.2d", no);
25597
25598
25599 if ((pbx_builtin_getvar_helper(chan, (const char *) varbuf + 2) == (const char *) NULL)) {
25600 ok = TRUE;
25601 }
25602 }
25603 if (ok) {
25604 size_t len = strlen(inbuf);
25605 subbuf = alloca(len + 1);
25606 ast_get_encoded_str(inbuf, subbuf, len + 1);
25607 pbx_builtin_setvar_helper(chan, varbuf, subbuf);
25608 if (sipdebug) {
25609 ast_debug(1, "SIP Header added \"%s\" as %s\n", inbuf, varbuf);
25610 }
25611 } else {
25612 ast_log(LOG_WARNING, "Too many SIP headers added, max 50\n");
25613 }
25614 ast_channel_unlock(chan);
25615 return 0;
25616 }
25617
25618
25619 static int sip_removeheader(struct ast_channel *chan, void *data)
25620 {
25621 struct ast_var_t *newvariable;
25622 struct varshead *headp;
25623 int removeall = 0;
25624 char *inbuf = (char *) data;
25625
25626 if (ast_strlen_zero(inbuf)) {
25627 removeall = 1;
25628 }
25629 ast_channel_lock(chan);
25630
25631 headp=&chan->varshead;
25632 AST_LIST_TRAVERSE_SAFE_BEGIN (headp, newvariable, entries) {
25633 if (strncasecmp(ast_var_name(newvariable), "SIPADDHEADER", strlen("SIPADDHEADER")) == 0) {
25634 if (removeall || (!strncasecmp(ast_var_value(newvariable),inbuf,strlen(inbuf)))) {
25635 if (sipdebug)
25636 ast_log(LOG_DEBUG,"removing SIP Header \"%s\" as %s\n",
25637 ast_var_value(newvariable),
25638 ast_var_name(newvariable));
25639 AST_LIST_REMOVE_CURRENT(entries);
25640 ast_var_delete(newvariable);
25641 }
25642 }
25643 }
25644 AST_LIST_TRAVERSE_SAFE_END;
25645
25646 ast_channel_unlock(chan);
25647 return 0;
25648 }
25649
25650
25651
25652
25653
25654
25655
25656 static int sip_sipredirect(struct sip_pvt *p, const char *dest)
25657 {
25658 char *cdest;
25659 char *extension, *host, *port;
25660 char tmp[80];
25661
25662 cdest = ast_strdupa(dest);
25663
25664 extension = strsep(&cdest, "@");
25665 host = strsep(&cdest, ":");
25666 port = strsep(&cdest, ":");
25667 if (ast_strlen_zero(extension)) {
25668 ast_log(LOG_ERROR, "Missing mandatory argument: extension\n");
25669 return 0;
25670 }
25671
25672
25673 if (!host) {
25674 char *localtmp;
25675
25676 ast_copy_string(tmp, get_header(&p->initreq, "To"), sizeof(tmp));
25677 if (ast_strlen_zero(tmp)) {
25678 ast_log(LOG_ERROR, "Cannot retrieve the 'To' header from the original SIP request!\n");
25679 return 0;
25680 }
25681 if ( ( (localtmp = strcasestr(tmp, "sip:")) || (localtmp = strcasestr(tmp, "sips:")) )
25682 && (localtmp = strchr(localtmp, '@'))) {
25683 char lhost[80], lport[80];
25684
25685 memset(lhost, 0, sizeof(lhost));
25686 memset(lport, 0, sizeof(lport));
25687 localtmp++;
25688
25689 sscanf(localtmp, "%80[^<>:; ]:%80[^<>:; ]", lhost, lport);
25690 if (ast_strlen_zero(lhost)) {
25691 ast_log(LOG_ERROR, "Can't find the host address\n");
25692 return 0;
25693 }
25694 host = ast_strdupa(lhost);
25695 if (!ast_strlen_zero(lport)) {
25696 port = ast_strdupa(lport);
25697 }
25698 }
25699 }
25700
25701 ast_string_field_build(p, our_contact, "Transfer <sip:%s@%s%s%s>", extension, host, port ? ":" : "", port ? port : "");
25702 transmit_response_reliable(p, "302 Moved Temporarily", &p->initreq);
25703
25704 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
25705 sip_alreadygone(p);
25706
25707 return 0;
25708 }
25709
25710
25711 static int sip_get_codec(struct ast_channel *chan)
25712 {
25713 struct sip_pvt *p = chan->tech_pvt;
25714 return p->jointcapability ? p->jointcapability : p->capability;
25715 }
25716
25717
25718 static void sip_poke_all_peers(void)
25719 {
25720 int ms = 0, num = 0;
25721 struct ao2_iterator i;
25722 struct sip_peer *peer;
25723
25724 if (!speerobjs)
25725 return;
25726
25727 i = ao2_iterator_init(peers, 0);
25728 while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
25729 ao2_lock(peer);
25730 if (num == global_qualify_peers) {
25731 ms += global_qualify_gap;
25732 num = 0;
25733 } else {
25734 num++;
25735 }
25736 AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, ms, sip_poke_peer_s, peer,
25737 unref_peer(_data, "removing poke peer ref"),
25738 unref_peer(peer, "removing poke peer ref"),
25739 ref_peer(peer, "adding poke peer ref"));
25740 ao2_unlock(peer);
25741 unref_peer(peer, "toss iterator peer ptr");
25742 }
25743 ao2_iterator_destroy(&i);
25744 }
25745
25746
25747 static void sip_send_all_registers(void)
25748 {
25749 int ms;
25750 int regspacing;
25751 if (!regobjs)
25752 return;
25753 regspacing = default_expiry * 1000/regobjs;
25754 if (regspacing > 100)
25755 regspacing = 100;
25756 ms = regspacing;
25757 ASTOBJ_CONTAINER_TRAVERSE(®l, 1, do {
25758 ASTOBJ_WRLOCK(iterator);
25759 ms += regspacing;
25760 AST_SCHED_REPLACE_UNREF(iterator->expire, sched, ms, sip_reregister, iterator,
25761 registry_unref(_data, "REPLACE sched del decs the refcount"),
25762 registry_unref(iterator, "REPLACE sched add failure decs the refcount"),
25763 registry_addref(iterator, "REPLACE sched add incs the refcount"));
25764 ASTOBJ_UNLOCK(iterator);
25765 } while (0)
25766 );
25767 }
25768
25769
25770 static void sip_send_all_mwi_subscriptions(void)
25771 {
25772 ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
25773 ASTOBJ_WRLOCK(iterator);
25774 AST_SCHED_DEL(sched, iterator->resub);
25775 if ((iterator->resub = ast_sched_add(sched, 1, sip_subscribe_mwi_do, ASTOBJ_REF(iterator))) < 0) {
25776 ASTOBJ_UNREF(iterator, sip_subscribe_mwi_destroy);
25777 }
25778 ASTOBJ_UNLOCK(iterator);
25779 } while (0));
25780 }
25781
25782
25783 static int sip_do_reload(enum channelreloadreason reason)
25784 {
25785 time_t start_poke, end_poke;
25786
25787 reload_config(reason);
25788 ast_sched_dump(sched);
25789
25790 start_poke = time(0);
25791
25792 ao2_t_callback(peers, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, peer_is_marked, NULL,
25793 "callback to remove marked peers");
25794
25795 ast_debug(4, "--------------- Done destroying pruned peers\n");
25796
25797
25798 sip_poke_all_peers();
25799
25800
25801 sip_send_all_registers();
25802
25803 sip_send_all_mwi_subscriptions();
25804
25805 end_poke = time(0);
25806
25807 ast_debug(4, "do_reload finished. peer poke/prune reg contact time = %d sec.\n", (int)(end_poke-start_poke));
25808
25809 ast_debug(4, "--------------- SIP reload done\n");
25810
25811 return 0;
25812 }
25813
25814
25815 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
25816 {
25817
25818 switch (cmd) {
25819 case CLI_INIT:
25820 e->command = "sip reload";
25821 e->usage =
25822 "Usage: sip reload\n"
25823 " Reloads SIP configuration from sip.conf\n";
25824 return NULL;
25825 case CLI_GENERATE:
25826 return NULL;
25827 }
25828
25829 ast_mutex_lock(&sip_reload_lock);
25830 if (sip_reloading)
25831 ast_verbose("Previous SIP reload not yet done\n");
25832 else {
25833 sip_reloading = TRUE;
25834 sip_reloadreason = (a && a->fd) ? CHANNEL_CLI_RELOAD : CHANNEL_MODULE_RELOAD;
25835 }
25836 ast_mutex_unlock(&sip_reload_lock);
25837 restart_monitor();
25838
25839 return CLI_SUCCESS;
25840 }
25841
25842
25843 static int reload(void)
25844 {
25845 if (sip_reload(0, 0, NULL))
25846 return 0;
25847 return 1;
25848 }
25849
25850
25851 static struct ast_cli_entry cli_sip[] = {
25852 AST_CLI_DEFINE(sip_show_channels, "List active SIP channels or subscriptions"),
25853 AST_CLI_DEFINE(sip_show_channelstats, "List statistics for active SIP channels"),
25854 AST_CLI_DEFINE(sip_show_domains, "List our local SIP domains"),
25855 AST_CLI_DEFINE(sip_show_inuse, "List all inuse/limits"),
25856 AST_CLI_DEFINE(sip_show_objects, "List all SIP object allocations"),
25857 AST_CLI_DEFINE(sip_show_peers, "List defined SIP peers"),
25858 AST_CLI_DEFINE(sip_show_registry, "List SIP registration status"),
25859 AST_CLI_DEFINE(sip_unregister, "Unregister (force expiration) a SIP peer from the registry"),
25860 AST_CLI_DEFINE(sip_show_settings, "Show SIP global settings"),
25861 AST_CLI_DEFINE(sip_show_mwi, "Show MWI subscriptions"),
25862 AST_CLI_DEFINE(sip_cli_notify, "Send a notify packet to a SIP peer"),
25863 AST_CLI_DEFINE(sip_show_channel, "Show detailed SIP channel info"),
25864 AST_CLI_DEFINE(sip_show_history, "Show SIP dialog history"),
25865 AST_CLI_DEFINE(sip_show_peer, "Show details on specific SIP peer"),
25866 AST_CLI_DEFINE(sip_show_users, "List defined SIP users"),
25867 AST_CLI_DEFINE(sip_show_user, "Show details on specific SIP user"),
25868 AST_CLI_DEFINE(sip_qualify_peer, "Send an OPTIONS packet to a peer"),
25869 AST_CLI_DEFINE(sip_show_sched, "Present a report on the status of the sched queue"),
25870 AST_CLI_DEFINE(sip_prune_realtime, "Prune cached Realtime users/peers"),
25871 AST_CLI_DEFINE(sip_do_debug, "Enable/Disable SIP debugging"),
25872 AST_CLI_DEFINE(sip_set_history, "Enable/Disable SIP history"),
25873 AST_CLI_DEFINE(sip_reload, "Reload SIP configuration"),
25874 AST_CLI_DEFINE(sip_show_tcp, "List TCP Connections")
25875 };
25876
25877
25878 static int load_module(void)
25879 {
25880 ast_verbose("SIP channel loading...\n");
25881
25882
25883 peers = ao2_t_container_alloc(HASH_PEER_SIZE, peer_hash_cb, peer_cmp_cb, "allocate peers");
25884 peers_by_ip = ao2_t_container_alloc(HASH_PEER_SIZE, peer_iphash_cb, peer_ipcmp_cb, "allocate peers_by_ip");
25885 dialogs = ao2_t_container_alloc(HASH_DIALOG_SIZE, dialog_hash_cb, dialog_cmp_cb, "allocate dialogs");
25886 threadt = ao2_t_container_alloc(HASH_DIALOG_SIZE, threadt_hash_cb, threadt_cmp_cb, "allocate threadt table");
25887
25888 ASTOBJ_CONTAINER_INIT(®l);
25889 ASTOBJ_CONTAINER_INIT(&submwil);
25890
25891 if (!(sched = sched_context_create())) {
25892 ast_log(LOG_ERROR, "Unable to create scheduler context\n");
25893 return AST_MODULE_LOAD_FAILURE;
25894 }
25895
25896 if (!(io = io_context_create())) {
25897 ast_log(LOG_ERROR, "Unable to create I/O context\n");
25898 sched_context_destroy(sched);
25899 return AST_MODULE_LOAD_FAILURE;
25900 }
25901
25902 sip_reloadreason = CHANNEL_MODULE_LOAD;
25903
25904 if(reload_config(sip_reloadreason))
25905 return AST_MODULE_LOAD_DECLINE;
25906
25907
25908
25909
25910
25911 memcpy(&sip_tech_info, &sip_tech, sizeof(sip_tech));
25912 memset((void *) &sip_tech_info.send_digit_begin, 0, sizeof(sip_tech_info.send_digit_begin));
25913
25914
25915 if (ast_channel_register(&sip_tech)) {
25916 ast_log(LOG_ERROR, "Unable to register channel type 'SIP'\n");
25917 io_context_destroy(io);
25918 sched_context_destroy(sched);
25919 return AST_MODULE_LOAD_FAILURE;
25920 }
25921
25922
25923 ast_cli_register_multiple(cli_sip, ARRAY_LEN(cli_sip));
25924
25925
25926 ast_rtp_proto_register(&sip_rtp);
25927
25928
25929 ast_udptl_proto_register(&sip_udptl);
25930
25931
25932 ast_register_application_xml(app_dtmfmode, sip_dtmfmode);
25933 ast_register_application_xml(app_sipaddheader, sip_addheader);
25934 ast_register_application_xml(app_sipremoveheader, sip_removeheader);
25935
25936
25937 ast_custom_function_register(&sip_header_function);
25938 ast_custom_function_register(&sippeer_function);
25939 ast_custom_function_register(&sipchaninfo_function);
25940 ast_custom_function_register(&checksipdomain_function);
25941
25942
25943 ast_manager_register2("SIPpeers", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peers,
25944 "List SIP peers (text format)", mandescr_show_peers);
25945 ast_manager_register2("SIPshowpeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peer,
25946 "Show SIP peer (text format)", mandescr_show_peer);
25947 ast_manager_register2("SIPqualifypeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_qualify_peer,
25948 "Show SIP peer (text format)", mandescr_show_peer);
25949 ast_manager_register2("SIPshowregistry", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_show_registry,
25950 "Show SIP registrations (text format)", mandescr_show_registry);
25951 ast_manager_register2("SIPnotify", EVENT_FLAG_SYSTEM, manager_sipnotify,
25952 "Send a SIP notify", mandescr_sipnotify);
25953 sip_poke_all_peers();
25954 sip_send_all_registers();
25955 sip_send_all_mwi_subscriptions();
25956
25957
25958 restart_monitor();
25959
25960 ast_realtime_require_field(ast_check_realtime("sipregs") ? "sipregs" : "sippeers",
25961 "name", RQ_CHAR, 10,
25962 "ipaddr", RQ_CHAR, 15,
25963 "port", RQ_UINTEGER2, 5,
25964 "regseconds", RQ_INTEGER4, 11,
25965 "defaultuser", RQ_CHAR, 10,
25966 "fullcontact", RQ_CHAR, 35,
25967 "regserver", RQ_CHAR, 20,
25968 "useragent", RQ_CHAR, 20,
25969 "lastms", RQ_INTEGER4, 11,
25970 SENTINEL);
25971
25972 return AST_MODULE_LOAD_SUCCESS;
25973 }
25974
25975
25976 static int unload_module(void)
25977 {
25978 struct sip_pvt *p;
25979 struct sip_threadinfo *th;
25980 struct ast_context *con;
25981 struct ao2_iterator i;
25982
25983 ast_sched_dump(sched);
25984
25985
25986 ast_channel_unregister(&sip_tech);
25987
25988
25989 ast_custom_function_unregister(&sipchaninfo_function);
25990 ast_custom_function_unregister(&sippeer_function);
25991 ast_custom_function_unregister(&sip_header_function);
25992 ast_custom_function_unregister(&checksipdomain_function);
25993
25994
25995 ast_unregister_application(app_dtmfmode);
25996 ast_unregister_application(app_sipaddheader);
25997 ast_unregister_application(app_sipremoveheader);
25998
25999
26000 ast_cli_unregister_multiple(cli_sip, ARRAY_LEN(cli_sip));
26001
26002
26003 ast_rtp_proto_unregister(&sip_rtp);
26004
26005
26006 ast_udptl_proto_unregister(&sip_udptl);
26007
26008
26009 ast_manager_unregister("SIPpeers");
26010 ast_manager_unregister("SIPshowpeer");
26011 ast_manager_unregister("SIPqualifypeer");
26012 ast_manager_unregister("SIPshowregistry");
26013 ast_manager_unregister("SIPnotify");
26014
26015
26016 if (sip_tcp_desc.master)
26017 ast_tcptls_server_stop(&sip_tcp_desc);
26018 if (sip_tls_desc.master)
26019 ast_tcptls_server_stop(&sip_tls_desc);
26020
26021
26022 i = ao2_iterator_init(threadt, 0);
26023 while ((th = ao2_t_iterator_next(&i, "iterate through tcp threads for 'sip show tcp'"))) {
26024 pthread_t thread = th->threadid;
26025 th->stop = 1;
26026 pthread_kill(thread, SIGURG);
26027 pthread_join(thread, NULL);
26028 ao2_t_ref(th, -1, "decrement ref from iterator");
26029 }
26030 ao2_iterator_destroy(&i);
26031
26032
26033 i = ao2_iterator_init(dialogs, 0);
26034 while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
26035 if (p->owner)
26036 ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
26037 ao2_t_ref(p, -1, "toss dialog ptr from iterator_next");
26038 }
26039 ao2_iterator_destroy(&i);
26040
26041 ast_mutex_lock(&monlock);
26042 if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP) && (monitor_thread != AST_PTHREADT_NULL)) {
26043 pthread_cancel(monitor_thread);
26044 pthread_kill(monitor_thread, SIGURG);
26045 pthread_join(monitor_thread, NULL);
26046 }
26047 monitor_thread = AST_PTHREADT_STOP;
26048 ast_mutex_unlock(&monlock);
26049
26050
26051 i = ao2_iterator_init(dialogs, 0);
26052 while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
26053 dialog_unlink_all(p, TRUE, TRUE);
26054 ao2_t_ref(p, -1, "throw away iterator result");
26055 }
26056 ao2_iterator_destroy(&i);
26057
26058
26059 ast_free_ha(localaddr);
26060
26061 clear_realm_authentication(authl);
26062
26063
26064 if (default_tls_cfg.certfile)
26065 ast_free(default_tls_cfg.certfile);
26066 if (default_tls_cfg.cipher)
26067 ast_free(default_tls_cfg.cipher);
26068 if (default_tls_cfg.cafile)
26069 ast_free(default_tls_cfg.cafile);
26070 if (default_tls_cfg.capath)
26071 ast_free(default_tls_cfg.capath);
26072
26073 ASTOBJ_CONTAINER_DESTROYALL(®l, sip_registry_destroy);
26074 ASTOBJ_CONTAINER_DESTROY(®l);
26075 ASTOBJ_CONTAINER_DESTROYALL(&submwil, sip_subscribe_mwi_destroy);
26076 ASTOBJ_CONTAINER_DESTROY(&submwil);
26077
26078 ao2_t_ref(peers, -1, "unref the peers table");
26079 ao2_t_ref(peers_by_ip, -1, "unref the peers_by_ip table");
26080 ao2_t_ref(dialogs, -1, "unref the dialogs table");
26081 ao2_t_ref(threadt, -1, "unref the thread table");
26082
26083 clear_sip_domains();
26084 ast_free_ha(global_contact_ha);
26085 close(sipsock);
26086 sched_context_destroy(sched);
26087 con = ast_context_find(used_context);
26088 if (con)
26089 ast_context_destroy(con, "SIP");
26090 ast_unload_realtime("sipregs");
26091 ast_unload_realtime("sippeers");
26092
26093 return 0;
26094 }
26095
26096 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Session Initiation Protocol (SIP)",
26097 .load = load_module,
26098 .unload = unload_module,
26099 .reload = reload,
26100 );