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
00209
00210
00211 #include "asterisk.h"
00212
00213 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 412873 $")
00214
00215 #include <signal.h>
00216 #include <sys/signal.h>
00217 #include <regex.h>
00218 #include <inttypes.h>
00219
00220 #include "asterisk/network.h"
00221 #include "asterisk/paths.h"
00222
00223
00224
00225
00226
00227
00228
00229
00230
00231
00232
00233
00234
00235
00236
00237 #include "asterisk/lock.h"
00238 #include "asterisk/config.h"
00239 #include "asterisk/module.h"
00240 #include "asterisk/pbx.h"
00241 #include "asterisk/sched.h"
00242 #include "asterisk/io.h"
00243 #include "asterisk/rtp_engine.h"
00244 #include "asterisk/udptl.h"
00245 #include "asterisk/acl.h"
00246 #include "asterisk/manager.h"
00247 #include "asterisk/callerid.h"
00248 #include "asterisk/cli.h"
00249 #include "asterisk/musiconhold.h"
00250 #include "asterisk/dsp.h"
00251 #include "asterisk/features.h"
00252 #include "asterisk/srv.h"
00253 #include "asterisk/astdb.h"
00254 #include "asterisk/causes.h"
00255 #include "asterisk/utils.h"
00256 #include "asterisk/file.h"
00257 #include "asterisk/astobj2.h"
00258 #include "asterisk/dnsmgr.h"
00259 #include "asterisk/devicestate.h"
00260 #include "asterisk/monitor.h"
00261 #include "asterisk/netsock2.h"
00262 #include "asterisk/localtime.h"
00263 #include "asterisk/abstract_jb.h"
00264 #include "asterisk/threadstorage.h"
00265 #include "asterisk/translate.h"
00266 #include "asterisk/ast_version.h"
00267 #include "asterisk/event.h"
00268 #include "asterisk/cel.h"
00269 #include "asterisk/data.h"
00270 #include "asterisk/aoc.h"
00271 #include "asterisk/message.h"
00272 #include "sip/include/sip.h"
00273 #include "sip/include/globals.h"
00274 #include "sip/include/config_parser.h"
00275 #include "sip/include/reqresp_parser.h"
00276 #include "sip/include/sip_utils.h"
00277 #include "sip/include/srtp.h"
00278 #include "sip/include/sdp_crypto.h"
00279 #include "asterisk/ccss.h"
00280 #include "asterisk/xml.h"
00281 #include "sip/include/dialog.h"
00282 #include "sip/include/dialplan_functions.h"
00283 #include "sip/include/security_events.h"
00284 #include "asterisk/sip_api.h"
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
00477
00478
00479
00480
00481
00482
00483
00484
00485
00486
00487
00488
00489
00490
00491
00492
00493
00494
00495
00496
00497
00498
00499
00500
00501
00502
00503
00504
00505
00506
00507
00508
00509
00510
00511
00512
00513
00514
00515
00516
00517
00518
00519
00520
00521
00522
00523
00524
00525
00526
00527
00528
00529
00530
00531
00532
00533
00534
00535
00536
00537
00538
00539
00540
00541
00542
00543
00544
00545
00546
00547
00548
00549
00550
00551
00552
00553
00554
00555
00556
00557
00558
00559
00560
00561
00562
00563
00564
00565
00566
00567
00568
00569
00570
00571
00572
00573
00574
00575
00576
00577
00578
00579
00580
00581
00582
00583
00584
00585
00586
00587
00588
00589
00590
00591
00592
00593
00594
00595
00596
00597
00598
00599
00600
00601
00602
00603
00604
00605
00606
00607
00608
00609 static int min_expiry = DEFAULT_MIN_EXPIRY;
00610 static int max_expiry = DEFAULT_MAX_EXPIRY;
00611 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
00612 static int min_subexpiry = DEFAULT_MIN_EXPIRY;
00613 static int max_subexpiry = DEFAULT_MAX_EXPIRY;
00614 static int mwi_expiry = DEFAULT_MWI_EXPIRY;
00615
00616 static int unauth_sessions = 0;
00617 static int authlimit = DEFAULT_AUTHLIMIT;
00618 static int authtimeout = DEFAULT_AUTHTIMEOUT;
00619
00620
00621
00622 static struct ast_jb_conf default_jbconf =
00623 {
00624 .flags = 0,
00625 .max_size = 200,
00626 .resync_threshold = 1000,
00627 .impl = "fixed",
00628 .target_extra = 40,
00629 };
00630 static struct ast_jb_conf global_jbconf;
00631
00632 static const char config[] = "sip.conf";
00633 static const char notify_config[] = "sip_notify.conf";
00634
00635
00636
00637 static const struct invstate2stringtable {
00638 const enum invitestates state;
00639 const char *desc;
00640 } invitestate2string[] = {
00641 {INV_NONE, "None" },
00642 {INV_CALLING, "Calling (Trying)"},
00643 {INV_PROCEEDING, "Proceeding "},
00644 {INV_EARLY_MEDIA, "Early media"},
00645 {INV_COMPLETED, "Completed (done)"},
00646 {INV_CONFIRMED, "Confirmed (up)"},
00647 {INV_TERMINATED, "Done"},
00648 {INV_CANCELLED, "Cancelled"}
00649 };
00650
00651
00652
00653
00654
00655
00656 static const struct cfsubscription_types {
00657 enum subscriptiontype type;
00658 const char * const event;
00659 const char * const mediatype;
00660 const char * const text;
00661 } subscription_types[] = {
00662 { NONE, "-", "unknown", "unknown" },
00663
00664 { DIALOG_INFO_XML, "dialog", "application/dialog-info+xml", "dialog-info+xml" },
00665 { CPIM_PIDF_XML, "presence", "application/cpim-pidf+xml", "cpim-pidf+xml" },
00666 { PIDF_XML, "presence", "application/pidf+xml", "pidf+xml" },
00667 { XPIDF_XML, "presence", "application/xpidf+xml", "xpidf+xml" },
00668 { MWI_NOTIFICATION, "message-summary", "application/simple-message-summary", "mwi" }
00669 };
00670
00671
00672
00673
00674
00675
00676 static const struct cfsip_methods {
00677 enum sipmethod id;
00678 int need_rtp;
00679 char * const text;
00680 enum can_create_dialog can_create;
00681 } sip_methods[] = {
00682 { SIP_UNKNOWN, RTP, "-UNKNOWN-",CAN_CREATE_DIALOG },
00683 { SIP_RESPONSE, NO_RTP, "SIP/2.0", CAN_NOT_CREATE_DIALOG },
00684 { SIP_REGISTER, NO_RTP, "REGISTER", CAN_CREATE_DIALOG },
00685 { SIP_OPTIONS, NO_RTP, "OPTIONS", CAN_CREATE_DIALOG },
00686 { SIP_NOTIFY, NO_RTP, "NOTIFY", CAN_CREATE_DIALOG },
00687 { SIP_INVITE, RTP, "INVITE", CAN_CREATE_DIALOG },
00688 { SIP_ACK, NO_RTP, "ACK", CAN_NOT_CREATE_DIALOG },
00689 { SIP_PRACK, NO_RTP, "PRACK", CAN_NOT_CREATE_DIALOG },
00690 { SIP_BYE, NO_RTP, "BYE", CAN_NOT_CREATE_DIALOG },
00691 { SIP_REFER, NO_RTP, "REFER", CAN_CREATE_DIALOG },
00692 { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE",CAN_CREATE_DIALOG },
00693 { SIP_MESSAGE, NO_RTP, "MESSAGE", CAN_CREATE_DIALOG },
00694 { SIP_UPDATE, NO_RTP, "UPDATE", CAN_NOT_CREATE_DIALOG },
00695 { SIP_INFO, NO_RTP, "INFO", CAN_NOT_CREATE_DIALOG },
00696 { SIP_CANCEL, NO_RTP, "CANCEL", CAN_NOT_CREATE_DIALOG },
00697 { SIP_PUBLISH, NO_RTP, "PUBLISH", CAN_CREATE_DIALOG },
00698 { SIP_PING, NO_RTP, "PING", CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
00699 };
00700
00701
00702
00703
00704
00705
00706
00707
00708 static const struct sip_reasons {
00709 enum AST_REDIRECTING_REASON code;
00710 char * const text;
00711 } sip_reason_table[] = {
00712 { AST_REDIRECTING_REASON_UNKNOWN, "unknown" },
00713 { AST_REDIRECTING_REASON_USER_BUSY, "user-busy" },
00714 { AST_REDIRECTING_REASON_NO_ANSWER, "no-answer" },
00715 { AST_REDIRECTING_REASON_UNAVAILABLE, "unavailable" },
00716 { AST_REDIRECTING_REASON_UNCONDITIONAL, "unconditional" },
00717 { AST_REDIRECTING_REASON_TIME_OF_DAY, "time-of-day" },
00718 { AST_REDIRECTING_REASON_DO_NOT_DISTURB, "do-not-disturb" },
00719 { AST_REDIRECTING_REASON_DEFLECTION, "deflection" },
00720 { AST_REDIRECTING_REASON_FOLLOW_ME, "follow-me" },
00721 { AST_REDIRECTING_REASON_OUT_OF_ORDER, "out-of-service" },
00722 { AST_REDIRECTING_REASON_AWAY, "away" },
00723 { AST_REDIRECTING_REASON_CALL_FWD_DTE, "unknown"},
00724 { AST_REDIRECTING_REASON_SEND_TO_VM, "send_to_vm"},
00725 };
00726
00727
00728
00729
00730
00731
00732
00733 static char default_language[MAX_LANGUAGE];
00734 static char default_callerid[AST_MAX_EXTENSION];
00735 static char default_mwi_from[80];
00736 static char default_fromdomain[AST_MAX_EXTENSION];
00737 static int default_fromdomainport;
00738 static char default_notifymime[AST_MAX_EXTENSION];
00739 static char default_vmexten[AST_MAX_EXTENSION];
00740 static int default_qualify;
00741 static int default_keepalive;
00742 static char default_mohinterpret[MAX_MUSICCLASS];
00743 static char default_mohsuggest[MAX_MUSICCLASS];
00744
00745 static char default_parkinglot[AST_MAX_CONTEXT];
00746 static char default_engine[256];
00747 static int default_maxcallbitrate;
00748 static struct ast_codec_pref default_prefs;
00749 static char default_zone[MAX_TONEZONE_COUNTRY];
00750 static unsigned int default_transports;
00751 static unsigned int default_primary_transport;
00752
00753
00754 static struct sip_settings sip_cfg;
00755
00756
00757
00758 #define SIP_PEDANTIC_DECODE(str) \
00759 if (sip_cfg.pedanticsipchecking && !ast_strlen_zero(str)) { \
00760 ast_uri_decode(str, ast_uri_sip_user); \
00761 } \
00762
00763 static unsigned int chan_idx;
00764 static int global_match_auth_username;
00765
00766 static int global_relaxdtmf;
00767 static int global_prematuremediafilter;
00768 static int global_rtptimeout;
00769 static int global_rtpholdtimeout;
00770 static int global_rtpkeepalive;
00771 static int global_reg_timeout;
00772 static int global_regattempts_max;
00773 static int global_reg_retry_403;
00774 static int global_shrinkcallerid;
00775 static int global_callcounter;
00776
00777
00778 static unsigned int global_tos_sip;
00779 static unsigned int global_tos_audio;
00780 static unsigned int global_tos_video;
00781 static unsigned int global_tos_text;
00782 static unsigned int global_cos_sip;
00783 static unsigned int global_cos_audio;
00784 static unsigned int global_cos_video;
00785 static unsigned int global_cos_text;
00786 static unsigned int recordhistory;
00787 static unsigned int dumphistory;
00788 static char global_useragent[AST_MAX_EXTENSION];
00789 static char global_sdpsession[AST_MAX_EXTENSION];
00790 static char global_sdpowner[AST_MAX_EXTENSION];
00791 static int global_authfailureevents;
00792 static int global_t1;
00793 static int global_t1min;
00794 static int global_timer_b;
00795 static unsigned int global_autoframing;
00796 static int global_qualifyfreq;
00797 static int global_qualify_gap;
00798 static int global_qualify_peers;
00799
00800 static enum st_mode global_st_mode;
00801 static enum st_refresher_param global_st_refresher;
00802 static int global_min_se;
00803 static int global_max_se;
00804
00805 static int global_store_sip_cause;
00806
00807 static int global_dynamic_exclude_static = 0;
00808 static unsigned char global_refer_addheaders;
00809
00810
00811
00812
00813
00814
00815
00816
00817 static int can_parse_xml;
00818
00819
00820
00821
00822 static int speerobjs = 0;
00823 static int rpeerobjs = 0;
00824 static int apeerobjs = 0;
00825 static int regobjs = 0;
00826
00827
00828 static struct ast_flags global_flags[3] = {{0}};
00829 static int global_t38_maxdatagram;
00830
00831 static struct ast_event_sub *network_change_event_subscription;
00832 static struct ast_event_sub *acl_change_event_subscription;
00833 static int network_change_event_sched_id = -1;
00834
00835 static char used_context[AST_MAX_CONTEXT];
00836
00837 AST_MUTEX_DEFINE_STATIC(netlock);
00838
00839
00840
00841 AST_MUTEX_DEFINE_STATIC(monlock);
00842
00843 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
00844
00845
00846
00847 static pthread_t monitor_thread = AST_PTHREADT_NULL;
00848
00849 static int sip_reloading = FALSE;
00850 static enum channelreloadreason sip_reloadreason;
00851
00852 struct ast_sched_context *sched;
00853 static struct io_context *io;
00854 static int *sipsock_read_id;
00855 struct sip_pkt;
00856 static AST_LIST_HEAD_STATIC(domain_list, domain);
00857
00858 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history);
00859
00860 static enum sip_debug_e sipdebug;
00861
00862
00863
00864
00865
00866 static int sipdebug_text;
00867
00868 static const struct _map_x_s referstatusstrings[] = {
00869 { REFER_IDLE, "<none>" },
00870 { REFER_SENT, "Request sent" },
00871 { REFER_RECEIVED, "Request received" },
00872 { REFER_CONFIRMED, "Confirmed" },
00873 { REFER_ACCEPTED, "Accepted" },
00874 { REFER_RINGING, "Target ringing" },
00875 { REFER_200OK, "Done" },
00876 { REFER_FAILED, "Failed" },
00877 { REFER_NOAUTH, "Failed - auth failure" },
00878 { -1, NULL}
00879 };
00880
00881
00882 #ifdef LOW_MEMORY
00883 static const int HASH_PEER_SIZE = 17;
00884 static const int HASH_DIALOG_SIZE = 17;
00885 #else
00886 static const int HASH_PEER_SIZE = 563;
00887 static const int HASH_DIALOG_SIZE = 563;
00888 #endif
00889
00890 static const struct {
00891 enum ast_cc_service_type service;
00892 const char *service_string;
00893 } sip_cc_service_map [] = {
00894 [AST_CC_NONE] = { AST_CC_NONE, "" },
00895 [AST_CC_CCBS] = { AST_CC_CCBS, "BS" },
00896 [AST_CC_CCNR] = { AST_CC_CCNR, "NR" },
00897 [AST_CC_CCNL] = { AST_CC_CCNL, "NL" },
00898 };
00899
00900 static enum ast_cc_service_type service_string_to_service_type(const char * const service_string)
00901 {
00902 enum ast_cc_service_type service;
00903 for (service = AST_CC_CCBS; service <= AST_CC_CCNL; ++service) {
00904 if (!strcasecmp(service_string, sip_cc_service_map[service].service_string)) {
00905 return service;
00906 }
00907 }
00908 return AST_CC_NONE;
00909 }
00910
00911 static const struct {
00912 enum sip_cc_notify_state state;
00913 const char *state_string;
00914 } sip_cc_notify_state_map [] = {
00915 [CC_QUEUED] = {CC_QUEUED, "cc-state: queued"},
00916 [CC_READY] = {CC_READY, "cc-state: ready"},
00917 };
00918
00919 AST_LIST_HEAD_STATIC(epa_static_data_list, epa_backend);
00920
00921 static int sip_epa_register(const struct epa_static_data *static_data)
00922 {
00923 struct epa_backend *backend = ast_calloc(1, sizeof(*backend));
00924
00925 if (!backend) {
00926 return -1;
00927 }
00928
00929 backend->static_data = static_data;
00930
00931 AST_LIST_LOCK(&epa_static_data_list);
00932 AST_LIST_INSERT_TAIL(&epa_static_data_list, backend, next);
00933 AST_LIST_UNLOCK(&epa_static_data_list);
00934 return 0;
00935 }
00936
00937 static void sip_epa_unregister_all(void)
00938 {
00939 struct epa_backend *backend;
00940
00941 AST_LIST_LOCK(&epa_static_data_list);
00942 while ((backend = AST_LIST_REMOVE_HEAD(&epa_static_data_list, next))) {
00943 ast_free(backend);
00944 }
00945 AST_LIST_UNLOCK(&epa_static_data_list);
00946 }
00947
00948 static void cc_handle_publish_error(struct sip_pvt *pvt, const int resp, struct sip_request *req, struct sip_epa_entry *epa_entry);
00949
00950 static void cc_epa_destructor(void *data)
00951 {
00952 struct sip_epa_entry *epa_entry = data;
00953 struct cc_epa_entry *cc_entry = epa_entry->instance_data;
00954 ast_free(cc_entry);
00955 }
00956
00957 static const struct epa_static_data cc_epa_static_data = {
00958 .event = CALL_COMPLETION,
00959 .name = "call-completion",
00960 .handle_error = cc_handle_publish_error,
00961 .destructor = cc_epa_destructor,
00962 };
00963
00964 static const struct epa_static_data *find_static_data(const char * const event_package)
00965 {
00966 const struct epa_backend *backend = NULL;
00967
00968 AST_LIST_LOCK(&epa_static_data_list);
00969 AST_LIST_TRAVERSE(&epa_static_data_list, backend, next) {
00970 if (!strcmp(backend->static_data->name, event_package)) {
00971 break;
00972 }
00973 }
00974 AST_LIST_UNLOCK(&epa_static_data_list);
00975 return backend ? backend->static_data : NULL;
00976 }
00977
00978 static struct sip_epa_entry *create_epa_entry (const char * const event_package, const char * const destination)
00979 {
00980 struct sip_epa_entry *epa_entry;
00981 const struct epa_static_data *static_data;
00982
00983 if (!(static_data = find_static_data(event_package))) {
00984 return NULL;
00985 }
00986
00987 if (!(epa_entry = ao2_t_alloc(sizeof(*epa_entry), static_data->destructor, "Allocate new EPA entry"))) {
00988 return NULL;
00989 }
00990
00991 epa_entry->static_data = static_data;
00992 ast_copy_string(epa_entry->destination, destination, sizeof(epa_entry->destination));
00993 return epa_entry;
00994 }
00995
00996
00997
00998
00999 static int esc_etag_counter;
01000 static const int DEFAULT_PUBLISH_EXPIRES = 3600;
01001
01002 #ifdef HAVE_LIBXML2
01003 static int cc_esc_publish_handler(struct sip_pvt *pvt, struct sip_request *req, struct event_state_compositor *esc, struct sip_esc_entry *esc_entry);
01004
01005 static const struct sip_esc_publish_callbacks cc_esc_publish_callbacks = {
01006 .initial_handler = cc_esc_publish_handler,
01007 .modify_handler = cc_esc_publish_handler,
01008 };
01009 #endif
01010
01011
01012
01013
01014
01015
01016
01017
01018
01019
01020
01021
01022
01023 static struct event_state_compositor {
01024 enum subscriptiontype event;
01025 const char * name;
01026 const struct sip_esc_publish_callbacks *callbacks;
01027 struct ao2_container *compositor;
01028 } event_state_compositors [] = {
01029 #ifdef HAVE_LIBXML2
01030 {CALL_COMPLETION, "call-completion", &cc_esc_publish_callbacks},
01031 #endif
01032 };
01033
01034 static const int ESC_MAX_BUCKETS = 37;
01035
01036 static void esc_entry_destructor(void *obj)
01037 {
01038 struct sip_esc_entry *esc_entry = obj;
01039 if (esc_entry->sched_id > -1) {
01040 AST_SCHED_DEL(sched, esc_entry->sched_id);
01041 }
01042 }
01043
01044 static int esc_hash_fn(const void *obj, const int flags)
01045 {
01046 const struct sip_esc_entry *entry = obj;
01047 return ast_str_hash(entry->entity_tag);
01048 }
01049
01050 static int esc_cmp_fn(void *obj, void *arg, int flags)
01051 {
01052 struct sip_esc_entry *entry1 = obj;
01053 struct sip_esc_entry *entry2 = arg;
01054
01055 return (!strcmp(entry1->entity_tag, entry2->entity_tag)) ? (CMP_MATCH | CMP_STOP) : 0;
01056 }
01057
01058 static struct event_state_compositor *get_esc(const char * const event_package) {
01059 int i;
01060 for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
01061 if (!strcasecmp(event_package, event_state_compositors[i].name)) {
01062 return &event_state_compositors[i];
01063 }
01064 }
01065 return NULL;
01066 }
01067
01068 static struct sip_esc_entry *get_esc_entry(const char * entity_tag, struct event_state_compositor *esc) {
01069 struct sip_esc_entry *entry;
01070 struct sip_esc_entry finder;
01071
01072 ast_copy_string(finder.entity_tag, entity_tag, sizeof(finder.entity_tag));
01073
01074 entry = ao2_find(esc->compositor, &finder, OBJ_POINTER);
01075
01076 return entry;
01077 }
01078
01079 static int publish_expire(const void *data)
01080 {
01081 struct sip_esc_entry *esc_entry = (struct sip_esc_entry *) data;
01082 struct event_state_compositor *esc = get_esc(esc_entry->event);
01083
01084 ast_assert(esc != NULL);
01085
01086 ao2_unlink(esc->compositor, esc_entry);
01087 ao2_ref(esc_entry, -1);
01088 return 0;
01089 }
01090
01091 static void create_new_sip_etag(struct sip_esc_entry *esc_entry, int is_linked)
01092 {
01093 int new_etag = ast_atomic_fetchadd_int(&esc_etag_counter, +1);
01094 struct event_state_compositor *esc = get_esc(esc_entry->event);
01095
01096 ast_assert(esc != NULL);
01097 if (is_linked) {
01098 ao2_unlink(esc->compositor, esc_entry);
01099 }
01100 snprintf(esc_entry->entity_tag, sizeof(esc_entry->entity_tag), "%d", new_etag);
01101 ao2_link(esc->compositor, esc_entry);
01102 }
01103
01104 static struct sip_esc_entry *create_esc_entry(struct event_state_compositor *esc, struct sip_request *req, const int expires)
01105 {
01106 struct sip_esc_entry *esc_entry;
01107 int expires_ms;
01108
01109 if (!(esc_entry = ao2_alloc(sizeof(*esc_entry), esc_entry_destructor))) {
01110 return NULL;
01111 }
01112
01113 esc_entry->event = esc->name;
01114
01115 expires_ms = expires * 1000;
01116
01117 ao2_ref(esc_entry, +1);
01118 esc_entry->sched_id = ast_sched_add(sched, expires_ms, publish_expire, esc_entry);
01119
01120
01121 create_new_sip_etag(esc_entry, 0);
01122
01123 return esc_entry;
01124 }
01125
01126 static int initialize_escs(void)
01127 {
01128 int i, res = 0;
01129 for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
01130 if (!((event_state_compositors[i].compositor) =
01131 ao2_container_alloc(ESC_MAX_BUCKETS, esc_hash_fn, esc_cmp_fn))) {
01132 res = -1;
01133 }
01134 }
01135 return res;
01136 }
01137
01138 static void destroy_escs(void)
01139 {
01140 int i;
01141 for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
01142 ao2_ref(event_state_compositors[i].compositor, -1);
01143 }
01144 }
01145
01146 struct state_notify_data {
01147 int state;
01148 struct ao2_container *device_state_info;
01149 int presence_state;
01150 const char *presence_subtype;
01151 const char *presence_message;
01152 };
01153
01154
01155
01156
01157
01158
01159
01160 struct ao2_container *dialogs_needdestroy;
01161
01162
01163
01164
01165
01166
01167
01168 struct ao2_container *dialogs_rtpcheck;
01169
01170
01171
01172
01173
01174
01175
01176
01177
01178
01179 static struct ao2_container *dialogs;
01180 #define sip_pvt_lock(x) ao2_lock(x)
01181 #define sip_pvt_trylock(x) ao2_trylock(x)
01182 #define sip_pvt_unlock(x) ao2_unlock(x)
01183
01184
01185 static struct ao2_container *threadt;
01186
01187
01188 static struct ao2_container *peers;
01189 static struct ao2_container *peers_by_ip;
01190
01191
01192 static struct sip_peer *bogus_peer;
01193
01194 #define BOGUS_PEER_MD5SECRET "intentionally_invalid_md5_string"
01195
01196
01197 static struct ast_register_list {
01198 ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
01199 int recheck;
01200 } regl;
01201
01202
01203 static struct ast_subscription_mwi_list {
01204 ASTOBJ_CONTAINER_COMPONENTS(struct sip_subscription_mwi);
01205 } submwil;
01206 static int temp_pvt_init(void *);
01207 static void temp_pvt_cleanup(void *);
01208
01209
01210 AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
01211
01212
01213 AST_THREADSTORAGE(sip_transport_str_buf);
01214
01215
01216 #define SIP_TRANSPORT_STR_BUFSIZE 128
01217
01218
01219 static struct sip_auth_container *authl = NULL;
01220
01221 AST_MUTEX_DEFINE_STATIC(authl_lock);
01222
01223
01224
01225
01226
01227
01228
01229
01230
01231
01232
01233
01234
01235
01236
01237
01238
01239 static int sipsock = -1;
01240
01241 struct ast_sockaddr bindaddr;
01242
01243
01244
01245
01246
01247
01248
01249 static struct ast_sockaddr internip;
01250
01251
01252
01253
01254
01255
01256
01257
01258
01259
01260
01261
01262
01263
01264
01265
01266 static struct ast_sockaddr externaddr;
01267 static struct ast_sockaddr media_address;
01268
01269 static char externhost[MAXHOSTNAMELEN];
01270 static time_t externexpire;
01271 static int externrefresh = 10;
01272 static uint16_t externtcpport;
01273 static uint16_t externtlsport;
01274
01275
01276
01277
01278
01279
01280
01281 static struct ast_ha *localaddr;
01282
01283 static int ourport_tcp;
01284 static int ourport_tls;
01285 static struct ast_sockaddr debugaddr;
01286
01287 static struct ast_config *notify_types = NULL;
01288
01289
01290
01291 #define UNLINK(element, head, prev) do { \
01292 if (prev) \
01293 (prev)->next = (element)->next; \
01294 else \
01295 (head) = (element)->next; \
01296 } while (0)
01297
01298 struct show_peers_context;
01299
01300
01301
01302
01303
01304
01305 static struct ast_channel *sip_request_call(const char *type, struct ast_format_cap *cap, const struct ast_channel *requestor, const char *dest, int *cause);
01306 static int sip_devicestate(const char *data);
01307 static int sip_sendtext(struct ast_channel *ast, const char *text);
01308 static int sip_call(struct ast_channel *ast, const char *dest, int timeout);
01309 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen);
01310 static int sip_hangup(struct ast_channel *ast);
01311 static int sip_answer(struct ast_channel *ast);
01312 static struct ast_frame *sip_read(struct ast_channel *ast);
01313 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
01314 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
01315 static int sip_transfer(struct ast_channel *ast, const char *dest);
01316 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
01317 static int sip_senddigit_begin(struct ast_channel *ast, char digit);
01318 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
01319 static int sip_setoption(struct ast_channel *chan, int option, void *data, int datalen);
01320 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen);
01321 static const char *sip_get_callid(struct ast_channel *chan);
01322
01323 static int handle_request_do(struct sip_request *req, struct ast_sockaddr *addr);
01324 static int sip_standard_port(enum sip_transport type, int port);
01325 static int sip_prepare_socket(struct sip_pvt *p);
01326 static int get_address_family_filter(unsigned int transport);
01327
01328
01329 static int sipsock_read(int *id, int fd, short events, void *ignore);
01330 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data);
01331 static int __sip_reliable_xmit(struct sip_pvt *p, uint32_t seqno, int resp, struct ast_str *data, int fatal, int sipmethod);
01332 static void add_cc_call_info_to_response(struct sip_pvt *p, struct sip_request *resp);
01333 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
01334 static int retrans_pkt(const void *data);
01335 static int transmit_response_using_temp(ast_string_field callid, struct ast_sockaddr *addr, int useglobal_nat, const int intended_method, const struct sip_request *req, const char *msg);
01336 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
01337 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
01338 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
01339 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable, int oldsdp, int rpid);
01340 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
01341 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);
01342 static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp);
01343 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
01344 static void transmit_fake_auth_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable);
01345 static int transmit_request(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch);
01346 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch);
01347 static int transmit_publish(struct sip_epa_entry *epa_entry, enum sip_publish_type publish_type, const char * const explicit_uri);
01348 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init, const char * const explicit_uri);
01349 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp);
01350 static int transmit_info_with_aoc(struct sip_pvt *p, struct ast_aoc_decoded *decoded);
01351 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
01352 static int transmit_info_with_vidupdate(struct sip_pvt *p);
01353 static int transmit_message(struct sip_pvt *p, int init, int auth);
01354 static int transmit_refer(struct sip_pvt *p, const char *dest);
01355 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten);
01356 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
01357 static int transmit_cc_notify(struct ast_cc_agent *agent, struct sip_pvt *subscription, enum sip_cc_notify_state state);
01358 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
01359 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno);
01360 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno);
01361 static void copy_request(struct sip_request *dst, const struct sip_request *src);
01362 static void receive_message(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
01363 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req, char **name, char **number, int set_call_forward);
01364 static int sip_send_mwi_to_peer(struct sip_peer *peer, int cache_only);
01365
01366
01367 static int __sip_autodestruct(const void *data);
01368 static void *registry_unref(struct sip_registry *reg, char *tag);
01369 static int update_call_counter(struct sip_pvt *fup, int event);
01370 static int auto_congest(const void *arg);
01371 static struct sip_pvt *find_call(struct sip_request *req, struct ast_sockaddr *addr, const int intended_method);
01372 static void free_old_route(struct sip_route *route);
01373 static void list_route(struct sip_route *route);
01374 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards, int resp);
01375 static enum check_auth_result register_verify(struct sip_pvt *p, struct ast_sockaddr *addr,
01376 struct sip_request *req, const char *uri);
01377 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
01378 static void check_pendings(struct sip_pvt *p);
01379 static void *sip_park_thread(void *stuff);
01380 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, uint32_t seqno, const char *park_exten, const char *park_context);
01381
01382 static void *sip_pickup_thread(void *stuff);
01383 static int sip_pickup(struct ast_channel *chan);
01384
01385 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
01386 static int is_method_allowed(unsigned int *allowed_methods, enum sipmethod method);
01387
01388
01389 static void try_suggested_sip_codec(struct sip_pvt *p);
01390 static const char *get_sdp_iterate(int* start, struct sip_request *req, const char *name);
01391 static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value);
01392 static int find_sdp(struct sip_request *req);
01393 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action);
01394 static int process_sdp_o(const char *o, struct sip_pvt *p);
01395 static int process_sdp_c(const char *c, struct ast_sockaddr *addr);
01396 static int process_sdp_a_sendonly(const char *a, int *sendonly);
01397 static int process_sdp_a_ice(const char *a, struct sip_pvt *p, struct ast_rtp_instance *instance);
01398 static int process_sdp_a_dtls(const char *a, struct sip_pvt *p, struct ast_rtp_instance *instance);
01399 static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newaudiortp, int *last_rtpmap_codec);
01400 static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newvideortp, int *last_rtpmap_codec);
01401 static int process_sdp_a_text(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newtextrtp, char *red_fmtp, int *red_num_gen, int *red_data_pt, int *last_rtpmap_codec);
01402 static int process_sdp_a_image(const char *a, struct sip_pvt *p);
01403 static void add_ice_to_sdp(struct ast_rtp_instance *instance, struct ast_str **a_buf);
01404 static void add_dtls_to_sdp(struct ast_rtp_instance *instance, struct ast_str **a_buf);
01405 static void start_ice(struct ast_rtp_instance *instance);
01406 static void add_codec_to_sdp(const struct sip_pvt *p, struct ast_format *codec,
01407 struct ast_str **m_buf, struct ast_str **a_buf,
01408 int debug, int *min_packet_size);
01409 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
01410 struct ast_str **m_buf, struct ast_str **a_buf,
01411 int debug);
01412 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38);
01413 static void do_setnat(struct sip_pvt *p);
01414 static void stop_media_flows(struct sip_pvt *p);
01415
01416
01417 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
01418 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
01419 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
01420 const char *secret, const char *md5secret, int sipmethod,
01421 const char *uri, enum xmittype reliable);
01422 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
01423 int sipmethod, const char *uri, enum xmittype reliable,
01424 struct ast_sockaddr *addr, struct sip_peer **authpeer);
01425 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, const char *uri, enum xmittype reliable, struct ast_sockaddr *addr);
01426
01427
01428 static int check_sip_domain(const char *domain, char *context, size_t len);
01429 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
01430 static void clear_sip_domains(void);
01431
01432
01433 static void add_realm_authentication(struct sip_auth_container **credentials, const char *configuration, int lineno);
01434 static struct sip_auth *find_realm_authentication(struct sip_auth_container *credentials, const char *realm);
01435
01436
01437 static int check_rtp_timeout(struct sip_pvt *dialog, time_t t);
01438 static int reload_config(enum channelreloadreason reason);
01439 static void add_diversion(struct sip_request *req, struct sip_pvt *pvt);
01440 static int expire_register(const void *data);
01441 static void *do_monitor(void *data);
01442 static int restart_monitor(void);
01443 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer);
01444 static struct ast_variable *copy_vars(struct ast_variable *src);
01445 static int dialog_find_multiple(void *obj, void *arg, int flags);
01446 static struct ast_channel *sip_pvt_lock_full(struct sip_pvt *pvt);
01447
01448 static int sip_refer_alloc(struct sip_pvt *p);
01449 static int sip_notify_alloc(struct sip_pvt *p);
01450 static void ast_quiet_chan(struct ast_channel *chan);
01451 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
01452 static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context);
01453 static void set_peer_nat(const struct sip_pvt *p, struct sip_peer *peer);
01454 static void check_for_nat(const struct ast_sockaddr *them, struct sip_pvt *p);
01455
01456
01457 static int extensionstate_update(const char *context, const char *exten, struct state_notify_data *data, struct sip_pvt *p, int force);
01458 static int cb_extensionstate(char *context, char *exten, struct ast_state_cb_info *info, void *data);
01459 static int sip_poke_noanswer(const void *data);
01460 static int sip_poke_peer(struct sip_peer *peer, int force);
01461 static void sip_poke_all_peers(void);
01462 static void sip_peer_hold(struct sip_pvt *p, int hold);
01463 static void mwi_event_cb(const struct ast_event *, void *);
01464 static void network_change_event_cb(const struct ast_event *, void *);
01465 static void acl_change_event_cb(const struct ast_event *event, void *userdata);
01466 static void sip_keepalive_all_peers(void);
01467
01468
01469 static const char *sip_nat_mode(const struct sip_pvt *p);
01470 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01471 static char *transfermode2str(enum transfermodes mode) attribute_const;
01472 static int peer_status(struct sip_peer *peer, char *status, int statuslen);
01473 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01474 static char * _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
01475 static struct sip_peer *_sip_show_peers_one(int fd, struct mansession *s, struct show_peers_context *cont, struct sip_peer *peer);
01476 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01477 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01478 static void print_group(int fd, ast_group_t group, int crlf);
01479 static void print_named_groups(int fd, struct ast_namedgroups *groups, int crlf);
01480 static const char *dtmfmode2str(int mode) attribute_const;
01481 static int str2dtmfmode(const char *str) attribute_unused;
01482 static const char *insecure2str(int mode) attribute_const;
01483 static const char *allowoverlap2str(int mode) attribute_const;
01484 static void cleanup_stale_contexts(char *new, char *old);
01485 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
01486 static const char *domain_mode_to_text(const enum domain_mode mode);
01487 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01488 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
01489 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01490 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
01491 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01492 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01493 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01494 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01495 static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01496 static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
01497 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
01498 static char *complete_sip_peer(const char *word, int state, int flags2);
01499 static char *complete_sip_registered_peer(const char *word, int state, int flags2);
01500 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state);
01501 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
01502 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state);
01503 static char *complete_sip_notify(const char *line, const char *word, int pos, int state);
01504 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01505 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01506 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01507 static char *sip_do_debug_ip(int fd, const char *arg);
01508 static char *sip_do_debug_peer(int fd, const char *arg);
01509 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01510 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01511 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01512 static int sip_dtmfmode(struct ast_channel *chan, const char *data);
01513 static int sip_addheader(struct ast_channel *chan, const char *data);
01514 static int sip_do_reload(enum channelreloadreason reason);
01515 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01516 static int ast_sockaddr_resolve_first_af(struct ast_sockaddr *addr,
01517 const char *name, int flag, int family);
01518 static int ast_sockaddr_resolve_first(struct ast_sockaddr *addr,
01519 const char *name, int flag);
01520 static int ast_sockaddr_resolve_first_transport(struct ast_sockaddr *addr,
01521 const char *name, int flag, unsigned int transport);
01522
01523
01524
01525
01526
01527 static void sip_dump_history(struct sip_pvt *dialog);
01528 static inline int sip_debug_test_addr(const struct ast_sockaddr *addr);
01529 static inline int sip_debug_test_pvt(struct sip_pvt *p);
01530 static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
01531 static void sip_dump_history(struct sip_pvt *dialog);
01532
01533
01534 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only);
01535 static int update_call_counter(struct sip_pvt *fup, int event);
01536 static void sip_destroy_peer(struct sip_peer *peer);
01537 static void sip_destroy_peer_fn(void *peer);
01538 static void set_peer_defaults(struct sip_peer *peer);
01539 static struct sip_peer *temp_peer(const char *name);
01540 static void register_peer_exten(struct sip_peer *peer, int onoff);
01541 static int sip_poke_peer_s(const void *data);
01542 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
01543 static void reg_source_db(struct sip_peer *peer);
01544 static void destroy_association(struct sip_peer *peer);
01545 static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
01546 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
01547 static void set_socket_transport(struct sip_socket *socket, int transport);
01548 static int peer_ipcmp_cb_full(void *obj, void *arg, void *data, int flags);
01549
01550
01551 static void realtime_update_peer(const char *peername, struct ast_sockaddr *addr, const char *username, const char *fullcontact, const char *useragent, int expirey, unsigned short deprecated_username, int lastms);
01552 static void update_peer(struct sip_peer *p, int expire);
01553 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config);
01554 static const char *get_name_from_variable(const struct ast_variable *var);
01555 static struct sip_peer *realtime_peer(const char *peername, struct ast_sockaddr *sin, char *callbackexten, int devstate_only, int which_objects);
01556 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01557
01558
01559 static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p);
01560 static void sip_registry_destroy(struct sip_registry *reg);
01561 static int sip_register(const char *value, int lineno);
01562 static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
01563 static int sip_reregister(const void *data);
01564 static int __sip_do_register(struct sip_registry *r);
01565 static int sip_reg_timeout(const void *data);
01566 static void sip_send_all_registers(void);
01567 static int sip_reinvite_retry(const void *data);
01568
01569
01570 static int determine_firstline_parts(struct sip_request *req);
01571 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
01572 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
01573 static int find_sip_method(const char *msg);
01574 static unsigned int parse_allowed_methods(struct sip_request *req);
01575 static unsigned int set_pvt_allowed_methods(struct sip_pvt *pvt, struct sip_request *req);
01576 static int parse_request(struct sip_request *req);
01577 static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
01578 static int method_match(enum sipmethod id, const char *name);
01579 static void parse_copy(struct sip_request *dst, const struct sip_request *src);
01580 static void parse_oli(struct sip_request *req, struct ast_channel *chan);
01581 static const char *find_alias(const char *name, const char *_default);
01582 static const char *__get_header(const struct sip_request *req, const char *name, int *start);
01583 static void lws2sws(struct ast_str *msgbuf);
01584 static void extract_uri(struct sip_pvt *p, struct sip_request *req);
01585 static char *remove_uri_parameters(char *uri);
01586 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
01587 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
01588 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
01589 static int set_address_from_contact(struct sip_pvt *pvt);
01590 static void check_via(struct sip_pvt *p, const struct sip_request *req);
01591 static int get_rpid(struct sip_pvt *p, struct sip_request *oreq);
01592 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq, char **name, char **number, int *reason);
01593 static enum sip_get_dest_result get_destination(struct sip_pvt *p, struct sip_request *oreq, int *cc_recall_core_id);
01594 static int transmit_state_notify(struct sip_pvt *p, struct state_notify_data *data, int full, int timeout);
01595 static void update_connectedline(struct sip_pvt *p, const void *data, size_t datalen);
01596 static void update_redirecting(struct sip_pvt *p, const void *data, size_t datalen);
01597 static int get_domain(const char *str, char *domain, int len);
01598 static void get_realm(struct sip_pvt *p, const struct sip_request *req);
01599 static char *get_content(struct sip_request *req);
01600
01601
01602 static void *_sip_tcp_helper_thread(struct ast_tcptls_session_instance *tcptls_session);
01603 static void *sip_tcp_worker_fn(void *);
01604
01605
01606 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
01607 static int init_req(struct sip_request *req, int sipmethod, const char *recip);
01608 static void deinit_req(struct sip_request *req);
01609 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, uint32_t seqno, int newbranch);
01610 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, const char * const explicit_uri);
01611 static int init_resp(struct sip_request *resp, const char *msg);
01612 static inline int resp_needs_contact(const char *msg, enum sipmethod method);
01613 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
01614 static const struct ast_sockaddr *sip_real_dst(const struct sip_pvt *p);
01615 static void build_via(struct sip_pvt *p);
01616 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
01617 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct ast_sockaddr *addr, int newdialog);
01618 static char *generate_random_string(char *buf, size_t size);
01619 static void build_callid_pvt(struct sip_pvt *pvt);
01620 static void change_callid_pvt(struct sip_pvt *pvt, const char *callid);
01621 static void build_callid_registry(struct sip_registry *reg, const struct ast_sockaddr *ourip, const char *fromdomain);
01622 static void build_localtag_registry(struct sip_registry *reg);
01623 static void make_our_tag(struct sip_pvt *pvt);
01624 static int add_header(struct sip_request *req, const char *var, const char *value);
01625 static int add_max_forwards(struct sip_pvt *dialog, struct sip_request *req);
01626 static int add_content(struct sip_request *req, const char *line);
01627 static int finalize_content(struct sip_request *req);
01628 static void destroy_msg_headers(struct sip_pvt *pvt);
01629 static int add_text(struct sip_request *req, struct sip_pvt *p);
01630 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode);
01631 static int add_rpid(struct sip_request *req, struct sip_pvt *p);
01632 static int add_vidupdate(struct sip_request *req);
01633 static void add_route(struct sip_request *req, struct sip_route *route);
01634 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
01635 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
01636 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
01637 static void set_destination(struct sip_pvt *p, char *uri);
01638 static void add_date(struct sip_request *req);
01639 static void add_expires(struct sip_request *req, int expires);
01640 static void build_contact(struct sip_pvt *p);
01641
01642
01643 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int *recount, int *nounlock);
01644 static int handle_request_update(struct sip_pvt *p, struct sip_request *req);
01645 static int handle_request_invite(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, int *recount, const char *e, int *nounlock);
01646 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, uint32_t seqno, int *nounlock);
01647 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
01648 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *sin, const char *e);
01649 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
01650 static int handle_request_message(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
01651 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e);
01652 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
01653 static int handle_request_options(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
01654 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, int *nounlock);
01655 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e);
01656 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, uint32_t seqno, int *nounlock);
01657
01658
01659 static void handle_response_publish(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01660 static void handle_response_invite(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01661 static void handle_response_notify(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01662 static void handle_response_refer(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01663 static void handle_response_subscribe(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01664 static int handle_response_register(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01665 static void handle_response(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01666
01667
01668 static int setup_srtp(struct sip_srtp **srtp);
01669 static int process_crypto(struct sip_pvt *p, struct ast_rtp_instance *rtp, struct sip_srtp **srtp, const char *a);
01670
01671
01672 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
01673 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
01674 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
01675 static void change_t38_state(struct sip_pvt *p, int state);
01676
01677
01678 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp);
01679 static int proc_session_timer(const void *vp);
01680 static void stop_session_timer(struct sip_pvt *p);
01681 static void start_session_timer(struct sip_pvt *p);
01682 static void restart_session_timer(struct sip_pvt *p);
01683 static const char *strefresherparam2str(enum st_refresher r);
01684 static int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher_param *const p_ref);
01685 static int parse_minse(const char *p_hdrval, int *const p_interval);
01686 static int st_get_se(struct sip_pvt *, int max);
01687 static enum st_refresher st_get_refresher(struct sip_pvt *);
01688 static enum st_mode st_get_mode(struct sip_pvt *, int no_cached);
01689 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p);
01690
01691
01692 static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp_instance *instance, struct ast_rtp_instance *vinstance, struct ast_rtp_instance *tinstance, const struct ast_format_cap *cap, int nat_active);
01693
01694
01695 static int sip_subscribe_mwi(const char *value, int lineno);
01696 static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi);
01697 static void sip_send_all_mwi_subscriptions(void);
01698 static int sip_subscribe_mwi_do(const void *data);
01699 static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi);
01700
01701
01702 struct ast_channel_tech sip_tech = {
01703 .type = "SIP",
01704 .description = "Session Initiation Protocol (SIP)",
01705 .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
01706 .requester = sip_request_call,
01707 .devicestate = sip_devicestate,
01708 .call = sip_call,
01709 .send_html = sip_sendhtml,
01710 .hangup = sip_hangup,
01711 .answer = sip_answer,
01712 .read = sip_read,
01713 .write = sip_write,
01714 .write_video = sip_write,
01715 .write_text = sip_write,
01716 .indicate = sip_indicate,
01717 .transfer = sip_transfer,
01718 .fixup = sip_fixup,
01719 .send_digit_begin = sip_senddigit_begin,
01720 .send_digit_end = sip_senddigit_end,
01721 .bridge = ast_rtp_instance_bridge,
01722 .early_bridge = ast_rtp_instance_early_bridge,
01723 .send_text = sip_sendtext,
01724 .func_channel_read = sip_acf_channel_read,
01725 .setoption = sip_setoption,
01726 .queryoption = sip_queryoption,
01727 .get_pvt_uniqueid = sip_get_callid,
01728 };
01729
01730
01731
01732
01733
01734
01735
01736 struct ast_channel_tech sip_tech_info;
01737
01738
01739 static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan);
01740 static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent);
01741 static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent);
01742 static void sip_cc_agent_respond(struct ast_cc_agent *agent, enum ast_cc_agent_response_reason reason);
01743 static int sip_cc_agent_status_request(struct ast_cc_agent *agent);
01744 static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent);
01745 static int sip_cc_agent_recall(struct ast_cc_agent *agent);
01746 static void sip_cc_agent_destructor(struct ast_cc_agent *agent);
01747
01748 static struct ast_cc_agent_callbacks sip_cc_agent_callbacks = {
01749 .type = "SIP",
01750 .init = sip_cc_agent_init,
01751 .start_offer_timer = sip_cc_agent_start_offer_timer,
01752 .stop_offer_timer = sip_cc_agent_stop_offer_timer,
01753 .respond = sip_cc_agent_respond,
01754 .status_request = sip_cc_agent_status_request,
01755 .start_monitoring = sip_cc_agent_start_monitoring,
01756 .callee_available = sip_cc_agent_recall,
01757 .destructor = sip_cc_agent_destructor,
01758 };
01759
01760 static int find_by_notify_uri_helper(void *obj, void *arg, int flags)
01761 {
01762 struct ast_cc_agent *agent = obj;
01763 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01764 const char *uri = arg;
01765
01766 return !sip_uri_cmp(agent_pvt->notify_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
01767 }
01768
01769 static struct ast_cc_agent *find_sip_cc_agent_by_notify_uri(const char * const uri)
01770 {
01771 struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_notify_uri_helper, (char *)uri, "SIP");
01772 return agent;
01773 }
01774
01775 static int find_by_subscribe_uri_helper(void *obj, void *arg, int flags)
01776 {
01777 struct ast_cc_agent *agent = obj;
01778 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01779 const char *uri = arg;
01780
01781 return !sip_uri_cmp(agent_pvt->subscribe_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
01782 }
01783
01784 static struct ast_cc_agent *find_sip_cc_agent_by_subscribe_uri(const char * const uri)
01785 {
01786 struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_subscribe_uri_helper, (char *)uri, "SIP");
01787 return agent;
01788 }
01789
01790 static int find_by_callid_helper(void *obj, void *arg, int flags)
01791 {
01792 struct ast_cc_agent *agent = obj;
01793 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01794 struct sip_pvt *call_pvt = arg;
01795
01796 return !strcmp(agent_pvt->original_callid, call_pvt->callid) ? CMP_MATCH | CMP_STOP : 0;
01797 }
01798
01799 static struct ast_cc_agent *find_sip_cc_agent_by_original_callid(struct sip_pvt *pvt)
01800 {
01801 struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_callid_helper, pvt, "SIP");
01802 return agent;
01803 }
01804
01805 static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan)
01806 {
01807 struct sip_cc_agent_pvt *agent_pvt = ast_calloc(1, sizeof(*agent_pvt));
01808 struct sip_pvt *call_pvt = ast_channel_tech_pvt(chan);
01809
01810 if (!agent_pvt) {
01811 return -1;
01812 }
01813
01814 ast_assert(!strcmp(ast_channel_tech(chan)->type, "SIP"));
01815
01816 ast_copy_string(agent_pvt->original_callid, call_pvt->callid, sizeof(agent_pvt->original_callid));
01817 ast_copy_string(agent_pvt->original_exten, call_pvt->exten, sizeof(agent_pvt->original_exten));
01818 agent_pvt->offer_timer_id = -1;
01819 agent->private_data = agent_pvt;
01820 sip_pvt_lock(call_pvt);
01821 ast_set_flag(&call_pvt->flags[0], SIP_OFFER_CC);
01822 sip_pvt_unlock(call_pvt);
01823 return 0;
01824 }
01825
01826 static int sip_offer_timer_expire(const void *data)
01827 {
01828 struct ast_cc_agent *agent = (struct ast_cc_agent *) data;
01829 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01830
01831 agent_pvt->offer_timer_id = -1;
01832
01833 return ast_cc_failed(agent->core_id, "SIP agent %s's offer timer expired", agent->device_name);
01834 }
01835
01836 static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent)
01837 {
01838 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01839 int when;
01840
01841 when = ast_get_cc_offer_timer(agent->cc_params) * 1000;
01842 agent_pvt->offer_timer_id = ast_sched_add(sched, when, sip_offer_timer_expire, agent);
01843 return 0;
01844 }
01845
01846 static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent)
01847 {
01848 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01849
01850 AST_SCHED_DEL(sched, agent_pvt->offer_timer_id);
01851 return 0;
01852 }
01853
01854 static void sip_cc_agent_respond(struct ast_cc_agent *agent, enum ast_cc_agent_response_reason reason)
01855 {
01856 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01857
01858 sip_pvt_lock(agent_pvt->subscribe_pvt);
01859 ast_set_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
01860 if (reason == AST_CC_AGENT_RESPONSE_SUCCESS || !ast_strlen_zero(agent_pvt->notify_uri)) {
01861
01862
01863
01864
01865
01866
01867
01868
01869
01870
01871
01872
01873 transmit_response(agent_pvt->subscribe_pvt, "200 OK", &agent_pvt->subscribe_pvt->initreq);
01874 transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_QUEUED);
01875 } else {
01876 transmit_response(agent_pvt->subscribe_pvt, "500 Internal Error", &agent_pvt->subscribe_pvt->initreq);
01877 }
01878 sip_pvt_unlock(agent_pvt->subscribe_pvt);
01879 agent_pvt->is_available = TRUE;
01880 }
01881
01882 static int sip_cc_agent_status_request(struct ast_cc_agent *agent)
01883 {
01884 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01885 enum ast_device_state state = agent_pvt->is_available ? AST_DEVICE_NOT_INUSE : AST_DEVICE_INUSE;
01886 return ast_cc_agent_status_response(agent->core_id, state);
01887 }
01888
01889 static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent)
01890 {
01891
01892
01893
01894
01895 return 0;
01896 }
01897
01898 static int sip_cc_agent_recall(struct ast_cc_agent *agent)
01899 {
01900 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01901
01902
01903
01904
01905 if (!agent_pvt->is_available) {
01906 return ast_cc_agent_caller_busy(agent->core_id, "Caller %s is busy, reporting to the core",
01907 agent->device_name);
01908 }
01909
01910
01911
01912 sip_pvt_lock(agent_pvt->subscribe_pvt);
01913 transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_READY);
01914 sip_pvt_unlock(agent_pvt->subscribe_pvt);
01915 return 0;
01916 }
01917
01918 static void sip_cc_agent_destructor(struct ast_cc_agent *agent)
01919 {
01920 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01921
01922 if (!agent_pvt) {
01923
01924 return;
01925 }
01926
01927 sip_cc_agent_stop_offer_timer(agent);
01928 if (agent_pvt->subscribe_pvt) {
01929 sip_pvt_lock(agent_pvt->subscribe_pvt);
01930 if (!ast_test_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
01931
01932
01933
01934 transmit_response(agent_pvt->subscribe_pvt, "500 Internal Server Error", &agent_pvt->subscribe_pvt->initreq);
01935 }
01936 sip_pvt_unlock(agent_pvt->subscribe_pvt);
01937 agent_pvt->subscribe_pvt = dialog_unref(agent_pvt->subscribe_pvt, "SIP CC agent destructor: Remove ref to subscription");
01938 }
01939 ast_free(agent_pvt);
01940 }
01941
01942 struct ao2_container *sip_monitor_instances;
01943
01944 static int sip_monitor_instance_hash_fn(const void *obj, const int flags)
01945 {
01946 const struct sip_monitor_instance *monitor_instance = obj;
01947 return monitor_instance->core_id;
01948 }
01949
01950 static int sip_monitor_instance_cmp_fn(void *obj, void *arg, int flags)
01951 {
01952 struct sip_monitor_instance *monitor_instance1 = obj;
01953 struct sip_monitor_instance *monitor_instance2 = arg;
01954
01955 return monitor_instance1->core_id == monitor_instance2->core_id ? CMP_MATCH | CMP_STOP : 0;
01956 }
01957
01958 static void sip_monitor_instance_destructor(void *data)
01959 {
01960 struct sip_monitor_instance *monitor_instance = data;
01961 if (monitor_instance->subscription_pvt) {
01962 sip_pvt_lock(monitor_instance->subscription_pvt);
01963 monitor_instance->subscription_pvt->expiry = 0;
01964 transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 0, monitor_instance->subscribe_uri);
01965 sip_pvt_unlock(monitor_instance->subscription_pvt);
01966 dialog_unref(monitor_instance->subscription_pvt, "Unref monitor instance ref of subscription pvt");
01967 }
01968 if (monitor_instance->suspension_entry) {
01969 monitor_instance->suspension_entry->body[0] = '\0';
01970 transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_REMOVE ,monitor_instance->notify_uri);
01971 ao2_t_ref(monitor_instance->suspension_entry, -1, "Decrementing suspension entry refcount in sip_monitor_instance_destructor");
01972 }
01973 ast_string_field_free_memory(monitor_instance);
01974 }
01975
01976 static struct sip_monitor_instance *sip_monitor_instance_init(int core_id, const char * const subscribe_uri, const char * const peername, const char * const device_name)
01977 {
01978 struct sip_monitor_instance *monitor_instance = ao2_alloc(sizeof(*monitor_instance), sip_monitor_instance_destructor);
01979
01980 if (!monitor_instance) {
01981 return NULL;
01982 }
01983
01984 if (ast_string_field_init(monitor_instance, 256)) {
01985 ao2_ref(monitor_instance, -1);
01986 return NULL;
01987 }
01988
01989 ast_string_field_set(monitor_instance, subscribe_uri, subscribe_uri);
01990 ast_string_field_set(monitor_instance, peername, peername);
01991 ast_string_field_set(monitor_instance, device_name, device_name);
01992 monitor_instance->core_id = core_id;
01993 ao2_link(sip_monitor_instances, monitor_instance);
01994 return monitor_instance;
01995 }
01996
01997 static int find_sip_monitor_instance_by_subscription_pvt(void *obj, void *arg, int flags)
01998 {
01999 struct sip_monitor_instance *monitor_instance = obj;
02000 return monitor_instance->subscription_pvt == arg ? CMP_MATCH | CMP_STOP : 0;
02001 }
02002
02003 static int find_sip_monitor_instance_by_suspension_entry(void *obj, void *arg, int flags)
02004 {
02005 struct sip_monitor_instance *monitor_instance = obj;
02006 return monitor_instance->suspension_entry == arg ? CMP_MATCH | CMP_STOP : 0;
02007 }
02008
02009 static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id);
02010 static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor);
02011 static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor);
02012 static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id);
02013 static void sip_cc_monitor_destructor(void *private_data);
02014
02015 static struct ast_cc_monitor_callbacks sip_cc_monitor_callbacks = {
02016 .type = "SIP",
02017 .request_cc = sip_cc_monitor_request_cc,
02018 .suspend = sip_cc_monitor_suspend,
02019 .unsuspend = sip_cc_monitor_unsuspend,
02020 .cancel_available_timer = sip_cc_monitor_cancel_available_timer,
02021 .destructor = sip_cc_monitor_destructor,
02022 };
02023
02024 static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id)
02025 {
02026 struct sip_monitor_instance *monitor_instance = monitor->private_data;
02027 enum ast_cc_service_type service = monitor->service_offered;
02028 int when;
02029
02030 if (!monitor_instance) {
02031 return -1;
02032 }
02033
02034 if (!(monitor_instance->subscription_pvt = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL, NULL))) {
02035 return -1;
02036 }
02037
02038 when = service == AST_CC_CCBS ? ast_get_ccbs_available_timer(monitor->interface->config_params) :
02039 ast_get_ccnr_available_timer(monitor->interface->config_params);
02040
02041 sip_pvt_lock(monitor_instance->subscription_pvt);
02042 ast_set_flag(&monitor_instance->subscription_pvt->flags[0], SIP_OUTGOING);
02043 create_addr(monitor_instance->subscription_pvt, monitor_instance->peername, 0, 1);
02044 ast_sip_ouraddrfor(&monitor_instance->subscription_pvt->sa, &monitor_instance->subscription_pvt->ourip, monitor_instance->subscription_pvt);
02045 monitor_instance->subscription_pvt->subscribed = CALL_COMPLETION;
02046 monitor_instance->subscription_pvt->expiry = when;
02047
02048 transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 2, monitor_instance->subscribe_uri);
02049 sip_pvt_unlock(monitor_instance->subscription_pvt);
02050
02051 ao2_t_ref(monitor, +1, "Adding a ref to the monitor for the scheduler");
02052 *available_timer_id = ast_sched_add(sched, when * 1000, ast_cc_available_timer_expire, monitor);
02053 return 0;
02054 }
02055
02056 static int construct_pidf_body(enum sip_cc_publish_state state, char *pidf_body, size_t size, const char *presentity)
02057 {
02058 struct ast_str *body = ast_str_alloca(size);
02059 char tuple_id[32];
02060
02061 generate_random_string(tuple_id, sizeof(tuple_id));
02062
02063
02064
02065
02066 ast_str_append(&body, 0, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
02067
02068
02069
02070
02071
02072
02073 ast_str_append(&body, 0, "<presence xmlns=\"urn:ietf:params:xml:ns:pidf\" entity=\"%s\">\n", presentity);
02074 ast_str_append(&body, 0, "<tuple id=\"%s\">\n", tuple_id);
02075 ast_str_append(&body, 0, "<status><basic>%s</basic></status>\n", state == CC_OPEN ? "open" : "closed");
02076 ast_str_append(&body, 0, "</tuple>\n");
02077 ast_str_append(&body, 0, "</presence>\n");
02078 ast_copy_string(pidf_body, ast_str_buffer(body), size);
02079 return 0;
02080 }
02081
02082 static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor)
02083 {
02084 struct sip_monitor_instance *monitor_instance = monitor->private_data;
02085 enum sip_publish_type publish_type;
02086 struct cc_epa_entry *cc_entry;
02087
02088 if (!monitor_instance) {
02089 return -1;
02090 }
02091
02092 if (!monitor_instance->suspension_entry) {
02093
02094 if (!(monitor_instance->suspension_entry = create_epa_entry("call-completion", monitor_instance->peername))) {
02095 ast_log(LOG_WARNING, "Unable to allocate sip EPA entry for call-completion\n");
02096 ao2_ref(monitor_instance, -1);
02097 return -1;
02098 }
02099 if (!(cc_entry = ast_calloc(1, sizeof(*cc_entry)))) {
02100 ast_log(LOG_WARNING, "Unable to allocate space for instance data of EPA entry for call-completion\n");
02101 ao2_ref(monitor_instance, -1);
02102 return -1;
02103 }
02104 cc_entry->core_id = monitor->core_id;
02105 monitor_instance->suspension_entry->instance_data = cc_entry;
02106 publish_type = SIP_PUBLISH_INITIAL;
02107 } else {
02108 publish_type = SIP_PUBLISH_MODIFY;
02109 cc_entry = monitor_instance->suspension_entry->instance_data;
02110 }
02111
02112 cc_entry->current_state = CC_CLOSED;
02113
02114 if (ast_strlen_zero(monitor_instance->notify_uri)) {
02115
02116
02117
02118
02119
02120
02121
02122
02123
02124
02125
02126
02127 return 0;
02128 }
02129 construct_pidf_body(CC_CLOSED, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
02130 return transmit_publish(monitor_instance->suspension_entry, publish_type, monitor_instance->notify_uri);
02131 }
02132
02133 static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor)
02134 {
02135 struct sip_monitor_instance *monitor_instance = monitor->private_data;
02136 struct cc_epa_entry *cc_entry;
02137
02138 if (!monitor_instance) {
02139 return -1;
02140 }
02141
02142 ast_assert(monitor_instance->suspension_entry != NULL);
02143
02144 cc_entry = monitor_instance->suspension_entry->instance_data;
02145 cc_entry->current_state = CC_OPEN;
02146 if (ast_strlen_zero(monitor_instance->notify_uri)) {
02147
02148
02149
02150
02151 return 0;
02152 }
02153 construct_pidf_body(CC_OPEN, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
02154 return transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_MODIFY, monitor_instance->notify_uri);
02155 }
02156
02157 static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id)
02158 {
02159 if (*sched_id != -1) {
02160 AST_SCHED_DEL(sched, *sched_id);
02161 ao2_t_ref(monitor, -1, "Removing scheduler's reference to the monitor");
02162 }
02163 return 0;
02164 }
02165
02166 static void sip_cc_monitor_destructor(void *private_data)
02167 {
02168 struct sip_monitor_instance *monitor_instance = private_data;
02169 ao2_unlink(sip_monitor_instances, monitor_instance);
02170 ast_module_unref(ast_module_info->self);
02171 }
02172
02173 static int sip_get_cc_information(struct sip_request *req, char *subscribe_uri, size_t size, enum ast_cc_service_type *service)
02174 {
02175 char *call_info = ast_strdupa(sip_get_header(req, "Call-Info"));
02176 char *uri;
02177 char *purpose;
02178 char *service_str;
02179 static const char cc_purpose[] = "purpose=call-completion";
02180 static const int cc_purpose_len = sizeof(cc_purpose) - 1;
02181
02182 if (ast_strlen_zero(call_info)) {
02183
02184 return -1;
02185 }
02186
02187 uri = strsep(&call_info, ";");
02188
02189 while ((purpose = strsep(&call_info, ";"))) {
02190 if (!strncmp(purpose, cc_purpose, cc_purpose_len)) {
02191 break;
02192 }
02193 }
02194 if (!purpose) {
02195
02196 return -1;
02197 }
02198
02199
02200 while ((service_str = strsep(&call_info, ";"))) {
02201 if (!strncmp(service_str, "m=", 2)) {
02202 break;
02203 }
02204 }
02205 if (!service_str) {
02206
02207
02208
02209 service_str = "BS";
02210 } else {
02211
02212
02213
02214 strsep(&service_str, "=");
02215 }
02216
02217 if ((*service = service_string_to_service_type(service_str)) == AST_CC_NONE) {
02218
02219 return -1;
02220 }
02221
02222 ast_copy_string(subscribe_uri, get_in_brackets(uri), size);
02223
02224 return 0;
02225 }
02226
02227
02228
02229
02230
02231
02232
02233
02234
02235
02236
02237
02238
02239
02240
02241
02242
02243
02244 static void sip_handle_cc(struct sip_pvt *pvt, struct sip_request *req, enum ast_cc_service_type service)
02245 {
02246 enum ast_cc_monitor_policies monitor_policy = ast_get_cc_monitor_policy(pvt->cc_params);
02247 int core_id;
02248 char interface_name[AST_CHANNEL_NAME];
02249
02250 if (monitor_policy == AST_CC_MONITOR_NEVER) {
02251
02252 return;
02253 }
02254
02255 if ((core_id = ast_cc_get_current_core_id(pvt->owner)) == -1) {
02256
02257 return;
02258 }
02259
02260 ast_channel_get_device_name(pvt->owner, interface_name, sizeof(interface_name));
02261
02262 if (monitor_policy == AST_CC_MONITOR_ALWAYS || monitor_policy == AST_CC_MONITOR_NATIVE) {
02263 char subscribe_uri[SIPBUFSIZE];
02264 char device_name[AST_CHANNEL_NAME];
02265 enum ast_cc_service_type offered_service;
02266 struct sip_monitor_instance *monitor_instance;
02267 if (sip_get_cc_information(req, subscribe_uri, sizeof(subscribe_uri), &offered_service)) {
02268
02269
02270
02271
02272 goto generic;
02273 }
02274 ast_channel_get_device_name(pvt->owner, device_name, sizeof(device_name));
02275 if (!(monitor_instance = sip_monitor_instance_init(core_id, subscribe_uri, pvt->peername, device_name))) {
02276
02277 goto generic;
02278 }
02279
02280
02281
02282
02283 ast_module_ref(ast_module_info->self);
02284 ast_queue_cc_frame(pvt->owner, "SIP", pvt->dialstring, offered_service, monitor_instance);
02285 ao2_ref(monitor_instance, -1);
02286 return;
02287 }
02288
02289 generic:
02290 if (monitor_policy == AST_CC_MONITOR_GENERIC || monitor_policy == AST_CC_MONITOR_ALWAYS) {
02291 ast_queue_cc_frame(pvt->owner, AST_CC_GENERIC_MONITOR_TYPE, interface_name, service, NULL);
02292 }
02293 }
02294
02295
02296 static struct ast_tls_config sip_tls_cfg;
02297
02298
02299 static struct ast_tls_config default_tls_cfg;
02300
02301
02302 static struct ast_tcptls_session_args sip_tcp_desc = {
02303 .accept_fd = -1,
02304 .master = AST_PTHREADT_NULL,
02305 .tls_cfg = NULL,
02306 .poll_timeout = -1,
02307 .name = "SIP TCP server",
02308 .accept_fn = ast_tcptls_server_root,
02309 .worker_fn = sip_tcp_worker_fn,
02310 };
02311
02312
02313 static struct ast_tcptls_session_args sip_tls_desc = {
02314 .accept_fd = -1,
02315 .master = AST_PTHREADT_NULL,
02316 .tls_cfg = &sip_tls_cfg,
02317 .poll_timeout = -1,
02318 .name = "SIP TLS server",
02319 .accept_fn = ast_tcptls_server_root,
02320 .worker_fn = sip_tcp_worker_fn,
02321 };
02322
02323
02324
02325 #define append_history(p, event, fmt , args... ) append_history_full(p, "%-15s " fmt, event, ## args)
02326
02327 struct sip_pvt *dialog_ref_debug(struct sip_pvt *p, const char *tag, char *file, int line, const char *func)
02328 {
02329 if (p)
02330 #ifdef REF_DEBUG
02331 __ao2_ref_debug(p, 1, tag, file, line, func);
02332 #else
02333 ao2_ref(p, 1);
02334 #endif
02335 else
02336 ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
02337 return p;
02338 }
02339
02340 struct sip_pvt *dialog_unref_debug(struct sip_pvt *p, const char *tag, char *file, int line, const char *func)
02341 {
02342 if (p)
02343 #ifdef REF_DEBUG
02344 __ao2_ref_debug(p, -1, tag, file, line, func);
02345 #else
02346 ao2_ref(p, -1);
02347 #endif
02348 return NULL;
02349 }
02350
02351
02352
02353
02354 static const char *map_x_s(const struct _map_x_s *table, int x, const char *errorstring)
02355 {
02356 const struct _map_x_s *cur;
02357
02358 for (cur = table; cur->s; cur++) {
02359 if (cur->x == x) {
02360 return cur->s;
02361 }
02362 }
02363 return errorstring;
02364 }
02365
02366
02367
02368
02369 static int map_s_x(const struct _map_x_s *table, const char *s, int errorvalue)
02370 {
02371 const struct _map_x_s *cur;
02372
02373 for (cur = table; cur->s; cur++) {
02374 if (!strcasecmp(cur->s, s)) {
02375 return cur->x;
02376 }
02377 }
02378 return errorvalue;
02379 }
02380
02381 static enum AST_REDIRECTING_REASON sip_reason_str_to_code(const char *text)
02382 {
02383 enum AST_REDIRECTING_REASON ast = AST_REDIRECTING_REASON_UNKNOWN;
02384 int i;
02385
02386 for (i = 0; i < ARRAY_LEN(sip_reason_table); ++i) {
02387 if (!strcasecmp(text, sip_reason_table[i].text)) {
02388 ast = sip_reason_table[i].code;
02389 break;
02390 }
02391 }
02392
02393 return ast;
02394 }
02395
02396 static const char *sip_reason_code_to_str(enum AST_REDIRECTING_REASON code)
02397 {
02398 if (code >= 0 && code < ARRAY_LEN(sip_reason_table)) {
02399 return sip_reason_table[code].text;
02400 }
02401
02402 return "unknown";
02403 }
02404
02405
02406
02407
02408
02409
02410
02411
02412 #define check_request_transport(peer, tmpl) ({ \
02413 int ret = 0; \
02414 if (peer->socket.type == tmpl->socket.type) \
02415 ; \
02416 else if (!(peer->transports & tmpl->socket.type)) {\
02417 ast_log(LOG_ERROR, \
02418 "'%s' is not a valid transport for '%s'. we only use '%s'! ending call.\n", \
02419 sip_get_transport(tmpl->socket.type), peer->name, get_transport_list(peer->transports) \
02420 ); \
02421 ret = 1; \
02422 } else if (peer->socket.type & SIP_TRANSPORT_TLS) { \
02423 ast_log(LOG_WARNING, \
02424 "peer '%s' HAS NOT USED (OR SWITCHED TO) TLS in favor of '%s' (but this was allowed in sip.conf)!\n", \
02425 peer->name, sip_get_transport(tmpl->socket.type) \
02426 ); \
02427 } else { \
02428 ast_debug(1, \
02429 "peer '%s' has contacted us over %s even though we prefer %s.\n", \
02430 peer->name, sip_get_transport(tmpl->socket.type), sip_get_transport(peer->socket.type) \
02431 ); \
02432 }\
02433 (ret); \
02434 })
02435
02436
02437
02438
02439 static struct ast_variable *copy_vars(struct ast_variable *src)
02440 {
02441 struct ast_variable *res = NULL, *tmp, *v = NULL;
02442
02443 for (v = src ; v ; v = v->next) {
02444 if ((tmp = ast_variable_new(v->name, v->value, v->file))) {
02445 tmp->next = res;
02446 res = tmp;
02447 }
02448 }
02449 return res;
02450 }
02451
02452 static void tcptls_packet_destructor(void *obj)
02453 {
02454 struct tcptls_packet *packet = obj;
02455
02456 ast_free(packet->data);
02457 }
02458
02459 static void sip_tcptls_client_args_destructor(void *obj)
02460 {
02461 struct ast_tcptls_session_args *args = obj;
02462 if (args->tls_cfg) {
02463 ast_free(args->tls_cfg->certfile);
02464 ast_free(args->tls_cfg->pvtfile);
02465 ast_free(args->tls_cfg->cipher);
02466 ast_free(args->tls_cfg->cafile);
02467 ast_free(args->tls_cfg->capath);
02468
02469 ast_ssl_teardown(args->tls_cfg);
02470 }
02471 ast_free(args->tls_cfg);
02472 ast_free((char *) args->name);
02473 }
02474
02475 static void sip_threadinfo_destructor(void *obj)
02476 {
02477 struct sip_threadinfo *th = obj;
02478 struct tcptls_packet *packet;
02479
02480 if (th->alert_pipe[1] > -1) {
02481 close(th->alert_pipe[0]);
02482 }
02483 if (th->alert_pipe[1] > -1) {
02484 close(th->alert_pipe[1]);
02485 }
02486 th->alert_pipe[0] = th->alert_pipe[1] = -1;
02487
02488 while ((packet = AST_LIST_REMOVE_HEAD(&th->packet_q, entry))) {
02489 ao2_t_ref(packet, -1, "thread destruction, removing packet from frame queue");
02490 }
02491
02492 if (th->tcptls_session) {
02493 ao2_t_ref(th->tcptls_session, -1, "remove tcptls_session for sip_threadinfo object");
02494 }
02495 }
02496
02497
02498 static struct sip_threadinfo *sip_threadinfo_create(struct ast_tcptls_session_instance *tcptls_session, int transport)
02499 {
02500 struct sip_threadinfo *th;
02501
02502 if (!tcptls_session || !(th = ao2_alloc(sizeof(*th), sip_threadinfo_destructor))) {
02503 return NULL;
02504 }
02505
02506 th->alert_pipe[0] = th->alert_pipe[1] = -1;
02507
02508 if (pipe(th->alert_pipe) == -1) {
02509 ao2_t_ref(th, -1, "Failed to open alert pipe on sip_threadinfo");
02510 ast_log(LOG_ERROR, "Could not create sip alert pipe in tcptls thread, error %s\n", strerror(errno));
02511 return NULL;
02512 }
02513 ao2_t_ref(tcptls_session, +1, "tcptls_session ref for sip_threadinfo object");
02514 th->tcptls_session = tcptls_session;
02515 th->type = transport ? transport : (tcptls_session->ssl ? SIP_TRANSPORT_TLS: SIP_TRANSPORT_TCP);
02516 ao2_t_link(threadt, th, "Adding new tcptls helper thread");
02517 ao2_t_ref(th, -1, "Decrementing threadinfo ref from alloc, only table ref remains");
02518 return th;
02519 }
02520
02521
02522 static int sip_tcptls_write(struct ast_tcptls_session_instance *tcptls_session, const void *buf, size_t len)
02523 {
02524 int res = len;
02525 struct sip_threadinfo *th = NULL;
02526 struct tcptls_packet *packet = NULL;
02527 struct sip_threadinfo tmp = {
02528 .tcptls_session = tcptls_session,
02529 };
02530 enum sip_tcptls_alert alert = TCPTLS_ALERT_DATA;
02531
02532 if (!tcptls_session) {
02533 return XMIT_ERROR;
02534 }
02535
02536 ao2_lock(tcptls_session);
02537
02538 if ((tcptls_session->fd == -1) ||
02539 !(th = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread")) ||
02540 !(packet = ao2_alloc(sizeof(*packet), tcptls_packet_destructor)) ||
02541 !(packet->data = ast_str_create(len))) {
02542 goto tcptls_write_setup_error;
02543 }
02544
02545
02546 ast_str_set(&packet->data, 0, "%s", (char *) buf);
02547 packet->len = len;
02548
02549
02550
02551
02552 ao2_lock(th);
02553 if (write(th->alert_pipe[1], &alert, sizeof(alert)) == -1) {
02554 ast_log(LOG_ERROR, "write() to alert pipe failed: %s\n", strerror(errno));
02555 ao2_t_ref(packet, -1, "could not write to alert pipe, remove packet");
02556 packet = NULL;
02557 res = XMIT_ERROR;
02558 } else {
02559 AST_LIST_INSERT_TAIL(&th->packet_q, packet, entry);
02560 }
02561 ao2_unlock(th);
02562
02563 ao2_unlock(tcptls_session);
02564 ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo object after finding it");
02565 return res;
02566
02567 tcptls_write_setup_error:
02568 if (th) {
02569 ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo obj, could not create packet");
02570 }
02571 if (packet) {
02572 ao2_t_ref(packet, -1, "could not allocate packet's data");
02573 }
02574 ao2_unlock(tcptls_session);
02575
02576 return XMIT_ERROR;
02577 }
02578
02579
02580 static void *sip_tcp_worker_fn(void *data)
02581 {
02582 struct ast_tcptls_session_instance *tcptls_session = data;
02583
02584 return _sip_tcp_helper_thread(tcptls_session);
02585 }
02586
02587
02588 static void sip_websocket_callback(struct ast_websocket *session, struct ast_variable *parameters, struct ast_variable *headers)
02589 {
02590 int res;
02591
02592 if (ast_websocket_set_nonblock(session)) {
02593 goto end;
02594 }
02595
02596 while ((res = ast_wait_for_input(ast_websocket_fd(session), -1)) > 0) {
02597 char *payload;
02598 uint64_t payload_len;
02599 enum ast_websocket_opcode opcode;
02600 int fragmented;
02601
02602 if (ast_websocket_read(session, &payload, &payload_len, &opcode, &fragmented)) {
02603
02604 break;
02605 }
02606
02607 if (opcode == AST_WEBSOCKET_OPCODE_TEXT || opcode == AST_WEBSOCKET_OPCODE_BINARY) {
02608 struct sip_request req = { 0, };
02609
02610 if (!(req.data = ast_str_create(payload_len + 1))) {
02611 goto end;
02612 }
02613
02614 if (ast_str_set(&req.data, -1, "%s", payload) == AST_DYNSTR_BUILD_FAILED) {
02615 deinit_req(&req);
02616 goto end;
02617 }
02618
02619 req.socket.fd = ast_websocket_fd(session);
02620 set_socket_transport(&req.socket, ast_websocket_is_secure(session) ? SIP_TRANSPORT_WSS : SIP_TRANSPORT_WS);
02621 req.socket.ws_session = session;
02622
02623 handle_request_do(&req, ast_websocket_remote_address(session));
02624 deinit_req(&req);
02625
02626 } else if (opcode == AST_WEBSOCKET_OPCODE_CLOSE) {
02627 break;
02628 }
02629 }
02630
02631 end:
02632 ast_websocket_unref(session);
02633 }
02634
02635
02636
02637
02638
02639
02640
02641
02642 static int sip_check_authtimeout(time_t start)
02643 {
02644 int timeout;
02645 time_t now;
02646 if(time(&now) == -1) {
02647 ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
02648 return -1;
02649 }
02650
02651 timeout = (authtimeout - (now - start)) * 1000;
02652 if (timeout < 0) {
02653
02654 return 0;
02655 }
02656
02657 return timeout;
02658 }
02659
02660
02661
02662
02663
02664
02665
02666
02667
02668
02669
02670
02671
02672
02673
02674
02675
02676
02677
02678
02679
02680 static int sip_tls_read(struct sip_request *req, struct sip_request *reqcpy, struct ast_tcptls_session_instance *tcptls_session,
02681 int authenticated, time_t start, struct sip_threadinfo *me)
02682 {
02683 int res, content_length, after_poll = 1, need_poll = 1;
02684 size_t datalen = ast_str_strlen(req->data);
02685 char buf[1024] = "";
02686 int timeout = -1;
02687
02688
02689 while (datalen < 4 || strncmp(REQ_OFFSET_TO_STR(req, data->used - 4), "\r\n\r\n", 4)) {
02690 if (!tcptls_session->client && !authenticated) {
02691 if ((timeout = sip_check_authtimeout(start)) < 0) {
02692 ast_debug(2, "SIP TLS server failed to determine authentication timeout\n");
02693 return -1;
02694 }
02695
02696 if (timeout == 0) {
02697 ast_debug(2, "SIP TLS server timed out\n");
02698 return -1;
02699 }
02700 } else {
02701 timeout = -1;
02702 }
02703
02704
02705
02706
02707 if (need_poll) {
02708 need_poll = 0;
02709 after_poll = 1;
02710 res = ast_wait_for_input(tcptls_session->fd, timeout);
02711 if (res < 0) {
02712 ast_debug(2, "SIP TLS server :: ast_wait_for_input returned %d\n", res);
02713 return -1;
02714 } else if (res == 0) {
02715
02716 ast_debug(2, "SIP TLS server timed out\n");
02717 return -1;
02718 }
02719 }
02720
02721 ao2_lock(tcptls_session);
02722 if (!fgets(buf, sizeof(buf), tcptls_session->f)) {
02723 ao2_unlock(tcptls_session);
02724 if (after_poll) {
02725 return -1;
02726 } else {
02727 need_poll = 1;
02728 continue;
02729 }
02730 }
02731 ao2_unlock(tcptls_session);
02732 after_poll = 0;
02733 if (me->stop) {
02734 return -1;
02735 }
02736 ast_str_append(&req->data, 0, "%s", buf);
02737
02738 datalen = ast_str_strlen(req->data);
02739 if (datalen > SIP_MAX_PACKET_SIZE) {
02740 ast_log(LOG_WARNING, "Rejecting TLS packet from '%s' because way too large: %zu\n",
02741 ast_sockaddr_stringify(&tcptls_session->remote_address), datalen);
02742 return -1;
02743 }
02744 }
02745 copy_request(reqcpy, req);
02746 parse_request(reqcpy);
02747
02748 if (sscanf(sip_get_header(reqcpy, "Content-Length"), "%30d", &content_length)) {
02749 while (content_length > 0) {
02750 size_t bytes_read;
02751 if (!tcptls_session->client && !authenticated) {
02752 if ((timeout = sip_check_authtimeout(start)) < 0) {
02753 return -1;
02754 }
02755
02756 if (timeout == 0) {
02757 ast_debug(2, "SIP TLS server timed out\n");
02758 return -1;
02759 }
02760 } else {
02761 timeout = -1;
02762 }
02763
02764 if (need_poll) {
02765 need_poll = 0;
02766 after_poll = 1;
02767 res = ast_wait_for_input(tcptls_session->fd, timeout);
02768 if (res < 0) {
02769 ast_debug(2, "SIP TLS server :: ast_wait_for_input returned %d\n", res);
02770 return -1;
02771 } else if (res == 0) {
02772
02773 ast_debug(2, "SIP TLS server timed out\n");
02774 return -1;
02775 }
02776 }
02777
02778 ao2_lock(tcptls_session);
02779 if (!(bytes_read = fread(buf, 1, MIN(sizeof(buf) - 1, content_length), tcptls_session->f))) {
02780 ao2_unlock(tcptls_session);
02781 if (after_poll) {
02782 return -1;
02783 } else {
02784 need_poll = 1;
02785 continue;
02786 }
02787 }
02788 buf[bytes_read] = '\0';
02789 ao2_unlock(tcptls_session);
02790 after_poll = 0;
02791 if (me->stop) {
02792 return -1;
02793 }
02794 content_length -= strlen(buf);
02795 ast_str_append(&req->data, 0, "%s", buf);
02796
02797 datalen = ast_str_strlen(req->data);
02798 if (datalen > SIP_MAX_PACKET_SIZE) {
02799 ast_log(LOG_WARNING, "Rejecting TLS packet from '%s' because way too large: %zu\n",
02800 ast_sockaddr_stringify(&tcptls_session->remote_address), datalen);
02801 return -1;
02802 }
02803 }
02804 }
02805
02806
02807 return 0;
02808 }
02809
02810
02811
02812
02813 enum message_integrity {
02814
02815
02816
02817
02818 MESSAGE_INVALID,
02819
02820
02821
02822 MESSAGE_FRAGMENT,
02823
02824
02825
02826
02827 MESSAGE_FRAGMENT_COMPLETE,
02828
02829
02830
02831 MESSAGE_COMPLETE,
02832 };
02833
02834
02835
02836
02837
02838
02839
02840
02841 static int read_raw_content_length(const char *message)
02842 {
02843 char *content_length_str;
02844 int content_length = -1;
02845
02846 struct ast_str *msg_copy;
02847 char *msg;
02848
02849
02850 if (!(msg_copy = ast_str_create(strlen(message) + 1))) {
02851 return -1;
02852 }
02853 ast_str_set(&msg_copy, 0, "%s", message);
02854
02855 if (sip_cfg.pedanticsipchecking) {
02856 lws2sws(msg_copy);
02857 }
02858
02859 msg = ast_str_buffer(msg_copy);
02860
02861
02862 if ((content_length_str = strcasestr(msg, "\nContent-Length:"))) {
02863 content_length_str += sizeof("\nContent-Length:") - 1;
02864 } else if ((content_length_str = strcasestr(msg, "\nl:"))) {
02865 content_length_str += sizeof("\nl:") - 1;
02866 } else {
02867
02868
02869
02870
02871
02872 goto done;
02873 }
02874
02875
02876 if (!strchr(content_length_str, '\n')) {
02877 goto done;
02878 }
02879
02880 if (sscanf(content_length_str, "%30d", &content_length) != 1) {
02881 content_length = -1;
02882 }
02883
02884 done:
02885 ast_free(msg_copy);
02886 return content_length;
02887 }
02888
02889
02890
02891
02892
02893
02894
02895
02896
02897
02898
02899
02900
02901 static enum message_integrity check_message_integrity(struct ast_str **request, struct ast_str **overflow)
02902 {
02903 char *message = ast_str_buffer(*request);
02904 char *body;
02905 int content_length;
02906 int message_len = ast_str_strlen(*request);
02907 int body_len;
02908
02909
02910
02911
02912
02913
02914 body = strstr(message, "\r\n\r\n");
02915 if (!body) {
02916
02917
02918
02919 return MESSAGE_FRAGMENT;
02920 }
02921 body += sizeof("\r\n\r\n") - 1;
02922 body_len = message_len - (body - message);
02923
02924 body[-1] = '\0';
02925 content_length = read_raw_content_length(message);
02926 body[-1] = '\n';
02927
02928 if (content_length < 0) {
02929 return MESSAGE_INVALID;
02930 } else if (content_length == 0) {
02931
02932
02933
02934
02935 if (body_len == 0) {
02936 return MESSAGE_COMPLETE;
02937 } else {
02938 ast_str_append(overflow, 0, "%s", body);
02939 ast_str_truncate(*request, message_len - body_len);
02940 return MESSAGE_FRAGMENT_COMPLETE;
02941 }
02942 }
02943
02944
02945
02946 if (body_len < content_length) {
02947
02948 return MESSAGE_FRAGMENT;
02949 } else if (body_len > content_length) {
02950
02951
02952
02953 ast_str_append(overflow, 0, "%s", body + content_length);
02954 ast_str_truncate(*request, message_len - (body_len - content_length));
02955 return MESSAGE_FRAGMENT_COMPLETE;
02956 } else {
02957
02958 return MESSAGE_COMPLETE;
02959 }
02960 }
02961
02962
02963
02964
02965
02966
02967
02968
02969
02970 static int sip_tcp_read(struct sip_request *req, struct ast_tcptls_session_instance *tcptls_session,
02971 int authenticated, time_t start)
02972 {
02973 enum message_integrity message_integrity = MESSAGE_FRAGMENT;
02974
02975 while (message_integrity == MESSAGE_FRAGMENT) {
02976 size_t datalen;
02977
02978 if (ast_str_strlen(tcptls_session->overflow_buf) == 0) {
02979 char readbuf[4097];
02980 int timeout;
02981 int res;
02982 if (!tcptls_session->client && !authenticated) {
02983 if ((timeout = sip_check_authtimeout(start)) < 0) {
02984 return -1;
02985 }
02986
02987 if (timeout == 0) {
02988 ast_debug(2, "SIP TCP server timed out\n");
02989 return -1;
02990 }
02991 } else {
02992 timeout = -1;
02993 }
02994 res = ast_wait_for_input(tcptls_session->fd, timeout);
02995 if (res < 0) {
02996 ast_debug(2, "SIP TCP server :: ast_wait_for_input returned %d\n", res);
02997 return -1;
02998 } else if (res == 0) {
02999 ast_debug(2, "SIP TCP server timed out\n");
03000 return -1;
03001 }
03002
03003 res = recv(tcptls_session->fd, readbuf, sizeof(readbuf) - 1, 0);
03004 if (res < 0) {
03005 ast_debug(2, "SIP TCP server error when receiving data\n");
03006 return -1;
03007 } else if (res == 0) {
03008 ast_debug(2, "SIP TCP server has shut down\n");
03009 return -1;
03010 }
03011 readbuf[res] = '\0';
03012 ast_str_append(&req->data, 0, "%s", readbuf);
03013 } else {
03014 ast_str_append(&req->data, 0, "%s", ast_str_buffer(tcptls_session->overflow_buf));
03015 ast_str_reset(tcptls_session->overflow_buf);
03016 }
03017
03018 datalen = ast_str_strlen(req->data);
03019 if (datalen > SIP_MAX_PACKET_SIZE) {
03020 ast_log(LOG_WARNING, "Rejecting TCP packet from '%s' because way too large: %zu\n",
03021 ast_sockaddr_stringify(&tcptls_session->remote_address), datalen);
03022 return -1;
03023 }
03024
03025 message_integrity = check_message_integrity(&req->data, &tcptls_session->overflow_buf);
03026 }
03027
03028 return 0;
03029 }
03030
03031
03032
03033
03034 static void *_sip_tcp_helper_thread(struct ast_tcptls_session_instance *tcptls_session)
03035 {
03036 int res, timeout = -1, authenticated = 0, flags;
03037 time_t start;
03038 struct sip_request req = { 0, } , reqcpy = { 0, };
03039 struct sip_threadinfo *me = NULL;
03040 char buf[1024] = "";
03041 struct pollfd fds[2] = { { 0 }, { 0 }, };
03042 struct ast_tcptls_session_args *ca = NULL;
03043
03044
03045
03046
03047
03048
03049
03050
03051
03052
03053
03054
03055 if (!tcptls_session->client) {
03056 if (ast_atomic_fetchadd_int(&unauth_sessions, +1) >= authlimit) {
03057
03058 goto cleanup;
03059 }
03060
03061 if ((flags = fcntl(tcptls_session->fd, F_GETFL)) == -1) {
03062 ast_log(LOG_ERROR, "error setting socket to non blocking mode, fcntl() failed: %s\n", strerror(errno));
03063 goto cleanup;
03064 }
03065
03066 flags |= O_NONBLOCK;
03067 if (fcntl(tcptls_session->fd, F_SETFL, flags) == -1) {
03068 ast_log(LOG_ERROR, "error setting socket to non blocking mode, fcntl() failed: %s\n", strerror(errno));
03069 goto cleanup;
03070 }
03071
03072 if (!(me = sip_threadinfo_create(tcptls_session, tcptls_session->ssl ? SIP_TRANSPORT_TLS : SIP_TRANSPORT_TCP))) {
03073 goto cleanup;
03074 }
03075 ao2_t_ref(me, +1, "Adding threadinfo ref for tcp_helper_thread");
03076 } else {
03077 struct sip_threadinfo tmp = {
03078 .tcptls_session = tcptls_session,
03079 };
03080
03081 if ((!(ca = tcptls_session->parent)) ||
03082 (!(me = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread"))) ||
03083 (!(tcptls_session = ast_tcptls_client_start(tcptls_session)))) {
03084 goto cleanup;
03085 }
03086 }
03087
03088 flags = 1;
03089 if (setsockopt(tcptls_session->fd, SOL_SOCKET, SO_KEEPALIVE, &flags, sizeof(flags))) {
03090 ast_log(LOG_ERROR, "error enabling TCP keep-alives on sip socket: %s\n", strerror(errno));
03091 goto cleanup;
03092 }
03093
03094 me->threadid = pthread_self();
03095 ast_debug(2, "Starting thread for %s server\n", tcptls_session->ssl ? "TLS" : "TCP");
03096
03097
03098 fds[0].fd = tcptls_session->fd;
03099 fds[1].fd = me->alert_pipe[0];
03100 fds[0].events = fds[1].events = POLLIN | POLLPRI;
03101
03102 if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
03103 goto cleanup;
03104 }
03105 if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET))) {
03106 goto cleanup;
03107 }
03108
03109 if(time(&start) == -1) {
03110 ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
03111 goto cleanup;
03112 }
03113
03114 for (;;) {
03115 struct ast_str *str_save;
03116
03117 if (!tcptls_session->client && req.authenticated && !authenticated) {
03118 authenticated = 1;
03119 ast_atomic_fetchadd_int(&unauth_sessions, -1);
03120 }
03121
03122
03123 if (!tcptls_session->client && !authenticated ) {
03124 if ((timeout = sip_check_authtimeout(start)) < 0) {
03125 goto cleanup;
03126 }
03127
03128 if (timeout == 0) {
03129 ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "TLS": "TCP");
03130 goto cleanup;
03131 }
03132 } else {
03133 timeout = -1;
03134 }
03135
03136 if (ast_str_strlen(tcptls_session->overflow_buf) == 0) {
03137 res = ast_poll(fds, 2, timeout);
03138 if (res < 0) {
03139 ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", tcptls_session->ssl ? "TLS": "TCP", res);
03140 goto cleanup;
03141 } else if (res == 0) {
03142
03143 ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "TLS": "TCP");
03144 goto cleanup;
03145 }
03146 }
03147
03148
03149
03150
03151
03152 if (fds[0].revents || (ast_str_strlen(tcptls_session->overflow_buf) > 0)) {
03153 fds[0].revents = 0;
03154
03155
03156 str_save = req.data;
03157 memset(&req, 0, sizeof(req));
03158 req.data = str_save;
03159 ast_str_reset(req.data);
03160
03161 str_save = reqcpy.data;
03162 memset(&reqcpy, 0, sizeof(reqcpy));
03163 reqcpy.data = str_save;
03164 ast_str_reset(reqcpy.data);
03165
03166 memset(buf, 0, sizeof(buf));
03167
03168 if (tcptls_session->ssl) {
03169 set_socket_transport(&req.socket, SIP_TRANSPORT_TLS);
03170 req.socket.port = htons(ourport_tls);
03171 } else {
03172 set_socket_transport(&req.socket, SIP_TRANSPORT_TCP);
03173 req.socket.port = htons(ourport_tcp);
03174 }
03175 req.socket.fd = tcptls_session->fd;
03176 if (tcptls_session->ssl) {
03177 res = sip_tls_read(&req, &reqcpy, tcptls_session, authenticated, start, me);
03178 } else {
03179 res = sip_tcp_read(&req, tcptls_session, authenticated, start);
03180 }
03181
03182 if (res < 0) {
03183 goto cleanup;
03184 }
03185
03186 req.socket.tcptls_session = tcptls_session;
03187 req.socket.ws_session = NULL;
03188 handle_request_do(&req, &tcptls_session->remote_address);
03189 }
03190
03191 if (fds[1].revents) {
03192 enum sip_tcptls_alert alert;
03193 struct tcptls_packet *packet;
03194
03195 fds[1].revents = 0;
03196
03197 if (read(me->alert_pipe[0], &alert, sizeof(alert)) == -1) {
03198 ast_log(LOG_ERROR, "read() failed: %s\n", strerror(errno));
03199 continue;
03200 }
03201
03202 switch (alert) {
03203 case TCPTLS_ALERT_STOP:
03204 goto cleanup;
03205 case TCPTLS_ALERT_DATA:
03206 ao2_lock(me);
03207 if (!(packet = AST_LIST_REMOVE_HEAD(&me->packet_q, entry))) {
03208 ast_log(LOG_WARNING, "TCPTLS thread alert_pipe indicated packet should be sent, but frame_q is empty\n");
03209 }
03210 ao2_unlock(me);
03211
03212 if (packet) {
03213 if (ast_tcptls_server_write(tcptls_session, ast_str_buffer(packet->data), packet->len) == -1) {
03214 ast_log(LOG_WARNING, "Failure to write to tcp/tls socket\n");
03215 }
03216 ao2_t_ref(packet, -1, "tcptls packet sent, this is no longer needed");
03217 }
03218 break;
03219 default:
03220 ast_log(LOG_ERROR, "Unknown tcptls thread alert '%d'\n", alert);
03221 }
03222 }
03223 }
03224
03225 ast_debug(2, "Shutting down thread for %s server\n", tcptls_session->ssl ? "TLS" : "TCP");
03226
03227 cleanup:
03228 if (tcptls_session && !tcptls_session->client && !authenticated) {
03229 ast_atomic_fetchadd_int(&unauth_sessions, -1);
03230 }
03231
03232 if (me) {
03233 ao2_t_unlink(threadt, me, "Removing tcptls helper thread, thread is closing");
03234 ao2_t_ref(me, -1, "Removing tcp_helper_threads threadinfo ref");
03235 }
03236 deinit_req(&reqcpy);
03237 deinit_req(&req);
03238
03239
03240 if (ca) {
03241 ao2_t_ref(ca, -1, "closing tcptls thread, getting rid of client tcptls_session arguments");
03242 }
03243
03244 if (tcptls_session) {
03245 ao2_lock(tcptls_session);
03246 ast_tcptls_close_session_file(tcptls_session);
03247 tcptls_session->parent = NULL;
03248 ao2_unlock(tcptls_session);
03249
03250 ao2_ref(tcptls_session, -1);
03251 tcptls_session = NULL;
03252 }
03253 return NULL;
03254 }
03255
03256 #ifdef REF_DEBUG
03257 struct sip_peer *_ref_peer(struct sip_peer *peer, char *tag, char *file, int line, const char *func)
03258 {
03259 if (peer)
03260 __ao2_ref_debug(peer, 1, tag, file, line, func);
03261 else
03262 ast_log(LOG_ERROR, "Attempt to Ref a null peer pointer\n");
03263 return peer;
03264 }
03265
03266 void *_unref_peer(struct sip_peer *peer, char *tag, char *file, int line, const char *func)
03267 {
03268 if (peer)
03269 __ao2_ref_debug(peer, -1, tag, file, line, func);
03270 return NULL;
03271 }
03272 #else
03273
03274
03275
03276
03277
03278 void *sip_unref_peer(struct sip_peer *peer, char *tag)
03279 {
03280 ao2_t_ref(peer, -1, tag);
03281 return NULL;
03282 }
03283
03284 struct sip_peer *sip_ref_peer(struct sip_peer *peer, char *tag)
03285 {
03286 ao2_t_ref(peer, 1, tag);
03287 return peer;
03288 }
03289 #endif
03290
03291 static void peer_sched_cleanup(struct sip_peer *peer)
03292 {
03293 if (peer->pokeexpire != -1) {
03294 AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
03295 sip_unref_peer(peer, "removing poke peer ref"));
03296 }
03297 if (peer->expire != -1) {
03298 AST_SCHED_DEL_UNREF(sched, peer->expire,
03299 sip_unref_peer(peer, "remove register expire ref"));
03300 }
03301 if (peer->keepalivesend != -1) {
03302 AST_SCHED_DEL_UNREF(sched, peer->keepalivesend,
03303 sip_unref_peer(peer, "remove keepalive peer ref"));
03304 }
03305 }
03306
03307 typedef enum {
03308 SIP_PEERS_MARKED,
03309 SIP_PEERS_ALL,
03310 } peer_unlink_flag_t;
03311
03312
03313
03314 static int match_and_cleanup_peer_sched(void *peerobj, void *arg, int flags)
03315 {
03316 struct sip_peer *peer = peerobj;
03317 peer_unlink_flag_t which = *(peer_unlink_flag_t *)arg;
03318
03319 if (which == SIP_PEERS_ALL || peer->the_mark) {
03320 peer_sched_cleanup(peer);
03321 if (peer->dnsmgr) {
03322 ast_dnsmgr_release(peer->dnsmgr);
03323 peer->dnsmgr = NULL;
03324 sip_unref_peer(peer, "Release peer from dnsmgr");
03325 }
03326 return CMP_MATCH;
03327 }
03328 return 0;
03329 }
03330
03331 static void unlink_peers_from_tables(peer_unlink_flag_t flag)
03332 {
03333 ao2_t_callback(peers, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE,
03334 match_and_cleanup_peer_sched, &flag, "initiating callback to remove marked peers");
03335 ao2_t_callback(peers_by_ip, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE,
03336 match_and_cleanup_peer_sched, &flag, "initiating callback to remove marked peers");
03337 }
03338
03339
03340 static void unlink_marked_peers_from_tables(void)
03341 {
03342 unlink_peers_from_tables(SIP_PEERS_MARKED);
03343 }
03344
03345 static void unlink_all_peers_from_tables(void)
03346 {
03347 unlink_peers_from_tables(SIP_PEERS_ALL);
03348 }
03349
03350
03351 static void unlink_peer_from_tables(struct sip_peer *peer)
03352 {
03353 ao2_t_unlink(peers, peer, "ao2_unlink of peer from peers table");
03354 if (!ast_sockaddr_isnull(&peer->addr)) {
03355 ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
03356 }
03357 }
03358
03359
03360
03361
03362
03363
03364
03365
03366
03367
03368
03369
03370 static void ref_proxy(struct sip_pvt *pvt, struct sip_proxy *proxy)
03371 {
03372 struct sip_proxy *old_obproxy = pvt->outboundproxy;
03373
03374
03375
03376 if (proxy && proxy != &sip_cfg.outboundproxy) {
03377 ao2_ref(proxy, +1);
03378 }
03379 pvt->outboundproxy = proxy;
03380 if (old_obproxy && old_obproxy != &sip_cfg.outboundproxy) {
03381 ao2_ref(old_obproxy, -1);
03382 }
03383 }
03384
03385
03386
03387
03388
03389
03390
03391
03392 void dialog_unlink_all(struct sip_pvt *dialog)
03393 {
03394 struct sip_pkt *cp;
03395 struct ast_channel *owner;
03396
03397 dialog_ref(dialog, "Let's bump the count in the unlink so it doesn't accidentally become dead before we are done");
03398
03399 ao2_t_unlink(dialogs, dialog, "unlinking dialog via ao2_unlink");
03400 ao2_t_unlink(dialogs_needdestroy, dialog, "unlinking dialog_needdestroy via ao2_unlink");
03401 ao2_t_unlink(dialogs_rtpcheck, dialog, "unlinking dialog_rtpcheck via ao2_unlink");
03402
03403
03404 owner = sip_pvt_lock_full(dialog);
03405 if (owner) {
03406 ast_debug(1, "Detaching from channel %s\n", ast_channel_name(owner));
03407 ast_channel_tech_pvt_set(owner, dialog_unref(ast_channel_tech_pvt(owner), "resetting channel dialog ptr in unlink_all"));
03408 ast_channel_unlock(owner);
03409 ast_channel_unref(owner);
03410 dialog->owner = NULL;
03411 }
03412 sip_pvt_unlock(dialog);
03413
03414 if (dialog->registry) {
03415 if (dialog->registry->call == dialog) {
03416 dialog->registry->call = dialog_unref(dialog->registry->call, "nulling out the registry's call dialog field in unlink_all");
03417 }
03418 dialog->registry = registry_unref(dialog->registry, "delete dialog->registry");
03419 }
03420 if (dialog->stateid != -1) {
03421 ast_extension_state_del(dialog->stateid, cb_extensionstate);
03422 dialog->stateid = -1;
03423 }
03424
03425 if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog) {
03426 dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
03427 }
03428 if (dialog->relatedpeer && dialog->relatedpeer->call == dialog) {
03429 dialog->relatedpeer->call = dialog_unref(dialog->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
03430 }
03431
03432
03433 while((cp = dialog->packets)) {
03434 dialog->packets = dialog->packets->next;
03435 AST_SCHED_DEL(sched, cp->retransid);
03436 dialog_unref(cp->owner, "remove all current packets in this dialog, and the pointer to the dialog too as part of __sip_destroy");
03437 if (cp->data) {
03438 ast_free(cp->data);
03439 }
03440 ast_free(cp);
03441 }
03442
03443 AST_SCHED_DEL_UNREF(sched, dialog->waitid, dialog_unref(dialog, "when you delete the waitid sched, you should dec the refcount for the stored dialog ptr"));
03444
03445 AST_SCHED_DEL_UNREF(sched, dialog->initid, dialog_unref(dialog, "when you delete the initid sched, you should dec the refcount for the stored dialog ptr"));
03446
03447 if (dialog->autokillid > -1) {
03448 AST_SCHED_DEL_UNREF(sched, dialog->autokillid, dialog_unref(dialog, "when you delete the autokillid sched, you should dec the refcount for the stored dialog ptr"));
03449 }
03450
03451 if (dialog->request_queue_sched_id > -1) {
03452 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"));
03453 }
03454
03455 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"));
03456
03457 if (dialog->t38id > -1) {
03458 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"));
03459 }
03460
03461 if (dialog->stimer) {
03462 stop_session_timer(dialog);
03463 }
03464
03465 dialog_unref(dialog, "Let's unbump the count in the unlink so the poor pvt can disappear if it is time");
03466 }
03467
03468 void *registry_unref(struct sip_registry *reg, char *tag)
03469 {
03470 ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount - 1);
03471 ASTOBJ_UNREF(reg, sip_registry_destroy);
03472 return NULL;
03473 }
03474
03475
03476 static struct sip_registry *registry_addref(struct sip_registry *reg, char *tag)
03477 {
03478 ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount + 1);
03479 return ASTOBJ_REF(reg);
03480 }
03481
03482
03483 static struct ast_udptl_protocol sip_udptl = {
03484 .type = "SIP",
03485 .get_udptl_info = sip_get_udptl_peer,
03486 .set_udptl_peer = sip_set_udptl_peer,
03487 };
03488
03489 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
03490 __attribute__((format(printf, 2, 3)));
03491
03492
03493
03494 static const char *referstatus2str(enum referstatus rstatus)
03495 {
03496 return map_x_s(referstatusstrings, rstatus, "");
03497 }
03498
03499 static inline void pvt_set_needdestroy(struct sip_pvt *pvt, const char *reason)
03500 {
03501 if (pvt->final_destruction_scheduled) {
03502 return;
03503 }
03504 append_history(pvt, "NeedDestroy", "Setting needdestroy because %s", reason);
03505 if (!pvt->needdestroy) {
03506 pvt->needdestroy = 1;
03507 ao2_t_link(dialogs_needdestroy, pvt, "link pvt into dialogs_needdestroy container");
03508 }
03509 }
03510
03511
03512
03513
03514 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
03515 {
03516 if (p->initreq.headers) {
03517 ast_debug(1, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
03518 } else {
03519 ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
03520 }
03521
03522 copy_request(&p->initreq, req);
03523 parse_request(&p->initreq);
03524 if (req->debug) {
03525 ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
03526 }
03527 }
03528
03529
03530 static void sip_alreadygone(struct sip_pvt *dialog)
03531 {
03532 ast_debug(3, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
03533 dialog->alreadygone = 1;
03534 }
03535
03536
03537 static int proxy_update(struct sip_proxy *proxy)
03538 {
03539
03540
03541 if (!ast_sockaddr_parse(&proxy->ip, proxy->name, 0)) {
03542
03543
03544 proxy->ip.ss.ss_family = get_address_family_filter(SIP_TRANSPORT_UDP);
03545 if (ast_get_ip_or_srv(&proxy->ip, proxy->name, sip_cfg.srvlookup ? "_sip._udp" : NULL) < 0) {
03546 ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
03547 return FALSE;
03548 }
03549
03550 }
03551
03552 ast_sockaddr_set_port(&proxy->ip, proxy->port);
03553
03554 proxy->last_dnsupdate = time(NULL);
03555 return TRUE;
03556 }
03557
03558
03559
03560
03561 static struct sip_proxy *proxy_from_config(const char *proxy, int sipconf_lineno, struct sip_proxy *dest)
03562 {
03563 char *mutable_proxy, *sep, *name;
03564 int allocated = 0;
03565
03566 if (!dest) {
03567 dest = ao2_alloc(sizeof(struct sip_proxy), NULL);
03568 if (!dest) {
03569 ast_log(LOG_WARNING, "Unable to allocate config storage for proxy\n");
03570 return NULL;
03571 }
03572 allocated = 1;
03573 }
03574
03575
03576 mutable_proxy = ast_skip_blanks(ast_strdupa(proxy));
03577 sep = strchr(mutable_proxy, ',');
03578 if (sep) {
03579 *sep++ = '\0';
03580 dest->force = !strncasecmp(ast_skip_blanks(sep), "force", 5);
03581 } else {
03582 dest->force = FALSE;
03583 }
03584
03585 sip_parse_host(mutable_proxy, sipconf_lineno, &name, &dest->port, &dest->transport);
03586
03587
03588 if (ast_strlen_zero(name)) {
03589 if (allocated) {
03590 ao2_ref(dest, -1);
03591 } else {
03592 dest->name[0] = '\0';
03593 }
03594 return NULL;
03595 }
03596 ast_copy_string(dest->name, name, sizeof(dest->name));
03597
03598
03599 proxy_update(dest);
03600
03601 return dest;
03602 }
03603
03604
03605
03606
03607
03608 unsigned int port_str2int(const char *pt, unsigned int standard)
03609 {
03610 int port = standard;
03611 if (ast_strlen_zero(pt) || (sscanf(pt, "%30d", &port) != 1) || (port < 1) || (port > 65535)) {
03612 port = standard;
03613 }
03614
03615 return port;
03616 }
03617
03618
03619 static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
03620 {
03621 if (dialog && dialog->options && dialog->options->outboundproxy) {
03622 if (sipdebug) {
03623 ast_debug(1, "OBPROXY: Applying dialplan set OBproxy to this call\n");
03624 }
03625 append_history(dialog, "OBproxy", "Using dialplan obproxy %s", dialog->options->outboundproxy->name);
03626 return dialog->options->outboundproxy;
03627 }
03628 if (peer && peer->outboundproxy) {
03629 if (sipdebug) {
03630 ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
03631 }
03632 append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
03633 return peer->outboundproxy;
03634 }
03635 if (sip_cfg.outboundproxy.name[0]) {
03636 if (sipdebug) {
03637 ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
03638 }
03639 append_history(dialog, "OBproxy", "Using global obproxy %s", sip_cfg.outboundproxy.name);
03640 return &sip_cfg.outboundproxy;
03641 }
03642 if (sipdebug) {
03643 ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
03644 }
03645 return NULL;
03646 }
03647
03648
03649
03650
03651
03652
03653
03654 static int method_match(enum sipmethod id, const char *name)
03655 {
03656 int len = strlen(sip_methods[id].text);
03657 int l_name = name ? strlen(name) : 0;
03658
03659 return (l_name >= len && name && name[len] < 33 &&
03660 !strncasecmp(sip_methods[id].text, name, len));
03661 }
03662
03663
03664 static int find_sip_method(const char *msg)
03665 {
03666 int i, res = 0;
03667
03668 if (ast_strlen_zero(msg)) {
03669 return 0;
03670 }
03671 for (i = 1; i < ARRAY_LEN(sip_methods) && !res; i++) {
03672 if (method_match(i, msg)) {
03673 res = sip_methods[i].id;
03674 }
03675 }
03676 return res;
03677 }
03678
03679
03680 static inline int sip_debug_test_addr(const struct ast_sockaddr *addr)
03681 {
03682
03683 if (!sipdebug) {
03684 return 0;
03685 }
03686
03687
03688 if (ast_sockaddr_isnull(&debugaddr)) {
03689 return 1;
03690 }
03691
03692
03693
03694
03695 if (ast_sockaddr_port(&debugaddr)) {
03696 return !ast_sockaddr_cmp(&debugaddr, addr);
03697 } else {
03698 return !ast_sockaddr_cmp_addr(&debugaddr, addr);
03699 }
03700 }
03701
03702
03703 static const struct ast_sockaddr *sip_real_dst(const struct sip_pvt *p)
03704 {
03705 if (p->outboundproxy) {
03706 return &p->outboundproxy->ip;
03707 }
03708
03709 return ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) || ast_test_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT) ? &p->recv : &p->sa;
03710 }
03711
03712
03713 static const char *sip_nat_mode(const struct sip_pvt *p)
03714 {
03715 return ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) ? "NAT" : "no NAT";
03716 }
03717
03718
03719 static inline int sip_debug_test_pvt(struct sip_pvt *p)
03720 {
03721 if (!sipdebug) {
03722 return 0;
03723 }
03724 return sip_debug_test_addr(sip_real_dst(p));
03725 }
03726
03727
03728 static int get_transport_str2enum(const char *transport)
03729 {
03730 int res = 0;
03731
03732 if (ast_strlen_zero(transport)) {
03733 return res;
03734 }
03735
03736 if (!strcasecmp(transport, "udp")) {
03737 res |= SIP_TRANSPORT_UDP;
03738 }
03739 if (!strcasecmp(transport, "tcp")) {
03740 res |= SIP_TRANSPORT_TCP;
03741 }
03742 if (!strcasecmp(transport, "tls")) {
03743 res |= SIP_TRANSPORT_TLS;
03744 }
03745 if (!strcasecmp(transport, "ws")) {
03746 res |= SIP_TRANSPORT_WS;
03747 }
03748 if (!strcasecmp(transport, "wss")) {
03749 res |= SIP_TRANSPORT_WSS;
03750 }
03751
03752 return res;
03753 }
03754
03755
03756 static inline const char *get_transport_list(unsigned int transports)
03757 {
03758 char *buf;
03759
03760 if (!transports) {
03761 return "UNKNOWN";
03762 }
03763
03764 if (!(buf = ast_threadstorage_get(&sip_transport_str_buf, SIP_TRANSPORT_STR_BUFSIZE))) {
03765 return "";
03766 }
03767
03768 memset(buf, 0, SIP_TRANSPORT_STR_BUFSIZE);
03769
03770 if (transports & SIP_TRANSPORT_UDP) {
03771 strncat(buf, "UDP,", SIP_TRANSPORT_STR_BUFSIZE - strlen(buf));
03772 }
03773 if (transports & SIP_TRANSPORT_TCP) {
03774 strncat(buf, "TCP,", SIP_TRANSPORT_STR_BUFSIZE - strlen(buf));
03775 }
03776 if (transports & SIP_TRANSPORT_TLS) {
03777 strncat(buf, "TLS,", SIP_TRANSPORT_STR_BUFSIZE - strlen(buf));
03778 }
03779 if (transports & SIP_TRANSPORT_WS) {
03780 strncat(buf, "WS,", SIP_TRANSPORT_STR_BUFSIZE - strlen(buf));
03781 }
03782 if (transports & SIP_TRANSPORT_WSS) {
03783 strncat(buf, "WSS,", SIP_TRANSPORT_STR_BUFSIZE - strlen(buf));
03784 }
03785
03786
03787 if (strlen(buf)) {
03788 buf[strlen(buf) - 1] = 0;
03789 }
03790
03791 return buf;
03792 }
03793
03794
03795 const char *sip_get_transport(enum sip_transport t)
03796 {
03797 switch (t) {
03798 case SIP_TRANSPORT_UDP:
03799 return "UDP";
03800 case SIP_TRANSPORT_TCP:
03801 return "TCP";
03802 case SIP_TRANSPORT_TLS:
03803 return "TLS";
03804 case SIP_TRANSPORT_WS:
03805 case SIP_TRANSPORT_WSS:
03806 return "WS";
03807 }
03808
03809 return "UNKNOWN";
03810 }
03811
03812
03813 static inline const char *get_srv_protocol(enum sip_transport t)
03814 {
03815 switch (t) {
03816 case SIP_TRANSPORT_UDP:
03817 return "udp";
03818 case SIP_TRANSPORT_WS:
03819 return "ws";
03820 case SIP_TRANSPORT_TLS:
03821 case SIP_TRANSPORT_TCP:
03822 return "tcp";
03823 case SIP_TRANSPORT_WSS:
03824 return "wss";
03825 }
03826
03827 return "udp";
03828 }
03829
03830
03831 static inline const char *get_srv_service(enum sip_transport t)
03832 {
03833 switch (t) {
03834 case SIP_TRANSPORT_TCP:
03835 case SIP_TRANSPORT_UDP:
03836 case SIP_TRANSPORT_WS:
03837 return "sip";
03838 case SIP_TRANSPORT_TLS:
03839 case SIP_TRANSPORT_WSS:
03840 return "sips";
03841 }
03842 return "sip";
03843 }
03844
03845
03846
03847
03848
03849
03850
03851 static inline const char *get_transport_pvt(struct sip_pvt *p)
03852 {
03853 if (p->outboundproxy && p->outboundproxy->transport) {
03854 set_socket_transport(&p->socket, p->outboundproxy->transport);
03855 }
03856
03857 return sip_get_transport(p->socket.type);
03858 }
03859
03860
03861
03862
03863
03864
03865
03866
03867
03868
03869
03870
03871 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data)
03872 {
03873 int res = 0;
03874 const struct ast_sockaddr *dst = sip_real_dst(p);
03875
03876 ast_debug(2, "Trying to put '%.11s' onto %s socket destined for %s\n", ast_str_buffer(data), get_transport_pvt(p), ast_sockaddr_stringify(dst));
03877
03878 if (sip_prepare_socket(p) < 0) {
03879 return XMIT_ERROR;
03880 }
03881
03882 if (p->socket.type == SIP_TRANSPORT_UDP) {
03883 res = ast_sendto(p->socket.fd, ast_str_buffer(data), ast_str_strlen(data), 0, dst);
03884 } else if (p->socket.tcptls_session) {
03885 res = sip_tcptls_write(p->socket.tcptls_session, ast_str_buffer(data), ast_str_strlen(data));
03886 } else if (p->socket.ws_session) {
03887 if (!(res = ast_websocket_write(p->socket.ws_session, AST_WEBSOCKET_OPCODE_TEXT, ast_str_buffer(data), ast_str_strlen(data)))) {
03888
03889 res = ast_str_strlen(data);
03890 }
03891 } else {
03892 ast_debug(2, "Socket type is TCP but no tcptls_session is present to write to\n");
03893 return XMIT_ERROR;
03894 }
03895
03896 if (res == -1) {
03897 switch (errno) {
03898 case EBADF:
03899 case EHOSTUNREACH:
03900 case ENETDOWN:
03901 case ENETUNREACH:
03902 case ECONNREFUSED:
03903 res = XMIT_ERROR;
03904 }
03905 }
03906 if (res != ast_str_strlen(data)) {
03907 ast_log(LOG_WARNING, "sip_xmit of %p (len %zu) to %s returned %d: %s\n", data, ast_str_strlen(data), ast_sockaddr_stringify(dst), res, strerror(errno));
03908 }
03909
03910 return res;
03911 }
03912
03913
03914 static void build_via(struct sip_pvt *p)
03915 {
03916
03917 const char *rport = (ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) || ast_test_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT)) ? ";rport" : "";
03918
03919
03920 snprintf(p->via, sizeof(p->via), "SIP/2.0/%s %s;branch=z9hG4bK%08x%s",
03921 get_transport_pvt(p),
03922 ast_sockaddr_stringify_remote(&p->ourip),
03923 (int) p->branch, rport);
03924 }
03925
03926
03927
03928
03929
03930
03931
03932
03933 static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p)
03934 {
03935 struct ast_sockaddr theirs;
03936
03937
03938
03939
03940
03941
03942
03943
03944
03945
03946
03947
03948
03949 int want_remap = 0;
03950
03951 ast_sockaddr_copy(us, &internip);
03952
03953 ast_ouraddrfor(them, us);
03954 ast_sockaddr_copy(&theirs, them);
03955
03956 if (ast_sockaddr_is_ipv6(&theirs)) {
03957 if (localaddr && !ast_sockaddr_isnull(&externaddr) && !ast_sockaddr_is_any(&bindaddr)) {
03958 ast_log(LOG_WARNING, "Address remapping activated in sip.conf "
03959 "but we're using IPv6, which doesn't need it. Please "
03960 "remove \"localnet\" and/or \"externaddr\" settings.\n");
03961 }
03962 } else {
03963 want_remap = localaddr &&
03964 !ast_sockaddr_isnull(&externaddr) &&
03965 ast_apply_ha(localaddr, &theirs) == AST_SENSE_ALLOW ;
03966 }
03967
03968 if (want_remap &&
03969 (!sip_cfg.matchexternaddrlocally || !ast_apply_ha(localaddr, us)) ) {
03970
03971 if (externexpire && time(NULL) >= externexpire) {
03972 if (ast_sockaddr_resolve_first(&externaddr, externhost, 0)) {
03973 ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
03974 }
03975 externexpire = time(NULL) + externrefresh;
03976 }
03977 if (!ast_sockaddr_isnull(&externaddr)) {
03978 ast_sockaddr_copy(us, &externaddr);
03979 switch (p->socket.type) {
03980 case SIP_TRANSPORT_TCP:
03981 if (!externtcpport && ast_sockaddr_port(&externaddr)) {
03982
03983 externtcpport = ast_sockaddr_port(&externaddr);
03984 }
03985 ast_sockaddr_set_port(us, externtcpport);
03986 break;
03987 case SIP_TRANSPORT_TLS:
03988 ast_sockaddr_set_port(us, externtlsport);
03989 break;
03990 case SIP_TRANSPORT_UDP:
03991 if (!ast_sockaddr_port(&externaddr)) {
03992 ast_sockaddr_set_port(us, ast_sockaddr_port(&bindaddr));
03993 }
03994 break;
03995 default:
03996 break;
03997 }
03998 }
03999 ast_debug(1, "Target address %s is not local, substituting externaddr\n",
04000 ast_sockaddr_stringify(them));
04001 } else {
04002
04003 switch (p->socket.type) {
04004 case SIP_TRANSPORT_TCP:
04005 if (!ast_sockaddr_is_any(&sip_tcp_desc.local_address)) {
04006 ast_sockaddr_copy(us,
04007 &sip_tcp_desc.local_address);
04008 } else {
04009 ast_sockaddr_set_port(us,
04010 ast_sockaddr_port(&sip_tcp_desc.local_address));
04011 }
04012 break;
04013 case SIP_TRANSPORT_TLS:
04014 if (!ast_sockaddr_is_any(&sip_tls_desc.local_address)) {
04015 ast_sockaddr_copy(us,
04016 &sip_tls_desc.local_address);
04017 } else {
04018 ast_sockaddr_set_port(us,
04019 ast_sockaddr_port(&sip_tls_desc.local_address));
04020 }
04021 break;
04022 case SIP_TRANSPORT_UDP:
04023
04024 default:
04025 if (!ast_sockaddr_is_any(&bindaddr)) {
04026 ast_sockaddr_copy(us, &bindaddr);
04027 }
04028 if (!ast_sockaddr_port(us)) {
04029 ast_sockaddr_set_port(us, ast_sockaddr_port(&bindaddr));
04030 }
04031 }
04032 }
04033 ast_debug(3, "Setting SIP_TRANSPORT_%s with address %s\n", sip_get_transport(p->socket.type), ast_sockaddr_stringify(us));
04034 }
04035
04036
04037 static __attribute__((format(printf, 2, 0))) void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
04038 {
04039 char buf[80], *c = buf;
04040 struct sip_history *hist;
04041 int l;
04042
04043 vsnprintf(buf, sizeof(buf), fmt, ap);
04044 strsep(&c, "\r\n");
04045 l = strlen(buf) + 1;
04046 if (!(hist = ast_calloc(1, sizeof(*hist) + l))) {
04047 return;
04048 }
04049 if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
04050 ast_free(hist);
04051 return;
04052 }
04053 memcpy(hist->event, buf, l);
04054 if (p->history_entries == MAX_HISTORY_ENTRIES) {
04055 struct sip_history *oldest;
04056 oldest = AST_LIST_REMOVE_HEAD(p->history, list);
04057 p->history_entries--;
04058 ast_free(oldest);
04059 }
04060 AST_LIST_INSERT_TAIL(p->history, hist, list);
04061 p->history_entries++;
04062 }
04063
04064
04065 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
04066 {
04067 va_list ap;
04068
04069 if (!p) {
04070 return;
04071 }
04072
04073 if (!p->do_history && !recordhistory && !dumphistory) {
04074 return;
04075 }
04076
04077 va_start(ap, fmt);
04078 append_history_va(p, fmt, ap);
04079 va_end(ap);
04080
04081 return;
04082 }
04083
04084
04085 static int retrans_pkt(const void *data)
04086 {
04087 struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
04088 int reschedule = DEFAULT_RETRANS;
04089 int xmitres = 0;
04090
04091 int64_t diff = pkt->retrans_stop_time - ast_tvdiff_ms(ast_tvnow(), pkt->time_sent);
04092
04093
04094
04095
04096 if ((diff <= 0) || (diff > pkt->retrans_stop_time)) {
04097 pkt->retrans_stop = 1;
04098 }
04099
04100
04101 sip_pvt_lock(pkt->owner);
04102
04103 if (!pkt->retrans_stop) {
04104 pkt->retrans++;
04105 if (!pkt->timer_t1) {
04106 if (sipdebug) {
04107 ast_debug(4, "SIP TIMER: Not rescheduling id #%d:%s (Method %d) (No timer T1)\n",
04108 pkt->retransid,
04109 sip_methods[pkt->method].text,
04110 pkt->method);
04111 }
04112 } else {
04113 int siptimer_a;
04114
04115 if (sipdebug) {
04116 ast_debug(4, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n",
04117 pkt->retransid,
04118 pkt->retrans,
04119 sip_methods[pkt->method].text,
04120 pkt->method);
04121 }
04122 if (!pkt->timer_a) {
04123 pkt->timer_a = 2 ;
04124 } else {
04125 pkt->timer_a = 2 * pkt->timer_a;
04126 }
04127
04128
04129 siptimer_a = pkt->timer_t1 * pkt->timer_a;
04130 if (pkt->method != SIP_INVITE && siptimer_a > 4000) {
04131 siptimer_a = 4000;
04132 }
04133
04134
04135 reschedule = siptimer_a;
04136 ast_debug(4, "** SIP timers: Rescheduling retransmission %d to %d ms (t1 %d ms (Retrans id #%d)) \n",
04137 pkt->retrans + 1,
04138 siptimer_a,
04139 pkt->timer_t1,
04140 pkt->retransid);
04141 }
04142
04143 if (sip_debug_test_pvt(pkt->owner)) {
04144 const struct ast_sockaddr *dst = sip_real_dst(pkt->owner);
04145 ast_verbose("Retransmitting #%d (%s) to %s:\n%s\n---\n",
04146 pkt->retrans, sip_nat_mode(pkt->owner),
04147 ast_sockaddr_stringify(dst),
04148 ast_str_buffer(pkt->data));
04149 }
04150
04151 append_history(pkt->owner, "ReTx", "%d %s", reschedule, ast_str_buffer(pkt->data));
04152 xmitres = __sip_xmit(pkt->owner, pkt->data);
04153
04154
04155
04156
04157
04158
04159 if (xmitres != XMIT_ERROR) {
04160 if (reschedule >= diff) {
04161 pkt->retrans_stop = 1;
04162 reschedule = diff;
04163 }
04164 sip_pvt_unlock(pkt->owner);
04165 return reschedule;
04166 }
04167 }
04168
04169
04170
04171
04172 pkt->retransid = -1;
04173
04174 if (pkt->method != SIP_OPTIONS && xmitres == 0) {
04175 if (pkt->is_fatal || sipdebug) {
04176 ast_log(LOG_WARNING, "Retransmission timeout reached on transmission %s for seqno %u (%s %s) -- See https://wiki.asterisk.org/wiki/display/AST/SIP+Retransmissions\n"
04177 "Packet timed out after %dms with no response\n",
04178 pkt->owner->callid,
04179 pkt->seqno,
04180 pkt->is_fatal ? "Critical" : "Non-critical",
04181 pkt->is_resp ? "Response" : "Request",
04182 (int) ast_tvdiff_ms(ast_tvnow(), pkt->time_sent));
04183 }
04184 } else if (pkt->method == SIP_OPTIONS && sipdebug) {
04185 ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s) -- See https://wiki.asterisk.org/wiki/display/AST/SIP+Retransmissions\n", pkt->owner->callid);
04186 }
04187
04188 if (xmitres == XMIT_ERROR) {
04189 ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission on Call ID %s\n", pkt->owner->callid);
04190 append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
04191 } else {
04192 append_history(pkt->owner, "MaxRetries", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
04193 }
04194
04195 if (pkt->is_fatal) {
04196 while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
04197 sip_pvt_unlock(pkt->owner);
04198 usleep(1);
04199 sip_pvt_lock(pkt->owner);
04200 }
04201 if (pkt->owner->owner && !ast_channel_hangupcause(pkt->owner->owner)) {
04202 ast_channel_hangupcause_set(pkt->owner->owner, AST_CAUSE_NO_USER_RESPONSE);
04203 }
04204 if (pkt->owner->owner) {
04205 ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet (see https://wiki.asterisk.org/wiki/display/AST/SIP+Retransmissions).\n", pkt->owner->callid);
04206
04207 if (pkt->is_resp &&
04208 (pkt->response_code >= 200) &&
04209 (pkt->response_code < 300) &&
04210 pkt->owner->pendinginvite &&
04211 ast_test_flag(&pkt->owner->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
04212
04213
04214
04215
04216
04217
04218
04219 pkt->owner->invitestate = INV_TERMINATED;
04220 pkt->owner->pendinginvite = 0;
04221 } else {
04222
04223 sip_alreadygone(pkt->owner);
04224 }
04225 ast_queue_hangup_with_cause(pkt->owner->owner, AST_CAUSE_NO_USER_RESPONSE);
04226 ast_channel_unlock(pkt->owner->owner);
04227 } else {
04228
04229
04230
04231 if (pkt->method != SIP_OPTIONS && pkt->method != SIP_REGISTER) {
04232 pvt_set_needdestroy(pkt->owner, "no response to critical packet");
04233 sip_alreadygone(pkt->owner);
04234 append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
04235 }
04236 }
04237 }
04238
04239 if (pkt->method == SIP_BYE) {
04240
04241 sip_alreadygone(pkt->owner);
04242 if (pkt->owner->owner) {
04243 ast_channel_unlock(pkt->owner->owner);
04244 }
04245 append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
04246 pvt_set_needdestroy(pkt->owner, "no response to BYE");
04247 }
04248
04249
04250 for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
04251 if (cur == pkt) {
04252 UNLINK(cur, pkt->owner->packets, prev);
04253 sip_pvt_unlock(pkt->owner);
04254 if (pkt->owner) {
04255 pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
04256 }
04257 if (pkt->data) {
04258 ast_free(pkt->data);
04259 }
04260 pkt->data = NULL;
04261 ast_free(pkt);
04262 return 0;
04263 }
04264 }
04265
04266 ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
04267 sip_pvt_unlock(pkt->owner);
04268 return 0;
04269 }
04270
04271
04272
04273
04274
04275
04276 static enum sip_result __sip_reliable_xmit(struct sip_pvt *p, uint32_t seqno, int resp, struct ast_str *data, int fatal, int sipmethod)
04277 {
04278 struct sip_pkt *pkt = NULL;
04279 int siptimer_a = DEFAULT_RETRANS;
04280 int xmitres = 0;
04281 int respid;
04282
04283 if (sipmethod == SIP_INVITE) {
04284
04285 p->pendinginvite = seqno;
04286 }
04287
04288
04289
04290
04291 if (!(p->socket.type & SIP_TRANSPORT_UDP)) {
04292 xmitres = __sip_xmit(p, data);
04293 if (xmitres == XMIT_ERROR) {
04294 append_history(p, "XmitErr", "%s", fatal ? "(Critical)" : "(Non-critical)");
04295 return AST_FAILURE;
04296 } else {
04297 return AST_SUCCESS;
04298 }
04299 }
04300
04301 if (!(pkt = ast_calloc(1, sizeof(*pkt)))) {
04302 return AST_FAILURE;
04303 }
04304
04305 if (!(pkt->data = ast_str_create(ast_str_strlen(data)))) {
04306 ast_free(pkt);
04307 return AST_FAILURE;
04308 }
04309 ast_str_set(&pkt->data, 0, "%s%s", ast_str_buffer(data), "\0");
04310
04311 pkt->method = sipmethod;
04312 pkt->seqno = seqno;
04313 pkt->is_resp = resp;
04314 pkt->is_fatal = fatal;
04315 pkt->owner = dialog_ref(p, "__sip_reliable_xmit: setting pkt->owner");
04316 pkt->next = p->packets;
04317 p->packets = pkt;
04318 if (resp) {
04319
04320 if (sscanf(ast_str_buffer(pkt->data), "SIP/2.0 %30u", &respid) == 1) {
04321 pkt->response_code = respid;
04322 }
04323 }
04324 pkt->timer_t1 = p->timer_t1;
04325 pkt->retransid = -1;
04326 if (pkt->timer_t1) {
04327 siptimer_a = pkt->timer_t1;
04328 }
04329
04330 pkt->time_sent = ast_tvnow();
04331 pkt->retrans_stop_time = 64 * (pkt->timer_t1 ? pkt->timer_t1 : DEFAULT_TIMER_T1);
04332
04333
04334 AST_SCHED_REPLACE_VARIABLE(pkt->retransid, sched, siptimer_a, retrans_pkt, pkt, 1);
04335 if (sipdebug) {
04336 ast_debug(4, "*** SIP TIMER: Initializing retransmit timer on packet: Id #%d\n", pkt->retransid);
04337 }
04338
04339 xmitres = __sip_xmit(pkt->owner, pkt->data);
04340
04341 if (xmitres == XMIT_ERROR) {
04342 append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
04343 ast_log(LOG_ERROR, "Serious Network Trouble; __sip_xmit returns error for pkt data\n");
04344 AST_SCHED_DEL(sched, pkt->retransid);
04345 p->packets = pkt->next;
04346 pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
04347 ast_free(pkt->data);
04348 ast_free(pkt);
04349 return AST_FAILURE;
04350 } else {
04351
04352
04353
04354
04355 if (monitor_thread != AST_PTHREADT_NULL) {
04356 pthread_kill(monitor_thread, SIGURG);
04357 }
04358 return AST_SUCCESS;
04359 }
04360 }
04361
04362
04363
04364
04365
04366
04367 static int __sip_autodestruct(const void *data)
04368 {
04369 struct sip_pvt *p = (struct sip_pvt *)data;
04370 struct ast_channel *owner;
04371
04372
04373 if (p->subscribed && p->subscribed != MWI_NOTIFICATION && p->subscribed != CALL_COMPLETION) {
04374 struct state_notify_data data = { 0, };
04375 data.state = AST_EXTENSION_DEACTIVATED;
04376
04377 transmit_state_notify(p, &data, 1, TRUE);
04378 p->subscribed = NONE;
04379 append_history(p, "Subscribestatus", "timeout");
04380 ast_debug(3, "Re-scheduled destruction of SIP subscription %s\n", p->callid ? p->callid : "<unknown>");
04381 return 10000;
04382 }
04383
04384
04385 if (p->packets) {
04386 if (!p->needdestroy) {
04387 char method_str[31];
04388 ast_debug(3, "Re-scheduled destruction of SIP call %s\n", p->callid ? p->callid : "<unknown>");
04389 append_history(p, "ReliableXmit", "timeout");
04390 if (sscanf(p->lastmsg, "Tx: %30s", method_str) == 1 || sscanf(p->lastmsg, "Rx: %30s", method_str) == 1) {
04391 if (p->ongoing_reinvite || method_match(SIP_CANCEL, method_str) || method_match(SIP_BYE, method_str)) {
04392 pvt_set_needdestroy(p, "autodestruct");
04393 }
04394 }
04395 return 10000;
04396 } else {
04397
04398 __sip_pretend_ack(p);
04399 }
04400 }
04401
04402
04403 p->autokillid = -1;
04404
04405
04406
04407
04408 owner = sip_pvt_lock_full(p);
04409 if (owner) {
04410 ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner %s in place (Method: %s). Rescheduling destruction for 10000 ms\n", p->callid, ast_channel_name(owner), sip_methods[p->method].text);
04411 ast_queue_hangup_with_cause(owner, AST_CAUSE_PROTOCOL_ERROR);
04412 ast_channel_unlock(owner);
04413 ast_channel_unref(owner);
04414 sip_pvt_unlock(p);
04415 return 10000;
04416 } else if (p->refer && !p->alreadygone) {
04417 ast_debug(3, "Finally hanging up channel after transfer: %s\n", p->callid);
04418 stop_media_flows(p);
04419 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
04420 append_history(p, "ReferBYE", "Sending BYE on transferer call leg %s", p->callid);
04421 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
04422 } else {
04423 append_history(p, "AutoDestroy", "%s", p->callid);
04424 ast_debug(3, "Auto destroying SIP dialog '%s'\n", p->callid);
04425 sip_pvt_unlock(p);
04426 dialog_unlink_all(p);
04427 sip_pvt_lock(p);
04428
04429
04430
04431 }
04432
04433 sip_pvt_unlock(p);
04434
04435 dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
04436
04437 return 0;
04438 }
04439
04440
04441
04442
04443 void sip_scheddestroy_final(struct sip_pvt *p, int ms)
04444 {
04445 if (p->final_destruction_scheduled) {
04446 return;
04447 }
04448
04449 sip_scheddestroy(p, ms);
04450 if (p->autokillid != -1) {
04451 p->final_destruction_scheduled = 1;
04452 }
04453 }
04454
04455
04456 void sip_scheddestroy(struct sip_pvt *p, int ms)
04457 {
04458 if (p->final_destruction_scheduled) {
04459 return;
04460 }
04461
04462 if (ms < 0) {
04463 if (p->timer_t1 == 0) {
04464 p->timer_t1 = global_t1;
04465 }
04466 if (p->timer_b == 0) {
04467 p->timer_b = global_timer_b;
04468 }
04469 ms = p->timer_t1 * 64;
04470 }
04471 if (sip_debug_test_pvt(p)) {
04472 ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
04473 }
04474 if (sip_cancel_destroy(p)) {
04475 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
04476 }
04477
04478 if (p->do_history) {
04479 append_history(p, "SchedDestroy", "%d ms", ms);
04480 }
04481 p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, dialog_ref(p, "setting ref as passing into ast_sched_add for __sip_autodestruct"));
04482
04483 if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_schedid > 0) {
04484 stop_session_timer(p);
04485 }
04486 }
04487
04488
04489
04490
04491
04492 int sip_cancel_destroy(struct sip_pvt *p)
04493 {
04494 if (p->final_destruction_scheduled) {
04495 return 0;
04496 }
04497
04498 if (p->autokillid > -1) {
04499 append_history(p, "CancelDestroy", "");
04500 AST_SCHED_DEL_UNREF(sched, p->autokillid, dialog_unref(p, "remove ref for autokillid"));
04501 }
04502 return 0;
04503 }
04504
04505
04506
04507 int __sip_ack(struct sip_pvt *p, uint32_t seqno, int resp, int sipmethod)
04508 {
04509 struct sip_pkt *cur, *prev = NULL;
04510 const char *msg = "Not Found";
04511 int res = FALSE;
04512
04513
04514
04515
04516
04517
04518 if (p->outboundproxy && !p->outboundproxy->force){
04519 ref_proxy(p, NULL);
04520 }
04521
04522 for (cur = p->packets; cur; prev = cur, cur = cur->next) {
04523 if (cur->seqno != seqno || cur->is_resp != resp) {
04524 continue;
04525 }
04526 if (cur->is_resp || cur->method == sipmethod) {
04527 res = TRUE;
04528 msg = "Found";
04529 if (!resp && (seqno == p->pendinginvite)) {
04530 ast_debug(1, "Acked pending invite %u\n", p->pendinginvite);
04531 p->pendinginvite = 0;
04532 }
04533 if (cur->retransid > -1) {
04534 if (sipdebug)
04535 ast_debug(4, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
04536 }
04537
04538
04539
04540
04541
04542
04543
04544
04545
04546
04547
04548
04549
04550
04551
04552
04553 while (cur->retransid > -1 && ast_sched_del(sched, cur->retransid)) {
04554 sip_pvt_unlock(p);
04555 usleep(1);
04556 sip_pvt_lock(p);
04557 }
04558 UNLINK(cur, p->packets, prev);
04559 dialog_unref(cur->owner, "unref pkt cur->owner dialog from sip ack before freeing pkt");
04560 if (cur->data) {
04561 ast_free(cur->data);
04562 }
04563 ast_free(cur);
04564 break;
04565 }
04566 }
04567 ast_debug(1, "Stopping retransmission on '%s' of %s %u: Match %s\n",
04568 p->callid, resp ? "Response" : "Request", seqno, msg);
04569 return res;
04570 }
04571
04572
04573
04574 void __sip_pretend_ack(struct sip_pvt *p)
04575 {
04576 struct sip_pkt *cur = NULL;
04577
04578 while (p->packets) {
04579 int method;
04580 if (cur == p->packets) {
04581 ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
04582 return;
04583 }
04584 cur = p->packets;
04585 method = (cur->method) ? cur->method : find_sip_method(ast_str_buffer(cur->data));
04586 __sip_ack(p, cur->seqno, cur->is_resp, method);
04587 }
04588 }
04589
04590
04591 int __sip_semi_ack(struct sip_pvt *p, uint32_t seqno, int resp, int sipmethod)
04592 {
04593 struct sip_pkt *cur;
04594 int res = FALSE;
04595
04596 for (cur = p->packets; cur; cur = cur->next) {
04597 if (cur->seqno == seqno && cur->is_resp == resp &&
04598 (cur->is_resp || method_match(sipmethod, ast_str_buffer(cur->data)))) {
04599
04600 if (cur->retransid > -1) {
04601 if (sipdebug)
04602 ast_debug(4, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
04603 }
04604 AST_SCHED_DEL(sched, cur->retransid);
04605 res = TRUE;
04606 break;
04607 }
04608 }
04609 ast_debug(1, "(Provisional) Stopping retransmission (but retaining packet) on '%s' %s %u: %s\n", p->callid, resp ? "Response" : "Request", seqno, res == -1 ? "Not Found" : "Found");
04610 return res;
04611 }
04612
04613
04614
04615 static void parse_copy(struct sip_request *dst, const struct sip_request *src)
04616 {
04617 copy_request(dst, src);
04618 parse_request(dst);
04619 }
04620
04621
04622 static void add_blank(struct sip_request *req)
04623 {
04624 if (!req->lines) {
04625
04626 ast_str_append(&req->data, 0, "\r\n");
04627 }
04628 }
04629
04630 static int send_provisional_keepalive_full(struct sip_pvt *pvt, int with_sdp)
04631 {
04632 const char *msg = NULL;
04633 struct ast_channel *chan;
04634 int res = 0;
04635 int old_sched_id = pvt->provisional_keepalive_sched_id;
04636
04637 chan = sip_pvt_lock_full(pvt);
04638
04639 if (old_sched_id != pvt->provisional_keepalive_sched_id) {
04640
04641 if (chan) {
04642 ast_channel_unlock(chan);
04643 chan = ast_channel_unref(chan);
04644 }
04645 sip_pvt_unlock(pvt);
04646 dialog_unref(pvt, "dialog ref for provisional keepalive");
04647 return 0;
04648 }
04649
04650 if (!pvt->last_provisional || !strncasecmp(pvt->last_provisional, "100", 3)) {
04651 msg = "183 Session Progress";
04652 }
04653
04654 if (pvt->invitestate < INV_COMPLETED) {
04655 if (with_sdp) {
04656 transmit_response_with_sdp(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq, XMIT_UNRELIABLE, FALSE, FALSE);
04657 } else {
04658 transmit_response(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq);
04659 }
04660 res = PROVIS_KEEPALIVE_TIMEOUT;
04661 }
04662
04663 if (chan) {
04664 ast_channel_unlock(chan);
04665 chan = ast_channel_unref(chan);
04666 }
04667
04668 if (!res) {
04669 pvt->provisional_keepalive_sched_id = -1;
04670 }
04671
04672 sip_pvt_unlock(pvt);
04673
04674 if (!res) {
04675 dialog_unref(pvt, "dialog ref for provisional keepalive");
04676 }
04677 return res;
04678 }
04679
04680 static int send_provisional_keepalive(const void *data)
04681 {
04682 struct sip_pvt *pvt = (struct sip_pvt *) data;
04683
04684 return send_provisional_keepalive_full(pvt, 0);
04685 }
04686
04687 static int send_provisional_keepalive_with_sdp(const void *data)
04688 {
04689 struct sip_pvt *pvt = (void *) data;
04690
04691 return send_provisional_keepalive_full(pvt, 1);
04692 }
04693
04694 static void update_provisional_keepalive(struct sip_pvt *pvt, int with_sdp)
04695 {
04696 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"));
04697
04698 pvt->provisional_keepalive_sched_id = ast_sched_add(sched, PROVIS_KEEPALIVE_TIMEOUT,
04699 with_sdp ? send_provisional_keepalive_with_sdp : send_provisional_keepalive, dialog_ref(pvt, "Increment refcount to pass dialog pointer to sched callback"));
04700 }
04701
04702 static void add_required_respheader(struct sip_request *req)
04703 {
04704 struct ast_str *str;
04705 int i;
04706
04707 if (!req->reqsipoptions) {
04708 return;
04709 }
04710
04711 str = ast_str_create(32);
04712
04713 for (i = 0; i < ARRAY_LEN(sip_options); ++i) {
04714 if (!(req->reqsipoptions & sip_options[i].id)) {
04715 continue;
04716 }
04717 if (ast_str_strlen(str) > 0) {
04718 ast_str_append(&str, 0, ", ");
04719 }
04720 ast_str_append(&str, 0, "%s", sip_options[i].text);
04721 }
04722
04723 if (ast_str_strlen(str) > 0) {
04724 add_header(req, "Require", ast_str_buffer(str));
04725 }
04726
04727 ast_free(str);
04728 }
04729
04730
04731 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno)
04732 {
04733 int res;
04734
04735 finalize_content(req);
04736 add_blank(req);
04737 if (sip_debug_test_pvt(p)) {
04738 const struct ast_sockaddr *dst = sip_real_dst(p);
04739
04740 ast_verbose("\n<--- %sTransmitting (%s) to %s --->\n%s\n<------------>\n",
04741 reliable ? "Reliably " : "", sip_nat_mode(p),
04742 ast_sockaddr_stringify(dst),
04743 ast_str_buffer(req->data));
04744 }
04745 if (p->do_history) {
04746 struct sip_request tmp = { .rlpart1 = 0, };
04747 parse_copy(&tmp, req);
04748 append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", ast_str_buffer(tmp.data), sip_get_header(&tmp, "CSeq"),
04749 (tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? REQ_OFFSET_TO_STR(&tmp, rlpart2) : sip_methods[tmp.method].text);
04750 deinit_req(&tmp);
04751 }
04752
04753
04754 if (p->initreq.method == SIP_INVITE && reliable == XMIT_CRITICAL) {
04755 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"));
04756 }
04757
04758 res = (reliable) ?
04759 __sip_reliable_xmit(p, seqno, 1, req->data, (reliable == XMIT_CRITICAL), req->method) :
04760 __sip_xmit(p, req->data);
04761 deinit_req(req);
04762 if (res > 0) {
04763 return 0;
04764 }
04765 return res;
04766 }
04767
04768
04769
04770
04771
04772
04773 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno)
04774 {
04775 int res;
04776
04777
04778
04779
04780 if (p->outboundproxy) {
04781 p->sa = p->outboundproxy->ip;
04782 }
04783
04784 finalize_content(req);
04785 add_blank(req);
04786 if (sip_debug_test_pvt(p)) {
04787 if (ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT)) {
04788 ast_verbose("%sTransmitting (NAT) to %s:\n%s\n---\n", reliable ? "Reliably " : "", ast_sockaddr_stringify(&p->recv), ast_str_buffer(req->data));
04789 } else {
04790 ast_verbose("%sTransmitting (no NAT) to %s:\n%s\n---\n", reliable ? "Reliably " : "", ast_sockaddr_stringify(&p->sa), ast_str_buffer(req->data));
04791 }
04792 }
04793 if (p->do_history) {
04794 struct sip_request tmp = { .rlpart1 = 0, };
04795 parse_copy(&tmp, req);
04796 append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", ast_str_buffer(tmp.data), sip_get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
04797 deinit_req(&tmp);
04798 }
04799 res = (reliable) ?
04800 __sip_reliable_xmit(p, seqno, 0, req->data, (reliable == XMIT_CRITICAL), req->method) :
04801 __sip_xmit(p, req->data);
04802 deinit_req(req);
04803 return res;
04804 }
04805
04806 static void enable_dsp_detect(struct sip_pvt *p)
04807 {
04808 int features = 0;
04809
04810 if (p->dsp) {
04811 return;
04812 }
04813
04814 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
04815 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
04816 if (p->rtp) {
04817 ast_rtp_instance_dtmf_mode_set(p->rtp, AST_RTP_DTMF_MODE_INBAND);
04818 }
04819 features |= DSP_FEATURE_DIGIT_DETECT;
04820 }
04821
04822 if (ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_CNG)) {
04823 features |= DSP_FEATURE_FAX_DETECT;
04824 }
04825
04826 if (!features) {
04827 return;
04828 }
04829
04830 if (!(p->dsp = ast_dsp_new())) {
04831 return;
04832 }
04833
04834 ast_dsp_set_features(p->dsp, features);
04835 if (global_relaxdtmf) {
04836 ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
04837 }
04838 }
04839
04840 static void disable_dsp_detect(struct sip_pvt *p)
04841 {
04842 if (p->dsp) {
04843 ast_dsp_free(p->dsp);
04844 p->dsp = NULL;
04845 }
04846 }
04847
04848
04849 static int sip_setoption(struct ast_channel *chan, int option, void *data, int datalen)
04850 {
04851 int res = -1;
04852 struct sip_pvt *p = ast_channel_tech_pvt(chan);
04853
04854 if (!p) {
04855 ast_log(LOG_ERROR, "Attempt to Ref a null pointer. sip private structure is gone!\n");
04856 return -1;
04857 }
04858
04859 sip_pvt_lock(p);
04860
04861 switch (option) {
04862 case AST_OPTION_FORMAT_READ:
04863 if (p->rtp) {
04864 res = ast_rtp_instance_set_read_format(p->rtp, (struct ast_format *) data);
04865 }
04866 break;
04867 case AST_OPTION_FORMAT_WRITE:
04868 if (p->rtp) {
04869 res = ast_rtp_instance_set_write_format(p->rtp, (struct ast_format *) data);
04870 }
04871 break;
04872 case AST_OPTION_MAKE_COMPATIBLE:
04873 if (p->rtp) {
04874 res = ast_rtp_instance_make_compatible(chan, p->rtp, (struct ast_channel *) data);
04875 }
04876 break;
04877 case AST_OPTION_DIGIT_DETECT:
04878 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
04879 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
04880 char *cp = (char *) data;
04881
04882 ast_debug(1, "%sabling digit detection on %s\n", *cp ? "En" : "Dis", ast_channel_name(chan));
04883 if (*cp) {
04884 enable_dsp_detect(p);
04885 } else {
04886 disable_dsp_detect(p);
04887 }
04888 res = 0;
04889 }
04890 break;
04891 case AST_OPTION_SECURE_SIGNALING:
04892 p->req_secure_signaling = *(unsigned int *) data;
04893 res = 0;
04894 break;
04895 case AST_OPTION_SECURE_MEDIA:
04896 ast_set2_flag(&p->flags[1], *(unsigned int *) data, SIP_PAGE2_USE_SRTP);
04897 res = 0;
04898 break;
04899 default:
04900 break;
04901 }
04902
04903 sip_pvt_unlock(p);
04904
04905 return res;
04906 }
04907
04908
04909 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen)
04910 {
04911 int res = -1;
04912 enum ast_t38_state state = T38_STATE_UNAVAILABLE;
04913 struct sip_pvt *p = (struct sip_pvt *) ast_channel_tech_pvt(chan);
04914 char *cp;
04915
04916 sip_pvt_lock(p);
04917
04918 switch (option) {
04919 case AST_OPTION_T38_STATE:
04920
04921 if (*datalen != sizeof(enum ast_t38_state)) {
04922 ast_log(LOG_ERROR, "Invalid datalen for AST_OPTION_T38_STATE option. Expected %d, got %d\n", (int)sizeof(enum ast_t38_state), *datalen);
04923 break;
04924 }
04925
04926
04927 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
04928 switch (p->t38.state) {
04929 case T38_LOCAL_REINVITE:
04930 case T38_PEER_REINVITE:
04931 state = T38_STATE_NEGOTIATING;
04932 break;
04933 case T38_ENABLED:
04934 state = T38_STATE_NEGOTIATED;
04935 break;
04936 case T38_REJECTED:
04937 state = T38_STATE_REJECTED;
04938 break;
04939 default:
04940 state = T38_STATE_UNKNOWN;
04941 }
04942 }
04943
04944 *((enum ast_t38_state *) data) = state;
04945 res = 0;
04946
04947 break;
04948 case AST_OPTION_DIGIT_DETECT:
04949 cp = (char *) data;
04950 *cp = p->dsp ? 1 : 0;
04951 ast_debug(1, "Reporting digit detection %sabled on %s\n", *cp ? "en" : "dis", ast_channel_name(chan));
04952 break;
04953 case AST_OPTION_SECURE_SIGNALING:
04954 *((unsigned int *) data) = p->req_secure_signaling;
04955 res = 0;
04956 break;
04957 case AST_OPTION_SECURE_MEDIA:
04958 *((unsigned int *) data) = ast_test_flag(&p->flags[1], SIP_PAGE2_USE_SRTP) ? 1 : 0;
04959 res = 0;
04960 break;
04961 case AST_OPTION_DEVICE_NAME:
04962 if (p && p->outgoing_call) {
04963 cp = (char *) data;
04964 ast_copy_string(cp, p->dialstring, *datalen);
04965 res = 0;
04966 }
04967
04968
04969
04970 break;
04971 default:
04972 break;
04973 }
04974
04975 sip_pvt_unlock(p);
04976
04977 return res;
04978 }
04979
04980
04981
04982
04983
04984 const char *find_closing_quote(const char *start, const char *lim)
04985 {
04986 char last_char = '\0';
04987 const char *s;
04988 for (s = start; *s && s != lim; last_char = *s++) {
04989 if (*s == '"' && last_char != '\\')
04990 break;
04991 }
04992 return s;
04993 }
04994
04995
04996 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
04997 {
04998 struct sip_pvt *p = ast_channel_tech_pvt(chan);
04999
05000 if (subclass != AST_HTML_URL)
05001 return -1;
05002
05003 ast_string_field_build(p, url, "<%s>;mode=active", data);
05004
05005 if (sip_debug_test_pvt(p))
05006 ast_debug(1, "Send URL %s, state = %d!\n", data, ast_channel_state(chan));
05007
05008 switch (ast_channel_state(chan)) {
05009 case AST_STATE_RING:
05010 transmit_response(p, "100 Trying", &p->initreq);
05011 break;
05012 case AST_STATE_RINGING:
05013 transmit_response(p, "180 Ringing", &p->initreq);
05014 break;
05015 case AST_STATE_UP:
05016 if (!p->pendinginvite) {
05017 transmit_reinvite_with_sdp(p, FALSE, FALSE);
05018 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
05019 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
05020 }
05021 break;
05022 default:
05023 ast_log(LOG_WARNING, "Don't know how to send URI when state is %d!\n", ast_channel_state(chan));
05024 }
05025
05026 return 0;
05027 }
05028
05029
05030 static const char *sip_get_callid(struct ast_channel *chan)
05031 {
05032 return ast_channel_tech_pvt(chan) ? ((struct sip_pvt *) ast_channel_tech_pvt(chan))->callid : "";
05033 }
05034
05035
05036
05037
05038
05039
05040 static int sip_sendtext(struct ast_channel *ast, const char *text)
05041 {
05042 struct sip_pvt *dialog = ast_channel_tech_pvt(ast);
05043 int debug;
05044
05045 if (!dialog) {
05046 return -1;
05047 }
05048
05049
05050 if (!text) {
05051 return 0;
05052 }
05053 if(!is_method_allowed(&dialog->allowed_methods, SIP_MESSAGE)) {
05054 ast_debug(2, "Trying to send MESSAGE to device that does not support it.\n");
05055 return 0;
05056 }
05057
05058 debug = sip_debug_test_pvt(dialog);
05059 if (debug) {
05060 ast_verbose("Sending text %s on %s\n", text, ast_channel_name(ast));
05061 }
05062
05063
05064 sip_pvt_lock(dialog);
05065 destroy_msg_headers(dialog);
05066 ast_string_field_set(dialog, msg_body, text);
05067 transmit_message(dialog, 0, 0);
05068 sip_pvt_unlock(dialog);
05069 return 0;
05070 }
05071
05072
05073
05074
05075
05076
05077 static void realtime_update_peer(const char *peername, struct ast_sockaddr *addr, const char *defaultuser, const char *fullcontact, const char *useragent, int expirey, unsigned short deprecated_username, int lastms)
05078 {
05079 char port[10];
05080 char ipaddr[INET6_ADDRSTRLEN];
05081 char regseconds[20];
05082 char *tablename = NULL;
05083 char str_lastms[20];
05084
05085 const char *sysname = ast_config_AST_SYSTEM_NAME;
05086 char *syslabel = NULL;
05087
05088 time_t nowtime = time(NULL) + expirey;
05089 const char *fc = fullcontact ? "fullcontact" : NULL;
05090
05091 int realtimeregs = ast_check_realtime("sipregs");
05092
05093 tablename = realtimeregs ? "sipregs" : "sippeers";
05094
05095 snprintf(str_lastms, sizeof(str_lastms), "%d", lastms);
05096 snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime);
05097 ast_copy_string(ipaddr, ast_sockaddr_isnull(addr) ? "" : ast_sockaddr_stringify_addr(addr), sizeof(ipaddr));
05098 ast_copy_string(port, ast_sockaddr_port(addr) ? ast_sockaddr_stringify_port(addr) : "", sizeof(port));
05099
05100 if (ast_strlen_zero(sysname))
05101 sysname = NULL;
05102 else if (sip_cfg.rtsave_sysname)
05103 syslabel = "regserver";
05104
05105
05106
05107
05108
05109
05110
05111 if (fc) {
05112 ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
05113 "port", port, "regseconds", regseconds,
05114 deprecated_username ? "username" : "defaultuser", defaultuser,
05115 "useragent", useragent, "lastms", str_lastms,
05116 fc, fullcontact, syslabel, sysname, SENTINEL);
05117 } else {
05118 ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
05119 "port", port, "regseconds", regseconds,
05120 "useragent", useragent, "lastms", str_lastms,
05121 deprecated_username ? "username" : "defaultuser", defaultuser,
05122 syslabel, sysname, SENTINEL);
05123 }
05124 }
05125
05126
05127 static void register_peer_exten(struct sip_peer *peer, int onoff)
05128 {
05129 char multi[256];
05130 char *stringp, *ext, *context;
05131 struct pbx_find_info q = { .stacklen = 0 };
05132
05133
05134
05135
05136
05137 if (ast_strlen_zero(sip_cfg.regcontext))
05138 return;
05139
05140 ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
05141 stringp = multi;
05142 while ((ext = strsep(&stringp, "&"))) {
05143 if ((context = strchr(ext, '@'))) {
05144 *context++ = '\0';
05145 if (!ast_context_find(context)) {
05146 ast_log(LOG_WARNING, "Context %s must exist in regcontext= in sip.conf!\n", context);
05147 continue;
05148 }
05149 } else {
05150 context = sip_cfg.regcontext;
05151 }
05152 if (onoff) {
05153 if (!ast_exists_extension(NULL, context, ext, 1, NULL)) {
05154 ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
05155 ast_strdup(peer->name), ast_free_ptr, "SIP");
05156 }
05157 } else if (pbx_find_extension(NULL, NULL, &q, context, ext, 1, NULL, "", E_MATCH)) {
05158 ast_context_remove_extension(context, ext, 1, NULL);
05159 }
05160 }
05161 }
05162
05163
05164 static void destroy_mailbox(struct sip_mailbox *mailbox)
05165 {
05166 if (mailbox->event_sub)
05167 ast_event_unsubscribe(mailbox->event_sub);
05168 ast_free(mailbox);
05169 }
05170
05171
05172 static void clear_peer_mailboxes(struct sip_peer *peer)
05173 {
05174 struct sip_mailbox *mailbox;
05175
05176 while ((mailbox = AST_LIST_REMOVE_HEAD(&peer->mailboxes, entry)))
05177 destroy_mailbox(mailbox);
05178 }
05179
05180 static void sip_destroy_peer_fn(void *peer)
05181 {
05182 sip_destroy_peer(peer);
05183 }
05184
05185
05186 static void sip_destroy_peer(struct sip_peer *peer)
05187 {
05188 ast_debug(3, "Destroying SIP peer %s\n", peer->name);
05189
05190
05191
05192
05193
05194
05195 clear_peer_mailboxes(peer);
05196
05197 if (peer->outboundproxy) {
05198 ao2_ref(peer->outboundproxy, -1);
05199 peer->outboundproxy = NULL;
05200 }
05201
05202
05203 if (peer->call) {
05204 dialog_unlink_all(peer->call);
05205 peer->call = dialog_unref(peer->call, "peer->call is being unset");
05206 }
05207
05208 if (peer->mwipvt) {
05209 dialog_unlink_all(peer->mwipvt);
05210 peer->mwipvt = dialog_unref(peer->mwipvt, "unreffing peer->mwipvt");
05211 }
05212
05213 if (peer->chanvars) {
05214 ast_variables_destroy(peer->chanvars);
05215 peer->chanvars = NULL;
05216 }
05217
05218 register_peer_exten(peer, FALSE);
05219 ast_free_acl_list(peer->acl);
05220 ast_free_acl_list(peer->directmediaacl);
05221 if (peer->selfdestruct)
05222 ast_atomic_fetchadd_int(&apeerobjs, -1);
05223 else if (!ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && peer->is_realtime) {
05224 ast_atomic_fetchadd_int(&rpeerobjs, -1);
05225 ast_debug(3, "-REALTIME- peer Destroyed. Name: %s. Realtime Peer objects: %d\n", peer->name, rpeerobjs);
05226 } else
05227 ast_atomic_fetchadd_int(&speerobjs, -1);
05228 if (peer->auth) {
05229 ao2_t_ref(peer->auth, -1, "Removing peer authentication");
05230 peer->auth = NULL;
05231 }
05232
05233 if (peer->socket.tcptls_session) {
05234 ao2_ref(peer->socket.tcptls_session, -1);
05235 peer->socket.tcptls_session = NULL;
05236 } else if (peer->socket.ws_session) {
05237 ast_websocket_unref(peer->socket.ws_session);
05238 peer->socket.ws_session = NULL;
05239 }
05240
05241 peer->named_callgroups = ast_unref_namedgroups(peer->named_callgroups);
05242 peer->named_pickupgroups = ast_unref_namedgroups(peer->named_pickupgroups);
05243
05244 ast_cc_config_params_destroy(peer->cc_params);
05245
05246 ast_string_field_free_memory(peer);
05247
05248 peer->caps = ast_format_cap_destroy(peer->caps);
05249
05250 ast_rtp_dtls_cfg_free(&peer->dtls_cfg);
05251 }
05252
05253
05254 static void update_peer(struct sip_peer *p, int expire)
05255 {
05256 int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
05257 if (sip_cfg.peer_rtupdate &&
05258 (p->is_realtime || rtcachefriends)) {
05259 realtime_update_peer(p->name, &p->addr, p->username, p->fullcontact, p->useragent, expire, p->deprecated_username, p->lastms);
05260 }
05261 }
05262
05263 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *cfg)
05264 {
05265 struct ast_variable *var = NULL;
05266 struct ast_flags flags = {0};
05267 char *cat = NULL;
05268 const char *insecure;
05269 while ((cat = ast_category_browse(cfg, cat))) {
05270 insecure = ast_variable_retrieve(cfg, cat, "insecure");
05271 set_insecure_flags(&flags, insecure, -1);
05272 if (ast_test_flag(&flags, SIP_INSECURE_PORT)) {
05273 var = ast_category_root(cfg, cat);
05274 break;
05275 }
05276 }
05277 return var;
05278 }
05279
05280 static struct ast_variable *get_insecure_variable_from_sippeers(const char *column, const char *value)
05281 {
05282 struct ast_config *peerlist;
05283 struct ast_variable *var = NULL;
05284 if ((peerlist = ast_load_realtime_multientry("sippeers", column, value, "insecure LIKE", "%port%", SENTINEL))) {
05285 if ((var = get_insecure_variable_from_config(peerlist))) {
05286
05287
05288 var = ast_variables_dup(var);
05289 }
05290 ast_config_destroy(peerlist);
05291 }
05292 return var;
05293 }
05294
05295
05296
05297
05298
05299
05300 static struct ast_variable *get_insecure_variable_from_sipregs(const char *column, const char *value, struct ast_variable **var)
05301 {
05302 struct ast_variable *varregs = NULL;
05303 struct ast_config *regs, *peers;
05304 char *regscat;
05305 const char *regname;
05306
05307 if (!(regs = ast_load_realtime_multientry("sipregs", column, value, SENTINEL))) {
05308 return NULL;
05309 }
05310
05311
05312 if (!(peers = ast_load_realtime_multientry("sippeers", "insecure LIKE", "%port%", SENTINEL))) {
05313 ast_config_destroy(regs);
05314 return NULL;
05315 }
05316
05317
05318
05319 regscat = NULL;
05320 while ((regscat = ast_category_browse(regs, regscat)) && (regname = ast_variable_retrieve(regs, regscat, "name"))) {
05321 char *peerscat;
05322 const char *peername;
05323
05324 peerscat = NULL;
05325 while ((peerscat = ast_category_browse(peers, peerscat)) && (peername = ast_variable_retrieve(peers, peerscat, "name"))) {
05326 if (!strcasecmp(regname, peername)) {
05327
05328
05329 const char *insecure = ast_variable_retrieve(peers, peerscat, "insecure");
05330 struct ast_flags flags = {0};
05331 set_insecure_flags(&flags, insecure, -1);
05332 if (ast_test_flag(&flags, SIP_INSECURE_PORT)) {
05333
05334 if ((varregs = ast_variables_dup(ast_category_root(regs, regscat)))) {
05335 if (!(*var = ast_variables_dup(ast_category_root(peers, peerscat)))) {
05336 ast_variables_destroy(varregs);
05337 varregs = NULL;
05338 }
05339 }
05340 goto done;
05341 }
05342 }
05343 }
05344 }
05345
05346 done:
05347 ast_config_destroy(regs);
05348 ast_config_destroy(peers);
05349 return varregs;
05350 }
05351
05352 static const char *get_name_from_variable(const struct ast_variable *var)
05353 {
05354
05355
05356
05357
05358
05359
05360
05361
05362 const struct ast_variable *tmp;
05363 for (tmp = var; tmp; tmp = tmp->next) {
05364 if (!strcasecmp(tmp->name, "name")) {
05365 if (!ast_strlen_zero(tmp->value)) {
05366 return tmp->value;
05367 }
05368 break;
05369 }
05370 }
05371 return NULL;
05372 }
05373
05374
05375
05376 static int realtime_peer_by_name(const char *const *name, struct ast_sockaddr *addr, const char *ipaddr, struct ast_variable **var, struct ast_variable **varregs)
05377 {
05378
05379 if ((*var = ast_load_realtime("sippeers", "name", *name, "host", "dynamic", SENTINEL))) {
05380 ;
05381
05382 } else if (addr && !(*var = ast_load_realtime("sippeers", "name", *name, "host", ipaddr, SENTINEL))) {
05383 ;
05384
05385 } else if ((*var = ast_load_realtime("sippeers", "name", *name, SENTINEL))) {
05386
05387
05388
05389
05390
05391
05392 if (addr) {
05393 struct ast_variable *tmp;
05394 for (tmp = *var; tmp; tmp = tmp->next) {
05395 if (!strcasecmp(tmp->name, "host")) {
05396 struct ast_sockaddr *addrs = NULL;
05397
05398 if (ast_sockaddr_resolve(&addrs,
05399 tmp->value,
05400 PARSE_PORT_FORBID,
05401 get_address_family_filter(SIP_TRANSPORT_UDP)) <= 0 ||
05402 ast_sockaddr_cmp(&addrs[0], addr)) {
05403
05404 ast_variables_destroy(*var);
05405 *var = NULL;
05406 }
05407 ast_free(addrs);
05408 break;
05409 }
05410 }
05411 }
05412 }
05413
05414
05415 if (*var) {
05416 if (varregs) {
05417 *varregs = ast_load_realtime("sipregs", "name", *name, SENTINEL);
05418 }
05419 return 1;
05420 }
05421 return 0;
05422 }
05423
05424
05425
05426
05427
05428
05429
05430 static struct ast_variable *realtime_peer_get_sippeer_helper(const char **name, struct ast_variable **varregs) {
05431 struct ast_variable *var = NULL;
05432 const char *old_name = *name;
05433 *name = get_name_from_variable(*varregs);
05434 if (!*name || !(var = ast_load_realtime("sippeers", "name", *name, SENTINEL))) {
05435 if (!*name) {
05436 ast_log(LOG_WARNING, "Found sipreg but it has no name\n");
05437 }
05438 ast_variables_destroy(*varregs);
05439 *varregs = NULL;
05440 *name = old_name;
05441 }
05442 return var;
05443 }
05444
05445
05446
05447
05448 static int realtime_peer_by_addr(const char **name, struct ast_sockaddr *addr, const char *ipaddr, const char *callbackexten, struct ast_variable **var, struct ast_variable **varregs)
05449 {
05450 char portstring[6];
05451 ast_copy_string(portstring, ast_sockaddr_stringify_port(addr), sizeof(portstring));
05452
05453
05454 *name = NULL;
05455
05456
05457 if (!ast_strlen_zero(callbackexten) && (*var = ast_load_realtime("sippeers", "host", ipaddr, "port", portstring, "callbackextension", callbackexten, SENTINEL))) {
05458 ;
05459
05460 } else if ((*var = ast_load_realtime("sippeers", "host", ipaddr, "port", portstring, SENTINEL))) {
05461 ;
05462
05463 } else if (varregs && (*varregs = ast_load_realtime("sipregs", "ipaddr", ipaddr, "port", portstring, SENTINEL)) &&
05464 (*var = realtime_peer_get_sippeer_helper(name, varregs))) {
05465 ;
05466
05467 } else if (!varregs && (*var = ast_load_realtime("sippeers", "ipaddr", ipaddr, "port", portstring, SENTINEL))) {
05468 ;
05469
05470 } else if ((*var = get_insecure_variable_from_sippeers("host", ipaddr))) {
05471 ;
05472
05473
05474
05475
05476 } else if (varregs && (*varregs = get_insecure_variable_from_sipregs("ipaddr", ipaddr, var))) {
05477 ;
05478
05479 } else if (!varregs && (*var = get_insecure_variable_from_sippeers("ipaddr", ipaddr))) {
05480 ;
05481 }
05482
05483
05484 if (!*var) {
05485 return 0;
05486 }
05487
05488
05489
05490
05491 if (!*name && !(*name = get_name_from_variable(*var))) {
05492 ast_log(LOG_WARNING, "Found peer for IP %s but it has no name\n", ipaddr);
05493 ast_variables_destroy(*var);
05494 *var = NULL;
05495 if (varregs && *varregs) {
05496 ast_variables_destroy(*varregs);
05497 *varregs = NULL;
05498 }
05499 return 0;
05500 }
05501
05502
05503
05504
05505 if (varregs && !*varregs) {
05506 *varregs = ast_load_realtime("sipregs", "name", *name, SENTINEL);
05507 }
05508 return 1;
05509 }
05510
05511 static int register_realtime_peers_with_callbackextens(void)
05512 {
05513 struct ast_config *cfg;
05514 char *cat = NULL;
05515
05516 if (!(ast_check_realtime("sippeers"))) {
05517 return 0;
05518 }
05519
05520
05521 if (!(cfg = ast_load_realtime_multientry("sippeers", "name LIKE", "%", "callbackextension LIKE", "%", SENTINEL))) {
05522 return -1;
05523 }
05524
05525 while ((cat = ast_category_browse(cfg, cat))) {
05526 struct sip_peer *peer;
05527 struct ast_variable *var = ast_category_root(cfg, cat);
05528
05529 if (!(peer = build_peer(cat, var, NULL, TRUE, FALSE))) {
05530 continue;
05531 }
05532 ast_log(LOG_NOTICE, "Created realtime peer '%s' for registration\n", peer->name);
05533
05534 peer->is_realtime = 1;
05535 sip_unref_peer(peer, "register_realtime_peers: Done registering releasing");
05536 }
05537
05538 ast_config_destroy(cfg);
05539
05540 return 0;
05541 }
05542
05543
05544
05545
05546
05547
05548
05549
05550
05551
05552 static struct sip_peer *realtime_peer(const char *newpeername, struct ast_sockaddr *addr, char *callbackexten, int devstate_only, int which_objects)
05553 {
05554 struct sip_peer *peer = NULL;
05555 struct ast_variable *var = NULL;
05556 struct ast_variable *varregs = NULL;
05557 char ipaddr[INET6_ADDRSTRLEN];
05558 int realtimeregs = ast_check_realtime("sipregs");
05559
05560 if (addr) {
05561 ast_copy_string(ipaddr, ast_sockaddr_stringify_addr(addr), sizeof(ipaddr));
05562 } else {
05563 ipaddr[0] = '\0';
05564 }
05565
05566 if (newpeername && realtime_peer_by_name(&newpeername, addr, ipaddr, &var, realtimeregs ? &varregs : NULL)) {
05567 ;
05568 } else if (addr && realtime_peer_by_addr(&newpeername, addr, ipaddr, callbackexten, &var, realtimeregs ? &varregs : NULL)) {
05569 ;
05570 } else {
05571 return NULL;
05572 }
05573
05574
05575
05576 if (which_objects == FINDUSERS) {
05577 struct ast_variable *tmp;
05578 for (tmp = var; tmp; tmp = tmp->next) {
05579 if (!strcasecmp(tmp->name, "type") && (!strcasecmp(tmp->value, "peer"))) {
05580 goto cleanup;
05581 }
05582 }
05583 }
05584
05585
05586 peer = build_peer(newpeername, var, varregs, TRUE, devstate_only);
05587 if (!peer) {
05588 goto cleanup;
05589 }
05590
05591
05592
05593 if (peer->type == 0) {
05594 if (which_objects == FINDUSERS) {
05595 peer->type = SIP_TYPE_USER;
05596 } else if (which_objects == FINDPEERS) {
05597 peer->type = SIP_TYPE_PEER;
05598 } else {
05599 peer->type = SIP_TYPE_PEER | SIP_TYPE_USER;
05600 }
05601 }
05602
05603 ast_debug(3, "-REALTIME- loading peer from database to memory. Name: %s. Peer objects: %d\n", peer->name, rpeerobjs);
05604
05605 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && !devstate_only) {
05606
05607 ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
05608 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
05609 AST_SCHED_REPLACE_UNREF(peer->expire, sched, sip_cfg.rtautoclear * 1000, expire_register, peer,
05610 sip_unref_peer(_data, "remove registration ref"),
05611 sip_unref_peer(peer, "remove registration ref"),
05612 sip_ref_peer(peer, "add registration ref"));
05613 }
05614 ao2_t_link(peers, peer, "link peer into peers table");
05615 if (!ast_sockaddr_isnull(&peer->addr)) {
05616 ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
05617 }
05618 }
05619 peer->is_realtime = 1;
05620
05621 cleanup:
05622 ast_variables_destroy(var);
05623 ast_variables_destroy(varregs);
05624 return peer;
05625 }
05626
05627
05628 static int find_by_name(void *obj, void *arg, void *data, int flags)
05629 {
05630 struct sip_peer *search = obj, *match = arg;
05631 int *which_objects = data;
05632
05633
05634 if (strcmp(search->name, match->name)) {
05635 return 0;
05636 }
05637
05638 switch (*which_objects) {
05639 case FINDUSERS:
05640 if (!(search->type & SIP_TYPE_USER)) {
05641 return 0;
05642 }
05643 break;
05644 case FINDPEERS:
05645 if (!(search->type & SIP_TYPE_PEER)) {
05646 return 0;
05647 }
05648 break;
05649 case FINDALLDEVICES:
05650 break;
05651 }
05652
05653 return CMP_MATCH | CMP_STOP;
05654 }
05655
05656 static struct sip_peer *sip_find_peer_full(const char *peer, struct ast_sockaddr *addr, char *callbackexten, int realtime, int which_objects, int devstate_only, int transport)
05657 {
05658 struct sip_peer *p = NULL;
05659 struct sip_peer tmp_peer;
05660
05661 if (peer) {
05662 ast_copy_string(tmp_peer.name, peer, sizeof(tmp_peer.name));
05663 p = ao2_t_callback_data(peers, OBJ_POINTER, find_by_name, &tmp_peer, &which_objects, "ao2_find in peers table");
05664 } else if (addr) {
05665 ast_sockaddr_copy(&tmp_peer.addr, addr);
05666 tmp_peer.flags[0].flags = 0;
05667 tmp_peer.transports = transport;
05668 p = ao2_t_callback_data(peers_by_ip, OBJ_POINTER, peer_ipcmp_cb_full, &tmp_peer, callbackexten, "ao2_find in peers_by_ip table");
05669 if (!p) {
05670 ast_set_flag(&tmp_peer.flags[0], SIP_INSECURE_PORT);
05671 p = ao2_t_callback_data(peers_by_ip, OBJ_POINTER, peer_ipcmp_cb_full, &tmp_peer, callbackexten, "ao2_find in peers_by_ip table 2");
05672 if (p) {
05673 return p;
05674 }
05675 }
05676 }
05677
05678 if (!p && (realtime || devstate_only)) {
05679
05680
05681 p = realtime_peer(peer, addr, callbackexten, devstate_only, which_objects);
05682 if (p) {
05683 switch (which_objects) {
05684 case FINDUSERS:
05685 if (!(p->type & SIP_TYPE_USER)) {
05686 sip_unref_peer(p, "Wrong type of realtime SIP endpoint");
05687 return NULL;
05688 }
05689 break;
05690 case FINDPEERS:
05691 if (!(p->type & SIP_TYPE_PEER)) {
05692 sip_unref_peer(p, "Wrong type of realtime SIP endpoint");
05693 return NULL;
05694 }
05695 break;
05696 case FINDALLDEVICES:
05697 break;
05698 }
05699 }
05700 }
05701
05702 return p;
05703 }
05704
05705
05706
05707
05708
05709
05710
05711
05712
05713
05714
05715
05716
05717
05718 struct sip_peer *sip_find_peer(const char *peer, struct ast_sockaddr *addr, int realtime, int which_objects, int devstate_only, int transport)
05719 {
05720 return sip_find_peer_full(peer, addr, NULL, realtime, which_objects, devstate_only, transport);
05721 }
05722
05723 static struct sip_peer *sip_find_peer_by_ip_and_exten(struct ast_sockaddr *addr, char *callbackexten, int transport)
05724 {
05725 return sip_find_peer_full(NULL, addr, callbackexten, TRUE, FINDPEERS, FALSE, transport);
05726 }
05727
05728
05729 static void do_setnat(struct sip_pvt *p)
05730 {
05731 const char *mode;
05732 int natflags;
05733
05734 natflags = ast_test_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP);
05735 mode = natflags ? "On" : "Off";
05736
05737 if (p->rtp) {
05738 ast_debug(1, "Setting NAT on RTP to %s\n", mode);
05739 ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_NAT, natflags);
05740 }
05741 if (p->vrtp) {
05742 ast_debug(1, "Setting NAT on VRTP to %s\n", mode);
05743 ast_rtp_instance_set_prop(p->vrtp, AST_RTP_PROPERTY_NAT, natflags);
05744 }
05745 if (p->udptl) {
05746 ast_debug(1, "Setting NAT on UDPTL to %s\n", mode);
05747 ast_udptl_setnat(p->udptl, natflags);
05748 }
05749 if (p->trtp) {
05750 ast_debug(1, "Setting NAT on TRTP to %s\n", mode);
05751 ast_rtp_instance_set_prop(p->trtp, AST_RTP_PROPERTY_NAT, natflags);
05752 }
05753 }
05754
05755
05756 static void change_t38_state(struct sip_pvt *p, int state)
05757 {
05758 int old = p->t38.state;
05759 struct ast_channel *chan = p->owner;
05760 struct ast_control_t38_parameters parameters = { .request_response = 0 };
05761
05762
05763 if (old == state)
05764 return;
05765
05766 p->t38.state = state;
05767 ast_debug(2, "T38 state changed to %d on channel %s\n", p->t38.state, chan ? ast_channel_name(chan) : "<none>");
05768
05769
05770 if (!chan)
05771 return;
05772
05773
05774 switch (state) {
05775 case T38_PEER_REINVITE:
05776 parameters = p->t38.their_parms;
05777 parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
05778 parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
05779 ast_udptl_set_tag(p->udptl, "%s", ast_channel_name(chan));
05780 break;
05781 case T38_ENABLED:
05782 parameters = p->t38.their_parms;
05783 parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
05784 parameters.request_response = AST_T38_NEGOTIATED;
05785 ast_udptl_set_tag(p->udptl, "%s", ast_channel_name(chan));
05786 break;
05787 case T38_REJECTED:
05788 case T38_DISABLED:
05789 if (old == T38_ENABLED) {
05790 parameters.request_response = AST_T38_TERMINATED;
05791 } else if (old == T38_LOCAL_REINVITE) {
05792 parameters.request_response = AST_T38_REFUSED;
05793 }
05794 break;
05795 case T38_LOCAL_REINVITE:
05796
05797 break;
05798 }
05799
05800
05801 if (parameters.request_response)
05802 ast_queue_control_data(chan, AST_CONTROL_T38_PARAMETERS, ¶meters, sizeof(parameters));
05803 }
05804
05805
05806 static void set_t38_capabilities(struct sip_pvt *p)
05807 {
05808 if (p->udptl) {
05809 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY) {
05810 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
05811 } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_FEC) {
05812 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
05813 } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL) {
05814 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
05815 }
05816 }
05817 }
05818
05819 static void copy_socket_data(struct sip_socket *to_sock, const struct sip_socket *from_sock)
05820 {
05821 if (to_sock->tcptls_session) {
05822 ao2_ref(to_sock->tcptls_session, -1);
05823 to_sock->tcptls_session = NULL;
05824 } else if (to_sock->ws_session) {
05825 ast_websocket_unref(to_sock->ws_session);
05826 to_sock->ws_session = NULL;
05827 }
05828
05829 if (from_sock->tcptls_session) {
05830 ao2_ref(from_sock->tcptls_session, +1);
05831 } else if (from_sock->ws_session) {
05832 ast_websocket_ref(from_sock->ws_session);
05833 }
05834
05835 *to_sock = *from_sock;
05836 }
05837
05838
05839 static int dialog_initialize_dtls_srtp(const struct sip_pvt *dialog, struct ast_rtp_instance *rtp, struct sip_srtp **srtp)
05840 {
05841 struct ast_rtp_engine_dtls *dtls;
05842
05843 if (!dialog->dtls_cfg.enabled) {
05844 return 0;
05845 }
05846
05847 if (!ast_rtp_engine_srtp_is_registered()) {
05848 ast_log(LOG_ERROR, "No SRTP module loaded, can't setup SRTP session.\n");
05849 return -1;
05850 }
05851
05852 if (!(dtls = ast_rtp_instance_get_dtls(rtp))) {
05853 ast_log(LOG_ERROR, "No DTLS-SRTP support present on engine for RTP instance '%p', was it compiled with support for it?\n",
05854 rtp);
05855 return -1;
05856 }
05857
05858 if (dtls->set_configuration(rtp, &dialog->dtls_cfg)) {
05859 ast_log(LOG_ERROR, "Attempted to set an invalid DTLS-SRTP configuration on RTP instance '%p'\n",
05860 rtp);
05861 return -1;
05862 }
05863
05864 if (!(*srtp = sip_srtp_alloc())) {
05865 ast_log(LOG_ERROR, "Failed to create required SRTP structure on RTP instance '%p'\n",
05866 rtp);
05867 return -1;
05868 }
05869
05870 return 0;
05871 }
05872
05873
05874
05875
05876 static int dialog_initialize_rtp(struct sip_pvt *dialog)
05877 {
05878 struct ast_sockaddr bindaddr_tmp;
05879 struct ast_rtp_engine_ice *ice;
05880
05881 if (!sip_methods[dialog->method].need_rtp) {
05882 return 0;
05883 }
05884
05885 ast_sockaddr_copy(&bindaddr_tmp, &bindaddr);
05886 if (!(dialog->rtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr_tmp, NULL))) {
05887 return -1;
05888 }
05889
05890 if (!ast_test_flag(&dialog->flags[2], SIP_PAGE3_ICE_SUPPORT) && (ice = ast_rtp_instance_get_ice(dialog->rtp))) {
05891 ice->stop(dialog->rtp);
05892 }
05893
05894 if (dialog_initialize_dtls_srtp(dialog, dialog->rtp, &dialog->srtp)) {
05895 return -1;
05896 }
05897
05898 if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS) ||
05899 (ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT) && (ast_format_cap_has_type(dialog->caps, AST_FORMAT_TYPE_VIDEO)))) {
05900 if (!(dialog->vrtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr_tmp, NULL))) {
05901 return -1;
05902 }
05903
05904 if (!ast_test_flag(&dialog->flags[2], SIP_PAGE3_ICE_SUPPORT) && (ice = ast_rtp_instance_get_ice(dialog->vrtp))) {
05905 ice->stop(dialog->vrtp);
05906 }
05907
05908 if (dialog_initialize_dtls_srtp(dialog, dialog->vrtp, &dialog->vsrtp)) {
05909 return -1;
05910 }
05911
05912 ast_rtp_instance_set_timeout(dialog->vrtp, dialog->rtptimeout);
05913 ast_rtp_instance_set_hold_timeout(dialog->vrtp, dialog->rtpholdtimeout);
05914 ast_rtp_instance_set_keepalive(dialog->vrtp, dialog->rtpkeepalive);
05915
05916 ast_rtp_instance_set_prop(dialog->vrtp, AST_RTP_PROPERTY_RTCP, 1);
05917 ast_rtp_instance_set_qos(dialog->vrtp, global_tos_video, global_cos_video, "SIP VIDEO");
05918 }
05919
05920 if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_TEXTSUPPORT)) {
05921 if (!(dialog->trtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr_tmp, NULL))) {
05922 return -1;
05923 }
05924
05925 if (!ast_test_flag(&dialog->flags[2], SIP_PAGE3_ICE_SUPPORT) && (ice = ast_rtp_instance_get_ice(dialog->trtp))) {
05926 ice->stop(dialog->trtp);
05927 }
05928
05929 if (dialog_initialize_dtls_srtp(dialog, dialog->trtp, &dialog->tsrtp)) {
05930 return -1;
05931 }
05932
05933
05934 ast_rtp_instance_set_keepalive(dialog->trtp, dialog->rtpkeepalive);
05935
05936 ast_rtp_instance_set_prop(dialog->trtp, AST_RTP_PROPERTY_RTCP, 1);
05937 }
05938
05939 ast_rtp_instance_set_timeout(dialog->rtp, dialog->rtptimeout);
05940 ast_rtp_instance_set_hold_timeout(dialog->rtp, dialog->rtpholdtimeout);
05941 ast_rtp_instance_set_keepalive(dialog->rtp, dialog->rtpkeepalive);
05942
05943 ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_RTCP, 1);
05944 ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
05945 ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
05946
05947 ast_rtp_instance_set_qos(dialog->rtp, global_tos_audio, global_cos_audio, "SIP RTP");
05948
05949 do_setnat(dialog);
05950
05951 return 0;
05952 }
05953
05954
05955
05956
05957
05958
05959
05960
05961 static int create_addr_from_peer(struct sip_pvt *dialog, struct sip_peer *peer)
05962 {
05963 struct sip_auth_container *credentials;
05964
05965
05966
05967
05968 if (dialog->socket.type && check_request_transport(peer, dialog))
05969 return -1;
05970 copy_socket_data(&dialog->socket, &peer->socket);
05971
05972 if (!(ast_sockaddr_isnull(&peer->addr) && ast_sockaddr_isnull(&peer->defaddr)) &&
05973 (!peer->maxms || ((peer->lastms >= 0) && (peer->lastms <= peer->maxms)))) {
05974 dialog->sa = ast_sockaddr_isnull(&peer->addr) ? peer->defaddr : peer->addr;
05975 dialog->recv = dialog->sa;
05976 } else
05977 return -1;
05978
05979
05980 ast_copy_flags(&dialog->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
05981 ast_copy_flags(&dialog->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
05982 ast_copy_flags(&dialog->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
05983 ast_format_cap_copy(dialog->caps, peer->caps);
05984 dialog->prefs = peer->prefs;
05985 dialog->amaflags = peer->amaflags;
05986
05987 ast_string_field_set(dialog, engine, peer->engine);
05988
05989 ast_rtp_dtls_cfg_copy(&peer->dtls_cfg, &dialog->dtls_cfg);
05990
05991 dialog->rtptimeout = peer->rtptimeout;
05992 dialog->rtpholdtimeout = peer->rtpholdtimeout;
05993 dialog->rtpkeepalive = peer->rtpkeepalive;
05994 if (dialog_initialize_rtp(dialog)) {
05995 return -1;
05996 }
05997
05998 if (dialog->rtp) {
05999 ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
06000 ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
06001
06002 ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(dialog->rtp), dialog->rtp, &dialog->prefs);
06003 dialog->autoframing = peer->autoframing;
06004 }
06005
06006
06007 ast_string_field_set(dialog, peername, peer->name);
06008 ast_string_field_set(dialog, authname, peer->username);
06009 ast_string_field_set(dialog, username, peer->username);
06010 ast_string_field_set(dialog, peersecret, peer->secret);
06011 ast_string_field_set(dialog, peermd5secret, peer->md5secret);
06012 ast_string_field_set(dialog, mohsuggest, peer->mohsuggest);
06013 ast_string_field_set(dialog, mohinterpret, peer->mohinterpret);
06014 ast_string_field_set(dialog, tohost, peer->tohost);
06015 ast_string_field_set(dialog, fullcontact, peer->fullcontact);
06016 ast_string_field_set(dialog, accountcode, peer->accountcode);
06017 ast_string_field_set(dialog, context, peer->context);
06018 ast_string_field_set(dialog, cid_num, peer->cid_num);
06019 ast_string_field_set(dialog, cid_name, peer->cid_name);
06020 ast_string_field_set(dialog, cid_tag, peer->cid_tag);
06021 ast_string_field_set(dialog, mwi_from, peer->mwi_from);
06022 if (!ast_strlen_zero(peer->parkinglot)) {
06023 ast_string_field_set(dialog, parkinglot, peer->parkinglot);
06024 }
06025 ast_string_field_set(dialog, engine, peer->engine);
06026 ref_proxy(dialog, obproxy_get(dialog, peer));
06027 dialog->callgroup = peer->callgroup;
06028 dialog->pickupgroup = peer->pickupgroup;
06029 ast_unref_namedgroups(dialog->named_callgroups);
06030 dialog->named_callgroups = ast_ref_namedgroups(peer->named_callgroups);
06031 ast_unref_namedgroups(dialog->named_pickupgroups);
06032 dialog->named_pickupgroups = ast_ref_namedgroups(peer->named_pickupgroups);
06033 ast_copy_string(dialog->zone, peer->zone, sizeof(dialog->zone));
06034 dialog->allowtransfer = peer->allowtransfer;
06035 dialog->jointnoncodeccapability = dialog->noncodeccapability;
06036
06037
06038 ao2_lock(peer);
06039 credentials = peer->auth;
06040 if (credentials) {
06041 ao2_t_ref(credentials, +1, "Ref peer auth for dialog");
06042 }
06043 ao2_unlock(peer);
06044 ao2_lock(dialog);
06045 if (dialog->peerauth) {
06046 ao2_t_ref(dialog->peerauth, -1, "Unref old dialog peer auth");
06047 }
06048 dialog->peerauth = credentials;
06049 ao2_unlock(dialog);
06050
06051 dialog->maxcallbitrate = peer->maxcallbitrate;
06052 dialog->disallowed_methods = peer->disallowed_methods;
06053 ast_cc_copy_config_params(dialog->cc_params, peer->cc_params);
06054 if (ast_strlen_zero(dialog->tohost))
06055 ast_string_field_set(dialog, tohost, ast_sockaddr_stringify_host_remote(&dialog->sa));
06056 if (!ast_strlen_zero(peer->fromdomain)) {
06057 ast_string_field_set(dialog, fromdomain, peer->fromdomain);
06058 if (!dialog->initreq.headers) {
06059 char *new_callid;
06060 char *tmpcall = ast_strdupa(dialog->callid);
06061
06062 new_callid = strchr(tmpcall, '@');
06063 if (new_callid) {
06064 int callid_size;
06065
06066 *new_callid = '\0';
06067
06068
06069 callid_size = strlen(tmpcall) + strlen(peer->fromdomain) + 2;
06070 new_callid = ast_alloca(callid_size);
06071 snprintf(new_callid, callid_size, "%s@%s", tmpcall, peer->fromdomain);
06072 change_callid_pvt(dialog, new_callid);
06073 }
06074 }
06075 }
06076 if (!ast_strlen_zero(peer->fromuser))
06077 ast_string_field_set(dialog, fromuser, peer->fromuser);
06078 if (!ast_strlen_zero(peer->language))
06079 ast_string_field_set(dialog, language, peer->language);
06080
06081
06082
06083
06084 if (peer->maxms && peer->lastms)
06085 dialog->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
06086 else
06087 dialog->timer_t1 = peer->timer_t1;
06088
06089
06090
06091 if (peer->timer_b)
06092 dialog->timer_b = peer->timer_b;
06093 else
06094 dialog->timer_b = 64 * dialog->timer_t1;
06095
06096 if ((ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
06097 (ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
06098 dialog->noncodeccapability |= AST_RTP_DTMF;
06099 else
06100 dialog->noncodeccapability &= ~AST_RTP_DTMF;
06101
06102 dialog->directmediaacl = ast_duplicate_acl_list(peer->directmediaacl);
06103
06104 if (peer->call_limit)
06105 ast_set_flag(&dialog->flags[0], SIP_CALL_LIMIT);
06106 if (!dialog->portinuri)
06107 dialog->portinuri = peer->portinuri;
06108 dialog->chanvars = copy_vars(peer->chanvars);
06109 if (peer->fromdomainport)
06110 dialog->fromdomainport = peer->fromdomainport;
06111 dialog->callingpres = peer->callingpres;
06112
06113 return 0;
06114 }
06115
06116
06117 static inline int default_sip_port(enum sip_transport type)
06118 {
06119 return type == SIP_TRANSPORT_TLS ? STANDARD_TLS_PORT : STANDARD_SIP_PORT;
06120 }
06121
06122
06123
06124
06125 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct ast_sockaddr *addr, int newdialog)
06126 {
06127 struct sip_peer *peer;
06128 char *peername, *peername2, *hostn;
06129 char host[MAXHOSTNAMELEN];
06130 char service[MAXHOSTNAMELEN];
06131 int srv_ret = 0;
06132 int tportno;
06133
06134 AST_DECLARE_APP_ARGS(hostport,
06135 AST_APP_ARG(host);
06136 AST_APP_ARG(port);
06137 );
06138
06139 peername = ast_strdupa(opeer);
06140 peername2 = ast_strdupa(opeer);
06141 AST_NONSTANDARD_RAW_ARGS(hostport, peername2, ':');
06142
06143 if (hostport.port)
06144 dialog->portinuri = 1;
06145
06146 dialog->timer_t1 = global_t1;
06147 dialog->timer_b = global_timer_b;
06148 peer = sip_find_peer(peername, NULL, TRUE, FINDPEERS, FALSE, 0);
06149
06150 if (peer) {
06151 int res;
06152 if (newdialog) {
06153 set_socket_transport(&dialog->socket, 0);
06154 }
06155 res = create_addr_from_peer(dialog, peer);
06156 dialog->relatedpeer = sip_ref_peer(peer, "create_addr: setting dialog's relatedpeer pointer");
06157 sip_unref_peer(peer, "create_addr: unref peer from sip_find_peer hashtab lookup");
06158 return res;
06159 } else if (ast_check_digits(peername)) {
06160
06161
06162
06163 ast_log(LOG_WARNING, "Purely numeric hostname (%s), and not a peer--rejecting!\n", peername);
06164 return -1;
06165 } else {
06166 dialog->rtptimeout = global_rtptimeout;
06167 dialog->rtpholdtimeout = global_rtpholdtimeout;
06168 dialog->rtpkeepalive = global_rtpkeepalive;
06169 if (dialog_initialize_rtp(dialog)) {
06170 return -1;
06171 }
06172 }
06173
06174 ast_string_field_set(dialog, tohost, hostport.host);
06175 dialog->allowed_methods &= ~sip_cfg.disallowed_methods;
06176
06177
06178 ref_proxy(dialog, obproxy_get(dialog, NULL));
06179
06180 if (addr) {
06181
06182 ast_sockaddr_copy(&dialog->sa, addr);
06183 } else {
06184
06185
06186
06187
06188
06189
06190 hostn = peername;
06191
06192
06193
06194 if (!hostport.port && sip_cfg.srvlookup) {
06195 snprintf(service, sizeof(service), "_%s._%s.%s",
06196 get_srv_service(dialog->socket.type),
06197 get_srv_protocol(dialog->socket.type), peername);
06198 if ((srv_ret = ast_get_srv(NULL, host, sizeof(host), &tportno,
06199 service)) > 0) {
06200 hostn = host;
06201 }
06202 }
06203
06204 if (ast_sockaddr_resolve_first_transport(&dialog->sa, hostn, 0, dialog->socket.type ? dialog->socket.type : SIP_TRANSPORT_UDP)) {
06205 ast_log(LOG_WARNING, "No such host: %s\n", peername);
06206 return -1;
06207 }
06208
06209 if (srv_ret > 0) {
06210 ast_sockaddr_set_port(&dialog->sa, tportno);
06211 }
06212 }
06213
06214 if (!dialog->socket.type)
06215 set_socket_transport(&dialog->socket, SIP_TRANSPORT_UDP);
06216 if (!dialog->socket.port) {
06217 dialog->socket.port = htons(ast_sockaddr_port(&bindaddr));
06218 }
06219
06220 if (!ast_sockaddr_port(&dialog->sa)) {
06221 ast_sockaddr_set_port(&dialog->sa, default_sip_port(dialog->socket.type));
06222 }
06223 ast_sockaddr_copy(&dialog->recv, &dialog->sa);
06224 return 0;
06225 }
06226
06227
06228
06229
06230 static int auto_congest(const void *arg)
06231 {
06232 struct sip_pvt *p = (struct sip_pvt *)arg;
06233
06234 sip_pvt_lock(p);
06235 p->initid = -1;
06236 if (p->owner) {
06237
06238 if (!ast_channel_trylock(p->owner)) {
06239 append_history(p, "Cong", "Auto-congesting (timer)");
06240 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
06241 ast_channel_unlock(p->owner);
06242 }
06243
06244
06245 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06246 }
06247 sip_pvt_unlock(p);
06248 dialog_unref(p, "unreffing arg passed into auto_congest callback (p->initid)");
06249 return 0;
06250 }
06251
06252
06253
06254
06255 static int sip_call(struct ast_channel *ast, const char *dest, int timeout)
06256 {
06257 int res;
06258 struct sip_pvt *p = ast_channel_tech_pvt(ast);
06259 struct varshead *headp;
06260 struct ast_var_t *current;
06261 const char *referer = NULL;
06262 int cc_core_id;
06263 char uri[SIPBUFSIZE] = "";
06264
06265 if ((ast_channel_state(ast) != AST_STATE_DOWN) && (ast_channel_state(ast) != AST_STATE_RESERVED)) {
06266 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast_channel_name(ast));
06267 return -1;
06268 }
06269
06270 if (ast_cc_is_recall(ast, &cc_core_id, "SIP")) {
06271 char device_name[AST_CHANNEL_NAME];
06272 struct ast_cc_monitor *recall_monitor;
06273 struct sip_monitor_instance *monitor_instance;
06274 ast_channel_get_device_name(ast, device_name, sizeof(device_name));
06275 if ((recall_monitor = ast_cc_get_monitor_by_recall_core_id(cc_core_id, device_name))) {
06276 monitor_instance = recall_monitor->private_data;
06277 ast_copy_string(uri, monitor_instance->notify_uri, sizeof(uri));
06278 ao2_t_ref(recall_monitor, -1, "Got the URI we need so unreffing monitor");
06279 }
06280 }
06281
06282
06283 headp=ast_channel_varshead(ast);
06284 AST_LIST_TRAVERSE(headp, current, entries) {
06285
06286 if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
06287 p->options->vxml_url = ast_var_value(current);
06288 } else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
06289 p->options->uri_options = ast_var_value(current);
06290 } else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
06291
06292 p->options->addsipheaders = 1;
06293 } else if (!strcasecmp(ast_var_name(current), "SIPFROMDOMAIN")) {
06294 ast_string_field_set(p, fromdomain, ast_var_value(current));
06295 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER")) {
06296
06297 p->options->transfer = 1;
06298 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REFERER")) {
06299
06300 referer = ast_var_value(current);
06301 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REPLACES")) {
06302
06303 p->options->replaces = ast_var_value(current);
06304 } else if (!strcasecmp(ast_var_name(current), "SIP_MAX_FORWARDS")) {
06305 if (sscanf(ast_var_value(current), "%30d", &(p->maxforwards)) != 1) {
06306 ast_log(LOG_WARNING, "The SIP_MAX_FORWARDS channel variable is not a valid integer.\n");
06307 }
06308 }
06309 }
06310
06311
06312 if (p->req_secure_signaling && p->socket.type != SIP_TRANSPORT_TLS) {
06313 ast_log(LOG_WARNING, "Encrypted signaling is required\n");
06314 ast_channel_hangupcause_set(ast, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
06315 return -1;
06316 }
06317
06318 if (ast_test_flag(&p->flags[1], SIP_PAGE2_USE_SRTP)) {
06319 if (ast_test_flag(&p->flags[0], SIP_REINVITE)) {
06320 ast_debug(1, "Direct media not possible when using SRTP, ignoring canreinvite setting\n");
06321 ast_clear_flag(&p->flags[0], SIP_REINVITE);
06322 }
06323
06324 if (p->rtp && !p->srtp && setup_srtp(&p->srtp) < 0) {
06325 ast_log(LOG_WARNING, "SRTP audio setup failed\n");
06326 return -1;
06327 }
06328
06329 if (p->vrtp && !p->vsrtp && setup_srtp(&p->vsrtp) < 0) {
06330 ast_log(LOG_WARNING, "SRTP video setup failed\n");
06331 return -1;
06332 }
06333
06334 if (p->trtp && !p->tsrtp && setup_srtp(&p->tsrtp) < 0) {
06335 ast_log(LOG_WARNING, "SRTP text setup failed\n");
06336 return -1;
06337 }
06338 }
06339
06340 res = 0;
06341 ast_set_flag(&p->flags[0], SIP_OUTGOING);
06342
06343
06344
06345
06346 ast_clear_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_T38);
06347
06348 if (p->options->transfer) {
06349 char buf[SIPBUFSIZE/2];
06350
06351 if (referer) {
06352 if (sipdebug)
06353 ast_debug(3, "Call for %s transferred by %s\n", p->username, referer);
06354 snprintf(buf, sizeof(buf)-1, "-> %s (via %s)", p->cid_name, referer);
06355 } else
06356 snprintf(buf, sizeof(buf)-1, "-> %s", p->cid_name);
06357 ast_string_field_set(p, cid_name, buf);
06358 }
06359 ast_debug(1, "Outgoing Call for %s\n", p->username);
06360
06361 res = update_call_counter(p, INC_CALL_RINGING);
06362
06363 if (res == -1) {
06364 ast_channel_hangupcause_set(ast, AST_CAUSE_USER_BUSY);
06365 return res;
06366 }
06367 p->callingpres = ast_party_id_presentation(&ast_channel_caller(ast)->id);
06368 ast_rtp_instance_available_formats(p->rtp, p->caps, p->prefcaps, p->jointcaps);
06369 p->jointnoncodeccapability = p->noncodeccapability;
06370
06371
06372 if (!(ast_format_cap_has_type(p->jointcaps, AST_FORMAT_TYPE_AUDIO))) {
06373 ast_log(LOG_WARNING, "No audio format found to offer. Cancelling call to %s\n", p->username);
06374 res = -1;
06375 } else {
06376 int xmitres;
06377 struct ast_party_connected_line connected;
06378 struct ast_set_party_connected_line update_connected;
06379
06380 sip_pvt_lock(p);
06381
06382
06383 memset(&update_connected, 0, sizeof(update_connected));
06384 ast_party_connected_line_init(&connected);
06385 if (!ast_strlen_zero(p->cid_num)
06386 || (p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
06387 update_connected.id.number = 1;
06388 connected.id.number.valid = 1;
06389 connected.id.number.str = (char *) p->cid_num;
06390 connected.id.number.presentation = p->callingpres;
06391 }
06392 if (!ast_strlen_zero(p->cid_name)
06393 || (p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
06394 update_connected.id.name = 1;
06395 connected.id.name.valid = 1;
06396 connected.id.name.str = (char *) p->cid_name;
06397 connected.id.name.presentation = p->callingpres;
06398 }
06399 if (update_connected.id.number || update_connected.id.name) {
06400
06401 ast_set_party_id_all(&update_connected.priv);
06402
06403 connected.id.tag = (char *) p->cid_tag;
06404 connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
06405 ast_channel_queue_connected_line_update(ast, &connected, &update_connected);
06406 }
06407
06408 xmitres = transmit_invite(p, SIP_INVITE, 1, 2, uri);
06409 if (xmitres == XMIT_ERROR) {
06410 sip_pvt_unlock(p);
06411 return -1;
06412 }
06413 p->invitestate = INV_CALLING;
06414
06415
06416 AST_SCHED_REPLACE_UNREF(p->initid, sched, p->timer_b, auto_congest, p,
06417 dialog_unref(_data, "dialog ptr dec when SCHED_REPLACE del op succeeded"),
06418 dialog_unref(p, "dialog ptr dec when SCHED_REPLACE add failed"),
06419 dialog_ref(p, "dialog ptr inc when SCHED_REPLACE add succeeded") );
06420 sip_pvt_unlock(p);
06421 }
06422 return res;
06423 }
06424
06425
06426
06427 static void sip_registry_destroy(struct sip_registry *reg)
06428 {
06429
06430 ast_debug(3, "Destroying registry entry for %s@%s\n", reg->username, reg->hostname);
06431
06432 if (reg->call) {
06433
06434
06435 reg->call->registry = registry_unref(reg->call->registry, "destroy reg->call->registry");
06436 ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", reg->username, reg->hostname);
06437 dialog_unlink_all(reg->call);
06438 reg->call = dialog_unref(reg->call, "unref reg->call");
06439
06440 }
06441 AST_SCHED_DEL(sched, reg->expire);
06442 AST_SCHED_DEL(sched, reg->timeout);
06443
06444 ast_string_field_free_memory(reg);
06445 ast_atomic_fetchadd_int(®objs, -1);
06446 ast_free(reg);
06447 }
06448
06449
06450 static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi)
06451 {
06452 if (mwi->call) {
06453 mwi->call->mwi = NULL;
06454 sip_destroy(mwi->call);
06455 }
06456
06457 AST_SCHED_DEL(sched, mwi->resub);
06458 ast_string_field_free_memory(mwi);
06459 ast_free(mwi);
06460 }
06461
06462
06463 static void offered_media_list_destroy(struct sip_pvt *p)
06464 {
06465 struct offered_media *offer;
06466 while ((offer = AST_LIST_REMOVE_HEAD(&p->offered_media, next))) {
06467 ast_free(offer->decline_m_line);
06468 ast_free(offer);
06469 }
06470 }
06471
06472
06473 void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist)
06474 {
06475 struct sip_request *req;
06476
06477
06478 if (p->stimer) {
06479 p->stimer->quit_flag = 1;
06480 stop_session_timer(p);
06481 ast_free(p->stimer);
06482 p->stimer = NULL;
06483 }
06484
06485 if (sip_debug_test_pvt(p))
06486 ast_verbose("Really destroying SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
06487
06488 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
06489 update_call_counter(p, DEC_CALL_LIMIT);
06490 ast_debug(2, "This call did not properly clean up call limits. Call ID %s\n", p->callid);
06491 }
06492
06493
06494 if (p->owner) {
06495 if (lockowner)
06496 ast_channel_lock(p->owner);
06497 ast_debug(1, "Detaching from %s\n", ast_channel_name(p->owner));
06498 ast_channel_tech_pvt_set(p->owner, NULL);
06499
06500 ast_channel_softhangup_internal_flag_add(p->owner, AST_SOFTHANGUP_DEV);
06501 if (lockowner)
06502 ast_channel_unlock(p->owner);
06503
06504 usleep(1);
06505 }
06506
06507
06508 if (p->relatedpeer && p->relatedpeer->mwipvt == p)
06509 p->relatedpeer->mwipvt = dialog_unref(p->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
06510 if (p->relatedpeer && p->relatedpeer->call == p)
06511 p->relatedpeer->call = dialog_unref(p->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
06512
06513 if (p->relatedpeer)
06514 p->relatedpeer = sip_unref_peer(p->relatedpeer,"unsetting a dialog relatedpeer field in sip_destroy");
06515
06516 if (p->registry) {
06517 if (p->registry->call == p)
06518 p->registry->call = dialog_unref(p->registry->call, "nulling out the registry's call dialog field in unlink_all");
06519 p->registry = registry_unref(p->registry, "delete p->registry");
06520 }
06521
06522 if (p->mwi) {
06523 p->mwi->call = NULL;
06524 p->mwi = NULL;
06525 }
06526
06527 if (dumphistory)
06528 sip_dump_history(p);
06529
06530 if (p->options) {
06531 if (p->options->outboundproxy) {
06532 ao2_ref(p->options->outboundproxy, -1);
06533 }
06534 ast_free(p->options);
06535 p->options = NULL;
06536 }
06537
06538 if (p->notify) {
06539 ast_variables_destroy(p->notify->headers);
06540 ast_free(p->notify->content);
06541 ast_free(p->notify);
06542 p->notify = NULL;
06543 }
06544 if (p->rtp) {
06545 ast_rtp_instance_destroy(p->rtp);
06546 p->rtp = NULL;
06547 }
06548 if (p->vrtp) {
06549 ast_rtp_instance_destroy(p->vrtp);
06550 p->vrtp = NULL;
06551 }
06552 if (p->trtp) {
06553 ast_rtp_instance_destroy(p->trtp);
06554 p->trtp = NULL;
06555 }
06556 if (p->udptl) {
06557 ast_udptl_destroy(p->udptl);
06558 p->udptl = NULL;
06559 }
06560 if (p->refer) {
06561 if (p->refer->refer_call) {
06562 p->refer->refer_call = dialog_unref(p->refer->refer_call, "unref dialog p->refer->refer_call");
06563 }
06564 ast_string_field_free_memory(p->refer);
06565 ast_free(p->refer);
06566 p->refer = NULL;
06567 }
06568 if (p->route) {
06569 free_old_route(p->route);
06570 p->route = NULL;
06571 }
06572 deinit_req(&p->initreq);
06573
06574
06575 if (p->history) {
06576 struct sip_history *hist;
06577 while ( (hist = AST_LIST_REMOVE_HEAD(p->history, list)) ) {
06578 ast_free(hist);
06579 p->history_entries--;
06580 }
06581 ast_free(p->history);
06582 p->history = NULL;
06583 }
06584
06585 while ((req = AST_LIST_REMOVE_HEAD(&p->request_queue, next))) {
06586 ast_free(req);
06587 }
06588
06589 offered_media_list_destroy(p);
06590
06591 if (p->chanvars) {
06592 ast_variables_destroy(p->chanvars);
06593 p->chanvars = NULL;
06594 }
06595
06596 destroy_msg_headers(p);
06597
06598 if (p->srtp) {
06599 sip_srtp_destroy(p->srtp);
06600 p->srtp = NULL;
06601 }
06602
06603 if (p->vsrtp) {
06604 sip_srtp_destroy(p->vsrtp);
06605 p->vsrtp = NULL;
06606 }
06607
06608 if (p->tsrtp) {
06609 sip_srtp_destroy(p->tsrtp);
06610 p->tsrtp = NULL;
06611 }
06612
06613 if (p->directmediaacl) {
06614 p->directmediaacl = ast_free_acl_list(p->directmediaacl);
06615 }
06616
06617 ast_string_field_free_memory(p);
06618
06619 ast_cc_config_params_destroy(p->cc_params);
06620 p->cc_params = NULL;
06621
06622 if (p->epa_entry) {
06623 ao2_ref(p->epa_entry, -1);
06624 p->epa_entry = NULL;
06625 }
06626
06627 if (p->socket.tcptls_session) {
06628 ao2_ref(p->socket.tcptls_session, -1);
06629 p->socket.tcptls_session = NULL;
06630 } else if (p->socket.ws_session) {
06631 ast_websocket_unref(p->socket.ws_session);
06632 p->socket.ws_session = NULL;
06633 }
06634
06635 if (p->peerauth) {
06636 ao2_t_ref(p->peerauth, -1, "Removing active peer authentication");
06637 p->peerauth = NULL;
06638 }
06639
06640 p->named_callgroups = ast_unref_namedgroups(p->named_callgroups);
06641 p->named_pickupgroups = ast_unref_namedgroups(p->named_pickupgroups);
06642
06643 p->caps = ast_format_cap_destroy(p->caps);
06644 p->jointcaps = ast_format_cap_destroy(p->jointcaps);
06645 p->peercaps = ast_format_cap_destroy(p->peercaps);
06646 p->redircaps = ast_format_cap_destroy(p->redircaps);
06647 p->prefcaps = ast_format_cap_destroy(p->prefcaps);
06648
06649 ast_rtp_dtls_cfg_free(&p->dtls_cfg);
06650
06651 if (p->last_device_state_info) {
06652 ao2_ref(p->last_device_state_info, -1);
06653 p->last_device_state_info = NULL;
06654 }
06655
06656
06657 if (p->logger_callid) {
06658 ast_callid_unref(p->logger_callid);
06659 }
06660 }
06661
06662
06663
06664
06665
06666
06667
06668
06669
06670
06671
06672
06673
06674
06675
06676 static int update_call_counter(struct sip_pvt *fup, int event)
06677 {
06678 char name[256];
06679 int *inuse = NULL, *call_limit = NULL, *ringing = NULL;
06680 int outgoing = fup->outgoing_call;
06681 struct sip_peer *p = NULL;
06682
06683 ast_debug(3, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
06684
06685
06686
06687
06688 if (!ast_test_flag(&fup->flags[0], SIP_CALL_LIMIT) && !ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD))
06689 return 0;
06690
06691 ast_copy_string(name, fup->username, sizeof(name));
06692
06693
06694 if (fup->relatedpeer) {
06695 p = sip_ref_peer(fup->relatedpeer, "ref related peer for update_call_counter");
06696 inuse = &p->inuse;
06697 call_limit = &p->call_limit;
06698 ringing = &p->ringing;
06699 ast_copy_string(name, fup->peername, sizeof(name));
06700 }
06701 if (!p) {
06702 ast_debug(2, "%s is not a local device, no call limit\n", name);
06703 return 0;
06704 }
06705
06706 switch(event) {
06707
06708 case DEC_CALL_LIMIT:
06709
06710 if (inuse) {
06711 sip_pvt_lock(fup);
06712 ao2_lock(p);
06713 if (*inuse > 0) {
06714 if (ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
06715 (*inuse)--;
06716 ast_clear_flag(&fup->flags[0], SIP_INC_COUNT);
06717 }
06718 } else {
06719 *inuse = 0;
06720 }
06721 ao2_unlock(p);
06722 sip_pvt_unlock(fup);
06723 }
06724
06725
06726 if (ringing) {
06727 sip_pvt_lock(fup);
06728 ao2_lock(p);
06729 if (*ringing > 0) {
06730 if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
06731 (*ringing)--;
06732 ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
06733 }
06734 } else {
06735 *ringing = 0;
06736 }
06737 ao2_unlock(p);
06738 sip_pvt_unlock(fup);
06739 }
06740
06741
06742 sip_pvt_lock(fup);
06743 ao2_lock(p);
06744 if (ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD) && sip_cfg.notifyhold) {
06745 ast_clear_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD);
06746 ao2_unlock(p);
06747 sip_pvt_unlock(fup);
06748 sip_peer_hold(fup, FALSE);
06749 } else {
06750 ao2_unlock(p);
06751 sip_pvt_unlock(fup);
06752 }
06753 if (sipdebug)
06754 ast_debug(2, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
06755 break;
06756
06757 case INC_CALL_RINGING:
06758 case INC_CALL_LIMIT:
06759
06760 if (*call_limit > 0 ) {
06761 if (*inuse >= *call_limit) {
06762 ast_log(LOG_NOTICE, "Call %s %s '%s' rejected due to usage limit of %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
06763 sip_unref_peer(p, "update_call_counter: unref peer p, call limit exceeded");
06764 return -1;
06765 }
06766 }
06767 if (ringing && (event == INC_CALL_RINGING)) {
06768 sip_pvt_lock(fup);
06769 ao2_lock(p);
06770 if (!ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
06771 (*ringing)++;
06772 ast_set_flag(&fup->flags[0], SIP_INC_RINGING);
06773 }
06774 ao2_unlock(p);
06775 sip_pvt_unlock(fup);
06776 }
06777 if (inuse) {
06778 sip_pvt_lock(fup);
06779 ao2_lock(p);
06780 if (!ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
06781 (*inuse)++;
06782 ast_set_flag(&fup->flags[0], SIP_INC_COUNT);
06783 }
06784 ao2_unlock(p);
06785 sip_pvt_unlock(fup);
06786 }
06787 if (sipdebug) {
06788 ast_debug(2, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", "peer", name, *inuse, *call_limit);
06789 }
06790 break;
06791
06792 case DEC_CALL_RINGING:
06793 if (ringing) {
06794 sip_pvt_lock(fup);
06795 ao2_lock(p);
06796 if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
06797 if (*ringing > 0) {
06798 (*ringing)--;
06799 }
06800 ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
06801 }
06802 ao2_unlock(p);
06803 sip_pvt_unlock(fup);
06804 }
06805 break;
06806
06807 default:
06808 ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
06809 }
06810
06811 if (p) {
06812 ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "SIP/%s", p->name);
06813 sip_unref_peer(p, "update_call_counter: sip_unref_peer from call counter");
06814 }
06815 return 0;
06816 }
06817
06818
06819 static void sip_destroy_fn(void *p)
06820 {
06821 sip_destroy(p);
06822 }
06823
06824
06825
06826
06827
06828
06829 struct sip_pvt *sip_destroy(struct sip_pvt *p)
06830 {
06831 ast_debug(3, "Destroying SIP dialog %s\n", p->callid);
06832 __sip_destroy(p, TRUE, TRUE);
06833 return NULL;
06834 }
06835
06836
06837 int hangup_sip2cause(int cause)
06838 {
06839
06840
06841 switch(cause) {
06842 case 401:
06843 return AST_CAUSE_CALL_REJECTED;
06844 case 403:
06845 return AST_CAUSE_CALL_REJECTED;
06846 case 404:
06847 return AST_CAUSE_UNALLOCATED;
06848 case 405:
06849 return AST_CAUSE_INTERWORKING;
06850 case 407:
06851 return AST_CAUSE_CALL_REJECTED;
06852 case 408:
06853 return AST_CAUSE_NO_USER_RESPONSE;
06854 case 409:
06855 return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
06856 case 410:
06857 return AST_CAUSE_NUMBER_CHANGED;
06858 case 411:
06859 return AST_CAUSE_INTERWORKING;
06860 case 413:
06861 return AST_CAUSE_INTERWORKING;
06862 case 414:
06863 return AST_CAUSE_INTERWORKING;
06864 case 415:
06865 return AST_CAUSE_INTERWORKING;
06866 case 420:
06867 return AST_CAUSE_NO_ROUTE_DESTINATION;
06868 case 480:
06869 return AST_CAUSE_NO_ANSWER;
06870 case 481:
06871 return AST_CAUSE_INTERWORKING;
06872 case 482:
06873 return AST_CAUSE_INTERWORKING;
06874 case 483:
06875 return AST_CAUSE_NO_ANSWER;
06876 case 484:
06877 return AST_CAUSE_INVALID_NUMBER_FORMAT;
06878 case 485:
06879 return AST_CAUSE_UNALLOCATED;
06880 case 486:
06881 return AST_CAUSE_BUSY;
06882 case 487:
06883 return AST_CAUSE_INTERWORKING;
06884 case 488:
06885 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
06886 case 491:
06887 return AST_CAUSE_INTERWORKING;
06888 case 493:
06889 return AST_CAUSE_INTERWORKING;
06890 case 500:
06891 return AST_CAUSE_FAILURE;
06892 case 501:
06893 return AST_CAUSE_FACILITY_REJECTED;
06894 case 502:
06895 return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
06896 case 503:
06897 return AST_CAUSE_CONGESTION;
06898 case 504:
06899 return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
06900 case 505:
06901 return AST_CAUSE_INTERWORKING;
06902 case 600:
06903 return AST_CAUSE_USER_BUSY;
06904 case 603:
06905 return AST_CAUSE_CALL_REJECTED;
06906 case 604:
06907 return AST_CAUSE_UNALLOCATED;
06908 case 606:
06909 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
06910 default:
06911 if (cause < 500 && cause >= 400) {
06912
06913 return AST_CAUSE_INTERWORKING;
06914 } else if (cause < 600 && cause >= 500) {
06915
06916 return AST_CAUSE_CONGESTION;
06917 } else if (cause < 700 && cause >= 600) {
06918
06919 return AST_CAUSE_INTERWORKING;
06920 }
06921 return AST_CAUSE_NORMAL;
06922 }
06923
06924 return 0;
06925 }
06926
06927
06928
06929
06930
06931
06932
06933
06934
06935
06936
06937
06938
06939
06940
06941
06942
06943
06944
06945
06946
06947
06948
06949
06950
06951
06952
06953
06954
06955
06956
06957
06958
06959 const char *hangup_cause2sip(int cause)
06960 {
06961 switch (cause) {
06962 case AST_CAUSE_UNALLOCATED:
06963 case AST_CAUSE_NO_ROUTE_DESTINATION:
06964 case AST_CAUSE_NO_ROUTE_TRANSIT_NET:
06965 return "404 Not Found";
06966 case AST_CAUSE_CONGESTION:
06967 case AST_CAUSE_SWITCH_CONGESTION:
06968 return "503 Service Unavailable";
06969 case AST_CAUSE_NO_USER_RESPONSE:
06970 return "408 Request Timeout";
06971 case AST_CAUSE_NO_ANSWER:
06972 case AST_CAUSE_UNREGISTERED:
06973 return "480 Temporarily unavailable";
06974 case AST_CAUSE_CALL_REJECTED:
06975 return "403 Forbidden";
06976 case AST_CAUSE_NUMBER_CHANGED:
06977 return "410 Gone";
06978 case AST_CAUSE_NORMAL_UNSPECIFIED:
06979 return "480 Temporarily unavailable";
06980 case AST_CAUSE_INVALID_NUMBER_FORMAT:
06981 return "484 Address incomplete";
06982 case AST_CAUSE_USER_BUSY:
06983 return "486 Busy here";
06984 case AST_CAUSE_FAILURE:
06985 return "500 Server internal failure";
06986 case AST_CAUSE_FACILITY_REJECTED:
06987 return "501 Not Implemented";
06988 case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
06989 return "503 Service Unavailable";
06990
06991 case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
06992 return "502 Bad Gateway";
06993 case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL:
06994 return "488 Not Acceptable Here";
06995 case AST_CAUSE_INTERWORKING:
06996 return "500 Network error";
06997
06998 case AST_CAUSE_NOTDEFINED:
06999 default:
07000 ast_debug(1, "AST hangup cause %d (no match found in SIP)\n", cause);
07001 return NULL;
07002 }
07003
07004
07005 return 0;
07006 }
07007
07008 static int reinvite_timeout(const void *data)
07009 {
07010 struct sip_pvt *dialog = (struct sip_pvt *) data;
07011 struct ast_channel *owner = sip_pvt_lock_full(dialog);
07012 dialog->reinviteid = -1;
07013 check_pendings(dialog);
07014 if (owner) {
07015 ast_channel_unlock(owner);
07016 ast_channel_unref(owner);
07017 }
07018 ao2_unlock(dialog);
07019 dialog_unref(dialog, "unref for reinvite timeout");
07020 return 0;
07021 }
07022
07023
07024
07025 static int sip_hangup(struct ast_channel *ast)
07026 {
07027 struct sip_pvt *p = ast_channel_tech_pvt(ast);
07028 int needcancel = FALSE;
07029 int needdestroy = 0;
07030 struct ast_channel *oldowner = ast;
07031
07032 if (!p) {
07033 ast_debug(1, "Asked to hangup channel that was not connected\n");
07034 return 0;
07035 }
07036 if (ast_channel_hangupcause(ast) == AST_CAUSE_ANSWERED_ELSEWHERE) {
07037 ast_debug(1, "This call was answered elsewhere\n");
07038 append_history(p, "Cancel", "Call answered elsewhere");
07039 p->answered_elsewhere = TRUE;
07040 }
07041
07042
07043 if (p->owner)
07044 p->hangupcause = ast_channel_hangupcause(p->owner);
07045
07046 if (ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
07047 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
07048 if (sipdebug)
07049 ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
07050 update_call_counter(p, DEC_CALL_LIMIT);
07051 }
07052 ast_debug(4, "SIP Transfer: Not hanging up right now... Rescheduling hangup for %s.\n", p->callid);
07053 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
07054 ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
07055 if (p->owner) {
07056 ast_channel_tech_pvt_set(p->owner, dialog_unref(ast_channel_tech_pvt(p->owner), "unref p->owner->tech_pvt"));
07057 sip_pvt_lock(p);
07058 p->owner = NULL;
07059 sip_pvt_unlock(p);
07060 }
07061 ast_module_unref(ast_module_info->self);
07062 return 0;
07063 }
07064
07065 ast_debug(1, "Hangup call %s, SIP callid %s\n", ast_channel_name(ast), p->callid);
07066
07067 sip_pvt_lock(p);
07068 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
07069 if (sipdebug)
07070 ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
07071 update_call_counter(p, DEC_CALL_LIMIT);
07072 }
07073
07074
07075 if (p->owner != ast) {
07076 ast_log(LOG_WARNING, "Huh? We aren't the owner? Can't hangup call.\n");
07077 sip_pvt_unlock(p);
07078 return 0;
07079 }
07080
07081
07082 if (p->invitestate < INV_COMPLETED && ast_channel_state(p->owner) != AST_STATE_UP) {
07083 needcancel = TRUE;
07084 ast_debug(4, "Hanging up channel in state %s (not UP)\n", ast_state2str(ast_channel_state(ast)));
07085 }
07086
07087 stop_media_flows(p);
07088
07089 append_history(p, needcancel ? "Cancel" : "Hangup", "Cause %s", ast_cause2str(p->hangupcause));
07090
07091
07092 disable_dsp_detect(p);
07093
07094 p->owner = NULL;
07095 ast_channel_tech_pvt_set(ast, dialog_unref(ast_channel_tech_pvt(ast), "unref ast->tech_pvt"));
07096
07097 ast_module_unref(ast_module_info->self);
07098
07099
07100
07101
07102
07103
07104 if (p->alreadygone)
07105 needdestroy = 1;
07106 else if (p->invitestate != INV_CALLING)
07107 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
07108
07109
07110 if (!p->alreadygone && p->initreq.data && ast_str_strlen(p->initreq.data)) {
07111 if (needcancel) {
07112 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
07113
07114 if (p->invitestate == INV_CALLING) {
07115
07116 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
07117
07118 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
07119 append_history(p, "DELAY", "Not sending cancel, waiting for timeout");
07120 } else {
07121 struct sip_pkt *cur;
07122
07123 for (cur = p->packets; cur; cur = cur->next) {
07124 __sip_semi_ack(p, cur->seqno, cur->is_resp, cur->method ? cur->method : find_sip_method(ast_str_buffer(cur->data)));
07125 }
07126 p->invitestate = INV_CANCELLED;
07127
07128 transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
07129
07130
07131 needdestroy = 0;
07132 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
07133 }
07134 } else {
07135 const char *res;
07136 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"));
07137 if (p->hangupcause && (res = hangup_cause2sip(p->hangupcause)))
07138 transmit_response_reliable(p, res, &p->initreq);
07139 else
07140 transmit_response_reliable(p, "603 Declined", &p->initreq);
07141 p->invitestate = INV_TERMINATED;
07142 }
07143 } else {
07144 if (p->stimer->st_active == TRUE) {
07145 stop_session_timer(p);
07146 }
07147
07148 if (!p->pendinginvite) {
07149 struct ast_channel *bridge = ast_bridged_channel(oldowner);
07150 char quality_buf[AST_MAX_USER_FIELD], *quality;
07151
07152
07153
07154
07155 while (bridge && ast_channel_trylock(bridge)) {
07156 sip_pvt_unlock(p);
07157 do {
07158 CHANNEL_DEADLOCK_AVOIDANCE(oldowner);
07159 } while (sip_pvt_trylock(p));
07160 bridge = ast_bridged_channel(oldowner);
07161 }
07162
07163 if (p->rtp) {
07164 ast_rtp_instance_set_stats_vars(oldowner, p->rtp);
07165 }
07166
07167 if (bridge) {
07168 struct sip_pvt *q = ast_channel_tech_pvt(bridge);
07169
07170 if (IS_SIP_TECH(ast_channel_tech(bridge)) && q && q->rtp) {
07171 ast_rtp_instance_set_stats_vars(bridge, q->rtp);
07172 }
07173 ast_channel_unlock(bridge);
07174 }
07175
07176
07177
07178
07179
07180 if (p->rtp && (quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
07181 if (p->do_history) {
07182 append_history(p, "RTCPaudio", "Quality:%s", quality);
07183 }
07184 pbx_builtin_setvar_helper(oldowner, "RTPAUDIOQOS", quality);
07185 }
07186 if (p->vrtp && (quality = ast_rtp_instance_get_quality(p->vrtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
07187 if (p->do_history) {
07188 append_history(p, "RTCPvideo", "Quality:%s", quality);
07189 }
07190 pbx_builtin_setvar_helper(oldowner, "RTPVIDEOQOS", quality);
07191 }
07192 if (p->trtp && (quality = ast_rtp_instance_get_quality(p->trtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
07193 if (p->do_history) {
07194 append_history(p, "RTCPtext", "Quality:%s", quality);
07195 }
07196 pbx_builtin_setvar_helper(oldowner, "RTPTEXTQOS", quality);
07197 }
07198
07199
07200 if (ast_channel_state(oldowner) == AST_STATE_UP) {
07201 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
07202 }
07203
07204 } else {
07205
07206
07207 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
07208 ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);
07209 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"));
07210 if (sip_cancel_destroy(p)) {
07211 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
07212 }
07213
07214
07215
07216
07217 if (p->ongoing_reinvite && p->reinviteid < 0) {
07218 p->reinviteid = ast_sched_add(sched, 32 * p->timer_t1, reinvite_timeout, dialog_ref(p, "ref for reinvite_timeout"));
07219 }
07220 }
07221 }
07222 }
07223 if (needdestroy) {
07224 pvt_set_needdestroy(p, "hangup");
07225 }
07226 sip_pvt_unlock(p);
07227 return 0;
07228 }
07229
07230
07231 static void try_suggested_sip_codec(struct sip_pvt *p)
07232 {
07233 struct ast_format fmt;
07234 const char *codec;
07235
07236 ast_format_clear(&fmt);
07237
07238 if (p->outgoing_call) {
07239 codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC_OUTBOUND");
07240 } else if (!(codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC_INBOUND"))) {
07241 codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC");
07242 }
07243
07244 if (!codec)
07245 return;
07246
07247 ast_getformatbyname(codec, &fmt);
07248 if (fmt.id) {
07249 ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC} variable\n", codec);
07250 if (ast_format_cap_iscompatible(p->jointcaps, &fmt)) {
07251 ast_format_cap_set(p->jointcaps, &fmt);
07252 ast_format_cap_set(p->caps, &fmt);
07253 } else
07254 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
07255 } else
07256 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n", codec);
07257 return;
07258 }
07259
07260
07261
07262 static int sip_answer(struct ast_channel *ast)
07263 {
07264 int res = 0;
07265 struct sip_pvt *p = ast_channel_tech_pvt(ast);
07266 int oldsdp = FALSE;
07267
07268 if (!p) {
07269 ast_debug(1, "Asked to answer channel %s without tech pvt; ignoring\n",
07270 ast_channel_name(ast));
07271 return res;
07272 }
07273 sip_pvt_lock(p);
07274 if (ast_channel_state(ast) != AST_STATE_UP) {
07275 try_suggested_sip_codec(p);
07276
07277 if (ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT)) {
07278 oldsdp = TRUE;
07279 }
07280
07281 ast_setstate(ast, AST_STATE_UP);
07282 ast_debug(1, "SIP answering channel: %s\n", ast_channel_name(ast));
07283 ast_rtp_instance_update_source(p->rtp);
07284 res = transmit_response_with_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL, oldsdp, TRUE);
07285 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
07286 }
07287 sip_pvt_unlock(p);
07288 return res;
07289 }
07290
07291
07292 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
07293 {
07294 struct sip_pvt *p = ast_channel_tech_pvt(ast);
07295 int res = 0;
07296
07297 switch (frame->frametype) {
07298 case AST_FRAME_VOICE:
07299 if (!(ast_format_cap_iscompatible(ast_channel_nativeformats(ast), &frame->subclass.format))) {
07300 char s1[512];
07301 ast_log(LOG_WARNING, "Asked to transmit frame type %s, while native formats is %s read/write = %s/%s\n",
07302 ast_getformatname(&frame->subclass.format),
07303 ast_getformatname_multiple(s1, sizeof(s1), ast_channel_nativeformats(ast)),
07304 ast_getformatname(ast_channel_readformat(ast)),
07305 ast_getformatname(ast_channel_writeformat(ast)));
07306 return 0;
07307 }
07308 if (p) {
07309 sip_pvt_lock(p);
07310 if (p->t38.state == T38_ENABLED) {
07311
07312 sip_pvt_unlock(p);
07313 break;
07314 } else if (p->rtp) {
07315
07316 if ((ast_channel_state(ast) != AST_STATE_UP) &&
07317 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
07318 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
07319 ast_rtp_instance_update_source(p->rtp);
07320 if (!global_prematuremediafilter) {
07321 p->invitestate = INV_EARLY_MEDIA;
07322 transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
07323 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
07324 }
07325 }
07326 p->lastrtptx = time(NULL);
07327 res = ast_rtp_instance_write(p->rtp, frame);
07328 }
07329 sip_pvt_unlock(p);
07330 }
07331 break;
07332 case AST_FRAME_VIDEO:
07333 if (p) {
07334 sip_pvt_lock(p);
07335 if (p->vrtp) {
07336
07337 if ((ast_channel_state(ast) != AST_STATE_UP) &&
07338 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
07339 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
07340 p->invitestate = INV_EARLY_MEDIA;
07341 transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
07342 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
07343 }
07344 p->lastrtptx = time(NULL);
07345 res = ast_rtp_instance_write(p->vrtp, frame);
07346 }
07347 sip_pvt_unlock(p);
07348 }
07349 break;
07350 case AST_FRAME_TEXT:
07351 if (p) {
07352 sip_pvt_lock(p);
07353 if (p->red) {
07354 ast_rtp_red_buffer(p->trtp, frame);
07355 } else {
07356 if (p->trtp) {
07357
07358 if ((ast_channel_state(ast) != AST_STATE_UP) &&
07359 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
07360 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
07361 p->invitestate = INV_EARLY_MEDIA;
07362 transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
07363 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
07364 }
07365 p->lastrtptx = time(NULL);
07366 res = ast_rtp_instance_write(p->trtp, frame);
07367 }
07368 }
07369 sip_pvt_unlock(p);
07370 }
07371 break;
07372 case AST_FRAME_IMAGE:
07373 return 0;
07374 break;
07375 case AST_FRAME_MODEM:
07376 if (p) {
07377 sip_pvt_lock(p);
07378
07379
07380
07381
07382 if ((ast_channel_state(ast) == AST_STATE_UP) &&
07383 p->udptl &&
07384 (p->t38.state == T38_ENABLED)) {
07385 res = ast_udptl_write(p->udptl, frame);
07386 }
07387 sip_pvt_unlock(p);
07388 }
07389 break;
07390 default:
07391 ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
07392 return 0;
07393 }
07394
07395 return res;
07396 }
07397
07398
07399
07400 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
07401 {
07402 int ret = -1;
07403 struct sip_pvt *p;
07404
07405 if (newchan && ast_test_flag(ast_channel_flags(newchan), AST_FLAG_ZOMBIE))
07406 ast_debug(1, "New channel is zombie\n");
07407 if (oldchan && ast_test_flag(ast_channel_flags(oldchan), AST_FLAG_ZOMBIE))
07408 ast_debug(1, "Old channel is zombie\n");
07409
07410 if (!newchan || !ast_channel_tech_pvt(newchan)) {
07411 if (!newchan)
07412 ast_log(LOG_WARNING, "No new channel! Fixup of %s failed.\n", ast_channel_name(oldchan));
07413 else
07414 ast_log(LOG_WARNING, "No SIP tech_pvt! Fixup of %s failed.\n", ast_channel_name(oldchan));
07415 return -1;
07416 }
07417 p = ast_channel_tech_pvt(newchan);
07418
07419 sip_pvt_lock(p);
07420 append_history(p, "Masq", "Old channel: %s\n", ast_channel_name(oldchan));
07421 append_history(p, "Masq (cont)", "...new owner: %s\n", ast_channel_name(newchan));
07422 if (p->owner != oldchan)
07423 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
07424 else {
07425 p->owner = newchan;
07426
07427
07428
07429
07430
07431
07432 sip_set_rtp_peer(newchan, NULL, NULL, 0, 0, 0);
07433 ret = 0;
07434 }
07435 ast_debug(3, "SIP Fixup: New owner for dialogue %s: %s (Old parent: %s)\n", p->callid, ast_channel_name(p->owner), ast_channel_name(oldchan));
07436
07437 sip_pvt_unlock(p);
07438 return ret;
07439 }
07440
07441 static int sip_senddigit_begin(struct ast_channel *ast, char digit)
07442 {
07443 struct sip_pvt *p = ast_channel_tech_pvt(ast);
07444 int res = 0;
07445
07446 if (!p) {
07447 ast_debug(1, "Asked to begin DTMF digit on channel %s with no pvt; ignoring\n",
07448 ast_channel_name(ast));
07449 return res;
07450 }
07451
07452 sip_pvt_lock(p);
07453 switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
07454 case SIP_DTMF_INBAND:
07455 res = -1;
07456 break;
07457 case SIP_DTMF_RFC2833:
07458 if (p->rtp)
07459 ast_rtp_instance_dtmf_begin(p->rtp, digit);
07460 break;
07461 default:
07462 break;
07463 }
07464 sip_pvt_unlock(p);
07465
07466 return res;
07467 }
07468
07469
07470
07471 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration)
07472 {
07473 struct sip_pvt *p = ast_channel_tech_pvt(ast);
07474 int res = 0;
07475
07476 if (!p) {
07477 ast_debug(1, "Asked to end DTMF digit on channel %s with no pvt; ignoring\n",
07478 ast_channel_name(ast));
07479 return res;
07480 }
07481
07482 sip_pvt_lock(p);
07483 switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
07484 case SIP_DTMF_INFO:
07485 case SIP_DTMF_SHORTINFO:
07486 transmit_info_with_digit(p, digit, duration);
07487 break;
07488 case SIP_DTMF_RFC2833:
07489 if (p->rtp)
07490 ast_rtp_instance_dtmf_end_with_duration(p->rtp, digit, duration);
07491 break;
07492 case SIP_DTMF_INBAND:
07493 res = -1;
07494 break;
07495 }
07496 sip_pvt_unlock(p);
07497
07498 return res;
07499 }
07500
07501
07502 static int sip_transfer(struct ast_channel *ast, const char *dest)
07503 {
07504 struct sip_pvt *p = ast_channel_tech_pvt(ast);
07505 int res;
07506
07507 if (!p) {
07508 ast_debug(1, "Asked to transfer channel %s with no pvt; ignoring\n",
07509 ast_channel_name(ast));
07510 return -1;
07511 }
07512
07513 if (dest == NULL)
07514 dest = "";
07515 sip_pvt_lock(p);
07516 if (ast_channel_state(ast) == AST_STATE_RING)
07517 res = sip_sipredirect(p, dest);
07518 else
07519 res = transmit_refer(p, dest);
07520 sip_pvt_unlock(p);
07521 return res;
07522 }
07523
07524
07525 static int interpret_t38_parameters(struct sip_pvt *p, const struct ast_control_t38_parameters *parameters)
07526 {
07527 int res = 0;
07528
07529 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) || !p->udptl) {
07530 return -1;
07531 }
07532 switch (parameters->request_response) {
07533 case AST_T38_NEGOTIATED:
07534 case AST_T38_REQUEST_NEGOTIATE:
07535
07536 if (!parameters->max_ifp) {
07537 if (p->t38.state == T38_PEER_REINVITE) {
07538 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"));
07539 transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
07540 }
07541 change_t38_state(p, T38_REJECTED);
07542 break;
07543 } else if (p->t38.state == T38_PEER_REINVITE) {
07544 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"));
07545 p->t38.our_parms = *parameters;
07546
07547
07548
07549 if (!p->t38.their_parms.fill_bit_removal) {
07550 p->t38.our_parms.fill_bit_removal = FALSE;
07551 }
07552 if (!p->t38.their_parms.transcoding_mmr) {
07553 p->t38.our_parms.transcoding_mmr = FALSE;
07554 }
07555 if (!p->t38.their_parms.transcoding_jbig) {
07556 p->t38.our_parms.transcoding_jbig = FALSE;
07557 }
07558 p->t38.our_parms.version = MIN(p->t38.our_parms.version, p->t38.their_parms.version);
07559 p->t38.our_parms.rate_management = p->t38.their_parms.rate_management;
07560 ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
07561 change_t38_state(p, T38_ENABLED);
07562 transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
07563 } else if (p->t38.state != T38_ENABLED) {
07564 p->t38.our_parms = *parameters;
07565 ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
07566 change_t38_state(p, T38_LOCAL_REINVITE);
07567 if (!p->pendinginvite) {
07568 transmit_reinvite_with_sdp(p, TRUE, FALSE);
07569 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
07570 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
07571 }
07572 }
07573 break;
07574 case AST_T38_TERMINATED:
07575 case AST_T38_REFUSED:
07576 case AST_T38_REQUEST_TERMINATE:
07577 if (p->t38.state == T38_PEER_REINVITE) {
07578 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"));
07579 change_t38_state(p, T38_REJECTED);
07580 transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
07581 } else if (p->t38.state == T38_ENABLED)
07582 transmit_reinvite_with_sdp(p, FALSE, FALSE);
07583 break;
07584 case AST_T38_REQUEST_PARMS: {
07585 struct ast_control_t38_parameters parameters = p->t38.their_parms;
07586
07587 if (p->t38.state == T38_PEER_REINVITE) {
07588 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"));
07589 parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
07590 parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
07591 if (p->owner) {
07592 ast_queue_control_data(p->owner, AST_CONTROL_T38_PARAMETERS, ¶meters, sizeof(parameters));
07593 }
07594
07595
07596
07597
07598 res = AST_T38_REQUEST_PARMS;
07599 }
07600 break;
07601 }
07602 default:
07603 res = -1;
07604 break;
07605 }
07606
07607 return res;
07608 }
07609
07610
07611
07612
07613
07614
07615
07616
07617
07618
07619 static int initialize_udptl(struct sip_pvt *p)
07620 {
07621 int natflags = ast_test_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP);
07622
07623 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
07624 return 1;
07625 }
07626
07627
07628 if (p->udptl) {
07629 return 0;
07630 }
07631
07632
07633 if ((p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, &bindaddr))) {
07634 if (p->owner) {
07635 ast_channel_set_fd(p->owner, 5, ast_udptl_fd(p->udptl));
07636 }
07637
07638 ast_udptl_setqos(p->udptl, global_tos_audio, global_cos_audio);
07639 p->t38_maxdatagram = p->relatedpeer ? p->relatedpeer->t38_maxdatagram : global_t38_maxdatagram;
07640 set_t38_capabilities(p);
07641
07642 ast_debug(1, "Setting NAT on UDPTL to %s\n", natflags ? "On" : "Off");
07643 ast_udptl_setnat(p->udptl, natflags);
07644 } else {
07645 ast_log(AST_LOG_WARNING, "UDPTL creation failed - disabling T38 for this dialog\n");
07646 ast_clear_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT);
07647 return 1;
07648 }
07649
07650 return 0;
07651 }
07652
07653
07654 static int sipinfo_send(
07655 struct ast_channel *chan,
07656 struct ast_variable *headers,
07657 const char *content_type,
07658 const char *content,
07659 const char *useragent_filter)
07660 {
07661 struct sip_pvt *p;
07662 struct ast_variable *var;
07663 struct sip_request req;
07664 int res = -1;
07665
07666 ast_channel_lock(chan);
07667
07668 if (ast_channel_tech(chan) != &sip_tech) {
07669 ast_log(LOG_WARNING, "Attempted to send a custom INFO on a non-SIP channel %s\n", ast_channel_name(chan));
07670 ast_channel_unlock(chan);
07671 return res;
07672 }
07673
07674 p = ast_channel_tech_pvt(chan);
07675 sip_pvt_lock(p);
07676
07677 if (!(ast_strlen_zero(useragent_filter))) {
07678 int match = (strstr(p->useragent, useragent_filter)) ? 1 : 0;
07679 if (!match) {
07680 goto cleanup;
07681 }
07682 }
07683
07684 reqprep(&req, p, SIP_INFO, 0, 1);
07685 for (var = headers; var; var = var->next) {
07686 add_header(&req, var->name, var->value);
07687 }
07688 if (!ast_strlen_zero(content) && !ast_strlen_zero(content_type)) {
07689 add_header(&req, "Content-Type", content_type);
07690 add_content(&req, content);
07691 }
07692
07693 res = send_request(p, &req, XMIT_RELIABLE, p->ocseq);
07694
07695 cleanup:
07696 sip_pvt_unlock(p);
07697 ast_channel_unlock(chan);
07698 return res;
07699 }
07700
07701
07702
07703
07704
07705 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
07706 {
07707 struct sip_pvt *p = ast_channel_tech_pvt(ast);
07708 int res = 0;
07709
07710 if (!p) {
07711 ast_debug(1, "Asked to indicate condition on channel %s with no pvt; ignoring\n",
07712 ast_channel_name(ast));
07713 return res;
07714 }
07715
07716 sip_pvt_lock(p);
07717 switch(condition) {
07718 case AST_CONTROL_RINGING:
07719 if (ast_channel_state(ast) == AST_STATE_RING) {
07720 p->invitestate = INV_EARLY_MEDIA;
07721 if (!ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) ||
07722 (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) {
07723
07724 transmit_provisional_response(p, "180 Ringing", &p->initreq, 0);
07725 ast_set_flag(&p->flags[0], SIP_RINGING);
07726 if (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) != SIP_PROG_INBAND_YES)
07727 break;
07728 } else {
07729
07730 }
07731 }
07732 res = -1;
07733 break;
07734 case AST_CONTROL_BUSY:
07735 if (ast_channel_state(ast) != AST_STATE_UP) {
07736 transmit_response_reliable(p, "486 Busy Here", &p->initreq);
07737 p->invitestate = INV_COMPLETED;
07738 sip_alreadygone(p);
07739 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
07740 break;
07741 }
07742 res = -1;
07743 break;
07744 case AST_CONTROL_CONGESTION:
07745 if (ast_channel_state(ast) != AST_STATE_UP) {
07746 transmit_response_reliable(p, "503 Service Unavailable", &p->initreq);
07747 p->invitestate = INV_COMPLETED;
07748 sip_alreadygone(p);
07749 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
07750 break;
07751 }
07752 res = -1;
07753 break;
07754 case AST_CONTROL_INCOMPLETE:
07755 if (ast_channel_state(ast) != AST_STATE_UP) {
07756 switch (ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP)) {
07757 case SIP_PAGE2_ALLOWOVERLAP_YES:
07758 transmit_response_reliable(p, "484 Address Incomplete", &p->initreq);
07759 p->invitestate = INV_COMPLETED;
07760 sip_alreadygone(p);
07761 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
07762 break;
07763 case SIP_PAGE2_ALLOWOVERLAP_DTMF:
07764
07765 break;
07766 default:
07767
07768 transmit_response_reliable(p, "404 Not Found", &p->initreq);
07769 p->invitestate = INV_COMPLETED;
07770 sip_alreadygone(p);
07771 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
07772 break;
07773 }
07774 }
07775 break;
07776 case AST_CONTROL_PROCEEDING:
07777 if ((ast_channel_state(ast) != AST_STATE_UP) &&
07778 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
07779 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
07780 transmit_response(p, "100 Trying", &p->initreq);
07781 p->invitestate = INV_PROCEEDING;
07782 break;
07783 }
07784 res = -1;
07785 break;
07786 case AST_CONTROL_PROGRESS:
07787 if ((ast_channel_state(ast) != AST_STATE_UP) &&
07788 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
07789 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
07790 p->invitestate = INV_EARLY_MEDIA;
07791 transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
07792 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
07793 break;
07794 }
07795 res = -1;
07796 break;
07797 case AST_CONTROL_HOLD:
07798 ast_rtp_instance_update_source(p->rtp);
07799 ast_moh_start(ast, data, p->mohinterpret);
07800 break;
07801 case AST_CONTROL_UNHOLD:
07802 ast_rtp_instance_update_source(p->rtp);
07803 ast_moh_stop(ast);
07804 break;
07805 case AST_CONTROL_VIDUPDATE:
07806 if (p->vrtp && !p->novideo) {
07807 transmit_info_with_vidupdate(p);
07808
07809 } else
07810 res = -1;
07811 break;
07812 case AST_CONTROL_T38_PARAMETERS:
07813 res = -1;
07814 if (datalen != sizeof(struct ast_control_t38_parameters)) {
07815 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);
07816 } else {
07817 const struct ast_control_t38_parameters *parameters = data;
07818 if (!initialize_udptl(p)) {
07819 res = interpret_t38_parameters(p, parameters);
07820 }
07821 }
07822 break;
07823 case AST_CONTROL_SRCUPDATE:
07824 ast_rtp_instance_update_source(p->rtp);
07825 break;
07826 case AST_CONTROL_SRCCHANGE:
07827 ast_rtp_instance_change_source(p->rtp);
07828 break;
07829 case AST_CONTROL_CONNECTED_LINE:
07830 update_connectedline(p, data, datalen);
07831 break;
07832 case AST_CONTROL_REDIRECTING:
07833 update_redirecting(p, data, datalen);
07834 break;
07835 case AST_CONTROL_AOC:
07836 {
07837 struct ast_aoc_decoded *decoded = ast_aoc_decode((struct ast_aoc_encoded *) data, datalen, ast);
07838 if (!decoded) {
07839 ast_log(LOG_ERROR, "Error decoding indicated AOC data\n");
07840 res = -1;
07841 break;
07842 }
07843 switch (ast_aoc_get_msg_type(decoded)) {
07844 case AST_AOC_REQUEST:
07845 if (ast_aoc_get_termination_request(decoded)) {
07846
07847
07848
07849
07850
07851
07852
07853 ast_debug(1, "AOC-E termination request received on %s. This is not yet supported on sip. Continue with hangup \n", ast_channel_name(p->owner));
07854 ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
07855 }
07856 break;
07857 case AST_AOC_D:
07858 case AST_AOC_E:
07859 if (ast_test_flag(&p->flags[2], SIP_PAGE3_SNOM_AOC)) {
07860 transmit_info_with_aoc(p, decoded);
07861 }
07862 break;
07863 case AST_AOC_S:
07864 default:
07865 break;
07866 }
07867 ast_aoc_destroy_decoded(decoded);
07868 }
07869 break;
07870 case AST_CONTROL_UPDATE_RTP_PEER:
07871 break;
07872 case AST_CONTROL_FLASH:
07873 res = -1;
07874 break;
07875 case AST_CONTROL_PVT_CAUSE_CODE:
07876 case -1:
07877 res = -1;
07878 break;
07879 default:
07880 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
07881 res = -1;
07882 break;
07883 }
07884 sip_pvt_unlock(p);
07885 return res;
07886 }
07887
07888
07889
07890
07891
07892
07893
07894
07895
07896
07897
07898
07899 static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title, const char *linkedid, struct ast_callid *callid)
07900 {
07901 struct ast_channel *tmp;
07902 struct ast_variable *v = NULL;
07903 struct ast_format fmt;
07904 struct ast_format_cap *what = NULL;
07905 int needvideo = 0;
07906 int needtext = 0;
07907 char buf[SIPBUFSIZE];
07908 char *exten;
07909
07910 {
07911 const char *my_name;
07912
07913 if (title) {
07914 my_name = title;
07915 } else {
07916 my_name = ast_strdupa(i->fromdomain);
07917 }
07918
07919 sip_pvt_unlock(i);
07920
07921 tmp = ast_channel_alloc(1, state, i->cid_num, i->cid_name, i->accountcode, i->exten, i->context, linkedid, i->amaflags, "SIP/%s-%08x", my_name, ast_atomic_fetchadd_int((int *)&chan_idx, +1));
07922 }
07923 if (!tmp) {
07924 ast_log(LOG_WARNING, "Unable to allocate AST channel structure for SIP channel\n");
07925 sip_pvt_lock(i);
07926 return NULL;
07927 }
07928
07929
07930 if (callid) {
07931 ast_channel_callid_set(tmp, callid);
07932 }
07933
07934 ast_channel_lock(tmp);
07935 sip_pvt_lock(i);
07936 ast_channel_cc_params_init(tmp, i->cc_params);
07937 ast_channel_caller(tmp)->id.tag = ast_strdup(i->cid_tag);
07938
07939 ast_channel_tech_set(tmp, (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);
07940
07941
07942
07943 if (!(ast_format_cap_is_empty(i->jointcaps))) {
07944 what = i->jointcaps;
07945 } else if (!(ast_format_cap_is_empty(i->caps))) {
07946 what = i->caps;
07947 } else {
07948 what = sip_cfg.caps;
07949 }
07950
07951
07952 ast_format_cap_copy(ast_channel_nativeformats(tmp), what);
07953
07954 ast_codec_choose(&i->prefs, ast_channel_nativeformats(tmp), 1, &fmt);
07955 ast_format_cap_remove_bytype(ast_channel_nativeformats(tmp), AST_FORMAT_TYPE_AUDIO);
07956 ast_format_cap_add(ast_channel_nativeformats(tmp), &fmt);
07957
07958 ast_debug(3, "*** Our native formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, ast_channel_nativeformats(tmp)));
07959 ast_debug(3, "*** Joint capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->jointcaps));
07960 ast_debug(3, "*** Our capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->caps));
07961 ast_debug(3, "*** AST_CODEC_CHOOSE formats are %s \n", ast_getformatname(&fmt));
07962 if (!ast_format_cap_is_empty(i->prefcaps)) {
07963 ast_debug(3, "*** Our preferred formats from the incoming channel are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->prefcaps));
07964 }
07965
07966
07967
07968
07969
07970 if (i->vrtp) {
07971 if (ast_test_flag(&i->flags[1], SIP_PAGE2_VIDEOSUPPORT))
07972 needvideo = 1;
07973 else if (!ast_format_cap_is_empty(i->prefcaps))
07974 needvideo = ast_format_cap_has_type(i->prefcaps, AST_FORMAT_TYPE_VIDEO);
07975 else
07976 needvideo = ast_format_cap_has_type(i->jointcaps, AST_FORMAT_TYPE_VIDEO);
07977 }
07978
07979 if (i->trtp) {
07980 if (!ast_format_cap_is_empty(i->prefcaps))
07981 needtext = ast_format_cap_has_type(i->prefcaps, AST_FORMAT_TYPE_TEXT);
07982 else
07983 needtext = ast_format_cap_has_type(i->jointcaps, AST_FORMAT_TYPE_TEXT);
07984 }
07985
07986 if (needvideo) {
07987 ast_debug(3, "This channel can handle video! HOLLYWOOD next!\n");
07988 } else {
07989 ast_debug(3, "This channel will not be able to handle video.\n");
07990 }
07991
07992 enable_dsp_detect(i);
07993
07994 if ((ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
07995 (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
07996 if (i->rtp) {
07997 ast_rtp_instance_dtmf_mode_set(i->rtp, AST_RTP_DTMF_MODE_INBAND);
07998 }
07999 } else if (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) {
08000 if (i->rtp) {
08001 ast_rtp_instance_dtmf_mode_set(i->rtp, AST_RTP_DTMF_MODE_RFC2833);
08002 }
08003 }
08004
08005
08006
08007
08008 if (i->rtp) {
08009 ast_channel_set_fd(tmp, 0, ast_rtp_instance_fd(i->rtp, 0));
08010 ast_channel_set_fd(tmp, 1, ast_rtp_instance_fd(i->rtp, 1));
08011 ast_rtp_instance_set_write_format(i->rtp, &fmt);
08012 ast_rtp_instance_set_read_format(i->rtp, &fmt);
08013 }
08014 if (needvideo && i->vrtp) {
08015 ast_channel_set_fd(tmp, 2, ast_rtp_instance_fd(i->vrtp, 0));
08016 ast_channel_set_fd(tmp, 3, ast_rtp_instance_fd(i->vrtp, 1));
08017 }
08018 if (needtext && i->trtp) {
08019 ast_channel_set_fd(tmp, 4, ast_rtp_instance_fd(i->trtp, 0));
08020 }
08021 if (i->udptl) {
08022 ast_channel_set_fd(tmp, 5, ast_udptl_fd(i->udptl));
08023 }
08024
08025 if (state == AST_STATE_RING) {
08026 ast_channel_rings_set(tmp, 1);
08027 }
08028 ast_channel_adsicpe_set(tmp, AST_ADSI_UNAVAILABLE);
08029
08030 ast_format_copy(ast_channel_writeformat(tmp), &fmt);
08031 ast_format_copy(ast_channel_rawwriteformat(tmp), &fmt);
08032
08033 ast_format_copy(ast_channel_readformat(tmp), &fmt);
08034 ast_format_copy(ast_channel_rawreadformat(tmp), &fmt);
08035
08036 ast_channel_tech_pvt_set(tmp, dialog_ref(i, "sip_new: set chan->tech_pvt to i"));
08037
08038 ast_channel_callgroup_set(tmp, i->callgroup);
08039 ast_channel_pickupgroup_set(tmp, i->pickupgroup);
08040
08041 ast_channel_named_callgroups_set(tmp, i->named_callgroups);
08042 ast_channel_named_pickupgroups_set(tmp, i->named_pickupgroups);
08043
08044 ast_channel_caller(tmp)->id.name.presentation = i->callingpres;
08045 ast_channel_caller(tmp)->id.number.presentation = i->callingpres;
08046 if (!ast_strlen_zero(i->parkinglot)) {
08047 ast_channel_parkinglot_set(tmp, i->parkinglot);
08048 }
08049 if (!ast_strlen_zero(i->accountcode)) {
08050 ast_channel_accountcode_set(tmp, i->accountcode);
08051 }
08052 if (i->amaflags) {
08053 ast_channel_amaflags_set(tmp, i->amaflags);
08054 }
08055 if (!ast_strlen_zero(i->language)) {
08056 ast_channel_language_set(tmp, i->language);
08057 }
08058 if (!ast_strlen_zero(i->zone)) {
08059 struct ast_tone_zone *zone;
08060 if (!(zone = ast_get_indication_zone(i->zone))) {
08061 ast_log(LOG_ERROR, "Unknown country code '%s' for tonezone. Check indications.conf for available country codes.\n", i->zone);
08062 }
08063 ast_channel_zone_set(tmp, zone);
08064 }
08065 i->owner = tmp;
08066 ast_module_ref(ast_module_info->self);
08067 ast_channel_context_set(tmp, i->context);
08068
08069
08070
08071
08072 exten = ast_strdupa(i->exten);
08073 sip_pvt_unlock(i);
08074 ast_channel_unlock(tmp);
08075 if (!ast_exists_extension(NULL, i->context, i->exten, 1, i->cid_num)) {
08076 ast_uri_decode(exten, ast_uri_sip_user);
08077 }
08078 ast_channel_lock(tmp);
08079 sip_pvt_lock(i);
08080 ast_channel_exten_set(tmp, exten);
08081
08082
08083
08084 if (!ast_strlen_zero(i->cid_num)) {
08085 ast_channel_caller(tmp)->ani.number.valid = 1;
08086 ast_channel_caller(tmp)->ani.number.str = ast_strdup(i->cid_num);
08087 }
08088 if (!ast_strlen_zero(i->rdnis)) {
08089 ast_channel_redirecting(tmp)->from.number.valid = 1;
08090 ast_channel_redirecting(tmp)->from.number.str = ast_strdup(i->rdnis);
08091 }
08092
08093 if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s")) {
08094 ast_channel_dialed(tmp)->number.str = ast_strdup(i->exten);
08095 }
08096
08097 ast_channel_priority_set(tmp, 1);
08098 if (!ast_strlen_zero(i->uri)) {
08099 pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
08100 }
08101 if (!ast_strlen_zero(i->domain)) {
08102 pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
08103 }
08104 if (!ast_strlen_zero(i->callid)) {
08105 pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
08106 }
08107 if (i->rtp) {
08108 ast_jb_configure(tmp, &global_jbconf);
08109 }
08110
08111 if (!i->relatedpeer) {
08112 ast_set_flag(ast_channel_flags(tmp), AST_FLAG_DISABLE_DEVSTATE_CACHE);
08113 }
08114
08115 for (v = i->chanvars ; v ; v = v->next) {
08116 char valuebuf[1024];
08117 pbx_builtin_setvar_helper(tmp, v->name, ast_get_encoded_str(v->value, valuebuf, sizeof(valuebuf)));
08118 }
08119
08120 if (i->do_history) {
08121 append_history(i, "NewChan", "Channel %s - from %s", ast_channel_name(tmp), i->callid);
08122 }
08123
08124
08125 if (sip_cfg.callevents) {
08126 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
08127 "Channel: %s\r\nUniqueid: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\n",
08128 ast_channel_name(tmp), ast_channel_uniqueid(tmp), "SIP", i->callid, i->fullcontact);
08129 }
08130
08131 return tmp;
08132 }
08133
08134
08135
08136
08137
08138 static const char *get_sdp_iterate(int *start, struct sip_request *req, const char *name)
08139 {
08140 int len = strlen(name);
08141 const char *line;
08142
08143 while (*start < (req->sdp_start + req->sdp_count)) {
08144 line = REQ_OFFSET_TO_STR(req, line[(*start)++]);
08145 if (!strncasecmp(line, name, len) && line[len] == '=') {
08146 return ast_skip_blanks(line + len + 1);
08147 }
08148 }
08149
08150
08151 (*start)++;
08152
08153 return "";
08154 }
08155
08156
08157
08158
08159
08160
08161 static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value)
08162 {
08163 char type = '\0';
08164 const char *line = NULL;
08165
08166 if (stop > (req->sdp_start + req->sdp_count)) {
08167 stop = req->sdp_start + req->sdp_count;
08168 }
08169
08170 while (*start < stop) {
08171 line = REQ_OFFSET_TO_STR(req, line[(*start)++]);
08172 if (line[1] == '=') {
08173 type = line[0];
08174 *value = ast_skip_blanks(line + 2);
08175 break;
08176 }
08177 }
08178
08179 return type;
08180 }
08181
08182
08183 static char *get_content_line(struct sip_request *req, char *name, char delimiter)
08184 {
08185 int i;
08186 int len = strlen(name);
08187 const char *line;
08188
08189 for (i = 0; i < req->lines; i++) {
08190 line = REQ_OFFSET_TO_STR(req, line[i]);
08191 if (!strncasecmp(line, name, len) && line[len] == delimiter) {
08192 return ast_skip_blanks(line + len + 1);
08193 }
08194 }
08195
08196 return "";
08197 }
08198
08199
08200 struct cfalias {
08201 const char *fullname;
08202 const char *shortname;
08203 };
08204 static const struct cfalias aliases[] = {
08205 { "Content-Type", "c" },
08206 { "Content-Encoding", "e" },
08207 { "From", "f" },
08208 { "Call-ID", "i" },
08209 { "Contact", "m" },
08210 { "Content-Length", "l" },
08211 { "Subject", "s" },
08212 { "To", "t" },
08213 { "Supported", "k" },
08214 { "Refer-To", "r" },
08215 { "Referred-By", "b" },
08216 { "Allow-Events", "u" },
08217 { "Event", "o" },
08218 { "Via", "v" },
08219 { "Accept-Contact", "a" },
08220 { "Reject-Contact", "j" },
08221 { "Request-Disposition", "d" },
08222 { "Session-Expires", "x" },
08223 { "Identity", "y" },
08224 { "Identity-Info", "n" },
08225 };
08226
08227
08228 static const char *find_alias(const char *name, const char *_default)
08229 {
08230 int x;
08231
08232 for (x = 0; x < ARRAY_LEN(aliases); x++) {
08233 if (!strcasecmp(aliases[x].fullname, name))
08234 return aliases[x].shortname;
08235 }
08236
08237 return _default;
08238 }
08239
08240
08241 static const char *find_full_alias(const char *name, const char *_default)
08242 {
08243 int x;
08244
08245 if (strlen(name) == 1) {
08246
08247 for (x = 0; x < ARRAY_LEN(aliases); ++x) {
08248 if (!strcasecmp(aliases[x].shortname, name))
08249 return aliases[x].fullname;
08250 }
08251 }
08252
08253 return _default;
08254 }
08255
08256 static const char *__get_header(const struct sip_request *req, const char *name, int *start)
08257 {
08258
08259
08260
08261
08262
08263
08264
08265
08266
08267 const char *sname = find_alias(name, NULL);
08268 int x, len = strlen(name), slen = (sname ? 1 : 0);
08269 for (x = *start; x < req->headers; x++) {
08270 const char *header = REQ_OFFSET_TO_STR(req, header[x]);
08271 int smatch = 0, match = !strncasecmp(header, name, len);
08272 if (slen) {
08273 smatch = !strncasecmp(header, sname, slen);
08274 }
08275 if (match || smatch) {
08276
08277 const char *r = header + (match ? len : slen );
08278 if (sip_cfg.pedanticsipchecking) {
08279 r = ast_skip_blanks(r);
08280 }
08281
08282 if (*r == ':') {
08283 *start = x+1;
08284 return ast_skip_blanks(r+1);
08285 }
08286 }
08287 }
08288
08289
08290 return "";
08291 }
08292
08293
08294
08295
08296 const char *sip_get_header(const struct sip_request *req, const char *name)
08297 {
08298 int start = 0;
08299 return __get_header(req, name, &start);
08300 }
08301
08302
08303 AST_THREADSTORAGE(sip_content_buf);
08304
08305
08306 static char *get_content(struct sip_request *req)
08307 {
08308 struct ast_str *str;
08309 int i;
08310
08311 if (!(str = ast_str_thread_get(&sip_content_buf, 128))) {
08312 return NULL;
08313 }
08314
08315 ast_str_reset(str);
08316
08317 for (i = 0; i < req->lines; i++) {
08318 if (ast_str_append(&str, 0, "%s\n", REQ_OFFSET_TO_STR(req, line[i])) < 0) {
08319 return NULL;
08320 }
08321 }
08322
08323 return ast_str_buffer(str);
08324 }
08325
08326
08327 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect)
08328 {
08329
08330 struct ast_frame *f;
08331
08332 if (!p->rtp) {
08333
08334 return &ast_null_frame;
08335 }
08336
08337 switch(ast_channel_fdno(ast)) {
08338 case 0:
08339 f = ast_rtp_instance_read(p->rtp, 0);
08340 break;
08341 case 1:
08342 f = ast_rtp_instance_read(p->rtp, 1);
08343 break;
08344 case 2:
08345 f = ast_rtp_instance_read(p->vrtp, 0);
08346 break;
08347 case 3:
08348 f = ast_rtp_instance_read(p->vrtp, 1);
08349 break;
08350 case 4:
08351 f = ast_rtp_instance_read(p->trtp, 0);
08352 if (sipdebug_text) {
08353 struct ast_str *out = ast_str_create(f->datalen * 4 + 6);
08354 int i;
08355 unsigned char* arr = f->data.ptr;
08356 do {
08357 if (!out) {
08358 break;
08359 }
08360 for (i = 0; i < f->datalen; i++) {
08361 ast_str_append(&out, 0, "%c", (arr[i] > ' ' && arr[i] < '}') ? arr[i] : '.');
08362 }
08363 ast_str_append(&out, 0, " -> ");
08364 for (i = 0; i < f->datalen; i++) {
08365 ast_str_append(&out, 0, "%02X ", arr[i]);
08366 }
08367 ast_verb(0, "%s\n", ast_str_buffer(out));
08368 ast_free(out);
08369 } while (0);
08370 }
08371 break;
08372 case 5:
08373 f = ast_udptl_read(p->udptl);
08374 break;
08375 default:
08376 f = &ast_null_frame;
08377 }
08378
08379 if (f && (f->frametype == AST_FRAME_DTMF_BEGIN || f->frametype == AST_FRAME_DTMF_END) &&
08380 (ast_test_flag(&p->flags[0], SIP_DTMF) != SIP_DTMF_RFC2833)) {
08381 ast_debug(1, "Ignoring DTMF (%c) RTP frame because dtmfmode is not RFC2833\n", f->subclass.integer);
08382 ast_frfree(f);
08383 return &ast_null_frame;
08384 }
08385
08386
08387 if (!p->owner || (f && f->frametype != AST_FRAME_VOICE)) {
08388 return f;
08389 }
08390
08391 if (f && !ast_format_cap_iscompatible(ast_channel_nativeformats(p->owner), &f->subclass.format)) {
08392 if (!ast_format_cap_iscompatible(p->jointcaps, &f->subclass.format)) {
08393 ast_debug(1, "Bogus frame of format '%s' received from '%s'!\n",
08394 ast_getformatname(&f->subclass.format), ast_channel_name(p->owner));
08395 ast_frfree(f);
08396 return &ast_null_frame;
08397 }
08398 ast_debug(1, "Oooh, format changed to %s\n",
08399 ast_getformatname(&f->subclass.format));
08400 ast_format_cap_remove_bytype(ast_channel_nativeformats(p->owner), AST_FORMAT_TYPE_AUDIO);
08401 ast_format_cap_add(ast_channel_nativeformats(p->owner), &f->subclass.format);
08402 ast_set_read_format(p->owner, ast_channel_readformat(p->owner));
08403 ast_set_write_format(p->owner, ast_channel_writeformat(p->owner));
08404 }
08405
08406 if (f && p->dsp) {
08407 f = ast_dsp_process(p->owner, p->dsp, f);
08408 if (f && f->frametype == AST_FRAME_DTMF) {
08409 if (f->subclass.integer == 'f') {
08410 ast_debug(1, "Fax CNG detected on %s\n", ast_channel_name(ast));
08411 *faxdetect = 1;
08412
08413 if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
08414 ast_dsp_set_features(p->dsp, DSP_FEATURE_DIGIT_DETECT);
08415 } else {
08416 ast_dsp_free(p->dsp);
08417 p->dsp = NULL;
08418 }
08419 } else {
08420 ast_debug(1, "* Detected inband DTMF '%c'\n", f->subclass.integer);
08421 }
08422 }
08423 }
08424
08425 return f;
08426 }
08427
08428
08429 static struct ast_frame *sip_read(struct ast_channel *ast)
08430 {
08431 struct ast_frame *fr;
08432 struct sip_pvt *p = ast_channel_tech_pvt(ast);
08433 int faxdetected = FALSE;
08434
08435 sip_pvt_lock(p);
08436 fr = sip_rtp_read(ast, p, &faxdetected);
08437 p->lastrtprx = time(NULL);
08438
08439
08440 if (faxdetected && ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_CNG)) {
08441 if (strcmp(ast_channel_exten(ast), "fax")) {
08442 const char *target_context = S_OR(ast_channel_macrocontext(ast), ast_channel_context(ast));
08443
08444
08445
08446
08447
08448 sip_pvt_unlock(p);
08449 ast_channel_unlock(ast);
08450 if (ast_exists_extension(ast, target_context, "fax", 1,
08451 S_COR(ast_channel_caller(ast)->id.number.valid, ast_channel_caller(ast)->id.number.str, NULL))) {
08452 ast_channel_lock(ast);
08453 sip_pvt_lock(p);
08454 ast_verb(2, "Redirecting '%s' to fax extension due to CNG detection\n", ast_channel_name(ast));
08455 pbx_builtin_setvar_helper(ast, "FAXEXTEN", ast_channel_exten(ast));
08456 if (ast_async_goto(ast, target_context, "fax", 1)) {
08457 ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", ast_channel_name(ast), target_context);
08458 }
08459 ast_frfree(fr);
08460 fr = &ast_null_frame;
08461 } else {
08462 ast_channel_lock(ast);
08463 sip_pvt_lock(p);
08464 ast_log(LOG_NOTICE, "FAX CNG detected but no fax extension\n");
08465 }
08466 }
08467 }
08468
08469
08470 if (fr && fr->frametype == AST_FRAME_VOICE && p->invitestate != INV_EARLY_MEDIA && ast_channel_state(ast) != AST_STATE_UP) {
08471 ast_frfree(fr);
08472 fr = &ast_null_frame;
08473 }
08474
08475 sip_pvt_unlock(p);
08476
08477 return fr;
08478 }
08479
08480
08481
08482 static char *generate_random_string(char *buf, size_t size)
08483 {
08484 long val[4];
08485 int x;
08486
08487 for (x=0; x<4; x++)
08488 val[x] = ast_random();
08489 snprintf(buf, size, "%08lx%08lx%08lx%08lx", val[0], val[1], val[2], val[3]);
08490
08491 return buf;
08492 }
08493
08494 static char *generate_uri(struct sip_pvt *pvt, char *buf, size_t size)
08495 {
08496 struct ast_str *uri = ast_str_alloca(size);
08497 ast_str_set(&uri, 0, "%s", pvt->socket.type == SIP_TRANSPORT_TLS ? "sips:" : "sip:");
08498
08499
08500
08501 ast_str_append(&uri, 0, "%s", generate_random_string(buf, size));
08502 ast_str_append(&uri, 0, "@%s", ast_sockaddr_stringify_remote(&pvt->ourip));
08503 ast_copy_string(buf, ast_str_buffer(uri), size);
08504 return buf;
08505 }
08506
08507
08508
08509
08510
08511
08512
08513
08514 static void build_callid_pvt(struct sip_pvt *pvt)
08515 {
08516 char buf[33];
08517 const char *host = S_OR(pvt->fromdomain, ast_sockaddr_stringify_remote(&pvt->ourip));
08518
08519 ast_string_field_build(pvt, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
08520 }
08521
08522
08523 #define CONTAINER_UNLINK(container, obj, tag) \
08524 ({ \
08525 int found = 0; \
08526 typeof((obj)) __removed_obj; \
08527 __removed_obj = ao2_t_callback((container), \
08528 OBJ_UNLINK | OBJ_POINTER, ao2_match_by_addr, (obj), (tag)); \
08529 if (__removed_obj) { \
08530 ao2_ref(__removed_obj, -1); \
08531 found = 1; \
08532 } \
08533 found; \
08534 })
08535
08536
08537
08538
08539
08540
08541
08542
08543
08544
08545 static void change_callid_pvt(struct sip_pvt *pvt, const char *callid)
08546 {
08547 int in_dialog_container;
08548 int in_rtp_container;
08549 char *oldid = ast_strdupa(pvt->callid);
08550
08551 ao2_lock(dialogs);
08552 ao2_lock(dialogs_rtpcheck);
08553 in_dialog_container = CONTAINER_UNLINK(dialogs, pvt,
08554 "About to change the callid -- remove the old name");
08555 in_rtp_container = CONTAINER_UNLINK(dialogs_rtpcheck, pvt,
08556 "About to change the callid -- remove the old name");
08557 if (callid) {
08558 ast_string_field_set(pvt, callid, callid);
08559 } else {
08560 build_callid_pvt(pvt);
08561 }
08562 if (in_dialog_container) {
08563 ao2_t_link(dialogs, pvt, "New dialog callid -- inserted back into table");
08564 }
08565 if (in_rtp_container) {
08566 ao2_t_link(dialogs_rtpcheck, pvt, "New dialog callid -- inserted back into table");
08567 }
08568 ao2_unlock(dialogs_rtpcheck);
08569 ao2_unlock(dialogs);
08570
08571 if (strcmp(oldid, pvt->callid)) {
08572 ast_debug(1, "SIP call-id changed from '%s' to '%s'\n", oldid, pvt->callid);
08573 }
08574 }
08575
08576
08577 static void build_callid_registry(struct sip_registry *reg, const struct ast_sockaddr *ourip, const char *fromdomain)
08578 {
08579 char buf[33];
08580
08581 const char *host = S_OR(fromdomain, ast_sockaddr_stringify_host_remote(ourip));
08582
08583 ast_string_field_build(reg, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
08584 }
08585
08586
08587 static void build_localtag_registry(struct sip_registry *reg)
08588 {
08589 ast_string_field_build(reg, localtag, "as%08lx", ast_random());
08590 }
08591
08592
08593 static void make_our_tag(struct sip_pvt *pvt)
08594 {
08595 ast_string_field_build(pvt, tag, "as%08lx", ast_random());
08596 }
08597
08598
08599 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p)
08600 {
08601 struct sip_st_dlg *stp;
08602
08603 if (p->stimer) {
08604 ast_log(LOG_ERROR, "Session-Timer struct already allocated\n");
08605 return p->stimer;
08606 }
08607
08608 if (!(stp = ast_calloc(1, sizeof(struct sip_st_dlg))))
08609 return NULL;
08610
08611 p->stimer = stp;
08612
08613 stp->st_schedid = -1;
08614
08615 return p->stimer;
08616 }
08617
08618 static void sip_pvt_callid_set(struct sip_pvt *pvt, struct ast_callid *callid)
08619 {
08620 if (pvt->logger_callid) {
08621 ast_callid_unref(pvt->logger_callid);
08622 }
08623 ast_callid_ref(callid);
08624 pvt->logger_callid = callid;
08625 }
08626
08627
08628
08629
08630
08631 struct sip_pvt *sip_alloc(ast_string_field callid, struct ast_sockaddr *addr,
08632 int useglobal_nat, const int intended_method, struct sip_request *req, struct ast_callid *logger_callid)
08633 {
08634 struct sip_pvt *p;
08635
08636 if (!(p = ao2_t_alloc(sizeof(*p), sip_destroy_fn, "allocate a dialog(pvt) struct")))
08637 return NULL;
08638
08639 if (ast_string_field_init(p, 512)) {
08640 ao2_t_ref(p, -1, "failed to string_field_init, drop p");
08641 return NULL;
08642 }
08643
08644 if (!(p->cc_params = ast_cc_config_params_init())) {
08645 ao2_t_ref(p, -1, "Yuck, couldn't allocate cc_params struct. Get rid o' p");
08646 return NULL;
08647 }
08648
08649 if (logger_callid) {
08650 sip_pvt_callid_set(p, logger_callid);
08651 }
08652
08653 p->caps = ast_format_cap_alloc_nolock();
08654 p->jointcaps = ast_format_cap_alloc_nolock();
08655 p->peercaps = ast_format_cap_alloc_nolock();
08656 p->redircaps = ast_format_cap_alloc_nolock();
08657 p->prefcaps = ast_format_cap_alloc_nolock();
08658
08659 if (!p->caps|| !p->jointcaps || !p->peercaps || !p->redircaps) {
08660 p->caps = ast_format_cap_destroy(p->caps);
08661 p->jointcaps = ast_format_cap_destroy(p->jointcaps);
08662 p->peercaps = ast_format_cap_destroy(p->peercaps);
08663 p->redircaps = ast_format_cap_destroy(p->redircaps);
08664 p->prefcaps = ast_format_cap_destroy(p->prefcaps);
08665 ao2_t_ref(p, -1, "Yuck, couldn't allocate format capabilities. Get rid o' p");
08666 return NULL;
08667 }
08668
08669
08670
08671
08672 if (req) {
08673 struct sip_via *via;
08674 const char *cseq = sip_get_header(req, "Cseq");
08675 uint32_t seqno;
08676
08677
08678 via = parse_via(sip_get_header(req, "Via"));
08679 if (via) {
08680
08681
08682 if (!ast_strlen_zero(via->branch) && !strncasecmp(via->branch, "z9hG4bK", 7)) {
08683 ast_string_field_set(p, initviabranch, via->branch);
08684 ast_string_field_set(p, initviasentby, via->sent_by);
08685 }
08686 free_via(via);
08687 }
08688
08689
08690
08691 if (!ast_strlen_zero(cseq) && (sscanf(cseq, "%30u", &seqno) == 1)) {
08692 p->init_icseq = seqno;
08693 }
08694
08695 set_socket_transport(&p->socket, req->socket.type);
08696 } else {
08697 set_socket_transport(&p->socket, SIP_TRANSPORT_UDP);
08698 }
08699
08700 p->socket.fd = -1;
08701 p->method = intended_method;
08702 p->initid = -1;
08703 p->waitid = -1;
08704 p->reinviteid = -1;
08705 p->autokillid = -1;
08706 p->request_queue_sched_id = -1;
08707 p->provisional_keepalive_sched_id = -1;
08708 p->t38id = -1;
08709 p->subscribed = NONE;
08710 p->stateid = -1;
08711 p->sessionversion_remote = -1;
08712 p->session_modify = TRUE;
08713 p->stimer = NULL;
08714 p->prefs = default_prefs;
08715 ast_copy_string(p->zone, default_zone, sizeof(p->zone));
08716 p->maxforwards = sip_cfg.default_max_forwards;
08717
08718 if (intended_method != SIP_OPTIONS) {
08719 p->timer_t1 = global_t1;
08720 p->timer_b = global_timer_b;
08721 }
08722
08723 if (!addr) {
08724 p->ourip = internip;
08725 } else {
08726 ast_sockaddr_copy(&p->sa, addr);
08727 ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
08728 }
08729
08730
08731 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
08732 ast_copy_flags(&p->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
08733 ast_copy_flags(&p->flags[2], &global_flags[2], SIP_PAGE3_FLAGS_TO_COPY);
08734
08735 p->do_history = recordhistory;
08736
08737 p->branch = ast_random();
08738 make_our_tag(p);
08739 p->ocseq = INITIAL_CSEQ;
08740 p->allowed_methods = UINT_MAX;
08741
08742 if (sip_methods[intended_method].need_rtp) {
08743 p->maxcallbitrate = default_maxcallbitrate;
08744 p->autoframing = global_autoframing;
08745 }
08746
08747 if (useglobal_nat && addr) {
08748
08749 ast_sockaddr_copy(&p->recv, addr);
08750 check_via(p, req);
08751 do_setnat(p);
08752 }
08753
08754 if (p->method != SIP_REGISTER) {
08755 ast_string_field_set(p, fromdomain, default_fromdomain);
08756 p->fromdomainport = default_fromdomainport;
08757 }
08758 build_via(p);
08759 if (!callid)
08760 build_callid_pvt(p);
08761 else
08762 ast_string_field_set(p, callid, callid);
08763
08764 ast_string_field_set(p, mohinterpret, default_mohinterpret);
08765 ast_string_field_set(p, mohsuggest, default_mohsuggest);
08766 ast_format_cap_copy(p->caps, sip_cfg.caps);
08767 p->allowtransfer = sip_cfg.allowtransfer;
08768 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
08769 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
08770 p->noncodeccapability |= AST_RTP_DTMF;
08771 }
08772 ast_string_field_set(p, context, sip_cfg.default_context);
08773 ast_string_field_set(p, parkinglot, default_parkinglot);
08774 ast_string_field_set(p, engine, default_engine);
08775
08776 AST_LIST_HEAD_INIT_NOLOCK(&p->request_queue);
08777 AST_LIST_HEAD_INIT_NOLOCK(&p->offered_media);
08778
08779
08780
08781 ao2_t_link(dialogs, p, "link pvt into dialogs table");
08782
08783 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");
08784 return p;
08785 }
08786
08787
08788
08789
08790
08791
08792
08793
08794
08795
08796
08797
08798
08799
08800
08801
08802 static int process_via(struct sip_pvt *p, const struct sip_request *req)
08803 {
08804 struct sip_via *via = parse_via(sip_get_header(req, "Via"));
08805
08806 if (!via) {
08807 ast_log(LOG_ERROR, "error processing via header\n");
08808 return -1;
08809 }
08810
08811 if (via->maddr) {
08812 if (ast_sockaddr_resolve_first_transport(&p->sa, via->maddr, PARSE_PORT_FORBID, p->socket.type)) {
08813 ast_log(LOG_WARNING, "Can't find address for maddr '%s'\n", via->maddr);
08814 ast_log(LOG_ERROR, "error processing via header\n");
08815 free_via(via);
08816 return -1;
08817 }
08818
08819 if (ast_sockaddr_is_ipv4_multicast(&p->sa)) {
08820 setsockopt(sipsock, IPPROTO_IP, IP_MULTICAST_TTL, &via->ttl, sizeof(via->ttl));
08821 }
08822 }
08823
08824 ast_sockaddr_set_port(&p->sa, via->port ? via->port : STANDARD_SIP_PORT);
08825
08826 free_via(via);
08827 return 0;
08828 }
08829
08830
08831 struct match_req_args {
08832 int method;
08833 const char *callid;
08834 const char *totag;
08835 const char *fromtag;
08836 uint32_t seqno;
08837
08838
08839 int respid;
08840
08841
08842 const char *ruri;
08843 const char *viabranch;
08844 const char *viasentby;
08845
08846
08847 int authentication_present;
08848 };
08849
08850 enum match_req_res {
08851 SIP_REQ_MATCH,
08852 SIP_REQ_NOT_MATCH,
08853 SIP_REQ_LOOP_DETECTED,
08854 SIP_REQ_FORKED,
08855 };
08856
08857
08858
08859
08860
08861
08862 static enum match_req_res match_req_to_dialog(struct sip_pvt *sip_pvt_ptr, struct match_req_args *arg)
08863 {
08864 const char *init_ruri = NULL;
08865 if (sip_pvt_ptr->initreq.headers) {
08866 init_ruri = REQ_OFFSET_TO_STR(&sip_pvt_ptr->initreq, rlpart2);
08867 }
08868
08869
08870
08871
08872 if (!ast_strlen_zero(arg->callid) && strcmp(sip_pvt_ptr->callid, arg->callid)) {
08873
08874 return SIP_REQ_NOT_MATCH;
08875 }
08876 if (arg->method == SIP_RESPONSE) {
08877
08878 if (strcmp(arg->fromtag, sip_pvt_ptr->tag)) {
08879
08880 return SIP_REQ_NOT_MATCH;
08881 }
08882
08883
08884
08885 if (!ast_strlen_zero(sip_pvt_ptr->theirtag) && ast_test_flag(&sip_pvt_ptr->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
08886 if (ast_strlen_zero(arg->totag)) {
08887
08888 return SIP_REQ_NOT_MATCH;
08889 }
08890
08891 if (strcmp(arg->totag, sip_pvt_ptr->theirtag)) {
08892
08893 char invite_branch[32] = { 0, };
08894 if (sip_pvt_ptr->invite_branch) {
08895 snprintf(invite_branch, sizeof(invite_branch), "z9hG4bK%08x", (int) sip_pvt_ptr->invite_branch);
08896 }
08897
08898
08899
08900
08901
08902
08903
08904
08905
08906
08907
08908
08909 if ((arg->respid == 200) &&
08910 !ast_strlen_zero(invite_branch) &&
08911 !ast_strlen_zero(arg->viabranch) &&
08912 !strcmp(invite_branch, arg->viabranch)) {
08913 return SIP_REQ_FORKED;
08914 }
08915
08916
08917 return SIP_REQ_NOT_MATCH;
08918 }
08919 }
08920 } else {
08921
08922
08923
08924 if (!arg->authentication_present && strcmp(arg->fromtag, sip_pvt_ptr->theirtag)) {
08925
08926 return SIP_REQ_NOT_MATCH;
08927 }
08928
08929 if (!ast_strlen_zero(arg->totag) && (strcmp(arg->totag, sip_pvt_ptr->tag))) {
08930
08931 return SIP_REQ_NOT_MATCH;
08932 }
08933 }
08934
08935
08936
08937
08938
08939
08940
08941
08942
08943
08944
08945
08946
08947
08948
08949
08950
08951 if ((arg->method != SIP_RESPONSE) &&
08952 ast_strlen_zero(arg->totag) &&
08953 (sip_pvt_ptr->init_icseq == arg->seqno) &&
08954 !ast_strlen_zero(sip_pvt_ptr->initviabranch) &&
08955 init_ruri) {
08956
08957
08958 if (ast_strlen_zero(arg->viabranch) ||
08959 strcmp(arg->viabranch, sip_pvt_ptr->initviabranch) ||
08960 ast_strlen_zero(arg->viasentby) ||
08961 strcmp(arg->viasentby, sip_pvt_ptr->initviasentby)) {
08962
08963
08964
08965 if ((sip_pvt_ptr->method != arg->method)) {
08966 return SIP_REQ_NOT_MATCH;
08967 }
08968
08969
08970
08971 if (sip_uri_cmp(init_ruri, arg->ruri)) {
08972
08973 return SIP_REQ_NOT_MATCH;
08974 }
08975
08976
08977
08978
08979
08980
08981
08982
08983
08984
08985
08986
08987
08988
08989
08990
08991
08992
08993
08994 return SIP_REQ_LOOP_DETECTED;
08995 }
08996 }
08997
08998
08999
09000
09001
09002
09003 if ((arg->method != SIP_RESPONSE) &&
09004 ast_strlen_zero(arg->totag) &&
09005 arg->authentication_present &&
09006 sip_uri_cmp(init_ruri, arg->ruri)) {
09007
09008
09009 return SIP_REQ_NOT_MATCH;
09010 }
09011
09012 return SIP_REQ_MATCH;
09013 }
09014
09015
09016
09017
09018 static void forked_invite_init(struct sip_request *req, const char *new_theirtag, struct sip_pvt *original, struct ast_sockaddr *addr)
09019 {
09020 struct sip_pvt *p;
09021 const char *callid;
09022 struct ast_callid *logger_callid;
09023
09024 sip_pvt_lock(original);
09025 callid = ast_strdupa(original->callid);
09026 logger_callid = original->logger_callid;
09027 if (logger_callid) {
09028 ast_callid_ref(logger_callid);
09029 }
09030 sip_pvt_unlock(original);
09031
09032 p = sip_alloc(callid, addr, 1, SIP_INVITE, req, logger_callid);
09033 if (logger_callid) {
09034 ast_callid_unref(logger_callid);
09035 }
09036 if (!p) {
09037 return;
09038 }
09039
09040
09041 sip_pvt_lock(p);
09042 while (sip_pvt_trylock(original)) {
09043
09044 sip_pvt_unlock(p);
09045 sched_yield();
09046 sip_pvt_lock(p);
09047 }
09048
09049 p->invitestate = INV_TERMINATED;
09050 p->ocseq = original->ocseq;
09051 p->branch = original->branch;
09052
09053 memcpy(&p->flags, &original->flags, sizeof(p->flags));
09054 copy_request(&p->initreq, &original->initreq);
09055 ast_string_field_set(p, theirtag, new_theirtag);
09056 ast_string_field_set(p, tag, original->tag);
09057 ast_string_field_set(p, uri, original->uri);
09058 ast_string_field_set(p, our_contact, original->our_contact);
09059 ast_string_field_set(p, fullcontact, original->fullcontact);
09060
09061 sip_pvt_unlock(original);
09062
09063 parse_ok_contact(p, req);
09064 build_route(p, req, 1, 0);
09065
09066 transmit_request(p, SIP_ACK, p->ocseq, XMIT_UNRELIABLE, TRUE);
09067 transmit_request(p, SIP_BYE, 0, XMIT_RELIABLE, TRUE);
09068
09069 pvt_set_needdestroy(p, "forked request");
09070 sip_pvt_unlock(p);
09071 dialog_unref(p, "setup forked invite termination");
09072 }
09073
09074
09075
09076
09077
09078
09079
09080
09081
09082
09083
09084
09085
09086
09087
09088
09089
09090
09091 static struct ast_channel *sip_pvt_lock_full(struct sip_pvt *pvt)
09092 {
09093 struct ast_channel *chan;
09094
09095
09096
09097
09098 for (;;) {
09099
09100 sip_pvt_lock(pvt);
09101 chan = pvt->owner;
09102 if (chan) {
09103
09104
09105
09106 ast_channel_ref(chan);
09107 } else {
09108
09109 return NULL;
09110 }
09111
09112
09113
09114
09115 sip_pvt_unlock(pvt);
09116
09117
09118 ast_channel_lock(chan);
09119 sip_pvt_lock(pvt);
09120
09121 if (pvt->owner == chan) {
09122
09123 break;
09124 }
09125
09126
09127
09128
09129
09130
09131 ast_channel_unlock(chan);
09132 ast_channel_unref(chan);
09133 sip_pvt_unlock(pvt);
09134 }
09135
09136
09137 return pvt->owner;
09138 }
09139
09140
09141
09142
09143
09144
09145 static struct sip_pvt *find_call(struct sip_request *req, struct ast_sockaddr *addr, const int intended_method)
09146 {
09147 char totag[128];
09148 char fromtag[128];
09149 const char *callid = sip_get_header(req, "Call-ID");
09150 const char *from = sip_get_header(req, "From");
09151 const char *to = sip_get_header(req, "To");
09152 const char *cseq = sip_get_header(req, "Cseq");
09153 struct sip_pvt *sip_pvt_ptr;
09154 uint32_t seqno;
09155
09156
09157 if (ast_strlen_zero(callid) || ast_strlen_zero(to) ||
09158 ast_strlen_zero(from) || ast_strlen_zero(cseq) ||
09159 (sscanf(cseq, "%30u", &seqno) != 1)) {
09160
09161
09162 if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
09163 transmit_response_using_temp(callid, addr, 1, intended_method,
09164 req, "400 Bad Request");
09165 }
09166 return NULL;
09167 }
09168
09169 if (sip_cfg.pedanticsipchecking) {
09170
09171
09172
09173
09174
09175
09176 if (gettag(req, "To", totag, sizeof(totag)))
09177 req->has_to_tag = 1;
09178 gettag(req, "From", fromtag, sizeof(fromtag));
09179
09180 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);
09181
09182
09183 if (ast_strlen_zero(fromtag)) {
09184 ast_debug(5, "%s request has no from tag, dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
09185 return NULL;
09186 }
09187
09188 if (ast_strlen_zero(totag) && (req->method == SIP_ACK || req->method == SIP_BYE || req->method == SIP_INFO )) {
09189 if (req->method != SIP_ACK) {
09190 transmit_response_using_temp(callid, addr, 1, intended_method, req, "481 Call leg/transaction does not exist");
09191 }
09192 ast_debug(5, "%s must have a to tag. dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
09193 return NULL;
09194 }
09195 }
09196
09197 if (!sip_cfg.pedanticsipchecking) {
09198 struct sip_pvt tmp_dialog = {
09199 .callid = callid,
09200 };
09201 sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find in dialogs");
09202 if (sip_pvt_ptr) {
09203
09204 return sip_pvt_ptr;
09205 }
09206 } else {
09207 struct sip_pvt tmp_dialog = {
09208 .callid = callid,
09209 };
09210
09211
09212 struct sip_pvt *fork_pvt = NULL;
09213 struct match_req_args args = { 0, };
09214 int found;
09215 struct ao2_iterator *iterator = ao2_t_callback(dialogs,
09216 OBJ_POINTER | OBJ_MULTIPLE,
09217 dialog_find_multiple,
09218 &tmp_dialog,
09219 "pedantic ao2_find in dialogs");
09220 struct sip_via *via = NULL;
09221
09222 args.method = req->method;
09223 args.callid = NULL;
09224 args.totag = totag;
09225 args.fromtag = fromtag;
09226 args.seqno = seqno;
09227
09228 args.ruri = REQ_OFFSET_TO_STR(req, rlpart2);
09229 via = parse_via(sip_get_header(req, "Via"));
09230 if (via) {
09231 args.viasentby = via->sent_by;
09232 args.viabranch = via->branch;
09233 }
09234
09235 if (!ast_strlen_zero(sip_get_header(req, "Authorization")) ||
09236 !ast_strlen_zero(sip_get_header(req, "Proxy-Authorization"))) {
09237 args.authentication_present = 1;
09238 }
09239
09240 if (req->method == SIP_RESPONSE) {
09241 const char* e = ast_skip_blanks(REQ_OFFSET_TO_STR(req, rlpart2));
09242 int respid;
09243 if (!ast_strlen_zero(e) && (sscanf(e, "%30d", &respid) == 1)) {
09244 args.respid = respid;
09245 }
09246 }
09247
09248
09249 while (iterator && (sip_pvt_ptr = ao2_iterator_next(iterator))) {
09250 sip_pvt_lock(sip_pvt_ptr);
09251 found = match_req_to_dialog(sip_pvt_ptr, &args);
09252 sip_pvt_unlock(sip_pvt_ptr);
09253
09254 switch (found) {
09255 case SIP_REQ_MATCH:
09256 ao2_iterator_destroy(iterator);
09257 dialog_unref(fork_pvt, "unref fork_pvt");
09258 free_via(via);
09259 return sip_pvt_ptr;
09260 case SIP_REQ_LOOP_DETECTED:
09261
09262
09263 transmit_response_using_temp(callid, addr, 1, intended_method, req, "482 (Loop Detected)");
09264 dialog_unref(sip_pvt_ptr, "pvt did not match incoming SIP msg, unref from search.");
09265 ao2_iterator_destroy(iterator);
09266 dialog_unref(fork_pvt, "unref fork_pvt");
09267 free_via(via);
09268 return NULL;
09269 case SIP_REQ_FORKED:
09270 dialog_unref(fork_pvt, "throwing way pvt to fork off of.");
09271 fork_pvt = dialog_ref(sip_pvt_ptr, "this pvt has a forked request, save this off to copy information into new dialog\n");
09272
09273 case SIP_REQ_NOT_MATCH:
09274 default:
09275 dialog_unref(sip_pvt_ptr, "pvt did not match incoming SIP msg, unref from search");
09276 break;
09277 }
09278 }
09279 if (iterator) {
09280 ao2_iterator_destroy(iterator);
09281 }
09282
09283
09284 if (fork_pvt) {
09285
09286
09287 if (fork_pvt->method == SIP_INVITE) {
09288 forked_invite_init(req, args.totag, fork_pvt, addr);
09289 dialog_unref(fork_pvt, "throwing way old forked pvt");
09290 free_via(via);
09291 return NULL;
09292 }
09293 fork_pvt = dialog_unref(fork_pvt, "throwing way pvt to fork off of");
09294 }
09295
09296 free_via(via);
09297 }
09298
09299
09300 if (sip_methods[intended_method].can_create == CAN_CREATE_DIALOG) {
09301 struct sip_pvt *p = NULL;
09302 struct ast_callid *logger_callid = NULL;
09303
09304 if (intended_method == SIP_INVITE) {
09305 logger_callid = ast_create_callid();
09306 }
09307
09308
09309 if (!(p = sip_alloc(callid, addr, 1, intended_method, req, logger_callid))) {
09310
09311
09312
09313
09314
09315
09316
09317
09318 transmit_response_using_temp(callid, addr, 1, intended_method, req, "500 Server internal error");
09319 ast_debug(4, "Failed allocating SIP dialog, sending 500 Server internal error and giving up\n");
09320 }
09321
09322 if (logger_callid) {
09323 ast_callid_unref(logger_callid);
09324 }
09325 return p;
09326 } else if( sip_methods[intended_method].can_create == CAN_CREATE_DIALOG_UNSUPPORTED_METHOD) {
09327
09328 transmit_response_using_temp(callid, addr, 1, intended_method, req, "501 Method Not Implemented");
09329 ast_debug(2, "Got a request with unsupported SIP method.\n");
09330 } else if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
09331
09332 transmit_response_using_temp(callid, addr, 1, intended_method, req, "481 Call leg/transaction does not exist");
09333 ast_debug(2, "That's odd... Got a request in unknown dialog. Callid %s\n", callid ? callid : "<unknown>");
09334 }
09335
09336
09337 if (intended_method == SIP_RESPONSE)
09338 ast_debug(2, "That's odd... Got a response on a call we don't know about. Callid %s\n", callid ? callid : "<unknown>");
09339
09340 return NULL;
09341 }
09342
09343
09344 static int sip_register(const char *value, int lineno)
09345 {
09346 struct sip_registry *reg, *tmp;
09347
09348 if (!(reg = ast_calloc_with_stringfields(1, struct sip_registry, 256))) {
09349 ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry entry\n");
09350 return -1;
09351 }
09352
09353 ASTOBJ_INIT(reg);
09354
09355 ast_copy_string(reg->name, value, sizeof(reg->name));
09356 if (sip_parse_register_line(reg, default_expiry, value, lineno)) {
09357 registry_unref(reg, "failure to parse, unref the reg pointer");
09358 return -1;
09359 }
09360
09361
09362 if (reg->refresh && !reg->expiry && !reg->configured_expiry) {
09363 reg->refresh = reg->expiry = reg->configured_expiry = default_expiry;
09364 }
09365
09366
09367 if ((tmp = ASTOBJ_CONTAINER_FIND(®l, reg->name))) {
09368 registry_unref(tmp, "throw away found registry");
09369 } else {
09370 ast_atomic_fetchadd_int(®objs, 1);
09371 ASTOBJ_CONTAINER_LINK(®l, reg);
09372 }
09373
09374
09375 registry_unref(reg, "unref the reg pointer");
09376
09377 return 0;
09378 }
09379
09380
09381 static int sip_subscribe_mwi(const char *value, int lineno)
09382 {
09383 struct sip_subscription_mwi *mwi;
09384 int portnum = 0;
09385 enum sip_transport transport = SIP_TRANSPORT_UDP;
09386 char buf[256] = "";
09387 char *username = NULL, *hostname = NULL, *secret = NULL, *authuser = NULL, *porta = NULL, *mailbox = NULL;
09388
09389 if (!value) {
09390 return -1;
09391 }
09392
09393 ast_copy_string(buf, value, sizeof(buf));
09394
09395 username = buf;
09396
09397 if ((hostname = strrchr(buf, '@'))) {
09398 *hostname++ = '\0';
09399 } else {
09400 return -1;
09401 }
09402
09403 if ((secret = strchr(username, ':'))) {
09404 *secret++ = '\0';
09405 if ((authuser = strchr(secret, ':'))) {
09406 *authuser++ = '\0';
09407 }
09408 }
09409
09410 if ((mailbox = strchr(hostname, '/'))) {
09411 *mailbox++ = '\0';
09412 }
09413
09414 if (ast_strlen_zero(username) || ast_strlen_zero(hostname) || ast_strlen_zero(mailbox)) {
09415 ast_log(LOG_WARNING, "Format for MWI subscription is user[:secret[:authuser]]@host[:port]/mailbox at line %d\n", lineno);
09416 return -1;
09417 }
09418
09419 if ((porta = strchr(hostname, ':'))) {
09420 *porta++ = '\0';
09421 if (!(portnum = atoi(porta))) {
09422 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
09423 return -1;
09424 }
09425 }
09426
09427 if (!(mwi = ast_calloc_with_stringfields(1, struct sip_subscription_mwi, 256))) {
09428 return -1;
09429 }
09430
09431 ASTOBJ_INIT(mwi);
09432 ast_string_field_set(mwi, username, username);
09433 if (secret) {
09434 ast_string_field_set(mwi, secret, secret);
09435 }
09436 if (authuser) {
09437 ast_string_field_set(mwi, authuser, authuser);
09438 }
09439 ast_string_field_set(mwi, hostname, hostname);
09440 ast_string_field_set(mwi, mailbox, mailbox);
09441 mwi->resub = -1;
09442 mwi->portno = portnum;
09443 mwi->transport = transport;
09444
09445 ASTOBJ_CONTAINER_LINK(&submwil, mwi);
09446 ASTOBJ_UNREF(mwi, sip_subscribe_mwi_destroy);
09447
09448 return 0;
09449 }
09450
09451 static void mark_method_allowed(unsigned int *allowed_methods, enum sipmethod method)
09452 {
09453 (*allowed_methods) |= (1 << method);
09454 }
09455
09456 static void mark_method_unallowed(unsigned int *allowed_methods, enum sipmethod method)
09457 {
09458 (*allowed_methods) &= ~(1 << method);
09459 }
09460
09461
09462 static int is_method_allowed(unsigned int *allowed_methods, enum sipmethod method)
09463 {
09464 return ((*allowed_methods) >> method) & 1;
09465 }
09466
09467 static void mark_parsed_methods(unsigned int *methods, char *methods_str)
09468 {
09469 char *method;
09470 for (method = strsep(&methods_str, ","); !ast_strlen_zero(method); method = strsep(&methods_str, ",")) {
09471 int id = find_sip_method(ast_skip_blanks(method));
09472 if (id == SIP_UNKNOWN) {
09473 continue;
09474 }
09475 mark_method_allowed(methods, id);
09476 }
09477 }
09478
09479
09480
09481
09482
09483
09484
09485
09486
09487
09488
09489
09490
09491
09492
09493
09494 static unsigned int parse_allowed_methods(struct sip_request *req)
09495 {
09496 char *allow = ast_strdupa(sip_get_header(req, "Allow"));
09497 unsigned int allowed_methods = SIP_UNKNOWN;
09498
09499 if (ast_strlen_zero(allow)) {
09500
09501
09502
09503
09504 char *contact = ast_strdupa(sip_get_header(req, "Contact"));
09505 char *methods = strstr(contact, ";methods=");
09506
09507 if (ast_strlen_zero(methods)) {
09508
09509
09510
09511
09512
09513
09514
09515
09516
09517
09518
09519 return UINT_MAX;
09520 }
09521 allow = ast_strip_quoted(methods + 9, "\"", "\"");
09522 }
09523 mark_parsed_methods(&allowed_methods, allow);
09524 return allowed_methods;
09525 }
09526
09527
09528
09529
09530
09531
09532
09533
09534
09535
09536 static unsigned int set_pvt_allowed_methods(struct sip_pvt *pvt, struct sip_request *req)
09537 {
09538 pvt->allowed_methods = parse_allowed_methods(req);
09539
09540 if (ast_test_flag(&pvt->flags[1], SIP_PAGE2_RPID_UPDATE)) {
09541 mark_method_allowed(&pvt->allowed_methods, SIP_UPDATE);
09542 }
09543 pvt->allowed_methods &= ~(pvt->disallowed_methods);
09544
09545 return pvt->allowed_methods;
09546 }
09547
09548
09549
09550 static void lws2sws(struct ast_str *data)
09551 {
09552 char *msgbuf = data->str;
09553 int len = ast_str_strlen(data);
09554 int h = 0, t = 0;
09555 int lws = 0;
09556
09557 for (; h < len;) {
09558
09559 if (msgbuf[h] == '\r') {
09560 h++;
09561 continue;
09562 }
09563
09564 if (msgbuf[h] == '\n') {
09565
09566 if (h + 1 == len)
09567 break;
09568
09569 if (msgbuf[h + 1] == ' ' || msgbuf[h + 1] == '\t') {
09570
09571 h++;
09572 continue;
09573 }
09574
09575 msgbuf[t++] = msgbuf[h++];
09576 lws = 0;
09577 continue;
09578 }
09579 if (msgbuf[h] == ' ' || msgbuf[h] == '\t') {
09580 if (lws) {
09581 h++;
09582 continue;
09583 }
09584 msgbuf[t++] = msgbuf[h++];
09585 lws = 1;
09586 continue;
09587 }
09588 msgbuf[t++] = msgbuf[h++];
09589 if (lws)
09590 lws = 0;
09591 }
09592 msgbuf[t] = '\0';
09593 data->used = t;
09594 }
09595
09596
09597
09598
09599 static int parse_request(struct sip_request *req)
09600 {
09601 char *c = req->data->str;
09602 ptrdiff_t *dst = req->header;
09603 int i = 0, lim = SIP_MAX_HEADERS - 1;
09604 unsigned int skipping_headers = 0;
09605 ptrdiff_t current_header_offset = 0;
09606 char *previous_header = "";
09607
09608 req->header[0] = 0;
09609 req->headers = -1;
09610 for (; *c; c++) {
09611 if (*c == '\r') {
09612 *c = '\0';
09613 } else if (*c == '\n') {
09614 *c = '\0';
09615 current_header_offset = (c + 1) - ast_str_buffer(req->data);
09616 previous_header = ast_str_buffer(req->data) + dst[i];
09617 if (skipping_headers) {
09618
09619
09620
09621 if (ast_strlen_zero(previous_header)) {
09622 skipping_headers = 0;
09623 }
09624 dst[i] = current_header_offset;
09625 continue;
09626 }
09627 if (sipdebug) {
09628 ast_debug(4, "%7s %2d [%3d]: %s\n",
09629 req->headers < 0 ? "Header" : "Body",
09630 i, (int) strlen(previous_header), previous_header);
09631 }
09632 if (ast_strlen_zero(previous_header) && req->headers < 0) {
09633 req->headers = i;
09634 dst = req->line;
09635 i = 0;
09636 lim = SIP_MAX_LINES - 1;
09637 } else {
09638 if (i++ == lim) {
09639
09640
09641
09642 if (req->headers != -1) {
09643 break;
09644 } else {
09645 req->headers = i;
09646 dst = req->line;
09647 i = 0;
09648 lim = SIP_MAX_LINES - 1;
09649 skipping_headers = 1;
09650 }
09651 }
09652 }
09653 dst[i] = current_header_offset;
09654 }
09655 }
09656
09657
09658
09659
09660
09661
09662 previous_header = ast_str_buffer(req->data) + dst[i];
09663 if ((i < lim) && !ast_strlen_zero(previous_header)) {
09664 if (sipdebug) {
09665 ast_debug(4, "%7s %2d [%3d]: %s\n",
09666 req->headers < 0 ? "Header" : "Body",
09667 i, (int) strlen(previous_header), previous_header );
09668 }
09669 i++;
09670 }
09671
09672
09673 if (req->headers >= 0) {
09674 req->lines = i;
09675 } else {
09676 req->headers = i;
09677 req->lines = 0;
09678
09679 req->line[0] = ast_str_strlen(req->data);
09680 }
09681
09682 if (*c) {
09683 ast_log(LOG_WARNING, "Too many lines, skipping <%s>\n", c);
09684 }
09685
09686
09687 return determine_firstline_parts(req);
09688 }
09689
09690
09691
09692
09693
09694
09695
09696
09697
09698 static int find_sdp(struct sip_request *req)
09699 {
09700 const char *content_type;
09701 const char *content_length;
09702 const char *search;
09703 char *boundary;
09704 unsigned int x;
09705 int boundaryisquoted = FALSE;
09706 int found_application_sdp = FALSE;
09707 int found_end_of_headers = FALSE;
09708
09709 content_length = sip_get_header(req, "Content-Length");
09710
09711 if (!ast_strlen_zero(content_length)) {
09712 if (sscanf(content_length, "%30u", &x) != 1) {
09713 ast_log(LOG_WARNING, "Invalid Content-Length: %s\n", content_length);
09714 return 0;
09715 }
09716
09717
09718
09719 if (x == 0)
09720 return 0;
09721 }
09722
09723 content_type = sip_get_header(req, "Content-Type");
09724
09725
09726 if (!strncasecmp(content_type, "application/sdp", 15)) {
09727 req->sdp_start = 0;
09728 req->sdp_count = req->lines;
09729 return req->lines ? 1 : 0;
09730 }
09731
09732
09733 if (strncasecmp(content_type, "multipart/mixed", 15))
09734 return 0;
09735
09736
09737 if ((search = strcasestr(content_type, ";boundary=")))
09738 search += 10;
09739 else if ((search = strcasestr(content_type, "; boundary=")))
09740 search += 11;
09741 else
09742 return 0;
09743
09744 if (ast_strlen_zero(search))
09745 return 0;
09746
09747
09748 if (*search == '\"') {
09749 search++;
09750 boundaryisquoted = TRUE;
09751 }
09752
09753
09754
09755 boundary = ast_strdupa(search - 2);
09756 boundary[0] = boundary[1] = '-';
09757
09758 if (boundaryisquoted)
09759 boundary[strlen(boundary) - 1] = '\0';
09760
09761
09762
09763
09764 for (x = 0; x < (req->lines); x++) {
09765 const char *line = REQ_OFFSET_TO_STR(req, line[x]);
09766 if (!strncasecmp(line, boundary, strlen(boundary))){
09767 if (found_application_sdp && found_end_of_headers) {
09768 req->sdp_count = (x - 1) - req->sdp_start;
09769 return 1;
09770 }
09771 found_application_sdp = FALSE;
09772 }
09773 if (!strcasecmp(line, "Content-Type: application/sdp"))
09774 found_application_sdp = TRUE;
09775
09776 if (ast_strlen_zero(line)) {
09777 if (found_application_sdp && !found_end_of_headers){
09778 req->sdp_start = x;
09779 found_end_of_headers = TRUE;
09780 }
09781 }
09782 }
09783 if (found_application_sdp && found_end_of_headers) {
09784 req->sdp_count = x - req->sdp_start;
09785 return TRUE;
09786 }
09787 return FALSE;
09788 }
09789
09790
09791 static void change_hold_state(struct sip_pvt *dialog, struct sip_request *req, int holdstate, int sendonly)
09792 {
09793 if (sip_cfg.notifyhold && (!holdstate || !ast_test_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD)))
09794 sip_peer_hold(dialog, holdstate);
09795 if (sip_cfg.callevents)
09796 manager_event(EVENT_FLAG_CALL, "Hold",
09797 "Status: %s\r\n"
09798 "Channel: %s\r\n"
09799 "Uniqueid: %s\r\n",
09800 holdstate ? "On" : "Off",
09801 ast_channel_name(dialog->owner),
09802 ast_channel_uniqueid(dialog->owner));
09803 append_history(dialog, holdstate ? "Hold" : "Unhold", "%s", ast_str_buffer(req->data));
09804 if (!holdstate) {
09805 ast_clear_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD);
09806 return;
09807 }
09808
09809
09810
09811 ast_clear_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD);
09812
09813 if (sendonly == 1)
09814 ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_ONEDIR);
09815 else if (sendonly == 2)
09816 ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_INACTIVE);
09817 else
09818 ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_ACTIVE);
09819 return;
09820 }
09821
09822
09823 static int get_ip_and_port_from_sdp(struct sip_request *req, const enum media_type media, struct ast_sockaddr *addr)
09824 {
09825 const char *m;
09826 const char *c;
09827 int miterator = req->sdp_start;
09828 int citerator = req->sdp_start;
09829 int x = 0;
09830 int numberofports;
09831 int len;
09832 int af;
09833 char proto[4], host[258] = "";
09834
09835 c = get_sdp_iterate(&citerator, req, "c");
09836 if (sscanf(c, "IN %3s %256s", proto, host) != 2) {
09837 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
09838
09839 }
09840
09841 for (m = get_sdp_iterate(&miterator, req, "m"); !ast_strlen_zero(m); m = get_sdp_iterate(&miterator, req, "m")) {
09842 if ((media == SDP_AUDIO && ((sscanf(m, "audio %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
09843 (sscanf(m, "audio %30u RTP/AVP %n", &x, &len) == 1 && len > 0))) ||
09844 (media == SDP_VIDEO && ((sscanf(m, "video %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
09845 (sscanf(m, "video %30u RTP/AVP %n", &x, &len) == 1 && len > 0)))) {
09846
09847
09848
09849
09850 c = get_sdp_iterate(&citerator, req, "c");
09851 if (!ast_strlen_zero(c)) {
09852 sscanf(c, "IN %3s %256s", proto, host);
09853 }
09854 break;
09855 }
09856 }
09857
09858 if (!strcmp("IP4", proto)) {
09859 af = AF_INET;
09860 } else if (!strcmp("IP6", proto)) {
09861 af = AF_INET6;
09862 } else {
09863 ast_log(LOG_WARNING, "Unknown protocol '%s'.\n", proto);
09864 return -1;
09865 }
09866
09867 if (ast_strlen_zero(host) || x == 0) {
09868 ast_log(LOG_WARNING, "Failed to read an alternate host or port in SDP. Expect %s problems\n", media == SDP_AUDIO ? "audio" : "video");
09869 return -1;
09870 }
09871
09872 if (ast_sockaddr_resolve_first_af(addr, host, 0, af)) {
09873 ast_log(LOG_WARNING, "Could not look up IP address of alternate hostname. Expect %s problems\n", media == SDP_AUDIO? "audio" : "video");
09874 return -1;
09875 }
09876
09877 return 0;
09878 }
09879
09880
09881
09882
09883
09884
09885
09886 static int sockaddr_is_null_or_any(const struct ast_sockaddr *addr)
09887 {
09888 return ast_sockaddr_isnull(addr) || ast_sockaddr_is_any(addr);
09889 }
09890
09891
09892 static int has_media_stream(struct sip_pvt *p, enum media_type m)
09893 {
09894 struct offered_media *offer = NULL;
09895 AST_LIST_TRAVERSE(&p->offered_media, offer, next) {
09896 if (m == offer->type) {
09897 return 1;
09898 }
09899 }
09900 return 0;
09901 }
09902
09903
09904
09905
09906
09907
09908 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action)
09909 {
09910 int res = 0;
09911
09912
09913 int start = req->sdp_start;
09914 int next = start;
09915 int iterator = start;
09916
09917
09918 char type = '\0';
09919 const char *value = NULL;
09920 const char *m = NULL;
09921 const char *nextm = NULL;
09922 int len = -1;
09923 struct offered_media *offer;
09924
09925
09926 struct ast_sockaddr sessionsa;
09927 struct ast_sockaddr audiosa;
09928 struct ast_sockaddr videosa;
09929 struct ast_sockaddr textsa;
09930 struct ast_sockaddr imagesa;
09931 struct ast_sockaddr *sa = NULL;
09932 struct ast_sockaddr *vsa = NULL;
09933 struct ast_sockaddr *tsa = NULL;
09934 struct ast_sockaddr *isa = NULL;
09935 int portno = -1;
09936 int vportno = -1;
09937 int tportno = -1;
09938 int udptlportno = -1;
09939
09940
09941 struct ast_format_cap *peercapability = ast_format_cap_alloc_nolock();
09942 struct ast_format_cap *vpeercapability = ast_format_cap_alloc_nolock();
09943 struct ast_format_cap *tpeercapability = ast_format_cap_alloc_nolock();
09944
09945 int peernoncodeccapability = 0, vpeernoncodeccapability = 0, tpeernoncodeccapability = 0;
09946
09947 struct ast_rtp_codecs newaudiortp = { 0, }, newvideortp = { 0, }, newtextrtp = { 0, };
09948 struct ast_format_cap *newjointcapability = ast_format_cap_alloc_nolock();
09949 struct ast_format_cap *newpeercapability = ast_format_cap_alloc_nolock();
09950 int newnoncodeccapability;
09951
09952 const char *codecs;
09953 int codec;
09954
09955
09956 int secure_audio = FALSE;
09957 int secure_video = FALSE;
09958
09959
09960 int sendonly = -1;
09961 int numberofports;
09962 int last_rtpmap_codec = 0;
09963 int red_data_pt[10];
09964 int red_num_gen = 0;
09965 char red_fmtp[100] = "empty";
09966 int debug = sip_debug_test_pvt(p);
09967
09968
09969 char buf[SIPBUFSIZE];
09970 struct ast_format tmp_fmt;
09971
09972
09973
09974 if (!p->rtp) {
09975 ast_log(LOG_ERROR, "Got SDP but have no RTP session allocated.\n");
09976 res = -1;
09977 goto process_sdp_cleanup;
09978 }
09979 if (!peercapability || !vpeercapability || !tpeercapability || !newpeercapability || !newjointcapability) {
09980 res = -1;
09981 goto process_sdp_cleanup;
09982 }
09983
09984 if (ast_rtp_codecs_payloads_initialize(&newaudiortp) || ast_rtp_codecs_payloads_initialize(&newvideortp) ||
09985 ast_rtp_codecs_payloads_initialize(&newtextrtp)) {
09986 res = -1;
09987 goto process_sdp_cleanup;
09988 }
09989
09990
09991 p->lastrtprx = p->lastrtptx = time(NULL);
09992
09993 offered_media_list_destroy(p);
09994
09995
09996 nextm = get_sdp_iterate(&next, req, "m");
09997 if (ast_strlen_zero(nextm)) {
09998 ast_log(LOG_WARNING, "Insufficient information for SDP (m= not found)\n");
09999 res = -1;
10000 goto process_sdp_cleanup;
10001 }
10002
10003
10004 while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
10005 int processed = FALSE;
10006 switch (type) {
10007 case 'o':
10008
10009
10010
10011 if (!process_sdp_o(value, p)) {
10012 res = (p->session_modify == FALSE) ? 0 : -1;
10013 goto process_sdp_cleanup;
10014 }
10015 processed = TRUE;
10016 break;
10017 case 'c':
10018 if (process_sdp_c(value, &sessionsa)) {
10019 processed = TRUE;
10020 sa = &sessionsa;
10021 vsa = sa;
10022 tsa = sa;
10023 isa = sa;
10024 }
10025 break;
10026 case 'a':
10027 if (process_sdp_a_sendonly(value, &sendonly)) {
10028 processed = TRUE;
10029 }
10030 else if (process_sdp_a_audio(value, p, &newaudiortp, &last_rtpmap_codec))
10031 processed = TRUE;
10032 else if (process_sdp_a_video(value, p, &newvideortp, &last_rtpmap_codec))
10033 processed = TRUE;
10034 else if (process_sdp_a_text(value, p, &newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec))
10035 processed = TRUE;
10036 else if (process_sdp_a_image(value, p))
10037 processed = TRUE;
10038
10039 if (process_sdp_a_ice(value, p, p->rtp)) {
10040 processed = TRUE;
10041 }
10042 if (process_sdp_a_ice(value, p, p->vrtp)) {
10043 processed = TRUE;
10044 }
10045 if (process_sdp_a_ice(value, p, p->trtp)) {
10046 processed = TRUE;
10047 }
10048
10049 if (process_sdp_a_dtls(value, p, p->rtp)) {
10050 processed = TRUE;
10051 }
10052 if (process_sdp_a_dtls(value, p, p->vrtp)) {
10053 processed = TRUE;
10054 }
10055 if (process_sdp_a_dtls(value, p, p->trtp)) {
10056 processed = TRUE;
10057 }
10058
10059 break;
10060 }
10061
10062 ast_debug(3, "Processing session-level SDP %c=%s... %s\n", type, value, (processed == TRUE)? "OK." : "UNSUPPORTED OR FAILED.");
10063 }
10064
10065
10066 p->novideo = TRUE;
10067 p->notext = TRUE;
10068
10069
10070 while (!ast_strlen_zero(nextm)) {
10071 int audio = FALSE;
10072 int video = FALSE;
10073 int image = FALSE;
10074 int text = FALSE;
10075 int processed_crypto = FALSE;
10076 char protocol[18] = {0,};
10077 int x;
10078 struct ast_rtp_engine_dtls *dtls;
10079
10080 numberofports = 0;
10081 len = -1;
10082 start = next;
10083 m = nextm;
10084 iterator = next;
10085 nextm = get_sdp_iterate(&next, req, "m");
10086
10087 if (!(offer = ast_calloc(1, sizeof(*offer)))) {
10088 ast_log(LOG_WARNING, "Failed to allocate memory for SDP offer list\n");
10089 res = -1;
10090 goto process_sdp_cleanup;
10091 }
10092 AST_LIST_INSERT_TAIL(&p->offered_media, offer, next);
10093 offer->type = SDP_UNKNOWN;
10094
10095
10096 if (strncmp(m, "audio ", 6) == 0) {
10097 if ((sscanf(m, "audio %30u/%30u %17s %n", &x, &numberofports, protocol, &len) == 3 && len > 0) ||
10098 (sscanf(m, "audio %30u %17s %n", &x, protocol, &len) == 2 && len > 0)) {
10099 codecs = m + len;
10100
10101
10102 if (!(offer->decline_m_line = ast_malloc(10 + strlen(protocol) + 1 + strlen(codecs) + 3))) {
10103 ast_log(LOG_WARNING, "Failed to allocate memory for SDP offer declination\n");
10104 res = -1;
10105 goto process_sdp_cleanup;
10106 }
10107
10108 sprintf(offer->decline_m_line, "m=audio 0 %s %s\r\n", protocol, codecs);
10109
10110 if (x == 0) {
10111 ast_log(LOG_WARNING, "Ignoring audio media offer because port number is zero\n");
10112 continue;
10113 }
10114
10115 if (has_media_stream(p, SDP_AUDIO)) {
10116 ast_log(LOG_WARNING, "Declining non-primary audio stream: %s\n", m);
10117 continue;
10118 }
10119
10120
10121 if (numberofports > 1) {
10122 ast_log(LOG_WARNING, "%d ports offered for audio media, not supported by Asterisk. Will try anyway...\n", numberofports);
10123 }
10124
10125 if ((!strcmp(protocol, "RTP/SAVPF") || !strcmp(protocol, "UDP/TLS/RTP/SAVPF")) && !ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {
10126 if (req->method != SIP_RESPONSE) {
10127 ast_log(LOG_NOTICE, "Received SAVPF profle in audio offer but AVPF is not enabled, enabling: %s\n", m);
10128 secure_audio = 1;
10129 ast_set_flag(&p->flags[2], SIP_PAGE3_USE_AVPF);
10130 }
10131 else {
10132
10133 ast_log(LOG_WARNING, "Received SAVPF profle in audio answer but AVPF is not enabled: %s\n", m);
10134 continue;
10135 }
10136 } else if ((!strcmp(protocol, "RTP/SAVP") || !strcmp(protocol, "UDP/TLS/RTP/SAVP")) && ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {
10137 if (req->method != SIP_RESPONSE) {
10138 ast_log(LOG_NOTICE, "Received SAVP profle in audio offer but AVPF is enabled, disabling: %s\n", m);
10139 secure_audio = 1;
10140 ast_clear_flag(&p->flags[2], SIP_PAGE3_USE_AVPF);
10141 }
10142 else {
10143 ast_log(LOG_WARNING, "Received SAVP profile in audio offer but AVPF is enabled: %s\n", m);
10144 continue;
10145 }
10146 } else if (!strcmp(protocol, "UDP/TLS/RTP/SAVP") || !strcmp(protocol, "UDP/TLS/RTP/SAVPF")) {
10147 secure_audio = 1;
10148
10149 if (p->srtp) {
10150 ast_set_flag(p->srtp, SRTP_CRYPTO_OFFER_OK);
10151 }
10152 } else if (!strcmp(protocol, "RTP/SAVP") || !strcmp(protocol, "RTP/SAVPF")) {
10153 secure_audio = 1;
10154 } else if (!strcmp(protocol, "RTP/AVPF") && !ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {
10155 if (req->method != SIP_RESPONSE) {
10156 ast_log(LOG_NOTICE, "Received AVPF profile in audio offer but AVPF is not enabled, enabling: %s\n", m);
10157 ast_set_flag(&p->flags[2], SIP_PAGE3_USE_AVPF);
10158 }
10159 else {
10160 ast_log(LOG_WARNING, "Received AVP profile in audio answer but AVPF is enabled: %s\n", m);
10161 continue;
10162 }
10163 } else if (!strcmp(protocol, "RTP/AVP") && ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {
10164 if (req->method != SIP_RESPONSE) {
10165 ast_log(LOG_NOTICE, "Received AVP profile in audio answer but AVPF is enabled, disabling: %s\n", m);
10166 ast_clear_flag(&p->flags[2], SIP_PAGE3_USE_AVPF);
10167 }
10168 else {
10169 ast_log(LOG_WARNING, "Received AVP profile in audio answer but AVPF is enabled: %s\n", m);
10170 continue;
10171 }
10172 } else if ((!strcmp(protocol, "UDP/TLS/RTP/SAVP") || !strcmp(protocol, "UDP/TLS/RTP/SAVPF")) &&
10173 (!(dtls = ast_rtp_instance_get_dtls(p->rtp)) || !dtls->active(p->rtp))) {
10174 ast_log(LOG_WARNING, "Received UDP/TLS in audio offer but DTLS is not enabled: %s\n", m);
10175 continue;
10176 } else if (strcmp(protocol, "RTP/AVP") && strcmp(protocol, "RTP/AVPF")) {
10177 ast_log(LOG_WARNING, "Unknown RTP profile in audio offer: %s\n", m);
10178 continue;
10179 }
10180
10181 audio = TRUE;
10182 offer->type = SDP_AUDIO;
10183 portno = x;
10184
10185
10186 for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
10187 if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
10188 ast_log(LOG_WARNING, "Invalid syntax in RTP audio format list: %s\n", codecs);
10189 res = -1;
10190 goto process_sdp_cleanup;
10191 }
10192 if (debug) {
10193 ast_verbose("Found RTP audio format %d\n", codec);
10194 }
10195
10196 ast_rtp_codecs_payloads_set_m_type(&newaudiortp, NULL, codec);
10197 }
10198 } else {
10199 ast_log(LOG_WARNING, "Rejecting audio media offer due to invalid or unsupported syntax: %s\n", m);
10200 res = -1;
10201 goto process_sdp_cleanup;
10202 }
10203 }
10204
10205 else if (strncmp(m, "video ", 6) == 0) {
10206 if ((sscanf(m, "video %30u/%30u %17s %n", &x, &numberofports, protocol, &len) == 3 && len > 0) ||
10207 (sscanf(m, "video %30u %17s %n", &x, protocol, &len) == 2 && len > 0)) {
10208 codecs = m + len;
10209
10210
10211 if (!(offer->decline_m_line = ast_malloc(10 + strlen(protocol) + 1 + strlen(codecs) + 3))) {
10212 ast_log(LOG_WARNING, "Failed to allocate memory for SDP offer declination\n");
10213 res = -1;
10214 goto process_sdp_cleanup;
10215 }
10216
10217 sprintf(offer->decline_m_line, "m=video 0 %s %s\r\n", protocol, codecs);
10218
10219 if (x == 0) {
10220 ast_log(LOG_WARNING, "Ignoring video stream offer because port number is zero\n");
10221 continue;
10222 }
10223
10224
10225 if (numberofports > 1) {
10226 ast_log(LOG_WARNING, "%d ports offered for video stream, not supported by Asterisk. Will try anyway...\n", numberofports);
10227 }
10228
10229 if (has_media_stream(p, SDP_VIDEO)) {
10230 ast_log(LOG_WARNING, "Declining non-primary video stream: %s\n", m);
10231 continue;
10232 }
10233
10234 if ((!strcmp(protocol, "RTP/SAVPF") || !strcmp(protocol, "UDP/TLS/RTP/SAVPF")) && !ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {
10235 ast_log(LOG_WARNING, "Received SAVPF profle in video offer but AVPF is not enabled: %s\n", m);
10236 continue;
10237 } else if ((!strcmp(protocol, "RTP/SAVP") || !strcmp(protocol, "UDP/TLS/RTP/SAVP")) && ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {
10238 ast_log(LOG_WARNING, "Received SAVP profile in video offer but AVPF is enabled: %s\n", m);
10239 continue;
10240 } else if (!strcmp(protocol, "UDP/TLS/RTP/SAVP") || !strcmp(protocol, "UDP/TLS/RTP/SAVPF")) {
10241 secure_video = 1;
10242
10243 if (p->vsrtp || (p->vsrtp = sip_srtp_alloc())) {
10244 ast_set_flag(p->vsrtp, SRTP_CRYPTO_OFFER_OK);
10245 }
10246 } else if (!strcmp(protocol, "RTP/SAVP") || !strcmp(protocol, "RTP/SAVPF")) {
10247 secure_video = 1;
10248 } else if (!strcmp(protocol, "RTP/AVPF") && !ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {
10249 ast_log(LOG_WARNING, "Received AVPF profile in video offer but AVPF is not enabled: %s\n", m);
10250 continue;
10251 } else if (!strcmp(protocol, "RTP/AVP") && ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {
10252 ast_log(LOG_WARNING, "Received AVP profile in video offer but AVPF is enabled: %s\n", m);
10253 continue;
10254 } else if (strcmp(protocol, "RTP/AVP") && strcmp(protocol, "RTP/AVPF")) {
10255 ast_log(LOG_WARNING, "Unknown RTP profile in video offer: %s\n", m);
10256 continue;
10257 }
10258
10259 video = TRUE;
10260 p->novideo = FALSE;
10261 offer->type = SDP_VIDEO;
10262 vportno = x;
10263
10264
10265 for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
10266 if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
10267 ast_log(LOG_WARNING, "Invalid syntax in RTP video format list: %s\n", codecs);
10268 res = -1;
10269 goto process_sdp_cleanup;
10270 }
10271 if (debug) {
10272 ast_verbose("Found RTP video format %d\n", codec);
10273 }
10274 ast_rtp_codecs_payloads_set_m_type(&newvideortp, NULL, codec);
10275 }
10276 } else {
10277 ast_log(LOG_WARNING, "Rejecting video media offer due to invalid or unsupported syntax: %s\n", m);
10278 res = -1;
10279 goto process_sdp_cleanup;
10280 }
10281 }
10282
10283 else if (strncmp(m, "text ", 5) == 0) {
10284 if ((sscanf(m, "text %30u/%30u %17s %n", &x, &numberofports, protocol, &len) == 3 && len > 0) ||
10285 (sscanf(m, "text %30u %17s %n", &x, protocol, &len) == 2 && len > 0)) {
10286 codecs = m + len;
10287
10288
10289 if (!(offer->decline_m_line = ast_malloc(9 + strlen(protocol) + 1 + strlen(codecs) + 3))) {
10290 ast_log(LOG_WARNING, "Failed to allocate memory for SDP offer declination\n");
10291 res = -1;
10292 goto process_sdp_cleanup;
10293 }
10294
10295 sprintf(offer->decline_m_line, "m=text 0 %s %s\r\n", protocol, codecs);
10296
10297 if (x == 0) {
10298 ast_log(LOG_WARNING, "Ignoring text stream offer because port number is zero\n");
10299 continue;
10300 }
10301
10302
10303 if (numberofports > 1) {
10304 ast_log(LOG_WARNING, "%d ports offered for text stream, not supported by Asterisk. Will try anyway...\n", numberofports);
10305 }
10306
10307 if (!strcmp(protocol, "RTP/AVPF") && !ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {
10308 ast_log(LOG_WARNING, "Received AVPF profile in text offer but AVPF is not enabled: %s\n", m);
10309 continue;
10310 } else if (!strcmp(protocol, "RTP/AVP") && ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {
10311 ast_log(LOG_WARNING, "Received AVP profile in text offer but AVPF is enabled: %s\n", m);
10312 continue;
10313 } else if (strcmp(protocol, "RTP/AVP") && strcmp(protocol, "RTP/AVPF")) {
10314 ast_log(LOG_WARNING, "Unknown RTP profile in text offer: %s\n", m);
10315 continue;
10316 }
10317
10318 if (has_media_stream(p, SDP_TEXT)) {
10319 ast_log(LOG_WARNING, "Declining non-primary text stream: %s\n", m);
10320 continue;
10321 }
10322
10323 text = TRUE;
10324 p->notext = FALSE;
10325 offer->type = SDP_TEXT;
10326 tportno = x;
10327
10328
10329 for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
10330 if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
10331 ast_log(LOG_WARNING, "Invalid syntax in RTP video format list: %s\n", codecs);
10332 res = -1;
10333 goto process_sdp_cleanup;
10334 }
10335 if (debug) {
10336 ast_verbose("Found RTP text format %d\n", codec);
10337 }
10338 ast_rtp_codecs_payloads_set_m_type(&newtextrtp, NULL, codec);
10339 }
10340 } else {
10341 ast_log(LOG_WARNING, "Rejecting text stream offer due to invalid or unsupported syntax: %s\n", m);
10342 res = -1;
10343 goto process_sdp_cleanup;
10344 }
10345 }
10346
10347 else if (strncmp(m, "image ", 6) == 0) {
10348 if (((sscanf(m, "image %30u udptl t38%n", &x, &len) == 1 && len > 0) ||
10349 (sscanf(m, "image %30u UDPTL t38%n", &x, &len) == 1 && len > 0))) {
10350
10351
10352 if (!(offer->decline_m_line = ast_malloc(22))) {
10353 ast_log(LOG_WARNING, "Failed to allocate memory for SDP offer declination\n");
10354 res = -1;
10355 goto process_sdp_cleanup;
10356 }
10357
10358 strcpy(offer->decline_m_line, "m=image 0 udptl t38\r\n");
10359
10360 if (x == 0) {
10361 ast_log(LOG_WARNING, "Ignoring image stream offer because port number is zero\n");
10362 continue;
10363 }
10364
10365 if (initialize_udptl(p)) {
10366 ast_log(LOG_WARNING, "Failed to initialize UDPTL, declining image stream\n");
10367 continue;
10368 }
10369
10370 if (has_media_stream(p, SDP_IMAGE)) {
10371 ast_log(LOG_WARNING, "Declining non-primary image stream: %s\n", m);
10372 continue;
10373 }
10374
10375 image = TRUE;
10376 if (debug) {
10377 ast_verbose("Got T.38 offer in SDP in dialog %s\n", p->callid);
10378 }
10379
10380 offer->type = SDP_IMAGE;
10381 udptlportno = x;
10382
10383 if (p->t38.state != T38_ENABLED) {
10384 memset(&p->t38.their_parms, 0, sizeof(p->t38.their_parms));
10385
10386
10387
10388 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
10389 }
10390 } else if (sscanf(m, "image %30u %17s t38%n", &x, protocol, &len) == 2 && len > 0) {
10391 ast_log(LOG_WARNING, "Declining image stream due to unsupported transport: %s\n", m);
10392
10393
10394 if (!(offer->decline_m_line = ast_malloc(10 + strlen(protocol) + 7))) {
10395 ast_log(LOG_WARNING, "Failed to allocate memory for SDP offer declination\n");
10396 res = -1;
10397 goto process_sdp_cleanup;
10398 }
10399
10400 sprintf(offer->decline_m_line, "m=image 0 %s t38\r\n", protocol);
10401 continue;
10402 } else {
10403 ast_log(LOG_WARNING, "Rejecting image media offer due to invalid or unsupported syntax: %s\n", m);
10404 res = -1;
10405 goto process_sdp_cleanup;
10406 }
10407 } else {
10408 char type[20] = {0,};
10409 if ((sscanf(m, "%19s %30u/%30u %n", type, &x, &numberofports, &len) == 3 && len > 0) ||
10410 (sscanf(m, "%19s %30u %n", type, &x, &len) == 2 && len > 0)) {
10411
10412
10413 if (!(offer->decline_m_line = ast_malloc(2 + strlen(type) + 3 + strlen(m + len) + 3))) {
10414 ast_log(LOG_WARNING, "Failed to allocate memory for SDP offer declination\n");
10415 res = -1;
10416 goto process_sdp_cleanup;
10417 }
10418
10419 sprintf(offer->decline_m_line, "m=%s 0 %s\r\n", type, m + len);
10420 continue;
10421 } else {
10422 ast_log(LOG_WARNING, "Unsupported top-level media type in offer: %s\n", m);
10423 res = -1;
10424 goto process_sdp_cleanup;
10425 }
10426 }
10427
10428
10429 while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
10430 int processed = FALSE;
10431
10432 switch (type) {
10433 case 'c':
10434 if (audio) {
10435 if (process_sdp_c(value, &audiosa)) {
10436 processed = TRUE;
10437 sa = &audiosa;
10438 }
10439 } else if (video) {
10440 if (process_sdp_c(value, &videosa)) {
10441 processed = TRUE;
10442 vsa = &videosa;
10443 }
10444 } else if (text) {
10445 if (process_sdp_c(value, &textsa)) {
10446 processed = TRUE;
10447 tsa = &textsa;
10448 }
10449 } else if (image) {
10450 if (process_sdp_c(value, &imagesa)) {
10451 processed = TRUE;
10452 isa = &imagesa;
10453 }
10454 }
10455 break;
10456 case 'a':
10457
10458 if (audio) {
10459 if (process_sdp_a_ice(value, p, p->rtp)) {
10460 processed = TRUE;
10461 } else if (process_sdp_a_dtls(value, p, p->rtp)) {
10462 processed = TRUE;
10463 } else if (process_sdp_a_sendonly(value, &sendonly)) {
10464 processed = TRUE;
10465 } else if (!processed_crypto && process_crypto(p, p->rtp, &p->srtp, value)) {
10466 processed_crypto = TRUE;
10467 processed = TRUE;
10468 } else if (process_sdp_a_audio(value, p, &newaudiortp, &last_rtpmap_codec)) {
10469 processed = TRUE;
10470 }
10471 }
10472
10473 else if (video) {
10474 if (process_sdp_a_ice(value, p, p->vrtp)) {
10475 processed = TRUE;
10476 } else if (process_sdp_a_dtls(value, p, p->vrtp)) {
10477 processed = TRUE;
10478 } else if (!processed_crypto && process_crypto(p, p->vrtp, &p->vsrtp, value)) {
10479 processed_crypto = TRUE;
10480 processed = TRUE;
10481 } else if (process_sdp_a_video(value, p, &newvideortp, &last_rtpmap_codec)) {
10482 processed = TRUE;
10483 }
10484 }
10485
10486 else if (text) {
10487 if (process_sdp_a_ice(value, p, p->trtp)) {
10488 processed = TRUE;
10489 } else if (process_sdp_a_text(value, p, &newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec)) {
10490 processed = TRUE;
10491 } else if (!processed_crypto && process_crypto(p, p->trtp, &p->tsrtp, value)) {
10492 processed_crypto = TRUE;
10493 processed = TRUE;
10494 }
10495 }
10496
10497 else if (image) {
10498 if (process_sdp_a_image(value, p))
10499 processed = TRUE;
10500 }
10501 break;
10502 }
10503
10504 ast_debug(3, "Processing media-level (%s) SDP %c=%s... %s\n",
10505 (audio == TRUE)? "audio" : (video == TRUE)? "video" : (text == TRUE)? "text" : "image",
10506 type, value,
10507 (processed == TRUE)? "OK." : "UNSUPPORTED OR FAILED.");
10508 }
10509
10510
10511 if (audio && secure_audio && !processed_crypto) {
10512 ast_log(LOG_WARNING, "Rejecting secure audio stream without encryption details: %s\n", m);
10513 return -1;
10514 } else if (video && secure_video && !processed_crypto) {
10515 ast_log(LOG_WARNING, "Rejecting secure video stream without encryption details: %s\n", m);
10516 return -1;
10517 }
10518 }
10519
10520
10521 if (!sa && !vsa && !tsa && !isa) {
10522 ast_log(LOG_WARNING, "Insufficient information in SDP (c=)...\n");
10523 res = -1;
10524 goto process_sdp_cleanup;
10525 }
10526
10527 if ((portno == -1) &&
10528 (vportno == -1) &&
10529 (tportno == -1) &&
10530 (udptlportno == -1)) {
10531 ast_log(LOG_WARNING, "Failing due to no acceptable offer found\n");
10532 res = -1;
10533 goto process_sdp_cleanup;
10534 }
10535
10536 if (secure_audio && !(p->srtp && (ast_test_flag(p->srtp, SRTP_CRYPTO_OFFER_OK)))) {
10537 ast_log(LOG_WARNING, "Can't provide secure audio requested in SDP offer\n");
10538 res = -1;
10539 goto process_sdp_cleanup;
10540 }
10541
10542 if (!secure_audio && p->srtp) {
10543 ast_log(LOG_WARNING, "We are requesting SRTP for audio, but they responded without it!\n");
10544 res = -1;
10545 goto process_sdp_cleanup;
10546 }
10547
10548 if (secure_video && !(p->vsrtp && (ast_test_flag(p->vsrtp, SRTP_CRYPTO_OFFER_OK)))) {
10549 ast_log(LOG_WARNING, "Can't provide secure video requested in SDP offer\n");
10550 res = -1;
10551 goto process_sdp_cleanup;
10552 }
10553
10554 if (!p->novideo && !secure_video && p->vsrtp) {
10555 ast_log(LOG_WARNING, "We are requesting SRTP for video, but they responded without it!\n");
10556 res = -1;
10557 goto process_sdp_cleanup;
10558 }
10559
10560 if (!(secure_audio || secure_video) && ast_test_flag(&p->flags[1], SIP_PAGE2_USE_SRTP)) {
10561 ast_log(LOG_WARNING, "Matched device setup to use SRTP, but request was not!\n");
10562 res = -1;
10563 goto process_sdp_cleanup;
10564 }
10565
10566 if (udptlportno == -1) {
10567 change_t38_state(p, T38_DISABLED);
10568 }
10569
10570
10571 ast_rtp_codecs_payload_formats(&newaudiortp, peercapability, &peernoncodeccapability);
10572 ast_rtp_codecs_payload_formats(&newvideortp, vpeercapability, &vpeernoncodeccapability);
10573 ast_rtp_codecs_payload_formats(&newtextrtp, tpeercapability, &tpeernoncodeccapability);
10574
10575 ast_format_cap_append(newpeercapability, peercapability);
10576 ast_format_cap_append(newpeercapability, vpeercapability);
10577 ast_format_cap_append(newpeercapability, tpeercapability);
10578
10579 ast_format_cap_joint_copy(p->caps, newpeercapability, newjointcapability);
10580 if (ast_format_cap_is_empty(newjointcapability) && udptlportno == -1) {
10581 ast_log(LOG_NOTICE, "No compatible codecs, not accepting this offer!\n");
10582
10583 res = -1;
10584 goto process_sdp_cleanup;
10585 }
10586
10587 newnoncodeccapability = p->noncodeccapability & peernoncodeccapability;
10588
10589 if (debug) {
10590
10591 char s1[SIPBUFSIZE], s2[SIPBUFSIZE], s3[SIPBUFSIZE], s4[SIPBUFSIZE], s5[SIPBUFSIZE];
10592
10593 ast_verbose("Capabilities: us - %s, peer - audio=%s/video=%s/text=%s, combined - %s\n",
10594 ast_getformatname_multiple(s1, SIPBUFSIZE, p->caps),
10595 ast_getformatname_multiple(s2, SIPBUFSIZE, peercapability),
10596 ast_getformatname_multiple(s3, SIPBUFSIZE, vpeercapability),
10597 ast_getformatname_multiple(s4, SIPBUFSIZE, tpeercapability),
10598 ast_getformatname_multiple(s5, SIPBUFSIZE, newjointcapability));
10599 }
10600 if (debug) {
10601 struct ast_str *s1 = ast_str_alloca(SIPBUFSIZE);
10602 struct ast_str *s2 = ast_str_alloca(SIPBUFSIZE);
10603 struct ast_str *s3 = ast_str_alloca(SIPBUFSIZE);
10604
10605 ast_verbose("Non-codec capabilities (dtmf): us - %s, peer - %s, combined - %s\n",
10606 ast_rtp_lookup_mime_multiple2(s1, NULL, p->noncodeccapability, 0, 0),
10607 ast_rtp_lookup_mime_multiple2(s2, NULL, peernoncodeccapability, 0, 0),
10608 ast_rtp_lookup_mime_multiple2(s3, NULL, newnoncodeccapability, 0, 0));
10609 }
10610
10611 if (portno != -1 || vportno != -1 || tportno != -1) {
10612
10613
10614 ast_format_cap_copy(p->jointcaps, newjointcapability);
10615 ast_format_cap_copy(p->peercaps, newpeercapability);
10616 p->jointnoncodeccapability = newnoncodeccapability;
10617
10618
10619 if (ast_test_flag(&p->flags[1], SIP_PAGE2_PREFERRED_CODEC)) {
10620 ast_codec_choose(&p->prefs, p->jointcaps, 1, &tmp_fmt);
10621 ast_format_cap_set(p->jointcaps, &tmp_fmt);
10622 }
10623 }
10624
10625
10626 if (p->rtp) {
10627 if (sa && portno > 0) {
10628 start_ice(p->rtp);
10629 ast_sockaddr_set_port(sa, portno);
10630 ast_rtp_instance_set_remote_address(p->rtp, sa);
10631 if (debug) {
10632 ast_verbose("Peer audio RTP is at port %s\n",
10633 ast_sockaddr_stringify(sa));
10634 }
10635
10636 ast_rtp_codecs_payloads_copy(&newaudiortp, ast_rtp_instance_get_codecs(p->rtp), p->rtp);
10637
10638
10639 ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_RTCP, 1);
10640
10641 if (p->owner) {
10642 ast_channel_set_fd(p->owner, 1, ast_rtp_instance_fd(p->rtp, 1));
10643 }
10644
10645 if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) {
10646 ast_clear_flag(&p->flags[0], SIP_DTMF);
10647 if (newnoncodeccapability & AST_RTP_DTMF) {
10648
10649 ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
10650
10651 ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF, 1);
10652 ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
10653 } else {
10654 ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
10655 }
10656 }
10657 } else if (udptlportno > 0) {
10658 if (debug)
10659 ast_verbose("Got T.38 Re-invite without audio. Keeping RTP active during T.38 session.\n");
10660
10661 if (p->owner) {
10662 ast_channel_set_fd(p->owner, 1, -1);
10663 }
10664
10665 ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_RTCP, 0);
10666 } else {
10667 ast_rtp_instance_stop(p->rtp);
10668 if (debug)
10669 ast_verbose("Peer doesn't provide audio\n");
10670 }
10671 }
10672
10673
10674 if (p->vrtp) {
10675 if (vsa && vportno > 0) {
10676 start_ice(p->vrtp);
10677 ast_sockaddr_set_port(vsa, vportno);
10678 ast_rtp_instance_set_remote_address(p->vrtp, vsa);
10679 if (debug) {
10680 ast_verbose("Peer video RTP is at port %s\n",
10681 ast_sockaddr_stringify(vsa));
10682 }
10683 ast_rtp_codecs_payloads_copy(&newvideortp, ast_rtp_instance_get_codecs(p->vrtp), p->vrtp);
10684 } else {
10685 ast_rtp_instance_stop(p->vrtp);
10686 if (debug)
10687 ast_verbose("Peer doesn't provide video\n");
10688 }
10689 }
10690
10691
10692 if (p->trtp) {
10693 if (tsa && tportno > 0) {
10694 start_ice(p->trtp);
10695 ast_sockaddr_set_port(tsa, tportno);
10696 ast_rtp_instance_set_remote_address(p->trtp, tsa);
10697 if (debug) {
10698 ast_verbose("Peer T.140 RTP is at port %s\n",
10699 ast_sockaddr_stringify(tsa));
10700 }
10701 if (ast_format_cap_iscompatible(p->jointcaps, ast_format_set(&tmp_fmt, AST_FORMAT_T140RED, 0))) {
10702 p->red = 1;
10703 ast_rtp_red_init(p->trtp, 300, red_data_pt, 2);
10704 } else {
10705 p->red = 0;
10706 }
10707 ast_rtp_codecs_payloads_copy(&newtextrtp, ast_rtp_instance_get_codecs(p->trtp), p->trtp);
10708 } else {
10709 ast_rtp_instance_stop(p->trtp);
10710 if (debug)
10711 ast_verbose("Peer doesn't provide T.140\n");
10712 }
10713 }
10714
10715
10716 if (p->udptl) {
10717 if (isa && udptlportno > 0) {
10718 if (ast_test_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP) && ast_test_flag(&p->flags[1], SIP_PAGE2_UDPTL_DESTINATION)) {
10719 ast_rtp_instance_get_remote_address(p->rtp, isa);
10720 if (!ast_sockaddr_isnull(isa) && debug) {
10721 ast_debug(1, "Peer T.38 UDPTL is set behind NAT and with destination, destination address now %s\n", ast_sockaddr_stringify(isa));
10722 }
10723 }
10724 ast_sockaddr_set_port(isa, udptlportno);
10725 ast_udptl_set_peer(p->udptl, isa);
10726 if (debug)
10727 ast_debug(1,"Peer T.38 UDPTL is at port %s\n", ast_sockaddr_stringify(isa));
10728
10729
10730 if (!ast_udptl_get_far_max_datagram(p->udptl)) {
10731
10732 ast_udptl_set_far_max_datagram(p->udptl, 0);
10733 }
10734
10735
10736 if ((t38action == SDP_T38_ACCEPT) &&
10737 (p->t38.state == T38_LOCAL_REINVITE)) {
10738 change_t38_state(p, T38_ENABLED);
10739 } else if ((t38action == SDP_T38_INITIATE) &&
10740 p->owner && p->lastinvite) {
10741 change_t38_state(p, T38_PEER_REINVITE);
10742
10743 if (ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_T38)) {
10744 ast_channel_lock(p->owner);
10745 if (strcmp(ast_channel_exten(p->owner), "fax")) {
10746 const char *target_context = S_OR(ast_channel_macrocontext(p->owner), ast_channel_context(p->owner));
10747 ast_channel_unlock(p->owner);
10748 if (ast_exists_extension(p->owner, target_context, "fax", 1,
10749 S_COR(ast_channel_caller(p->owner)->id.number.valid, ast_channel_caller(p->owner)->id.number.str, NULL))) {
10750 ast_verb(2, "Redirecting '%s' to fax extension due to peer T.38 re-INVITE\n", ast_channel_name(p->owner));
10751 pbx_builtin_setvar_helper(p->owner, "FAXEXTEN", ast_channel_exten(p->owner));
10752 if (ast_async_goto(p->owner, target_context, "fax", 1)) {
10753 ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", ast_channel_name(p->owner), target_context);
10754 }
10755 } else {
10756 ast_log(LOG_NOTICE, "T.38 re-INVITE detected but no fax extension\n");
10757 }
10758 } else {
10759 ast_channel_unlock(p->owner);
10760 }
10761 }
10762 }
10763 } else {
10764 change_t38_state(p, T38_DISABLED);
10765 ast_udptl_stop(p->udptl);
10766 if (debug)
10767 ast_debug(1, "Peer doesn't provide T.38 UDPTL\n");
10768 }
10769 }
10770
10771 if ((portno == -1) && (p->t38.state != T38_DISABLED) && (p->t38.state != T38_REJECTED)) {
10772 ast_debug(3, "Have T.38 but no audio, accepting offer anyway\n");
10773 res = 0;
10774 goto process_sdp_cleanup;
10775 }
10776
10777
10778 ast_debug(2, "We're settling with these formats: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, p->jointcaps));
10779
10780 if (!p->owner) {
10781 res = 0;
10782 goto process_sdp_cleanup;
10783 }
10784
10785 ast_debug(4, "We have an owner, now see if we need to change this call\n");
10786 if (ast_format_cap_has_type(p->jointcaps, AST_FORMAT_TYPE_AUDIO)) {
10787 if (debug) {
10788 char s1[SIPBUFSIZE], s2[SIPBUFSIZE];
10789 ast_debug(1, "Setting native formats after processing SDP. peer joint formats %s, old nativeformats %s\n",
10790 ast_getformatname_multiple(s1, SIPBUFSIZE, p->jointcaps),
10791 ast_getformatname_multiple(s2, SIPBUFSIZE, ast_channel_nativeformats(p->owner)));
10792 }
10793
10794 ast_codec_choose(&p->prefs, p->jointcaps, 1, &tmp_fmt);
10795
10796 ast_format_cap_set(ast_channel_nativeformats(p->owner), &tmp_fmt);
10797 ast_format_cap_joint_append(p->caps, vpeercapability, ast_channel_nativeformats(p->owner));
10798 ast_format_cap_joint_append(p->caps, tpeercapability, ast_channel_nativeformats(p->owner));
10799
10800 ast_set_read_format(p->owner, ast_channel_readformat(p->owner));
10801 ast_set_write_format(p->owner, ast_channel_writeformat(p->owner));
10802 }
10803
10804 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) && (!ast_sockaddr_isnull(sa) || !ast_sockaddr_isnull(vsa) || !ast_sockaddr_isnull(tsa) || !ast_sockaddr_isnull(isa)) && (!sendonly || sendonly == -1)) {
10805 ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
10806
10807 ast_queue_frame(p->owner, &ast_null_frame);
10808 change_hold_state(p, req, FALSE, sendonly);
10809 } else if ((sockaddr_is_null_or_any(sa) && sockaddr_is_null_or_any(vsa) && sockaddr_is_null_or_any(tsa) && sockaddr_is_null_or_any(isa)) || (sendonly && sendonly != -1)) {
10810 ast_queue_control_data(p->owner, AST_CONTROL_HOLD,
10811 S_OR(p->mohsuggest, NULL),
10812 !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
10813 if (sendonly)
10814 ast_rtp_instance_stop(p->rtp);
10815
10816
10817 ast_queue_frame(p->owner, &ast_null_frame);
10818 change_hold_state(p, req, TRUE, sendonly);
10819 }
10820
10821 process_sdp_cleanup:
10822 if (res) {
10823 offered_media_list_destroy(p);
10824 }
10825 ast_rtp_codecs_payloads_destroy(&newtextrtp);
10826 ast_rtp_codecs_payloads_destroy(&newvideortp);
10827 ast_rtp_codecs_payloads_destroy(&newaudiortp);
10828 ast_format_cap_destroy(peercapability);
10829 ast_format_cap_destroy(vpeercapability);
10830 ast_format_cap_destroy(tpeercapability);
10831 ast_format_cap_destroy(newjointcapability);
10832 ast_format_cap_destroy(newpeercapability);
10833 return res;
10834 }
10835
10836 static int process_sdp_o(const char *o, struct sip_pvt *p)
10837 {
10838 char *o_copy;
10839 char *token;
10840 int64_t rua_version;
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851 p->session_modify = TRUE;
10852
10853 if (ast_strlen_zero(o)) {
10854 ast_log(LOG_WARNING, "SDP syntax error. SDP without an o= line\n");
10855 return FALSE;
10856 }
10857
10858 o_copy = ast_strdupa(o);
10859 token = strsep(&o_copy, " ");
10860 if (!o_copy) {
10861 ast_log(LOG_WARNING, "SDP syntax error in o= line username\n");
10862 return FALSE;
10863 }
10864 token = strsep(&o_copy, " ");
10865 if (!o_copy) {
10866 ast_log(LOG_WARNING, "SDP syntax error in o= line session-id\n");
10867 return FALSE;
10868 }
10869 token = strsep(&o_copy, " ");
10870 if (!o_copy) {
10871 ast_log(LOG_WARNING, "SDP syntax error in o= line\n");
10872 return FALSE;
10873 }
10874 if (!sscanf(token, "%30" SCNd64, &rua_version)) {
10875 ast_log(LOG_WARNING, "SDP syntax error in o= line version\n");
10876 return FALSE;
10877 }
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897 if (ast_test_flag(&p->flags[1], SIP_PAGE2_IGNORESDPVERSION) ||
10898 (p->sessionversion_remote < 0) ||
10899 (p->sessionversion_remote < rua_version)) {
10900 p->sessionversion_remote = rua_version;
10901 } else {
10902 if (p->t38.state == T38_LOCAL_REINVITE) {
10903 p->sessionversion_remote = rua_version;
10904 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);
10905 } else {
10906 p->session_modify = FALSE;
10907 ast_debug(2, "Call %s responded to our reinvite without changing SDP version; ignoring SDP.\n", p->callid);
10908 return FALSE;
10909 }
10910 }
10911
10912 return TRUE;
10913 }
10914
10915 static int process_sdp_c(const char *c, struct ast_sockaddr *addr)
10916 {
10917 char proto[4], host[258];
10918 int af;
10919
10920
10921 if (sscanf(c, "IN %3s %255s", proto, host) == 2) {
10922 if (!strcmp("IP4", proto)) {
10923 af = AF_INET;
10924 } else if (!strcmp("IP6", proto)) {
10925 af = AF_INET6;
10926 } else {
10927 ast_log(LOG_WARNING, "Unknown protocol '%s'.\n", proto);
10928 return FALSE;
10929 }
10930 if (ast_sockaddr_resolve_first_af(addr, host, 0, af)) {
10931 ast_log(LOG_WARNING, "Unable to lookup RTP Audio host in c= line, '%s'\n", c);
10932 return FALSE;
10933 }
10934 return TRUE;
10935 } else {
10936 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
10937 return FALSE;
10938 }
10939 return FALSE;
10940 }
10941
10942 static int process_sdp_a_sendonly(const char *a, int *sendonly)
10943 {
10944 int found = FALSE;
10945
10946 if (!strcasecmp(a, "sendonly")) {
10947 if (*sendonly == -1)
10948 *sendonly = 1;
10949 found = TRUE;
10950 } else if (!strcasecmp(a, "inactive")) {
10951 if (*sendonly == -1)
10952 *sendonly = 2;
10953 found = TRUE;
10954 } else if (!strcasecmp(a, "sendrecv")) {
10955 if (*sendonly == -1)
10956 *sendonly = 0;
10957 found = TRUE;
10958 }
10959 return found;
10960 }
10961
10962 static int process_sdp_a_ice(const char *a, struct sip_pvt *p, struct ast_rtp_instance *instance)
10963 {
10964 struct ast_rtp_engine_ice *ice;
10965 int found = FALSE;
10966 char ufrag[256], pwd[256], foundation[32], transport[4], address[46], cand_type[6], relay_address[46] = "";
10967 struct ast_rtp_engine_ice_candidate candidate = { 0, };
10968 int port, relay_port = 0;
10969
10970 if (!instance || !(ice = ast_rtp_instance_get_ice(instance))) {
10971 return found;
10972 }
10973
10974 if (sscanf(a, "ice-ufrag: %255s", ufrag) == 1) {
10975 ice->set_authentication(instance, ufrag, NULL);
10976 found = TRUE;
10977 } else if (sscanf(a, "ice-pwd: %255s", pwd) == 1) {
10978 ice->set_authentication(instance, NULL, pwd);
10979 found = TRUE;
10980 } else if (sscanf(a, "candidate: %31s %30u %3s %30u %23s %30u typ %5s %*s %23s %*s %30u", foundation, &candidate.id, transport, &candidate.priority,
10981 address, &port, cand_type, relay_address, &relay_port) >= 7) {
10982 candidate.foundation = foundation;
10983 candidate.transport = transport;
10984
10985 ast_sockaddr_parse(&candidate.address, address, PARSE_PORT_FORBID);
10986 ast_sockaddr_set_port(&candidate.address, port);
10987
10988 if (!strcasecmp(cand_type, "host")) {
10989 candidate.type = AST_RTP_ICE_CANDIDATE_TYPE_HOST;
10990 } else if (!strcasecmp(cand_type, "srflx")) {
10991 candidate.type = AST_RTP_ICE_CANDIDATE_TYPE_SRFLX;
10992 } else if (!strcasecmp(cand_type, "relay")) {
10993 candidate.type = AST_RTP_ICE_CANDIDATE_TYPE_RELAYED;
10994 } else {
10995 return found;
10996 }
10997
10998 if (!ast_strlen_zero(relay_address)) {
10999 ast_sockaddr_parse(&candidate.relay_address, relay_address, PARSE_PORT_FORBID);
11000 }
11001
11002 if (relay_port) {
11003 ast_sockaddr_set_port(&candidate.relay_address, relay_port);
11004 }
11005
11006 ice->add_remote_candidate(instance, &candidate);
11007
11008 found = TRUE;
11009 } else if (!strcasecmp(a, "ice-lite")) {
11010 ice->ice_lite(instance);
11011 found = TRUE;
11012 }
11013
11014 return found;
11015 }
11016
11017 static int process_sdp_a_dtls(const char *a, struct sip_pvt *p, struct ast_rtp_instance *instance)
11018 {
11019 struct ast_rtp_engine_dtls *dtls;
11020 int found = FALSE;
11021 char value[256], hash[6];
11022
11023 if (!instance || !p->dtls_cfg.enabled || !(dtls = ast_rtp_instance_get_dtls(instance))) {
11024 return found;
11025 }
11026
11027 if (sscanf(a, "setup: %255s", value) == 1) {
11028 found = TRUE;
11029
11030 if (!strcasecmp(value, "active")) {
11031 dtls->set_setup(instance, AST_RTP_DTLS_SETUP_ACTIVE);
11032 } else if (!strcasecmp(value, "passive")) {
11033 dtls->set_setup(instance, AST_RTP_DTLS_SETUP_PASSIVE);
11034 } else if (!strcasecmp(value, "actpass")) {
11035 dtls->set_setup(instance, AST_RTP_DTLS_SETUP_ACTPASS);
11036 } else if (!strcasecmp(value, "holdconn")) {
11037 dtls->set_setup(instance, AST_RTP_DTLS_SETUP_HOLDCONN);
11038 } else {
11039 ast_log(LOG_WARNING, "Unsupported setup attribute value '%s' received on dialog '%s'\n",
11040 value, p->callid);
11041 }
11042 } else if (sscanf(a, "connection: %255s", value) == 1) {
11043 found = TRUE;
11044
11045 if (!strcasecmp(value, "new")) {
11046 dtls->reset(instance);
11047 } else if (!strcasecmp(value, "existing")) {
11048
11049 } else {
11050 ast_log(LOG_WARNING, "Unsupported connection attribute value '%s' received on dialog '%s'\n",
11051 value, p->callid);
11052 }
11053 } else if (sscanf(a, "fingerprint: %5s %255s", hash, value) == 2) {
11054 found = TRUE;
11055
11056 if (!strcasecmp(hash, "sha-1")) {
11057 dtls->set_fingerprint(instance, AST_RTP_DTLS_HASH_SHA1, value);
11058 } else {
11059 ast_log(LOG_WARNING, "Unsupported fingerprint hash type '%s' received on dialog '%s'\n",
11060 hash, p->callid);
11061 }
11062 }
11063
11064 return found;
11065 }
11066
11067 static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newaudiortp, int *last_rtpmap_codec)
11068 {
11069 int found = FALSE;
11070 int codec;
11071 char mimeSubtype[128];
11072 char fmtp_string[256];
11073 unsigned int sample_rate;
11074 int debug = sip_debug_test_pvt(p);
11075
11076 if (!strncasecmp(a, "ptime", 5)) {
11077 char *tmp = strrchr(a, ':');
11078 long int framing = 0;
11079 if (tmp) {
11080 tmp++;
11081 framing = strtol(tmp, NULL, 10);
11082 if (framing == LONG_MIN || framing == LONG_MAX) {
11083 framing = 0;
11084 ast_debug(1, "Can't read framing from SDP: %s\n", a);
11085 }
11086 }
11087 if (framing && p->autoframing) {
11088 struct ast_codec_pref *pref = &ast_rtp_instance_get_codecs(p->rtp)->pref;
11089 int codec_n;
11090 for (codec_n = 0; codec_n < AST_RTP_MAX_PT; codec_n++) {
11091 struct ast_rtp_payload_type format = ast_rtp_codecs_payload_lookup(ast_rtp_instance_get_codecs(p->rtp), codec_n);
11092 if (!format.asterisk_format)
11093 continue;
11094 ast_debug(1, "Setting framing for %s to %ld\n", ast_getformatname(&format.format), framing);
11095 ast_codec_pref_setsize(pref, &format.format, framing);
11096 }
11097 ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(p->rtp), p->rtp, pref);
11098 }
11099 found = TRUE;
11100 } else if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
11101
11102 if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
11103 if (!(ast_rtp_codecs_payloads_set_rtpmap_type_rate(newaudiortp, NULL, codec, "audio", mimeSubtype,
11104 ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0, sample_rate))) {
11105 if (debug)
11106 ast_verbose("Found audio description format %s for ID %d\n", mimeSubtype, codec);
11107
11108 (*last_rtpmap_codec)++;
11109 found = TRUE;
11110 } else {
11111 ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
11112 if (debug)
11113 ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
11114 }
11115 } else {
11116 if (debug)
11117 ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
11118 }
11119 } else if (sscanf(a, "fmtp: %30u %255s", &codec, fmtp_string) == 2) {
11120 struct ast_format *format;
11121
11122 if ((format = ast_rtp_codecs_get_payload_format(newaudiortp, codec))) {
11123 unsigned int bit_rate;
11124
11125 if (!ast_format_sdp_parse(format, fmtp_string)) {
11126 found = TRUE;
11127 } else {
11128 ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
11129 }
11130
11131 switch ((int) format->id) {
11132 case AST_FORMAT_SIREN7:
11133 if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
11134 if (bit_rate != 32000) {
11135 ast_log(LOG_WARNING, "Got Siren7 offer at %d bps, but only 32000 bps supported; ignoring.\n", bit_rate);
11136 ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
11137 } else {
11138 found = TRUE;
11139 }
11140 }
11141 break;
11142 case AST_FORMAT_SIREN14:
11143 if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
11144 if (bit_rate != 48000) {
11145 ast_log(LOG_WARNING, "Got Siren14 offer at %d bps, but only 48000 bps supported; ignoring.\n", bit_rate);
11146 ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
11147 } else {
11148 found = TRUE;
11149 }
11150 }
11151 break;
11152 case AST_FORMAT_G719:
11153 if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
11154 if (bit_rate != 64000) {
11155 ast_log(LOG_WARNING, "Got G.719 offer at %d bps, but only 64000 bps supported; ignoring.\n", bit_rate);
11156 ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
11157 } else {
11158 found = TRUE;
11159 }
11160 }
11161 break;
11162 }
11163 }
11164 }
11165
11166 return found;
11167 }
11168
11169 static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newvideortp, int *last_rtpmap_codec)
11170 {
11171 int found = FALSE;
11172 int codec;
11173 char mimeSubtype[128];
11174 unsigned int sample_rate;
11175 int debug = sip_debug_test_pvt(p);
11176 char fmtp_string[256];
11177
11178 if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
11179
11180 if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
11181
11182 if (!strncasecmp(mimeSubtype, "H26", 3) || !strncasecmp(mimeSubtype, "MP4", 3)) {
11183 if (!(ast_rtp_codecs_payloads_set_rtpmap_type_rate(newvideortp, NULL, codec, "video", mimeSubtype, 0, sample_rate))) {
11184 if (debug)
11185 ast_verbose("Found video description format %s for ID %d\n", mimeSubtype, codec);
11186
11187 (*last_rtpmap_codec)++;
11188 found = TRUE;
11189 } else {
11190 ast_rtp_codecs_payloads_unset(newvideortp, NULL, codec);
11191 if (debug)
11192 ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
11193 }
11194 }
11195 } else {
11196 if (debug)
11197 ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
11198 }
11199 } else if (sscanf(a, "fmtp: %30u %255s", &codec, fmtp_string) == 2) {
11200 struct ast_format *format;
11201
11202 if ((format = ast_rtp_codecs_get_payload_format(newvideortp, codec))) {
11203 if (!ast_format_sdp_parse(format, fmtp_string)) {
11204 found = TRUE;
11205 } else {
11206 ast_rtp_codecs_payloads_unset(newvideortp, NULL, codec);
11207 }
11208 }
11209 }
11210
11211 return found;
11212 }
11213
11214 static int process_sdp_a_text(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newtextrtp, char *red_fmtp, int *red_num_gen, int *red_data_pt, int *last_rtpmap_codec)
11215 {
11216 int found = FALSE;
11217 int codec;
11218 char mimeSubtype[128];
11219 unsigned int sample_rate;
11220 char *red_cp;
11221 int debug = sip_debug_test_pvt(p);
11222
11223 if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
11224
11225 if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
11226 if (!strncasecmp(mimeSubtype, "T140", 4)) {
11227 if (p->trtp) {
11228
11229 ast_rtp_codecs_payloads_set_rtpmap_type_rate(newtextrtp, NULL, codec, "text", mimeSubtype, 0, sample_rate);
11230 found = TRUE;
11231 }
11232 } else if (!strncasecmp(mimeSubtype, "RED", 3)) {
11233 if (p->trtp) {
11234 ast_rtp_codecs_payloads_set_rtpmap_type_rate(newtextrtp, NULL, codec, "text", mimeSubtype, 0, sample_rate);
11235 sprintf(red_fmtp, "fmtp:%d ", codec);
11236 if (debug)
11237 ast_verbose("RED submimetype has payload type: %d\n", codec);
11238 found = TRUE;
11239 }
11240 }
11241 } else {
11242 if (debug)
11243 ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
11244 }
11245 } else if (!strncmp(a, red_fmtp, strlen(red_fmtp))) {
11246
11247 red_cp = &red_fmtp[strlen(red_fmtp)];
11248 strncpy(red_fmtp, a, 100);
11249
11250 sscanf(red_cp, "%30u", &red_data_pt[*red_num_gen]);
11251 red_cp = strtok(red_cp, "/");
11252 while (red_cp && (*red_num_gen)++ < AST_RED_MAX_GENERATION) {
11253 sscanf(red_cp, "%30u", &red_data_pt[*red_num_gen]);
11254 red_cp = strtok(NULL, "/");
11255 }
11256 red_cp = red_fmtp;
11257 found = TRUE;
11258 }
11259
11260 return found;
11261 }
11262
11263 static int process_sdp_a_image(const char *a, struct sip_pvt *p)
11264 {
11265 int found = FALSE;
11266 char s[256];
11267 unsigned int x;
11268 char *attrib = ast_strdupa(a);
11269 char *pos;
11270
11271 if (initialize_udptl(p)) {
11272 return found;
11273 }
11274
11275
11276
11277
11278
11279
11280 for (pos = attrib; *pos; ++pos) {
11281 *pos = tolower(*pos);
11282 }
11283
11284 if ((sscanf(attrib, "t38faxmaxbuffer:%30u", &x) == 1)) {
11285 ast_debug(3, "MaxBufferSize:%d\n", x);
11286 found = TRUE;
11287 } else if ((sscanf(attrib, "t38maxbitrate:%30u", &x) == 1) || (sscanf(attrib, "t38faxmaxrate:%30u", &x) == 1)) {
11288 ast_debug(3, "T38MaxBitRate: %d\n", x);
11289 switch (x) {
11290 case 14400:
11291 p->t38.their_parms.rate = AST_T38_RATE_14400;
11292 break;
11293 case 12000:
11294 p->t38.their_parms.rate = AST_T38_RATE_12000;
11295 break;
11296 case 9600:
11297 p->t38.their_parms.rate = AST_T38_RATE_9600;
11298 break;
11299 case 7200:
11300 p->t38.their_parms.rate = AST_T38_RATE_7200;
11301 break;
11302 case 4800:
11303 p->t38.their_parms.rate = AST_T38_RATE_4800;
11304 break;
11305 case 2400:
11306 p->t38.their_parms.rate = AST_T38_RATE_2400;
11307 break;
11308 }
11309 found = TRUE;
11310 } else if ((sscanf(attrib, "t38faxversion:%30u", &x) == 1)) {
11311 ast_debug(3, "FaxVersion: %u\n", x);
11312 p->t38.their_parms.version = x;
11313 found = TRUE;
11314 } else if ((sscanf(attrib, "t38faxmaxdatagram:%30u", &x) == 1) || (sscanf(attrib, "t38maxdatagram:%30u", &x) == 1)) {
11315
11316 if (((signed int) p->t38_maxdatagram >= 0) && ((unsigned int) p->t38_maxdatagram > x)) {
11317 ast_debug(1, "Overriding T38FaxMaxDatagram '%d' with '%d'\n", x, p->t38_maxdatagram);
11318 x = p->t38_maxdatagram;
11319 }
11320 ast_debug(3, "FaxMaxDatagram: %u\n", x);
11321 ast_udptl_set_far_max_datagram(p->udptl, x);
11322 found = TRUE;
11323 } else if ((strncmp(attrib, "t38faxfillbitremoval", 20) == 0)) {
11324 if (sscanf(attrib, "t38faxfillbitremoval:%30u", &x) == 1) {
11325 ast_debug(3, "FillBitRemoval: %d\n", x);
11326 if (x == 1) {
11327 p->t38.their_parms.fill_bit_removal = TRUE;
11328 }
11329 } else {
11330 ast_debug(3, "FillBitRemoval\n");
11331 p->t38.their_parms.fill_bit_removal = TRUE;
11332 }
11333 found = TRUE;
11334 } else if ((strncmp(attrib, "t38faxtranscodingmmr", 20) == 0)) {
11335 if (sscanf(attrib, "t38faxtranscodingmmr:%30u", &x) == 1) {
11336 ast_debug(3, "Transcoding MMR: %d\n", x);
11337 if (x == 1) {
11338 p->t38.their_parms.transcoding_mmr = TRUE;
11339 }
11340 } else {
11341 ast_debug(3, "Transcoding MMR\n");
11342 p->t38.their_parms.transcoding_mmr = TRUE;
11343 }
11344 found = TRUE;
11345 } else if ((strncmp(attrib, "t38faxtranscodingjbig", 21) == 0)) {
11346 if (sscanf(attrib, "t38faxtranscodingjbig:%30u", &x) == 1) {
11347 ast_debug(3, "Transcoding JBIG: %d\n", x);
11348 if (x == 1) {
11349 p->t38.their_parms.transcoding_jbig = TRUE;
11350 }
11351 } else {
11352 ast_debug(3, "Transcoding JBIG\n");
11353 p->t38.their_parms.transcoding_jbig = TRUE;
11354 }
11355 found = TRUE;
11356 } else if ((sscanf(attrib, "t38faxratemanagement:%255s", s) == 1)) {
11357 ast_debug(3, "RateManagement: %s\n", s);
11358 if (!strcasecmp(s, "localTCF"))
11359 p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_LOCAL_TCF;
11360 else if (!strcasecmp(s, "transferredTCF"))
11361 p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF;
11362 found = TRUE;
11363 } else if ((sscanf(attrib, "t38faxudpec:%255s", s) == 1)) {
11364 ast_debug(3, "UDP EC: %s\n", s);
11365 if (!strcasecmp(s, "t38UDPRedundancy")) {
11366 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
11367 } else if (!strcasecmp(s, "t38UDPFEC")) {
11368 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
11369 } else {
11370 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
11371 }
11372 found = TRUE;
11373 }
11374
11375 return found;
11376 }
11377
11378
11379
11380
11381 static int add_supported(struct sip_pvt *pvt, struct sip_request *req)
11382 {
11383 int res;
11384 if (st_get_mode(pvt, 0) != SESSION_TIMER_MODE_REFUSE) {
11385 res = add_header(req, "Supported", "replaces, timer");
11386 } else {
11387 res = add_header(req, "Supported", "replaces");
11388 }
11389 return res;
11390 }
11391
11392
11393 static int add_header(struct sip_request *req, const char *var, const char *value)
11394 {
11395 if (req->headers == SIP_MAX_HEADERS) {
11396 ast_log(LOG_WARNING, "Out of SIP header space\n");
11397 return -1;
11398 }
11399
11400 if (req->lines) {
11401 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
11402 return -1;
11403 }
11404
11405 if (sip_cfg.compactheaders) {
11406 var = find_alias(var, var);
11407 }
11408
11409 ast_str_append(&req->data, 0, "%s: %s\r\n", var, value);
11410 req->header[req->headers] = ast_str_strlen(req->data);
11411
11412 req->headers++;
11413
11414 return 0;
11415 }
11416
11417
11418
11419
11420
11421 static int add_max_forwards(struct sip_pvt *dialog, struct sip_request *req)
11422 {
11423 char clen[10];
11424
11425 snprintf(clen, sizeof(clen), "%d", dialog->maxforwards);
11426
11427 return add_header(req, "Max-Forwards", clen);
11428 }
11429
11430
11431 static int finalize_content(struct sip_request *req)
11432 {
11433 char clen[10];
11434
11435 if (req->lines) {
11436 ast_log(LOG_WARNING, "finalize_content() called on a message that has already been finalized\n");
11437 return -1;
11438 }
11439
11440 snprintf(clen, sizeof(clen), "%zd", ast_str_strlen(req->content));
11441 add_header(req, "Content-Length", clen);
11442
11443 if (ast_str_strlen(req->content)) {
11444 ast_str_append(&req->data, 0, "\r\n%s", ast_str_buffer(req->content));
11445 }
11446 req->lines = ast_str_strlen(req->content) ? 1 : 0;
11447 return 0;
11448 }
11449
11450
11451 static int add_content(struct sip_request *req, const char *line)
11452 {
11453 if (req->lines) {
11454 ast_log(LOG_WARNING, "Can't add more content when the content has been finalized\n");
11455 return -1;
11456 }
11457
11458 ast_str_append(&req->content, 0, "%s", line);
11459 return 0;
11460 }
11461
11462
11463 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field)
11464 {
11465 const char *tmp = sip_get_header(orig, field);
11466
11467 if (!ast_strlen_zero(tmp))
11468 return add_header(req, field, tmp);
11469 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
11470 return -1;
11471 }
11472
11473
11474 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field)
11475 {
11476 int start = 0;
11477 int copied = 0;
11478 for (;;) {
11479 const char *tmp = __get_header(orig, field, &start);
11480
11481 if (ast_strlen_zero(tmp))
11482 break;
11483
11484 add_header(req, field, tmp);
11485 copied++;
11486 }
11487 return copied ? 0 : -1;
11488 }
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field)
11499 {
11500 int copied = 0;
11501 int start = 0;
11502
11503 for (;;) {
11504 char new[512];
11505 const char *oh = __get_header(orig, field, &start);
11506
11507 if (ast_strlen_zero(oh))
11508 break;
11509
11510 if (!copied) {
11511 char leftmost[512], *others, *rport;
11512
11513
11514 ast_copy_string(leftmost, oh, sizeof(leftmost));
11515 others = strchr(leftmost, ',');
11516 if (others)
11517 *others++ = '\0';
11518
11519
11520 rport = strstr(leftmost, ";rport");
11521 if (rport && *(rport+6) == '=')
11522 rport = NULL;
11523
11524 if (((ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT)) || (rport && ast_test_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT)))) {
11525
11526 char *end;
11527
11528 rport = strstr(leftmost, ";rport");
11529
11530 if (rport) {
11531 end = strchr(rport + 1, ';');
11532 if (end)
11533 memmove(rport, end, strlen(end) + 1);
11534 else
11535 *rport = '\0';
11536 }
11537
11538
11539 snprintf(new, sizeof(new), "%s;received=%s;rport=%d%s%s",
11540 leftmost, ast_sockaddr_stringify_addr_remote(&p->recv),
11541 ast_sockaddr_port(&p->recv),
11542 others ? "," : "", others ? others : "");
11543 } else {
11544
11545 snprintf(new, sizeof(new), "%s;received=%s%s%s",
11546 leftmost, ast_sockaddr_stringify_addr_remote(&p->recv),
11547 others ? "," : "", others ? others : "");
11548 }
11549 oh = new;
11550 }
11551 add_header(req, field, oh);
11552 copied++;
11553 }
11554 if (!copied) {
11555 ast_log(LOG_NOTICE, "No header field '%s' present to copy\n", field);
11556 return -1;
11557 }
11558 return 0;
11559 }
11560
11561
11562 static void add_route(struct sip_request *req, struct sip_route *route)
11563 {
11564 char r[SIPBUFSIZE*2], *p;
11565 int n, rem = sizeof(r);
11566
11567 if (!route)
11568 return;
11569
11570 p = r;
11571 for (;route ; route = route->next) {
11572 n = strlen(route->hop);
11573 if (rem < n+3)
11574 break;
11575 if (p != r) {
11576 *p++ = ',';
11577 --rem;
11578 }
11579 *p++ = '<';
11580 ast_copy_string(p, route->hop, rem);
11581 p += n;
11582 *p++ = '>';
11583 rem -= (n+2);
11584 }
11585 *p = '\0';
11586 add_header(req, "Route", r);
11587 }
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598 static void set_destination(struct sip_pvt *p, char *uri)
11599 {
11600 char *trans, *h, *maddr, hostname[256];
11601 int hn;
11602 int debug=sip_debug_test_pvt(p);
11603 int tls_on = FALSE;
11604
11605 if (debug)
11606 ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
11607
11608 if ((trans = strcasestr(uri, ";transport="))) {
11609 trans += strlen(";transport=");
11610
11611 if (!strncasecmp(trans, "ws", 2)) {
11612 if (debug)
11613 ast_verbose("set_destination: URI is for WebSocket, we can't set destination\n");
11614 return;
11615 }
11616 }
11617
11618
11619 h = strchr(uri, '@');
11620 if (h)
11621 ++h;
11622 else {
11623 h = uri;
11624 if (!strncasecmp(h, "sip:", 4)) {
11625 h += 4;
11626 } else if (!strncasecmp(h, "sips:", 5)) {
11627 h += 5;
11628 tls_on = TRUE;
11629 }
11630 }
11631 hn = strcspn(h, ";>") + 1;
11632 if (hn > sizeof(hostname))
11633 hn = sizeof(hostname);
11634 ast_copy_string(hostname, h, hn);
11635
11636 h += hn - 1;
11637
11638
11639
11640 if (ast_sockaddr_resolve_first_transport(&p->sa, hostname, 0, p->socket.type)) {
11641 ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
11642 return;
11643 }
11644
11645
11646 maddr = strstr(h, "maddr=");
11647 if (maddr) {
11648 int port;
11649
11650 maddr += 6;
11651 hn = strspn(maddr, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
11652 "0123456789-.:[]") + 1;
11653 if (hn > sizeof(hostname))
11654 hn = sizeof(hostname);
11655 ast_copy_string(hostname, maddr, hn);
11656
11657 port = ast_sockaddr_port(&p->sa);
11658
11659
11660
11661 if (ast_sockaddr_resolve_first_transport(&p->sa, hostname, PARSE_PORT_FORBID, p->socket.type)) {
11662 ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
11663 return;
11664 }
11665
11666 ast_sockaddr_set_port(&p->sa, port);
11667 }
11668
11669 if (!ast_sockaddr_port(&p->sa)) {
11670 ast_sockaddr_set_port(&p->sa, tls_on ?
11671 STANDARD_TLS_PORT : STANDARD_SIP_PORT);
11672 }
11673
11674 if (debug) {
11675 ast_verbose("set_destination: set destination to %s\n",
11676 ast_sockaddr_stringify(&p->sa));
11677 }
11678 }
11679
11680
11681 static int init_resp(struct sip_request *resp, const char *msg)
11682 {
11683
11684 memset(resp, 0, sizeof(*resp));
11685 resp->method = SIP_RESPONSE;
11686 if (!(resp->data = ast_str_create(SIP_MIN_PACKET)))
11687 goto e_return;
11688 if (!(resp->content = ast_str_create(SIP_MIN_PACKET)))
11689 goto e_free_data;
11690 resp->header[0] = 0;
11691 ast_str_set(&resp->data, 0, "SIP/2.0 %s\r\n", msg);
11692 resp->headers++;
11693 return 0;
11694
11695 e_free_data:
11696 ast_free(resp->data);
11697 resp->data = NULL;
11698 e_return:
11699 return -1;
11700 }
11701
11702
11703 static int init_req(struct sip_request *req, int sipmethod, const char *recip)
11704 {
11705
11706 memset(req, 0, sizeof(*req));
11707 if (!(req->data = ast_str_create(SIP_MIN_PACKET)))
11708 goto e_return;
11709 if (!(req->content = ast_str_create(SIP_MIN_PACKET)))
11710 goto e_free_data;
11711 req->method = sipmethod;
11712 req->header[0] = 0;
11713 ast_str_set(&req->data, 0, "%s %s SIP/2.0\r\n", sip_methods[sipmethod].text, recip);
11714 req->headers++;
11715 return 0;
11716
11717 e_free_data:
11718 ast_free(req->data);
11719 req->data = NULL;
11720 e_return:
11721 return -1;
11722 }
11723
11724
11725 static void deinit_req(struct sip_request *req)
11726 {
11727 if (req->data) {
11728 ast_free(req->data);
11729 req->data = NULL;
11730 }
11731 if (req->content) {
11732 ast_free(req->content);
11733 req->content = NULL;
11734 }
11735 }
11736
11737
11738
11739 static inline int resp_needs_contact(const char *msg, enum sipmethod method) {
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755 switch (method) {
11756
11757 case SIP_INVITE:
11758 case SIP_UPDATE:
11759 case SIP_SUBSCRIBE:
11760 case SIP_NOTIFY:
11761 if ((msg[0] >= '1' && msg[0] <= '3') || !strncmp(msg, "485", 3))
11762 return 1;
11763 break;
11764
11765
11766 case SIP_REGISTER:
11767 case SIP_OPTIONS:
11768 if (msg[0] == '2' || msg[0] == '3' || !strncmp(msg, "485", 3))
11769 return 1;
11770 break;
11771
11772
11773 case SIP_BYE:
11774 case SIP_PRACK:
11775 case SIP_MESSAGE:
11776 case SIP_PUBLISH:
11777 if (msg[0] == '3' || !strncmp(msg, "485", 3))
11778 return 1;
11779 break;
11780
11781
11782 case SIP_REFER:
11783 if (msg[0] >= '2' && msg[0] <= '6')
11784 return 1;
11785 break;
11786
11787
11788 case SIP_ACK:
11789 case SIP_CANCEL:
11790 case SIP_INFO:
11791 case SIP_PING:
11792 default:
11793 return 0;
11794 }
11795 return 0;
11796 }
11797
11798
11799 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req)
11800 {
11801 char newto[256];
11802 const char *ot;
11803
11804 init_resp(resp, msg);
11805 copy_via_headers(p, resp, req, "Via");
11806 if (msg[0] == '1' || msg[0] == '2')
11807 copy_all_header(resp, req, "Record-Route");
11808 copy_header(resp, req, "From");
11809 ot = sip_get_header(req, "To");
11810 if (!strcasestr(ot, "tag=") && strncmp(msg, "100", 3)) {
11811
11812
11813 if (!ast_strlen_zero(p->theirtag) && ast_test_flag(&p->flags[0], SIP_OUTGOING))
11814 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
11815 else if (p->tag && !ast_test_flag(&p->flags[0], SIP_OUTGOING))
11816 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
11817 else
11818 ast_copy_string(newto, ot, sizeof(newto));
11819 ot = newto;
11820 }
11821 add_header(resp, "To", ot);
11822 copy_header(resp, req, "Call-ID");
11823 copy_header(resp, req, "CSeq");
11824 if (!ast_strlen_zero(global_useragent))
11825 add_header(resp, "Server", global_useragent);
11826 add_header(resp, "Allow", ALLOWED_METHODS);
11827 add_supported(p, resp);
11828
11829
11830 if (p->method == SIP_INVITE && p->stimer && p->stimer->st_active == TRUE) {
11831 char se_hdr[256];
11832 snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval,
11833 p->stimer->st_ref == SESSION_TIMER_REFRESHER_US ? "uas" : "uac");
11834 add_header(resp, "Session-Expires", se_hdr);
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845 if (p->stimer->st_ref == SESSION_TIMER_REFRESHER_THEM ||
11846 (p->stimer->st_ref == SESSION_TIMER_REFRESHER_US &&
11847 p->stimer->st_active_peer_ua == TRUE)) {
11848 resp->reqsipoptions |= SIP_OPT_TIMER;
11849 }
11850 }
11851
11852 if (msg[0] == '2' && (p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER || p->method == SIP_PUBLISH)) {
11853
11854
11855 add_expires(resp, p->expiry);
11856 if (p->expiry) {
11857 char contact[SIPBUFSIZE];
11858 const char *contact_uri = p->method == SIP_SUBSCRIBE ? p->our_contact : p->fullcontact;
11859 char *brackets = strchr(contact_uri, '<');
11860 snprintf(contact, sizeof(contact), "%s%s%s;expires=%d", brackets ? "" : "<", contact_uri, brackets ? "" : ">", p->expiry);
11861 add_header(resp, "Contact", contact);
11862 }
11863 } else if (!ast_strlen_zero(p->our_contact) && resp_needs_contact(msg, p->method)) {
11864 add_header(resp, "Contact", p->our_contact);
11865 }
11866
11867 if (!ast_strlen_zero(p->url)) {
11868 add_header(resp, "Access-URL", p->url);
11869 ast_string_field_set(p, url, NULL);
11870 }
11871
11872
11873
11874
11875
11876
11877
11878 p->sa = p->recv;
11879
11880 if (process_via(p, req)) {
11881 ast_log(LOG_WARNING, "error processing via header, will send response to originating address\n");
11882 }
11883
11884 return 0;
11885 }
11886
11887
11888 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, uint32_t seqno, int newbranch)
11889 {
11890 struct sip_request *orig = &p->initreq;
11891 char stripped[80];
11892 char tmp[80];
11893 char newto[256];
11894 const char *c;
11895 const char *ot, *of;
11896 int is_strict = FALSE;
11897 int is_outbound = ast_test_flag(&p->flags[0], SIP_OUTGOING);
11898
11899 snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", sip_methods[sipmethod].text);
11900
11901 if (!seqno) {
11902 p->ocseq++;
11903 seqno = p->ocseq;
11904 }
11905
11906
11907 if (sipmethod == SIP_CANCEL) {
11908 p->branch = p->invite_branch;
11909 build_via(p);
11910 } else if (newbranch && (sipmethod == SIP_INVITE)) {
11911 p->branch ^= ast_random();
11912 p->invite_branch = p->branch;
11913 build_via(p);
11914 } else if (newbranch) {
11915 p->branch ^= ast_random();
11916 build_via(p);
11917 }
11918
11919
11920 if (p->route && !ast_strlen_zero(p->route->hop) && strstr(p->route->hop, ";lr") == NULL) {
11921 is_strict = TRUE;
11922 if (sipdebug)
11923 ast_debug(1, "Strict routing enforced for session %s\n", p->callid);
11924 }
11925
11926 if (sipmethod == SIP_CANCEL)
11927 c = REQ_OFFSET_TO_STR(&p->initreq, rlpart2);
11928 else if (sipmethod == SIP_ACK) {
11929
11930
11931 if (!ast_strlen_zero(p->okcontacturi))
11932 c = is_strict ? p->route->hop : p->okcontacturi;
11933 else
11934 c = REQ_OFFSET_TO_STR(&p->initreq, rlpart2);
11935 } else if (!ast_strlen_zero(p->okcontacturi))
11936 c = is_strict ? p->route->hop : p->okcontacturi;
11937 else if (!ast_strlen_zero(p->uri))
11938 c = p->uri;
11939 else {
11940 char *n;
11941
11942 ast_copy_string(stripped, sip_get_header(orig, is_outbound ? "To" : "From"),
11943 sizeof(stripped));
11944 n = get_in_brackets(stripped);
11945 c = remove_uri_parameters(n);
11946 }
11947 init_req(req, sipmethod, c);
11948
11949 snprintf(tmp, sizeof(tmp), "%u %s", seqno, sip_methods[sipmethod].text);
11950
11951 add_header(req, "Via", p->via);
11952
11953
11954
11955
11956
11957 if (p->route &&
11958 !(sipmethod == SIP_CANCEL ||
11959 (sipmethod == SIP_ACK && (p->invitestate == INV_COMPLETED || p->invitestate == INV_CANCELLED)))) {
11960 set_destination(p, p->route->hop);
11961 add_route(req, is_strict ? p->route->next : p->route);
11962 }
11963 add_max_forwards(p, req);
11964
11965 ot = sip_get_header(orig, "To");
11966 of = sip_get_header(orig, "From");
11967
11968
11969
11970 if (!strcasestr(ot, "tag=") && sipmethod != SIP_CANCEL) {
11971
11972
11973 if (is_outbound && !ast_strlen_zero(p->theirtag))
11974 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
11975 else if (!is_outbound)
11976 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
11977 else
11978 snprintf(newto, sizeof(newto), "%s", ot);
11979 ot = newto;
11980 }
11981
11982 if (is_outbound) {
11983 add_header(req, "From", of);
11984 add_header(req, "To", ot);
11985 } else {
11986 add_header(req, "From", ot);
11987 add_header(req, "To", of);
11988 }
11989
11990 if (sipmethod != SIP_BYE && sipmethod != SIP_CANCEL && sipmethod != SIP_MESSAGE)
11991 add_header(req, "Contact", p->our_contact);
11992
11993 copy_header(req, orig, "Call-ID");
11994 add_header(req, "CSeq", tmp);
11995
11996 if (!ast_strlen_zero(global_useragent))
11997 add_header(req, "User-Agent", global_useragent);
11998
11999 if (!ast_strlen_zero(p->url)) {
12000 add_header(req, "Access-URL", p->url);
12001 ast_string_field_set(p, url, NULL);
12002 }
12003
12004
12005
12006
12007
12008
12009
12010
12011 if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE
12012 && sipmethod == SIP_INVITE) {
12013 char se_hdr[256];
12014 snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval,
12015 p->stimer->st_ref == SESSION_TIMER_REFRESHER_US ? "uac" : "uas");
12016 add_header(req, "Session-Expires", se_hdr);
12017 snprintf(se_hdr, sizeof(se_hdr), "%d", st_get_se(p, FALSE));
12018 add_header(req, "Min-SE", se_hdr);
12019 }
12020
12021 return 0;
12022 }
12023
12024
12025 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
12026 {
12027 struct sip_request resp;
12028 uint32_t seqno = 0;
12029
12030 if (reliable && (sscanf(sip_get_header(req, "CSeq"), "%30u ", &seqno) != 1)) {
12031 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", sip_get_header(req, "CSeq"));
12032 return -1;
12033 }
12034 respprep(&resp, p, msg, req);
12035
12036 if (ast_test_flag(&p->flags[0], SIP_SENDRPID)
12037 && ast_test_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND)
12038 && (!strncmp(msg, "180", 3) || !strncmp(msg, "183", 3))) {
12039 ast_clear_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND);
12040 add_rpid(&resp, p);
12041 }
12042 if (ast_test_flag(&p->flags[0], SIP_OFFER_CC)) {
12043 add_cc_call_info_to_response(p, &resp);
12044 }
12045
12046
12047 if (!strncmp(msg, "302", 3)) {
12048 add_diversion(&resp, p);
12049 }
12050
12051
12052
12053 if (p->method == SIP_INVITE && msg[0] != '1') {
12054 char buf[20];
12055
12056 if (ast_test_flag(&p->flags[1], SIP_PAGE2_Q850_REASON)) {
12057 int hangupcause = 0;
12058
12059 if (p->owner && ast_channel_hangupcause(p->owner)) {
12060 hangupcause = ast_channel_hangupcause(p->owner);
12061 } else if (p->hangupcause) {
12062 hangupcause = p->hangupcause;
12063 } else {
12064 int respcode;
12065 if (sscanf(msg, "%30d ", &respcode))
12066 hangupcause = hangup_sip2cause(respcode);
12067 }
12068
12069 if (hangupcause) {
12070 sprintf(buf, "Q.850;cause=%i", hangupcause & 0x7f);
12071 add_header(&resp, "Reason", buf);
12072 }
12073 }
12074
12075 if (p->owner && ast_channel_hangupcause(p->owner)) {
12076 add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(ast_channel_hangupcause(p->owner)));
12077 snprintf(buf, sizeof(buf), "%d", ast_channel_hangupcause(p->owner));
12078 add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
12079 }
12080 }
12081 return send_response(p, &resp, reliable, seqno);
12082 }
12083
12084 static int transmit_response_with_sip_etag(struct sip_pvt *p, const char *msg, const struct sip_request *req, struct sip_esc_entry *esc_entry, int need_new_etag)
12085 {
12086 struct sip_request resp;
12087
12088 if (need_new_etag) {
12089 create_new_sip_etag(esc_entry, 1);
12090 }
12091 respprep(&resp, p, msg, req);
12092 add_header(&resp, "SIP-ETag", esc_entry->entity_tag);
12093
12094 return send_response(p, &resp, 0, 0);
12095 }
12096
12097 static int temp_pvt_init(void *data)
12098 {
12099 struct sip_pvt *p = data;
12100
12101 p->do_history = 0;
12102 return ast_string_field_init(p, 512);
12103 }
12104
12105 static void temp_pvt_cleanup(void *data)
12106 {
12107 struct sip_pvt *p = data;
12108
12109 ast_string_field_free_memory(p);
12110
12111 ast_free(data);
12112 }
12113
12114
12115 static int transmit_response_using_temp(ast_string_field callid, struct ast_sockaddr *addr, int useglobal_nat, const int intended_method, const struct sip_request *req, const char *msg)
12116 {
12117 struct sip_pvt *p = NULL;
12118
12119 if (!(p = ast_threadstorage_get(&ts_temp_pvt, sizeof(*p)))) {
12120 ast_log(LOG_ERROR, "Failed to get temporary pvt\n");
12121 return -1;
12122 }
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132 p->method = intended_method;
12133
12134 if (!addr) {
12135 ast_sockaddr_copy(&p->ourip, &internip);
12136 } else {
12137 ast_sockaddr_copy(&p->sa, addr);
12138 ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
12139 }
12140
12141 p->branch = ast_random();
12142 make_our_tag(p);
12143 p->ocseq = INITIAL_CSEQ;
12144
12145 if (useglobal_nat && addr) {
12146 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT_FORCE_RPORT);
12147 ast_copy_flags(&p->flags[2], &global_flags[2], SIP_PAGE3_NAT_AUTO_RPORT);
12148 ast_sockaddr_copy(&p->recv, addr);
12149 check_via(p, req);
12150 }
12151
12152 ast_string_field_set(p, fromdomain, default_fromdomain);
12153 p->fromdomainport = default_fromdomainport;
12154 build_via(p);
12155 ast_string_field_set(p, callid, callid);
12156
12157 copy_socket_data(&p->socket, &req->socket);
12158
12159
12160 __transmit_response(p, msg, req, XMIT_UNRELIABLE);
12161
12162
12163 ast_string_field_init(p, 0);
12164
12165 return 0;
12166 }
12167
12168
12169 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req)
12170 {
12171 return __transmit_response(p, msg, req, XMIT_UNRELIABLE);
12172 }
12173
12174
12175 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported)
12176 {
12177 struct sip_request resp;
12178 respprep(&resp, p, msg, req);
12179 add_date(&resp);
12180 add_header(&resp, "Unsupported", unsupported);
12181 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
12182 }
12183
12184
12185 static int transmit_response_with_minse(struct sip_pvt *p, const char *msg, const struct sip_request *req, int minse_int)
12186 {
12187 struct sip_request resp;
12188 char minse_str[20];
12189
12190 respprep(&resp, p, msg, req);
12191 add_date(&resp);
12192
12193 snprintf(minse_str, sizeof(minse_str), "%d", minse_int);
12194 add_header(&resp, "Min-SE", minse_str);
12195 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
12196 }
12197
12198
12199
12200
12201
12202 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req)
12203 {
12204 return __transmit_response(p, msg, req, req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL);
12205 }
12206
12207
12208 static void add_date(struct sip_request *req)
12209 {
12210 char tmp[256];
12211 struct tm tm;
12212 time_t t = time(NULL);
12213
12214 gmtime_r(&t, &tm);
12215 strftime(tmp, sizeof(tmp), "%a, %d %b %Y %T GMT", &tm);
12216 add_header(req, "Date", tmp);
12217 }
12218
12219
12220 static void add_expires(struct sip_request *req, int expires)
12221 {
12222 char tmp[32];
12223
12224 snprintf(tmp, sizeof(tmp), "%d", expires);
12225 add_header(req, "Expires", tmp);
12226 }
12227
12228
12229 static int transmit_response_with_retry_after(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *seconds)
12230 {
12231 struct sip_request resp;
12232 respprep(&resp, p, msg, req);
12233 add_header(&resp, "Retry-After", seconds);
12234 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
12235 }
12236
12237
12238 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req)
12239 {
12240 struct sip_request resp;
12241 respprep(&resp, p, msg, req);
12242 add_date(&resp);
12243 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
12244 }
12245
12246
12247 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
12248 {
12249 struct sip_request resp;
12250 respprep(&resp, p, msg, req);
12251 add_header(&resp, "Accept", "application/sdp");
12252 return send_response(p, &resp, reliable, 0);
12253 }
12254
12255
12256 static int transmit_response_with_minexpires(struct sip_pvt *p, const char *msg, const struct sip_request *req, int minexpires)
12257 {
12258 struct sip_request resp;
12259 char tmp[32];
12260
12261 snprintf(tmp, sizeof(tmp), "%d", minexpires);
12262 respprep(&resp, p, msg, req);
12263 add_header(&resp, "Min-Expires", tmp);
12264 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
12265 }
12266
12267
12268 static int transmit_response_with_auth(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *nonce, enum xmittype reliable, const char *header, int stale)
12269 {
12270 struct sip_request resp;
12271 char tmp[512];
12272 uint32_t seqno = 0;
12273
12274 if (reliable && (sscanf(sip_get_header(req, "CSeq"), "%30u ", &seqno) != 1)) {
12275 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", sip_get_header(req, "CSeq"));
12276 return -1;
12277 }
12278
12279 get_realm(p, req);
12280
12281
12282
12283 snprintf(tmp, sizeof(tmp), "Digest algorithm=MD5, realm=\"%s\", nonce=\"%s\"%s", p->realm, nonce, stale ? ", stale=true" : "");
12284 respprep(&resp, p, msg, req);
12285 add_header(&resp, header, tmp);
12286 append_history(p, "AuthChal", "Auth challenge sent for %s - nc %d", p->username, p->noncecount);
12287 return send_response(p, &resp, reliable, seqno);
12288 }
12289
12290
12291
12292
12293
12294
12295
12296 static int get_domain(const char *str, char *domain, int len)
12297 {
12298 char tmpf[256];
12299 char *a, *from;
12300
12301 *domain = '\0';
12302 ast_copy_string(tmpf, str, sizeof(tmpf));
12303 from = get_in_brackets(tmpf);
12304 if (!ast_strlen_zero(from)) {
12305 if (strncasecmp(from, "sip:", 4)) {
12306 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", from);
12307 return -1;
12308 }
12309 from += 4;
12310 } else
12311 from = NULL;
12312
12313 if (from) {
12314 int bracket = 0;
12315
12316
12317 if ((a = strchr(from, ';')))
12318 *a = '\0';
12319
12320 for (a = from; *a != '\0'; ++a) {
12321 if (*a == ':' && bracket == 0) {
12322 *a = '\0';
12323 break;
12324 } else if (*a == '[') {
12325 ++bracket;
12326 } else if (*a == ']') {
12327 --bracket;
12328 }
12329 }
12330 if ((a = strchr(from, '@'))) {
12331 *a = '\0';
12332 ast_copy_string(domain, a + 1, len);
12333 } else
12334 ast_copy_string(domain, from, len);
12335 }
12336
12337 return ast_strlen_zero(domain);
12338 }
12339
12340
12341
12342
12343
12344 static void get_realm(struct sip_pvt *p, const struct sip_request *req)
12345 {
12346 char domain[MAXHOSTNAMELEN];
12347
12348 if (!ast_strlen_zero(p->realm))
12349 return;
12350
12351 if (sip_cfg.domainsasrealm &&
12352 !AST_LIST_EMPTY(&domain_list))
12353 {
12354
12355 if (!get_domain(sip_get_header(req, "From"), domain, sizeof(domain))) {
12356 if (check_sip_domain(domain, NULL, 0)) {
12357 ast_string_field_set(p, realm, domain);
12358 return;
12359 }
12360 }
12361
12362 if (!get_domain(sip_get_header(req, "To"), domain, sizeof(domain))) {
12363 if (check_sip_domain(domain, NULL, 0)) {
12364 ast_string_field_set(p, realm, domain);
12365 return;
12366 }
12367 }
12368 }
12369
12370
12371 ast_string_field_set(p, realm, sip_cfg.realm);
12372 }
12373
12374
12375
12376
12377
12378
12379
12380
12381 static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp)
12382 {
12383 int res;
12384
12385 if (!(res = with_sdp ? transmit_response_with_sdp(p, msg, req, XMIT_UNRELIABLE, FALSE, FALSE) : transmit_response(p, msg, req))) {
12386 p->last_provisional = msg;
12387 update_provisional_keepalive(p, with_sdp);
12388 }
12389
12390 return res;
12391 }
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401 static void destroy_msg_headers(struct sip_pvt *pvt)
12402 {
12403 struct sip_msg_hdr *doomed;
12404
12405 while ((doomed = AST_LIST_REMOVE_HEAD(&pvt->msg_headers, next))) {
12406 ast_free(doomed);
12407 }
12408 }
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420 static void add_msg_header(struct sip_pvt *pvt, const char *hdr_name, const char *hdr_value)
12421 {
12422 size_t hdr_len_name;
12423 size_t hdr_len_value;
12424 struct sip_msg_hdr *node;
12425 char *pos;
12426
12427 hdr_len_name = strlen(hdr_name) + 1;
12428 hdr_len_value = strlen(hdr_value) + 1;
12429
12430 node = ast_calloc(1, sizeof(*node) + hdr_len_name + hdr_len_value);
12431 if (!node) {
12432 return;
12433 }
12434 pos = node->stuff;
12435 node->name = pos;
12436 strcpy(pos, hdr_name);
12437 pos += hdr_len_name;
12438 node->value = pos;
12439 strcpy(pos, hdr_value);
12440
12441 AST_LIST_INSERT_TAIL(&pvt->msg_headers, node, next);
12442 }
12443
12444
12445 static int add_text(struct sip_request *req, struct sip_pvt *p)
12446 {
12447 const char *content_type = NULL;
12448 struct sip_msg_hdr *node;
12449
12450
12451 AST_LIST_TRAVERSE(&p->msg_headers, node, next) {
12452 if (!strcasecmp(node->name, "Content-Type")) {
12453
12454 content_type = node->value;
12455 } else {
12456 add_header(req, node->name, node->value);
12457 }
12458 }
12459 if (ast_strlen_zero(content_type)) {
12460
12461 content_type = "text/plain;charset=UTF-8";
12462 }
12463 add_header(req, "Content-Type", content_type);
12464
12465
12466 add_content(req, p->msg_body);
12467 return 0;
12468 }
12469
12470
12471
12472
12473
12474 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode)
12475 {
12476 char tmp[256];
12477 int event;
12478 if (mode) {
12479
12480 if ('0' <= digit && digit <= '9') {
12481 event = digit - '0';
12482 } else if (digit == '*') {
12483 event = 10;
12484 } else if (digit == '#') {
12485 event = 11;
12486 } else if ('A' <= digit && digit <= 'D') {
12487 event = 12 + digit - 'A';
12488 } else if ('a' <= digit && digit <= 'd') {
12489 event = 12 + digit - 'a';
12490 } else {
12491
12492 event = 0;
12493 }
12494 snprintf(tmp, sizeof(tmp), "%d\r\n", event);
12495 add_header(req, "Content-Type", "application/dtmf");
12496 add_content(req, tmp);
12497 } else {
12498
12499 snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=%u\r\n", digit, duration);
12500 add_header(req, "Content-Type", "application/dtmf-relay");
12501 add_content(req, tmp);
12502 }
12503 return 0;
12504 }
12505
12506
12507
12508
12509
12510 static int add_rpid(struct sip_request *req, struct sip_pvt *p)
12511 {
12512 struct ast_str *tmp = ast_str_alloca(256);
12513 char tmp2[256];
12514 char *lid_num;
12515 char *lid_name;
12516 int lid_pres;
12517 const char *fromdomain;
12518 const char *privacy = NULL;
12519 const char *screen = NULL;
12520 struct ast_party_id connected_id;
12521 const char *anonymous_string = "\"Anonymous\" <sip:anonymous@anonymous.invalid>";
12522
12523 if (!ast_test_flag(&p->flags[0], SIP_SENDRPID)) {
12524 return 0;
12525 }
12526
12527 if (!p->owner) {
12528 return 0;
12529 }
12530 connected_id = ast_channel_connected_effective_id(p->owner);
12531 lid_num = S_COR(connected_id.number.valid, connected_id.number.str, NULL);
12532 if (!lid_num) {
12533 return 0;
12534 }
12535 lid_name = S_COR(connected_id.name.valid, connected_id.name.str, NULL);
12536 if (!lid_name) {
12537 lid_name = lid_num;
12538 }
12539 lid_pres = ast_party_id_presentation(&connected_id);
12540
12541 if (((lid_pres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) &&
12542 (ast_test_flag(&p->flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND) == SIP_PAGE2_TRUST_ID_OUTBOUND_NO)) {
12543
12544 return 0;
12545 }
12546
12547 fromdomain = p->fromdomain;
12548 if (!fromdomain ||
12549 ((ast_test_flag(&p->flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND) == SIP_PAGE2_TRUST_ID_OUTBOUND_YES) &&
12550 !strcmp("anonymous.invalid", fromdomain))) {
12551
12552
12553 fromdomain = ast_sockaddr_stringify_host_remote(&p->ourip);
12554 }
12555
12556 lid_num = ast_uri_encode(lid_num, tmp2, sizeof(tmp2), ast_uri_sip_user);
12557
12558 if (ast_test_flag(&p->flags[0], SIP_SENDRPID_PAI)) {
12559 if (ast_test_flag(&p->flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND) != SIP_PAGE2_TRUST_ID_OUTBOUND_LEGACY) {
12560
12561
12562 ast_str_set(&tmp, -1, "\"%s\" <sip:%s@%s>", lid_name, lid_num, fromdomain);
12563 if ((lid_pres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
12564 add_header(req, "Privacy", "id");
12565 }
12566 } else {
12567
12568
12569 if ((lid_pres & AST_PRES_RESTRICTION) == AST_PRES_ALLOWED) {
12570 ast_str_set(&tmp, -1, "\"%s\" <sip:%s@%s>", lid_name, lid_num, fromdomain);
12571 } else {
12572 ast_str_set(&tmp, -1, "%s", anonymous_string);
12573 }
12574 }
12575 add_header(req, "P-Asserted-Identity", ast_str_buffer(tmp));
12576 } else {
12577 ast_str_set(&tmp, -1, "\"%s\" <sip:%s@%s>;party=%s", lid_name, lid_num, fromdomain, p->outgoing_call ? "calling" : "called");
12578
12579 switch (lid_pres) {
12580 case AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED:
12581 case AST_PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN:
12582 privacy = "off";
12583 screen = "no";
12584 break;
12585 case AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN:
12586 case AST_PRES_ALLOWED_NETWORK_NUMBER:
12587 privacy = "off";
12588 screen = "yes";
12589 break;
12590 case AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED:
12591 case AST_PRES_PROHIB_USER_NUMBER_FAILED_SCREEN:
12592 privacy = "full";
12593 screen = "no";
12594 break;
12595 case AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN:
12596 case AST_PRES_PROHIB_NETWORK_NUMBER:
12597 privacy = "full";
12598 screen = "yes";
12599 break;
12600 case AST_PRES_NUMBER_NOT_AVAILABLE:
12601 break;
12602 default:
12603 if ((lid_pres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
12604 privacy = "full";
12605 }
12606 else
12607 privacy = "off";
12608 screen = "no";
12609 break;
12610 }
12611
12612 if (!ast_strlen_zero(privacy) && !ast_strlen_zero(screen)) {
12613 ast_str_append(&tmp, -1, ";privacy=%s;screen=%s", privacy, screen);
12614 }
12615
12616 add_header(req, "Remote-Party-ID", ast_str_buffer(tmp));
12617 }
12618 return 0;
12619 }
12620
12621
12622
12623 static int add_vidupdate(struct sip_request *req)
12624 {
12625 const char *xml_is_a_huge_waste_of_space =
12626 "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
12627 " <media_control>\r\n"
12628 " <vc_primitive>\r\n"
12629 " <to_encoder>\r\n"
12630 " <picture_fast_update>\r\n"
12631 " </picture_fast_update>\r\n"
12632 " </to_encoder>\r\n"
12633 " </vc_primitive>\r\n"
12634 " </media_control>\r\n";
12635 add_header(req, "Content-Type", "application/media_control+xml");
12636 add_content(req, xml_is_a_huge_waste_of_space);
12637 return 0;
12638 }
12639
12640
12641 static void add_ice_to_sdp(struct ast_rtp_instance *instance, struct ast_str **a_buf)
12642 {
12643 struct ast_rtp_engine_ice *ice = ast_rtp_instance_get_ice(instance);
12644 const char *username, *password;
12645 struct ao2_container *candidates;
12646 struct ao2_iterator i;
12647 struct ast_rtp_engine_ice_candidate *candidate;
12648
12649
12650 if (!ice || !(candidates = ice->get_local_candidates(instance))) {
12651 return;
12652 }
12653
12654 if ((username = ice->get_ufrag(instance))) {
12655 ast_str_append(a_buf, 0, "a=ice-ufrag:%s\r\n", username);
12656 }
12657 if ((password = ice->get_password(instance))) {
12658 ast_str_append(a_buf, 0, "a=ice-pwd:%s\r\n", password);
12659 }
12660
12661 i = ao2_iterator_init(candidates, 0);
12662
12663 while ((candidate = ao2_iterator_next(&i))) {
12664 ast_str_append(a_buf, 0, "a=candidate:%s %d %s %d ", candidate->foundation, candidate->id, candidate->transport, candidate->priority);
12665 ast_str_append(a_buf, 0, "%s ", ast_sockaddr_stringify_host(&candidate->address));
12666
12667 if (candidate->type == AST_RTP_ICE_CANDIDATE_TYPE_SRFLX
12668 && candidate->id == AST_RTP_ICE_COMPONENT_RTCP) {
12669 ast_str_append(a_buf, 0, "%d typ ", ast_sockaddr_port(&candidate->address) + 1);
12670 } else {
12671 ast_str_append(a_buf, 0, "%s typ ", ast_sockaddr_stringify_port(&candidate->address));
12672 }
12673
12674 if (candidate->type == AST_RTP_ICE_CANDIDATE_TYPE_HOST) {
12675 ast_str_append(a_buf, 0, "host");
12676 } else if (candidate->type == AST_RTP_ICE_CANDIDATE_TYPE_SRFLX) {
12677 ast_str_append(a_buf, 0, "srflx");
12678 } else if (candidate->type == AST_RTP_ICE_CANDIDATE_TYPE_RELAYED) {
12679 ast_str_append(a_buf, 0, "relay");
12680 }
12681
12682 if (!ast_sockaddr_isnull(&candidate->relay_address)) {
12683 ast_str_append(a_buf, 0, " raddr %s ", ast_sockaddr_stringify_host(&candidate->relay_address));
12684 ast_str_append(a_buf, 0, "rport %s", ast_sockaddr_stringify_port(&candidate->relay_address));
12685 }
12686
12687 ast_str_append(a_buf, 0, "\r\n");
12688 ao2_ref(candidate, -1);
12689 }
12690
12691 ao2_iterator_destroy(&i);
12692
12693 ao2_ref(candidates, -1);
12694 }
12695
12696
12697 static void start_ice(struct ast_rtp_instance *instance)
12698 {
12699 struct ast_rtp_engine_ice *ice = ast_rtp_instance_get_ice(instance);
12700
12701 if (!ice) {
12702 return;
12703 }
12704
12705 ice->start(instance);
12706 }
12707
12708
12709 static void add_dtls_to_sdp(struct ast_rtp_instance *instance, struct ast_str **a_buf)
12710 {
12711 struct ast_rtp_engine_dtls *dtls;
12712 const char *fingerprint;
12713
12714 if (!instance || !(dtls = ast_rtp_instance_get_dtls(instance)) || !dtls->active(instance)) {
12715 return;
12716 }
12717
12718 switch (dtls->get_connection(instance)) {
12719 case AST_RTP_DTLS_CONNECTION_NEW:
12720 ast_str_append(a_buf, 0, "a=connection:new\r\n");
12721 break;
12722 case AST_RTP_DTLS_CONNECTION_EXISTING:
12723 ast_str_append(a_buf, 0, "a=connection:existing\r\n");
12724 break;
12725 default:
12726 break;
12727 }
12728
12729 switch (dtls->get_setup(instance)) {
12730 case AST_RTP_DTLS_SETUP_ACTIVE:
12731 ast_str_append(a_buf, 0, "a=setup:active\r\n");
12732 break;
12733 case AST_RTP_DTLS_SETUP_PASSIVE:
12734 ast_str_append(a_buf, 0, "a=setup:passive\r\n");
12735 break;
12736 case AST_RTP_DTLS_SETUP_ACTPASS:
12737 ast_str_append(a_buf, 0, "a=setup:actpass\r\n");
12738 break;
12739 case AST_RTP_DTLS_SETUP_HOLDCONN:
12740 ast_str_append(a_buf, 0, "a=setup:holdconn\r\n");
12741 break;
12742 default:
12743 break;
12744 }
12745
12746 if ((fingerprint = dtls->get_fingerprint(instance, AST_RTP_DTLS_HASH_SHA1))) {
12747 ast_str_append(a_buf, 0, "a=fingerprint:SHA-1 %s\r\n", fingerprint);
12748 }
12749 }
12750
12751
12752 static void add_codec_to_sdp(const struct sip_pvt *p,
12753 struct ast_format *format,
12754 struct ast_str **m_buf,
12755 struct ast_str **a_buf,
12756 int debug,
12757 int *min_packet_size)
12758 {
12759 int rtp_code;
12760 struct ast_format_list fmt;
12761 const char *mime;
12762 unsigned int rate;
12763
12764 if (debug)
12765 ast_verbose("Adding codec %d (%s) to SDP\n", format->id, ast_getformatname(format));
12766
12767 if (((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->rtp), 1, format, 0)) == -1) ||
12768 !(mime = ast_rtp_lookup_mime_subtype2(1, format, 0, ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0)) ||
12769 !(rate = ast_rtp_lookup_sample_rate2(1, format, 0))) {
12770 return;
12771 }
12772
12773 if (p->rtp) {
12774 struct ast_codec_pref *pref = &ast_rtp_instance_get_codecs(p->rtp)->pref;
12775 fmt = ast_codec_pref_getsize(pref, format);
12776 } else
12777 return;
12778 ast_str_append(m_buf, 0, " %d", rtp_code);
12779 ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code, mime, rate);
12780
12781 ast_format_sdp_generate(format, rtp_code, a_buf);
12782
12783 switch ((int) format->id) {
12784 case AST_FORMAT_G729A:
12785
12786 ast_str_append(a_buf, 0, "a=fmtp:%d annexb=no\r\n", rtp_code);
12787 break;
12788 case AST_FORMAT_G723_1:
12789
12790 ast_str_append(a_buf, 0, "a=fmtp:%d annexa=no\r\n", rtp_code);
12791 break;
12792 case AST_FORMAT_ILBC:
12793
12794 ast_str_append(a_buf, 0, "a=fmtp:%d mode=%d\r\n", rtp_code, fmt.cur_ms);
12795 break;
12796 case AST_FORMAT_SIREN7:
12797
12798 ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=32000\r\n", rtp_code);
12799 break;
12800 case AST_FORMAT_SIREN14:
12801
12802 ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=48000\r\n", rtp_code);
12803 break;
12804 case AST_FORMAT_G719:
12805
12806 ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=64000\r\n", rtp_code);
12807 break;
12808 }
12809
12810 if (fmt.cur_ms && (fmt.cur_ms < *min_packet_size))
12811 *min_packet_size = fmt.cur_ms;
12812
12813
12814 if ((*min_packet_size)==0 && fmt.cur_ms)
12815 *min_packet_size = fmt.cur_ms;
12816 }
12817
12818
12819
12820 static void add_vcodec_to_sdp(const struct sip_pvt *p, struct ast_format *format,
12821 struct ast_str **m_buf, struct ast_str **a_buf,
12822 int debug, int *min_packet_size)
12823 {
12824 int rtp_code;
12825 const char *subtype;
12826 unsigned int rate;
12827
12828 if (!p->vrtp)
12829 return;
12830
12831 if (debug)
12832 ast_verbose("Adding video codec %d (%s) to SDP\n", format->id, ast_getformatname(format));
12833
12834 if (((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->vrtp), 1, format, 0)) == -1) ||
12835 !(subtype = ast_rtp_lookup_mime_subtype2(1, format, 0, 0)) ||
12836 !(rate = ast_rtp_lookup_sample_rate2(1, format, 0))) {
12837 return;
12838 }
12839
12840 ast_str_append(m_buf, 0, " %d", rtp_code);
12841 ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code, subtype, rate);
12842
12843 ast_format_sdp_generate(format, rtp_code, a_buf);
12844 }
12845
12846
12847 static void add_tcodec_to_sdp(const struct sip_pvt *p, struct ast_format *format,
12848 struct ast_str **m_buf, struct ast_str **a_buf,
12849 int debug, int *min_packet_size)
12850 {
12851 int rtp_code;
12852
12853 if (!p->trtp)
12854 return;
12855
12856 if (debug)
12857 ast_verbose("Adding text codec %d (%s) to SDP\n", format->id, ast_getformatname(format));
12858
12859 if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->trtp), 1, format, 0)) == -1)
12860 return;
12861
12862 ast_str_append(m_buf, 0, " %d", rtp_code);
12863 ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
12864 ast_rtp_lookup_mime_subtype2(1, format, 0, 0),
12865 ast_rtp_lookup_sample_rate2(1, format, 0));
12866
12867
12868 if (format->id == AST_FORMAT_T140RED) {
12869 struct ast_format tmp_fmt;
12870 int t140code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->trtp), 1, ast_format_set(&tmp_fmt, AST_FORMAT_T140, 0), 0);
12871 ast_str_append(a_buf, 0, "a=fmtp:%d %d/%d/%d\r\n", rtp_code,
12872 t140code,
12873 t140code,
12874 t140code);
12875
12876 }
12877 }
12878
12879
12880
12881 static unsigned int t38_get_rate(enum ast_control_t38_rate rate)
12882 {
12883 switch (rate) {
12884 case AST_T38_RATE_2400:
12885 return 2400;
12886 case AST_T38_RATE_4800:
12887 return 4800;
12888 case AST_T38_RATE_7200:
12889 return 7200;
12890 case AST_T38_RATE_9600:
12891 return 9600;
12892 case AST_T38_RATE_12000:
12893 return 12000;
12894 case AST_T38_RATE_14400:
12895 return 14400;
12896 default:
12897 return 0;
12898 }
12899 }
12900
12901
12902 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
12903 struct ast_str **m_buf, struct ast_str **a_buf,
12904 int debug)
12905 {
12906 int rtp_code;
12907
12908 if (debug)
12909 ast_verbose("Adding non-codec 0x%x (%s) to SDP\n", format, ast_rtp_lookup_mime_subtype2(0, NULL, format, 0));
12910 if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->rtp), 0, NULL, format)) == -1)
12911 return;
12912
12913 ast_str_append(m_buf, 0, " %d", rtp_code);
12914 ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
12915 ast_rtp_lookup_mime_subtype2(0, NULL, format, 0),
12916 ast_rtp_lookup_sample_rate2(0, NULL, format));
12917 if (format == AST_RTP_DTMF)
12918 ast_str_append(a_buf, 0, "a=fmtp:%d 0-16\r\n", rtp_code);
12919 }
12920
12921
12922
12923
12924 static void get_our_media_address(struct sip_pvt *p, int needvideo, int needtext,
12925 struct ast_sockaddr *addr, struct ast_sockaddr *vaddr,
12926 struct ast_sockaddr *taddr, struct ast_sockaddr *dest,
12927 struct ast_sockaddr *vdest, struct ast_sockaddr *tdest)
12928 {
12929 int use_externip = 0;
12930
12931
12932 ast_rtp_instance_get_local_address(p->rtp, addr);
12933 if (p->vrtp) {
12934 ast_rtp_instance_get_local_address(p->vrtp, vaddr);
12935 }
12936 if (p->trtp) {
12937 ast_rtp_instance_get_local_address(p->trtp, taddr);
12938 }
12939
12940
12941
12942
12943 use_externip = ast_sockaddr_cmp_addr(&p->ourip, addr);
12944
12945
12946
12947 if (!ast_sockaddr_isnull(&p->redirip)) {
12948 ast_sockaddr_copy(dest, &p->redirip);
12949 } else {
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961 ast_sockaddr_copy(dest,
12962 !ast_sockaddr_isnull(&media_address) ? &media_address :
12963 !ast_sockaddr_is_any(addr) && !use_externip ? addr :
12964 &p->ourip);
12965 ast_sockaddr_set_port(dest, ast_sockaddr_port(addr));
12966 }
12967
12968 if (needvideo) {
12969
12970 if (!ast_sockaddr_isnull(&p->vredirip)) {
12971 ast_sockaddr_copy(vdest, &p->vredirip);
12972 } else {
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984 ast_sockaddr_copy(vdest,
12985 !ast_sockaddr_isnull(&media_address) ? &media_address :
12986 !ast_sockaddr_is_any(vaddr) && !use_externip ? vaddr :
12987 &p->ourip);
12988 ast_sockaddr_set_port(vdest, ast_sockaddr_port(vaddr));
12989 }
12990 }
12991
12992 if (needtext) {
12993
12994 if (!ast_sockaddr_isnull(&p->tredirip)) {
12995 ast_sockaddr_copy(tdest, &p->tredirip);
12996 } else {
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008 ast_sockaddr_copy(tdest,
13009 !ast_sockaddr_isnull(&media_address) ? &media_address :
13010 !ast_sockaddr_is_any(taddr) && !use_externip ? taddr :
13011 &p->ourip);
13012 ast_sockaddr_set_port(tdest, ast_sockaddr_port(taddr));
13013 }
13014 }
13015 }
13016
13017 static void get_crypto_attrib(struct sip_pvt *p, struct sip_srtp *srtp, const char **a_crypto)
13018 {
13019 int taglen = 80;
13020
13021
13022 if (srtp) {
13023 if (!srtp->crypto) {
13024 srtp->crypto = sdp_crypto_setup();
13025 }
13026
13027 if (p->dtls_cfg.enabled) {
13028
13029 return;
13030 }
13031
13032
13033 if (ast_test_flag(srtp, SRTP_CRYPTO_TAG_80)) {
13034 taglen = 80;
13035 } else if (ast_test_flag(&p->flags[2], SIP_PAGE3_SRTP_TAG_32) ||
13036 ast_test_flag(srtp, SRTP_CRYPTO_TAG_32)) {
13037 taglen = 32;
13038 }
13039
13040 if (srtp->crypto && (sdp_crypto_offer(srtp->crypto, taglen) >= 0)) {
13041 *a_crypto = sdp_crypto_attrib(srtp->crypto);
13042 }
13043
13044 if (!*a_crypto) {
13045 ast_log(LOG_WARNING, "No SRTP key management enabled\n");
13046 }
13047 }
13048 }
13049
13050 static char *get_sdp_rtp_profile(const struct sip_pvt *p, unsigned int secure, struct ast_rtp_instance *instance)
13051 {
13052 struct ast_rtp_engine_dtls *dtls;
13053
13054 if ((dtls = ast_rtp_instance_get_dtls(instance)) && dtls->active(instance)) {
13055 return ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF) ? "UDP/TLS/RTP/SAVPF" : "UDP/TLS/RTP/SAVP";
13056 } else {
13057 if (ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {
13058 return secure ? "RTP/SAVPF" : "RTP/AVPF";
13059 } else {
13060 return secure ? "RTP/SAVP" : "RTP/AVP";
13061 }
13062 }
13063 }
13064
13065
13066
13067
13068
13069
13070
13071 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38)
13072 {
13073 struct ast_format_cap *alreadysent = ast_format_cap_alloc_nolock();
13074 struct ast_format_cap *tmpcap = ast_format_cap_alloc_nolock();
13075 int res = AST_SUCCESS;
13076 int doing_directmedia = FALSE;
13077 struct ast_sockaddr addr = { {0,} };
13078 struct ast_sockaddr vaddr = { {0,} };
13079 struct ast_sockaddr taddr = { {0,} };
13080 struct ast_sockaddr udptladdr = { {0,} };
13081 struct ast_sockaddr dest = { {0,} };
13082 struct ast_sockaddr vdest = { {0,} };
13083 struct ast_sockaddr tdest = { {0,} };
13084 struct ast_sockaddr udptldest = { {0,} };
13085
13086
13087 struct offered_media *offer;
13088 char *version = "v=0\r\n";
13089 char subject[256];
13090 char owner[256];
13091 char connection[256];
13092 char *session_time = "t=0 0\r\n";
13093 char bandwidth[256] = "";
13094 char *hold = "";
13095 struct ast_str *m_audio = ast_str_alloca(256);
13096 struct ast_str *m_video = ast_str_alloca(256);
13097 struct ast_str *m_text = ast_str_alloca(256);
13098 struct ast_str *m_modem = ast_str_alloca(256);
13099 struct ast_str *a_audio = ast_str_create(256);
13100 struct ast_str *a_video = ast_str_create(256);
13101 struct ast_str *a_text = ast_str_create(256);
13102 struct ast_str *a_modem = ast_str_alloca(1024);
13103 const char *a_crypto = NULL;
13104 const char *v_a_crypto = NULL;
13105 const char *t_a_crypto = NULL;
13106
13107 int x;
13108 struct ast_format tmp_fmt;
13109 int needaudio = FALSE;
13110 int needvideo = FALSE;
13111 int needtext = FALSE;
13112 int debug = sip_debug_test_pvt(p);
13113 int min_audio_packet_size = 0;
13114 int min_video_packet_size = 0;
13115 int min_text_packet_size = 0;
13116
13117 char codecbuf[SIPBUFSIZE];
13118 char buf[SIPBUFSIZE];
13119
13120
13121 snprintf(subject, sizeof(subject), "s=%s\r\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
13122
13123 if (!alreadysent || !tmpcap) {
13124 res = AST_FAILURE;
13125 goto add_sdp_cleanup;
13126 }
13127 if (!p->rtp) {
13128 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
13129 res = AST_FAILURE;
13130 goto add_sdp_cleanup;
13131
13132 }
13133
13134
13135
13136
13137 if (!p->sessionid) {
13138 p->sessionid = (int)ast_random();
13139 p->sessionversion = p->sessionid;
13140 } else {
13141 if (oldsdp == FALSE)
13142 p->sessionversion++;
13143 }
13144
13145 if (add_audio) {
13146 doing_directmedia = (!ast_sockaddr_isnull(&p->redirip) && !(ast_format_cap_is_empty(p->redircaps))) ? TRUE : FALSE;
13147
13148 if ((ast_format_cap_has_type(p->jointcaps, AST_FORMAT_TYPE_VIDEO)) && !p->novideo) {
13149 ast_format_cap_joint_copy(p->jointcaps, p->redircaps, tmpcap);
13150 if (doing_directmedia && !ast_format_cap_has_type(tmpcap, AST_FORMAT_TYPE_VIDEO)) {
13151 ast_debug(2, "This call needs video offers, but caller probably did not offer it!\n");
13152 } else if (p->vrtp) {
13153 needvideo = TRUE;
13154 ast_debug(2, "This call needs video offers!\n");
13155 } else {
13156 ast_debug(2, "This call needs video offers, but there's no video support enabled!\n");
13157 }
13158 }
13159
13160 if ((ast_format_cap_has_type(p->jointcaps, AST_FORMAT_TYPE_TEXT)) && !p->notext) {
13161 if (sipdebug_text)
13162 ast_verbose("We think we can do text\n");
13163 if (p->trtp) {
13164 if (sipdebug_text) {
13165 ast_verbose("And we have a text rtp object\n");
13166 }
13167 needtext = TRUE;
13168 ast_debug(2, "This call needs text offers! \n");
13169 } else {
13170 ast_debug(2, "This call needs text offers, but there's no text support enabled ! \n");
13171 }
13172 }
13173 }
13174
13175 get_our_media_address(p, needvideo, needtext, &addr, &vaddr, &taddr, &dest, &vdest, &tdest);
13176
13177 snprintf(owner, sizeof(owner), "o=%s %d %d IN %s %s\r\n",
13178 ast_strlen_zero(global_sdpowner) ? "-" : global_sdpowner,
13179 p->sessionid, p->sessionversion,
13180 (ast_sockaddr_is_ipv6(&dest) && !ast_sockaddr_is_ipv4_mapped(&dest)) ?
13181 "IP6" : "IP4",
13182 ast_sockaddr_stringify_addr_remote(&dest));
13183
13184 snprintf(connection, sizeof(connection), "c=IN %s %s\r\n",
13185 (ast_sockaddr_is_ipv6(&dest) && !ast_sockaddr_is_ipv4_mapped(&dest)) ?
13186 "IP6" : "IP4",
13187 ast_sockaddr_stringify_addr_remote(&dest));
13188
13189 if (add_audio) {
13190 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_ONEDIR) {
13191 hold = "a=recvonly\r\n";
13192 doing_directmedia = FALSE;
13193 } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_INACTIVE) {
13194 hold = "a=inactive\r\n";
13195 doing_directmedia = FALSE;
13196 } else {
13197 hold = "a=sendrecv\r\n";
13198 }
13199
13200 ast_format_cap_copy(tmpcap, p->jointcaps);
13201
13202
13203 ast_debug(1, "** Our capability: %s Video flag: %s Text flag: %s\n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), tmpcap),
13204 p->novideo ? "True" : "False", p->notext ? "True" : "False");
13205 ast_debug(1, "** Our prefcodec: %s \n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), p->prefcaps));
13206
13207 if (doing_directmedia) {
13208 ast_format_cap_joint_copy(p->jointcaps, p->redircaps, tmpcap);
13209 ast_debug(1, "** Our native-bridge filtered capablity: %s\n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), tmpcap));
13210 }
13211
13212
13213 if (ast_format_cap_has_type(tmpcap, AST_FORMAT_TYPE_AUDIO))
13214 needaudio = TRUE;
13215
13216 if (debug) {
13217 ast_verbose("Audio is at %s\n", ast_sockaddr_stringify_port(&addr));
13218 }
13219
13220
13221
13222 if (needvideo) {
13223 get_crypto_attrib(p, p->vsrtp, &v_a_crypto);
13224 ast_str_append(&m_video, 0, "m=video %d %s", ast_sockaddr_port(&vdest),
13225 get_sdp_rtp_profile(p, v_a_crypto ? 1 : 0, p->vrtp));
13226
13227
13228 if (p->maxcallbitrate)
13229 snprintf(bandwidth, sizeof(bandwidth), "b=CT:%d\r\n", p->maxcallbitrate);
13230 if (debug) {
13231 ast_verbose("Video is at %s\n", ast_sockaddr_stringify(&vdest));
13232 }
13233
13234 if (!doing_directmedia) {
13235 if (ast_test_flag(&p->flags[2], SIP_PAGE3_ICE_SUPPORT)) {
13236 add_ice_to_sdp(p->vrtp, &a_video);
13237 }
13238
13239 add_dtls_to_sdp(p->vrtp, &a_video);
13240 }
13241 }
13242
13243
13244
13245 if (needtext) {
13246 if (sipdebug_text)
13247 ast_verbose("Lets set up the text sdp\n");
13248 get_crypto_attrib(p, p->tsrtp, &t_a_crypto);
13249 ast_str_append(&m_text, 0, "m=text %d %s", ast_sockaddr_port(&tdest),
13250 get_sdp_rtp_profile(p, t_a_crypto ? 1 : 0, p->trtp));
13251 if (debug) {
13252 ast_verbose("Text is at %s\n", ast_sockaddr_stringify(&taddr));
13253 }
13254
13255 if (!doing_directmedia) {
13256 if (ast_test_flag(&p->flags[2], SIP_PAGE3_ICE_SUPPORT)) {
13257 add_ice_to_sdp(p->trtp, &a_text);
13258 }
13259
13260 add_dtls_to_sdp(p->trtp, &a_text);
13261 }
13262 }
13263
13264
13265
13266
13267
13268
13269 get_crypto_attrib(p, p->srtp, &a_crypto);
13270 ast_str_append(&m_audio, 0, "m=audio %d %s", ast_sockaddr_port(&dest),
13271 get_sdp_rtp_profile(p, a_crypto ? 1 : 0, p->rtp));
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282 ast_format_cap_iter_start(p->prefcaps);
13283 while (!(ast_format_cap_iter_next(p->prefcaps, &tmp_fmt))) {
13284 if (AST_FORMAT_GET_TYPE(tmp_fmt.id) != AST_FORMAT_TYPE_AUDIO ||
13285 !ast_format_cap_iscompatible(tmpcap, &tmp_fmt)) {
13286 continue;
13287 }
13288 add_codec_to_sdp(p, &tmp_fmt, &m_audio, &a_audio, debug, &min_audio_packet_size);
13289 ast_format_cap_add(alreadysent, &tmp_fmt);
13290 }
13291 ast_format_cap_iter_end(p->prefcaps);
13292
13293
13294 for (x = 0; x < AST_CODEC_PREF_SIZE; x++) {
13295 struct ast_format pref;
13296
13297 if (!(ast_codec_pref_index(&p->prefs, x, &pref)))
13298 break;
13299
13300 if (!ast_format_cap_get_compatible_format(tmpcap, &pref, &tmp_fmt))
13301 continue;
13302
13303 if (ast_format_cap_iscompatible(alreadysent, &tmp_fmt))
13304 continue;
13305
13306 if (AST_FORMAT_GET_TYPE(tmp_fmt.id) == AST_FORMAT_TYPE_AUDIO) {
13307 add_codec_to_sdp(p, &tmp_fmt, &m_audio, &a_audio, debug, &min_audio_packet_size);
13308 } else if (needvideo && (AST_FORMAT_GET_TYPE(tmp_fmt.id) == AST_FORMAT_TYPE_VIDEO)) {
13309 add_vcodec_to_sdp(p, &tmp_fmt, &m_video, &a_video, debug, &min_video_packet_size);
13310 } else if (needtext && (AST_FORMAT_GET_TYPE(tmp_fmt.id) == AST_FORMAT_TYPE_TEXT)) {
13311 add_tcodec_to_sdp(p, &tmp_fmt, &m_text, &a_text, debug, &min_text_packet_size);
13312 }
13313
13314 ast_format_cap_add(alreadysent, &tmp_fmt);
13315 }
13316
13317
13318 ast_format_cap_iter_start(tmpcap);
13319 while (!(ast_format_cap_iter_next(tmpcap, &tmp_fmt))) {
13320 if (ast_format_cap_iscompatible(alreadysent, &tmp_fmt))
13321 continue;
13322
13323 if (AST_FORMAT_GET_TYPE(tmp_fmt.id) == AST_FORMAT_TYPE_AUDIO) {
13324 add_codec_to_sdp(p, &tmp_fmt, &m_audio, &a_audio, debug, &min_audio_packet_size);
13325 } else if (needvideo && (AST_FORMAT_GET_TYPE(tmp_fmt.id) == AST_FORMAT_TYPE_VIDEO)) {
13326 add_vcodec_to_sdp(p, &tmp_fmt, &m_video, &a_video, debug, &min_video_packet_size);
13327 } else if (needtext && (AST_FORMAT_GET_TYPE(tmp_fmt.id) == AST_FORMAT_TYPE_TEXT)) {
13328 add_tcodec_to_sdp(p, &tmp_fmt, &m_text, &a_text, debug, &min_text_packet_size);
13329 }
13330 }
13331 ast_format_cap_iter_end(tmpcap);
13332
13333
13334 for (x = 1LL; x <= AST_RTP_MAX; x <<= 1) {
13335 if (!(p->jointnoncodeccapability & x))
13336 continue;
13337
13338 add_noncodec_to_sdp(p, x, &m_audio, &a_audio, debug);
13339 }
13340
13341 ast_debug(3, "-- Done with adding codecs to SDP\n");
13342
13343 if (!p->owner || !ast_internal_timing_enabled(p->owner))
13344 ast_str_append(&a_audio, 0, "a=silenceSupp:off - - - -\r\n");
13345
13346 if (min_audio_packet_size)
13347 ast_str_append(&a_audio, 0, "a=ptime:%d\r\n", min_audio_packet_size);
13348
13349
13350 if (min_video_packet_size)
13351 ast_str_append(&a_video, 0, "a=ptime:%d\r\n", min_video_packet_size);
13352
13353
13354 if (min_text_packet_size)
13355 ast_str_append(&a_text, 0, "a=ptime:%d\r\n", min_text_packet_size);
13356
13357 if (!doing_directmedia) {
13358 if (ast_test_flag(&p->flags[2], SIP_PAGE3_ICE_SUPPORT)) {
13359 add_ice_to_sdp(p->rtp, &a_audio);
13360 }
13361
13362 add_dtls_to_sdp(p->rtp, &a_audio);
13363 }
13364 }
13365
13366 if (add_t38) {
13367
13368 ast_udptl_get_us(p->udptl, &udptladdr);
13369
13370
13371 ast_sockaddr_copy(&udptldest, &p->ourip);
13372 ast_sockaddr_set_port(&udptldest, ast_sockaddr_port(&udptladdr));
13373
13374 if (debug) {
13375 ast_debug(1, "T.38 UDPTL is at %s port %d\n", ast_sockaddr_stringify_addr(&p->ourip), ast_sockaddr_port(&udptladdr));
13376 }
13377
13378
13379
13380
13381 ast_str_append(&m_modem, 0, "m=image %d udptl t38\r\n", ast_sockaddr_port(&udptldest));
13382
13383 if (ast_sockaddr_cmp(&udptldest, &dest)) {
13384 ast_str_append(&m_modem, 0, "c=IN %s %s\r\n",
13385 (ast_sockaddr_is_ipv6(&udptldest) && !ast_sockaddr_is_ipv4_mapped(&udptldest)) ?
13386 "IP6" : "IP4", ast_sockaddr_stringify_addr_remote(&udptldest));
13387 }
13388
13389 ast_str_append(&a_modem, 0, "a=T38FaxVersion:%d\r\n", p->t38.our_parms.version);
13390 ast_str_append(&a_modem, 0, "a=T38MaxBitRate:%d\r\n", t38_get_rate(p->t38.our_parms.rate));
13391 if (p->t38.our_parms.fill_bit_removal) {
13392 ast_str_append(&a_modem, 0, "a=T38FaxFillBitRemoval\r\n");
13393 }
13394 if (p->t38.our_parms.transcoding_mmr) {
13395 ast_str_append(&a_modem, 0, "a=T38FaxTranscodingMMR\r\n");
13396 }
13397 if (p->t38.our_parms.transcoding_jbig) {
13398 ast_str_append(&a_modem, 0, "a=T38FaxTranscodingJBIG\r\n");
13399 }
13400 switch (p->t38.our_parms.rate_management) {
13401 case AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF:
13402 ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:transferredTCF\r\n");
13403 break;
13404 case AST_T38_RATE_MANAGEMENT_LOCAL_TCF:
13405 ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:localTCF\r\n");
13406 break;
13407 }
13408 ast_str_append(&a_modem, 0, "a=T38FaxMaxDatagram:%u\r\n", ast_udptl_get_local_max_datagram(p->udptl));
13409 switch (ast_udptl_get_error_correction_scheme(p->udptl)) {
13410 case UDPTL_ERROR_CORRECTION_NONE:
13411 break;
13412 case UDPTL_ERROR_CORRECTION_FEC:
13413 ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPFEC\r\n");
13414 break;
13415 case UDPTL_ERROR_CORRECTION_REDUNDANCY:
13416 ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPRedundancy\r\n");
13417 break;
13418 }
13419 }
13420
13421 if (needaudio)
13422 ast_str_append(&m_audio, 0, "\r\n");
13423 if (needvideo)
13424 ast_str_append(&m_video, 0, "\r\n");
13425 if (needtext)
13426 ast_str_append(&m_text, 0, "\r\n");
13427
13428 add_header(resp, "Content-Type", "application/sdp");
13429 add_content(resp, version);
13430 add_content(resp, owner);
13431 add_content(resp, subject);
13432 add_content(resp, connection);
13433
13434 if (needvideo) {
13435 add_content(resp, bandwidth);
13436 }
13437 add_content(resp, session_time);
13438
13439 if (!AST_LIST_EMPTY(&p->offered_media)) {
13440 AST_LIST_TRAVERSE(&p->offered_media, offer, next) {
13441 switch (offer->type) {
13442 case SDP_AUDIO:
13443 if (needaudio) {
13444 add_content(resp, ast_str_buffer(m_audio));
13445 add_content(resp, ast_str_buffer(a_audio));
13446 add_content(resp, hold);
13447 if (a_crypto) {
13448 add_content(resp, a_crypto);
13449 }
13450 } else {
13451 add_content(resp, offer->decline_m_line);
13452 }
13453 break;
13454 case SDP_VIDEO:
13455 if (needvideo) {
13456 add_content(resp, ast_str_buffer(m_video));
13457 add_content(resp, ast_str_buffer(a_video));
13458 add_content(resp, hold);
13459 if (v_a_crypto) {
13460 add_content(resp, v_a_crypto);
13461 }
13462 } else {
13463 add_content(resp, offer->decline_m_line);
13464 }
13465 break;
13466 case SDP_TEXT:
13467 if (needtext) {
13468 add_content(resp, ast_str_buffer(m_text));
13469 add_content(resp, ast_str_buffer(a_text));
13470 add_content(resp, hold);
13471 if (t_a_crypto) {
13472 add_content(resp, t_a_crypto);
13473 }
13474 } else {
13475 add_content(resp, offer->decline_m_line);
13476 }
13477 break;
13478 case SDP_IMAGE:
13479 if (add_t38) {
13480 add_content(resp, ast_str_buffer(m_modem));
13481 add_content(resp, ast_str_buffer(a_modem));
13482 } else {
13483 add_content(resp, offer->decline_m_line);
13484 }
13485 break;
13486 case SDP_UNKNOWN:
13487 add_content(resp, offer->decline_m_line);
13488 break;
13489 }
13490 }
13491 } else {
13492
13493 if (needaudio) {
13494 add_content(resp, ast_str_buffer(m_audio));
13495 add_content(resp, ast_str_buffer(a_audio));
13496 add_content(resp, hold);
13497 if (a_crypto) {
13498 add_content(resp, a_crypto);
13499 }
13500 }
13501 if (needvideo) {
13502 add_content(resp, ast_str_buffer(m_video));
13503 add_content(resp, ast_str_buffer(a_video));
13504 add_content(resp, hold);
13505 if (v_a_crypto) {
13506 add_content(resp, v_a_crypto);
13507 }
13508 }
13509 if (needtext) {
13510 add_content(resp, ast_str_buffer(m_text));
13511 add_content(resp, ast_str_buffer(a_text));
13512 add_content(resp, hold);
13513 if (t_a_crypto) {
13514 add_content(resp, t_a_crypto);
13515 }
13516 }
13517 if (add_t38) {
13518 add_content(resp, ast_str_buffer(m_modem));
13519 add_content(resp, ast_str_buffer(a_modem));
13520 }
13521 }
13522
13523
13524 p->lastrtprx = p->lastrtptx = time(NULL);
13525
13526
13527
13528
13529
13530 ao2_lock(dialogs_rtpcheck);
13531 ao2_t_unlink(dialogs_rtpcheck, p, "unlink pvt into dialogs_rtpcheck container");
13532 ao2_t_link(dialogs_rtpcheck, p, "link pvt into dialogs_rtpcheck container");
13533 ao2_unlock(dialogs_rtpcheck);
13534
13535 ast_debug(3, "Done building SDP. Settling with this capability: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, tmpcap));
13536
13537 add_sdp_cleanup:
13538 ast_free(a_text);
13539 ast_free(a_video);
13540 ast_free(a_audio);
13541 alreadysent = ast_format_cap_destroy(alreadysent);
13542 tmpcap = ast_format_cap_destroy(tmpcap);
13543
13544 return res;
13545 }
13546
13547
13548 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
13549 {
13550 struct sip_request resp;
13551 uint32_t seqno;
13552
13553 if (sscanf(sip_get_header(req, "CSeq"), "%30u ", &seqno) != 1) {
13554 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", sip_get_header(req, "CSeq"));
13555 return -1;
13556 }
13557 respprep(&resp, p, msg, req);
13558 if (p->udptl) {
13559 add_sdp(&resp, p, 0, 0, 1);
13560 } else
13561 ast_log(LOG_ERROR, "Can't add SDP to response, since we have no UDPTL session allocated. Call-ID %s\n", p->callid);
13562 if (retrans && !p->pendinginvite)
13563 p->pendinginvite = seqno;
13564 return send_response(p, &resp, retrans, seqno);
13565 }
13566
13567
13568 static void copy_request(struct sip_request *dst, const struct sip_request *src)
13569 {
13570
13571
13572
13573 struct ast_str *duplicate = dst->data;
13574 struct ast_str *duplicate_content = dst->content;
13575
13576
13577
13578 *dst = *src;
13579 dst->data = duplicate;
13580 dst->content = duplicate_content;
13581
13582
13583 if (!dst->data && !(dst->data = ast_str_create(ast_str_strlen(src->data) + 1))) {
13584 return;
13585 }
13586 ast_str_copy_string(&dst->data, src->data);
13587
13588
13589 if (src->content) {
13590 if (!dst->content && !(dst->content = ast_str_create(ast_str_strlen(src->content) + 1))) {
13591 return;
13592 }
13593 ast_str_copy_string(&dst->content, src->content);
13594 }
13595 }
13596
13597 static void add_cc_call_info_to_response(struct sip_pvt *p, struct sip_request *resp)
13598 {
13599 char uri[SIPBUFSIZE];
13600 struct ast_str *header = ast_str_alloca(SIPBUFSIZE);
13601 struct ast_cc_agent *agent = find_sip_cc_agent_by_original_callid(p);
13602 struct sip_cc_agent_pvt *agent_pvt;
13603
13604 if (!agent) {
13605
13606
13607
13608 ast_log(LOG_WARNING, "Can't find SIP CC agent for call '%s' even though OFFER_CC flag was set?\n", p->callid);
13609 return;
13610 }
13611
13612 agent_pvt = agent->private_data;
13613
13614 if (!ast_strlen_zero(agent_pvt->subscribe_uri)) {
13615 ast_copy_string(uri, agent_pvt->subscribe_uri, sizeof(uri));
13616 } else {
13617 generate_uri(p, uri, sizeof(uri));
13618 ast_copy_string(agent_pvt->subscribe_uri, uri, sizeof(agent_pvt->subscribe_uri));
13619 }
13620
13621
13622
13623
13624 ast_str_set(&header, 0, "<%s>;purpose=call-completion;m=%s", uri, "NR");
13625 add_header(resp, "Call-Info", ast_str_buffer(header));
13626 ao2_ref(agent, -1);
13627 }
13628
13629
13630
13631
13632 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable, int oldsdp, int rpid)
13633 {
13634 struct sip_request resp;
13635 uint32_t seqno;
13636 if (sscanf(sip_get_header(req, "CSeq"), "%30u ", &seqno) != 1) {
13637 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", sip_get_header(req, "CSeq"));
13638 return -1;
13639 }
13640 respprep(&resp, p, msg, req);
13641 if (rpid == TRUE) {
13642 add_rpid(&resp, p);
13643 }
13644 if (ast_test_flag(&p->flags[0], SIP_OFFER_CC)) {
13645 add_cc_call_info_to_response(p, &resp);
13646 }
13647 if (p->rtp) {
13648 if (!p->autoframing && !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
13649 ast_debug(1, "Setting framing from config on incoming call\n");
13650 ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(p->rtp), p->rtp, &p->prefs);
13651 }
13652 ast_rtp_instance_activate(p->rtp);
13653 try_suggested_sip_codec(p);
13654 if (p->t38.state == T38_ENABLED) {
13655 add_sdp(&resp, p, oldsdp, TRUE, TRUE);
13656 } else {
13657 add_sdp(&resp, p, oldsdp, TRUE, FALSE);
13658 }
13659 } else
13660 ast_log(LOG_ERROR, "Can't add SDP to response, since we have no RTP session allocated. Call-ID %s\n", p->callid);
13661 if (reliable && !p->pendinginvite)
13662 p->pendinginvite = seqno;
13663 add_required_respheader(&resp);
13664 return send_response(p, &resp, reliable, seqno);
13665 }
13666
13667
13668 static int determine_firstline_parts(struct sip_request *req)
13669 {
13670 char *e = ast_skip_blanks(req->data->str);
13671 char *local_rlpart1;
13672
13673 if (!*e)
13674 return -1;
13675 req->rlpart1 = e - req->data->str;
13676 local_rlpart1 = e;
13677 e = ast_skip_nonblanks(e);
13678 if (*e)
13679 *e++ = '\0';
13680
13681 e = ast_skip_blanks(e);
13682 if ( !*e )
13683 return -1;
13684 ast_trim_blanks(e);
13685
13686 if (!strcasecmp(local_rlpart1, "SIP/2.0") ) {
13687 if (strlen(e) < 3)
13688 return -1;
13689 req->rlpart2 = e - req->data->str;
13690 } else {
13691 if ( *e == '<' ) {
13692 ast_debug(3, "Oops. Bogus uri in <> %s\n", e);
13693 e++;
13694 if (!*e)
13695 return -1;
13696 }
13697 req->rlpart2 = e - req->data->str;
13698 e = ast_skip_nonblanks(e);
13699 if (*e)
13700 *e++ = '\0';
13701 e = ast_skip_blanks(e);
13702 if (strcasecmp(e, "SIP/2.0") ) {
13703 ast_debug(3, "Skipping packet - Bad request protocol %s\n", e);
13704 return -1;
13705 }
13706 }
13707 return 1;
13708 }
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp)
13724 {
13725 struct sip_request req;
13726
13727 reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ? SIP_UPDATE : SIP_INVITE, 0, 1);
13728
13729 add_header(&req, "Allow", ALLOWED_METHODS);
13730 add_supported(p, &req);
13731 if (sipdebug) {
13732 if (oldsdp == TRUE)
13733 add_header(&req, "X-asterisk-Info", "SIP re-invite (Session-Timers)");
13734 else
13735 add_header(&req, "X-asterisk-Info", "SIP re-invite (External RTP bridge)");
13736 }
13737
13738 if (ast_test_flag(&p->flags[0], SIP_SENDRPID))
13739 add_rpid(&req, p);
13740
13741 if (p->do_history) {
13742 append_history(p, "ReInv", "Re-invite sent");
13743 }
13744
13745 offered_media_list_destroy(p);
13746
13747 try_suggested_sip_codec(p);
13748 if (t38version) {
13749 add_sdp(&req, p, oldsdp, FALSE, TRUE);
13750 } else {
13751 add_sdp(&req, p, oldsdp, TRUE, FALSE);
13752 }
13753
13754
13755 initialize_initreq(p, &req);
13756 p->lastinvite = p->ocseq;
13757 ast_set_flag(&p->flags[0], SIP_OUTGOING);
13758 p->ongoing_reinvite = 1;
13759 return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
13760 }
13761
13762
13763 static char *remove_uri_parameters(char *uri)
13764 {
13765 char *atsign;
13766 atsign = strchr(uri, '@');
13767 if (!atsign) {
13768 atsign = uri;
13769 }
13770 atsign = strchr(atsign, ';');
13771 if (atsign)
13772 *atsign = '\0';
13773 return uri;
13774 }
13775
13776
13777 static void extract_uri(struct sip_pvt *p, struct sip_request *req)
13778 {
13779 char stripped[SIPBUFSIZE];
13780 char *c;
13781
13782 ast_copy_string(stripped, sip_get_header(req, "Contact"), sizeof(stripped));
13783 c = get_in_brackets(stripped);
13784
13785 c = remove_uri_parameters(c);
13786 if (!ast_strlen_zero(c)) {
13787 ast_string_field_set(p, uri, c);
13788 }
13789
13790 }
13791
13792
13793 static void build_contact(struct sip_pvt *p)
13794 {
13795 char tmp[SIPBUFSIZE];
13796 char *user = ast_uri_encode(p->exten, tmp, sizeof(tmp), ast_uri_sip_user);
13797
13798 if (p->socket.type == SIP_TRANSPORT_UDP) {
13799 ast_string_field_build(p, our_contact, "<sip:%s%s%s>", user,
13800 ast_strlen_zero(user) ? "" : "@", ast_sockaddr_stringify_remote(&p->ourip));
13801 } else {
13802 ast_string_field_build(p, our_contact, "<sip:%s%s%s;transport=%s>", user,
13803 ast_strlen_zero(user) ? "" : "@", ast_sockaddr_stringify_remote(&p->ourip),
13804 sip_get_transport(p->socket.type));
13805 }
13806 }
13807
13808
13809 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, const char * const explicit_uri)
13810 {
13811 struct ast_str *invite = ast_str_alloca(256);
13812 char from[256];
13813 char to[256];
13814 char tmp_n[SIPBUFSIZE/2];
13815 char tmp_l[SIPBUFSIZE/2];
13816 const char *l = NULL;
13817 const char *n = NULL;
13818 const char *d = NULL;
13819 const char *urioptions = "";
13820 int ourport;
13821 int cid_has_name = 1;
13822 int cid_has_num = 1;
13823 struct ast_party_id connected_id;
13824
13825 if (ast_test_flag(&p->flags[0], SIP_USEREQPHONE)) {
13826 const char *s = p->username;
13827
13828
13829
13830
13831
13832
13833 if (*s == '+')
13834 s++;
13835 for (; *s; s++) {
13836 if (!strchr(AST_DIGIT_ANYNUM, *s) )
13837 break;
13838 }
13839
13840 if (!*s)
13841 urioptions = ";user=phone";
13842 }
13843
13844
13845 snprintf(p->lastmsg, sizeof(p->lastmsg), "Init: %s", sip_methods[sipmethod].text);
13846
13847 if (ast_strlen_zero(p->fromdomain)) {
13848 d = ast_sockaddr_stringify_host_remote(&p->ourip);
13849 }
13850 if (p->owner) {
13851 connected_id = ast_channel_connected_effective_id(p->owner);
13852
13853 if ((ast_party_id_presentation(&connected_id) & AST_PRES_RESTRICTION) == AST_PRES_ALLOWED) {
13854 if (connected_id.number.valid) {
13855 l = connected_id.number.str;
13856 }
13857 if (connected_id.name.valid) {
13858 n = connected_id.name.str;
13859 }
13860 } else {
13861
13862
13863 l = "anonymous";
13864 n = CALLERID_UNKNOWN;
13865 d = FROMDOMAIN_INVALID;
13866 }
13867 }
13868
13869
13870
13871
13872
13873
13874
13875 if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->mwi_from)) {
13876 l = p->mwi_from;
13877 }
13878
13879 if (ast_strlen_zero(l)) {
13880 cid_has_num = 0;
13881 l = default_callerid;
13882 }
13883 if (ast_strlen_zero(n)) {
13884 cid_has_name = 0;
13885 n = l;
13886 }
13887
13888
13889 if (!ast_strlen_zero(p->fromuser))
13890 l = p->fromuser;
13891 else
13892 ast_string_field_set(p, fromuser, l);
13893
13894
13895 if (!ast_strlen_zero(p->fromname))
13896 n = p->fromname;
13897 else
13898 ast_string_field_set(p, fromname, n);
13899
13900
13901 if (!ast_strlen_zero(p->fromdomain))
13902 d = p->fromdomain;
13903 else
13904 ast_string_field_set(p, fromdomain, d);
13905
13906 ast_copy_string(tmp_l, l, sizeof(tmp_l));
13907 if (sip_cfg.pedanticsipchecking) {
13908 ast_escape_quoted(n, tmp_n, sizeof(tmp_n));
13909 n = tmp_n;
13910 ast_uri_encode(l, tmp_l, sizeof(tmp_l), ast_uri_sip_user);
13911 }
13912
13913 ourport = (p->fromdomainport) ? p->fromdomainport : ast_sockaddr_port(&p->ourip);
13914
13915
13916 if (cid_has_name || !cid_has_num) {
13917 snprintf(from, sizeof(from), "\"%s\" ", n);
13918 } else {
13919 from[0] = '\0';
13920 }
13921
13922 if (!sip_standard_port(p->socket.type, ourport)) {
13923 size_t offset = strlen(from);
13924 snprintf(&from[offset], sizeof(from) - offset, "<sip:%s@%s:%d>;tag=%s", tmp_l, d, ourport, p->tag);
13925 } else {
13926 size_t offset = strlen(from);
13927 snprintf(&from[offset], sizeof(from) - offset, "<sip:%s@%s>;tag=%s", tmp_l, d, p->tag);
13928 }
13929
13930 if (!ast_strlen_zero(explicit_uri)) {
13931 ast_str_set(&invite, 0, "%s", explicit_uri);
13932 } else {
13933
13934 if (!ast_strlen_zero(p->fullcontact)) {
13935
13936 ast_str_append(&invite, 0, "%s", p->fullcontact);
13937 } else {
13938
13939 ast_str_append(&invite, 0, "sip:");
13940 if (!ast_strlen_zero(p->username)) {
13941 n = p->username;
13942 if (sip_cfg.pedanticsipchecking) {
13943 ast_uri_encode(n, tmp_n, sizeof(tmp_n), ast_uri_sip_user);
13944 n = tmp_n;
13945 }
13946 ast_str_append(&invite, 0, "%s@", n);
13947 }
13948 ast_str_append(&invite, 0, "%s", p->tohost);
13949 if (p->portinuri) {
13950 ast_str_append(&invite, 0, ":%d", ast_sockaddr_port(&p->sa));
13951 }
13952 ast_str_append(&invite, 0, "%s", urioptions);
13953 }
13954 }
13955
13956
13957 if (p->options && !ast_strlen_zero(p->options->uri_options))
13958 ast_str_append(&invite, 0, ";%s", p->options->uri_options);
13959
13960
13961
13962
13963 ast_string_field_set(p, uri, ast_str_buffer(invite));
13964
13965 if (!ast_strlen_zero(p->todnid)) {
13966
13967 if (!strchr(p->todnid, '@')) {
13968
13969 snprintf(to, sizeof(to), "<sip:%s@%s>%s%s", p->todnid, p->tohost, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
13970 } else {
13971 snprintf(to, sizeof(to), "<sip:%s>%s%s", p->todnid, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
13972 }
13973 } else {
13974 if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->theirtag)) {
13975
13976 snprintf(to, sizeof(to), "<%s%s>;tag=%s", (strncasecmp(p->uri, "sip:", 4) ? "sip:" : ""), p->uri, p->theirtag);
13977 } else if (p->options && p->options->vxml_url) {
13978
13979 snprintf(to, sizeof(to), "<%s>;%s", p->uri, p->options->vxml_url);
13980 } else {
13981 snprintf(to, sizeof(to), "<%s>", p->uri);
13982 }
13983 }
13984
13985 init_req(req, sipmethod, p->uri);
13986
13987 snprintf(tmp_n, sizeof(tmp_n), "%u %s", ++p->ocseq, sip_methods[sipmethod].text);
13988
13989 add_header(req, "Via", p->via);
13990 add_max_forwards(p, req);
13991
13992
13993
13994
13995 add_route(req, p->route);
13996
13997 add_header(req, "From", from);
13998 add_header(req, "To", to);
13999 ast_string_field_set(p, exten, l);
14000 build_contact(p);
14001 add_header(req, "Contact", p->our_contact);
14002 add_header(req, "Call-ID", p->callid);
14003 add_header(req, "CSeq", tmp_n);
14004 if (!ast_strlen_zero(global_useragent)) {
14005 add_header(req, "User-Agent", global_useragent);
14006 }
14007 }
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017 static void add_diversion(struct sip_request *req, struct sip_pvt *pvt)
14018 {
14019 struct ast_party_id diverting_from;
14020 const char *reason;
14021 char header_text[256];
14022
14023
14024 if (!sip_cfg.send_diversion) {
14025 return;
14026 }
14027
14028 if (!pvt->owner) {
14029 return;
14030 }
14031
14032 diverting_from = ast_channel_redirecting_effective_from(pvt->owner);
14033 if (!diverting_from.number.valid
14034 || ast_strlen_zero(diverting_from.number.str)) {
14035 return;
14036 }
14037
14038 reason = sip_reason_code_to_str(ast_channel_redirecting(pvt->owner)->reason);
14039
14040
14041 if (!diverting_from.name.valid
14042 || ast_strlen_zero(diverting_from.name.str)) {
14043 snprintf(header_text, sizeof(header_text), "<sip:%s@%s>;reason=%s", diverting_from.number.str,
14044 ast_sockaddr_stringify_host_remote(&pvt->ourip), reason);
14045 } else {
14046 snprintf(header_text, sizeof(header_text), "\"%s\" <sip:%s@%s>;reason=%s",
14047 diverting_from.name.str, diverting_from.number.str,
14048 ast_sockaddr_stringify_host_remote(&pvt->ourip), reason);
14049 }
14050
14051 add_header(req, "Diversion", header_text);
14052 }
14053
14054 static int transmit_publish(struct sip_epa_entry *epa_entry, enum sip_publish_type publish_type, const char * const explicit_uri)
14055 {
14056 struct sip_pvt *pvt;
14057 int expires;
14058
14059 epa_entry->publish_type = publish_type;
14060
14061 if (!(pvt = sip_alloc(NULL, NULL, 0, SIP_PUBLISH, NULL, NULL))) {
14062 return -1;
14063 }
14064
14065 sip_pvt_lock(pvt);
14066
14067 if (create_addr(pvt, epa_entry->destination, NULL, TRUE)) {
14068 sip_pvt_unlock(pvt);
14069 dialog_unlink_all(pvt);
14070 dialog_unref(pvt, "create_addr failed in transmit_publish. Unref dialog");
14071 return -1;
14072 }
14073 ast_sip_ouraddrfor(&pvt->sa, &pvt->ourip, pvt);
14074 ast_set_flag(&pvt->flags[0], SIP_OUTGOING);
14075 expires = (publish_type == SIP_PUBLISH_REMOVE) ? 0 : DEFAULT_PUBLISH_EXPIRES;
14076 pvt->expiry = expires;
14077
14078
14079 ao2_ref(epa_entry, +1);
14080 pvt->epa_entry = epa_entry;
14081
14082 transmit_invite(pvt, SIP_PUBLISH, FALSE, 2, explicit_uri);
14083 sip_pvt_unlock(pvt);
14084 sip_scheddestroy(pvt, DEFAULT_TRANS_TIMEOUT);
14085 dialog_unref(pvt, "Done with the sip_pvt allocated for transmitting PUBLISH");
14086 return 0;
14087 }
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init, const char * const explicit_uri)
14099 {
14100 struct sip_request req;
14101 struct ast_variable *var;
14102
14103 if (init) {
14104 p->branch ^= ast_random();
14105 p->invite_branch = p->branch;
14106 build_via(p);
14107 }
14108 if (init > 1) {
14109 initreqprep(&req, p, sipmethod, explicit_uri);
14110 } else {
14111
14112 reqprep(&req, p, sipmethod, 0, init ? 0 : 1);
14113 }
14114
14115 if (p->options && p->options->auth) {
14116 add_header(&req, p->options->authheader, p->options->auth);
14117 }
14118 add_date(&req);
14119 if (sipmethod == SIP_REFER && p->refer) {
14120 if (!ast_strlen_zero(p->refer->refer_to)) {
14121 add_header(&req, "Refer-To", p->refer->refer_to);
14122 }
14123 if (!ast_strlen_zero(p->refer->referred_by)) {
14124 add_header(&req, "Referred-By", p->refer->referred_by);
14125 }
14126 } else if (sipmethod == SIP_SUBSCRIBE) {
14127 if (p->subscribed == MWI_NOTIFICATION) {
14128 add_header(&req, "Event", "message-summary");
14129 add_header(&req, "Accept", "application/simple-message-summary");
14130 } else if (p->subscribed == CALL_COMPLETION) {
14131 add_header(&req, "Event", "call-completion");
14132 add_header(&req, "Accept", "application/call-completion");
14133 }
14134 add_expires(&req, p->expiry);
14135 }
14136
14137
14138
14139 if (p->options && !ast_strlen_zero(p->options->replaces)) {
14140 add_header(&req, "Replaces", p->options->replaces);
14141 add_header(&req, "Require", "replaces");
14142 }
14143
14144
14145 if (st_get_mode(p, 0) == SESSION_TIMER_MODE_ORIGINATE
14146 || (st_get_mode(p, 0) == SESSION_TIMER_MODE_ACCEPT
14147 && st_get_se(p, FALSE) != DEFAULT_MIN_SE)) {
14148 char i2astr[10];
14149
14150 if (!p->stimer->st_interval) {
14151 p->stimer->st_interval = st_get_se(p, TRUE);
14152 }
14153
14154 p->stimer->st_active = TRUE;
14155 if (st_get_mode(p, 0) == SESSION_TIMER_MODE_ORIGINATE) {
14156 snprintf(i2astr, sizeof(i2astr), "%d", p->stimer->st_interval);
14157 add_header(&req, "Session-Expires", i2astr);
14158 }
14159
14160 snprintf(i2astr, sizeof(i2astr), "%d", st_get_se(p, FALSE));
14161 add_header(&req, "Min-SE", i2astr);
14162 }
14163
14164 add_header(&req, "Allow", ALLOWED_METHODS);
14165 add_supported(p, &req);
14166
14167 if (p->owner && ((p->options && p->options->addsipheaders)
14168 || (p->refer && global_refer_addheaders))) {
14169 struct ast_channel *chan = p->owner;
14170 struct varshead *headp;
14171
14172 ast_channel_lock(chan);
14173
14174 headp = ast_channel_varshead(chan);
14175
14176 if (!headp) {
14177 ast_log(LOG_WARNING, "No Headp for the channel...ooops!\n");
14178 } else {
14179 const struct ast_var_t *current;
14180 AST_LIST_TRAVERSE(headp, current, entries) {
14181
14182 if (!strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
14183 char *content, *end;
14184 const char *header = ast_var_value(current);
14185 char *headdup = ast_strdupa(header);
14186
14187
14188 if (*headdup == '"') {
14189 headdup++;
14190 }
14191 if ((content = strchr(headdup, ':'))) {
14192 *content++ = '\0';
14193 content = ast_skip_blanks(content);
14194
14195 end = content + strlen(content) -1;
14196 if (*end == '"') {
14197 *end = '\0';
14198 }
14199
14200 add_header(&req, headdup, content);
14201 if (sipdebug) {
14202 ast_debug(1, "Adding SIP Header \"%s\" with content :%s: \n", headdup, content);
14203 }
14204 }
14205 }
14206 }
14207 }
14208
14209 ast_channel_unlock(chan);
14210 }
14211 if ((sipmethod == SIP_INVITE || sipmethod == SIP_UPDATE) && ast_test_flag(&p->flags[0], SIP_SENDRPID))
14212 add_rpid(&req, p);
14213 if (sipmethod == SIP_INVITE) {
14214 add_diversion(&req, p);
14215 }
14216 if (sdp) {
14217 offered_media_list_destroy(p);
14218 if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
14219 ast_debug(1, "T38 is in state %d on channel %s\n", p->t38.state, p->owner ? ast_channel_name(p->owner) : "<none>");
14220 add_sdp(&req, p, FALSE, FALSE, TRUE);
14221 } else if (p->rtp) {
14222 try_suggested_sip_codec(p);
14223 add_sdp(&req, p, FALSE, TRUE, FALSE);
14224 }
14225 } else if (sipmethod == SIP_NOTIFY && p->notify) {
14226 for (var = p->notify->headers; var; var = var->next) {
14227 add_header(&req, var->name, var->value);
14228 }
14229 if (ast_str_strlen(p->notify->content)) {
14230 add_content(&req, ast_str_buffer(p->notify->content));
14231 }
14232 } else if (sipmethod == SIP_PUBLISH) {
14233 switch (p->epa_entry->static_data->event) {
14234 case CALL_COMPLETION:
14235 add_header(&req, "Event", "call-completion");
14236 add_expires(&req, p->expiry);
14237 if (p->epa_entry->publish_type != SIP_PUBLISH_INITIAL) {
14238 add_header(&req, "SIP-If-Match", p->epa_entry->entity_tag);
14239 }
14240
14241 if (!ast_strlen_zero(p->epa_entry->body)) {
14242 add_header(&req, "Content-Type", "application/pidf+xml");
14243 add_content(&req, p->epa_entry->body);
14244 }
14245 default:
14246 break;
14247 }
14248 }
14249
14250 if (!p->initreq.headers || init > 2) {
14251 initialize_initreq(p, &req);
14252 }
14253 if (sipmethod == SIP_INVITE || sipmethod == SIP_SUBSCRIBE) {
14254 p->lastinvite = p->ocseq;
14255 }
14256 return send_request(p, &req, init ? XMIT_CRITICAL : XMIT_RELIABLE, p->ocseq);
14257 }
14258
14259
14260 static int sip_subscribe_mwi_do(const void *data)
14261 {
14262 struct sip_subscription_mwi *mwi = (struct sip_subscription_mwi*)data;
14263
14264 if (!mwi) {
14265 return -1;
14266 }
14267
14268 mwi->resub = -1;
14269 __sip_subscribe_mwi_do(mwi);
14270 ASTOBJ_UNREF(mwi, sip_subscribe_mwi_destroy);
14271
14272 return 0;
14273 }
14274
14275 static void on_dns_update_registry(struct ast_sockaddr *old, struct ast_sockaddr *new, void *data)
14276 {
14277 struct sip_registry *reg = data;
14278 const char *old_str;
14279
14280
14281 if (ast_sockaddr_isnull(new)) {
14282 ast_debug(1, "Empty sockaddr change...ignoring!\n");
14283 return;
14284 }
14285
14286 if (!ast_sockaddr_port(new)) {
14287 ast_sockaddr_set_port(new, reg->portno);
14288 }
14289
14290 old_str = ast_strdupa(ast_sockaddr_stringify(old));
14291
14292 ast_debug(1, "Changing registry %s from %s to %s\n", S_OR(reg->peername, reg->hostname), old_str, ast_sockaddr_stringify(new));
14293 ast_sockaddr_copy(®->us, new);
14294 }
14295
14296 static void on_dns_update_peer(struct ast_sockaddr *old, struct ast_sockaddr *new, void *data)
14297 {
14298 struct sip_peer *peer = data;
14299 const char *old_str;
14300
14301
14302 if (ast_sockaddr_isnull(new)) {
14303 ast_debug(1, "Empty sockaddr change...ignoring!\n");
14304 return;
14305 }
14306
14307 if (!ast_sockaddr_isnull(&peer->addr)) {
14308 ao2_unlink(peers_by_ip, peer);
14309 }
14310
14311 if (!ast_sockaddr_port(new)) {
14312 ast_sockaddr_set_port(new, default_sip_port(peer->socket.type));
14313 }
14314
14315 old_str = ast_strdupa(ast_sockaddr_stringify(old));
14316 ast_debug(1, "Changing peer %s address from %s to %s\n", peer->name, old_str, ast_sockaddr_stringify(new));
14317
14318 ao2_lock(peer);
14319 ast_sockaddr_copy(&peer->addr, new);
14320 ao2_unlock(peer);
14321
14322 ao2_link(peers_by_ip, peer);
14323 }
14324
14325 static void on_dns_update_mwi(struct ast_sockaddr *old, struct ast_sockaddr *new, void *data)
14326 {
14327 struct sip_subscription_mwi *mwi = data;
14328 const char *old_str;
14329
14330
14331 if (ast_sockaddr_isnull(new)) {
14332 ast_debug(1, "Empty sockaddr change...ignoring!\n");
14333 return;
14334 }
14335
14336 old_str = ast_strdupa(ast_sockaddr_stringify(old));
14337 ast_debug(1, "Changing mwi %s from %s to %s\n", mwi->hostname, old_str, ast_sockaddr_stringify(new));
14338 ast_sockaddr_copy(&mwi->us, new);
14339 }
14340
14341
14342 static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi)
14343 {
14344
14345 if (!mwi->dnsmgr) {
14346 char transport[MAXHOSTNAMELEN];
14347 struct sip_subscription_mwi *saved;
14348 snprintf(transport, sizeof(transport), "_%s._%s", get_srv_service(mwi->transport), get_srv_protocol(mwi->transport));
14349
14350 mwi->us.ss.ss_family = get_address_family_filter(mwi->transport);
14351 saved = ASTOBJ_REF(mwi);
14352 ast_dnsmgr_lookup_cb(mwi->hostname, &mwi->us, &mwi->dnsmgr, sip_cfg.srvlookup ? transport : NULL, on_dns_update_mwi, saved);
14353 if (!mwi->dnsmgr) {
14354 ASTOBJ_UNREF(saved, sip_subscribe_mwi_destroy);
14355 }
14356 }
14357
14358
14359 if (mwi->call) {
14360 transmit_invite(mwi->call, SIP_SUBSCRIBE, 0, 0, NULL);
14361 return 0;
14362 }
14363
14364
14365 if (!(mwi->call = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL, NULL))) {
14366 return -1;
14367 }
14368
14369 ref_proxy(mwi->call, obproxy_get(mwi->call, NULL));
14370
14371 if (!ast_sockaddr_port(&mwi->us) && mwi->portno) {
14372 ast_sockaddr_set_port(&mwi->us, mwi->portno);
14373 }
14374
14375
14376 if (create_addr(mwi->call, mwi->hostname, &mwi->us, 0)) {
14377 dialog_unlink_all(mwi->call);
14378 mwi->call = dialog_unref(mwi->call, "unref dialog after unlink_all");
14379 return 0;
14380 }
14381
14382 mwi->call->expiry = mwi_expiry;
14383
14384 if (!mwi->dnsmgr && mwi->portno) {
14385 ast_sockaddr_set_port(&mwi->call->sa, mwi->portno);
14386 ast_sockaddr_set_port(&mwi->call->recv, mwi->portno);
14387 } else {
14388 mwi->portno = ast_sockaddr_port(&mwi->call->sa);
14389 }
14390
14391
14392 if (!ast_strlen_zero(mwi->authuser)) {
14393 ast_string_field_set(mwi->call, peername, mwi->authuser);
14394 ast_string_field_set(mwi->call, authname, mwi->authuser);
14395 ast_string_field_set(mwi->call, fromuser, mwi->authuser);
14396 } else {
14397 ast_string_field_set(mwi->call, peername, mwi->username);
14398 ast_string_field_set(mwi->call, authname, mwi->username);
14399 ast_string_field_set(mwi->call, fromuser, mwi->username);
14400 }
14401 ast_string_field_set(mwi->call, username, mwi->username);
14402 if (!ast_strlen_zero(mwi->secret)) {
14403 ast_string_field_set(mwi->call, peersecret, mwi->secret);
14404 }
14405 set_socket_transport(&mwi->call->socket, mwi->transport);
14406 mwi->call->socket.port = htons(mwi->portno);
14407 ast_sip_ouraddrfor(&mwi->call->sa, &mwi->call->ourip, mwi->call);
14408 build_contact(mwi->call);
14409 build_via(mwi->call);
14410
14411
14412 change_callid_pvt(mwi->call, NULL);
14413
14414 ast_set_flag(&mwi->call->flags[0], SIP_OUTGOING);
14415
14416
14417 mwi->call->mwi = ASTOBJ_REF(mwi);
14418
14419 mwi->call->subscribed = MWI_NOTIFICATION;
14420
14421
14422 transmit_invite(mwi->call, SIP_SUBSCRIBE, 0, 2, NULL);
14423
14424 return 0;
14425 }
14426
14427
14428 static struct ast_channel *find_ringing_channel(struct ao2_container *device_state_info, struct sip_pvt *p)
14429 {
14430 struct ao2_iterator citer;
14431 struct ast_device_state_info *device_state;
14432 struct ast_channel *c = NULL;
14433 struct timeval tv = {0,};
14434
14435
14436 citer = ao2_iterator_init(device_state_info, 0);
14437 for (; (device_state = ao2_iterator_next(&citer)); ao2_ref(device_state, -1)) {
14438 if (!device_state->causing_channel || (device_state->device_state != AST_DEVICE_RINGING &&
14439 device_state->device_state != AST_DEVICE_RINGINUSE)) {
14440 continue;
14441 }
14442 ast_channel_lock(device_state->causing_channel);
14443 if (ast_tvzero(tv) || ast_tvcmp(ast_channel_creationtime(device_state->causing_channel), tv) < 0) {
14444 c = device_state->causing_channel;
14445 tv = ast_channel_creationtime(c);
14446 }
14447 ast_channel_unlock(device_state->causing_channel);
14448 }
14449 ao2_iterator_destroy(&citer);
14450 return c ? ast_channel_ref(c) : NULL;
14451 }
14452
14453
14454 static int allow_notify_user_presence(struct sip_pvt *p)
14455 {
14456 return (strstr(p->useragent, "Digium")) ? 1 : 0;
14457 }
14458
14459
14460 static void state_notify_build_xml(struct state_notify_data *data, int full, const char *exten, const char *context, struct ast_str **tmp, struct sip_pvt *p, int subscribed, const char *mfrom, const char *mto)
14461 {
14462 enum state { NOTIFY_OPEN, NOTIFY_INUSE, NOTIFY_CLOSED } local_state = NOTIFY_OPEN;
14463 const char *statestring = "terminated";
14464 const char *pidfstate = "--";
14465 const char *pidfnote ="Ready";
14466 char hint[AST_MAX_EXTENSION];
14467
14468 switch (data->state) {
14469 case (AST_EXTENSION_RINGING | AST_EXTENSION_INUSE):
14470 statestring = (sip_cfg.notifyringing) ? "early" : "confirmed";
14471 local_state = NOTIFY_INUSE;
14472 pidfstate = "busy";
14473 pidfnote = "Ringing";
14474 break;
14475 case AST_EXTENSION_RINGING:
14476 statestring = "early";
14477 local_state = NOTIFY_INUSE;
14478 pidfstate = "busy";
14479 pidfnote = "Ringing";
14480 break;
14481 case AST_EXTENSION_INUSE:
14482 statestring = "confirmed";
14483 local_state = NOTIFY_INUSE;
14484 pidfstate = "busy";
14485 pidfnote = "On the phone";
14486 break;
14487 case AST_EXTENSION_BUSY:
14488 statestring = "confirmed";
14489 local_state = NOTIFY_CLOSED;
14490 pidfstate = "busy";
14491 pidfnote = "On the phone";
14492 break;
14493 case AST_EXTENSION_UNAVAILABLE:
14494 statestring = "terminated";
14495 local_state = NOTIFY_CLOSED;
14496 pidfstate = "away";
14497 pidfnote = "Unavailable";
14498 break;
14499 case AST_EXTENSION_ONHOLD:
14500 statestring = "confirmed";
14501 local_state = NOTIFY_CLOSED;
14502 pidfstate = "busy";
14503 pidfnote = "On hold";
14504 break;
14505 case AST_EXTENSION_NOT_INUSE:
14506 default:
14507
14508 break;
14509 }
14510
14511
14512 if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, context, exten)) {
14513 char *hint2;
14514 char *individual_hint = NULL;
14515 int hint_count = 0, unavailable_count = 0;
14516
14517
14518 if ((hint2 = strrchr(hint, ','))) {
14519 *hint2 = '\0';
14520 }
14521 hint2 = hint;
14522
14523 while ((individual_hint = strsep(&hint2, "&"))) {
14524 hint_count++;
14525
14526 if (ast_device_state(individual_hint) == AST_DEVICE_UNAVAILABLE)
14527 unavailable_count++;
14528 }
14529
14530
14531
14532
14533 if (hint_count > 0 && hint_count == unavailable_count) {
14534 local_state = NOTIFY_CLOSED;
14535 pidfstate = "away";
14536 pidfnote = "Not online";
14537 }
14538 }
14539
14540 switch (subscribed) {
14541 case XPIDF_XML:
14542 case CPIM_PIDF_XML:
14543 ast_str_append(tmp, 0,
14544 "<?xml version=\"1.0\"?>\n"
14545 "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n"
14546 "<presence>\n");
14547 ast_str_append(tmp, 0, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
14548 ast_str_append(tmp, 0, "<atom id=\"%s\">\n", exten);
14549 ast_str_append(tmp, 0, "<address uri=\"%s;user=ip\" priority=\"0.800000\">\n", mto);
14550 ast_str_append(tmp, 0, "<status status=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "open" : (local_state == NOTIFY_INUSE) ? "inuse" : "closed");
14551 ast_str_append(tmp, 0, "<msnsubstatus substatus=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "online" : (local_state == NOTIFY_INUSE) ? "onthephone" : "offline");
14552 ast_str_append(tmp, 0, "</address>\n</atom>\n</presence>\n");
14553 break;
14554 case PIDF_XML:
14555 ast_str_append(tmp, 0,
14556 "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"
14557 "<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);
14558 ast_str_append(tmp, 0, "<pp:person><status>\n");
14559 if (pidfstate[0] != '-') {
14560 ast_str_append(tmp, 0, "<ep:activities><ep:%s/></ep:activities>\n", pidfstate);
14561 }
14562 ast_str_append(tmp, 0, "</status></pp:person>\n");
14563 ast_str_append(tmp, 0, "<note>%s</note>\n", pidfnote);
14564 ast_str_append(tmp, 0, "<tuple id=\"%s\">\n", exten);
14565 ast_str_append(tmp, 0, "<contact priority=\"1\">%s</contact>\n", mto);
14566 if (pidfstate[0] == 'b')
14567 ast_str_append(tmp, 0, "<status><basic>open</basic></status>\n");
14568 else
14569 ast_str_append(tmp, 0, "<status><basic>%s</basic></status>\n", (local_state != NOTIFY_CLOSED) ? "open" : "closed");
14570
14571 if (allow_notify_user_presence(p) && (data->presence_state != AST_PRESENCE_INVALID)
14572 && (data->presence_state != AST_PRESENCE_NOT_SET)) {
14573 ast_str_append(tmp, 0, "</tuple>\n");
14574 ast_str_append(tmp, 0, "<tuple id=\"digium-presence\">\n");
14575 ast_str_append(tmp, 0, "<status>\n");
14576 ast_str_append(tmp, 0, "<digium_presence type=\"%s\" subtype=\"%s\">%s</digium_presence>\n",
14577 ast_presence_state2str(data->presence_state),
14578 S_OR(data->presence_subtype, ""),
14579 S_OR(data->presence_message, ""));
14580 ast_str_append(tmp, 0, "</status>\n");
14581 ast_test_suite_event_notify("DIGIUM_PRESENCE_SENT",
14582 "PresenceState: %s\r\n"
14583 "Subtype: %s\r\n"
14584 "Message: %s",
14585 ast_presence_state2str(data->presence_state),
14586 S_OR(data->presence_subtype, ""),
14587 S_OR(data->presence_message, ""));
14588 }
14589 ast_str_append(tmp, 0, "</tuple>\n</presence>\n");
14590 break;
14591 case DIALOG_INFO_XML:
14592 ast_str_append(tmp, 0, "<?xml version=\"1.0\"?>\n");
14593 ast_str_append(tmp, 0, "<dialog-info xmlns=\"urn:ietf:params:xml:ns:dialog-info\" version=\"%u\" state=\"%s\" entity=\"%s\">\n", p->dialogver, full ? "full" : "partial", mto);
14594 if (data->state > 0 && (data->state & AST_EXTENSION_RINGING) && sip_cfg.notifyringing) {
14595
14596 char local_display[AST_MAX_EXTENSION * 2];
14597 char remote_display[AST_MAX_EXTENSION * 2];
14598 char *local_target = ast_strdupa(mto);
14599
14600
14601
14602
14603
14604
14605
14606
14607 char *remote_target = ast_strdupa(mto);
14608
14609 ast_xml_escape(exten, local_display, sizeof(local_display));
14610 ast_xml_escape(exten, remote_display, sizeof(remote_display));
14611
14612
14613
14614
14615 if (sip_cfg.notifycid) {
14616 struct ast_channel *callee;
14617
14618 callee = find_ringing_channel(data->device_state_info, p);
14619 if (callee) {
14620 static char *anonymous = "anonymous";
14621 static char *invalid = "anonymous.invalid";
14622 char *cid_num;
14623 char *connected_num;
14624 int need;
14625 int cid_num_restricted, connected_num_restricted;
14626
14627 ast_channel_lock(callee);
14628
14629 cid_num_restricted = (ast_channel_caller(callee)->id.number.presentation &
14630 AST_PRES_RESTRICTION) == AST_PRES_RESTRICTED;
14631 cid_num = S_COR(ast_channel_caller(callee)->id.number.valid,
14632 S_COR(cid_num_restricted, anonymous,
14633 ast_channel_caller(callee)->id.number.str), "");
14634
14635 need = strlen(cid_num) + (cid_num_restricted ? strlen(invalid) :
14636 strlen(p->fromdomain)) + sizeof("sip:@");
14637 local_target = ast_alloca(need);
14638
14639 snprintf(local_target, need, "sip:%s@%s", cid_num,
14640 cid_num_restricted ? invalid : p->fromdomain);
14641
14642 ast_xml_escape(S_COR(ast_channel_caller(callee)->id.name.valid,
14643 S_COR((ast_channel_caller(callee)->id.name.presentation &
14644 AST_PRES_RESTRICTION) == AST_PRES_RESTRICTED, anonymous,
14645 ast_channel_caller(callee)->id.name.str), ""),
14646 local_display, sizeof(local_display));
14647
14648 connected_num_restricted = (ast_channel_connected(callee)->id.number.presentation &
14649 AST_PRES_RESTRICTION) == AST_PRES_RESTRICTED;
14650 connected_num = S_COR(ast_channel_connected(callee)->id.number.valid,
14651 S_COR(connected_num_restricted, anonymous,
14652 ast_channel_connected(callee)->id.number.str), "");
14653
14654 need = strlen(connected_num) + (connected_num_restricted ? strlen(invalid) :
14655 strlen(p->fromdomain)) + sizeof("sip:@");
14656 remote_target = ast_alloca(need);
14657
14658 snprintf(remote_target, need, "sip:%s@%s", connected_num,
14659 connected_num_restricted ? invalid : p->fromdomain);
14660
14661 ast_xml_escape(S_COR(ast_channel_connected(callee)->id.name.valid,
14662 S_COR((ast_channel_connected(callee)->id.name.presentation &
14663 AST_PRES_RESTRICTION) == AST_PRES_RESTRICTED, anonymous,
14664 ast_channel_connected(callee)->id.name.str), ""),
14665 remote_display, sizeof(remote_display));
14666
14667 ast_channel_unlock(callee);
14668 callee = ast_channel_unref(callee);
14669 }
14670
14671
14672
14673 if (sip_cfg.pedanticsipchecking) {
14674 ast_str_append(tmp, 0, "<dialog id=\"%s\" call-id=\"pickup-%s\" local-tag=\"%s\" remote-tag=\"%s\" direction=\"recipient\">\n",
14675 exten, p->callid, p->theirtag, p->tag);
14676 } else {
14677 ast_str_append(tmp, 0, "<dialog id=\"%s\" call-id=\"pickup-%s\" direction=\"recipient\">\n",
14678 exten, p->callid);
14679 }
14680 ast_str_append(tmp, 0,
14681 "<remote>\n"
14682
14683
14684 "<identity display=\"%s\">%s</identity>\n"
14685 "<target uri=\"%s\"/>\n"
14686 "</remote>\n"
14687 "<local>\n"
14688 "<identity display=\"%s\">%s</identity>\n"
14689 "<target uri=\"%s\"/>\n"
14690 "</local>\n",
14691 remote_display, remote_target, remote_target, local_display, local_target, local_target);
14692 } else {
14693 ast_str_append(tmp, 0, "<dialog id=\"%s\" direction=\"recipient\">\n", exten);
14694 }
14695
14696 } else {
14697 ast_str_append(tmp, 0, "<dialog id=\"%s\">\n", exten);
14698 }
14699 ast_str_append(tmp, 0, "<state>%s</state>\n", statestring);
14700 if (data->state == AST_EXTENSION_ONHOLD) {
14701 ast_str_append(tmp, 0, "<local>\n<target uri=\"%s\">\n"
14702 "<param pname=\"+sip.rendering\" pvalue=\"no\"/>\n"
14703 "</target>\n</local>\n", mto);
14704 }
14705 ast_str_append(tmp, 0, "</dialog>\n</dialog-info>\n");
14706 break;
14707 case NONE:
14708 default:
14709 break;
14710 }
14711 }
14712
14713 static int transmit_cc_notify(struct ast_cc_agent *agent, struct sip_pvt *subscription, enum sip_cc_notify_state state)
14714 {
14715 struct sip_request req;
14716 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
14717 char uri[SIPBUFSIZE];
14718 char state_str[64];
14719 char subscription_state_hdr[64];
14720
14721 if (state < CC_QUEUED || state > CC_READY) {
14722 ast_log(LOG_WARNING, "Invalid state provided for transmit_cc_notify (%d)\n", state);
14723 return -1;
14724 }
14725
14726 reqprep(&req, subscription, SIP_NOTIFY, 0, TRUE);
14727 snprintf(state_str, sizeof(state_str), "%s\r\n", sip_cc_notify_state_map[state].state_string);
14728 add_header(&req, "Event", "call-completion");
14729 add_header(&req, "Content-Type", "application/call-completion");
14730 snprintf(subscription_state_hdr, sizeof(subscription_state_hdr), "active;expires=%d", subscription->expiry);
14731 add_header(&req, "Subscription-State", subscription_state_hdr);
14732 if (state == CC_READY) {
14733 generate_uri(subscription, agent_pvt->notify_uri, sizeof(agent_pvt->notify_uri));
14734 snprintf(uri, sizeof(uri) - 1, "cc-URI: %s\r\n", agent_pvt->notify_uri);
14735 }
14736 add_content(&req, state_str);
14737 if (state == CC_READY) {
14738 add_content(&req, uri);
14739 }
14740 return send_request(subscription, &req, XMIT_RELIABLE, subscription->ocseq);
14741 }
14742
14743
14744 static int transmit_state_notify(struct sip_pvt *p, struct state_notify_data *data, int full, int timeout)
14745 {
14746 struct ast_str *tmp = ast_str_alloca(4000);
14747 char from[256], to[256];
14748 char *c, *mfrom, *mto;
14749 struct sip_request req;
14750 const struct cfsubscription_types *subscriptiontype;
14751
14752
14753 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
14754 return 0;
14755 }
14756
14757 memset(from, 0, sizeof(from));
14758 memset(to, 0, sizeof(to));
14759
14760 subscriptiontype = find_subscription_type(p->subscribed);
14761
14762 ast_copy_string(from, sip_get_header(&p->initreq, "From"), sizeof(from));
14763 c = get_in_brackets(from);
14764 if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
14765 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
14766 return -1;
14767 }
14768
14769 mfrom = remove_uri_parameters(c);
14770
14771 ast_copy_string(to, sip_get_header(&p->initreq, "To"), sizeof(to));
14772 c = get_in_brackets(to);
14773 if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
14774 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
14775 return -1;
14776 }
14777 mto = remove_uri_parameters(c);
14778
14779 reqprep(&req, p, SIP_NOTIFY, 0, 1);
14780
14781 switch(data->state) {
14782 case AST_EXTENSION_DEACTIVATED:
14783 if (timeout)
14784 add_header(&req, "Subscription-State", "terminated;reason=timeout");
14785 else {
14786 add_header(&req, "Subscription-State", "terminated;reason=probation");
14787 add_header(&req, "Retry-After", "60");
14788 }
14789 break;
14790 case AST_EXTENSION_REMOVED:
14791 add_header(&req, "Subscription-State", "terminated;reason=noresource");
14792 break;
14793 default:
14794 if (p->expiry)
14795 add_header(&req, "Subscription-State", "active");
14796 else
14797 add_header(&req, "Subscription-State", "terminated;reason=timeout");
14798 }
14799
14800 switch (p->subscribed) {
14801 case XPIDF_XML:
14802 case CPIM_PIDF_XML:
14803 add_header(&req, "Event", subscriptiontype->event);
14804 state_notify_build_xml(data, full, p->exten, p->context, &tmp, p, p->subscribed, mfrom, mto);
14805 add_header(&req, "Content-Type", subscriptiontype->mediatype);
14806 p->dialogver++;
14807 break;
14808 case PIDF_XML:
14809 add_header(&req, "Event", subscriptiontype->event);
14810 state_notify_build_xml(data, full, p->exten, p->context, &tmp, p, p->subscribed, mfrom, mto);
14811 add_header(&req, "Content-Type", subscriptiontype->mediatype);
14812 p->dialogver++;
14813 break;
14814 case DIALOG_INFO_XML:
14815 add_header(&req, "Event", subscriptiontype->event);
14816 state_notify_build_xml(data, full, p->exten, p->context, &tmp, p, p->subscribed, mfrom, mto);
14817 add_header(&req, "Content-Type", subscriptiontype->mediatype);
14818 p->dialogver++;
14819 break;
14820 case NONE:
14821 default:
14822 break;
14823 }
14824
14825 add_content(&req, ast_str_buffer(tmp));
14826
14827 p->pendinginvite = p->ocseq;
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842 return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
14843 }
14844
14845
14846
14847
14848
14849
14850
14851 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten)
14852 {
14853 struct sip_request req;
14854 struct ast_str *out = ast_str_alloca(500);
14855 int ourport = (p->fromdomainport) ? p->fromdomainport : ast_sockaddr_port(&p->ourip);
14856 const char *domain;
14857 const char *exten = S_OR(vmexten, default_vmexten);
14858
14859 initreqprep(&req, p, SIP_NOTIFY, NULL);
14860 add_header(&req, "Event", "message-summary");
14861 add_header(&req, "Content-Type", default_notifymime);
14862 ast_str_append(&out, 0, "Messages-Waiting: %s\r\n", newmsgs ? "yes" : "no");
14863
14864
14865 domain = S_OR(p->fromdomain, ast_sockaddr_stringify_host_remote(&p->ourip));
14866
14867 if (!sip_standard_port(p->socket.type, ourport)) {
14868 if (p->socket.type == SIP_TRANSPORT_UDP) {
14869 ast_str_append(&out, 0, "Message-Account: sip:%s@%s:%d\r\n", exten, domain, ourport);
14870 } else {
14871 ast_str_append(&out, 0, "Message-Account: sip:%s@%s:%d;transport=%s\r\n", exten, domain, ourport, sip_get_transport(p->socket.type));
14872 }
14873 } else {
14874 if (p->socket.type == SIP_TRANSPORT_UDP) {
14875 ast_str_append(&out, 0, "Message-Account: sip:%s@%s\r\n", exten, domain);
14876 } else {
14877 ast_str_append(&out, 0, "Message-Account: sip:%s@%s;transport=%s\r\n", exten, domain, sip_get_transport(p->socket.type));
14878 }
14879 }
14880
14881
14882
14883 ast_str_append(&out, 0, "Voice-Message: %d/%d%s\r\n",
14884 newmsgs, oldmsgs, (ast_test_flag(&p->flags[1], SIP_PAGE2_BUGGY_MWI) ? "" : " (0/0)"));
14885
14886 if (p->subscribed) {
14887 if (p->expiry) {
14888 add_header(&req, "Subscription-State", "active");
14889 } else {
14890 add_header(&req, "Subscription-State", "terminated;reason=timeout");
14891 }
14892 }
14893
14894 add_content(&req, ast_str_buffer(out));
14895
14896 if (!p->initreq.headers) {
14897 initialize_initreq(p, &req);
14898 }
14899 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
14900 }
14901
14902
14903 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate)
14904 {
14905 struct sip_request req;
14906 char tmp[SIPBUFSIZE/2];
14907
14908 reqprep(&req, p, SIP_NOTIFY, 0, 1);
14909 snprintf(tmp, sizeof(tmp), "refer;id=%d", cseq);
14910 add_header(&req, "Event", tmp);
14911 add_header(&req, "Subscription-state", terminate ? "terminated;reason=noresource" : "active");
14912 add_header(&req, "Content-Type", "message/sipfrag;version=2.0");
14913 add_header(&req, "Allow", ALLOWED_METHODS);
14914 add_supported(p, &req);
14915
14916 snprintf(tmp, sizeof(tmp), "SIP/2.0 %s\r\n", message);
14917 add_content(&req, tmp);
14918
14919 if (!p->initreq.headers) {
14920 initialize_initreq(p, &req);
14921 }
14922
14923 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
14924 }
14925
14926 static int manager_sipnotify(struct mansession *s, const struct message *m)
14927 {
14928 const char *channame = astman_get_header(m, "Channel");
14929 struct ast_variable *vars = astman_get_variables(m);
14930 struct sip_pvt *p;
14931 struct ast_variable *header, *var;
14932
14933 if (ast_strlen_zero(channame)) {
14934 astman_send_error(s, m, "SIPNotify requires a channel name");
14935 return 0;
14936 }
14937
14938 if (!strncasecmp(channame, "sip/", 4)) {
14939 channame += 4;
14940 }
14941
14942 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL, NULL))) {
14943 astman_send_error(s, m, "Unable to build sip pvt data for notify (memory/socket error)");
14944 return 0;
14945 }
14946
14947 if (create_addr(p, channame, NULL, 0)) {
14948
14949 dialog_unlink_all(p);
14950 dialog_unref(p, "unref dialog inside for loop" );
14951
14952 astman_send_error(s, m, "Could not create address");
14953 return 0;
14954 }
14955
14956
14957 ast_set_flag(&p->flags[0], SIP_OUTGOING);
14958 sip_notify_alloc(p);
14959
14960 p->notify->headers = header = ast_variable_new("Subscription-State", "terminated", "");
14961
14962 for (var = vars; var; var = var->next) {
14963 if (!strcasecmp(var->name, "Content")) {
14964 if (ast_str_strlen(p->notify->content))
14965 ast_str_append(&p->notify->content, 0, "\r\n");
14966 ast_str_append(&p->notify->content, 0, "%s", var->value);
14967 } else if (!strcasecmp(var->name, "Content-Length")) {
14968 ast_log(LOG_WARNING, "it is not necessary to specify Content-Length, ignoring\n");
14969 } else {
14970 header->next = ast_variable_new(var->name, var->value, "");
14971 header = header->next;
14972 }
14973 }
14974
14975 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
14976 transmit_invite(p, SIP_NOTIFY, 0, 2, NULL);
14977 dialog_unref(p, "bump down the count of p since we're done with it.");
14978
14979 astman_send_ack(s, m, "Notify Sent");
14980 ast_variables_destroy(vars);
14981 return 0;
14982 }
14983
14984
14985
14986 static void update_redirecting(struct sip_pvt *p, const void *data, size_t datalen)
14987 {
14988 struct sip_request resp;
14989
14990 if (ast_channel_state(p->owner) == AST_STATE_UP || ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
14991 return;
14992 }
14993
14994 respprep(&resp, p, "181 Call is being forwarded", &p->initreq);
14995 add_diversion(&resp, p);
14996 send_response(p, &resp, XMIT_UNRELIABLE, 0);
14997 }
14998
14999
15000 static void update_connectedline(struct sip_pvt *p, const void *data, size_t datalen)
15001 {
15002 struct ast_party_id connected_id = ast_channel_connected_effective_id(p->owner);
15003
15004 if (!ast_test_flag(&p->flags[0], SIP_SENDRPID)) {
15005 return;
15006 }
15007 if (!connected_id.number.valid
15008 || ast_strlen_zero(connected_id.number.str)) {
15009 return;
15010 }
15011
15012 append_history(p, "ConnectedLine", "%s party is now %s <%s>",
15013 ast_test_flag(&p->flags[0], SIP_OUTGOING) ? "Calling" : "Called",
15014 S_COR(connected_id.name.valid, connected_id.name.str, ""),
15015 S_COR(connected_id.number.valid, connected_id.number.str, ""));
15016
15017 if (ast_channel_state(p->owner) == AST_STATE_UP || ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
15018 struct sip_request req;
15019
15020 if (!p->pendinginvite && (p->invitestate == INV_CONFIRMED || p->invitestate == INV_TERMINATED)) {
15021 reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ? SIP_UPDATE : SIP_INVITE, 0, 1);
15022
15023 add_header(&req, "Allow", ALLOWED_METHODS);
15024 add_supported(p, &req);
15025 add_rpid(&req, p);
15026 add_sdp(&req, p, FALSE, TRUE, FALSE);
15027
15028 initialize_initreq(p, &req);
15029 p->lastinvite = p->ocseq;
15030 ast_set_flag(&p->flags[0], SIP_OUTGOING);
15031 p->invitestate = INV_CALLING;
15032 send_request(p, &req, XMIT_CRITICAL, p->ocseq);
15033 } else if ((is_method_allowed(&p->allowed_methods, SIP_UPDATE)) && (!ast_strlen_zero(p->okcontacturi))) {
15034 reqprep(&req, p, SIP_UPDATE, 0, 1);
15035 add_rpid(&req, p);
15036 add_header(&req, "X-Asterisk-rpid-update", "Yes");
15037 send_request(p, &req, XMIT_CRITICAL, p->ocseq);
15038 } else {
15039
15040 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
15041 }
15042 } else {
15043 ast_set_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND);
15044 if (ast_test_flag(&p->flags[1], SIP_PAGE2_RPID_IMMEDIATE)) {
15045 struct sip_request resp;
15046
15047 if ((ast_channel_state(p->owner) == AST_STATE_RING) && !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT)) {
15048 ast_clear_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND);
15049 respprep(&resp, p, "180 Ringing", &p->initreq);
15050 add_rpid(&resp, p);
15051 send_response(p, &resp, XMIT_UNRELIABLE, 0);
15052 ast_set_flag(&p->flags[0], SIP_RINGING);
15053 } else if (ast_channel_state(p->owner) == AST_STATE_RINGING) {
15054 ast_clear_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND);
15055 respprep(&resp, p, "183 Session Progress", &p->initreq);
15056 add_rpid(&resp, p);
15057 send_response(p, &resp, XMIT_UNRELIABLE, 0);
15058 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
15059 } else {
15060 ast_debug(1, "Unable able to send update to '%s' in state '%s'\n", ast_channel_name(p->owner), ast_state2str(ast_channel_state(p->owner)));
15061 }
15062 }
15063 }
15064 }
15065
15066 static const struct _map_x_s regstatestrings[] = {
15067 { REG_STATE_FAILED, "Failed" },
15068 { REG_STATE_UNREGISTERED, "Unregistered"},
15069 { REG_STATE_REGSENT, "Request Sent"},
15070 { REG_STATE_AUTHSENT, "Auth. Sent"},
15071 { REG_STATE_REGISTERED, "Registered"},
15072 { REG_STATE_REJECTED, "Rejected"},
15073 { REG_STATE_TIMEOUT, "Timeout"},
15074 { REG_STATE_NOAUTH, "No Authentication"},
15075 { -1, NULL }
15076 };
15077
15078
15079 static const char *regstate2str(enum sipregistrystate regstate)
15080 {
15081 return map_x_s(regstatestrings, regstate, "Unknown");
15082 }
15083
15084
15085
15086
15087
15088
15089
15090 static int sip_reregister(const void *data)
15091 {
15092
15093 struct sip_registry *r = (struct sip_registry *) data;
15094
15095
15096 if (!r) {
15097 return 0;
15098 }
15099
15100 if (r->call && r->call->do_history) {
15101 append_history(r->call, "RegistryRenew", "Account: %s@%s", r->username, r->hostname);
15102 }
15103
15104
15105 if (sipdebug) {
15106 ast_log(LOG_NOTICE, " -- Re-registration for %s@%s\n", r->username, r->hostname);
15107 }
15108
15109 r->expire = -1;
15110 r->expiry = r->configured_expiry;
15111 __sip_do_register(r);
15112 registry_unref(r, "unref the re-register scheduled event");
15113 return 0;
15114 }
15115
15116
15117
15118
15119 static int __sip_do_register(struct sip_registry *r)
15120 {
15121 int res;
15122
15123 res = transmit_register(r, SIP_REGISTER, NULL, NULL);
15124 return res;
15125 }
15126
15127
15128
15129
15130
15131
15132
15133 static int sip_reg_timeout(const void *data)
15134 {
15135
15136
15137 struct sip_registry *r = (struct sip_registry *)data;
15138 struct sip_pvt *p;
15139
15140
15141 if (!r) {
15142 return 0;
15143 }
15144
15145 if (r->dnsmgr) {
15146
15147 ast_dnsmgr_refresh(r->dnsmgr);
15148 }
15149
15150
15151
15152
15153
15154 if (r->call) {
15155
15156
15157 p = r->call;
15158 sip_pvt_lock(p);
15159 pvt_set_needdestroy(p, "registration timeout");
15160
15161 __sip_pretend_ack(p);
15162 sip_pvt_unlock(p);
15163
15164
15165
15166 if (p->registry) {
15167 p->registry = registry_unref(p->registry, "p->registry unreffed");
15168 }
15169 r->call = dialog_unref(r->call, "unrefing r->call");
15170 }
15171
15172 r->timeout = -1;
15173 if (global_regattempts_max && r->regattempts >= global_regattempts_max) {
15174
15175
15176
15177 ast_log(LOG_NOTICE, " -- Last Registration Attempt #%d failed, Giving up forever trying to register '%s@%s'\n", r->regattempts, r->username, r->hostname);
15178 r->regstate = REG_STATE_FAILED;
15179 } else {
15180 r->regstate = REG_STATE_UNREGISTERED;
15181 transmit_register(r, SIP_REGISTER, NULL, NULL);
15182 ast_log(LOG_NOTICE, " -- Registration for '%s@%s' timed out, trying again (Attempt #%d)\n", r->username, r->hostname, r->regattempts);
15183 }
15184 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));
15185 registry_unref(r, "unreffing registry_unref r");
15186 return 0;
15187 }
15188
15189 static const char *sip_sanitized_host(const char *host)
15190 {
15191 struct ast_sockaddr addr = { { 0, 0, }, };
15192
15193
15194
15195
15196 if (!ast_sockaddr_parse(&addr, host, PARSE_PORT_FORBID)) {
15197 return host;
15198 }
15199 return ast_sockaddr_stringify_host_remote(&addr);
15200 }
15201
15202
15203
15204
15205 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader)
15206 {
15207 struct sip_request req;
15208 char from[256];
15209 char to[256];
15210 char tmp[80];
15211 char addr[80];
15212 struct sip_pvt *p;
15213 struct sip_peer *peer = NULL;
15214 int res;
15215 int portno = 0;
15216
15217
15218 if (r == NULL || ((auth == NULL) && (r->regstate == REG_STATE_REGSENT || r->regstate == REG_STATE_AUTHSENT))) {
15219 if (r) {
15220 ast_log(LOG_NOTICE, "Strange, trying to register %s@%s when registration already pending\n", r->username, r->hostname);
15221 }
15222 return 0;
15223 }
15224
15225 if (r->dnsmgr == NULL) {
15226 char transport[MAXHOSTNAMELEN];
15227 peer = sip_find_peer(r->hostname, NULL, TRUE, FINDPEERS, FALSE, 0);
15228 snprintf(transport, sizeof(transport), "_%s._%s",get_srv_service(r->transport), get_srv_protocol(r->transport));
15229 r->us.ss.ss_family = get_address_family_filter(r->transport);
15230
15231
15232
15233
15234
15235 if (!obproxy_get(r->call, peer)) {
15236 registry_addref(r, "add reg ref for dnsmgr");
15237 ast_dnsmgr_lookup_cb(peer ? peer->tohost : r->hostname, &r->us, &r->dnsmgr, sip_cfg.srvlookup ? transport : NULL, on_dns_update_registry, r);
15238 if (!r->dnsmgr) {
15239
15240 registry_unref(r, "remove reg ref, dnsmgr disabled");
15241 }
15242 }
15243 if (peer) {
15244 peer = sip_unref_peer(peer, "removing peer ref for dnsmgr_lookup");
15245 }
15246 }
15247
15248 if (r->call) {
15249 if (!auth) {
15250 ast_log(LOG_WARNING, "Already have a REGISTER going on to %s@%s?? \n", r->username, r->hostname);
15251 return 0;
15252 } else {
15253 p = dialog_ref(r->call, "getting a copy of the r->call dialog in transmit_register");
15254 ast_string_field_set(p, theirtag, NULL);
15255 }
15256 } else {
15257
15258 if (!r->callid_valid) {
15259 build_callid_registry(r, &internip, default_fromdomain);
15260 build_localtag_registry(r);
15261 r->callid_valid = TRUE;
15262 }
15263
15264 if (!(p = sip_alloc( r->callid, NULL, 0, SIP_REGISTER, NULL, NULL))) {
15265 ast_log(LOG_WARNING, "Unable to allocate registration transaction (memory or socket error)\n");
15266 return 0;
15267 }
15268
15269
15270 ast_string_field_set(p, tag, r->localtag);
15271
15272 if (p->do_history) {
15273 append_history(p, "RegistryInit", "Account: %s@%s", r->username, r->hostname);
15274 }
15275
15276 p->socket.type = r->transport;
15277
15278
15279 if (!ast_sockaddr_isnull(&r->us)) {
15280 if (!ast_sockaddr_port(&r->us) && r->portno) {
15281 ast_sockaddr_set_port(&r->us, r->portno);
15282 }
15283
15284
15285
15286
15287
15288 if ((peer = sip_find_peer(S_OR(r->peername, r->hostname), NULL, TRUE, FINDPEERS, FALSE, 0))) {
15289 if (ast_sockaddr_cmp(&peer->addr, &r->us)) {
15290 on_dns_update_peer(&peer->addr, &r->us, peer);
15291 }
15292 peer = sip_unref_peer(peer, "unref after sip_find_peer");
15293 }
15294 }
15295
15296
15297 if (create_addr(p, S_OR(r->peername, r->hostname), &r->us, 0)) {
15298
15299
15300 dialog_unlink_all(p);
15301 p = dialog_unref(p, "unref dialog after unlink_all");
15302 if (r->timeout > -1) {
15303 AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
15304 registry_unref(_data, "del for REPLACE of registry ptr"),
15305 registry_unref(r, "object ptr dec when SCHED_REPLACE add failed"),
15306 registry_addref(r,"add for REPLACE registry ptr"));
15307 ast_log(LOG_WARNING, "Still have a registration timeout for %s@%s (create_addr() error), %d\n", r->username, r->hostname, r->timeout);
15308 } else {
15309 r->timeout = ast_sched_add(sched, global_reg_timeout * 1000, sip_reg_timeout, registry_addref(r, "add for REPLACE registry ptr"));
15310 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);
15311 }
15312 r->regattempts++;
15313 return 0;
15314 }
15315
15316
15317 ast_string_field_set(r, callid, p->callid);
15318
15319 if (!r->dnsmgr && r->portno) {
15320 ast_sockaddr_set_port(&p->sa, r->portno);
15321 ast_sockaddr_set_port(&p->recv, r->portno);
15322 }
15323 if (!ast_strlen_zero(p->fromdomain)) {
15324 portno = (p->fromdomainport) ? p->fromdomainport : STANDARD_SIP_PORT;
15325 } else if (!ast_strlen_zero(r->regdomain)) {
15326 portno = (r->regdomainport) ? r->regdomainport : STANDARD_SIP_PORT;
15327 } else {
15328 portno = ast_sockaddr_port(&p->sa);
15329 }
15330
15331 ast_set_flag(&p->flags[0], SIP_OUTGOING);
15332 r->call = dialog_ref(p, "copying dialog into registry r->call");
15333 p->registry = registry_addref(r, "transmit_register: addref to p->registry in transmit_register");
15334 if (!ast_strlen_zero(r->secret)) {
15335 ast_string_field_set(p, peersecret, r->secret);
15336 }
15337 if (!ast_strlen_zero(r->md5secret))
15338 ast_string_field_set(p, peermd5secret, r->md5secret);
15339
15340
15341 if (!ast_strlen_zero(r->authuser)) {
15342 ast_string_field_set(p, peername, r->authuser);
15343 ast_string_field_set(p, authname, r->authuser);
15344 } else if (!ast_strlen_zero(r->username)) {
15345 ast_string_field_set(p, peername, r->username);
15346 ast_string_field_set(p, authname, r->username);
15347 ast_string_field_set(p, fromuser, r->username);
15348 }
15349 if (!ast_strlen_zero(r->username)) {
15350 ast_string_field_set(p, username, r->username);
15351 }
15352
15353 if (!ast_strlen_zero(r->callback)) {
15354 ast_string_field_set(p, exten, r->callback);
15355 }
15356
15357
15358 set_socket_transport(&p->socket, r->transport);
15359 if (r->transport == SIP_TRANSPORT_TLS || r->transport == SIP_TRANSPORT_TCP) {
15360 p->socket.port =
15361 htons(ast_sockaddr_port(&sip_tcp_desc.local_address));
15362 }
15363
15364
15365
15366
15367
15368
15369 ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
15370 build_contact(p);
15371 }
15372
15373
15374 if (auth == NULL) {
15375 if (r->timeout > -1) {
15376 ast_log(LOG_WARNING, "Still have a registration timeout, #%d - deleting it\n", r->timeout);
15377 }
15378 AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
15379 registry_unref(_data,"reg ptr unrefed from del in SCHED_REPLACE"),
15380 registry_unref(r,"reg ptr unrefed from add failure in SCHED_REPLACE"),
15381 registry_addref(r,"reg ptr reffed from add in SCHED_REPLACE"));
15382 ast_debug(1, "Scheduled a registration timeout for %s id #%d \n", r->hostname, r->timeout);
15383 }
15384
15385 snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%s", r->username, S_OR(r->regdomain, sip_sanitized_host(p->tohost)), p->tag);
15386 if (!ast_strlen_zero(p->theirtag)) {
15387 snprintf(to, sizeof(to), "<sip:%s@%s>;tag=%s", r->username, S_OR(r->regdomain, sip_sanitized_host(p->tohost)), p->theirtag);
15388 } else {
15389 snprintf(to, sizeof(to), "<sip:%s@%s>", r->username, S_OR(r->regdomain, sip_sanitized_host(p->tohost)));
15390 }
15391
15392
15393
15394 if (portno && portno != STANDARD_SIP_PORT) {
15395 snprintf(addr, sizeof(addr), "sip:%s:%d", S_OR(p->fromdomain,S_OR(r->regdomain, sip_sanitized_host(r->hostname))), portno);
15396 } else {
15397 snprintf(addr, sizeof(addr), "sip:%s", S_OR(p->fromdomain,S_OR(r->regdomain, sip_sanitized_host(r->hostname))));
15398 }
15399
15400 ast_string_field_set(p, uri, addr);
15401
15402 p->branch ^= ast_random();
15403
15404 init_req(&req, sipmethod, addr);
15405
15406
15407 snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, sip_methods[sipmethod].text);
15408 p->ocseq = r->ocseq;
15409
15410 build_via(p);
15411 add_header(&req, "Via", p->via);
15412 add_max_forwards(p, &req);
15413 add_header(&req, "From", from);
15414 add_header(&req, "To", to);
15415 add_header(&req, "Call-ID", p->callid);
15416 add_header(&req, "CSeq", tmp);
15417 if (!ast_strlen_zero(global_useragent))
15418 add_header(&req, "User-Agent", global_useragent);
15419
15420 if (auth) {
15421 add_header(&req, authheader, auth);
15422 } else if (!ast_strlen_zero(r->nonce)) {
15423 char digest[1024];
15424
15425
15426
15427
15428
15429
15430 if (sipdebug) {
15431 ast_debug(1, " >>> Re-using Auth data for %s@%s\n", r->username, r->hostname);
15432 }
15433 ast_string_field_set(p, realm, r->realm);
15434 ast_string_field_set(p, nonce, r->nonce);
15435 ast_string_field_set(p, domain, r->authdomain);
15436 ast_string_field_set(p, opaque, r->opaque);
15437 ast_string_field_set(p, qop, r->qop);
15438 p->noncecount = ++r->noncecount;
15439
15440 memset(digest, 0, sizeof(digest));
15441 if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
15442 add_header(&req, "Authorization", digest);
15443 } else {
15444 ast_log(LOG_NOTICE, "No authorization available for authentication of registration to %s@%s\n", r->username, r->hostname);
15445 }
15446 }
15447
15448 add_expires(&req, r->expiry);
15449 add_header(&req, "Contact", p->our_contact);
15450
15451 initialize_initreq(p, &req);
15452 if (sip_debug_test_pvt(p)) {
15453 ast_verbose("REGISTER %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
15454 }
15455 r->regstate = auth ? REG_STATE_AUTHSENT : REG_STATE_REGSENT;
15456 r->regattempts++;
15457 ast_debug(4, "REGISTER attempt %d to %s@%s\n", r->regattempts, r->username, r->hostname);
15458 res = send_request(p, &req, XMIT_CRITICAL, p->ocseq);
15459 dialog_unref(p, "p is finished here at the end of transmit_register");
15460 return res;
15461 }
15462
15463
15464
15465
15466
15467 static int transmit_message(struct sip_pvt *p, int init, int auth)
15468 {
15469 struct sip_request req;
15470
15471 if (init) {
15472 initreqprep(&req, p, SIP_MESSAGE, NULL);
15473 initialize_initreq(p, &req);
15474 } else {
15475 reqprep(&req, p, SIP_MESSAGE, 0, 1);
15476 }
15477 if (auth) {
15478 return transmit_request_with_auth(p, SIP_MESSAGE, p->ocseq, XMIT_RELIABLE, 0);
15479 } else {
15480 add_text(&req, p);
15481 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
15482 }
15483 }
15484
15485
15486 static int sip_refer_alloc(struct sip_pvt *p)
15487 {
15488 p->refer = ast_calloc_with_stringfields(1, struct sip_refer, 512);
15489 return p->refer ? 1 : 0;
15490 }
15491
15492
15493 static int sip_notify_alloc(struct sip_pvt *p)
15494 {
15495 p->notify = ast_calloc(1, sizeof(struct sip_notify));
15496 if (p->notify) {
15497 p->notify->content = ast_str_create(128);
15498 }
15499 return p->notify ? 1 : 0;
15500 }
15501
15502
15503
15504
15505
15506
15507 static int transmit_refer(struct sip_pvt *p, const char *dest)
15508 {
15509 char from[256];
15510 const char *of;
15511 char *c;
15512 char referto[256];
15513 int use_tls=FALSE;
15514
15515 if (sipdebug) {
15516 ast_debug(1, "SIP transfer of %s to %s\n", p->callid, dest);
15517 }
15518
15519
15520 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
15521 of = sip_get_header(&p->initreq, "To");
15522 } else {
15523 of = sip_get_header(&p->initreq, "From");
15524 }
15525
15526 ast_copy_string(from, of, sizeof(from));
15527 of = get_in_brackets(from);
15528 ast_string_field_set(p, from, of);
15529 if (!strncasecmp(of, "sip:", 4)) {
15530 of += 4;
15531 } else if (!strncasecmp(of, "sips:", 5)) {
15532 of += 5;
15533 use_tls = TRUE;
15534 } else {
15535 ast_log(LOG_NOTICE, "From address missing 'sip(s):', assuming sip:\n");
15536 }
15537
15538 if (strchr(dest, '@')) {
15539 c = NULL;
15540 } else if ((c = strchr(of, '@'))) {
15541 *c++ = '\0';
15542 }
15543 if (c) {
15544 snprintf(referto, sizeof(referto), "<sip%s:%s@%s>", use_tls ? "s" : "", dest, c);
15545 } else {
15546 snprintf(referto, sizeof(referto), "<sip%s:%s>", use_tls ? "s" : "", dest);
15547 }
15548
15549
15550 sip_refer_alloc(p);
15551 ast_string_field_set(p->refer, refer_to, referto);
15552 ast_string_field_set(p->refer, referred_by, p->our_contact);
15553 p->refer->status = REFER_SENT;
15554
15555 return transmit_invite(p, SIP_REFER, FALSE, 0, NULL);
15556
15557
15558
15559
15560
15561
15562
15563
15564 }
15565
15566
15567 static int transmit_info_with_aoc(struct sip_pvt *p, struct ast_aoc_decoded *decoded)
15568 {
15569 struct sip_request req;
15570 struct ast_str *str = ast_str_alloca(512);
15571 const struct ast_aoc_unit_entry *unit_entry = ast_aoc_get_unit_info(decoded, 0);
15572 enum ast_aoc_charge_type charging = ast_aoc_get_charge_type(decoded);
15573
15574 reqprep(&req, p, SIP_INFO, 0, 1);
15575
15576 if (ast_aoc_get_msg_type(decoded) == AST_AOC_D) {
15577 ast_str_append(&str, 0, "type=active;");
15578 } else if (ast_aoc_get_msg_type(decoded) == AST_AOC_E) {
15579 ast_str_append(&str, 0, "type=terminated;");
15580 } else {
15581
15582 return -1;
15583 }
15584
15585 switch (charging) {
15586 case AST_AOC_CHARGE_FREE:
15587 ast_str_append(&str, 0, "free-of-charge;");
15588 break;
15589 case AST_AOC_CHARGE_CURRENCY:
15590 ast_str_append(&str, 0, "charging;");
15591 ast_str_append(&str, 0, "charging-info=currency;");
15592 ast_str_append(&str, 0, "amount=%u;", ast_aoc_get_currency_amount(decoded));
15593 ast_str_append(&str, 0, "multiplier=%s;", ast_aoc_get_currency_multiplier_decimal(decoded));
15594 if (!ast_strlen_zero(ast_aoc_get_currency_name(decoded))) {
15595 ast_str_append(&str, 0, "currency=%s;", ast_aoc_get_currency_name(decoded));
15596 }
15597 break;
15598 case AST_AOC_CHARGE_UNIT:
15599 ast_str_append(&str, 0, "charging;");
15600 ast_str_append(&str, 0, "charging-info=pulse;");
15601 if (unit_entry) {
15602 ast_str_append(&str, 0, "recorded-units=%u;", unit_entry->amount);
15603 }
15604 break;
15605 default:
15606 ast_str_append(&str, 0, "not-available;");
15607 };
15608
15609 add_header(&req, "AOC", ast_str_buffer(str));
15610
15611 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
15612 }
15613
15614
15615 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration)
15616 {
15617 struct sip_request req;
15618
15619 reqprep(&req, p, SIP_INFO, 0, 1);
15620 add_digit(&req, digit, duration, (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_SHORTINFO));
15621 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
15622 }
15623
15624
15625 static int transmit_info_with_vidupdate(struct sip_pvt *p)
15626 {
15627 struct sip_request req;
15628
15629 reqprep(&req, p, SIP_INFO, 0, 1);
15630 add_vidupdate(&req);
15631 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
15632 }
15633
15634
15635
15636
15637 static int transmit_request(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch)
15638 {
15639 struct sip_request resp;
15640
15641 reqprep(&resp, p, sipmethod, seqno, newbranch);
15642 if (sipmethod == SIP_CANCEL && p->answered_elsewhere) {
15643 add_header(&resp, "Reason", "SIP;cause=200;text=\"Call completed elsewhere\"");
15644 }
15645
15646 if (sipmethod == SIP_ACK) {
15647 p->invitestate = INV_CONFIRMED;
15648 }
15649
15650 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
15651 }
15652
15653
15654 void sip_auth_headers(enum sip_auth_type code, char **header, char **respheader)
15655 {
15656 if (code == WWW_AUTH) {
15657 *header = "WWW-Authenticate";
15658 *respheader = "Authorization";
15659 } else if (code == PROXY_AUTH) {
15660 *header = "Proxy-Authenticate";
15661 *respheader = "Proxy-Authorization";
15662 } else {
15663 ast_verbose("-- wrong response code %d\n", code);
15664 *header = *respheader = "Invalid";
15665 }
15666 }
15667
15668
15669 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch)
15670 {
15671 struct sip_request resp;
15672
15673 reqprep(&resp, p, sipmethod, seqno, newbranch);
15674 if (!ast_strlen_zero(p->realm)) {
15675 char digest[1024];
15676
15677 memset(digest, 0, sizeof(digest));
15678 if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
15679 char *dummy, *response;
15680 enum sip_auth_type code = p->options ? p->options->auth_type : PROXY_AUTH;
15681 sip_auth_headers(code, &dummy, &response);
15682 add_header(&resp, response, digest);
15683 } else {
15684 ast_log(LOG_WARNING, "No authentication available for call %s\n", p->callid);
15685 }
15686 }
15687
15688 switch (sipmethod) {
15689 case SIP_BYE:
15690 {
15691 char buf[20];
15692
15693
15694
15695
15696
15697 if (ast_test_flag(&p->flags[1], SIP_PAGE2_Q850_REASON) && p->hangupcause) {
15698 snprintf(buf, sizeof(buf), "Q.850;cause=%d", p->hangupcause & 0x7f);
15699 add_header(&resp, "Reason", buf);
15700 }
15701
15702 add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->hangupcause));
15703 snprintf(buf, sizeof(buf), "%d", p->hangupcause);
15704 add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
15705 break;
15706 }
15707 case SIP_MESSAGE:
15708 add_text(&resp, p);
15709 break;
15710 default:
15711 break;
15712 }
15713
15714 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
15715 }
15716
15717
15718 static void destroy_association(struct sip_peer *peer)
15719 {
15720 int realtimeregs = ast_check_realtime("sipregs");
15721 char *tablename = (realtimeregs) ? "sipregs" : "sippeers";
15722
15723 if (!sip_cfg.ignore_regexpire) {
15724 if (peer->rt_fromcontact && sip_cfg.peer_rtupdate) {
15725 ast_update_realtime(tablename, "name", peer->name, "fullcontact", "", "ipaddr", "", "port", "", "regseconds", "0", "regserver", "", "useragent", "", "lastms", "0", SENTINEL);
15726 } else {
15727 ast_db_del("SIP/Registry", peer->name);
15728 ast_db_del("SIP/PeerMethods", peer->name);
15729 }
15730 }
15731 }
15732
15733 static void set_socket_transport(struct sip_socket *socket, int transport)
15734 {
15735
15736 if (socket->type != transport) {
15737 socket->fd = -1;
15738 socket->type = transport;
15739 if (socket->tcptls_session) {
15740 ao2_ref(socket->tcptls_session, -1);
15741 socket->tcptls_session = NULL;
15742 } else if (socket->ws_session) {
15743 ast_websocket_unref(socket->ws_session);
15744 socket->ws_session = NULL;
15745 }
15746 }
15747 }
15748
15749
15750 static int expire_register(const void *data)
15751 {
15752 struct sip_peer *peer = (struct sip_peer *)data;
15753
15754 if (!peer) {
15755 return 0;
15756 }
15757
15758 peer->expire = -1;
15759 peer->portinuri = 0;
15760
15761 destroy_association(peer);
15762 set_socket_transport(&peer->socket, peer->default_outbound_transport);
15763
15764 if (peer->socket.tcptls_session) {
15765 ao2_ref(peer->socket.tcptls_session, -1);
15766 peer->socket.tcptls_session = NULL;
15767 } else if (peer->socket.ws_session) {
15768 ast_websocket_unref(peer->socket.ws_session);
15769 peer->socket.ws_session = NULL;
15770 }
15771
15772 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
15773 register_peer_exten(peer, FALSE);
15774 ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "SIP/%s", peer->name);
15775
15776
15777
15778
15779 if (peer->is_realtime) {
15780 ast_debug(3, "-REALTIME- peer expired registration. Name: %s. Realtime peer objects now %d\n", peer->name, rpeerobjs);
15781 }
15782
15783 if (peer->selfdestruct ||
15784 ast_test_flag(&peer->flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
15785 unlink_peer_from_tables(peer);
15786 } else if (!ast_sockaddr_isnull(&peer->addr)) {
15787
15788
15789
15790 ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
15791 }
15792
15793
15794
15795 memset(&peer->addr, 0, sizeof(peer->addr));
15796
15797 sip_unref_peer(peer, "removing peer ref for expire_register");
15798
15799 return 0;
15800 }
15801
15802
15803 static int sip_poke_peer_s(const void *data)
15804 {
15805 struct sip_peer *peer = (struct sip_peer *)data;
15806 struct sip_peer *foundpeer;
15807
15808 peer->pokeexpire = -1;
15809
15810 foundpeer = ao2_find(peers, peer, OBJ_POINTER);
15811 if (!foundpeer) {
15812 sip_unref_peer(peer, "removing poke peer ref");
15813 return 0;
15814 } else if (foundpeer->name != peer->name) {
15815 sip_unref_peer(foundpeer, "removing above peer ref");
15816 sip_unref_peer(peer, "removing poke peer ref");
15817 return 0;
15818 }
15819
15820 sip_unref_peer(foundpeer, "removing above peer ref");
15821 sip_poke_peer(peer, 0);
15822 sip_unref_peer(peer, "removing poke peer ref");
15823
15824 return 0;
15825 }
15826
15827
15828 static void reg_source_db(struct sip_peer *peer)
15829 {
15830 char data[256];
15831 struct ast_sockaddr sa;
15832 int expire;
15833 char full_addr[128];
15834 AST_DECLARE_APP_ARGS(args,
15835 AST_APP_ARG(addr);
15836 AST_APP_ARG(port);
15837 AST_APP_ARG(expiry_str);
15838 AST_APP_ARG(username);
15839 AST_APP_ARG(contact);
15840 );
15841
15842
15843 if (peer->rt_fromcontact && sip_cfg.peer_rtupdate) {
15844 return;
15845 }
15846 if (ast_db_get("SIP/Registry", peer->name, data, sizeof(data))) {
15847 return;
15848 }
15849
15850 AST_NONSTANDARD_RAW_ARGS(args, data, ':');
15851
15852 snprintf(full_addr, sizeof(full_addr), "%s:%s", args.addr, args.port);
15853
15854 if (!ast_sockaddr_parse(&sa, full_addr, 0)) {
15855 return;
15856 }
15857
15858 if (args.expiry_str) {
15859 expire = atoi(args.expiry_str);
15860 } else {
15861 return;
15862 }
15863
15864 if (args.username) {
15865 ast_string_field_set(peer, username, args.username);
15866 }
15867 if (args.contact) {
15868 ast_string_field_set(peer, fullcontact, args.contact);
15869 }
15870
15871 ast_debug(2, "SIP Seeding peer from astdb: '%s' at %s@%s for %d\n",
15872 peer->name, peer->username, ast_sockaddr_stringify_host(&sa), expire);
15873
15874 ast_sockaddr_copy(&peer->addr, &sa);
15875 if (peer->maxms) {
15876
15877 AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
15878 ast_random() % ((peer->qualifyfreq) ? peer->qualifyfreq : global_qualifyfreq) + 1,
15879 sip_poke_peer_s, peer,
15880 sip_unref_peer(_data, "removing poke peer ref"),
15881 sip_unref_peer(peer, "removing poke peer ref"),
15882 sip_ref_peer(peer, "adding poke peer ref"));
15883 }
15884 AST_SCHED_REPLACE_UNREF(peer->expire, sched, (expire + 10) * 1000, expire_register, peer,
15885 sip_unref_peer(_data, "remove registration ref"),
15886 sip_unref_peer(peer, "remove registration ref"),
15887 sip_ref_peer(peer, "add registration ref"));
15888 register_peer_exten(peer, TRUE);
15889 }
15890
15891
15892 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req)
15893 {
15894 char contact[SIPBUFSIZE];
15895 char *c;
15896
15897
15898 ast_copy_string(contact, sip_get_header(req, "Contact"), sizeof(contact));
15899 c = get_in_brackets(contact);
15900
15901
15902 ast_string_field_set(pvt, fullcontact, c);
15903
15904
15905 ast_string_field_set(pvt, okcontacturi, c);
15906
15907
15908
15909 return TRUE;
15910 }
15911
15912
15913
15914
15915
15916
15917
15918 static int parse_uri_legacy_check(char *uri, const char *scheme, char **user, char **pass, char **hostport, char **transport)
15919 {
15920 int ret = parse_uri(uri, scheme, user, pass, hostport, transport);
15921 if (sip_cfg.legacy_useroption_parsing) {
15922 char *p;
15923 if ((p = strchr(uri, (int)';'))) {
15924 *p = '\0';
15925 }
15926 }
15927 return ret;
15928 }
15929
15930 static int __set_address_from_contact(const char *fullcontact, struct ast_sockaddr *addr, int tcp)
15931 {
15932 char *hostport, *transport;
15933 char contact_buf[256];
15934 char *contact;
15935
15936
15937 ast_copy_string(contact_buf, fullcontact, sizeof(contact_buf));
15938 contact = contact_buf;
15939
15940
15941
15942
15943
15944
15945
15946
15947 if (parse_uri_legacy_check(contact, "sip:,sips:", &contact, NULL, &hostport,
15948 &transport)) {
15949 ast_log(LOG_WARNING, "Invalid contact uri %s (missing sip: or sips:), attempting to use anyway\n", fullcontact);
15950 }
15951
15952
15953
15954
15955
15956
15957
15958
15959
15960
15961 if (ast_strlen_zero(hostport)) {
15962 ast_log(LOG_WARNING, "Invalid URI: parse_uri failed to acquire hostport\n");
15963 return -1;
15964 }
15965
15966 if (ast_sockaddr_resolve_first_transport(addr, hostport, 0, get_transport_str2enum(transport))) {
15967 ast_log(LOG_WARNING, "Invalid host name in Contact: (can't "
15968 "resolve in DNS) : '%s'\n", hostport);
15969 return -1;
15970 }
15971
15972
15973 if (!ast_sockaddr_port(addr)) {
15974 ast_sockaddr_set_port(addr,
15975 (get_transport_str2enum(transport) ==
15976 SIP_TRANSPORT_TLS ||
15977 !strncasecmp(fullcontact, "sips", 4)) ?
15978 STANDARD_TLS_PORT : STANDARD_SIP_PORT);
15979 }
15980
15981 return 0;
15982 }
15983
15984
15985 static int set_address_from_contact(struct sip_pvt *pvt)
15986 {
15987 if (ast_test_flag(&pvt->flags[0], SIP_NAT_FORCE_RPORT)) {
15988
15989
15990
15991 pvt->sa = pvt->recv;
15992 return 0;
15993 }
15994
15995 return __set_address_from_contact(pvt->fullcontact, &pvt->sa, pvt->socket.type == SIP_TRANSPORT_TLS ? 1 : 0);
15996 }
15997
15998
15999 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *peer, struct sip_request *req)
16000 {
16001 char contact[SIPBUFSIZE];
16002 char data[SIPBUFSIZE];
16003 const char *expires = sip_get_header(req, "Expires");
16004 int expire = atoi(expires);
16005 char *curi = NULL, *hostport = NULL, *transport = NULL;
16006 int transport_type;
16007 const char *useragent;
16008 struct ast_sockaddr oldsin, testsa;
16009 char *firstcuri = NULL;
16010 int start = 0;
16011 int wildcard_found = 0;
16012 int single_binding_found = 0;
16013
16014 ast_copy_string(contact, __get_header(req, "Contact", &start), sizeof(contact));
16015
16016 if (ast_strlen_zero(expires)) {
16017 char *s = strcasestr(contact, ";expires=");
16018 if (s) {
16019 expires = strsep(&s, ";");
16020 if (sscanf(expires + 9, "%30d", &expire) != 1) {
16021 expire = default_expiry;
16022 }
16023 } else {
16024
16025 expire = default_expiry;
16026 }
16027 }
16028
16029 if (expire > max_expiry) {
16030 expire = max_expiry;
16031 }
16032 if (expire < min_expiry && expire != 0) {
16033 expire = min_expiry;
16034 }
16035 pvt->expiry = expire;
16036
16037 copy_socket_data(&pvt->socket, &req->socket);
16038
16039 do {
16040
16041 curi = contact;
16042 if (strchr(contact, '<') == NULL)
16043 strsep(&curi, ";");
16044 curi = get_in_brackets(contact);
16045 if (!firstcuri) {
16046 firstcuri = ast_strdupa(curi);
16047 }
16048
16049 if (!strcasecmp(curi, "*")) {
16050 wildcard_found = 1;
16051 } else {
16052 single_binding_found = 1;
16053 }
16054
16055 if (wildcard_found && (ast_strlen_zero(expires) || expire != 0 || single_binding_found)) {
16056
16057
16058 return PARSE_REGISTER_FAILED;
16059 }
16060
16061 ast_copy_string(contact, __get_header(req, "Contact", &start), sizeof(contact));
16062 } while (!ast_strlen_zero(contact));
16063 curi = firstcuri;
16064
16065
16066
16067
16068
16069 if (ast_strlen_zero(curi) && ast_strlen_zero(expires)) {
16070
16071 if (peer->expire > -1 && !ast_strlen_zero(peer->fullcontact)) {
16072 pvt->expiry = ast_sched_when(sched, peer->expire);
16073 }
16074 return PARSE_REGISTER_QUERY;
16075 } else if (!strcasecmp(curi, "*") || !expire) {
16076
16077 AST_SCHED_DEL_UNREF(sched, peer->expire,
16078 sip_unref_peer(peer, "remove register expire ref"));
16079 ast_verb(3, "Unregistered SIP '%s'\n", peer->name);
16080 expire_register(sip_ref_peer(peer,"add ref for explicit expire_register"));
16081 return PARSE_REGISTER_UPDATE;
16082 }
16083
16084
16085 ast_string_field_set(peer, fullcontact, curi);
16086
16087
16088 ast_string_field_build(pvt, our_contact, "<%s>", curi);
16089
16090
16091 if (ast_strlen_zero(curi) || parse_uri_legacy_check(curi, "sip:,sips:", &curi, NULL, &hostport, &transport)) {
16092 ast_log(LOG_NOTICE, "Not a valid SIP contact (missing sip:/sips:) trying to use anyway\n");
16093 }
16094
16095
16096 if (!(transport_type = get_transport_str2enum(transport))) {
16097 transport_type = pvt->socket.type;
16098 }
16099
16100
16101
16102
16103 if ((peer->socket.type != transport_type) && (peer->transports & transport_type)) {
16104 set_socket_transport(&peer->socket, transport_type);
16105 }
16106
16107 oldsin = peer->addr;
16108
16109
16110 if (!ast_sockaddr_isnull(&peer->addr) && (!peer->is_realtime || ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS))) {
16111 ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
16112 }
16113
16114 if ((transport_type != SIP_TRANSPORT_WS) && (transport_type != SIP_TRANSPORT_WSS) &&
16115 (!ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) && !ast_test_flag(&peer->flags[0], SIP_NAT_RPORT_PRESENT))) {
16116
16117 ast_debug(1, "Store REGISTER's Contact header for call routing.\n");
16118
16119
16120 if (ast_sockaddr_resolve_first_transport(&testsa, hostport, 0, peer->socket.type)) {
16121 ast_log(LOG_WARNING, "Invalid hostport '%s'\n", hostport);
16122 ast_string_field_set(peer, fullcontact, "");
16123 ast_string_field_set(pvt, our_contact, "");
16124 return PARSE_REGISTER_FAILED;
16125 }
16126
16127
16128
16129 peer->portinuri = ast_sockaddr_port(&testsa) ? TRUE : FALSE;
16130
16131 if (!ast_sockaddr_port(&testsa)) {
16132 ast_sockaddr_set_port(&testsa, default_sip_port(transport_type));
16133 }
16134
16135 ast_sockaddr_copy(&peer->addr, &testsa);
16136 } else {
16137
16138
16139 ast_debug(1, "Store REGISTER's src-IP:port for call routing.\n");
16140 peer->addr = pvt->recv;
16141 }
16142
16143
16144 if (ast_apply_acl(sip_cfg.contact_acl, &peer->addr, "SIP contact ACL: ") != AST_SENSE_ALLOW ||
16145 ast_apply_acl(peer->contactacl, &peer->addr, "SIP contact ACL: ") != AST_SENSE_ALLOW) {
16146 ast_log(LOG_WARNING, "Domain '%s' disallowed by contact ACL (violating IP %s)\n", hostport,
16147 ast_sockaddr_stringify_addr(&peer->addr));
16148 ast_string_field_set(peer, fullcontact, "");
16149 ast_string_field_set(pvt, our_contact, "");
16150 return PARSE_REGISTER_DENIED;
16151 }
16152
16153
16154
16155
16156 if ((peer->socket.type == pvt->socket.type) &&
16157 !ast_sockaddr_cmp(&peer->addr, &pvt->recv)) {
16158 copy_socket_data(&peer->socket, &pvt->socket);
16159 }
16160
16161
16162 if (!peer->is_realtime || ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
16163 ao2_t_link(peers_by_ip, peer, "ao2_link into peers_by_ip table");
16164 }
16165
16166
16167 peer->sipoptions = pvt->sipoptions;
16168
16169 if (!ast_strlen_zero(curi) && ast_strlen_zero(peer->username)) {
16170 ast_string_field_set(peer, username, curi);
16171 }
16172
16173 AST_SCHED_DEL_UNREF(sched, peer->expire,
16174 sip_unref_peer(peer, "remove register expire ref"));
16175
16176 if (peer->is_realtime && !ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
16177 peer->expire = -1;
16178 } else {
16179 peer->expire = ast_sched_add(sched, (expire + 10) * 1000, expire_register,
16180 sip_ref_peer(peer, "add registration ref"));
16181 if (peer->expire == -1) {
16182 sip_unref_peer(peer, "remote registration ref");
16183 }
16184 }
16185 snprintf(data, sizeof(data), "%s:%d:%s:%s", ast_sockaddr_stringify(&peer->addr),
16186 expire, peer->username, peer->fullcontact);
16187
16188 if (!peer->rt_fromcontact || !sip_cfg.peer_rtupdate)
16189 ast_db_put("SIP/Registry", peer->name, data);
16190 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Registered\r\nAddress: %s\r\n", peer->name, ast_sockaddr_stringify(&peer->addr));
16191
16192
16193 if (ast_sockaddr_cmp(&peer->addr, &oldsin)) {
16194 ast_verb(3, "Registered SIP '%s' at %s\n", peer->name,
16195 ast_sockaddr_stringify(&peer->addr));
16196 }
16197 sip_pvt_unlock(pvt);
16198 sip_poke_peer(peer, 0);
16199 sip_pvt_lock(pvt);
16200 register_peer_exten(peer, 1);
16201
16202
16203 useragent = sip_get_header(req, "User-Agent");
16204 if (strcasecmp(useragent, peer->useragent)) {
16205 ast_string_field_set(peer, useragent, useragent);
16206 ast_verb(4, "Saved useragent \"%s\" for peer %s\n", peer->useragent, peer->name);
16207 }
16208 return PARSE_REGISTER_UPDATE;
16209 }
16210
16211
16212 static void free_old_route(struct sip_route *route)
16213 {
16214 struct sip_route *next;
16215
16216 while (route) {
16217 next = route->next;
16218 ast_free(route);
16219 route = next;
16220 }
16221 }
16222
16223
16224 static void list_route(struct sip_route *route)
16225 {
16226 if (!route) {
16227 ast_verbose("list_route: no route\n");
16228 } else {
16229 for (;route; route = route->next)
16230 ast_verbose("list_route: hop: <%s>\n", route->hop);
16231 }
16232 }
16233
16234
16235
16236 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards, int resp)
16237 {
16238 struct sip_route *thishop, *head, *tail;
16239 int start = 0;
16240 int len;
16241 const char *rr, *c;
16242
16243
16244 if (p->route && p->route_persistent) {
16245 ast_debug(1, "build_route: Retaining previous route: <%s>\n", p->route->hop);
16246 return;
16247 }
16248
16249 if (p->route) {
16250 free_old_route(p->route);
16251 p->route = NULL;
16252 }
16253
16254
16255
16256 if ((resp < 100) || (resp > 199)) {
16257 p->route_persistent = 1;
16258 }
16259
16260
16261
16262
16263
16264
16265 head = NULL;
16266 tail = head;
16267
16268 for (;;) {
16269
16270 int len = 0;
16271 const char *uri;
16272 rr = __get_header(req, "Record-Route", &start);
16273 if (*rr == '\0') {
16274 break;
16275 }
16276 while (!get_in_brackets_const(rr, &uri, &len)) {
16277 len++;
16278 rr = strchr(rr, ',');
16279 if(rr >= uri && rr < (uri + len)) {
16280
16281 const char *next_br = strchr(rr, '<');
16282 if (next_br && next_br < (uri + len)) {
16283 rr++;
16284 continue;
16285 }
16286 continue;
16287 }
16288 if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
16289 ast_copy_string(thishop->hop, uri, len);
16290 ast_debug(2, "build_route: Record-Route hop: <%s>\n", thishop->hop);
16291
16292 if (backwards) {
16293
16294 thishop->next = head;
16295 head = thishop;
16296
16297 if (!tail) {
16298 tail = thishop;
16299 }
16300 } else {
16301 thishop->next = NULL;
16302
16303 if (tail) {
16304 tail->next = thishop;
16305 } else {
16306 head = thishop;
16307 }
16308 tail = thishop;
16309 }
16310 }
16311 rr = strchr(uri + len, ',');
16312 if (rr == NULL) {
16313
16314 break;
16315 }
16316
16317 rr++;
16318 }
16319 }
16320
16321
16322 if (!head || (!ast_strlen_zero(head->hop) && strstr(head->hop, ";lr") == NULL) ) {
16323
16324
16325 char *contact = ast_strdupa(sip_get_header(req, "Contact"));
16326 if (!ast_strlen_zero(contact)) {
16327 ast_debug(2, "build_route: Contact hop: %s\n", contact);
16328
16329 c = get_in_brackets(contact);
16330 len = strlen(c) + 1;
16331 if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
16332
16333 ast_copy_string(thishop->hop, c, len);
16334 thishop->next = NULL;
16335
16336 if (tail) {
16337 tail->next = thishop;
16338 } else {
16339 head = thishop;
16340 }
16341 }
16342 }
16343 }
16344
16345
16346 p->route = head;
16347
16348
16349 if (sip_debug_test_pvt(p)) {
16350 list_route(p->route);
16351 }
16352 }
16353
16354
16355
16356
16357
16358
16359
16360 static void build_nonce(struct sip_pvt *p, int forceupdate)
16361 {
16362 if (p->stalenonce || forceupdate || ast_strlen_zero(p->nonce)) {
16363 ast_string_field_build(p, nonce, "%08lx", ast_random());
16364 p->stalenonce = 0;
16365 }
16366 }
16367
16368
16369 void sip_digest_parser(char *c, struct digestkeys *keys)
16370 {
16371 struct digestkeys *i = i;
16372
16373 while(c && *(c = ast_skip_blanks(c)) ) {
16374 for (i = keys; i->key != NULL; i++) {
16375 const char *separator = ",";
16376
16377 if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
16378 continue;
16379 }
16380
16381 c += strlen(i->key);
16382 if (*c == '"') {
16383 c++;
16384 separator = "\"";
16385 }
16386 i->s = c;
16387 strsep(&c, separator);
16388 break;
16389 }
16390 if (i->key == NULL) {
16391 strsep(&c, " ,");
16392 }
16393 }
16394 }
16395
16396
16397
16398
16399
16400
16401 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
16402 const char *secret, const char *md5secret, int sipmethod,
16403 const char *uri, enum xmittype reliable)
16404 {
16405 const char *response;
16406 char *reqheader, *respheader;
16407 const char *authtoken;
16408 char a1_hash[256];
16409 char resp_hash[256]="";
16410 char *c;
16411 int is_bogus_peer = 0;
16412 int wrongnonce = FALSE;
16413 int good_response;
16414 const char *usednonce = p->nonce;
16415 struct ast_str *buf;
16416 int res;
16417
16418
16419 struct digestkeys keys[] = {
16420 [K_RESP] = { "response=", "" },
16421 [K_URI] = { "uri=", "" },
16422 [K_USER] = { "username=", "" },
16423 [K_NONCE] = { "nonce=", "" },
16424 [K_LAST] = { NULL, NULL}
16425 };
16426
16427
16428 if (ast_strlen_zero(secret) && ast_strlen_zero(md5secret)) {
16429 return AUTH_SUCCESSFUL;
16430 }
16431
16432
16433
16434 response = "401 Unauthorized";
16435
16436
16437
16438
16439
16440 sip_auth_headers(WWW_AUTH, &respheader, &reqheader);
16441
16442 authtoken = sip_get_header(req, reqheader);
16443 if (req->ignore && !ast_strlen_zero(p->nonce) && ast_strlen_zero(authtoken)) {
16444
16445
16446 if (!reliable) {
16447
16448
16449 transmit_response_with_auth(p, response, req, p->nonce, reliable, respheader, 0);
16450
16451 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16452 }
16453 return AUTH_CHALLENGE_SENT;
16454 } else if (ast_strlen_zero(p->nonce) || ast_strlen_zero(authtoken)) {
16455
16456 build_nonce(p, 1);
16457 transmit_response_with_auth(p, response, req, p->nonce, reliable, respheader, 0);
16458
16459 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16460 return AUTH_CHALLENGE_SENT;
16461 }
16462
16463
16464
16465
16466
16467
16468 if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN))) {
16469 return AUTH_SECRET_FAILED;
16470 }
16471
16472
16473 res = ast_str_set(&buf, 0, "%s", authtoken);
16474
16475 if (res == AST_DYNSTR_BUILD_FAILED) {
16476 return AUTH_SECRET_FAILED;
16477 }
16478
16479 c = buf->str;
16480
16481 sip_digest_parser(c, keys);
16482
16483
16484
16485 if (md5secret && strcmp(md5secret, BOGUS_PEER_MD5SECRET) == 0) {
16486 is_bogus_peer = 1;
16487 }
16488
16489
16490 if (strcmp(username, keys[K_USER].s) && !is_bogus_peer) {
16491 ast_log(LOG_WARNING, "username mismatch, have <%s>, digest has <%s>\n",
16492 username, keys[K_USER].s);
16493
16494 return AUTH_USERNAME_MISMATCH;
16495 }
16496
16497
16498
16499 if (strcasecmp(p->nonce, keys[K_NONCE].s) || p->stalenonce) {
16500 wrongnonce = TRUE;
16501 usednonce = keys[K_NONCE].s;
16502 } else {
16503 p->stalenonce = 1;
16504 }
16505
16506 if (!ast_strlen_zero(md5secret)) {
16507 ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
16508 } else {
16509 char a1[256];
16510
16511 snprintf(a1, sizeof(a1), "%s:%s:%s", username, p->realm, secret);
16512 ast_md5_hash(a1_hash, a1);
16513 }
16514
16515
16516 {
16517 char a2[256];
16518 char a2_hash[256];
16519 char resp[256];
16520
16521 snprintf(a2, sizeof(a2), "%s:%s", sip_methods[sipmethod].text,
16522 S_OR(keys[K_URI].s, uri));
16523 ast_md5_hash(a2_hash, a2);
16524 snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, usednonce, a2_hash);
16525 ast_md5_hash(resp_hash, resp);
16526 }
16527
16528 good_response = keys[K_RESP].s &&
16529 !strncasecmp(keys[K_RESP].s, resp_hash, strlen(resp_hash)) &&
16530 !is_bogus_peer;
16531 if (wrongnonce) {
16532 if (good_response) {
16533 if (sipdebug)
16534 ast_log(LOG_NOTICE, "Correct auth, but based on stale nonce received from '%s'\n", sip_get_header(req, "From"));
16535
16536 build_nonce(p, 0);
16537 transmit_response_with_auth(p, response, req, p->nonce, reliable, respheader, TRUE);
16538 } else {
16539
16540 if (!req->ignore) {
16541 if (sipdebug) {
16542 ast_log(LOG_NOTICE, "Bad authentication received from '%s'\n", sip_get_header(req, "To"));
16543 }
16544 build_nonce(p, 1);
16545 } else {
16546 if (sipdebug) {
16547 ast_log(LOG_NOTICE, "Duplicate authentication received from '%s'\n", sip_get_header(req, "To"));
16548 }
16549 }
16550 transmit_response_with_auth(p, response, req, p->nonce, reliable, respheader, FALSE);
16551 }
16552
16553
16554 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16555 return AUTH_CHALLENGE_SENT;
16556 }
16557 if (good_response) {
16558 append_history(p, "AuthOK", "Auth challenge successful for %s", username);
16559 return AUTH_SUCCESSFUL;
16560 }
16561
16562
16563
16564
16565
16566
16567 return AUTH_SECRET_FAILED;
16568 }
16569
16570
16571 static void sip_peer_hold(struct sip_pvt *p, int hold)
16572 {
16573 if (!p->relatedpeer) {
16574 return;
16575 }
16576
16577
16578 ast_atomic_fetchadd_int(&p->relatedpeer->onhold, (hold ? +1 : -1));
16579
16580
16581 ast_devstate_changed(AST_DEVICE_UNKNOWN, (ast_test_flag(ast_channel_flags(p->owner), AST_FLAG_DISABLE_DEVSTATE_CACHE) ? AST_DEVSTATE_NOT_CACHABLE : AST_DEVSTATE_CACHABLE),
16582 "SIP/%s", p->relatedpeer->name);
16583
16584 return;
16585 }
16586
16587
16588 static void mwi_event_cb(const struct ast_event *event, void *userdata)
16589 {
16590 struct sip_peer *peer = userdata;
16591
16592 sip_send_mwi_to_peer(peer, 0);
16593 }
16594
16595 static void network_change_event_subscribe(void)
16596 {
16597 if (!network_change_event_subscription) {
16598 network_change_event_subscription = ast_event_subscribe(AST_EVENT_NETWORK_CHANGE,
16599 network_change_event_cb, "SIP Network Change", NULL, AST_EVENT_IE_END);
16600 }
16601 }
16602
16603 static void network_change_event_unsubscribe(void)
16604 {
16605 if (network_change_event_subscription) {
16606 network_change_event_subscription = ast_event_unsubscribe(network_change_event_subscription);
16607 }
16608 }
16609
16610 static void acl_change_event_subscribe(void)
16611 {
16612 if (!acl_change_event_subscription) {
16613 acl_change_event_subscription = ast_event_subscribe(AST_EVENT_ACL_CHANGE,
16614 acl_change_event_cb, "Manager must react to Named ACL changes", NULL, AST_EVENT_IE_END);
16615 }
16616
16617 }
16618
16619 static void acl_change_event_unsubscribe(void)
16620 {
16621 if (acl_change_event_subscription) {
16622 acl_change_event_subscription = ast_event_unsubscribe(acl_change_event_subscription);
16623 }
16624 }
16625
16626 static int network_change_event_sched_cb(const void *data)
16627 {
16628 network_change_event_sched_id = -1;
16629 sip_send_all_registers();
16630 sip_send_all_mwi_subscriptions();
16631 return 0;
16632 }
16633
16634 static void network_change_event_cb(const struct ast_event *event, void *userdata)
16635 {
16636 ast_debug(1, "SIP, got a network change event, renewing all SIP registrations.\n");
16637 if (network_change_event_sched_id == -1) {
16638 network_change_event_sched_id = ast_sched_add(sched, 1000, network_change_event_sched_cb, NULL);
16639 }
16640 }
16641
16642 static void cb_extensionstate_destroy(int id, void *data)
16643 {
16644 struct sip_pvt *p = data;
16645
16646 dialog_unref(p, "the extensionstate containing this dialog ptr was destroyed");
16647 }
16648
16649
16650
16651
16652 static int extensionstate_update(const char *context, const char *exten, struct state_notify_data *data, struct sip_pvt *p, int force)
16653 {
16654 sip_pvt_lock(p);
16655
16656 switch (data->state) {
16657 case AST_EXTENSION_DEACTIVATED:
16658 case AST_EXTENSION_REMOVED:
16659 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16660 ast_verb(2, "Extension state: Watcher for hint %s %s. Notify User %s\n", exten, data->state == AST_EXTENSION_DEACTIVATED ? "deactivated" : "removed", p->username);
16661 p->subscribed = NONE;
16662 append_history(p, "Subscribestatus", "%s", data->state == AST_EXTENSION_REMOVED ? "HintRemoved" : "Deactivated");
16663 break;
16664 default:
16665 if (force) {
16666
16667 } else if ((p->laststate == data->state && (~data->state & AST_EXTENSION_RINGING)) &&
16668 (p->last_presence_state == data->presence_state &&
16669 !strcmp(p->last_presence_subtype, data->presence_subtype) &&
16670 !strcmp(p->last_presence_message, data->presence_message))) {
16671
16672 sip_pvt_unlock(p);
16673 return 0;
16674 } else if (data->state & AST_EXTENSION_RINGING) {
16675
16676 struct ast_channel *ringing = find_ringing_channel(data->device_state_info, p);
16677 if (ringing) {
16678 if (!ast_tvcmp(ast_channel_creationtime(ringing), p->last_ringing_channel_time)) {
16679
16680 ao2_ref(ringing, -1);
16681 sip_pvt_unlock(p);
16682 return 0;
16683 } else {
16684 p->last_ringing_channel_time = ast_channel_creationtime(ringing);
16685 ao2_ref(ringing, -1);
16686 }
16687 }
16688
16689
16690
16691
16692
16693 }
16694
16695 if (data->device_state_info) {
16696 ao2_ref(data->device_state_info, 1);
16697 }
16698 ao2_cleanup(p->last_device_state_info);
16699 p->last_device_state_info = data->device_state_info;
16700 p->laststate = data->state;
16701 p->last_presence_state = data->presence_state;
16702 ast_string_field_set(p, last_presence_subtype, S_OR(data->presence_subtype, ""));
16703 ast_string_field_set(p, last_presence_message, S_OR(data->presence_message, ""));
16704 break;
16705 }
16706 if (p->subscribed != NONE) {
16707 if (!p->pendinginvite) {
16708 transmit_state_notify(p, data, 1, FALSE);
16709 if (p->last_device_state_info) {
16710
16711 ao2_ref(p->last_device_state_info, -1);
16712 p->last_device_state_info = NULL;
16713 }
16714 } else {
16715
16716
16717 ast_set_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
16718 }
16719 }
16720
16721 if (!force) {
16722 ast_verb(2, "Extension Changed %s[%s] new state %s for Notify User %s %s\n", exten, context, ast_extension_state2str(data->state), p->username,
16723 ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE) ? "(queued)" : "");
16724 }
16725
16726 sip_pvt_unlock(p);
16727
16728 return 0;
16729 }
16730
16731
16732
16733
16734 static int cb_extensionstate(char *context, char *exten, struct ast_state_cb_info *info, void *data)
16735 {
16736 struct sip_pvt *p = data;
16737 struct state_notify_data notify_data = {
16738 .state = info->exten_state,
16739 .device_state_info = info->device_state_info,
16740 .presence_state = info->presence_state,
16741 .presence_subtype = info->presence_subtype,
16742 .presence_message = info->presence_message,
16743 };
16744
16745 if ((info->reason == AST_HINT_UPDATE_PRESENCE) && !(allow_notify_user_presence(p))) {
16746
16747 return 0;
16748 }
16749
16750 return extensionstate_update(context, exten, ¬ify_data, p, FALSE);
16751 }
16752
16753
16754
16755
16756 static void transmit_fake_auth_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable)
16757 {
16758
16759
16760 const char *response = "401 Unauthorized";
16761 const char *reqheader = "Authorization";
16762 const char *respheader = "WWW-Authenticate";
16763 const char *authtoken;
16764 struct ast_str *buf;
16765 char *c;
16766
16767
16768 enum keys { K_NONCE, K_LAST };
16769 struct x {
16770 const char *key;
16771 const char *s;
16772 } *i, keys[] = {
16773 [K_NONCE] = { "nonce=", "" },
16774 [K_LAST] = { NULL, NULL}
16775 };
16776
16777 authtoken = sip_get_header(req, reqheader);
16778 if (req->ignore && !ast_strlen_zero(p->nonce) && ast_strlen_zero(authtoken)) {
16779
16780
16781 transmit_response_with_auth(p, response, req, p->nonce, reliable, respheader, 0);
16782
16783 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16784 return;
16785 } else if (ast_strlen_zero(p->nonce) || ast_strlen_zero(authtoken)) {
16786
16787 build_nonce(p, 1);
16788 transmit_response_with_auth(p, response, req, p->nonce, reliable, respheader, 0);
16789
16790 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16791 return;
16792 }
16793
16794 if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN))) {
16795 __transmit_response(p, "403 Forbidden", &p->initreq, reliable);
16796 return;
16797 }
16798
16799
16800 if (ast_str_set(&buf, 0, "%s", authtoken) == AST_DYNSTR_BUILD_FAILED) {
16801 __transmit_response(p, "403 Forbidden", &p->initreq, reliable);
16802 return;
16803 }
16804
16805 c = buf->str;
16806
16807 while (c && *(c = ast_skip_blanks(c))) {
16808 for (i = keys; i->key != NULL; i++) {
16809 const char *separator = ",";
16810
16811 if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
16812 continue;
16813 }
16814
16815 c += strlen(i->key);
16816 if (*c == '"') {
16817 c++;
16818 separator = "\"";
16819 }
16820 i->s = c;
16821 strsep(&c, separator);
16822 break;
16823 }
16824 if (i->key == NULL) {
16825 strsep(&c, " ,");
16826 }
16827 }
16828
16829
16830 if (strcasecmp(p->nonce, keys[K_NONCE].s)) {
16831 if (!req->ignore) {
16832 build_nonce(p, 1);
16833 }
16834 transmit_response_with_auth(p, response, req, p->nonce, reliable, respheader, FALSE);
16835
16836
16837 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16838 } else {
16839 __transmit_response(p, "403 Forbidden", &p->initreq, reliable);
16840 }
16841 }
16842
16843
16844
16845
16846
16847
16848
16849
16850
16851
16852
16853
16854
16855
16856
16857 static char *terminate_uri(char *uri)
16858 {
16859 char *t = uri;
16860 while (*t && *t > ' ' && *t != ';') {
16861 t++;
16862 }
16863 *t = '\0';
16864 return uri;
16865 }
16866
16867
16868
16869
16870
16871
16872
16873 static void extract_host_from_hostport(char **hostport)
16874 {
16875 char *dont_care;
16876 ast_sockaddr_split_hostport(*hostport, hostport, &dont_care, PARSE_PORT_IGNORE);
16877 }
16878
16879
16880
16881 static void update_peer_lastmsgssent(struct sip_peer *peer, int value, int locked)
16882 {
16883 if (!locked) {
16884 ao2_lock(peer);
16885 }
16886 peer->lastmsgssent = value;
16887 if (!locked) {
16888 ao2_unlock(peer);
16889 }
16890 }
16891
16892
16893
16894
16895
16896
16897
16898 static enum check_auth_result register_verify(struct sip_pvt *p, struct ast_sockaddr *addr,
16899 struct sip_request *req, const char *uri)
16900 {
16901 enum check_auth_result res = AUTH_NOT_FOUND;
16902 struct sip_peer *peer;
16903 char tmp[256];
16904 char *c, *name, *unused_password, *domain;
16905 char *uri2 = ast_strdupa(uri);
16906 int send_mwi = 0;
16907
16908 terminate_uri(uri2);
16909
16910 ast_copy_string(tmp, sip_get_header(req, "To"), sizeof(tmp));
16911
16912 c = get_in_brackets(tmp);
16913 c = remove_uri_parameters(c);
16914
16915 if (parse_uri_legacy_check(c, "sip:,sips:", &name, &unused_password, &domain, NULL)) {
16916 ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, ast_sockaddr_stringify_addr(addr));
16917 return -1;
16918 }
16919
16920 SIP_PEDANTIC_DECODE(name);
16921 SIP_PEDANTIC_DECODE(domain);
16922
16923 extract_host_from_hostport(&domain);
16924
16925 if (ast_strlen_zero(domain)) {
16926
16927 transmit_response(p, "404 Not found", &p->initreq);
16928 return AUTH_UNKNOWN_DOMAIN;
16929 }
16930
16931 if (ast_strlen_zero(name)) {
16932
16933
16934
16935
16936
16937
16938
16939 name = domain;
16940 }
16941
16942
16943
16944
16945
16946 if (!AST_LIST_EMPTY(&domain_list)) {
16947 if (!check_sip_domain(domain, NULL, 0)) {
16948 if (sip_cfg.alwaysauthreject) {
16949 transmit_fake_auth_response(p, &p->initreq, XMIT_UNRELIABLE);
16950 } else {
16951 transmit_response(p, "404 Not found (unknown domain)", &p->initreq);
16952 }
16953 return AUTH_UNKNOWN_DOMAIN;
16954 }
16955 }
16956
16957 ast_string_field_set(p, exten, name);
16958 build_contact(p);
16959 if (req->ignore) {
16960
16961 const char *expires = sip_get_header(req, "Expires");
16962 int expire = atoi(expires);
16963
16964 if (ast_strlen_zero(expires)) {
16965 if ((expires = strcasestr(sip_get_header(req, "Contact"), ";expires="))) {
16966 expire = atoi(expires + 9);
16967 }
16968 }
16969 if (!ast_strlen_zero(expires) && expire == 0) {
16970 transmit_response_with_date(p, "200 OK", req);
16971 return 0;
16972 }
16973 }
16974 peer = sip_find_peer(name, NULL, TRUE, FINDPEERS, FALSE, 0);
16975
16976
16977
16978 if (!peer && sip_cfg.alwaysauthreject && sip_cfg.autocreatepeer == AUTOPEERS_DISABLED) {
16979 peer = bogus_peer;
16980 sip_ref_peer(peer, "register_verify: ref the bogus_peer");
16981 }
16982
16983 if (!(peer && ast_apply_acl(peer->acl, addr, "SIP Peer ACL: "))) {
16984
16985 if (peer) {
16986 sip_unref_peer(peer, "register_verify: sip_unref_peer: from sip_find_peer operation");
16987 peer = NULL;
16988 res = AUTH_ACL_FAILED;
16989 } else {
16990 res = AUTH_NOT_FOUND;
16991 }
16992 }
16993
16994 if (peer) {
16995 ao2_lock(peer);
16996 if (!peer->host_dynamic) {
16997 ast_log(LOG_ERROR, "Peer '%s' is trying to register, but not configured as host=dynamic\n", peer->name);
16998 res = AUTH_PEER_NOT_DYNAMIC;
16999 } else {
17000
17001 set_peer_nat(p, peer);
17002
17003 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_NAT_FORCE_RPORT);
17004
17005 if (!(res = check_auth(p, req, peer->name, peer->secret, peer->md5secret, SIP_REGISTER, uri2, XMIT_UNRELIABLE))) {
17006 if (sip_cancel_destroy(p))
17007 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
17008
17009 if (check_request_transport(peer, req)) {
17010 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
17011 transmit_response_with_date(p, "403 Forbidden", req);
17012 res = AUTH_BAD_TRANSPORT;
17013 } else {
17014
17015
17016
17017 switch (parse_register_contact(p, peer, req)) {
17018 case PARSE_REGISTER_DENIED:
17019 ast_log(LOG_WARNING, "Registration denied because of contact ACL\n");
17020 transmit_response_with_date(p, "603 Denied", req);
17021 res = 0;
17022 break;
17023 case PARSE_REGISTER_FAILED:
17024 ast_log(LOG_WARNING, "Failed to parse contact info\n");
17025 transmit_response_with_date(p, "400 Bad Request", req);
17026 res = 0;
17027 break;
17028 case PARSE_REGISTER_QUERY:
17029 ast_string_field_set(p, fullcontact, peer->fullcontact);
17030 transmit_response_with_date(p, "200 OK", req);
17031 res = 0;
17032 send_mwi = 1;
17033 break;
17034 case PARSE_REGISTER_UPDATE:
17035 ast_string_field_set(p, fullcontact, peer->fullcontact);
17036
17037 if (p->expiry != 0) {
17038 update_peer(peer, p->expiry);
17039 }
17040
17041 transmit_response_with_date(p, "200 OK", req);
17042 send_mwi = 1;
17043 res = 0;
17044 break;
17045 }
17046 }
17047
17048 }
17049 }
17050 ao2_unlock(peer);
17051 }
17052 if (!peer && sip_cfg.autocreatepeer != AUTOPEERS_DISABLED) {
17053
17054 peer = temp_peer(name);
17055 if (peer) {
17056 ao2_t_link(peers, peer, "link peer into peer table");
17057 if (!ast_sockaddr_isnull(&peer->addr)) {
17058 ao2_t_link(peers_by_ip, peer, "link peer into peers-by-ip table");
17059 }
17060 ao2_lock(peer);
17061 if (sip_cancel_destroy(p))
17062 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
17063 switch (parse_register_contact(p, peer, req)) {
17064 case PARSE_REGISTER_DENIED:
17065 ast_log(LOG_WARNING, "Registration denied because of contact ACL\n");
17066 transmit_response_with_date(p, "403 Forbidden", req);
17067 res = 0;
17068 break;
17069 case PARSE_REGISTER_FAILED:
17070 ast_log(LOG_WARNING, "Failed to parse contact info\n");
17071 transmit_response_with_date(p, "400 Bad Request", req);
17072 res = 0;
17073 break;
17074 case PARSE_REGISTER_QUERY:
17075 ast_string_field_set(p, fullcontact, peer->fullcontact);
17076 transmit_response_with_date(p, "200 OK", req);
17077 send_mwi = 1;
17078 res = 0;
17079 break;
17080 case PARSE_REGISTER_UPDATE:
17081 ast_string_field_set(p, fullcontact, peer->fullcontact);
17082
17083 transmit_response_with_date(p, "200 OK", req);
17084 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Registered\r\nAddress: %s\r\n", peer->name, ast_sockaddr_stringify(addr));
17085 send_mwi = 1;
17086 res = 0;
17087 break;
17088 }
17089 ao2_unlock(peer);
17090 }
17091 }
17092 if (!res) {
17093 if (send_mwi) {
17094 sip_pvt_unlock(p);
17095 sip_send_mwi_to_peer(peer, 0);
17096 sip_pvt_lock(p);
17097 } else {
17098 update_peer_lastmsgssent(peer, -1, 0);
17099 }
17100 ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "SIP/%s", peer->name);
17101 }
17102 if (res < 0) {
17103 switch (res) {
17104 case AUTH_SECRET_FAILED:
17105
17106 transmit_response(p, "403 Forbidden", &p->initreq);
17107 if (global_authfailureevents) {
17108 const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
17109 const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
17110 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
17111 "ChannelType: SIP\r\n"
17112 "Peer: SIP/%s\r\n"
17113 "PeerStatus: Rejected\r\n"
17114 "Cause: AUTH_SECRET_FAILED\r\n"
17115 "Address: %s\r\n"
17116 "Port: %s\r\n",
17117 name, peer_addr, peer_port);
17118 }
17119 break;
17120 case AUTH_USERNAME_MISMATCH:
17121
17122
17123
17124
17125 case AUTH_NOT_FOUND:
17126 case AUTH_PEER_NOT_DYNAMIC:
17127 case AUTH_ACL_FAILED:
17128 if (sip_cfg.alwaysauthreject) {
17129 transmit_fake_auth_response(p, &p->initreq, XMIT_UNRELIABLE);
17130 if (global_authfailureevents) {
17131 const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
17132 const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
17133 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
17134 "ChannelType: SIP\r\n"
17135 "Peer: SIP/%s\r\n"
17136 "PeerStatus: Rejected\r\n"
17137 "Cause: %s\r\n"
17138 "Address: %s\r\n"
17139 "Port: %s\r\n",
17140 name,
17141 res == AUTH_PEER_NOT_DYNAMIC ? "AUTH_PEER_NOT_DYNAMIC" : "URI_NOT_FOUND",
17142 peer_addr, peer_port);
17143 }
17144 } else {
17145
17146 if (res == AUTH_PEER_NOT_DYNAMIC) {
17147 transmit_response(p, "403 Forbidden", &p->initreq);
17148 if (global_authfailureevents) {
17149 const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
17150 const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
17151 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
17152 "ChannelType: SIP\r\n"
17153 "Peer: SIP/%s\r\n"
17154 "PeerStatus: Rejected\r\n"
17155 "Cause: AUTH_PEER_NOT_DYNAMIC\r\n"
17156 "Address: %s\r\n"
17157 "Port: %s\r\n",
17158 name, peer_addr, peer_port);
17159 }
17160 } else {
17161 transmit_response(p, "404 Not found", &p->initreq);
17162 if (global_authfailureevents) {
17163 const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
17164 const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
17165 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
17166 "ChannelType: SIP\r\n"
17167 "Peer: SIP/%s\r\n"
17168 "PeerStatus: Rejected\r\n"
17169 "Cause: %s\r\n"
17170 "Address: %s\r\n"
17171 "Port: %s\r\n",
17172 name,
17173 (res == AUTH_USERNAME_MISMATCH) ? "AUTH_USERNAME_MISMATCH" : "URI_NOT_FOUND",
17174 peer_addr, peer_port);
17175 }
17176 }
17177 }
17178 break;
17179 case AUTH_BAD_TRANSPORT:
17180 default:
17181 break;
17182 }
17183 }
17184 if (peer) {
17185 sip_unref_peer(peer, "register_verify: sip_unref_peer: tossing stack peer pointer at end of func");
17186 }
17187
17188 return res;
17189 }
17190
17191
17192 static void sip_set_redirstr(struct sip_pvt *p, char *reason) {
17193
17194 if (!strcmp(reason, "unknown")) {
17195 ast_string_field_set(p, redircause, "UNKNOWN");
17196 } else if (!strcmp(reason, "user-busy")) {
17197 ast_string_field_set(p, redircause, "BUSY");
17198 } else if (!strcmp(reason, "no-answer")) {
17199 ast_string_field_set(p, redircause, "NOANSWER");
17200 } else if (!strcmp(reason, "unavailable")) {
17201 ast_string_field_set(p, redircause, "UNREACHABLE");
17202 } else if (!strcmp(reason, "unconditional")) {
17203 ast_string_field_set(p, redircause, "UNCONDITIONAL");
17204 } else if (!strcmp(reason, "time-of-day")) {
17205 ast_string_field_set(p, redircause, "UNKNOWN");
17206 } else if (!strcmp(reason, "do-not-disturb")) {
17207 ast_string_field_set(p, redircause, "UNKNOWN");
17208 } else if (!strcmp(reason, "deflection")) {
17209 ast_string_field_set(p, redircause, "UNKNOWN");
17210 } else if (!strcmp(reason, "follow-me")) {
17211 ast_string_field_set(p, redircause, "UNKNOWN");
17212 } else if (!strcmp(reason, "out-of-service")) {
17213 ast_string_field_set(p, redircause, "UNREACHABLE");
17214 } else if (!strcmp(reason, "away")) {
17215 ast_string_field_set(p, redircause, "UNREACHABLE");
17216 } else {
17217 ast_string_field_set(p, redircause, "UNKNOWN");
17218 }
17219 }
17220
17221
17222
17223
17224
17225 static int get_pai(struct sip_pvt *p, struct sip_request *req)
17226 {
17227 char pai[256];
17228 char privacy[64];
17229 char *cid_num = NULL;
17230 char *cid_name = NULL;
17231 char emptyname[1] = "";
17232 int callingpres = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
17233 char *uri = NULL;
17234 int is_anonymous = 0, do_update = 1, no_name = 0;
17235
17236 ast_copy_string(pai, sip_get_header(req, "P-Asserted-Identity"), sizeof(pai));
17237
17238 if (ast_strlen_zero(pai)) {
17239 return 0;
17240 }
17241
17242
17243 if (get_name_and_number(pai, &cid_name, &cid_num)) {
17244 return 0;
17245 }
17246
17247 if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(cid_num)) {
17248 ast_shrink_phone_number(cid_num);
17249 }
17250
17251 uri = get_in_brackets(pai);
17252 if (!strncasecmp(uri, "sip:anonymous@anonymous.invalid", 31)) {
17253 callingpres = AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
17254
17255
17256
17257 ast_free(cid_num);
17258 is_anonymous = 1;
17259 cid_num = (char *)p->cid_num;
17260 }
17261
17262 ast_copy_string(privacy, sip_get_header(req, "Privacy"), sizeof(privacy));
17263 if (!ast_strlen_zero(privacy) && !strncmp(privacy, "id", 2)) {
17264 callingpres = AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
17265 }
17266 if (!cid_name) {
17267 no_name = 1;
17268 cid_name = (char *)emptyname;
17269 }
17270
17271 if (!strcasecmp(p->cid_num, cid_num) && !strcasecmp(p->cid_name, cid_name) && p->callingpres == callingpres) {
17272 do_update = 0;
17273 } else {
17274
17275 ast_string_field_set(p, cid_num, cid_num);
17276 ast_string_field_set(p, cid_name, cid_name);
17277 p->callingpres = callingpres;
17278
17279 if (p->owner) {
17280 ast_set_callerid(p->owner, cid_num, cid_name, NULL);
17281 ast_channel_caller(p->owner)->id.name.presentation = callingpres;
17282 ast_channel_caller(p->owner)->id.number.presentation = callingpres;
17283 }
17284 }
17285
17286
17287 if (!is_anonymous) {
17288 ast_free(cid_num);
17289 }
17290 if (!no_name) {
17291 ast_free(cid_name);
17292 }
17293
17294 return do_update;
17295 }
17296
17297
17298
17299
17300
17301 static int get_rpid(struct sip_pvt *p, struct sip_request *oreq)
17302 {
17303 char tmp[256];
17304 struct sip_request *req;
17305 char *cid_num = "";
17306 char *cid_name = "";
17307 int callingpres = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
17308 char *privacy = "";
17309 char *screen = "";
17310 char *start, *end;
17311
17312 if (!ast_test_flag(&p->flags[0], SIP_TRUSTRPID))
17313 return 0;
17314 req = oreq;
17315 if (!req)
17316 req = &p->initreq;
17317 ast_copy_string(tmp, sip_get_header(req, "Remote-Party-ID"), sizeof(tmp));
17318 if (ast_strlen_zero(tmp)) {
17319 return get_pai(p, req);
17320 }
17321
17322
17323
17324
17325
17326
17327
17328
17329
17330 start = tmp;
17331
17332 if (*start == '"') {
17333 *start++ = '\0';
17334 end = strchr(start, '"');
17335 if (!end)
17336 return 0;
17337 *end++ = '\0';
17338 cid_name = start;
17339 start = ast_skip_blanks(end);
17340
17341 } else {
17342 cid_name = start;
17343 start = end = strchr(start, '<');
17344 if (!start) {
17345 return 0;
17346 }
17347
17348 while (--end >= cid_name && *end < 33) {
17349 *end = '\0';
17350 }
17351 }
17352
17353 if (*start != '<')
17354 return 0;
17355 *start++ = '\0';
17356 end = strchr(start, '@');
17357 if (!end)
17358 return 0;
17359 *end++ = '\0';
17360 if (strncasecmp(start, "sip:", 4))
17361 return 0;
17362 cid_num = start + 4;
17363 if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(cid_num))
17364 ast_shrink_phone_number(cid_num);
17365 start = end;
17366
17367 end = strchr(start, '>');
17368 if (!end)
17369 return 0;
17370 *end++ = '\0';
17371 if (*end) {
17372 start = end;
17373 if (*start != ';')
17374 return 0;
17375 *start++ = '\0';
17376 while (!ast_strlen_zero(start)) {
17377 end = strchr(start, ';');
17378 if (end)
17379 *end++ = '\0';
17380 if (!strncasecmp(start, "privacy=", 8))
17381 privacy = start + 8;
17382 else if (!strncasecmp(start, "screen=", 7))
17383 screen = start + 7;
17384 start = end;
17385 }
17386
17387 if (!strcasecmp(privacy, "full")) {
17388 if (!strcasecmp(screen, "yes"))
17389 callingpres = AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN;
17390 else if (!strcasecmp(screen, "no"))
17391 callingpres = AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
17392 } else {
17393 if (!strcasecmp(screen, "yes"))
17394 callingpres = AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN;
17395 else if (!strcasecmp(screen, "no"))
17396 callingpres = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
17397 }
17398 }
17399
17400
17401 if (!strcasecmp(p->cid_num, cid_num) && !strcasecmp(p->cid_name, cid_name) && p->callingpres == callingpres)
17402 return 0;
17403
17404 ast_string_field_set(p, cid_num, cid_num);
17405 ast_string_field_set(p, cid_name, cid_name);
17406 p->callingpres = callingpres;
17407
17408 if (p->owner) {
17409 ast_set_callerid(p->owner, cid_num, cid_name, NULL);
17410 ast_channel_caller(p->owner)->id.name.presentation = callingpres;
17411 ast_channel_caller(p->owner)->id.number.presentation = callingpres;
17412 }
17413
17414 return 1;
17415 }
17416
17417
17418 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq, char **name, char **number, int *reason)
17419 {
17420 char tmp[256], *exten, *rexten, *rdomain, *rname = NULL;
17421 char *params, *reason_param = NULL;
17422 struct sip_request *req;
17423
17424 req = oreq ? oreq : &p->initreq;
17425
17426 ast_copy_string(tmp, sip_get_header(req, "Diversion"), sizeof(tmp));
17427 if (ast_strlen_zero(tmp))
17428 return -1;
17429
17430 if ((params = strchr(tmp, '>'))) {
17431 params = strchr(params, ';');
17432 }
17433
17434 exten = get_in_brackets(tmp);
17435 if (!strncasecmp(exten, "sip:", 4)) {
17436 exten += 4;
17437 } else if (!strncasecmp(exten, "sips:", 5)) {
17438 exten += 5;
17439 } else {
17440 ast_log(LOG_WARNING, "Huh? Not an RDNIS SIP header (%s)?\n", exten);
17441 return -1;
17442 }
17443
17444
17445 if (params) {
17446 *params = '\0';
17447 params++;
17448 while (*params == ';' || *params == ' ')
17449 params++;
17450
17451 if ((reason_param = strcasestr(params, "reason="))) {
17452 char *end;
17453 reason_param+=7;
17454 if ((end = strchr(reason_param, ';'))) {
17455 *end = '\0';
17456 }
17457
17458 if (*reason_param == '"')
17459 reason_param = ast_strip_quoted(reason_param, "\"", "\"");
17460 if (!ast_strlen_zero(reason_param)) {
17461 sip_set_redirstr(p, reason_param);
17462 if (p->owner) {
17463 pbx_builtin_setvar_helper(p->owner, "__PRIREDIRECTREASON", p->redircause);
17464 pbx_builtin_setvar_helper(p->owner, "__SIPREDIRECTREASON", reason_param);
17465 }
17466 }
17467 }
17468 }
17469
17470 rdomain = exten;
17471 rexten = strsep(&rdomain, "@");
17472 if (p->owner)
17473 pbx_builtin_setvar_helper(p->owner, "__SIPRDNISDOMAIN", rdomain);
17474
17475 if (sip_debug_test_pvt(p))
17476 ast_verbose("RDNIS for this call is %s (reason %s)\n", exten, S_OR(reason_param, ""));
17477
17478
17479
17480 if (*tmp == '\"') {
17481 char *end_quote;
17482 rname = tmp + 1;
17483 end_quote = strchr(rname, '\"');
17484 if (end_quote) {
17485 *end_quote = '\0';
17486 }
17487 }
17488
17489 if (number) {
17490 *number = ast_strdup(rexten);
17491 }
17492
17493 if (name && rname) {
17494 *name = ast_strdup(rname);
17495 }
17496
17497 if (reason && !ast_strlen_zero(reason_param)) {
17498 *reason = sip_reason_str_to_code(reason_param);
17499 }
17500
17501 return 0;
17502 }
17503
17504
17505
17506
17507
17508
17509
17510
17511
17512
17513
17514
17515
17516
17517
17518 static enum sip_get_dest_result get_destination(struct sip_pvt *p, struct sip_request *oreq, int *cc_recall_core_id)
17519 {
17520 char tmp[256] = "", *uri, *unused_password, *domain;
17521 char tmpf[256] = "", *from = NULL;
17522 struct sip_request *req;
17523 char *decoded_uri;
17524
17525 req = oreq;
17526 if (!req) {
17527 req = &p->initreq;
17528 }
17529
17530
17531 if (req->rlpart2) {
17532 ast_copy_string(tmp, REQ_OFFSET_TO_STR(req, rlpart2), sizeof(tmp));
17533 }
17534
17535 uri = ast_strdupa(get_in_brackets(tmp));
17536
17537 if (parse_uri_legacy_check(uri, "sip:,sips:", &uri, &unused_password, &domain, NULL)) {
17538 ast_log(LOG_WARNING, "Not a SIP header (%s)?\n", uri);
17539 return SIP_GET_DEST_INVALID_URI;
17540 }
17541
17542 SIP_PEDANTIC_DECODE(domain);
17543 SIP_PEDANTIC_DECODE(uri);
17544
17545 extract_host_from_hostport(&domain);
17546
17547 if (ast_strlen_zero(uri)) {
17548
17549
17550
17551
17552
17553 uri = "s";
17554 }
17555
17556 ast_string_field_set(p, domain, domain);
17557
17558
17559
17560
17561
17562 ast_copy_string(tmpf, sip_get_header(req, "From"), sizeof(tmpf));
17563 if (!ast_strlen_zero(tmpf)) {
17564 from = get_in_brackets(tmpf);
17565 if (parse_uri_legacy_check(from, "sip:,sips:", &from, NULL, &domain, NULL)) {
17566 ast_log(LOG_WARNING, "Not a SIP header (%s)?\n", from);
17567 return SIP_GET_DEST_INVALID_URI;
17568 }
17569
17570 SIP_PEDANTIC_DECODE(from);
17571 SIP_PEDANTIC_DECODE(domain);
17572
17573 extract_host_from_hostport(&domain);
17574
17575 ast_string_field_set(p, fromdomain, domain);
17576 }
17577
17578 if (!AST_LIST_EMPTY(&domain_list)) {
17579 char domain_context[AST_MAX_EXTENSION];
17580
17581 domain_context[0] = '\0';
17582 if (!check_sip_domain(p->domain, domain_context, sizeof(domain_context))) {
17583 if (!sip_cfg.allow_external_domains && (req->method == SIP_INVITE || req->method == SIP_REFER)) {
17584 ast_debug(1, "Got SIP %s to non-local domain '%s'; refusing request.\n", sip_methods[req->method].text, p->domain);
17585 return SIP_GET_DEST_REFUSED;
17586 }
17587 }
17588
17589
17590 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_HAVEPEERCONTEXT) && !ast_strlen_zero(domain_context)) {
17591 ast_string_field_set(p, context, domain_context);
17592 }
17593 }
17594
17595
17596 if (req->method == SIP_SUBSCRIBE && !ast_strlen_zero(p->subscribecontext)) {
17597 ast_string_field_set(p, context, p->subscribecontext);
17598 }
17599
17600 if (sip_debug_test_pvt(p)) {
17601 ast_verbose("Looking for %s in %s (domain %s)\n", uri, p->context, p->domain);
17602 }
17603
17604
17605
17606 decoded_uri = ast_strdupa(uri);
17607 ast_uri_decode(decoded_uri, ast_uri_sip_user);
17608
17609
17610 if (req->method == SIP_SUBSCRIBE) {
17611 char hint[AST_MAX_EXTENSION];
17612 int which = 0;
17613 if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, uri) ||
17614 (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, decoded_uri) && (which = 1))) {
17615 if (!oreq) {
17616 ast_string_field_set(p, exten, which ? decoded_uri : uri);
17617 }
17618 return SIP_GET_DEST_EXTEN_FOUND;
17619 } else {
17620 return SIP_GET_DEST_EXTEN_NOT_FOUND;
17621 }
17622 } else {
17623 struct ast_cc_agent *agent;
17624
17625
17626
17627 if (ast_exists_extension(NULL, p->context, uri, 1, S_OR(p->cid_num, from))) {
17628 if (!oreq) {
17629 ast_string_field_set(p, exten, uri);
17630 }
17631 return SIP_GET_DEST_EXTEN_FOUND;
17632 }
17633 if (ast_exists_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from))
17634 || !strcmp(decoded_uri, ast_pickup_ext())) {
17635 if (!oreq) {
17636 ast_string_field_set(p, exten, decoded_uri);
17637 }
17638 return SIP_GET_DEST_EXTEN_FOUND;
17639 }
17640 if ((agent = find_sip_cc_agent_by_notify_uri(tmp))) {
17641 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
17642
17643
17644
17645 ast_string_field_set(p, exten, agent_pvt->original_exten);
17646
17647
17648
17649 ast_cc_agent_recalling(agent->core_id, "SIP caller %s is attempting recall",
17650 agent->device_name);
17651 if (cc_recall_core_id) {
17652 *cc_recall_core_id = agent->core_id;
17653 }
17654 ao2_ref(agent, -1);
17655 return SIP_GET_DEST_EXTEN_FOUND;
17656 }
17657 }
17658
17659 if (ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP)
17660 && (ast_canmatch_extension(NULL, p->context, uri, 1, S_OR(p->cid_num, from))
17661 || ast_canmatch_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from))
17662 || !strncmp(decoded_uri, ast_pickup_ext(), strlen(decoded_uri)))) {
17663
17664 return SIP_GET_DEST_EXTEN_MATCHMORE;
17665 }
17666
17667 return SIP_GET_DEST_EXTEN_NOT_FOUND;
17668 }
17669
17670
17671
17672
17673 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag)
17674 {
17675 struct sip_pvt *sip_pvt_ptr;
17676 struct sip_pvt tmp_dialog = {
17677 .callid = callid,
17678 };
17679
17680 if (totag) {
17681 ast_debug(4, "Looking for callid %s (fromtag %s totag %s)\n", callid, fromtag ? fromtag : "<no fromtag>", totag ? totag : "<no totag>");
17682 }
17683
17684
17685
17686 sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find of dialog in dialogs table");
17687 if (sip_pvt_ptr) {
17688
17689 sip_pvt_lock(sip_pvt_ptr);
17690 if (sip_cfg.pedanticsipchecking) {
17691 unsigned char frommismatch = 0, tomismatch = 0;
17692
17693 if (ast_strlen_zero(fromtag)) {
17694 sip_pvt_unlock(sip_pvt_ptr);
17695 ast_debug(4, "Matched %s call for callid=%s - no from tag specified, pedantic check fails\n",
17696 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
17697 return NULL;
17698 }
17699
17700 if (ast_strlen_zero(totag)) {
17701 sip_pvt_unlock(sip_pvt_ptr);
17702 ast_debug(4, "Matched %s call for callid=%s - no to tag specified, pedantic check fails\n",
17703 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
17704 return NULL;
17705 }
17706
17707
17708
17709
17710
17711
17712
17713
17714
17715
17716
17717
17718
17719
17720 frommismatch = !!strcmp(fromtag, sip_pvt_ptr->theirtag);
17721 tomismatch = !!strcmp(totag, sip_pvt_ptr->tag);
17722
17723
17724
17725
17726 if ((frommismatch && ast_test_flag(&sip_pvt_ptr->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) || tomismatch) {
17727 sip_pvt_unlock(sip_pvt_ptr);
17728 if (frommismatch) {
17729 ast_debug(4, "Matched %s call for callid=%s - pedantic from tag check fails; their tag is %s our tag is %s\n",
17730 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid,
17731 fromtag, sip_pvt_ptr->theirtag);
17732 }
17733 if (tomismatch) {
17734 ast_debug(4, "Matched %s call for callid=%s - pedantic to tag check fails; their tag is %s our tag is %s\n",
17735 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid,
17736 totag, sip_pvt_ptr->tag);
17737 }
17738 return NULL;
17739 }
17740 }
17741
17742 if (totag)
17743 ast_debug(4, "Matched %s call - their tag is %s Our tag is %s\n",
17744 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING",
17745 sip_pvt_ptr->theirtag, sip_pvt_ptr->tag);
17746
17747
17748 while (sip_pvt_ptr->owner && ast_channel_trylock(sip_pvt_ptr->owner)) {
17749 sip_pvt_unlock(sip_pvt_ptr);
17750 usleep(1);
17751 sip_pvt_lock(sip_pvt_ptr);
17752 }
17753 }
17754
17755 return sip_pvt_ptr;
17756 }
17757
17758
17759
17760
17761
17762
17763
17764
17765 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req)
17766 {
17767 const char *p_referred_by = NULL;
17768 char *h_refer_to = NULL;
17769 char *h_referred_by = NULL;
17770 char *refer_to;
17771 const char *p_refer_to;
17772 char *referred_by_uri = NULL;
17773 char *ptr;
17774 struct sip_request *req = NULL;
17775 const char *transfer_context = NULL;
17776 struct sip_refer *refer;
17777
17778 req = outgoing_req;
17779 refer = transferer->refer;
17780
17781 if (!req) {
17782 req = &transferer->initreq;
17783 }
17784
17785 p_refer_to = sip_get_header(req, "Refer-To");
17786 if (ast_strlen_zero(p_refer_to)) {
17787 ast_log(LOG_WARNING, "Refer-To Header missing. Skipping transfer.\n");
17788 return -2;
17789 }
17790 h_refer_to = ast_strdupa(p_refer_to);
17791 refer_to = get_in_brackets(h_refer_to);
17792 if (!strncasecmp(refer_to, "sip:", 4)) {
17793 refer_to += 4;
17794 } else if (!strncasecmp(refer_to, "sips:", 5)) {
17795 refer_to += 5;
17796 } else {
17797 ast_log(LOG_WARNING, "Can't transfer to non-sip: URI. (Refer-to: %s)?\n", refer_to);
17798 return -3;
17799 }
17800
17801
17802 p_referred_by = sip_get_header(req, "Referred-By");
17803
17804
17805 if (transferer->owner) {
17806 struct ast_channel *peer = ast_bridged_channel(transferer->owner);
17807 if (peer) {
17808 pbx_builtin_setvar_helper(peer, "SIPREFERRINGCONTEXT", transferer->context);
17809 pbx_builtin_setvar_helper(peer, "SIPREFERREDBYHDR", p_referred_by);
17810 }
17811 }
17812
17813 if (!ast_strlen_zero(p_referred_by)) {
17814 h_referred_by = ast_strdupa(p_referred_by);
17815
17816 referred_by_uri = get_in_brackets(h_referred_by);
17817
17818 if (!strncasecmp(referred_by_uri, "sip:", 4)) {
17819 referred_by_uri += 4;
17820 } else if (!strncasecmp(referred_by_uri, "sips:", 5)) {
17821 referred_by_uri += 5;
17822 } else {
17823 ast_log(LOG_WARNING, "Huh? Not a sip: header (Referred-by: %s). Skipping.\n", referred_by_uri);
17824 referred_by_uri = NULL;
17825 }
17826 }
17827
17828
17829 if ((ptr = strcasestr(refer_to, "replaces="))) {
17830 char *to = NULL, *from = NULL, *callid;
17831
17832
17833 refer->attendedtransfer = 1;
17834
17835 callid = ast_strdupa(ptr + 9);
17836 ast_uri_decode(callid, ast_uri_sip_user);
17837 if ((ptr = strchr(callid, ';'))) {
17838 *ptr++ = '\0';
17839 }
17840 ast_string_field_set(refer, replaces_callid, callid);
17841
17842 if (ptr) {
17843
17844 to = strcasestr(ptr, "to-tag=");
17845 from = strcasestr(ptr, "from-tag=");
17846 }
17847
17848
17849 if (to) {
17850 ptr = to + 7;
17851 if ((to = strchr(ptr, '&'))) {
17852 *to = '\0';
17853 }
17854 if ((to = strchr(ptr, ';'))) {
17855 *to = '\0';
17856 }
17857 ast_string_field_set(refer, replaces_callid_totag, ptr);
17858 }
17859
17860 if (from) {
17861 ptr = from + 9;
17862 if ((from = strchr(ptr, '&'))) {
17863 *from = '\0';
17864 }
17865 if ((from = strchr(ptr, ';'))) {
17866 *from = '\0';
17867 }
17868 ast_string_field_set(refer, replaces_callid_fromtag, ptr);
17869 }
17870
17871 if (!strcmp(refer->replaces_callid, transferer->callid) &&
17872 (!sip_cfg.pedanticsipchecking ||
17873 (!strcmp(refer->replaces_callid_fromtag, transferer->theirtag) &&
17874 !strcmp(refer->replaces_callid_totag, transferer->tag)))) {
17875 ast_log(LOG_WARNING, "Got an attempt to replace own Call-ID on %s\n", transferer->callid);
17876 return -4;
17877 }
17878
17879 if (!sip_cfg.pedanticsipchecking) {
17880 ast_debug(2, "Attended transfer: Will use Replace-Call-ID : %s (No check of from/to tags)\n", refer->replaces_callid);
17881 } else {
17882 ast_debug(2, "Attended transfer: Will use Replace-Call-ID : %s F-tag: %s T-tag: %s\n", refer->replaces_callid, refer->replaces_callid_fromtag ? refer->replaces_callid_fromtag : "<none>", refer->replaces_callid_totag ? refer->replaces_callid_totag : "<none>");
17883 }
17884 }
17885
17886 if ((ptr = strchr(refer_to, '@'))) {
17887 char *urioption = NULL, *domain;
17888 int bracket = 0;
17889 *ptr++ = '\0';
17890
17891 if ((urioption = strchr(ptr, ';'))) {
17892 *urioption++ = '\0';
17893 }
17894
17895 domain = ptr;
17896
17897
17898 for (; *ptr != '\0'; ++ptr) {
17899 if (*ptr == ':' && bracket == 0) {
17900 *ptr = '\0';
17901 break;
17902 } else if (*ptr == '[') {
17903 ++bracket;
17904 } else if (*ptr == ']') {
17905 --bracket;
17906 }
17907 }
17908
17909 SIP_PEDANTIC_DECODE(domain);
17910 SIP_PEDANTIC_DECODE(urioption);
17911
17912
17913 ast_string_field_set(refer, refer_to_domain, domain);
17914 if (urioption) {
17915 ast_string_field_set(refer, refer_to_urioption, urioption);
17916 }
17917 }
17918
17919 if ((ptr = strchr(refer_to, ';')))
17920 *ptr = '\0';
17921
17922 SIP_PEDANTIC_DECODE(refer_to);
17923 ast_string_field_set(refer, refer_to, refer_to);
17924
17925 if (referred_by_uri) {
17926 if ((ptr = strchr(referred_by_uri, ';')))
17927 *ptr = '\0';
17928 SIP_PEDANTIC_DECODE(referred_by_uri);
17929 ast_string_field_build(refer, referred_by, "<sip:%s>", referred_by_uri);
17930 } else {
17931 ast_string_field_set(refer, referred_by, "");
17932 }
17933
17934
17935 if (transferer->owner) {
17936
17937 transfer_context = pbx_builtin_getvar_helper(transferer->owner, "TRANSFER_CONTEXT");
17938 if (ast_strlen_zero(transfer_context)) {
17939 transfer_context = ast_channel_macrocontext(transferer->owner);
17940 }
17941 }
17942 if (ast_strlen_zero(transfer_context)) {
17943 transfer_context = S_OR(transferer->context, sip_cfg.default_context);
17944 }
17945
17946 ast_string_field_set(refer, refer_to_context, transfer_context);
17947
17948
17949 if (refer->attendedtransfer || ast_exists_extension(NULL, transfer_context, refer_to, 1, NULL)) {
17950 if (sip_debug_test_pvt(transferer)) {
17951 ast_verbose("SIP transfer to extension %s@%s by %s\n", refer_to, transfer_context, referred_by_uri);
17952 }
17953
17954 return 0;
17955 }
17956 if (sip_debug_test_pvt(transferer))
17957 ast_verbose("Failed SIP Transfer to non-existing extension %s in context %s\n n", refer_to, transfer_context);
17958
17959
17960 return -1;
17961 }
17962
17963
17964
17965
17966
17967 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq)
17968 {
17969 char tmp[256] = "", *c, *a;
17970 struct sip_request *req = oreq ? oreq : &p->initreq;
17971 struct sip_refer *refer = NULL;
17972 const char *transfer_context = NULL;
17973
17974 if (!p->refer && !sip_refer_alloc(p))
17975 return -1;
17976
17977 refer = p->refer;
17978
17979 ast_copy_string(tmp, sip_get_header(req, "Also"), sizeof(tmp));
17980 c = get_in_brackets(tmp);
17981
17982 if (parse_uri_legacy_check(c, "sip:,sips:", &c, NULL, &a, NULL)) {
17983 ast_log(LOG_WARNING, "Huh? Not a SIP header in Also: transfer (%s)?\n", c);
17984 return -1;
17985 }
17986
17987 SIP_PEDANTIC_DECODE(c);
17988 SIP_PEDANTIC_DECODE(a);
17989
17990 if (!ast_strlen_zero(a)) {
17991 ast_string_field_set(refer, refer_to_domain, a);
17992 }
17993
17994 if (sip_debug_test_pvt(p))
17995 ast_verbose("Looking for %s in %s\n", c, p->context);
17996
17997
17998 if (p->owner) {
17999
18000 transfer_context = pbx_builtin_getvar_helper(p->owner, "TRANSFER_CONTEXT");
18001 if (ast_strlen_zero(transfer_context)) {
18002 transfer_context = ast_channel_macrocontext(p->owner);
18003 }
18004 }
18005 if (ast_strlen_zero(transfer_context)) {
18006 transfer_context = S_OR(p->context, sip_cfg.default_context);
18007 }
18008
18009 if (ast_exists_extension(NULL, transfer_context, c, 1, NULL)) {
18010
18011 ast_debug(1, "SIP Bye-also transfer to Extension %s@%s \n", c, transfer_context);
18012 ast_string_field_set(refer, refer_to, c);
18013 ast_string_field_set(refer, referred_by, "");
18014 ast_string_field_set(refer, refer_contact, "");
18015
18016 ast_string_field_set(p, context, transfer_context);
18017 return 0;
18018 } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
18019 return 1;
18020 }
18021
18022 return -1;
18023 }
18024
18025
18026 static void set_peer_nat(const struct sip_pvt *p, struct sip_peer *peer)
18027 {
18028
18029 if (!p || !peer) {
18030 return;
18031 }
18032
18033 if (ast_test_flag(&peer->flags[2], SIP_PAGE3_NAT_AUTO_RPORT)) {
18034 if (p->natdetected) {
18035 ast_set_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT);
18036 } else {
18037 ast_clear_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT);
18038 }
18039 }
18040
18041 if (ast_test_flag(&peer->flags[2], SIP_PAGE3_NAT_AUTO_COMEDIA)) {
18042 if (p->natdetected) {
18043 ast_set_flag(&peer->flags[1], SIP_PAGE2_SYMMETRICRTP);
18044 } else {
18045 ast_clear_flag(&peer->flags[1], SIP_PAGE2_SYMMETRICRTP);
18046 }
18047 }
18048 }
18049
18050
18051
18052
18053
18054
18055
18056
18057 static void check_for_nat(const struct ast_sockaddr *addr, struct sip_pvt *p)
18058 {
18059
18060 if (!addr || !p) {
18061 return;
18062 }
18063
18064 if (ast_sockaddr_cmp_addr(addr, &p->recv)) {
18065 char *tmp_str = ast_strdupa(ast_sockaddr_stringify_addr(addr));
18066 ast_debug(3, "NAT detected for %s / %s\n", tmp_str, ast_sockaddr_stringify_addr(&p->recv));
18067 p->natdetected = 1;
18068 if (ast_test_flag(&p->flags[2], SIP_PAGE3_NAT_AUTO_RPORT)) {
18069 ast_set_flag(&p->flags[0], SIP_NAT_FORCE_RPORT);
18070 }
18071 if (ast_test_flag(&p->flags[2], SIP_PAGE3_NAT_AUTO_COMEDIA)) {
18072 ast_set_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP);
18073 }
18074 } else {
18075 p->natdetected = 0;
18076 if (ast_test_flag(&p->flags[2], SIP_PAGE3_NAT_AUTO_RPORT)) {
18077 ast_clear_flag(&p->flags[0], SIP_NAT_FORCE_RPORT);
18078 }
18079 if (ast_test_flag(&p->flags[2], SIP_PAGE3_NAT_AUTO_COMEDIA)) {
18080 ast_clear_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP);
18081 }
18082 }
18083
18084 }
18085
18086
18087 static void check_via(struct sip_pvt *p, const struct sip_request *req)
18088 {
18089 char via[512];
18090 char *c, *maddr;
18091 struct ast_sockaddr tmp = { { 0, } };
18092 uint16_t port;
18093
18094 ast_copy_string(via, sip_get_header(req, "Via"), sizeof(via));
18095
18096
18097 if (!strncasecmp(via, "SIP/2.0/WS", 10)) {
18098 return;
18099 }
18100
18101
18102 c = strchr(via, ',');
18103 if (c)
18104 *c = '\0';
18105
18106
18107 c = strstr(via, ";rport");
18108 if (c && (c[6] != '=')) {
18109 ast_set_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT);
18110 ast_set_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT);
18111 }
18112
18113
18114 maddr = strstr(via, "maddr=");
18115 if (maddr) {
18116 maddr += 6;
18117 c = maddr + strspn(maddr, "abcdefghijklmnopqrstuvwxyz"
18118 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-.:[]");
18119 *c = '\0';
18120 }
18121
18122 c = strchr(via, ';');
18123 if (c)
18124 *c = '\0';
18125
18126 c = strchr(via, ' ');
18127 if (c) {
18128 *c = '\0';
18129 c = ast_skip_blanks(c+1);
18130 if (strcasecmp(via, "SIP/2.0/UDP") && strcasecmp(via, "SIP/2.0/TCP") && strcasecmp(via, "SIP/2.0/TLS")) {
18131 ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
18132 return;
18133 }
18134
18135 if (maddr && ast_sockaddr_resolve_first(&p->sa, maddr, 0)) {
18136 p->sa = p->recv;
18137 }
18138
18139 if (ast_sockaddr_resolve_first(&tmp, c, 0)) {
18140 ast_log(LOG_WARNING, "Could not resolve socket address for '%s'\n", c);
18141 port = STANDARD_SIP_PORT;
18142 } else if (!(port = ast_sockaddr_port(&tmp))) {
18143 port = STANDARD_SIP_PORT;
18144 ast_sockaddr_set_port(&tmp, port);
18145 }
18146
18147 ast_sockaddr_set_port(&p->sa, port);
18148
18149 check_for_nat(&tmp, p);
18150
18151 if (sip_debug_test_pvt(p)) {
18152 ast_verbose("Sending to %s (%s)\n",
18153 ast_sockaddr_stringify(sip_real_dst(p)),
18154 sip_nat_mode(p));
18155 }
18156 }
18157 }
18158
18159
18160 static enum check_auth_result check_peer_ok(struct sip_pvt *p, char *of,
18161 struct sip_request *req, int sipmethod, struct ast_sockaddr *addr,
18162 struct sip_peer **authpeer,
18163 enum xmittype reliable, char *calleridname, char *uri2)
18164 {
18165 enum check_auth_result res;
18166 int debug = sip_debug_test_addr(addr);
18167 struct sip_peer *peer;
18168
18169 if (sipmethod == SIP_SUBSCRIBE) {
18170
18171
18172
18173 peer = sip_find_peer(of, NULL, TRUE, FINDALLDEVICES, FALSE, 0);
18174 } else {
18175
18176 peer = sip_find_peer(of, NULL, TRUE, FINDUSERS, FALSE, 0);
18177
18178
18179 if (!peer) {
18180 char *uri_tmp, *callback = NULL, *dummy;
18181 uri_tmp = ast_strdupa(uri2);
18182 parse_uri(uri_tmp, "sip:,sips:", &callback, &dummy, &dummy, &dummy);
18183 if (!ast_strlen_zero(callback) && (peer = sip_find_peer_by_ip_and_exten(&p->recv, callback, p->socket.type))) {
18184 ;
18185 } else {
18186 peer = sip_find_peer(NULL, &p->recv, TRUE, FINDPEERS, FALSE, p->socket.type);
18187 }
18188 }
18189 }
18190
18191 if (!peer) {
18192 if (debug) {
18193 ast_verbose("No matching peer for '%s' from '%s'\n",
18194 of, ast_sockaddr_stringify(&p->recv));
18195 }
18196
18197
18198
18199
18200 if (sip_cfg.allowguest || !sip_cfg.alwaysauthreject) {
18201 return AUTH_DONT_KNOW;
18202 }
18203
18204
18205
18206
18207 peer = bogus_peer;
18208 sip_ref_peer(peer, "sip_ref_peer: check_peer_ok: must ref bogus_peer so unreffing it does not fail");
18209 }
18210
18211
18212
18213
18214
18215
18216
18217 set_peer_nat(p, peer);
18218
18219 if (p->natdetected && ast_test_flag(&peer->flags[2], SIP_PAGE3_NAT_AUTO_RPORT)) {
18220 ast_sockaddr_copy(&peer->addr, &p->recv);
18221 }
18222
18223 if (!ast_apply_acl(peer->acl, addr, "SIP Peer ACL: ")) {
18224 ast_debug(2, "Found peer '%s' for '%s', but fails host access\n", peer->name, of);
18225 sip_unref_peer(peer, "sip_unref_peer: check_peer_ok: from sip_find_peer call, early return of AUTH_ACL_FAILED");
18226 return AUTH_ACL_FAILED;
18227 }
18228 if (debug && peer != bogus_peer) {
18229 ast_verbose("Found peer '%s' for '%s' from %s\n",
18230 peer->name, of, ast_sockaddr_stringify(&p->recv));
18231 }
18232
18233
18234
18235 if (p->rtp) {
18236 ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(p->rtp), p->rtp, &peer->prefs);
18237 p->autoframing = peer->autoframing;
18238 }
18239
18240
18241 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
18242 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
18243 ast_copy_flags(&p->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
18244
18245 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) && p->udptl) {
18246 p->t38_maxdatagram = peer->t38_maxdatagram;
18247 set_t38_capabilities(p);
18248 }
18249
18250 ast_rtp_dtls_cfg_copy(&peer->dtls_cfg, &p->dtls_cfg);
18251
18252
18253
18254 if (p->sipoptions)
18255 peer->sipoptions = p->sipoptions;
18256
18257 do_setnat(p);
18258
18259 ast_string_field_set(p, peersecret, peer->secret);
18260 ast_string_field_set(p, peermd5secret, peer->md5secret);
18261 ast_string_field_set(p, subscribecontext, peer->subscribecontext);
18262 ast_string_field_set(p, mohinterpret, peer->mohinterpret);
18263 ast_string_field_set(p, mohsuggest, peer->mohsuggest);
18264 if (!ast_strlen_zero(peer->parkinglot)) {
18265 ast_string_field_set(p, parkinglot, peer->parkinglot);
18266 }
18267 ast_string_field_set(p, engine, peer->engine);
18268 p->disallowed_methods = peer->disallowed_methods;
18269 set_pvt_allowed_methods(p, req);
18270 ast_cc_copy_config_params(p->cc_params, peer->cc_params);
18271 if (peer->callingpres)
18272 p->callingpres = peer->callingpres;
18273 if (peer->maxms && peer->lastms)
18274 p->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
18275 else
18276 p->timer_t1 = peer->timer_t1;
18277
18278
18279 if (peer->timer_b)
18280 p->timer_b = peer->timer_b;
18281 else
18282 p->timer_b = 64 * p->timer_t1;
18283
18284 p->allowtransfer = peer->allowtransfer;
18285
18286 if (ast_test_flag(&peer->flags[0], SIP_INSECURE_INVITE)) {
18287
18288 ast_string_field_set(p, peersecret, NULL);
18289 ast_string_field_set(p, peermd5secret, NULL);
18290 }
18291 if (!(res = check_auth(p, req, peer->name, p->peersecret, p->peermd5secret, sipmethod, uri2, reliable))) {
18292
18293 if (peer->call_limit)
18294 ast_set_flag(&p->flags[0], SIP_CALL_LIMIT);
18295 ast_string_field_set(p, peername, peer->name);
18296 ast_string_field_set(p, authname, peer->name);
18297
18298 ast_rtp_dtls_cfg_copy(&peer->dtls_cfg, &p->dtls_cfg);
18299
18300 if (sipmethod == SIP_INVITE) {
18301
18302 ast_variables_destroy(p->chanvars);
18303 p->chanvars = copy_vars(peer->chanvars);
18304 }
18305
18306 if (authpeer) {
18307 ao2_t_ref(peer, 1, "copy pointer into (*authpeer)");
18308 (*authpeer) = peer;
18309 }
18310
18311 if (!ast_strlen_zero(peer->username)) {
18312 ast_string_field_set(p, username, peer->username);
18313
18314
18315 ast_string_field_set(p, authname, peer->username);
18316 }
18317 if (!get_rpid(p, req)) {
18318 if (!ast_strlen_zero(peer->cid_num)) {
18319 char *tmp = ast_strdupa(peer->cid_num);
18320 if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
18321 ast_shrink_phone_number(tmp);
18322 ast_string_field_set(p, cid_num, tmp);
18323 }
18324 if (!ast_strlen_zero(peer->cid_name))
18325 ast_string_field_set(p, cid_name, peer->cid_name);
18326 if (peer->callingpres)
18327 p->callingpres = peer->callingpres;
18328 }
18329 if (!ast_strlen_zero(peer->cid_tag)) {
18330 ast_string_field_set(p, cid_tag, peer->cid_tag);
18331 }
18332 ast_string_field_set(p, fullcontact, peer->fullcontact);
18333 if (!ast_strlen_zero(peer->context)) {
18334 ast_string_field_set(p, context, peer->context);
18335 }
18336 if (!ast_strlen_zero(peer->messagecontext)) {
18337 ast_string_field_set(p, messagecontext, peer->messagecontext);
18338 }
18339 if (!ast_strlen_zero(peer->mwi_from)) {
18340 ast_string_field_set(p, mwi_from, peer->mwi_from);
18341 }
18342 ast_string_field_set(p, peersecret, peer->secret);
18343 ast_string_field_set(p, peermd5secret, peer->md5secret);
18344 ast_string_field_set(p, language, peer->language);
18345 ast_string_field_set(p, accountcode, peer->accountcode);
18346 p->amaflags = peer->amaflags;
18347 p->callgroup = peer->callgroup;
18348 p->pickupgroup = peer->pickupgroup;
18349 ast_unref_namedgroups(p->named_callgroups);
18350 p->named_callgroups = ast_ref_namedgroups(peer->named_callgroups);
18351 ast_unref_namedgroups(p->named_pickupgroups);
18352 p->named_pickupgroups = ast_ref_namedgroups(peer->named_pickupgroups);
18353 ast_format_cap_copy(p->caps, peer->caps);
18354 ast_format_cap_copy(p->jointcaps, peer->caps);
18355 p->prefs = peer->prefs;
18356 ast_copy_string(p->zone, peer->zone, sizeof(p->zone));
18357 if (peer->maxforwards > 0) {
18358 p->maxforwards = peer->maxforwards;
18359 }
18360 if (!(ast_format_cap_is_empty(p->peercaps))) {
18361 struct ast_format_cap *tmp = ast_format_cap_joint(p->jointcaps, p->peercaps);
18362 struct ast_format_cap *tmp2;
18363 if (tmp) {
18364 tmp2 = p->jointcaps;
18365 p->jointcaps = tmp;
18366 ast_format_cap_destroy(tmp2);
18367 }
18368 }
18369 p->maxcallbitrate = peer->maxcallbitrate;
18370 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
18371 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
18372 p->noncodeccapability |= AST_RTP_DTMF;
18373 else
18374 p->noncodeccapability &= ~AST_RTP_DTMF;
18375 p->jointnoncodeccapability = p->noncodeccapability;
18376 p->rtptimeout = peer->rtptimeout;
18377 p->rtpholdtimeout = peer->rtpholdtimeout;
18378 p->rtpkeepalive = peer->rtpkeepalive;
18379 if (!dialog_initialize_rtp(p)) {
18380 if (p->rtp) {
18381 ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(p->rtp), p->rtp, &peer->prefs);
18382 p->autoframing = peer->autoframing;
18383 }
18384 } else {
18385 res = AUTH_RTP_FAILED;
18386 }
18387 }
18388 sip_unref_peer(peer, "check_peer_ok: sip_unref_peer: tossing temp ptr to peer from sip_find_peer");
18389 return res;
18390 }
18391
18392
18393
18394
18395
18396
18397
18398 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
18399 int sipmethod, const char *uri, enum xmittype reliable,
18400 struct ast_sockaddr *addr, struct sip_peer **authpeer)
18401 {
18402 char from[256], *of, *name, *unused_password, *domain;
18403 enum check_auth_result res = AUTH_DONT_KNOW;
18404 char calleridname[256];
18405 char *uri2 = ast_strdupa(uri);
18406
18407 terminate_uri(uri2);
18408
18409 ast_copy_string(from, sip_get_header(req, "From"), sizeof(from));
18410
18411
18412
18413 if (!(of = (char *) get_calleridname(from, calleridname, sizeof(calleridname)))) {
18414 ast_log(LOG_ERROR, "FROM header can not be parsed \n");
18415 return res;
18416 }
18417
18418 if (calleridname[0]) {
18419 ast_string_field_set(p, cid_name, calleridname);
18420 }
18421
18422 if (ast_strlen_zero(p->exten)) {
18423 char *t = uri2;
18424 if (!strncasecmp(t, "sip:", 4))
18425 t+= 4;
18426 else if (!strncasecmp(t, "sips:", 5))
18427 t += 5;
18428 ast_string_field_set(p, exten, t);
18429 t = strchr(p->exten, '@');
18430 if (t)
18431 *t = '\0';
18432
18433 if (ast_strlen_zero(p->our_contact))
18434 build_contact(p);
18435 }
18436
18437 of = get_in_brackets(of);
18438
18439
18440 ast_string_field_set(p, from, of);
18441
18442 if (parse_uri_legacy_check(of, "sip:,sips:", &name, &unused_password, &domain, NULL)) {
18443 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
18444 }
18445
18446 SIP_PEDANTIC_DECODE(name);
18447 SIP_PEDANTIC_DECODE(domain);
18448
18449 extract_host_from_hostport(&domain);
18450
18451 if (ast_strlen_zero(domain)) {
18452
18453 ast_log(LOG_ERROR, "Empty domain name in FROM header\n");
18454 return res;
18455 }
18456
18457 if (ast_strlen_zero(name)) {
18458
18459
18460
18461 name = domain;
18462 } else {
18463
18464 char *tmp = ast_strdupa(name);
18465
18466
18467
18468 tmp = strsep(&tmp, ";");
18469 if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp)) {
18470 ast_shrink_phone_number(tmp);
18471 }
18472 ast_string_field_set(p, cid_num, tmp);
18473 }
18474
18475 if (global_match_auth_username) {
18476
18477
18478
18479
18480
18481
18482
18483
18484 const char *hdr = sip_get_header(req, "Authorization");
18485 if (ast_strlen_zero(hdr)) {
18486 hdr = sip_get_header(req, "Proxy-Authorization");
18487 }
18488
18489 if (!ast_strlen_zero(hdr) && (hdr = strstr(hdr, "username=\""))) {
18490 ast_copy_string(from, hdr + strlen("username=\""), sizeof(from));
18491 name = from;
18492 name = strsep(&name, "\"");
18493 }
18494 }
18495
18496 res = check_peer_ok(p, name, req, sipmethod, addr,
18497 authpeer, reliable, calleridname, uri2);
18498 if (res != AUTH_DONT_KNOW) {
18499 return res;
18500 }
18501
18502
18503 if (sip_cfg.allowguest) {
18504
18505 get_rpid(p, req);
18506 p->rtptimeout = global_rtptimeout;
18507 p->rtpholdtimeout = global_rtpholdtimeout;
18508 p->rtpkeepalive = global_rtpkeepalive;
18509 if (!dialog_initialize_rtp(p)) {
18510 res = AUTH_SUCCESSFUL;
18511 } else {
18512 res = AUTH_RTP_FAILED;
18513 }
18514 } else {
18515 res = AUTH_SECRET_FAILED;
18516 }
18517
18518 if (ast_test_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT)) {
18519 ast_set_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT);
18520 }
18521
18522 return res;
18523 }
18524
18525
18526
18527
18528 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, const char *uri, enum xmittype reliable, struct ast_sockaddr *addr)
18529 {
18530 return check_user_full(p, req, sipmethod, uri, reliable, addr, NULL);
18531 }
18532
18533 static int set_message_vars_from_req(struct ast_msg *msg, struct sip_request *req)
18534 {
18535 size_t x;
18536 char name_buf[1024];
18537 char val_buf[1024];
18538 const char *name;
18539 char *c;
18540 int res = 0;
18541
18542 for (x = 0; x < req->headers; x++) {
18543 const char *header = REQ_OFFSET_TO_STR(req, header[x]);
18544
18545 if ((c = strchr(header, ':'))) {
18546 ast_copy_string(name_buf, header, MIN((c - header + 1), sizeof(name_buf)));
18547 ast_copy_string(val_buf, ast_skip_blanks(c + 1), sizeof(val_buf));
18548 ast_trim_blanks(name_buf);
18549
18550
18551 name = find_full_alias(name_buf, name_buf);
18552
18553 res = ast_msg_set_var(msg, name, val_buf);
18554 if (res) {
18555 break;
18556 }
18557 }
18558 }
18559 return res;
18560 }
18561
18562
18563
18564
18565 static void receive_message(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e)
18566 {
18567 char *buf;
18568 size_t len;
18569 struct ast_frame f;
18570 const char *content_type = sip_get_header(req, "Content-Type");
18571 struct ast_msg *msg;
18572 int res;
18573 char *from;
18574 char *to;
18575 char from_name[50];
18576 char stripped[SIPBUFSIZE];
18577
18578 if (strncmp(content_type, "text/plain", strlen("text/plain"))) {
18579 transmit_response(p, "415 Unsupported Media Type", req);
18580 if (!p->owner) {
18581 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18582 }
18583 return;
18584 }
18585
18586 if (!(buf = get_content(req))) {
18587 ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
18588 transmit_response(p, "500 Internal Server Error", req);
18589 if (!p->owner) {
18590 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18591 }
18592 return;
18593 }
18594
18595
18596
18597 len = strlen(buf);
18598 while (len > 0) {
18599 if (buf[--len] != '\n') {
18600 ++len;
18601 break;
18602 }
18603 }
18604 buf[len] = '\0';
18605
18606 if (p->owner) {
18607 if (sip_debug_test_pvt(p)) {
18608 ast_verbose("SIP Text message received: '%s'\n", buf);
18609 }
18610 memset(&f, 0, sizeof(f));
18611 f.frametype = AST_FRAME_TEXT;
18612 f.subclass.integer = 0;
18613 f.offset = 0;
18614 f.data.ptr = buf;
18615 f.datalen = strlen(buf) + 1;
18616 ast_queue_frame(p->owner, &f);
18617 transmit_response(p, "202 Accepted", req);
18618 return;
18619 }
18620
18621
18622
18623
18624
18625
18626
18627
18628 if (!sip_cfg.accept_outofcall_message) {
18629
18630 ast_debug(1, "MESSAGE outside of a call administratively disabled.\n");
18631 transmit_response(p, "405 Method Not Allowed", req);
18632 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18633 return;
18634 }
18635
18636 copy_request(&p->initreq, req);
18637
18638 if (sip_cfg.auth_message_requests) {
18639 int res;
18640
18641 set_pvt_allowed_methods(p, req);
18642 res = check_user(p, req, SIP_MESSAGE, e, XMIT_UNRELIABLE, addr);
18643 if (res == AUTH_CHALLENGE_SENT) {
18644 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18645 return;
18646 }
18647 if (res < 0) {
18648 ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", sip_get_header(req, "From"));
18649 transmit_response(p, "403 Forbidden", req);
18650 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18651 return;
18652 }
18653
18654 } else {
18655 struct sip_peer *peer;
18656
18657
18658
18659
18660
18661
18662
18663 peer = sip_find_peer(NULL, &p->recv, TRUE, FINDPEERS, 0, p->socket.type);
18664 if (peer) {
18665
18666 if (ast_strlen_zero(peer->secret) && ast_strlen_zero(peer->md5secret)) {
18667 ast_string_field_set(p, context, peer->context);
18668 }
18669 if (!ast_strlen_zero(peer->messagecontext)) {
18670 ast_string_field_set(p, messagecontext, peer->messagecontext);
18671 }
18672 ast_string_field_set(p, peername, peer->name);
18673 peer = sip_unref_peer(peer, "from sip_find_peer() in receive_message");
18674 }
18675 }
18676
18677
18678
18679
18680 if (!ast_strlen_zero(p->messagecontext)) {
18681 ast_string_field_set(p, context, p->messagecontext);
18682 } else if (!ast_strlen_zero(sip_cfg.messagecontext)) {
18683 ast_string_field_set(p, context, sip_cfg.messagecontext);
18684 }
18685
18686 switch (get_destination(p, NULL, NULL)) {
18687 case SIP_GET_DEST_REFUSED:
18688
18689 transmit_response(p, "403 Forbidden", req);
18690 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18691 return;
18692 case SIP_GET_DEST_INVALID_URI:
18693 transmit_response(p, "416 Unsupported URI Scheme", req);
18694 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18695 return;
18696 case SIP_GET_DEST_EXTEN_NOT_FOUND:
18697 case SIP_GET_DEST_EXTEN_MATCHMORE:
18698 transmit_response(p, "404 Not Found", req);
18699 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18700 return;
18701 case SIP_GET_DEST_EXTEN_FOUND:
18702 break;
18703 }
18704
18705 if (!(msg = ast_msg_alloc())) {
18706 transmit_response(p, "500 Internal Server Error", req);
18707 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18708 return;
18709 }
18710
18711 to = ast_strdupa(REQ_OFFSET_TO_STR(req, rlpart2));
18712 from = ast_strdupa(sip_get_header(req, "From"));
18713
18714 res = ast_msg_set_to(msg, "%s", to);
18715
18716
18717 from = (char *) get_calleridname(from, from_name, sizeof(from_name));
18718 from = get_in_brackets(from);
18719 if (from_name[0]) {
18720 res |= ast_msg_set_from(msg, "\"%s\" <%s>", from_name, from);
18721 } else {
18722 res |= ast_msg_set_from(msg, "<%s>", from);
18723 }
18724
18725 res |= ast_msg_set_body(msg, "%s", buf);
18726 res |= ast_msg_set_context(msg, "%s", p->context);
18727
18728 res |= ast_msg_set_var(msg, "SIP_RECVADDR", ast_sockaddr_stringify(&p->recv));
18729 if (!ast_strlen_zero(p->peername)) {
18730 res |= ast_msg_set_var(msg, "SIP_PEERNAME", p->peername);
18731 }
18732
18733 ast_copy_string(stripped, sip_get_header(req, "Contact"), sizeof(stripped));
18734 res |= ast_msg_set_var(msg, "SIP_FULLCONTACT", get_in_brackets(stripped));
18735
18736 res |= ast_msg_set_exten(msg, "%s", p->exten);
18737 res |= set_message_vars_from_req(msg, req);
18738
18739 if (res) {
18740 ast_msg_destroy(msg);
18741 transmit_response(p, "500 Internal Server Error", req);
18742 } else {
18743 ast_msg_queue(msg);
18744 transmit_response(p, "202 Accepted", req);
18745 }
18746
18747 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18748 }
18749
18750
18751 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18752 {
18753 #define FORMAT "%-25.25s %-15.15s %-15.15s \n"
18754 #define FORMAT2 "%-25.25s %-15.15s %-15.15s \n"
18755 char ilimits[40];
18756 char iused[40];
18757 int showall = FALSE;
18758 struct ao2_iterator i;
18759 struct sip_peer *peer;
18760
18761 switch (cmd) {
18762 case CLI_INIT:
18763 e->command = "sip show inuse";
18764 e->usage =
18765 "Usage: sip show inuse [all]\n"
18766 " List all SIP devices usage counters and limits.\n"
18767 " Add option \"all\" to show all devices, not only those with a limit.\n";
18768 return NULL;
18769 case CLI_GENERATE:
18770 return NULL;
18771 }
18772
18773 if (a->argc < 3)
18774 return CLI_SHOWUSAGE;
18775
18776 if (a->argc == 4 && !strcmp(a->argv[3], "all"))
18777 showall = TRUE;
18778
18779 ast_cli(a->fd, FORMAT, "* Peer name", "In use", "Limit");
18780
18781 i = ao2_iterator_init(peers, 0);
18782 while ((peer = ao2_t_iterator_next(&i, "iterate thru peer table"))) {
18783 ao2_lock(peer);
18784 if (peer->call_limit)
18785 snprintf(ilimits, sizeof(ilimits), "%d", peer->call_limit);
18786 else
18787 ast_copy_string(ilimits, "N/A", sizeof(ilimits));
18788 snprintf(iused, sizeof(iused), "%d/%d/%d", peer->inuse, peer->ringing, peer->onhold);
18789 if (showall || peer->call_limit)
18790 ast_cli(a->fd, FORMAT2, peer->name, iused, ilimits);
18791 ao2_unlock(peer);
18792 sip_unref_peer(peer, "toss iterator pointer");
18793 }
18794 ao2_iterator_destroy(&i);
18795
18796 return CLI_SUCCESS;
18797 #undef FORMAT
18798 #undef FORMAT2
18799 }
18800
18801
18802
18803 static char *transfermode2str(enum transfermodes mode)
18804 {
18805 if (mode == TRANSFER_OPENFORALL)
18806 return "open";
18807 else if (mode == TRANSFER_CLOSED)
18808 return "closed";
18809 return "strict";
18810 }
18811
18812
18813
18814
18815
18816
18817
18818 static const struct _map_x_s stmodes[] = {
18819 { SESSION_TIMER_MODE_ACCEPT, "Accept"},
18820 { SESSION_TIMER_MODE_ORIGINATE, "Originate"},
18821 { SESSION_TIMER_MODE_REFUSE, "Refuse"},
18822 { -1, NULL},
18823 };
18824
18825 static const char *stmode2str(enum st_mode m)
18826 {
18827 return map_x_s(stmodes, m, "Unknown");
18828 }
18829
18830 static enum st_mode str2stmode(const char *s)
18831 {
18832 return map_s_x(stmodes, s, -1);
18833 }
18834
18835
18836 static const struct _map_x_s strefresher_params[] = {
18837 { SESSION_TIMER_REFRESHER_PARAM_UNKNOWN, "unknown" },
18838 { SESSION_TIMER_REFRESHER_PARAM_UAC, "uac" },
18839 { SESSION_TIMER_REFRESHER_PARAM_UAS, "uas" },
18840 { -1, NULL },
18841 };
18842
18843 static const struct _map_x_s strefreshers[] = {
18844 { SESSION_TIMER_REFRESHER_AUTO, "auto" },
18845 { SESSION_TIMER_REFRESHER_US, "us" },
18846 { SESSION_TIMER_REFRESHER_THEM, "them" },
18847 { -1, NULL },
18848 };
18849
18850 static const char *strefresherparam2str(enum st_refresher r)
18851 {
18852 return map_x_s(strefresher_params, r, "Unknown");
18853 }
18854
18855 static enum st_refresher str2strefresherparam(const char *s)
18856 {
18857 return map_s_x(strefresher_params, s, -1);
18858 }
18859
18860
18861 static struct _map_x_s autopeermodes[] = {
18862 { AUTOPEERS_DISABLED, "Off"},
18863 { AUTOPEERS_VOLATILE, "Volatile"},
18864 { AUTOPEERS_PERSIST, "Persisted"},
18865 { -1, NULL},
18866 };
18867
18868 static const char *strefresher2str(enum st_refresher r)
18869 {
18870 return map_x_s(strefreshers, r, "Unknown");
18871 }
18872
18873 static const char *autocreatepeer2str(enum autocreatepeer_mode r)
18874 {
18875 return map_x_s(autopeermodes, r, "Unknown");
18876 }
18877
18878 static int peer_status(struct sip_peer *peer, char *status, int statuslen)
18879 {
18880 int res = 0;
18881 if (peer->maxms) {
18882 if (peer->lastms < 0) {
18883 ast_copy_string(status, "UNREACHABLE", statuslen);
18884 } else if (peer->lastms > peer->maxms) {
18885 snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
18886 res = 1;
18887 } else if (peer->lastms) {
18888 snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
18889 res = 1;
18890 } else {
18891 ast_copy_string(status, "UNKNOWN", statuslen);
18892 }
18893 } else {
18894 ast_copy_string(status, "Unmonitored", statuslen);
18895
18896 res = -1;
18897 }
18898 return res;
18899 }
18900
18901
18902 static char *sip_show_tcp(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18903 {
18904 struct sip_threadinfo *th;
18905 struct ao2_iterator i;
18906
18907 #define FORMAT2 "%-47.47s %9.9s %6.6s\n"
18908 #define FORMAT "%-47.47s %-9.9s %-6.6s\n"
18909
18910 switch (cmd) {
18911 case CLI_INIT:
18912 e->command = "sip show tcp";
18913 e->usage =
18914 "Usage: sip show tcp\n"
18915 " Lists all active TCP/TLS sessions.\n";
18916 return NULL;
18917 case CLI_GENERATE:
18918 return NULL;
18919 }
18920
18921 if (a->argc != 3)
18922 return CLI_SHOWUSAGE;
18923
18924 ast_cli(a->fd, FORMAT2, "Address", "Transport", "Type");
18925
18926 i = ao2_iterator_init(threadt, 0);
18927 while ((th = ao2_t_iterator_next(&i, "iterate through tcp threads for 'sip show tcp'"))) {
18928 ast_cli(a->fd, FORMAT,
18929 ast_sockaddr_stringify(&th->tcptls_session->remote_address),
18930 sip_get_transport(th->type),
18931 (th->tcptls_session->client ? "Client" : "Server"));
18932 ao2_t_ref(th, -1, "decrement ref from iterator");
18933 }
18934 ao2_iterator_destroy(&i);
18935
18936 return CLI_SUCCESS;
18937 #undef FORMAT
18938 #undef FORMAT2
18939 }
18940
18941
18942 static char *sip_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18943 {
18944 regex_t regexbuf;
18945 int havepattern = FALSE;
18946 struct ao2_iterator user_iter;
18947 struct sip_peer *user;
18948
18949 #define FORMAT "%-25.25s %-15.15s %-15.15s %-15.15s %-5.5s%-10.10s\n"
18950
18951 switch (cmd) {
18952 case CLI_INIT:
18953 e->command = "sip show users";
18954 e->usage =
18955 "Usage: sip show users [like <pattern>]\n"
18956 " Lists all known SIP users.\n"
18957 " Optional regular expression pattern is used to filter the user list.\n";
18958 return NULL;
18959 case CLI_GENERATE:
18960 return NULL;
18961 }
18962
18963 switch (a->argc) {
18964 case 5:
18965 if (!strcasecmp(a->argv[3], "like")) {
18966 if (regcomp(®exbuf, a->argv[4], REG_EXTENDED | REG_NOSUB))
18967 return CLI_SHOWUSAGE;
18968 havepattern = TRUE;
18969 } else
18970 return CLI_SHOWUSAGE;
18971 case 3:
18972 break;
18973 default:
18974 return CLI_SHOWUSAGE;
18975 }
18976
18977 ast_cli(a->fd, FORMAT, "Username", "Secret", "Accountcode", "Def.Context", "ACL", "Forcerport");
18978
18979 user_iter = ao2_iterator_init(peers, 0);
18980 while ((user = ao2_t_iterator_next(&user_iter, "iterate thru peers table"))) {
18981 ao2_lock(user);
18982 if (!(user->type & SIP_TYPE_USER)) {
18983 ao2_unlock(user);
18984 sip_unref_peer(user, "sip show users");
18985 continue;
18986 }
18987
18988 if (havepattern && regexec(®exbuf, user->name, 0, NULL, 0)) {
18989 ao2_unlock(user);
18990 sip_unref_peer(user, "sip show users");
18991 continue;
18992 }
18993
18994 ast_cli(a->fd, FORMAT, user->name,
18995 user->secret,
18996 user->accountcode,
18997 user->context,
18998 AST_CLI_YESNO(ast_acl_list_is_empty(user->acl) == 0),
18999 AST_CLI_YESNO(ast_test_flag(&user->flags[0], SIP_NAT_FORCE_RPORT)));
19000 ao2_unlock(user);
19001 sip_unref_peer(user, "sip show users");
19002 }
19003 ao2_iterator_destroy(&user_iter);
19004
19005 if (havepattern)
19006 regfree(®exbuf);
19007
19008 return CLI_SUCCESS;
19009 #undef FORMAT
19010 }
19011
19012
19013 static int manager_show_registry(struct mansession *s, const struct message *m)
19014 {
19015 const char *id = astman_get_header(m, "ActionID");
19016 char idtext[256] = "";
19017 int total = 0;
19018
19019 if (!ast_strlen_zero(id))
19020 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
19021
19022 astman_send_listack(s, m, "Registrations will follow", "start");
19023
19024 ASTOBJ_CONTAINER_TRAVERSE(®l, 1, do {
19025 ASTOBJ_RDLOCK(iterator);
19026 astman_append(s,
19027 "Event: RegistryEntry\r\n"
19028 "%s"
19029 "Host: %s\r\n"
19030 "Port: %d\r\n"
19031 "Username: %s\r\n"
19032 "Domain: %s\r\n"
19033 "DomainPort: %d\r\n"
19034 "Refresh: %d\r\n"
19035 "State: %s\r\n"
19036 "RegistrationTime: %ld\r\n"
19037 "\r\n",
19038 idtext,
19039 iterator->hostname,
19040 iterator->portno ? iterator->portno : STANDARD_SIP_PORT,
19041 iterator->username,
19042 S_OR(iterator->regdomain,iterator->hostname),
19043 iterator->regdomainport ? iterator->regdomainport : STANDARD_SIP_PORT,
19044 iterator->refresh,
19045 regstate2str(iterator->regstate),
19046 (long) iterator->regtime.tv_sec);
19047 ASTOBJ_UNLOCK(iterator);
19048 total++;
19049 } while(0));
19050
19051 astman_append(s,
19052 "Event: RegistrationsComplete\r\n"
19053 "EventList: Complete\r\n"
19054 "ListItems: %d\r\n"
19055 "%s"
19056 "\r\n", total, idtext);
19057
19058 return 0;
19059 }
19060
19061
19062
19063 static int manager_sip_show_peers(struct mansession *s, const struct message *m)
19064 {
19065 const char *id = astman_get_header(m, "ActionID");
19066 const char *a[] = {"sip", "show", "peers"};
19067 char idtext[256] = "";
19068 int total = 0;
19069
19070 if (!ast_strlen_zero(id))
19071 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
19072
19073 astman_send_listack(s, m, "Peer status list will follow", "start");
19074
19075 _sip_show_peers(-1, &total, s, m, 3, a);
19076
19077 astman_append(s,
19078 "Event: PeerlistComplete\r\n"
19079 "EventList: Complete\r\n"
19080 "ListItems: %d\r\n"
19081 "%s"
19082 "\r\n", total, idtext);
19083 return 0;
19084 }
19085
19086
19087 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
19088 {
19089 switch (cmd) {
19090 case CLI_INIT:
19091 e->command = "sip show peers";
19092 e->usage =
19093 "Usage: sip show peers [like <pattern>]\n"
19094 " Lists all known SIP peers.\n"
19095 " Optional regular expression pattern is used to filter the peer list.\n";
19096 return NULL;
19097 case CLI_GENERATE:
19098 return NULL;
19099 }
19100
19101 return _sip_show_peers(a->fd, NULL, NULL, NULL, a->argc, (const char **) a->argv);
19102 }
19103
19104 int peercomparefunc(const void *a, const void *b);
19105
19106 int peercomparefunc(const void *a, const void *b)
19107 {
19108 struct sip_peer **ap = (struct sip_peer **)a;
19109 struct sip_peer **bp = (struct sip_peer **)b;
19110 return strcmp((*ap)->name, (*bp)->name);
19111 }
19112
19113
19114 #define PEERS_FORMAT2 "%-25.25s %-39.39s %-3.3s %-10.10s %-10.10s %-3.3s %-8s %-11s %-32.32s %s\n"
19115
19116
19117 struct show_peers_context {
19118 regex_t regexbuf;
19119 int havepattern;
19120 char idtext[256];
19121 int realtimepeers;
19122 int peers_mon_online;
19123 int peers_mon_offline;
19124 int peers_unmon_offline;
19125 int peers_unmon_online;
19126 };
19127
19128
19129 static char *_sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[])
19130 {
19131 struct show_peers_context cont = {
19132 .havepattern = FALSE,
19133 .idtext = "",
19134
19135 .peers_mon_online = 0,
19136 .peers_mon_offline = 0,
19137 .peers_unmon_online = 0,
19138 .peers_unmon_offline = 0,
19139 };
19140
19141 struct sip_peer *peer;
19142 struct ao2_iterator* it_peers;
19143
19144 int total_peers = 0;
19145 const char *id;
19146 struct sip_peer **peerarray;
19147 int k;
19148
19149 cont.realtimepeers = ast_check_realtime("sippeers");
19150
19151 if (s) {
19152 id = astman_get_header(m, "ActionID");
19153 if (!ast_strlen_zero(id)) {
19154 snprintf(cont.idtext, sizeof(cont.idtext), "ActionID: %s\r\n", id);
19155 }
19156 }
19157
19158 switch (argc) {
19159 case 5:
19160 if (!strcasecmp(argv[3], "like")) {
19161 if (regcomp(&cont.regexbuf, argv[4], REG_EXTENDED | REG_NOSUB)) {
19162 return CLI_SHOWUSAGE;
19163 }
19164 cont.havepattern = TRUE;
19165 } else {
19166 return CLI_SHOWUSAGE;
19167 }
19168 case 3:
19169 break;
19170 default:
19171 return CLI_SHOWUSAGE;
19172 }
19173
19174 if (!s) {
19175
19176 ast_cli(fd, PEERS_FORMAT2, "Name/username", "Host", "Dyn", "Forcerport", "Comedia", "ACL", "Port", "Status", "Description", (cont.realtimepeers ? "Realtime" : ""));
19177 }
19178
19179 ao2_lock(peers);
19180 if (!(it_peers = ao2_callback(peers, OBJ_MULTIPLE, NULL, NULL))) {
19181 ast_log(AST_LOG_ERROR, "Unable to create iterator for peers container for sip show peers\n");
19182 ao2_unlock(peers);
19183 return CLI_FAILURE;
19184 }
19185 if (!(peerarray = ast_calloc(sizeof(struct sip_peer *), ao2_container_count(peers)))) {
19186 ast_log(AST_LOG_ERROR, "Unable to allocate peer array for sip show peers\n");
19187 ao2_iterator_destroy(it_peers);
19188 ao2_unlock(peers);
19189 return CLI_FAILURE;
19190 }
19191 ao2_unlock(peers);
19192
19193 while ((peer = ao2_t_iterator_next(it_peers, "iterate thru peers table"))) {
19194 ao2_lock(peer);
19195
19196 if (!(peer->type & SIP_TYPE_PEER)) {
19197 ao2_unlock(peer);
19198 sip_unref_peer(peer, "unref peer because it's actually a user");
19199 continue;
19200 }
19201
19202 if (cont.havepattern && regexec(&cont.regexbuf, peer->name, 0, NULL, 0)) {
19203 ao2_unlock(peer);
19204 sip_unref_peer(peer, "toss iterator peer ptr before continue");
19205 continue;
19206 }
19207
19208 peerarray[total_peers++] = peer;
19209 ao2_unlock(peer);
19210 }
19211 ao2_iterator_destroy(it_peers);
19212
19213 qsort(peerarray, total_peers, sizeof(struct sip_peer *), peercomparefunc);
19214
19215 for(k = 0; k < total_peers; k++) {
19216 peerarray[k] = _sip_show_peers_one(fd, s, &cont, peerarray[k]);
19217 }
19218
19219 if (!s) {
19220 ast_cli(fd, "%d sip peers [Monitored: %d online, %d offline Unmonitored: %d online, %d offline]\n",
19221 total_peers, cont.peers_mon_online, cont.peers_mon_offline, cont.peers_unmon_online, cont.peers_unmon_offline);
19222 }
19223
19224 if (cont.havepattern) {
19225 regfree(&cont.regexbuf);
19226 }
19227
19228 if (total) {
19229 *total = total_peers;
19230 }
19231
19232 ast_free(peerarray);
19233
19234 return CLI_SUCCESS;
19235 }
19236
19237
19238 static struct sip_peer *_sip_show_peers_one(int fd, struct mansession *s, struct show_peers_context *cont, struct sip_peer *peer)
19239 {
19240
19241
19242
19243
19244 char name[256];
19245 char status[20] = "";
19246 char pstatus;
19247
19248
19249
19250
19251
19252
19253 char *tmp_port;
19254 char *tmp_host;
19255
19256 tmp_port = ast_sockaddr_isnull(&peer->addr) ?
19257 "0" : ast_strdupa(ast_sockaddr_stringify_port(&peer->addr));
19258
19259 tmp_host = ast_sockaddr_isnull(&peer->addr) ?
19260 "(Unspecified)" : ast_strdupa(ast_sockaddr_stringify_addr(&peer->addr));
19261
19262 ao2_lock(peer);
19263 if (cont->havepattern && regexec(&cont->regexbuf, peer->name, 0, NULL, 0)) {
19264 ao2_unlock(peer);
19265 return sip_unref_peer(peer, "toss iterator peer ptr no match");
19266 }
19267
19268 if (!ast_strlen_zero(peer->username) && !s) {
19269 snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
19270 } else {
19271 ast_copy_string(name, peer->name, sizeof(name));
19272 }
19273
19274 pstatus = peer_status(peer, status, sizeof(status));
19275 if (pstatus == 1) {
19276 cont->peers_mon_online++;
19277 } else if (pstatus == 0) {
19278 cont->peers_mon_offline++;
19279 } else {
19280 if (ast_sockaddr_isnull(&peer->addr) ||
19281 !ast_sockaddr_port(&peer->addr)) {
19282 cont->peers_unmon_offline++;
19283 } else {
19284 cont->peers_unmon_online++;
19285 }
19286 }
19287
19288 if (!s) {
19289 ast_cli(fd, PEERS_FORMAT2, name,
19290 tmp_host,
19291 peer->host_dynamic ? " D " : " ",
19292 force_rport_string(peer->flags),
19293 comedia_string(peer->flags),
19294 (!ast_acl_list_is_empty(peer->acl)) ? " A " : " ",
19295 tmp_port, status,
19296 peer->description ? peer->description : "",
19297 cont->realtimepeers ? (peer->is_realtime ? "Cached RT" : "") : "");
19298 } else {
19299
19300 astman_append(s,
19301 "Event: PeerEntry\r\n%s"
19302 "Channeltype: SIP\r\n"
19303 "ObjectName: %s\r\n"
19304 "ChanObjectType: peer\r\n"
19305 "IPaddress: %s\r\n"
19306 "IPport: %s\r\n"
19307 "Dynamic: %s\r\n"
19308 "AutoForcerport: %s\r\n"
19309 "Forcerport: %s\r\n"
19310 "AutoComedia: %s\r\n"
19311 "Comedia: %s\r\n"
19312 "VideoSupport: %s\r\n"
19313 "TextSupport: %s\r\n"
19314 "ACL: %s\r\n"
19315 "Status: %s\r\n"
19316 "RealtimeDevice: %s\r\n"
19317 "Description: %s\r\n\r\n",
19318 cont->idtext,
19319 peer->name,
19320 ast_sockaddr_isnull(&peer->addr) ? "-none-" : tmp_host,
19321 ast_sockaddr_isnull(&peer->addr) ? "0" : tmp_port,
19322 peer->host_dynamic ? "yes" : "no",
19323 ast_test_flag(&peer->flags[2], SIP_PAGE3_NAT_AUTO_RPORT) ? "yes" : "no",
19324 ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) ? "yes" : "no",
19325 ast_test_flag(&peer->flags[2], SIP_PAGE3_NAT_AUTO_COMEDIA) ? "yes" : "no",
19326 ast_test_flag(&peer->flags[1], SIP_PAGE2_SYMMETRICRTP) ? "yes" : "no",
19327 ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "yes" : "no",
19328 ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT) ? "yes" : "no",
19329 ast_acl_list_is_empty(peer->acl) ? "no" : "yes",
19330 status,
19331 cont->realtimepeers ? (peer->is_realtime ? "yes" : "no") : "no",
19332 peer->description);
19333 }
19334 ao2_unlock(peer);
19335
19336 return sip_unref_peer(peer, "toss iterator peer ptr");
19337 }
19338 #undef PEERS_FORMAT2
19339
19340 static int peer_dump_func(void *userobj, void *arg, int flags)
19341 {
19342 struct sip_peer *peer = userobj;
19343 int refc = ao2_t_ref(userobj, 0, "");
19344 struct ast_cli_args *a = (struct ast_cli_args *) arg;
19345
19346 ast_cli(a->fd, "name: %s\ntype: peer\nobjflags: %d\nrefcount: %d\n\n",
19347 peer->name, 0, refc);
19348 return 0;
19349 }
19350
19351 static int dialog_dump_func(void *userobj, void *arg, int flags)
19352 {
19353 struct sip_pvt *pvt = userobj;
19354 int refc = ao2_t_ref(userobj, 0, "");
19355 struct ast_cli_args *a = (struct ast_cli_args *) arg;
19356
19357 ast_cli(a->fd, "name: %s\ntype: dialog\nobjflags: %d\nrefcount: %d\n\n",
19358 pvt->callid, 0, refc);
19359 return 0;
19360 }
19361
19362
19363
19364 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
19365 {
19366 char tmp[256];
19367
19368 switch (cmd) {
19369 case CLI_INIT:
19370 e->command = "sip show objects";
19371 e->usage =
19372 "Usage: sip show objects\n"
19373 " Lists status of known SIP objects\n";
19374 return NULL;
19375 case CLI_GENERATE:
19376 return NULL;
19377 }
19378
19379 if (a->argc != 3)
19380 return CLI_SHOWUSAGE;
19381 ast_cli(a->fd, "-= Peer objects: %d static, %d realtime, %d autocreate =-\n\n", speerobjs, rpeerobjs, apeerobjs);
19382 ao2_t_callback(peers, OBJ_NODATA, peer_dump_func, a, "initiate ao2_callback to dump peers");
19383 ast_cli(a->fd, "-= Peer objects by IP =-\n\n");
19384 ao2_t_callback(peers_by_ip, OBJ_NODATA, peer_dump_func, a, "initiate ao2_callback to dump peers_by_ip");
19385 ast_cli(a->fd, "-= Registry objects: %d =-\n\n", regobjs);
19386 ASTOBJ_CONTAINER_DUMP(a->fd, tmp, sizeof(tmp), ®l);
19387 ast_cli(a->fd, "-= Dialog objects:\n\n");
19388 ao2_t_callback(dialogs, OBJ_NODATA, dialog_dump_func, a, "initiate ao2_callback to dump dialogs");
19389 return CLI_SUCCESS;
19390 }
19391
19392 static void print_group(int fd, ast_group_t group, int crlf)
19393 {
19394 char buf[256];
19395 ast_cli(fd, crlf ? "%s\r\n" : "%s\n", ast_print_group(buf, sizeof(buf), group) );
19396 }
19397
19398
19399 static void print_named_groups(int fd, struct ast_namedgroups *group, int crlf)
19400 {
19401 struct ast_str *buf = ast_str_create(1024);
19402 if (buf) {
19403 ast_cli(fd, crlf ? "%s\r\n" : "%s\n", ast_print_namedgroups(&buf, group) );
19404 ast_free(buf);
19405 }
19406 }
19407
19408
19409 static const struct _map_x_s dtmfstr[] = {
19410 { SIP_DTMF_RFC2833, "rfc2833" },
19411 { SIP_DTMF_INFO, "info" },
19412 { SIP_DTMF_SHORTINFO, "shortinfo" },
19413 { SIP_DTMF_INBAND, "inband" },
19414 { SIP_DTMF_AUTO, "auto" },
19415 { -1, NULL },
19416 };
19417
19418
19419 static const char *dtmfmode2str(int mode)
19420 {
19421 return map_x_s(dtmfstr, mode, "<error>");
19422 }
19423
19424
19425 static int str2dtmfmode(const char *str)
19426 {
19427 return map_s_x(dtmfstr, str, -1);
19428 }
19429
19430 static const struct _map_x_s insecurestr[] = {
19431 { SIP_INSECURE_PORT, "port" },
19432 { SIP_INSECURE_INVITE, "invite" },
19433 { SIP_INSECURE_PORT | SIP_INSECURE_INVITE, "port,invite" },
19434 { 0, "no" },
19435 { -1, NULL },
19436 };
19437
19438
19439 static const char *insecure2str(int mode)
19440 {
19441 return map_x_s(insecurestr, mode, "<error>");
19442 }
19443
19444 static const struct _map_x_s allowoverlapstr[] = {
19445 { SIP_PAGE2_ALLOWOVERLAP_YES, "Yes" },
19446 { SIP_PAGE2_ALLOWOVERLAP_DTMF, "DTMF" },
19447 { SIP_PAGE2_ALLOWOVERLAP_NO, "No" },
19448 { -1, NULL },
19449 };
19450
19451
19452 static const char *allowoverlap2str(int mode)
19453 {
19454 return map_x_s(allowoverlapstr, mode, "<error>");
19455 }
19456
19457 static const struct _map_x_s trust_id_outboundstr[] = {
19458 { SIP_PAGE2_TRUST_ID_OUTBOUND_LEGACY, "Legacy" },
19459 { SIP_PAGE2_TRUST_ID_OUTBOUND_NO, "No" },
19460 { SIP_PAGE2_TRUST_ID_OUTBOUND_YES, "Yes" },
19461 { -1, NULL },
19462 };
19463
19464 static const char *trust_id_outbound2str(int mode)
19465 {
19466 return map_x_s(trust_id_outboundstr, mode, "<error>");
19467 }
19468
19469
19470
19471
19472 static void cleanup_stale_contexts(char *new, char *old)
19473 {
19474 char *oldcontext, *newcontext, *stalecontext, *stringp, newlist[AST_MAX_CONTEXT];
19475
19476 while ((oldcontext = strsep(&old, "&"))) {
19477 stalecontext = '\0';
19478 ast_copy_string(newlist, new, sizeof(newlist));
19479 stringp = newlist;
19480 while ((newcontext = strsep(&stringp, "&"))) {
19481 if (!strcmp(newcontext, oldcontext)) {
19482
19483 stalecontext = '\0';
19484 break;
19485 } else if (strcmp(newcontext, oldcontext)) {
19486 stalecontext = oldcontext;
19487 }
19488
19489 }
19490 if (stalecontext)
19491 ast_context_destroy(ast_context_find(stalecontext), "SIP");
19492 }
19493 }
19494
19495
19496
19497
19498
19499
19500
19501
19502
19503 static int dialog_checkrtp_cb(void *dialogobj, void *arg, int flags)
19504 {
19505 struct sip_pvt *dialog = dialogobj;
19506 time_t *t = arg;
19507 int match_status;
19508
19509 if (sip_pvt_trylock(dialog)) {
19510 return 0;
19511 }
19512
19513 if (dialog->rtp || dialog->vrtp) {
19514 match_status = check_rtp_timeout(dialog, *t);
19515 } else {
19516
19517 match_status = CMP_MATCH;
19518 }
19519 sip_pvt_unlock(dialog);
19520
19521 return match_status;
19522 }
19523
19524
19525
19526
19527
19528
19529
19530
19531
19532
19533
19534 static int dialog_needdestroy(void *dialogobj, void *arg, int flags)
19535 {
19536 struct sip_pvt *dialog = dialogobj;
19537
19538 if (sip_pvt_trylock(dialog)) {
19539
19540
19541 return 0;
19542 }
19543
19544
19545
19546
19547 if (dialog->needdestroy && !dialog->packets && !dialog->owner) {
19548
19549 if (dialog->rtp && ast_rtp_instance_get_bridged(dialog->rtp)) {
19550 ast_debug(2, "Bridge still active. Delaying destruction of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
19551 sip_pvt_unlock(dialog);
19552 return 0;
19553 }
19554
19555 if (dialog->vrtp && ast_rtp_instance_get_bridged(dialog->vrtp)) {
19556 ast_debug(2, "Bridge still active. Delaying destroy of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
19557 sip_pvt_unlock(dialog);
19558 return 0;
19559 }
19560
19561 sip_pvt_unlock(dialog);
19562
19563
19564 dialog_unlink_all(dialog);
19565 return 0;
19566 }
19567
19568 sip_pvt_unlock(dialog);
19569
19570 return 0;
19571 }
19572
19573
19574
19575 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
19576 {
19577 struct sip_peer *peer, *pi;
19578 int prunepeer = FALSE;
19579 int multi = FALSE;
19580 const char *name = NULL;
19581 regex_t regexbuf;
19582 int havepattern = 0;
19583 struct ao2_iterator i;
19584 static const char * const choices[] = { "all", "like", NULL };
19585 char *cmplt;
19586
19587 if (cmd == CLI_INIT) {
19588 e->command = "sip prune realtime [peer|all]";
19589 e->usage =
19590 "Usage: sip prune realtime [peer [<name>|all|like <pattern>]|all]\n"
19591 " Prunes object(s) from the cache.\n"
19592 " Optional regular expression pattern is used to filter the objects.\n";
19593 return NULL;
19594 } else if (cmd == CLI_GENERATE) {
19595 if (a->pos == 4 && !strcasecmp(a->argv[3], "peer")) {
19596 cmplt = ast_cli_complete(a->word, choices, a->n);
19597 if (!cmplt)
19598 cmplt = complete_sip_peer(a->word, a->n - sizeof(choices), SIP_PAGE2_RTCACHEFRIENDS);
19599 return cmplt;
19600 }
19601 if (a->pos == 5 && !strcasecmp(a->argv[4], "like"))
19602 return complete_sip_peer(a->word, a->n, SIP_PAGE2_RTCACHEFRIENDS);
19603 return NULL;
19604 }
19605 switch (a->argc) {
19606 case 4:
19607 name = a->argv[3];
19608
19609 if (!strcasecmp(name, "peer") || !strcasecmp(name, "like"))
19610 return CLI_SHOWUSAGE;
19611 prunepeer = TRUE;
19612 if (!strcasecmp(name, "all")) {
19613 multi = TRUE;
19614 name = NULL;
19615 }
19616
19617 break;
19618 case 5:
19619
19620 name = a->argv[4];
19621 if (!strcasecmp(a->argv[3], "peer"))
19622 prunepeer = TRUE;
19623 else if (!strcasecmp(a->argv[3], "like")) {
19624 prunepeer = TRUE;
19625 multi = TRUE;
19626 } else
19627 return CLI_SHOWUSAGE;
19628 if (!strcasecmp(name, "like"))
19629 return CLI_SHOWUSAGE;
19630 if (!multi && !strcasecmp(name, "all")) {
19631 multi = TRUE;
19632 name = NULL;
19633 }
19634 break;
19635 case 6:
19636 name = a->argv[5];
19637 multi = TRUE;
19638
19639 if (strcasecmp(a->argv[4], "like"))
19640 return CLI_SHOWUSAGE;
19641 if (!strcasecmp(a->argv[3], "peer")) {
19642 prunepeer = TRUE;
19643 } else
19644 return CLI_SHOWUSAGE;
19645 break;
19646 default:
19647 return CLI_SHOWUSAGE;
19648 }
19649
19650 if (multi && name) {
19651 if (regcomp(®exbuf, name, REG_EXTENDED | REG_NOSUB)) {
19652 return CLI_SHOWUSAGE;
19653 }
19654 havepattern = 1;
19655 }
19656
19657 if (multi) {
19658 if (prunepeer) {
19659 int pruned = 0;
19660
19661 i = ao2_iterator_init(peers, 0);
19662 while ((pi = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
19663 ao2_lock(pi);
19664 if (name && regexec(®exbuf, pi->name, 0, NULL, 0)) {
19665 ao2_unlock(pi);
19666 sip_unref_peer(pi, "toss iterator peer ptr before continue");
19667 continue;
19668 };
19669 if (ast_test_flag(&pi->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
19670 pi->the_mark = 1;
19671 pruned++;
19672 }
19673 ao2_unlock(pi);
19674 sip_unref_peer(pi, "toss iterator peer ptr");
19675 }
19676 ao2_iterator_destroy(&i);
19677 if (pruned) {
19678 unlink_marked_peers_from_tables();
19679 ast_cli(a->fd, "%d peers pruned.\n", pruned);
19680 } else
19681 ast_cli(a->fd, "No peers found to prune.\n");
19682 }
19683 } else {
19684 if (prunepeer) {
19685 struct sip_peer tmp;
19686 ast_copy_string(tmp.name, name, sizeof(tmp.name));
19687 if ((peer = ao2_t_find(peers, &tmp, OBJ_POINTER | OBJ_UNLINK, "finding to unlink from peers"))) {
19688 if (!ast_sockaddr_isnull(&peer->addr)) {
19689 ao2_t_unlink(peers_by_ip, peer, "unlinking peer from peers_by_ip also");
19690 }
19691 if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
19692 ast_cli(a->fd, "Peer '%s' is not a Realtime peer, cannot be pruned.\n", name);
19693
19694 ao2_t_link(peers, peer, "link peer into peer table");
19695 if (!ast_sockaddr_isnull(&peer->addr)) {
19696 ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
19697 }
19698 } else
19699 ast_cli(a->fd, "Peer '%s' pruned.\n", name);
19700 sip_unref_peer(peer, "sip_prune_realtime: sip_unref_peer: tossing temp peer ptr");
19701 } else
19702 ast_cli(a->fd, "Peer '%s' not found.\n", name);
19703 }
19704 }
19705
19706 if (havepattern) {
19707 regfree(®exbuf);
19708 }
19709
19710 return CLI_SUCCESS;
19711 }
19712
19713
19714 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref)
19715 {
19716 int x;
19717 struct ast_format codec;
19718
19719 for(x = 0; x < AST_CODEC_PREF_SIZE; x++) {
19720 if (!(ast_codec_pref_index(pref, x, &codec))) {
19721 break;
19722 }
19723 ast_cli(fd, "%s", ast_getformatname(&codec));
19724 ast_cli(fd, ":%d", pref->framing[x]);
19725 if (x < 31 && ast_codec_pref_index(pref, x + 1, &codec))
19726 ast_cli(fd, ",");
19727 }
19728 if (!x)
19729 ast_cli(fd, "none");
19730 }
19731
19732
19733 static const char *domain_mode_to_text(const enum domain_mode mode)
19734 {
19735 switch (mode) {
19736 case SIP_DOMAIN_AUTO:
19737 return "[Automatic]";
19738 case SIP_DOMAIN_CONFIG:
19739 return "[Configured]";
19740 }
19741
19742 return "";
19743 }
19744
19745
19746 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
19747 {
19748 struct domain *d;
19749 #define FORMAT "%-40.40s %-20.20s %-16.16s\n"
19750
19751 switch (cmd) {
19752 case CLI_INIT:
19753 e->command = "sip show domains";
19754 e->usage =
19755 "Usage: sip show domains\n"
19756 " Lists all configured SIP local domains.\n"
19757 " Asterisk only responds to SIP messages to local domains.\n";
19758 return NULL;
19759 case CLI_GENERATE:
19760 return NULL;
19761 }
19762
19763 if (AST_LIST_EMPTY(&domain_list)) {
19764 ast_cli(a->fd, "SIP Domain support not enabled.\n\n");
19765 return CLI_SUCCESS;
19766 } else {
19767 ast_cli(a->fd, FORMAT, "Our local SIP domains:", "Context", "Set by");
19768 AST_LIST_LOCK(&domain_list);
19769 AST_LIST_TRAVERSE(&domain_list, d, list)
19770 ast_cli(a->fd, FORMAT, d->domain, S_OR(d->context, "(default)"),
19771 domain_mode_to_text(d->mode));
19772 AST_LIST_UNLOCK(&domain_list);
19773 ast_cli(a->fd, "\n");
19774 return CLI_SUCCESS;
19775 }
19776 }
19777 #undef FORMAT
19778
19779
19780 static int manager_sip_show_peer(struct mansession *s, const struct message *m)
19781 {
19782 const char *a[4];
19783 const char *peer;
19784
19785 peer = astman_get_header(m, "Peer");
19786 if (ast_strlen_zero(peer)) {
19787 astman_send_error(s, m, "Peer: <name> missing.");
19788 return 0;
19789 }
19790 a[0] = "sip";
19791 a[1] = "show";
19792 a[2] = "peer";
19793 a[3] = peer;
19794
19795 _sip_show_peer(1, -1, s, m, 4, a);
19796 astman_append(s, "\r\n" );
19797 return 0;
19798 }
19799
19800
19801 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
19802 {
19803 switch (cmd) {
19804 case CLI_INIT:
19805 e->command = "sip show peer";
19806 e->usage =
19807 "Usage: sip show peer <name> [load]\n"
19808 " Shows all details on one SIP peer and the current status.\n"
19809 " Option \"load\" forces lookup of peer in realtime storage.\n";
19810 return NULL;
19811 case CLI_GENERATE:
19812 return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
19813 }
19814 return _sip_show_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
19815 }
19816
19817 static void send_manager_peer_status(struct mansession *s, struct sip_peer *peer, const char *idText)
19818 {
19819 char time[128] = "";
19820 char status[128] = "";
19821 if (peer->maxms) {
19822 if (peer->lastms < 0) {
19823 snprintf(status, sizeof(status), "PeerStatus: Unreachable\r\n");
19824 } else if (peer->lastms > peer->maxms) {
19825 snprintf(status, sizeof(status), "PeerStatus: Lagged\r\n");
19826 snprintf(time, sizeof(time), "Time: %d\r\n", peer->lastms);
19827 } else if (peer->lastms) {
19828 snprintf(status, sizeof(status), "PeerStatus: Reachable\r\n");
19829 snprintf(time, sizeof(time), "Time: %d\r\n", peer->lastms);
19830 } else {
19831 snprintf(status, sizeof(status), "PeerStatus: Unknown\r\n");
19832 }
19833 } else {
19834 snprintf(status, sizeof(status), "PeerStatus: Unmonitored\r\n");
19835 }
19836
19837 astman_append(s,
19838 "Event: PeerStatus\r\n"
19839 "Privilege: System\r\n"
19840 "ChannelType: SIP\r\n"
19841 "Peer: SIP/%s\r\n"
19842 "%s"
19843 "%s"
19844 "%s"
19845 "\r\n",
19846 peer->name, status, time, idText);
19847 }
19848
19849
19850 static int manager_sip_peer_status(struct mansession *s, const struct message *m)
19851 {
19852 const char *id = astman_get_header(m,"ActionID");
19853 const char *peer_name = astman_get_header(m,"Peer");
19854 char idText[256] = "";
19855 struct sip_peer *peer = NULL;
19856
19857 if (!ast_strlen_zero(id)) {
19858 snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
19859 }
19860
19861 if (!ast_strlen_zero(peer_name)) {
19862
19863 if (strlen(peer_name) >= 4 && !strncasecmp("SIP/", peer_name, 4)) {
19864 peer_name += 4;
19865 }
19866
19867 peer = sip_find_peer(peer_name, NULL, TRUE, FINDPEERS, FALSE, 0);
19868 if (!peer) {
19869 astman_send_error(s, m, "No such peer");
19870 return 0;
19871 }
19872 }
19873
19874 astman_send_ack(s, m, "Peer status will follow");
19875
19876 if (!peer) {
19877 struct ao2_iterator i = ao2_iterator_init(peers, 0);
19878 while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table for SIPpeerstatus"))) {
19879 ao2_lock(peer);
19880 send_manager_peer_status(s, peer, idText);
19881 ao2_unlock(peer);
19882 sip_unref_peer(peer, "unref peer for SIPpeerstatus");
19883 }
19884 ao2_iterator_destroy(&i);
19885 } else {
19886 ao2_lock(peer);
19887 send_manager_peer_status(s, peer, idText);
19888 ao2_unlock(peer);
19889 sip_unref_peer(peer, "unref peer for SIPpeerstatus");
19890 }
19891
19892
19893 astman_append(s,
19894 "Event: SIPpeerstatusComplete\r\n"
19895 "%s"
19896 "\r\n",
19897 idText);
19898
19899 return 0;
19900 }
19901
19902
19903
19904 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
19905 {
19906 struct sip_peer *peer;
19907 int load_realtime;
19908
19909 if (argc < 4)
19910 return CLI_SHOWUSAGE;
19911
19912 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
19913 if ((peer = sip_find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0))) {
19914 sip_poke_peer(peer, 1);
19915 sip_unref_peer(peer, "qualify: done with peer");
19916 } else if (type == 0) {
19917 ast_cli(fd, "Peer '%s' not found\n", argv[3]);
19918 } else {
19919 astman_send_error(s, m, "Peer not found");
19920 }
19921 return CLI_SUCCESS;
19922 }
19923
19924
19925 static int manager_sip_qualify_peer(struct mansession *s, const struct message *m)
19926 {
19927 const char *a[4];
19928 const char *peer;
19929
19930 peer = astman_get_header(m, "Peer");
19931 if (ast_strlen_zero(peer)) {
19932 astman_send_error(s, m, "Peer: <name> missing.");
19933 return 0;
19934 }
19935 a[0] = "sip";
19936 a[1] = "qualify";
19937 a[2] = "peer";
19938 a[3] = peer;
19939
19940 _sip_qualify_peer(1, -1, s, m, 4, a);
19941 astman_append(s, "\r\n\r\n" );
19942 return 0;
19943 }
19944
19945
19946 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
19947 {
19948 switch (cmd) {
19949 case CLI_INIT:
19950 e->command = "sip qualify peer";
19951 e->usage =
19952 "Usage: sip qualify peer <name> [load]\n"
19953 " Requests a response from one SIP peer and the current status.\n"
19954 " Option \"load\" forces lookup of peer in realtime storage.\n";
19955 return NULL;
19956 case CLI_GENERATE:
19957 return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
19958 }
19959 return _sip_qualify_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
19960 }
19961
19962
19963 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer)
19964 {
19965 struct sip_mailbox *mailbox;
19966
19967 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
19968 ast_str_append(mailbox_str, 0, "%s%s%s%s",
19969 mailbox->mailbox,
19970 ast_strlen_zero(mailbox->context) ? "" : "@",
19971 S_OR(mailbox->context, ""),
19972 AST_LIST_NEXT(mailbox, entry) ? "," : "");
19973 }
19974 }
19975
19976 static struct _map_x_s faxecmodes[] = {
19977 { SIP_PAGE2_T38SUPPORT_UDPTL, "None"},
19978 { SIP_PAGE2_T38SUPPORT_UDPTL_FEC, "FEC"},
19979 { SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY, "Redundancy"},
19980 { -1, NULL},
19981 };
19982
19983 static const char *faxec2str(int faxec)
19984 {
19985 return map_x_s(faxecmodes, faxec, "Unknown");
19986 }
19987
19988
19989 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
19990 {
19991 char status[30] = "";
19992 char cbuf[256];
19993 struct sip_peer *peer;
19994 char codec_buf[512];
19995 struct ast_codec_pref *pref;
19996 struct ast_variable *v;
19997 int x = 0, load_realtime;
19998 struct ast_format codec;
19999 int realtimepeers;
20000
20001 realtimepeers = ast_check_realtime("sippeers");
20002
20003 if (argc < 4)
20004 return CLI_SHOWUSAGE;
20005
20006 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
20007 peer = sip_find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0);
20008
20009 if (s) {
20010 if (peer) {
20011 const char *id = astman_get_header(m, "ActionID");
20012
20013 astman_append(s, "Response: Success\r\n");
20014 if (!ast_strlen_zero(id))
20015 astman_append(s, "ActionID: %s\r\n", id);
20016 } else {
20017 snprintf (cbuf, sizeof(cbuf), "Peer %s not found.", argv[3]);
20018 astman_send_error(s, m, cbuf);
20019 return CLI_SUCCESS;
20020 }
20021 }
20022 if (peer && type==0 ) {
20023 struct ast_str *mailbox_str = ast_str_alloca(512);
20024 struct sip_auth_container *credentials;
20025
20026 ao2_lock(peer);
20027 credentials = peer->auth;
20028 if (credentials) {
20029 ao2_t_ref(credentials, +1, "Ref peer auth for show");
20030 }
20031 ao2_unlock(peer);
20032
20033 ast_cli(fd, "\n\n");
20034 ast_cli(fd, " * Name : %s\n", peer->name);
20035 ast_cli(fd, " Description : %s\n", peer->description);
20036 if (realtimepeers) {
20037 ast_cli(fd, " Realtime peer: %s\n", peer->is_realtime ? "Yes, cached" : "No");
20038 }
20039 ast_cli(fd, " Secret : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
20040 ast_cli(fd, " MD5Secret : %s\n", ast_strlen_zero(peer->md5secret)?"<Not set>":"<Set>");
20041 ast_cli(fd, " Remote Secret: %s\n", ast_strlen_zero(peer->remotesecret)?"<Not set>":"<Set>");
20042 if (credentials) {
20043 struct sip_auth *auth;
20044
20045 AST_LIST_TRAVERSE(&credentials->list, auth, node) {
20046 ast_cli(fd, " Realm-auth : Realm %-15.15s User %-10.20s %s\n",
20047 auth->realm,
20048 auth->username,
20049 !ast_strlen_zero(auth->secret)
20050 ? "<Secret set>"
20051 : (!ast_strlen_zero(auth->md5secret)
20052 ? "<MD5secret set>" : "<Not set>"));
20053 }
20054 ao2_t_ref(credentials, -1, "Unref peer auth for show");
20055 }
20056 ast_cli(fd, " Context : %s\n", peer->context);
20057 ast_cli(fd, " Record On feature : %s\n", peer->record_on_feature);
20058 ast_cli(fd, " Record Off feature : %s\n", peer->record_off_feature);
20059 ast_cli(fd, " Subscr.Cont. : %s\n", S_OR(peer->subscribecontext, "<Not set>") );
20060 ast_cli(fd, " Language : %s\n", peer->language);
20061 ast_cli(fd, " Tonezone : %s\n", peer->zone[0] != '\0' ? peer->zone : "<Not set>");
20062 if (!ast_strlen_zero(peer->accountcode))
20063 ast_cli(fd, " Accountcode : %s\n", peer->accountcode);
20064 ast_cli(fd, " AMA flags : %s\n", ast_cdr_flags2str(peer->amaflags));
20065 ast_cli(fd, " Transfer mode: %s\n", transfermode2str(peer->allowtransfer));
20066 ast_cli(fd, " CallingPres : %s\n", ast_describe_caller_presentation(peer->callingpres));
20067 if (!ast_strlen_zero(peer->fromuser))
20068 ast_cli(fd, " FromUser : %s\n", peer->fromuser);
20069 if (!ast_strlen_zero(peer->fromdomain))
20070 ast_cli(fd, " FromDomain : %s Port %d\n", peer->fromdomain, (peer->fromdomainport) ? peer->fromdomainport : STANDARD_SIP_PORT);
20071 ast_cli(fd, " Callgroup : ");
20072 print_group(fd, peer->callgroup, 0);
20073 ast_cli(fd, " Pickupgroup : ");
20074 print_group(fd, peer->pickupgroup, 0);
20075 ast_cli(fd, " Named Callgr : ");
20076 print_named_groups(fd, peer->named_callgroups, 0);
20077 ast_cli(fd, " Nam. Pickupgr: ");
20078 print_named_groups(fd, peer->named_pickupgroups, 0);
20079 peer_mailboxes_to_str(&mailbox_str, peer);
20080 ast_cli(fd, " MOH Suggest : %s\n", peer->mohsuggest);
20081 ast_cli(fd, " Mailbox : %s\n", ast_str_buffer(mailbox_str));
20082 ast_cli(fd, " VM Extension : %s\n", peer->vmexten);
20083 ast_cli(fd, " LastMsgsSent : %d/%d\n", (peer->lastmsgssent & 0x7fff0000) >> 16, peer->lastmsgssent & 0xffff);
20084 ast_cli(fd, " Call limit : %d\n", peer->call_limit);
20085 ast_cli(fd, " Max forwards : %d\n", peer->maxforwards);
20086 if (peer->busy_level)
20087 ast_cli(fd, " Busy level : %d\n", peer->busy_level);
20088 ast_cli(fd, " Dynamic : %s\n", AST_CLI_YESNO(peer->host_dynamic));
20089 ast_cli(fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
20090 ast_cli(fd, " MaxCallBR : %d kbps\n", peer->maxcallbitrate);
20091 ast_cli(fd, " Expire : %ld\n", ast_sched_when(sched, peer->expire));
20092 ast_cli(fd, " Insecure : %s\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
20093 ast_cli(fd, " Force rport : %s\n", force_rport_string(peer->flags));
20094 ast_cli(fd, " Symmetric RTP: %s\n", comedia_string(peer->flags));
20095 ast_cli(fd, " ACL : %s\n", AST_CLI_YESNO(ast_acl_list_is_empty(peer->acl) == 0));
20096 ast_cli(fd, " DirectMedACL : %s\n", AST_CLI_YESNO(ast_acl_list_is_empty(peer->directmediaacl) == 0));
20097 ast_cli(fd, " T.38 support : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
20098 ast_cli(fd, " T.38 EC mode : %s\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
20099 ast_cli(fd, " T.38 MaxDtgrm: %d\n", peer->t38_maxdatagram);
20100 ast_cli(fd, " DirectMedia : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)));
20101 ast_cli(fd, " PromiscRedir : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)));
20102 ast_cli(fd, " User=Phone : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)));
20103 ast_cli(fd, " Video Support: %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT) || ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS)));
20104 ast_cli(fd, " Text Support : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)));
20105 ast_cli(fd, " Ign SDP ver : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_IGNORESDPVERSION)));
20106 ast_cli(fd, " Trust RPID : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_TRUSTRPID)));
20107 ast_cli(fd, " Send RPID : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_SENDRPID)));
20108 ast_cli(fd, " TrustIDOutbnd: %s\n", trust_id_outbound2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND)));
20109 ast_cli(fd, " Subscriptions: %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
20110 ast_cli(fd, " Overlap dial : %s\n", allowoverlap2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWOVERLAP)));
20111 if (peer->outboundproxy)
20112 ast_cli(fd, " Outb. proxy : %s %s\n", ast_strlen_zero(peer->outboundproxy->name) ? "<not set>" : peer->outboundproxy->name,
20113 peer->outboundproxy->force ? "(forced)" : "");
20114
20115
20116 ast_cli(fd, " DTMFmode : %s\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
20117 ast_cli(fd, " Timer T1 : %d\n", peer->timer_t1);
20118 ast_cli(fd, " Timer B : %d\n", peer->timer_b);
20119 ast_cli(fd, " ToHost : %s\n", peer->tohost);
20120 ast_cli(fd, " Addr->IP : %s\n", ast_sockaddr_stringify(&peer->addr));
20121 ast_cli(fd, " Defaddr->IP : %s\n", ast_sockaddr_stringify(&peer->defaddr));
20122 ast_cli(fd, " Prim.Transp. : %s\n", sip_get_transport(peer->socket.type));
20123 ast_cli(fd, " Allowed.Trsp : %s\n", get_transport_list(peer->transports));
20124 if (!ast_strlen_zero(sip_cfg.regcontext))
20125 ast_cli(fd, " Reg. exten : %s\n", peer->regexten);
20126 ast_cli(fd, " Def. Username: %s\n", peer->username);
20127 ast_cli(fd, " SIP Options : ");
20128 if (peer->sipoptions) {
20129 int lastoption = -1;
20130 for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
20131 if (sip_options[x].id != lastoption) {
20132 if (peer->sipoptions & sip_options[x].id)
20133 ast_cli(fd, "%s ", sip_options[x].text);
20134 lastoption = x;
20135 }
20136 }
20137 } else
20138 ast_cli(fd, "(none)");
20139
20140 ast_cli(fd, "\n");
20141 ast_cli(fd, " Codecs : ");
20142 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->caps);
20143 ast_cli(fd, "%s\n", codec_buf);
20144 ast_cli(fd, " Codec Order : (");
20145 print_codec_to_cli(fd, &peer->prefs);
20146 ast_cli(fd, ")\n");
20147
20148 ast_cli(fd, " Auto-Framing : %s\n", AST_CLI_YESNO(peer->autoframing));
20149 ast_cli(fd, " Status : ");
20150 peer_status(peer, status, sizeof(status));
20151 ast_cli(fd, "%s\n", status);
20152 ast_cli(fd, " Useragent : %s\n", peer->useragent);
20153 ast_cli(fd, " Reg. Contact : %s\n", peer->fullcontact);
20154 ast_cli(fd, " Qualify Freq : %d ms\n", peer->qualifyfreq);
20155 ast_cli(fd, " Keepalive : %d ms\n", peer->keepalive * 1000);
20156 if (peer->chanvars) {
20157 ast_cli(fd, " Variables :\n");
20158 for (v = peer->chanvars ; v ; v = v->next)
20159 ast_cli(fd, " %s = %s\n", v->name, v->value);
20160 }
20161
20162 ast_cli(fd, " Sess-Timers : %s\n", stmode2str(peer->stimer.st_mode_oper));
20163 ast_cli(fd, " Sess-Refresh : %s\n", strefresherparam2str(peer->stimer.st_ref));
20164 ast_cli(fd, " Sess-Expires : %d secs\n", peer->stimer.st_max_se);
20165 ast_cli(fd, " Min-Sess : %d secs\n", peer->stimer.st_min_se);
20166 ast_cli(fd, " RTP Engine : %s\n", peer->engine);
20167 ast_cli(fd, " Parkinglot : %s\n", peer->parkinglot);
20168 ast_cli(fd, " Use Reason : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_Q850_REASON)));
20169 ast_cli(fd, " Encryption : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_USE_SRTP)));
20170 ast_cli(fd, "\n");
20171 peer = sip_unref_peer(peer, "sip_show_peer: sip_unref_peer: done with peer ptr");
20172 } else if (peer && type == 1) {
20173 char buffer[256];
20174 struct ast_str *tmp_str = ast_str_alloca(512);
20175 astman_append(s, "Channeltype: SIP\r\n");
20176 astman_append(s, "ObjectName: %s\r\n", peer->name);
20177 astman_append(s, "ChanObjectType: peer\r\n");
20178 astman_append(s, "SecretExist: %s\r\n", ast_strlen_zero(peer->secret)?"N":"Y");
20179 astman_append(s, "RemoteSecretExist: %s\r\n", ast_strlen_zero(peer->remotesecret)?"N":"Y");
20180 astman_append(s, "MD5SecretExist: %s\r\n", ast_strlen_zero(peer->md5secret)?"N":"Y");
20181 astman_append(s, "Context: %s\r\n", peer->context);
20182 astman_append(s, "Language: %s\r\n", peer->language);
20183 astman_append(s, "ToneZone: %s\r\n", peer->zone[0] != '\0' ? peer->zone : "<Not set>");
20184 if (!ast_strlen_zero(peer->accountcode))
20185 astman_append(s, "Accountcode: %s\r\n", peer->accountcode);
20186 astman_append(s, "AMAflags: %s\r\n", ast_cdr_flags2str(peer->amaflags));
20187 astman_append(s, "CID-CallingPres: %s\r\n", ast_describe_caller_presentation(peer->callingpres));
20188 if (!ast_strlen_zero(peer->fromuser))
20189 astman_append(s, "SIP-FromUser: %s\r\n", peer->fromuser);
20190 if (!ast_strlen_zero(peer->fromdomain))
20191 astman_append(s, "SIP-FromDomain: %s\r\nSip-FromDomain-Port: %d\r\n", peer->fromdomain, (peer->fromdomainport) ? peer->fromdomainport : STANDARD_SIP_PORT);
20192 astman_append(s, "Callgroup: ");
20193 astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->callgroup));
20194 astman_append(s, "Pickupgroup: ");
20195 astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->pickupgroup));
20196 astman_append(s, "Named Callgroup: ");
20197 astman_append(s, "%s\r\n", ast_print_namedgroups(&tmp_str, peer->named_callgroups));
20198 ast_str_reset(tmp_str);
20199 astman_append(s, "Named Pickupgroup: ");
20200 astman_append(s, "%s\r\n", ast_print_namedgroups(&tmp_str, peer->named_pickupgroups));
20201 ast_str_reset(tmp_str);
20202 astman_append(s, "MOHSuggest: %s\r\n", peer->mohsuggest);
20203 peer_mailboxes_to_str(&tmp_str, peer);
20204 astman_append(s, "VoiceMailbox: %s\r\n", ast_str_buffer(tmp_str));
20205 astman_append(s, "TransferMode: %s\r\n", transfermode2str(peer->allowtransfer));
20206 astman_append(s, "LastMsgsSent: %d\r\n", peer->lastmsgssent);
20207 astman_append(s, "Maxforwards: %d\r\n", peer->maxforwards);
20208 astman_append(s, "Call-limit: %d\r\n", peer->call_limit);
20209 astman_append(s, "Busy-level: %d\r\n", peer->busy_level);
20210 astman_append(s, "MaxCallBR: %d kbps\r\n", peer->maxcallbitrate);
20211 astman_append(s, "Dynamic: %s\r\n", peer->host_dynamic?"Y":"N");
20212 astman_append(s, "Callerid: %s\r\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, ""));
20213 astman_append(s, "RegExpire: %ld seconds\r\n", ast_sched_when(sched, peer->expire));
20214 astman_append(s, "SIP-AuthInsecure: %s\r\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
20215 astman_append(s, "SIP-Forcerport: %s\r\n", ast_test_flag(&peer->flags[2], SIP_PAGE3_NAT_AUTO_RPORT) ?
20216 (ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) ? "A" : "a") :
20217 (ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) ? "Y" : "N"));
20218 astman_append(s, "SIP-Comedia: %s\r\n", ast_test_flag(&peer->flags[2], SIP_PAGE3_NAT_AUTO_COMEDIA) ?
20219 (ast_test_flag(&peer->flags[1], SIP_PAGE2_SYMMETRICRTP) ? "A" : "a") :
20220 (ast_test_flag(&peer->flags[1], SIP_PAGE2_SYMMETRICRTP) ? "Y" : "N"));
20221 astman_append(s, "ACL: %s\r\n", (ast_acl_list_is_empty(peer->acl) ? "N" : "Y"));
20222 astman_append(s, "SIP-CanReinvite: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)?"Y":"N"));
20223 astman_append(s, "SIP-DirectMedia: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)?"Y":"N"));
20224 astman_append(s, "SIP-PromiscRedir: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)?"Y":"N"));
20225 astman_append(s, "SIP-UserPhone: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)?"Y":"N"));
20226 astman_append(s, "SIP-VideoSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)?"Y":"N"));
20227 astman_append(s, "SIP-TextSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)?"Y":"N"));
20228 astman_append(s, "SIP-T.38Support: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)?"Y":"N"));
20229 astman_append(s, "SIP-T.38EC: %s\r\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
20230 astman_append(s, "SIP-T.38MaxDtgrm: %d\r\n", peer->t38_maxdatagram);
20231 astman_append(s, "SIP-Sess-Timers: %s\r\n", stmode2str(peer->stimer.st_mode_oper));
20232 astman_append(s, "SIP-Sess-Refresh: %s\r\n", strefresherparam2str(peer->stimer.st_ref));
20233 astman_append(s, "SIP-Sess-Expires: %d\r\n", peer->stimer.st_max_se);
20234 astman_append(s, "SIP-Sess-Min: %d\r\n", peer->stimer.st_min_se);
20235 astman_append(s, "SIP-RTP-Engine: %s\r\n", peer->engine);
20236 astman_append(s, "SIP-Encryption: %s\r\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_USE_SRTP) ? "Y" : "N");
20237
20238
20239 astman_append(s, "SIP-DTMFmode: %s\r\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
20240 astman_append(s, "ToHost: %s\r\n", peer->tohost);
20241 astman_append(s, "Address-IP: %s\r\nAddress-Port: %d\r\n", ast_sockaddr_stringify_addr(&peer->addr), ast_sockaddr_port(&peer->addr));
20242 astman_append(s, "Default-addr-IP: %s\r\nDefault-addr-port: %d\r\n", ast_sockaddr_stringify_addr(&peer->defaddr), ast_sockaddr_port(&peer->defaddr));
20243 astman_append(s, "Default-Username: %s\r\n", peer->username);
20244 if (!ast_strlen_zero(sip_cfg.regcontext))
20245 astman_append(s, "RegExtension: %s\r\n", peer->regexten);
20246 astman_append(s, "Codecs: ");
20247 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->caps);
20248 astman_append(s, "%s\r\n", codec_buf);
20249 astman_append(s, "CodecOrder: ");
20250 pref = &peer->prefs;
20251 for(x = 0; x < AST_CODEC_PREF_SIZE ; x++) {
20252 if (!(ast_codec_pref_index(pref, x, &codec))) {
20253 break;
20254 }
20255 astman_append(s, "%s", ast_getformatname(&codec));
20256 if ((x < (AST_CODEC_PREF_SIZE - 1)) && ast_codec_pref_index(pref, x+1, &codec))
20257 astman_append(s, ",");
20258 }
20259
20260 astman_append(s, "\r\n");
20261 astman_append(s, "Status: ");
20262 peer_status(peer, status, sizeof(status));
20263 astman_append(s, "%s\r\n", status);
20264 astman_append(s, "SIP-Useragent: %s\r\n", peer->useragent);
20265 astman_append(s, "Reg-Contact: %s\r\n", peer->fullcontact);
20266 astman_append(s, "QualifyFreq: %d ms\r\n", peer->qualifyfreq);
20267 astman_append(s, "Parkinglot: %s\r\n", peer->parkinglot);
20268 if (peer->chanvars) {
20269 for (v = peer->chanvars ; v ; v = v->next) {
20270 astman_append(s, "ChanVariable: %s=%s\r\n", v->name, v->value);
20271 }
20272 }
20273 astman_append(s, "SIP-Use-Reason-Header: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_Q850_REASON)) ? "Y" : "N");
20274 astman_append(s, "Description: %s\r\n", peer->description);
20275
20276 peer = sip_unref_peer(peer, "sip_show_peer: sip_unref_peer: done with peer");
20277
20278 } else {
20279 ast_cli(fd, "Peer %s not found.\n", argv[3]);
20280 ast_cli(fd, "\n");
20281 }
20282
20283 return CLI_SUCCESS;
20284 }
20285
20286
20287 static char *complete_sip_user(const char *word, int state)
20288 {
20289 char *result = NULL;
20290 int wordlen = strlen(word);
20291 int which = 0;
20292 struct ao2_iterator user_iter;
20293 struct sip_peer *user;
20294
20295 user_iter = ao2_iterator_init(peers, 0);
20296 while ((user = ao2_t_iterator_next(&user_iter, "iterate thru peers table"))) {
20297 ao2_lock(user);
20298 if (!(user->type & SIP_TYPE_USER)) {
20299 ao2_unlock(user);
20300 sip_unref_peer(user, "complete sip user");
20301 continue;
20302 }
20303
20304 if (!strncasecmp(word, user->name, wordlen) && ++which > state) {
20305 result = ast_strdup(user->name);
20306 }
20307 ao2_unlock(user);
20308 sip_unref_peer(user, "complete sip user");
20309 if (result) {
20310 break;
20311 }
20312 }
20313 ao2_iterator_destroy(&user_iter);
20314 return result;
20315 }
20316
20317 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state)
20318 {
20319 if (pos == 3)
20320 return complete_sip_user(word, state);
20321
20322 return NULL;
20323 }
20324
20325
20326 static char *sip_show_user(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
20327 {
20328 char cbuf[256];
20329 struct sip_peer *user;
20330 struct ast_variable *v;
20331 int load_realtime;
20332
20333 switch (cmd) {
20334 case CLI_INIT:
20335 e->command = "sip show user";
20336 e->usage =
20337 "Usage: sip show user <name> [load]\n"
20338 " Shows all details on one SIP user and the current status.\n"
20339 " Option \"load\" forces lookup of peer in realtime storage.\n";
20340 return NULL;
20341 case CLI_GENERATE:
20342 return complete_sip_show_user(a->line, a->word, a->pos, a->n);
20343 }
20344
20345 if (a->argc < 4)
20346 return CLI_SHOWUSAGE;
20347
20348
20349 load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? TRUE : FALSE;
20350
20351 if ((user = sip_find_peer(a->argv[3], NULL, load_realtime, FINDUSERS, FALSE, 0))) {
20352 ao2_lock(user);
20353 ast_cli(a->fd, "\n\n");
20354 ast_cli(a->fd, " * Name : %s\n", user->name);
20355 ast_cli(a->fd, " Secret : %s\n", ast_strlen_zero(user->secret)?"<Not set>":"<Set>");
20356 ast_cli(a->fd, " MD5Secret : %s\n", ast_strlen_zero(user->md5secret)?"<Not set>":"<Set>");
20357 ast_cli(a->fd, " Context : %s\n", user->context);
20358 ast_cli(a->fd, " Language : %s\n", user->language);
20359 if (!ast_strlen_zero(user->accountcode))
20360 ast_cli(a->fd, " Accountcode : %s\n", user->accountcode);
20361 ast_cli(a->fd, " AMA flags : %s\n", ast_cdr_flags2str(user->amaflags));
20362 ast_cli(a->fd, " Tonezone : %s\n", user->zone[0] != '\0' ? user->zone : "<Not set>");
20363 ast_cli(a->fd, " Transfer mode: %s\n", transfermode2str(user->allowtransfer));
20364 ast_cli(a->fd, " MaxCallBR : %d kbps\n", user->maxcallbitrate);
20365 ast_cli(a->fd, " CallingPres : %s\n", ast_describe_caller_presentation(user->callingpres));
20366 ast_cli(a->fd, " Call limit : %d\n", user->call_limit);
20367 ast_cli(a->fd, " Callgroup : ");
20368 print_group(a->fd, user->callgroup, 0);
20369 ast_cli(a->fd, " Pickupgroup : ");
20370 print_group(a->fd, user->pickupgroup, 0);
20371 ast_cli(a->fd, " Named Callgr : ");
20372 print_named_groups(a->fd, user->named_callgroups, 0);
20373 ast_cli(a->fd, " Nam. Pickupgr: ");
20374 print_named_groups(a->fd, user->named_pickupgroups, 0);
20375 ast_cli(a->fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), user->cid_name, user->cid_num, "<unspecified>"));
20376 ast_cli(a->fd, " ACL : %s\n", AST_CLI_YESNO(ast_acl_list_is_empty(user->acl) == 0));
20377 ast_cli(a->fd, " Sess-Timers : %s\n", stmode2str(user->stimer.st_mode_oper));
20378 ast_cli(a->fd, " Sess-Refresh : %s\n", strefresherparam2str(user->stimer.st_ref));
20379 ast_cli(a->fd, " Sess-Expires : %d secs\n", user->stimer.st_max_se);
20380 ast_cli(a->fd, " Sess-Min-SE : %d secs\n", user->stimer.st_min_se);
20381 ast_cli(a->fd, " RTP Engine : %s\n", user->engine);
20382
20383 ast_cli(a->fd, " Codec Order : (");
20384 print_codec_to_cli(a->fd, &user->prefs);
20385 ast_cli(a->fd, ")\n");
20386
20387 ast_cli(a->fd, " Auto-Framing: %s \n", AST_CLI_YESNO(user->autoframing));
20388 if (user->chanvars) {
20389 ast_cli(a->fd, " Variables :\n");
20390 for (v = user->chanvars ; v ; v = v->next)
20391 ast_cli(a->fd, " %s = %s\n", v->name, v->value);
20392 }
20393
20394 ast_cli(a->fd, "\n");
20395
20396 ao2_unlock(user);
20397 sip_unref_peer(user, "sip show user");
20398 } else {
20399 ast_cli(a->fd, "User %s not found.\n", a->argv[3]);
20400 ast_cli(a->fd, "\n");
20401 }
20402
20403 return CLI_SUCCESS;
20404 }
20405
20406
20407 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
20408 {
20409 struct ast_str *cbuf;
20410 struct ast_cb_names cbnames = {9, { "retrans_pkt",
20411 "__sip_autodestruct",
20412 "expire_register",
20413 "auto_congest",
20414 "sip_reg_timeout",
20415 "sip_poke_peer_s",
20416 "sip_poke_noanswer",
20417 "sip_reregister",
20418 "sip_reinvite_retry"},
20419 { retrans_pkt,
20420 __sip_autodestruct,
20421 expire_register,
20422 auto_congest,
20423 sip_reg_timeout,
20424 sip_poke_peer_s,
20425 sip_poke_noanswer,
20426 sip_reregister,
20427 sip_reinvite_retry}};
20428
20429 switch (cmd) {
20430 case CLI_INIT:
20431 e->command = "sip show sched";
20432 e->usage =
20433 "Usage: sip show sched\n"
20434 " Shows stats on what's in the sched queue at the moment\n";
20435 return NULL;
20436 case CLI_GENERATE:
20437 return NULL;
20438 }
20439
20440 cbuf = ast_str_alloca(2048);
20441
20442 ast_cli(a->fd, "\n");
20443 ast_sched_report(sched, &cbuf, &cbnames);
20444 ast_cli(a->fd, "%s", ast_str_buffer(cbuf));
20445
20446 return CLI_SUCCESS;
20447 }
20448
20449
20450 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
20451 {
20452 #define FORMAT2 "%-39.39s %-6.6s %-12.12s %8.8s %-20.20s %-25.25s\n"
20453 #define FORMAT "%-39.39s %-6.6s %-12.12s %8d %-20.20s %-25.25s\n"
20454 char host[80];
20455 char user[80];
20456 char tmpdat[256];
20457 struct ast_tm tm;
20458 int counter = 0;
20459
20460 switch (cmd) {
20461 case CLI_INIT:
20462 e->command = "sip show registry";
20463 e->usage =
20464 "Usage: sip show registry\n"
20465 " Lists all registration requests and status.\n";
20466 return NULL;
20467 case CLI_GENERATE:
20468 return NULL;
20469 }
20470
20471 if (a->argc != 3)
20472 return CLI_SHOWUSAGE;
20473 ast_cli(a->fd, FORMAT2, "Host", "dnsmgr", "Username", "Refresh", "State", "Reg.Time");
20474
20475 ASTOBJ_CONTAINER_TRAVERSE(®l, 1, do {
20476 ASTOBJ_RDLOCK(iterator);
20477 snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
20478 snprintf(user, sizeof(user), "%s", iterator->username);
20479 if (!ast_strlen_zero(iterator->regdomain)) {
20480 snprintf(tmpdat, sizeof(tmpdat), "%s", user);
20481 snprintf(user, sizeof(user), "%s@%s", tmpdat, iterator->regdomain);}
20482 if (iterator->regdomainport) {
20483 snprintf(tmpdat, sizeof(tmpdat), "%s", user);
20484 snprintf(user, sizeof(user), "%s:%d", tmpdat, iterator->regdomainport);}
20485 if (iterator->regtime.tv_sec) {
20486 ast_localtime(&iterator->regtime, &tm, NULL);
20487 ast_strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T", &tm);
20488 } else
20489 tmpdat[0] = '\0';
20490 ast_cli(a->fd, FORMAT, host, (iterator->dnsmgr) ? "Y" : "N", user, iterator->refresh, regstate2str(iterator->regstate), tmpdat);
20491 ASTOBJ_UNLOCK(iterator);
20492 counter++;
20493 } while(0));
20494 ast_cli(a->fd, "%d SIP registrations.\n", counter);
20495 return CLI_SUCCESS;
20496 #undef FORMAT
20497 #undef FORMAT2
20498 }
20499
20500
20501
20502
20503
20504 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
20505 {
20506 struct sip_peer *peer;
20507 int load_realtime = 0;
20508
20509 switch (cmd) {
20510 case CLI_INIT:
20511 e->command = "sip unregister";
20512 e->usage =
20513 "Usage: sip unregister <peer>\n"
20514 " Unregister (force expiration) a SIP peer from the registry\n";
20515 return NULL;
20516 case CLI_GENERATE:
20517 return complete_sip_unregister(a->line, a->word, a->pos, a->n);
20518 }
20519
20520 if (a->argc != 3)
20521 return CLI_SHOWUSAGE;
20522
20523 if ((peer = sip_find_peer(a->argv[2], NULL, load_realtime, FINDPEERS, TRUE, 0))) {
20524 if (peer->expire > 0) {
20525 AST_SCHED_DEL_UNREF(sched, peer->expire,
20526 sip_unref_peer(peer, "remove register expire ref"));
20527 expire_register(sip_ref_peer(peer, "ref for expire_register"));
20528 ast_cli(a->fd, "Unregistered peer \'%s\'\n\n", a->argv[2]);
20529 } else {
20530 ast_cli(a->fd, "Peer %s not registered\n", a->argv[2]);
20531 }
20532 sip_unref_peer(peer, "sip_unregister: sip_unref_peer via sip_unregister: done with peer from sip_find_peer call");
20533 } else {
20534 ast_cli(a->fd, "Peer unknown: \'%s\'. Not unregistered.\n", a->argv[2]);
20535 }
20536
20537 return CLI_SUCCESS;
20538 }
20539
20540
20541 static int show_chanstats_cb(void *__cur, void *__arg, int flags)
20542 {
20543 #define FORMAT2 "%-15.15s %-11.11s %-8.8s %-10.10s %-10.10s ( %%) %-6.6s %-10.10s %-10.10s ( %%) %-6.6s\n"
20544 #define FORMAT "%-15.15s %-11.11s %-8.8s %-10.10u%-1.1s %-10.10u (%5.2f%%) %-6.4lf %-10.10u%-1.1s %-10.10u (%5.2f%%) %-6.4lf\n"
20545 struct sip_pvt *cur = __cur;
20546 struct ast_rtp_instance_stats stats;
20547 char durbuf[10];
20548 int duration;
20549 int durh, durm, durs;
20550 struct ast_channel *c;
20551 struct __show_chan_arg *arg = __arg;
20552 int fd = arg->fd;
20553
20554 sip_pvt_lock(cur);
20555 c = cur->owner;
20556
20557 if (cur->subscribed != NONE) {
20558
20559 sip_pvt_unlock(cur);
20560 return 0;
20561 }
20562
20563 if (!cur->rtp) {
20564 if (sipdebug) {
20565 ast_cli(fd, "%-15.15s %-11.11s (inv state: %s) -- %s\n",
20566 ast_sockaddr_stringify_addr(&cur->sa), cur->callid,
20567 invitestate2string[cur->invitestate].desc,
20568 "-- No RTP active");
20569 }
20570 sip_pvt_unlock(cur);
20571 return 0;
20572 }
20573
20574 if (ast_rtp_instance_get_stats(cur->rtp, &stats, AST_RTP_INSTANCE_STAT_ALL)) {
20575 sip_pvt_unlock(cur);
20576 ast_log(LOG_WARNING, "Could not get RTP stats.\n");
20577 return 0;
20578 }
20579
20580 if (c && ast_channel_cdr(c) && !ast_tvzero(ast_channel_cdr(c)->start)) {
20581 duration = (int)(ast_tvdiff_ms(ast_tvnow(), ast_channel_cdr(c)->start) / 1000);
20582 durh = duration / 3600;
20583 durm = (duration % 3600) / 60;
20584 durs = duration % 60;
20585 snprintf(durbuf, sizeof(durbuf), "%02d:%02d:%02d", durh, durm, durs);
20586 } else {
20587 durbuf[0] = '\0';
20588 }
20589
20590 ast_cli(fd, FORMAT,
20591 ast_sockaddr_stringify_addr(&cur->sa),
20592 cur->callid,
20593 durbuf,
20594 stats.rxcount > (unsigned int) 100000 ? (unsigned int) (stats.rxcount)/(unsigned int) 1000 : stats.rxcount,
20595 stats.rxcount > (unsigned int) 100000 ? "K":" ",
20596 stats.rxploss,
20597 (stats.rxcount + stats.rxploss) > 0 ? (double) stats.rxploss / (stats.rxcount + stats.rxploss) * 100 : 0,
20598 stats.rxjitter,
20599 stats.txcount > (unsigned int) 100000 ? (unsigned int) (stats.txcount)/(unsigned int) 1000 : stats.txcount,
20600 stats.txcount > (unsigned int) 100000 ? "K":" ",
20601 stats.txploss,
20602 stats.txcount > 0 ? (double) stats.txploss / stats.txcount * 100 : 0,
20603 stats.txjitter
20604 );
20605 arg->numchans++;
20606 sip_pvt_unlock(cur);
20607
20608 return 0;
20609 }
20610
20611
20612 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
20613 {
20614 struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
20615
20616 switch (cmd) {
20617 case CLI_INIT:
20618 e->command = "sip show channelstats";
20619 e->usage =
20620 "Usage: sip show channelstats\n"
20621 " Lists all currently active SIP channel's RTCP statistics.\n"
20622 " Note that calls in the much optimized RTP P2P bridge mode will not show any packets here.";
20623 return NULL;
20624 case CLI_GENERATE:
20625 return NULL;
20626 }
20627
20628 if (a->argc != 3)
20629 return CLI_SHOWUSAGE;
20630
20631 ast_cli(a->fd, FORMAT2, "Peer", "Call ID", "Duration", "Recv: Pack", "Lost", "Jitter", "Send: Pack", "Lost", "Jitter");
20632
20633 ao2_t_callback(dialogs, OBJ_NODATA, show_chanstats_cb, &arg, "callback to sip show chanstats");
20634 ast_cli(a->fd, "%d active SIP channel%s\n", arg.numchans, (arg.numchans != 1) ? "s" : "");
20635 return CLI_SUCCESS;
20636 }
20637 #undef FORMAT
20638 #undef FORMAT2
20639
20640
20641 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
20642 {
20643 int realtimepeers;
20644 int realtimeregs;
20645 char codec_buf[SIPBUFSIZE];
20646 const char *msg;
20647 struct sip_auth_container *credentials;
20648
20649 switch (cmd) {
20650 case CLI_INIT:
20651 e->command = "sip show settings";
20652 e->usage =
20653 "Usage: sip show settings\n"
20654 " Provides detailed list of the configuration of the SIP channel.\n";
20655 return NULL;
20656 case CLI_GENERATE:
20657 return NULL;
20658 }
20659
20660 if (a->argc != 3)
20661 return CLI_SHOWUSAGE;
20662
20663 realtimepeers = ast_check_realtime("sippeers");
20664 realtimeregs = ast_check_realtime("sipregs");
20665
20666 ast_mutex_lock(&authl_lock);
20667 credentials = authl;
20668 if (credentials) {
20669 ao2_t_ref(credentials, +1, "Ref global auth for show");
20670 }
20671 ast_mutex_unlock(&authl_lock);
20672
20673 ast_cli(a->fd, "\n\nGlobal Settings:\n");
20674 ast_cli(a->fd, "----------------\n");
20675 ast_cli(a->fd, " UDP Bindaddress: %s\n", ast_sockaddr_stringify(&bindaddr));
20676 if (ast_sockaddr_is_ipv6(&bindaddr) && ast_sockaddr_is_any(&bindaddr)) {
20677 ast_cli(a->fd, " ** Additional Info:\n");
20678 ast_cli(a->fd, " [::] may include IPv4 in addition to IPv6, if such a feature is enabled in the OS.\n");
20679 }
20680 ast_cli(a->fd, " TCP SIP Bindaddress: %s\n",
20681 sip_cfg.tcp_enabled != FALSE ?
20682 ast_sockaddr_stringify(&sip_tcp_desc.local_address) :
20683 "Disabled");
20684 ast_cli(a->fd, " TLS SIP Bindaddress: %s\n",
20685 default_tls_cfg.enabled != FALSE ?
20686 ast_sockaddr_stringify(&sip_tls_desc.local_address) :
20687 "Disabled");
20688 ast_cli(a->fd, " Videosupport: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT)));
20689 ast_cli(a->fd, " Textsupport: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT)));
20690 ast_cli(a->fd, " Ignore SDP sess. ver.: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION)));
20691 ast_cli(a->fd, " AutoCreate Peer: %s\n", autocreatepeer2str(sip_cfg.autocreatepeer));
20692 ast_cli(a->fd, " Match Auth Username: %s\n", AST_CLI_YESNO(global_match_auth_username));
20693 ast_cli(a->fd, " Allow unknown access: %s\n", AST_CLI_YESNO(sip_cfg.allowguest));
20694 ast_cli(a->fd, " Allow subscriptions: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
20695 ast_cli(a->fd, " Allow overlap dialing: %s\n", allowoverlap2str(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP)));
20696 ast_cli(a->fd, " Allow promisc. redir: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_PROMISCREDIR)));
20697 ast_cli(a->fd, " Enable call counters: %s\n", AST_CLI_YESNO(global_callcounter));
20698 ast_cli(a->fd, " SIP domain support: %s\n", AST_CLI_YESNO(!AST_LIST_EMPTY(&domain_list)));
20699 ast_cli(a->fd, " Realm. auth: %s\n", AST_CLI_YESNO(credentials != NULL));
20700 if (credentials) {
20701 struct sip_auth *auth;
20702
20703 AST_LIST_TRAVERSE(&credentials->list, auth, node) {
20704 ast_cli(a->fd, " Realm. auth entry: Realm %-15.15s User %-10.20s %s\n",
20705 auth->realm,
20706 auth->username,
20707 !ast_strlen_zero(auth->secret)
20708 ? "<Secret set>"
20709 : (!ast_strlen_zero(auth->md5secret)
20710 ? "<MD5secret set>" : "<Not set>"));
20711 }
20712 ao2_t_ref(credentials, -1, "Unref global auth for show");
20713 }
20714 ast_cli(a->fd, " Our auth realm %s\n", sip_cfg.realm);
20715 ast_cli(a->fd, " Use domains as realms: %s\n", AST_CLI_YESNO(sip_cfg.domainsasrealm));
20716 ast_cli(a->fd, " Call to non-local dom.: %s\n", AST_CLI_YESNO(sip_cfg.allow_external_domains));
20717 ast_cli(a->fd, " URI user is phone no: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_USEREQPHONE)));
20718 ast_cli(a->fd, " Always auth rejects: %s\n", AST_CLI_YESNO(sip_cfg.alwaysauthreject));
20719 ast_cli(a->fd, " Direct RTP setup: %s\n", AST_CLI_YESNO(sip_cfg.directrtpsetup));
20720 ast_cli(a->fd, " User Agent: %s\n", global_useragent);
20721 ast_cli(a->fd, " SDP Session Name: %s\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
20722 ast_cli(a->fd, " SDP Owner Name: %s\n", ast_strlen_zero(global_sdpowner) ? "-" : global_sdpowner);
20723 ast_cli(a->fd, " Reg. context: %s\n", S_OR(sip_cfg.regcontext, "(not set)"));
20724 ast_cli(a->fd, " Regexten on Qualify: %s\n", AST_CLI_YESNO(sip_cfg.regextenonqualify));
20725 ast_cli(a->fd, " Trust RPID: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_TRUSTRPID)));
20726 ast_cli(a->fd, " Send RPID: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_SENDRPID)));
20727 ast_cli(a->fd, " Legacy userfield parse: %s\n", AST_CLI_YESNO(sip_cfg.legacy_useroption_parsing));
20728 ast_cli(a->fd, " Send Diversion: %s\n", AST_CLI_YESNO(sip_cfg.send_diversion));
20729 ast_cli(a->fd, " Caller ID: %s\n", default_callerid);
20730 if ((default_fromdomainport) && (default_fromdomainport != STANDARD_SIP_PORT)) {
20731 ast_cli(a->fd, " From: Domain: %s:%d\n", default_fromdomain, default_fromdomainport);
20732 } else {
20733 ast_cli(a->fd, " From: Domain: %s\n", default_fromdomain);
20734 }
20735 ast_cli(a->fd, " Record SIP history: %s\n", AST_CLI_ONOFF(recordhistory));
20736 ast_cli(a->fd, " Call Events: %s\n", AST_CLI_ONOFF(sip_cfg.callevents));
20737 ast_cli(a->fd, " Auth. Failure Events: %s\n", AST_CLI_ONOFF(global_authfailureevents));
20738
20739 ast_cli(a->fd, " T.38 support: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
20740 ast_cli(a->fd, " T.38 EC mode: %s\n", faxec2str(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
20741 ast_cli(a->fd, " T.38 MaxDtgrm: %d\n", global_t38_maxdatagram);
20742 if (!realtimepeers && !realtimeregs)
20743 ast_cli(a->fd, " SIP realtime: Disabled\n" );
20744 else
20745 ast_cli(a->fd, " SIP realtime: Enabled\n" );
20746 ast_cli(a->fd, " Qualify Freq : %d ms\n", global_qualifyfreq);
20747 ast_cli(a->fd, " Q.850 Reason header: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_Q850_REASON)));
20748 ast_cli(a->fd, " Store SIP_CAUSE: %s\n", AST_CLI_YESNO(global_store_sip_cause));
20749 ast_cli(a->fd, "\nNetwork QoS Settings:\n");
20750 ast_cli(a->fd, "---------------------------\n");
20751 ast_cli(a->fd, " IP ToS SIP: %s\n", ast_tos2str(global_tos_sip));
20752 ast_cli(a->fd, " IP ToS RTP audio: %s\n", ast_tos2str(global_tos_audio));
20753 ast_cli(a->fd, " IP ToS RTP video: %s\n", ast_tos2str(global_tos_video));
20754 ast_cli(a->fd, " IP ToS RTP text: %s\n", ast_tos2str(global_tos_text));
20755 ast_cli(a->fd, " 802.1p CoS SIP: %d\n", global_cos_sip);
20756 ast_cli(a->fd, " 802.1p CoS RTP audio: %d\n", global_cos_audio);
20757 ast_cli(a->fd, " 802.1p CoS RTP video: %d\n", global_cos_video);
20758 ast_cli(a->fd, " 802.1p CoS RTP text: %d\n", global_cos_text);
20759 ast_cli(a->fd, " Jitterbuffer enabled: %s\n", AST_CLI_YESNO(ast_test_flag(&global_jbconf, AST_JB_ENABLED)));
20760 if (ast_test_flag(&global_jbconf, AST_JB_ENABLED)) {
20761 ast_cli(a->fd, " Jitterbuffer forced: %s\n", AST_CLI_YESNO(ast_test_flag(&global_jbconf, AST_JB_FORCED)));
20762 ast_cli(a->fd, " Jitterbuffer max size: %ld\n", global_jbconf.max_size);
20763 ast_cli(a->fd, " Jitterbuffer resync: %ld\n", global_jbconf.resync_threshold);
20764 ast_cli(a->fd, " Jitterbuffer impl: %s\n", global_jbconf.impl);
20765 if (!strcasecmp(global_jbconf.impl, "adaptive")) {
20766 ast_cli(a->fd, " Jitterbuffer tgt extra: %ld\n", global_jbconf.target_extra);
20767 }
20768 ast_cli(a->fd, " Jitterbuffer log: %s\n", AST_CLI_YESNO(ast_test_flag(&global_jbconf, AST_JB_LOG)));
20769 }
20770
20771 ast_cli(a->fd, "\nNetwork Settings:\n");
20772 ast_cli(a->fd, "---------------------------\n");
20773
20774 if (localaddr == NULL)
20775 msg = "Disabled, no localnet list";
20776 else if (ast_sockaddr_isnull(&externaddr))
20777 msg = "Disabled";
20778 else if (!ast_strlen_zero(externhost))
20779 msg = "Enabled using externhost";
20780 else
20781 msg = "Enabled using externaddr";
20782 ast_cli(a->fd, " SIP address remapping: %s\n", msg);
20783 ast_cli(a->fd, " Externhost: %s\n", S_OR(externhost, "<none>"));
20784 ast_cli(a->fd, " Externaddr: %s\n", ast_sockaddr_stringify(&externaddr));
20785 ast_cli(a->fd, " Externrefresh: %d\n", externrefresh);
20786 {
20787 struct ast_ha *d;
20788 const char *prefix = "Localnet:";
20789
20790 for (d = localaddr; d ; prefix = "", d = d->next) {
20791 const char *addr = ast_strdupa(ast_sockaddr_stringify_addr(&d->addr));
20792 const char *mask = ast_strdupa(ast_sockaddr_stringify_addr(&d->netmask));
20793 ast_cli(a->fd, " %-24s%s/%s\n", prefix, addr, mask);
20794 }
20795 }
20796 ast_cli(a->fd, "\nGlobal Signalling Settings:\n");
20797 ast_cli(a->fd, "---------------------------\n");
20798 ast_cli(a->fd, " Codecs: ");
20799 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, sip_cfg.caps);
20800 ast_cli(a->fd, "%s\n", codec_buf);
20801 ast_cli(a->fd, " Codec Order: ");
20802 print_codec_to_cli(a->fd, &default_prefs);
20803 ast_cli(a->fd, "\n");
20804 ast_cli(a->fd, " Relax DTMF: %s\n", AST_CLI_YESNO(global_relaxdtmf));
20805 ast_cli(a->fd, " RFC2833 Compensation: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_RFC2833_COMPENSATE)));
20806 ast_cli(a->fd, " Symmetric RTP: %s\n", comedia_string(global_flags));
20807 ast_cli(a->fd, " Compact SIP headers: %s\n", AST_CLI_YESNO(sip_cfg.compactheaders));
20808 ast_cli(a->fd, " RTP Keepalive: %d %s\n", global_rtpkeepalive, global_rtpkeepalive ? "" : "(Disabled)" );
20809 ast_cli(a->fd, " RTP Timeout: %d %s\n", global_rtptimeout, global_rtptimeout ? "" : "(Disabled)" );
20810 ast_cli(a->fd, " RTP Hold Timeout: %d %s\n", global_rtpholdtimeout, global_rtpholdtimeout ? "" : "(Disabled)");
20811 ast_cli(a->fd, " MWI NOTIFY mime type: %s\n", default_notifymime);
20812 ast_cli(a->fd, " DNS SRV lookup: %s\n", AST_CLI_YESNO(sip_cfg.srvlookup));
20813 ast_cli(a->fd, " Pedantic SIP support: %s\n", AST_CLI_YESNO(sip_cfg.pedanticsipchecking));
20814 ast_cli(a->fd, " Reg. min duration %d secs\n", min_expiry);
20815 ast_cli(a->fd, " Reg. max duration: %d secs\n", max_expiry);
20816 ast_cli(a->fd, " Reg. default duration: %d secs\n", default_expiry);
20817 ast_cli(a->fd, " Sub. min duration %d secs\n", min_subexpiry);
20818 ast_cli(a->fd, " Sub. max duration: %d secs\n", max_subexpiry);
20819 ast_cli(a->fd, " Outbound reg. timeout: %d secs\n", global_reg_timeout);
20820 ast_cli(a->fd, " Outbound reg. attempts: %d\n", global_regattempts_max);
20821 ast_cli(a->fd, " Outbound reg. retry 403:%d\n", global_reg_retry_403);
20822 ast_cli(a->fd, " Notify ringing state: %s\n", AST_CLI_YESNO(sip_cfg.notifyringing));
20823 if (sip_cfg.notifyringing) {
20824 ast_cli(a->fd, " Include CID: %s%s\n",
20825 AST_CLI_YESNO(sip_cfg.notifycid),
20826 sip_cfg.notifycid == IGNORE_CONTEXT ? " (Ignoring context)" : "");
20827 }
20828 ast_cli(a->fd, " Notify hold state: %s\n", AST_CLI_YESNO(sip_cfg.notifyhold));
20829 ast_cli(a->fd, " SIP Transfer mode: %s\n", transfermode2str(sip_cfg.allowtransfer));
20830 ast_cli(a->fd, " Max Call Bitrate: %d kbps\n", default_maxcallbitrate);
20831 ast_cli(a->fd, " Auto-Framing: %s\n", AST_CLI_YESNO(global_autoframing));
20832 ast_cli(a->fd, " Outb. proxy: %s %s\n", ast_strlen_zero(sip_cfg.outboundproxy.name) ? "<not set>" : sip_cfg.outboundproxy.name,
20833 sip_cfg.outboundproxy.force ? "(forced)" : "");
20834 ast_cli(a->fd, " Session Timers: %s\n", stmode2str(global_st_mode));
20835 ast_cli(a->fd, " Session Refresher: %s\n", strefresherparam2str(global_st_refresher));
20836 ast_cli(a->fd, " Session Expires: %d secs\n", global_max_se);
20837 ast_cli(a->fd, " Session Min-SE: %d secs\n", global_min_se);
20838 ast_cli(a->fd, " Timer T1: %d\n", global_t1);
20839 ast_cli(a->fd, " Timer T1 minimum: %d\n", global_t1min);
20840 ast_cli(a->fd, " Timer B: %d\n", global_timer_b);
20841 ast_cli(a->fd, " No premature media: %s\n", AST_CLI_YESNO(global_prematuremediafilter));
20842 ast_cli(a->fd, " Max forwards: %d\n", sip_cfg.default_max_forwards);
20843
20844 ast_cli(a->fd, "\nDefault Settings:\n");
20845 ast_cli(a->fd, "-----------------\n");
20846 ast_cli(a->fd, " Allowed transports: %s\n", get_transport_list(default_transports));
20847 ast_cli(a->fd, " Outbound transport: %s\n", sip_get_transport(default_primary_transport));
20848 ast_cli(a->fd, " Context: %s\n", sip_cfg.default_context);
20849 ast_cli(a->fd, " Record on feature: %s\n", sip_cfg.default_record_on_feature);
20850 ast_cli(a->fd, " Record off feature: %s\n", sip_cfg.default_record_off_feature);
20851 ast_cli(a->fd, " Force rport: %s\n", force_rport_string(global_flags));
20852 ast_cli(a->fd, " DTMF: %s\n", dtmfmode2str(ast_test_flag(&global_flags[0], SIP_DTMF)));
20853 ast_cli(a->fd, " Qualify: %d\n", default_qualify);
20854 ast_cli(a->fd, " Keepalive: %d\n", default_keepalive);
20855 ast_cli(a->fd, " Use ClientCode: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_USECLIENTCODE)));
20856 ast_cli(a->fd, " Progress inband: %s\n", (ast_test_flag(&global_flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER) ? "Never" : (AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_PROG_INBAND) != SIP_PROG_INBAND_NO)));
20857 ast_cli(a->fd, " Language: %s\n", default_language);
20858 ast_cli(a->fd, " Tone zone: %s\n", default_zone[0] != '\0' ? default_zone : "<Not set>");
20859 ast_cli(a->fd, " MOH Interpret: %s\n", default_mohinterpret);
20860 ast_cli(a->fd, " MOH Suggest: %s\n", default_mohsuggest);
20861 ast_cli(a->fd, " Voice Mail Extension: %s\n", default_vmexten);
20862
20863
20864 if (realtimepeers || realtimeregs) {
20865 ast_cli(a->fd, "\nRealtime SIP Settings:\n");
20866 ast_cli(a->fd, "----------------------\n");
20867 ast_cli(a->fd, " Realtime Peers: %s\n", AST_CLI_YESNO(realtimepeers));
20868 ast_cli(a->fd, " Realtime Regs: %s\n", AST_CLI_YESNO(realtimeregs));
20869 ast_cli(a->fd, " Cache Friends: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)));
20870 ast_cli(a->fd, " Update: %s\n", AST_CLI_YESNO(sip_cfg.peer_rtupdate));
20871 ast_cli(a->fd, " Ignore Reg. Expire: %s\n", AST_CLI_YESNO(sip_cfg.ignore_regexpire));
20872 ast_cli(a->fd, " Save sys. name: %s\n", AST_CLI_YESNO(sip_cfg.rtsave_sysname));
20873 ast_cli(a->fd, " Auto Clear: %d (%s)\n", sip_cfg.rtautoclear, ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR) ? "Enabled" : "Disabled");
20874 }
20875 ast_cli(a->fd, "\n----\n");
20876 return CLI_SUCCESS;
20877 }
20878
20879 static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
20880 {
20881 #define FORMAT "%-30.30s %-12.12s %-10.10s %-10.10s\n"
20882 char host[80];
20883
20884 switch (cmd) {
20885 case CLI_INIT:
20886 e->command = "sip show mwi";
20887 e->usage =
20888 "Usage: sip show mwi\n"
20889 " Provides a list of MWI subscriptions and status.\n";
20890 return NULL;
20891 case CLI_GENERATE:
20892 return NULL;
20893 }
20894
20895 ast_cli(a->fd, FORMAT, "Host", "Username", "Mailbox", "Subscribed");
20896
20897 ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
20898 ASTOBJ_RDLOCK(iterator);
20899 snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
20900 ast_cli(a->fd, FORMAT, host, iterator->username, iterator->mailbox, AST_CLI_YESNO(iterator->subscribed));
20901 ASTOBJ_UNLOCK(iterator);
20902 } while(0));
20903
20904 return CLI_SUCCESS;
20905 #undef FORMAT
20906 }
20907
20908
20909
20910 static const char *subscription_type2str(enum subscriptiontype subtype)
20911 {
20912 int i;
20913
20914 for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
20915 if (subscription_types[i].type == subtype) {
20916 return subscription_types[i].text;
20917 }
20918 }
20919 return subscription_types[0].text;
20920 }
20921
20922
20923 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype)
20924 {
20925 int i;
20926
20927 for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
20928 if (subscription_types[i].type == subtype) {
20929 return &subscription_types[i];
20930 }
20931 }
20932 return &subscription_types[0];
20933 }
20934
20935
20936
20937
20938
20939
20940
20941
20942 #define FORMAT4 "%-15.15s %-15.15s %-15.15s %-15.15s %-13.13s %-15.15s %-10.10s %-6.6d\n"
20943 #define FORMAT3 "%-15.15s %-15.15s %-15.15s %-15.15s %-13.13s %-15.15s %-10.10s %-6.6s\n"
20944 #define FORMAT2 "%-15.15s %-15.15s %-15.15s %-15.15s %-7.7s %-15.15s %-10.10s %-10.10s\n"
20945 #define FORMAT "%-15.15s %-15.15s %-15.15s %-15.15s %-3.3s %-3.3s %-15.15s %-10.10s %-10.10s\n"
20946
20947
20948 static int show_channels_cb(void *__cur, void *__arg, int flags)
20949 {
20950 struct sip_pvt *cur = __cur;
20951 struct __show_chan_arg *arg = __arg;
20952 const struct ast_sockaddr *dst;
20953
20954 sip_pvt_lock(cur);
20955 dst = sip_real_dst(cur);
20956
20957
20958 if (cur->subscribed == NONE && !arg->subscriptions) {
20959
20960 const char *referstatus = cur->refer ? referstatus2str(cur->refer->status) : "";
20961 char formatbuf[SIPBUFSIZE/2];
20962
20963 ast_cli(arg->fd, FORMAT, ast_sockaddr_stringify_addr(dst),
20964 S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
20965 cur->callid,
20966 cur->owner ? ast_getformatname_multiple(formatbuf, sizeof(formatbuf), ast_channel_nativeformats(cur->owner)) : "(nothing)",
20967 AST_CLI_YESNO(ast_test_flag(&cur->flags[1], SIP_PAGE2_CALL_ONHOLD)),
20968 cur->needdestroy ? "(d)" : "",
20969 cur->lastmsg ,
20970 referstatus,
20971 cur->relatedpeer ? cur->relatedpeer->name : "<guest>"
20972 );
20973 arg->numchans++;
20974 }
20975 if (cur->subscribed != NONE && arg->subscriptions) {
20976 struct ast_str *mailbox_str = ast_str_alloca(512);
20977 if (cur->subscribed == MWI_NOTIFICATION && cur->relatedpeer)
20978 peer_mailboxes_to_str(&mailbox_str, cur->relatedpeer);
20979 ast_cli(arg->fd, FORMAT4, ast_sockaddr_stringify_addr(dst),
20980 S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
20981 cur->callid,
20982
20983 cur->subscribed == MWI_NOTIFICATION ? "--" : cur->subscribeuri,
20984 cur->subscribed == MWI_NOTIFICATION ? "<none>" : ast_extension_state2str(cur->laststate),
20985 subscription_type2str(cur->subscribed),
20986 cur->subscribed == MWI_NOTIFICATION ? S_OR(ast_str_buffer(mailbox_str), "<none>") : "<none>",
20987 cur->expiry
20988 );
20989 arg->numchans++;
20990 }
20991 sip_pvt_unlock(cur);
20992 return 0;
20993 }
20994
20995
20996
20997
20998
20999
21000 static char *sip_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
21001 {
21002 struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
21003
21004
21005 if (cmd == CLI_INIT) {
21006 e->command = "sip show {channels|subscriptions}";
21007 e->usage =
21008 "Usage: sip show channels\n"
21009 " Lists all currently active SIP calls (dialogs).\n"
21010 "Usage: sip show subscriptions\n"
21011 " Lists active SIP subscriptions.\n";
21012 return NULL;
21013 } else if (cmd == CLI_GENERATE)
21014 return NULL;
21015
21016 if (a->argc != e->args)
21017 return CLI_SHOWUSAGE;
21018 arg.subscriptions = !strcasecmp(a->argv[e->args - 1], "subscriptions");
21019 if (!arg.subscriptions)
21020 ast_cli(arg.fd, FORMAT2, "Peer", "User/ANR", "Call ID", "Format", "Hold", "Last Message", "Expiry", "Peer");
21021 else
21022 ast_cli(arg.fd, FORMAT3, "Peer", "User", "Call ID", "Extension", "Last state", "Type", "Mailbox", "Expiry");
21023
21024
21025 ao2_t_callback(dialogs, OBJ_NODATA, show_channels_cb, &arg, "callback to show channels");
21026
21027
21028 ast_cli(arg.fd, "%d active SIP %s%s\n", arg.numchans,
21029 (arg.subscriptions ? "subscription" : "dialog"),
21030 ESS(arg.numchans));
21031 return CLI_SUCCESS;
21032 #undef FORMAT
21033 #undef FORMAT2
21034 #undef FORMAT3
21035 }
21036
21037
21038
21039
21040
21041
21042 static char *complete_sipch(const char *line, const char *word, int pos, int state)
21043 {
21044 int which=0;
21045 struct sip_pvt *cur;
21046 char *c = NULL;
21047 int wordlen = strlen(word);
21048 struct ao2_iterator i;
21049
21050 if (pos != 3) {
21051 return NULL;
21052 }
21053
21054 i = ao2_iterator_init(dialogs, 0);
21055 while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
21056 sip_pvt_lock(cur);
21057 if (!strncasecmp(word, cur->callid, wordlen) && ++which > state) {
21058 c = ast_strdup(cur->callid);
21059 sip_pvt_unlock(cur);
21060 dialog_unref(cur, "drop ref in iterator loop break");
21061 break;
21062 }
21063 sip_pvt_unlock(cur);
21064 dialog_unref(cur, "drop ref in iterator loop");
21065 }
21066 ao2_iterator_destroy(&i);
21067 return c;
21068 }
21069
21070
21071
21072 static char *complete_sip_peer(const char *word, int state, int flags2)
21073 {
21074 char *result = NULL;
21075 int wordlen = strlen(word);
21076 int which = 0;
21077 struct ao2_iterator i = ao2_iterator_init(peers, 0);
21078 struct sip_peer *peer;
21079
21080 while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
21081
21082 if (!strncasecmp(word, peer->name, wordlen) &&
21083 (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
21084 ++which > state)
21085 result = ast_strdup(peer->name);
21086 sip_unref_peer(peer, "toss iterator peer ptr before break");
21087 if (result) {
21088 break;
21089 }
21090 }
21091 ao2_iterator_destroy(&i);
21092 return result;
21093 }
21094
21095
21096 static char *complete_sip_registered_peer(const char *word, int state, int flags2)
21097 {
21098 char *result = NULL;
21099 int wordlen = strlen(word);
21100 int which = 0;
21101 struct ao2_iterator i;
21102 struct sip_peer *peer;
21103
21104 i = ao2_iterator_init(peers, 0);
21105 while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
21106 if (!strncasecmp(word, peer->name, wordlen) &&
21107 (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
21108 ++which > state && peer->expire > 0)
21109 result = ast_strdup(peer->name);
21110 if (result) {
21111 sip_unref_peer(peer, "toss iterator peer ptr before break");
21112 break;
21113 }
21114 sip_unref_peer(peer, "toss iterator peer ptr");
21115 }
21116 ao2_iterator_destroy(&i);
21117 return result;
21118 }
21119
21120
21121 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state)
21122 {
21123 if (pos == 3)
21124 return complete_sipch(line, word, pos, state);
21125
21126 return NULL;
21127 }
21128
21129
21130 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state)
21131 {
21132 if (pos == 3) {
21133 return complete_sip_peer(word, state, 0);
21134 }
21135
21136 return NULL;
21137 }
21138
21139
21140 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state)
21141 {
21142 if (pos == 2)
21143 return complete_sip_registered_peer(word, state, 0);
21144
21145 return NULL;
21146 }
21147
21148
21149 static char *complete_sip_notify(const char *line, const char *word, int pos, int state)
21150 {
21151 char *c = NULL;
21152
21153 if (pos == 2) {
21154 int which = 0;
21155 char *cat = NULL;
21156 int wordlen = strlen(word);
21157
21158
21159
21160 if (!notify_types)
21161 return NULL;
21162
21163 while ( (cat = ast_category_browse(notify_types, cat)) ) {
21164 if (!strncasecmp(word, cat, wordlen) && ++which > state) {
21165 c = ast_strdup(cat);
21166 break;
21167 }
21168 }
21169 return c;
21170 }
21171
21172 if (pos > 2)
21173 return complete_sip_peer(word, state, 0);
21174
21175 return NULL;
21176 }
21177
21178
21179 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
21180 {
21181 struct sip_pvt *cur;
21182 size_t len;
21183 int found = 0;
21184 struct ao2_iterator i;
21185
21186 switch (cmd) {
21187 case CLI_INIT:
21188 e->command = "sip show channel";
21189 e->usage =
21190 "Usage: sip show channel <call-id>\n"
21191 " Provides detailed status on a given SIP dialog (identified by SIP call-id).\n";
21192 return NULL;
21193 case CLI_GENERATE:
21194 return complete_sipch(a->line, a->word, a->pos, a->n);
21195 }
21196
21197 if (a->argc != 4)
21198 return CLI_SHOWUSAGE;
21199 len = strlen(a->argv[3]);
21200
21201 i = ao2_iterator_init(dialogs, 0);
21202 while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
21203 sip_pvt_lock(cur);
21204
21205 if (!strncasecmp(cur->callid, a->argv[3], len)) {
21206 char formatbuf[SIPBUFSIZE/2];
21207 ast_cli(a->fd, "\n");
21208 if (cur->subscribed != NONE) {
21209 ast_cli(a->fd, " * Subscription (type: %s)\n", subscription_type2str(cur->subscribed));
21210 } else {
21211 ast_cli(a->fd, " * SIP Call\n");
21212 }
21213 ast_cli(a->fd, " Curr. trans. direction: %s\n", ast_test_flag(&cur->flags[0], SIP_OUTGOING) ? "Outgoing" : "Incoming");
21214 ast_cli(a->fd, " Call-ID: %s\n", cur->callid);
21215 ast_cli(a->fd, " Owner channel ID: %s\n", cur->owner ? ast_channel_name(cur->owner) : "<none>");
21216 ast_cli(a->fd, " Our Codec Capability: %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->caps));
21217 ast_cli(a->fd, " Non-Codec Capability (DTMF): %d\n", cur->noncodeccapability);
21218 ast_cli(a->fd, " Their Codec Capability: %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->peercaps));
21219 ast_cli(a->fd, " Joint Codec Capability: %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->jointcaps));
21220 ast_cli(a->fd, " Format: %s\n", cur->owner ? ast_getformatname_multiple(formatbuf, sizeof(formatbuf), ast_channel_nativeformats(cur->owner)) : "(nothing)" );
21221 ast_cli(a->fd, " T.38 support %s\n", AST_CLI_YESNO(cur->udptl != NULL));
21222 ast_cli(a->fd, " Video support %s\n", AST_CLI_YESNO(cur->vrtp != NULL));
21223 ast_cli(a->fd, " MaxCallBR: %d kbps\n", cur->maxcallbitrate);
21224 ast_cli(a->fd, " Theoretical Address: %s\n", ast_sockaddr_stringify(&cur->sa));
21225 ast_cli(a->fd, " Received Address: %s\n", ast_sockaddr_stringify(&cur->recv));
21226 ast_cli(a->fd, " SIP Transfer mode: %s\n", transfermode2str(cur->allowtransfer));
21227 ast_cli(a->fd, " Force rport: %s\n", force_rport_string(cur->flags));
21228 if (ast_sockaddr_isnull(&cur->redirip)) {
21229 ast_cli(a->fd,
21230 " Audio IP: %s (local)\n",
21231 ast_sockaddr_stringify_addr(&cur->ourip));
21232 } else {
21233 ast_cli(a->fd,
21234 " Audio IP: %s (Outside bridge)\n",
21235 ast_sockaddr_stringify_addr(&cur->redirip));
21236 }
21237 ast_cli(a->fd, " Our Tag: %s\n", cur->tag);
21238 ast_cli(a->fd, " Their Tag: %s\n", cur->theirtag);
21239 ast_cli(a->fd, " SIP User agent: %s\n", cur->useragent);
21240 if (!ast_strlen_zero(cur->username)) {
21241 ast_cli(a->fd, " Username: %s\n", cur->username);
21242 }
21243 if (!ast_strlen_zero(cur->peername)) {
21244 ast_cli(a->fd, " Peername: %s\n", cur->peername);
21245 }
21246 if (!ast_strlen_zero(cur->uri)) {
21247 ast_cli(a->fd, " Original uri: %s\n", cur->uri);
21248 }
21249 if (!ast_strlen_zero(cur->cid_num)) {
21250 ast_cli(a->fd, " Caller-ID: %s\n", cur->cid_num);
21251 }
21252 ast_cli(a->fd, " Need Destroy: %s\n", AST_CLI_YESNO(cur->needdestroy));
21253 ast_cli(a->fd, " Last Message: %s\n", cur->lastmsg);
21254 ast_cli(a->fd, " Promiscuous Redir: %s\n", AST_CLI_YESNO(ast_test_flag(&cur->flags[0], SIP_PROMISCREDIR)));
21255 ast_cli(a->fd, " Route: ");
21256 if (cur->route) {
21257 struct sip_route *route;
21258 int first = 1;
21259
21260 for (route = cur->route; route; route = route->next) {
21261 ast_cli(a->fd, "%s<%s>", first ? "" : ", ", route->hop);
21262 first = 0;
21263 }
21264 ast_cli(a->fd, "\n");
21265 } else {
21266 ast_cli(a->fd, "N/A\n");
21267 }
21268 ast_cli(a->fd, " DTMF Mode: %s\n", dtmfmode2str(ast_test_flag(&cur->flags[0], SIP_DTMF)));
21269 ast_cli(a->fd, " SIP Options: ");
21270 if (cur->sipoptions) {
21271 int x;
21272 for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
21273 if (cur->sipoptions & sip_options[x].id)
21274 ast_cli(a->fd, "%s ", sip_options[x].text);
21275 }
21276 ast_cli(a->fd, "\n");
21277 } else {
21278 ast_cli(a->fd, "(none)\n");
21279 }
21280
21281 if (!cur->stimer) {
21282 ast_cli(a->fd, " Session-Timer: Uninitiallized\n");
21283 } else {
21284 ast_cli(a->fd, " Session-Timer: %s\n", cur->stimer->st_active ? "Active" : "Inactive");
21285 if (cur->stimer->st_active == TRUE) {
21286 ast_cli(a->fd, " S-Timer Interval: %d\n", cur->stimer->st_interval);
21287 ast_cli(a->fd, " S-Timer Refresher: %s\n", strefresher2str(cur->stimer->st_ref));
21288 ast_cli(a->fd, " S-Timer Sched Id: %d\n", cur->stimer->st_schedid);
21289 ast_cli(a->fd, " S-Timer Peer Sts: %s\n", cur->stimer->st_active_peer_ua ? "Active" : "Inactive");
21290 ast_cli(a->fd, " S-Timer Cached Min-SE: %d\n", cur->stimer->st_cached_min_se);
21291 ast_cli(a->fd, " S-Timer Cached SE: %d\n", cur->stimer->st_cached_max_se);
21292 ast_cli(a->fd, " S-Timer Cached Ref: %s\n", strefresherparam2str(cur->stimer->st_cached_ref));
21293 ast_cli(a->fd, " S-Timer Cached Mode: %s\n", stmode2str(cur->stimer->st_cached_mode));
21294 }
21295 }
21296
21297 ast_cli(a->fd, "\n\n");
21298
21299 found++;
21300 }
21301
21302 sip_pvt_unlock(cur);
21303
21304 ao2_t_ref(cur, -1, "toss dialog ptr set by iterator_next");
21305 }
21306 ao2_iterator_destroy(&i);
21307
21308 if (!found) {
21309 ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
21310 }
21311
21312 return CLI_SUCCESS;
21313 }
21314
21315
21316 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
21317 {
21318 struct sip_pvt *cur;
21319 size_t len;
21320 int found = 0;
21321 struct ao2_iterator i;
21322
21323 switch (cmd) {
21324 case CLI_INIT:
21325 e->command = "sip show history";
21326 e->usage =
21327 "Usage: sip show history <call-id>\n"
21328 " Provides detailed dialog history on a given SIP call (specified by call-id).\n";
21329 return NULL;
21330 case CLI_GENERATE:
21331 return complete_sip_show_history(a->line, a->word, a->pos, a->n);
21332 }
21333
21334 if (a->argc != 4) {
21335 return CLI_SHOWUSAGE;
21336 }
21337
21338 if (!recordhistory) {
21339 ast_cli(a->fd, "\n***Note: History recording is currently DISABLED. Use 'sip set history on' to ENABLE.\n");
21340 }
21341
21342 len = strlen(a->argv[3]);
21343
21344 i = ao2_iterator_init(dialogs, 0);
21345 while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
21346 sip_pvt_lock(cur);
21347 if (!strncasecmp(cur->callid, a->argv[3], len)) {
21348 struct sip_history *hist;
21349 int x = 0;
21350
21351 ast_cli(a->fd, "\n");
21352 if (cur->subscribed != NONE) {
21353 ast_cli(a->fd, " * Subscription\n");
21354 } else {
21355 ast_cli(a->fd, " * SIP Call\n");
21356 }
21357 if (cur->history) {
21358 AST_LIST_TRAVERSE(cur->history, hist, list)
21359 ast_cli(a->fd, "%d. %s\n", ++x, hist->event);
21360 }
21361 if (x == 0) {
21362 ast_cli(a->fd, "Call '%s' has no history\n", cur->callid);
21363 }
21364 found++;
21365 }
21366 sip_pvt_unlock(cur);
21367 ao2_t_ref(cur, -1, "toss dialog ptr from iterator_next");
21368 }
21369 ao2_iterator_destroy(&i);
21370
21371 if (!found) {
21372 ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
21373 }
21374
21375 return CLI_SUCCESS;
21376 }
21377
21378
21379 static void sip_dump_history(struct sip_pvt *dialog)
21380 {
21381 int x = 0;
21382 struct sip_history *hist;
21383 static int errmsg = 0;
21384
21385 if (!dialog) {
21386 return;
21387 }
21388
21389 if (!option_debug && !sipdebug) {
21390 if (!errmsg) {
21391 ast_log(LOG_NOTICE, "You must have debugging enabled (SIP or Asterisk) in order to dump SIP history.\n");
21392 errmsg = 1;
21393 }
21394 return;
21395 }
21396
21397 ast_debug(1, "\n---------- SIP HISTORY for '%s' \n", dialog->callid);
21398 if (dialog->subscribed) {
21399 ast_debug(1, " * Subscription\n");
21400 } else {
21401 ast_debug(1, " * SIP Call\n");
21402 }
21403 if (dialog->history) {
21404 AST_LIST_TRAVERSE(dialog->history, hist, list)
21405 ast_debug(1, " %-3.3d. %s\n", ++x, hist->event);
21406 }
21407 if (!x) {
21408 ast_debug(1, "Call '%s' has no history\n", dialog->callid);
21409 }
21410 ast_debug(1, "\n---------- END SIP HISTORY for '%s' \n", dialog->callid);
21411 }
21412
21413
21414
21415 static void handle_request_info(struct sip_pvt *p, struct sip_request *req)
21416 {
21417 const char *buf = "";
21418 unsigned int event;
21419 const char *c = sip_get_header(req, "Content-Type");
21420
21421
21422 if (!strcasecmp(c, "application/dtmf-relay") ||
21423 !strcasecmp(c, "application/vnd.nortelnetworks.digits") ||
21424 !strcasecmp(c, "application/dtmf")) {
21425 unsigned int duration = 0;
21426
21427 if (!p->owner) {
21428 transmit_response(p, "481 Call leg/transaction does not exist", req);
21429 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21430 return;
21431 }
21432
21433
21434
21435 if (strcasecmp(c, "application/dtmf")) {
21436 const char *tmp;
21437
21438 if (ast_strlen_zero(buf = get_content_line(req, "Signal", '='))
21439 && ast_strlen_zero(buf = get_content_line(req, "d", '='))) {
21440 ast_log(LOG_WARNING, "Unable to retrieve DTMF signal for INFO message on "
21441 "call %s\n", p->callid);
21442 transmit_response(p, "200 OK", req);
21443 return;
21444 }
21445 if (!ast_strlen_zero((tmp = get_content_line(req, "Duration", '=')))) {
21446 sscanf(tmp, "%30u", &duration);
21447 }
21448 } else {
21449
21450 buf = get_content(req);
21451 }
21452
21453
21454 if (ast_strlen_zero(buf)) {
21455 transmit_response(p, "200 OK", req);
21456 return;
21457 }
21458
21459 if (!duration) {
21460 duration = 100;
21461 }
21462
21463 if (buf[0] == '*') {
21464 event = 10;
21465 } else if (buf[0] == '#') {
21466 event = 11;
21467 } else if (buf[0] == '!') {
21468 event = 16;
21469 } else if ('A' <= buf[0] && buf[0] <= 'D') {
21470 event = 12 + buf[0] - 'A';
21471 } else if ('a' <= buf[0] && buf[0] <= 'd') {
21472 event = 12 + buf[0] - 'a';
21473 } else if ((sscanf(buf, "%30u", &event) != 1) || event > 16) {
21474 ast_log(AST_LOG_WARNING, "Unable to convert DTMF event signal code to a valid "
21475 "value for INFO message on call %s\n", p->callid);
21476 transmit_response(p, "200 OK", req);
21477 return;
21478 }
21479
21480 if (event == 16) {
21481
21482 struct ast_frame f = { AST_FRAME_CONTROL, { AST_CONTROL_FLASH, } };
21483 ast_queue_frame(p->owner, &f);
21484 if (sipdebug) {
21485 ast_verbose("* DTMF-relay event received: FLASH\n");
21486 }
21487 } else {
21488
21489 struct ast_frame f = { AST_FRAME_DTMF, };
21490 if (event < 10) {
21491 f.subclass.integer = '0' + event;
21492 } else if (event == 10) {
21493 f.subclass.integer = '*';
21494 } else if (event == 11) {
21495 f.subclass.integer = '#';
21496 } else {
21497 f.subclass.integer = 'A' + (event - 12);
21498 }
21499 f.len = duration;
21500 ast_queue_frame(p->owner, &f);
21501 if (sipdebug) {
21502 ast_verbose("* DTMF-relay event received: %c\n", (int) f.subclass.integer);
21503 }
21504 }
21505 transmit_response(p, "200 OK", req);
21506 return;
21507 } else if (!strcasecmp(c, "application/media_control+xml")) {
21508
21509 if (p->owner) {
21510 ast_queue_control(p->owner, AST_CONTROL_VIDUPDATE);
21511 }
21512 transmit_response(p, "200 OK", req);
21513 return;
21514 } else if (!ast_strlen_zero(c = sip_get_header(req, "X-ClientCode"))) {
21515
21516 if (ast_test_flag(&p->flags[0], SIP_USECLIENTCODE)) {
21517 if (p->owner && ast_channel_cdr(p->owner)) {
21518 ast_cdr_setuserfield(p->owner, c);
21519 }
21520 if (p->owner && ast_bridged_channel(p->owner) && ast_channel_cdr(ast_bridged_channel(p->owner))) {
21521 ast_cdr_setuserfield(ast_bridged_channel(p->owner), c);
21522 }
21523 transmit_response(p, "200 OK", req);
21524 } else {
21525 transmit_response(p, "403 Forbidden", req);
21526 }
21527 return;
21528 } else if (!ast_strlen_zero(c = sip_get_header(req, "Record"))) {
21529
21530
21531
21532
21533 struct ast_call_feature *feat = NULL;
21534 int j;
21535 struct ast_frame f = { AST_FRAME_DTMF, };
21536 int suppress_warning = 0;
21537
21538 if (!p->owner) {
21539 transmit_response(p, "481 Call leg/transaction does not exist", req);
21540 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21541 return;
21542 }
21543
21544
21545 ast_rdlock_call_features();
21546 if (p->relatedpeer) {
21547 if (!strcasecmp(c, "on")) {
21548 if (ast_strlen_zero(p->relatedpeer->record_on_feature)) {
21549 suppress_warning = 1;
21550 } else {
21551 feat = ast_find_call_feature(p->relatedpeer->record_on_feature);
21552 }
21553 } else if (!strcasecmp(c, "off")) {
21554 if (ast_strlen_zero(p->relatedpeer->record_off_feature)) {
21555 suppress_warning = 1;
21556 } else {
21557 feat = ast_find_call_feature(p->relatedpeer->record_off_feature);
21558 }
21559 } else {
21560 ast_log(LOG_ERROR, "Received INFO requesting to record with invalid value: %s\n", c);
21561 }
21562 }
21563 if (!feat || ast_strlen_zero(feat->exten)) {
21564 if (!suppress_warning) {
21565 ast_log(LOG_WARNING, "Recording requested, but no One Touch Monitor registered. (See features.conf)\n");
21566 }
21567
21568 transmit_response(p, "403 Forbidden", req);
21569 ast_unlock_call_features();
21570 return;
21571 }
21572
21573 f.len = 100;
21574 for (j=0; j < strlen(feat->exten); j++) {
21575 f.subclass.integer = feat->exten[j];
21576 ast_queue_frame(p->owner, &f);
21577 if (sipdebug) {
21578 ast_verbose("* DTMF-relay event faked: %c\n", f.subclass.integer);
21579 }
21580 }
21581 ast_unlock_call_features();
21582
21583 ast_debug(1, "Got a Request to Record the channel, state %s\n", c);
21584 transmit_response(p, "200 OK", req);
21585 return;
21586 } else if (ast_strlen_zero(c = sip_get_header(req, "Content-Length")) || !strcasecmp(c, "0")) {
21587
21588 transmit_response(p, "200 OK", req);
21589 return;
21590 }
21591
21592
21593
21594 ast_log(LOG_WARNING, "Unable to parse INFO message from %s. Content %s\n", p->callid, buf);
21595 transmit_response(p, "415 Unsupported media type", req);
21596 return;
21597 }
21598
21599
21600 static char *sip_do_debug_ip(int fd, const char *arg)
21601 {
21602 if (ast_sockaddr_resolve_first_af(&debugaddr, arg, 0, 0)) {
21603 return CLI_SHOWUSAGE;
21604 }
21605
21606 ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_sockaddr_stringify_addr(&debugaddr));
21607 sipdebug |= sip_debug_console;
21608
21609 return CLI_SUCCESS;
21610 }
21611
21612
21613 static char *sip_do_debug_peer(int fd, const char *arg)
21614 {
21615 struct sip_peer *peer = sip_find_peer(arg, NULL, TRUE, FINDPEERS, FALSE, 0);
21616 if (!peer) {
21617 ast_cli(fd, "No such peer '%s'\n", arg);
21618 } else if (ast_sockaddr_isnull(&peer->addr)) {
21619 ast_cli(fd, "Unable to get IP address of peer '%s'\n", arg);
21620 } else {
21621 ast_sockaddr_copy(&debugaddr, &peer->addr);
21622 ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_sockaddr_stringify_addr(&debugaddr));
21623 sipdebug |= sip_debug_console;
21624 }
21625 if (peer) {
21626 sip_unref_peer(peer, "sip_do_debug_peer: sip_unref_peer, from sip_find_peer call");
21627 }
21628 return CLI_SUCCESS;
21629 }
21630
21631
21632 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
21633 {
21634 int oldsipdebug = sipdebug & sip_debug_console;
21635 const char *what;
21636
21637 if (cmd == CLI_INIT) {
21638 e->command = "sip set debug {on|off|ip|peer}";
21639 e->usage =
21640 "Usage: sip set debug {off|on|ip addr[:port]|peer peername}\n"
21641 " Globally disables dumping of SIP packets,\n"
21642 " or enables it either globally or for a (single)\n"
21643 " IP address or registered peer.\n";
21644 return NULL;
21645 } else if (cmd == CLI_GENERATE) {
21646 if (a->pos == 4 && !strcasecmp(a->argv[3], "peer"))
21647 return complete_sip_peer(a->word, a->n, 0);
21648 return NULL;
21649 }
21650
21651 what = a->argv[e->args-1];
21652 if (a->argc == e->args) {
21653 if (!strcasecmp(what, "on")) {
21654 sipdebug |= sip_debug_console;
21655 sipdebug_text = 1;
21656 memset(&debugaddr, 0, sizeof(debugaddr));
21657 ast_cli(a->fd, "SIP Debugging %senabled\n", oldsipdebug ? "re-" : "");
21658 return CLI_SUCCESS;
21659 } else if (!strcasecmp(what, "off")) {
21660 sipdebug &= ~sip_debug_console;
21661 sipdebug_text = 0;
21662 ast_cli(a->fd, "SIP Debugging Disabled\n");
21663 return CLI_SUCCESS;
21664 }
21665 } else if (a->argc == e->args +1) {
21666 if (!strcasecmp(what, "ip"))
21667 return sip_do_debug_ip(a->fd, a->argv[e->args]);
21668 else if (!strcasecmp(what, "peer"))
21669 return sip_do_debug_peer(a->fd, a->argv[e->args]);
21670 }
21671 return CLI_SHOWUSAGE;
21672 }
21673
21674
21675 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
21676 {
21677 struct ast_variable *varlist;
21678 int i;
21679
21680 switch (cmd) {
21681 case CLI_INIT:
21682 e->command = "sip notify";
21683 e->usage =
21684 "Usage: sip notify <type> <peer> [<peer>...]\n"
21685 " Send a NOTIFY message to a SIP peer or peers\n"
21686 " Message types are defined in sip_notify.conf\n";
21687 return NULL;
21688 case CLI_GENERATE:
21689 return complete_sip_notify(a->line, a->word, a->pos, a->n);
21690 }
21691
21692 if (a->argc < 4)
21693 return CLI_SHOWUSAGE;
21694
21695 if (!notify_types) {
21696 ast_cli(a->fd, "No %s file found, or no types listed there\n", notify_config);
21697 return CLI_FAILURE;
21698 }
21699
21700 varlist = ast_variable_browse(notify_types, a->argv[2]);
21701
21702 if (!varlist) {
21703 ast_cli(a->fd, "Unable to find notify type '%s'\n", a->argv[2]);
21704 return CLI_FAILURE;
21705 }
21706
21707 for (i = 3; i < a->argc; i++) {
21708 struct sip_pvt *p;
21709 char buf[512];
21710 struct ast_variable *header, *var;
21711
21712 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL, NULL))) {
21713 ast_log(LOG_WARNING, "Unable to build sip pvt data for notify (memory/socket error)\n");
21714 return CLI_FAILURE;
21715 }
21716
21717 if (create_addr(p, a->argv[i], NULL, 1)) {
21718
21719 dialog_unlink_all(p);
21720 dialog_unref(p, "unref dialog inside for loop" );
21721
21722 ast_cli(a->fd, "Could not create address for '%s'\n", a->argv[i]);
21723 continue;
21724 }
21725
21726
21727 ast_set_flag(&p->flags[0], SIP_OUTGOING);
21728 sip_notify_alloc(p);
21729 p->notify->headers = header = ast_variable_new("Subscription-State", "terminated", "");
21730
21731 for (var = varlist; var; var = var->next) {
21732 ast_copy_string(buf, var->value, sizeof(buf));
21733 ast_unescape_semicolon(buf);
21734
21735 if (!strcasecmp(var->name, "Content")) {
21736 if (ast_str_strlen(p->notify->content))
21737 ast_str_append(&p->notify->content, 0, "\r\n");
21738 ast_str_append(&p->notify->content, 0, "%s", buf);
21739 } else if (!strcasecmp(var->name, "Content-Length")) {
21740 ast_log(LOG_WARNING, "it is not necessary to specify Content-Length in sip_notify.conf, ignoring\n");
21741 } else {
21742 header->next = ast_variable_new(var->name, buf, "");
21743 header = header->next;
21744 }
21745 }
21746
21747
21748 ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
21749 build_via(p);
21750
21751 change_callid_pvt(p, NULL);
21752
21753 ast_cli(a->fd, "Sending NOTIFY of type '%s' to '%s'\n", a->argv[2], a->argv[i]);
21754 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
21755 transmit_invite(p, SIP_NOTIFY, 0, 2, NULL);
21756 dialog_unref(p, "bump down the count of p since we're done with it.");
21757 }
21758
21759 return CLI_SUCCESS;
21760 }
21761
21762
21763 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
21764 {
21765 switch (cmd) {
21766 case CLI_INIT:
21767 e->command = "sip set history {on|off}";
21768 e->usage =
21769 "Usage: sip set history {on|off}\n"
21770 " Enables/Disables recording of SIP dialog history for debugging purposes.\n"
21771 " Use 'sip show history' to view the history of a call number.\n";
21772 return NULL;
21773 case CLI_GENERATE:
21774 return NULL;
21775 }
21776
21777 if (a->argc != e->args)
21778 return CLI_SHOWUSAGE;
21779
21780 if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
21781 recordhistory = TRUE;
21782 ast_cli(a->fd, "SIP History Recording Enabled (use 'sip show history')\n");
21783 } else if (!strncasecmp(a->argv[e->args - 1], "off", 3)) {
21784 recordhistory = FALSE;
21785 ast_cli(a->fd, "SIP History Recording Disabled\n");
21786 } else {
21787 return CLI_SHOWUSAGE;
21788 }
21789 return CLI_SUCCESS;
21790 }
21791
21792
21793 static int do_register_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code)
21794 {
21795 char *header, *respheader;
21796 char digest[1024];
21797
21798 p->authtries++;
21799 sip_auth_headers(code, &header, &respheader);
21800 memset(digest, 0, sizeof(digest));
21801 if (reply_digest(p, req, header, SIP_REGISTER, digest, sizeof(digest))) {
21802
21803
21804 if (sip_debug_test_pvt(p) && p->registry)
21805 ast_verbose("No authentication challenge, sending blank registration to domain/host name %s\n", p->registry->hostname);
21806
21807 return -1;
21808 }
21809 if (p->do_history)
21810 append_history(p, "RegistryAuth", "Try: %d", p->authtries);
21811 if (sip_debug_test_pvt(p) && p->registry)
21812 ast_verbose("Responding to challenge, registration to domain/host name %s\n", p->registry->hostname);
21813 return transmit_register(p->registry, SIP_REGISTER, digest, respheader);
21814 }
21815
21816
21817 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code, int sipmethod, int init)
21818 {
21819 char *header, *respheader;
21820 char digest[1024];
21821
21822 if (!p->options && !(p->options = ast_calloc(1, sizeof(*p->options))))
21823 return -2;
21824
21825 p->authtries++;
21826 sip_auth_headers(code, &header, &respheader);
21827 ast_debug(2, "Auth attempt %d on %s\n", p->authtries, sip_methods[sipmethod].text);
21828 memset(digest, 0, sizeof(digest));
21829 if (reply_digest(p, req, header, sipmethod, digest, sizeof(digest) )) {
21830
21831 return -1;
21832 }
21833
21834 p->options->auth = digest;
21835 p->options->authheader = respheader;
21836 return transmit_invite(p, sipmethod, sipmethod == SIP_INVITE, init, NULL);
21837 }
21838
21839
21840
21841
21842
21843 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len)
21844 {
21845 char tmp[512];
21846 char *c;
21847 char oldnonce[256];
21848
21849
21850 const struct x {
21851 const char *key;
21852 const ast_string_field *field;
21853 } *i, keys[] = {
21854 { "realm=", &p->realm },
21855 { "nonce=", &p->nonce },
21856 { "opaque=", &p->opaque },
21857 { "qop=", &p->qop },
21858 { "domain=", &p->domain },
21859 { NULL, 0 },
21860 };
21861
21862 ast_copy_string(tmp, sip_get_header(req, header), sizeof(tmp));
21863 if (ast_strlen_zero(tmp))
21864 return -1;
21865 if (strncasecmp(tmp, "Digest ", strlen("Digest "))) {
21866 ast_log(LOG_WARNING, "missing Digest.\n");
21867 return -1;
21868 }
21869 c = tmp + strlen("Digest ");
21870 ast_copy_string(oldnonce, p->nonce, sizeof(oldnonce));
21871 while (c && *(c = ast_skip_blanks(c))) {
21872 for (i = keys; i->key != NULL; i++) {
21873 char *src, *separator;
21874 if (strncasecmp(c, i->key, strlen(i->key)) != 0)
21875 continue;
21876
21877 c += strlen(i->key);
21878 if (*c == '"') {
21879 src = ++c;
21880 separator = "\"";
21881 } else {
21882 src = c;
21883 separator = ",";
21884 }
21885 strsep(&c, separator);
21886 ast_string_field_ptr_set(p, i->field, src);
21887 break;
21888 }
21889 if (i->key == NULL)
21890 strsep(&c, ",");
21891 }
21892
21893 if (strcmp(p->nonce, oldnonce))
21894 p->noncecount = 0;
21895
21896
21897 if (p->registry) {
21898 struct sip_registry *r = p->registry;
21899
21900 if (strcmp(r->nonce, p->nonce)) {
21901 ast_string_field_set(r, realm, p->realm);
21902 ast_string_field_set(r, nonce, p->nonce);
21903 ast_string_field_set(r, authdomain, p->domain);
21904 ast_string_field_set(r, opaque, p->opaque);
21905 ast_string_field_set(r, qop, p->qop);
21906 r->noncecount = 0;
21907 }
21908 }
21909 return build_reply_digest(p, sipmethod, digest, digest_len);
21910 }
21911
21912
21913
21914
21915
21916
21917 static int build_reply_digest(struct sip_pvt *p, int method, char* digest, int digest_len)
21918 {
21919 char a1[256];
21920 char a2[256];
21921 char a1_hash[256];
21922 char a2_hash[256];
21923 char resp[256];
21924 char resp_hash[256];
21925 char uri[256];
21926 char opaque[256] = "";
21927 char cnonce[80];
21928 const char *username;
21929 const char *secret;
21930 const char *md5secret;
21931 struct sip_auth *auth;
21932 struct sip_auth_container *credentials;
21933
21934 if (!ast_strlen_zero(p->domain))
21935 snprintf(uri, sizeof(uri), "%s:%s", p->socket.type == SIP_TRANSPORT_TLS ? "sips" : "sip", p->domain);
21936 else if (!ast_strlen_zero(p->uri))
21937 ast_copy_string(uri, p->uri, sizeof(uri));
21938 else
21939 snprintf(uri, sizeof(uri), "%s:%s@%s", p->socket.type == SIP_TRANSPORT_TLS ? "sips" : "sip", p->username, ast_sockaddr_stringify_host_remote(&p->sa));
21940
21941 snprintf(cnonce, sizeof(cnonce), "%08lx", ast_random());
21942
21943
21944 ao2_lock(p);
21945 credentials = p->peerauth;
21946 if (credentials) {
21947 ao2_t_ref(credentials, +1, "Ref peer auth for digest");
21948 }
21949 ao2_unlock(p);
21950 auth = find_realm_authentication(credentials, p->realm);
21951 if (!auth) {
21952
21953 if (credentials) {
21954 ao2_t_ref(credentials, -1, "Unref peer auth for digest");
21955 }
21956 ast_mutex_lock(&authl_lock);
21957 credentials = authl;
21958 if (credentials) {
21959 ao2_t_ref(credentials, +1, "Ref global auth for digest");
21960 }
21961 ast_mutex_unlock(&authl_lock);
21962 auth = find_realm_authentication(credentials, p->realm);
21963 }
21964
21965 if (auth) {
21966 ast_debug(3, "use realm [%s] from peer [%s][%s]\n", auth->username, p->peername, p->username);
21967 username = auth->username;
21968 secret = auth->secret;
21969 md5secret = auth->md5secret;
21970 if (sipdebug)
21971 ast_debug(1, "Using realm %s authentication for call %s\n", p->realm, p->callid);
21972 } else {
21973
21974 username = p->authname;
21975 secret = p->relatedpeer
21976 && !ast_strlen_zero(p->relatedpeer->remotesecret)
21977 ? p->relatedpeer->remotesecret : p->peersecret;
21978 md5secret = p->peermd5secret;
21979 }
21980 if (ast_strlen_zero(username)) {
21981
21982 if (credentials) {
21983 ao2_t_ref(credentials, -1, "Unref auth for digest");
21984 }
21985 return -1;
21986 }
21987
21988
21989 snprintf(a1, sizeof(a1), "%s:%s:%s", username, p->realm, secret);
21990 snprintf(a2, sizeof(a2), "%s:%s", sip_methods[method].text, uri);
21991 if (!ast_strlen_zero(md5secret))
21992 ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
21993 else
21994 ast_md5_hash(a1_hash, a1);
21995 ast_md5_hash(a2_hash, a2);
21996
21997 p->noncecount++;
21998 if (!ast_strlen_zero(p->qop))
21999 snprintf(resp, sizeof(resp), "%s:%s:%08x:%s:%s:%s", a1_hash, p->nonce, p->noncecount, cnonce, "auth", a2_hash);
22000 else
22001 snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, p->nonce, a2_hash);
22002 ast_md5_hash(resp_hash, resp);
22003
22004
22005 if (!ast_strlen_zero(p->opaque)) {
22006 snprintf(opaque, sizeof(opaque), ", opaque=\"%s\"", p->opaque);
22007 }
22008
22009
22010 if (!ast_strlen_zero(p->qop))
22011 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);
22012 else
22013 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);
22014
22015 append_history(p, "AuthResp", "Auth response sent for %s in realm %s - nc %d", username, p->realm, p->noncecount);
22016
22017 if (credentials) {
22018 ao2_t_ref(credentials, -1, "Unref auth for digest");
22019 }
22020 return 0;
22021 }
22022
22023
22024 static int func_header_read(struct ast_channel *chan, const char *function, char *data, char *buf, size_t len)
22025 {
22026 struct sip_pvt *p;
22027 const char *content = NULL;
22028 AST_DECLARE_APP_ARGS(args,
22029 AST_APP_ARG(header);
22030 AST_APP_ARG(number);
22031 );
22032 int i, number, start = 0;
22033
22034 if (!chan) {
22035 ast_log(LOG_WARNING, "No channel was provided to %s function.\n", function);
22036 return -1;
22037 }
22038
22039 if (ast_strlen_zero(data)) {
22040 ast_log(LOG_WARNING, "This function requires a header name.\n");
22041 return -1;
22042 }
22043
22044 ast_channel_lock(chan);
22045 if (!IS_SIP_TECH(ast_channel_tech(chan))) {
22046 ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
22047 ast_channel_unlock(chan);
22048 return -1;
22049 }
22050
22051 AST_STANDARD_APP_ARGS(args, data);
22052 if (!args.number) {
22053 number = 1;
22054 } else {
22055 sscanf(args.number, "%30d", &number);
22056 if (number < 1)
22057 number = 1;
22058 }
22059
22060 p = ast_channel_tech_pvt(chan);
22061
22062
22063 if (!p) {
22064 ast_channel_unlock(chan);
22065 return -1;
22066 }
22067
22068 for (i = 0; i < number; i++)
22069 content = __get_header(&p->initreq, args.header, &start);
22070
22071 if (ast_strlen_zero(content)) {
22072 ast_channel_unlock(chan);
22073 return -1;
22074 }
22075
22076 ast_copy_string(buf, content, len);
22077 ast_channel_unlock(chan);
22078
22079 return 0;
22080 }
22081
22082 static struct ast_custom_function sip_header_function = {
22083 .name = "SIP_HEADER",
22084 .read = func_header_read,
22085 };
22086
22087
22088 static int func_check_sipdomain(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
22089 {
22090 if (ast_strlen_zero(data)) {
22091 ast_log(LOG_WARNING, "CHECKSIPDOMAIN requires an argument - A domain name\n");
22092 return -1;
22093 }
22094 if (check_sip_domain(data, NULL, 0))
22095 ast_copy_string(buf, data, len);
22096 else
22097 buf[0] = '\0';
22098 return 0;
22099 }
22100
22101 static struct ast_custom_function checksipdomain_function = {
22102 .name = "CHECKSIPDOMAIN",
22103 .read = func_check_sipdomain,
22104 };
22105
22106
22107 static int function_sippeer(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
22108 {
22109 struct sip_peer *peer;
22110 char *colname;
22111
22112 if ((colname = strchr(data, ':'))) {
22113 static int deprecation_warning = 0;
22114 *colname++ = '\0';
22115 if (deprecation_warning++ % 10 == 0)
22116 ast_log(LOG_WARNING, "SIPPEER(): usage of ':' to separate arguments is deprecated. Please use ',' instead.\n");
22117 } else if ((colname = strchr(data, ',')))
22118 *colname++ = '\0';
22119 else
22120 colname = "ip";
22121
22122 if (!(peer = sip_find_peer(data, NULL, TRUE, FINDPEERS, FALSE, 0)))
22123 return -1;
22124
22125 if (!strcasecmp(colname, "ip")) {
22126 ast_copy_string(buf, ast_sockaddr_stringify_addr(&peer->addr), len);
22127 } else if (!strcasecmp(colname, "port")) {
22128 snprintf(buf, len, "%d", ast_sockaddr_port(&peer->addr));
22129 } else if (!strcasecmp(colname, "status")) {
22130 peer_status(peer, buf, len);
22131 } else if (!strcasecmp(colname, "language")) {
22132 ast_copy_string(buf, peer->language, len);
22133 } else if (!strcasecmp(colname, "regexten")) {
22134 ast_copy_string(buf, peer->regexten, len);
22135 } else if (!strcasecmp(colname, "limit")) {
22136 snprintf(buf, len, "%d", peer->call_limit);
22137 } else if (!strcasecmp(colname, "busylevel")) {
22138 snprintf(buf, len, "%d", peer->busy_level);
22139 } else if (!strcasecmp(colname, "curcalls")) {
22140 snprintf(buf, len, "%d", peer->inuse);
22141 } else if (!strcasecmp(colname, "maxforwards")) {
22142 snprintf(buf, len, "%d", peer->maxforwards);
22143 } else if (!strcasecmp(colname, "accountcode")) {
22144 ast_copy_string(buf, peer->accountcode, len);
22145 } else if (!strcasecmp(colname, "callgroup")) {
22146 ast_print_group(buf, len, peer->callgroup);
22147 } else if (!strcasecmp(colname, "pickupgroup")) {
22148 ast_print_group(buf, len, peer->pickupgroup);
22149 } else if (!strcasecmp(colname, "namedcallgroup")) {
22150 struct ast_str *tmp_str = ast_str_create(1024);
22151 if (tmp_str) {
22152 ast_copy_string(buf, ast_print_namedgroups(&tmp_str, peer->named_callgroups), len);
22153 ast_free(tmp_str);
22154 }
22155 } else if (!strcasecmp(colname, "namedpickupgroup")) {
22156 struct ast_str *tmp_str = ast_str_create(1024);
22157 if (tmp_str) {
22158 ast_copy_string(buf, ast_print_namedgroups(&tmp_str, peer->named_pickupgroups), len);
22159 ast_free(tmp_str);
22160 }
22161 } else if (!strcasecmp(colname, "useragent")) {
22162 ast_copy_string(buf, peer->useragent, len);
22163 } else if (!strcasecmp(colname, "mailbox")) {
22164 struct ast_str *mailbox_str = ast_str_alloca(512);
22165 peer_mailboxes_to_str(&mailbox_str, peer);
22166 ast_copy_string(buf, ast_str_buffer(mailbox_str), len);
22167 } else if (!strcasecmp(colname, "context")) {
22168 ast_copy_string(buf, peer->context, len);
22169 } else if (!strcasecmp(colname, "expire")) {
22170 snprintf(buf, len, "%d", peer->expire);
22171 } else if (!strcasecmp(colname, "dynamic")) {
22172 ast_copy_string(buf, peer->host_dynamic ? "yes" : "no", len);
22173 } else if (!strcasecmp(colname, "callerid_name")) {
22174 ast_copy_string(buf, peer->cid_name, len);
22175 } else if (!strcasecmp(colname, "callerid_num")) {
22176 ast_copy_string(buf, peer->cid_num, len);
22177 } else if (!strcasecmp(colname, "codecs")) {
22178 ast_getformatname_multiple(buf, len -1, peer->caps);
22179 } else if (!strcasecmp(colname, "encryption")) {
22180 snprintf(buf, len, "%d", ast_test_flag(&peer->flags[1], SIP_PAGE2_USE_SRTP));
22181 } else if (!strncasecmp(colname, "chanvar[", 8)) {
22182 char *chanvar=colname + 8;
22183 struct ast_variable *v;
22184
22185 chanvar = strsep(&chanvar, "]");
22186 for (v = peer->chanvars ; v ; v = v->next) {
22187 if (!strcasecmp(v->name, chanvar)) {
22188 ast_copy_string(buf, v->value, len);
22189 }
22190 }
22191 } else if (!strncasecmp(colname, "codec[", 6)) {
22192 char *codecnum;
22193 struct ast_format codec;
22194
22195 codecnum = colname + 6;
22196 codecnum = strsep(&codecnum, "]");
22197 if((ast_codec_pref_index(&peer->prefs, atoi(codecnum), &codec))) {
22198 ast_copy_string(buf, ast_getformatname(&codec), len);
22199 } else {
22200 buf[0] = '\0';
22201 }
22202 } else {
22203 buf[0] = '\0';
22204 }
22205
22206 sip_unref_peer(peer, "sip_unref_peer from function_sippeer, just before return");
22207
22208 return 0;
22209 }
22210
22211
22212 static struct ast_custom_function sippeer_function = {
22213 .name = "SIPPEER",
22214 .read = function_sippeer,
22215 };
22216
22217
22218 static int function_sipchaninfo_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
22219 {
22220 struct sip_pvt *p;
22221 static int deprecated = 0;
22222
22223 *buf = 0;
22224
22225 if (!chan) {
22226 ast_log(LOG_WARNING, "No channel was provided to %s function.\n", cmd);
22227 return -1;
22228 }
22229
22230 if (!data) {
22231 ast_log(LOG_WARNING, "This function requires a parameter name.\n");
22232 return -1;
22233 }
22234
22235 ast_channel_lock(chan);
22236 if (!IS_SIP_TECH(ast_channel_tech(chan))) {
22237 ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
22238 ast_channel_unlock(chan);
22239 return -1;
22240 }
22241
22242 if (deprecated++ % 20 == 0) {
22243
22244 ast_log(LOG_WARNING, "SIPCHANINFO() is deprecated. Please transition to using CHANNEL().\n");
22245 }
22246
22247 p = ast_channel_tech_pvt(chan);
22248
22249
22250 if (!p) {
22251 ast_channel_unlock(chan);
22252 return -1;
22253 }
22254
22255 if (!strcasecmp(data, "peerip")) {
22256 ast_copy_string(buf, ast_sockaddr_stringify_addr(&p->sa), len);
22257 } else if (!strcasecmp(data, "recvip")) {
22258 ast_copy_string(buf, ast_sockaddr_stringify_addr(&p->recv), len);
22259 } else if (!strcasecmp(data, "from")) {
22260 ast_copy_string(buf, p->from, len);
22261 } else if (!strcasecmp(data, "uri")) {
22262 ast_copy_string(buf, p->uri, len);
22263 } else if (!strcasecmp(data, "useragent")) {
22264 ast_copy_string(buf, p->useragent, len);
22265 } else if (!strcasecmp(data, "peername")) {
22266 ast_copy_string(buf, p->peername, len);
22267 } else if (!strcasecmp(data, "t38passthrough")) {
22268 if ((p->t38.state == T38_DISABLED) || (p->t38.state == T38_REJECTED)) {
22269 ast_copy_string(buf, "0", len);
22270 } else {
22271 ast_copy_string(buf, "1", len);
22272 }
22273 } else {
22274 ast_channel_unlock(chan);
22275 return -1;
22276 }
22277 ast_channel_unlock(chan);
22278
22279 return 0;
22280 }
22281
22282
22283 static struct ast_custom_function sipchaninfo_function = {
22284 .name = "SIPCHANINFO",
22285 .read = function_sipchaninfo_read,
22286 };
22287
22288
22289
22290
22291 static void change_redirecting_information(struct sip_pvt *p, struct sip_request *req,
22292 struct ast_party_redirecting *redirecting,
22293 struct ast_set_party_redirecting *update_redirecting, int set_call_forward)
22294 {
22295 char *redirecting_from_name = NULL;
22296 char *redirecting_from_number = NULL;
22297 char *redirecting_to_name = NULL;
22298 char *redirecting_to_number = NULL;
22299 int reason = AST_REDIRECTING_REASON_UNCONDITIONAL;
22300 int is_response = req->method == SIP_RESPONSE;
22301 int res = 0;
22302
22303 res = get_rdnis(p, req, &redirecting_from_name, &redirecting_from_number, &reason);
22304 if (res == -1) {
22305 if (is_response) {
22306 get_name_and_number(sip_get_header(req, "TO"), &redirecting_from_name, &redirecting_from_number);
22307 } else {
22308 return;
22309 }
22310 }
22311
22312
22313
22314
22315
22316 if (is_response) {
22317 parse_moved_contact(p, req, &redirecting_to_name, &redirecting_to_number, set_call_forward);
22318 } else {
22319 get_name_and_number(sip_get_header(req, "TO"), &redirecting_to_name, &redirecting_to_number);
22320 }
22321
22322 if (!ast_strlen_zero(redirecting_from_number)) {
22323 ast_debug(3, "Got redirecting from number %s\n", redirecting_from_number);
22324 update_redirecting->from.number = 1;
22325 redirecting->from.number.valid = 1;
22326 ast_free(redirecting->from.number.str);
22327 redirecting->from.number.str = redirecting_from_number;
22328 }
22329 if (!ast_strlen_zero(redirecting_from_name)) {
22330 ast_debug(3, "Got redirecting from name %s\n", redirecting_from_name);
22331 update_redirecting->from.name = 1;
22332 redirecting->from.name.valid = 1;
22333 ast_free(redirecting->from.name.str);
22334 redirecting->from.name.str = redirecting_from_name;
22335 }
22336 if (!ast_strlen_zero(p->cid_tag)) {
22337 ast_free(redirecting->from.tag);
22338 redirecting->from.tag = ast_strdup(p->cid_tag);
22339 ast_free(redirecting->to.tag);
22340 redirecting->to.tag = ast_strdup(p->cid_tag);
22341 }
22342 if (!ast_strlen_zero(redirecting_to_number)) {
22343 ast_debug(3, "Got redirecting to number %s\n", redirecting_to_number);
22344 update_redirecting->to.number = 1;
22345 redirecting->to.number.valid = 1;
22346 ast_free(redirecting->to.number.str);
22347 redirecting->to.number.str = redirecting_to_number;
22348 }
22349 if (!ast_strlen_zero(redirecting_to_name)) {
22350 ast_debug(3, "Got redirecting to name %s\n", redirecting_from_number);
22351 update_redirecting->to.name = 1;
22352 redirecting->to.name.valid = 1;
22353 ast_free(redirecting->to.name.str);
22354 redirecting->to.name.str = redirecting_to_name;
22355 }
22356 redirecting->reason = reason;
22357 }
22358
22359
22360
22361
22362
22363
22364
22365 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req, char **name, char **number, int set_call_forward)
22366 {
22367 char contact[SIPBUFSIZE];
22368 char *contact_name = NULL;
22369 char *contact_number = NULL;
22370 char *separator, *trans;
22371 char *domain;
22372 enum sip_transport transport = SIP_TRANSPORT_UDP;
22373
22374 ast_copy_string(contact, sip_get_header(req, "Contact"), sizeof(contact));
22375 if ((separator = strchr(contact, ',')))
22376 *separator = '\0';
22377
22378 contact_number = get_in_brackets(contact);
22379 if ((trans = strcasestr(contact_number, ";transport="))) {
22380 trans += 11;
22381
22382 if ((separator = strchr(trans, ';')))
22383 *separator = '\0';
22384
22385 if (!strncasecmp(trans, "tcp", 3))
22386 transport = SIP_TRANSPORT_TCP;
22387 else if (!strncasecmp(trans, "tls", 3))
22388 transport = SIP_TRANSPORT_TLS;
22389 else {
22390 if (strncasecmp(trans, "udp", 3))
22391 ast_debug(1, "received contact with an invalid transport, '%s'\n", contact_number);
22392
22393 transport = SIP_TRANSPORT_UDP;
22394 }
22395 }
22396 contact_number = remove_uri_parameters(contact_number);
22397
22398 if (p->socket.tcptls_session) {
22399 ao2_ref(p->socket.tcptls_session, -1);
22400 p->socket.tcptls_session = NULL;
22401 } else if (p->socket.ws_session) {
22402 ast_websocket_unref(p->socket.ws_session);
22403 p->socket.ws_session = NULL;
22404 }
22405
22406 set_socket_transport(&p->socket, transport);
22407
22408 if (set_call_forward && ast_test_flag(&p->flags[0], SIP_PROMISCREDIR)) {
22409 char *host = NULL;
22410 if (!strncasecmp(contact_number, "sip:", 4))
22411 contact_number += 4;
22412 else if (!strncasecmp(contact_number, "sips:", 5))
22413 contact_number += 5;
22414 separator = strchr(contact_number, '/');
22415 if (separator)
22416 *separator = '\0';
22417 if ((host = strchr(contact_number, '@'))) {
22418 *host++ = '\0';
22419 ast_debug(2, "Found promiscuous redirection to 'SIP/%s::::%s@%s'\n", contact_number, sip_get_transport(transport), host);
22420 if (p->owner)
22421 ast_channel_call_forward_build(p->owner, "SIP/%s::::%s@%s", contact_number, sip_get_transport(transport), host);
22422 } else {
22423 ast_debug(2, "Found promiscuous redirection to 'SIP/::::%s@%s'\n", sip_get_transport(transport), contact_number);
22424 if (p->owner)
22425 ast_channel_call_forward_build(p->owner, "SIP/::::%s@%s", sip_get_transport(transport), contact_number);
22426 }
22427 } else {
22428 separator = strchr(contact, '@');
22429 if (separator) {
22430 *separator++ = '\0';
22431 domain = separator;
22432 } else {
22433
22434 domain = contact;
22435 }
22436 separator = strchr(contact, '/');
22437 if (separator)
22438 *separator = '\0';
22439
22440 if (!strncasecmp(contact_number, "sip:", 4))
22441 contact_number += 4;
22442 else if (!strncasecmp(contact_number, "sips:", 5))
22443 contact_number += 5;
22444 separator = strchr(contact_number, ';');
22445 if (separator)
22446 *separator = '\0';
22447 ast_uri_decode(contact_number, ast_uri_sip_user);
22448 if (set_call_forward) {
22449 ast_debug(2, "Received 302 Redirect to extension '%s' (domain %s)\n", contact_number, domain);
22450 if (p->owner) {
22451 pbx_builtin_setvar_helper(p->owner, "SIPDOMAIN", domain);
22452 ast_channel_call_forward_set(p->owner, contact_number);
22453 }
22454 }
22455 }
22456
22457
22458
22459 if (*contact == '\"') {
22460 contact_name = contact + 1;
22461 if (!(separator = (char *)find_closing_quote(contact_name, NULL))) {
22462 ast_log(LOG_NOTICE, "No closing quote on name in Contact header? %s\n", contact);
22463 }
22464 *separator = '\0';
22465 }
22466
22467 if (name && !ast_strlen_zero(contact_name)) {
22468 *name = ast_strdup(contact_name);
22469 }
22470 if (number) {
22471 *number = ast_strdup(contact_number);
22472 }
22473 }
22474
22475
22476
22477
22478
22479
22480 static void check_pendings(struct sip_pvt *p)
22481 {
22482 if (ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
22483 if (p->reinviteid > -1) {
22484
22485 return;
22486 } else if (p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA) {
22487
22488 p->invitestate = INV_CANCELLED;
22489 transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
22490
22491 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
22492 ast_clear_flag(&p->flags[0], SIP_PENDINGBYE);
22493 }
22494
22495
22496 } else {
22497
22498
22499
22500 if (p->pendinginvite && !p->ongoing_reinvite)
22501 return;
22502
22503 if (p->owner) {
22504 ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
22505 }
22506
22507 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, TRUE);
22508 ast_clear_flag(&p->flags[0], SIP_PENDINGBYE);
22509 }
22510 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22511 } else if (ast_test_flag(&p->flags[0], SIP_NEEDREINVITE)) {
22512
22513 if (p->pendinginvite || p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA || p->waitid > 0) {
22514 ast_debug(2, "NOT Sending pending reinvite (yet) on '%s'\n", p->callid);
22515 } else {
22516 ast_debug(2, "Sending pending reinvite on '%s'\n", p->callid);
22517
22518 transmit_reinvite_with_sdp(p, (p->t38.state == T38_LOCAL_REINVITE ? TRUE : FALSE), FALSE);
22519 ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);
22520 }
22521 }
22522 }
22523
22524
22525
22526
22527
22528 static int sip_reinvite_retry(const void *data)
22529 {
22530 struct sip_pvt *p = (struct sip_pvt *) data;
22531 struct ast_channel *owner;
22532
22533 sip_pvt_lock(p);
22534 while ((owner = p->owner) && ast_channel_trylock(owner)) {
22535 sip_pvt_unlock(p);
22536 usleep(1);
22537 sip_pvt_lock(p);
22538 }
22539 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
22540 p->waitid = -1;
22541 check_pendings(p);
22542 sip_pvt_unlock(p);
22543 if (owner) {
22544 ast_channel_unlock(owner);
22545 }
22546 dialog_unref(p, "unref the dialog ptr from sip_reinvite_retry, because it held a dialog ptr");
22547 return 0;
22548 }
22549
22550
22551
22552
22553
22554
22555 static void handle_response_update(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
22556 {
22557 if (p->options) {
22558 p->options->auth_type = (resp == 401 ? WWW_AUTH : PROXY_AUTH);
22559 }
22560 if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp, SIP_UPDATE, 1)) {
22561 ast_log(LOG_NOTICE, "Failed to authenticate on UPDATE to '%s'\n", sip_get_header(&p->initreq, "From"));
22562 }
22563 }
22564
22565 static void cc_handle_publish_error(struct sip_pvt *pvt, const int resp, struct sip_request *req, struct sip_epa_entry *epa_entry)
22566 {
22567 struct cc_epa_entry *cc_entry = epa_entry->instance_data;
22568 struct sip_monitor_instance *monitor_instance = ao2_callback(sip_monitor_instances, 0,
22569 find_sip_monitor_instance_by_suspension_entry, epa_entry);
22570 const char *min_expires;
22571
22572 if (!monitor_instance) {
22573 ast_log(LOG_WARNING, "Can't find monitor_instance corresponding to epa_entry %p.\n", epa_entry);
22574 return;
22575 }
22576
22577 if (resp != 423) {
22578 ast_cc_monitor_failed(cc_entry->core_id, monitor_instance->device_name,
22579 "Received error response to our PUBLISH");
22580 ao2_ref(monitor_instance, -1);
22581 return;
22582 }
22583
22584
22585
22586
22587
22588
22589
22590
22591
22592 min_expires = sip_get_header(req, "Min-Expires");
22593 if (ast_strlen_zero(min_expires)) {
22594 pvt->expiry *= 2;
22595 if (pvt->expiry < 0) {
22596
22597 ast_cc_monitor_failed(cc_entry->core_id, monitor_instance->device_name,
22598 "PUBLISH expiry overflowed");
22599 ao2_ref(monitor_instance, -1);
22600 return;
22601 }
22602 } else if (sscanf(min_expires, "%30d", &pvt->expiry) != 1) {
22603 ast_cc_monitor_failed(cc_entry->core_id, monitor_instance->device_name,
22604 "Min-Expires has non-numeric value");
22605 ao2_ref(monitor_instance, -1);
22606 return;
22607 }
22608
22609
22610
22611 transmit_invite(pvt, SIP_PUBLISH, FALSE, 0, NULL);
22612 ao2_ref(monitor_instance, -1);
22613 }
22614
22615 static void handle_response_publish(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
22616 {
22617 struct sip_epa_entry *epa_entry = p->epa_entry;
22618 const char *etag = sip_get_header(req, "Sip-ETag");
22619
22620 ast_assert(epa_entry != NULL);
22621
22622 if (resp == 401 || resp == 407) {
22623 ast_string_field_set(p, theirtag, NULL);
22624 if (p->options) {
22625 p->options->auth_type = (resp == 401 ? WWW_AUTH : PROXY_AUTH);
22626 }
22627 if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp, SIP_PUBLISH, 0)) {
22628 ast_log(LOG_NOTICE, "Failed to authenticate on PUBLISH to '%s'\n", sip_get_header(&p->initreq, "From"));
22629 pvt_set_needdestroy(p, "Failed to authenticate on PUBLISH");
22630 sip_alreadygone(p);
22631 }
22632 return;
22633 }
22634
22635 if (resp == 501 || resp == 405) {
22636 mark_method_unallowed(&p->allowed_methods, SIP_PUBLISH);
22637 }
22638
22639 if (resp == 200) {
22640 p->authtries = 0;
22641
22642
22643
22644 if (!ast_strlen_zero(etag)) {
22645 ast_copy_string(epa_entry->entity_tag, etag, sizeof(epa_entry->entity_tag));
22646 }
22647
22648
22649
22650
22651 if (epa_entry->static_data->handle_ok) {
22652 epa_entry->static_data->handle_ok(p, req, epa_entry);
22653 }
22654 } else {
22655
22656
22657
22658
22659 if (epa_entry->static_data->handle_error) {
22660 epa_entry->static_data->handle_error(p, resp, req, epa_entry);
22661 }
22662 }
22663 }
22664
22665
22666
22667
22668
22669
22670
22671
22672
22673
22674
22675
22676 static void sip_queue_hangup_cause(struct sip_pvt *p, int cause)
22677 {
22678 struct ast_channel *owner = p->owner;
22679 const char *name = ast_strdupa(ast_channel_name(owner));
22680
22681
22682 ast_channel_ref(owner);
22683 ast_channel_unlock(owner);
22684 sip_pvt_unlock(p);
22685 ast_set_hangupsource(owner, name, 0);
22686 if (cause) {
22687 ast_queue_hangup_with_cause(owner, cause);
22688 } else {
22689 ast_queue_hangup(owner);
22690 }
22691 ast_channel_unref(owner);
22692
22693
22694 owner = sip_pvt_lock_full(p);
22695 if (owner) {
22696 ast_channel_unref(owner);
22697 }
22698 }
22699
22700
22701 static void handle_response_invite(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
22702 {
22703 int outgoing = ast_test_flag(&p->flags[0], SIP_OUTGOING);
22704 int res = 0;
22705 int xmitres = 0;
22706 int reinvite = ast_test_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
22707 char *p_hdrval;
22708 int rtn;
22709 struct ast_party_connected_line connected;
22710 struct ast_set_party_connected_line update_connected;
22711
22712 if (reinvite) {
22713 ast_debug(4, "SIP response %d to RE-invite on %s call %s\n", resp, outgoing ? "outgoing" : "incoming", p->callid);
22714 } else {
22715 ast_debug(4, "SIP response %d to standard invite\n", resp);
22716 }
22717
22718 if (p->alreadygone) {
22719 ast_debug(1, "Got response on call that is already terminated: %s (ignoring)\n", p->callid);
22720 return;
22721 }
22722
22723
22724
22725 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"));
22726
22727
22728
22729
22730 if (resp > 100 && resp < 200 && resp!=101 && resp != 180 && resp != 181 && resp != 182 && resp != 183) {
22731 resp = 183;
22732 }
22733
22734
22735 if ((resp >= 200) && (resp < 300)) {
22736 resp = 200;
22737 }
22738
22739
22740 if (resp >= 100 && resp < 200 && p->invitestate == INV_CALLING) {
22741 p->invitestate = INV_PROCEEDING;
22742 }
22743
22744
22745 if (resp >= 300 && (p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA )) {
22746 p->invitestate = INV_COMPLETED;
22747 }
22748
22749 if ((resp >= 200 && reinvite)) {
22750 p->ongoing_reinvite = 0;
22751 if (p->reinviteid > -1) {
22752 AST_SCHED_DEL_UNREF(sched, p->reinviteid, dialog_unref(p, "unref dialog for reinvite timeout because of a final response"));
22753 }
22754 }
22755
22756
22757 if ((resp == 200 || resp >= 300) && p->pendinginvite && seqno == p->pendinginvite) {
22758 p->pendinginvite = 0;
22759 }
22760
22761
22762
22763
22764 if (!reinvite) {
22765 set_pvt_allowed_methods(p, req);
22766 }
22767
22768 switch (resp) {
22769 case 100:
22770 case 101:
22771 if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p)) {
22772 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
22773 }
22774 check_pendings(p);
22775 break;
22776
22777 case 180:
22778 case 182:
22779 if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p)) {
22780 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
22781 }
22782
22783
22784
22785 parse_ok_contact(p, req);
22786 if (!reinvite) {
22787 build_route(p, req, 1, resp);
22788 }
22789 if (!req->ignore && p->owner) {
22790 if (get_rpid(p, req)) {
22791
22792 ast_party_connected_line_init(&connected);
22793 memset(&update_connected, 0, sizeof(update_connected));
22794
22795 update_connected.id.number = 1;
22796 connected.id.number.valid = 1;
22797 connected.id.number.str = (char *) p->cid_num;
22798 connected.id.number.presentation = p->callingpres;
22799
22800 update_connected.id.name = 1;
22801 connected.id.name.valid = 1;
22802 connected.id.name.str = (char *) p->cid_name;
22803 connected.id.name.presentation = p->callingpres;
22804
22805
22806 ast_set_party_id_all(&update_connected.priv);
22807
22808 connected.id.tag = (char *) p->cid_tag;
22809 connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
22810 ast_channel_queue_connected_line_update(p->owner, &connected,
22811 &update_connected);
22812 }
22813 sip_handle_cc(p, req, AST_CC_CCNR);
22814 ast_queue_control(p->owner, AST_CONTROL_RINGING);
22815 if (ast_channel_state(p->owner) != AST_STATE_UP) {
22816 ast_setstate(p->owner, AST_STATE_RINGING);
22817 }
22818 }
22819 if (find_sdp(req)) {
22820 if (p->invitestate != INV_CANCELLED) {
22821 p->invitestate = INV_EARLY_MEDIA;
22822 }
22823 res = process_sdp(p, req, SDP_T38_NONE);
22824 if (!req->ignore && p->owner) {
22825
22826 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
22827 }
22828 ast_rtp_instance_activate(p->rtp);
22829 }
22830 check_pendings(p);
22831 break;
22832
22833 case 181:
22834 if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
22835 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
22836
22837
22838
22839 parse_ok_contact(p, req);
22840 if (!reinvite) {
22841 build_route(p, req, 1, resp);
22842 }
22843 if (!req->ignore && p->owner) {
22844 struct ast_party_redirecting redirecting;
22845 struct ast_set_party_redirecting update_redirecting;
22846
22847 ast_party_redirecting_init(&redirecting);
22848 memset(&update_redirecting, 0, sizeof(update_redirecting));
22849 change_redirecting_information(p, req, &redirecting, &update_redirecting,
22850 FALSE);
22851
22852
22853 ast_set_party_id_all(&update_redirecting.priv_orig);
22854 ast_set_party_id_all(&update_redirecting.priv_from);
22855 ast_set_party_id_all(&update_redirecting.priv_to);
22856
22857 ast_channel_queue_redirecting_update(p->owner, &redirecting,
22858 &update_redirecting);
22859 ast_party_redirecting_free(&redirecting);
22860 sip_handle_cc(p, req, AST_CC_CCNR);
22861 }
22862 check_pendings(p);
22863 break;
22864
22865 case 183:
22866 if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p)) {
22867 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
22868 }
22869
22870
22871
22872 parse_ok_contact(p, req);
22873 if (!reinvite) {
22874 build_route(p, req, 1, resp);
22875 }
22876 if (!req->ignore && p->owner) {
22877 if (get_rpid(p, req)) {
22878
22879 ast_party_connected_line_init(&connected);
22880 memset(&update_connected, 0, sizeof(update_connected));
22881
22882 update_connected.id.number = 1;
22883 connected.id.number.valid = 1;
22884 connected.id.number.str = (char *) p->cid_num;
22885 connected.id.number.presentation = p->callingpres;
22886
22887 update_connected.id.name = 1;
22888 connected.id.name.valid = 1;
22889 connected.id.name.str = (char *) p->cid_name;
22890 connected.id.name.presentation = p->callingpres;
22891
22892
22893 ast_set_party_id_all(&update_connected.priv);
22894
22895 connected.id.tag = (char *) p->cid_tag;
22896 connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
22897 ast_channel_queue_connected_line_update(p->owner, &connected,
22898 &update_connected);
22899 }
22900 sip_handle_cc(p, req, AST_CC_CCNR);
22901 }
22902 if (find_sdp(req)) {
22903 if (p->invitestate != INV_CANCELLED) {
22904 p->invitestate = INV_EARLY_MEDIA;
22905 }
22906 res = process_sdp(p, req, SDP_T38_NONE);
22907 if (!req->ignore && p->owner) {
22908
22909 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
22910 }
22911 ast_rtp_instance_activate(p->rtp);
22912 } else {
22913
22914
22915
22916
22917 if (!req->ignore && p->owner) {
22918 ast_queue_control(p->owner, AST_CONTROL_RINGING);
22919 }
22920 }
22921 check_pendings(p);
22922 break;
22923
22924 case 200:
22925 if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p)) {
22926 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
22927 }
22928 p->authtries = 0;
22929 if (find_sdp(req)) {
22930 if ((res = process_sdp(p, req, SDP_T38_ACCEPT)) && !req->ignore) {
22931 if (!reinvite) {
22932
22933
22934 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
22935 p->hangupcause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
22936 if (p->owner) {
22937 ast_channel_hangupcause_set(p->owner, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
22938 sip_queue_hangup_cause(p, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
22939 }
22940 }
22941 }
22942 ast_rtp_instance_activate(p->rtp);
22943 } else if (!reinvite) {
22944 struct ast_sockaddr remote_address = {{0,}};
22945
22946 ast_rtp_instance_get_remote_address(p->rtp, &remote_address);
22947 if (ast_sockaddr_isnull(&remote_address) || (!ast_strlen_zero(p->theirprovtag) && strcmp(p->theirtag, p->theirprovtag))) {
22948 ast_log(LOG_WARNING, "Received response: \"200 OK\" from '%s' without SDP\n", p->relatedpeer->name);
22949 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
22950 ast_rtp_instance_activate(p->rtp);
22951 }
22952 }
22953
22954 if (!req->ignore && p->owner) {
22955 int rpid_changed;
22956
22957 rpid_changed = get_rpid(p, req);
22958 if (rpid_changed || !reinvite) {
22959
22960 ast_party_connected_line_init(&connected);
22961 memset(&update_connected, 0, sizeof(update_connected));
22962 if (rpid_changed
22963 || !ast_strlen_zero(p->cid_num)
22964 || (p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
22965 update_connected.id.number = 1;
22966 connected.id.number.valid = 1;
22967 connected.id.number.str = (char *) p->cid_num;
22968 connected.id.number.presentation = p->callingpres;
22969 }
22970 if (rpid_changed
22971 || !ast_strlen_zero(p->cid_name)
22972 || (p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
22973 update_connected.id.name = 1;
22974 connected.id.name.valid = 1;
22975 connected.id.name.str = (char *) p->cid_name;
22976 connected.id.name.presentation = p->callingpres;
22977 }
22978 if (update_connected.id.number || update_connected.id.name) {
22979
22980 ast_set_party_id_all(&update_connected.priv);
22981
22982 connected.id.tag = (char *) p->cid_tag;
22983 connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
22984 ast_channel_queue_connected_line_update(p->owner, &connected,
22985 &update_connected);
22986 }
22987 }
22988 }
22989
22990
22991
22992
22993 if (outgoing) {
22994 update_call_counter(p, DEC_CALL_RINGING);
22995 parse_ok_contact(p, req);
22996
22997 if (!reinvite) {
22998 build_route(p, req, 1, resp);
22999 }
23000 if(set_address_from_contact(p)) {
23001
23002
23003 if (!p->route && !req->ignore) {
23004 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
23005 }
23006 }
23007
23008 }
23009
23010 if (!req->ignore && p->owner) {
23011 if (!reinvite && !res) {
23012 ast_queue_control(p->owner, AST_CONTROL_ANSWER);
23013 if (sip_cfg.callevents) {
23014 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
23015 "Channel: %s\r\nChanneltype: %s\r\nUniqueid: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
23016 ast_channel_name(p->owner), "SIP", ast_channel_uniqueid(p->owner), p->callid, p->fullcontact, p->peername);
23017 }
23018 } else {
23019 if (p->t38.state == T38_DISABLED || p->t38.state == T38_REJECTED) {
23020 ast_queue_control(p->owner, AST_CONTROL_UPDATE_RTP_PEER);
23021 } else {
23022 ast_queue_frame(p->owner, &ast_null_frame);
23023 }
23024 }
23025 } else {
23026
23027
23028
23029 if (!req->ignore) {
23030 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
23031 }
23032 }
23033
23034
23035 if (st_get_mode(p, 0) != SESSION_TIMER_MODE_REFUSE) {
23036 p_hdrval = (char*)sip_get_header(req, "Session-Expires");
23037 if (!ast_strlen_zero(p_hdrval)) {
23038
23039 enum st_refresher_param st_ref_param;
23040 int tmp_st_interval = 0;
23041 rtn = parse_session_expires(p_hdrval, &tmp_st_interval, &st_ref_param);
23042 if (rtn != 0) {
23043 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
23044 } else if (tmp_st_interval < st_get_se(p, FALSE)) {
23045 ast_log(LOG_WARNING, "Got Session-Expires less than local Min-SE in 200 OK, tearing down call\n");
23046 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
23047 }
23048 if (st_ref_param == SESSION_TIMER_REFRESHER_PARAM_UAC) {
23049 p->stimer->st_ref = SESSION_TIMER_REFRESHER_US;
23050 } else if (st_ref_param == SESSION_TIMER_REFRESHER_PARAM_UAS) {
23051 p->stimer->st_ref = SESSION_TIMER_REFRESHER_THEM;
23052 } else {
23053 ast_log(LOG_WARNING, "Unknown refresher on %s\n", p->callid);
23054 }
23055 if (tmp_st_interval) {
23056 p->stimer->st_interval = tmp_st_interval;
23057 }
23058 p->stimer->st_active = TRUE;
23059 p->stimer->st_active_peer_ua = TRUE;
23060 start_session_timer(p);
23061 } else {
23062
23063 if (st_get_mode(p, 0) == SESSION_TIMER_MODE_ORIGINATE) {
23064 p->stimer->st_ref = SESSION_TIMER_REFRESHER_US;
23065 p->stimer->st_active_peer_ua = FALSE;
23066 start_session_timer(p);
23067 }
23068 }
23069 }
23070
23071
23072
23073 p->invitestate = INV_TERMINATED;
23074 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
23075 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, TRUE);
23076 check_pendings(p);
23077 break;
23078
23079 case 407:
23080 case 401:
23081
23082 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
23083 if (p->options) {
23084 p->options->auth_type = resp;
23085 }
23086
23087
23088 ast_string_field_set(p, theirtag, NULL);
23089 if (!req->ignore) {
23090 if (p->authtries < MAX_AUTHTRIES) {
23091 p->invitestate = INV_CALLING;
23092 }
23093 if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, SIP_INVITE, 1)) {
23094 ast_log(LOG_NOTICE, "Failed to authenticate on INVITE to '%s'\n", sip_get_header(&p->initreq, "From"));
23095 pvt_set_needdestroy(p, "failed to authenticate on INVITE");
23096 sip_alreadygone(p);
23097 if (p->owner) {
23098 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
23099 }
23100 }
23101 }
23102 break;
23103
23104 case 403:
23105
23106 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
23107 ast_log(LOG_WARNING, "Received response: \"Forbidden\" from '%s'\n", sip_get_header(&p->initreq, "From"));
23108 if (!req->ignore && p->owner) {
23109 sip_queue_hangup_cause(p, hangup_sip2cause(resp));
23110 }
23111 break;
23112
23113 case 404:
23114 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
23115 if (p->owner && !req->ignore) {
23116 sip_queue_hangup_cause(p, hangup_sip2cause(resp));
23117 }
23118 break;
23119
23120 case 481:
23121
23122 ast_log(LOG_WARNING, "Re-invite to non-existing call leg on other UA. SIP dialog '%s'. Giving up.\n", p->callid);
23123 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
23124 if (p->owner) {
23125 ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
23126 }
23127 break;
23128
23129 case 422:
23130 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
23131 ast_string_field_set(p, theirtag, NULL);
23132 proc_422_rsp(p, req);
23133 break;
23134
23135 case 428:
23136 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
23137 append_history(p, "Identity", "SIP identity is required. Not supported by Asterisk.");
23138 ast_log(LOG_WARNING, "SIP identity required by proxy. SIP dialog '%s'. Giving up.\n", p->callid);
23139 if (p->owner && !req->ignore) {
23140 ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
23141 }
23142 break;
23143
23144 case 487:
23145
23146
23147
23148 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
23149 if (p->owner && !req->ignore) {
23150 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_NORMAL_CLEARING);
23151 append_history(p, "Hangup", "Got 487 on CANCEL request from us. Queued AST hangup request");
23152 } else if (!req->ignore) {
23153 update_call_counter(p, DEC_CALL_LIMIT);
23154 append_history(p, "Hangup", "Got 487 on CANCEL request from us on call without owner. Killing this dialog.");
23155 }
23156 check_pendings(p);
23157 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
23158 break;
23159 case 415:
23160 case 488:
23161 case 606:
23162 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
23163 if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
23164 change_t38_state(p, T38_REJECTED);
23165
23166
23167
23168
23169
23170 transmit_reinvite_with_sdp(p, FALSE, FALSE);
23171 } else {
23172
23173 if (p->owner && !req->ignore) {
23174 ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
23175 }
23176 }
23177 break;
23178 case 491:
23179 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
23180 if (p->owner && !req->ignore) {
23181 if (ast_channel_state(p->owner) != AST_STATE_UP) {
23182 ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
23183 } else {
23184
23185
23186
23187 int wait;
23188
23189
23190 if (p->outgoing_call) {
23191 wait = 2100 + ast_random() % 2000;
23192 } else {
23193 wait = ast_random() % 2000;
23194 }
23195 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."));
23196 ast_debug(2, "Reinvite race. Scheduled sip_reinvite_retry in %d secs in handle_response_invite (waitid %d, dialog '%s')\n",
23197 wait, p->waitid, p->callid);
23198 }
23199 }
23200 break;
23201
23202 case 408:
23203 case 405:
23204 case 501:
23205 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
23206 if (p->owner) {
23207 ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
23208 }
23209 break;
23210 }
23211 if (xmitres == XMIT_ERROR) {
23212 ast_log(LOG_WARNING, "Could not transmit message in dialog %s\n", p->callid);
23213 }
23214 }
23215
23216
23217
23218
23219 static void handle_response_notify(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
23220 {
23221 switch (resp) {
23222 case 200:
23223
23224 if (p->owner) {
23225 if (p->refer) {
23226 ast_log(LOG_NOTICE, "Got OK on REFER Notify message\n");
23227 } else {
23228 ast_log(LOG_WARNING, "Notify answer on an owned channel? - %s\n", ast_channel_name(p->owner));
23229 }
23230 } else {
23231 if (p->subscribed == NONE && !p->refer) {
23232 ast_debug(4, "Got 200 accepted on NOTIFY %s\n", p->callid);
23233 pvt_set_needdestroy(p, "received 200 response");
23234 }
23235 if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
23236 struct state_notify_data data = {
23237 .state = p->laststate,
23238 .device_state_info = p->last_device_state_info,
23239 .presence_state = p->last_presence_state,
23240 .presence_subtype = p->last_presence_subtype,
23241 .presence_message = p->last_presence_message,
23242 };
23243
23244 ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
23245 extensionstate_update(p->context, p->exten, &data, p, TRUE);
23246 }
23247 }
23248 break;
23249 case 401:
23250 case 407:
23251 if (!p->notify) {
23252 break;
23253 }
23254 ast_string_field_set(p, theirtag, NULL);
23255 if (ast_strlen_zero(p->authname)) {
23256 ast_log(LOG_WARNING, "Asked to authenticate NOTIFY to %s but we have no matching peer or realm auth!\n", ast_sockaddr_stringify(&p->recv));
23257 pvt_set_needdestroy(p, "unable to authenticate NOTIFY");
23258 }
23259 if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_NOTIFY, 0)) {
23260 ast_log(LOG_NOTICE, "Failed to authenticate on NOTIFY to '%s'\n", sip_get_header(&p->initreq, "From"));
23261 pvt_set_needdestroy(p, "failed to authenticate NOTIFY");
23262 }
23263 break;
23264 case 481:
23265 pvt_set_needdestroy(p, "Received 481 response for NOTIFY");
23266 break;
23267 }
23268 }
23269
23270
23271 static void handle_response_subscribe(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
23272 {
23273 if (p->subscribed == CALL_COMPLETION) {
23274 struct sip_monitor_instance *monitor_instance;
23275
23276 if (resp < 300) {
23277 return;
23278 }
23279
23280
23281 monitor_instance = ao2_callback(sip_monitor_instances, 0,
23282 find_sip_monitor_instance_by_subscription_pvt, p);
23283 if (monitor_instance) {
23284 ast_cc_monitor_failed(monitor_instance->core_id,
23285 monitor_instance->device_name,
23286 "Received error response to our SUBSCRIBE");
23287 }
23288 return;
23289 }
23290
23291 if (p->subscribed != MWI_NOTIFICATION) {
23292 return;
23293 }
23294 if (!p->mwi) {
23295 return;
23296 }
23297
23298 switch (resp) {
23299 case 200:
23300 ast_debug(3, "Got 200 OK on subscription for MWI\n");
23301 set_pvt_allowed_methods(p, req);
23302 if (p->options) {
23303 if (p->options->outboundproxy) {
23304 ao2_ref(p->options->outboundproxy, -1);
23305 }
23306 ast_free(p->options);
23307 p->options = NULL;
23308 }
23309 p->mwi->subscribed = 1;
23310 if ((p->mwi->resub = ast_sched_add(sched, mwi_expiry * 1000, sip_subscribe_mwi_do, ASTOBJ_REF(p->mwi))) < 0) {
23311 ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
23312 }
23313 break;
23314 case 401:
23315 case 407:
23316 ast_string_field_set(p, theirtag, NULL);
23317 if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_SUBSCRIBE, 0)) {
23318 ast_log(LOG_NOTICE, "Failed to authenticate on SUBSCRIBE to '%s'\n", sip_get_header(&p->initreq, "From"));
23319 p->mwi->call = NULL;
23320 ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
23321 pvt_set_needdestroy(p, "failed to authenticate SUBSCRIBE");
23322 }
23323 break;
23324 case 403:
23325 transmit_response_with_date(p, "200 OK", req);
23326 ast_log(LOG_WARNING, "Authentication failed while trying to subscribe for MWI.\n");
23327 p->mwi->call = NULL;
23328 ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
23329 pvt_set_needdestroy(p, "received 403 response");
23330 sip_alreadygone(p);
23331 break;
23332 case 404:
23333 ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side said that a mailbox may not have been configured.\n");
23334 p->mwi->call = NULL;
23335 ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
23336 pvt_set_needdestroy(p, "received 404 response");
23337 break;
23338 case 481:
23339 ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side said that our dialog did not exist.\n");
23340 p->mwi->call = NULL;
23341 ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
23342 pvt_set_needdestroy(p, "received 481 response");
23343 break;
23344 case 500:
23345 case 501:
23346 ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side may have suffered a heart attack.\n");
23347 p->mwi->call = NULL;
23348 ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
23349 pvt_set_needdestroy(p, "received 500/501 response");
23350 break;
23351 }
23352 }
23353
23354
23355
23356
23357 static void handle_response_refer(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
23358 {
23359 enum ast_control_transfer message = AST_TRANSFER_FAILED;
23360
23361
23362 if (!p->refer)
23363 return;
23364
23365 switch (resp) {
23366 case 202:
23367
23368
23369 p->refer->status = REFER_ACCEPTED;
23370
23371 ast_debug(3, "Got 202 accepted on transfer\n");
23372
23373 break;
23374
23375 case 401:
23376 case 407:
23377 if (ast_strlen_zero(p->authname)) {
23378 ast_log(LOG_WARNING, "Asked to authenticate REFER to %s but we have no matching peer or realm auth!\n",
23379 ast_sockaddr_stringify(&p->recv));
23380 if (p->owner) {
23381 ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
23382 }
23383 pvt_set_needdestroy(p, "unable to authenticate REFER");
23384 }
23385 if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_REFER, 0)) {
23386 ast_log(LOG_NOTICE, "Failed to authenticate on REFER to '%s'\n", sip_get_header(&p->initreq, "From"));
23387 p->refer->status = REFER_NOAUTH;
23388 if (p->owner) {
23389 ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
23390 }
23391 pvt_set_needdestroy(p, "failed to authenticate REFER");
23392 }
23393 break;
23394
23395 case 405:
23396
23397
23398 ast_log(LOG_NOTICE, "SIP transfer to %s failed, REFER not allowed. \n", p->refer->refer_to);
23399 pvt_set_needdestroy(p, "received 405 response");
23400 p->refer->status = REFER_FAILED;
23401 if (p->owner) {
23402 ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
23403 }
23404 break;
23405
23406 case 481:
23407
23408
23409
23410
23411 ast_log(LOG_WARNING, "Remote host can't match REFER request to call '%s'. Giving up.\n", p->callid);
23412 if (p->owner)
23413 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
23414 pvt_set_needdestroy(p, "received 481 response");
23415 break;
23416
23417 case 500:
23418 case 501:
23419
23420
23421 ast_log(LOG_NOTICE, "SIP transfer to %s failed, call miserably fails. \n", p->refer->refer_to);
23422 pvt_set_needdestroy(p, "received 500/501 response");
23423 p->refer->status = REFER_FAILED;
23424 if (p->owner) {
23425 ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
23426 }
23427 break;
23428 case 603:
23429 ast_log(LOG_NOTICE, "SIP transfer to %s declined, call miserably fails. \n", p->refer->refer_to);
23430 p->refer->status = REFER_FAILED;
23431 pvt_set_needdestroy(p, "received 603 response");
23432 if (p->owner) {
23433 ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
23434 }
23435 break;
23436 default:
23437
23438
23439
23440
23441 if (resp < 299) {
23442 ast_log(LOG_WARNING, "SIP transfer to %s had unxpected 2xx response (%d), confusion is possible. \n", p->refer->refer_to, resp);
23443 } else {
23444 ast_log(LOG_WARNING, "SIP transfer to %s with response (%d). \n", p->refer->refer_to, resp);
23445 }
23446
23447 p->refer->status = REFER_FAILED;
23448 pvt_set_needdestroy(p, "received failure response");
23449 if (p->owner) {
23450 ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
23451 }
23452 break;
23453 }
23454 }
23455
23456
23457 static int handle_response_register(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
23458 {
23459 int expires, expires_ms;
23460 struct sip_registry *r;
23461 r=p->registry;
23462
23463 switch (resp) {
23464 case 401:
23465 if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
23466 ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s@%s' (Tries %d)\n", p->registry->username, p->registry->hostname, p->authtries);
23467 pvt_set_needdestroy(p, "failed to authenticate REGISTER");
23468 }
23469 break;
23470 case 403:
23471 if (global_reg_retry_403) {
23472 ast_log(LOG_NOTICE, "Treating 403 response to REGISTER as non-fatal for %s@%s\n",
23473 p->registry->username, p->registry->hostname);
23474 ast_string_field_set(r, nonce, "");
23475 ast_string_field_set(p, nonce, "");
23476 break;
23477 }
23478 ast_log(LOG_WARNING, "Forbidden - wrong password on authentication for REGISTER for '%s' to '%s'\n", p->registry->username, p->registry->hostname);
23479 AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 403"));
23480 r->regstate = REG_STATE_NOAUTH;
23481 pvt_set_needdestroy(p, "received 403 response");
23482 break;
23483 case 404:
23484 ast_log(LOG_WARNING, "Got 404 Not found on SIP register to service %s@%s, giving up\n", p->registry->username, p->registry->hostname);
23485 pvt_set_needdestroy(p, "received 404 response");
23486 if (r->call)
23487 r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 404");
23488 r->regstate = REG_STATE_REJECTED;
23489 AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 404"));
23490 break;
23491 case 407:
23492 if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
23493 ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s' (tries '%d')\n", sip_get_header(&p->initreq, "From"), p->authtries);
23494 pvt_set_needdestroy(p, "failed to authenticate REGISTER");
23495 }
23496 break;
23497 case 408:
23498
23499 if (r) {
23500 r->regattempts = 0;
23501 } else {
23502 ast_log(LOG_WARNING, "Got a 408 response to our REGISTER on call %s after we had destroyed the registry object\n", p->callid);
23503 }
23504 break;
23505 case 423:
23506 r->expiry = atoi(sip_get_header(req, "Min-Expires"));
23507 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);
23508 AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 423"));
23509 if (r->call) {
23510 r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 423");
23511 pvt_set_needdestroy(p, "received 423 response");
23512 }
23513 if (r->expiry > max_expiry) {
23514 ast_log(LOG_WARNING, "Required expiration time from %s@%s is too high, giving up\n", p->registry->username, p->registry->hostname);
23515 r->expiry = r->configured_expiry;
23516 r->regstate = REG_STATE_REJECTED;
23517 } else {
23518 r->regstate = REG_STATE_UNREGISTERED;
23519 transmit_register(r, SIP_REGISTER, NULL, NULL);
23520 }
23521 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));
23522 break;
23523 case 479:
23524 ast_log(LOG_WARNING, "Got error 479 on register to %s@%s, giving up (check config)\n", p->registry->username, p->registry->hostname);
23525 pvt_set_needdestroy(p, "received 479 response");
23526 if (r->call)
23527 r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 479");
23528 r->regstate = REG_STATE_REJECTED;
23529 AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 479"));
23530 break;
23531 case 200:
23532 if (!r) {
23533 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));
23534 pvt_set_needdestroy(p, "received erroneous 200 response");
23535 return 0;
23536 }
23537
23538 r->regstate = REG_STATE_REGISTERED;
23539 r->regtime = ast_tvnow();
23540 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));
23541 r->regattempts = 0;
23542 ast_debug(1, "Registration successful\n");
23543 if (r->timeout > -1) {
23544 ast_debug(1, "Cancelling timeout %d\n", r->timeout);
23545 }
23546 AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 200"));
23547 if (r->call)
23548 r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 200");
23549 p->registry = registry_unref(p->registry, "unref registry entry p->registry");
23550
23551
23552 pvt_set_needdestroy(p, "Registration successfull");
23553
23554
23555
23556
23557
23558 expires = 0;
23559
23560
23561 if (!ast_strlen_zero(sip_get_header(req, "Contact"))) {
23562 const char *contact = NULL;
23563 const char *tmptmp = NULL;
23564 int start = 0;
23565 for(;;) {
23566 contact = __get_header(req, "Contact", &start);
23567
23568 if(!ast_strlen_zero(contact)) {
23569 if( (tmptmp=strstr(contact, p->our_contact))) {
23570 contact=tmptmp;
23571 break;
23572 }
23573 } else
23574 break;
23575 }
23576 tmptmp = strcasestr(contact, "expires=");
23577 if (tmptmp) {
23578 if (sscanf(tmptmp + 8, "%30d", &expires) != 1) {
23579 expires = 0;
23580 }
23581 }
23582
23583 }
23584 if (!expires)
23585 expires=atoi(sip_get_header(req, "expires"));
23586 if (!expires)
23587 expires=default_expiry;
23588
23589 expires_ms = expires * 1000;
23590 if (expires <= EXPIRY_GUARD_LIMIT)
23591 expires_ms -= MAX((expires_ms * EXPIRY_GUARD_PCT), EXPIRY_GUARD_MIN);
23592 else
23593 expires_ms -= EXPIRY_GUARD_SECS * 1000;
23594 if (sipdebug)
23595 ast_log(LOG_NOTICE, "Outbound Registration: Expiry for %s is %d sec (Scheduling reregistration in %d s)\n", r->hostname, expires, expires_ms/1000);
23596
23597 r->refresh= (int) expires_ms / 1000;
23598
23599
23600 AST_SCHED_REPLACE_UNREF(r->expire, sched, expires_ms, sip_reregister, r,
23601 registry_unref(_data,"unref in REPLACE del fail"),
23602 registry_unref(r,"unref in REPLACE add fail"),
23603 registry_addref(r,"The Addition side of REPLACE"));
23604 }
23605 return 1;
23606 }
23607
23608
23609 static void handle_response_peerpoke(struct sip_pvt *p, int resp, struct sip_request *req)
23610 {
23611 struct sip_peer *peer = p->relatedpeer ;
23612 int statechanged, is_reachable, was_reachable;
23613 int pingtime = ast_tvdiff_ms(ast_tvnow(), peer->ps);
23614
23615
23616
23617
23618
23619
23620 if (pingtime < 1) {
23621 pingtime = 1;
23622 }
23623
23624 if (!peer->maxms) {
23625 pvt_set_needdestroy(p, "got OPTIONS response but qualify is not enabled");
23626 return;
23627 }
23628
23629
23630
23631
23632
23633 was_reachable = peer->lastms > 0 && peer->lastms <= peer->maxms;
23634 is_reachable = pingtime <= peer->maxms;
23635 statechanged = peer->lastms == 0
23636 || was_reachable != is_reachable;
23637
23638 peer->lastms = pingtime;
23639 peer->call = dialog_unref(peer->call, "unref dialog peer->call");
23640 if (statechanged) {
23641 const char *s = is_reachable ? "Reachable" : "Lagged";
23642 char str_lastms[20];
23643 snprintf(str_lastms, sizeof(str_lastms), "%d", pingtime);
23644
23645 ast_log(LOG_NOTICE, "Peer '%s' is now %s. (%dms / %dms)\n",
23646 peer->name, s, pingtime, peer->maxms);
23647 ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "SIP/%s", peer->name);
23648 if (sip_cfg.peer_rtupdate) {
23649 ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", str_lastms, SENTINEL);
23650 }
23651 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
23652 "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: %s\r\nTime: %d\r\n",
23653 peer->name, s, pingtime);
23654 if (is_reachable && sip_cfg.regextenonqualify)
23655 register_peer_exten(peer, TRUE);
23656 }
23657
23658 pvt_set_needdestroy(p, "got OPTIONS response");
23659
23660
23661 AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
23662 is_reachable ? peer->qualifyfreq : DEFAULT_FREQ_NOTOK,
23663 sip_poke_peer_s, peer,
23664 sip_unref_peer(_data, "removing poke peer ref"),
23665 sip_unref_peer(peer, "removing poke peer ref"),
23666 sip_ref_peer(peer, "adding poke peer ref"));
23667 }
23668
23669
23670
23671
23672
23673
23674
23675
23676 static void handle_response_info(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
23677 {
23678 int sipmethod = SIP_INFO;
23679
23680 switch (resp) {
23681 case 401:
23682 case 407:
23683 ast_log(LOG_WARNING, "Host '%s' requests authentication (%d) for '%s'\n",
23684 ast_sockaddr_stringify(&p->sa), resp, sip_methods[sipmethod].text);
23685 break;
23686 case 405:
23687 case 501:
23688 mark_method_unallowed(&p->allowed_methods, sipmethod);
23689 if (p->relatedpeer) {
23690 mark_method_allowed(&p->relatedpeer->disallowed_methods, sipmethod);
23691 }
23692 ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n",
23693 ast_sockaddr_stringify(&p->sa), sip_methods[sipmethod].text);
23694 break;
23695 default:
23696 if (300 <= resp && resp < 700) {
23697 ast_verb(3, "Got SIP %s response %d \"%s\" back from host '%s'\n",
23698 sip_methods[sipmethod].text, resp, rest, ast_sockaddr_stringify(&p->sa));
23699 }
23700 break;
23701 }
23702 }
23703
23704
23705
23706
23707
23708
23709 static int do_message_auth(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
23710 {
23711 char *header;
23712 char *respheader;
23713 char digest[1024];
23714
23715 if (p->options) {
23716 p->options->auth_type = (resp == 401 ? WWW_AUTH : PROXY_AUTH);
23717 }
23718
23719 if (p->authtries == MAX_AUTHTRIES) {
23720 ast_log(LOG_NOTICE, "Failed to authenticate MESSAGE with host '%s'\n",
23721 ast_sockaddr_stringify(&p->sa));
23722 return -1;
23723 }
23724
23725 ++p->authtries;
23726 sip_auth_headers((resp == 401 ? WWW_AUTH : PROXY_AUTH), &header, &respheader);
23727 memset(digest, 0, sizeof(digest));
23728 if (reply_digest(p, req, header, SIP_MESSAGE, digest, sizeof(digest))) {
23729
23730 ast_debug(1, "Nothing to use for MESSAGE authentication\n");
23731 return -1;
23732 }
23733
23734 if (p->do_history) {
23735 append_history(p, "MessageAuth", "Try: %d", p->authtries);
23736 }
23737
23738 transmit_message(p, 0, 1);
23739 return 0;
23740 }
23741
23742
23743
23744
23745
23746
23747
23748
23749
23750 static void handle_response_message(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
23751 {
23752 int sipmethod = SIP_MESSAGE;
23753 int in_dialog = ast_test_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
23754
23755 switch (resp) {
23756 case 401:
23757 case 407:
23758 if (do_message_auth(p, resp, rest, req, seqno) && !in_dialog) {
23759 pvt_set_needdestroy(p, "MESSAGE authentication failed");
23760 }
23761 break;
23762 case 405:
23763 case 501:
23764 mark_method_unallowed(&p->allowed_methods, sipmethod);
23765 if (p->relatedpeer) {
23766 mark_method_allowed(&p->relatedpeer->disallowed_methods, sipmethod);
23767 }
23768 ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n",
23769 ast_sockaddr_stringify(&p->sa), sip_methods[sipmethod].text);
23770 if (!in_dialog) {
23771 pvt_set_needdestroy(p, "MESSAGE not implemented or allowed");
23772 }
23773 break;
23774 default:
23775 if (100 <= resp && resp < 200) {
23776
23777 } else if (200 <= resp && resp < 300) {
23778 p->authtries = 0;
23779 if (!in_dialog) {
23780 pvt_set_needdestroy(p, "MESSAGE delivery accepted");
23781 }
23782 } else if (300 <= resp && resp < 700) {
23783 ast_verb(3, "Got SIP %s response %d \"%s\" back from host '%s'\n",
23784 sip_methods[sipmethod].text, resp, rest, ast_sockaddr_stringify(&p->sa));
23785 if (!in_dialog) {
23786 pvt_set_needdestroy(p, (300 <= resp && resp < 600)
23787 ? "MESSAGE delivery failed" : "MESSAGE delivery refused");
23788 }
23789 }
23790 break;
23791 }
23792 }
23793
23794
23795 static void stop_media_flows(struct sip_pvt *p)
23796 {
23797
23798 if (p->rtp)
23799 ast_rtp_instance_stop(p->rtp);
23800 if (p->vrtp)
23801 ast_rtp_instance_stop(p->vrtp);
23802 if (p->trtp)
23803 ast_rtp_instance_stop(p->trtp);
23804 if (p->udptl)
23805 ast_udptl_stop(p->udptl);
23806 }
23807
23808
23809
23810 static void handle_response(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
23811 {
23812 struct ast_channel *owner;
23813 int sipmethod;
23814 const char *c = sip_get_header(req, "Cseq");
23815
23816 char *c_copy = ast_strdupa(c);
23817
23818 const char *msg = ast_skip_blanks(ast_skip_nonblanks(c_copy));
23819
23820 if (!msg)
23821 msg = "";
23822
23823 sipmethod = find_sip_method(msg);
23824
23825 owner = p->owner;
23826 if (owner) {
23827 const char *rp = NULL, *rh = NULL;
23828
23829 ast_channel_hangupcause_set(owner, 0);
23830 if (ast_test_flag(&p->flags[1], SIP_PAGE2_Q850_REASON) && (rh = sip_get_header(req, "Reason"))) {
23831 rh = ast_skip_blanks(rh);
23832 if (!strncasecmp(rh, "Q.850", 5)) {
23833 int cause = ast_channel_hangupcause(owner);
23834 rp = strstr(rh, "cause=");
23835 if (rp && sscanf(rp + 6, "%30d", &cause) == 1) {
23836 ast_channel_hangupcause_set(owner, cause & 0x7f);
23837 if (req->debug)
23838 ast_verbose("Using Reason header for cause code: %d\n", ast_channel_hangupcause(owner));
23839 }
23840 }
23841 }
23842
23843 if (!ast_channel_hangupcause(owner))
23844 ast_channel_hangupcause_set(owner, hangup_sip2cause(resp));
23845 }
23846
23847 if (p->socket.type == SIP_TRANSPORT_UDP) {
23848 int ack_res = FALSE;
23849
23850
23851 if ((resp >= 100) && (resp <= 199)) {
23852
23853 if (sipmethod == SIP_INVITE) {
23854 ack_res = __sip_semi_ack(p, seqno, 0, sipmethod);
23855 }
23856 } else {
23857 ack_res = __sip_ack(p, seqno, 0, sipmethod);
23858 }
23859
23860 if (ack_res == FALSE) {
23861
23862 if (sipmethod == SIP_INVITE && resp >= 200) {
23863 transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, resp < 300 ? TRUE: FALSE);
23864 }
23865
23866 append_history(p, "Ignore", "Ignoring this retransmit\n");
23867 return;
23868 }
23869 }
23870
23871
23872 if (!p->owner && sipmethod == SIP_NOTIFY && p->pendinginvite) {
23873 p->pendinginvite = 0;
23874 }
23875
23876
23877 if (ast_strlen_zero(p->theirtag) || (resp >= 200)) {
23878 char tag[128];
23879
23880 gettag(req, "To", tag, sizeof(tag));
23881 ast_string_field_set(p, theirtag, tag);
23882 } else {
23883
23884 ast_string_field_set(p, theirprovtag, p->theirtag);
23885 }
23886
23887
23888
23889
23890
23891
23892
23893
23894
23895
23896
23897
23898
23899
23900
23901
23902 if ((resp == 404 || resp == 408 || resp == 481) && sipmethod == SIP_BYE) {
23903 pvt_set_needdestroy(p, "received 4XX response to a BYE");
23904 return;
23905 }
23906
23907 if (p->relatedpeer && sipmethod == SIP_OPTIONS) {
23908
23909
23910
23911 if (resp != 100)
23912 handle_response_peerpoke(p, resp, req);
23913 } else if (sipmethod == SIP_REFER && resp >= 200) {
23914 handle_response_refer(p, resp, rest, req, seqno);
23915 } else if (sipmethod == SIP_PUBLISH) {
23916
23917
23918
23919 handle_response_publish(p, resp, rest, req, seqno);
23920 } else if (sipmethod == SIP_INFO) {
23921
23922 handle_response_info(p, resp, rest, req, seqno);
23923 } else if (sipmethod == SIP_MESSAGE) {
23924
23925 handle_response_message(p, resp, rest, req, seqno);
23926 } else if (sipmethod == SIP_NOTIFY) {
23927
23928 handle_response_notify(p, resp, rest, req, seqno);
23929 } else if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
23930 switch(resp) {
23931 case 100:
23932 case 101:
23933 case 183:
23934 case 180:
23935 case 182:
23936 case 181:
23937 if (sipmethod == SIP_INVITE)
23938 handle_response_invite(p, resp, rest, req, seqno);
23939 break;
23940 case 200:
23941 p->authtries = 0;
23942 if (sipmethod == SIP_INVITE) {
23943 handle_response_invite(p, resp, rest, req, seqno);
23944 } else if (sipmethod == SIP_REGISTER) {
23945 handle_response_register(p, resp, rest, req, seqno);
23946 } else if (sipmethod == SIP_SUBSCRIBE) {
23947 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
23948 handle_response_subscribe(p, resp, rest, req, seqno);
23949 } else if (sipmethod == SIP_BYE) {
23950 pvt_set_needdestroy(p, "received 200 response");
23951 ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
23952 }
23953 break;
23954 case 401:
23955 case 407:
23956 if (sipmethod == SIP_INVITE)
23957 handle_response_invite(p, resp, rest, req, seqno);
23958 else if (sipmethod == SIP_SUBSCRIBE)
23959 handle_response_subscribe(p, resp, rest, req, seqno);
23960 else if (p->registry && sipmethod == SIP_REGISTER)
23961 handle_response_register(p, resp, rest, req, seqno);
23962 else if (sipmethod == SIP_UPDATE) {
23963 handle_response_update(p, resp, rest, req, seqno);
23964 } else if (sipmethod == SIP_BYE) {
23965 if (p->options)
23966 p->options->auth_type = resp;
23967 if (ast_strlen_zero(p->authname)) {
23968 ast_log(LOG_WARNING, "Asked to authenticate %s, to %s but we have no matching peer!\n",
23969 msg, ast_sockaddr_stringify(&p->recv));
23970 pvt_set_needdestroy(p, "unable to authenticate BYE");
23971 } else if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp, sipmethod, 0)) {
23972 ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, sip_get_header(&p->initreq, "From"));
23973 pvt_set_needdestroy(p, "failed to authenticate BYE");
23974 }
23975 } else {
23976 ast_log(LOG_WARNING, "Got authentication request (%d) on %s to '%s'\n", resp, sip_methods[sipmethod].text, sip_get_header(req, "To"));
23977 pvt_set_needdestroy(p, "received 407 response");
23978 }
23979 break;
23980 case 403:
23981 if (sipmethod == SIP_INVITE)
23982 handle_response_invite(p, resp, rest, req, seqno);
23983 else if (sipmethod == SIP_SUBSCRIBE)
23984 handle_response_subscribe(p, resp, rest, req, seqno);
23985 else if (p->registry && sipmethod == SIP_REGISTER)
23986 handle_response_register(p, resp, rest, req, seqno);
23987 else {
23988 ast_log(LOG_WARNING, "Forbidden - maybe wrong password on authentication for %s\n", msg);
23989 pvt_set_needdestroy(p, "received 403 response");
23990 }
23991 break;
23992 case 404:
23993 if (p->registry && sipmethod == SIP_REGISTER)
23994 handle_response_register(p, resp, rest, req, seqno);
23995 else if (sipmethod == SIP_INVITE)
23996 handle_response_invite(p, resp, rest, req, seqno);
23997 else if (sipmethod == SIP_SUBSCRIBE)
23998 handle_response_subscribe(p, resp, rest, req, seqno);
23999 else if (owner)
24000 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
24001 break;
24002 case 423:
24003 if (sipmethod == SIP_REGISTER)
24004 handle_response_register(p, resp, rest, req, seqno);
24005 break;
24006 case 408:
24007 if (sipmethod == SIP_INVITE)
24008 handle_response_invite(p, resp, rest, req, seqno);
24009 else if (sipmethod == SIP_REGISTER)
24010 handle_response_register(p, resp, rest, req, seqno);
24011 else if (sipmethod == SIP_BYE) {
24012 pvt_set_needdestroy(p, "received 408 response");
24013 ast_debug(4, "Got timeout on bye. Thanks for the answer. Now, kill this call\n");
24014 } else {
24015 if (owner)
24016 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
24017 pvt_set_needdestroy(p, "received 408 response");
24018 }
24019 break;
24020
24021 case 428:
24022 case 422:
24023 if (sipmethod == SIP_INVITE) {
24024 handle_response_invite(p, resp, rest, req, seqno);
24025 }
24026 break;
24027
24028 case 481:
24029 if (sipmethod == SIP_INVITE) {
24030 handle_response_invite(p, resp, rest, req, seqno);
24031 } else if (sipmethod == SIP_SUBSCRIBE) {
24032 handle_response_subscribe(p, resp, rest, req, seqno);
24033 } else if (sipmethod == SIP_BYE) {
24034
24035
24036 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
24037 } else if (sipmethod == SIP_CANCEL) {
24038
24039
24040 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
24041 } else {
24042 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
24043
24044 }
24045 break;
24046 case 487:
24047 if (sipmethod == SIP_INVITE)
24048 handle_response_invite(p, resp, rest, req, seqno);
24049 break;
24050 case 415:
24051 case 488:
24052 case 606:
24053 if (sipmethod == SIP_INVITE)
24054 handle_response_invite(p, resp, rest, req, seqno);
24055 break;
24056 case 491:
24057 if (sipmethod == SIP_INVITE)
24058 handle_response_invite(p, resp, rest, req, seqno);
24059 else {
24060 ast_debug(1, "Got 491 on %s, unsupported. Call ID %s\n", sip_methods[sipmethod].text, p->callid);
24061 pvt_set_needdestroy(p, "received 491 response");
24062 }
24063 break;
24064 case 405:
24065 case 501:
24066 mark_method_unallowed(&p->allowed_methods, sipmethod);
24067 if (p->relatedpeer) {
24068 mark_method_allowed(&p->relatedpeer->disallowed_methods, sipmethod);
24069 }
24070 if (sipmethod == SIP_INVITE)
24071 handle_response_invite(p, resp, rest, req, seqno);
24072 else
24073 ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n", ast_sockaddr_stringify(&p->sa), msg);
24074 break;
24075 default:
24076 if ((resp >= 200) && (resp < 300)) {
24077 if (sipmethod == SIP_INVITE) {
24078 handle_response_invite(p, resp, rest, req, seqno);
24079 }
24080 } else if ((resp >= 300) && (resp < 700)) {
24081
24082 if ((resp != 487))
24083 ast_verb(3, "Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_sockaddr_stringify(&p->sa));
24084
24085 if (sipmethod == SIP_INVITE)
24086 stop_media_flows(p);
24087
24088
24089 switch(resp) {
24090 case 300:
24091 case 301:
24092 case 302:
24093 case 305:
24094 if (p->owner) {
24095 struct ast_party_redirecting redirecting;
24096 struct ast_set_party_redirecting update_redirecting;
24097
24098 ast_party_redirecting_init(&redirecting);
24099 memset(&update_redirecting, 0, sizeof(update_redirecting));
24100 change_redirecting_information(p, req, &redirecting,
24101 &update_redirecting, TRUE);
24102 ast_channel_set_redirecting(p->owner, &redirecting,
24103 &update_redirecting);
24104 ast_party_redirecting_free(&redirecting);
24105 }
24106
24107 case 486:
24108 case 600:
24109 case 603:
24110 if (p->owner) {
24111 sip_handle_cc(p, req, AST_CC_CCBS);
24112 ast_queue_control(p->owner, AST_CONTROL_BUSY);
24113 }
24114 break;
24115 case 482:
24116 case 480:
24117 case 404:
24118 case 410:
24119 case 400:
24120 case 500:
24121 if (sipmethod == SIP_SUBSCRIBE) {
24122 handle_response_subscribe(p, resp, rest, req, seqno);
24123 break;
24124 }
24125
24126 case 502:
24127 case 503:
24128 case 504:
24129 if (owner)
24130 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
24131 break;
24132 case 484:
24133 if (owner && sipmethod != SIP_BYE) {
24134 switch (ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP)) {
24135 case SIP_PAGE2_ALLOWOVERLAP_YES:
24136 ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
24137 break;
24138 default:
24139 ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(404));
24140 break;
24141 }
24142 }
24143 break;
24144 default:
24145
24146 if (owner && sipmethod != SIP_BYE)
24147 ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
24148 break;
24149 }
24150
24151 if (sipmethod == SIP_INVITE)
24152 transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
24153 sip_alreadygone(p);
24154 if (!p->owner) {
24155 pvt_set_needdestroy(p, "transaction completed");
24156 }
24157 } else if ((resp >= 100) && (resp < 200)) {
24158 if (sipmethod == SIP_INVITE) {
24159 if (!req->ignore && sip_cancel_destroy(p))
24160 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
24161 if (find_sdp(req))
24162 process_sdp(p, req, SDP_T38_NONE);
24163 if (p->owner) {
24164
24165 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
24166 }
24167 }
24168 } else
24169 ast_log(LOG_NOTICE, "Don't know how to handle a %d %s response from %s\n", resp, rest, p->owner ? ast_channel_name(p->owner) : ast_sockaddr_stringify(&p->sa));
24170 }
24171 } else {
24172
24173
24174 if (req->debug)
24175 ast_verbose("SIP Response message for INCOMING dialog %s arrived\n", msg);
24176
24177 if (sipmethod == SIP_INVITE && resp == 200) {
24178
24179
24180 char tag[128];
24181
24182 gettag(req, "To", tag, sizeof(tag));
24183 ast_string_field_set(p, theirtag, tag);
24184 }
24185
24186 switch(resp) {
24187 case 200:
24188 if (sipmethod == SIP_INVITE) {
24189 handle_response_invite(p, resp, rest, req, seqno);
24190 } else if (sipmethod == SIP_CANCEL) {
24191 ast_debug(1, "Got 200 OK on CANCEL\n");
24192
24193
24194 } else if (sipmethod == SIP_BYE) {
24195 pvt_set_needdestroy(p, "transaction completed");
24196 }
24197 break;
24198 case 401:
24199 case 407:
24200 if (sipmethod == SIP_INVITE)
24201 handle_response_invite(p, resp, rest, req, seqno);
24202 else if (sipmethod == SIP_BYE) {
24203 if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, sipmethod, 0)) {
24204 ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, sip_get_header(&p->initreq, "From"));
24205 pvt_set_needdestroy(p, "failed to authenticate BYE");
24206 }
24207 }
24208 break;
24209 case 481:
24210 if (sipmethod == SIP_INVITE) {
24211
24212 handle_response_invite(p, resp, rest, req, seqno);
24213 } else if (sipmethod == SIP_BYE) {
24214 pvt_set_needdestroy(p, "received 481 response");
24215 } else if (sipdebug) {
24216 ast_debug(1, "Remote host can't match request %s to call '%s'. Giving up\n", sip_methods[sipmethod].text, p->callid);
24217 }
24218 break;
24219 case 501:
24220 if (sipmethod == SIP_INVITE)
24221 handle_response_invite(p, resp, rest, req, seqno);
24222 break;
24223 default:
24224 if ((resp >= 100) && (resp < 200)) {
24225 if (sipmethod == SIP_INVITE) {
24226 if (!req->ignore && sip_cancel_destroy(p))
24227 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
24228 }
24229 } else if ((resp >= 200) && (resp < 300)) {
24230 if (sipmethod == SIP_INVITE) {
24231 handle_response_invite(p, resp, rest, req, seqno);
24232 }
24233 } else if ((resp >= 300) && (resp < 700)) {
24234 if ((resp != 487))
24235 ast_verb(3, "Incoming call: Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_sockaddr_stringify(&p->sa));
24236 switch(resp) {
24237 case 415:
24238 case 488:
24239 case 603:
24240 case 500:
24241 case 502:
24242 case 503:
24243 case 504:
24244
24245
24246 if (sipmethod == SIP_INVITE && sip_cancel_destroy(p))
24247 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
24248 break;
24249 }
24250 }
24251 break;
24252 }
24253 }
24254 }
24255
24256
24257
24258
24259
24260
24261
24262 static void *sip_park_thread(void *stuff)
24263 {
24264 struct ast_channel *transferee, *transferer;
24265 struct sip_pvt *transferer_pvt;
24266 struct sip_dual *d;
24267 int ext;
24268 int res;
24269
24270 d = stuff;
24271 transferee = d->chan1;
24272 transferer = d->chan2;
24273 transferer_pvt = ast_channel_tech_pvt(transferer);
24274
24275 ast_debug(4, "SIP Park: Transferer channel %s, Transferee %s\n", ast_channel_name(transferer), ast_channel_name(transferee));
24276
24277 res = ast_park_call_exten(transferee, transferer, d->park_exten, d->park_context, 0, &ext);
24278
24279 sip_pvt_lock(transferer_pvt);
24280 #ifdef WHEN_WE_KNOW_THAT_THE_CLIENT_SUPPORTS_MESSAGE
24281 if (res) {
24282 destroy_msg_headers(transferer_pvt);
24283 ast_string_field_set(transferer_pvt, msg_body, "Unable to park call.");
24284 transmit_message(transferer_pvt, 0, 0);
24285 } else {
24286
24287 destroy_msg_headers(transferer_pvt);
24288 sprintf(buf, "Call parked on extension '%d'.", ext);
24289 ast_string_field_set(transferer_pvt, msg_body, buf);
24290 transmit_message(transferer_pvt, 0, 0);
24291 }
24292 #endif
24293
24294
24295
24296 ast_set_flag(&transferer_pvt->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
24297 if (!res) {
24298
24299 append_history(transferer_pvt, "SIPpark", "Parked call on %d", ext);
24300 transmit_notify_with_sipfrag(transferer_pvt, d->seqno, "200 OK", TRUE);
24301 sip_pvt_unlock(transferer_pvt);
24302 ast_channel_hangupcause_set(transferer, AST_CAUSE_NORMAL_CLEARING);
24303 ast_debug(1, "SIP Call parked on extension '%d'\n", ext);
24304 } else {
24305 transmit_notify_with_sipfrag(transferer_pvt, d->seqno, "503 Service Unavailable", TRUE);
24306 append_history(transferer_pvt, "SIPpark", "Parking failed\n");
24307 sip_pvt_unlock(transferer_pvt);
24308 ast_log(AST_LOG_NOTICE, "SIP Call parked failed for %s\n", ast_channel_name(transferee));
24309 ast_hangup(transferee);
24310 }
24311 ast_hangup(transferer);
24312
24313 deinit_req(&d->req);
24314 ast_free(d->park_exten);
24315 ast_free(d->park_context);
24316 ast_free(d);
24317 return NULL;
24318 }
24319
24320
24321 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, uint32_t seqno, const char *park_exten, const char *park_context)
24322 {
24323 struct sip_dual *d;
24324 struct ast_channel *transferee, *transferer;
24325 pthread_t th;
24326
24327 transferee = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, ast_channel_accountcode(chan1), ast_channel_exten(chan1), ast_channel_context(chan1), ast_channel_linkedid(chan1), ast_channel_amaflags(chan1), "Parking/%s", ast_channel_name(chan1));
24328 transferer = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, ast_channel_accountcode(chan2), ast_channel_exten(chan2), ast_channel_context(chan2), ast_channel_linkedid(chan2), ast_channel_amaflags(chan2), "SIPPeer/%s", ast_channel_name(chan2));
24329 d = ast_calloc(1, sizeof(*d));
24330 if (!transferee || !transferer || !d) {
24331 if (transferee) {
24332 ast_hangup(transferee);
24333 }
24334 if (transferer) {
24335 ast_hangup(transferer);
24336 }
24337 ast_free(d);
24338 return -1;
24339 }
24340 d->park_exten = ast_strdup(park_exten);
24341 d->park_context = ast_strdup(park_context);
24342 if (!d->park_exten || !d->park_context) {
24343 ast_hangup(transferee);
24344 ast_hangup(transferer);
24345 ast_free(d->park_exten);
24346 ast_free(d->park_context);
24347 ast_free(d);
24348 return -1;
24349 }
24350
24351
24352 ast_format_copy(ast_channel_readformat(transferee), ast_channel_readformat(chan1));
24353 ast_format_copy(ast_channel_writeformat(transferee), ast_channel_writeformat(chan1));
24354
24355
24356 if (ast_channel_masquerade(transferee, chan1)) {
24357 ast_hangup(transferee);
24358 ast_hangup(transferer);
24359 ast_free(d->park_exten);
24360 ast_free(d->park_context);
24361 ast_free(d);
24362 return -1;
24363 }
24364
24365
24366 ast_channel_context_set(transferee, ast_channel_context(chan1));
24367 ast_channel_exten_set(transferee, ast_channel_exten(chan1));
24368 ast_channel_priority_set(transferee, ast_channel_priority(chan1));
24369
24370 ast_do_masquerade(transferee);
24371
24372
24373
24374
24375
24376 ast_format_copy(ast_channel_readformat(transferer), ast_channel_readformat(chan2));
24377 ast_format_copy(ast_channel_writeformat(transferer), ast_channel_writeformat(chan2));
24378 ast_channel_parkinglot_set(transferer, ast_channel_parkinglot(chan2));
24379
24380
24381 if (ast_channel_masquerade(transferer, chan2)) {
24382 ast_hangup(transferee);
24383 ast_hangup(transferer);
24384 ast_free(d->park_exten);
24385 ast_free(d->park_context);
24386 ast_free(d);
24387 return -1;
24388 }
24389
24390
24391 ast_channel_context_set(transferer, ast_channel_context(chan2));
24392 ast_channel_exten_set(transferer, ast_channel_exten(chan2));
24393 ast_channel_priority_set(transferer, ast_channel_priority(chan2));
24394
24395 ast_do_masquerade(transferer);
24396
24397
24398 copy_request(&d->req, req);
24399 d->chan1 = transferee;
24400 d->chan2 = transferer;
24401 d->seqno = seqno;
24402 if (ast_pthread_create_detached_background(&th, NULL, sip_park_thread, d) < 0) {
24403
24404 ast_hangup(transferer);
24405 ast_hangup(transferee);
24406 deinit_req(&d->req);
24407 ast_free(d->park_exten);
24408 ast_free(d->park_context);
24409 ast_free(d);
24410
24411 return -1;
24412 }
24413 return 0;
24414 }
24415
24416
24417
24418
24419
24420 static void *sip_pickup_thread(void *stuff)
24421 {
24422 struct ast_channel *chan;
24423 chan = stuff;
24424
24425 if (ast_pickup_call(chan)) {
24426 ast_channel_hangupcause_set(chan, AST_CAUSE_CALL_REJECTED);
24427 } else {
24428 ast_channel_hangupcause_set(chan, AST_CAUSE_NORMAL_CLEARING);
24429 }
24430 ast_hangup(chan);
24431 ast_channel_unref(chan);
24432 chan = NULL;
24433 return NULL;
24434 }
24435
24436
24437
24438
24439 static int sip_pickup(struct ast_channel *chan)
24440 {
24441 pthread_t threadid;
24442
24443 ast_channel_ref(chan);
24444
24445 if (ast_pthread_create_detached_background(&threadid, NULL, sip_pickup_thread, chan)) {
24446 ast_debug(1, "Unable to start Group pickup thread on channel %s\n", ast_channel_name(chan));
24447 ast_channel_unref(chan);
24448 return -1;
24449 }
24450 ast_debug(1, "Started Group pickup thread on channel %s\n", ast_channel_name(chan));
24451 return 0;
24452 }
24453
24454
24455
24456
24457
24458 static void ast_quiet_chan(struct ast_channel *chan)
24459 {
24460 if (chan && ast_channel_state(chan) == AST_STATE_UP) {
24461 if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_MOH))
24462 ast_moh_stop(chan);
24463 else if (ast_channel_generatordata(chan))
24464 ast_deactivate_generator(chan);
24465 }
24466 }
24467
24468
24469
24470 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target)
24471 {
24472 int res = 0;
24473 struct ast_channel *peera = NULL,
24474 *peerb = NULL,
24475 *peerc = NULL,
24476 *peerd = NULL;
24477
24478
24479
24480
24481 ast_debug(4, "Sip transfer:--------------------\n");
24482 if (transferer->chan1)
24483 ast_debug(4, "-- Transferer to PBX channel: %s State %s\n", ast_channel_name(transferer->chan1), ast_state2str(ast_channel_state(transferer->chan1)));
24484 else
24485 ast_debug(4, "-- No transferer first channel - odd??? \n");
24486 if (target->chan1)
24487 ast_debug(4, "-- Transferer to PBX second channel (target): %s State %s\n", ast_channel_name(target->chan1), ast_state2str(ast_channel_state(target->chan1)));
24488 else
24489 ast_debug(4, "-- No target first channel ---\n");
24490 if (transferer->chan2)
24491 ast_debug(4, "-- Bridged call to transferee: %s State %s\n", ast_channel_name(transferer->chan2), ast_state2str(ast_channel_state(transferer->chan2)));
24492 else
24493 ast_debug(4, "-- No bridged call to transferee\n");
24494 if (target->chan2)
24495 ast_debug(4, "-- Bridged call to transfer target: %s State %s\n", target->chan2 ? ast_channel_name(target->chan2) : "<none>", target->chan2 ? ast_state2str(ast_channel_state(target->chan2)) : "(none)");
24496 else
24497 ast_debug(4, "-- No target second channel ---\n");
24498 ast_debug(4, "-- END Sip transfer:--------------------\n");
24499 if (transferer->chan2) {
24500 peera = transferer->chan1;
24501 peerb = target->chan1;
24502 peerc = transferer->chan2;
24503 peerd = target->chan2;
24504 ast_debug(3, "SIP transfer: Four channels to handle\n");
24505 } else if (target->chan2) {
24506 peera = target->chan1;
24507 peerb = transferer->chan1;
24508 peerc = target->chan2;
24509 peerd = transferer->chan2;
24510 ast_debug(3, "SIP transfer: Three channels to handle\n");
24511 }
24512
24513 if (peera && peerb && peerc && (peerb != peerc)) {
24514 ast_quiet_chan(peera);
24515
24516
24517
24518 ast_quiet_chan(peerc);
24519 if (peerd)
24520 ast_quiet_chan(peerd);
24521
24522 ast_debug(4, "SIP transfer: trying to masquerade %s into %s\n", ast_channel_name(peerc), ast_channel_name(peerb));
24523 if (ast_channel_masquerade(peerb, peerc)) {
24524 ast_log(LOG_WARNING, "Failed to masquerade %s into %s\n", ast_channel_name(peerb), ast_channel_name(peerc));
24525 res = -1;
24526 } else
24527 ast_debug(4, "SIP transfer: Succeeded to masquerade channels.\n");
24528 return res;
24529 } else {
24530 ast_log(LOG_NOTICE, "SIP Transfer attempted with no appropriate bridged calls to transfer\n");
24531 if (transferer->chan1)
24532 ast_softhangup_nolock(transferer->chan1, AST_SOFTHANGUP_DEV);
24533 if (target->chan1)
24534 ast_softhangup_nolock(target->chan1, AST_SOFTHANGUP_DEV);
24535 return -1;
24536 }
24537 return 0;
24538 }
24539
24540
24541
24542
24543
24544
24545 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize)
24546 {
24547 const char *thetag;
24548
24549 if (!tagbuf)
24550 return NULL;
24551 tagbuf[0] = '\0';
24552 thetag = sip_get_header(req, header);
24553 thetag = strcasestr(thetag, ";tag=");
24554 if (thetag) {
24555 thetag += 5;
24556 ast_copy_string(tagbuf, thetag, tagbufsize);
24557 return strsep(&tagbuf, ";");
24558 }
24559 return NULL;
24560 }
24561
24562 static int handle_cc_notify(struct sip_pvt *pvt, struct sip_request *req)
24563 {
24564 struct sip_monitor_instance *monitor_instance = ao2_callback(sip_monitor_instances, 0,
24565 find_sip_monitor_instance_by_subscription_pvt, pvt);
24566 const char *status = get_content_line(req, "cc-state", ':');
24567 struct cc_epa_entry *cc_entry;
24568 char *uri;
24569
24570 if (!monitor_instance) {
24571 transmit_response(pvt, "400 Bad Request", req);
24572 return -1;
24573 }
24574
24575 if (ast_strlen_zero(status)) {
24576 ao2_ref(monitor_instance, -1);
24577 transmit_response(pvt, "400 Bad Request", req);
24578 return -1;
24579 }
24580
24581 if (!strcmp(status, "queued")) {
24582
24583
24584
24585
24586 ast_cc_monitor_request_acked(monitor_instance->core_id, "SIP endpoint %s accepted request", monitor_instance->device_name);
24587 transmit_response(pvt, "200 OK", req);
24588 ao2_ref(monitor_instance, -1);
24589 return 0;
24590 }
24591
24592
24593 uri = get_content_line(req, "cc-URI", ':');
24594 if (ast_strlen_zero(uri)) {
24595 uri = get_in_brackets((char *)sip_get_header(req, "From"));
24596 }
24597
24598 ast_string_field_set(monitor_instance, notify_uri, uri);
24599 if (monitor_instance->suspension_entry) {
24600 cc_entry = monitor_instance->suspension_entry->instance_data;
24601 if (cc_entry->current_state == CC_CLOSED) {
24602
24603
24604
24605
24606
24607 construct_pidf_body(CC_CLOSED, monitor_instance->suspension_entry->body,
24608 sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
24609 transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_INITIAL, monitor_instance->notify_uri);
24610 } else {
24611 ast_cc_monitor_callee_available(monitor_instance->core_id, "SIP monitored callee has become available");
24612 }
24613 } else {
24614 ast_cc_monitor_callee_available(monitor_instance->core_id, "SIP monitored callee has become available");
24615 }
24616 ao2_ref(monitor_instance, -1);
24617 transmit_response(pvt, "200 OK", req);
24618
24619 return 0;
24620 }
24621
24622
24623 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e)
24624 {
24625
24626
24627 int res = 0;
24628 const char *event = sip_get_header(req, "Event");
24629 char *sep;
24630
24631 if( (sep = strchr(event, ';')) ) {
24632 *sep++ = '\0';
24633 }
24634
24635 if (sipdebug)
24636 ast_debug(2, "Got NOTIFY Event: %s\n", event);
24637
24638 if (!strcmp(event, "refer")) {
24639
24640
24641
24642
24643 char *buf, *cmd, *code;
24644 int respcode;
24645 int success = TRUE;
24646
24647
24648
24649
24650
24651
24652
24653
24654 if (strncasecmp(sip_get_header(req, "Content-Type"), "message/sipfrag", strlen("message/sipfrag"))) {
24655
24656 transmit_response(p, "400 Bad request", req);
24657 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
24658 return -1;
24659 }
24660
24661
24662 if (ast_strlen_zero(buf = get_content(req))) {
24663 ast_log(LOG_WARNING, "Unable to retrieve attachment from NOTIFY %s\n", p->callid);
24664 transmit_response(p, "400 Bad request", req);
24665 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
24666 return -1;
24667 }
24668
24669
24670
24671
24672
24673
24674
24675
24676
24677
24678
24679
24680
24681
24682
24683
24684
24685
24686
24687
24688
24689 ast_debug(3, "* SIP Transfer NOTIFY Attachment: \n---%s\n---\n", buf);
24690 cmd = ast_skip_blanks(buf);
24691 code = cmd;
24692
24693 while(*code && (*code > 32)) {
24694 code++;
24695 }
24696 *code++ = '\0';
24697 code = ast_skip_blanks(code);
24698 sep = code;
24699 sep++;
24700 while(*sep && (*sep > 32)) {
24701 sep++;
24702 }
24703 *sep++ = '\0';
24704 respcode = atoi(code);
24705 switch (respcode) {
24706 case 200:
24707
24708 break;
24709 case 301:
24710 case 302:
24711
24712 success = FALSE;
24713 break;
24714 case 503:
24715 case 603:
24716
24717 success = FALSE;
24718 break;
24719 case 0:
24720
24721 ast_log(LOG_NOTICE, "Error parsing sipfrag in NOTIFY in response to REFER.\n");
24722 success = FALSE;
24723 break;
24724 default:
24725 if (respcode < 200) {
24726
24727 success = -1;
24728 } else {
24729 ast_log(LOG_NOTICE, "Got unknown code '%d' in NOTIFY in response to REFER.\n", respcode);
24730 success = FALSE;
24731 }
24732 break;
24733 }
24734 if (success == FALSE) {
24735 ast_log(LOG_NOTICE, "Transfer failed. Sorry. Nothing further to do with this call\n");
24736 }
24737
24738 if (p->owner && success != -1) {
24739 enum ast_control_transfer message = success ? AST_TRANSFER_SUCCESS : AST_TRANSFER_FAILED;
24740 ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
24741 }
24742
24743 transmit_response(p, "200 OK", req);
24744 } else if (!strcmp(event, "message-summary")) {
24745 const char *mailbox = NULL;
24746 char *c = ast_strdupa(get_content_line(req, "Voice-Message", ':'));
24747
24748 if (!p->mwi) {
24749 struct sip_peer *peer = sip_find_peer(NULL, &p->recv, TRUE, FINDPEERS, FALSE, p->socket.type);
24750
24751 if (peer) {
24752 mailbox = ast_strdupa(peer->unsolicited_mailbox);
24753 sip_unref_peer(peer, "removing unsolicited mwi ref");
24754 }
24755 } else {
24756 mailbox = p->mwi->mailbox;
24757 }
24758
24759 if (!ast_strlen_zero(mailbox) && !ast_strlen_zero(c)) {
24760 char *old = strsep(&c, " ");
24761 char *new = strsep(&old, "/");
24762 struct ast_event *event;
24763
24764 if ((event = ast_event_new(AST_EVENT_MWI,
24765 AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox,
24766 AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, "SIP_Remote",
24767 AST_EVENT_IE_NEWMSGS, AST_EVENT_IE_PLTYPE_UINT, atoi(new),
24768 AST_EVENT_IE_OLDMSGS, AST_EVENT_IE_PLTYPE_UINT, atoi(old),
24769 AST_EVENT_IE_END))) {
24770 ast_event_queue_and_cache(event);
24771 }
24772 transmit_response(p, "200 OK", req);
24773 } else {
24774 transmit_response(p, "489 Bad event", req);
24775 res = -1;
24776 }
24777 } else if (!strcmp(event, "keep-alive")) {
24778
24779
24780 transmit_response(p, "200 OK", req);
24781 } else if (!strcmp(event, "call-completion")) {
24782 res = handle_cc_notify(p, req);
24783 } else {
24784
24785 transmit_response(p, "489 Bad event", req);
24786 res = -1;
24787 }
24788
24789 if (!p->lastinvite)
24790 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
24791
24792 return res;
24793 }
24794
24795
24796
24797
24798 static int handle_request_options(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e)
24799 {
24800 const char *msg;
24801 enum sip_get_dest_result gotdest;
24802 int res;
24803
24804 if (p->lastinvite) {
24805
24806 transmit_response_with_allow(p, "200 OK", req, 0);
24807 return 0;
24808 }
24809
24810 if (sip_cfg.auth_options_requests) {
24811
24812 copy_request(&p->initreq, req);
24813 set_pvt_allowed_methods(p, req);
24814 res = check_user(p, req, SIP_OPTIONS, e, XMIT_UNRELIABLE, addr);
24815 if (res == AUTH_CHALLENGE_SENT) {
24816 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
24817 return 0;
24818 }
24819 if (res < 0) {
24820 ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", sip_get_header(req, "From"));
24821 transmit_response(p, "403 Forbidden", req);
24822 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
24823 return 0;
24824 }
24825 }
24826
24827
24828 gotdest = get_destination(p, req, NULL);
24829 build_contact(p);
24830
24831 if (ast_strlen_zero(p->context))
24832 ast_string_field_set(p, context, sip_cfg.default_context);
24833
24834 if (ast_shutting_down()) {
24835 msg = "503 Unavailable";
24836 } else {
24837 msg = "404 Not Found";
24838 switch (gotdest) {
24839 case SIP_GET_DEST_INVALID_URI:
24840 msg = "416 Unsupported URI scheme";
24841 break;
24842 case SIP_GET_DEST_EXTEN_MATCHMORE:
24843 case SIP_GET_DEST_REFUSED:
24844 case SIP_GET_DEST_EXTEN_NOT_FOUND:
24845
24846 break;
24847 case SIP_GET_DEST_EXTEN_FOUND:
24848 msg = "200 OK";
24849 break;
24850 }
24851 }
24852 transmit_response_with_allow(p, msg, req, 0);
24853
24854
24855
24856 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
24857
24858 return 0;
24859 }
24860
24861
24862
24863
24864
24865
24866
24867
24868
24869
24870
24871
24872
24873 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, int *nounlock)
24874 {
24875 int earlyreplace = 0;
24876 int oneleggedreplace = 0;
24877 struct ast_channel *c = p->owner;
24878 struct ast_channel *replacecall = p->refer->refer_call->owner;
24879 struct ast_channel *targetcall;
24880
24881
24882 if (ast_channel_state(replacecall) == AST_STATE_RING)
24883 earlyreplace = 1;
24884
24885
24886 if (!(targetcall = ast_bridged_channel(replacecall))) {
24887
24888 if (!earlyreplace) {
24889 ast_debug(2, " Attended transfer attempted to replace call with no bridge (maybe ringing). Channel %s!\n", ast_channel_name(replacecall));
24890 oneleggedreplace = 1;
24891 }
24892 }
24893 if (targetcall && ast_channel_state(targetcall) == AST_STATE_RINGING)
24894 ast_debug(4, "SIP transfer: Target channel is in ringing state\n");
24895
24896 if (targetcall)
24897 ast_debug(4, "SIP transfer: Invite Replace incoming channel should bridge to channel %s while hanging up channel %s\n", ast_channel_name(targetcall), ast_channel_name(replacecall));
24898 else
24899 ast_debug(4, "SIP transfer: Invite Replace incoming channel should replace and hang up channel %s (one call leg)\n", ast_channel_name(replacecall));
24900
24901 if (req->ignore) {
24902 ast_log(LOG_NOTICE, "Ignoring this INVITE with replaces in a stupid way.\n");
24903
24904
24905
24906 transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE, FALSE);
24907
24908 if (c) {
24909 *nounlock = 1;
24910 ast_channel_unlock(c);
24911 }
24912 ast_channel_unlock(replacecall);
24913 sip_pvt_unlock(p->refer->refer_call);
24914 return 1;
24915 }
24916 if (!c) {
24917
24918 ast_log(LOG_ERROR, "Unable to create new channel. Invite/replace failed.\n");
24919 transmit_response_reliable(p, "503 Service Unavailable", req);
24920 append_history(p, "Xfer", "INVITE/Replace Failed. No new channel.");
24921 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
24922 ast_channel_unlock(replacecall);
24923 sip_pvt_unlock(p->refer->refer_call);
24924 return 1;
24925 }
24926 append_history(p, "Xfer", "INVITE/Replace received");
24927
24928
24929
24930
24931
24932
24933
24934
24935
24936
24937
24938 transmit_response(p, "100 Trying", req);
24939 ast_setstate(c, AST_STATE_RING);
24940
24941
24942
24943
24944
24945 transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE, FALSE);
24946
24947 ast_setstate(c, AST_STATE_UP);
24948
24949
24950 ast_quiet_chan(replacecall);
24951 ast_quiet_chan(targetcall);
24952 ast_debug(4, "Invite/Replaces: preparing to masquerade %s into %s\n", ast_channel_name(c), ast_channel_name(replacecall));
24953
24954
24955 if (! earlyreplace && ! oneleggedreplace )
24956 ast_set_flag(&p->refer->refer_call->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
24957
24958
24959 if(ast_channel_masquerade(replacecall, c))
24960 ast_log(LOG_ERROR, "Failed to masquerade C into Replacecall\n");
24961 else
24962 ast_debug(4, "Invite/Replaces: Going to masquerade %s into %s\n", ast_channel_name(c), ast_channel_name(replacecall));
24963
24964
24965
24966
24967
24968 ast_channel_ref(c);
24969 ast_channel_unlock(replacecall);
24970 ast_channel_unlock(c);
24971 sip_pvt_unlock(p->refer->refer_call);
24972 sip_pvt_unlock(p);
24973 if (ast_do_masquerade(replacecall)) {
24974 ast_log(LOG_WARNING, "Failed to perform masquerade with INVITE replaces\n");
24975 }
24976 if (earlyreplace || oneleggedreplace ) {
24977 ast_channel_lock(c);
24978 ast_channel_hangupcause_set(c, AST_CAUSE_SWITCH_CONGESTION);
24979 ast_channel_unlock(c);
24980 }
24981
24982
24983 ast_hangup(c);
24984
24985 *nounlock = 1;
24986
24987 sip_pvt_lock(p);
24988 ast_channel_unref(c);
24989 return 0;
24990 }
24991
24992
24993 static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context)
24994 {
24995 struct ast_str *str = ast_str_alloca(AST_MAX_EXTENSION + AST_MAX_CONTEXT + 2);
24996 struct ast_app *pickup = pbx_findapp("Pickup");
24997
24998 if (!pickup) {
24999 ast_log(LOG_ERROR, "Unable to perform pickup: Application 'Pickup' not loaded (app_directed_pickup.so).\n");
25000 return -1;
25001 }
25002
25003 ast_str_set(&str, 0, "%s@%s", extension, sip_cfg.notifycid == IGNORE_CONTEXT ? "PICKUPMARK" : context);
25004
25005 ast_debug(2, "About to call Pickup(%s)\n", ast_str_buffer(str));
25006
25007
25008
25009
25010 pbx_exec(channel, pickup, ast_str_buffer(str));
25011
25012 return 0;
25013 }
25014
25015
25016 static int sip_t38_abort(const void *data)
25017 {
25018 struct sip_pvt *p = (struct sip_pvt *) data;
25019
25020 sip_pvt_lock(p);
25021
25022
25023
25024
25025
25026 if (p->t38id != -1) {
25027 change_t38_state(p, T38_REJECTED);
25028 transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
25029 p->t38id = -1;
25030 dialog_unref(p, "unref the dialog ptr from sip_t38_abort, because it held a dialog ptr");
25031 }
25032 sip_pvt_unlock(p);
25033 return 0;
25034 }
25035
25036
25037
25038
25039
25040
25041
25042
25043
25044
25045
25046
25047 static int handle_request_update(struct sip_pvt *p, struct sip_request *req)
25048 {
25049 if (ast_strlen_zero(sip_get_header(req, "X-Asterisk-rpid-update"))) {
25050 transmit_response(p, "501 Method Not Implemented", req);
25051 return 0;
25052 }
25053 if (!p->owner) {
25054 transmit_response(p, "481 Call/Transaction Does Not Exist", req);
25055 return 0;
25056 }
25057 if (get_rpid(p, req)) {
25058 struct ast_party_connected_line connected;
25059 struct ast_set_party_connected_line update_connected;
25060
25061 ast_party_connected_line_init(&connected);
25062 memset(&update_connected, 0, sizeof(update_connected));
25063
25064 update_connected.id.number = 1;
25065 connected.id.number.valid = 1;
25066 connected.id.number.str = (char *) p->cid_num;
25067 connected.id.number.presentation = p->callingpres;
25068
25069 update_connected.id.name = 1;
25070 connected.id.name.valid = 1;
25071 connected.id.name.str = (char *) p->cid_name;
25072 connected.id.name.presentation = p->callingpres;
25073
25074
25075 ast_set_party_id_all(&update_connected.priv);
25076
25077 connected.id.tag = (char *) p->cid_tag;
25078 connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
25079 ast_channel_queue_connected_line_update(p->owner, &connected, &update_connected);
25080 }
25081 transmit_response(p, "200 OK", req);
25082 return 0;
25083 }
25084
25085
25086
25087
25088
25089
25090
25091 static int handle_request_invite_st(struct sip_pvt *p, struct sip_request *req,
25092 const char *required, int reinvite)
25093 {
25094 const char *p_uac_se_hdr;
25095 const char *p_uac_min_se;
25096 int uac_max_se = -1;
25097 int uac_min_se = -1;
25098 int st_active = FALSE;
25099 int st_interval = 0;
25100 enum st_refresher tmp_st_ref = SESSION_TIMER_REFRESHER_AUTO;
25101 int dlg_min_se = -1;
25102 int dlg_max_se = global_max_se;
25103 int rtn;
25104
25105
25106 if ((p->sipoptions & SIP_OPT_TIMER)) {
25107 enum st_refresher_param st_ref_param = SESSION_TIMER_REFRESHER_PARAM_UNKNOWN;
25108
25109
25110
25111 ast_debug(2, "Incoming INVITE with 'timer' option supported\n");
25112
25113
25114 if (!p->stimer) {
25115 sip_st_alloc(p);
25116 }
25117
25118
25119 p_uac_se_hdr = sip_get_header(req, "Session-Expires");
25120 if (!ast_strlen_zero(p_uac_se_hdr)) {
25121 ast_debug(2, "INVITE also has \"Session-Expires\" header.\n");
25122 rtn = parse_session_expires(p_uac_se_hdr, &uac_max_se, &st_ref_param);
25123 tmp_st_ref = (st_ref_param == SESSION_TIMER_REFRESHER_PARAM_UAC) ? SESSION_TIMER_REFRESHER_THEM : SESSION_TIMER_REFRESHER_US;
25124 if (rtn != 0) {
25125 transmit_response_reliable(p, "400 Session-Expires Invalid Syntax", req);
25126 return -1;
25127 }
25128 }
25129
25130
25131 p_uac_min_se = sip_get_header(req, "Min-SE");
25132 if (!ast_strlen_zero(p_uac_min_se)) {
25133 ast_debug(2, "INVITE also has \"Min-SE\" header.\n");
25134 rtn = parse_minse(p_uac_min_se, &uac_min_se);
25135 if (rtn != 0) {
25136 transmit_response_reliable(p, "400 Min-SE Invalid Syntax", req);
25137 return -1;
25138 }
25139 }
25140
25141 dlg_min_se = st_get_se(p, FALSE);
25142 switch (st_get_mode(p, 1)) {
25143 case SESSION_TIMER_MODE_ACCEPT:
25144 case SESSION_TIMER_MODE_ORIGINATE:
25145 if (uac_max_se > 0 && uac_max_se < dlg_min_se) {
25146 transmit_response_with_minse(p, "422 Session Interval Too Small", req, dlg_min_se);
25147 return -1;
25148 }
25149
25150 p->stimer->st_active_peer_ua = TRUE;
25151 st_active = TRUE;
25152 if (st_ref_param == SESSION_TIMER_REFRESHER_PARAM_UNKNOWN) {
25153 tmp_st_ref = st_get_refresher(p);
25154 }
25155
25156 dlg_max_se = st_get_se(p, TRUE);
25157 if (uac_max_se > 0) {
25158 if (dlg_max_se >= uac_min_se) {
25159 st_interval = (uac_max_se < dlg_max_se) ? uac_max_se : dlg_max_se;
25160 } else {
25161 st_interval = uac_max_se;
25162 }
25163 } else if (uac_min_se > 0) {
25164 st_interval = MAX(dlg_max_se, uac_min_se);
25165 } else {
25166 st_interval = dlg_max_se;
25167 }
25168 break;
25169
25170 case SESSION_TIMER_MODE_REFUSE:
25171 if (p->reqsipoptions & SIP_OPT_TIMER) {
25172 transmit_response_with_unsupported(p, "420 Option Disabled", req, required);
25173 ast_log(LOG_WARNING, "Received SIP INVITE with supported but disabled option: %s\n", required);
25174 return -1;
25175 }
25176 break;
25177
25178 default:
25179 ast_log(LOG_ERROR, "Internal Error %d at %s:%d\n", st_get_mode(p, 1), __FILE__, __LINE__);
25180 break;
25181 }
25182 } else {
25183
25184
25185
25186 switch (st_get_mode(p, 1)) {
25187 case SESSION_TIMER_MODE_ORIGINATE:
25188 st_active = TRUE;
25189 st_interval = st_get_se(p, TRUE);
25190 tmp_st_ref = SESSION_TIMER_REFRESHER_US;
25191 p->stimer->st_active_peer_ua = (p->sipoptions & SIP_OPT_TIMER) ? TRUE : FALSE;
25192 break;
25193
25194 default:
25195 break;
25196 }
25197 }
25198
25199 if (reinvite == 0) {
25200
25201 if (st_active == TRUE) {
25202 p->stimer->st_active = TRUE;
25203 p->stimer->st_interval = st_interval;
25204 p->stimer->st_ref = tmp_st_ref;
25205 }
25206 } else {
25207 if (p->stimer->st_active == TRUE) {
25208
25209
25210
25211 ast_debug (2, "Restarting session-timers on a refresh - %s\n", p->callid);
25212
25213
25214 if (st_interval > 0) {
25215 p->stimer->st_interval = st_interval;
25216 p->stimer->st_ref = tmp_st_ref;
25217 }
25218 }
25219 }
25220
25221 return 0;
25222 }
25223
25224
25225
25226
25227
25228
25229
25230
25231 static int handle_request_invite(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, int *recount, const char *e, int *nounlock)
25232 {
25233 int res = INV_REQ_SUCCESS;
25234 int gotdest;
25235 const char *p_replaces;
25236 char *replace_id = NULL;
25237 int refer_locked = 0;
25238 const char *required;
25239 unsigned int required_profile = 0;
25240 struct ast_channel *c = NULL;
25241 struct sip_peer *authpeer = NULL;
25242 int reinvite = 0;
25243 struct ast_party_redirecting redirecting;
25244 struct ast_set_party_redirecting update_redirecting;
25245
25246 struct {
25247 char exten[AST_MAX_EXTENSION];
25248 char context[AST_MAX_CONTEXT];
25249 } pickup = {
25250 .exten = "",
25251 };
25252
25253
25254 if (!p->sipoptions) {
25255 const char *supported = sip_get_header(req, "Supported");
25256 if (!ast_strlen_zero(supported)) {
25257 p->sipoptions = parse_sip_options(supported, NULL, 0);
25258 }
25259 }
25260
25261
25262 required = sip_get_header(req, "Require");
25263 if (!ast_strlen_zero(required)) {
25264 char unsupported[256] = { 0, };
25265 required_profile = parse_sip_options(required, unsupported, ARRAY_LEN(unsupported));
25266
25267
25268
25269 if (!ast_strlen_zero(unsupported)) {
25270 transmit_response_with_unsupported(p, "420 Bad extension (unsupported)", req, unsupported);
25271 ast_log(LOG_WARNING, "Received SIP INVITE with unsupported required extension: required:%s unsupported:%s\n", required, unsupported);
25272 p->invitestate = INV_COMPLETED;
25273 if (!p->lastinvite)
25274 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
25275 res = INV_REQ_ERROR;
25276 goto request_invite_cleanup;
25277 }
25278 }
25279
25280
25281
25282 p->sipoptions |= required_profile;
25283 p->reqsipoptions = required_profile;
25284
25285
25286 if (ast_test_flag(&p->flags[0], SIP_OUTGOING) && p->owner && (p->invitestate != INV_TERMINATED && p->invitestate != INV_CONFIRMED) && ast_channel_state(p->owner) != AST_STATE_UP) {
25287
25288
25289
25290
25291
25292 int different;
25293 const char *initial_rlpart2 = REQ_OFFSET_TO_STR(&p->initreq, rlpart2);
25294 const char *this_rlpart2 = REQ_OFFSET_TO_STR(req, rlpart2);
25295 if (sip_cfg.pedanticsipchecking)
25296 different = sip_uri_cmp(initial_rlpart2, this_rlpart2);
25297 else
25298 different = strcmp(initial_rlpart2, this_rlpart2);
25299 if (!different) {
25300 transmit_response(p, "482 Loop Detected", req);
25301 p->invitestate = INV_COMPLETED;
25302 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
25303 res = INV_REQ_FAILED;
25304 goto request_invite_cleanup;
25305 } else {
25306
25307
25308
25309
25310
25311
25312
25313 char *uri = ast_strdupa(this_rlpart2);
25314 char *at = strchr(uri, '@');
25315 char *peerorhost;
25316 ast_debug(2, "Potential spiral detected. Original RURI was %s, new RURI is %s\n", initial_rlpart2, this_rlpart2);
25317 transmit_response(p, "100 Trying", req);
25318 if (at) {
25319 *at = '\0';
25320 }
25321
25322 if ((peerorhost = strchr(uri, ':'))) {
25323 *peerorhost++ = '\0';
25324 }
25325 ast_string_field_set(p, theirtag, NULL);
25326
25327
25328 ast_channel_call_forward_set(p->owner, peerorhost);
25329 ast_queue_control(p->owner, AST_CONTROL_BUSY);
25330 res = INV_REQ_FAILED;
25331 goto request_invite_cleanup;
25332 }
25333 }
25334
25335 if (!req->ignore && p->pendinginvite) {
25336 if (!ast_test_flag(&p->flags[0], SIP_OUTGOING) && (p->invitestate == INV_COMPLETED || p->invitestate == INV_TERMINATED)) {
25337
25338
25339
25340
25341
25342
25343
25344
25345
25346
25347 __sip_ack(p, p->pendinginvite, 1, 0);
25348 } else {
25349
25350 p->glareinvite = seqno;
25351 if (p->rtp && find_sdp(req)) {
25352 struct ast_sockaddr addr;
25353 if (get_ip_and_port_from_sdp(req, SDP_AUDIO, &addr)) {
25354 ast_log(LOG_WARNING, "Failed to set an alternate media source on glared reinvite. Audio may not work properly on this call.\n");
25355 } else {
25356 ast_rtp_instance_set_alt_remote_address(p->rtp, &addr);
25357 }
25358 if (p->vrtp) {
25359 if (get_ip_and_port_from_sdp(req, SDP_VIDEO, &addr)) {
25360 ast_log(LOG_WARNING, "Failed to set an alternate media source on glared reinvite. Video may not work properly on this call.\n");
25361 } else {
25362 ast_rtp_instance_set_alt_remote_address(p->vrtp, &addr);
25363 }
25364 }
25365 }
25366 transmit_response_reliable(p, "491 Request Pending", req);
25367 check_via(p, req);
25368 ast_debug(1, "Got INVITE on call where we already have pending INVITE, deferring that - %s\n", p->callid);
25369
25370 res = INV_REQ_FAILED;
25371 goto request_invite_cleanup;
25372 }
25373 }
25374
25375 p_replaces = sip_get_header(req, "Replaces");
25376 if (!ast_strlen_zero(p_replaces)) {
25377
25378 char *ptr;
25379 char *fromtag = NULL;
25380 char *totag = NULL;
25381 char *start, *to;
25382 int error = 0;
25383
25384 if (p->owner) {
25385 ast_debug(3, "INVITE w Replaces on existing call? Refusing action. [%s]\n", p->callid);
25386 transmit_response_reliable(p, "400 Bad request", req);
25387 check_via(p, req);
25388 copy_request(&p->initreq, req);
25389
25390 res = INV_REQ_ERROR;
25391 goto request_invite_cleanup;
25392 }
25393
25394 if (sipdebug)
25395 ast_debug(3, "INVITE part of call transfer. Replaces [%s]\n", p_replaces);
25396
25397 replace_id = ast_strdupa(p_replaces);
25398 ast_uri_decode(replace_id, ast_uri_sip_user);
25399
25400 if (!p->refer && !sip_refer_alloc(p)) {
25401 transmit_response_reliable(p, "500 Server Internal Error", req);
25402 append_history(p, "Xfer", "INVITE/Replace Failed. Out of memory.");
25403 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
25404 p->invitestate = INV_COMPLETED;
25405 res = INV_REQ_ERROR;
25406 check_via(p, req);
25407 copy_request(&p->initreq, req);
25408 goto request_invite_cleanup;
25409 }
25410
25411
25412
25413
25414
25415
25416
25417
25418
25419
25420 replace_id = ast_skip_blanks(replace_id);
25421
25422 start = replace_id;
25423 while ( (ptr = strsep(&start, ";")) ) {
25424 ptr = ast_skip_blanks(ptr);
25425 if ( (to = strcasestr(ptr, "to-tag=") ) )
25426 totag = to + 7;
25427 else if ( (to = strcasestr(ptr, "from-tag=") ) ) {
25428 fromtag = to + 9;
25429 fromtag = strsep(&fromtag, "&");
25430 }
25431 }
25432
25433 if (sipdebug)
25434 ast_debug(4, "Invite/replaces: Will use Replace-Call-ID : %s Fromtag: %s Totag: %s\n",
25435 replace_id,
25436 fromtag ? fromtag : "<no from tag>",
25437 totag ? totag : "<no to tag>");
25438
25439
25440
25441
25442
25443 if (strncmp(replace_id, "pickup-", 7) == 0) {
25444 struct sip_pvt *subscription = NULL;
25445 replace_id += 7;
25446
25447 if ((subscription = get_sip_pvt_byid_locked(replace_id, totag, fromtag)) == NULL) {
25448 ast_log(LOG_NOTICE, "Unable to find subscription with call-id: %s\n", replace_id);
25449 transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
25450 error = 1;
25451 } else {
25452 ast_log(LOG_NOTICE, "Trying to pick up %s@%s\n", subscription->exten, subscription->context);
25453 ast_copy_string(pickup.exten, subscription->exten, sizeof(pickup.exten));
25454 ast_copy_string(pickup.context, subscription->context, sizeof(pickup.context));
25455 sip_pvt_unlock(subscription);
25456 if (subscription->owner) {
25457 ast_channel_unlock(subscription->owner);
25458 }
25459 subscription = dialog_unref(subscription, "unref dialog subscription");
25460 }
25461 }
25462
25463
25464 if (!error && ast_strlen_zero(pickup.exten) && (p->refer->refer_call = get_sip_pvt_byid_locked(replace_id, totag, fromtag)) == NULL) {
25465 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existent call id (%s)!\n", replace_id);
25466 transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
25467 error = 1;
25468 } else {
25469 refer_locked = 1;
25470 }
25471
25472
25473
25474
25475
25476 if (p->refer->refer_call == p) {
25477 ast_log(LOG_NOTICE, "INVITE with replaces into it's own call id (%s == %s)!\n", replace_id, p->callid);
25478 transmit_response_reliable(p, "400 Bad request", req);
25479 error = 1;
25480 }
25481
25482 if (!error && ast_strlen_zero(pickup.exten) && !p->refer->refer_call->owner) {
25483
25484 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existing call id (%s)!\n", replace_id);
25485
25486 transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replace)", req);
25487 error = 1;
25488 }
25489
25490 if (!error && ast_strlen_zero(pickup.exten) && ast_channel_state(p->refer->refer_call->owner) != AST_STATE_RINGING && ast_channel_state(p->refer->refer_call->owner) != AST_STATE_RING && ast_channel_state(p->refer->refer_call->owner) != AST_STATE_UP) {
25491 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-ringing or active call id (%s)!\n", replace_id);
25492 transmit_response_reliable(p, "603 Declined (Replaces)", req);
25493 error = 1;
25494 }
25495
25496 if (error) {
25497 append_history(p, "Xfer", "INVITE/Replace Failed.");
25498 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
25499 sip_pvt_unlock(p);
25500 if (p->refer->refer_call) {
25501 sip_pvt_unlock(p->refer->refer_call);
25502 if (p->refer->refer_call->owner) {
25503 ast_channel_unlock(p->refer->refer_call->owner);
25504 }
25505 p->refer->refer_call = dialog_unref(p->refer->refer_call, "unref dialog p->refer->refer_call");
25506 }
25507 refer_locked = 0;
25508 p->invitestate = INV_COMPLETED;
25509 res = INV_REQ_ERROR;
25510 check_via(p, req);
25511 copy_request(&p->initreq, req);
25512 goto request_invite_cleanup;
25513 }
25514 }
25515
25516
25517
25518
25519 if (!req->ignore) {
25520 int newcall = (p->initreq.headers ? TRUE : FALSE);
25521
25522 if (sip_cancel_destroy(p))
25523 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
25524
25525 p->pendinginvite = seqno;
25526 check_via(p, req);
25527
25528 copy_request(&p->initreq, req);
25529 if (sipdebug)
25530 ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
25531 if (!p->owner) {
25532 if (req->debug)
25533 ast_verbose("Using INVITE request as basis request - %s\n", p->callid);
25534 if (newcall)
25535 append_history(p, "Invite", "New call: %s", p->callid);
25536 parse_ok_contact(p, req);
25537 } else {
25538 ast_clear_flag(&p->flags[0], SIP_OUTGOING);
25539 if (get_rpid(p, req)) {
25540 struct ast_party_connected_line connected;
25541 struct ast_set_party_connected_line update_connected;
25542
25543 ast_party_connected_line_init(&connected);
25544 memset(&update_connected, 0, sizeof(update_connected));
25545
25546 update_connected.id.number = 1;
25547 connected.id.number.valid = 1;
25548 connected.id.number.str = (char *) p->cid_num;
25549 connected.id.number.presentation = p->callingpres;
25550
25551 update_connected.id.name = 1;
25552 connected.id.name.valid = 1;
25553 connected.id.name.str = (char *) p->cid_name;
25554 connected.id.name.presentation = p->callingpres;
25555
25556
25557 ast_set_party_id_all(&update_connected.priv);
25558
25559 connected.id.tag = (char *) p->cid_tag;
25560 connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
25561 ast_channel_queue_connected_line_update(p->owner, &connected,
25562 &update_connected);
25563 }
25564
25565 if (find_sdp(req)) {
25566 if (process_sdp(p, req, SDP_T38_INITIATE)) {
25567 if (!ast_strlen_zero(sip_get_header(req, "Content-Encoding"))) {
25568
25569
25570
25571 transmit_response_reliable(p, "415 Unsupported Media type", req);
25572 } else {
25573 transmit_response_reliable(p, "488 Not acceptable here", req);
25574 }
25575 if (!p->lastinvite)
25576 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
25577 res = INV_REQ_ERROR;
25578 goto request_invite_cleanup;
25579 }
25580 ast_queue_control(p->owner, AST_CONTROL_SRCUPDATE);
25581 } else {
25582 ast_format_cap_copy(p->jointcaps, p->caps);
25583 ast_debug(1, "Hm.... No sdp for the moment\n");
25584
25585
25586
25587 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
25588 ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
25589
25590 ast_queue_frame(p->owner, &ast_null_frame);
25591 change_hold_state(p, req, FALSE, 0);
25592 }
25593 }
25594 if (p->do_history)
25595 append_history(p, "ReInv", "Re-invite received");
25596 }
25597 } else if (req->debug)
25598 ast_verbose("Ignoring this INVITE request\n");
25599
25600 if (!p->lastinvite && !req->ignore && !p->owner) {
25601
25602
25603 int cc_recall_core_id = -1;
25604 set_pvt_allowed_methods(p, req);
25605 res = check_user_full(p, req, SIP_INVITE, e, XMIT_RELIABLE, addr, &authpeer);
25606 if (res == AUTH_CHALLENGE_SENT) {
25607 p->invitestate = INV_COMPLETED;
25608 goto request_invite_cleanup;
25609 }
25610 if (res < 0) {
25611 ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", sip_get_header(req, "From"));
25612 transmit_response_reliable(p, "403 Forbidden", req);
25613 p->invitestate = INV_COMPLETED;
25614 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
25615 goto request_invite_cleanup;
25616 }
25617
25618
25619 if (p->relatedpeer) {
25620 p->relatedpeer = sip_unref_peer(p->relatedpeer,"unsetting the relatedpeer field in the dialog, before it is set to something else.");
25621 }
25622 if (authpeer) {
25623 p->relatedpeer = sip_ref_peer(authpeer, "setting dialog's relatedpeer pointer");
25624 }
25625
25626 req->authenticated = 1;
25627
25628
25629 if (find_sdp(req)) {
25630 if (process_sdp(p, req, SDP_T38_INITIATE)) {
25631
25632
25633
25634 if (!ast_strlen_zero(sip_get_header(req, "Content-Encoding"))) {
25635 transmit_response_reliable(p, "415 Unsupported Media type", req);
25636 } else {
25637
25638 transmit_response_reliable(p, "488 Not acceptable here", req);
25639 }
25640 p->invitestate = INV_COMPLETED;
25641 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
25642 ast_debug(1, "No compatible codecs for this SIP call.\n");
25643 res = INV_REQ_ERROR;
25644 goto request_invite_cleanup;
25645 }
25646 } else {
25647 ast_format_cap_copy(p->jointcaps, p->caps);
25648 ast_debug(2, "No SDP in Invite, third party call control\n");
25649 }
25650
25651
25652 if (ast_strlen_zero(p->context))
25653 ast_string_field_set(p, context, sip_cfg.default_context);
25654
25655
25656
25657 ast_debug(1, "Checking SIP call limits for device %s\n", p->username);
25658 if ((res = update_call_counter(p, INC_CALL_LIMIT))) {
25659 if (res < 0) {
25660 ast_log(LOG_NOTICE, "Failed to place call for device %s, too many calls\n", p->username);
25661 transmit_response_reliable(p, "480 Temporarily Unavailable (Call limit) ", req);
25662 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
25663 p->invitestate = INV_COMPLETED;
25664
25665 res = AUTH_SESSION_LIMIT;
25666 }
25667
25668 goto request_invite_cleanup;
25669 }
25670 gotdest = get_destination(p, NULL, &cc_recall_core_id);
25671 extract_uri(p, req);
25672 build_contact(p);
25673
25674 if (p->rtp) {
25675 ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
25676 ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
25677 }
25678
25679 if (!replace_id && (gotdest != SIP_GET_DEST_EXTEN_FOUND)) {
25680 switch(gotdest) {
25681 case SIP_GET_DEST_INVALID_URI:
25682 transmit_response_reliable(p, "416 Unsupported URI scheme", req);
25683 break;
25684 case SIP_GET_DEST_EXTEN_MATCHMORE:
25685 if (ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP)
25686 == SIP_PAGE2_ALLOWOVERLAP_YES) {
25687 transmit_response_reliable(p, "484 Address Incomplete", req);
25688 break;
25689 }
25690
25691
25692
25693
25694
25695
25696
25697
25698
25699 case SIP_GET_DEST_EXTEN_NOT_FOUND:
25700 {
25701 char *decoded_exten = ast_strdupa(p->exten);
25702 transmit_response_reliable(p, "404 Not Found", req);
25703 ast_uri_decode(decoded_exten, ast_uri_sip_user);
25704 ast_log(LOG_NOTICE, "Call from '%s' (%s) to extension"
25705 " '%s' rejected because extension not found in context '%s'.\n",
25706 S_OR(p->username, p->peername), ast_sockaddr_stringify(&p->recv), decoded_exten, p->context);
25707 }
25708 break;
25709 case SIP_GET_DEST_REFUSED:
25710 default:
25711 transmit_response_reliable(p, "403 Forbidden", req);
25712 }
25713
25714 p->invitestate = INV_COMPLETED;
25715 update_call_counter(p, DEC_CALL_LIMIT);
25716 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
25717 res = INV_REQ_FAILED;
25718 goto request_invite_cleanup;
25719 } else {
25720
25721
25722 if (ast_strlen_zero(p->exten))
25723 ast_string_field_set(p, exten, "s");
25724
25725
25726 make_our_tag(p);
25727
25728 if (handle_request_invite_st(p, req, required, reinvite)) {
25729 p->invitestate = INV_COMPLETED;
25730 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
25731 res = INV_REQ_ERROR;
25732 goto request_invite_cleanup;
25733 }
25734
25735
25736
25737
25738 c = sip_new(p, AST_STATE_DOWN, S_OR(p->peername, NULL), NULL, p->logger_callid);
25739
25740 if (cc_recall_core_id != -1) {
25741 ast_setup_cc_recall_datastore(c, cc_recall_core_id);
25742 ast_cc_agent_set_interfaces_chanvar(c);
25743 }
25744 *recount = 1;
25745
25746
25747 build_route(p, req, 0, 0);
25748
25749 if (c) {
25750 ast_party_redirecting_init(&redirecting);
25751 memset(&update_redirecting, 0, sizeof(update_redirecting));
25752 change_redirecting_information(p, req, &redirecting, &update_redirecting,
25753 FALSE);
25754 ast_channel_set_redirecting(c, &redirecting, &update_redirecting);
25755 ast_party_redirecting_free(&redirecting);
25756 }
25757 }
25758 } else {
25759 ast_party_redirecting_init(&redirecting);
25760 memset(&update_redirecting, 0, sizeof(update_redirecting));
25761 if (sipdebug) {
25762 if (!req->ignore)
25763 ast_debug(2, "Got a SIP re-invite for call %s\n", p->callid);
25764 else
25765 ast_debug(2, "Got a SIP re-transmit of INVITE for call %s\n", p->callid);
25766 }
25767 if (!req->ignore)
25768 reinvite = 1;
25769
25770 if (handle_request_invite_st(p, req, required, reinvite)) {
25771 p->invitestate = INV_COMPLETED;
25772 if (!p->lastinvite) {
25773 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
25774 }
25775 res = INV_REQ_ERROR;
25776 goto request_invite_cleanup;
25777 }
25778
25779 c = p->owner;
25780 change_redirecting_information(p, req, &redirecting, &update_redirecting, FALSE);
25781 if (c) {
25782 ast_channel_set_redirecting(c, &redirecting, &update_redirecting);
25783 }
25784 ast_party_redirecting_free(&redirecting);
25785 }
25786
25787
25788 parse_oli(req, p->owner);
25789
25790 if (p->stimer->st_active == TRUE) {
25791 if (reinvite == 0) {
25792 start_session_timer(p);
25793 } else {
25794 restart_session_timer(p);
25795 }
25796 }
25797
25798 if (!req->ignore && p)
25799 p->lastinvite = seqno;
25800
25801 if (c && replace_id) {
25802 if (!ast_strlen_zero(pickup.exten)) {
25803 append_history(p, "Xfer", "INVITE/Replace received");
25804
25805
25806 transmit_response(p, "100 Trying", req);
25807 p->invitestate = INV_PROCEEDING;
25808 ast_setstate(c, AST_STATE_RING);
25809
25810
25811 ast_channel_unlock(c);
25812 *nounlock = 1;
25813
25814
25815
25816
25817
25818
25819 sip_pvt_unlock(p);
25820 do_magic_pickup(c, pickup.exten, pickup.context);
25821
25822 ast_hangup(c);
25823 sip_pvt_lock(p);
25824
25825 res = INV_REQ_FAILED;
25826 goto request_invite_cleanup;
25827 } else {
25828
25829 if (sipdebug)
25830 ast_debug(4, "Sending this call to the invite/replcaes handler %s\n", p->callid);
25831 res = handle_invite_replaces(p, req, addr, seqno, nounlock);
25832 refer_locked = 0;
25833 goto request_invite_cleanup;
25834 }
25835 }
25836
25837
25838 if (c) {
25839 enum ast_channel_state c_state = ast_channel_state(c);
25840
25841 if (c_state != AST_STATE_UP && reinvite &&
25842 (p->invitestate == INV_TERMINATED || p->invitestate == INV_CONFIRMED)) {
25843
25844
25845
25846
25847
25848
25849
25850
25851
25852 c_state = AST_STATE_UP;
25853 }
25854
25855 switch(c_state) {
25856 case AST_STATE_DOWN:
25857 ast_debug(2, "%s: New call is still down.... Trying... \n", ast_channel_name(c));
25858 transmit_provisional_response(p, "100 Trying", req, 0);
25859 p->invitestate = INV_PROCEEDING;
25860 ast_setstate(c, AST_STATE_RING);
25861 if (strcmp(p->exten, ast_pickup_ext())) {
25862 enum ast_pbx_result result;
25863
25864 result = ast_pbx_start(c);
25865
25866 switch(result) {
25867 case AST_PBX_FAILED:
25868 ast_log(LOG_WARNING, "Failed to start PBX :(\n");
25869 p->invitestate = INV_COMPLETED;
25870 transmit_response_reliable(p, "503 Unavailable", req);
25871 break;
25872 case AST_PBX_CALL_LIMIT:
25873 ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
25874 p->invitestate = INV_COMPLETED;
25875 transmit_response_reliable(p, "480 Temporarily Unavailable", req);
25876 res = AUTH_SESSION_LIMIT;
25877 break;
25878 case AST_PBX_SUCCESS:
25879
25880 break;
25881 }
25882
25883 if (result) {
25884
25885
25886 ast_channel_unlock(c);
25887 *nounlock = 1;
25888 sip_pvt_unlock(p);
25889 ast_hangup(c);
25890 sip_pvt_lock(p);
25891 c = NULL;
25892 }
25893 } else {
25894 if (sip_pickup(c)) {
25895 ast_log(LOG_WARNING, "Failed to start Group pickup by %s\n", ast_channel_name(c));
25896 transmit_response_reliable(p, "480 Temporarily Unavailable", req);
25897 sip_alreadygone(p);
25898 ast_channel_hangupcause_set(c, AST_CAUSE_FAILURE);
25899
25900
25901 ast_channel_unlock(c);
25902 *nounlock = 1;
25903
25904 p->invitestate = INV_COMPLETED;
25905 sip_pvt_unlock(p);
25906 ast_hangup(c);
25907 sip_pvt_lock(p);
25908 c = NULL;
25909 }
25910 }
25911 break;
25912 case AST_STATE_RING:
25913 transmit_provisional_response(p, "100 Trying", req, 0);
25914 p->invitestate = INV_PROCEEDING;
25915 break;
25916 case AST_STATE_RINGING:
25917 transmit_provisional_response(p, "180 Ringing", req, 0);
25918 p->invitestate = INV_PROCEEDING;
25919 break;
25920 case AST_STATE_UP:
25921 ast_debug(2, "%s: This call is UP.... \n", ast_channel_name(c));
25922
25923 transmit_response(p, "100 Trying", req);
25924
25925 if (p->t38.state == T38_PEER_REINVITE) {
25926 if (p->t38id > -1) {
25927
25928 AST_SCHED_DEL_UNREF(sched, p->t38id, dialog_unref(p, "remove ref for t38id"));
25929 }
25930 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."));
25931 } else if (p->t38.state == T38_ENABLED) {
25932 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
25933 transmit_response_with_t38_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL)));
25934 } else if ((p->t38.state == T38_DISABLED) || (p->t38.state == T38_REJECTED)) {
25935
25936 if (p->srtp && !ast_test_flag(p->srtp, SRTP_CRYPTO_OFFER_OK)) {
25937 ast_log(LOG_WARNING, "Target does not support required crypto\n");
25938 transmit_response_reliable(p, "488 Not Acceptable Here (crypto)", req);
25939 } else {
25940 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
25941 transmit_response_with_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL)), p->session_modify == TRUE ? FALSE : TRUE, FALSE);
25942 ast_queue_control(p->owner, AST_CONTROL_UPDATE_RTP_PEER);
25943 }
25944 }
25945
25946 p->invitestate = INV_TERMINATED;
25947 break;
25948 default:
25949 ast_log(LOG_WARNING, "Don't know how to handle INVITE in state %d\n", ast_channel_state(c));
25950 transmit_response(p, "100 Trying", req);
25951 break;
25952 }
25953 } else {
25954 if (p && (p->autokillid == -1)) {
25955 const char *msg;
25956
25957 if ((ast_format_cap_is_empty(p->jointcaps)))
25958 msg = "488 Not Acceptable Here (codec error)";
25959 else {
25960 ast_log(LOG_NOTICE, "Unable to create/find SIP channel for this INVITE\n");
25961 msg = "503 Unavailable";
25962 }
25963 transmit_response_reliable(p, msg, req);
25964 p->invitestate = INV_COMPLETED;
25965 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
25966 }
25967 }
25968
25969 request_invite_cleanup:
25970
25971 if (refer_locked && p->refer && p->refer->refer_call) {
25972 sip_pvt_unlock(p->refer->refer_call);
25973 if (p->refer->refer_call->owner) {
25974 ast_channel_unlock(p->refer->refer_call->owner);
25975 }
25976 p->refer->refer_call = dialog_unref(p->refer->refer_call, "unref dialog p->refer->refer_call");
25977 }
25978 if (authpeer) {
25979 authpeer = sip_unref_peer(authpeer, "sip_unref_peer, from handle_request_invite authpeer");
25980 }
25981
25982 return res;
25983 }
25984
25985
25986
25987 static void parse_oli(struct sip_request *req, struct ast_channel *chan)
25988 {
25989 const char *from = NULL;
25990 const char *s = NULL;
25991 int ani2 = 0;
25992
25993 if (!chan || !req) {
25994
25995 return;
25996 }
25997
25998 from = sip_get_header(req, "From");
25999 if (ast_strlen_zero(from)) {
26000
26001 return;
26002 }
26003
26004
26005 if ((s = strcasestr(from, ";isup-oli="))) {
26006 s += 10;
26007 } else if ((s = strcasestr(from, ";ss7-oli="))) {
26008 s += 9;
26009 } else if ((s = strcasestr(from, ";oli="))) {
26010 s += 5;
26011 }
26012
26013 if (ast_strlen_zero(s)) {
26014
26015 return;
26016 }
26017
26018
26019 if (*s == '\"') {
26020 s++;
26021 }
26022
26023 if (sscanf(s, "%d", &ani2)) {
26024 ast_channel_caller(chan)->ani2 = ani2;
26025 }
26026
26027 return;
26028 }
26029
26030
26031
26032
26033
26034
26035
26036
26037
26038
26039
26040
26041
26042
26043 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, uint32_t seqno, int *nounlock)
26044 {
26045 struct sip_dual target;
26046
26047 int res = 0;
26048 struct sip_pvt *targetcall_pvt;
26049 struct ast_party_connected_line connected_to_transferee;
26050 struct ast_party_connected_line connected_to_target;
26051 char transferer_linkedid[32];
26052 struct ast_channel *chans[2];
26053
26054
26055 if (!(targetcall_pvt = get_sip_pvt_byid_locked(transferer->refer->replaces_callid, transferer->refer->replaces_callid_totag,
26056 transferer->refer->replaces_callid_fromtag))) {
26057 if (transferer->refer->localtransfer) {
26058
26059
26060
26061 transmit_notify_with_sipfrag(transferer, seqno, "481 Call leg/transaction does not exist", TRUE);
26062 append_history(transferer, "Xfer", "Refer failed");
26063 ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
26064 transferer->refer->status = REFER_FAILED;
26065 return -1;
26066 }
26067
26068 ast_debug(3, "SIP attended transfer: Not our call - generating INVITE with replaces\n");
26069 return 0;
26070 }
26071
26072
26073 append_history(transferer, "Xfer", "Refer accepted");
26074 if (!targetcall_pvt->owner) {
26075 ast_debug(4, "SIP attended transfer: Error: No owner of target call\n");
26076
26077 transmit_notify_with_sipfrag(transferer, seqno, "503 Service Unavailable", TRUE);
26078 append_history(transferer, "Xfer", "Refer failed");
26079 ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
26080 transferer->refer->status = REFER_FAILED;
26081 sip_pvt_unlock(targetcall_pvt);
26082 if (targetcall_pvt)
26083 ao2_t_ref(targetcall_pvt, -1, "Drop targetcall_pvt pointer");
26084 return -1;
26085 }
26086
26087
26088 target.chan1 = ast_channel_ref(targetcall_pvt->owner);
26089 target.chan2 = ast_bridged_channel(targetcall_pvt->owner);
26090 if (target.chan2) {
26091 ast_channel_ref(target.chan2);
26092 }
26093
26094 if (!target.chan2 || !(ast_channel_state(target.chan2) == AST_STATE_UP || ast_channel_state(target.chan2) == AST_STATE_RINGING) ) {
26095
26096 if (target.chan2)
26097 ast_debug(4, "SIP attended transfer: Error: Wrong state of target call: %s\n", ast_state2str(ast_channel_state(target.chan2)));
26098 else if (ast_channel_state(target.chan1) != AST_STATE_RING)
26099 ast_debug(4, "SIP attended transfer: Error: No target channel\n");
26100 else
26101 ast_debug(4, "SIP attended transfer: Attempting transfer in ringing state\n");
26102 }
26103
26104
26105 if (sipdebug) {
26106 if (current->chan2)
26107 ast_debug(4, "SIP attended transfer: trying to bridge %s and %s\n", ast_channel_name(target.chan1), ast_channel_name(current->chan2));
26108 else
26109 ast_debug(4, "SIP attended transfer: trying to make %s take over (masq) %s\n", ast_channel_name(target.chan1), ast_channel_name(current->chan1));
26110 }
26111
26112 ast_set_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
26113
26114 ast_copy_string(transferer_linkedid, ast_channel_linkedid(transferer->owner), sizeof(transferer_linkedid));
26115
26116
26117 chans[0] = transferer->owner;
26118 chans[1] = target.chan1;
26119 ast_manager_event_multichan(EVENT_FLAG_CALL, "Transfer", 2, chans,
26120 "TransferMethod: SIP\r\n"
26121 "TransferType: Attended\r\n"
26122 "Channel: %s\r\n"
26123 "Uniqueid: %s\r\n"
26124 "SIP-Callid: %s\r\n"
26125 "TargetChannel: %s\r\n"
26126 "TargetUniqueid: %s\r\n",
26127 ast_channel_name(transferer->owner),
26128 ast_channel_uniqueid(transferer->owner),
26129 transferer->callid,
26130 ast_channel_name(target.chan1),
26131 ast_channel_uniqueid(target.chan1));
26132 ast_party_connected_line_init(&connected_to_transferee);
26133 ast_party_connected_line_init(&connected_to_target);
26134
26135 ast_party_connected_line_copy(&connected_to_transferee, ast_channel_connected(current->chan1));
26136
26137 ast_party_connected_line_copy(&connected_to_target, ast_channel_connected(target.chan1));
26138
26139 ast_party_id_reset(&connected_to_transferee.priv);
26140 ast_party_id_reset(&connected_to_target.priv);
26141 connected_to_target.source = connected_to_transferee.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
26142 res = attempt_transfer(current, &target);
26143 if (res) {
26144
26145 transmit_notify_with_sipfrag(transferer, seqno, "486 Busy Here", TRUE);
26146 append_history(transferer, "Xfer", "Refer failed");
26147 ast_clear_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
26148
26149 sip_pvt_unlock(targetcall_pvt);
26150 ast_channel_unlock(target.chan1);
26151 } else {
26152
26153 const char *xfersound = pbx_builtin_getvar_helper(target.chan1, "ATTENDED_TRANSFER_COMPLETE_SOUND");
26154
26155
26156 ast_cel_report_event(target.chan1, AST_CEL_ATTENDEDTRANSFER, NULL, transferer_linkedid, target.chan2);
26157
26158
26159 transmit_notify_with_sipfrag(transferer, seqno, "200 OK", TRUE);
26160 append_history(transferer, "Xfer", "Refer succeeded");
26161 transferer->refer->status = REFER_200OK;
26162 if (target.chan2 && !ast_strlen_zero(xfersound) && ast_streamfile(target.chan2, xfersound, ast_channel_language(target.chan2)) >= 0) {
26163 ast_waitstream(target.chan2, "");
26164 }
26165
26166
26167
26168
26169
26170
26171
26172
26173
26174
26175
26176 ast_channel_ref(current->chan1);
26177 ast_channel_unlock(current->chan1);
26178 ast_channel_unlock(target.chan1);
26179 *nounlock = 1;
26180 sip_pvt_unlock(targetcall_pvt);
26181 sip_pvt_unlock(transferer);
26182
26183 ast_do_masquerade(target.chan1);
26184
26185 if (target.chan2) {
26186 ast_indicate(target.chan2, AST_CONTROL_UNHOLD);
26187 }
26188
26189 if (current->chan2 && ast_channel_state(current->chan2) == AST_STATE_RING) {
26190 ast_indicate(target.chan1, AST_CONTROL_RINGING);
26191 }
26192
26193 if (target.chan2) {
26194 ast_channel_queue_connected_line_update(target.chan1, &connected_to_transferee, NULL);
26195 ast_channel_queue_connected_line_update(target.chan2, &connected_to_target, NULL);
26196 } else {
26197
26198
26199
26200
26201
26202
26203
26204 struct ast_control_read_action_payload *frame_payload;
26205 int payload_size;
26206 int frame_size;
26207 unsigned char connected_line_data[1024];
26208 payload_size = ast_connected_line_build_data(connected_line_data,
26209 sizeof(connected_line_data), &connected_to_target, NULL);
26210 frame_size = payload_size + sizeof(*frame_payload);
26211 if (payload_size != -1) {
26212 frame_payload = ast_alloca(frame_size);
26213 frame_payload->payload_size = payload_size;
26214 memcpy(frame_payload->payload, connected_line_data, payload_size);
26215 frame_payload->action = AST_FRAME_READ_ACTION_CONNECTED_LINE_MACRO;
26216 ast_queue_control_data(target.chan1, AST_CONTROL_READ_ACTION, frame_payload, frame_size);
26217 }
26218
26219
26220
26221
26222 ast_channel_queue_connected_line_update(target.chan1, &connected_to_transferee, NULL);
26223
26224 }
26225 sip_pvt_lock(transferer);
26226
26227 ast_channel_unref(current->chan1);
26228 }
26229
26230
26231 ast_party_connected_line_free(&connected_to_target);
26232 ast_party_connected_line_free(&connected_to_transferee);
26233 ast_channel_unref(target.chan1);
26234 if (target.chan2) {
26235 ast_channel_unref(target.chan2);
26236 }
26237 if (targetcall_pvt)
26238 ao2_t_ref(targetcall_pvt, -1, "drop targetcall_pvt");
26239 return 1;
26240 }
26241
26242
26243
26244
26245
26246
26247
26248
26249
26250
26251
26252
26253
26254
26255
26256
26257
26258
26259
26260
26261
26262
26263
26264
26265
26266
26267
26268
26269
26270
26271
26272
26273
26274
26275
26276
26277
26278
26279
26280
26281
26282
26283
26284
26285
26286
26287
26288
26289
26290
26291
26292
26293
26294
26295
26296
26297
26298
26299
26300
26301
26302
26303
26304
26305
26306 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, uint32_t seqno, int *nounlock)
26307 {
26308
26309
26310
26311
26312 struct sip_dual current = { 0, };
26313 struct ast_channel *chans[2] = { 0, };
26314 char *refer_to = NULL;
26315 char *refer_to_domain = NULL;
26316 char *refer_to_context = NULL;
26317 char *referred_by = NULL;
26318 char *callid = NULL;
26319 int localtransfer = 0;
26320 int attendedtransfer = 0;
26321 int res = 0;
26322 struct ast_party_redirecting redirecting;
26323 struct ast_set_party_redirecting update_redirecting;
26324
26325 if (req->debug) {
26326 ast_verbose("Call %s got a SIP call transfer from %s: (REFER)!\n",
26327 p->callid,
26328 ast_test_flag(&p->flags[0], SIP_OUTGOING) ? "callee" : "caller");
26329 }
26330
26331 if (!p->owner) {
26332
26333
26334 ast_debug(3, "Call %s: Declined REFER, outside of dialog...\n", p->callid);
26335 transmit_response(p, "603 Declined (No dialog)", req);
26336 if (!req->ignore) {
26337 append_history(p, "Xfer", "Refer failed. Outside of dialog.");
26338 sip_alreadygone(p);
26339 pvt_set_needdestroy(p, "outside of dialog");
26340 }
26341 res = 0;
26342 goto handle_refer_cleanup;
26343 }
26344
26345
26346 if (p->allowtransfer == TRANSFER_CLOSED ) {
26347
26348 transmit_response(p, "603 Declined (policy)", req);
26349 append_history(p, "Xfer", "Refer failed. Allowtransfer == closed.");
26350
26351 res = 0;
26352 goto handle_refer_cleanup;
26353 }
26354
26355 if (!req->ignore && ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
26356
26357 transmit_response(p, "491 Request pending", req);
26358 append_history(p, "Xfer", "Refer failed. Request pending.");
26359 res = 0;
26360 goto handle_refer_cleanup;
26361 }
26362
26363
26364 if (!p->refer && !sip_refer_alloc(p)) {
26365 transmit_response(p, "500 Internal Server Error", req);
26366 append_history(p, "Xfer", "Refer failed. Memory allocation error.");
26367 res = -3;
26368 goto handle_refer_cleanup;
26369 }
26370
26371 res = get_refer_info(p, req);
26372
26373 p->refer->status = REFER_SENT;
26374
26375 if (res != 0) {
26376 switch (res) {
26377 case -2:
26378 transmit_response(p, "400 Bad Request (Refer-to missing)", req);
26379 append_history(p, "Xfer", "Refer failed. Refer-to missing.");
26380 if (req->debug) {
26381 ast_debug(1, "SIP transfer to black hole can't be handled (no refer-to: )\n");
26382 }
26383 break;
26384 case -3:
26385 transmit_response(p, "603 Declined (Non sip: uri)", req);
26386 append_history(p, "Xfer", "Refer failed. Non SIP uri");
26387 if (req->debug) {
26388 ast_debug(1, "SIP transfer to non-SIP uri denied\n");
26389 }
26390 break;
26391 default:
26392
26393 transmit_response(p, "202 Accepted", req);
26394 append_history(p, "Xfer", "Refer failed. Bad extension.");
26395 transmit_notify_with_sipfrag(p, seqno, "404 Not found", TRUE);
26396 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
26397 if (req->debug) {
26398 ast_debug(1, "SIP transfer to bad extension: %s\n", p->refer->refer_to);
26399 }
26400 break;
26401 }
26402 res = 0;
26403 goto handle_refer_cleanup;
26404 }
26405 if (ast_strlen_zero(p->context)) {
26406 ast_string_field_set(p, context, sip_cfg.default_context);
26407 }
26408
26409
26410 if (sip_cfg.allow_external_domains && check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
26411 p->refer->localtransfer = 1;
26412 if (sipdebug) {
26413 ast_debug(3, "This SIP transfer is local : %s\n", p->refer->refer_to_domain);
26414 }
26415 } else if (AST_LIST_EMPTY(&domain_list) || check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
26416
26417 p->refer->localtransfer = 1;
26418 } else if (sipdebug) {
26419 ast_debug(3, "This SIP transfer is to a remote SIP extension (remote domain %s)\n", p->refer->refer_to_domain);
26420 }
26421
26422
26423
26424 if (req->ignore) {
26425 goto handle_refer_cleanup;
26426 }
26427
26428
26429
26430
26431
26432
26433
26434
26435
26436
26437
26438
26439
26440
26441
26442
26443
26444
26445
26446
26447
26448
26449
26450
26451
26452
26453 chans[0] = current.chan1 = p->owner;
26454
26455
26456 chans[1] = current.chan2 = ast_bridged_channel(current.chan1);
26457
26458 ast_channel_ref(current.chan1);
26459 if (current.chan2) {
26460 ast_channel_ref(current.chan2);
26461 }
26462
26463 if (sipdebug) {
26464 ast_debug(3, "SIP %s transfer: Transferer channel %s, transferee channel %s\n",
26465 p->refer->attendedtransfer ? "attended" : "blind",
26466 ast_channel_name(current.chan1),
26467 current.chan2 ? ast_channel_name(current.chan2) : "<none>");
26468 }
26469
26470 if (!current.chan2 && !p->refer->attendedtransfer) {
26471
26472
26473
26474 if (sipdebug) {
26475 ast_debug(3, "Refused SIP transfer on non-bridged channel.\n");
26476 }
26477 p->refer->status = REFER_FAILED;
26478 append_history(p, "Xfer", "Refer failed. Non-bridged channel.");
26479 transmit_response(p, "603 Declined", req);
26480 res = -1;
26481 goto handle_refer_cleanup;
26482 }
26483
26484 if (current.chan2) {
26485 if (sipdebug) {
26486 ast_debug(4, "Got SIP transfer, applying to bridged peer '%s'\n", ast_channel_name(current.chan2));
26487 }
26488 ast_queue_control(current.chan1, AST_CONTROL_UNHOLD);
26489 }
26490
26491 ast_set_flag(&p->flags[0], SIP_GOTREFER);
26492
26493
26494 transmit_response(p, "202 Accepted", req);
26495
26496
26497 if (p->refer->attendedtransfer) {
26498
26499 if ((res = local_attended_transfer(p, ¤t, req, seqno, nounlock))) {
26500 goto handle_refer_cleanup;
26501 }
26502
26503 if (sipdebug) {
26504 ast_debug(4, "SIP attended transfer: Still not our call - generating INVITE with replaces\n");
26505 }
26506
26507 }
26508
26509
26510 refer_to = ast_strdupa(p->refer->refer_to);
26511 refer_to_domain = ast_strdupa(p->refer->refer_to_domain);
26512 refer_to_context = ast_strdupa(p->refer->refer_to_context);
26513 referred_by = ast_strdupa(p->refer->referred_by);
26514 callid = ast_strdupa(p->callid);
26515 localtransfer = p->refer->localtransfer;
26516 attendedtransfer = p->refer->attendedtransfer;
26517
26518 if (!*nounlock) {
26519 ast_channel_unlock(p->owner);
26520 *nounlock = 1;
26521 }
26522 sip_pvt_unlock(p);
26523
26524
26525 if (localtransfer && ast_parking_ext_valid(refer_to, current.chan1, refer_to_context)) {
26526 sip_pvt_lock(p);
26527 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
26528 p->refer->status = REFER_200OK;
26529 append_history(p, "Xfer", "REFER to call parking.");
26530 sip_pvt_unlock(p);
26531
26532 ast_manager_event_multichan(EVENT_FLAG_CALL, "Transfer", 2, chans,
26533 "TransferMethod: SIP\r\n"
26534 "TransferType: Blind\r\n"
26535 "Channel: %s\r\n"
26536 "Uniqueid: %s\r\n"
26537 "SIP-Callid: %s\r\n"
26538 "TargetChannel: %s\r\n"
26539 "TargetUniqueid: %s\r\n"
26540 "TransferExten: %s\r\n"
26541 "Transfer2Parking: Yes\r\n",
26542 ast_channel_name(current.chan1),
26543 ast_channel_uniqueid(current.chan1),
26544 callid,
26545 ast_channel_name(current.chan2),
26546 ast_channel_uniqueid(current.chan2),
26547 refer_to);
26548
26549 if (sipdebug) {
26550 ast_debug(4, "SIP transfer to parking: trying to park %s. Parked by %s\n", ast_channel_name(current.chan2), ast_channel_name(current.chan1));
26551 }
26552
26553
26554 if (sip_park(current.chan2, current.chan1, req, seqno, refer_to, refer_to_context)) {
26555 sip_pvt_lock(p);
26556 transmit_notify_with_sipfrag(p, seqno, "500 Internal Server Error", TRUE);
26557 } else {
26558 sip_pvt_lock(p);
26559 }
26560 goto handle_refer_cleanup;
26561 }
26562
26563
26564
26565
26566 if (current.chan1 && current.chan2) {
26567 ast_debug(3, "chan1->name: %s\n", ast_channel_name(current.chan1));
26568 pbx_builtin_setvar_helper(current.chan1, "BLINDTRANSFER", ast_channel_name(current.chan2));
26569 }
26570
26571 if (current.chan2) {
26572 pbx_builtin_setvar_helper(current.chan2, "BLINDTRANSFER", ast_channel_name(current.chan1));
26573 pbx_builtin_setvar_helper(current.chan2, "SIPDOMAIN", refer_to_domain);
26574 pbx_builtin_setvar_helper(current.chan2, "SIPTRANSFER", "yes");
26575
26576 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER", "yes");
26577
26578 if (!ast_strlen_zero(referred_by)) {
26579 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REFERER", referred_by);
26580 }
26581
26582
26583
26584
26585
26586 ast_channel_lock(p->owner);
26587 sip_pvt_lock(p);
26588 ast_party_redirecting_init(&redirecting);
26589 memset(&update_redirecting, 0, sizeof(update_redirecting));
26590 change_redirecting_information(p, req, &redirecting, &update_redirecting, FALSE);
26591
26592
26593
26594
26595 sip_pvt_unlock(p);
26596 ast_channel_unlock(p->owner);
26597 ast_channel_update_redirecting(current.chan2, &redirecting, &update_redirecting);
26598 ast_party_redirecting_free(&redirecting);
26599 }
26600
26601 sip_pvt_lock(p);
26602
26603 if (!ast_strlen_zero(p->refer->replaces_callid)) {
26604 char tempheader[SIPBUFSIZE];
26605 snprintf(tempheader, sizeof(tempheader), "%s%s%s%s%s", p->refer->replaces_callid,
26606 p->refer->replaces_callid_totag ? ";to-tag=" : "",
26607 p->refer->replaces_callid_totag,
26608 p->refer->replaces_callid_fromtag ? ";from-tag=" : "",
26609 p->refer->replaces_callid_fromtag);
26610
26611 if (current.chan2) {
26612 sip_pvt_unlock(p);
26613 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REPLACES", tempheader);
26614 sip_pvt_lock(p);
26615 }
26616 }
26617
26618
26619
26620
26621 if (!p->refer->attendedtransfer) {
26622 transmit_notify_with_sipfrag(p, seqno, "180 Ringing", FALSE);
26623 }
26624
26625
26626
26627
26628
26629 if (!current.chan2) {
26630
26631
26632
26633
26634
26635
26636
26637 p->refer->status = REFER_FAILED;
26638 transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable (can't handle one-legged xfers)", TRUE);
26639 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
26640 append_history(p, "Xfer", "Refer failed (only bridged calls).");
26641 res = -1;
26642 goto handle_refer_cleanup;
26643 }
26644 ast_set_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
26645
26646 sip_pvt_unlock(p);
26647
26648
26649
26650
26651
26652 ast_indicate(current.chan2, AST_CONTROL_UNHOLD);
26653 res = ast_async_goto(current.chan2, refer_to_context, refer_to, 1);
26654
26655 if (!res) {
26656 ast_manager_event_multichan(EVENT_FLAG_CALL, "Transfer", 2, chans,
26657 "TransferMethod: SIP\r\n"
26658 "TransferType: Blind\r\n"
26659 "Channel: %s\r\n"
26660 "Uniqueid: %s\r\n"
26661 "SIP-Callid: %s\r\n"
26662 "TargetChannel: %s\r\n"
26663 "TargetUniqueid: %s\r\n"
26664 "TransferExten: %s\r\n"
26665 "TransferContext: %s\r\n",
26666 ast_channel_name(current.chan1),
26667 ast_channel_uniqueid(current.chan1),
26668 callid,
26669 ast_channel_name(current.chan2),
26670 ast_channel_uniqueid(current.chan2),
26671 refer_to,
26672 refer_to_context);
26673
26674 ast_debug(3, "%s transfer succeeded. Telling transferer.\n", attendedtransfer? "Attended" : "Blind");
26675
26676
26677 ast_channel_lock(current.chan1);
26678 ast_cel_report_event(current.chan1, p->refer->attendedtransfer? AST_CEL_ATTENDEDTRANSFER : AST_CEL_BLINDTRANSFER, NULL, p->refer->attendedtransfer ? NULL : p->refer->refer_to, current.chan2);
26679 ast_channel_unlock(current.chan1);
26680
26681 sip_pvt_lock(p);
26682 transmit_notify_with_sipfrag(p, seqno, "200 Ok", TRUE);
26683 if (p->refer->localtransfer) {
26684 p->refer->status = REFER_200OK;
26685 }
26686 if (p->owner) {
26687 ast_channel_hangupcause_set(p->owner, AST_CAUSE_NORMAL_CLEARING);
26688 }
26689 append_history(p, "Xfer", "Refer succeeded.");
26690 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
26691
26692
26693 res = 0;
26694 } else {
26695 sip_pvt_lock(p);
26696 ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
26697 ast_debug(3, "%s transfer failed. Resuming original call.\n", p->refer->attendedtransfer? "Attended" : "Blind");
26698 append_history(p, "Xfer", "Refer failed.");
26699
26700 p->refer->status = REFER_FAILED;
26701 transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable", TRUE);
26702 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
26703 res = -1;
26704 }
26705
26706 handle_refer_cleanup:
26707 if (current.chan1) {
26708 ast_channel_unref(current.chan1);
26709 }
26710 if (current.chan2) {
26711 ast_channel_unref(current.chan2);
26712 }
26713
26714
26715 return res;
26716 }
26717
26718
26719 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req)
26720 {
26721
26722 check_via(p, req);
26723 sip_alreadygone(p);
26724
26725 if (p->owner && ast_channel_state(p->owner) == AST_STATE_UP) {
26726
26727 transmit_response(p, "200 OK", req);
26728 ast_debug(1, "Got CANCEL on an answered call. Ignoring... \n");
26729 return 0;
26730 }
26731
26732
26733
26734
26735
26736
26737 if (p->invitestate == INV_TERMINATED || p->invitestate == INV_COMPLETED) {
26738 __sip_pretend_ack(p);
26739 }
26740 if (p->invitestate != INV_TERMINATED)
26741 p->invitestate = INV_CANCELLED;
26742
26743 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD))
26744 update_call_counter(p, DEC_CALL_LIMIT);
26745
26746 stop_media_flows(p);
26747 if (p->owner) {
26748 sip_queue_hangup_cause(p, 0);
26749 } else {
26750 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
26751 }
26752 if (ast_str_strlen(p->initreq.data) > 0) {
26753 struct sip_pkt *pkt, *prev_pkt;
26754
26755
26756
26757
26758
26759
26760
26761
26762
26763
26764
26765 for (pkt = p->packets, prev_pkt = NULL; pkt; prev_pkt = pkt, pkt = pkt->next) {
26766 if (pkt->seqno == p->lastinvite && pkt->response_code == 487) {
26767 AST_SCHED_DEL(sched, pkt->retransid);
26768 UNLINK(pkt, p->packets, prev_pkt);
26769 dialog_unref(pkt->owner, "unref packet->owner from dialog");
26770 if (pkt->data) {
26771 ast_free(pkt->data);
26772 }
26773 ast_free(pkt);
26774 break;
26775 }
26776 }
26777 transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
26778 transmit_response(p, "200 OK", req);
26779 return 1;
26780 } else {
26781 transmit_response(p, "481 Call Leg Does Not Exist", req);
26782 return 0;
26783 }
26784 }
26785
26786
26787 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req)
26788 {
26789 struct ast_channel *c=NULL;
26790 int res;
26791 struct ast_channel *bridged_to;
26792 const char *required;
26793
26794
26795 if (p->pendinginvite && !ast_test_flag(&p->flags[0], SIP_OUTGOING) && !req->ignore) {
26796 transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
26797 }
26798
26799 __sip_pretend_ack(p);
26800
26801 p->invitestate = INV_TERMINATED;
26802
26803 copy_request(&p->initreq, req);
26804 if (sipdebug)
26805 ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
26806 check_via(p, req);
26807 sip_alreadygone(p);
26808
26809
26810 if (p->do_history || p->owner) {
26811 char quality_buf[AST_MAX_USER_FIELD], *quality;
26812 struct ast_channel *bridge = p->owner ? ast_bridged_channel(p->owner) : NULL;
26813
26814
26815
26816
26817 while (bridge && ast_channel_trylock(bridge)) {
26818 ast_channel_unlock(p->owner);
26819 do {
26820
26821 sip_pvt_unlock(p);
26822 usleep(1);
26823 sip_pvt_lock(p);
26824 } while (p->owner && ast_channel_trylock(p->owner));
26825 bridge = p->owner ? ast_bridged_channel(p->owner) : NULL;
26826 }
26827
26828
26829 if (p->rtp && (quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
26830 if (p->do_history) {
26831 append_history(p, "RTCPaudio", "Quality:%s", quality);
26832
26833 if ((quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY_JITTER, quality_buf, sizeof(quality_buf)))) {
26834 append_history(p, "RTCPaudioJitter", "Quality:%s", quality);
26835 }
26836 if ((quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY_LOSS, quality_buf, sizeof(quality_buf)))) {
26837 append_history(p, "RTCPaudioLoss", "Quality:%s", quality);
26838 }
26839 if ((quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY_RTT, quality_buf, sizeof(quality_buf)))) {
26840 append_history(p, "RTCPaudioRTT", "Quality:%s", quality);
26841 }
26842 }
26843
26844 if (p->owner) {
26845 ast_rtp_instance_set_stats_vars(p->owner, p->rtp);
26846 }
26847
26848 }
26849
26850 if (bridge) {
26851 struct sip_pvt *q = ast_channel_tech_pvt(bridge);
26852
26853 if (IS_SIP_TECH(ast_channel_tech(bridge)) && q && q->rtp) {
26854 ast_rtp_instance_set_stats_vars(bridge, q->rtp);
26855 }
26856 ast_channel_unlock(bridge);
26857 }
26858
26859 if (p->vrtp && (quality = ast_rtp_instance_get_quality(p->vrtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
26860 if (p->do_history) {
26861 append_history(p, "RTCPvideo", "Quality:%s", quality);
26862 }
26863 if (p->owner) {
26864 pbx_builtin_setvar_helper(p->owner, "RTPVIDEOQOS", quality);
26865 }
26866 }
26867 if (p->trtp && (quality = ast_rtp_instance_get_quality(p->trtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
26868 if (p->do_history) {
26869 append_history(p, "RTCPtext", "Quality:%s", quality);
26870 }
26871 if (p->owner) {
26872 pbx_builtin_setvar_helper(p->owner, "RTPTEXTQOS", quality);
26873 }
26874 }
26875 }
26876
26877 stop_media_flows(p);
26878 stop_session_timer(p);
26879
26880 if (!ast_strlen_zero(sip_get_header(req, "Also"))) {
26881 ast_log(LOG_NOTICE, "Client '%s' using deprecated BYE/Also transfer method. Ask vendor to support REFER instead\n",
26882 ast_sockaddr_stringify(&p->recv));
26883 if (ast_strlen_zero(p->context))
26884 ast_string_field_set(p, context, sip_cfg.default_context);
26885 res = get_also_info(p, req);
26886 if (!res) {
26887 c = p->owner;
26888 if (c) {
26889 bridged_to = ast_bridged_channel(c);
26890 if (bridged_to) {
26891
26892 ast_queue_control(c, AST_CONTROL_UNHOLD);
26893 ast_channel_unlock(c);
26894 ast_async_goto(bridged_to, p->context, p->refer->refer_to, 1);
26895 ast_channel_lock(c);
26896 } else
26897 ast_queue_hangup(p->owner);
26898 }
26899 } else {
26900 ast_log(LOG_WARNING, "Invalid transfer information from '%s'\n", ast_sockaddr_stringify(&p->recv));
26901 if (p->owner)
26902 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
26903 }
26904 } else if (p->owner) {
26905 sip_queue_hangup_cause(p, 0);
26906 sip_scheddestroy_final(p, DEFAULT_TRANS_TIMEOUT);
26907 ast_debug(3, "Received bye, issuing owner hangup\n");
26908 } else {
26909 sip_scheddestroy_final(p, DEFAULT_TRANS_TIMEOUT);
26910 ast_debug(3, "Received bye, no owner, selfdestruct soon.\n");
26911 }
26912 ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
26913
26914
26915 required = sip_get_header(req, "Require");
26916 if (!ast_strlen_zero(required)) {
26917 char unsupported[256] = { 0, };
26918 parse_sip_options(required, unsupported, ARRAY_LEN(unsupported));
26919
26920
26921 if (!ast_strlen_zero(unsupported)) {
26922 transmit_response_with_unsupported(p, "420 Bad extension (unsupported)", req, unsupported);
26923 ast_log(LOG_WARNING, "Received SIP BYE with unsupported required extension: required:%s unsupported:%s\n", required, unsupported);
26924 } else {
26925 transmit_response(p, "200 OK", req);
26926 }
26927 } else {
26928 transmit_response(p, "200 OK", req);
26929 }
26930
26931 return 1;
26932 }
26933
26934
26935 static int handle_request_message(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e)
26936 {
26937 if (!req->ignore) {
26938 if (req->debug)
26939 ast_verbose("Receiving message!\n");
26940 receive_message(p, req, addr, e);
26941 } else
26942 transmit_response(p, "202 Accepted", req);
26943 return 1;
26944 }
26945
26946 static int sip_msg_send(const struct ast_msg *msg, const char *to, const char *from);
26947
26948 static const struct ast_msg_tech sip_msg_tech = {
26949 .name = "sip",
26950 .msg_send = sip_msg_send,
26951 };
26952
26953
26954
26955
26956
26957
26958
26959
26960
26961
26962
26963
26964 static int block_msg_header(const char *header_name)
26965 {
26966 int idx;
26967
26968
26969
26970
26971
26972 static const char *hdr[] = {
26973 "To",
26974 "From",
26975 "Via",
26976 "Route",
26977 "Contact",
26978 "Call-ID",
26979 "CSeq",
26980 "Allow",
26981 "Content-Length",
26982 "Request-URI",
26983 };
26984
26985 for (idx = 0; idx < ARRAY_LEN(hdr); ++idx) {
26986 if (!strcasecmp(header_name, hdr[idx])) {
26987
26988 return 1;
26989 }
26990 }
26991 return 0;
26992 }
26993
26994 static int sip_msg_send(const struct ast_msg *msg, const char *to, const char *from)
26995 {
26996 struct sip_pvt *pvt;
26997 int res;
26998 char *to_uri;
26999 char *to_host;
27000 char *to_user;
27001 const char *var;
27002 const char *val;
27003 struct ast_msg_var_iterator *iter;
27004 struct sip_peer *peer_ptr;
27005
27006 if (!(pvt = sip_alloc(NULL, NULL, 0, SIP_MESSAGE, NULL, NULL))) {
27007 return -1;
27008 }
27009
27010 for (iter = ast_msg_var_iterator_init(msg);
27011 ast_msg_var_iterator_next(msg, iter, &var, &val);
27012 ast_msg_var_unref_current(iter)) {
27013 if (!strcasecmp(var, "Request-URI")) {
27014 ast_string_field_set(pvt, fullcontact, val);
27015 ast_msg_var_unref_current(iter);
27016 break;
27017 }
27018 }
27019 ast_msg_var_iterator_destroy(iter);
27020
27021 to_uri = ast_strdupa(to);
27022 to_uri = get_in_brackets(to_uri);
27023 parse_uri(to_uri, "sip:,sips:", &to_user, NULL, &to_host, NULL);
27024
27025 if (ast_strlen_zero(to_host)) {
27026 ast_log(LOG_WARNING, "MESSAGE(to) is invalid for SIP - '%s'\n", to);
27027 dialog_unlink_all(pvt);
27028 dialog_unref(pvt, "MESSAGE(to) is invalid for SIP");
27029 return -1;
27030 }
27031
27032 if (!ast_strlen_zero(from)) {
27033 if ((peer_ptr = sip_find_peer(from, NULL, 0, 1, 0, 0))) {
27034 ast_string_field_set(pvt, fromname, S_OR(peer_ptr->cid_name, peer_ptr->name));
27035 ast_string_field_set(pvt, fromuser, S_OR(peer_ptr->cid_num, peer_ptr->name));
27036 sip_unref_peer(peer_ptr, "sip_unref_peer, from sip_msg_send, sip_find_peer");
27037 } else if (strchr(from, '<')) {
27038 char *sender;
27039 char *name = NULL, *location = NULL, *user = NULL, *domain = NULL;
27040
27041 sender = ast_strdupa(from);
27042 ast_callerid_parse(sender, &name, &location);
27043 if (ast_strlen_zero(location)) {
27044
27045
27046
27047
27048
27049
27050
27051
27052
27053
27054
27055 location = name;
27056 name = NULL;
27057 }
27058 ast_string_field_set(pvt, fromname, name);
27059 if (strchr(location, ':')) {
27060 parse_uri(location, "sip:,sips:", &user, NULL, &domain, NULL);
27061 SIP_PEDANTIC_DECODE(user);
27062 SIP_PEDANTIC_DECODE(domain);
27063 extract_host_from_hostport(&domain);
27064 ast_string_field_set(pvt, fromuser, user);
27065 ast_string_field_set(pvt, fromdomain, domain);
27066 } else {
27067 ast_string_field_set(pvt, fromuser, location);
27068 }
27069 } else {
27070 ast_string_field_set(pvt, fromname, from);
27071 }
27072 }
27073
27074 sip_pvt_lock(pvt);
27075
27076
27077 if (create_addr(pvt, to_host, NULL, TRUE)) {
27078 sip_pvt_unlock(pvt);
27079 dialog_unlink_all(pvt);
27080 dialog_unref(pvt, "create_addr failed sending a MESSAGE");
27081 return -1;
27082 }
27083
27084 if (!ast_strlen_zero(to_user)) {
27085 ast_string_field_set(pvt, username, to_user);
27086 }
27087 ast_sip_ouraddrfor(&pvt->sa, &pvt->ourip, pvt);
27088 build_via(pvt);
27089 ast_set_flag(&pvt->flags[0], SIP_OUTGOING);
27090
27091
27092
27093
27094 for (iter = ast_msg_var_iterator_init(msg);
27095 ast_msg_var_iterator_next(msg, iter, &var, &val);
27096 ast_msg_var_unref_current(iter)) {
27097 if (!strcasecmp(var, "Max-Forwards")) {
27098
27099 if (sscanf(val, "%30d", &pvt->maxforwards) != 1 || pvt->maxforwards < 1) {
27100 sip_pvt_unlock(pvt);
27101 dialog_unlink_all(pvt);
27102 dialog_unref(pvt, "MESSAGE(Max-Forwards) reached zero.");
27103 ast_log(LOG_NOTICE,
27104 "MESSAGE(Max-Forwards) reached zero. MESSAGE not sent.\n");
27105 return -1;
27106 }
27107 --pvt->maxforwards;
27108 continue;
27109 }
27110 if (block_msg_header(var)) {
27111
27112 continue;
27113 }
27114 add_msg_header(pvt, var, val);
27115 }
27116 ast_msg_var_iterator_destroy(iter);
27117
27118 ast_string_field_set(pvt, msg_body, ast_msg_get_body(msg));
27119 res = transmit_message(pvt, 1, 0);
27120
27121 sip_pvt_unlock(pvt);
27122 sip_scheddestroy(pvt, DEFAULT_TRANS_TIMEOUT);
27123 dialog_unref(pvt, "sent a MESSAGE");
27124
27125 return res;
27126 }
27127
27128 static enum sip_publish_type determine_sip_publish_type(struct sip_request *req, const char * const event, const char * const etag, const char * const expires, int *expires_int)
27129 {
27130 int etag_present = !ast_strlen_zero(etag);
27131 int body_present = req->lines > 0;
27132
27133 ast_assert(expires_int != NULL);
27134
27135 if (ast_strlen_zero(expires)) {
27136
27137
27138
27139
27140 *expires_int = DEFAULT_PUBLISH_EXPIRES;
27141 } else if (sscanf(expires, "%30d", expires_int) != 1) {
27142 return SIP_PUBLISH_UNKNOWN;
27143 }
27144
27145 if (*expires_int == 0) {
27146 return SIP_PUBLISH_REMOVE;
27147 } else if (!etag_present && body_present) {
27148 return SIP_PUBLISH_INITIAL;
27149 } else if (etag_present && !body_present) {
27150 return SIP_PUBLISH_REFRESH;
27151 } else if (etag_present && body_present) {
27152 return SIP_PUBLISH_MODIFY;
27153 }
27154
27155 return SIP_PUBLISH_UNKNOWN;
27156 }
27157
27158 #ifdef HAVE_LIBXML2
27159 static int pidf_validate_tuple(struct ast_xml_node *tuple_node)
27160 {
27161 const char *id;
27162 int status_found = FALSE;
27163 struct ast_xml_node *tuple_children;
27164 struct ast_xml_node *tuple_children_iterator;
27165
27166 if (!(id = ast_xml_get_attribute(tuple_node, "id"))) {
27167 ast_log(LOG_WARNING, "Tuple XML element has no attribute 'id'\n");
27168 return FALSE;
27169 }
27170
27171 ast_xml_free_attr(id);
27172
27173 if (!(tuple_children = ast_xml_node_get_children(tuple_node))) {
27174
27175 ast_log(LOG_WARNING, "Tuple XML element has no child elements\n");
27176 return FALSE;
27177 }
27178 for (tuple_children_iterator = tuple_children; tuple_children_iterator;
27179 tuple_children_iterator = ast_xml_node_get_next(tuple_children_iterator)) {
27180
27181
27182
27183
27184 if (strcmp(ast_xml_node_get_name(tuple_children_iterator), "status")) {
27185
27186 continue;
27187 }
27188 if (status_found == TRUE) {
27189
27190 ast_log(LOG_WARNING, "Multiple status elements found in tuple. Only one allowed\n");
27191 return FALSE;
27192 }
27193 status_found = TRUE;
27194 }
27195 return status_found;
27196 }
27197
27198
27199 static int pidf_validate_presence(struct ast_xml_doc *doc)
27200 {
27201 struct ast_xml_node *presence_node = ast_xml_get_root(doc);
27202 struct ast_xml_node *child_nodes;
27203 struct ast_xml_node *node_iterator;
27204 struct ast_xml_ns *ns;
27205 const char *entity;
27206 const char *namespace;
27207 const char presence_namespace[] = "urn:ietf:params:xml:ns:pidf";
27208
27209 if (!presence_node) {
27210 ast_log(LOG_WARNING, "Unable to retrieve root node of the XML document\n");
27211 return FALSE;
27212 }
27213
27214
27215
27216 if (strcmp(ast_xml_node_get_name(presence_node), "presence")) {
27217 ast_log(LOG_WARNING, "Root node of PIDF document is not 'presence'. Invalid\n");
27218 return FALSE;
27219 }
27220
27221
27222
27223
27224 if (!(entity = ast_xml_get_attribute(presence_node, "entity"))) {
27225 ast_log(LOG_WARNING, "Presence element of PIDF document has no 'entity' attribute\n");
27226 return FALSE;
27227 }
27228
27229 ast_xml_free_attr(entity);
27230
27231 if (!(ns = ast_xml_find_namespace(doc, presence_node, NULL))) {
27232 ast_log(LOG_WARNING, "Couldn't find default namespace...\n");
27233 return FALSE;
27234 }
27235
27236 namespace = ast_xml_get_ns_href(ns);
27237 if (ast_strlen_zero(namespace) || strcmp(namespace, presence_namespace)) {
27238 ast_log(LOG_WARNING, "PIDF document has invalid namespace value %s\n", namespace);
27239 return FALSE;
27240 }
27241
27242 if (!(child_nodes = ast_xml_node_get_children(presence_node))) {
27243 ast_log(LOG_WARNING, "PIDF document has no elements as children of 'presence'. Invalid\n");
27244 return FALSE;
27245 }
27246
27247
27248
27249
27250
27251
27252
27253
27254
27255 for (node_iterator = child_nodes; node_iterator;
27256 node_iterator = ast_xml_node_get_next(node_iterator)) {
27257 if (strcmp(ast_xml_node_get_name(node_iterator), "tuple")) {
27258
27259 continue;
27260 }
27261 if (pidf_validate_tuple(node_iterator) == FALSE) {
27262 ast_log(LOG_WARNING, "Unable to validate tuple\n");
27263 return FALSE;
27264 }
27265 }
27266
27267 return TRUE;
27268 }
27269
27270
27271
27272
27273
27274
27275
27276
27277
27278
27279
27280
27281
27282
27283
27284
27285 static int sip_pidf_validate(struct sip_request *req, struct ast_xml_doc **pidf_doc)
27286 {
27287 struct ast_xml_doc *doc;
27288 const char *content_type = sip_get_header(req, "Content-Type");
27289 char *pidf_body;
27290 int res;
27291
27292 if (ast_strlen_zero(content_type) || strcmp(content_type, "application/pidf+xml")) {
27293 ast_log(LOG_WARNING, "Content type is not PIDF\n");
27294 return FALSE;
27295 }
27296
27297 if (!(pidf_body = get_content(req))) {
27298 ast_log(LOG_WARNING, "Unable to get PIDF body\n");
27299 return FALSE;
27300 }
27301
27302 if (!(doc = ast_xml_read_memory(pidf_body, strlen(pidf_body)))) {
27303 ast_log(LOG_WARNING, "Unable to open XML PIDF document. Is it malformed?\n");
27304 return FALSE;
27305 }
27306
27307 res = pidf_validate_presence(doc);
27308 if (res == TRUE) {
27309 *pidf_doc = doc;
27310 } else {
27311 ast_xml_close(doc);
27312 }
27313 return res;
27314 }
27315
27316 static int cc_esc_publish_handler(struct sip_pvt *pvt, struct sip_request *req, struct event_state_compositor *esc, struct sip_esc_entry *esc_entry)
27317 {
27318 const char *uri = REQ_OFFSET_TO_STR(req, rlpart2);
27319 struct ast_cc_agent *agent;
27320 struct sip_cc_agent_pvt *agent_pvt;
27321 struct ast_xml_doc *pidf_doc = NULL;
27322 const char *basic_status = NULL;
27323 struct ast_xml_node *presence_node;
27324 struct ast_xml_node *presence_children;
27325 struct ast_xml_node *tuple_node;
27326 struct ast_xml_node *tuple_children;
27327 struct ast_xml_node *status_node;
27328 struct ast_xml_node *status_children;
27329 struct ast_xml_node *basic_node;
27330 int res = 0;
27331
27332 if (!((agent = find_sip_cc_agent_by_notify_uri(uri)) || (agent = find_sip_cc_agent_by_subscribe_uri(uri)))) {
27333 ast_log(LOG_WARNING, "Could not find agent using uri '%s'\n", uri);
27334 transmit_response(pvt, "412 Conditional Request Failed", req);
27335 return -1;
27336 }
27337
27338 agent_pvt = agent->private_data;
27339
27340 if (sip_pidf_validate(req, &pidf_doc) == FALSE) {
27341 res = -1;
27342 goto cc_publish_cleanup;
27343 }
27344
27345
27346
27347
27348
27349
27350
27351 presence_node = ast_xml_get_root(pidf_doc);
27352 if (!(presence_children = ast_xml_node_get_children(presence_node))) {
27353 ast_log(LOG_WARNING, "No tuples within presence element.\n");
27354 res = -1;
27355 goto cc_publish_cleanup;
27356 }
27357
27358 if (!(tuple_node = ast_xml_find_element(presence_children, "tuple", NULL, NULL))) {
27359 ast_log(LOG_NOTICE, "Couldn't find tuple node?\n");
27360 res = -1;
27361 goto cc_publish_cleanup;
27362 }
27363
27364
27365
27366
27367 tuple_children = ast_xml_node_get_children(tuple_node);
27368
27369 status_node = ast_xml_find_element(tuple_children, "status", NULL, NULL);
27370
27371 if (!(status_children = ast_xml_node_get_children(status_node))) {
27372 ast_log(LOG_WARNING, "No basic elements within status element.\n");
27373 res = -1;
27374 goto cc_publish_cleanup;
27375 }
27376
27377 if (!(basic_node = ast_xml_find_element(status_children, "basic", NULL, NULL))) {
27378 ast_log(LOG_WARNING, "Couldn't find basic node?\n");
27379 res = -1;
27380 goto cc_publish_cleanup;
27381 }
27382
27383 basic_status = ast_xml_get_text(basic_node);
27384
27385 if (ast_strlen_zero(basic_status)) {
27386 ast_log(LOG_NOTICE, "NOthing in basic node?\n");
27387 res = -1;
27388 goto cc_publish_cleanup;
27389 }
27390
27391 if (!strcmp(basic_status, "open")) {
27392 agent_pvt->is_available = TRUE;
27393 ast_cc_agent_caller_available(agent->core_id, "Received PUBLISH stating SIP caller %s is available",
27394 agent->device_name);
27395 } else if (!strcmp(basic_status, "closed")) {
27396 agent_pvt->is_available = FALSE;
27397 ast_cc_agent_caller_busy(agent->core_id, "Received PUBLISH stating SIP caller %s is busy",
27398 agent->device_name);
27399 } else {
27400 ast_log(LOG_NOTICE, "Invalid content in basic element: %s\n", basic_status);
27401 }
27402
27403 cc_publish_cleanup:
27404 if (basic_status) {
27405 ast_xml_free_text(basic_status);
27406 }
27407 if (pidf_doc) {
27408 ast_xml_close(pidf_doc);
27409 }
27410 ao2_ref(agent, -1);
27411 if (res) {
27412 transmit_response(pvt, "400 Bad Request", req);
27413 }
27414 return res;
27415 }
27416
27417 #endif
27418
27419 static int handle_sip_publish_initial(struct sip_pvt *p, struct sip_request *req, struct event_state_compositor *esc, const int expires)
27420 {
27421 struct sip_esc_entry *esc_entry = create_esc_entry(esc, req, expires);
27422 int res = 0;
27423
27424 if (!esc_entry) {
27425 transmit_response(p, "503 Internal Server Failure", req);
27426 return -1;
27427 }
27428
27429 if (esc->callbacks->initial_handler) {
27430 res = esc->callbacks->initial_handler(p, req, esc, esc_entry);
27431 }
27432
27433 if (!res) {
27434 transmit_response_with_sip_etag(p, "200 OK", req, esc_entry, 0);
27435 }
27436
27437 ao2_ref(esc_entry, -1);
27438 return res;
27439 }
27440
27441 static int handle_sip_publish_refresh(struct sip_pvt *p, struct sip_request *req, struct event_state_compositor *esc, const char * const etag, const int expires)
27442 {
27443 struct sip_esc_entry *esc_entry = get_esc_entry(etag, esc);
27444 int expires_ms = expires * 1000;
27445 int res = 0;
27446
27447 if (!esc_entry) {
27448 transmit_response(p, "412 Conditional Request Failed", req);
27449 return -1;
27450 }
27451
27452 AST_SCHED_REPLACE_UNREF(esc_entry->sched_id, sched, expires_ms, publish_expire, esc_entry,
27453 ao2_ref(_data, -1),
27454 ao2_ref(esc_entry, -1),
27455 ao2_ref(esc_entry, +1));
27456
27457 if (esc->callbacks->refresh_handler) {
27458 res = esc->callbacks->refresh_handler(p, req, esc, esc_entry);
27459 }
27460
27461 if (!res) {
27462 transmit_response_with_sip_etag(p, "200 OK", req, esc_entry, 1);
27463 }
27464
27465 ao2_ref(esc_entry, -1);
27466 return res;
27467 }
27468
27469 static int handle_sip_publish_modify(struct sip_pvt *p, struct sip_request *req, struct event_state_compositor *esc, const char * const etag, const int expires)
27470 {
27471 struct sip_esc_entry *esc_entry = get_esc_entry(etag, esc);
27472 int expires_ms = expires * 1000;
27473 int res = 0;
27474
27475 if (!esc_entry) {
27476 transmit_response(p, "412 Conditional Request Failed", req);
27477 return -1;
27478 }
27479
27480 AST_SCHED_REPLACE_UNREF(esc_entry->sched_id, sched, expires_ms, publish_expire, esc_entry,
27481 ao2_ref(_data, -1),
27482 ao2_ref(esc_entry, -1),
27483 ao2_ref(esc_entry, +1));
27484
27485 if (esc->callbacks->modify_handler) {
27486 res = esc->callbacks->modify_handler(p, req, esc, esc_entry);
27487 }
27488
27489 if (!res) {
27490 transmit_response_with_sip_etag(p, "200 OK", req, esc_entry, 1);
27491 }
27492
27493 ao2_ref(esc_entry, -1);
27494 return res;
27495 }
27496
27497 static int handle_sip_publish_remove(struct sip_pvt *p, struct sip_request *req, struct event_state_compositor *esc, const char * const etag)
27498 {
27499 struct sip_esc_entry *esc_entry = get_esc_entry(etag, esc);
27500 int res = 0;
27501
27502 if (!esc_entry) {
27503 transmit_response(p, "412 Conditional Request Failed", req);
27504 return -1;
27505 }
27506
27507 AST_SCHED_DEL(sched, esc_entry->sched_id);
27508
27509 ao2_ref(esc_entry, -1);
27510
27511 if (esc->callbacks->remove_handler) {
27512 res = esc->callbacks->remove_handler(p, req, esc, esc_entry);
27513 }
27514
27515 if (!res) {
27516 transmit_response_with_sip_etag(p, "200 OK", req, esc_entry, 1);
27517 }
27518
27519
27520 ao2_unlink(esc->compositor, esc_entry);
27521 ao2_ref(esc_entry, -1);
27522 return res;
27523 }
27524
27525 static int handle_request_publish(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const uint32_t seqno, const char *uri)
27526 {
27527 const char *etag = sip_get_header(req, "SIP-If-Match");
27528 const char *event = sip_get_header(req, "Event");
27529 struct event_state_compositor *esc;
27530 enum sip_publish_type publish_type;
27531 const char *expires_str = sip_get_header(req, "Expires");
27532 int expires_int;
27533 int auth_result;
27534 int handler_result = -1;
27535
27536 if (ast_strlen_zero(event)) {
27537 transmit_response(p, "489 Bad Event", req);
27538 pvt_set_needdestroy(p, "missing Event: header");
27539 return -1;
27540 }
27541
27542 if (!(esc = get_esc(event))) {
27543 transmit_response(p, "489 Bad Event", req);
27544 pvt_set_needdestroy(p, "unknown event package in publish");
27545 return -1;
27546 }
27547
27548 auth_result = check_user(p, req, SIP_PUBLISH, uri, XMIT_UNRELIABLE, addr);
27549 if (auth_result == AUTH_CHALLENGE_SENT) {
27550 p->lastinvite = seqno;
27551 return 0;
27552 } else if (auth_result < 0) {
27553 ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", sip_get_header(req, "From"));
27554 transmit_response(p, "403 Forbidden", req);
27555 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
27556 ast_string_field_set(p, theirtag, NULL);
27557 return 0;
27558 } else if (auth_result == AUTH_SUCCESSFUL && p->lastinvite) {
27559
27560 __sip_ack(p, p->lastinvite, 1, 0);
27561 }
27562
27563 publish_type = determine_sip_publish_type(req, event, etag, expires_str, &expires_int);
27564
27565 if (expires_int > max_expiry) {
27566 expires_int = max_expiry;
27567 } else if (expires_int < min_expiry && expires_int > 0) {
27568 transmit_response_with_minexpires(p, "423 Interval too small", req, min_expiry);
27569 pvt_set_needdestroy(p, "Expires is less that the min expires allowed.");
27570 return 0;
27571 }
27572 p->expiry = expires_int;
27573
27574
27575
27576
27577 switch (publish_type) {
27578 case SIP_PUBLISH_UNKNOWN:
27579 transmit_response(p, "400 Bad Request", req);
27580 break;
27581 case SIP_PUBLISH_INITIAL:
27582 handler_result = handle_sip_publish_initial(p, req, esc, expires_int);
27583 break;
27584 case SIP_PUBLISH_REFRESH:
27585 handler_result = handle_sip_publish_refresh(p, req, esc, etag, expires_int);
27586 break;
27587 case SIP_PUBLISH_MODIFY:
27588 handler_result = handle_sip_publish_modify(p, req, esc, etag, expires_int);
27589 break;
27590 case SIP_PUBLISH_REMOVE:
27591 handler_result = handle_sip_publish_remove(p, req, esc, etag);
27592 break;
27593 default:
27594 transmit_response(p, "400 Impossible Condition", req);
27595 break;
27596 }
27597 if (!handler_result && p->expiry > 0) {
27598 sip_scheddestroy(p, (p->expiry + 10) * 1000);
27599 } else {
27600 pvt_set_needdestroy(p, "forcing expiration");
27601 }
27602
27603 return handler_result;
27604 }
27605
27606
27607
27608
27609
27610
27611
27612 static void add_peer_mwi_subs(struct sip_peer *peer)
27613 {
27614 struct sip_mailbox *mailbox;
27615
27616 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
27617 if (mailbox->event_sub) {
27618 ast_event_unsubscribe(mailbox->event_sub);
27619 }
27620
27621 mailbox->event_sub = ast_event_subscribe(AST_EVENT_MWI, mwi_event_cb, "SIP mbox event", peer,
27622 AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox->mailbox,
27623 AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, S_OR(mailbox->context, "default"),
27624 AST_EVENT_IE_END);
27625 }
27626 }
27627
27628 static int handle_cc_subscribe(struct sip_pvt *p, struct sip_request *req)
27629 {
27630 const char *uri = REQ_OFFSET_TO_STR(req, rlpart2);
27631 char *param_separator;
27632 struct ast_cc_agent *agent;
27633 struct sip_cc_agent_pvt *agent_pvt;
27634 const char *expires_str = sip_get_header(req, "Expires");
27635 int expires = -1;
27636
27637 if (!ast_strlen_zero(expires_str)) {
27638 sscanf(expires_str, "%30d", &expires);
27639 }
27640
27641 if ((param_separator = strchr(uri, ';'))) {
27642 *param_separator = '\0';
27643 }
27644
27645 p->subscribed = CALL_COMPLETION;
27646
27647 if (!(agent = find_sip_cc_agent_by_subscribe_uri(uri))) {
27648 if (!expires) {
27649
27650
27651
27652
27653
27654
27655 transmit_response(p, "200 OK", req);
27656 return 0;
27657 }
27658 ast_log(LOG_WARNING, "Invalid URI '%s' in CC subscribe\n", uri);
27659 transmit_response(p, "404 Not Found", req);
27660 return -1;
27661 }
27662
27663 agent_pvt = agent->private_data;
27664
27665 if (!expires) {
27666
27667
27668
27669 ast_cc_failed(agent->core_id, "CC is being canceled by %s", agent->device_name);
27670 transmit_response(p, "200 OK", req);
27671 ao2_ref(agent, -1);
27672 return 0;
27673 }
27674
27675 agent_pvt->subscribe_pvt = dialog_ref(p, "SIP CC agent gains reference to subscription dialog");
27676 ast_cc_agent_accept_request(agent->core_id, "SIP caller %s has requested CC via SUBSCRIBE",
27677 agent->device_name);
27678
27679
27680
27681
27682 ao2_ref(agent, -1);
27683 return 0;
27684 }
27685
27686
27687 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e)
27688 {
27689 int res = 0;
27690 struct sip_peer *authpeer = NULL;
27691 char *event = ast_strdupa(sip_get_header(req, "Event"));
27692 int resubscribe = (p->subscribed != NONE) && !req->ignore;
27693 char *options;
27694
27695 if (p->initreq.headers) {
27696
27697 if (p->initreq.method != SIP_SUBSCRIBE) {
27698
27699
27700 transmit_response(p, "403 Forbidden (within dialog)", req);
27701
27702 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);
27703 return 0;
27704 } else if (req->debug) {
27705 if (resubscribe)
27706 ast_debug(1, "Got a re-subscribe on existing subscription %s\n", p->callid);
27707 else
27708 ast_debug(1, "Got a new subscription %s (possibly with auth) or retransmission\n", p->callid);
27709 }
27710 }
27711
27712
27713
27714
27715 if (!sip_cfg.allowsubscribe) {
27716 transmit_response(p, "403 Forbidden (policy)", req);
27717 pvt_set_needdestroy(p, "forbidden");
27718 return 0;
27719 }
27720
27721 if (!req->ignore && !resubscribe) {
27722 const char *to = sip_get_header(req, "To");
27723 char totag[128];
27724 set_pvt_allowed_methods(p, req);
27725
27726
27727 if (!ast_strlen_zero(to) && gettag(req, "To", totag, sizeof(totag))) {
27728 if (req->debug)
27729 ast_verbose("Received resubscription for a dialog we no longer know about. Telling remote side to subscribe again.\n");
27730 transmit_response(p, "481 Subscription does not exist", req);
27731 pvt_set_needdestroy(p, "subscription does not exist");
27732 return 0;
27733 }
27734
27735
27736 if (req->debug)
27737 ast_verbose("Creating new subscription\n");
27738
27739 copy_request(&p->initreq, req);
27740 if (sipdebug)
27741 ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
27742 check_via(p, req);
27743 build_route(p, req, 0, 0);
27744 } else if (req->debug && req->ignore)
27745 ast_verbose("Ignoring this SUBSCRIBE request\n");
27746
27747
27748 if (ast_strlen_zero(event)) {
27749 transmit_response(p, "489 Bad Event", req);
27750 ast_debug(2, "Received SIP subscribe for unknown event package: <none>\n");
27751 pvt_set_needdestroy(p, "unknown event package in subscribe");
27752 return 0;
27753 }
27754 if ((options = strchr(event, ';')) != NULL) {
27755 *options++ = '\0';
27756 }
27757
27758
27759
27760
27761 if (p->subscribed == NONE || resubscribe) {
27762 res = check_user_full(p, req, SIP_SUBSCRIBE, e, XMIT_UNRELIABLE, addr, &authpeer);
27763
27764
27765 if (res == AUTH_CHALLENGE_SENT)
27766 return 0;
27767 if (res != AUTH_SUCCESSFUL) {
27768 ast_log(LOG_NOTICE, "Failed to authenticate device %s for SUBSCRIBE\n", sip_get_header(req, "From"));
27769 transmit_response(p, "403 Forbidden", req);
27770
27771 pvt_set_needdestroy(p, "authentication failed");
27772 return 0;
27773 }
27774 }
27775
27776
27777
27778
27779
27780
27781 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
27782 transmit_response(p, "403 Forbidden (policy)", req);
27783 pvt_set_needdestroy(p, "subscription not allowed");
27784 if (authpeer) {
27785 sip_unref_peer(authpeer, "sip_unref_peer, from handle_request_subscribe (authpeer 1)");
27786 }
27787 return 0;
27788 }
27789
27790
27791 parse_ok_contact(p, req);
27792 build_contact(p);
27793
27794
27795 if (ast_strlen_zero(p->tag)) {
27796 make_our_tag(p);
27797 }
27798
27799 if (!strcmp(event, "presence") || !strcmp(event, "dialog")) {
27800 int gotdest;
27801 const char *accept;
27802 int start = 0;
27803 enum subscriptiontype subscribed = NONE;
27804 const char *unknown_accept = NULL;
27805
27806
27807 gotdest = get_destination(p, NULL, NULL);
27808 if (gotdest != SIP_GET_DEST_EXTEN_FOUND) {
27809 if (gotdest == SIP_GET_DEST_INVALID_URI) {
27810 transmit_response(p, "416 Unsupported URI scheme", req);
27811 } else {
27812 transmit_response(p, "404 Not Found", req);
27813 }
27814 pvt_set_needdestroy(p, "subscription target not found");
27815 if (authpeer) {
27816 sip_unref_peer(authpeer, "sip_unref_peer, from handle_request_subscribe (authpeer 2)");
27817 }
27818 return 0;
27819 }
27820
27821
27822 accept = __get_header(req, "Accept", &start);
27823 while ((subscribed == NONE) && !ast_strlen_zero(accept)) {
27824 if (strstr(accept, "application/pidf+xml")) {
27825 if (strstr(p->useragent, "Polycom")) {
27826 subscribed = XPIDF_XML;
27827 } else {
27828 subscribed = PIDF_XML;
27829 }
27830 } else if (strstr(accept, "application/dialog-info+xml")) {
27831 subscribed = DIALOG_INFO_XML;
27832
27833 } else if (strstr(accept, "application/cpim-pidf+xml")) {
27834 subscribed = CPIM_PIDF_XML;
27835 } else if (strstr(accept, "application/xpidf+xml")) {
27836 subscribed = XPIDF_XML;
27837 } else {
27838 unknown_accept = accept;
27839 }
27840
27841 accept = __get_header(req, "Accept", &start);
27842 }
27843
27844 if (!start) {
27845 if (p->subscribed == NONE) {
27846 transmit_response(p, "489 Bad Event", req);
27847 ast_log(LOG_WARNING,"SUBSCRIBE failure: no Accept header: pvt: "
27848 "stateid: %d, laststate: %d, dialogver: %u, subscribecont: "
27849 "'%s', subscribeuri: '%s'\n",
27850 p->stateid,
27851 p->laststate,
27852 p->dialogver,
27853 p->subscribecontext,
27854 p->subscribeuri);
27855 pvt_set_needdestroy(p, "no Accept header");
27856 if (authpeer) {
27857 sip_unref_peer(authpeer, "sip_unref_peer, from handle_request_subscribe (authpeer 2)");
27858 }
27859 return 0;
27860 }
27861
27862
27863 } else if (subscribed == NONE) {
27864
27865 char buf[200];
27866
27867 if (!ast_strlen_zero(unknown_accept)) {
27868 snprintf(buf, sizeof(buf), "489 Bad Event (format %s)", unknown_accept);
27869 } else {
27870 snprintf(buf, sizeof(buf), "489 Bad Event");
27871 }
27872 transmit_response(p, buf, req);
27873 ast_log(LOG_WARNING,"SUBSCRIBE failure: unrecognized format:"
27874 "'%s' pvt: subscribed: %d, stateid: %d, laststate: %d,"
27875 "dialogver: %u, subscribecont: '%s', subscribeuri: '%s'\n",
27876 unknown_accept,
27877 (int)p->subscribed,
27878 p->stateid,
27879 p->laststate,
27880 p->dialogver,
27881 p->subscribecontext,
27882 p->subscribeuri);
27883 pvt_set_needdestroy(p, "unrecognized format");
27884 if (authpeer) {
27885 sip_unref_peer(authpeer, "sip_unref_peer, from handle_request_subscribe (authpeer 2)");
27886 }
27887 return 0;
27888 } else {
27889 p->subscribed = subscribed;
27890 }
27891 } else if (!strcmp(event, "message-summary")) {
27892 int start = 0;
27893 int found_supported = 0;
27894 const char *accept;
27895
27896 accept = __get_header(req, "Accept", &start);
27897 while (!found_supported && !ast_strlen_zero(accept)) {
27898 found_supported = strcmp(accept, "application/simple-message-summary") ? 0 : 1;
27899 if (!found_supported && (option_debug > 2)) {
27900 ast_debug(1, "Received SIP mailbox subscription for unknown format: %s\n", accept);
27901 }
27902 accept = __get_header(req, "Accept", &start);
27903 }
27904 if (start && !found_supported) {
27905
27906 transmit_response(p, "406 Not Acceptable", req);
27907 ast_debug(2, "Received SIP mailbox subscription for unknown format: %s\n", accept);
27908 pvt_set_needdestroy(p, "unknown format");
27909 if (authpeer) {
27910 sip_unref_peer(authpeer, "sip_unref_peer, from handle_request_subscribe (authpeer 3)");
27911 }
27912 return 0;
27913 }
27914
27915
27916
27917
27918
27919 if (!authpeer || AST_LIST_EMPTY(&authpeer->mailboxes)) {
27920 if (!authpeer) {
27921 transmit_response(p, "404 Not found", req);
27922 } else {
27923 transmit_response(p, "404 Not found (no mailbox)", req);
27924 ast_log(LOG_NOTICE, "Received SIP subscribe for peer without mailbox: %s\n", S_OR(authpeer->name, ""));
27925 }
27926 pvt_set_needdestroy(p, "received 404 response");
27927
27928 if (authpeer) {
27929 sip_unref_peer(authpeer, "sip_unref_peer, from handle_request_subscribe (authpeer 3)");
27930 }
27931 return 0;
27932 }
27933
27934 p->subscribed = MWI_NOTIFICATION;
27935 if (ast_test_flag(&authpeer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY)) {
27936 ao2_unlock(p);
27937 add_peer_mwi_subs(authpeer);
27938 ao2_lock(p);
27939 }
27940 if (authpeer->mwipvt != p) {
27941
27942 if (authpeer->mwipvt) {
27943 dialog_unlink_all(authpeer->mwipvt);
27944 authpeer->mwipvt = dialog_unref(authpeer->mwipvt, "unref dialog authpeer->mwipvt");
27945 }
27946 authpeer->mwipvt = dialog_ref(p, "setting peers' mwipvt to p");
27947 }
27948
27949 if (p->relatedpeer != authpeer) {
27950 if (p->relatedpeer) {
27951 sip_unref_peer(p->relatedpeer, "Unref previously stored relatedpeer ptr");
27952 }
27953 p->relatedpeer = sip_ref_peer(authpeer, "setting dialog's relatedpeer pointer");
27954 }
27955
27956 } else if (!strcmp(event, "call-completion")) {
27957 handle_cc_subscribe(p, req);
27958 } else {
27959 transmit_response(p, "489 Bad Event", req);
27960 ast_debug(2, "Received SIP subscribe for unknown event package: %s\n", event);
27961 pvt_set_needdestroy(p, "unknown event package");
27962 if (authpeer) {
27963 sip_unref_peer(authpeer, "sip_unref_peer, from handle_request_subscribe (authpeer 5)");
27964 }
27965 return 0;
27966 }
27967
27968 if (!req->ignore) {
27969 p->lastinvite = seqno;
27970 }
27971 if (!p->needdestroy) {
27972 p->expiry = atoi(sip_get_header(req, "Expires"));
27973
27974
27975 if (p->expiry > max_subexpiry) {
27976 p->expiry = max_subexpiry;
27977 } else if (p->expiry < min_subexpiry && p->expiry > 0) {
27978 transmit_response_with_minexpires(p, "423 Interval too small", req, min_subexpiry);
27979 ast_log(LOG_WARNING, "Received subscription for extension \"%s\" context \"%s\" "
27980 "with Expire header less than 'subminexpire' limit. Received \"Expire: %d\" min is %d\n",
27981 p->exten, p->context, p->expiry, min_subexpiry);
27982 pvt_set_needdestroy(p, "Expires is less that the min expires allowed.");
27983 if (authpeer) {
27984 sip_unref_peer(authpeer, "sip_unref_peer, from handle_request_subscribe (authpeer 6)");
27985 }
27986 return 0;
27987 }
27988
27989 if (sipdebug) {
27990 const char *action = p->expiry > 0 ? "Adding" : "Removing";
27991 if (p->subscribed == MWI_NOTIFICATION && p->relatedpeer) {
27992 ast_debug(2, "%s subscription for mailbox notification - peer %s\n",
27993 action, p->relatedpeer->name);
27994 } else if (p->subscribed == CALL_COMPLETION) {
27995 ast_debug(2, "%s CC subscription for peer %s\n", action, p->username);
27996 } else {
27997 ast_debug(2, "%s subscription for extension %s context %s for peer %s\n",
27998 action, p->exten, p->context, p->username);
27999 }
28000 }
28001 if (p->autokillid > -1 && sip_cancel_destroy(p))
28002 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
28003 if (p->expiry > 0)
28004 sip_scheddestroy(p, (p->expiry + 10) * 1000);
28005
28006 if (p->subscribed == MWI_NOTIFICATION) {
28007 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
28008 transmit_response(p, "200 OK", req);
28009 if (p->relatedpeer) {
28010 struct sip_peer *peer = p->relatedpeer;
28011 sip_ref_peer(peer, "ensure a peer ref is held during MWI sending");
28012 ao2_unlock(p);
28013 sip_send_mwi_to_peer(peer, 0);
28014 ao2_lock(p);
28015 sip_unref_peer(peer, "release a peer ref now that MWI is sent");
28016 }
28017 } else if (p->subscribed != CALL_COMPLETION) {
28018 struct state_notify_data data = { 0, };
28019 char *subtype = NULL;
28020 char *message = NULL;
28021 struct ao2_container *device_state_info = NULL;
28022
28023 if (p->expiry > 0 && !resubscribe) {
28024
28025 if (p->stateid != -1) {
28026 ast_extension_state_del(p->stateid, cb_extensionstate);
28027 }
28028 dialog_ref(p, "copying dialog ptr into extension state struct");
28029 p->stateid = ast_extension_state_add_destroy_extended(p->context, p->exten, cb_extensionstate, cb_extensionstate_destroy, p);
28030 if (p->stateid == -1) {
28031 dialog_unref(p, "copying dialog ptr into extension state struct failed");
28032 }
28033 }
28034
28035 sip_pvt_unlock(p);
28036 data.state = ast_extension_state_extended(NULL, p->context, p->exten, &device_state_info);
28037 sip_pvt_lock(p);
28038
28039 if (data.state < 0) {
28040 ao2_cleanup(device_state_info);
28041 if (p->expiry > 0) {
28042 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_sockaddr_stringify(&p->sa));
28043 }
28044 transmit_response(p, "404 Not found", req);
28045 pvt_set_needdestroy(p, "no extension for SUBSCRIBE");
28046 if (authpeer) {
28047 sip_unref_peer(authpeer, "sip_unref_peer, from handle_request_subscribe (authpeer 6)");
28048 }
28049 return 0;
28050 }
28051 if (allow_notify_user_presence(p)) {
28052 data.presence_state = ast_hint_presence_state(NULL, p->context, p->exten, &subtype, &message);
28053 data.presence_subtype = subtype;
28054 data.presence_message = message;
28055 }
28056 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
28057 transmit_response(p, "200 OK", req);
28058
28059 data.device_state_info = device_state_info;
28060 if (data.state & AST_EXTENSION_RINGING) {
28061
28062
28063
28064 struct ast_channel *ringing = find_ringing_channel(data.device_state_info, p);
28065 if (ringing) {
28066 p->last_ringing_channel_time = ast_channel_creationtime(ringing);
28067 ao2_ref(ringing, -1);
28068 }
28069
28070
28071
28072 }
28073 extensionstate_update(p->context, p->exten, &data, p, TRUE);
28074 append_history(p, "Subscribestatus", "%s", ast_extension_state2str(data.state));
28075
28076 ast_string_field_build(p, subscribeuri, "%s@%s", p->exten, p->context);
28077
28078
28079 ao2_cleanup(device_state_info);
28080 ast_free(subtype);
28081 ast_free(message);
28082 }
28083 if (!p->expiry) {
28084 pvt_set_needdestroy(p, "forcing expiration");
28085 }
28086 }
28087
28088 if (authpeer) {
28089 sip_unref_peer(authpeer, "unref pointer into (*authpeer)");
28090 }
28091 return 1;
28092 }
28093
28094
28095 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e)
28096 {
28097 enum check_auth_result res;
28098
28099
28100
28101 if (p->initreq.headers && p->initreq.method != SIP_REGISTER) {
28102 ast_log(LOG_WARNING, "Ignoring spurious REGISTER with Call-ID: %s\n", p->callid);
28103 return -1;
28104 }
28105
28106
28107 copy_request(&p->initreq, req);
28108 if (sipdebug)
28109 ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
28110 check_via(p, req);
28111
28112 if ((res = register_verify(p, addr, req, e)) < 0) {
28113 const char *reason;
28114
28115 switch (res) {
28116 case AUTH_SECRET_FAILED:
28117 reason = "Wrong password";
28118 break;
28119 case AUTH_USERNAME_MISMATCH:
28120 reason = "Username/auth name mismatch";
28121 break;
28122 case AUTH_NOT_FOUND:
28123 reason = "No matching peer found";
28124 break;
28125 case AUTH_UNKNOWN_DOMAIN:
28126 reason = "Not a local domain";
28127 break;
28128 case AUTH_PEER_NOT_DYNAMIC:
28129 reason = "Peer is not supposed to register";
28130 break;
28131 case AUTH_ACL_FAILED:
28132 reason = "Device does not match ACL";
28133 break;
28134 case AUTH_BAD_TRANSPORT:
28135 reason = "Device not configured to use this transport type";
28136 break;
28137 case AUTH_RTP_FAILED:
28138 reason = "RTP initialization failed";
28139 break;
28140 default:
28141 reason = "Unknown failure";
28142 break;
28143 }
28144 ast_log(LOG_NOTICE, "Registration from '%s' failed for '%s' - %s\n",
28145 sip_get_header(req, "To"), ast_sockaddr_stringify(addr),
28146 reason);
28147 append_history(p, "RegRequest", "Failed : Account %s : %s", sip_get_header(req, "To"), reason);
28148 } else {
28149 req->authenticated = 1;
28150 append_history(p, "RegRequest", "Succeeded : Account %s", sip_get_header(req, "To"));
28151 }
28152
28153 if (res != AUTH_CHALLENGE_SENT) {
28154
28155
28156 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
28157 }
28158
28159 return res;
28160 }
28161
28162
28163
28164
28165
28166
28167
28168
28169 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int *recount, int *nounlock)
28170 {
28171
28172
28173 const char *cmd;
28174 const char *cseq;
28175 const char *useragent;
28176 const char *via;
28177 const char *callid;
28178 int via_pos = 0;
28179 uint32_t seqno;
28180 int len;
28181 int respid;
28182 int res = 0;
28183 const char *e;
28184 int error = 0;
28185 int oldmethod = p->method;
28186 int acked = 0;
28187
28188
28189
28190
28191 cseq = sip_get_header(req, "Cseq");
28192 cmd = REQ_OFFSET_TO_STR(req, header[0]);
28193
28194 via = __get_header(req, "Via", &via_pos);
28195
28196 callid = sip_get_header(req, "Call-ID");
28197
28198
28199 if (ast_strlen_zero(cmd) || ast_strlen_zero(cseq) || ast_strlen_zero(via)) {
28200 ast_log(LOG_ERROR, "Dropping this SIP message with Call-ID '%s', it's incomplete.\n", callid);
28201 error = 1;
28202 }
28203 if (!error && sscanf(cseq, "%30u%n", &seqno, &len) != 1) {
28204 ast_log(LOG_ERROR, "No seqno in '%s'. Dropping incomplete message.\n", cmd);
28205 error = 1;
28206 }
28207 if (error) {
28208 if (!p->initreq.headers) {
28209 pvt_set_needdestroy(p, "no headers");
28210 }
28211 return -1;
28212 }
28213
28214
28215 cmd = REQ_OFFSET_TO_STR(req, rlpart1);
28216 e = ast_skip_blanks(REQ_OFFSET_TO_STR(req, rlpart2));
28217
28218
28219 useragent = sip_get_header(req, "User-Agent");
28220 if (!ast_strlen_zero(useragent))
28221 ast_string_field_set(p, useragent, useragent);
28222
28223
28224 if (req->method == SIP_RESPONSE) {
28225
28226
28227
28228
28229
28230
28231 if (ast_strlen_zero(e)) {
28232 return 0;
28233 }
28234 if (sscanf(e, "%30d %n", &respid, &len) != 1) {
28235 ast_log(LOG_WARNING, "Invalid response: '%s'\n", e);
28236 return 0;
28237 }
28238 if (respid <= 0) {
28239 ast_log(LOG_WARNING, "Invalid SIP response code: '%d'\n", respid);
28240 return 0;
28241 }
28242
28243
28244
28245 if (!ast_strlen_zero(__get_header(req, "via", &via_pos))) {
28246 ast_log(LOG_WARNING, "Misrouted SIP response '%s' with Call-ID '%s', too many vias\n", e, callid);
28247 return 0;
28248 }
28249 if (p->ocseq && (p->ocseq < seqno)) {
28250 ast_debug(1, "Ignoring out of order response %u (expecting %u)\n", seqno, p->ocseq);
28251 return -1;
28252 } else {
28253 if ((respid == 200) || ((respid >= 300) && (respid <= 399))) {
28254 extract_uri(p, req);
28255 }
28256
28257 if (p->owner) {
28258 struct ast_control_pvt_cause_code *cause_code;
28259 int data_size = sizeof(*cause_code);
28260
28261 data_size += 4 + strlen(REQ_OFFSET_TO_STR(req, rlpart2));
28262 cause_code = ast_alloca(data_size);
28263 memset(cause_code, 0, data_size);
28264
28265 ast_copy_string(cause_code->chan_name, ast_channel_name(p->owner), AST_CHANNEL_NAME);
28266
28267 snprintf(cause_code->code, data_size - sizeof(*cause_code) + 1, "SIP %s", REQ_OFFSET_TO_STR(req, rlpart2));
28268
28269 cause_code->ast_cause = hangup_sip2cause(respid);
28270 if (global_store_sip_cause) {
28271 cause_code->emulate_sip_cause = 1;
28272 }
28273
28274 ast_queue_control_data(p->owner, AST_CONTROL_PVT_CAUSE_CODE, cause_code, data_size);
28275 ast_channel_hangupcause_hash_set(p->owner, cause_code, data_size);
28276 }
28277
28278 handle_response(p, respid, e + len, req, seqno);
28279 }
28280 return 0;
28281 }
28282
28283
28284
28285
28286 p->method = req->method;
28287 ast_debug(4, "**** Received %s (%d) - Command in SIP %s\n", sip_methods[p->method].text, sip_methods[p->method].id, cmd);
28288
28289 if (p->icseq && (p->icseq > seqno) ) {
28290 if (p->pendinginvite && seqno == p->pendinginvite && (req->method == SIP_ACK || req->method == SIP_CANCEL)) {
28291 ast_debug(2, "Got CANCEL or ACK on INVITE with transactions in between.\n");
28292 } else {
28293 ast_debug(1, "Ignoring too old SIP packet packet %u (expecting >= %u)\n", seqno, p->icseq);
28294 if (req->method == SIP_INVITE) {
28295 unsigned int ran = (ast_random() % 10) + 1;
28296 char seconds[4];
28297 snprintf(seconds, sizeof(seconds), "%u", ran);
28298 transmit_response_with_retry_after(p, "500 Server error", req, seconds);
28299 } else if (req->method != SIP_ACK) {
28300 transmit_response(p, "500 Server error", req);
28301 }
28302 return -1;
28303 }
28304 } else if (p->icseq &&
28305 p->icseq == seqno &&
28306 req->method != SIP_ACK &&
28307 (p->method != SIP_CANCEL || p->alreadygone)) {
28308
28309
28310
28311 req->ignore = 1;
28312 ast_debug(3, "Ignoring SIP message because of retransmit (%s Seqno %u, ours %u)\n", sip_methods[p->method].text, p->icseq, seqno);
28313 }
28314
28315
28316
28317 if (!p->pendinginvite && (req->method == SIP_CANCEL)) {
28318 transmit_response(p, "481 Call/Transaction Does Not Exist", req);
28319 return res;
28320 }
28321
28322 if (seqno >= p->icseq)
28323
28324
28325
28326 p->icseq = seqno;
28327
28328
28329 if (ast_strlen_zero(p->theirtag)) {
28330 char tag[128];
28331
28332 gettag(req, "From", tag, sizeof(tag));
28333 ast_string_field_set(p, theirtag, tag);
28334 }
28335 snprintf(p->lastmsg, sizeof(p->lastmsg), "Rx: %s", cmd);
28336
28337 if (sip_cfg.pedanticsipchecking) {
28338
28339
28340
28341
28342 if (!p->initreq.headers && req->has_to_tag) {
28343
28344 if (!req->ignore && req->method == SIP_INVITE) {
28345
28346
28347
28348
28349
28350
28351 char totag[128];
28352 gettag(req, "To", totag, sizeof(totag));
28353 ast_string_field_set(p, tag, totag);
28354 p->pendinginvite = p->icseq;
28355 transmit_response_reliable(p, "481 Call/Transaction Does Not Exist", req);
28356
28357 return res;
28358 } else if (req->method != SIP_ACK) {
28359 transmit_response(p, "481 Call/Transaction Does Not Exist", req);
28360 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
28361 return res;
28362 }
28363
28364 }
28365 }
28366
28367 if (!e && (p->method == SIP_INVITE || p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER || p->method == SIP_NOTIFY || p->method == SIP_PUBLISH)) {
28368 transmit_response(p, "400 Bad request", req);
28369 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
28370 return -1;
28371 }
28372
28373
28374 switch (p->method) {
28375 case SIP_OPTIONS:
28376 res = handle_request_options(p, req, addr, e);
28377 break;
28378 case SIP_INVITE:
28379 res = handle_request_invite(p, req, addr, seqno, recount, e, nounlock);
28380
28381 if (res < 9) {
28382 sip_report_security_event(p, req, res);
28383 }
28384
28385 switch (res) {
28386 case INV_REQ_SUCCESS:
28387 res = 1;
28388 break;
28389 case INV_REQ_FAILED:
28390 res = 0;
28391 break;
28392 case INV_REQ_ERROR:
28393 res = -1;
28394 break;
28395 default:
28396 res = 0;
28397 break;
28398 }
28399
28400 break;
28401 case SIP_REFER:
28402 res = handle_request_refer(p, req, seqno, nounlock);
28403 break;
28404 case SIP_CANCEL:
28405 res = handle_request_cancel(p, req);
28406 break;
28407 case SIP_BYE:
28408 res = handle_request_bye(p, req);
28409 break;
28410 case SIP_MESSAGE:
28411 res = handle_request_message(p, req, addr, e);
28412 break;
28413 case SIP_PUBLISH:
28414 res = handle_request_publish(p, req, addr, seqno, e);
28415 break;
28416 case SIP_SUBSCRIBE:
28417 res = handle_request_subscribe(p, req, addr, seqno, e);
28418 break;
28419 case SIP_REGISTER:
28420 res = handle_request_register(p, req, addr, e);
28421 sip_report_security_event(p, req, res);
28422 break;
28423 case SIP_INFO:
28424 if (req->debug)
28425 ast_verbose("Receiving INFO!\n");
28426 if (!req->ignore)
28427 handle_request_info(p, req);
28428 else
28429 transmit_response(p, "200 OK", req);
28430 break;
28431 case SIP_NOTIFY:
28432 res = handle_request_notify(p, req, addr, seqno, e);
28433 break;
28434 case SIP_UPDATE:
28435 res = handle_request_update(p, req);
28436 break;
28437 case SIP_ACK:
28438
28439 if (seqno == p->pendinginvite) {
28440 p->invitestate = INV_TERMINATED;
28441 p->pendinginvite = 0;
28442 acked = __sip_ack(p, seqno, 1 , 0);
28443 if (p->owner && find_sdp(req)) {
28444 if (process_sdp(p, req, SDP_T38_NONE)) {
28445 return -1;
28446 }
28447 if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
28448 ast_queue_control(p->owner, AST_CONTROL_SRCCHANGE);
28449 }
28450 }
28451 check_pendings(p);
28452 } else if (p->glareinvite == seqno) {
28453
28454 p->glareinvite = 0;
28455 acked = __sip_ack(p, seqno, 1, 0);
28456 }
28457 if (!acked) {
28458
28459
28460 p->method = oldmethod;
28461 }
28462 if (!p->lastinvite && ast_strlen_zero(p->nonce)) {
28463 pvt_set_needdestroy(p, "unmatched ACK");
28464 }
28465 break;
28466 default:
28467 transmit_response_with_allow(p, "501 Method Not Implemented", req, 0);
28468 ast_log(LOG_NOTICE, "Unknown SIP command '%s' from '%s'\n",
28469 cmd, ast_sockaddr_stringify(&p->sa));
28470
28471 if (!p->initreq.headers) {
28472 pvt_set_needdestroy(p, "unimplemented method");
28473 }
28474 break;
28475 }
28476 return res;
28477 }
28478
28479
28480
28481
28482
28483
28484 static int sipsock_read(int *id, int fd, short events, void *ignore)
28485 {
28486 struct sip_request req;
28487 struct ast_sockaddr addr;
28488 int res;
28489 static char readbuf[65535];
28490
28491 memset(&req, 0, sizeof(req));
28492 res = ast_recvfrom(fd, readbuf, sizeof(readbuf) - 1, 0, &addr);
28493 if (res < 0) {
28494 #if !defined(__FreeBSD__)
28495 if (errno == EAGAIN)
28496 ast_log(LOG_NOTICE, "SIP: Received packet with bad UDP checksum\n");
28497 else
28498 #endif
28499 if (errno != ECONNREFUSED)
28500 ast_log(LOG_WARNING, "Recv error: %s\n", strerror(errno));
28501 return 1;
28502 }
28503
28504 readbuf[res] = '\0';
28505
28506 if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
28507 return 1;
28508 }
28509
28510 if (ast_str_set(&req.data, 0, "%s", readbuf) == AST_DYNSTR_BUILD_FAILED) {
28511 return -1;
28512 }
28513
28514 req.socket.fd = sipsock;
28515 set_socket_transport(&req.socket, SIP_TRANSPORT_UDP);
28516 req.socket.tcptls_session = NULL;
28517 req.socket.port = htons(ast_sockaddr_port(&bindaddr));
28518
28519 handle_request_do(&req, &addr);
28520 deinit_req(&req);
28521
28522 return 1;
28523 }
28524
28525
28526
28527
28528
28529 static int handle_request_do(struct sip_request *req, struct ast_sockaddr *addr)
28530 {
28531 struct sip_pvt *p;
28532 struct ast_channel *owner_chan_ref = NULL;
28533 int recount = 0;
28534 int nounlock = 0;
28535
28536 if (sip_debug_test_addr(addr))
28537 req->debug = 1;
28538 if (sip_cfg.pedanticsipchecking)
28539 lws2sws(req->data);
28540 if (req->debug) {
28541 ast_verbose("\n<--- SIP read from %s:%s --->\n%s\n<------------->\n",
28542 sip_get_transport(req->socket.type), ast_sockaddr_stringify(addr), ast_str_buffer(req->data));
28543 }
28544
28545 if (parse_request(req) == -1) {
28546 ast_str_reset(req->data);
28547 return 1;
28548 }
28549 req->method = find_sip_method(REQ_OFFSET_TO_STR(req, rlpart1));
28550
28551 if (req->debug)
28552 ast_verbose("--- (%d headers %d lines)%s ---\n", req->headers, req->lines, (req->headers + req->lines == 0) ? " Nat keepalive" : "");
28553
28554 if (req->headers < 2) {
28555 ast_str_reset(req->data);
28556 return 1;
28557 }
28558 ast_mutex_lock(&netlock);
28559
28560
28561 p = find_call(req, addr, req->method);
28562 if (p == NULL) {
28563 ast_debug(1, "Invalid SIP message - rejected , no callid, len %zu\n", ast_str_strlen(req->data));
28564 ast_mutex_unlock(&netlock);
28565 return 1;
28566 }
28567
28568 if (p->logger_callid) {
28569 ast_callid_threadassoc_add(p->logger_callid);
28570 }
28571
28572
28573
28574 owner_chan_ref = sip_pvt_lock_full(p);
28575
28576 copy_socket_data(&p->socket, &req->socket);
28577
28578 ast_sockaddr_copy(&p->recv, addr);
28579
28580
28581 if (p->owner) {
28582 req->authenticated = 1;
28583 }
28584
28585 if (p->do_history)
28586 append_history(p, "Rx", "%s / %s / %s", ast_str_buffer(req->data), sip_get_header(req, "CSeq"), REQ_OFFSET_TO_STR(req, rlpart2));
28587
28588 if (handle_incoming(p, req, addr, &recount, &nounlock) == -1) {
28589
28590 ast_debug(1, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
28591 }
28592
28593 if (recount) {
28594 ast_update_use_count();
28595 }
28596
28597 if (p->owner && !nounlock) {
28598 ast_channel_unlock(p->owner);
28599 }
28600 if (owner_chan_ref) {
28601 ast_channel_unref(owner_chan_ref);
28602 }
28603 sip_pvt_unlock(p);
28604 ao2_t_ref(p, -1, "throw away dialog ptr from find_call at end of routine");
28605 ast_mutex_unlock(&netlock);
28606
28607 if (p->logger_callid) {
28608 ast_callid_threadassoc_remove();
28609 }
28610
28611 return 1;
28612 }
28613
28614
28615
28616
28617
28618
28619
28620 static int sip_standard_port(enum sip_transport type, int port)
28621 {
28622 if (type & SIP_TRANSPORT_TLS)
28623 return port == STANDARD_TLS_PORT;
28624 else
28625 return port == STANDARD_SIP_PORT;
28626 }
28627
28628 static int threadinfo_locate_cb(void *obj, void *arg, int flags)
28629 {
28630 struct sip_threadinfo *th = obj;
28631 struct ast_sockaddr *s = arg;
28632
28633 if (!ast_sockaddr_cmp(s, &th->tcptls_session->remote_address)) {
28634 return CMP_MATCH | CMP_STOP;
28635 }
28636
28637 return 0;
28638 }
28639
28640
28641
28642
28643
28644
28645 static struct ast_tcptls_session_instance *sip_tcp_locate(struct ast_sockaddr *s)
28646 {
28647 struct sip_threadinfo *th;
28648 struct ast_tcptls_session_instance *tcptls_instance = NULL;
28649
28650 if ((th = ao2_callback(threadt, 0, threadinfo_locate_cb, s))) {
28651 tcptls_instance = (ao2_ref(th->tcptls_session, +1), th->tcptls_session);
28652 ao2_t_ref(th, -1, "decrement ref from callback");
28653 }
28654
28655 return tcptls_instance;
28656 }
28657
28658
28659
28660
28661
28662
28663 int get_address_family_filter(unsigned int transport)
28664 {
28665 const struct ast_sockaddr *addr = NULL;
28666
28667 if ((transport == SIP_TRANSPORT_UDP) || !transport) {
28668 addr = &bindaddr;
28669 } else if (transport == SIP_TRANSPORT_TCP || transport == SIP_TRANSPORT_WS) {
28670 addr = &sip_tcp_desc.local_address;
28671 } else if (transport == SIP_TRANSPORT_TLS || transport == SIP_TRANSPORT_WSS) {
28672 addr = &sip_tls_desc.local_address;
28673 }
28674
28675 if (ast_sockaddr_is_ipv6(addr) && ast_sockaddr_is_any(addr)) {
28676 return 0;
28677 }
28678
28679 return addr->ss.ss_family;
28680 }
28681
28682
28683 static int sip_prepare_socket(struct sip_pvt *p)
28684 {
28685 struct sip_socket *s = &p->socket;
28686 static const char name[] = "SIP socket";
28687 struct sip_threadinfo *th = NULL;
28688 struct ast_tcptls_session_instance *tcptls_session;
28689 struct ast_tcptls_session_args *ca;
28690 struct ast_sockaddr sa_tmp;
28691 pthread_t launched;
28692
28693
28694 if ((s->fd != -1) && (s->type == SIP_TRANSPORT_UDP)) {
28695 return s->fd;
28696 }
28697 if ((s->type & (SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS)) &&
28698 (s->tcptls_session) &&
28699 (s->tcptls_session->fd != -1)) {
28700 return s->tcptls_session->fd;
28701 }
28702 if ((s->type & (SIP_TRANSPORT_WS | SIP_TRANSPORT_WSS))) {
28703 return s->ws_session ? ast_websocket_fd(s->ws_session) : -1;
28704 }
28705
28706
28707
28708
28709 if (p->outboundproxy && p->outboundproxy->transport) {
28710 s->type = p->outboundproxy->transport;
28711 }
28712
28713 if (s->type == SIP_TRANSPORT_UDP) {
28714 s->fd = sipsock;
28715 return s->fd;
28716 }
28717
28718
28719
28720
28721
28722
28723
28724
28725
28726
28727
28728 ast_sockaddr_copy(&sa_tmp, sip_real_dst(p));
28729 if ((tcptls_session = sip_tcp_locate(&sa_tmp))) {
28730 s->fd = tcptls_session->fd;
28731 if (s->tcptls_session) {
28732 ao2_ref(s->tcptls_session, -1);
28733 s->tcptls_session = NULL;
28734 }
28735 s->tcptls_session = tcptls_session;
28736 return s->fd;
28737
28738 } else if (s->tcptls_session) {
28739 return s->fd;
28740 }
28741
28742
28743
28744 if (!(ca = ao2_alloc(sizeof(*ca), sip_tcptls_client_args_destructor)) ||
28745 !(ca->name = ast_strdup(name))) {
28746 goto create_tcptls_session_fail;
28747 }
28748 ca->accept_fd = -1;
28749 ast_sockaddr_copy(&ca->remote_address,sip_real_dst(p));
28750
28751 if (s->type == SIP_TRANSPORT_TLS) {
28752 if (!(ca->tls_cfg = ast_calloc(1, sizeof(*ca->tls_cfg)))) {
28753 goto create_tcptls_session_fail;
28754 }
28755 memcpy(ca->tls_cfg, &default_tls_cfg, sizeof(*ca->tls_cfg));
28756
28757 if (!(ca->tls_cfg->certfile = ast_strdup(default_tls_cfg.certfile)) ||
28758 !(ca->tls_cfg->pvtfile = ast_strdup(default_tls_cfg.pvtfile)) ||
28759 !(ca->tls_cfg->cipher = ast_strdup(default_tls_cfg.cipher)) ||
28760 !(ca->tls_cfg->cafile = ast_strdup(default_tls_cfg.cafile)) ||
28761 !(ca->tls_cfg->capath = ast_strdup(default_tls_cfg.capath))) {
28762
28763 goto create_tcptls_session_fail;
28764 }
28765
28766
28767 if (!ast_strlen_zero(p->tohost)) {
28768 ast_copy_string(ca->hostname, p->tohost, sizeof(ca->hostname));
28769 }
28770 }
28771
28772
28773 if (!(s->tcptls_session = ast_tcptls_client_create(ca))) {
28774 goto create_tcptls_session_fail;
28775 }
28776
28777 s->fd = s->tcptls_session->fd;
28778
28779
28780
28781
28782
28783 if (!(th = sip_threadinfo_create(s->tcptls_session, s->type))) {
28784 goto create_tcptls_session_fail;
28785 }
28786
28787
28788 ao2_ref(s->tcptls_session, +1);
28789
28790 if (ast_pthread_create_detached_background(&launched, NULL, sip_tcp_worker_fn, s->tcptls_session)) {
28791 ast_debug(1, "Unable to launch '%s'.", ca->name);
28792 ao2_ref(s->tcptls_session, -1);
28793 goto create_tcptls_session_fail;
28794 }
28795
28796 return s->fd;
28797
28798 create_tcptls_session_fail:
28799 if (ca) {
28800 ao2_t_ref(ca, -1, "failed to create client, getting rid of client tcptls_session arguments");
28801 }
28802 if (s->tcptls_session) {
28803 ast_tcptls_close_session_file(s->tcptls_session);
28804 s->fd = -1;
28805 ao2_ref(s->tcptls_session, -1);
28806 s->tcptls_session = NULL;
28807 }
28808 if (th) {
28809 ao2_t_unlink(threadt, th, "Removing tcptls thread info object, thread failed to open");
28810 }
28811
28812 return -1;
28813 }
28814
28815
28816
28817
28818
28819 static int get_cached_mwi(struct sip_peer *peer, int *new, int *old)
28820 {
28821 struct sip_mailbox *mailbox;
28822 int in_cache;
28823
28824 in_cache = 0;
28825 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
28826 struct ast_event *event;
28827 event = ast_event_get_cached(AST_EVENT_MWI,
28828 AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox->mailbox,
28829 AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, S_OR(mailbox->context, "default"),
28830 AST_EVENT_IE_END);
28831 if (!event)
28832 continue;
28833 *new += ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
28834 *old += ast_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS);
28835 ast_event_destroy(event);
28836 in_cache = 1;
28837 }
28838
28839 return in_cache;
28840 }
28841
28842
28843
28844
28845
28846 static int sip_send_mwi_to_peer(struct sip_peer *peer, int cache_only)
28847 {
28848
28849 struct sip_pvt *p;
28850 int newmsgs = 0, oldmsgs = 0;
28851 const char *vmexten = NULL;
28852
28853 ao2_lock(peer);
28854
28855 if (peer->vmexten) {
28856 vmexten = ast_strdupa(peer->vmexten);
28857 }
28858
28859 if (ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY) && !peer->mwipvt) {
28860 update_peer_lastmsgssent(peer, -1, 1);
28861 ao2_unlock(peer);
28862 return -1;
28863 }
28864
28865
28866 if (ast_sockaddr_isnull(&peer->addr) && ast_sockaddr_isnull(&peer->defaddr)) {
28867 update_peer_lastmsgssent(peer, -1, 1);
28868 ao2_unlock(peer);
28869 return -1;
28870 }
28871
28872
28873 if (!get_cached_mwi(peer, &newmsgs, &oldmsgs) && !cache_only) {
28874
28875 struct ast_str *mailbox_str = ast_str_alloca(512);
28876 peer_mailboxes_to_str(&mailbox_str, peer);
28877
28878 if (!ast_str_strlen(mailbox_str)) {
28879 ao2_unlock(peer);
28880 return -1;
28881 }
28882 ao2_unlock(peer);
28883
28884 if (!ast_str_strlen(mailbox_str)) {
28885 update_peer_lastmsgssent(peer, -1, 0);
28886 return 0;
28887 }
28888 ast_app_inboxcount(ast_str_buffer(mailbox_str), &newmsgs, &oldmsgs);
28889 ao2_lock(peer);
28890 }
28891
28892 if (peer->mwipvt) {
28893
28894 p = dialog_ref(peer->mwipvt, "sip_send_mwi_to_peer: Setting dialog ptr p from peer->mwipvt");
28895 ao2_unlock(peer);
28896 } else {
28897 ao2_unlock(peer);
28898
28899 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL, NULL))) {
28900 update_peer_lastmsgssent(peer, -1, 0);
28901 return -1;
28902 }
28903
28904
28905
28906
28907
28908 set_socket_transport(&p->socket, 0);
28909 if (create_addr_from_peer(p, peer)) {
28910
28911 dialog_unlink_all(p);
28912 dialog_unref(p, "unref dialog p just created via sip_alloc");
28913 update_peer_lastmsgssent(peer, -1, 0);
28914 return -1;
28915 }
28916
28917 ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
28918 build_via(p);
28919
28920 ao2_lock(peer);
28921 if (!ast_strlen_zero(peer->mwi_from)) {
28922 ast_string_field_set(p, mwi_from, peer->mwi_from);
28923 } else if (!ast_strlen_zero(default_mwi_from)) {
28924 ast_string_field_set(p, mwi_from, default_mwi_from);
28925 }
28926 ao2_unlock(peer);
28927
28928
28929 change_callid_pvt(p, NULL);
28930
28931
28932 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
28933 }
28934
28935
28936
28937 sip_pvt_lock(p);
28938
28939
28940 ast_set_flag(&p->flags[0], SIP_OUTGOING);
28941
28942 transmit_notify_with_mwi(p, newmsgs, oldmsgs, vmexten);
28943 sip_pvt_unlock(p);
28944 dialog_unref(p, "unref dialog ptr p just before it goes out of scope at the end of sip_send_mwi_to_peer.");
28945
28946 update_peer_lastmsgssent(peer, ((newmsgs > 0x7fff ? 0x7fff0000 : (newmsgs << 16)) | (oldmsgs > 0xffff ? 0xffff : oldmsgs)), 0);
28947
28948 return 0;
28949 }
28950
28951
28952
28953
28954
28955
28956 static int check_rtp_timeout(struct sip_pvt *dialog, time_t t)
28957 {
28958 int timeout;
28959 int hold_timeout;
28960 int keepalive;
28961
28962 if (!dialog->rtp) {
28963
28964
28965
28966
28967 return CMP_MATCH;
28968 }
28969
28970
28971 if (!dialog->owner) {
28972 return CMP_MATCH;
28973 }
28974
28975
28976 if (!ast_sockaddr_isnull(&dialog->redirip)) {
28977 return CMP_MATCH;
28978 }
28979
28980
28981 if (dialog->t38.state == T38_ENABLED) {
28982 return CMP_MATCH;
28983 }
28984
28985 if (ast_channel_state(dialog->owner) != AST_STATE_UP) {
28986 return 0;
28987 }
28988
28989
28990 timeout = ast_rtp_instance_get_timeout(dialog->rtp);
28991 hold_timeout = ast_rtp_instance_get_hold_timeout(dialog->rtp);
28992 keepalive = ast_rtp_instance_get_keepalive(dialog->rtp);
28993
28994
28995 if (!keepalive && !timeout && !hold_timeout) {
28996 return CMP_MATCH;
28997 }
28998
28999
29000 if (dialog->lastrtptx && keepalive && (t > dialog->lastrtptx + keepalive)) {
29001
29002 dialog->lastrtptx = time(NULL);
29003 ast_rtp_instance_sendcng(dialog->rtp, 0);
29004 }
29005
29006
29007
29008
29009
29010
29011
29012
29013 if (dialog->lastrtprx && (timeout || hold_timeout) && (t > dialog->lastrtprx + timeout)) {
29014 if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD) || (hold_timeout && (t > dialog->lastrtprx + hold_timeout))) {
29015
29016 if (timeout) {
29017 if (!dialog->owner || ast_channel_trylock(dialog->owner)) {
29018
29019
29020
29021
29022 return 0;
29023 }
29024 ast_log(LOG_NOTICE, "Disconnecting call '%s' for lack of RTP activity in %ld seconds\n",
29025 ast_channel_name(dialog->owner), (long) (t - dialog->lastrtprx));
29026 manager_event(EVENT_FLAG_CALL, "SessionTimeout", "Source: RTPTimeout\r\n"
29027 "Channel: %s\r\nUniqueid: %s\r\n", ast_channel_name(dialog->owner), ast_channel_uniqueid(dialog->owner));
29028
29029 ast_softhangup_nolock(dialog->owner, AST_SOFTHANGUP_DEV);
29030 ast_channel_unlock(dialog->owner);
29031
29032
29033
29034
29035 ast_rtp_instance_set_timeout(dialog->rtp, 0);
29036 ast_rtp_instance_set_hold_timeout(dialog->rtp, 0);
29037 if (dialog->vrtp) {
29038 ast_rtp_instance_set_timeout(dialog->vrtp, 0);
29039 ast_rtp_instance_set_hold_timeout(dialog->vrtp, 0);
29040 }
29041
29042 return CMP_MATCH;
29043 }
29044 }
29045 }
29046 return 0;
29047 }
29048
29049
29050
29051
29052
29053 static void *do_monitor(void *data)
29054 {
29055 int res;
29056 time_t t;
29057 int reloading;
29058
29059
29060 if (sipsock > -1) {
29061 sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
29062 }
29063
29064
29065 for(;;) {
29066
29067 ast_mutex_lock(&sip_reload_lock);
29068 reloading = sip_reloading;
29069 sip_reloading = FALSE;
29070 ast_mutex_unlock(&sip_reload_lock);
29071 if (reloading) {
29072 ast_verb(1, "Reloading SIP\n");
29073 sip_do_reload(sip_reloadreason);
29074
29075
29076 if (sipsock > -1) {
29077 if (sipsock_read_id) {
29078 sipsock_read_id = ast_io_change(io, sipsock_read_id, sipsock, NULL, 0, NULL);
29079 } else {
29080 sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
29081 }
29082 } else if (sipsock_read_id) {
29083 ast_io_remove(io, sipsock_read_id);
29084 sipsock_read_id = NULL;
29085 }
29086 }
29087
29088
29089 t = time(NULL);
29090
29091
29092
29093
29094
29095 ao2_t_callback(dialogs_rtpcheck, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE,
29096 dialog_checkrtp_cb, &t,
29097 "callback to check rtptimeout and hangup calls if necessary");
29098
29099
29100
29101
29102 ao2_t_callback(dialogs_needdestroy, OBJ_NODATA | OBJ_MULTIPLE, dialog_needdestroy,
29103 NULL, "callback to check dialogs which need to be destroyed");
29104
29105
29106
29107
29108
29109
29110
29111 pthread_testcancel();
29112
29113 res = ast_sched_wait(sched);
29114 if ((res < 0) || (res > 1000)) {
29115 res = 1000;
29116 }
29117 res = ast_io_wait(io, res);
29118 if (res > 20) {
29119 ast_debug(1, "chan_sip: ast_io_wait ran %d all at once\n", res);
29120 }
29121 ast_mutex_lock(&monlock);
29122 res = ast_sched_runq(sched);
29123 if (res >= 20) {
29124 ast_debug(1, "chan_sip: ast_sched_runq ran %d all at once\n", res);
29125 }
29126 ast_mutex_unlock(&monlock);
29127 }
29128
29129
29130 return NULL;
29131 }
29132
29133
29134 static int restart_monitor(void)
29135 {
29136
29137 if (monitor_thread == AST_PTHREADT_STOP)
29138 return 0;
29139 ast_mutex_lock(&monlock);
29140 if (monitor_thread == pthread_self()) {
29141 ast_mutex_unlock(&monlock);
29142 ast_log(LOG_WARNING, "Cannot kill myself\n");
29143 return -1;
29144 }
29145 if (monitor_thread != AST_PTHREADT_NULL) {
29146
29147 pthread_kill(monitor_thread, SIGURG);
29148 } else {
29149
29150 if (ast_pthread_create_background(&monitor_thread, NULL, do_monitor, NULL) < 0) {
29151 ast_mutex_unlock(&monlock);
29152 ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
29153 return -1;
29154 }
29155 }
29156 ast_mutex_unlock(&monlock);
29157 return 0;
29158 }
29159
29160 static void acl_change_event_cb(const struct ast_event *event, void *userdata)
29161 {
29162 ast_log(LOG_NOTICE, "Reloading chan_sip in response to ACL change event.\n");
29163
29164 ast_mutex_lock(&sip_reload_lock);
29165
29166 if (sip_reloading) {
29167 ast_verbose("Previous SIP reload not yet done\n");
29168 } else {
29169 sip_reloading = TRUE;
29170 sip_reloadreason = CHANNEL_ACL_RELOAD;
29171 }
29172
29173 ast_mutex_unlock(&sip_reload_lock);
29174
29175 restart_monitor();
29176 }
29177
29178
29179 static void restart_session_timer(struct sip_pvt *p)
29180 {
29181 if (!p->stimer) {
29182 ast_log(LOG_WARNING, "Null stimer in restart_session_timer - %s\n", p->callid);
29183 return;
29184 }
29185
29186 if (p->stimer->st_active == TRUE) {
29187 ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
29188 AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
29189 dialog_unref(p, "Removing session timer ref"));
29190 start_session_timer(p);
29191 }
29192 }
29193
29194
29195
29196 static void stop_session_timer(struct sip_pvt *p)
29197 {
29198 if (!p->stimer) {
29199 ast_log(LOG_WARNING, "Null stimer in stop_session_timer - %s\n", p->callid);
29200 return;
29201 }
29202
29203 if (p->stimer->st_active == TRUE) {
29204 p->stimer->st_active = FALSE;
29205 ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
29206 AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
29207 dialog_unref(p, "removing session timer ref"));
29208 }
29209 }
29210
29211
29212
29213 static void start_session_timer(struct sip_pvt *p)
29214 {
29215 unsigned int timeout_ms;
29216
29217 if (!p->stimer) {
29218 ast_log(LOG_WARNING, "Null stimer in start_session_timer - %s\n", p->callid);
29219 return;
29220 }
29221
29222 if (p->stimer->st_schedid > -1) {
29223
29224 ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
29225 AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
29226 dialog_unref(p, "unref stimer->st_schedid from dialog"));
29227 }
29228
29229
29230
29231
29232
29233
29234
29235
29236
29237
29238 timeout_ms = (1000 * p->stimer->st_interval);
29239 if (p->stimer->st_ref == SESSION_TIMER_REFRESHER_US) {
29240 timeout_ms /= 2;
29241 } else {
29242 timeout_ms -= MIN(timeout_ms / 3, 32000);
29243 }
29244
29245 p->stimer->st_schedid = ast_sched_add(sched, timeout_ms, proc_session_timer,
29246 dialog_ref(p, "adding session timer ref"));
29247
29248 if (p->stimer->st_schedid < 0) {
29249 dialog_unref(p, "removing session timer ref");
29250 ast_log(LOG_ERROR, "ast_sched_add failed - %s\n", p->callid);
29251 } else {
29252 p->stimer->st_active = TRUE;
29253 ast_debug(2, "Session timer started: %d - %s %ums\n", p->stimer->st_schedid, p->callid, timeout_ms);
29254 }
29255 }
29256
29257
29258
29259 static int proc_session_timer(const void *vp)
29260 {
29261 struct sip_pvt *p = (struct sip_pvt *) vp;
29262 int res = 0;
29263
29264 if (!p->stimer) {
29265 ast_log(LOG_WARNING, "Null stimer in proc_session_timer - %s\n", p->callid);
29266 goto return_unref;
29267 }
29268
29269 ast_debug(2, "Session timer expired: %d - %s\n", p->stimer->st_schedid, p->callid);
29270
29271 if (!p->owner) {
29272 goto return_unref;
29273 }
29274
29275 if ((p->stimer->st_active != TRUE) || (ast_channel_state(p->owner) != AST_STATE_UP)) {
29276 goto return_unref;
29277 }
29278
29279 if (p->stimer->st_ref == SESSION_TIMER_REFRESHER_US) {
29280 res = 1;
29281 if (T38_ENABLED == p->t38.state) {
29282 transmit_reinvite_with_sdp(p, TRUE, TRUE);
29283 } else {
29284 transmit_reinvite_with_sdp(p, FALSE, TRUE);
29285 }
29286 } else {
29287 if (p->stimer->quit_flag) {
29288 goto return_unref;
29289 }
29290 ast_log(LOG_WARNING, "Session-Timer expired - %s\n", p->callid);
29291 sip_pvt_lock(p);
29292 while (p->owner && ast_channel_trylock(p->owner)) {
29293 sip_pvt_unlock(p);
29294 usleep(1);
29295 if (p->stimer && p->stimer->quit_flag) {
29296 goto return_unref;
29297 }
29298 sip_pvt_lock(p);
29299 }
29300
29301 manager_event(EVENT_FLAG_CALL, "SessionTimeout", "Source: SIPSessionTimer\r\n"
29302 "Channel: %s\r\nUniqueid: %s\r\n", ast_channel_name(p->owner), ast_channel_uniqueid(p->owner));
29303 ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
29304 ast_channel_unlock(p->owner);
29305 sip_pvt_unlock(p);
29306 }
29307
29308 return_unref:
29309 if (!res) {
29310
29311 if (p->stimer) {
29312 ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
29313 p->stimer->st_schedid = -1;
29314 stop_session_timer(p);
29315 }
29316
29317
29318
29319 dialog_unref(p, "removing session timer ref");
29320 }
29321
29322 return res;
29323 }
29324
29325
29326
29327 int parse_minse (const char *p_hdrval, int *const p_interval)
29328 {
29329 if (ast_strlen_zero(p_hdrval)) {
29330 ast_log(LOG_WARNING, "Null Min-SE header\n");
29331 return -1;
29332 }
29333
29334 *p_interval = 0;
29335 p_hdrval = ast_skip_blanks(p_hdrval);
29336 if (!sscanf(p_hdrval, "%30d", p_interval)) {
29337 ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
29338 return -1;
29339 }
29340
29341 ast_debug(2, "Received Min-SE: %d\n", *p_interval);
29342 return 0;
29343 }
29344
29345
29346
29347 int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher_param *const p_ref)
29348 {
29349 char *p_token;
29350 int ref_idx;
29351 char *p_se_hdr;
29352
29353 if (ast_strlen_zero(p_hdrval)) {
29354 ast_log(LOG_WARNING, "Null Session-Expires header\n");
29355 return -1;
29356 }
29357
29358 *p_ref = SESSION_TIMER_REFRESHER_PARAM_UNKNOWN;
29359 *p_interval = 0;
29360
29361 p_se_hdr = ast_strdupa(p_hdrval);
29362 p_se_hdr = ast_skip_blanks(p_se_hdr);
29363
29364 while ((p_token = strsep(&p_se_hdr, ";"))) {
29365 p_token = ast_skip_blanks(p_token);
29366 if (!sscanf(p_token, "%30d", p_interval)) {
29367 ast_log(LOG_WARNING, "Parsing of Session-Expires failed\n");
29368 return -1;
29369 }
29370
29371 ast_debug(2, "Session-Expires: %d\n", *p_interval);
29372
29373 if (!p_se_hdr)
29374 continue;
29375
29376 p_se_hdr = ast_skip_blanks(p_se_hdr);
29377 ref_idx = strlen("refresher=");
29378 if (!strncasecmp(p_se_hdr, "refresher=", ref_idx)) {
29379 p_se_hdr += ref_idx;
29380 p_se_hdr = ast_skip_blanks(p_se_hdr);
29381
29382 if (!strncasecmp(p_se_hdr, "uac", strlen("uac"))) {
29383 *p_ref = SESSION_TIMER_REFRESHER_PARAM_UAC;
29384 ast_debug(2, "Refresher: UAC\n");
29385 } else if (!strncasecmp(p_se_hdr, "uas", strlen("uas"))) {
29386 *p_ref = SESSION_TIMER_REFRESHER_PARAM_UAS;
29387 ast_debug(2, "Refresher: UAS\n");
29388 } else {
29389 ast_log(LOG_WARNING, "Invalid refresher value %s\n", p_se_hdr);
29390 return -1;
29391 }
29392 break;
29393 }
29394 }
29395 return 0;
29396 }
29397
29398
29399
29400
29401
29402
29403
29404
29405
29406 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp)
29407 {
29408 int rtn;
29409 const char *p_hdrval;
29410 int minse;
29411
29412 p_hdrval = sip_get_header(rsp, "Min-SE");
29413 if (ast_strlen_zero(p_hdrval)) {
29414 ast_log(LOG_WARNING, "422 response without a Min-SE header %s\n", p_hdrval);
29415 return;
29416 }
29417 rtn = parse_minse(p_hdrval, &minse);
29418 if (rtn != 0) {
29419 ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
29420 return;
29421 }
29422 p->stimer->st_cached_min_se = minse;
29423 if (p->stimer->st_interval < minse) {
29424 p->stimer->st_interval = minse;
29425 }
29426 transmit_invite(p, SIP_INVITE, 1, 2, NULL);
29427 }
29428
29429
29430
29431
29432
29433
29434 int st_get_se(struct sip_pvt *p, int max)
29435 {
29436 if (max == TRUE) {
29437 if (p->stimer->st_cached_max_se) {
29438 return p->stimer->st_cached_max_se;
29439 }
29440 if (p->relatedpeer) {
29441 p->stimer->st_cached_max_se = p->relatedpeer->stimer.st_max_se;
29442 return (p->stimer->st_cached_max_se);
29443 }
29444 p->stimer->st_cached_max_se = global_max_se;
29445 return (p->stimer->st_cached_max_se);
29446 }
29447
29448 if (p->stimer->st_cached_min_se) {
29449 return p->stimer->st_cached_min_se;
29450 }
29451 if (p->relatedpeer) {
29452 p->stimer->st_cached_min_se = p->relatedpeer->stimer.st_min_se;
29453 return (p->stimer->st_cached_min_se);
29454 }
29455 p->stimer->st_cached_min_se = global_min_se;
29456 return (p->stimer->st_cached_min_se);
29457 }
29458
29459
29460
29461
29462
29463
29464
29465
29466 enum st_refresher st_get_refresher(struct sip_pvt *p)
29467 {
29468 if (p->stimer->st_cached_ref != SESSION_TIMER_REFRESHER_AUTO) {
29469 return p->stimer->st_cached_ref;
29470 }
29471
29472 if (p->relatedpeer) {
29473 p->stimer->st_cached_ref = (p->relatedpeer->stimer.st_ref == SESSION_TIMER_REFRESHER_PARAM_UAC) ? SESSION_TIMER_REFRESHER_THEM : SESSION_TIMER_REFRESHER_US;
29474 return p->stimer->st_cached_ref;
29475 }
29476
29477 p->stimer->st_cached_ref = (global_st_refresher == SESSION_TIMER_REFRESHER_PARAM_UAC) ? SESSION_TIMER_REFRESHER_THEM : SESSION_TIMER_REFRESHER_US;
29478 return p->stimer->st_cached_ref;
29479 }
29480
29481
29482
29483
29484
29485
29486
29487
29488 enum st_mode st_get_mode(struct sip_pvt *p, int no_cached)
29489 {
29490 if (!p->stimer) {
29491 sip_st_alloc(p);
29492 if (!p->stimer) {
29493 return SESSION_TIMER_MODE_INVALID;
29494 }
29495 }
29496
29497 if (!no_cached && p->stimer->st_cached_mode != SESSION_TIMER_MODE_INVALID)
29498 return p->stimer->st_cached_mode;
29499
29500 if (p->relatedpeer) {
29501 p->stimer->st_cached_mode = p->relatedpeer->stimer.st_mode_oper;
29502 return p->stimer->st_cached_mode;
29503 }
29504
29505 p->stimer->st_cached_mode = global_st_mode;
29506 return global_st_mode;
29507 }
29508
29509
29510 static int sip_send_keepalive(const void *data)
29511 {
29512 struct sip_peer *peer = (struct sip_peer*) data;
29513 int res = 0;
29514 const char keepalive[] = "\r\n";
29515
29516 peer->keepalivesend = -1;
29517
29518 if (!peer->keepalive || ast_sockaddr_isnull(&peer->addr)) {
29519 sip_unref_peer(peer, "release keepalive peer ref");
29520 return 0;
29521 }
29522
29523
29524 if ((peer->socket.fd != -1) && (peer->socket.type == SIP_TRANSPORT_UDP)) {
29525 res = ast_sendto(peer->socket.fd, keepalive, sizeof(keepalive), 0, &peer->addr);
29526 } else if ((peer->socket.type & (SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS)) &&
29527 (peer->socket.tcptls_session) &&
29528 (peer->socket.tcptls_session->fd != -1)) {
29529 res = sip_tcptls_write(peer->socket.tcptls_session, keepalive, sizeof(keepalive));
29530 } else if (peer->socket.type == SIP_TRANSPORT_UDP) {
29531 res = ast_sendto(sipsock, keepalive, sizeof(keepalive), 0, &peer->addr);
29532 }
29533
29534 if (res == -1) {
29535 switch (errno) {
29536 case EBADF:
29537 case EHOSTUNREACH:
29538 case ENETDOWN:
29539 case ENETUNREACH:
29540 case ECONNREFUSED:
29541 res = XMIT_ERROR;
29542 }
29543 }
29544
29545 if (res != sizeof(keepalive)) {
29546 ast_log(LOG_WARNING, "sip_send_keepalive to %s returned %d: %s\n", ast_sockaddr_stringify(&peer->addr), res, strerror(errno));
29547 }
29548
29549 AST_SCHED_REPLACE_UNREF(peer->keepalivesend, sched,
29550 peer->keepalive * 1000, sip_send_keepalive, peer,
29551 sip_unref_peer(_data, "removing keepalive peer ref"),
29552 sip_unref_peer(peer, "removing keepalive peer ref"),
29553 sip_ref_peer(peer, "adding keepalive peer ref"));
29554
29555 sip_unref_peer(peer, "release keepalive peer ref");
29556
29557 return 0;
29558 }
29559
29560
29561 static int sip_poke_noanswer(const void *data)
29562 {
29563 struct sip_peer *peer = (struct sip_peer *)data;
29564
29565 peer->pokeexpire = -1;
29566
29567 if (peer->lastms > -1) {
29568 ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE! Last qualify: %d\n", peer->name, peer->lastms);
29569 if (sip_cfg.peer_rtupdate) {
29570 ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", "-1", SENTINEL);
29571 }
29572 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer->name, -1);
29573 if (sip_cfg.regextenonqualify) {
29574 register_peer_exten(peer, FALSE);
29575 }
29576 }
29577
29578 if (peer->call) {
29579 dialog_unlink_all(peer->call);
29580 peer->call = dialog_unref(peer->call, "unref dialog peer->call");
29581
29582 }
29583
29584
29585 if (peer->lastms > -1) {
29586 peer->lastms = -1;
29587 ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "SIP/%s", peer->name);
29588 }
29589
29590
29591 AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
29592 DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer,
29593 sip_unref_peer(_data, "removing poke peer ref"),
29594 sip_unref_peer(peer, "removing poke peer ref"),
29595 sip_ref_peer(peer, "adding poke peer ref"));
29596
29597
29598 sip_unref_peer(peer, "release peer poke noanswer ref");
29599
29600 return 0;
29601 }
29602
29603
29604
29605
29606
29607
29608
29609
29610
29611 static int sip_poke_peer(struct sip_peer *peer, int force)
29612 {
29613 struct sip_pvt *p;
29614 int xmitres = 0;
29615
29616 if ((!peer->maxms && !force) || ast_sockaddr_isnull(&peer->addr)) {
29617
29618
29619 AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
29620 sip_unref_peer(peer, "removing poke peer ref"));
29621
29622 peer->lastms = 0;
29623 if (peer->call) {
29624 peer->call = dialog_unref(peer->call, "unref dialog peer->call");
29625 }
29626 return 0;
29627 }
29628 if (peer->call) {
29629 if (sipdebug) {
29630 ast_log(LOG_NOTICE, "Still have a QUALIFY dialog active, deleting\n");
29631 }
29632 dialog_unlink_all(peer->call);
29633 peer->call = dialog_unref(peer->call, "unref dialog peer->call");
29634
29635 }
29636 if (!(p = sip_alloc(NULL, NULL, 0, SIP_OPTIONS, NULL, NULL))) {
29637 return -1;
29638 }
29639 peer->call = dialog_ref(p, "copy sip alloc from p to peer->call");
29640
29641 p->sa = peer->addr;
29642 p->recv = peer->addr;
29643 copy_socket_data(&p->socket, &peer->socket);
29644 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
29645 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
29646 ast_copy_flags(&p->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
29647
29648
29649 if (!ast_strlen_zero(peer->fullcontact)) {
29650 ast_string_field_set(p, fullcontact, peer->fullcontact);
29651 }
29652
29653 if (!ast_strlen_zero(peer->fromuser)) {
29654 ast_string_field_set(p, fromuser, peer->fromuser);
29655 }
29656
29657 if (!ast_strlen_zero(peer->tohost)) {
29658 ast_string_field_set(p, tohost, peer->tohost);
29659 } else {
29660 ast_string_field_set(p, tohost, ast_sockaddr_stringify_host_remote(&peer->addr));
29661 }
29662
29663
29664 ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
29665 build_via(p);
29666
29667
29668 change_callid_pvt(p, NULL);
29669
29670 AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
29671 sip_unref_peer(peer, "removing poke peer ref"));
29672
29673 if (p->relatedpeer)
29674 p->relatedpeer = sip_unref_peer(p->relatedpeer,"unsetting the relatedpeer field in the dialog, before it is set to something else.");
29675 p->relatedpeer = sip_ref_peer(peer, "setting the relatedpeer field in the dialog");
29676 ast_set_flag(&p->flags[0], SIP_OUTGOING);
29677 #ifdef VOCAL_DATA_HACK
29678 ast_copy_string(p->username, "__VOCAL_DATA_SHOULD_READ_THE_SIP_SPEC__", sizeof(p->username));
29679 xmitres = transmit_invite(p, SIP_INVITE, 0, 2, NULL);
29680 #else
29681 xmitres = transmit_invite(p, SIP_OPTIONS, 0, 2, NULL);
29682 #endif
29683 peer->ps = ast_tvnow();
29684 if (xmitres == XMIT_ERROR) {
29685
29686 sip_poke_noanswer(sip_ref_peer(peer, "add ref for peerexpire (fake, for sip_poke_noanswer to remove)"));
29687 } else if (!force) {
29688 AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, peer->maxms * 2, sip_poke_noanswer, peer,
29689 sip_unref_peer(_data, "removing poke peer ref"),
29690 sip_unref_peer(peer, "removing poke peer ref"),
29691 sip_ref_peer(peer, "adding poke peer ref"));
29692 }
29693 dialog_unref(p, "unref dialog at end of sip_poke_peer, obtained from sip_alloc, just before it goes out of scope");
29694 return 0;
29695 }
29696
29697
29698
29699
29700
29701
29702
29703
29704
29705
29706
29707
29708
29709
29710
29711
29712
29713
29714
29715
29716
29717
29718
29719
29720
29721
29722
29723
29724
29725
29726
29727
29728
29729
29730 static int sip_devicestate(const char *data)
29731 {
29732 char *host;
29733 char *tmp;
29734 struct sip_peer *p;
29735
29736 int res = AST_DEVICE_INVALID;
29737
29738
29739 host = ast_strdupa(data ? data : "");
29740 if ((tmp = strchr(host, '@')))
29741 host = tmp + 1;
29742
29743 ast_debug(3, "Checking device state for peer %s\n", host);
29744
29745
29746
29747
29748
29749
29750
29751
29752 if ((p = sip_find_peer(host, NULL, FALSE, FINDALLDEVICES, TRUE, 0))) {
29753 if (!(ast_sockaddr_isnull(&p->addr) && ast_sockaddr_isnull(&p->defaddr))) {
29754
29755
29756
29757
29758
29759
29760
29761
29762
29763
29764
29765 if (p->onhold)
29766
29767 res = AST_DEVICE_ONHOLD;
29768 else if (p->ringing) {
29769 if (p->ringing == p->inuse)
29770 res = AST_DEVICE_RINGING;
29771 else
29772 res = AST_DEVICE_RINGINUSE;
29773 } else if (p->call_limit && (p->inuse == p->call_limit))
29774
29775 res = AST_DEVICE_BUSY;
29776 else if (p->call_limit && p->busy_level && p->inuse >= p->busy_level)
29777
29778 res = AST_DEVICE_BUSY;
29779 else if (p->call_limit && p->inuse)
29780
29781 res = AST_DEVICE_INUSE;
29782 else if (p->maxms && ((p->lastms > p->maxms) || (p->lastms < 0)))
29783
29784 res = AST_DEVICE_UNAVAILABLE;
29785 else
29786 res = AST_DEVICE_NOT_INUSE;
29787 } else {
29788
29789 res = AST_DEVICE_UNAVAILABLE;
29790 }
29791 sip_unref_peer(p, "sip_unref_peer, from sip_devicestate, release ref from sip_find_peer");
29792 }
29793
29794 return res;
29795 }
29796
29797
29798
29799
29800
29801
29802
29803
29804
29805
29806
29807
29808
29809
29810
29811
29812 static struct ast_channel *sip_request_call(const char *type, struct ast_format_cap *cap, const struct ast_channel *requestor, const char *dest, int *cause)
29813 {
29814 struct sip_pvt *p;
29815 struct ast_channel *tmpc = NULL;
29816 char *ext = NULL, *host;
29817 char tmp[256];
29818 char tmp2[256];
29819 char *dnid;
29820 char *secret = NULL;
29821 char *md5secret = NULL;
29822 char *authname = NULL;
29823 char *trans = NULL;
29824 char dialstring[256];
29825 char *remote_address;
29826 enum sip_transport transport = 0;
29827 struct ast_callid *callid;
29828 AST_DECLARE_APP_ARGS(args,
29829 AST_APP_ARG(peerorhost);
29830 AST_APP_ARG(exten);
29831 AST_APP_ARG(remote_address);
29832 );
29833
29834
29835
29836
29837
29838
29839
29840
29841 if (!(ast_format_cap_has_type(cap, AST_FORMAT_TYPE_AUDIO))) {
29842 ast_log(LOG_NOTICE, "Asked to get a channel of unsupported format %s while capability is %s\n",
29843 ast_getformatname_multiple(tmp, sizeof(tmp), cap),
29844 ast_getformatname_multiple(tmp2, sizeof(tmp2), sip_cfg.caps));
29845 *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
29846 return NULL;
29847 }
29848 ast_debug(1, "Asked to create a SIP channel with formats: %s\n", ast_getformatname_multiple(tmp, sizeof(tmp), cap));
29849
29850 if (ast_strlen_zero(dest)) {
29851 ast_log(LOG_ERROR, "Unable to create channel with empty destination.\n");
29852 *cause = AST_CAUSE_CHANNEL_UNACCEPTABLE;
29853 return NULL;
29854 }
29855
29856 callid = ast_read_threadstorage_callid();
29857 if (!(p = sip_alloc(NULL, NULL, 0, SIP_INVITE, NULL, callid))) {
29858 ast_log(LOG_ERROR, "Unable to build sip pvt data for '%s' (Out of memory or socket error)\n", dest);
29859 *cause = AST_CAUSE_SWITCH_CONGESTION;
29860 if (callid) {
29861 ast_callid_unref(callid);
29862 }
29863 return NULL;
29864 }
29865
29866 p->outgoing_call = TRUE;
29867
29868 snprintf(dialstring, sizeof(dialstring), "%s/%s", type, dest);
29869 ast_string_field_set(p, dialstring, dialstring);
29870
29871 if (!(p->options = ast_calloc(1, sizeof(*p->options)))) {
29872 dialog_unlink_all(p);
29873 dialog_unref(p, "unref dialog p from mem fail");
29874
29875 ast_log(LOG_ERROR, "Unable to build option SIP data structure - Out of memory\n");
29876 *cause = AST_CAUSE_SWITCH_CONGESTION;
29877 if (callid) {
29878 ast_callid_unref(callid);
29879 }
29880 return NULL;
29881 }
29882
29883
29884 ast_copy_string(tmp, dest, sizeof(tmp));
29885
29886
29887 dnid = strchr(tmp, '!');
29888 if (dnid != NULL) {
29889 *dnid++ = '\0';
29890 ast_string_field_set(p, todnid, dnid);
29891 }
29892
29893
29894 AST_NONSTANDARD_APP_ARGS(args, tmp, '/');
29895
29896
29897 host = strchr(args.peerorhost, '@');
29898 if (host) {
29899 *host++ = '\0';
29900 ext = args.peerorhost;
29901 secret = strchr(ext, ':');
29902 }
29903 if (secret) {
29904 *secret++ = '\0';
29905 md5secret = strchr(secret, ':');
29906 }
29907 if (md5secret) {
29908 *md5secret++ = '\0';
29909 authname = strchr(md5secret, ':');
29910 }
29911 if (authname) {
29912 *authname++ = '\0';
29913 trans = strchr(authname, ':');
29914 }
29915 if (trans) {
29916 *trans++ = '\0';
29917 if (!strcasecmp(trans, "tcp"))
29918 transport = SIP_TRANSPORT_TCP;
29919 else if (!strcasecmp(trans, "tls"))
29920 transport = SIP_TRANSPORT_TLS;
29921 else {
29922 if (strcasecmp(trans, "udp"))
29923 ast_log(LOG_WARNING, "'%s' is not a valid transport option to Dial() for SIP calls, using udp by default.\n", trans);
29924 transport = SIP_TRANSPORT_UDP;
29925 }
29926 } else {
29927 transport = SIP_TRANSPORT_UDP;
29928 }
29929
29930 if (!host) {
29931 ext = args.exten;
29932 host = args.peerorhost;
29933 remote_address = args.remote_address;
29934 } else {
29935 remote_address = args.remote_address;
29936 if (!ast_strlen_zero(args.exten)) {
29937 ast_log(LOG_NOTICE, "Conflicting extension values given. Using '%s' and not '%s'\n", ext, args.exten);
29938 }
29939 }
29940
29941 if (!ast_strlen_zero(remote_address)) {
29942 p->options->outboundproxy = proxy_from_config(remote_address, 0, NULL);
29943 if (!p->options->outboundproxy) {
29944 ast_log(LOG_WARNING, "Unable to parse outboundproxy %s. We will not use this remote IP address\n", remote_address);
29945 }
29946 }
29947
29948 set_socket_transport(&p->socket, transport);
29949
29950
29951
29952
29953
29954
29955 if (create_addr(p, host, NULL, 1)) {
29956 *cause = AST_CAUSE_UNREGISTERED;
29957 ast_debug(3, "Cant create SIP call - target device not registered\n");
29958 dialog_unlink_all(p);
29959 dialog_unref(p, "unref dialog p UNREGISTERED");
29960
29961 if (callid) {
29962 ast_callid_unref(callid);
29963 }
29964 return NULL;
29965 }
29966 if (ast_strlen_zero(p->peername) && ext)
29967 ast_string_field_set(p, peername, ext);
29968
29969 ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
29970
29971
29972 check_for_nat(&p->sa, p);
29973
29974
29975 if (p->relatedpeer) {
29976
29977 if (!ast_strlen_zero(p->relatedpeer->fullcontact) && !p->natdetected &&
29978 (ast_test_flag(&p->flags[2], SIP_PAGE3_NAT_AUTO_RPORT) && !ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT))) {
29979
29980
29981 struct ast_sockaddr tmpaddr;
29982
29983 __set_address_from_contact(p->relatedpeer->fullcontact, &tmpaddr, 0);
29984
29985 check_for_nat(&tmpaddr, p);
29986 }
29987
29988 set_peer_nat(p, p->relatedpeer);
29989 }
29990
29991 do_setnat(p);
29992
29993 build_via(p);
29994
29995
29996 change_callid_pvt(p, NULL);
29997
29998
29999
30000
30001
30002
30003 if (ext) {
30004 ast_string_field_set(p, username, ext);
30005 ast_string_field_set(p, fullcontact, NULL);
30006 }
30007 if (secret && !ast_strlen_zero(secret))
30008 ast_string_field_set(p, peersecret, secret);
30009
30010 if (md5secret && !ast_strlen_zero(md5secret))
30011 ast_string_field_set(p, peermd5secret, md5secret);
30012
30013 if (authname && !ast_strlen_zero(authname))
30014 ast_string_field_set(p, authname, authname);
30015 #if 0
30016 printf("Setting up to call extension '%s' at '%s'\n", ext ? ext : "<none>", host);
30017 #endif
30018 ast_format_cap_append(p->prefcaps, cap);
30019 ast_format_cap_joint_copy(cap, p->caps, p->jointcaps);
30020
30021 sip_pvt_lock(p);
30022
30023 tmpc = sip_new(p, AST_STATE_DOWN, host, requestor ? ast_channel_linkedid(requestor) : NULL, callid);
30024 if (callid) {
30025 callid = ast_callid_unref(callid);
30026 }
30027
30028 if (sip_cfg.callevents)
30029 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
30030 "Channel: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
30031 p->owner ? ast_channel_name(p->owner) : "", "SIP", p->callid, p->fullcontact, p->peername);
30032 sip_pvt_unlock(p);
30033 if (!tmpc) {
30034 dialog_unlink_all(p);
30035
30036 } else {
30037 ast_channel_unlock(tmpc);
30038 }
30039 dialog_unref(p, "toss pvt ptr at end of sip_request_call");
30040 ast_update_use_count();
30041 restart_monitor();
30042 return tmpc;
30043 }
30044
30045
30046 static void set_insecure_flags (struct ast_flags *flags, const char *value, int lineno)
30047 {
30048 if (ast_strlen_zero(value))
30049 return;
30050
30051 if (!ast_false(value)) {
30052 char buf[64];
30053 char *word, *next;
30054
30055 ast_copy_string(buf, value, sizeof(buf));
30056 next = buf;
30057 while ((word = strsep(&next, ","))) {
30058 if (!strcasecmp(word, "port"))
30059 ast_set_flag(&flags[0], SIP_INSECURE_PORT);
30060 else if (!strcasecmp(word, "invite"))
30061 ast_set_flag(&flags[0], SIP_INSECURE_INVITE);
30062 else
30063 ast_log(LOG_WARNING, "Unknown insecure mode '%s' on line %d\n", value, lineno);
30064 }
30065 }
30066 }
30067
30068
30069
30070
30071
30072 static int handle_t38_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v,
30073 int *maxdatagram)
30074 {
30075 int res = 1;
30076
30077 if (!strcasecmp(v->name, "t38pt_udptl")) {
30078 char *buf = ast_strdupa(v->value);
30079 char *word, *next = buf;
30080
30081 ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT);
30082
30083 while ((word = strsep(&next, ","))) {
30084 if (ast_true(word) || !strcasecmp(word, "fec")) {
30085 ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
30086 ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_FEC);
30087 } else if (!strcasecmp(word, "redundancy")) {
30088 ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
30089 ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY);
30090 } else if (!strcasecmp(word, "none")) {
30091 ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
30092 ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL);
30093 } else if (!strncasecmp(word, "maxdatagram=", 12)) {
30094 if (sscanf(&word[12], "%30u", maxdatagram) != 1) {
30095 ast_log(LOG_WARNING, "Invalid maxdatagram '%s' at line %d of %s\n", v->value, v->lineno, config);
30096 *maxdatagram = global_t38_maxdatagram;
30097 }
30098 }
30099 }
30100 } else if (!strcasecmp(v->name, "t38pt_usertpsource")) {
30101 ast_set_flag(&mask[1], SIP_PAGE2_UDPTL_DESTINATION);
30102 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_UDPTL_DESTINATION);
30103 } else {
30104 res = 0;
30105 }
30106
30107 return res;
30108 }
30109
30110
30111
30112
30113
30114
30115
30116
30117 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v)
30118 {
30119 int res = 1;
30120
30121 if (!strcasecmp(v->name, "trustrpid")) {
30122 ast_set_flag(&mask[0], SIP_TRUSTRPID);
30123 ast_set2_flag(&flags[0], ast_true(v->value), SIP_TRUSTRPID);
30124 } else if (!strcasecmp(v->name, "sendrpid")) {
30125 ast_set_flag(&mask[0], SIP_SENDRPID);
30126 if (!strcasecmp(v->value, "pai")) {
30127 ast_set_flag(&flags[0], SIP_SENDRPID_PAI);
30128 } else if (!strcasecmp(v->value, "rpid")) {
30129 ast_set_flag(&flags[0], SIP_SENDRPID_RPID);
30130 } else if (ast_true(v->value)) {
30131 ast_set_flag(&flags[0], SIP_SENDRPID_RPID);
30132 }
30133 } else if (!strcasecmp(v->name, "rpid_update")) {
30134 ast_set_flag(&mask[1], SIP_PAGE2_RPID_UPDATE);
30135 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RPID_UPDATE);
30136 } else if (!strcasecmp(v->name, "rpid_immediate")) {
30137 ast_set_flag(&mask[1], SIP_PAGE2_RPID_IMMEDIATE);
30138 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RPID_IMMEDIATE);
30139 } else if (!strcasecmp(v->name, "trust_id_outbound")) {
30140 ast_set_flag(&mask[1], SIP_PAGE2_TRUST_ID_OUTBOUND);
30141 ast_clear_flag(&flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND);
30142 if (!strcasecmp(v->value, "legacy")) {
30143 ast_set_flag(&flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND_LEGACY);
30144 } else if (ast_true(v->value)) {
30145 ast_set_flag(&flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND_YES);
30146 } else if (ast_false(v->value)) {
30147 ast_set_flag(&flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND_NO);
30148 } else {
30149 ast_log(LOG_WARNING, "Unknown trust_id_outbound mode '%s' on line %d, using legacy\n", v->value, v->lineno);
30150 ast_set_flag(&flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND_LEGACY);
30151 }
30152 } else if (!strcasecmp(v->name, "g726nonstandard")) {
30153 ast_set_flag(&mask[0], SIP_G726_NONSTANDARD);
30154 ast_set2_flag(&flags[0], ast_true(v->value), SIP_G726_NONSTANDARD);
30155 } else if (!strcasecmp(v->name, "useclientcode")) {
30156 ast_set_flag(&mask[0], SIP_USECLIENTCODE);
30157 ast_set2_flag(&flags[0], ast_true(v->value), SIP_USECLIENTCODE);
30158 } else if (!strcasecmp(v->name, "dtmfmode")) {
30159 ast_set_flag(&mask[0], SIP_DTMF);
30160 ast_clear_flag(&flags[0], SIP_DTMF);
30161 if (!strcasecmp(v->value, "inband"))
30162 ast_set_flag(&flags[0], SIP_DTMF_INBAND);
30163 else if (!strcasecmp(v->value, "rfc2833"))
30164 ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
30165 else if (!strcasecmp(v->value, "info"))
30166 ast_set_flag(&flags[0], SIP_DTMF_INFO);
30167 else if (!strcasecmp(v->value, "shortinfo"))
30168 ast_set_flag(&flags[0], SIP_DTMF_SHORTINFO);
30169 else if (!strcasecmp(v->value, "auto"))
30170 ast_set_flag(&flags[0], SIP_DTMF_AUTO);
30171 else {
30172 ast_log(LOG_WARNING, "Unknown dtmf mode '%s' on line %d, using rfc2833\n", v->value, v->lineno);
30173 ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
30174 }
30175 } else if (!strcasecmp(v->name, "nat")) {
30176 sip_parse_nat_option(v->value, mask, flags);
30177 } else if (!strcasecmp(v->name, "directmedia") || !strcasecmp(v->name, "canreinvite")) {
30178 ast_set_flag(&mask[0], SIP_REINVITE);
30179 ast_clear_flag(&flags[0], SIP_REINVITE);
30180 if (ast_true(v->value)) {
30181 ast_set_flag(&flags[0], SIP_DIRECT_MEDIA | SIP_DIRECT_MEDIA_NAT);
30182 } else if (!ast_false(v->value)) {
30183 char buf[64];
30184 char *word, *next = buf;
30185
30186 ast_copy_string(buf, v->value, sizeof(buf));
30187 while ((word = strsep(&next, ","))) {
30188 if (!strcasecmp(word, "update")) {
30189 ast_set_flag(&flags[0], SIP_REINVITE_UPDATE | SIP_DIRECT_MEDIA);
30190 } else if (!strcasecmp(word, "nonat")) {
30191 ast_set_flag(&flags[0], SIP_DIRECT_MEDIA);
30192 ast_clear_flag(&flags[0], SIP_DIRECT_MEDIA_NAT);
30193 } else if (!strcasecmp(word, "outgoing")) {
30194 ast_set_flag(&flags[0], SIP_DIRECT_MEDIA);
30195 ast_set_flag(&mask[2], SIP_PAGE3_DIRECT_MEDIA_OUTGOING);
30196 ast_set_flag(&flags[2], SIP_PAGE3_DIRECT_MEDIA_OUTGOING);
30197 } else {
30198 ast_log(LOG_WARNING, "Unknown directmedia mode '%s' on line %d\n", v->value, v->lineno);
30199 }
30200 }
30201 }
30202 } else if (!strcasecmp(v->name, "insecure")) {
30203 ast_set_flag(&mask[0], SIP_INSECURE);
30204 ast_clear_flag(&flags[0], SIP_INSECURE);
30205 set_insecure_flags(&flags[0], v->value, v->lineno);
30206 } else if (!strcasecmp(v->name, "progressinband")) {
30207 ast_set_flag(&mask[0], SIP_PROG_INBAND);
30208 ast_clear_flag(&flags[0], SIP_PROG_INBAND);
30209 if (ast_true(v->value))
30210 ast_set_flag(&flags[0], SIP_PROG_INBAND_YES);
30211 else if (strcasecmp(v->value, "never"))
30212 ast_set_flag(&flags[0], SIP_PROG_INBAND_NO);
30213 } else if (!strcasecmp(v->name, "promiscredir")) {
30214 ast_set_flag(&mask[0], SIP_PROMISCREDIR);
30215 ast_set2_flag(&flags[0], ast_true(v->value), SIP_PROMISCREDIR);
30216 } else if (!strcasecmp(v->name, "videosupport")) {
30217 if (!strcasecmp(v->value, "always")) {
30218 ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
30219 ast_set_flag(&flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
30220 } else {
30221 ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT);
30222 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_VIDEOSUPPORT);
30223 }
30224 } else if (!strcasecmp(v->name, "textsupport")) {
30225 ast_set_flag(&mask[1], SIP_PAGE2_TEXTSUPPORT);
30226 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_TEXTSUPPORT);
30227 res = 1;
30228 } else if (!strcasecmp(v->name, "allowoverlap")) {
30229 ast_set_flag(&mask[1], SIP_PAGE2_ALLOWOVERLAP);
30230 ast_clear_flag(&flags[1], SIP_PAGE2_ALLOWOVERLAP);
30231 if (ast_true(v->value)) {
30232 ast_set_flag(&flags[1], SIP_PAGE2_ALLOWOVERLAP_YES);
30233 } else if (!strcasecmp(v->value, "dtmf")){
30234 ast_set_flag(&flags[1], SIP_PAGE2_ALLOWOVERLAP_DTMF);
30235 }
30236 } else if (!strcasecmp(v->name, "allowsubscribe")) {
30237 ast_set_flag(&mask[1], SIP_PAGE2_ALLOWSUBSCRIBE);
30238 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWSUBSCRIBE);
30239 } else if (!strcasecmp(v->name, "ignoresdpversion")) {
30240 ast_set_flag(&mask[1], SIP_PAGE2_IGNORESDPVERSION);
30241 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_IGNORESDPVERSION);
30242 } else if (!strcasecmp(v->name, "faxdetect")) {
30243 ast_set_flag(&mask[1], SIP_PAGE2_FAX_DETECT);
30244 if (ast_true(v->value)) {
30245 ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_BOTH);
30246 } else if (ast_false(v->value)) {
30247 ast_clear_flag(&flags[1], SIP_PAGE2_FAX_DETECT_BOTH);
30248 } else {
30249 char *buf = ast_strdupa(v->value);
30250 char *word, *next = buf;
30251
30252 while ((word = strsep(&next, ","))) {
30253 if (!strcasecmp(word, "cng")) {
30254 ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_CNG);
30255 } else if (!strcasecmp(word, "t38")) {
30256 ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_T38);
30257 } else {
30258 ast_log(LOG_WARNING, "Unknown faxdetect mode '%s' on line %d.\n", word, v->lineno);
30259 }
30260 }
30261 }
30262 } else if (!strcasecmp(v->name, "rfc2833compensate")) {
30263 ast_set_flag(&mask[1], SIP_PAGE2_RFC2833_COMPENSATE);
30264 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RFC2833_COMPENSATE);
30265 } else if (!strcasecmp(v->name, "buggymwi")) {
30266 ast_set_flag(&mask[1], SIP_PAGE2_BUGGY_MWI);
30267 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_BUGGY_MWI);
30268 } else
30269 res = 0;
30270
30271 return res;
30272 }
30273
30274
30275 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context)
30276 {
30277 struct domain *d;
30278
30279 if (ast_strlen_zero(domain)) {
30280 ast_log(LOG_WARNING, "Zero length domain.\n");
30281 return 1;
30282 }
30283
30284 if (!(d = ast_calloc(1, sizeof(*d))))
30285 return 0;
30286
30287 ast_copy_string(d->domain, domain, sizeof(d->domain));
30288
30289 if (!ast_strlen_zero(context))
30290 ast_copy_string(d->context, context, sizeof(d->context));
30291
30292 d->mode = mode;
30293
30294 AST_LIST_LOCK(&domain_list);
30295 AST_LIST_INSERT_TAIL(&domain_list, d, list);
30296 AST_LIST_UNLOCK(&domain_list);
30297
30298 if (sipdebug)
30299 ast_debug(1, "Added local SIP domain '%s'\n", domain);
30300
30301 return 1;
30302 }
30303
30304
30305 static int check_sip_domain(const char *domain, char *context, size_t len)
30306 {
30307 struct domain *d;
30308 int result = 0;
30309
30310 AST_LIST_LOCK(&domain_list);
30311 AST_LIST_TRAVERSE(&domain_list, d, list) {
30312 if (strcasecmp(d->domain, domain)) {
30313 continue;
30314 }
30315
30316 if (len && !ast_strlen_zero(d->context))
30317 ast_copy_string(context, d->context, len);
30318
30319 result = 1;
30320 break;
30321 }
30322 AST_LIST_UNLOCK(&domain_list);
30323
30324 return result;
30325 }
30326
30327
30328 static void clear_sip_domains(void)
30329 {
30330 struct domain *d;
30331
30332 AST_LIST_LOCK(&domain_list);
30333 while ((d = AST_LIST_REMOVE_HEAD(&domain_list, list)))
30334 ast_free(d);
30335 AST_LIST_UNLOCK(&domain_list);
30336 }
30337
30338
30339
30340
30341
30342
30343
30344
30345
30346 static void destroy_realm_authentication(void *obj)
30347 {
30348 struct sip_auth_container *credentials = obj;
30349 struct sip_auth *auth;
30350
30351 while ((auth = AST_LIST_REMOVE_HEAD(&credentials->list, node))) {
30352 ast_free(auth);
30353 }
30354 }
30355
30356
30357
30358
30359
30360
30361
30362
30363
30364
30365
30366 static void add_realm_authentication(struct sip_auth_container **credentials, const char *configuration, int lineno)
30367 {
30368 char *authcopy;
30369 char *username=NULL, *realm=NULL, *secret=NULL, *md5secret=NULL;
30370 struct sip_auth *auth;
30371
30372 if (ast_strlen_zero(configuration)) {
30373
30374 return;
30375 }
30376
30377 ast_debug(1, "Auth config :: %s\n", configuration);
30378
30379 authcopy = ast_strdupa(configuration);
30380 username = authcopy;
30381
30382
30383 realm = strrchr(username, '@');
30384 if (realm)
30385 *realm++ = '\0';
30386 if (ast_strlen_zero(username) || ast_strlen_zero(realm)) {
30387 ast_log(LOG_WARNING, "Format for authentication entry is user[:secret]@realm at line %d\n", lineno);
30388 return;
30389 }
30390
30391
30392 if ((secret = strchr(username, ':'))) {
30393 *secret++ = '\0';
30394 } else if ((md5secret = strchr(username, '#'))) {
30395 *md5secret++ = '\0';
30396 }
30397
30398
30399 if (!*credentials) {
30400 *credentials = ao2_t_alloc(sizeof(**credentials), destroy_realm_authentication,
30401 "Create realm auth container.");
30402 if (!*credentials) {
30403
30404 return;
30405 }
30406 }
30407
30408
30409 auth = ast_calloc(1, sizeof(*auth));
30410 if (!auth) {
30411 return;
30412 }
30413 ast_copy_string(auth->realm, realm, sizeof(auth->realm));
30414 ast_copy_string(auth->username, username, sizeof(auth->username));
30415 if (secret)
30416 ast_copy_string(auth->secret, secret, sizeof(auth->secret));
30417 if (md5secret)
30418 ast_copy_string(auth->md5secret, md5secret, sizeof(auth->md5secret));
30419
30420
30421 AST_LIST_INSERT_TAIL(&(*credentials)->list, auth, node);
30422
30423 ast_verb(3, "Added authentication for realm %s\n", realm);
30424 }
30425
30426
30427
30428
30429
30430
30431
30432
30433
30434
30435 static struct sip_auth *find_realm_authentication(struct sip_auth_container *credentials, const char *realm)
30436 {
30437 struct sip_auth *auth;
30438
30439 if (credentials) {
30440 AST_LIST_TRAVERSE(&credentials->list, auth, node) {
30441 if (!strcasecmp(auth->realm, realm)) {
30442 break;
30443 }
30444 }
30445 } else {
30446 auth = NULL;
30447 }
30448
30449 return auth;
30450 }
30451
30452
30453
30454
30455 static struct ast_variable *add_var(const char *buf, struct ast_variable *list)
30456 {
30457 struct ast_variable *tmpvar = NULL;
30458 char *varname = ast_strdupa(buf), *varval = NULL;
30459
30460 if ((varval = strchr(varname, '='))) {
30461 *varval++ = '\0';
30462 if ((tmpvar = ast_variable_new(varname, varval, ""))) {
30463 tmpvar->next = list;
30464 list = tmpvar;
30465 }
30466 }
30467 return list;
30468 }
30469
30470
30471 static void set_peer_defaults(struct sip_peer *peer)
30472 {
30473 if (peer->expire == 0) {
30474
30475
30476
30477 peer->expire = -1;
30478 peer->pokeexpire = -1;
30479 peer->keepalivesend = -1;
30480 set_socket_transport(&peer->socket, SIP_TRANSPORT_UDP);
30481 }
30482 peer->type = SIP_TYPE_PEER;
30483 ast_copy_flags(&peer->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
30484 ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
30485 ast_copy_flags(&peer->flags[2], &global_flags[2], SIP_PAGE3_FLAGS_TO_COPY);
30486 ast_string_field_set(peer, context, sip_cfg.default_context);
30487 ast_string_field_set(peer, record_on_feature, sip_cfg.default_record_on_feature);
30488 ast_string_field_set(peer, record_off_feature, sip_cfg.default_record_off_feature);
30489 ast_string_field_set(peer, messagecontext, sip_cfg.messagecontext);
30490 ast_string_field_set(peer, subscribecontext, sip_cfg.default_subscribecontext);
30491 ast_string_field_set(peer, language, default_language);
30492 ast_string_field_set(peer, mohinterpret, default_mohinterpret);
30493 ast_string_field_set(peer, mohsuggest, default_mohsuggest);
30494 ast_string_field_set(peer, engine, default_engine);
30495 ast_sockaddr_setnull(&peer->addr);
30496 ast_sockaddr_setnull(&peer->defaddr);
30497 ast_format_cap_copy(peer->caps, sip_cfg.caps);
30498 peer->maxcallbitrate = default_maxcallbitrate;
30499 peer->rtptimeout = global_rtptimeout;
30500 peer->rtpholdtimeout = global_rtpholdtimeout;
30501 peer->rtpkeepalive = global_rtpkeepalive;
30502 peer->allowtransfer = sip_cfg.allowtransfer;
30503 peer->autoframing = global_autoframing;
30504 peer->t38_maxdatagram = global_t38_maxdatagram;
30505 peer->qualifyfreq = global_qualifyfreq;
30506 if (global_callcounter)
30507 peer->call_limit=INT_MAX;
30508 ast_string_field_set(peer, vmexten, default_vmexten);
30509 ast_string_field_set(peer, secret, "");
30510 ast_string_field_set(peer, description, "");
30511 ast_string_field_set(peer, remotesecret, "");
30512 ast_string_field_set(peer, md5secret, "");
30513 ast_string_field_set(peer, cid_num, "");
30514 ast_string_field_set(peer, cid_name, "");
30515 ast_string_field_set(peer, cid_tag, "");
30516 ast_string_field_set(peer, fromdomain, "");
30517 ast_string_field_set(peer, fromuser, "");
30518 ast_string_field_set(peer, regexten, "");
30519 peer->callgroup = 0;
30520 peer->pickupgroup = 0;
30521 peer->maxms = default_qualify;
30522 peer->keepalive = default_keepalive;
30523 peer->prefs = default_prefs;
30524 ast_string_field_set(peer, zone, default_zone);
30525 peer->stimer.st_mode_oper = global_st_mode;
30526 peer->stimer.st_ref = global_st_refresher;
30527 peer->stimer.st_min_se = global_min_se;
30528 peer->stimer.st_max_se = global_max_se;
30529 peer->timer_t1 = global_t1;
30530 peer->timer_b = global_timer_b;
30531 clear_peer_mailboxes(peer);
30532 peer->disallowed_methods = sip_cfg.disallowed_methods;
30533 peer->transports = default_transports;
30534 peer->default_outbound_transport = default_primary_transport;
30535 if (peer->outboundproxy) {
30536 ao2_ref(peer->outboundproxy, -1);
30537 peer->outboundproxy = NULL;
30538 }
30539 }
30540
30541
30542 static struct sip_peer *temp_peer(const char *name)
30543 {
30544 struct sip_peer *peer;
30545
30546 if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct")))
30547 return NULL;
30548
30549 if (ast_string_field_init(peer, 512)) {
30550 ao2_t_ref(peer, -1, "failed to string_field_init, drop peer");
30551 return NULL;
30552 }
30553
30554 if (!(peer->cc_params = ast_cc_config_params_init())) {
30555 ao2_t_ref(peer, -1, "failed to allocate cc_params for peer");
30556 return NULL;
30557 }
30558
30559 if (!(peer->caps = ast_format_cap_alloc_nolock())) {
30560 ao2_t_ref(peer, -1, "failed to allocate format capabilities, drop peer");
30561 return NULL;
30562 }
30563
30564 ast_atomic_fetchadd_int(&apeerobjs, 1);
30565 set_peer_defaults(peer);
30566
30567 ast_copy_string(peer->name, name, sizeof(peer->name));
30568
30569 peer->selfdestruct = TRUE;
30570 peer->host_dynamic = TRUE;
30571 peer->prefs = default_prefs;
30572 reg_source_db(peer);
30573
30574 return peer;
30575 }
30576
30577
30578 static void add_peer_mailboxes(struct sip_peer *peer, const char *value)
30579 {
30580 char *next, *mbox, *context;
30581
30582 next = ast_strdupa(value);
30583
30584 while ((mbox = context = strsep(&next, ","))) {
30585 struct sip_mailbox *mailbox;
30586 int duplicate = 0;
30587
30588 mbox = ast_strip(mbox);
30589 strsep(&context, "@");
30590
30591 if (ast_strlen_zero(mbox)) {
30592 continue;
30593 }
30594
30595
30596 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
30597 if (!strcmp(mailbox->mailbox, mbox) && !strcmp(S_OR(mailbox->context, ""), S_OR(context, ""))) {
30598 duplicate = 1;
30599 break;
30600 }
30601 }
30602 if (duplicate) {
30603 continue;
30604 }
30605
30606 if (!(mailbox = ast_calloc(1, sizeof(*mailbox) + strlen(mbox) + strlen(S_OR(context, ""))))) {
30607 continue;
30608 }
30609
30610 if (!ast_strlen_zero(context)) {
30611 mailbox->context = mailbox->mailbox + strlen(mbox) + 1;
30612 strcpy(mailbox->context, context);
30613 }
30614 strcpy(mailbox->mailbox, mbox);
30615
30616 AST_LIST_INSERT_TAIL(&peer->mailboxes, mailbox, entry);
30617 }
30618 }
30619
30620
30621 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only)
30622 {
30623 struct sip_peer *peer = NULL;
30624 struct ast_acl_list *oldacl = NULL;
30625 struct ast_acl_list *olddirectmediaacl = NULL;
30626 int found = 0;
30627 int firstpass = 1;
30628 uint16_t port = 0;
30629 int format = 0;
30630 int timerb_set = 0, timert1_set = 0;
30631 time_t regseconds = 0;
30632 struct ast_flags peerflags[3] = {{(0)}};
30633 struct ast_flags mask[3] = {{(0)}};
30634 struct sip_peer tmp_peer;
30635 const char *srvlookup = NULL;
30636 static int deprecation_warning = 1;
30637 int alt_fullcontact = alt ? 1 : 0, headercount = 0;
30638 struct ast_str *fullcontact = ast_str_alloca(512);
30639 int acl_change_subscription_needed = 0;
30640
30641 if (!realtime || ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
30642
30643
30644
30645
30646
30647 ast_copy_string(tmp_peer.name, name, sizeof(tmp_peer.name));
30648 peer = ao2_t_find(peers, &tmp_peer, OBJ_POINTER | OBJ_UNLINK, "find and unlink peer from peers table");
30649 }
30650
30651 if (peer) {
30652
30653 found++;
30654
30655
30656 if (!ast_sockaddr_isnull(&peer->addr)) {
30657 ao2_t_unlink(peers_by_ip, peer, "ao2_unlink peer from peers_by_ip table");
30658 }
30659 if (!(peer->the_mark))
30660 firstpass = 0;
30661 } else {
30662 if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct"))) {
30663 return NULL;
30664 }
30665 if (!(peer->caps = ast_format_cap_alloc_nolock())) {
30666 ao2_t_ref(peer, -1, "failed to allocate format capabilities, drop peer");
30667 return NULL;
30668 }
30669 if (ast_string_field_init(peer, 512)) {
30670 ao2_t_ref(peer, -1, "failed to string_field_init, drop peer");
30671 return NULL;
30672 }
30673
30674 if (!(peer->cc_params = ast_cc_config_params_init())) {
30675 ao2_t_ref(peer, -1, "failed to allocate cc_params for peer");
30676 return NULL;
30677 }
30678
30679 if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
30680 ast_atomic_fetchadd_int(&rpeerobjs, 1);
30681 ast_debug(3, "-REALTIME- peer built. Name: %s. Peer objects: %d\n", name, rpeerobjs);
30682 } else
30683 ast_atomic_fetchadd_int(&speerobjs, 1);
30684 }
30685
30686
30687 if (firstpass) {
30688 oldacl = peer->acl;
30689 peer->acl = NULL;
30690 olddirectmediaacl = peer->directmediaacl;
30691 peer->directmediaacl = NULL;
30692 set_peer_defaults(peer);
30693 peer->type = 0;
30694 }
30695
30696
30697 ast_copy_string(peer->name, name, sizeof(peer->name));
30698
30699
30700 if (peer->chanvars) {
30701 ast_variables_destroy(peer->chanvars);
30702 peer->chanvars = NULL;
30703
30704 }
30705
30706 if (found)
30707 peer->portinuri = 0;
30708
30709
30710 ao2_lock(peer);
30711 if (peer->auth) {
30712 ao2_t_ref(peer->auth, -1, "Removing old peer authentication");
30713 peer->auth = NULL;
30714 }
30715 ao2_unlock(peer);
30716
30717
30718 peer->default_outbound_transport = 0;
30719 peer->transports = 0;
30720
30721 if (!devstate_only) {
30722 struct sip_mailbox *mailbox;
30723 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
30724 mailbox->delme = 1;
30725 }
30726 }
30727
30728
30729 peer->named_callgroups = ast_unref_namedgroups(peer->named_callgroups);
30730 peer->named_pickupgroups = ast_unref_namedgroups(peer->named_pickupgroups);
30731
30732 for (; v || ((v = alt) && !(alt=NULL)); v = v->next) {
30733 if (!devstate_only) {
30734 if (handle_common_options(&peerflags[0], &mask[0], v)) {
30735 continue;
30736 }
30737 if (handle_t38_options(&peerflags[0], &mask[0], v, &peer->t38_maxdatagram)) {
30738 continue;
30739 }
30740 if (!strcasecmp(v->name, "transport")) {
30741 char *val = ast_strdupa(v->value);
30742 char *trans;
30743
30744 peer->transports = peer->default_outbound_transport = 0;
30745 while ((trans = strsep(&val, ","))) {
30746 trans = ast_skip_blanks(trans);
30747
30748 if (!strncasecmp(trans, "udp", 3)) {
30749 peer->transports |= SIP_TRANSPORT_UDP;
30750 } else if (!strncasecmp(trans, "wss", 3)) {
30751 peer->transports |= SIP_TRANSPORT_WSS;
30752 } else if (!strncasecmp(trans, "ws", 2)) {
30753 peer->transports |= SIP_TRANSPORT_WS;
30754 } else if (sip_cfg.tcp_enabled && !strncasecmp(trans, "tcp", 3)) {
30755 peer->transports |= SIP_TRANSPORT_TCP;
30756 } else if (default_tls_cfg.enabled && !strncasecmp(trans, "tls", 3)) {
30757 peer->transports |= SIP_TRANSPORT_TLS;
30758 } else if (!strncasecmp(trans, "tcp", 3) || !strncasecmp(trans, "tls", 3)) {
30759 ast_log(LOG_WARNING, "'%.3s' is not a valid transport type when %.3senable=no. If no other is specified, the defaults from general will be used.\n", trans, trans);
30760 } else {
30761 ast_log(LOG_NOTICE, "'%s' is not a valid transport type. if no other is specified, the defaults from general will be used.\n", trans);
30762 }
30763
30764 if (!peer->default_outbound_transport) {
30765 peer->default_outbound_transport = peer->transports;
30766 }
30767 }
30768 } else if (realtime && !strcasecmp(v->name, "regseconds")) {
30769 ast_get_time_t(v->value, ®seconds, 0, NULL);
30770 } else if (realtime && !strcasecmp(v->name, "name")) {
30771 ast_copy_string(peer->name, v->value, sizeof(peer->name));
30772 } else if (realtime && !strcasecmp(v->name, "useragent")) {
30773 ast_string_field_set(peer, useragent, v->value);
30774 } else if (!strcasecmp(v->name, "type")) {
30775 if (!strcasecmp(v->value, "peer")) {
30776 peer->type |= SIP_TYPE_PEER;
30777 } else if (!strcasecmp(v->value, "user")) {
30778 peer->type |= SIP_TYPE_USER;
30779 } else if (!strcasecmp(v->value, "friend")) {
30780 peer->type = SIP_TYPE_USER | SIP_TYPE_PEER;
30781 }
30782 } else if (!strcasecmp(v->name, "remotesecret")) {
30783 ast_string_field_set(peer, remotesecret, v->value);
30784 } else if (!strcasecmp(v->name, "secret")) {
30785 ast_string_field_set(peer, secret, v->value);
30786 } else if (!strcasecmp(v->name, "description")) {
30787 ast_string_field_set(peer, description, v->value);
30788 } else if (!strcasecmp(v->name, "md5secret")) {
30789 ast_string_field_set(peer, md5secret, v->value);
30790 } else if (!strcasecmp(v->name, "auth")) {
30791 add_realm_authentication(&peer->auth, v->value, v->lineno);
30792 } else if (!strcasecmp(v->name, "callerid")) {
30793 char cid_name[80] = { '\0' }, cid_num[80] = { '\0' };
30794
30795 ast_callerid_split(v->value, cid_name, sizeof(cid_name), cid_num, sizeof(cid_num));
30796 ast_string_field_set(peer, cid_name, cid_name);
30797 ast_string_field_set(peer, cid_num, cid_num);
30798 } else if (!strcasecmp(v->name, "mwi_from")) {
30799 ast_string_field_set(peer, mwi_from, v->value);
30800 } else if (!strcasecmp(v->name, "fullname")) {
30801 ast_string_field_set(peer, cid_name, v->value);
30802 } else if (!strcasecmp(v->name, "trunkname")) {
30803
30804 ast_string_field_set(peer, cid_name, "");
30805 } else if (!strcasecmp(v->name, "cid_number")) {
30806 ast_string_field_set(peer, cid_num, v->value);
30807 } else if (!strcasecmp(v->name, "cid_tag")) {
30808 ast_string_field_set(peer, cid_tag, v->value);
30809 } else if (!strcasecmp(v->name, "context")) {
30810 ast_string_field_set(peer, context, v->value);
30811 ast_set_flag(&peer->flags[1], SIP_PAGE2_HAVEPEERCONTEXT);
30812 } else if (!strcasecmp(v->name, "recordonfeature")) {
30813 ast_string_field_set(peer, record_on_feature, v->value);
30814 } else if (!strcasecmp(v->name, "recordofffeature")) {
30815 ast_string_field_set(peer, record_off_feature, v->value);
30816 } else if (!strcasecmp(v->name, "outofcall_message_context")) {
30817 ast_string_field_set(peer, messagecontext, v->value);
30818 } else if (!strcasecmp(v->name, "subscribecontext")) {
30819 ast_string_field_set(peer, subscribecontext, v->value);
30820 } else if (!strcasecmp(v->name, "fromdomain")) {
30821 char *fromdomainport;
30822 ast_string_field_set(peer, fromdomain, v->value);
30823 if ((fromdomainport = strchr(peer->fromdomain, ':'))) {
30824 *fromdomainport++ = '\0';
30825 if (!(peer->fromdomainport = port_str2int(fromdomainport, 0))) {
30826 ast_log(LOG_NOTICE, "'%s' is not a valid port number for fromdomain.\n",fromdomainport);
30827 }
30828 } else {
30829 peer->fromdomainport = STANDARD_SIP_PORT;
30830 }
30831 } else if (!strcasecmp(v->name, "usereqphone")) {
30832 ast_set2_flag(&peer->flags[0], ast_true(v->value), SIP_USEREQPHONE);
30833 } else if (!strcasecmp(v->name, "fromuser")) {
30834 ast_string_field_set(peer, fromuser, v->value);
30835 } else if (!strcasecmp(v->name, "outboundproxy")) {
30836 struct sip_proxy *proxy;
30837 if (ast_strlen_zero(v->value)) {
30838 ast_log(LOG_WARNING, "no value given for outbound proxy on line %d of sip.conf\n", v->lineno);
30839 continue;
30840 }
30841 proxy = proxy_from_config(v->value, v->lineno, peer->outboundproxy);
30842 if (!proxy) {
30843 ast_log(LOG_WARNING, "failure parsing the outbound proxy on line %d of sip.conf.\n", v->lineno);
30844 continue;
30845 }
30846 peer->outboundproxy = proxy;
30847 } else if (!strcasecmp(v->name, "host")) {
30848 if (!strcasecmp(v->value, "dynamic")) {
30849
30850 if ((!found && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) || !peer->host_dynamic) {
30851
30852
30853 ast_sockaddr_setnull(&peer->addr);
30854 }
30855 peer->host_dynamic = TRUE;
30856 } else {
30857
30858 AST_SCHED_DEL_UNREF(sched, peer->expire,
30859 sip_unref_peer(peer, "removing register expire ref"));
30860 peer->host_dynamic = FALSE;
30861 srvlookup = v->value;
30862 }
30863 } else if (!strcasecmp(v->name, "defaultip")) {
30864 if (!ast_strlen_zero(v->value) && ast_get_ip(&peer->defaddr, v->value)) {
30865 sip_unref_peer(peer, "sip_unref_peer: from build_peer defaultip");
30866 return NULL;
30867 }
30868 } else if (!strcasecmp(v->name, "permit") || !strcasecmp(v->name, "deny") || !strcasecmp(v->name, "acl")) {
30869 int ha_error = 0;
30870 if (!ast_strlen_zero(v->value)) {
30871 ast_append_acl(v->name, v->value, &peer->acl, &ha_error, &acl_change_subscription_needed);
30872 }
30873 if (ha_error) {
30874 ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
30875 }
30876 } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny") || !strcasecmp(v->name, "contactacl")) {
30877 int ha_error = 0;
30878 if (!ast_strlen_zero(v->value)) {
30879 ast_append_acl(v->name + 7, v->value, &peer->contactacl, &ha_error, &acl_change_subscription_needed);
30880 }
30881 if (ha_error) {
30882 ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
30883 }
30884 } else if (!strcasecmp(v->name, "directmediapermit") || !strcasecmp(v->name, "directmediadeny") || !strcasecmp(v->name, "directmediaacl")) {
30885 int ha_error = 0;
30886 ast_append_acl(v->name + 11, v->value, &peer->directmediaacl, &ha_error, &acl_change_subscription_needed);
30887 if (ha_error) {
30888 ast_log(LOG_ERROR, "Bad directmedia ACL entry in configuration line %d : %s\n", v->lineno, v->value);
30889 }
30890 } else if (!strcasecmp(v->name, "port")) {
30891 peer->portinuri = 1;
30892 if (!(port = port_str2int(v->value, 0))) {
30893 if (realtime) {
30894
30895 peer->portinuri = 0;
30896 } else {
30897 ast_log(LOG_WARNING, "Invalid peer port configuration at line %d : %s\n", v->lineno, v->value);
30898 }
30899 }
30900 } else if (!strcasecmp(v->name, "callingpres")) {
30901 peer->callingpres = ast_parse_caller_presentation(v->value);
30902 if (peer->callingpres == -1) {
30903 peer->callingpres = atoi(v->value);
30904 }
30905 } else if (!strcasecmp(v->name, "username") || !strcmp(v->name, "defaultuser")) {
30906 ast_string_field_set(peer, username, v->value);
30907 if (!strcasecmp(v->name, "username")) {
30908 if (deprecation_warning) {
30909 ast_log(LOG_NOTICE, "The 'username' field for sip peers has been deprecated in favor of the term 'defaultuser'\n");
30910 deprecation_warning = 0;
30911 }
30912 peer->deprecated_username = 1;
30913 }
30914 } else if (!strcasecmp(v->name, "tonezone")) {
30915 struct ast_tone_zone *new_zone;
30916 if (!(new_zone = ast_get_indication_zone(v->value))) {
30917 ast_log(LOG_ERROR, "Unknown country code '%s' for tonezone in device [%s] at line %d. Check indications.conf for available country codes.\n", v->value, peer->name, v->lineno);
30918 } else {
30919 ast_tone_zone_unref(new_zone);
30920 ast_string_field_set(peer, zone, v->value);
30921 }
30922 } else if (!strcasecmp(v->name, "language")) {
30923 ast_string_field_set(peer, language, v->value);
30924 } else if (!strcasecmp(v->name, "regexten")) {
30925 ast_string_field_set(peer, regexten, v->value);
30926 } else if (!strcasecmp(v->name, "callbackextension")) {
30927 ast_string_field_set(peer, callback, v->value);
30928 } else if (!strcasecmp(v->name, "amaflags")) {
30929 format = ast_cdr_amaflags2int(v->value);
30930 if (format < 0) {
30931 ast_log(LOG_WARNING, "Invalid AMA Flags for peer: %s at line %d\n", v->value, v->lineno);
30932 } else {
30933 peer->amaflags = format;
30934 }
30935 } else if (!strcasecmp(v->name, "maxforwards")) {
30936 if (sscanf(v->value, "%30d", &peer->maxforwards) != 1
30937 || peer->maxforwards < 1 || 255 < peer->maxforwards) {
30938 ast_log(LOG_WARNING, "'%s' is not a valid maxforwards value at line %d. Using default.\n", v->value, v->lineno);
30939 peer->maxforwards = sip_cfg.default_max_forwards;
30940 }
30941 } else if (!strcasecmp(v->name, "accountcode")) {
30942 ast_string_field_set(peer, accountcode, v->value);
30943 } else if (!strcasecmp(v->name, "mohinterpret")) {
30944 ast_string_field_set(peer, mohinterpret, v->value);
30945 } else if (!strcasecmp(v->name, "mohsuggest")) {
30946 ast_string_field_set(peer, mohsuggest, v->value);
30947 } else if (!strcasecmp(v->name, "parkinglot")) {
30948 ast_string_field_set(peer, parkinglot, v->value);
30949 } else if (!strcasecmp(v->name, "rtp_engine")) {
30950 ast_string_field_set(peer, engine, v->value);
30951 } else if (!strcasecmp(v->name, "mailbox")) {
30952 add_peer_mailboxes(peer, v->value);
30953 } else if (!strcasecmp(v->name, "hasvoicemail")) {
30954
30955
30956 if (ast_true(v->value) && AST_LIST_EMPTY(&peer->mailboxes)) {
30957 add_peer_mailboxes(peer, name);
30958 }
30959 } else if (!strcasecmp(v->name, "subscribemwi")) {
30960 ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_SUBSCRIBEMWIONLY);
30961 } else if (!strcasecmp(v->name, "vmexten")) {
30962 ast_string_field_set(peer, vmexten, v->value);
30963 } else if (!strcasecmp(v->name, "callgroup")) {
30964 peer->callgroup = ast_get_group(v->value);
30965 } else if (!strcasecmp(v->name, "allowtransfer")) {
30966 peer->allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
30967 } else if (!strcasecmp(v->name, "pickupgroup")) {
30968 peer->pickupgroup = ast_get_group(v->value);
30969 } else if (!strcasecmp(v->name, "namedcallgroup")) {
30970 peer->named_callgroups = ast_get_namedgroups(v->value);
30971 } else if (!strcasecmp(v->name, "namedpickupgroup")) {
30972 peer->named_pickupgroups = ast_get_namedgroups(v->value);
30973 } else if (!strcasecmp(v->name, "allow")) {
30974 int error = ast_parse_allow_disallow(&peer->prefs, peer->caps, v->value, TRUE);
30975 if (error) {
30976 ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
30977 }
30978 } else if (!strcasecmp(v->name, "disallow")) {
30979 int error = ast_parse_allow_disallow(&peer->prefs, peer->caps, v->value, FALSE);
30980 if (error) {
30981 ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
30982 }
30983 } else if (!strcasecmp(v->name, "preferred_codec_only")) {
30984 ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_PREFERRED_CODEC);
30985 } else if (!strcasecmp(v->name, "autoframing")) {
30986 peer->autoframing = ast_true(v->value);
30987 } else if (!strcasecmp(v->name, "rtptimeout")) {
30988 if ((sscanf(v->value, "%30d", &peer->rtptimeout) != 1) || (peer->rtptimeout < 0)) {
30989 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
30990 peer->rtptimeout = global_rtptimeout;
30991 }
30992 } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
30993 if ((sscanf(v->value, "%30d", &peer->rtpholdtimeout) != 1) || (peer->rtpholdtimeout < 0)) {
30994 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
30995 peer->rtpholdtimeout = global_rtpholdtimeout;
30996 }
30997 } else if (!strcasecmp(v->name, "rtpkeepalive")) {
30998 if ((sscanf(v->value, "%30d", &peer->rtpkeepalive) != 1) || (peer->rtpkeepalive < 0)) {
30999 ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d. Using default.\n", v->value, v->lineno);
31000 peer->rtpkeepalive = global_rtpkeepalive;
31001 }
31002 } else if (!strcasecmp(v->name, "timert1")) {
31003 if ((sscanf(v->value, "%30d", &peer->timer_t1) != 1) || (peer->timer_t1 < 200) || (peer->timer_t1 < global_t1min)) {
31004 ast_log(LOG_WARNING, "'%s' is not a valid T1 time at line %d. Using default.\n", v->value, v->lineno);
31005 peer->timer_t1 = global_t1min;
31006 }
31007 timert1_set = 1;
31008 } else if (!strcasecmp(v->name, "timerb")) {
31009 if ((sscanf(v->value, "%30d", &peer->timer_b) != 1) || (peer->timer_b < 200)) {
31010 ast_log(LOG_WARNING, "'%s' is not a valid Timer B time at line %d. Using default.\n", v->value, v->lineno);
31011 peer->timer_b = global_timer_b;
31012 }
31013 timerb_set = 1;
31014 } else if (!strcasecmp(v->name, "setvar")) {
31015 peer->chanvars = add_var(v->value, peer->chanvars);
31016 } else if (!strcasecmp(v->name, "header")) {
31017 char tmp[4096];
31018 snprintf(tmp, sizeof(tmp), "__SIPADDHEADERpre%2d=%s", ++headercount, v->value);
31019 peer->chanvars = add_var(tmp, peer->chanvars);
31020 } else if (!strcasecmp(v->name, "qualifyfreq")) {
31021 int i;
31022 if (sscanf(v->value, "%30d", &i) == 1) {
31023 peer->qualifyfreq = i * 1000;
31024 } else {
31025 ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
31026 peer->qualifyfreq = global_qualifyfreq;
31027 }
31028 } else if (!strcasecmp(v->name, "maxcallbitrate")) {
31029 peer->maxcallbitrate = atoi(v->value);
31030 if (peer->maxcallbitrate < 0) {
31031 peer->maxcallbitrate = default_maxcallbitrate;
31032 }
31033 } else if (!strcasecmp(v->name, "session-timers")) {
31034 int i = (int) str2stmode(v->value);
31035 if (i < 0) {
31036 ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
31037 peer->stimer.st_mode_oper = global_st_mode;
31038 } else {
31039 peer->stimer.st_mode_oper = i;
31040 }
31041 } else if (!strcasecmp(v->name, "session-expires")) {
31042 if (sscanf(v->value, "%30d", &peer->stimer.st_max_se) != 1) {
31043 ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
31044 peer->stimer.st_max_se = global_max_se;
31045 }
31046 } else if (!strcasecmp(v->name, "session-minse")) {
31047 if (sscanf(v->value, "%30d", &peer->stimer.st_min_se) != 1) {
31048 ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
31049 peer->stimer.st_min_se = global_min_se;
31050 }
31051 if (peer->stimer.st_min_se < DEFAULT_MIN_SE) {
31052 ast_log(LOG_WARNING, "session-minse '%s' at line %d of %s is not allowed to be < %d secs\n", v->value, v->lineno, config, DEFAULT_MIN_SE);
31053 peer->stimer.st_min_se = global_min_se;
31054 }
31055 } else if (!strcasecmp(v->name, "session-refresher")) {
31056 int i = (int) str2strefresherparam(v->value);
31057 if (i < 0) {
31058 ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
31059 peer->stimer.st_ref = global_st_refresher;
31060 } else {
31061 peer->stimer.st_ref = i;
31062 }
31063 } else if (!strcasecmp(v->name, "disallowed_methods")) {
31064 char *disallow = ast_strdupa(v->value);
31065 mark_parsed_methods(&peer->disallowed_methods, disallow);
31066 } else if (!strcasecmp(v->name, "unsolicited_mailbox")) {
31067 ast_string_field_set(peer, unsolicited_mailbox, v->value);
31068 } else if (!strcasecmp(v->name, "use_q850_reason")) {
31069 ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_Q850_REASON);
31070 } else if (!strcasecmp(v->name, "encryption")) {
31071 ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_USE_SRTP);
31072 } else if (!strcasecmp(v->name, "encryption_taglen")) {
31073 ast_set2_flag(&peer->flags[2], !strcasecmp(v->value, "32"), SIP_PAGE3_SRTP_TAG_32);
31074 } else if (!strcasecmp(v->name, "snom_aoc_enabled")) {
31075 ast_set2_flag(&peer->flags[2], ast_true(v->value), SIP_PAGE3_SNOM_AOC);
31076 } else if (!strcasecmp(v->name, "avpf")) {
31077 ast_set2_flag(&peer->flags[2], ast_true(v->value), SIP_PAGE3_USE_AVPF);
31078 } else if (!strcasecmp(v->name, "icesupport")) {
31079 ast_set2_flag(&peer->flags[2], ast_true(v->value), SIP_PAGE3_ICE_SUPPORT);
31080 } else {
31081 ast_rtp_dtls_cfg_parse(&peer->dtls_cfg, v->name, v->value);
31082 }
31083 }
31084
31085
31086 peer->dtls_cfg.suite = (ast_test_flag(&peer->flags[2], SIP_PAGE3_SRTP_TAG_32) ? AST_AES_CM_128_HMAC_SHA1_32 : AST_AES_CM_128_HMAC_SHA1_80);
31087
31088
31089 if (realtime && !strcasecmp(v->name, "lastms")) {
31090 sscanf(v->value, "%30d", &peer->lastms);
31091 } else if (realtime && !strcasecmp(v->name, "ipaddr") && !ast_strlen_zero(v->value) ) {
31092 ast_sockaddr_parse(&peer->addr, v->value, PARSE_PORT_FORBID);
31093 } else if (realtime && !strcasecmp(v->name, "fullcontact")) {
31094 if (alt_fullcontact && !alt) {
31095
31096
31097
31098
31099
31100 alt_fullcontact = 0;
31101 ast_str_reset(fullcontact);
31102 }
31103
31104 if (ast_str_strlen(fullcontact) > 0) {
31105 ast_str_append(&fullcontact, 0, ";%s", v->value);
31106 } else {
31107 ast_str_set(&fullcontact, 0, "%s", v->value);
31108 }
31109 } else if (!strcasecmp(v->name, "qualify")) {
31110 if (!strcasecmp(v->value, "no")) {
31111 peer->maxms = 0;
31112 } else if (!strcasecmp(v->value, "yes")) {
31113 peer->maxms = default_qualify ? default_qualify : DEFAULT_MAXMS;
31114 } else if (sscanf(v->value, "%30d", &peer->maxms) != 1) {
31115 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);
31116 peer->maxms = 0;
31117 }
31118 if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && peer->maxms > 0) {
31119
31120
31121
31122
31123 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);
31124 peer->maxms = 0;
31125 }
31126 } else if (!strcasecmp(v->name, "keepalive")) {
31127 if (!strcasecmp(v->value, "no")) {
31128 peer->keepalive = 0;
31129 } else if (!strcasecmp(v->value, "yes")) {
31130 peer->keepalive = DEFAULT_KEEPALIVE_INTERVAL;
31131 } else if (sscanf(v->value, "%30d", &peer->keepalive) != 1) {
31132 ast_log(LOG_WARNING, "Keep alive of peer '%s' should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", peer->name, v->lineno);
31133 peer->keepalive = 0;
31134 }
31135 } else if (!strcasecmp(v->name, "callcounter")) {
31136 peer->call_limit = ast_true(v->value) ? INT_MAX : 0;
31137 } else if (!strcasecmp(v->name, "call-limit")) {
31138 peer->call_limit = atoi(v->value);
31139 if (peer->call_limit < 0) {
31140 peer->call_limit = 0;
31141 }
31142 } else if (!strcasecmp(v->name, "busylevel")) {
31143 peer->busy_level = atoi(v->value);
31144 if (peer->busy_level < 0) {
31145 peer->busy_level = 0;
31146 }
31147 } else if (ast_cc_is_config_param(v->name)) {
31148 ast_cc_set_param(peer->cc_params, v->name, v->value);
31149 }
31150 }
31151
31152 if (!devstate_only) {
31153 struct sip_mailbox *mailbox;
31154 AST_LIST_TRAVERSE_SAFE_BEGIN(&peer->mailboxes, mailbox, entry) {
31155 if (mailbox->delme) {
31156 AST_LIST_REMOVE_CURRENT(entry);
31157 destroy_mailbox(mailbox);
31158 }
31159 }
31160 AST_LIST_TRAVERSE_SAFE_END;
31161 }
31162
31163 if (!can_parse_xml && (ast_get_cc_agent_policy(peer->cc_params) == AST_CC_AGENT_NATIVE)) {
31164 ast_log(LOG_WARNING, "Peer %s has a cc_agent_policy of 'native' but required libxml2 dependency is not installed. Changing policy to 'never'\n", peer->name);
31165 ast_set_cc_agent_policy(peer->cc_params, AST_CC_AGENT_NEVER);
31166 }
31167
31168
31169
31170 if (peer->timer_b < peer->timer_t1 * 64) {
31171 if (timerb_set && timert1_set) {
31172 ast_log(LOG_WARNING, "Timer B has been set lower than recommended for peer %s (%d < 64 * Timer-T1=%d)\n", peer->name, peer->timer_b, peer->timer_t1);
31173 } else if (timerb_set) {
31174 if ((peer->timer_t1 = peer->timer_b / 64) < global_t1min) {
31175 ast_log(LOG_WARNING, "Timer B has been set lower than recommended (%d < 64 * timert1=%d). (RFC 3261, 17.1.1.2)\n", peer->timer_b, peer->timer_t1);
31176 peer->timer_t1 = global_t1min;
31177 peer->timer_b = peer->timer_t1 * 64;
31178 }
31179 peer->timer_t1 = peer->timer_b / 64;
31180 } else {
31181 peer->timer_b = peer->timer_t1 * 64;
31182 }
31183 }
31184
31185 if (!peer->default_outbound_transport) {
31186
31187 peer->transports = default_transports;
31188
31189 peer->default_outbound_transport = default_primary_transport;
31190 }
31191
31192
31193
31194
31195
31196 if (((peer->socket.type != peer->default_outbound_transport) && (peer->expire == -1)) ||
31197 !(peer->socket.type & peer->transports) || !(peer->socket.type)) {
31198 set_socket_transport(&peer->socket, peer->default_outbound_transport);
31199 }
31200
31201 ast_copy_flags(&peer->flags[0], &peerflags[0], mask[0].flags);
31202 ast_copy_flags(&peer->flags[1], &peerflags[1], mask[1].flags);
31203 ast_copy_flags(&peer->flags[2], &peerflags[2], mask[2].flags);
31204
31205 if (ast_str_strlen(fullcontact)) {
31206 ast_string_field_set(peer, fullcontact, ast_str_buffer(fullcontact));
31207 peer->rt_fromcontact = TRUE;
31208
31209
31210
31211
31212
31213
31214
31215
31216 if ((!ast_test_flag(&peer->flags[2], SIP_PAGE3_NAT_AUTO_RPORT) && !ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT))
31217 || ast_sockaddr_isnull(&peer->addr)) {
31218 __set_address_from_contact(ast_str_buffer(fullcontact), &peer->addr, 0);
31219 }
31220 }
31221
31222 if (srvlookup && peer->dnsmgr == NULL) {
31223 char transport[MAXHOSTNAMELEN];
31224 char _srvlookup[MAXHOSTNAMELEN];
31225 char *params;
31226
31227 ast_copy_string(_srvlookup, srvlookup, sizeof(_srvlookup));
31228 if ((params = strchr(_srvlookup, ';'))) {
31229 *params++ = '\0';
31230 }
31231
31232 snprintf(transport, sizeof(transport), "_%s._%s", get_srv_service(peer->socket.type), get_srv_protocol(peer->socket.type));
31233
31234 peer->addr.ss.ss_family = get_address_family_filter(peer->socket.type);
31235 if (ast_dnsmgr_lookup_cb(_srvlookup, &peer->addr, &peer->dnsmgr, sip_cfg.srvlookup && !peer->portinuri ? transport : NULL,
31236 on_dns_update_peer, sip_ref_peer(peer, "Store peer on dnsmgr"))) {
31237 ast_log(LOG_ERROR, "srvlookup failed for host: %s, on peer %s, removing peer\n", _srvlookup, peer->name);
31238 sip_unref_peer(peer, "dnsmgr lookup failed, getting rid of peer dnsmgr ref");
31239 sip_unref_peer(peer, "getting rid of a peer pointer");
31240 return NULL;
31241 }
31242 if (!peer->dnsmgr) {
31243
31244 sip_unref_peer(peer, "dnsmgr disabled, unref peer");
31245 }
31246
31247 ast_string_field_set(peer, tohost, srvlookup);
31248
31249 if (global_dynamic_exclude_static && !ast_sockaddr_isnull(&peer->addr)) {
31250 int ha_error = 0;
31251
31252 ast_append_acl("deny", ast_sockaddr_stringify_addr(&peer->addr), &sip_cfg.contact_acl, &ha_error, NULL);
31253 if (ha_error) {
31254 ast_log(LOG_ERROR, "Bad or unresolved host/IP entry in configuration for peer %s, cannot add to contact ACL\n", peer->name);
31255 }
31256 }
31257 } else if (peer->dnsmgr && !peer->host_dynamic) {
31258
31259 ast_dnsmgr_refresh(peer->dnsmgr);
31260 }
31261
31262 if (port && !realtime && peer->host_dynamic) {
31263 ast_sockaddr_set_port(&peer->defaddr, port);
31264 } else if (port) {
31265 ast_sockaddr_set_port(&peer->addr, port);
31266 }
31267
31268 if (ast_sockaddr_port(&peer->addr) == 0) {
31269 ast_sockaddr_set_port(&peer->addr,
31270 (peer->socket.type & SIP_TRANSPORT_TLS) ?
31271 STANDARD_TLS_PORT : STANDARD_SIP_PORT);
31272 }
31273 if (ast_sockaddr_port(&peer->defaddr) == 0) {
31274 ast_sockaddr_set_port(&peer->defaddr,
31275 (peer->socket.type & SIP_TRANSPORT_TLS) ?
31276 STANDARD_TLS_PORT : STANDARD_SIP_PORT);
31277 }
31278 if (!peer->socket.port) {
31279 peer->socket.port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
31280 }
31281
31282 if (realtime) {
31283 int enablepoke = 1;
31284
31285 if (!sip_cfg.ignore_regexpire && peer->host_dynamic) {
31286 time_t nowtime = time(NULL);
31287
31288 if ((nowtime - regseconds) > 0) {
31289 destroy_association(peer);
31290 memset(&peer->addr, 0, sizeof(peer->addr));
31291 peer->lastms = -1;
31292 enablepoke = 0;
31293 ast_debug(1, "Bah, we're expired (%d/%d/%d)!\n", (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
31294 }
31295 }
31296
31297
31298 if (!devstate_only && enablepoke) {
31299 sip_ref_peer(peer, "schedule qualify");
31300 sip_poke_peer(peer, 0);
31301 }
31302 }
31303
31304 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
31305 sip_cfg.allowsubscribe = TRUE;
31306 }
31307
31308 if (peer->host_dynamic && (!peer->is_realtime || !sip_cfg.peer_rtupdate)) {
31309 reg_source_db(peer);
31310 }
31311
31312
31313
31314 if (!devstate_only && !ast_test_flag(&peer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY) &&
31315 !AST_LIST_EMPTY(&peer->mailboxes)) {
31316 add_peer_mwi_subs(peer);
31317
31318
31319
31320 sip_send_mwi_to_peer(peer, 1);
31321 }
31322
31323 peer->the_mark = 0;
31324
31325 oldacl = ast_free_acl_list(oldacl);
31326 olddirectmediaacl = ast_free_acl_list(olddirectmediaacl);
31327 if (!ast_strlen_zero(peer->callback)) {
31328 char *reg_string;
31329 if (ast_asprintf(®_string, "%s?%s:%s@%s/%s", peer->name, peer->username, !ast_strlen_zero(peer->remotesecret) ? peer->remotesecret : peer->secret, peer->tohost, peer->callback) >= 0) {
31330 sip_register(reg_string, 0);
31331 ast_free(reg_string);
31332 }
31333 }
31334
31335
31336 if (acl_change_subscription_needed) {
31337 acl_change_event_subscribe();
31338 }
31339
31340 return peer;
31341 }
31342
31343 static int peer_markall_func(void *device, void *arg, int flags)
31344 {
31345 struct sip_peer *peer = device;
31346 if (!peer->selfdestruct) {
31347 peer->the_mark = 1;
31348 }
31349 return 0;
31350 }
31351
31352 static int peer_markall_autopeers_func(void *device, void *arg, int flags)
31353 {
31354 struct sip_peer *peer = device;
31355 if (peer->selfdestruct) {
31356 peer->the_mark = 1;
31357 }
31358 return 0;
31359 }
31360
31361
31362
31363
31364
31365 static void sip_set_default_format_capabilities(struct ast_format_cap *cap)
31366 {
31367 struct ast_format tmp_fmt;
31368
31369 ast_format_cap_remove_all(cap);
31370 ast_format_cap_add(cap, ast_format_set(&tmp_fmt, AST_FORMAT_ULAW, 0));
31371 ast_format_cap_add(cap, ast_format_set(&tmp_fmt, AST_FORMAT_TESTLAW, 0));
31372 ast_format_cap_add(cap, ast_format_set(&tmp_fmt, AST_FORMAT_ALAW, 0));
31373 ast_format_cap_add(cap, ast_format_set(&tmp_fmt, AST_FORMAT_GSM, 0));
31374 ast_format_cap_add(cap, ast_format_set(&tmp_fmt, AST_FORMAT_H263, 0));
31375 }
31376
31377 static void display_nat_warning(const char *cat, int reason, struct ast_flags *flags) {
31378 int global_nat, specific_nat;
31379
31380 if (reason == CHANNEL_MODULE_LOAD && (specific_nat = ast_test_flag(&flags[0], SIP_NAT_FORCE_RPORT)) != (global_nat = ast_test_flag(&global_flags[0], SIP_NAT_FORCE_RPORT))) {
31381 ast_log(LOG_WARNING, "!!! PLEASE NOTE: Setting 'nat' for a peer/user that differs from the global setting can make\n");
31382 ast_log(LOG_WARNING, "!!! the name of that peer/user discoverable by an attacker. Replies for non-existent peers/users\n");
31383 ast_log(LOG_WARNING, "!!! will be sent to a different port than replies for an existing peer/user. If at all possible,\n");
31384 ast_log(LOG_WARNING, "!!! use the global 'nat' setting and do not set 'nat' per peer/user.\n");
31385 ast_log(LOG_WARNING, "!!! (config category='%s' global force_rport='%s' peer/user force_rport='%s')\n", cat, AST_CLI_YESNO(global_nat), AST_CLI_YESNO(specific_nat));
31386 }
31387 }
31388
31389 static void cleanup_all_regs(void)
31390 {
31391
31392
31393 ASTOBJ_CONTAINER_TRAVERSE(®l, 1, do {
31394 ASTOBJ_WRLOCK(iterator);
31395 if (iterator->call) {
31396 ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", iterator->username, iterator->hostname);
31397
31398 dialog_unlink_all(iterator->call);
31399 iterator->call = dialog_unref(iterator->call, "remove iterator->call from registry traversal");
31400 }
31401 if (iterator->expire > -1) {
31402 AST_SCHED_DEL_UNREF(sched, iterator->expire, registry_unref(iterator, "reg ptr unref from reload config"));
31403 }
31404 if (iterator->timeout > -1) {
31405 AST_SCHED_DEL_UNREF(sched, iterator->timeout, registry_unref(iterator, "reg ptr unref from reload config"));
31406 }
31407 if (iterator->dnsmgr) {
31408 ast_dnsmgr_release(iterator->dnsmgr);
31409 iterator->dnsmgr = NULL;
31410 registry_unref(iterator, "reg ptr unref from dnsmgr");
31411 }
31412 ASTOBJ_UNLOCK(iterator);
31413 } while(0));
31414 }
31415
31416
31417
31418
31419
31420
31421
31422 static int reload_config(enum channelreloadreason reason)
31423 {
31424 struct ast_config *cfg, *ucfg;
31425 struct ast_variable *v;
31426 struct sip_peer *peer;
31427 char *cat, *stringp, *context, *oldregcontext;
31428 char newcontexts[AST_MAX_CONTEXT], oldcontexts[AST_MAX_CONTEXT];
31429 struct ast_flags mask[3] = {{0}};
31430 struct ast_flags setflags[3] = {{0}};
31431 struct ast_flags config_flags = { (reason == CHANNEL_MODULE_LOAD || reason == CHANNEL_ACL_RELOAD) ? 0 : ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) ? 0 : CONFIG_FLAG_FILEUNCHANGED };
31432 int auto_sip_domains = FALSE;
31433 struct ast_sockaddr old_bindaddr = bindaddr;
31434 int registry_count = 0, peer_count = 0, timerb_set = 0, timert1_set = 0;
31435 int subscribe_network_change = 1;
31436 time_t run_start, run_end;
31437 int bindport = 0;
31438 int acl_change_subscription_needed = 0;
31439 int min_subexpiry_set = 0, max_subexpiry_set = 0;
31440
31441 run_start = time(0);
31442 ast_unload_realtime("sipregs");
31443 ast_unload_realtime("sippeers");
31444 cfg = ast_config_load(config, config_flags);
31445
31446
31447 if (!cfg) {
31448 ast_log(LOG_NOTICE, "Unable to load config %s\n", config);
31449 return -1;
31450 } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
31451 ucfg = ast_config_load("users.conf", config_flags);
31452 if (ucfg == CONFIG_STATUS_FILEUNCHANGED) {
31453 return 1;
31454 } else if (ucfg == CONFIG_STATUS_FILEINVALID) {
31455 ast_log(LOG_ERROR, "Contents of users.conf are invalid and cannot be parsed\n");
31456 return 1;
31457 }
31458
31459 ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
31460 if ((cfg = ast_config_load(config, config_flags)) == CONFIG_STATUS_FILEINVALID) {
31461 ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed\n", config);
31462 ast_config_destroy(ucfg);
31463 return 1;
31464 }
31465 if (!cfg) {
31466
31467 ast_log(LOG_NOTICE, "Unable to load config %s\n", config);
31468 return -1;
31469 }
31470 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
31471 ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed\n", config);
31472 return 1;
31473 } else {
31474 ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
31475 if ((ucfg = ast_config_load("users.conf", config_flags)) == CONFIG_STATUS_FILEINVALID) {
31476 ast_log(LOG_ERROR, "Contents of users.conf are invalid and cannot be parsed\n");
31477 ast_config_destroy(cfg);
31478 return 1;
31479 }
31480 }
31481
31482 sip_cfg.contact_acl = ast_free_acl_list(sip_cfg.contact_acl);
31483
31484 default_tls_cfg.enabled = FALSE;
31485
31486 if (reason != CHANNEL_MODULE_LOAD) {
31487 ast_debug(4, "--------------- SIP reload started\n");
31488
31489 clear_sip_domains();
31490 ast_mutex_lock(&authl_lock);
31491 if (authl) {
31492 ao2_t_ref(authl, -1, "Removing old global authentication");
31493 authl = NULL;
31494 }
31495 ast_mutex_unlock(&authl_lock);
31496
31497 cleanup_all_regs();
31498
31499
31500 ASTOBJ_CONTAINER_DESTROYALL(®l, sip_registry_destroy);
31501 ast_debug(4, "--------------- Done destroying registry list\n");
31502 ao2_t_callback(peers, OBJ_NODATA, peer_markall_func, NULL, "callback to mark all peers");
31503 }
31504
31505
31506 if (reason != CHANNEL_MODULE_LOAD) {
31507 ast_free(default_tls_cfg.certfile);
31508 ast_free(default_tls_cfg.pvtfile);
31509 ast_free(default_tls_cfg.cipher);
31510 ast_free(default_tls_cfg.cafile);
31511 ast_free(default_tls_cfg.capath);
31512 }
31513 default_tls_cfg.certfile = ast_strdup(AST_CERTFILE);
31514 default_tls_cfg.pvtfile = ast_strdup("");
31515 default_tls_cfg.cipher = ast_strdup("");
31516 default_tls_cfg.cafile = ast_strdup("");
31517 default_tls_cfg.capath = ast_strdup("");
31518
31519
31520 ast_copy_string(oldcontexts, sip_cfg.regcontext, sizeof(oldcontexts));
31521 oldregcontext = oldcontexts;
31522
31523
31524
31525 sipdebug &= sip_debug_console;
31526 ast_clear_flag(&global_flags[0], AST_FLAGS_ALL);
31527 ast_clear_flag(&global_flags[1], AST_FLAGS_ALL);
31528 ast_clear_flag(&global_flags[2], AST_FLAGS_ALL);
31529
31530
31531 ast_sockaddr_parse(&bindaddr, "0.0.0.0:0", 0);
31532 memset(&internip, 0, sizeof(internip));
31533
31534
31535 ast_free_ha(localaddr);
31536 memset(&localaddr, 0, sizeof(localaddr));
31537 memset(&externaddr, 0, sizeof(externaddr));
31538 memset(&media_address, 0, sizeof(media_address));
31539 memset(&default_prefs, 0 , sizeof(default_prefs));
31540 memset(&sip_cfg.outboundproxy, 0, sizeof(struct sip_proxy));
31541 sip_cfg.outboundproxy.force = FALSE;
31542 default_transports = SIP_TRANSPORT_UDP;
31543 default_primary_transport = SIP_TRANSPORT_UDP;
31544 ourport_tcp = STANDARD_SIP_PORT;
31545 ourport_tls = STANDARD_TLS_PORT;
31546 externtcpport = STANDARD_SIP_PORT;
31547 externtlsport = STANDARD_TLS_PORT;
31548 sip_cfg.srvlookup = DEFAULT_SRVLOOKUP;
31549 global_tos_sip = DEFAULT_TOS_SIP;
31550 global_tos_audio = DEFAULT_TOS_AUDIO;
31551 global_tos_video = DEFAULT_TOS_VIDEO;
31552 global_tos_text = DEFAULT_TOS_TEXT;
31553 global_cos_sip = DEFAULT_COS_SIP;
31554 global_cos_audio = DEFAULT_COS_AUDIO;
31555 global_cos_video = DEFAULT_COS_VIDEO;
31556 global_cos_text = DEFAULT_COS_TEXT;
31557
31558 externhost[0] = '\0';
31559 externexpire = 0;
31560 externrefresh = 10;
31561
31562
31563 sip_cfg.allow_external_domains = DEFAULT_ALLOW_EXT_DOM;
31564 sip_cfg.regcontext[0] = '\0';
31565 sip_set_default_format_capabilities(sip_cfg.caps);
31566 sip_cfg.regextenonqualify = DEFAULT_REGEXTENONQUALIFY;
31567 sip_cfg.legacy_useroption_parsing = DEFAULT_LEGACY_USEROPTION_PARSING;
31568 sip_cfg.send_diversion = DEFAULT_SEND_DIVERSION;
31569 sip_cfg.notifyringing = DEFAULT_NOTIFYRINGING;
31570 sip_cfg.notifycid = DEFAULT_NOTIFYCID;
31571 sip_cfg.notifyhold = FALSE;
31572 sip_cfg.directrtpsetup = FALSE;
31573 sip_cfg.alwaysauthreject = DEFAULT_ALWAYSAUTHREJECT;
31574 sip_cfg.auth_options_requests = DEFAULT_AUTH_OPTIONS;
31575 sip_cfg.auth_message_requests = DEFAULT_AUTH_MESSAGE;
31576 sip_cfg.messagecontext[0] = '\0';
31577 sip_cfg.accept_outofcall_message = DEFAULT_ACCEPT_OUTOFCALL_MESSAGE;
31578 sip_cfg.allowsubscribe = FALSE;
31579 sip_cfg.disallowed_methods = SIP_UNKNOWN;
31580 sip_cfg.contact_acl = NULL;
31581 snprintf(global_useragent, sizeof(global_useragent), "%s %s", DEFAULT_USERAGENT, ast_get_version());
31582 snprintf(global_sdpsession, sizeof(global_sdpsession), "%s %s", DEFAULT_SDPSESSION, ast_get_version());
31583 snprintf(global_sdpowner, sizeof(global_sdpowner), "%s", DEFAULT_SDPOWNER);
31584 global_prematuremediafilter = TRUE;
31585 ast_copy_string(default_notifymime, DEFAULT_NOTIFYMIME, sizeof(default_notifymime));
31586 ast_copy_string(sip_cfg.realm, S_OR(ast_config_AST_SYSTEM_NAME, DEFAULT_REALM), sizeof(sip_cfg.realm));
31587 sip_cfg.domainsasrealm = DEFAULT_DOMAINSASREALM;
31588 ast_copy_string(default_callerid, DEFAULT_CALLERID, sizeof(default_callerid));
31589 ast_copy_string(default_mwi_from, DEFAULT_MWI_FROM, sizeof(default_mwi_from));
31590 sip_cfg.compactheaders = DEFAULT_COMPACTHEADERS;
31591 global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
31592 global_regattempts_max = 0;
31593 global_reg_retry_403 = 0;
31594 sip_cfg.pedanticsipchecking = DEFAULT_PEDANTIC;
31595 sip_cfg.autocreatepeer = DEFAULT_AUTOCREATEPEER;
31596 global_autoframing = 0;
31597 sip_cfg.allowguest = DEFAULT_ALLOWGUEST;
31598 global_callcounter = DEFAULT_CALLCOUNTER;
31599 global_match_auth_username = FALSE;
31600 global_rtptimeout = 0;
31601 global_rtpholdtimeout = 0;
31602 global_rtpkeepalive = DEFAULT_RTPKEEPALIVE;
31603 sip_cfg.allowtransfer = TRANSFER_OPENFORALL;
31604 sip_cfg.rtautoclear = 120;
31605 ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE);
31606 ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP_YES);
31607 sip_cfg.peer_rtupdate = TRUE;
31608 global_dynamic_exclude_static = 0;
31609 sip_cfg.tcp_enabled = FALSE;
31610
31611
31612 global_st_mode = SESSION_TIMER_MODE_ACCEPT;
31613 global_st_refresher = SESSION_TIMER_REFRESHER_PARAM_UAS;
31614 global_min_se = DEFAULT_MIN_SE;
31615 global_max_se = DEFAULT_MAX_SE;
31616
31617
31618 global_qualify_gap = DEFAULT_QUALIFY_GAP;
31619 global_qualify_peers = DEFAULT_QUALIFY_PEERS;
31620
31621
31622 ast_copy_string(sip_cfg.default_context, DEFAULT_CONTEXT, sizeof(sip_cfg.default_context));
31623 ast_copy_string(sip_cfg.default_record_on_feature, DEFAULT_RECORD_FEATURE, sizeof(sip_cfg.default_record_on_feature));
31624 ast_copy_string(sip_cfg.default_record_off_feature, DEFAULT_RECORD_FEATURE, sizeof(sip_cfg.default_record_off_feature));
31625 sip_cfg.default_subscribecontext[0] = '\0';
31626 sip_cfg.default_max_forwards = DEFAULT_MAX_FORWARDS;
31627 default_language[0] = '\0';
31628 default_fromdomain[0] = '\0';
31629 default_fromdomainport = 0;
31630 default_qualify = DEFAULT_QUALIFY;
31631 default_keepalive = DEFAULT_KEEPALIVE;
31632 default_zone[0] = '\0';
31633 default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
31634 ast_copy_string(default_mohinterpret, DEFAULT_MOHINTERPRET, sizeof(default_mohinterpret));
31635 ast_copy_string(default_mohsuggest, DEFAULT_MOHSUGGEST, sizeof(default_mohsuggest));
31636 ast_copy_string(default_vmexten, DEFAULT_VMEXTEN, sizeof(default_vmexten));
31637 ast_set_flag(&global_flags[0], SIP_DTMF_RFC2833);
31638 ast_set_flag(&global_flags[0], SIP_DIRECT_MEDIA);
31639 ast_set_flag(&global_flags[2], SIP_PAGE3_NAT_AUTO_RPORT);
31640 ast_copy_string(default_engine, DEFAULT_ENGINE, sizeof(default_engine));
31641 ast_copy_string(default_parkinglot, DEFAULT_PARKINGLOT, sizeof(default_parkinglot));
31642
31643
31644 dumphistory = FALSE;
31645 recordhistory = FALSE;
31646 sipdebug &= ~sip_debug_config;
31647
31648
31649 global_relaxdtmf = FALSE;
31650 sip_cfg.callevents = DEFAULT_CALLEVENTS;
31651 global_authfailureevents = FALSE;
31652 global_t1 = DEFAULT_TIMER_T1;
31653 global_timer_b = 64 * DEFAULT_TIMER_T1;
31654 global_t1min = DEFAULT_T1MIN;
31655 global_qualifyfreq = DEFAULT_QUALIFYFREQ;
31656 global_t38_maxdatagram = -1;
31657 global_shrinkcallerid = 1;
31658 global_refer_addheaders = TRUE;
31659 authlimit = DEFAULT_AUTHLIMIT;
31660 authtimeout = DEFAULT_AUTHTIMEOUT;
31661 global_store_sip_cause = DEFAULT_STORE_SIP_CAUSE;
31662 min_expiry = DEFAULT_MIN_EXPIRY;
31663 max_expiry = DEFAULT_MAX_EXPIRY;
31664 default_expiry = DEFAULT_DEFAULT_EXPIRY;
31665
31666 sip_cfg.matchexternaddrlocally = DEFAULT_MATCHEXTERNADDRLOCALLY;
31667
31668
31669 memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
31670
31671 ast_clear_flag(&global_flags[1], SIP_PAGE2_FAX_DETECT);
31672 ast_clear_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT | SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
31673 ast_clear_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT);
31674 ast_clear_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION);
31675
31676
31677 for (v = ast_variable_browse(cfg, "general"); v; v = v->next) {
31678 if (handle_common_options(&setflags[0], &mask[0], v)) {
31679 continue;
31680 }
31681 if (handle_t38_options(&setflags[0], &mask[0], v, &global_t38_maxdatagram)) {
31682 continue;
31683 }
31684
31685 if (!ast_jb_read_conf(&global_jbconf, v->name, v->value)) {
31686 continue;
31687 }
31688
31689
31690 if (!strcasecmp(v->name, "tlsverifyclient")) {
31691 ast_log(LOG_WARNING, "Ignoring unsupported option 'tlsverifyclient'\n");
31692 continue;
31693 } else if (!ast_tls_read_conf(&default_tls_cfg, &sip_tls_desc, v->name, v->value)) {
31694 continue;
31695 }
31696
31697 if (!strcasecmp(v->name, "context")) {
31698 ast_copy_string(sip_cfg.default_context, v->value, sizeof(sip_cfg.default_context));
31699 } else if (!strcasecmp(v->name, "recordonfeature")) {
31700 ast_copy_string(sip_cfg.default_record_on_feature, v->value, sizeof(sip_cfg.default_record_on_feature));
31701 } else if (!strcasecmp(v->name, "recordofffeature")) {
31702 ast_copy_string(sip_cfg.default_record_off_feature, v->value, sizeof(sip_cfg.default_record_off_feature));
31703 } else if (!strcasecmp(v->name, "subscribecontext")) {
31704 ast_copy_string(sip_cfg.default_subscribecontext, v->value, sizeof(sip_cfg.default_subscribecontext));
31705 } else if (!strcasecmp(v->name, "callcounter")) {
31706 global_callcounter = ast_true(v->value) ? 1 : 0;
31707 } else if (!strcasecmp(v->name, "allowguest")) {
31708 sip_cfg.allowguest = ast_true(v->value) ? 1 : 0;
31709 } else if (!strcasecmp(v->name, "realm")) {
31710 ast_copy_string(sip_cfg.realm, v->value, sizeof(sip_cfg.realm));
31711 } else if (!strcasecmp(v->name, "domainsasrealm")) {
31712 sip_cfg.domainsasrealm = ast_true(v->value);
31713 } else if (!strcasecmp(v->name, "useragent")) {
31714 ast_copy_string(global_useragent, v->value, sizeof(global_useragent));
31715 ast_debug(1, "Setting SIP channel User-Agent Name to %s\n", global_useragent);
31716 } else if (!strcasecmp(v->name, "sdpsession")) {
31717 ast_copy_string(global_sdpsession, v->value, sizeof(global_sdpsession));
31718 } else if (!strcasecmp(v->name, "sdpowner")) {
31719
31720 if (!strstr(v->value, " ")) {
31721 ast_copy_string(global_sdpowner, v->value, sizeof(global_sdpowner));
31722 } else {
31723 ast_log(LOG_WARNING, "'%s' must not contain spaces at line %d. Using default.\n", v->value, v->lineno);
31724 }
31725 } else if (!strcasecmp(v->name, "allowtransfer")) {
31726 sip_cfg.allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
31727 } else if (!strcasecmp(v->name, "rtcachefriends")) {
31728 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTCACHEFRIENDS);
31729 } else if (!strcasecmp(v->name, "rtsavesysname")) {
31730 sip_cfg.rtsave_sysname = ast_true(v->value);
31731 } else if (!strcasecmp(v->name, "rtupdate")) {
31732 sip_cfg.peer_rtupdate = ast_true(v->value);
31733 } else if (!strcasecmp(v->name, "ignoreregexpire")) {
31734 sip_cfg.ignore_regexpire = ast_true(v->value);
31735 } else if (!strcasecmp(v->name, "timert1")) {
31736
31737
31738
31739 global_t1 = atoi(v->value);
31740 } else if (!strcasecmp(v->name, "timerb")) {
31741 int tmp = atoi(v->value);
31742 if (tmp < 500) {
31743 global_timer_b = global_t1 * 64;
31744 ast_log(LOG_WARNING, "Invalid value for timerb ('%s'). Setting to default ('%d').\n", v->value, global_timer_b);
31745 }
31746 timerb_set = 1;
31747 } else if (!strcasecmp(v->name, "t1min")) {
31748 global_t1min = atoi(v->value);
31749 } else if (!strcasecmp(v->name, "transport")) {
31750 char *val = ast_strdupa(v->value);
31751 char *trans;
31752
31753 default_transports = default_primary_transport = 0;
31754 while ((trans = strsep(&val, ","))) {
31755 trans = ast_skip_blanks(trans);
31756
31757 if (!strncasecmp(trans, "udp", 3)) {
31758 default_transports |= SIP_TRANSPORT_UDP;
31759 } else if (!strncasecmp(trans, "tcp", 3)) {
31760 default_transports |= SIP_TRANSPORT_TCP;
31761 } else if (!strncasecmp(trans, "tls", 3)) {
31762 default_transports |= SIP_TRANSPORT_TLS;
31763 } else if (!strncasecmp(trans, "wss", 3)) {
31764 default_transports |= SIP_TRANSPORT_WSS;
31765 } else if (!strncasecmp(trans, "ws", 2)) {
31766 default_transports |= SIP_TRANSPORT_WS;
31767 } else {
31768 ast_log(LOG_NOTICE, "'%s' is not a valid transport type. if no other is specified, udp will be used.\n", trans);
31769 }
31770 if (default_primary_transport == 0) {
31771 default_primary_transport = default_transports;
31772 }
31773 }
31774 } else if (!strcasecmp(v->name, "tcpenable")) {
31775 if (!ast_false(v->value)) {
31776 ast_debug(2, "Enabling TCP socket for listening\n");
31777 sip_cfg.tcp_enabled = TRUE;
31778 }
31779 } else if (!strcasecmp(v->name, "tcpbindaddr")) {
31780 if (ast_parse_arg(v->value, PARSE_ADDR,
31781 &sip_tcp_desc.local_address)) {
31782 ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n",
31783 v->name, v->value, v->lineno, config);
31784 }
31785 ast_debug(2, "Setting TCP socket address to %s\n",
31786 ast_sockaddr_stringify(&sip_tcp_desc.local_address));
31787 } else if (!strcasecmp(v->name, "dynamic_exclude_static") || !strcasecmp(v->name, "dynamic_excludes_static")) {
31788 global_dynamic_exclude_static = ast_true(v->value);
31789 } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny") || !strcasecmp(v->name, "contactacl")) {
31790 int ha_error = 0;
31791 ast_append_acl(v->name + 7, v->value, &sip_cfg.contact_acl, &ha_error, &acl_change_subscription_needed);
31792 if (ha_error) {
31793 ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
31794 }
31795 } else if (!strcasecmp(v->name, "rtautoclear")) {
31796 int i = atoi(v->value);
31797 if (i > 0) {
31798 sip_cfg.rtautoclear = i;
31799 } else {
31800 i = 0;
31801 }
31802 ast_set2_flag(&global_flags[1], i || ast_true(v->value), SIP_PAGE2_RTAUTOCLEAR);
31803 } else if (!strcasecmp(v->name, "usereqphone")) {
31804 ast_set2_flag(&global_flags[0], ast_true(v->value), SIP_USEREQPHONE);
31805 } else if (!strcasecmp(v->name, "prematuremedia")) {
31806 global_prematuremediafilter = ast_true(v->value);
31807 } else if (!strcasecmp(v->name, "relaxdtmf")) {
31808 global_relaxdtmf = ast_true(v->value);
31809 } else if (!strcasecmp(v->name, "vmexten")) {
31810 ast_copy_string(default_vmexten, v->value, sizeof(default_vmexten));
31811 } else if (!strcasecmp(v->name, "rtptimeout")) {
31812 if ((sscanf(v->value, "%30d", &global_rtptimeout) != 1) || (global_rtptimeout < 0)) {
31813 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
31814 global_rtptimeout = 0;
31815 }
31816 } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
31817 if ((sscanf(v->value, "%30d", &global_rtpholdtimeout) != 1) || (global_rtpholdtimeout < 0)) {
31818 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
31819 global_rtpholdtimeout = 0;
31820 }
31821 } else if (!strcasecmp(v->name, "rtpkeepalive")) {
31822 if ((sscanf(v->value, "%30d", &global_rtpkeepalive) != 1) || (global_rtpkeepalive < 0)) {
31823 ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d. Using default.\n", v->value, v->lineno);
31824 global_rtpkeepalive = DEFAULT_RTPKEEPALIVE;
31825 }
31826 } else if (!strcasecmp(v->name, "compactheaders")) {
31827 sip_cfg.compactheaders = ast_true(v->value);
31828 } else if (!strcasecmp(v->name, "notifymimetype")) {
31829 ast_copy_string(default_notifymime, v->value, sizeof(default_notifymime));
31830 } else if (!strcasecmp(v->name, "directrtpsetup")) {
31831 sip_cfg.directrtpsetup = ast_true(v->value);
31832 } else if (!strcasecmp(v->name, "notifyringing")) {
31833 sip_cfg.notifyringing = ast_true(v->value);
31834 } else if (!strcasecmp(v->name, "notifyhold")) {
31835 sip_cfg.notifyhold = ast_true(v->value);
31836 } else if (!strcasecmp(v->name, "notifycid")) {
31837 if (!strcasecmp(v->value, "ignore-context")) {
31838 sip_cfg.notifycid = IGNORE_CONTEXT;
31839 } else {
31840 sip_cfg.notifycid = ast_true(v->value) ? ENABLED : DISABLED;
31841 }
31842 } else if (!strcasecmp(v->name, "alwaysauthreject")) {
31843 sip_cfg.alwaysauthreject = ast_true(v->value);
31844 } else if (!strcasecmp(v->name, "auth_options_requests")) {
31845 if (ast_true(v->value)) {
31846 sip_cfg.auth_options_requests = 1;
31847 }
31848 } else if (!strcasecmp(v->name, "auth_message_requests")) {
31849 sip_cfg.auth_message_requests = ast_true(v->value) ? 1 : 0;
31850 } else if (!strcasecmp(v->name, "accept_outofcall_message")) {
31851 sip_cfg.accept_outofcall_message = ast_true(v->value) ? 1 : 0;
31852 } else if (!strcasecmp(v->name, "outofcall_message_context")) {
31853 ast_copy_string(sip_cfg.messagecontext, v->value, sizeof(sip_cfg.messagecontext));
31854 } else if (!strcasecmp(v->name, "mohinterpret")) {
31855 ast_copy_string(default_mohinterpret, v->value, sizeof(default_mohinterpret));
31856 } else if (!strcasecmp(v->name, "mohsuggest")) {
31857 ast_copy_string(default_mohsuggest, v->value, sizeof(default_mohsuggest));
31858 } else if (!strcasecmp(v->name, "tonezone")) {
31859 struct ast_tone_zone *new_zone;
31860 if (!(new_zone = ast_get_indication_zone(v->value))) {
31861 ast_log(LOG_ERROR, "Unknown country code '%s' for tonezone in [general] at line %d. Check indications.conf for available country codes.\n", v->value, v->lineno);
31862 } else {
31863 ast_tone_zone_unref(new_zone);
31864 ast_copy_string(default_zone, v->value, sizeof(default_zone));
31865 }
31866 } else if (!strcasecmp(v->name, "language")) {
31867 ast_copy_string(default_language, v->value, sizeof(default_language));
31868 } else if (!strcasecmp(v->name, "regcontext")) {
31869 ast_copy_string(newcontexts, v->value, sizeof(newcontexts));
31870 stringp = newcontexts;
31871
31872 cleanup_stale_contexts(stringp, oldregcontext);
31873
31874 while ((context = strsep(&stringp, "&"))) {
31875 ast_copy_string(used_context, context, sizeof(used_context));
31876 ast_context_find_or_create(NULL, NULL, context, "SIP");
31877 }
31878 ast_copy_string(sip_cfg.regcontext, v->value, sizeof(sip_cfg.regcontext));
31879 } else if (!strcasecmp(v->name, "regextenonqualify")) {
31880 sip_cfg.regextenonqualify = ast_true(v->value);
31881 } else if (!strcasecmp(v->name, "legacy_useroption_parsing")) {
31882 sip_cfg.legacy_useroption_parsing = ast_true(v->value);
31883 } else if (!strcasecmp(v->name, "send_diversion")) {
31884 sip_cfg.send_diversion = ast_true(v->value);
31885 } else if (!strcasecmp(v->name, "callerid")) {
31886 ast_copy_string(default_callerid, v->value, sizeof(default_callerid));
31887 } else if (!strcasecmp(v->name, "mwi_from")) {
31888 ast_copy_string(default_mwi_from, v->value, sizeof(default_mwi_from));
31889 } else if (!strcasecmp(v->name, "fromdomain")) {
31890 char *fromdomainport;
31891 ast_copy_string(default_fromdomain, v->value, sizeof(default_fromdomain));
31892 if ((fromdomainport = strchr(default_fromdomain, ':'))) {
31893 *fromdomainport++ = '\0';
31894 if (!(default_fromdomainport = port_str2int(fromdomainport, 0))) {
31895 ast_log(LOG_NOTICE, "'%s' is not a valid port number for fromdomain.\n",fromdomainport);
31896 }
31897 } else {
31898 default_fromdomainport = STANDARD_SIP_PORT;
31899 }
31900 } else if (!strcasecmp(v->name, "outboundproxy")) {
31901 struct sip_proxy *proxy;
31902 if (ast_strlen_zero(v->value)) {
31903 ast_log(LOG_WARNING, "no value given for outbound proxy on line %d of sip.conf\n", v->lineno);
31904 continue;
31905 }
31906 proxy = proxy_from_config(v->value, v->lineno, &sip_cfg.outboundproxy);
31907 if (!proxy) {
31908 ast_log(LOG_WARNING, "failure parsing the outbound proxy on line %d of sip.conf.\n", v->lineno);
31909 continue;
31910 }
31911 } else if (!strcasecmp(v->name, "autocreatepeer")) {
31912 if (!strcasecmp(v->value, "persist")) {
31913 sip_cfg.autocreatepeer = AUTOPEERS_PERSIST;
31914 } else {
31915 sip_cfg.autocreatepeer = ast_true(v->value) ? AUTOPEERS_VOLATILE : AUTOPEERS_DISABLED;
31916 }
31917 } else if (!strcasecmp(v->name, "match_auth_username")) {
31918 global_match_auth_username = ast_true(v->value);
31919 } else if (!strcasecmp(v->name, "srvlookup")) {
31920 sip_cfg.srvlookup = ast_true(v->value);
31921 } else if (!strcasecmp(v->name, "pedantic")) {
31922 sip_cfg.pedanticsipchecking = ast_true(v->value);
31923 } else if (!strcasecmp(v->name, "maxexpirey") || !strcasecmp(v->name, "maxexpiry")) {
31924 max_expiry = atoi(v->value);
31925 if (max_expiry < 1) {
31926 max_expiry = DEFAULT_MAX_EXPIRY;
31927 }
31928 } else if (!strcasecmp(v->name, "minexpirey") || !strcasecmp(v->name, "minexpiry")) {
31929 min_expiry = atoi(v->value);
31930 if (min_expiry < 1) {
31931 min_expiry = DEFAULT_MIN_EXPIRY;
31932 }
31933 } else if (!strcasecmp(v->name, "defaultexpiry") || !strcasecmp(v->name, "defaultexpirey")) {
31934 default_expiry = atoi(v->value);
31935 if (default_expiry < 1) {
31936 default_expiry = DEFAULT_DEFAULT_EXPIRY;
31937 }
31938 } else if (!strcasecmp(v->name, "submaxexpirey") || !strcasecmp(v->name, "submaxexpiry")) {
31939 max_subexpiry = atoi(v->value);
31940 if (max_subexpiry < 1) {
31941 max_subexpiry = DEFAULT_MAX_EXPIRY;
31942 }
31943 max_subexpiry_set = 1;
31944 } else if (!strcasecmp(v->name, "subminexpirey") || !strcasecmp(v->name, "subminexpiry")) {
31945 min_subexpiry = atoi(v->value);
31946 if (min_subexpiry < 1) {
31947 min_subexpiry = DEFAULT_MIN_EXPIRY;
31948 }
31949 min_subexpiry_set = 1;
31950 } else if (!strcasecmp(v->name, "mwiexpiry") || !strcasecmp(v->name, "mwiexpirey")) {
31951 mwi_expiry = atoi(v->value);
31952 if (mwi_expiry < 1) {
31953 mwi_expiry = DEFAULT_MWI_EXPIRY;
31954 }
31955 } else if (!strcasecmp(v->name, "tcpauthtimeout")) {
31956 if (ast_parse_arg(v->value, PARSE_INT32|PARSE_DEFAULT|PARSE_IN_RANGE,
31957 &authtimeout, DEFAULT_AUTHTIMEOUT, 1, INT_MAX)) {
31958 ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n",
31959 v->name, v->value, v->lineno, config);
31960 }
31961 } else if (!strcasecmp(v->name, "tcpauthlimit")) {
31962 if (ast_parse_arg(v->value, PARSE_INT32|PARSE_DEFAULT|PARSE_IN_RANGE,
31963 &authlimit, DEFAULT_AUTHLIMIT, 1, INT_MAX)) {
31964 ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n",
31965 v->name, v->value, v->lineno, config);
31966 }
31967 } else if (!strcasecmp(v->name, "sipdebug")) {
31968 if (ast_true(v->value))
31969 sipdebug |= sip_debug_config;
31970 } else if (!strcasecmp(v->name, "dumphistory")) {
31971 dumphistory = ast_true(v->value);
31972 } else if (!strcasecmp(v->name, "recordhistory")) {
31973 recordhistory = ast_true(v->value);
31974 } else if (!strcasecmp(v->name, "registertimeout")) {
31975 global_reg_timeout = atoi(v->value);
31976 if (global_reg_timeout < 1) {
31977 global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
31978 }
31979 } else if (!strcasecmp(v->name, "registerattempts")) {
31980 global_regattempts_max = atoi(v->value);
31981 } else if (!strcasecmp(v->name, "register_retry_403")) {
31982 global_reg_retry_403 = ast_true(v->value);
31983 } else if (!strcasecmp(v->name, "bindaddr") || !strcasecmp(v->name, "udpbindaddr")) {
31984 if (ast_parse_arg(v->value, PARSE_ADDR, &bindaddr)) {
31985 ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
31986 }
31987 } else if (!strcasecmp(v->name, "localnet")) {
31988 struct ast_ha *na;
31989 int ha_error = 0;
31990
31991 if (!(na = ast_append_ha("d", v->value, localaddr, &ha_error))) {
31992 ast_log(LOG_WARNING, "Invalid localnet value: %s\n", v->value);
31993 } else {
31994 localaddr = na;
31995 }
31996 if (ha_error) {
31997 ast_log(LOG_ERROR, "Bad localnet configuration value line %d : %s\n", v->lineno, v->value);
31998 }
31999 } else if (!strcasecmp(v->name, "media_address")) {
32000 if (ast_parse_arg(v->value, PARSE_ADDR, &media_address))
32001 ast_log(LOG_WARNING, "Invalid address for media_address keyword: %s\n", v->value);
32002 } else if (!strcasecmp(v->name, "externaddr") || !strcasecmp(v->name, "externip")) {
32003 if (ast_parse_arg(v->value, PARSE_ADDR, &externaddr)) {
32004 ast_log(LOG_WARNING,
32005 "Invalid address for externaddr keyword: %s\n",
32006 v->value);
32007 }
32008 externexpire = 0;
32009 } else if (!strcasecmp(v->name, "externhost")) {
32010 ast_copy_string(externhost, v->value, sizeof(externhost));
32011 if (ast_sockaddr_resolve_first(&externaddr, externhost, 0)) {
32012 ast_log(LOG_WARNING, "Invalid address for externhost keyword: %s\n", externhost);
32013 }
32014 externexpire = time(NULL);
32015 } else if (!strcasecmp(v->name, "externrefresh")) {
32016 if (sscanf(v->value, "%30d", &externrefresh) != 1) {
32017 ast_log(LOG_WARNING, "Invalid externrefresh value '%s', must be an integer >0 at line %d\n", v->value, v->lineno);
32018 externrefresh = 10;
32019 }
32020 } else if (!strcasecmp(v->name, "externtcpport")) {
32021 if (!(externtcpport = port_str2int(v->value, 0))) {
32022 ast_log(LOG_WARNING, "Invalid externtcpport value, must be a positive integer between 1 and 65535 at line %d\n", v->lineno);
32023 externtcpport = 0;
32024 }
32025 } else if (!strcasecmp(v->name, "externtlsport")) {
32026 if (!(externtlsport = port_str2int(v->value, STANDARD_TLS_PORT))) {
32027 ast_log(LOG_WARNING, "Invalid externtlsport value, must be a positive integer between 1 and 65535 at line %d\n", v->lineno);
32028 }
32029 } else if (!strcasecmp(v->name, "allow")) {
32030 int error = ast_parse_allow_disallow(&default_prefs, sip_cfg.caps, v->value, TRUE);
32031 if (error) {
32032 ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
32033 }
32034 } else if (!strcasecmp(v->name, "disallow")) {
32035 int error = ast_parse_allow_disallow(&default_prefs, sip_cfg.caps, v->value, FALSE);
32036 if (error) {
32037 ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
32038 }
32039 } else if (!strcasecmp(v->name, "preferred_codec_only")) {
32040 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_PREFERRED_CODEC);
32041 } else if (!strcasecmp(v->name, "autoframing")) {
32042 global_autoframing = ast_true(v->value);
32043 } else if (!strcasecmp(v->name, "allowexternaldomains")) {
32044 sip_cfg.allow_external_domains = ast_true(v->value);
32045 } else if (!strcasecmp(v->name, "autodomain")) {
32046 auto_sip_domains = ast_true(v->value);
32047 } else if (!strcasecmp(v->name, "domain")) {
32048 char *domain = ast_strdupa(v->value);
32049 char *cntx = strchr(domain, ',');
32050
32051 if (cntx) {
32052 *cntx++ = '\0';
32053 }
32054
32055 if (ast_strlen_zero(cntx)) {
32056 ast_debug(1, "No context specified at line %d for domain '%s'\n", v->lineno, domain);
32057 }
32058 if (ast_strlen_zero(domain)) {
32059 ast_log(LOG_WARNING, "Empty domain specified at line %d\n", v->lineno);
32060 } else {
32061 add_sip_domain(ast_strip(domain), SIP_DOMAIN_CONFIG, cntx ? ast_strip(cntx) : "");
32062 }
32063 } else if (!strcasecmp(v->name, "register")) {
32064 if (sip_register(v->value, v->lineno) == 0) {
32065 registry_count++;
32066 }
32067 } else if (!strcasecmp(v->name, "mwi")) {
32068 sip_subscribe_mwi(v->value, v->lineno);
32069 } else if (!strcasecmp(v->name, "tos_sip")) {
32070 if (ast_str2tos(v->value, &global_tos_sip)) {
32071 ast_log(LOG_WARNING, "Invalid tos_sip value at line %d, refer to QoS documentation\n", v->lineno);
32072 }
32073 } else if (!strcasecmp(v->name, "tos_audio")) {
32074 if (ast_str2tos(v->value, &global_tos_audio)) {
32075 ast_log(LOG_WARNING, "Invalid tos_audio value at line %d, refer to QoS documentation\n", v->lineno);
32076 }
32077 } else if (!strcasecmp(v->name, "tos_video")) {
32078 if (ast_str2tos(v->value, &global_tos_video)) {
32079 ast_log(LOG_WARNING, "Invalid tos_video value at line %d, refer to QoS documentation\n", v->lineno);
32080 }
32081 } else if (!strcasecmp(v->name, "tos_text")) {
32082 if (ast_str2tos(v->value, &global_tos_text)) {
32083 ast_log(LOG_WARNING, "Invalid tos_text value at line %d, refer to QoS documentation\n", v->lineno);
32084 }
32085 } else if (!strcasecmp(v->name, "cos_sip")) {
32086 if (ast_str2cos(v->value, &global_cos_sip)) {
32087 ast_log(LOG_WARNING, "Invalid cos_sip value at line %d, refer to QoS documentation\n", v->lineno);
32088 }
32089 } else if (!strcasecmp(v->name, "cos_audio")) {
32090 if (ast_str2cos(v->value, &global_cos_audio)) {
32091 ast_log(LOG_WARNING, "Invalid cos_audio value at line %d, refer to QoS documentation\n", v->lineno);
32092 }
32093 } else if (!strcasecmp(v->name, "cos_video")) {
32094 if (ast_str2cos(v->value, &global_cos_video)) {
32095 ast_log(LOG_WARNING, "Invalid cos_video value at line %d, refer to QoS documentation\n", v->lineno);
32096 }
32097 } else if (!strcasecmp(v->name, "cos_text")) {
32098 if (ast_str2cos(v->value, &global_cos_text)) {
32099 ast_log(LOG_WARNING, "Invalid cos_text value at line %d, refer to QoS documentation\n", v->lineno);
32100 }
32101 } else if (!strcasecmp(v->name, "bindport")) {
32102 if (sscanf(v->value, "%5d", &bindport) != 1) {
32103 ast_log(LOG_WARNING, "Invalid port number '%s' at line %d of %s\n", v->value, v->lineno, config);
32104 }
32105 } else if (!strcasecmp(v->name, "qualify")) {
32106 if (!strcasecmp(v->value, "no")) {
32107 default_qualify = 0;
32108 } else if (!strcasecmp(v->value, "yes")) {
32109 default_qualify = DEFAULT_MAXMS;
32110 } else if (sscanf(v->value, "%30d", &default_qualify) != 1) {
32111 ast_log(LOG_WARNING, "Qualification default should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", v->lineno);
32112 default_qualify = 0;
32113 }
32114 } else if (!strcasecmp(v->name, "keepalive")) {
32115 if (!strcasecmp(v->value, "no")) {
32116 default_keepalive = 0;
32117 } else if (!strcasecmp(v->value, "yes")) {
32118 default_keepalive = DEFAULT_KEEPALIVE_INTERVAL;
32119 } else if (sscanf(v->value, "%30d", &default_keepalive) != 1) {
32120 ast_log(LOG_WARNING, "Keep alive default should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", v->lineno);
32121 default_keepalive = 0;
32122 }
32123 } else if (!strcasecmp(v->name, "qualifyfreq")) {
32124 int i;
32125 if (sscanf(v->value, "%30d", &i) == 1) {
32126 global_qualifyfreq = i * 1000;
32127 } else {
32128 ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
32129 global_qualifyfreq = DEFAULT_QUALIFYFREQ;
32130 }
32131 } else if (!strcasecmp(v->name, "callevents")) {
32132 sip_cfg.callevents = ast_true(v->value);
32133 } else if (!strcasecmp(v->name, "authfailureevents")) {
32134 global_authfailureevents = ast_true(v->value);
32135 } else if (!strcasecmp(v->name, "maxcallbitrate")) {
32136 default_maxcallbitrate = atoi(v->value);
32137 if (default_maxcallbitrate < 0) {
32138 default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
32139 }
32140 } else if (!strcasecmp(v->name, "matchexternaddrlocally") || !strcasecmp(v->name, "matchexterniplocally")) {
32141 sip_cfg.matchexternaddrlocally = ast_true(v->value);
32142 } else if (!strcasecmp(v->name, "session-timers")) {
32143 int i = (int) str2stmode(v->value);
32144 if (i < 0) {
32145 ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
32146 global_st_mode = SESSION_TIMER_MODE_ACCEPT;
32147 } else {
32148 global_st_mode = i;
32149 }
32150 } else if (!strcasecmp(v->name, "session-expires")) {
32151 if (sscanf(v->value, "%30d", &global_max_se) != 1) {
32152 ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
32153 global_max_se = DEFAULT_MAX_SE;
32154 }
32155 } else if (!strcasecmp(v->name, "session-minse")) {
32156 if (sscanf(v->value, "%30d", &global_min_se) != 1) {
32157 ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
32158 global_min_se = DEFAULT_MIN_SE;
32159 }
32160 if (global_min_se < DEFAULT_MIN_SE) {
32161 ast_log(LOG_WARNING, "session-minse '%s' at line %d of %s is not allowed to be < %d secs\n", v->value, v->lineno, config, DEFAULT_MIN_SE);
32162 global_min_se = DEFAULT_MIN_SE;
32163 }
32164 } else if (!strcasecmp(v->name, "session-refresher")) {
32165 int i = (int) str2strefresherparam(v->value);
32166 if (i < 0) {
32167 ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
32168 global_st_refresher = SESSION_TIMER_REFRESHER_PARAM_UAS;
32169 } else {
32170 global_st_refresher = i;
32171 }
32172 } else if (!strcasecmp(v->name, "storesipcause")) {
32173 global_store_sip_cause = ast_true(v->value);
32174 if (global_store_sip_cause) {
32175 ast_log(LOG_WARNING, "Usage of SIP_CAUSE is deprecated. Please use HANGUPCAUSE instead.\n");
32176 }
32177 } else if (!strcasecmp(v->name, "qualifygap")) {
32178 if (sscanf(v->value, "%30d", &global_qualify_gap) != 1) {
32179 ast_log(LOG_WARNING, "Invalid qualifygap '%s' at line %d of %s\n", v->value, v->lineno, config);
32180 global_qualify_gap = DEFAULT_QUALIFY_GAP;
32181 }
32182 } else if (!strcasecmp(v->name, "qualifypeers")) {
32183 if (sscanf(v->value, "%30d", &global_qualify_peers) != 1) {
32184 ast_log(LOG_WARNING, "Invalid pokepeers '%s' at line %d of %s\n", v->value, v->lineno, config);
32185 global_qualify_peers = DEFAULT_QUALIFY_PEERS;
32186 }
32187 } else if (!strcasecmp(v->name, "disallowed_methods")) {
32188 char *disallow = ast_strdupa(v->value);
32189 mark_parsed_methods(&sip_cfg.disallowed_methods, disallow);
32190 } else if (!strcasecmp(v->name, "shrinkcallerid")) {
32191 if (ast_true(v->value)) {
32192 global_shrinkcallerid = 1;
32193 } else if (ast_false(v->value)) {
32194 global_shrinkcallerid = 0;
32195 } else {
32196 ast_log(LOG_WARNING, "shrinkcallerid value %s is not valid at line %d.\n", v->value, v->lineno);
32197 }
32198 } else if (!strcasecmp(v->name, "use_q850_reason")) {
32199 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_Q850_REASON);
32200 } else if (!strcasecmp(v->name, "maxforwards")) {
32201 if (sscanf(v->value, "%30d", &sip_cfg.default_max_forwards) != 1
32202 || sip_cfg.default_max_forwards < 1 || 255 < sip_cfg.default_max_forwards) {
32203 ast_log(LOG_WARNING, "'%s' is not a valid maxforwards value at line %d. Using default.\n", v->value, v->lineno);
32204 sip_cfg.default_max_forwards = DEFAULT_MAX_FORWARDS;
32205 }
32206 } else if (!strcasecmp(v->name, "subscribe_network_change_event")) {
32207 if (ast_true(v->value)) {
32208 subscribe_network_change = 1;
32209 } else if (ast_false(v->value)) {
32210 subscribe_network_change = 0;
32211 } else {
32212 ast_log(LOG_WARNING, "subscribe_network_change_event value %s is not valid at line %d.\n", v->value, v->lineno);
32213 }
32214 } else if (!strcasecmp(v->name, "snom_aoc_enabled")) {
32215 ast_set2_flag(&global_flags[2], ast_true(v->value), SIP_PAGE3_SNOM_AOC);
32216 } else if (!strcasecmp(v->name, "icesupport")) {
32217 ast_set2_flag(&global_flags[2], ast_true(v->value), SIP_PAGE3_ICE_SUPPORT);
32218 } else if (!strcasecmp(v->name, "parkinglot")) {
32219 ast_copy_string(default_parkinglot, v->value, sizeof(default_parkinglot));
32220 } else if (!strcasecmp(v->name, "refer_addheaders")) {
32221 global_refer_addheaders = ast_true(v->value);
32222 }
32223 }
32224
32225
32226 ast_copy_flags(&global_flags[0], &setflags[0], mask[0].flags);
32227 ast_copy_flags(&global_flags[1], &setflags[1], mask[1].flags);
32228 ast_copy_flags(&global_flags[2], &setflags[2], mask[2].flags);
32229
32230
32231 if (!min_subexpiry_set) {
32232 min_subexpiry = min_expiry;
32233 }
32234 if (!max_subexpiry_set) {
32235 max_subexpiry = max_expiry;
32236 }
32237
32238 if (reason != CHANNEL_MODULE_LOAD && sip_cfg.autocreatepeer != AUTOPEERS_PERSIST) {
32239 ao2_t_callback(peers, OBJ_NODATA, peer_markall_autopeers_func, NULL, "callback to mark autopeers for destruction");
32240 }
32241
32242 if (subscribe_network_change) {
32243 network_change_event_subscribe();
32244 } else {
32245 network_change_event_unsubscribe();
32246 }
32247
32248 if (global_t1 < global_t1min) {
32249 ast_log(LOG_WARNING, "'t1min' (%d) cannot be greater than 't1timer' (%d). Resetting 't1timer' to the value of 't1min'\n", global_t1min, global_t1);
32250 global_t1 = global_t1min;
32251 }
32252
32253 if (global_timer_b < global_t1 * 64) {
32254 if (timerb_set && timert1_set) {
32255 ast_log(LOG_WARNING, "Timer B has been set lower than recommended (%d < 64 * timert1=%d). (RFC 3261, 17.1.1.2)\n", global_timer_b, global_t1);
32256 } else if (timerb_set) {
32257 if ((global_t1 = global_timer_b / 64) < global_t1min) {
32258 ast_log(LOG_WARNING, "Timer B has been set lower than recommended (%d < 64 * timert1=%d). (RFC 3261, 17.1.1.2)\n", global_timer_b, global_t1);
32259 global_t1 = global_t1min;
32260 global_timer_b = global_t1 * 64;
32261 }
32262 } else {
32263 global_timer_b = global_t1 * 64;
32264 }
32265 }
32266 if (!sip_cfg.allow_external_domains && AST_LIST_EMPTY(&domain_list)) {
32267 ast_log(LOG_WARNING, "To disallow external domains, you need to configure local SIP domains.\n");
32268 sip_cfg.allow_external_domains = 1;
32269 }
32270
32271 if (!sip_cfg.tcp_enabled && (default_transports & SIP_TRANSPORT_TCP)) {
32272 ast_log(LOG_WARNING, "Cannot use 'tcp' transport with tcpenable=no. Removing from available transports.\n");
32273 default_primary_transport &= ~SIP_TRANSPORT_TCP;
32274 default_transports &= ~SIP_TRANSPORT_TCP;
32275 }
32276 if (!default_tls_cfg.enabled && (default_transports & SIP_TRANSPORT_TLS)) {
32277 ast_log(LOG_WARNING, "Cannot use 'tls' transport with tlsenable=no. Removing from available transports.\n");
32278 default_primary_transport &= ~SIP_TRANSPORT_TLS;
32279 default_transports &= ~SIP_TRANSPORT_TLS;
32280 }
32281 if (!default_transports) {
32282 ast_log(LOG_WARNING, "No valid transports available, falling back to 'udp'.\n");
32283 default_transports = default_primary_transport = SIP_TRANSPORT_UDP;
32284 } else if (!default_primary_transport) {
32285 ast_log(LOG_WARNING, "No valid default transport. Selecting 'udp' as default.\n");
32286 default_primary_transport = SIP_TRANSPORT_UDP;
32287 }
32288
32289
32290 for (v = ast_variable_browse(cfg, "authentication"); v ; v = v->next) {
32291
32292 if (!strcasecmp(v->name, "auth")) {
32293 add_realm_authentication(&authl, v->value, v->lineno);
32294 }
32295 }
32296
32297 if (bindport) {
32298 if (ast_sockaddr_port(&bindaddr)) {
32299 ast_log(LOG_WARNING, "bindport is also specified in bindaddr. "
32300 "Using %d.\n", bindport);
32301 }
32302 ast_sockaddr_set_port(&bindaddr, bindport);
32303 }
32304
32305 if (!ast_sockaddr_port(&bindaddr)) {
32306 ast_sockaddr_set_port(&bindaddr, STANDARD_SIP_PORT);
32307 }
32308
32309
32310 ast_sockaddr_copy(&internip, &bindaddr);
32311 if (ast_find_ourip(&internip, &bindaddr, 0)) {
32312 ast_log(LOG_WARNING, "Unable to get own IP address, SIP disabled\n");
32313 ast_config_destroy(cfg);
32314 return 0;
32315 }
32316
32317 ast_mutex_lock(&netlock);
32318 if ((sipsock > -1) && (ast_sockaddr_cmp(&old_bindaddr, &bindaddr))) {
32319 close(sipsock);
32320 sipsock = -1;
32321 }
32322 if (sipsock < 0) {
32323 sipsock = socket(ast_sockaddr_is_ipv6(&bindaddr) ?
32324 AF_INET6 : AF_INET, SOCK_DGRAM, 0);
32325 if (sipsock < 0) {
32326 ast_log(LOG_WARNING, "Unable to create SIP socket: %s\n", strerror(errno));
32327 ast_config_destroy(cfg);
32328 ast_mutex_unlock(&netlock);
32329 return -1;
32330 } else {
32331
32332 const int reuseFlag = 1;
32333
32334 setsockopt(sipsock, SOL_SOCKET, SO_REUSEADDR,
32335 (const char*)&reuseFlag,
32336 sizeof reuseFlag);
32337
32338 ast_enable_packet_fragmentation(sipsock);
32339
32340 if (ast_bind(sipsock, &bindaddr) < 0) {
32341 ast_log(LOG_WARNING, "Failed to bind to %s: %s\n",
32342 ast_sockaddr_stringify(&bindaddr), strerror(errno));
32343 close(sipsock);
32344 sipsock = -1;
32345 } else {
32346 ast_verb(2, "SIP Listening on %s\n", ast_sockaddr_stringify(&bindaddr));
32347 ast_set_qos(sipsock, global_tos_sip, global_cos_sip, "SIP");
32348 }
32349 }
32350 } else {
32351 ast_set_qos(sipsock, global_tos_sip, global_cos_sip, "SIP");
32352 }
32353 ast_mutex_unlock(&netlock);
32354
32355
32356 if (sip_cfg.tcp_enabled) {
32357 if (ast_sockaddr_isnull(&sip_tcp_desc.local_address)) {
32358 ast_sockaddr_copy(&sip_tcp_desc.local_address, &bindaddr);
32359 }
32360 if (!ast_sockaddr_port(&sip_tcp_desc.local_address)) {
32361 ast_sockaddr_set_port(&sip_tcp_desc.local_address, STANDARD_SIP_PORT);
32362 }
32363 } else {
32364 ast_sockaddr_setnull(&sip_tcp_desc.local_address);
32365 }
32366 ast_tcptls_server_start(&sip_tcp_desc);
32367 if (sip_cfg.tcp_enabled && sip_tcp_desc.accept_fd == -1) {
32368
32369 ast_log(LOG_ERROR, "SIP TCP Server start failed. Not listening on TCP socket.\n");
32370 } else {
32371 ast_debug(2, "SIP TCP server started\n");
32372 }
32373
32374
32375 memcpy(sip_tls_desc.tls_cfg, &default_tls_cfg, sizeof(default_tls_cfg));
32376
32377 if (ast_ssl_setup(sip_tls_desc.tls_cfg)) {
32378 if (ast_sockaddr_isnull(&sip_tls_desc.local_address)) {
32379 ast_sockaddr_copy(&sip_tls_desc.local_address, &bindaddr);
32380 ast_sockaddr_set_port(&sip_tls_desc.local_address,
32381 STANDARD_TLS_PORT);
32382 }
32383 if (!ast_sockaddr_port(&sip_tls_desc.local_address)) {
32384 ast_sockaddr_set_port(&sip_tls_desc.local_address,
32385 STANDARD_TLS_PORT);
32386 }
32387 ast_tcptls_server_start(&sip_tls_desc);
32388 if (default_tls_cfg.enabled && sip_tls_desc.accept_fd == -1) {
32389 ast_log(LOG_ERROR, "TLS Server start failed. Not listening on TLS socket.\n");
32390 sip_tls_desc.tls_cfg = NULL;
32391 }
32392 } else if (sip_tls_desc.tls_cfg->enabled) {
32393 sip_tls_desc.tls_cfg = NULL;
32394 ast_log(LOG_WARNING, "SIP TLS server did not load because of errors.\n");
32395 }
32396
32397 if (ucfg) {
32398 struct ast_variable *gen;
32399 int genhassip, genregistersip;
32400 const char *hassip, *registersip;
32401
32402 genhassip = ast_true(ast_variable_retrieve(ucfg, "general", "hassip"));
32403 genregistersip = ast_true(ast_variable_retrieve(ucfg, "general", "registersip"));
32404 gen = ast_variable_browse(ucfg, "general");
32405 cat = ast_category_browse(ucfg, NULL);
32406 while (cat) {
32407 if (strcasecmp(cat, "general")) {
32408 hassip = ast_variable_retrieve(ucfg, cat, "hassip");
32409 registersip = ast_variable_retrieve(ucfg, cat, "registersip");
32410 if (ast_true(hassip) || (!hassip && genhassip)) {
32411 peer = build_peer(cat, gen, ast_variable_browse(ucfg, cat), 0, 0);
32412 if (peer) {
32413
32414 peer->type = SIP_TYPE_USER | SIP_TYPE_PEER;
32415 ao2_t_link(peers, peer, "link peer into peer table");
32416 if ((peer->type & SIP_TYPE_PEER) && !ast_sockaddr_isnull(&peer->addr)) {
32417 ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
32418 }
32419
32420 sip_unref_peer(peer, "sip_unref_peer: from reload_config");
32421 peer_count++;
32422 }
32423 }
32424 if (ast_true(registersip) || (!registersip && genregistersip)) {
32425 char tmp[256];
32426 const char *host = ast_variable_retrieve(ucfg, cat, "host");
32427 const char *username = ast_variable_retrieve(ucfg, cat, "username");
32428 const char *secret = ast_variable_retrieve(ucfg, cat, "secret");
32429 const char *contact = ast_variable_retrieve(ucfg, cat, "contact");
32430 const char *authuser = ast_variable_retrieve(ucfg, cat, "authuser");
32431 if (!host) {
32432 host = ast_variable_retrieve(ucfg, "general", "host");
32433 }
32434 if (!username) {
32435 username = ast_variable_retrieve(ucfg, "general", "username");
32436 }
32437 if (!secret) {
32438 secret = ast_variable_retrieve(ucfg, "general", "secret");
32439 }
32440 if (!contact) {
32441 contact = "s";
32442 }
32443 if (!ast_strlen_zero(username) && !ast_strlen_zero(host)) {
32444 if (!ast_strlen_zero(secret)) {
32445 if (!ast_strlen_zero(authuser)) {
32446 snprintf(tmp, sizeof(tmp), "%s?%s:%s:%s@%s/%s", cat, username, secret, authuser, host, contact);
32447 } else {
32448 snprintf(tmp, sizeof(tmp), "%s?%s:%s@%s/%s", cat, username, secret, host, contact);
32449 }
32450 } else if (!ast_strlen_zero(authuser)) {
32451 snprintf(tmp, sizeof(tmp), "%s?%s::%s@%s/%s", cat, username, authuser, host, contact);
32452 } else {
32453 snprintf(tmp, sizeof(tmp), "%s?%s@%s/%s", cat, username, host, contact);
32454 }
32455 if (sip_register(tmp, 0) == 0) {
32456 registry_count++;
32457 }
32458 }
32459 }
32460 }
32461 cat = ast_category_browse(ucfg, cat);
32462 }
32463 ast_config_destroy(ucfg);
32464 }
32465
32466
32467 cat = NULL;
32468 while ( (cat = ast_category_browse(cfg, cat)) ) {
32469 const char *utype;
32470 if (!strcasecmp(cat, "general") || !strcasecmp(cat, "authentication"))
32471 continue;
32472 utype = ast_variable_retrieve(cfg, cat, "type");
32473 if (!utype) {
32474 ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
32475 continue;
32476 } else {
32477 if (!strcasecmp(utype, "user")) {
32478 ;
32479 } else if (!strcasecmp(utype, "friend")) {
32480 ;
32481 } else if (!strcasecmp(utype, "peer")) {
32482 ;
32483 } else {
32484 ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, "sip.conf");
32485 continue;
32486 }
32487 peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0, 0);
32488 if (peer) {
32489 display_nat_warning(cat, reason, &peer->flags[0]);
32490 ao2_t_link(peers, peer, "link peer into peers table");
32491 if ((peer->type & SIP_TYPE_PEER) && !ast_sockaddr_isnull(&peer->addr)) {
32492 ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
32493 }
32494 sip_unref_peer(peer, "unref the result of the build_peer call. Now, the links from the tables are the only ones left.");
32495 peer_count++;
32496 }
32497 }
32498 }
32499
32500
32501
32502
32503
32504
32505 if (auto_sip_domains) {
32506 char temp[MAXHOSTNAMELEN];
32507
32508
32509 if (!ast_sockaddr_isnull(&bindaddr) && !ast_sockaddr_is_any(&bindaddr)) {
32510 add_sip_domain(ast_sockaddr_stringify_addr(&bindaddr),
32511 SIP_DOMAIN_AUTO, NULL);
32512 } else if (!ast_sockaddr_isnull(&internip) && !ast_sockaddr_is_any(&internip)) {
32513
32514 add_sip_domain(ast_sockaddr_stringify_addr(&internip),
32515 SIP_DOMAIN_AUTO, NULL);
32516 } else {
32517 ast_log(LOG_NOTICE, "Can't add wildcard IP address to domain list, please add IP address to domain manually.\n");
32518 }
32519
32520
32521 if (!ast_sockaddr_isnull(&sip_tcp_desc.local_address) &&
32522 !ast_sockaddr_cmp(&bindaddr, &sip_tcp_desc.local_address)) {
32523 add_sip_domain(ast_sockaddr_stringify_addr(&sip_tcp_desc.local_address),
32524 SIP_DOMAIN_AUTO, NULL);
32525 }
32526
32527
32528 if (!ast_sockaddr_isnull(&sip_tls_desc.local_address) &&
32529 !ast_sockaddr_cmp(&bindaddr, &sip_tls_desc.local_address) &&
32530 !ast_sockaddr_cmp(&sip_tcp_desc.local_address,
32531 &sip_tls_desc.local_address)) {
32532 add_sip_domain(ast_sockaddr_stringify_addr(&sip_tcp_desc.local_address),
32533 SIP_DOMAIN_AUTO, NULL);
32534 }
32535
32536
32537 if (!ast_sockaddr_isnull(&externaddr)) {
32538 add_sip_domain(ast_sockaddr_stringify_addr(&externaddr),
32539 SIP_DOMAIN_AUTO, NULL);
32540 }
32541
32542
32543 if (!ast_strlen_zero(externhost)) {
32544 add_sip_domain(externhost, SIP_DOMAIN_AUTO, NULL);
32545 }
32546
32547
32548 if (!gethostname(temp, sizeof(temp))) {
32549 add_sip_domain(temp, SIP_DOMAIN_AUTO, NULL);
32550 }
32551 }
32552
32553
32554 ast_config_destroy(cfg);
32555
32556 register_realtime_peers_with_callbackextens();
32557
32558
32559 if (notify_types) {
32560 ast_config_destroy(notify_types);
32561 }
32562 if ((notify_types = ast_config_load(notify_config, config_flags)) == CONFIG_STATUS_FILEINVALID) {
32563 ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed.\n", notify_config);
32564 notify_types = NULL;
32565 }
32566
32567
32568 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);
32569 run_end = time(0);
32570 ast_debug(4, "SIP reload_config done...Runtime= %d sec\n", (int)(run_end-run_start));
32571
32572
32573 if (acl_change_subscription_needed) {
32574 acl_change_event_subscribe();
32575 }
32576
32577 return 0;
32578 }
32579
32580 static int apply_directmedia_acl(struct sip_pvt *p, struct ast_acl_list *directmediaacl, const char *op)
32581 {
32582 struct ast_sockaddr us = { { 0, }, }, them = { { 0, }, };
32583 int res = AST_SENSE_ALLOW;
32584
32585 ast_rtp_instance_get_remote_address(p->rtp, &them);
32586 ast_rtp_instance_get_local_address(p->rtp, &us);
32587
32588 if ((res = ast_apply_acl(directmediaacl, &them, "SIP Direct Media ACL: ")) == AST_SENSE_DENY) {
32589 const char *us_addr = ast_strdupa(ast_sockaddr_stringify(&us));
32590 const char *them_addr = ast_strdupa(ast_sockaddr_stringify(&them));
32591
32592 ast_debug(3, "Reinvite %s to %s denied by directmedia ACL on %s\n",
32593 op, them_addr, us_addr);
32594 }
32595
32596 return res;
32597 }
32598
32599 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan)
32600 {
32601 struct sip_pvt *p;
32602 struct ast_udptl *udptl = NULL;
32603
32604 p = ast_channel_tech_pvt(chan);
32605 if (!p) {
32606 return NULL;
32607 }
32608
32609 sip_pvt_lock(p);
32610 if (p->udptl && ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
32611 udptl = p->udptl;
32612 }
32613 sip_pvt_unlock(p);
32614 return udptl;
32615 }
32616
32617 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl)
32618 {
32619 struct sip_pvt *p;
32620
32621
32622 ast_channel_lock(chan);
32623 p = ast_channel_tech_pvt(chan);
32624 if (!p) {
32625 ast_channel_unlock(chan);
32626 return -1;
32627 }
32628 sip_pvt_lock(p);
32629 if (p->owner != chan) {
32630
32631 ast_debug(1, "The private is not owned by channel %s anymore.\n", ast_channel_name(chan));
32632 sip_pvt_unlock(p);
32633 ast_channel_unlock(chan);
32634 return 0;
32635 }
32636
32637 if (udptl) {
32638 ast_udptl_get_peer(udptl, &p->udptlredirip);
32639 } else {
32640 memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
32641 }
32642 if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
32643 if (!p->pendinginvite) {
32644 ast_debug(3, "Sending reinvite on SIP '%s' - It's UDPTL soon redirected to IP %s\n",
32645 p->callid, ast_sockaddr_stringify(udptl ? &p->udptlredirip : &p->ourip));
32646 transmit_reinvite_with_sdp(p, TRUE, FALSE);
32647 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
32648 ast_debug(3, "Deferring reinvite on SIP '%s' - It's UDPTL will be redirected to IP %s\n",
32649 p->callid, ast_sockaddr_stringify(udptl ? &p->udptlredirip : &p->ourip));
32650 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
32651 }
32652 }
32653
32654 p->lastrtprx = p->lastrtptx = time(NULL);
32655 sip_pvt_unlock(p);
32656 ast_channel_unlock(chan);
32657 return 0;
32658 }
32659
32660 static int sip_allow_anyrtp_remote(struct ast_channel *chan1, struct ast_channel *chan2, char *rtptype)
32661 {
32662 struct sip_pvt *p1 = NULL, *p2 = NULL;
32663 struct ast_acl_list *p2_directmediaacl = NULL;
32664 struct ast_acl_list *p1_directmediaacl = NULL;
32665 int res = 1;
32666
32667 if (!(p1 = ast_channel_tech_pvt(chan1))) {
32668 return 0;
32669 }
32670
32671 if (!(p2 = ast_channel_tech_pvt(chan2))) {
32672 return 0;
32673 }
32674
32675 sip_pvt_lock(p2);
32676 if (p2->relatedpeer && p2->relatedpeer->directmediaacl) {
32677 p2_directmediaacl = ast_duplicate_acl_list(p2->relatedpeer->directmediaacl);
32678 }
32679 sip_pvt_unlock(p2);
32680
32681 sip_pvt_lock(p1);
32682 if (p1->relatedpeer && p1->relatedpeer->directmediaacl) {
32683 p1_directmediaacl = ast_duplicate_acl_list(p1->relatedpeer->directmediaacl);
32684 }
32685
32686 if (p2_directmediaacl && ast_test_flag(&p1->flags[0], SIP_DIRECT_MEDIA)) {
32687 if (!apply_directmedia_acl(p1, p2_directmediaacl, rtptype)) {
32688 res = 0;
32689 }
32690 }
32691 sip_pvt_unlock(p1);
32692
32693 if (res == 0) {
32694 goto allow_anyrtp_remote_end;
32695 }
32696
32697 sip_pvt_lock(p2);
32698 if (p1_directmediaacl && ast_test_flag(&p2->flags[0], SIP_DIRECT_MEDIA)) {
32699 if (!apply_directmedia_acl(p2, p1_directmediaacl, rtptype)) {
32700 res = 0;
32701 }
32702 }
32703 sip_pvt_unlock(p2);
32704
32705 allow_anyrtp_remote_end:
32706
32707 if (p2_directmediaacl) {
32708 p2_directmediaacl = ast_free_acl_list(p2_directmediaacl);
32709 }
32710
32711 if (p1_directmediaacl) {
32712 p1_directmediaacl = ast_free_acl_list(p1_directmediaacl);
32713 }
32714
32715 return res;
32716 }
32717
32718 static int sip_allow_rtp_remote(struct ast_channel *chan1, struct ast_channel *chan2)
32719 {
32720 return sip_allow_anyrtp_remote(chan1, chan2, "audio");
32721 }
32722
32723 static int sip_allow_vrtp_remote(struct ast_channel *chan1, struct ast_channel *chan2)
32724 {
32725 return sip_allow_anyrtp_remote(chan1, chan2, "video");
32726 }
32727
32728 static enum ast_rtp_glue_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
32729 {
32730 struct sip_pvt *p = NULL;
32731 enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_LOCAL;
32732
32733 if (!(p = ast_channel_tech_pvt(chan))) {
32734 return AST_RTP_GLUE_RESULT_FORBID;
32735 }
32736
32737 sip_pvt_lock(p);
32738 if (!(p->rtp)) {
32739 sip_pvt_unlock(p);
32740 return AST_RTP_GLUE_RESULT_FORBID;
32741 }
32742
32743 ao2_ref(p->rtp, +1);
32744 *instance = p->rtp;
32745
32746 if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
32747 res = AST_RTP_GLUE_RESULT_REMOTE;
32748 } else if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA_NAT)) {
32749 res = AST_RTP_GLUE_RESULT_REMOTE;
32750 } else if (ast_test_flag(&global_jbconf, AST_JB_FORCED)) {
32751 res = AST_RTP_GLUE_RESULT_FORBID;
32752 }
32753
32754 if (p->srtp) {
32755 res = AST_RTP_GLUE_RESULT_FORBID;
32756 }
32757
32758 sip_pvt_unlock(p);
32759
32760 return res;
32761 }
32762
32763 static enum ast_rtp_glue_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
32764 {
32765 struct sip_pvt *p = NULL;
32766 enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_FORBID;
32767
32768 if (!(p = ast_channel_tech_pvt(chan))) {
32769 return AST_RTP_GLUE_RESULT_FORBID;
32770 }
32771
32772 sip_pvt_lock(p);
32773 if (!(p->vrtp)) {
32774 sip_pvt_unlock(p);
32775 return AST_RTP_GLUE_RESULT_FORBID;
32776 }
32777
32778 ao2_ref(p->vrtp, +1);
32779 *instance = p->vrtp;
32780
32781 if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
32782 res = AST_RTP_GLUE_RESULT_REMOTE;
32783 }
32784
32785 sip_pvt_unlock(p);
32786
32787 return res;
32788 }
32789
32790 static enum ast_rtp_glue_result sip_get_trtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
32791 {
32792 struct sip_pvt *p = NULL;
32793 enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_FORBID;
32794
32795 if (!(p = ast_channel_tech_pvt(chan))) {
32796 return AST_RTP_GLUE_RESULT_FORBID;
32797 }
32798
32799 sip_pvt_lock(p);
32800 if (!(p->trtp)) {
32801 sip_pvt_unlock(p);
32802 return AST_RTP_GLUE_RESULT_FORBID;
32803 }
32804
32805 ao2_ref(p->trtp, +1);
32806 *instance = p->trtp;
32807
32808 if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
32809 res = AST_RTP_GLUE_RESULT_REMOTE;
32810 }
32811
32812 sip_pvt_unlock(p);
32813
32814 return res;
32815 }
32816
32817 static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp_instance *instance, struct ast_rtp_instance *vinstance, struct ast_rtp_instance *tinstance, const struct ast_format_cap *cap, int nat_active)
32818 {
32819 struct sip_pvt *p;
32820 int changed = 0;
32821
32822
32823 ast_channel_lock(chan);
32824 p = ast_channel_tech_pvt(chan);
32825 if (!p) {
32826 ast_channel_unlock(chan);
32827 return -1;
32828 }
32829 sip_pvt_lock(p);
32830 if (p->owner != chan) {
32831
32832 ast_debug(1, "The private is not owned by channel %s anymore.\n", ast_channel_name(chan));
32833 sip_pvt_unlock(p);
32834 ast_channel_unlock(chan);
32835 return 0;
32836 }
32837
32838
32839 if ((instance || vinstance || tinstance) &&
32840 !ast_bridged_channel(chan) &&
32841 !sip_cfg.directrtpsetup) {
32842 sip_pvt_unlock(p);
32843 ast_channel_unlock(chan);
32844 return 0;
32845 }
32846
32847 if (p->alreadygone) {
32848
32849 sip_pvt_unlock(p);
32850 ast_channel_unlock(chan);
32851 return 0;
32852 }
32853
32854
32855
32856
32857 if (nat_active && !ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA_NAT)) {
32858 sip_pvt_unlock(p);
32859 ast_channel_unlock(chan);
32860 return 0;
32861 }
32862
32863 if (instance) {
32864 changed |= ast_rtp_instance_get_and_cmp_remote_address(instance, &p->redirip);
32865
32866 if (p->rtp) {
32867
32868 ast_channel_set_fd(chan, 1, -1);
32869
32870 ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_RTCP, 0);
32871 }
32872 } else if (!ast_sockaddr_isnull(&p->redirip)) {
32873 memset(&p->redirip, 0, sizeof(p->redirip));
32874 changed = 1;
32875
32876 if (p->rtp) {
32877
32878
32879 ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_RTCP, 1);
32880
32881 ast_channel_set_fd(chan, 1, ast_rtp_instance_fd(p->rtp, 1));
32882 }
32883 }
32884
32885 if (vinstance) {
32886 changed |= ast_rtp_instance_get_and_cmp_remote_address(vinstance, &p->vredirip);
32887
32888 if (p->vrtp) {
32889
32890 ast_channel_set_fd(chan, 3, -1);
32891
32892 ast_rtp_instance_set_prop(p->vrtp, AST_RTP_PROPERTY_RTCP, 0);
32893 }
32894 } else if (!ast_sockaddr_isnull(&p->vredirip)) {
32895 memset(&p->vredirip, 0, sizeof(p->vredirip));
32896 changed = 1;
32897
32898 if (p->vrtp) {
32899
32900
32901 ast_rtp_instance_set_prop(p->vrtp, AST_RTP_PROPERTY_RTCP, 1);
32902
32903 ast_channel_set_fd(chan, 3, ast_rtp_instance_fd(p->vrtp, 1));
32904 }
32905 }
32906
32907 if (tinstance) {
32908 changed |= ast_rtp_instance_get_and_cmp_remote_address(tinstance, &p->tredirip);
32909 } else if (!ast_sockaddr_isnull(&p->tredirip)) {
32910 memset(&p->tredirip, 0, sizeof(p->tredirip));
32911 changed = 1;
32912 }
32913 if (cap && !ast_format_cap_is_empty(cap) && !ast_format_cap_identical(p->redircaps, cap)) {
32914 ast_format_cap_copy(p->redircaps, cap);
32915 changed = 1;
32916 }
32917
32918 if (ast_test_flag(&p->flags[2], SIP_PAGE3_DIRECT_MEDIA_OUTGOING) && !p->outgoing_call) {
32919
32920
32921
32922
32923 ast_clear_flag(&p->flags[2], SIP_PAGE3_DIRECT_MEDIA_OUTGOING);
32924 sip_pvt_unlock(p);
32925 ast_channel_unlock(chan);
32926 return 0;
32927 }
32928
32929 if (changed && !ast_test_flag(&p->flags[0], SIP_GOTREFER) && !ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
32930 if (ast_channel_state(chan) != AST_STATE_UP) {
32931 if (p->do_history)
32932 append_history(p, "ExtInv", "Initial invite sent with remote bridge proposal.");
32933 ast_debug(1, "Early remote bridge setting SIP '%s' - Sending media to %s\n", p->callid, ast_sockaddr_stringify(instance ? &p->redirip : &p->ourip));
32934 } else if (!p->pendinginvite) {
32935 ast_debug(3, "Sending reinvite on SIP '%s' - It's audio soon redirected to IP %s\n", p->callid, ast_sockaddr_stringify(instance ? &p->redirip : &p->ourip));
32936 transmit_reinvite_with_sdp(p, FALSE, FALSE);
32937 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
32938 ast_debug(3, "Deferring reinvite on SIP '%s' - It's audio will be redirected to IP %s\n", p->callid, ast_sockaddr_stringify(instance ? &p->redirip : &p->ourip));
32939
32940 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
32941 }
32942 }
32943
32944 p->lastrtprx = p->lastrtptx = time(NULL);
32945 sip_pvt_unlock(p);
32946 ast_channel_unlock(chan);
32947 return 0;
32948 }
32949
32950 static void sip_get_codec(struct ast_channel *chan, struct ast_format_cap *result)
32951 {
32952 struct sip_pvt *p = ast_channel_tech_pvt(chan);
32953 ast_format_cap_append(result, ast_format_cap_is_empty(p->peercaps) ? p->caps : p->peercaps);
32954 }
32955
32956 static struct ast_rtp_glue sip_rtp_glue = {
32957 .type = "SIP",
32958 .get_rtp_info = sip_get_rtp_peer,
32959 .allow_rtp_remote = sip_allow_rtp_remote,
32960 .get_vrtp_info = sip_get_vrtp_peer,
32961 .allow_vrtp_remote = sip_allow_vrtp_remote,
32962 .get_trtp_info = sip_get_trtp_peer,
32963 .update_peer = sip_set_rtp_peer,
32964 .get_codec = sip_get_codec,
32965 };
32966
32967 static char *app_dtmfmode = "SIPDtmfMode";
32968 static char *app_sipaddheader = "SIPAddHeader";
32969 static char *app_sipremoveheader = "SIPRemoveHeader";
32970 #ifdef TEST_FRAMEWORK
32971 static char *app_sipsendcustominfo = "SIPSendCustomINFO";
32972 #endif
32973
32974
32975 static int sip_dtmfmode(struct ast_channel *chan, const char *data)
32976 {
32977 struct sip_pvt *p;
32978 const char *mode = data;
32979
32980 if (!data) {
32981 ast_log(LOG_WARNING, "This application requires the argument: info, inband, rfc2833\n");
32982 return 0;
32983 }
32984 ast_channel_lock(chan);
32985 if (!IS_SIP_TECH(ast_channel_tech(chan))) {
32986 ast_log(LOG_WARNING, "Call this application only on SIP incoming calls\n");
32987 ast_channel_unlock(chan);
32988 return 0;
32989 }
32990 p = ast_channel_tech_pvt(chan);
32991 if (!p) {
32992 ast_channel_unlock(chan);
32993 return 0;
32994 }
32995 sip_pvt_lock(p);
32996 if (!strcasecmp(mode, "info")) {
32997 ast_clear_flag(&p->flags[0], SIP_DTMF);
32998 ast_set_flag(&p->flags[0], SIP_DTMF_INFO);
32999 p->jointnoncodeccapability &= ~AST_RTP_DTMF;
33000 } else if (!strcasecmp(mode, "shortinfo")) {
33001 ast_clear_flag(&p->flags[0], SIP_DTMF);
33002 ast_set_flag(&p->flags[0], SIP_DTMF_SHORTINFO);
33003 p->jointnoncodeccapability &= ~AST_RTP_DTMF;
33004 } else if (!strcasecmp(mode, "rfc2833")) {
33005 ast_clear_flag(&p->flags[0], SIP_DTMF);
33006 ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
33007 p->jointnoncodeccapability |= AST_RTP_DTMF;
33008 } else if (!strcasecmp(mode, "inband")) {
33009 ast_clear_flag(&p->flags[0], SIP_DTMF);
33010 ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
33011 p->jointnoncodeccapability &= ~AST_RTP_DTMF;
33012 } else {
33013 ast_log(LOG_WARNING, "I don't know about this dtmf mode: %s\n", mode);
33014 }
33015 if (p->rtp)
33016 ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
33017 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
33018 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
33019 enable_dsp_detect(p);
33020 } else {
33021 disable_dsp_detect(p);
33022 }
33023 sip_pvt_unlock(p);
33024 ast_channel_unlock(chan);
33025 return 0;
33026 }
33027
33028
33029 static int sip_addheader(struct ast_channel *chan, const char *data)
33030 {
33031 int no = 0;
33032 int ok = FALSE;
33033 char varbuf[30];
33034 const char *inbuf = data;
33035 char *subbuf;
33036
33037 if (ast_strlen_zero(inbuf)) {
33038 ast_log(LOG_WARNING, "This application requires the argument: Header\n");
33039 return 0;
33040 }
33041 ast_channel_lock(chan);
33042
33043
33044 while (!ok && no <= 50) {
33045 no++;
33046 snprintf(varbuf, sizeof(varbuf), "__SIPADDHEADER%.2d", no);
33047
33048
33049 if ((pbx_builtin_getvar_helper(chan, (const char *) varbuf + 2) == (const char *) NULL)) {
33050 ok = TRUE;
33051 }
33052 }
33053 if (ok) {
33054 size_t len = strlen(inbuf);
33055 subbuf = ast_alloca(len + 1);
33056 ast_get_encoded_str(inbuf, subbuf, len + 1);
33057 pbx_builtin_setvar_helper(chan, varbuf, subbuf);
33058 if (sipdebug) {
33059 ast_debug(1, "SIP Header added \"%s\" as %s\n", inbuf, varbuf);
33060 }
33061 } else {
33062 ast_log(LOG_WARNING, "Too many SIP headers added, max 50\n");
33063 }
33064 ast_channel_unlock(chan);
33065 return 0;
33066 }
33067
33068
33069 static int sip_removeheader(struct ast_channel *chan, const char *data)
33070 {
33071 struct ast_var_t *newvariable;
33072 struct varshead *headp;
33073 int removeall = 0;
33074 char *inbuf = (char *) data;
33075
33076 if (ast_strlen_zero(inbuf)) {
33077 removeall = 1;
33078 }
33079 ast_channel_lock(chan);
33080
33081 headp=ast_channel_varshead(chan);
33082 AST_LIST_TRAVERSE_SAFE_BEGIN (headp, newvariable, entries) {
33083 if (strncasecmp(ast_var_name(newvariable), "SIPADDHEADER", strlen("SIPADDHEADER")) == 0) {
33084 if (removeall || (!strncasecmp(ast_var_value(newvariable),inbuf,strlen(inbuf)))) {
33085 if (sipdebug) {
33086 ast_debug(1,"removing SIP Header \"%s\" as %s\n",
33087 ast_var_value(newvariable),
33088 ast_var_name(newvariable));
33089 }
33090 AST_LIST_REMOVE_CURRENT(entries);
33091 ast_var_delete(newvariable);
33092 }
33093 }
33094 }
33095 AST_LIST_TRAVERSE_SAFE_END;
33096
33097 ast_channel_unlock(chan);
33098 return 0;
33099 }
33100
33101 #ifdef TEST_FRAMEWORK
33102
33103 static int sip_sendcustominfo(struct ast_channel *chan, const char *data)
33104 {
33105 char *info_data, *useragent;
33106
33107 if (ast_strlen_zero(data)) {
33108 ast_log(LOG_WARNING, "You must provide data to be sent\n");
33109 return 0;
33110 }
33111
33112 useragent = ast_strdupa(data);
33113 info_data = strsep(&useragent, ",");
33114
33115 if (ast_sipinfo_send(chan, NULL, "text/plain", info_data, useragent)) {
33116 ast_log(LOG_WARNING, "Failed to create payload for custom SIP INFO\n");
33117 return 0;
33118 }
33119 return 0;
33120 }
33121 #endif
33122
33123
33124
33125
33126
33127
33128
33129 static int sip_sipredirect(struct sip_pvt *p, const char *dest)
33130 {
33131 char *cdest;
33132 char *extension, *domain;
33133
33134 cdest = ast_strdupa(dest);
33135
33136 extension = strsep(&cdest, "@");
33137 domain = cdest;
33138 if (ast_strlen_zero(extension)) {
33139 ast_log(LOG_ERROR, "Missing mandatory argument: extension\n");
33140 return 0;
33141 }
33142
33143
33144 if (!domain) {
33145 char *local_to_header;
33146 char to_header[256];
33147
33148 ast_copy_string(to_header, sip_get_header(&p->initreq, "To"), sizeof(to_header));
33149 if (ast_strlen_zero(to_header)) {
33150 ast_log(LOG_ERROR, "Cannot retrieve the 'To' header from the original SIP request!\n");
33151 return 0;
33152 }
33153 if (((local_to_header = strcasestr(to_header, "sip:")) || (local_to_header = strcasestr(to_header, "sips:")))
33154 && (local_to_header = strchr(local_to_header, '@'))) {
33155 char ldomain[256];
33156
33157 memset(ldomain, 0, sizeof(ldomain));
33158 local_to_header++;
33159
33160 sscanf(local_to_header, "%256[^<>; ]", ldomain);
33161 if (ast_strlen_zero(ldomain)) {
33162 ast_log(LOG_ERROR, "Can't find the host address\n");
33163 return 0;
33164 }
33165 domain = ast_strdupa(ldomain);
33166 }
33167 }
33168
33169 ast_string_field_build(p, our_contact, "Transfer <sip:%s@%s>", extension, domain);
33170 transmit_response_reliable(p, "302 Moved Temporarily", &p->initreq);
33171
33172 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
33173 sip_alreadygone(p);
33174
33175 if (p->owner) {
33176 enum ast_control_transfer message = AST_TRANSFER_SUCCESS;
33177 ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
33178 }
33179
33180 return 0;
33181 }
33182
33183 static int sip_is_xml_parsable(void)
33184 {
33185 #ifdef HAVE_LIBXML2
33186 return TRUE;
33187 #else
33188 return FALSE;
33189 #endif
33190 }
33191
33192
33193 static void sip_poke_all_peers(void)
33194 {
33195 int ms = 0, num = 0;
33196 struct ao2_iterator i;
33197 struct sip_peer *peer;
33198
33199 if (!speerobjs) {
33200 return;
33201 }
33202
33203 i = ao2_iterator_init(peers, 0);
33204 while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
33205 ao2_lock(peer);
33206
33207 if (peer->maxms) {
33208 if (num == global_qualify_peers) {
33209 ms += global_qualify_gap;
33210 num = 0;
33211 } else {
33212 num++;
33213 }
33214 AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, ms, sip_poke_peer_s, peer,
33215 sip_unref_peer(_data, "removing poke peer ref"),
33216 sip_unref_peer(peer, "removing poke peer ref"),
33217 sip_ref_peer(peer, "adding poke peer ref"));
33218 }
33219 ao2_unlock(peer);
33220 sip_unref_peer(peer, "toss iterator peer ptr");
33221 }
33222 ao2_iterator_destroy(&i);
33223 }
33224
33225
33226 static void sip_keepalive_all_peers(void)
33227 {
33228 struct ao2_iterator i;
33229 struct sip_peer *peer;
33230
33231 if (!speerobjs) {
33232 return;
33233 }
33234
33235 i = ao2_iterator_init(peers, 0);
33236 while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
33237 ao2_lock(peer);
33238 AST_SCHED_REPLACE_UNREF(peer->keepalivesend, sched, 0, sip_send_keepalive, peer,
33239 sip_unref_peer(_data, "removing poke peer ref"),
33240 sip_unref_peer(peer, "removing poke peer ref"),
33241 sip_ref_peer(peer, "adding poke peer ref"));
33242 ao2_unlock(peer);
33243 sip_unref_peer(peer, "toss iterator peer ptr");
33244 }
33245 ao2_iterator_destroy(&i);
33246 }
33247
33248
33249 static void sip_send_all_registers(void)
33250 {
33251 int ms;
33252 int regspacing;
33253 if (!regobjs) {
33254 return;
33255 }
33256 regspacing = default_expiry * 1000/regobjs;
33257 if (regspacing > 100) {
33258 regspacing = 100;
33259 }
33260 ms = regspacing;
33261 ASTOBJ_CONTAINER_TRAVERSE(®l, 1, do {
33262 ASTOBJ_WRLOCK(iterator);
33263 ms += regspacing;
33264 AST_SCHED_REPLACE_UNREF(iterator->expire, sched, ms, sip_reregister, iterator,
33265 registry_unref(_data, "REPLACE sched del decs the refcount"),
33266 registry_unref(iterator, "REPLACE sched add failure decs the refcount"),
33267 registry_addref(iterator, "REPLACE sched add incs the refcount"));
33268 ASTOBJ_UNLOCK(iterator);
33269 } while (0)
33270 );
33271 }
33272
33273
33274 static void sip_send_all_mwi_subscriptions(void)
33275 {
33276 ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
33277 struct sip_subscription_mwi *saved;
33278 ASTOBJ_WRLOCK(iterator);
33279 AST_SCHED_DEL(sched, iterator->resub);
33280 saved = ASTOBJ_REF(iterator);
33281 if ((iterator->resub = ast_sched_add(sched, 1, sip_subscribe_mwi_do, saved)) < 0) {
33282 ASTOBJ_UNREF(saved, sip_subscribe_mwi_destroy);
33283 }
33284 ASTOBJ_UNLOCK(iterator);
33285 } while (0));
33286 }
33287
33288
33289 static int setup_srtp(struct sip_srtp **srtp)
33290 {
33291 if (!ast_rtp_engine_srtp_is_registered()) {
33292 ast_log(LOG_ERROR, "No SRTP module loaded, can't setup SRTP session.\n");
33293 return -1;
33294 }
33295
33296 if (!(*srtp = sip_srtp_alloc())) {
33297 return -1;
33298 }
33299
33300 return 0;
33301 }
33302
33303 static int process_crypto(struct sip_pvt *p, struct ast_rtp_instance *rtp, struct sip_srtp **srtp, const char *a)
33304 {
33305 struct ast_rtp_engine_dtls *dtls;
33306
33307
33308 if (!rtp) {
33309 ast_debug(3, "Received offer with crypto line for media stream that is not enabled\n");
33310 return FALSE;
33311 }
33312
33313 if (strncasecmp(a, "crypto:", 7)) {
33314 return FALSE;
33315 }
33316 if (!*srtp) {
33317 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
33318 ast_log(LOG_WARNING, "Ignoring unexpected crypto attribute in SDP answer\n");
33319 return FALSE;
33320 }
33321
33322 if (setup_srtp(srtp) < 0) {
33323 return FALSE;
33324 }
33325 }
33326
33327 if (!(*srtp)->crypto && !((*srtp)->crypto = sdp_crypto_setup())) {
33328 return FALSE;
33329 }
33330
33331 if (sdp_crypto_process((*srtp)->crypto, a, rtp, *srtp) < 0) {
33332 return FALSE;
33333 }
33334
33335 ast_set_flag(*srtp, SRTP_CRYPTO_OFFER_OK);
33336
33337 if ((dtls = ast_rtp_instance_get_dtls(rtp))) {
33338 dtls->stop(rtp);
33339 p->dtls_cfg.enabled = 0;
33340 }
33341
33342 return TRUE;
33343 }
33344
33345
33346 static int sip_do_reload(enum channelreloadreason reason)
33347 {
33348 time_t start_poke, end_poke;
33349
33350 reload_config(reason);
33351 ast_sched_dump(sched);
33352
33353 start_poke = time(0);
33354
33355 unlink_marked_peers_from_tables();
33356
33357 ast_debug(4, "--------------- Done destroying pruned peers\n");
33358
33359
33360 sip_poke_all_peers();
33361
33362
33363 sip_keepalive_all_peers();
33364
33365
33366 sip_send_all_registers();
33367
33368 sip_send_all_mwi_subscriptions();
33369
33370 end_poke = time(0);
33371
33372 ast_debug(4, "do_reload finished. peer poke/prune reg contact time = %d sec.\n", (int)(end_poke-start_poke));
33373
33374 ast_debug(4, "--------------- SIP reload done\n");
33375
33376 return 0;
33377 }
33378
33379
33380 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
33381 {
33382 static struct sip_peer *tmp_peer, *new_peer;
33383
33384 switch (cmd) {
33385 case CLI_INIT:
33386 e->command = "sip reload";
33387 e->usage =
33388 "Usage: sip reload\n"
33389 " Reloads SIP configuration from sip.conf\n";
33390 return NULL;
33391 case CLI_GENERATE:
33392 return NULL;
33393 }
33394
33395 ast_mutex_lock(&sip_reload_lock);
33396 if (sip_reloading) {
33397 ast_verbose("Previous SIP reload not yet done\n");
33398 } else {
33399 sip_reloading = TRUE;
33400 sip_reloadreason = (a && a->fd) ? CHANNEL_CLI_RELOAD : CHANNEL_MODULE_RELOAD;
33401 }
33402 ast_mutex_unlock(&sip_reload_lock);
33403 restart_monitor();
33404
33405 tmp_peer = bogus_peer;
33406
33407 if ((new_peer = temp_peer("(bogus_peer)"))) {
33408 ast_string_field_set(new_peer, md5secret, BOGUS_PEER_MD5SECRET);
33409 ast_clear_flag(&new_peer->flags[0], SIP_INSECURE);
33410 bogus_peer = new_peer;
33411 ao2_t_ref(tmp_peer, -1, "unref the old bogus_peer during reload");
33412 } else {
33413 ast_log(LOG_ERROR, "Could not update the fake authentication peer.\n");
33414
33415 }
33416
33417 return CLI_SUCCESS;
33418 }
33419
33420
33421 static int reload(void)
33422 {
33423 if (sip_reload(0, 0, NULL)) {
33424 return 0;
33425 }
33426 return 1;
33427 }
33428
33429
33430
33431
33432
33433 static int ast_sockaddr_resolve_first_af(struct ast_sockaddr *addr,
33434 const char* name, int flag, int family)
33435 {
33436 struct ast_sockaddr *addrs;
33437 int addrs_cnt;
33438
33439 addrs_cnt = ast_sockaddr_resolve(&addrs, name, flag, family);
33440 if (addrs_cnt <= 0) {
33441 return 1;
33442 }
33443 if (addrs_cnt > 1) {
33444 ast_debug(1, "Multiple addresses, using the first one only\n");
33445 }
33446
33447 ast_sockaddr_copy(addr, &addrs[0]);
33448
33449 ast_free(addrs);
33450 return 0;
33451 }
33452
33453
33454
33455
33456
33457 static int ast_sockaddr_resolve_first(struct ast_sockaddr *addr,
33458 const char* name, int flag)
33459 {
33460 return ast_sockaddr_resolve_first_af(addr, name, flag, get_address_family_filter(SIP_TRANSPORT_UDP));
33461 }
33462
33463
33464
33465
33466
33467 static int ast_sockaddr_resolve_first_transport(struct ast_sockaddr *addr,
33468 const char* name, int flag, unsigned int transport)
33469 {
33470 return ast_sockaddr_resolve_first_af(addr, name, flag, get_address_family_filter(transport));
33471 }
33472
33473
33474
33475
33476 static int peer_hash_cb(const void *obj, const int flags)
33477 {
33478 const struct sip_peer *peer = obj;
33479
33480 return ast_str_case_hash(peer->name);
33481 }
33482
33483
33484
33485
33486 static int peer_cmp_cb(void *obj, void *arg, int flags)
33487 {
33488 struct sip_peer *peer = obj, *peer2 = arg;
33489
33490 return !strcasecmp(peer->name, peer2->name) ? CMP_MATCH | CMP_STOP : 0;
33491 }
33492
33493
33494
33495
33496
33497
33498 static int peer_iphash_cb(const void *obj, const int flags)
33499 {
33500 const struct sip_peer *peer = obj;
33501 int ret = 0;
33502
33503 if (ast_sockaddr_isnull(&peer->addr)) {
33504 ast_log(LOG_ERROR, "Empty address\n");
33505 }
33506
33507 ret = ast_sockaddr_hash(&peer->addr);
33508
33509 if (ret < 0) {
33510 ret = -ret;
33511 }
33512
33513 return ret;
33514 }
33515
33516
33517
33518
33519
33520
33521
33522
33523
33524
33525
33526
33527
33528
33529
33530
33531
33532
33533
33534 static int peer_ipcmp_cb_full(void *obj, void *arg, void *data, int flags)
33535 {
33536 struct sip_peer *peer = obj, *peer2 = arg;
33537 char *callback = data;
33538
33539 if (!ast_strlen_zero(callback) && strcasecmp(peer->callback, callback)) {
33540
33541 return 0;
33542 }
33543
33544
33545
33546 if (ast_sockaddr_cmp_addr(&peer->addr, &peer2->addr)) {
33547
33548 return 0;
33549 }
33550
33551
33552 if ((peer->transports & peer2->transports) & (SIP_TRANSPORT_TLS | SIP_TRANSPORT_TCP)) {
33553
33554 return CMP_MATCH | CMP_STOP;
33555 } else if (ast_test_flag(&peer2->flags[0], SIP_INSECURE_PORT)) {
33556
33557
33558 return ast_test_flag(&peer->flags[0], SIP_INSECURE_PORT) ?
33559 (CMP_MATCH | CMP_STOP) : 0;
33560 }
33561
33562
33563 return ast_sockaddr_port(&peer->addr) == ast_sockaddr_port(&peer2->addr) ?
33564 (CMP_MATCH | CMP_STOP) : 0;
33565 }
33566
33567 static int peer_ipcmp_cb(void *obj, void *arg, int flags)
33568 {
33569 return peer_ipcmp_cb_full(obj, arg, NULL, flags);
33570 }
33571
33572 static int threadt_hash_cb(const void *obj, const int flags)
33573 {
33574 const struct sip_threadinfo *th = obj;
33575
33576 return ast_sockaddr_hash(&th->tcptls_session->remote_address);
33577 }
33578
33579 static int threadt_cmp_cb(void *obj, void *arg, int flags)
33580 {
33581 struct sip_threadinfo *th = obj, *th2 = arg;
33582
33583 return (th->tcptls_session == th2->tcptls_session) ? CMP_MATCH | CMP_STOP : 0;
33584 }
33585
33586
33587
33588
33589 static int dialog_hash_cb(const void *obj, const int flags)
33590 {
33591 const struct sip_pvt *pvt = obj;
33592
33593 return ast_str_case_hash(pvt->callid);
33594 }
33595
33596
33597
33598
33599 static int dialog_find_multiple(void *obj, void *arg, int flags)
33600 {
33601 struct sip_pvt *pvt = obj, *pvt2 = arg;
33602
33603 return !strcasecmp(pvt->callid, pvt2->callid) ? CMP_MATCH : 0;
33604 }
33605
33606
33607
33608
33609 static int dialog_cmp_cb(void *obj, void *arg, int flags)
33610 {
33611 struct sip_pvt *pvt = obj, *pvt2 = arg;
33612
33613 return !strcasecmp(pvt->callid, pvt2->callid) ? CMP_MATCH | CMP_STOP : 0;
33614 }
33615
33616
33617 static struct ast_cli_entry cli_sip[] = {
33618 AST_CLI_DEFINE(sip_show_channels, "List active SIP channels or subscriptions"),
33619 AST_CLI_DEFINE(sip_show_channelstats, "List statistics for active SIP channels"),
33620 AST_CLI_DEFINE(sip_show_domains, "List our local SIP domains"),
33621 AST_CLI_DEFINE(sip_show_inuse, "List all inuse/limits"),
33622 AST_CLI_DEFINE(sip_show_objects, "List all SIP object allocations"),
33623 AST_CLI_DEFINE(sip_show_peers, "List defined SIP peers"),
33624 AST_CLI_DEFINE(sip_show_registry, "List SIP registration status"),
33625 AST_CLI_DEFINE(sip_unregister, "Unregister (force expiration) a SIP peer from the registry"),
33626 AST_CLI_DEFINE(sip_show_settings, "Show SIP global settings"),
33627 AST_CLI_DEFINE(sip_show_mwi, "Show MWI subscriptions"),
33628 AST_CLI_DEFINE(sip_cli_notify, "Send a notify packet to a SIP peer"),
33629 AST_CLI_DEFINE(sip_show_channel, "Show detailed SIP channel info"),
33630 AST_CLI_DEFINE(sip_show_history, "Show SIP dialog history"),
33631 AST_CLI_DEFINE(sip_show_peer, "Show details on specific SIP peer"),
33632 AST_CLI_DEFINE(sip_show_users, "List defined SIP users"),
33633 AST_CLI_DEFINE(sip_show_user, "Show details on specific SIP user"),
33634 AST_CLI_DEFINE(sip_qualify_peer, "Send an OPTIONS packet to a peer"),
33635 AST_CLI_DEFINE(sip_show_sched, "Present a report on the status of the scheduler queue"),
33636 AST_CLI_DEFINE(sip_prune_realtime, "Prune cached Realtime users/peers"),
33637 AST_CLI_DEFINE(sip_do_debug, "Enable/Disable SIP debugging"),
33638 AST_CLI_DEFINE(sip_set_history, "Enable/Disable SIP history"),
33639 AST_CLI_DEFINE(sip_reload, "Reload SIP configuration"),
33640 AST_CLI_DEFINE(sip_show_tcp, "List TCP Connections")
33641 };
33642
33643
33644 static void sip_register_tests(void)
33645 {
33646 sip_config_parser_register_tests();
33647 sip_request_parser_register_tests();
33648 sip_dialplan_function_register_tests();
33649 }
33650
33651
33652 static void sip_unregister_tests(void)
33653 {
33654 sip_config_parser_unregister_tests();
33655 sip_request_parser_unregister_tests();
33656 sip_dialplan_function_unregister_tests();
33657 }
33658
33659 #ifdef TEST_FRAMEWORK
33660 AST_TEST_DEFINE(test_sip_mwi_subscribe_parse)
33661 {
33662 int found = 0;
33663 enum ast_test_result_state res = AST_TEST_PASS;
33664 const char *mwi1 = "1234@mysipprovider.com/1234";
33665 const char *mwi2 = "1234:password@mysipprovider.com/1234";
33666 const char *mwi3 = "1234:password@mysipprovider.com:5061/1234";
33667 const char *mwi4 = "1234:password:authuser@mysipprovider.com/1234";
33668 const char *mwi5 = "1234:password:authuser@mysipprovider.com:5061/1234";
33669 const char *mwi6 = "1234:password";
33670
33671 switch (cmd) {
33672 case TEST_INIT:
33673 info->name = "sip_mwi_subscribe_parse_test";
33674 info->category = "/channels/chan_sip/";
33675 info->summary = "SIP MWI subscribe line parse unit test";
33676 info->description =
33677 "Tests the parsing of mwi subscription lines (e.g., mwi => from sip.conf)";
33678 return AST_TEST_NOT_RUN;
33679 case TEST_EXECUTE:
33680 break;
33681 }
33682
33683 if (sip_subscribe_mwi(mwi1, 1)) {
33684 res = AST_TEST_FAIL;
33685 } else {
33686 found = 0;
33687 res = AST_TEST_FAIL;
33688 ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
33689 ASTOBJ_WRLOCK(iterator);
33690 if (
33691 !strcmp(iterator->hostname, "mysipprovider.com") &&
33692 !strcmp(iterator->username, "1234") &&
33693 !strcmp(iterator->secret, "") &&
33694 !strcmp(iterator->authuser, "") &&
33695 !strcmp(iterator->mailbox, "1234") &&
33696 iterator->portno == 0) {
33697 found = 1;
33698 res = AST_TEST_PASS;
33699 }
33700 ASTOBJ_UNLOCK(iterator);
33701 } while(0));
33702 if (!found) {
33703 ast_test_status_update(test, "sip_subscribe_mwi test 1 failed\n");
33704 }
33705 }
33706
33707 if (sip_subscribe_mwi(mwi2, 1)) {
33708 res = AST_TEST_FAIL;
33709 } else {
33710 found = 0;
33711 res = AST_TEST_FAIL;
33712 ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
33713 ASTOBJ_WRLOCK(iterator);
33714 if (
33715 !strcmp(iterator->hostname, "mysipprovider.com") &&
33716 !strcmp(iterator->username, "1234") &&
33717 !strcmp(iterator->secret, "password") &&
33718 !strcmp(iterator->authuser, "") &&
33719 !strcmp(iterator->mailbox, "1234") &&
33720 iterator->portno == 0) {
33721 found = 1;
33722 res = AST_TEST_PASS;
33723 }
33724 ASTOBJ_UNLOCK(iterator);
33725 } while(0));
33726 if (!found) {
33727 ast_test_status_update(test, "sip_subscribe_mwi test 2 failed\n");
33728 }
33729 }
33730
33731 if (sip_subscribe_mwi(mwi3, 1)) {
33732 res = AST_TEST_FAIL;
33733 } else {
33734 found = 0;
33735 res = AST_TEST_FAIL;
33736 ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
33737 ASTOBJ_WRLOCK(iterator);
33738 if (
33739 !strcmp(iterator->hostname, "mysipprovider.com") &&
33740 !strcmp(iterator->username, "1234") &&
33741 !strcmp(iterator->secret, "password") &&
33742 !strcmp(iterator->authuser, "") &&
33743 !strcmp(iterator->mailbox, "1234") &&
33744 iterator->portno == 5061) {
33745 found = 1;
33746 res = AST_TEST_PASS;
33747 }
33748 ASTOBJ_UNLOCK(iterator);
33749 } while(0));
33750 if (!found) {
33751 ast_test_status_update(test, "sip_subscribe_mwi test 3 failed\n");
33752 }
33753 }
33754
33755 if (sip_subscribe_mwi(mwi4, 1)) {
33756 res = AST_TEST_FAIL;
33757 } else {
33758 found = 0;
33759 res = AST_TEST_FAIL;
33760 ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
33761 ASTOBJ_WRLOCK(iterator);
33762 if (
33763 !strcmp(iterator->hostname, "mysipprovider.com") &&
33764 !strcmp(iterator->username, "1234") &&
33765 !strcmp(iterator->secret, "password") &&
33766 !strcmp(iterator->authuser, "authuser") &&
33767 !strcmp(iterator->mailbox, "1234") &&
33768 iterator->portno == 0) {
33769 found = 1;
33770 res = AST_TEST_PASS;
33771 }
33772 ASTOBJ_UNLOCK(iterator);
33773 } while(0));
33774 if (!found) {
33775 ast_test_status_update(test, "sip_subscribe_mwi test 4 failed\n");
33776 }
33777 }
33778
33779 if (sip_subscribe_mwi(mwi5, 1)) {
33780 res = AST_TEST_FAIL;
33781 } else {
33782 found = 0;
33783 res = AST_TEST_FAIL;
33784 ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
33785 ASTOBJ_WRLOCK(iterator);
33786 if (
33787 !strcmp(iterator->hostname, "mysipprovider.com") &&
33788 !strcmp(iterator->username, "1234") &&
33789 !strcmp(iterator->secret, "password") &&
33790 !strcmp(iterator->authuser, "authuser") &&
33791 !strcmp(iterator->mailbox, "1234") &&
33792 iterator->portno == 5061) {
33793 found = 1;
33794 res = AST_TEST_PASS;
33795 }
33796 ASTOBJ_UNLOCK(iterator);
33797 } while(0));
33798 if (!found) {
33799 ast_test_status_update(test, "sip_subscribe_mwi test 5 failed\n");
33800 }
33801 }
33802
33803 if (sip_subscribe_mwi(mwi6, 1)) {
33804 res = AST_TEST_PASS;
33805 } else {
33806 res = AST_TEST_FAIL;
33807 }
33808 return res;
33809 }
33810
33811 AST_TEST_DEFINE(test_sip_peers_get)
33812 {
33813 struct sip_peer *peer;
33814 struct ast_data *node;
33815 struct ast_data_query query = {
33816 .path = "/asterisk/channel/sip/peers",
33817 .search = "peers/peer/name=test_peer_data_provider"
33818 };
33819
33820 switch (cmd) {
33821 case TEST_INIT:
33822 info->name = "sip_peers_get_data_test";
33823 info->category = "/main/data/sip/peers/";
33824 info->summary = "SIP peers data providers unit test";
33825 info->description =
33826 "Tests whether the SIP peers data provider implementation works as expected.";
33827 return AST_TEST_NOT_RUN;
33828 case TEST_EXECUTE:
33829 break;
33830 }
33831
33832
33833 peer = build_peer("test_peer_data_provider", NULL, NULL, 0, 0);
33834 if (!peer) {
33835 return AST_TEST_FAIL;
33836 }
33837 peer->type = SIP_TYPE_USER;
33838 peer->call_limit = 10;
33839 ao2_link(peers, peer);
33840
33841
33842 node = ast_data_get(&query);
33843 if (!node) {
33844 ao2_unlink(peers, peer);
33845 ao2_ref(peer, -1);
33846 return AST_TEST_FAIL;
33847 }
33848
33849
33850 if (strcmp(ast_data_retrieve_string(node, "peer/name"), "test_peer_data_provider")) {
33851 ao2_unlink(peers, peer);
33852 ao2_ref(peer, -1);
33853 ast_data_free(node);
33854 return AST_TEST_FAIL;
33855 }
33856
33857 if (strcmp(ast_data_retrieve_string(node, "peer/type"), "user")) {
33858 ao2_unlink(peers, peer);
33859 ao2_ref(peer, -1);
33860 ast_data_free(node);
33861 return AST_TEST_FAIL;
33862 }
33863
33864 if (ast_data_retrieve_int(node, "peer/call_limit") != 10) {
33865 ao2_unlink(peers, peer);
33866 ao2_ref(peer, -1);
33867 ast_data_free(node);
33868 return AST_TEST_FAIL;
33869 }
33870
33871
33872 ast_data_free(node);
33873
33874 ao2_unlink(peers, peer);
33875 ao2_ref(peer, -1);
33876
33877 return AST_TEST_PASS;
33878 }
33879
33880
33881
33882
33883
33884
33885
33886
33887
33888
33889
33890
33891
33892
33893
33894
33895
33896
33897
33898 static int mock_tcp_loop(char *fragments[], size_t num_fragments,
33899 struct ast_str **overflow, char **messages, int *num_messages, struct ast_test* test)
33900 {
33901 struct ast_str *req_data;
33902 int i = 0;
33903 int res = 0;
33904
33905 req_data = ast_str_create(128);
33906 ast_str_reset(*overflow);
33907
33908 while (i < num_fragments || ast_str_strlen(*overflow) > 0) {
33909 enum message_integrity message_integrity = MESSAGE_FRAGMENT;
33910 ast_str_reset(req_data);
33911 while (message_integrity == MESSAGE_FRAGMENT) {
33912 if (ast_str_strlen(*overflow) > 0) {
33913 ast_str_append(&req_data, 0, "%s", ast_str_buffer(*overflow));
33914 ast_str_reset(*overflow);
33915 } else {
33916 ast_str_append(&req_data, 0, "%s", fragments[i++]);
33917 }
33918 message_integrity = check_message_integrity(&req_data, overflow);
33919 }
33920 if (strcmp(ast_str_buffer(req_data), messages[*num_messages])) {
33921 ast_test_status_update(test, "Mismatch in SIP messages.\n");
33922 ast_test_status_update(test, "Expected message:\n%s", messages[*num_messages]);
33923 ast_test_status_update(test, "Parsed message:\n%s", ast_str_buffer(req_data));
33924 res = -1;
33925 goto end;
33926 } else {
33927 ast_test_status_update(test, "Successfully read message:\n%s", ast_str_buffer(req_data));
33928 }
33929 (*num_messages)++;
33930 }
33931
33932 end:
33933 ast_free(req_data);
33934 return res;
33935 };
33936
33937 AST_TEST_DEFINE(test_tcp_message_fragmentation)
33938 {
33939
33940 char *normal[] = {
33941 "INVITE sip:bob@example.org SIP/2.0\r\n"
33942 "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
33943 "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
33944 "To: <sip:bob@example.org:5060>\r\n"
33945 "Call-ID: 12345\r\n"
33946 "CSeq: 1 INVITE\r\n"
33947 "Contact: sip:127.0.0.1:5061\r\n"
33948 "Max-Forwards: 70\r\n"
33949 "Content-Type: application/sdp\r\n"
33950 "Content-Length: 130\r\n"
33951 "\r\n"
33952 "v=0\r\n"
33953 "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
33954 "s=-\r\n"
33955 "c=IN IP4 127.0.0.1\r\n"
33956 "t=0 0\r\n"
33957 "m=audio 10000 RTP/AVP 0\r\n"
33958 "a=rtpmap:0 PCMU/8000\r\n"
33959 };
33960
33961
33962
33963
33964 char *fragmented[] = {
33965 "INVITE sip:bob@example.org SIP/2.0\r\n"
33966 "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
33967 "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
33968 "To: <sip:bob@example.org:5060>\r\n"
33969 "Call-ID: 12345\r\n"
33970 "CSeq: 1 INVITE\r\n"
33971 "Contact: sip:127.0.0.1:5061\r\n"
33972 "Max-Forwards: ",
33973
33974 "70\r\n"
33975 "Content-Type: application/sdp\r\n"
33976 "Content-Length: 130\r\n"
33977 "\r\n"
33978 "v=0\r\n"
33979 "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
33980 "s=-\r\n"
33981 "c=IN IP4 127.0.0.1\r\n"
33982 "t=0 0\r\n"
33983 "m=audio 10000 RTP/AVP 0\r\n"
33984 "a=rtpmap:0 PCMU/8000\r\n"
33985 };
33986
33987
33988
33989 char *fragmented_body[] = {
33990 "INVITE sip:bob@example.org SIP/2.0\r\n"
33991 "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
33992 "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
33993 "To: <sip:bob@example.org:5060>\r\n"
33994 "Call-ID: 12345\r\n"
33995 "CSeq: 1 INVITE\r\n"
33996 "Contact: sip:127.0.0.1:5061\r\n"
33997 "Max-Forwards: 70\r\n"
33998 "Content-Type: application/sdp\r\n"
33999 "Content-Length: 130\r\n"
34000 "\r\n",
34001
34002 "v=0\r\n"
34003 "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
34004 "s=-\r\n"
34005 "c=IN IP4 127.0.0.1\r\n"
34006 "t=0 0\r\n"
34007 "m=audio 10000 RTP/AVP 0\r\n"
34008 "a=rtpmap:0 PCMU/8000\r\n"
34009 };
34010
34011
34012
34013
34014 char *multi_fragment[] = {
34015 "INVITE sip:bob@example.org SIP/2.0\r\n"
34016 "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
34017 "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
34018 "To: <sip:bob@example.org:5060>\r\n"
34019 "Call-ID: 12345\r\n"
34020 "CSeq: 1 INVITE\r\n",
34021
34022 "Contact: sip:127.0.0.1:5061\r\n"
34023 "Max-Forwards: 70\r\n"
34024 "Content-Type: application/sdp\r\n"
34025 "Content-Length: 130\r\n"
34026 "\r\n"
34027 "v=0\r\n"
34028 "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
34029 "s=-\r\n"
34030 "c=IN IP4",
34031
34032 " 127.0.0.1\r\n"
34033 "t=0 0\r\n"
34034 "m=audio 10000 RTP/AVP 0\r\n"
34035 "a=rtpmap:0 PCMU/8000\r\n"
34036 };
34037
34038
34039
34040
34041 char *multi_message[] = {
34042 "SIP/2.0 100 Trying\r\n"
34043 "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
34044 "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
34045 "To: <sip:bob@example.org:5060>\r\n"
34046 "Call-ID: 12345\r\n"
34047 "CSeq: 1 INVITE\r\n"
34048 "Contact: <sip:bob@example.org:5060>\r\n"
34049 "Content-Length: 0\r\n"
34050 "\r\n"
34051 "SIP/2.0 180 Ringing\r\n"
34052 "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
34053 "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
34054 "To: <sip:bob@example.org:5060>\r\n"
34055 "Call-ID: 12345\r\n"
34056 "CSeq: 1 INVITE\r\n"
34057 "Contact: <sip:bob@example.org:5060>\r\n"
34058 "Content-Length: 0\r\n"
34059 "\r\n"
34060 };
34061 char *multi_message_divided[] = {
34062 "SIP/2.0 100 Trying\r\n"
34063 "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
34064 "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
34065 "To: <sip:bob@example.org:5060>\r\n"
34066 "Call-ID: 12345\r\n"
34067 "CSeq: 1 INVITE\r\n"
34068 "Contact: <sip:bob@example.org:5060>\r\n"
34069 "Content-Length: 0\r\n"
34070 "\r\n",
34071
34072 "SIP/2.0 180 Ringing\r\n"
34073 "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
34074 "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
34075 "To: <sip:bob@example.org:5060>\r\n"
34076 "Call-ID: 12345\r\n"
34077 "CSeq: 1 INVITE\r\n"
34078 "Contact: <sip:bob@example.org:5060>\r\n"
34079 "Content-Length: 0\r\n"
34080 "\r\n"
34081 };
34082
34083
34084
34085 char *multi_message_body[] = {
34086 "INVITE sip:bob@example.org SIP/2.0\r\n"
34087 "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
34088 "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
34089 "To: <sip:bob@example.org:5060>\r\n"
34090 "Call-ID: 12345\r\n"
34091 "CSeq: 1 INVITE\r\n"
34092 "Contact: sip:127.0.0.1:5061\r\n"
34093 "Max-Forwards: 70\r\n"
34094 "Content-Type: application/sdp\r\n"
34095 "Content-Length: 130\r\n"
34096 "\r\n"
34097 "v=0\r\n"
34098 "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
34099 "s=-\r\n"
34100 "c=IN IP4 127.0.0.1\r\n"
34101 "t=0 0\r\n"
34102 "m=audio 10000 RTP/AVP 0\r\n"
34103 "a=rtpmap:0 PCMU/8000\r\n"
34104 "INVITE sip:bob@example.org SIP/2.0\r\n"
34105 "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
34106 "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
34107 "To: <sip:bob@example.org:5060>\r\n"
34108 "Call-ID: 12345\r\n"
34109 "CSeq: 2 INVITE\r\n"
34110 "Contact: sip:127.0.0.1:5061\r\n"
34111 "Max-Forwards: 70\r\n"
34112 "Content-Type: application/sdp\r\n"
34113 "Content-Length: 130\r\n"
34114 "\r\n"
34115 "v=0\r\n"
34116 "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
34117 "s=-\r\n"
34118 "c=IN IP4 127.0.0.1\r\n"
34119 "t=0 0\r\n"
34120 "m=audio 10000 RTP/AVP 0\r\n"
34121 "a=rtpmap:0 PCMU/8000\r\n"
34122 };
34123 char *multi_message_body_divided[] = {
34124 "INVITE sip:bob@example.org SIP/2.0\r\n"
34125 "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
34126 "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
34127 "To: <sip:bob@example.org:5060>\r\n"
34128 "Call-ID: 12345\r\n"
34129 "CSeq: 1 INVITE\r\n"
34130 "Contact: sip:127.0.0.1:5061\r\n"
34131 "Max-Forwards: 70\r\n"
34132 "Content-Type: application/sdp\r\n"
34133 "Content-Length: 130\r\n"
34134 "\r\n"
34135 "v=0\r\n"
34136 "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
34137 "s=-\r\n"
34138 "c=IN IP4 127.0.0.1\r\n"
34139 "t=0 0\r\n"
34140 "m=audio 10000 RTP/AVP 0\r\n"
34141 "a=rtpmap:0 PCMU/8000\r\n",
34142
34143 "INVITE sip:bob@example.org SIP/2.0\r\n"
34144 "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
34145 "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
34146 "To: <sip:bob@example.org:5060>\r\n"
34147 "Call-ID: 12345\r\n"
34148 "CSeq: 2 INVITE\r\n"
34149 "Contact: sip:127.0.0.1:5061\r\n"
34150 "Max-Forwards: 70\r\n"
34151 "Content-Type: application/sdp\r\n"
34152 "Content-Length: 130\r\n"
34153 "\r\n"
34154 "v=0\r\n"
34155 "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
34156 "s=-\r\n"
34157 "c=IN IP4 127.0.0.1\r\n"
34158 "t=0 0\r\n"
34159 "m=audio 10000 RTP/AVP 0\r\n"
34160 "a=rtpmap:0 PCMU/8000\r\n"
34161 };
34162
34163
34164
34165
34166
34167 char *multi_message_in_fragments[] = {
34168 "SIP/2.0 100 Trying\r\n"
34169 "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
34170 "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
34171 "To: <sip:bob@example.org:5060>\r\n"
34172 "Call-ID: 12345\r\n"
34173 "CSeq: 1 INVI",
34174
34175 "TE\r\n"
34176 "Contact: <sip:bob@example.org:5060>\r\n"
34177 "Content-Length: 0\r\n"
34178 "\r\n"
34179 "SIP/2.0 180 Ringing\r\n"
34180 "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
34181 "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
34182 "To: <sip:bob@example.org:5060>\r\n"
34183 "Call-ID: 12345\r\n"
34184 "CSeq: 1 INVITE\r\n"
34185 "Contact: <sip:bob@example.org:5060>\r\n"
34186 "Content-Length: 0\r\n"
34187 "\r\n"
34188 };
34189
34190
34191
34192
34193 char *compact[] = {
34194 "INVITE sip:bob@example.org SIP/2.0\r\n"
34195 "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
34196 "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
34197 "To: <sip:bob@example.org:5060>\r\n"
34198 "Call-ID: 12345\r\n"
34199 "CSeq: 1 INVITE\r\n"
34200 "Contact: sip:127.0.0.1:5061\r\n"
34201 "Max-Forwards: 70\r\n"
34202 "Content-Type: application/sdp\r\n"
34203 "l:130\r\n"
34204 "\r\n"
34205 "v=0\r\n"
34206 "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
34207 "s=-\r\n"
34208 "c=IN IP4 127.0.0.1\r\n"
34209 "t=0 0\r\n"
34210 "m=audio 10000 RTP/AVP 0\r\n"
34211 "a=rtpmap:0 PCMU/8000\r\n"
34212 };
34213
34214
34215
34216
34217 char *faux[] = {
34218 "INVITE sip:bob@example.org SIP/2.0\r\n"
34219 "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
34220 "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
34221 "To: <sip:bob@example.org:5060>\r\n"
34222 "Call-ID: 12345\r\n"
34223 "CSeq: 1 INVITE\r\n"
34224 "Contact: sip:127.0.0.1:5061\r\n"
34225 "Max-Forwards: 70\r\n"
34226 "Content-Type: application/sdp\r\n"
34227 "DisContent-Length: 0\r\n"
34228 "MalContent-Length: 60\r\n"
34229 "Content-Length:130\r\n"
34230 "\r\n"
34231 "v=0\r\n"
34232 "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
34233 "s=-\r\n"
34234 "c=IN IP4 127.0.0.1\r\n"
34235 "t=0 0\r\n"
34236 "m=audio 10000 RTP/AVP 0\r\n"
34237 "a=rtpmap:0 PCMU/8000\r\n"
34238 };
34239
34240
34241
34242
34243
34244
34245 char *folded[] = {
34246 "INVITE sip:bob@example.org SIP/2.0\r\n"
34247 "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
34248 "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
34249 "To: <sip:bob@example.org:5060>\r\n"
34250 "Call-ID: 12345\r\n"
34251 "CSeq: 1 INVITE\r\n"
34252 "Contact: sip:127.0.0.1:5061\r\n"
34253 "Max-Forwards: 70\r\n"
34254 "Content-Type: application/sdp\r\n"
34255 "Content-Length: \t\r\n"
34256 "\t \r\n"
34257 " 130\t \r\n"
34258 "\r\n"
34259 "v=0\r\n"
34260 "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
34261 "s=-\r\n"
34262 "c=IN IP4 127.0.0.1\r\n"
34263 "t=0 0\r\n"
34264 "m=audio 10000 RTP/AVP 0\r\n"
34265 "a=rtpmap:0 PCMU/8000\r\n"
34266 };
34267
34268
34269
34270
34271
34272 char *cl_in_body[] = {
34273 "INVITE sip:bob@example.org SIP/2.0\r\n"
34274 "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
34275 "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
34276 "To: <sip:bob@example.org:5060>\r\n"
34277 "Call-ID: 12345\r\n"
34278 "CSeq: 1 INVITE\r\n"
34279 "Contact: sip:127.0.0.1:5061\r\n"
34280 "Max-Forwards: 70\r\n"
34281 "Content-Type: application/sdp\r\n"
34282 "l: 149\r\n"
34283 "\r\n"
34284 "v=0\r\n"
34285 "Content-Length: 0\r\n"
34286 "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
34287 "s=-\r\n"
34288 "c=IN IP4 127.0.0.1\r\n"
34289 "t=0 0\r\n"
34290 "m=audio 10000 RTP/AVP 0\r\n"
34291 "a=rtpmap:0 PCMU/8000\r\n"
34292 };
34293
34294 struct ast_str *overflow;
34295 struct {
34296 char **fragments;
34297 char **expected;
34298 int num_expected;
34299 const char *description;
34300 } tests[] = {
34301 { normal, normal, 1, "normal" },
34302 { fragmented, normal, 1, "fragmented" },
34303 { fragmented_body, normal, 1, "fragmented_body" },
34304 { multi_fragment, normal, 1, "multi_fragment" },
34305 { multi_message, multi_message_divided, 2, "multi_message" },
34306 { multi_message_body, multi_message_body_divided, 2, "multi_message_body" },
34307 { multi_message_in_fragments, multi_message_divided, 2, "multi_message_in_fragments" },
34308 { compact, compact, 1, "compact" },
34309 { faux, faux, 1, "faux" },
34310 { folded, folded, 1, "folded" },
34311 { cl_in_body, cl_in_body, 1, "cl_in_body" },
34312 };
34313 int i;
34314 enum ast_test_result_state res = AST_TEST_PASS;
34315
34316 switch (cmd) {
34317 case TEST_INIT:
34318 info->name = "sip_tcp_message_fragmentation";
34319 info->category = "/main/sip/transport/";
34320 info->summary = "SIP TCP message fragmentation test";
34321 info->description =
34322 "Tests reception of different TCP messages that have been fragmented or"
34323 "run together. This test mimicks the code that TCP reception uses.";
34324 return AST_TEST_NOT_RUN;
34325 case TEST_EXECUTE:
34326 break;
34327 }
34328 if (!sip_cfg.pedanticsipchecking) {
34329 ast_log(LOG_WARNING, "Not running test. Pedantic SIP checking is not enabled, so it is guaranteed to fail\n");
34330 return AST_TEST_NOT_RUN;
34331 }
34332
34333 overflow = ast_str_create(128);
34334 if (!overflow) {
34335 return AST_TEST_FAIL;
34336 }
34337 for (i = 0; i < ARRAY_LEN(tests); ++i) {
34338 int num_messages = 0;
34339 if (mock_tcp_loop(tests[i].fragments, ARRAY_LEN(tests[i].fragments),
34340 &overflow, tests[i].expected, &num_messages, test)) {
34341 ast_test_status_update(test, "Failed to parse message '%s'\n", tests[i].description);
34342 res = AST_TEST_FAIL;
34343 break;
34344 }
34345 if (num_messages != tests[i].num_expected) {
34346 ast_test_status_update(test, "Did not receive the expected number of messages. "
34347 "Expected %d but received %d\n", tests[i].num_expected, num_messages);
34348 res = AST_TEST_FAIL;
34349 break;
34350 }
34351 }
34352 ast_free(overflow);
34353 return res;
34354 }
34355
34356 AST_TEST_DEFINE(get_in_brackets_const_test)
34357 {
34358 const char *input;
34359 const char *start = NULL;
34360 int len = 0;
34361 int res;
34362
34363 #define CHECK_RESULTS(in, expected_res, expected_start, expected_len) do { \
34364 input = (in); \
34365 res = get_in_brackets_const(input, &start, &len); \
34366 if ((expected_res) != res) { \
34367 ast_test_status_update(test, "Unexpected result: %d != %d\n", expected_res, res); \
34368 return AST_TEST_FAIL; \
34369 } \
34370 if ((expected_start) != start) { \
34371 const char *e = expected_start ? expected_start : "(null)"; \
34372 const char *a = start ? start : "(null)"; \
34373 ast_test_status_update(test, "Unexpected start: %s != %s\n", e, a); \
34374 return AST_TEST_FAIL; \
34375 } \
34376 if ((expected_len) != len) { \
34377 ast_test_status_update(test, "Unexpected len: %d != %d\n", expected_len, len); \
34378 return AST_TEST_FAIL; \
34379 } \
34380 } while(0)
34381
34382 switch (cmd) {
34383 case TEST_INIT:
34384 info->name = __func__;
34385 info->category = "/channels/chan_sip/";
34386 info->summary = "get_in_brackets_const test";
34387 info->description =
34388 "Tests the get_in_brackets_const function";
34389 return AST_TEST_NOT_RUN;
34390 case TEST_EXECUTE:
34391 break;
34392 }
34393
34394 CHECK_RESULTS("", 1, NULL, -1);
34395 CHECK_RESULTS("normal <test>", 0, input + 8, 4);
34396 CHECK_RESULTS("\"normal\" <test>", 0, input + 10, 4);
34397 CHECK_RESULTS("not normal <test", -1, NULL, -1);
34398 CHECK_RESULTS("\"yes < really\" <test>", 0, input + 16, 4);
34399 CHECK_RESULTS("\"even > this\" <test>", 0, input + 15, 4);
34400 CHECK_RESULTS("<sip:id1@10.10.10.10;lr>", 0, input + 1, 22);
34401 CHECK_RESULTS("<sip:id1@10.10.10.10;lr>, <sip:id1@10.10.10.20;lr>", 0, input + 1, 22);
34402 CHECK_RESULTS("<sip:id1,id2@10.10.10.10;lr>", 0, input + 1, 26);
34403 CHECK_RESULTS("<sip:id1@10., <sip:id2@10.10.10.10;lr>", 0, input + 1, 36);
34404 CHECK_RESULTS("\"quoted text\" <sip:dlg1@10.10.10.10;lr>", 0, input + 15, 23);
34405
34406 return AST_TEST_PASS;
34407 }
34408
34409 #endif
34410
34411 #define DATA_EXPORT_SIP_PEER(MEMBER) \
34412 MEMBER(sip_peer, name, AST_DATA_STRING) \
34413 MEMBER(sip_peer, secret, AST_DATA_PASSWORD) \
34414 MEMBER(sip_peer, md5secret, AST_DATA_PASSWORD) \
34415 MEMBER(sip_peer, remotesecret, AST_DATA_PASSWORD) \
34416 MEMBER(sip_peer, context, AST_DATA_STRING) \
34417 MEMBER(sip_peer, subscribecontext, AST_DATA_STRING) \
34418 MEMBER(sip_peer, username, AST_DATA_STRING) \
34419 MEMBER(sip_peer, accountcode, AST_DATA_STRING) \
34420 MEMBER(sip_peer, tohost, AST_DATA_STRING) \
34421 MEMBER(sip_peer, regexten, AST_DATA_STRING) \
34422 MEMBER(sip_peer, fromuser, AST_DATA_STRING) \
34423 MEMBER(sip_peer, fromdomain, AST_DATA_STRING) \
34424 MEMBER(sip_peer, fullcontact, AST_DATA_STRING) \
34425 MEMBER(sip_peer, cid_num, AST_DATA_STRING) \
34426 MEMBER(sip_peer, cid_name, AST_DATA_STRING) \
34427 MEMBER(sip_peer, vmexten, AST_DATA_STRING) \
34428 MEMBER(sip_peer, language, AST_DATA_STRING) \
34429 MEMBER(sip_peer, mohinterpret, AST_DATA_STRING) \
34430 MEMBER(sip_peer, mohsuggest, AST_DATA_STRING) \
34431 MEMBER(sip_peer, parkinglot, AST_DATA_STRING) \
34432 MEMBER(sip_peer, useragent, AST_DATA_STRING) \
34433 MEMBER(sip_peer, mwi_from, AST_DATA_STRING) \
34434 MEMBER(sip_peer, engine, AST_DATA_STRING) \
34435 MEMBER(sip_peer, unsolicited_mailbox, AST_DATA_STRING) \
34436 MEMBER(sip_peer, is_realtime, AST_DATA_BOOLEAN) \
34437 MEMBER(sip_peer, host_dynamic, AST_DATA_BOOLEAN) \
34438 MEMBER(sip_peer, autoframing, AST_DATA_BOOLEAN) \
34439 MEMBER(sip_peer, inuse, AST_DATA_INTEGER) \
34440 MEMBER(sip_peer, ringing, AST_DATA_INTEGER) \
34441 MEMBER(sip_peer, onhold, AST_DATA_INTEGER) \
34442 MEMBER(sip_peer, call_limit, AST_DATA_INTEGER) \
34443 MEMBER(sip_peer, t38_maxdatagram, AST_DATA_INTEGER) \
34444 MEMBER(sip_peer, maxcallbitrate, AST_DATA_INTEGER) \
34445 MEMBER(sip_peer, rtptimeout, AST_DATA_SECONDS) \
34446 MEMBER(sip_peer, rtpholdtimeout, AST_DATA_SECONDS) \
34447 MEMBER(sip_peer, rtpkeepalive, AST_DATA_SECONDS) \
34448 MEMBER(sip_peer, lastms, AST_DATA_MILLISECONDS) \
34449 MEMBER(sip_peer, maxms, AST_DATA_MILLISECONDS) \
34450 MEMBER(sip_peer, qualifyfreq, AST_DATA_MILLISECONDS) \
34451 MEMBER(sip_peer, timer_t1, AST_DATA_MILLISECONDS) \
34452 MEMBER(sip_peer, timer_b, AST_DATA_MILLISECONDS) \
34453 MEMBER(sip_peer, description, AST_DATA_STRING)
34454
34455 AST_DATA_STRUCTURE(sip_peer, DATA_EXPORT_SIP_PEER);
34456
34457 static int peers_data_provider_get(const struct ast_data_search *search,
34458 struct ast_data *data_root)
34459 {
34460 struct sip_peer *peer;
34461 struct ao2_iterator i;
34462 struct ast_data *data_peer, *data_peer_mailboxes = NULL, *data_peer_mailbox, *enum_node;
34463 struct ast_data *data_sip_options;
34464 int total_mailboxes, x;
34465 struct sip_mailbox *mailbox;
34466
34467 i = ao2_iterator_init(peers, 0);
34468 while ((peer = ao2_iterator_next(&i))) {
34469 ao2_lock(peer);
34470
34471 data_peer = ast_data_add_node(data_root, "peer");
34472 if (!data_peer) {
34473 ao2_unlock(peer);
34474 ao2_ref(peer, -1);
34475 continue;
34476 }
34477
34478 ast_data_add_structure(sip_peer, data_peer, peer);
34479
34480
34481 enum_node = ast_data_add_node(data_peer, "allowtransfer");
34482 if (!enum_node) {
34483 ao2_unlock(peer);
34484 ao2_ref(peer, -1);
34485 continue;
34486 }
34487 ast_data_add_str(enum_node, "text", transfermode2str(peer->allowtransfer));
34488 ast_data_add_int(enum_node, "value", peer->allowtransfer);
34489
34490
34491 ast_data_add_str(data_peer, "transports", get_transport_list(peer->transports));
34492
34493
34494 if ((peer->type & SIP_TYPE_USER) && (peer->type & SIP_TYPE_PEER)) {
34495 ast_data_add_str(data_peer, "type", "friend");
34496 } else if (peer->type & SIP_TYPE_PEER) {
34497 ast_data_add_str(data_peer, "type", "peer");
34498 } else if (peer->type & SIP_TYPE_USER) {
34499 ast_data_add_str(data_peer, "type", "user");
34500 }
34501
34502
34503 total_mailboxes = 0;
34504 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
34505 if (!total_mailboxes) {
34506 data_peer_mailboxes = ast_data_add_node(data_peer, "mailboxes");
34507 if (!data_peer_mailboxes) {
34508 break;
34509 }
34510 total_mailboxes++;
34511 }
34512
34513 data_peer_mailbox = ast_data_add_node(data_peer_mailboxes, "mailbox");
34514 if (!data_peer_mailbox) {
34515 continue;
34516 }
34517 ast_data_add_str(data_peer_mailbox, "mailbox", mailbox->mailbox);
34518 ast_data_add_str(data_peer_mailbox, "context", mailbox->context);
34519 }
34520
34521
34522 enum_node = ast_data_add_node(data_peer, "amaflags");
34523 if (!enum_node) {
34524 ao2_unlock(peer);
34525 ao2_ref(peer, -1);
34526 continue;
34527 }
34528 ast_data_add_int(enum_node, "value", peer->amaflags);
34529 ast_data_add_str(enum_node, "text", ast_cdr_flags2str(peer->amaflags));
34530
34531
34532 data_sip_options = ast_data_add_node(data_peer, "sipoptions");
34533 if (!data_sip_options) {
34534 ao2_unlock(peer);
34535 ao2_ref(peer, -1);
34536 continue;
34537 }
34538 for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
34539 ast_data_add_bool(data_sip_options, sip_options[x].text, peer->sipoptions & sip_options[x].id);
34540 }
34541
34542
34543 enum_node = ast_data_add_node(data_peer, "callingpres");
34544 if (!enum_node) {
34545 ao2_unlock(peer);
34546 ao2_ref(peer, -1);
34547 continue;
34548 }
34549 ast_data_add_int(enum_node, "value", peer->callingpres);
34550 ast_data_add_str(enum_node, "text", ast_describe_caller_presentation(peer->callingpres));
34551
34552
34553 ast_data_add_codecs(data_peer, "codecs", peer->caps);
34554
34555 if (!ast_data_search_match(search, data_peer)) {
34556 ast_data_remove_node(data_root, data_peer);
34557 }
34558
34559 ao2_unlock(peer);
34560 ao2_ref(peer, -1);
34561 }
34562 ao2_iterator_destroy(&i);
34563
34564 return 0;
34565 }
34566
34567 static const struct ast_data_handler peers_data_provider = {
34568 .version = AST_DATA_HANDLER_VERSION,
34569 .get = peers_data_provider_get
34570 };
34571
34572 static const struct ast_data_entry sip_data_providers[] = {
34573 AST_DATA_ENTRY("asterisk/channel/sip/peers", &peers_data_provider),
34574 };
34575
34576 static const struct ast_sip_api_tech chan_sip_api_provider = {
34577 .version = AST_SIP_API_VERSION,
34578 .name = "chan_sip",
34579 .sipinfo_send = sipinfo_send,
34580 };
34581
34582
34583 static int load_module(void)
34584 {
34585 ast_verbose("SIP channel loading...\n");
34586
34587 if (!(sip_tech.capabilities = ast_format_cap_alloc())) {
34588 return AST_MODULE_LOAD_FAILURE;
34589 }
34590
34591 if (ast_sip_api_provider_register(&chan_sip_api_provider)) {
34592 return AST_MODULE_LOAD_FAILURE;
34593 }
34594
34595
34596
34597 peers = ao2_t_container_alloc(HASH_PEER_SIZE, peer_hash_cb, peer_cmp_cb, "allocate peers");
34598 peers_by_ip = ao2_t_container_alloc(HASH_PEER_SIZE, peer_iphash_cb, peer_ipcmp_cb, "allocate peers_by_ip");
34599 dialogs = ao2_t_container_alloc(HASH_DIALOG_SIZE, dialog_hash_cb, dialog_cmp_cb, "allocate dialogs");
34600 dialogs_needdestroy = ao2_t_container_alloc(1, NULL, NULL, "allocate dialogs_needdestroy");
34601 dialogs_rtpcheck = ao2_t_container_alloc(HASH_DIALOG_SIZE, dialog_hash_cb, dialog_cmp_cb, "allocate dialogs for rtpchecks");
34602 threadt = ao2_t_container_alloc(HASH_DIALOG_SIZE, threadt_hash_cb, threadt_cmp_cb, "allocate threadt table");
34603 if (!peers || !peers_by_ip || !dialogs || !dialogs_needdestroy || !dialogs_rtpcheck
34604 || !threadt) {
34605 ast_log(LOG_ERROR, "Unable to create primary SIP container(s)\n");
34606 return AST_MODULE_LOAD_FAILURE;
34607 }
34608
34609 if (!(sip_cfg.caps = ast_format_cap_alloc())) {
34610 return AST_MODULE_LOAD_FAILURE;
34611 }
34612 ast_format_cap_add_all_by_type(sip_tech.capabilities, AST_FORMAT_TYPE_AUDIO);
34613
34614 ASTOBJ_CONTAINER_INIT(®l);
34615 ASTOBJ_CONTAINER_INIT(&submwil);
34616
34617 if (!(sched = ast_sched_context_create())) {
34618 ast_log(LOG_ERROR, "Unable to create scheduler context\n");
34619 return AST_MODULE_LOAD_FAILURE;
34620 }
34621
34622 if (!(io = io_context_create())) {
34623 ast_log(LOG_ERROR, "Unable to create I/O context\n");
34624 return AST_MODULE_LOAD_FAILURE;
34625 }
34626
34627 sip_reloadreason = CHANNEL_MODULE_LOAD;
34628
34629 can_parse_xml = sip_is_xml_parsable();
34630 if (reload_config(sip_reloadreason)) {
34631 ast_sip_api_provider_unregister();
34632 return AST_MODULE_LOAD_DECLINE;
34633 }
34634
34635
34636 if (!(bogus_peer = temp_peer("(bogus_peer)"))) {
34637 ast_log(LOG_ERROR, "Unable to create bogus_peer for authentication\n");
34638 io_context_destroy(io);
34639 ast_sched_context_destroy(sched);
34640 return AST_MODULE_LOAD_FAILURE;
34641 }
34642
34643 ast_string_field_set(bogus_peer, md5secret, BOGUS_PEER_MD5SECRET);
34644 ast_clear_flag(&bogus_peer->flags[0], SIP_INSECURE);
34645
34646
34647
34648
34649
34650 memcpy(&sip_tech_info, &sip_tech, sizeof(sip_tech));
34651 memset((void *) &sip_tech_info.send_digit_begin, 0, sizeof(sip_tech_info.send_digit_begin));
34652
34653 if (ast_msg_tech_register(&sip_msg_tech)) {
34654
34655 return AST_MODULE_LOAD_FAILURE;
34656 }
34657
34658
34659 if (ast_channel_register(&sip_tech)) {
34660 ast_log(LOG_ERROR, "Unable to register channel type 'SIP'\n");
34661 ao2_t_ref(bogus_peer, -1, "unref the bogus_peer");
34662 io_context_destroy(io);
34663 ast_sched_context_destroy(sched);
34664 return AST_MODULE_LOAD_FAILURE;
34665 }
34666
34667 #ifdef TEST_FRAMEWORK
34668 AST_TEST_REGISTER(test_sip_peers_get);
34669 AST_TEST_REGISTER(test_sip_mwi_subscribe_parse);
34670 AST_TEST_REGISTER(test_tcp_message_fragmentation);
34671 AST_TEST_REGISTER(get_in_brackets_const_test);
34672 #endif
34673
34674
34675 ast_data_register_multiple(sip_data_providers, ARRAY_LEN(sip_data_providers));
34676
34677
34678 ast_cli_register_multiple(cli_sip, ARRAY_LEN(cli_sip));
34679
34680
34681 ast_udptl_proto_register(&sip_udptl);
34682
34683
34684 ast_rtp_glue_register(&sip_rtp_glue);
34685
34686
34687 ast_register_application_xml(app_dtmfmode, sip_dtmfmode);
34688 ast_register_application_xml(app_sipaddheader, sip_addheader);
34689 ast_register_application_xml(app_sipremoveheader, sip_removeheader);
34690 #ifdef TEST_FRAMEWORK
34691 ast_register_application_xml(app_sipsendcustominfo, sip_sendcustominfo);
34692 #endif
34693
34694
34695 ast_custom_function_register(&sip_header_function);
34696 ast_custom_function_register(&sippeer_function);
34697 ast_custom_function_register(&sipchaninfo_function);
34698 ast_custom_function_register(&checksipdomain_function);
34699
34700
34701 ast_manager_register_xml("SIPpeers", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peers);
34702 ast_manager_register_xml("SIPshowpeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peer);
34703 ast_manager_register_xml("SIPqualifypeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_qualify_peer);
34704 ast_manager_register_xml("SIPshowregistry", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_show_registry);
34705 ast_manager_register_xml("SIPnotify", EVENT_FLAG_SYSTEM, manager_sipnotify);
34706 ast_manager_register_xml("SIPpeerstatus", EVENT_FLAG_SYSTEM, manager_sip_peer_status);
34707 sip_poke_all_peers();
34708 sip_keepalive_all_peers();
34709 sip_send_all_registers();
34710 sip_send_all_mwi_subscriptions();
34711 initialize_escs();
34712
34713 if (sip_epa_register(&cc_epa_static_data)) {
34714 ast_sip_api_provider_unregister();
34715 return AST_MODULE_LOAD_DECLINE;
34716 }
34717
34718 if (sip_reqresp_parser_init() == -1) {
34719 ast_log(LOG_ERROR, "Unable to initialize the SIP request and response parser\n");
34720 ast_sip_api_provider_unregister();
34721 return AST_MODULE_LOAD_DECLINE;
34722 }
34723
34724 if (can_parse_xml) {
34725
34726
34727
34728 if (ast_cc_agent_register(&sip_cc_agent_callbacks)) {
34729 ast_sip_api_provider_unregister();
34730 return AST_MODULE_LOAD_DECLINE;
34731 }
34732 }
34733 if (ast_cc_monitor_register(&sip_cc_monitor_callbacks)) {
34734 ast_sip_api_provider_unregister();
34735 return AST_MODULE_LOAD_DECLINE;
34736 }
34737 if (!(sip_monitor_instances = ao2_container_alloc(37, sip_monitor_instance_hash_fn, sip_monitor_instance_cmp_fn))) {
34738 ast_sip_api_provider_unregister();
34739 return AST_MODULE_LOAD_DECLINE;
34740 }
34741
34742
34743 restart_monitor();
34744
34745 ast_realtime_require_field(ast_check_realtime("sipregs") ? "sipregs" : "sippeers",
34746 "name", RQ_CHAR, 10,
34747 "ipaddr", RQ_CHAR, INET6_ADDRSTRLEN - 1,
34748 "port", RQ_UINTEGER2, 5,
34749 "regseconds", RQ_INTEGER4, 11,
34750 "defaultuser", RQ_CHAR, 10,
34751 "fullcontact", RQ_CHAR, 35,
34752 "regserver", RQ_CHAR, 20,
34753 "useragent", RQ_CHAR, 20,
34754 "lastms", RQ_INTEGER4, 11,
34755 SENTINEL);
34756
34757
34758 sip_register_tests();
34759 network_change_event_subscribe();
34760
34761 ast_websocket_add_protocol("sip", sip_websocket_callback);
34762
34763 return AST_MODULE_LOAD_SUCCESS;
34764 }
34765
34766
34767 static int unload_module(void)
34768 {
34769 struct sip_pvt *p;
34770 struct sip_threadinfo *th;
34771 struct ast_context *con;
34772 struct ao2_iterator i;
34773 int wait_count;
34774
34775 ast_sip_api_provider_unregister();
34776
34777 ast_websocket_remove_protocol("sip", sip_websocket_callback);
34778
34779 network_change_event_unsubscribe();
34780 acl_change_event_unsubscribe();
34781
34782 ast_sched_dump(sched);
34783
34784
34785 ast_channel_unregister(&sip_tech);
34786
34787 ast_msg_tech_unregister(&sip_msg_tech);
34788
34789
34790 ast_custom_function_unregister(&sipchaninfo_function);
34791 ast_custom_function_unregister(&sippeer_function);
34792 ast_custom_function_unregister(&sip_header_function);
34793 ast_custom_function_unregister(&checksipdomain_function);
34794
34795
34796 ast_unregister_application(app_dtmfmode);
34797 ast_unregister_application(app_sipaddheader);
34798 ast_unregister_application(app_sipremoveheader);
34799 #ifdef TEST_FRAMEWORK
34800 ast_unregister_application(app_sipsendcustominfo);
34801
34802 AST_TEST_UNREGISTER(test_sip_peers_get);
34803 AST_TEST_UNREGISTER(test_sip_mwi_subscribe_parse);
34804 AST_TEST_UNREGISTER(test_tcp_message_fragmentation);
34805 AST_TEST_UNREGISTER(get_in_brackets_const_test);
34806 #endif
34807
34808 ast_data_unregister(NULL);
34809
34810
34811 ast_cli_unregister_multiple(cli_sip, ARRAY_LEN(cli_sip));
34812
34813
34814 ast_udptl_proto_unregister(&sip_udptl);
34815
34816
34817 ast_rtp_glue_unregister(&sip_rtp_glue);
34818
34819
34820 ast_manager_unregister("SIPpeers");
34821 ast_manager_unregister("SIPshowpeer");
34822 ast_manager_unregister("SIPqualifypeer");
34823 ast_manager_unregister("SIPshowregistry");
34824 ast_manager_unregister("SIPnotify");
34825 ast_manager_unregister("SIPpeerstatus");
34826
34827
34828 if (sip_tcp_desc.master) {
34829 ast_tcptls_server_stop(&sip_tcp_desc);
34830 }
34831 if (sip_tls_desc.master) {
34832 ast_tcptls_server_stop(&sip_tls_desc);
34833 }
34834 ast_ssl_teardown(sip_tls_desc.tls_cfg);
34835
34836
34837 i = ao2_iterator_init(threadt, 0);
34838 while ((th = ao2_t_iterator_next(&i, "iterate through tcp threads for 'sip show tcp'"))) {
34839 pthread_t thread = th->threadid;
34840 th->stop = 1;
34841 pthread_kill(thread, SIGURG);
34842 ao2_t_ref(th, -1, "decrement ref from iterator");
34843 }
34844 ao2_iterator_destroy(&i);
34845
34846
34847 i = ao2_iterator_init(dialogs, 0);
34848 while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
34849 if (p->owner)
34850 ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
34851 ao2_t_ref(p, -1, "toss dialog ptr from iterator_next");
34852 }
34853 ao2_iterator_destroy(&i);
34854
34855 unlink_all_peers_from_tables();
34856
34857 ast_mutex_lock(&monlock);
34858 if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP) && (monitor_thread != AST_PTHREADT_NULL)) {
34859 pthread_t th = monitor_thread;
34860 monitor_thread = AST_PTHREADT_STOP;
34861 pthread_cancel(th);
34862 pthread_kill(th, SIGURG);
34863 ast_mutex_unlock(&monlock);
34864 pthread_join(th, NULL);
34865 } else {
34866 monitor_thread = AST_PTHREADT_STOP;
34867 ast_mutex_unlock(&monlock);
34868 }
34869
34870
34871 i = ao2_iterator_init(dialogs, 0);
34872 while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
34873 dialog_unlink_all(p);
34874 ao2_t_ref(p, -1, "throw away iterator result");
34875 }
34876 ao2_iterator_destroy(&i);
34877
34878
34879 ast_free_ha(localaddr);
34880
34881 ast_mutex_lock(&authl_lock);
34882 if (authl) {
34883 ao2_t_ref(authl, -1, "Removing global authentication");
34884 authl = NULL;
34885 }
34886 ast_mutex_unlock(&authl_lock);
34887
34888 sip_epa_unregister_all();
34889 destroy_escs();
34890
34891 ast_free(default_tls_cfg.certfile);
34892 ast_free(default_tls_cfg.pvtfile);
34893 ast_free(default_tls_cfg.cipher);
34894 ast_free(default_tls_cfg.cafile);
34895 ast_free(default_tls_cfg.capath);
34896
34897 cleanup_all_regs();
34898 ASTOBJ_CONTAINER_DESTROYALL(®l, sip_registry_destroy);
34899 ASTOBJ_CONTAINER_DESTROY(®l);
34900
34901 ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
34902 ASTOBJ_WRLOCK(iterator);
34903 if (iterator->dnsmgr) {
34904 ast_dnsmgr_release(iterator->dnsmgr);
34905 iterator->dnsmgr = NULL;
34906 ASTOBJ_UNREF(iterator, sip_subscribe_mwi_destroy);
34907 }
34908 ASTOBJ_UNLOCK(iterator);
34909 } while(0));
34910 ASTOBJ_CONTAINER_DESTROYALL(&submwil, sip_subscribe_mwi_destroy);
34911 ASTOBJ_CONTAINER_DESTROY(&submwil);
34912
34913
34914
34915
34916
34917
34918
34919
34920 wait_count = 1000;
34921 while (ao2_container_count(threadt) && --wait_count) {
34922 sched_yield();
34923 }
34924 if (!wait_count) {
34925 ast_debug(2, "TCP/TLS thread container did not become empty :(\n");
34926 }
34927
34928 ao2_t_ref(bogus_peer, -1, "unref the bogus_peer");
34929
34930 ao2_t_ref(peers, -1, "unref the peers table");
34931 ao2_t_ref(peers_by_ip, -1, "unref the peers_by_ip table");
34932 ao2_t_ref(dialogs, -1, "unref the dialogs table");
34933 ao2_t_ref(dialogs_needdestroy, -1, "unref dialogs_needdestroy");
34934 ao2_t_ref(dialogs_rtpcheck, -1, "unref dialogs_rtpcheck");
34935 ao2_t_ref(threadt, -1, "unref the thread table");
34936 ao2_t_ref(sip_monitor_instances, -1, "unref the sip_monitor_instances table");
34937
34938 clear_sip_domains();
34939 sip_cfg.contact_acl = ast_free_acl_list(sip_cfg.contact_acl);
34940 if (sipsock_read_id) {
34941 ast_io_remove(io, sipsock_read_id);
34942 sipsock_read_id = NULL;
34943 }
34944 close(sipsock);
34945 io_context_destroy(io);
34946 ast_sched_context_destroy(sched);
34947 con = ast_context_find(used_context);
34948 if (con) {
34949 ast_context_destroy(con, "SIP");
34950 }
34951 ast_unload_realtime("sipregs");
34952 ast_unload_realtime("sippeers");
34953 ast_cc_monitor_unregister(&sip_cc_monitor_callbacks);
34954 ast_cc_agent_unregister(&sip_cc_agent_callbacks);
34955
34956 sip_reqresp_parser_exit();
34957 sip_unregister_tests();
34958
34959 if (notify_types) {
34960 ast_config_destroy(notify_types);
34961 notify_types = NULL;
34962 }
34963
34964 ast_format_cap_destroy(sip_tech.capabilities);
34965 sip_cfg.caps = ast_format_cap_destroy(sip_cfg.caps);
34966
34967 return 0;
34968 }
34969
34970 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Session Initiation Protocol (SIP)",
34971 .load = load_module,
34972 .unload = unload_module,
34973 .reload = reload,
34974 .load_pri = AST_MODPRI_CHANNEL_DRIVER,
34975 .nonoptreq = "res_crypto,chan_local,res_http_websocket",
34976 );