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 #include "asterisk.h"
00211
00212 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 374456 $")
00213
00214 #include <signal.h>
00215 #include <sys/signal.h>
00216 #include <regex.h>
00217 #include <inttypes.h>
00218
00219 #include "asterisk/network.h"
00220 #include "asterisk/paths.h"
00221
00222
00223
00224
00225
00226
00227
00228
00229
00230
00231
00232
00233 #include "asterisk/lock.h"
00234 #include "asterisk/config.h"
00235 #include "asterisk/module.h"
00236 #include "asterisk/pbx.h"
00237 #include "asterisk/sched.h"
00238 #include "asterisk/io.h"
00239 #include "asterisk/rtp_engine.h"
00240 #include "asterisk/udptl.h"
00241 #include "asterisk/acl.h"
00242 #include "asterisk/manager.h"
00243 #include "asterisk/callerid.h"
00244 #include "asterisk/cli.h"
00245 #include "asterisk/musiconhold.h"
00246 #include "asterisk/dsp.h"
00247 #include "asterisk/features.h"
00248 #include "asterisk/srv.h"
00249 #include "asterisk/astdb.h"
00250 #include "asterisk/causes.h"
00251 #include "asterisk/utils.h"
00252 #include "asterisk/file.h"
00253 #include "asterisk/astobj2.h"
00254 #include "asterisk/dnsmgr.h"
00255 #include "asterisk/devicestate.h"
00256 #include "asterisk/monitor.h"
00257 #include "asterisk/netsock2.h"
00258 #include "asterisk/localtime.h"
00259 #include "asterisk/abstract_jb.h"
00260 #include "asterisk/threadstorage.h"
00261 #include "asterisk/translate.h"
00262 #include "asterisk/ast_version.h"
00263 #include "asterisk/event.h"
00264 #include "asterisk/cel.h"
00265 #include "asterisk/data.h"
00266 #include "asterisk/aoc.h"
00267 #include "sip/include/sip.h"
00268 #include "sip/include/globals.h"
00269 #include "sip/include/config_parser.h"
00270 #include "sip/include/reqresp_parser.h"
00271 #include "sip/include/sip_utils.h"
00272 #include "sip/include/srtp.h"
00273 #include "sip/include/sdp_crypto.h"
00274 #include "asterisk/ccss.h"
00275 #include "asterisk/xml.h"
00276 #include "sip/include/dialog.h"
00277 #include "sip/include/dialplan_functions.h"
00278
00279
00280
00281
00282
00283
00284
00285
00286
00287
00288
00289
00290
00291
00292
00293
00294
00295
00296
00297
00298
00299
00300
00301
00302
00303
00304
00305
00306
00307
00308
00309
00310
00311
00312
00313
00314
00315
00316
00317
00318
00319
00320
00321
00322
00323
00324
00325
00326
00327
00328
00329
00330
00331
00332
00333
00334
00335
00336
00337
00338
00339
00340
00341
00342
00343
00344
00345
00346
00347
00348
00349
00350
00351
00352
00353
00354
00355
00356
00357
00358
00359
00360
00361
00362
00363
00364
00365
00366
00367
00368
00369
00370
00371
00372
00373
00374
00375
00376
00377
00378
00379
00380
00381
00382
00383
00384
00385
00386
00387
00388
00389
00390
00391
00392
00393
00394
00395
00396
00397
00398
00399
00400
00401
00402
00403
00404
00405
00406
00407
00408
00409
00410
00411
00412
00413
00414
00415
00416
00417
00418
00419
00420
00421
00422
00423
00424
00425
00426
00427
00428
00429
00430
00431
00432
00433
00434
00435
00436
00437
00438
00439
00440
00441
00442
00443
00444
00445
00446
00447
00448
00449
00450
00451
00452
00453
00454
00455
00456
00457
00458
00459
00460
00461
00462
00463
00464
00465
00466
00467
00468
00469
00470
00471
00472
00473
00474
00475
00476
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 static int min_expiry = DEFAULT_MIN_EXPIRY;
00559 static int max_expiry = DEFAULT_MAX_EXPIRY;
00560 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
00561 static int mwi_expiry = DEFAULT_MWI_EXPIRY;
00562
00563 static int unauth_sessions = 0;
00564 static int authlimit = DEFAULT_AUTHLIMIT;
00565 static int authtimeout = DEFAULT_AUTHTIMEOUT;
00566
00567
00568
00569 static struct ast_jb_conf default_jbconf =
00570 {
00571 .flags = 0,
00572 .max_size = 200,
00573 .resync_threshold = 1000,
00574 .impl = "fixed",
00575 .target_extra = 40,
00576 };
00577 static struct ast_jb_conf global_jbconf;
00578
00579 static const char config[] = "sip.conf";
00580 static const char notify_config[] = "sip_notify.conf";
00581
00582
00583
00584 static const struct invstate2stringtable {
00585 const enum invitestates state;
00586 const char *desc;
00587 } invitestate2string[] = {
00588 {INV_NONE, "None" },
00589 {INV_CALLING, "Calling (Trying)"},
00590 {INV_PROCEEDING, "Proceeding "},
00591 {INV_EARLY_MEDIA, "Early media"},
00592 {INV_COMPLETED, "Completed (done)"},
00593 {INV_CONFIRMED, "Confirmed (up)"},
00594 {INV_TERMINATED, "Done"},
00595 {INV_CANCELLED, "Cancelled"}
00596 };
00597
00598
00599
00600
00601
00602
00603 static const struct cfsubscription_types {
00604 enum subscriptiontype type;
00605 const char * const event;
00606 const char * const mediatype;
00607 const char * const text;
00608 } subscription_types[] = {
00609 { NONE, "-", "unknown", "unknown" },
00610
00611 { DIALOG_INFO_XML, "dialog", "application/dialog-info+xml", "dialog-info+xml" },
00612 { CPIM_PIDF_XML, "presence", "application/cpim-pidf+xml", "cpim-pidf+xml" },
00613 { PIDF_XML, "presence", "application/pidf+xml", "pidf+xml" },
00614 { XPIDF_XML, "presence", "application/xpidf+xml", "xpidf+xml" },
00615 { MWI_NOTIFICATION, "message-summary", "application/simple-message-summary", "mwi" }
00616 };
00617
00618
00619
00620
00621
00622
00623 static const struct cfsip_methods {
00624 enum sipmethod id;
00625 int need_rtp;
00626 char * const text;
00627 enum can_create_dialog can_create;
00628 } sip_methods[] = {
00629 { SIP_UNKNOWN, RTP, "-UNKNOWN-",CAN_CREATE_DIALOG },
00630 { SIP_RESPONSE, NO_RTP, "SIP/2.0", CAN_NOT_CREATE_DIALOG },
00631 { SIP_REGISTER, NO_RTP, "REGISTER", CAN_CREATE_DIALOG },
00632 { SIP_OPTIONS, NO_RTP, "OPTIONS", CAN_CREATE_DIALOG },
00633 { SIP_NOTIFY, NO_RTP, "NOTIFY", CAN_CREATE_DIALOG },
00634 { SIP_INVITE, RTP, "INVITE", CAN_CREATE_DIALOG },
00635 { SIP_ACK, NO_RTP, "ACK", CAN_NOT_CREATE_DIALOG },
00636 { SIP_PRACK, NO_RTP, "PRACK", CAN_NOT_CREATE_DIALOG },
00637 { SIP_BYE, NO_RTP, "BYE", CAN_NOT_CREATE_DIALOG },
00638 { SIP_REFER, NO_RTP, "REFER", CAN_CREATE_DIALOG },
00639 { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE",CAN_CREATE_DIALOG },
00640 { SIP_MESSAGE, NO_RTP, "MESSAGE", CAN_CREATE_DIALOG },
00641 { SIP_UPDATE, NO_RTP, "UPDATE", CAN_NOT_CREATE_DIALOG },
00642 { SIP_INFO, NO_RTP, "INFO", CAN_NOT_CREATE_DIALOG },
00643 { SIP_CANCEL, NO_RTP, "CANCEL", CAN_NOT_CREATE_DIALOG },
00644 { SIP_PUBLISH, NO_RTP, "PUBLISH", CAN_CREATE_DIALOG },
00645 { SIP_PING, NO_RTP, "PING", CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
00646 };
00647
00648
00649
00650
00651
00652
00653
00654
00655 static const struct sip_reasons {
00656 enum AST_REDIRECTING_REASON code;
00657 char * const text;
00658 } sip_reason_table[] = {
00659 { AST_REDIRECTING_REASON_UNKNOWN, "unknown" },
00660 { AST_REDIRECTING_REASON_USER_BUSY, "user-busy" },
00661 { AST_REDIRECTING_REASON_NO_ANSWER, "no-answer" },
00662 { AST_REDIRECTING_REASON_UNAVAILABLE, "unavailable" },
00663 { AST_REDIRECTING_REASON_UNCONDITIONAL, "unconditional" },
00664 { AST_REDIRECTING_REASON_TIME_OF_DAY, "time-of-day" },
00665 { AST_REDIRECTING_REASON_DO_NOT_DISTURB, "do-not-disturb" },
00666 { AST_REDIRECTING_REASON_DEFLECTION, "deflection" },
00667 { AST_REDIRECTING_REASON_FOLLOW_ME, "follow-me" },
00668 { AST_REDIRECTING_REASON_OUT_OF_ORDER, "out-of-service" },
00669 { AST_REDIRECTING_REASON_AWAY, "away" },
00670 { AST_REDIRECTING_REASON_CALL_FWD_DTE, "unknown"}
00671 };
00672
00673
00674
00675
00676
00677
00678
00679 static char default_language[MAX_LANGUAGE];
00680 static char default_callerid[AST_MAX_EXTENSION];
00681 static char default_mwi_from[80];
00682 static char default_fromdomain[AST_MAX_EXTENSION];
00683 static int default_fromdomainport;
00684 static char default_notifymime[AST_MAX_EXTENSION];
00685 static char default_vmexten[AST_MAX_EXTENSION];
00686 static int default_qualify;
00687 static char default_mohinterpret[MAX_MUSICCLASS];
00688 static char default_mohsuggest[MAX_MUSICCLASS];
00689
00690 static char default_parkinglot[AST_MAX_CONTEXT];
00691 static char default_engine[256];
00692 static int default_maxcallbitrate;
00693 static struct ast_codec_pref default_prefs;
00694 static unsigned int default_transports;
00695 static unsigned int default_primary_transport;
00696
00697
00698 static struct sip_settings sip_cfg;
00699
00700
00701
00702 #define SIP_PEDANTIC_DECODE(str) \
00703 if (sip_cfg.pedanticsipchecking && !ast_strlen_zero(str)) { \
00704 ast_uri_decode(str); \
00705 } \
00706
00707 static unsigned int chan_idx;
00708 static int global_match_auth_username;
00709
00710 static int global_relaxdtmf;
00711 static int global_prematuremediafilter;
00712 static int global_rtptimeout;
00713 static int global_rtpholdtimeout;
00714 static int global_rtpkeepalive;
00715 static int global_reg_timeout;
00716 static int global_regattempts_max;
00717 static int global_shrinkcallerid;
00718 static int global_callcounter;
00719
00720
00721 static unsigned int global_tos_sip;
00722 static unsigned int global_tos_audio;
00723 static unsigned int global_tos_video;
00724 static unsigned int global_tos_text;
00725 static unsigned int global_cos_sip;
00726 static unsigned int global_cos_audio;
00727 static unsigned int global_cos_video;
00728 static unsigned int global_cos_text;
00729 static unsigned int recordhistory;
00730 static unsigned int dumphistory;
00731 static char global_useragent[AST_MAX_EXTENSION];
00732 static char global_sdpsession[AST_MAX_EXTENSION];
00733 static char global_sdpowner[AST_MAX_EXTENSION];
00734 static int global_authfailureevents;
00735 static int global_t1;
00736 static int global_t1min;
00737 static int global_timer_b;
00738 static unsigned int global_autoframing;
00739 static int global_qualifyfreq;
00740 static int global_qualify_gap;
00741 static int global_qualify_peers;
00742
00743 static enum st_mode global_st_mode;
00744 static enum st_refresher_param global_st_refresher;
00745 static int global_min_se;
00746 static int global_max_se;
00747
00748 static int global_store_sip_cause;
00749
00750 static int global_dynamic_exclude_static = 0;
00751
00752
00753
00754
00755
00756
00757
00758
00759 static int can_parse_xml;
00760
00761
00762
00763
00764 static int speerobjs = 0;
00765 static int rpeerobjs = 0;
00766 static int apeerobjs = 0;
00767 static int regobjs = 0;
00768
00769
00770 static struct ast_flags global_flags[3] = {{0}};
00771 static int global_t38_maxdatagram;
00772
00773 static struct ast_event_sub *network_change_event_subscription;
00774 static int network_change_event_sched_id = -1;
00775
00776 static char used_context[AST_MAX_CONTEXT];
00777
00778 AST_MUTEX_DEFINE_STATIC(netlock);
00779
00780
00781
00782 AST_MUTEX_DEFINE_STATIC(monlock);
00783
00784 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
00785
00786
00787
00788 static pthread_t monitor_thread = AST_PTHREADT_NULL;
00789
00790 static int sip_reloading = FALSE;
00791 static enum channelreloadreason sip_reloadreason;
00792
00793 struct sched_context *sched;
00794 static struct io_context *io;
00795 static int *sipsock_read_id;
00796 struct sip_pkt;
00797 static AST_LIST_HEAD_STATIC(domain_list, domain);
00798
00799 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history);
00800
00801 static enum sip_debug_e sipdebug;
00802
00803
00804
00805
00806
00807 static int sipdebug_text;
00808
00809 static const struct _map_x_s referstatusstrings[] = {
00810 { REFER_IDLE, "<none>" },
00811 { REFER_SENT, "Request sent" },
00812 { REFER_RECEIVED, "Request received" },
00813 { REFER_CONFIRMED, "Confirmed" },
00814 { REFER_ACCEPTED, "Accepted" },
00815 { REFER_RINGING, "Target ringing" },
00816 { REFER_200OK, "Done" },
00817 { REFER_FAILED, "Failed" },
00818 { REFER_NOAUTH, "Failed - auth failure" },
00819 { -1, NULL}
00820 };
00821
00822
00823 #ifdef LOW_MEMORY
00824 static const int HASH_PEER_SIZE = 17;
00825 static const int HASH_DIALOG_SIZE = 17;
00826 #else
00827 static const int HASH_PEER_SIZE = 563;
00828 static const int HASH_DIALOG_SIZE = 563;
00829 #endif
00830
00831 static const struct {
00832 enum ast_cc_service_type service;
00833 const char *service_string;
00834 } sip_cc_service_map [] = {
00835 [AST_CC_NONE] = { AST_CC_NONE, "" },
00836 [AST_CC_CCBS] = { AST_CC_CCBS, "BS" },
00837 [AST_CC_CCNR] = { AST_CC_CCNR, "NR" },
00838 [AST_CC_CCNL] = { AST_CC_CCNL, "NL" },
00839 };
00840
00841 static enum ast_cc_service_type service_string_to_service_type(const char * const service_string)
00842 {
00843 enum ast_cc_service_type service;
00844 for (service = AST_CC_CCBS; service <= AST_CC_CCNL; ++service) {
00845 if (!strcasecmp(service_string, sip_cc_service_map[service].service_string)) {
00846 return service;
00847 }
00848 }
00849 return AST_CC_NONE;
00850 }
00851
00852 static const struct {
00853 enum sip_cc_notify_state state;
00854 const char *state_string;
00855 } sip_cc_notify_state_map [] = {
00856 [CC_QUEUED] = {CC_QUEUED, "cc-state: queued"},
00857 [CC_READY] = {CC_READY, "cc-state: ready"},
00858 };
00859
00860 AST_LIST_HEAD_STATIC(epa_static_data_list, epa_backend);
00861
00862 static int sip_epa_register(const struct epa_static_data *static_data)
00863 {
00864 struct epa_backend *backend = ast_calloc(1, sizeof(*backend));
00865
00866 if (!backend) {
00867 return -1;
00868 }
00869
00870 backend->static_data = static_data;
00871
00872 AST_LIST_LOCK(&epa_static_data_list);
00873 AST_LIST_INSERT_TAIL(&epa_static_data_list, backend, next);
00874 AST_LIST_UNLOCK(&epa_static_data_list);
00875 return 0;
00876 }
00877
00878 static void sip_epa_unregister_all(void)
00879 {
00880 struct epa_backend *backend;
00881
00882 AST_LIST_LOCK(&epa_static_data_list);
00883 while ((backend = AST_LIST_REMOVE_HEAD(&epa_static_data_list, next))) {
00884 ast_free(backend);
00885 }
00886 AST_LIST_UNLOCK(&epa_static_data_list);
00887 }
00888
00889 static void cc_handle_publish_error(struct sip_pvt *pvt, const int resp, struct sip_request *req, struct sip_epa_entry *epa_entry);
00890
00891 static void cc_epa_destructor(void *data)
00892 {
00893 struct sip_epa_entry *epa_entry = data;
00894 struct cc_epa_entry *cc_entry = epa_entry->instance_data;
00895 ast_free(cc_entry);
00896 }
00897
00898 static const struct epa_static_data cc_epa_static_data = {
00899 .event = CALL_COMPLETION,
00900 .name = "call-completion",
00901 .handle_error = cc_handle_publish_error,
00902 .destructor = cc_epa_destructor,
00903 };
00904
00905 static const struct epa_static_data *find_static_data(const char * const event_package)
00906 {
00907 const struct epa_backend *backend = NULL;
00908
00909 AST_LIST_LOCK(&epa_static_data_list);
00910 AST_LIST_TRAVERSE(&epa_static_data_list, backend, next) {
00911 if (!strcmp(backend->static_data->name, event_package)) {
00912 break;
00913 }
00914 }
00915 AST_LIST_UNLOCK(&epa_static_data_list);
00916 return backend ? backend->static_data : NULL;
00917 }
00918
00919 static struct sip_epa_entry *create_epa_entry (const char * const event_package, const char * const destination)
00920 {
00921 struct sip_epa_entry *epa_entry;
00922 const struct epa_static_data *static_data;
00923
00924 if (!(static_data = find_static_data(event_package))) {
00925 return NULL;
00926 }
00927
00928 if (!(epa_entry = ao2_t_alloc(sizeof(*epa_entry), static_data->destructor, "Allocate new EPA entry"))) {
00929 return NULL;
00930 }
00931
00932 epa_entry->static_data = static_data;
00933 ast_copy_string(epa_entry->destination, destination, sizeof(epa_entry->destination));
00934 return epa_entry;
00935 }
00936
00937
00938
00939
00940 static int esc_etag_counter;
00941 static const int DEFAULT_PUBLISH_EXPIRES = 3600;
00942
00943 #ifdef HAVE_LIBXML2
00944 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);
00945
00946 static const struct sip_esc_publish_callbacks cc_esc_publish_callbacks = {
00947 .initial_handler = cc_esc_publish_handler,
00948 .modify_handler = cc_esc_publish_handler,
00949 };
00950 #endif
00951
00952
00953
00954
00955
00956
00957
00958
00959
00960
00961
00962
00963
00964 static struct event_state_compositor {
00965 enum subscriptiontype event;
00966 const char * name;
00967 const struct sip_esc_publish_callbacks *callbacks;
00968 struct ao2_container *compositor;
00969 } event_state_compositors [] = {
00970 #ifdef HAVE_LIBXML2
00971 {CALL_COMPLETION, "call-completion", &cc_esc_publish_callbacks},
00972 #endif
00973 };
00974
00975 static const int ESC_MAX_BUCKETS = 37;
00976
00977 static void esc_entry_destructor(void *obj)
00978 {
00979 struct sip_esc_entry *esc_entry = obj;
00980 if (esc_entry->sched_id > -1) {
00981 AST_SCHED_DEL(sched, esc_entry->sched_id);
00982 }
00983 }
00984
00985 static int esc_hash_fn(const void *obj, const int flags)
00986 {
00987 const struct sip_esc_entry *entry = obj;
00988 return ast_str_hash(entry->entity_tag);
00989 }
00990
00991 static int esc_cmp_fn(void *obj, void *arg, int flags)
00992 {
00993 struct sip_esc_entry *entry1 = obj;
00994 struct sip_esc_entry *entry2 = arg;
00995
00996 return (!strcmp(entry1->entity_tag, entry2->entity_tag)) ? (CMP_MATCH | CMP_STOP) : 0;
00997 }
00998
00999 static struct event_state_compositor *get_esc(const char * const event_package) {
01000 int i;
01001 for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
01002 if (!strcasecmp(event_package, event_state_compositors[i].name)) {
01003 return &event_state_compositors[i];
01004 }
01005 }
01006 return NULL;
01007 }
01008
01009 static struct sip_esc_entry *get_esc_entry(const char * entity_tag, struct event_state_compositor *esc) {
01010 struct sip_esc_entry *entry;
01011 struct sip_esc_entry finder;
01012
01013 ast_copy_string(finder.entity_tag, entity_tag, sizeof(finder.entity_tag));
01014
01015 entry = ao2_find(esc->compositor, &finder, OBJ_POINTER);
01016
01017 return entry;
01018 }
01019
01020 static int publish_expire(const void *data)
01021 {
01022 struct sip_esc_entry *esc_entry = (struct sip_esc_entry *) data;
01023 struct event_state_compositor *esc = get_esc(esc_entry->event);
01024
01025 ast_assert(esc != NULL);
01026
01027 ao2_unlink(esc->compositor, esc_entry);
01028 ao2_ref(esc_entry, -1);
01029 return 0;
01030 }
01031
01032 static void create_new_sip_etag(struct sip_esc_entry *esc_entry, int is_linked)
01033 {
01034 int new_etag = ast_atomic_fetchadd_int(&esc_etag_counter, +1);
01035 struct event_state_compositor *esc = get_esc(esc_entry->event);
01036
01037 ast_assert(esc != NULL);
01038 if (is_linked) {
01039 ao2_unlink(esc->compositor, esc_entry);
01040 }
01041 snprintf(esc_entry->entity_tag, sizeof(esc_entry->entity_tag), "%d", new_etag);
01042 ao2_link(esc->compositor, esc_entry);
01043 }
01044
01045 static struct sip_esc_entry *create_esc_entry(struct event_state_compositor *esc, struct sip_request *req, const int expires)
01046 {
01047 struct sip_esc_entry *esc_entry;
01048 int expires_ms;
01049
01050 if (!(esc_entry = ao2_alloc(sizeof(*esc_entry), esc_entry_destructor))) {
01051 return NULL;
01052 }
01053
01054 esc_entry->event = esc->name;
01055
01056 expires_ms = expires * 1000;
01057
01058 ao2_ref(esc_entry, +1);
01059 esc_entry->sched_id = ast_sched_add(sched, expires_ms, publish_expire, esc_entry);
01060
01061
01062 create_new_sip_etag(esc_entry, 0);
01063
01064 return esc_entry;
01065 }
01066
01067 static int initialize_escs(void)
01068 {
01069 int i, res = 0;
01070 for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
01071 if (!((event_state_compositors[i].compositor) =
01072 ao2_container_alloc(ESC_MAX_BUCKETS, esc_hash_fn, esc_cmp_fn))) {
01073 res = -1;
01074 }
01075 }
01076 return res;
01077 }
01078
01079 static void destroy_escs(void)
01080 {
01081 int i;
01082 for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
01083 ao2_ref(event_state_compositors[i].compositor, -1);
01084 }
01085 }
01086
01087
01088
01089
01090
01091 struct ao2_container *dialogs_to_destroy;
01092
01093
01094
01095
01096
01097
01098
01099
01100
01101 static struct ao2_container *dialogs;
01102 #define sip_pvt_lock(x) ao2_lock(x)
01103 #define sip_pvt_trylock(x) ao2_trylock(x)
01104 #define sip_pvt_unlock(x) ao2_unlock(x)
01105
01106
01107 static struct ao2_container *threadt;
01108
01109
01110 static struct ao2_container *peers;
01111 static struct ao2_container *peers_by_ip;
01112
01113
01114 static struct ast_register_list {
01115 ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
01116 int recheck;
01117 } regl;
01118
01119
01120 static struct ast_subscription_mwi_list {
01121 ASTOBJ_CONTAINER_COMPONENTS(struct sip_subscription_mwi);
01122 } submwil;
01123 static int temp_pvt_init(void *);
01124 static void temp_pvt_cleanup(void *);
01125
01126
01127 AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
01128
01129
01130 static struct sip_auth_container *authl = NULL;
01131
01132 AST_MUTEX_DEFINE_STATIC(authl_lock);
01133
01134
01135
01136
01137
01138
01139
01140
01141
01142
01143
01144
01145
01146
01147
01148
01149
01150 static int sipsock = -1;
01151
01152 struct ast_sockaddr bindaddr;
01153
01154
01155
01156
01157
01158
01159
01160 static struct ast_sockaddr internip;
01161
01162
01163
01164
01165
01166
01167
01168
01169
01170
01171
01172
01173
01174
01175
01176
01177 static struct ast_sockaddr externaddr;
01178 static struct ast_sockaddr media_address;
01179
01180 static char externhost[MAXHOSTNAMELEN];
01181 static time_t externexpire;
01182 static int externrefresh = 10;
01183 static uint16_t externtcpport;
01184 static uint16_t externtlsport;
01185
01186
01187
01188
01189
01190
01191
01192 static struct ast_ha *localaddr;
01193
01194 static int ourport_tcp;
01195 static int ourport_tls;
01196 static struct ast_sockaddr debugaddr;
01197
01198 static struct ast_config *notify_types = NULL;
01199
01200
01201
01202 #define UNLINK(element, head, prev) do { \
01203 if (prev) \
01204 (prev)->next = (element)->next; \
01205 else \
01206 (head) = (element)->next; \
01207 } while (0)
01208
01209
01210
01211
01212
01213
01214 static struct ast_channel *sip_request_call(const char *type, format_t format, const struct ast_channel *requestor, void *data, int *cause);
01215 static int sip_devicestate(void *data);
01216 static int sip_sendtext(struct ast_channel *ast, const char *text);
01217 static int sip_call(struct ast_channel *ast, char *dest, int timeout);
01218 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen);
01219 static int sip_hangup(struct ast_channel *ast);
01220 static int sip_answer(struct ast_channel *ast);
01221 static struct ast_frame *sip_read(struct ast_channel *ast);
01222 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
01223 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
01224 static int sip_transfer(struct ast_channel *ast, const char *dest);
01225 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
01226 static int sip_senddigit_begin(struct ast_channel *ast, char digit);
01227 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
01228 static int sip_setoption(struct ast_channel *chan, int option, void *data, int datalen);
01229 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen);
01230 static const char *sip_get_callid(struct ast_channel *chan);
01231
01232 static int handle_request_do(struct sip_request *req, struct ast_sockaddr *addr);
01233 static int sip_standard_port(enum sip_transport type, int port);
01234 static int sip_prepare_socket(struct sip_pvt *p);
01235 static int get_address_family_filter(unsigned int transport);
01236
01237
01238 static int sipsock_read(int *id, int fd, short events, void *ignore);
01239 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data);
01240 static int __sip_reliable_xmit(struct sip_pvt *p, uint32_t seqno, int resp, struct ast_str *data, int fatal, int sipmethod);
01241 static void add_cc_call_info_to_response(struct sip_pvt *p, struct sip_request *resp);
01242 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
01243 static int retrans_pkt(const void *data);
01244 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);
01245 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
01246 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
01247 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
01248 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);
01249 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
01250 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);
01251 static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp);
01252 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
01253 static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable);
01254 static int transmit_request(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch);
01255 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch);
01256 static int transmit_publish(struct sip_epa_entry *epa_entry, enum sip_publish_type publish_type, const char * const explicit_uri);
01257 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init, const char * const explicit_uri);
01258 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp);
01259 static int transmit_info_with_aoc(struct sip_pvt *p, struct ast_aoc_decoded *decoded);
01260 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
01261 static int transmit_info_with_vidupdate(struct sip_pvt *p);
01262 static int transmit_message_with_text(struct sip_pvt *p, const char *text);
01263 static int transmit_refer(struct sip_pvt *p, const char *dest);
01264 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten);
01265 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
01266 static int transmit_cc_notify(struct ast_cc_agent *agent, struct sip_pvt *subscription, enum sip_cc_notify_state state);
01267 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
01268 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno);
01269 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno);
01270 static void copy_request(struct sip_request *dst, const struct sip_request *src);
01271 static void receive_message(struct sip_pvt *p, struct sip_request *req);
01272 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req, char **name, char **number, int set_call_forward);
01273 static int sip_send_mwi_to_peer(struct sip_peer *peer, int cache_only);
01274
01275
01276 static int __sip_autodestruct(const void *data);
01277 static void *registry_unref(struct sip_registry *reg, char *tag);
01278 static int update_call_counter(struct sip_pvt *fup, int event);
01279 static int auto_congest(const void *arg);
01280 static struct sip_pvt *find_call(struct sip_request *req, struct ast_sockaddr *addr, const int intended_method);
01281 static void free_old_route(struct sip_route *route);
01282 static void list_route(struct sip_route *route);
01283 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards, int resp);
01284 static enum check_auth_result register_verify(struct sip_pvt *p, struct ast_sockaddr *addr,
01285 struct sip_request *req, const char *uri);
01286 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
01287 static void check_pendings(struct sip_pvt *p);
01288 static void *sip_park_thread(void *stuff);
01289 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);
01290
01291 static void *sip_pickup_thread(void *stuff);
01292 static int sip_pickup(struct ast_channel *chan);
01293
01294 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
01295 static int is_method_allowed(unsigned int *allowed_methods, enum sipmethod method);
01296
01297
01298 static void try_suggested_sip_codec(struct sip_pvt *p);
01299 static const char *get_sdp_iterate(int* start, struct sip_request *req, const char *name);
01300 static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value);
01301 static int find_sdp(struct sip_request *req);
01302 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action);
01303 static int process_sdp_o(const char *o, struct sip_pvt *p);
01304 static int process_sdp_c(const char *c, struct ast_sockaddr *addr);
01305 static int process_sdp_a_sendonly(const char *a, int *sendonly);
01306 static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newaudiortp, int *last_rtpmap_codec);
01307 static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newvideortp, int *last_rtpmap_codec);
01308 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);
01309 static int process_sdp_a_image(const char *a, struct sip_pvt *p);
01310 static void add_codec_to_sdp(const struct sip_pvt *p, format_t codec,
01311 struct ast_str **m_buf, struct ast_str **a_buf,
01312 int debug, int *min_packet_size);
01313 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
01314 struct ast_str **m_buf, struct ast_str **a_buf,
01315 int debug);
01316 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38);
01317 static void do_setnat(struct sip_pvt *p);
01318 static void stop_media_flows(struct sip_pvt *p);
01319
01320
01321 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
01322 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
01323 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
01324 const char *secret, const char *md5secret, int sipmethod,
01325 const char *uri, enum xmittype reliable, int ignore);
01326 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
01327 int sipmethod, const char *uri, enum xmittype reliable,
01328 struct ast_sockaddr *addr, struct sip_peer **authpeer);
01329 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, const char *uri, enum xmittype reliable, struct ast_sockaddr *addr);
01330
01331
01332 static int check_sip_domain(const char *domain, char *context, size_t len);
01333 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
01334 static void clear_sip_domains(void);
01335
01336
01337 static void add_realm_authentication(struct sip_auth_container **credentials, const char *configuration, int lineno);
01338 static struct sip_auth *find_realm_authentication(struct sip_auth_container *credentials, const char *realm);
01339
01340
01341 static void check_rtp_timeout(struct sip_pvt *dialog, time_t t);
01342 static int reload_config(enum channelreloadreason reason);
01343 static void add_diversion_header(struct sip_request *req, struct sip_pvt *pvt);
01344 static int expire_register(const void *data);
01345 static void *do_monitor(void *data);
01346 static int restart_monitor(void);
01347 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer);
01348 static struct ast_variable *copy_vars(struct ast_variable *src);
01349 static int dialog_find_multiple(void *obj, void *arg, int flags);
01350 static struct ast_channel *sip_pvt_lock_full(struct sip_pvt *pvt);
01351
01352 static int sip_refer_allocate(struct sip_pvt *p);
01353 static int sip_notify_allocate(struct sip_pvt *p);
01354 static void ast_quiet_chan(struct ast_channel *chan);
01355 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
01356 static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context);
01357
01358
01359 static int cb_extensionstate(char *context, char* exten, int state, void *data);
01360 static int sip_devicestate(void *data);
01361 static int sip_poke_noanswer(const void *data);
01362 static int sip_poke_peer(struct sip_peer *peer, int force);
01363 static void sip_poke_all_peers(void);
01364 static void sip_peer_hold(struct sip_pvt *p, int hold);
01365 static void mwi_event_cb(const struct ast_event *, void *);
01366 static void network_change_event_cb(const struct ast_event *, void *);
01367
01368
01369 static const char *sip_nat_mode(const struct sip_pvt *p);
01370 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01371 static char *transfermode2str(enum transfermodes mode) attribute_const;
01372 static int peer_status(struct sip_peer *peer, char *status, int statuslen);
01373 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01374 static char * _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
01375 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01376 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01377 static void print_group(int fd, ast_group_t group, int crlf);
01378 static const char *dtmfmode2str(int mode) attribute_const;
01379 static int str2dtmfmode(const char *str) attribute_unused;
01380 static const char *insecure2str(int mode) attribute_const;
01381 static const char *allowoverlap2str(int mode) attribute_const;
01382 static void cleanup_stale_contexts(char *new, char *old);
01383 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
01384 static const char *domain_mode_to_text(const enum domain_mode mode);
01385 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01386 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
01387 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01388 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
01389 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01390 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01391 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01392 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01393 static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01394 static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
01395 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
01396 static char *complete_sip_peer(const char *word, int state, int flags2);
01397 static char *complete_sip_registered_peer(const char *word, int state, int flags2);
01398 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state);
01399 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
01400 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state);
01401 static char *complete_sipnotify(const char *line, const char *word, int pos, int state);
01402 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01403 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01404 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01405 static char *sip_do_debug_ip(int fd, const char *arg);
01406 static char *sip_do_debug_peer(int fd, const char *arg);
01407 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01408 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01409 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01410 static int sip_dtmfmode(struct ast_channel *chan, const char *data);
01411 static int sip_addheader(struct ast_channel *chan, const char *data);
01412 static int sip_do_reload(enum channelreloadreason reason);
01413 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01414 static int ast_sockaddr_resolve_first_af(struct ast_sockaddr *addr,
01415 const char *name, int flag, int family);
01416 static int ast_sockaddr_resolve_first(struct ast_sockaddr *addr,
01417 const char *name, int flag);
01418 static int ast_sockaddr_resolve_first_transport(struct ast_sockaddr *addr,
01419 const char *name, int flag, unsigned int transport);
01420
01421
01422
01423
01424
01425 static void sip_dump_history(struct sip_pvt *dialog);
01426 static inline int sip_debug_test_addr(const struct ast_sockaddr *addr);
01427 static inline int sip_debug_test_pvt(struct sip_pvt *p);
01428 static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
01429 static void sip_dump_history(struct sip_pvt *dialog);
01430
01431
01432 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only);
01433 static int update_call_counter(struct sip_pvt *fup, int event);
01434 static void sip_destroy_peer(struct sip_peer *peer);
01435 static void sip_destroy_peer_fn(void *peer);
01436 static void set_peer_defaults(struct sip_peer *peer);
01437 static struct sip_peer *temp_peer(const char *name);
01438 static void register_peer_exten(struct sip_peer *peer, int onoff);
01439 static struct sip_peer *find_peer(const char *peer, struct ast_sockaddr *addr, int realtime, int forcenamematch, int devstate_only, int transport);
01440 static int sip_poke_peer_s(const void *data);
01441 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
01442 static void reg_source_db(struct sip_peer *peer);
01443 static void destroy_association(struct sip_peer *peer);
01444 static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
01445 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
01446 static void set_socket_transport(struct sip_socket *socket, int transport);
01447
01448
01449 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);
01450 static void update_peer(struct sip_peer *p, int expire);
01451 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config);
01452 static const char *get_name_from_variable(const struct ast_variable *var);
01453 static struct sip_peer *realtime_peer(const char *peername, struct ast_sockaddr *sin, int devstate_only, int which_objects);
01454 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01455
01456
01457 static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p);
01458 static void sip_registry_destroy(struct sip_registry *reg);
01459 static int sip_register(const char *value, int lineno);
01460 static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
01461 static int sip_reregister(const void *data);
01462 static int __sip_do_register(struct sip_registry *r);
01463 static int sip_reg_timeout(const void *data);
01464 static void sip_send_all_registers(void);
01465 static int sip_reinvite_retry(const void *data);
01466
01467
01468 static void append_date(struct sip_request *req);
01469 static int determine_firstline_parts(struct sip_request *req);
01470 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
01471 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
01472 static int find_sip_method(const char *msg);
01473 static unsigned int parse_allowed_methods(struct sip_request *req);
01474 static unsigned int set_pvt_allowed_methods(struct sip_pvt *pvt, struct sip_request *req);
01475 static int parse_request(struct sip_request *req);
01476 static const char *get_header(const struct sip_request *req, const char *name);
01477 static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
01478 static int method_match(enum sipmethod id, const char *name);
01479 static void parse_copy(struct sip_request *dst, const struct sip_request *src);
01480 static const char *find_alias(const char *name, const char *_default);
01481 static const char *__get_header(const struct sip_request *req, const char *name, int *start);
01482 static void lws2sws(struct ast_str *msgbuf);
01483 static void extract_uri(struct sip_pvt *p, struct sip_request *req);
01484 static char *remove_uri_parameters(char *uri);
01485 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
01486 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
01487 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
01488 static int set_address_from_contact(struct sip_pvt *pvt);
01489 static void check_via(struct sip_pvt *p, struct sip_request *req);
01490 static int get_rpid(struct sip_pvt *p, struct sip_request *oreq);
01491 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq, char **name, char **number, int *reason);
01492 static enum sip_get_dest_result get_destination(struct sip_pvt *p, struct sip_request *oreq, int *cc_recall_core_id);
01493 static int get_msg_text(char *buf, int len, struct sip_request *req);
01494 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout);
01495 static void update_connectedline(struct sip_pvt *p, const void *data, size_t datalen);
01496 static void update_redirecting(struct sip_pvt *p, const void *data, size_t datalen);
01497 static int get_domain(const char *str, char *domain, int len);
01498 static void get_realm(struct sip_pvt *p, const struct sip_request *req);
01499
01500
01501 static void *_sip_tcp_helper_thread(struct ast_tcptls_session_instance *tcptls_session);
01502 static void *sip_tcp_worker_fn(void *);
01503
01504
01505 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
01506 static int init_req(struct sip_request *req, int sipmethod, const char *recip);
01507 static void deinit_req(struct sip_request *req);
01508 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, uint32_t seqno, int newbranch);
01509 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, const char * const explicit_uri);
01510 static int init_resp(struct sip_request *resp, const char *msg);
01511 static inline int resp_needs_contact(const char *msg, enum sipmethod method);
01512 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
01513 static const struct ast_sockaddr *sip_real_dst(const struct sip_pvt *p);
01514 static void build_via(struct sip_pvt *p);
01515 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
01516 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct ast_sockaddr *addr, int newdialog);
01517 static char *generate_random_string(char *buf, size_t size);
01518 static void build_callid_pvt(struct sip_pvt *pvt);
01519 static void change_callid_pvt(struct sip_pvt *pvt, const char *callid);
01520 static void build_callid_registry(struct sip_registry *reg, const struct ast_sockaddr *ourip, const char *fromdomain);
01521 static void make_our_tag(struct sip_pvt *pvt);
01522 static int add_header(struct sip_request *req, const char *var, const char *value);
01523 static int add_header_max_forwards(struct sip_pvt *dialog, struct sip_request *req);
01524 static int add_content(struct sip_request *req, const char *line);
01525 static int finalize_content(struct sip_request *req);
01526 static int add_text(struct sip_request *req, const char *text);
01527 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode);
01528 static int add_rpid(struct sip_request *req, struct sip_pvt *p);
01529 static int add_vidupdate(struct sip_request *req);
01530 static void add_route(struct sip_request *req, struct sip_route *route);
01531 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
01532 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
01533 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
01534 static void set_destination(struct sip_pvt *p, char *uri);
01535 static void append_date(struct sip_request *req);
01536 static void build_contact(struct sip_pvt *p);
01537
01538
01539 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int *recount, int *nounlock);
01540 static int handle_request_update(struct sip_pvt *p, struct sip_request *req);
01541 static int handle_request_invite(struct sip_pvt *p, struct sip_request *req, int debug, uint32_t seqno, struct ast_sockaddr *addr, int *recount, const char *e, int *nounlock);
01542 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, uint32_t seqno, int *nounlock);
01543 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
01544 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *sin, const char *e);
01545 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
01546 static int handle_request_message(struct sip_pvt *p, struct sip_request *req);
01547 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e);
01548 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
01549 static int handle_request_options(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
01550 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, uint32_t seqno, struct ast_sockaddr *addr, int *nounlock);
01551 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e);
01552 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, uint32_t seqno, int *nounlock);
01553
01554
01555 static void handle_response_publish(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01556 static void handle_response_invite(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01557 static void handle_response_notify(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01558 static void handle_response_refer(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01559 static void handle_response_subscribe(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01560 static int handle_response_register(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01561 static void handle_response(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01562
01563
01564 static int setup_srtp(struct sip_srtp **srtp);
01565 static int process_crypto(struct sip_pvt *p, struct ast_rtp_instance *rtp, struct sip_srtp **srtp, const char *a);
01566
01567
01568 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
01569 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
01570 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
01571 static void change_t38_state(struct sip_pvt *p, int state);
01572
01573
01574 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp);
01575 static int proc_session_timer(const void *vp);
01576 static void stop_session_timer(struct sip_pvt *p);
01577 static void start_session_timer(struct sip_pvt *p);
01578 static void restart_session_timer(struct sip_pvt *p);
01579 static const char *strefresherparam2str(enum st_refresher r);
01580 static int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher_param *const p_ref);
01581 static int parse_minse(const char *p_hdrval, int *const p_interval);
01582 static int st_get_se(struct sip_pvt *, int max);
01583 static enum st_refresher st_get_refresher(struct sip_pvt *);
01584 static enum st_mode st_get_mode(struct sip_pvt *, int no_cached);
01585 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p);
01586
01587
01588 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, format_t codecs, int nat_active);
01589
01590
01591 static int sip_subscribe_mwi(const char *value, int lineno);
01592 static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi);
01593 static void sip_send_all_mwi_subscriptions(void);
01594 static int sip_subscribe_mwi_do(const void *data);
01595 static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi);
01596
01597
01598 const struct ast_channel_tech sip_tech = {
01599 .type = "SIP",
01600 .description = "Session Initiation Protocol (SIP)",
01601 .capabilities = AST_FORMAT_AUDIO_MASK,
01602 .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
01603 .requester = sip_request_call,
01604 .devicestate = sip_devicestate,
01605 .call = sip_call,
01606 .send_html = sip_sendhtml,
01607 .hangup = sip_hangup,
01608 .answer = sip_answer,
01609 .read = sip_read,
01610 .write = sip_write,
01611 .write_video = sip_write,
01612 .write_text = sip_write,
01613 .indicate = sip_indicate,
01614 .transfer = sip_transfer,
01615 .fixup = sip_fixup,
01616 .send_digit_begin = sip_senddigit_begin,
01617 .send_digit_end = sip_senddigit_end,
01618 .bridge = ast_rtp_instance_bridge,
01619 .early_bridge = ast_rtp_instance_early_bridge,
01620 .send_text = sip_sendtext,
01621 .func_channel_read = sip_acf_channel_read,
01622 .setoption = sip_setoption,
01623 .queryoption = sip_queryoption,
01624 .get_pvt_uniqueid = sip_get_callid,
01625 };
01626
01627
01628
01629
01630
01631
01632
01633 struct ast_channel_tech sip_tech_info;
01634
01635 static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan);
01636 static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent);
01637 static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent);
01638 static void sip_cc_agent_respond(struct ast_cc_agent *agent, enum ast_cc_agent_response_reason reason);
01639 static int sip_cc_agent_status_request(struct ast_cc_agent *agent);
01640 static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent);
01641 static int sip_cc_agent_recall(struct ast_cc_agent *agent);
01642 static void sip_cc_agent_destructor(struct ast_cc_agent *agent);
01643
01644 static struct ast_cc_agent_callbacks sip_cc_agent_callbacks = {
01645 .type = "SIP",
01646 .init = sip_cc_agent_init,
01647 .start_offer_timer = sip_cc_agent_start_offer_timer,
01648 .stop_offer_timer = sip_cc_agent_stop_offer_timer,
01649 .respond = sip_cc_agent_respond,
01650 .status_request = sip_cc_agent_status_request,
01651 .start_monitoring = sip_cc_agent_start_monitoring,
01652 .callee_available = sip_cc_agent_recall,
01653 .destructor = sip_cc_agent_destructor,
01654 };
01655
01656 static int find_by_notify_uri_helper(void *obj, void *arg, int flags)
01657 {
01658 struct ast_cc_agent *agent = obj;
01659 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01660 const char *uri = arg;
01661
01662 return !sip_uri_cmp(agent_pvt->notify_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
01663 }
01664
01665 static struct ast_cc_agent *find_sip_cc_agent_by_notify_uri(const char * const uri)
01666 {
01667 struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_notify_uri_helper, (char *)uri, "SIP");
01668 return agent;
01669 }
01670
01671 static int find_by_subscribe_uri_helper(void *obj, void *arg, int flags)
01672 {
01673 struct ast_cc_agent *agent = obj;
01674 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01675 const char *uri = arg;
01676
01677 return !sip_uri_cmp(agent_pvt->subscribe_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
01678 }
01679
01680 static struct ast_cc_agent *find_sip_cc_agent_by_subscribe_uri(const char * const uri)
01681 {
01682 struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_subscribe_uri_helper, (char *)uri, "SIP");
01683 return agent;
01684 }
01685
01686 static int find_by_callid_helper(void *obj, void *arg, int flags)
01687 {
01688 struct ast_cc_agent *agent = obj;
01689 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01690 struct sip_pvt *call_pvt = arg;
01691
01692 return !strcmp(agent_pvt->original_callid, call_pvt->callid) ? CMP_MATCH | CMP_STOP : 0;
01693 }
01694
01695 static struct ast_cc_agent *find_sip_cc_agent_by_original_callid(struct sip_pvt *pvt)
01696 {
01697 struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_callid_helper, pvt, "SIP");
01698 return agent;
01699 }
01700
01701 static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan)
01702 {
01703 struct sip_cc_agent_pvt *agent_pvt = ast_calloc(1, sizeof(*agent_pvt));
01704 struct sip_pvt *call_pvt = chan->tech_pvt;
01705
01706 if (!agent_pvt) {
01707 return -1;
01708 }
01709
01710 ast_assert(!strcmp(chan->tech->type, "SIP"));
01711
01712 ast_copy_string(agent_pvt->original_callid, call_pvt->callid, sizeof(agent_pvt->original_callid));
01713 ast_copy_string(agent_pvt->original_exten, call_pvt->exten, sizeof(agent_pvt->original_exten));
01714 agent_pvt->offer_timer_id = -1;
01715 agent->private_data = agent_pvt;
01716 sip_pvt_lock(call_pvt);
01717 ast_set_flag(&call_pvt->flags[0], SIP_OFFER_CC);
01718 sip_pvt_unlock(call_pvt);
01719 return 0;
01720 }
01721
01722 static int sip_offer_timer_expire(const void *data)
01723 {
01724 struct ast_cc_agent *agent = (struct ast_cc_agent *) data;
01725 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01726
01727 agent_pvt->offer_timer_id = -1;
01728
01729 return ast_cc_failed(agent->core_id, "SIP agent %s's offer timer expired", agent->device_name);
01730 }
01731
01732 static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent)
01733 {
01734 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01735 int when;
01736
01737 when = ast_get_cc_offer_timer(agent->cc_params) * 1000;
01738 agent_pvt->offer_timer_id = ast_sched_add(sched, when, sip_offer_timer_expire, agent);
01739 return 0;
01740 }
01741
01742 static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent)
01743 {
01744 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01745
01746 AST_SCHED_DEL(sched, agent_pvt->offer_timer_id);
01747 return 0;
01748 }
01749
01750 static void sip_cc_agent_respond(struct ast_cc_agent *agent, enum ast_cc_agent_response_reason reason)
01751 {
01752 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01753
01754 sip_pvt_lock(agent_pvt->subscribe_pvt);
01755 ast_set_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
01756 if (reason == AST_CC_AGENT_RESPONSE_SUCCESS || !ast_strlen_zero(agent_pvt->notify_uri)) {
01757
01758
01759
01760
01761
01762
01763
01764
01765
01766
01767
01768
01769 transmit_response(agent_pvt->subscribe_pvt, "200 OK", &agent_pvt->subscribe_pvt->initreq);
01770 transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_QUEUED);
01771 } else {
01772 transmit_response(agent_pvt->subscribe_pvt, "500 Internal Error", &agent_pvt->subscribe_pvt->initreq);
01773 }
01774 sip_pvt_unlock(agent_pvt->subscribe_pvt);
01775 agent_pvt->is_available = TRUE;
01776 }
01777
01778 static int sip_cc_agent_status_request(struct ast_cc_agent *agent)
01779 {
01780 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01781 enum ast_device_state state = agent_pvt->is_available ? AST_DEVICE_NOT_INUSE : AST_DEVICE_INUSE;
01782 return ast_cc_agent_status_response(agent->core_id, state);
01783 }
01784
01785 static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent)
01786 {
01787
01788
01789
01790
01791 return 0;
01792 }
01793
01794 static int sip_cc_agent_recall(struct ast_cc_agent *agent)
01795 {
01796 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01797
01798
01799
01800
01801 if (!agent_pvt->is_available) {
01802 return ast_cc_agent_caller_busy(agent->core_id, "Caller %s is busy, reporting to the core",
01803 agent->device_name);
01804 }
01805
01806
01807
01808 sip_pvt_lock(agent_pvt->subscribe_pvt);
01809 transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_READY);
01810 sip_pvt_unlock(agent_pvt->subscribe_pvt);
01811 return 0;
01812 }
01813
01814 static void sip_cc_agent_destructor(struct ast_cc_agent *agent)
01815 {
01816 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01817
01818 if (!agent_pvt) {
01819
01820 return;
01821 }
01822
01823 sip_cc_agent_stop_offer_timer(agent);
01824 if (agent_pvt->subscribe_pvt) {
01825 sip_pvt_lock(agent_pvt->subscribe_pvt);
01826 if (!ast_test_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
01827
01828
01829
01830 transmit_response(agent_pvt->subscribe_pvt, "500 Internal Server Error", &agent_pvt->subscribe_pvt->initreq);
01831 }
01832 sip_pvt_unlock(agent_pvt->subscribe_pvt);
01833 agent_pvt->subscribe_pvt = dialog_unref(agent_pvt->subscribe_pvt, "SIP CC agent destructor: Remove ref to subscription");
01834 }
01835 ast_free(agent_pvt);
01836 }
01837
01838 struct ao2_container *sip_monitor_instances;
01839
01840 static int sip_monitor_instance_hash_fn(const void *obj, const int flags)
01841 {
01842 const struct sip_monitor_instance *monitor_instance = obj;
01843 return monitor_instance->core_id;
01844 }
01845
01846 static int sip_monitor_instance_cmp_fn(void *obj, void *arg, int flags)
01847 {
01848 struct sip_monitor_instance *monitor_instance1 = obj;
01849 struct sip_monitor_instance *monitor_instance2 = arg;
01850
01851 return monitor_instance1->core_id == monitor_instance2->core_id ? CMP_MATCH | CMP_STOP : 0;
01852 }
01853
01854 static void sip_monitor_instance_destructor(void *data)
01855 {
01856 struct sip_monitor_instance *monitor_instance = data;
01857 if (monitor_instance->subscription_pvt) {
01858 sip_pvt_lock(monitor_instance->subscription_pvt);
01859 monitor_instance->subscription_pvt->expiry = 0;
01860 transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 0, monitor_instance->subscribe_uri);
01861 sip_pvt_unlock(monitor_instance->subscription_pvt);
01862 dialog_unref(monitor_instance->subscription_pvt, "Unref monitor instance ref of subscription pvt");
01863 }
01864 if (monitor_instance->suspension_entry) {
01865 monitor_instance->suspension_entry->body[0] = '\0';
01866 transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_REMOVE ,monitor_instance->notify_uri);
01867 ao2_t_ref(monitor_instance->suspension_entry, -1, "Decrementing suspension entry refcount in sip_monitor_instance_destructor");
01868 }
01869 ast_string_field_free_memory(monitor_instance);
01870 }
01871
01872 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)
01873 {
01874 struct sip_monitor_instance *monitor_instance = ao2_alloc(sizeof(*monitor_instance), sip_monitor_instance_destructor);
01875
01876 if (!monitor_instance) {
01877 return NULL;
01878 }
01879
01880 if (ast_string_field_init(monitor_instance, 256)) {
01881 ao2_ref(monitor_instance, -1);
01882 return NULL;
01883 }
01884
01885 ast_string_field_set(monitor_instance, subscribe_uri, subscribe_uri);
01886 ast_string_field_set(monitor_instance, peername, peername);
01887 ast_string_field_set(monitor_instance, device_name, device_name);
01888 monitor_instance->core_id = core_id;
01889 ao2_link(sip_monitor_instances, monitor_instance);
01890 return monitor_instance;
01891 }
01892
01893 static int find_sip_monitor_instance_by_subscription_pvt(void *obj, void *arg, int flags)
01894 {
01895 struct sip_monitor_instance *monitor_instance = obj;
01896 return monitor_instance->subscription_pvt == arg ? CMP_MATCH | CMP_STOP : 0;
01897 }
01898
01899 static int find_sip_monitor_instance_by_suspension_entry(void *obj, void *arg, int flags)
01900 {
01901 struct sip_monitor_instance *monitor_instance = obj;
01902 return monitor_instance->suspension_entry == arg ? CMP_MATCH | CMP_STOP : 0;
01903 }
01904
01905 static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id);
01906 static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor);
01907 static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor);
01908 static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id);
01909 static void sip_cc_monitor_destructor(void *private_data);
01910
01911 static struct ast_cc_monitor_callbacks sip_cc_monitor_callbacks = {
01912 .type = "SIP",
01913 .request_cc = sip_cc_monitor_request_cc,
01914 .suspend = sip_cc_monitor_suspend,
01915 .unsuspend = sip_cc_monitor_unsuspend,
01916 .cancel_available_timer = sip_cc_monitor_cancel_available_timer,
01917 .destructor = sip_cc_monitor_destructor,
01918 };
01919
01920 static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id)
01921 {
01922 struct sip_monitor_instance *monitor_instance = monitor->private_data;
01923 enum ast_cc_service_type service = monitor->service_offered;
01924 int when;
01925
01926 if (!monitor_instance) {
01927 return -1;
01928 }
01929
01930 if (!(monitor_instance->subscription_pvt = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL))) {
01931 return -1;
01932 }
01933
01934 when = service == AST_CC_CCBS ? ast_get_ccbs_available_timer(monitor->interface->config_params) :
01935 ast_get_ccnr_available_timer(monitor->interface->config_params);
01936
01937 sip_pvt_lock(monitor_instance->subscription_pvt);
01938 ast_set_flag(&monitor_instance->subscription_pvt->flags[0], SIP_OUTGOING);
01939 create_addr(monitor_instance->subscription_pvt, monitor_instance->peername, 0, 1);
01940 ast_sip_ouraddrfor(&monitor_instance->subscription_pvt->sa, &monitor_instance->subscription_pvt->ourip, monitor_instance->subscription_pvt);
01941 monitor_instance->subscription_pvt->subscribed = CALL_COMPLETION;
01942 monitor_instance->subscription_pvt->expiry = when;
01943
01944 transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 2, monitor_instance->subscribe_uri);
01945 sip_pvt_unlock(monitor_instance->subscription_pvt);
01946
01947 ao2_t_ref(monitor, +1, "Adding a ref to the monitor for the scheduler");
01948 *available_timer_id = ast_sched_add(sched, when * 1000, ast_cc_available_timer_expire, monitor);
01949 return 0;
01950 }
01951
01952 static int construct_pidf_body(enum sip_cc_publish_state state, char *pidf_body, size_t size, const char *presentity)
01953 {
01954 struct ast_str *body = ast_str_alloca(size);
01955 char tuple_id[32];
01956
01957 generate_random_string(tuple_id, sizeof(tuple_id));
01958
01959
01960
01961
01962 ast_str_append(&body, 0, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
01963
01964
01965
01966
01967
01968
01969 ast_str_append(&body, 0, "<presence xmlns=\"urn:ietf:params:xml:ns:pidf\" entity=\"%s\">\n", presentity);
01970 ast_str_append(&body, 0, "<tuple id=\"%s\">\n", tuple_id);
01971 ast_str_append(&body, 0, "<status><basic>%s</basic></status>\n", state == CC_OPEN ? "open" : "closed");
01972 ast_str_append(&body, 0, "</tuple>\n");
01973 ast_str_append(&body, 0, "</presence>\n");
01974 ast_copy_string(pidf_body, ast_str_buffer(body), size);
01975 return 0;
01976 }
01977
01978 static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor)
01979 {
01980 struct sip_monitor_instance *monitor_instance = monitor->private_data;
01981 enum sip_publish_type publish_type;
01982 struct cc_epa_entry *cc_entry;
01983
01984 if (!monitor_instance) {
01985 return -1;
01986 }
01987
01988 if (!monitor_instance->suspension_entry) {
01989
01990 if (!(monitor_instance->suspension_entry = create_epa_entry("call-completion", monitor_instance->peername))) {
01991 ast_log(LOG_WARNING, "Unable to allocate sip EPA entry for call-completion\n");
01992 ao2_ref(monitor_instance, -1);
01993 return -1;
01994 }
01995 if (!(cc_entry = ast_calloc(1, sizeof(*cc_entry)))) {
01996 ast_log(LOG_WARNING, "Unable to allocate space for instance data of EPA entry for call-completion\n");
01997 ao2_ref(monitor_instance, -1);
01998 return -1;
01999 }
02000 cc_entry->core_id = monitor->core_id;
02001 monitor_instance->suspension_entry->instance_data = cc_entry;
02002 publish_type = SIP_PUBLISH_INITIAL;
02003 } else {
02004 publish_type = SIP_PUBLISH_MODIFY;
02005 cc_entry = monitor_instance->suspension_entry->instance_data;
02006 }
02007
02008 cc_entry->current_state = CC_CLOSED;
02009
02010 if (ast_strlen_zero(monitor_instance->notify_uri)) {
02011
02012
02013
02014
02015
02016
02017
02018
02019
02020
02021
02022
02023 return 0;
02024 }
02025 construct_pidf_body(CC_CLOSED, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
02026 return transmit_publish(monitor_instance->suspension_entry, publish_type, monitor_instance->notify_uri);
02027 }
02028
02029 static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor)
02030 {
02031 struct sip_monitor_instance *monitor_instance = monitor->private_data;
02032 struct cc_epa_entry *cc_entry;
02033
02034 if (!monitor_instance) {
02035 return -1;
02036 }
02037
02038 ast_assert(monitor_instance->suspension_entry != NULL);
02039
02040 cc_entry = monitor_instance->suspension_entry->instance_data;
02041 cc_entry->current_state = CC_OPEN;
02042 if (ast_strlen_zero(monitor_instance->notify_uri)) {
02043
02044
02045
02046
02047 return 0;
02048 }
02049 construct_pidf_body(CC_OPEN, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
02050 return transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_MODIFY, monitor_instance->notify_uri);
02051 }
02052
02053 static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id)
02054 {
02055 if (*sched_id != -1) {
02056 AST_SCHED_DEL(sched, *sched_id);
02057 ao2_t_ref(monitor, -1, "Removing scheduler's reference to the monitor");
02058 }
02059 return 0;
02060 }
02061
02062 static void sip_cc_monitor_destructor(void *private_data)
02063 {
02064 struct sip_monitor_instance *monitor_instance = private_data;
02065 ao2_unlink(sip_monitor_instances, monitor_instance);
02066 ast_module_unref(ast_module_info->self);
02067 }
02068
02069 static int sip_get_cc_information(struct sip_request *req, char *subscribe_uri, size_t size, enum ast_cc_service_type *service)
02070 {
02071 char *call_info = ast_strdupa(get_header(req, "Call-Info"));
02072 char *uri;
02073 char *purpose;
02074 char *service_str;
02075 static const char cc_purpose[] = "purpose=call-completion";
02076 static const int cc_purpose_len = sizeof(cc_purpose) - 1;
02077
02078 if (ast_strlen_zero(call_info)) {
02079
02080 return -1;
02081 }
02082
02083 uri = strsep(&call_info, ";");
02084
02085 while ((purpose = strsep(&call_info, ";"))) {
02086 if (!strncmp(purpose, cc_purpose, cc_purpose_len)) {
02087 break;
02088 }
02089 }
02090 if (!purpose) {
02091
02092 return -1;
02093 }
02094
02095
02096 while ((service_str = strsep(&call_info, ";"))) {
02097 if (!strncmp(service_str, "m=", 2)) {
02098 break;
02099 }
02100 }
02101 if (!service_str) {
02102
02103
02104
02105 service_str = "BS";
02106 } else {
02107
02108
02109
02110 strsep(&service_str, "=");
02111 }
02112
02113 if ((*service = service_string_to_service_type(service_str)) == AST_CC_NONE) {
02114
02115 return -1;
02116 }
02117
02118 ast_copy_string(subscribe_uri, get_in_brackets(uri), size);
02119
02120 return 0;
02121 }
02122
02123
02124
02125
02126
02127
02128
02129
02130
02131
02132
02133
02134
02135
02136
02137
02138
02139
02140 static void sip_handle_cc(struct sip_pvt *pvt, struct sip_request *req, enum ast_cc_service_type service)
02141 {
02142 enum ast_cc_monitor_policies monitor_policy = ast_get_cc_monitor_policy(pvt->cc_params);
02143 int core_id;
02144 char interface_name[AST_CHANNEL_NAME];
02145
02146 if (monitor_policy == AST_CC_MONITOR_NEVER) {
02147
02148 return;
02149 }
02150
02151 if ((core_id = ast_cc_get_current_core_id(pvt->owner)) == -1) {
02152
02153 return;
02154 }
02155
02156 ast_channel_get_device_name(pvt->owner, interface_name, sizeof(interface_name));
02157
02158 if (monitor_policy == AST_CC_MONITOR_ALWAYS || monitor_policy == AST_CC_MONITOR_NATIVE) {
02159 char subscribe_uri[SIPBUFSIZE];
02160 char device_name[AST_CHANNEL_NAME];
02161 enum ast_cc_service_type offered_service;
02162 struct sip_monitor_instance *monitor_instance;
02163 if (sip_get_cc_information(req, subscribe_uri, sizeof(subscribe_uri), &offered_service)) {
02164
02165
02166
02167
02168 goto generic;
02169 }
02170 ast_channel_get_device_name(pvt->owner, device_name, sizeof(device_name));
02171 if (!(monitor_instance = sip_monitor_instance_init(core_id, subscribe_uri, pvt->peername, device_name))) {
02172
02173 goto generic;
02174 }
02175
02176
02177
02178
02179 ast_module_ref(ast_module_info->self);
02180 ast_queue_cc_frame(pvt->owner, "SIP", pvt->dialstring, offered_service, monitor_instance);
02181 ao2_ref(monitor_instance, -1);
02182 return;
02183 }
02184
02185 generic:
02186 if (monitor_policy == AST_CC_MONITOR_GENERIC || monitor_policy == AST_CC_MONITOR_ALWAYS) {
02187 ast_queue_cc_frame(pvt->owner, AST_CC_GENERIC_MONITOR_TYPE, interface_name, service, NULL);
02188 }
02189 }
02190
02191
02192 static struct ast_tls_config sip_tls_cfg;
02193
02194
02195 static struct ast_tls_config default_tls_cfg;
02196
02197
02198 static struct ast_tcptls_session_args sip_tcp_desc = {
02199 .accept_fd = -1,
02200 .master = AST_PTHREADT_NULL,
02201 .tls_cfg = NULL,
02202 .poll_timeout = -1,
02203 .name = "SIP TCP server",
02204 .accept_fn = ast_tcptls_server_root,
02205 .worker_fn = sip_tcp_worker_fn,
02206 };
02207
02208
02209 static struct ast_tcptls_session_args sip_tls_desc = {
02210 .accept_fd = -1,
02211 .master = AST_PTHREADT_NULL,
02212 .tls_cfg = &sip_tls_cfg,
02213 .poll_timeout = -1,
02214 .name = "SIP TLS server",
02215 .accept_fn = ast_tcptls_server_root,
02216 .worker_fn = sip_tcp_worker_fn,
02217 };
02218
02219
02220
02221 #define append_history(p, event, fmt , args... ) append_history_full(p, "%-15s " fmt, event, ## args)
02222
02223 struct sip_pvt *dialog_ref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
02224 {
02225 if (p)
02226 #ifdef REF_DEBUG
02227 __ao2_ref_debug(p, 1, tag, file, line, func);
02228 #else
02229 ao2_ref(p, 1);
02230 #endif
02231 else
02232 ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
02233 return p;
02234 }
02235
02236 struct sip_pvt *dialog_unref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
02237 {
02238 if (p)
02239 #ifdef REF_DEBUG
02240 __ao2_ref_debug(p, -1, tag, file, line, func);
02241 #else
02242 ao2_ref(p, -1);
02243 #endif
02244 return NULL;
02245 }
02246
02247
02248
02249
02250 static const char *map_x_s(const struct _map_x_s *table, int x, const char *errorstring)
02251 {
02252 const struct _map_x_s *cur;
02253
02254 for (cur = table; cur->s; cur++)
02255 if (cur->x == x)
02256 return cur->s;
02257 return errorstring;
02258 }
02259
02260
02261
02262
02263 static int map_s_x(const struct _map_x_s *table, const char *s, int errorvalue)
02264 {
02265 const struct _map_x_s *cur;
02266
02267 for (cur = table; cur->s; cur++)
02268 if (!strcasecmp(cur->s, s))
02269 return cur->x;
02270 return errorvalue;
02271 }
02272
02273 static enum AST_REDIRECTING_REASON sip_reason_str_to_code(const char *text)
02274 {
02275 enum AST_REDIRECTING_REASON ast = AST_REDIRECTING_REASON_UNKNOWN;
02276 int i;
02277
02278 for (i = 0; i < ARRAY_LEN(sip_reason_table); ++i) {
02279 if (!strcasecmp(text, sip_reason_table[i].text)) {
02280 ast = sip_reason_table[i].code;
02281 break;
02282 }
02283 }
02284
02285 return ast;
02286 }
02287
02288 static const char *sip_reason_code_to_str(enum AST_REDIRECTING_REASON code)
02289 {
02290 if (code >= 0 && code < ARRAY_LEN(sip_reason_table)) {
02291 return sip_reason_table[code].text;
02292 }
02293
02294 return "unknown";
02295 }
02296
02297
02298
02299
02300
02301
02302
02303
02304 #define check_request_transport(peer, tmpl) ({ \
02305 int ret = 0; \
02306 if (peer->socket.type == tmpl->socket.type) \
02307 ; \
02308 else if (!(peer->transports & tmpl->socket.type)) {\
02309 ast_log(LOG_ERROR, \
02310 "'%s' is not a valid transport for '%s'. we only use '%s'! ending call.\n", \
02311 get_transport(tmpl->socket.type), peer->name, get_transport_list(peer->transports) \
02312 ); \
02313 ret = 1; \
02314 } else if (peer->socket.type & SIP_TRANSPORT_TLS) { \
02315 ast_log(LOG_WARNING, \
02316 "peer '%s' HAS NOT USED (OR SWITCHED TO) TLS in favor of '%s' (but this was allowed in sip.conf)!\n", \
02317 peer->name, get_transport(tmpl->socket.type) \
02318 ); \
02319 } else { \
02320 ast_debug(1, \
02321 "peer '%s' has contacted us over %s even though we prefer %s.\n", \
02322 peer->name, get_transport(tmpl->socket.type), get_transport(peer->socket.type) \
02323 ); \
02324 }\
02325 (ret); \
02326 })
02327
02328
02329
02330
02331 static struct ast_variable *copy_vars(struct ast_variable *src)
02332 {
02333 struct ast_variable *res = NULL, *tmp, *v = NULL;
02334
02335 for (v = src ; v ; v = v->next) {
02336 if ((tmp = ast_variable_new(v->name, v->value, v->file))) {
02337 tmp->next = res;
02338 res = tmp;
02339 }
02340 }
02341 return res;
02342 }
02343
02344 static void tcptls_packet_destructor(void *obj)
02345 {
02346 struct tcptls_packet *packet = obj;
02347
02348 ast_free(packet->data);
02349 }
02350
02351 static void sip_tcptls_client_args_destructor(void *obj)
02352 {
02353 struct ast_tcptls_session_args *args = obj;
02354 if (args->tls_cfg) {
02355 ast_free(args->tls_cfg->certfile);
02356 ast_free(args->tls_cfg->pvtfile);
02357 ast_free(args->tls_cfg->cipher);
02358 ast_free(args->tls_cfg->cafile);
02359 ast_free(args->tls_cfg->capath);
02360
02361 ast_ssl_teardown(args->tls_cfg);
02362 }
02363 ast_free(args->tls_cfg);
02364 ast_free((char *) args->name);
02365 }
02366
02367 static void sip_threadinfo_destructor(void *obj)
02368 {
02369 struct sip_threadinfo *th = obj;
02370 struct tcptls_packet *packet;
02371 if (th->alert_pipe[1] > -1) {
02372 close(th->alert_pipe[0]);
02373 }
02374 if (th->alert_pipe[1] > -1) {
02375 close(th->alert_pipe[1]);
02376 }
02377 th->alert_pipe[0] = th->alert_pipe[1] = -1;
02378
02379 while ((packet = AST_LIST_REMOVE_HEAD(&th->packet_q, entry))) {
02380 ao2_t_ref(packet, -1, "thread destruction, removing packet from frame queue");
02381 }
02382
02383 if (th->tcptls_session) {
02384 ao2_t_ref(th->tcptls_session, -1, "remove tcptls_session for sip_threadinfo object");
02385 }
02386 }
02387
02388
02389 static struct sip_threadinfo *sip_threadinfo_create(struct ast_tcptls_session_instance *tcptls_session, int transport)
02390 {
02391 struct sip_threadinfo *th;
02392
02393 if (!tcptls_session || !(th = ao2_alloc(sizeof(*th), sip_threadinfo_destructor))) {
02394 return NULL;
02395 }
02396
02397 th->alert_pipe[0] = th->alert_pipe[1] = -1;
02398
02399 if (pipe(th->alert_pipe) == -1) {
02400 ao2_t_ref(th, -1, "Failed to open alert pipe on sip_threadinfo");
02401 ast_log(LOG_ERROR, "Could not create sip alert pipe in tcptls thread, error %s\n", strerror(errno));
02402 return NULL;
02403 }
02404 ao2_t_ref(tcptls_session, +1, "tcptls_session ref for sip_threadinfo object");
02405 th->tcptls_session = tcptls_session;
02406 th->type = transport ? transport : (tcptls_session->ssl ? SIP_TRANSPORT_TLS: SIP_TRANSPORT_TCP);
02407 ao2_t_link(threadt, th, "Adding new tcptls helper thread");
02408 ao2_t_ref(th, -1, "Decrementing threadinfo ref from alloc, only table ref remains");
02409 return th;
02410 }
02411
02412
02413 static int sip_tcptls_write(struct ast_tcptls_session_instance *tcptls_session, const void *buf, size_t len)
02414 {
02415 int res = len;
02416 struct sip_threadinfo *th = NULL;
02417 struct tcptls_packet *packet = NULL;
02418 struct sip_threadinfo tmp = {
02419 .tcptls_session = tcptls_session,
02420 };
02421 enum sip_tcptls_alert alert = TCPTLS_ALERT_DATA;
02422
02423 if (!tcptls_session) {
02424 return XMIT_ERROR;
02425 }
02426
02427 ast_mutex_lock(&tcptls_session->lock);
02428
02429 if ((tcptls_session->fd == -1) ||
02430 !(th = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread")) ||
02431 !(packet = ao2_alloc(sizeof(*packet), tcptls_packet_destructor)) ||
02432 !(packet->data = ast_str_create(len))) {
02433 goto tcptls_write_setup_error;
02434 }
02435
02436
02437 ast_str_set(&packet->data, 0, "%s", (char *) buf);
02438 packet->len = len;
02439
02440
02441
02442
02443 ao2_lock(th);
02444 if (write(th->alert_pipe[1], &alert, sizeof(alert)) == -1) {
02445 ast_log(LOG_ERROR, "write() to alert pipe failed: %s\n", strerror(errno));
02446 ao2_t_ref(packet, -1, "could not write to alert pipe, remove packet");
02447 packet = NULL;
02448 res = XMIT_ERROR;
02449 } else {
02450 AST_LIST_INSERT_TAIL(&th->packet_q, packet, entry);
02451 }
02452 ao2_unlock(th);
02453
02454 ast_mutex_unlock(&tcptls_session->lock);
02455 ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo object after finding it");
02456 return res;
02457
02458 tcptls_write_setup_error:
02459 if (th) {
02460 ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo obj, could not create packet");
02461 }
02462 if (packet) {
02463 ao2_t_ref(packet, -1, "could not allocate packet's data");
02464 }
02465 ast_mutex_unlock(&tcptls_session->lock);
02466
02467 return XMIT_ERROR;
02468 }
02469
02470
02471 static void *sip_tcp_worker_fn(void *data)
02472 {
02473 struct ast_tcptls_session_instance *tcptls_session = data;
02474
02475 return _sip_tcp_helper_thread(tcptls_session);
02476 }
02477
02478
02479
02480
02481
02482
02483
02484
02485 static int sip_check_authtimeout(time_t start)
02486 {
02487 int timeout;
02488 time_t now;
02489 if(time(&now) == -1) {
02490 ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
02491 return -1;
02492 }
02493
02494 timeout = (authtimeout - (now - start)) * 1000;
02495 if (timeout < 0) {
02496
02497 return 0;
02498 }
02499
02500 return timeout;
02501 }
02502
02503
02504
02505
02506 static void *_sip_tcp_helper_thread(struct ast_tcptls_session_instance *tcptls_session)
02507 {
02508 int res, cl, timeout = -1, authenticated = 0, flags, after_poll = 0, need_poll = 1;
02509 time_t start;
02510 struct sip_request req = { 0, } , reqcpy = { 0, };
02511 struct sip_threadinfo *me = NULL;
02512 char buf[1024] = "";
02513 struct pollfd fds[2] = { { 0 }, { 0 }, };
02514 struct ast_tcptls_session_args *ca = NULL;
02515
02516
02517
02518
02519
02520
02521
02522
02523
02524
02525
02526
02527 if (!tcptls_session->client) {
02528 if (ast_atomic_fetchadd_int(&unauth_sessions, +1) >= authlimit) {
02529
02530 goto cleanup;
02531 }
02532
02533 if ((flags = fcntl(tcptls_session->fd, F_GETFL)) == -1) {
02534 ast_log(LOG_ERROR, "error setting socket to non blocking mode, fcntl() failed: %s\n", strerror(errno));
02535 goto cleanup;
02536 }
02537
02538 flags |= O_NONBLOCK;
02539 if (fcntl(tcptls_session->fd, F_SETFL, flags) == -1) {
02540 ast_log(LOG_ERROR, "error setting socket to non blocking mode, fcntl() failed: %s\n", strerror(errno));
02541 goto cleanup;
02542 }
02543
02544 if (!(me = sip_threadinfo_create(tcptls_session, tcptls_session->ssl ? SIP_TRANSPORT_TLS : SIP_TRANSPORT_TCP))) {
02545 goto cleanup;
02546 }
02547 ao2_t_ref(me, +1, "Adding threadinfo ref for tcp_helper_thread");
02548 } else {
02549 struct sip_threadinfo tmp = {
02550 .tcptls_session = tcptls_session,
02551 };
02552
02553 if ((!(ca = tcptls_session->parent)) ||
02554 (!(me = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread"))) ||
02555 (!(tcptls_session = ast_tcptls_client_start(tcptls_session)))) {
02556 goto cleanup;
02557 }
02558 }
02559
02560 flags = 1;
02561 if (setsockopt(tcptls_session->fd, SOL_SOCKET, SO_KEEPALIVE, &flags, sizeof(flags))) {
02562 ast_log(LOG_ERROR, "error enabling TCP keep-alives on sip socket: %s\n", strerror(errno));
02563 goto cleanup;
02564 }
02565
02566 me->threadid = pthread_self();
02567 ast_debug(2, "Starting thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");
02568
02569
02570 fds[0].fd = tcptls_session->fd;
02571 fds[1].fd = me->alert_pipe[0];
02572 fds[0].events = fds[1].events = POLLIN | POLLPRI;
02573
02574 if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
02575 goto cleanup;
02576 }
02577 if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET))) {
02578 goto cleanup;
02579 }
02580
02581 if(time(&start) == -1) {
02582 ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
02583 goto cleanup;
02584 }
02585
02586 for (;;) {
02587 struct ast_str *str_save;
02588
02589 if (!tcptls_session->client && req.authenticated && !authenticated) {
02590 authenticated = 1;
02591 ast_atomic_fetchadd_int(&unauth_sessions, -1);
02592 }
02593
02594
02595 if (!tcptls_session->client && !authenticated ) {
02596 if ((timeout = sip_check_authtimeout(start)) < 0) {
02597 goto cleanup;
02598 }
02599
02600 if (timeout == 0) {
02601 ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
02602 goto cleanup;
02603 }
02604 } else {
02605 timeout = -1;
02606 }
02607
02608 res = ast_poll(fds, 2, timeout);
02609 if (res < 0) {
02610 ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", tcptls_session->ssl ? "SSL": "TCP", res);
02611 goto cleanup;
02612 } else if (res == 0) {
02613
02614 ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
02615 goto cleanup;
02616 }
02617
02618
02619
02620 if (fds[0].revents) {
02621 after_poll = 1;
02622
02623 fds[0].revents = 0;
02624
02625
02626 str_save = req.data;
02627 memset(&req, 0, sizeof(req));
02628 req.data = str_save;
02629 ast_str_reset(req.data);
02630
02631 str_save = reqcpy.data;
02632 memset(&reqcpy, 0, sizeof(reqcpy));
02633 reqcpy.data = str_save;
02634 ast_str_reset(reqcpy.data);
02635
02636 memset(buf, 0, sizeof(buf));
02637
02638 if (tcptls_session->ssl) {
02639 set_socket_transport(&req.socket, SIP_TRANSPORT_TLS);
02640 req.socket.port = htons(ourport_tls);
02641 } else {
02642 set_socket_transport(&req.socket, SIP_TRANSPORT_TCP);
02643 req.socket.port = htons(ourport_tcp);
02644 }
02645 req.socket.fd = tcptls_session->fd;
02646
02647
02648 while (ast_str_strlen(req.data) < 4 || strncmp(REQ_OFFSET_TO_STR(&req, data->used - 4), "\r\n\r\n", 4)) {
02649 if (!tcptls_session->client && !authenticated ) {
02650 if ((timeout = sip_check_authtimeout(start)) < 0) {
02651 goto cleanup;
02652 }
02653
02654 if (timeout == 0) {
02655 ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
02656 goto cleanup;
02657 }
02658 } else {
02659 timeout = -1;
02660 }
02661
02662
02663
02664
02665 if (!tcptls_session->ssl || need_poll) {
02666 need_poll = 0;
02667 after_poll = 1;
02668 res = ast_wait_for_input(tcptls_session->fd, timeout);
02669 if (res < 0) {
02670 ast_debug(2, "SIP TCP server :: ast_wait_for_input returned %d\n", res);
02671 goto cleanup;
02672 } else if (res == 0) {
02673
02674 ast_debug(2, "SIP TCP server timed out\n");
02675 goto cleanup;
02676 }
02677 }
02678
02679 ast_mutex_lock(&tcptls_session->lock);
02680 if (!fgets(buf, sizeof(buf), tcptls_session->f)) {
02681 ast_mutex_unlock(&tcptls_session->lock);
02682 if (after_poll) {
02683 goto cleanup;
02684 } else {
02685 need_poll = 1;
02686 continue;
02687 }
02688 }
02689 ast_mutex_unlock(&tcptls_session->lock);
02690 after_poll = 0;
02691 if (me->stop) {
02692 goto cleanup;
02693 }
02694 ast_str_append(&req.data, 0, "%s", buf);
02695 }
02696 copy_request(&reqcpy, &req);
02697 parse_request(&reqcpy);
02698
02699 if (sscanf(get_header(&reqcpy, "Content-Length"), "%30d", &cl)) {
02700 while (cl > 0) {
02701 size_t bytes_read;
02702 if (!tcptls_session->client && !authenticated ) {
02703 if ((timeout = sip_check_authtimeout(start)) < 0) {
02704 goto cleanup;
02705 }
02706
02707 if (timeout == 0) {
02708 ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
02709 goto cleanup;
02710 }
02711 } else {
02712 timeout = -1;
02713 }
02714
02715 if (!tcptls_session->ssl || need_poll) {
02716 need_poll = 0;
02717 after_poll = 1;
02718 res = ast_wait_for_input(tcptls_session->fd, timeout);
02719 if (res < 0) {
02720 ast_debug(2, "SIP TCP server :: ast_wait_for_input returned %d\n", res);
02721 goto cleanup;
02722 } else if (res == 0) {
02723
02724 ast_debug(2, "SIP TCP server timed out\n");
02725 goto cleanup;
02726 }
02727 }
02728
02729 ast_mutex_lock(&tcptls_session->lock);
02730 if (!(bytes_read = fread(buf, 1, MIN(sizeof(buf) - 1, cl), tcptls_session->f))) {
02731 ast_mutex_unlock(&tcptls_session->lock);
02732 if (after_poll) {
02733 goto cleanup;
02734 } else {
02735 need_poll = 1;
02736 continue;
02737 }
02738 }
02739 buf[bytes_read] = '\0';
02740 ast_mutex_unlock(&tcptls_session->lock);
02741 after_poll = 0;
02742 if (me->stop) {
02743 goto cleanup;
02744 }
02745 cl -= strlen(buf);
02746 ast_str_append(&req.data, 0, "%s", buf);
02747 }
02748 }
02749
02750
02751
02752 req.socket.tcptls_session = tcptls_session;
02753 handle_request_do(&req, &tcptls_session->remote_address);
02754 }
02755
02756 if (fds[1].revents) {
02757 enum sip_tcptls_alert alert;
02758 struct tcptls_packet *packet;
02759
02760 fds[1].revents = 0;
02761
02762 if (read(me->alert_pipe[0], &alert, sizeof(alert)) == -1) {
02763 ast_log(LOG_ERROR, "read() failed: %s\n", strerror(errno));
02764 continue;
02765 }
02766
02767 switch (alert) {
02768 case TCPTLS_ALERT_STOP:
02769 goto cleanup;
02770 case TCPTLS_ALERT_DATA:
02771 ao2_lock(me);
02772 if (!(packet = AST_LIST_REMOVE_HEAD(&me->packet_q, entry))) {
02773 ast_log(LOG_WARNING, "TCPTLS thread alert_pipe indicated packet should be sent, but frame_q is empty\n");
02774 }
02775 ao2_unlock(me);
02776
02777 if (packet) {
02778 if (ast_tcptls_server_write(tcptls_session, ast_str_buffer(packet->data), packet->len) == -1) {
02779 ast_log(LOG_WARNING, "Failure to write to tcp/tls socket\n");
02780 }
02781 ao2_t_ref(packet, -1, "tcptls packet sent, this is no longer needed");
02782 }
02783 break;
02784 default:
02785 ast_log(LOG_ERROR, "Unknown tcptls thread alert '%d'\n", alert);
02786 }
02787 }
02788 }
02789
02790 ast_debug(2, "Shutting down thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");
02791
02792 cleanup:
02793 if (tcptls_session && !tcptls_session->client && !authenticated) {
02794 ast_atomic_fetchadd_int(&unauth_sessions, -1);
02795 }
02796
02797 if (me) {
02798 ao2_t_unlink(threadt, me, "Removing tcptls helper thread, thread is closing");
02799 ao2_t_ref(me, -1, "Removing tcp_helper_threads threadinfo ref");
02800 }
02801 deinit_req(&reqcpy);
02802 deinit_req(&req);
02803
02804
02805 if (ca) {
02806 ao2_t_ref(ca, -1, "closing tcptls thread, getting rid of client tcptls_session arguments");
02807 }
02808
02809 if (tcptls_session) {
02810 ast_mutex_lock(&tcptls_session->lock);
02811 ast_tcptls_close_session_file(tcptls_session);
02812 tcptls_session->parent = NULL;
02813 ast_mutex_unlock(&tcptls_session->lock);
02814
02815 ao2_ref(tcptls_session, -1);
02816 tcptls_session = NULL;
02817 }
02818 return NULL;
02819 }
02820
02821 #ifdef REF_DEBUG
02822 #define ref_peer(arg1,arg2) _ref_peer((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
02823 #define unref_peer(arg1,arg2) _unref_peer((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
02824 static struct sip_peer *_ref_peer(struct sip_peer *peer, char *tag, char *file, int line, const char *func)
02825 {
02826 if (peer)
02827 __ao2_ref_debug(peer, 1, tag, file, line, func);
02828 else
02829 ast_log(LOG_ERROR, "Attempt to Ref a null peer pointer\n");
02830 return peer;
02831 }
02832
02833 static struct sip_peer *_unref_peer(struct sip_peer *peer, char *tag, char *file, int line, const char *func)
02834 {
02835 if (peer)
02836 __ao2_ref_debug(peer, -1, tag, file, line, func);
02837 return NULL;
02838 }
02839 #else
02840
02841
02842
02843
02844
02845 static void *unref_peer(struct sip_peer *peer, char *tag)
02846 {
02847 ao2_t_ref(peer, -1, tag);
02848 return NULL;
02849 }
02850
02851 static struct sip_peer *ref_peer(struct sip_peer *peer, char *tag)
02852 {
02853 ao2_t_ref(peer, 1, tag);
02854 return peer;
02855 }
02856 #endif
02857
02858 static void peer_sched_cleanup(struct sip_peer *peer)
02859 {
02860 if (peer->pokeexpire != -1) {
02861 AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
02862 unref_peer(peer, "removing poke peer ref"));
02863 }
02864 if (peer->expire != -1) {
02865 AST_SCHED_DEL_UNREF(sched, peer->expire,
02866 unref_peer(peer, "remove register expire ref"));
02867 }
02868 }
02869
02870 typedef enum {
02871 SIP_PEERS_MARKED,
02872 SIP_PEERS_ALL,
02873 } peer_unlink_flag_t;
02874
02875
02876
02877 static int match_and_cleanup_peer_sched(void *peerobj, void *arg, int flags)
02878 {
02879 struct sip_peer *peer = peerobj;
02880 peer_unlink_flag_t which = *(peer_unlink_flag_t *)arg;
02881
02882 if (which == SIP_PEERS_ALL || peer->the_mark) {
02883 peer_sched_cleanup(peer);
02884 if (peer->dnsmgr) {
02885 ast_dnsmgr_release(peer->dnsmgr);
02886 peer->dnsmgr = NULL;
02887 unref_peer(peer, "Release peer from dnsmgr");
02888 }
02889 return CMP_MATCH;
02890 }
02891 return 0;
02892 }
02893
02894 static void unlink_peers_from_tables(peer_unlink_flag_t flag)
02895 {
02896 ao2_t_callback(peers, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE,
02897 match_and_cleanup_peer_sched, &flag, "initiating callback to remove marked peers");
02898 ao2_t_callback(peers_by_ip, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE,
02899 match_and_cleanup_peer_sched, &flag, "initiating callback to remove marked peers");
02900 }
02901
02902
02903 static void unlink_marked_peers_from_tables(void)
02904 {
02905 unlink_peers_from_tables(SIP_PEERS_MARKED);
02906 }
02907
02908 static void unlink_all_peers_from_tables(void)
02909 {
02910 unlink_peers_from_tables(SIP_PEERS_ALL);
02911 }
02912
02913
02914 static void unlink_peer_from_tables(struct sip_peer *peer)
02915 {
02916 ao2_t_unlink(peers, peer, "ao2_unlink of peer from peers table");
02917 if (!ast_sockaddr_isnull(&peer->addr)) {
02918 ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
02919 }
02920 }
02921
02922
02923
02924
02925
02926
02927
02928
02929
02930
02931
02932
02933 static void ref_proxy(struct sip_pvt *pvt, struct sip_proxy *proxy)
02934 {
02935 struct sip_proxy *old_obproxy = pvt->outboundproxy;
02936
02937
02938
02939 if (proxy && proxy != &sip_cfg.outboundproxy) {
02940 ao2_ref(proxy, +1);
02941 }
02942 pvt->outboundproxy = proxy;
02943 if (old_obproxy && old_obproxy != &sip_cfg.outboundproxy) {
02944 ao2_ref(old_obproxy, -1);
02945 }
02946 }
02947
02948
02949
02950
02951
02952
02953
02954
02955 void dialog_unlink_all(struct sip_pvt *dialog)
02956 {
02957 struct sip_pkt *cp;
02958 struct ast_channel *owner;
02959
02960 dialog_ref(dialog, "Let's bump the count in the unlink so it doesn't accidentally become dead before we are done");
02961
02962 ao2_t_unlink(dialogs, dialog, "unlinking dialog via ao2_unlink");
02963
02964
02965 owner = sip_pvt_lock_full(dialog);
02966 if (owner) {
02967 ast_debug(1, "Detaching from channel %s\n", owner->name);
02968 owner->tech_pvt = dialog_unref(owner->tech_pvt, "resetting channel dialog ptr in unlink_all");
02969 ast_channel_unlock(owner);
02970 ast_channel_unref(owner);
02971 dialog->owner = NULL;
02972 }
02973 sip_pvt_unlock(dialog);
02974
02975 if (dialog->registry) {
02976 if (dialog->registry->call == dialog) {
02977 dialog->registry->call = dialog_unref(dialog->registry->call, "nulling out the registry's call dialog field in unlink_all");
02978 }
02979 dialog->registry = registry_unref(dialog->registry, "delete dialog->registry");
02980 }
02981 if (dialog->stateid != -1) {
02982 ast_extension_state_del(dialog->stateid, cb_extensionstate);
02983 dialog->stateid = -1;
02984 }
02985
02986 if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog) {
02987 dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
02988 }
02989 if (dialog->relatedpeer && dialog->relatedpeer->call == dialog) {
02990 dialog->relatedpeer->call = dialog_unref(dialog->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
02991 }
02992
02993
02994 while((cp = dialog->packets)) {
02995 dialog->packets = dialog->packets->next;
02996 AST_SCHED_DEL(sched, cp->retransid);
02997 dialog_unref(cp->owner, "remove all current packets in this dialog, and the pointer to the dialog too as part of __sip_destroy");
02998 if (cp->data) {
02999 ast_free(cp->data);
03000 }
03001 ast_free(cp);
03002 }
03003
03004 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"));
03005
03006 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"));
03007
03008 if (dialog->autokillid > -1) {
03009 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"));
03010 }
03011
03012 if (dialog->request_queue_sched_id > -1) {
03013 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"));
03014 }
03015
03016 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"));
03017
03018 if (dialog->t38id > -1) {
03019 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"));
03020 }
03021
03022 if (dialog->stimer) {
03023 stop_session_timer(dialog);
03024 }
03025
03026 dialog_unref(dialog, "Let's unbump the count in the unlink so the poor pvt can disappear if it is time");
03027 }
03028
03029 void *registry_unref(struct sip_registry *reg, char *tag)
03030 {
03031 ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount - 1);
03032 ASTOBJ_UNREF(reg, sip_registry_destroy);
03033 return NULL;
03034 }
03035
03036
03037 static struct sip_registry *registry_addref(struct sip_registry *reg, char *tag)
03038 {
03039 ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount + 1);
03040 return ASTOBJ_REF(reg);
03041 }
03042
03043
03044 static struct ast_udptl_protocol sip_udptl = {
03045 .type = "SIP",
03046 .get_udptl_info = sip_get_udptl_peer,
03047 .set_udptl_peer = sip_set_udptl_peer,
03048 };
03049
03050 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
03051 __attribute__((format(printf, 2, 3)));
03052
03053
03054
03055 static const char *referstatus2str(enum referstatus rstatus)
03056 {
03057 return map_x_s(referstatusstrings, rstatus, "");
03058 }
03059
03060 static inline void pvt_set_needdestroy(struct sip_pvt *pvt, const char *reason)
03061 {
03062 if (pvt->final_destruction_scheduled) {
03063 return;
03064 }
03065 append_history(pvt, "NeedDestroy", "Setting needdestroy because %s", reason);
03066 pvt->needdestroy = 1;
03067 }
03068
03069
03070
03071
03072 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
03073 {
03074 if (p->initreq.headers) {
03075 ast_debug(1, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
03076 } else {
03077 ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
03078 }
03079
03080 copy_request(&p->initreq, req);
03081 parse_request(&p->initreq);
03082 if (req->debug) {
03083 ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
03084 }
03085 }
03086
03087
03088 static void sip_alreadygone(struct sip_pvt *dialog)
03089 {
03090 ast_debug(3, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
03091 dialog->alreadygone = 1;
03092 }
03093
03094
03095 static int proxy_update(struct sip_proxy *proxy)
03096 {
03097
03098
03099 if (!ast_sockaddr_parse(&proxy->ip, proxy->name, 0)) {
03100
03101
03102 proxy->ip.ss.ss_family = get_address_family_filter(SIP_TRANSPORT_UDP);
03103 if (ast_get_ip_or_srv(&proxy->ip, proxy->name, sip_cfg.srvlookup ? "_sip._udp" : NULL) < 0) {
03104 ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
03105 return FALSE;
03106 }
03107
03108 }
03109
03110 ast_sockaddr_set_port(&proxy->ip, proxy->port);
03111
03112 proxy->last_dnsupdate = time(NULL);
03113 return TRUE;
03114 }
03115
03116
03117
03118
03119 static struct sip_proxy *proxy_from_config(const char *proxy, int sipconf_lineno, struct sip_proxy *dest)
03120 {
03121 char *mutable_proxy, *sep, *name;
03122 int allocated = 0;
03123
03124 if (!dest) {
03125 dest = ao2_alloc(sizeof(struct sip_proxy), NULL);
03126 if (!dest) {
03127 ast_log(LOG_WARNING, "Unable to allocate config storage for proxy\n");
03128 return NULL;
03129 }
03130 allocated = 1;
03131 }
03132
03133
03134 mutable_proxy = ast_skip_blanks(ast_strdupa(proxy));
03135 sep = strchr(mutable_proxy, ',');
03136 if (sep) {
03137 *sep++ = '\0';
03138 dest->force = !strncasecmp(ast_skip_blanks(sep), "force", 5);
03139 } else {
03140 dest->force = FALSE;
03141 }
03142
03143 sip_parse_host(mutable_proxy, sipconf_lineno, &name, &dest->port, &dest->transport);
03144
03145
03146 if (ast_strlen_zero(name)) {
03147 if (allocated) {
03148 ao2_ref(dest, -1);
03149 } else {
03150 dest->name[0] = '\0';
03151 }
03152 return NULL;
03153 }
03154 ast_copy_string(dest->name, name, sizeof(dest->name));
03155
03156
03157 proxy_update(dest);
03158
03159 return dest;
03160 }
03161
03162
03163
03164
03165
03166 unsigned int port_str2int(const char *pt, unsigned int standard)
03167 {
03168 int port = standard;
03169 if (ast_strlen_zero(pt) || (sscanf(pt, "%30d", &port) != 1) || (port < 1) || (port > 65535)) {
03170 port = standard;
03171 }
03172
03173 return port;
03174 }
03175
03176
03177 static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
03178 {
03179 if (dialog && dialog->options && dialog->options->outboundproxy) {
03180 if (sipdebug) {
03181 ast_debug(1, "OBPROXY: Applying dialplan set OBproxy to this call\n");
03182 }
03183 append_history(dialog, "OBproxy", "Using dialplan obproxy %s", dialog->options->outboundproxy->name);
03184 return dialog->options->outboundproxy;
03185 }
03186 if (peer && peer->outboundproxy) {
03187 if (sipdebug) {
03188 ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
03189 }
03190 append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
03191 return peer->outboundproxy;
03192 }
03193 if (sip_cfg.outboundproxy.name[0]) {
03194 if (sipdebug) {
03195 ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
03196 }
03197 append_history(dialog, "OBproxy", "Using global obproxy %s", sip_cfg.outboundproxy.name);
03198 return &sip_cfg.outboundproxy;
03199 }
03200 if (sipdebug) {
03201 ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
03202 }
03203 return NULL;
03204 }
03205
03206
03207
03208
03209
03210
03211
03212 static int method_match(enum sipmethod id, const char *name)
03213 {
03214 int len = strlen(sip_methods[id].text);
03215 int l_name = name ? strlen(name) : 0;
03216
03217 return (l_name >= len && name && name[len] < 33 &&
03218 !strncasecmp(sip_methods[id].text, name, len));
03219 }
03220
03221
03222 static int find_sip_method(const char *msg)
03223 {
03224 int i, res = 0;
03225
03226 if (ast_strlen_zero(msg)) {
03227 return 0;
03228 }
03229 for (i = 1; i < ARRAY_LEN(sip_methods) && !res; i++) {
03230 if (method_match(i, msg)) {
03231 res = sip_methods[i].id;
03232 }
03233 }
03234 return res;
03235 }
03236
03237
03238 static inline int sip_debug_test_addr(const struct ast_sockaddr *addr)
03239 {
03240
03241 if (!sipdebug) {
03242 return 0;
03243 }
03244
03245
03246 if (ast_sockaddr_isnull(&debugaddr)) {
03247 return 1;
03248 }
03249
03250
03251
03252
03253 if (ast_sockaddr_port(&debugaddr)) {
03254 return !ast_sockaddr_cmp(&debugaddr, addr);
03255 } else {
03256 return !ast_sockaddr_cmp_addr(&debugaddr, addr);
03257 }
03258 }
03259
03260
03261 static const struct ast_sockaddr *sip_real_dst(const struct sip_pvt *p)
03262 {
03263 if (p->outboundproxy) {
03264 return &p->outboundproxy->ip;
03265 }
03266
03267 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;
03268 }
03269
03270
03271 static const char *sip_nat_mode(const struct sip_pvt *p)
03272 {
03273 return ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) ? "NAT" : "no NAT";
03274 }
03275
03276
03277 static inline int sip_debug_test_pvt(struct sip_pvt *p)
03278 {
03279 if (!sipdebug) {
03280 return 0;
03281 }
03282 return sip_debug_test_addr(sip_real_dst(p));
03283 }
03284
03285
03286 static int get_transport_str2enum(const char *transport)
03287 {
03288 int res = 0;
03289
03290 if (ast_strlen_zero(transport)) {
03291 return res;
03292 }
03293
03294 if (!strcasecmp(transport, "udp")) {
03295 res |= SIP_TRANSPORT_UDP;
03296 }
03297 if (!strcasecmp(transport, "tcp")) {
03298 res |= SIP_TRANSPORT_TCP;
03299 }
03300 if (!strcasecmp(transport, "tls")) {
03301 res |= SIP_TRANSPORT_TLS;
03302 }
03303
03304 return res;
03305 }
03306
03307
03308 static inline const char *get_transport_list(unsigned int transports) {
03309 switch (transports) {
03310 case SIP_TRANSPORT_UDP:
03311 return "UDP";
03312 case SIP_TRANSPORT_TCP:
03313 return "TCP";
03314 case SIP_TRANSPORT_TLS:
03315 return "TLS";
03316 case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TCP:
03317 return "TCP,UDP";
03318 case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TLS:
03319 return "TLS,UDP";
03320 case SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS:
03321 return "TLS,TCP";
03322 default:
03323 return transports ?
03324 "TLS,TCP,UDP" : "UNKNOWN";
03325 }
03326 }
03327
03328
03329 static inline const char *get_transport(enum sip_transport t)
03330 {
03331 switch (t) {
03332 case SIP_TRANSPORT_UDP:
03333 return "UDP";
03334 case SIP_TRANSPORT_TCP:
03335 return "TCP";
03336 case SIP_TRANSPORT_TLS:
03337 return "TLS";
03338 }
03339
03340 return "UNKNOWN";
03341 }
03342
03343
03344 static inline const char *get_srv_protocol(enum sip_transport t)
03345 {
03346 switch (t) {
03347 case SIP_TRANSPORT_UDP:
03348 return "udp";
03349 case SIP_TRANSPORT_TLS:
03350 case SIP_TRANSPORT_TCP:
03351 return "tcp";
03352 }
03353
03354 return "udp";
03355 }
03356
03357
03358 static inline const char *get_srv_service(enum sip_transport t)
03359 {
03360 switch (t) {
03361 case SIP_TRANSPORT_TCP:
03362 case SIP_TRANSPORT_UDP:
03363 return "sip";
03364 case SIP_TRANSPORT_TLS:
03365 return "sips";
03366 }
03367 return "sip";
03368 }
03369
03370
03371
03372
03373
03374
03375
03376 static inline const char *get_transport_pvt(struct sip_pvt *p)
03377 {
03378 if (p->outboundproxy && p->outboundproxy->transport) {
03379 set_socket_transport(&p->socket, p->outboundproxy->transport);
03380 }
03381
03382 return get_transport(p->socket.type);
03383 }
03384
03385
03386
03387
03388
03389
03390
03391
03392
03393
03394
03395
03396 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data)
03397 {
03398 int res = 0;
03399 const struct ast_sockaddr *dst = sip_real_dst(p);
03400
03401 ast_debug(2, "Trying to put '%.11s' onto %s socket destined for %s\n", data->str, get_transport_pvt(p), ast_sockaddr_stringify(dst));
03402
03403 if (sip_prepare_socket(p) < 0) {
03404 return XMIT_ERROR;
03405 }
03406
03407 if (p->socket.type == SIP_TRANSPORT_UDP) {
03408 res = ast_sendto(p->socket.fd, data->str, ast_str_strlen(data), 0, dst);
03409 } else if (p->socket.tcptls_session) {
03410 res = sip_tcptls_write(p->socket.tcptls_session, data->str, ast_str_strlen(data));
03411 } else {
03412 ast_debug(2, "Socket type is TCP but no tcptls_session is present to write to\n");
03413 return XMIT_ERROR;
03414 }
03415
03416 if (res == -1) {
03417 switch (errno) {
03418 case EBADF:
03419 case EHOSTUNREACH:
03420 case ENETDOWN:
03421 case ENETUNREACH:
03422 case ECONNREFUSED:
03423 res = XMIT_ERROR;
03424 }
03425 }
03426 if (res != ast_str_strlen(data)) {
03427 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));
03428 }
03429
03430 return res;
03431 }
03432
03433
03434 static void build_via(struct sip_pvt *p)
03435 {
03436
03437 const char *rport = (ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) || ast_test_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT)) ? ";rport" : "";
03438
03439
03440 snprintf(p->via, sizeof(p->via), "SIP/2.0/%s %s;branch=z9hG4bK%08x%s",
03441 get_transport_pvt(p),
03442 ast_sockaddr_stringify_remote(&p->ourip),
03443 (int) p->branch, rport);
03444 }
03445
03446
03447
03448
03449
03450
03451
03452
03453 static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p)
03454 {
03455 struct ast_sockaddr theirs;
03456
03457
03458
03459
03460
03461
03462
03463
03464
03465
03466
03467
03468
03469 int want_remap = 0;
03470
03471 ast_sockaddr_copy(us, &internip);
03472
03473 ast_ouraddrfor(them, us);
03474 ast_sockaddr_copy(&theirs, them);
03475
03476 if (ast_sockaddr_is_ipv6(&theirs)) {
03477 if (localaddr && !ast_sockaddr_isnull(&externaddr) && !ast_sockaddr_is_any(&bindaddr)) {
03478 ast_log(LOG_WARNING, "Address remapping activated in sip.conf "
03479 "but we're using IPv6, which doesn't need it. Please "
03480 "remove \"localnet\" and/or \"externaddr\" settings.\n");
03481 }
03482 } else {
03483 want_remap = localaddr &&
03484 !ast_sockaddr_isnull(&externaddr) &&
03485 ast_apply_ha(localaddr, &theirs) == AST_SENSE_ALLOW ;
03486 }
03487
03488 if (want_remap &&
03489 (!sip_cfg.matchexternaddrlocally || !ast_apply_ha(localaddr, us)) ) {
03490
03491 if (externexpire && time(NULL) >= externexpire) {
03492 if (ast_sockaddr_resolve_first(&externaddr, externhost, 0)) {
03493 ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
03494 }
03495 externexpire = time(NULL) + externrefresh;
03496 }
03497 if (!ast_sockaddr_isnull(&externaddr)) {
03498 ast_sockaddr_copy(us, &externaddr);
03499 switch (p->socket.type) {
03500 case SIP_TRANSPORT_TCP:
03501 if (!externtcpport && ast_sockaddr_port(&externaddr)) {
03502
03503 externtcpport = ast_sockaddr_port(&externaddr);
03504 }
03505 ast_sockaddr_set_port(us, externtcpport);
03506 break;
03507 case SIP_TRANSPORT_TLS:
03508 ast_sockaddr_set_port(us, externtlsport);
03509 break;
03510 case SIP_TRANSPORT_UDP:
03511 if (!ast_sockaddr_port(&externaddr)) {
03512 ast_sockaddr_set_port(us, ast_sockaddr_port(&bindaddr));
03513 }
03514 break;
03515 default:
03516 break;
03517 }
03518 }
03519 ast_debug(1, "Target address %s is not local, substituting externaddr\n",
03520 ast_sockaddr_stringify(them));
03521 } else {
03522
03523 switch (p->socket.type) {
03524 case SIP_TRANSPORT_TCP:
03525 if (!ast_sockaddr_is_any(&sip_tcp_desc.local_address)) {
03526 ast_sockaddr_copy(us,
03527 &sip_tcp_desc.local_address);
03528 } else {
03529 ast_sockaddr_set_port(us,
03530 ast_sockaddr_port(&sip_tcp_desc.local_address));
03531 }
03532 break;
03533 case SIP_TRANSPORT_TLS:
03534 if (!ast_sockaddr_is_any(&sip_tls_desc.local_address)) {
03535 ast_sockaddr_copy(us,
03536 &sip_tls_desc.local_address);
03537 } else {
03538 ast_sockaddr_set_port(us,
03539 ast_sockaddr_port(&sip_tls_desc.local_address));
03540 }
03541 break;
03542 case SIP_TRANSPORT_UDP:
03543
03544 default:
03545 if (!ast_sockaddr_is_any(&bindaddr)) {
03546 ast_sockaddr_copy(us, &bindaddr);
03547 }
03548 if (!ast_sockaddr_port(us)) {
03549 ast_sockaddr_set_port(us, ast_sockaddr_port(&bindaddr));
03550 }
03551 }
03552 }
03553 ast_debug(3, "Setting SIP_TRANSPORT_%s with address %s\n", get_transport(p->socket.type), ast_sockaddr_stringify(us));
03554 }
03555
03556
03557 static __attribute__((format(printf, 2, 0))) void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
03558 {
03559 char buf[80], *c = buf;
03560 struct sip_history *hist;
03561 int l;
03562
03563 vsnprintf(buf, sizeof(buf), fmt, ap);
03564 strsep(&c, "\r\n");
03565 l = strlen(buf) + 1;
03566 if (!(hist = ast_calloc(1, sizeof(*hist) + l))) {
03567 return;
03568 }
03569 if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
03570 ast_free(hist);
03571 return;
03572 }
03573 memcpy(hist->event, buf, l);
03574 if (p->history_entries == MAX_HISTORY_ENTRIES) {
03575 struct sip_history *oldest;
03576 oldest = AST_LIST_REMOVE_HEAD(p->history, list);
03577 p->history_entries--;
03578 ast_free(oldest);
03579 }
03580 AST_LIST_INSERT_TAIL(p->history, hist, list);
03581 p->history_entries++;
03582 }
03583
03584
03585 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
03586 {
03587 va_list ap;
03588
03589 if (!p) {
03590 return;
03591 }
03592
03593 if (!p->do_history && !recordhistory && !dumphistory) {
03594 return;
03595 }
03596
03597 va_start(ap, fmt);
03598 append_history_va(p, fmt, ap);
03599 va_end(ap);
03600
03601 return;
03602 }
03603
03604
03605 static int retrans_pkt(const void *data)
03606 {
03607 struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
03608 int reschedule = DEFAULT_RETRANS;
03609 int xmitres = 0;
03610
03611 int64_t diff = pkt->retrans_stop_time - ast_tvdiff_ms(ast_tvnow(), pkt->time_sent);
03612
03613
03614
03615
03616 if ((diff <= 0) || (diff > pkt->retrans_stop_time)) {
03617 pkt->retrans_stop = 1;
03618 }
03619
03620
03621 sip_pvt_lock(pkt->owner);
03622
03623 if (!pkt->retrans_stop) {
03624 pkt->retrans++;
03625 if (!pkt->timer_t1) {
03626 if (sipdebug) {
03627 ast_debug(4, "SIP TIMER: Not rescheduling id #%d:%s (Method %d) (No timer T1)\n",
03628 pkt->retransid,
03629 sip_methods[pkt->method].text,
03630 pkt->method);
03631 }
03632 } else {
03633 int siptimer_a;
03634
03635 if (sipdebug) {
03636 ast_debug(4, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n",
03637 pkt->retransid,
03638 pkt->retrans,
03639 sip_methods[pkt->method].text,
03640 pkt->method);
03641 }
03642 if (!pkt->timer_a) {
03643 pkt->timer_a = 2 ;
03644 } else {
03645 pkt->timer_a = 2 * pkt->timer_a;
03646 }
03647
03648
03649 siptimer_a = pkt->timer_t1 * pkt->timer_a;
03650 if (pkt->method != SIP_INVITE && siptimer_a > 4000) {
03651 siptimer_a = 4000;
03652 }
03653
03654
03655 reschedule = siptimer_a;
03656 ast_debug(4, "** SIP timers: Rescheduling retransmission %d to %d ms (t1 %d ms (Retrans id #%d)) \n",
03657 pkt->retrans + 1,
03658 siptimer_a,
03659 pkt->timer_t1,
03660 pkt->retransid);
03661 }
03662
03663 if (sip_debug_test_pvt(pkt->owner)) {
03664 const struct ast_sockaddr *dst = sip_real_dst(pkt->owner);
03665 ast_verbose("Retransmitting #%d (%s) to %s:\n%s\n---\n",
03666 pkt->retrans, sip_nat_mode(pkt->owner),
03667 ast_sockaddr_stringify(dst),
03668 pkt->data->str);
03669 }
03670
03671 append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data->str);
03672 xmitres = __sip_xmit(pkt->owner, pkt->data);
03673
03674
03675
03676
03677
03678
03679 if (xmitres != XMIT_ERROR) {
03680 if (reschedule >= diff) {
03681 pkt->retrans_stop = 1;
03682 reschedule = diff;
03683 }
03684 sip_pvt_unlock(pkt->owner);
03685 return reschedule;
03686 }
03687 }
03688
03689
03690
03691
03692 pkt->retransid = -1;
03693
03694 if (pkt->method != SIP_OPTIONS && xmitres == 0) {
03695 if (pkt->is_fatal || sipdebug) {
03696 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"
03697 "Packet timed out after %dms with no response\n",
03698 pkt->owner->callid,
03699 pkt->seqno,
03700 pkt->is_fatal ? "Critical" : "Non-critical",
03701 pkt->is_resp ? "Response" : "Request",
03702 (int) ast_tvdiff_ms(ast_tvnow(), pkt->time_sent));
03703 }
03704 } else if (pkt->method == SIP_OPTIONS && sipdebug) {
03705 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);
03706 }
03707
03708 if (xmitres == XMIT_ERROR) {
03709 ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission on Call ID %s\n", pkt->owner->callid);
03710 append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03711 } else {
03712 append_history(pkt->owner, "MaxRetries", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03713 }
03714
03715 if (pkt->is_fatal) {
03716 while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
03717 sip_pvt_unlock(pkt->owner);
03718 usleep(1);
03719 sip_pvt_lock(pkt->owner);
03720 }
03721 if (pkt->owner->owner && !pkt->owner->owner->hangupcause) {
03722 pkt->owner->owner->hangupcause = AST_CAUSE_NO_USER_RESPONSE;
03723 }
03724 if (pkt->owner->owner) {
03725 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);
03726
03727 if (pkt->is_resp &&
03728 (pkt->response_code >= 200) &&
03729 (pkt->response_code < 300) &&
03730 pkt->owner->pendinginvite &&
03731 ast_test_flag(&pkt->owner->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
03732
03733
03734
03735
03736
03737
03738
03739 pkt->owner->invitestate = INV_TERMINATED;
03740 pkt->owner->pendinginvite = 0;
03741 } else {
03742
03743 sip_alreadygone(pkt->owner);
03744 }
03745 ast_queue_hangup_with_cause(pkt->owner->owner, AST_CAUSE_NO_USER_RESPONSE);
03746 ast_channel_unlock(pkt->owner->owner);
03747 } else {
03748
03749
03750
03751 if (pkt->method != SIP_OPTIONS && pkt->method != SIP_REGISTER) {
03752 pvt_set_needdestroy(pkt->owner, "no response to critical packet");
03753 sip_alreadygone(pkt->owner);
03754 append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
03755 }
03756 }
03757 }
03758
03759 if (pkt->method == SIP_BYE) {
03760
03761 sip_alreadygone(pkt->owner);
03762 if (pkt->owner->owner) {
03763 ast_channel_unlock(pkt->owner->owner);
03764 }
03765 append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
03766 pvt_set_needdestroy(pkt->owner, "no response to BYE");
03767 }
03768
03769
03770 for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
03771 if (cur == pkt) {
03772 UNLINK(cur, pkt->owner->packets, prev);
03773 sip_pvt_unlock(pkt->owner);
03774 if (pkt->owner) {
03775 pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
03776 }
03777 if (pkt->data) {
03778 ast_free(pkt->data);
03779 }
03780 pkt->data = NULL;
03781 ast_free(pkt);
03782 return 0;
03783 }
03784 }
03785
03786 ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
03787 sip_pvt_unlock(pkt->owner);
03788 return 0;
03789 }
03790
03791
03792
03793
03794
03795
03796 static enum sip_result __sip_reliable_xmit(struct sip_pvt *p, uint32_t seqno, int resp, struct ast_str *data, int fatal, int sipmethod)
03797 {
03798 struct sip_pkt *pkt = NULL;
03799 int siptimer_a = DEFAULT_RETRANS;
03800 int xmitres = 0;
03801 int respid;
03802
03803 if (sipmethod == SIP_INVITE) {
03804
03805 p->pendinginvite = seqno;
03806 }
03807
03808
03809
03810
03811 if (!(p->socket.type & SIP_TRANSPORT_UDP)) {
03812 xmitres = __sip_xmit(p, data);
03813 if (xmitres == XMIT_ERROR) {
03814 append_history(p, "XmitErr", "%s", fatal ? "(Critical)" : "(Non-critical)");
03815 return AST_FAILURE;
03816 } else {
03817 return AST_SUCCESS;
03818 }
03819 }
03820
03821 if (!(pkt = ast_calloc(1, sizeof(*pkt)))) {
03822 return AST_FAILURE;
03823 }
03824
03825 if (!(pkt->data = ast_str_create(ast_str_strlen(data)))) {
03826 ast_free(pkt);
03827 return AST_FAILURE;
03828 }
03829 ast_str_set(&pkt->data, 0, "%s%s", data->str, "\0");
03830
03831 pkt->method = sipmethod;
03832 pkt->seqno = seqno;
03833 pkt->is_resp = resp;
03834 pkt->is_fatal = fatal;
03835 pkt->owner = dialog_ref(p, "__sip_reliable_xmit: setting pkt->owner");
03836 pkt->next = p->packets;
03837 p->packets = pkt;
03838 if (resp) {
03839
03840 if (sscanf(ast_str_buffer(pkt->data), "SIP/2.0 %30u", &respid) == 1) {
03841 pkt->response_code = respid;
03842 }
03843 }
03844 pkt->timer_t1 = p->timer_t1;
03845 pkt->retransid = -1;
03846 if (pkt->timer_t1) {
03847 siptimer_a = pkt->timer_t1;
03848 }
03849
03850 pkt->time_sent = ast_tvnow();
03851 pkt->retrans_stop_time = 64 * (pkt->timer_t1 ? pkt->timer_t1 : DEFAULT_TIMER_T1);
03852
03853
03854 AST_SCHED_REPLACE_VARIABLE(pkt->retransid, sched, siptimer_a, retrans_pkt, pkt, 1);
03855 if (sipdebug) {
03856 ast_debug(4, "*** SIP TIMER: Initializing retransmit timer on packet: Id #%d\n", pkt->retransid);
03857 }
03858
03859 xmitres = __sip_xmit(pkt->owner, pkt->data);
03860
03861 if (xmitres == XMIT_ERROR) {
03862 append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03863 ast_log(LOG_ERROR, "Serious Network Trouble; __sip_xmit returns error for pkt data\n");
03864 AST_SCHED_DEL(sched, pkt->retransid);
03865 p->packets = pkt->next;
03866 pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
03867 ast_free(pkt->data);
03868 ast_free(pkt);
03869 return AST_FAILURE;
03870 } else {
03871
03872
03873
03874
03875 if (monitor_thread != AST_PTHREADT_NULL) {
03876 pthread_kill(monitor_thread, SIGURG);
03877 }
03878 return AST_SUCCESS;
03879 }
03880 }
03881
03882
03883
03884
03885
03886
03887 static int __sip_autodestruct(const void *data)
03888 {
03889 struct sip_pvt *p = (struct sip_pvt *)data;
03890 struct ast_channel *owner;
03891
03892
03893 if (p->subscribed && p->subscribed != MWI_NOTIFICATION && p->subscribed != CALL_COMPLETION) {
03894 transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE);
03895 p->subscribed = NONE;
03896 append_history(p, "Subscribestatus", "timeout");
03897 ast_debug(3, "Re-scheduled destruction of SIP subscription %s\n", p->callid ? p->callid : "<unknown>");
03898 return 10000;
03899 }
03900
03901
03902 if (p->packets) {
03903 if (!p->needdestroy) {
03904 char method_str[31];
03905 ast_debug(3, "Re-scheduled destruction of SIP call %s\n", p->callid ? p->callid : "<unknown>");
03906 append_history(p, "ReliableXmit", "timeout");
03907 if (sscanf(p->lastmsg, "Tx: %30s", method_str) == 1 || sscanf(p->lastmsg, "Rx: %30s", method_str) == 1) {
03908 if (p->ongoing_reinvite || method_match(SIP_CANCEL, method_str) || method_match(SIP_BYE, method_str)) {
03909 pvt_set_needdestroy(p, "autodestruct");
03910 }
03911 }
03912 return 10000;
03913 } else {
03914
03915 __sip_pretend_ack(p);
03916 }
03917 }
03918
03919
03920 p->autokillid = -1;
03921
03922
03923
03924
03925 owner = sip_pvt_lock_full(p);
03926 if (owner) {
03927 ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner %s in place (Method: %s). Rescheduling destruction for 10000 ms\n", p->callid, owner->name, sip_methods[p->method].text);
03928 ast_queue_hangup_with_cause(owner, AST_CAUSE_PROTOCOL_ERROR);
03929 ast_channel_unlock(owner);
03930 ast_channel_unref(owner);
03931 sip_pvt_unlock(p);
03932 return 10000;
03933 } else if (p->refer && !p->alreadygone) {
03934 ast_debug(3, "Finally hanging up channel after transfer: %s\n", p->callid);
03935 stop_media_flows(p);
03936 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
03937 append_history(p, "ReferBYE", "Sending BYE on transferer call leg %s", p->callid);
03938 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
03939 } else {
03940 append_history(p, "AutoDestroy", "%s", p->callid);
03941 ast_debug(3, "Auto destroying SIP dialog '%s'\n", p->callid);
03942 sip_pvt_unlock(p);
03943 dialog_unlink_all(p);
03944 sip_pvt_lock(p);
03945
03946
03947
03948 }
03949
03950 sip_pvt_unlock(p);
03951
03952 dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
03953
03954 return 0;
03955 }
03956
03957
03958
03959
03960 void sip_scheddestroy_final(struct sip_pvt *p, int ms)
03961 {
03962 if (p->final_destruction_scheduled) {
03963 return;
03964 }
03965
03966 sip_scheddestroy(p, ms);
03967 if (p->autokillid != -1) {
03968 p->final_destruction_scheduled = 1;
03969 }
03970 }
03971
03972
03973 void sip_scheddestroy(struct sip_pvt *p, int ms)
03974 {
03975 if (p->final_destruction_scheduled) {
03976 return;
03977 }
03978
03979 if (ms < 0) {
03980 if (p->timer_t1 == 0) {
03981 p->timer_t1 = global_t1;
03982 }
03983 if (p->timer_b == 0) {
03984 p->timer_b = global_timer_b;
03985 }
03986 ms = p->timer_t1 * 64;
03987 }
03988 if (sip_debug_test_pvt(p)) {
03989 ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
03990 }
03991 if (sip_cancel_destroy(p)) {
03992 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
03993 }
03994
03995 if (p->do_history) {
03996 append_history(p, "SchedDestroy", "%d ms", ms);
03997 }
03998 p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, dialog_ref(p, "setting ref as passing into ast_sched_add for __sip_autodestruct"));
03999
04000 if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_schedid > 0) {
04001 stop_session_timer(p);
04002 }
04003 }
04004
04005
04006
04007
04008
04009 int sip_cancel_destroy(struct sip_pvt *p)
04010 {
04011 if (p->final_destruction_scheduled) {
04012 return 0;
04013 }
04014
04015 if (p->autokillid > -1) {
04016 append_history(p, "CancelDestroy", "");
04017 AST_SCHED_DEL_UNREF(sched, p->autokillid, dialog_unref(p, "remove ref for autokillid"));
04018 }
04019 return 0;
04020 }
04021
04022
04023
04024 int __sip_ack(struct sip_pvt *p, uint32_t seqno, int resp, int sipmethod)
04025 {
04026 struct sip_pkt *cur, *prev = NULL;
04027 const char *msg = "Not Found";
04028 int res = FALSE;
04029
04030
04031
04032
04033
04034
04035 if (p->outboundproxy && !p->outboundproxy->force){
04036 ref_proxy(p, NULL);
04037 }
04038
04039 for (cur = p->packets; cur; prev = cur, cur = cur->next) {
04040 if (cur->seqno != seqno || cur->is_resp != resp) {
04041 continue;
04042 }
04043 if (cur->is_resp || cur->method == sipmethod) {
04044 res = TRUE;
04045 msg = "Found";
04046 if (!resp && (seqno == p->pendinginvite)) {
04047 ast_debug(1, "Acked pending invite %u\n", p->pendinginvite);
04048 p->pendinginvite = 0;
04049 }
04050 if (cur->retransid > -1) {
04051 if (sipdebug)
04052 ast_debug(4, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
04053 }
04054
04055
04056
04057
04058
04059
04060
04061
04062
04063
04064
04065
04066
04067
04068
04069
04070 while (cur->retransid > -1 && ast_sched_del(sched, cur->retransid)) {
04071 sip_pvt_unlock(p);
04072 usleep(1);
04073 sip_pvt_lock(p);
04074 }
04075 UNLINK(cur, p->packets, prev);
04076 dialog_unref(cur->owner, "unref pkt cur->owner dialog from sip ack before freeing pkt");
04077 if (cur->data) {
04078 ast_free(cur->data);
04079 }
04080 ast_free(cur);
04081 break;
04082 }
04083 }
04084 ast_debug(1, "Stopping retransmission on '%s' of %s %u: Match %s\n",
04085 p->callid, resp ? "Response" : "Request", seqno, msg);
04086 return res;
04087 }
04088
04089
04090
04091 void __sip_pretend_ack(struct sip_pvt *p)
04092 {
04093 struct sip_pkt *cur = NULL;
04094
04095 while (p->packets) {
04096 int method;
04097 if (cur == p->packets) {
04098 ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
04099 return;
04100 }
04101 cur = p->packets;
04102 method = (cur->method) ? cur->method : find_sip_method(cur->data->str);
04103 __sip_ack(p, cur->seqno, cur->is_resp, method);
04104 }
04105 }
04106
04107
04108 int __sip_semi_ack(struct sip_pvt *p, uint32_t seqno, int resp, int sipmethod)
04109 {
04110 struct sip_pkt *cur;
04111 int res = FALSE;
04112
04113 for (cur = p->packets; cur; cur = cur->next) {
04114 if (cur->seqno == seqno && cur->is_resp == resp &&
04115 (cur->is_resp || method_match(sipmethod, cur->data->str))) {
04116
04117 if (cur->retransid > -1) {
04118 if (sipdebug)
04119 ast_debug(4, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
04120 }
04121 AST_SCHED_DEL(sched, cur->retransid);
04122 res = TRUE;
04123 break;
04124 }
04125 }
04126 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");
04127 return res;
04128 }
04129
04130
04131
04132 static void parse_copy(struct sip_request *dst, const struct sip_request *src)
04133 {
04134 copy_request(dst, src);
04135 parse_request(dst);
04136 }
04137
04138
04139 static void add_blank(struct sip_request *req)
04140 {
04141 if (!req->lines) {
04142
04143 ast_str_append(&req->data, 0, "\r\n");
04144 }
04145 }
04146
04147 static int send_provisional_keepalive_full(struct sip_pvt *pvt, int with_sdp)
04148 {
04149 const char *msg = NULL;
04150 struct ast_channel *chan;
04151 int res = 0;
04152
04153 chan = sip_pvt_lock_full(pvt);
04154
04155 if (!pvt->last_provisional || !strncasecmp(pvt->last_provisional, "100", 3)) {
04156 msg = "183 Session Progress";
04157 }
04158
04159 if (pvt->invitestate < INV_COMPLETED) {
04160 if (with_sdp) {
04161 transmit_response_with_sdp(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq, XMIT_UNRELIABLE, FALSE, FALSE);
04162 } else {
04163 transmit_response(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq);
04164 }
04165 res = PROVIS_KEEPALIVE_TIMEOUT;
04166 }
04167
04168 if (chan) {
04169 ast_channel_unlock(chan);
04170 chan = ast_channel_unref(chan);
04171 }
04172
04173 if (!res) {
04174 pvt->provisional_keepalive_sched_id = -1;
04175 }
04176
04177 sip_pvt_unlock(pvt);
04178
04179 #if 0
04180
04181
04182
04183
04184
04185
04186
04187
04188 if (!res) {
04189 dialog_unref(pvt, "dialog ref for provisional keepalive");
04190 }
04191 #endif
04192
04193 return res;
04194 }
04195
04196 static int send_provisional_keepalive(const void *data) {
04197 struct sip_pvt *pvt = (struct sip_pvt *) data;
04198
04199 return send_provisional_keepalive_full(pvt, 0);
04200 }
04201
04202 static int send_provisional_keepalive_with_sdp(const void *data) {
04203 struct sip_pvt *pvt = (void *)data;
04204
04205 return send_provisional_keepalive_full(pvt, 1);
04206 }
04207
04208 static void update_provisional_keepalive(struct sip_pvt *pvt, int with_sdp)
04209 {
04210 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"));
04211
04212 pvt->provisional_keepalive_sched_id = ast_sched_add(sched, PROVIS_KEEPALIVE_TIMEOUT,
04213 with_sdp ? send_provisional_keepalive_with_sdp : send_provisional_keepalive, dialog_ref(pvt, "Increment refcount to pass dialog pointer to sched callback"));
04214 }
04215
04216
04217 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno)
04218 {
04219 int res;
04220
04221 finalize_content(req);
04222 add_blank(req);
04223 if (sip_debug_test_pvt(p)) {
04224 const struct ast_sockaddr *dst = sip_real_dst(p);
04225
04226 ast_verbose("\n<--- %sTransmitting (%s) to %s --->\n%s\n<------------>\n",
04227 reliable ? "Reliably " : "", sip_nat_mode(p),
04228 ast_sockaddr_stringify(dst),
04229 req->data->str);
04230 }
04231 if (p->do_history) {
04232 struct sip_request tmp = { .rlPart1 = 0, };
04233 parse_copy(&tmp, req);
04234 append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", tmp.data->str, get_header(&tmp, "CSeq"),
04235 (tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? REQ_OFFSET_TO_STR(&tmp, rlPart2) : sip_methods[tmp.method].text);
04236 deinit_req(&tmp);
04237 }
04238
04239
04240 if (p->initreq.method == SIP_INVITE && reliable == XMIT_CRITICAL) {
04241 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"));
04242 }
04243
04244 res = (reliable) ?
04245 __sip_reliable_xmit(p, seqno, 1, req->data, (reliable == XMIT_CRITICAL), req->method) :
04246 __sip_xmit(p, req->data);
04247 deinit_req(req);
04248 if (res > 0) {
04249 return 0;
04250 }
04251 return res;
04252 }
04253
04254
04255
04256
04257
04258
04259 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno)
04260 {
04261 int res;
04262
04263
04264
04265
04266 if (p->outboundproxy) {
04267 p->sa = p->outboundproxy->ip;
04268 }
04269
04270 finalize_content(req);
04271 add_blank(req);
04272 if (sip_debug_test_pvt(p)) {
04273 if (ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT)) {
04274 ast_verbose("%sTransmitting (NAT) to %s:\n%s\n---\n", reliable ? "Reliably " : "", ast_sockaddr_stringify(&p->recv), req->data->str);
04275 } else {
04276 ast_verbose("%sTransmitting (no NAT) to %s:\n%s\n---\n", reliable ? "Reliably " : "", ast_sockaddr_stringify(&p->sa), req->data->str);
04277 }
04278 }
04279 if (p->do_history) {
04280 struct sip_request tmp = { .rlPart1 = 0, };
04281 parse_copy(&tmp, req);
04282 append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", tmp.data->str, get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
04283 deinit_req(&tmp);
04284 }
04285 res = (reliable) ?
04286 __sip_reliable_xmit(p, seqno, 0, req->data, (reliable == XMIT_CRITICAL), req->method) :
04287 __sip_xmit(p, req->data);
04288 deinit_req(req);
04289 return res;
04290 }
04291
04292 static void enable_dsp_detect(struct sip_pvt *p)
04293 {
04294 int features = 0;
04295
04296 if (p->dsp) {
04297 return;
04298 }
04299
04300 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
04301 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
04302 if (p->rtp) {
04303 ast_rtp_instance_dtmf_mode_set(p->rtp, AST_RTP_DTMF_MODE_INBAND);
04304 }
04305 features |= DSP_FEATURE_DIGIT_DETECT;
04306 }
04307
04308 if (ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_CNG)) {
04309 features |= DSP_FEATURE_FAX_DETECT;
04310 }
04311
04312 if (!features) {
04313 return;
04314 }
04315
04316 if (!(p->dsp = ast_dsp_new())) {
04317 return;
04318 }
04319
04320 ast_dsp_set_features(p->dsp, features);
04321 if (global_relaxdtmf) {
04322 ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
04323 }
04324 }
04325
04326 static void disable_dsp_detect(struct sip_pvt *p)
04327 {
04328 if (p->dsp) {
04329 ast_dsp_free(p->dsp);
04330 p->dsp = NULL;
04331 }
04332 }
04333
04334
04335 static int sip_setoption(struct ast_channel *chan, int option, void *data, int datalen)
04336 {
04337 int res = -1;
04338 struct sip_pvt *p = chan->tech_pvt;
04339
04340 if (!p) {
04341 ast_log(LOG_ERROR, "Attempt to Ref a null pointer. sip private structure is gone!\n");
04342 return -1;
04343 }
04344
04345 sip_pvt_lock(p);
04346
04347 switch (option) {
04348 case AST_OPTION_FORMAT_READ:
04349 if (p->rtp) {
04350 res = ast_rtp_instance_set_read_format(p->rtp, *(int *) data);
04351 }
04352 break;
04353 case AST_OPTION_FORMAT_WRITE:
04354 if (p->rtp) {
04355 res = ast_rtp_instance_set_write_format(p->rtp, *(int *) data);
04356 }
04357 break;
04358 case AST_OPTION_MAKE_COMPATIBLE:
04359 if (p->rtp) {
04360 res = ast_rtp_instance_make_compatible(chan, p->rtp, (struct ast_channel *) data);
04361 }
04362 break;
04363 case AST_OPTION_DIGIT_DETECT:
04364 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
04365 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
04366 char *cp = (char *) data;
04367
04368 ast_debug(1, "%sabling digit detection on %s\n", *cp ? "En" : "Dis", chan->name);
04369 if (*cp) {
04370 enable_dsp_detect(p);
04371 } else {
04372 disable_dsp_detect(p);
04373 }
04374 res = 0;
04375 }
04376 break;
04377 case AST_OPTION_SECURE_SIGNALING:
04378 p->req_secure_signaling = *(unsigned int *) data;
04379 res = 0;
04380 break;
04381 case AST_OPTION_SECURE_MEDIA:
04382 ast_set2_flag(&p->flags[1], *(unsigned int *) data, SIP_PAGE2_USE_SRTP);
04383 res = 0;
04384 break;
04385 default:
04386 break;
04387 }
04388
04389 sip_pvt_unlock(p);
04390
04391 return res;
04392 }
04393
04394
04395 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen)
04396 {
04397 int res = -1;
04398 enum ast_t38_state state = T38_STATE_UNAVAILABLE;
04399 struct sip_pvt *p = (struct sip_pvt *) chan->tech_pvt;
04400 char *cp;
04401
04402 sip_pvt_lock(p);
04403
04404 switch (option) {
04405 case AST_OPTION_T38_STATE:
04406
04407 if (*datalen != sizeof(enum ast_t38_state)) {
04408 ast_log(LOG_ERROR, "Invalid datalen for AST_OPTION_T38_STATE option. Expected %d, got %d\n", (int)sizeof(enum ast_t38_state), *datalen);
04409 break;
04410 }
04411
04412
04413 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
04414 switch (p->t38.state) {
04415 case T38_LOCAL_REINVITE:
04416 case T38_PEER_REINVITE:
04417 state = T38_STATE_NEGOTIATING;
04418 break;
04419 case T38_ENABLED:
04420 state = T38_STATE_NEGOTIATED;
04421 break;
04422 default:
04423 state = T38_STATE_UNKNOWN;
04424 }
04425 }
04426
04427 *((enum ast_t38_state *) data) = state;
04428 res = 0;
04429
04430 break;
04431 case AST_OPTION_DIGIT_DETECT:
04432 cp = (char *) data;
04433 *cp = p->dsp ? 1 : 0;
04434 ast_debug(1, "Reporting digit detection %sabled on %s\n", *cp ? "en" : "dis", chan->name);
04435 break;
04436 case AST_OPTION_SECURE_SIGNALING:
04437 *((unsigned int *) data) = p->req_secure_signaling;
04438 res = 0;
04439 break;
04440 case AST_OPTION_SECURE_MEDIA:
04441 *((unsigned int *) data) = ast_test_flag(&p->flags[1], SIP_PAGE2_USE_SRTP) ? 1 : 0;
04442 res = 0;
04443 break;
04444 case AST_OPTION_DEVICE_NAME:
04445 if (p && p->outgoing_call) {
04446 cp = (char *) data;
04447 ast_copy_string(cp, p->dialstring, *datalen);
04448 res = 0;
04449 }
04450
04451
04452
04453 break;
04454 default:
04455 break;
04456 }
04457
04458 sip_pvt_unlock(p);
04459
04460 return res;
04461 }
04462
04463
04464
04465
04466
04467 const char *find_closing_quote(const char *start, const char *lim)
04468 {
04469 char last_char = '\0';
04470 const char *s;
04471 for (s = start; *s && s != lim; last_char = *s++) {
04472 if (*s == '"' && last_char != '\\')
04473 break;
04474 }
04475 return s;
04476 }
04477
04478
04479 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
04480 {
04481 struct sip_pvt *p = chan->tech_pvt;
04482
04483 if (subclass != AST_HTML_URL)
04484 return -1;
04485
04486 ast_string_field_build(p, url, "<%s>;mode=active", data);
04487
04488 if (sip_debug_test_pvt(p))
04489 ast_debug(1, "Send URL %s, state = %d!\n", data, chan->_state);
04490
04491 switch (chan->_state) {
04492 case AST_STATE_RING:
04493 transmit_response(p, "100 Trying", &p->initreq);
04494 break;
04495 case AST_STATE_RINGING:
04496 transmit_response(p, "180 Ringing", &p->initreq);
04497 break;
04498 case AST_STATE_UP:
04499 if (!p->pendinginvite) {
04500 transmit_reinvite_with_sdp(p, FALSE, FALSE);
04501 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
04502 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
04503 }
04504 break;
04505 default:
04506 ast_log(LOG_WARNING, "Don't know how to send URI when state is %d!\n", chan->_state);
04507 }
04508
04509 return 0;
04510 }
04511
04512
04513 static const char *sip_get_callid(struct ast_channel *chan)
04514 {
04515 return chan->tech_pvt ? ((struct sip_pvt *) chan->tech_pvt)->callid : "";
04516 }
04517
04518
04519
04520
04521
04522
04523 static int sip_sendtext(struct ast_channel *ast, const char *text)
04524 {
04525 struct sip_pvt *dialog = ast->tech_pvt;
04526 int debug;
04527
04528 if (!dialog) {
04529 return -1;
04530 }
04531
04532
04533 if (!text) {
04534 return 0;
04535 }
04536 if(!is_method_allowed(&dialog->allowed_methods, SIP_MESSAGE)) {
04537 ast_debug(2, "Trying to send MESSAGE to device that does not support it.\n");
04538 return(0);
04539 }
04540
04541 debug = sip_debug_test_pvt(dialog);
04542 if (debug) {
04543 ast_verbose("Sending text %s on %s\n", text, ast->name);
04544 }
04545
04546 transmit_message_with_text(dialog, text);
04547 return 0;
04548 }
04549
04550
04551
04552
04553
04554
04555 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)
04556 {
04557 char port[10];
04558 char ipaddr[INET6_ADDRSTRLEN];
04559 char regseconds[20];
04560 char *tablename = NULL;
04561 char str_lastms[20];
04562
04563 const char *sysname = ast_config_AST_SYSTEM_NAME;
04564 char *syslabel = NULL;
04565
04566 time_t nowtime = time(NULL) + expirey;
04567 const char *fc = fullcontact ? "fullcontact" : NULL;
04568
04569 int realtimeregs = ast_check_realtime("sipregs");
04570
04571 tablename = realtimeregs ? "sipregs" : "sippeers";
04572
04573
04574 snprintf(str_lastms, sizeof(str_lastms), "%d", lastms);
04575 snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime);
04576 ast_copy_string(ipaddr, ast_sockaddr_isnull(addr) ? "" : ast_sockaddr_stringify_addr(addr), sizeof(ipaddr));
04577 ast_copy_string(port, ast_sockaddr_port(addr) ? ast_sockaddr_stringify_port(addr) : "", sizeof(port));
04578
04579 if (ast_strlen_zero(sysname))
04580 sysname = NULL;
04581 else if (sip_cfg.rtsave_sysname)
04582 syslabel = "regserver";
04583
04584
04585
04586
04587
04588
04589
04590 if (fc) {
04591 ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
04592 "port", port, "regseconds", regseconds,
04593 deprecated_username ? "username" : "defaultuser", defaultuser,
04594 "useragent", useragent, "lastms", str_lastms,
04595 fc, fullcontact, syslabel, sysname, SENTINEL);
04596 } else {
04597 ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
04598 "port", port, "regseconds", regseconds,
04599 "useragent", useragent, "lastms", str_lastms,
04600 deprecated_username ? "username" : "defaultuser", defaultuser,
04601 syslabel, sysname, SENTINEL);
04602 }
04603 }
04604
04605
04606 static void register_peer_exten(struct sip_peer *peer, int onoff)
04607 {
04608 char multi[256];
04609 char *stringp, *ext, *context;
04610 struct pbx_find_info q = { .stacklen = 0 };
04611
04612
04613
04614
04615
04616 if (ast_strlen_zero(sip_cfg.regcontext))
04617 return;
04618
04619 ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
04620 stringp = multi;
04621 while ((ext = strsep(&stringp, "&"))) {
04622 if ((context = strchr(ext, '@'))) {
04623 *context++ = '\0';
04624 if (!ast_context_find(context)) {
04625 ast_log(LOG_WARNING, "Context %s must exist in regcontext= in sip.conf!\n", context);
04626 continue;
04627 }
04628 } else {
04629 context = sip_cfg.regcontext;
04630 }
04631 if (onoff) {
04632 if (!ast_exists_extension(NULL, context, ext, 1, NULL)) {
04633 ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
04634 ast_strdup(peer->name), ast_free_ptr, "SIP");
04635 }
04636 } else if (pbx_find_extension(NULL, NULL, &q, context, ext, 1, NULL, "", E_MATCH)) {
04637 ast_context_remove_extension(context, ext, 1, NULL);
04638 }
04639 }
04640 }
04641
04642
04643 static void destroy_mailbox(struct sip_mailbox *mailbox)
04644 {
04645 if (mailbox->event_sub)
04646 ast_event_unsubscribe(mailbox->event_sub);
04647 ast_free(mailbox);
04648 }
04649
04650
04651 static void clear_peer_mailboxes(struct sip_peer *peer)
04652 {
04653 struct sip_mailbox *mailbox;
04654
04655 while ((mailbox = AST_LIST_REMOVE_HEAD(&peer->mailboxes, entry)))
04656 destroy_mailbox(mailbox);
04657 }
04658
04659 static void sip_destroy_peer_fn(void *peer)
04660 {
04661 sip_destroy_peer(peer);
04662 }
04663
04664
04665 static void sip_destroy_peer(struct sip_peer *peer)
04666 {
04667 ast_debug(3, "Destroying SIP peer %s\n", peer->name);
04668
04669
04670
04671
04672
04673
04674 clear_peer_mailboxes(peer);
04675
04676 if (peer->outboundproxy) {
04677 ao2_ref(peer->outboundproxy, -1);
04678 peer->outboundproxy = NULL;
04679 }
04680
04681
04682 if (peer->call) {
04683 dialog_unlink_all(peer->call);
04684 peer->call = dialog_unref(peer->call, "peer->call is being unset");
04685 }
04686
04687 if (peer->mwipvt) {
04688 dialog_unlink_all(peer->mwipvt);
04689 peer->mwipvt = dialog_unref(peer->mwipvt, "unreffing peer->mwipvt");
04690 }
04691
04692 if (peer->chanvars) {
04693 ast_variables_destroy(peer->chanvars);
04694 peer->chanvars = NULL;
04695 }
04696
04697 register_peer_exten(peer, FALSE);
04698 ast_free_ha(peer->ha);
04699 ast_free_ha(peer->directmediaha);
04700 if (peer->selfdestruct)
04701 ast_atomic_fetchadd_int(&apeerobjs, -1);
04702 else if (!ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && peer->is_realtime) {
04703 ast_atomic_fetchadd_int(&rpeerobjs, -1);
04704 ast_debug(3, "-REALTIME- peer Destroyed. Name: %s. Realtime Peer objects: %d\n", peer->name, rpeerobjs);
04705 } else
04706 ast_atomic_fetchadd_int(&speerobjs, -1);
04707 if (peer->auth) {
04708 ao2_t_ref(peer->auth, -1, "Removing peer authentication");
04709 peer->auth = NULL;
04710 }
04711
04712 if (peer->socket.tcptls_session) {
04713 ao2_ref(peer->socket.tcptls_session, -1);
04714 peer->socket.tcptls_session = NULL;
04715 }
04716
04717 ast_cc_config_params_destroy(peer->cc_params);
04718
04719 ast_string_field_free_memory(peer);
04720 }
04721
04722
04723 static void update_peer(struct sip_peer *p, int expire)
04724 {
04725 int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
04726 if (sip_cfg.peer_rtupdate &&
04727 (p->is_realtime || rtcachefriends)) {
04728 realtime_update_peer(p->name, &p->addr, p->username, p->fullcontact, p->useragent, expire, p->deprecated_username, p->lastms);
04729 }
04730 }
04731
04732 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *cfg)
04733 {
04734 struct ast_variable *var = NULL;
04735 struct ast_flags flags = {0};
04736 char *cat = NULL;
04737 const char *insecure;
04738 while ((cat = ast_category_browse(cfg, cat))) {
04739 insecure = ast_variable_retrieve(cfg, cat, "insecure");
04740 set_insecure_flags(&flags, insecure, -1);
04741 if (ast_test_flag(&flags, SIP_INSECURE_PORT)) {
04742 var = ast_category_root(cfg, cat);
04743 break;
04744 }
04745 }
04746 return var;
04747 }
04748
04749 static struct ast_variable *get_insecure_variable_from_sippeers(const char *column, const char *value)
04750 {
04751 struct ast_config *peerlist;
04752 struct ast_variable *var = NULL;
04753 if ((peerlist = ast_load_realtime_multientry("sippeers", column, value, "insecure LIKE", "%port%", SENTINEL))) {
04754 if ((var = get_insecure_variable_from_config(peerlist))) {
04755
04756
04757 var = ast_variables_dup(var);
04758 }
04759 ast_config_destroy(peerlist);
04760 }
04761 return var;
04762 }
04763
04764
04765
04766
04767
04768
04769 static struct ast_variable *get_insecure_variable_from_sipregs(const char *column, const char *value, struct ast_variable **var)
04770 {
04771 struct ast_variable *varregs = NULL;
04772 struct ast_config *regs, *peers;
04773 char *regscat;
04774 const char *regname;
04775
04776 if (!(regs = ast_load_realtime_multientry("sipregs", column, value, SENTINEL))) {
04777 return NULL;
04778 }
04779
04780
04781 if (!(peers = ast_load_realtime_multientry("sippeers", "insecure LIKE", "%port%", SENTINEL))) {
04782 ast_config_destroy(regs);
04783 return NULL;
04784 }
04785
04786
04787
04788 regscat = NULL;
04789 while ((regscat = ast_category_browse(regs, regscat)) && (regname = ast_variable_retrieve(regs, regscat, "name"))) {
04790 char *peerscat;
04791 const char *peername;
04792
04793 peerscat = NULL;
04794 while ((peerscat = ast_category_browse(peers, peerscat)) && (peername = ast_variable_retrieve(peers, peerscat, "name"))) {
04795 if (!strcasecmp(regname, peername)) {
04796
04797
04798 const char *insecure = ast_variable_retrieve(peers, peerscat, "insecure");
04799 struct ast_flags flags = {0};
04800 set_insecure_flags(&flags, insecure, -1);
04801 if (ast_test_flag(&flags, SIP_INSECURE_PORT)) {
04802
04803 if ((varregs = ast_variables_dup(ast_category_root(regs, regscat)))) {
04804 if (!(*var = ast_variables_dup(ast_category_root(peers, peerscat)))) {
04805 ast_variables_destroy(varregs);
04806 varregs = NULL;
04807 }
04808 }
04809 goto done;
04810 }
04811 }
04812 }
04813 }
04814
04815 done:
04816 ast_config_destroy(regs);
04817 ast_config_destroy(peers);
04818 return varregs;
04819 }
04820
04821 static const char *get_name_from_variable(const struct ast_variable *var)
04822 {
04823
04824
04825
04826
04827
04828
04829
04830
04831 const struct ast_variable *tmp;
04832 for (tmp = var; tmp; tmp = tmp->next) {
04833 if (!strcasecmp(tmp->name, "name")) {
04834 if (!ast_strlen_zero(tmp->value)) {
04835 return tmp->value;
04836 }
04837 break;
04838 }
04839 }
04840 return NULL;
04841 }
04842
04843
04844
04845 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)
04846 {
04847
04848 if ((*var = ast_load_realtime("sippeers", "name", *name, "host", "dynamic", SENTINEL))) {
04849 ;
04850
04851 } else if (addr && !(*var = ast_load_realtime("sippeers", "name", *name, "host", ipaddr, SENTINEL))) {
04852 ;
04853
04854 } else if ((*var = ast_load_realtime("sippeers", "name", *name, SENTINEL))) {
04855
04856
04857
04858
04859
04860
04861 if (addr) {
04862 struct ast_variable *tmp;
04863 for (tmp = *var; tmp; tmp = tmp->next) {
04864 if (!strcasecmp(tmp->name, "host")) {
04865 struct ast_sockaddr *addrs = NULL;
04866
04867 if (ast_sockaddr_resolve(&addrs,
04868 tmp->value,
04869 PARSE_PORT_FORBID,
04870 get_address_family_filter(SIP_TRANSPORT_UDP)) <= 0 ||
04871 ast_sockaddr_cmp(&addrs[0], addr)) {
04872
04873 ast_variables_destroy(*var);
04874 *var = NULL;
04875 }
04876 ast_free(addrs);
04877 break;
04878 }
04879 }
04880 }
04881 }
04882
04883
04884 if (*var) {
04885 if (varregs) {
04886 *varregs = ast_load_realtime("sipregs", "name", *name, SENTINEL);
04887 }
04888 return 1;
04889 }
04890 return 0;
04891 }
04892
04893
04894
04895
04896
04897
04898
04899 static struct ast_variable *realtime_peer_get_sippeer_helper(const char **name, struct ast_variable **varregs) {
04900 struct ast_variable *var = NULL;
04901 const char *old_name = *name;
04902 *name = get_name_from_variable(*varregs);
04903 if (!*name || !(var = ast_load_realtime("sippeers", "name", *name, SENTINEL))) {
04904 if (!*name) {
04905 ast_log(LOG_WARNING, "Found sipreg but it has no name\n");
04906 }
04907 ast_variables_destroy(*varregs);
04908 *varregs = NULL;
04909 *name = old_name;
04910 }
04911 return var;
04912 }
04913
04914
04915
04916
04917 static int realtime_peer_by_addr(const char **name, struct ast_sockaddr *addr, const char *ipaddr, struct ast_variable **var, struct ast_variable **varregs)
04918 {
04919 char portstring[6];
04920 ast_copy_string(portstring, ast_sockaddr_stringify_port(addr), sizeof(portstring));
04921
04922
04923 *name = NULL;
04924
04925
04926 if ((*var = ast_load_realtime("sippeers", "host", ipaddr, "port", portstring, SENTINEL))) {
04927 ;
04928
04929 } else if (varregs && (*varregs = ast_load_realtime("sipregs", "ipaddr", ipaddr, "port", portstring, SENTINEL)) &&
04930 (*var = realtime_peer_get_sippeer_helper(name, varregs))) {
04931 ;
04932
04933 } else if (!varregs && (*var = ast_load_realtime("sippeers", "ipaddr", ipaddr, "port", portstring, SENTINEL))) {
04934 ;
04935
04936 } else if ((*var = get_insecure_variable_from_sippeers("host", ipaddr))) {
04937 ;
04938
04939
04940
04941
04942 } else if (varregs && (*varregs = get_insecure_variable_from_sipregs("ipaddr", ipaddr, var))) {
04943 ;
04944
04945 } else if (!varregs && (*var = get_insecure_variable_from_sippeers("ipaddr", ipaddr))) {
04946 ;
04947 }
04948
04949
04950 if (!*var) {
04951 return 0;
04952 }
04953
04954
04955
04956
04957 if (!*name && !(*name = get_name_from_variable(*var))) {
04958 ast_log(LOG_WARNING, "Found peer for IP %s but it has no name\n", ipaddr);
04959 ast_variables_destroy(*var);
04960 *var = NULL;
04961 if (varregs && *varregs) {
04962 ast_variables_destroy(*varregs);
04963 *varregs = NULL;
04964 }
04965 return 0;
04966 }
04967
04968
04969
04970
04971 if (varregs && !*varregs) {
04972 *varregs = ast_load_realtime("sipregs", "name", *name, SENTINEL);
04973 }
04974 return 1;
04975 }
04976
04977
04978
04979
04980
04981
04982
04983
04984
04985
04986 static struct sip_peer *realtime_peer(const char *newpeername, struct ast_sockaddr *addr, int devstate_only, int which_objects)
04987 {
04988 struct sip_peer *peer = NULL;
04989 struct ast_variable *var = NULL;
04990 struct ast_variable *varregs = NULL;
04991 char ipaddr[INET6_ADDRSTRLEN];
04992 int realtimeregs = ast_check_realtime("sipregs");
04993
04994 if (addr) {
04995 ast_copy_string(ipaddr, ast_sockaddr_stringify_addr(addr), sizeof(ipaddr));
04996 } else {
04997 ipaddr[0] = '\0';
04998 }
04999
05000 if (newpeername && realtime_peer_by_name(&newpeername, addr, ipaddr, &var, realtimeregs ? &varregs : NULL)) {
05001 ;
05002 } else if (addr && realtime_peer_by_addr(&newpeername, addr, ipaddr, &var, realtimeregs ? &varregs : NULL)) {
05003 ;
05004 } else {
05005 return NULL;
05006 }
05007
05008
05009
05010 if (which_objects == FINDUSERS) {
05011 struct ast_variable *tmp;
05012 for (tmp = var; tmp; tmp = tmp->next) {
05013 if (!strcasecmp(tmp->name, "type") && (!strcasecmp(tmp->value, "peer"))) {
05014 goto cleanup;
05015 }
05016 }
05017 }
05018
05019
05020 peer = build_peer(newpeername, var, varregs, TRUE, devstate_only);
05021 if (!peer) {
05022 goto cleanup;
05023 }
05024
05025
05026
05027 if (peer->type == 0) {
05028 if (which_objects == FINDUSERS) {
05029 peer->type = SIP_TYPE_USER;
05030 } else if (which_objects == FINDPEERS) {
05031 peer->type = SIP_TYPE_PEER;
05032 } else {
05033 peer->type = SIP_TYPE_PEER | SIP_TYPE_USER;
05034 }
05035 }
05036
05037 ast_debug(3, "-REALTIME- loading peer from database to memory. Name: %s. Peer objects: %d\n", peer->name, rpeerobjs);
05038
05039 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && !devstate_only) {
05040
05041 ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
05042 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
05043 AST_SCHED_REPLACE_UNREF(peer->expire, sched, sip_cfg.rtautoclear * 1000, expire_register, peer,
05044 unref_peer(_data, "remove registration ref"),
05045 unref_peer(peer, "remove registration ref"),
05046 ref_peer(peer, "add registration ref"));
05047 }
05048 ao2_t_link(peers, peer, "link peer into peers table");
05049 if (!ast_sockaddr_isnull(&peer->addr)) {
05050 ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
05051 }
05052 }
05053 peer->is_realtime = 1;
05054
05055 cleanup:
05056 ast_variables_destroy(var);
05057 ast_variables_destroy(varregs);
05058 return peer;
05059 }
05060
05061
05062 static int find_by_name(void *obj, void *arg, void *data, int flags)
05063 {
05064 struct sip_peer *search = obj, *match = arg;
05065 int *which_objects = data;
05066
05067
05068 if (strcmp(search->name, match->name)) {
05069 return 0;
05070 }
05071
05072 switch (*which_objects) {
05073 case FINDUSERS:
05074 if (!(search->type & SIP_TYPE_USER)) {
05075 return 0;
05076 }
05077 break;
05078 case FINDPEERS:
05079 if (!(search->type & SIP_TYPE_PEER)) {
05080 return 0;
05081 }
05082 break;
05083 case FINDALLDEVICES:
05084 break;
05085 }
05086
05087 return CMP_MATCH | CMP_STOP;
05088 }
05089
05090
05091
05092
05093
05094
05095
05096
05097
05098
05099
05100
05101
05102
05103 static struct sip_peer *find_peer(const char *peer, struct ast_sockaddr *addr, int realtime, int which_objects, int devstate_only, int transport)
05104 {
05105 struct sip_peer *p = NULL;
05106 struct sip_peer tmp_peer;
05107
05108 if (peer) {
05109 ast_copy_string(tmp_peer.name, peer, sizeof(tmp_peer.name));
05110 p = ao2_t_callback_data(peers, OBJ_POINTER, find_by_name, &tmp_peer, &which_objects, "ao2_find in peers table");
05111 } else if (addr) {
05112 ast_sockaddr_copy(&tmp_peer.addr, addr);
05113 tmp_peer.flags[0].flags = 0;
05114 tmp_peer.transports = transport;
05115 p = ao2_t_find(peers_by_ip, &tmp_peer, OBJ_POINTER, "ao2_find in peers_by_ip table");
05116 if (!p) {
05117 ast_set_flag(&tmp_peer.flags[0], SIP_INSECURE_PORT);
05118 p = ao2_t_find(peers_by_ip, &tmp_peer, OBJ_POINTER, "ao2_find in peers_by_ip table 2");
05119 if (p) {
05120 return p;
05121 }
05122 }
05123 }
05124
05125 if (!p && (realtime || devstate_only)) {
05126 p = realtime_peer(peer, addr, devstate_only, which_objects);
05127 if (p) {
05128 switch (which_objects) {
05129 case FINDUSERS:
05130 if (!(p->type & SIP_TYPE_USER)) {
05131 unref_peer(p, "Wrong type of realtime SIP endpoint");
05132 return NULL;
05133 }
05134 break;
05135 case FINDPEERS:
05136 if (!(p->type & SIP_TYPE_PEER)) {
05137 unref_peer(p, "Wrong type of realtime SIP endpoint");
05138 return NULL;
05139 }
05140 break;
05141 case FINDALLDEVICES:
05142 break;
05143 }
05144 }
05145 }
05146
05147 return p;
05148 }
05149
05150
05151 static void do_setnat(struct sip_pvt *p)
05152 {
05153 const char *mode;
05154 int natflags;
05155
05156 natflags = ast_test_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP);
05157 mode = natflags ? "On" : "Off";
05158
05159 if (p->rtp) {
05160 ast_debug(1, "Setting NAT on RTP to %s\n", mode);
05161 ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_NAT, natflags);
05162 }
05163 if (p->vrtp) {
05164 ast_debug(1, "Setting NAT on VRTP to %s\n", mode);
05165 ast_rtp_instance_set_prop(p->vrtp, AST_RTP_PROPERTY_NAT, natflags);
05166 }
05167 if (p->udptl) {
05168 ast_debug(1, "Setting NAT on UDPTL to %s\n", mode);
05169 ast_udptl_setnat(p->udptl, natflags);
05170 }
05171 if (p->trtp) {
05172 ast_debug(1, "Setting NAT on TRTP to %s\n", mode);
05173 ast_rtp_instance_set_prop(p->trtp, AST_RTP_PROPERTY_NAT, natflags);
05174 }
05175 }
05176
05177
05178 static void change_t38_state(struct sip_pvt *p, int state)
05179 {
05180 int old = p->t38.state;
05181 struct ast_channel *chan = p->owner;
05182 struct ast_control_t38_parameters parameters = { .request_response = 0 };
05183
05184
05185 if (old == state)
05186 return;
05187
05188 p->t38.state = state;
05189 ast_debug(2, "T38 state changed to %d on channel %s\n", p->t38.state, chan ? chan->name : "<none>");
05190
05191
05192 if (!chan)
05193 return;
05194
05195
05196 switch (state) {
05197 case T38_PEER_REINVITE:
05198 parameters = p->t38.their_parms;
05199 parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
05200 parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
05201 ast_udptl_set_tag(p->udptl, "%s", chan->name);
05202 break;
05203 case T38_ENABLED:
05204 parameters = p->t38.their_parms;
05205 parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
05206 parameters.request_response = AST_T38_NEGOTIATED;
05207 ast_udptl_set_tag(p->udptl, "%s", chan->name);
05208 break;
05209 case T38_DISABLED:
05210 if (old == T38_ENABLED) {
05211 parameters.request_response = AST_T38_TERMINATED;
05212 } else if (old == T38_LOCAL_REINVITE) {
05213 parameters.request_response = AST_T38_REFUSED;
05214 }
05215 break;
05216 case T38_LOCAL_REINVITE:
05217
05218 break;
05219 }
05220
05221
05222 if (parameters.request_response)
05223 ast_queue_control_data(chan, AST_CONTROL_T38_PARAMETERS, ¶meters, sizeof(parameters));
05224 }
05225
05226
05227 static void set_t38_capabilities(struct sip_pvt *p)
05228 {
05229 if (p->udptl) {
05230 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY) {
05231 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
05232 } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_FEC) {
05233 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
05234 } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL) {
05235 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
05236 }
05237 }
05238 }
05239
05240 static void copy_socket_data(struct sip_socket *to_sock, const struct sip_socket *from_sock)
05241 {
05242 if (to_sock->tcptls_session) {
05243 ao2_ref(to_sock->tcptls_session, -1);
05244 to_sock->tcptls_session = NULL;
05245 }
05246
05247 if (from_sock->tcptls_session) {
05248 ao2_ref(from_sock->tcptls_session, +1);
05249 }
05250
05251 *to_sock = *from_sock;
05252 }
05253
05254
05255
05256
05257 static int dialog_initialize_rtp(struct sip_pvt *dialog)
05258 {
05259 struct ast_sockaddr bindaddr_tmp;
05260
05261 if (!sip_methods[dialog->method].need_rtp) {
05262 return 0;
05263 }
05264
05265 ast_sockaddr_copy(&bindaddr_tmp, &bindaddr);
05266 if (!(dialog->rtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr_tmp, NULL))) {
05267 return -1;
05268 }
05269
05270 if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS) ||
05271 (ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT) && (dialog->capability & AST_FORMAT_VIDEO_MASK))) {
05272 if (!(dialog->vrtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr_tmp, NULL))) {
05273 return -1;
05274 }
05275 ast_rtp_instance_set_timeout(dialog->vrtp, dialog->rtptimeout);
05276 ast_rtp_instance_set_hold_timeout(dialog->vrtp, dialog->rtpholdtimeout);
05277 ast_rtp_instance_set_keepalive(dialog->vrtp, dialog->rtpkeepalive);
05278
05279 ast_rtp_instance_set_prop(dialog->vrtp, AST_RTP_PROPERTY_RTCP, 1);
05280 ast_rtp_instance_set_qos(dialog->vrtp, global_tos_video, global_cos_video, "SIP VIDEO");
05281 }
05282
05283 if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_TEXTSUPPORT)) {
05284 if (!(dialog->trtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr_tmp, NULL))) {
05285 return -1;
05286 }
05287
05288 ast_rtp_instance_set_keepalive(dialog->trtp, dialog->rtpkeepalive);
05289
05290 ast_rtp_instance_set_prop(dialog->trtp, AST_RTP_PROPERTY_RTCP, 1);
05291 }
05292
05293 ast_rtp_instance_set_timeout(dialog->rtp, dialog->rtptimeout);
05294 ast_rtp_instance_set_hold_timeout(dialog->rtp, dialog->rtpholdtimeout);
05295 ast_rtp_instance_set_keepalive(dialog->rtp, dialog->rtpkeepalive);
05296
05297 ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_RTCP, 1);
05298 ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
05299 ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
05300
05301 ast_rtp_instance_set_qos(dialog->rtp, global_tos_audio, global_cos_audio, "SIP RTP");
05302
05303 do_setnat(dialog);
05304
05305 return 0;
05306 }
05307
05308
05309
05310
05311
05312
05313
05314
05315 static int create_addr_from_peer(struct sip_pvt *dialog, struct sip_peer *peer)
05316 {
05317 struct sip_auth_container *credentials;
05318
05319
05320
05321
05322 if (dialog->socket.type && check_request_transport(peer, dialog))
05323 return -1;
05324 copy_socket_data(&dialog->socket, &peer->socket);
05325
05326 if (!(ast_sockaddr_isnull(&peer->addr) && ast_sockaddr_isnull(&peer->defaddr)) &&
05327 (!peer->maxms || ((peer->lastms >= 0) && (peer->lastms <= peer->maxms)))) {
05328 dialog->sa = ast_sockaddr_isnull(&peer->addr) ? peer->defaddr : peer->addr;
05329 dialog->recv = dialog->sa;
05330 } else
05331 return -1;
05332
05333
05334 ast_copy_flags(&dialog->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
05335 ast_copy_flags(&dialog->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
05336 ast_copy_flags(&dialog->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
05337 dialog->capability = peer->capability;
05338 dialog->prefs = peer->prefs;
05339 dialog->amaflags = peer->amaflags;
05340
05341 ast_string_field_set(dialog, engine, peer->engine);
05342
05343 dialog->rtptimeout = peer->rtptimeout;
05344 dialog->rtpholdtimeout = peer->rtpholdtimeout;
05345 dialog->rtpkeepalive = peer->rtpkeepalive;
05346 if (dialog_initialize_rtp(dialog)) {
05347 return -1;
05348 }
05349
05350 if (dialog->rtp) {
05351 ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
05352 ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
05353
05354 ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(dialog->rtp), dialog->rtp, &dialog->prefs);
05355 dialog->autoframing = peer->autoframing;
05356 }
05357
05358
05359 ast_string_field_set(dialog, peername, peer->name);
05360 ast_string_field_set(dialog, authname, peer->username);
05361 ast_string_field_set(dialog, username, peer->username);
05362 ast_string_field_set(dialog, peersecret, peer->secret);
05363 ast_string_field_set(dialog, peermd5secret, peer->md5secret);
05364 ast_string_field_set(dialog, mohsuggest, peer->mohsuggest);
05365 ast_string_field_set(dialog, mohinterpret, peer->mohinterpret);
05366 ast_string_field_set(dialog, tohost, peer->tohost);
05367 ast_string_field_set(dialog, fullcontact, peer->fullcontact);
05368 ast_string_field_set(dialog, accountcode, peer->accountcode);
05369 ast_string_field_set(dialog, context, peer->context);
05370 ast_string_field_set(dialog, cid_num, peer->cid_num);
05371 ast_string_field_set(dialog, cid_name, peer->cid_name);
05372 ast_string_field_set(dialog, cid_tag, peer->cid_tag);
05373 ast_string_field_set(dialog, mwi_from, peer->mwi_from);
05374 if (!ast_strlen_zero(peer->parkinglot)) {
05375 ast_string_field_set(dialog, parkinglot, peer->parkinglot);
05376 }
05377 ast_string_field_set(dialog, engine, peer->engine);
05378 ref_proxy(dialog, obproxy_get(dialog, peer));
05379 dialog->callgroup = peer->callgroup;
05380 dialog->pickupgroup = peer->pickupgroup;
05381 dialog->allowtransfer = peer->allowtransfer;
05382 dialog->jointnoncodeccapability = dialog->noncodeccapability;
05383
05384
05385 ao2_lock(peer);
05386 credentials = peer->auth;
05387 if (credentials) {
05388 ao2_t_ref(credentials, +1, "Ref peer auth for dialog");
05389 }
05390 ao2_unlock(peer);
05391 ao2_lock(dialog);
05392 if (dialog->peerauth) {
05393 ao2_t_ref(dialog->peerauth, -1, "Unref old dialog peer auth");
05394 }
05395 dialog->peerauth = credentials;
05396 ao2_unlock(dialog);
05397
05398 dialog->maxcallbitrate = peer->maxcallbitrate;
05399 dialog->disallowed_methods = peer->disallowed_methods;
05400 ast_cc_copy_config_params(dialog->cc_params, peer->cc_params);
05401 if (ast_strlen_zero(dialog->tohost))
05402 ast_string_field_set(dialog, tohost, ast_sockaddr_stringify_host_remote(&dialog->sa));
05403 if (!ast_strlen_zero(peer->fromdomain)) {
05404 ast_string_field_set(dialog, fromdomain, peer->fromdomain);
05405 if (!dialog->initreq.headers) {
05406 char *new_callid;
05407 char *tmpcall = ast_strdupa(dialog->callid);
05408
05409 new_callid = strchr(tmpcall, '@');
05410 if (new_callid) {
05411 int callid_size;
05412
05413 *new_callid = '\0';
05414
05415
05416 callid_size = strlen(tmpcall) + strlen(peer->fromdomain) + 2;
05417 new_callid = ast_alloca(callid_size);
05418 snprintf(new_callid, callid_size, "%s@%s", tmpcall, peer->fromdomain);
05419 change_callid_pvt(dialog, new_callid);
05420 }
05421 }
05422 }
05423 if (!ast_strlen_zero(peer->fromuser))
05424 ast_string_field_set(dialog, fromuser, peer->fromuser);
05425 if (!ast_strlen_zero(peer->language))
05426 ast_string_field_set(dialog, language, peer->language);
05427
05428
05429
05430
05431 if (peer->maxms && peer->lastms)
05432 dialog->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
05433 else
05434 dialog->timer_t1 = peer->timer_t1;
05435
05436
05437
05438 if (peer->timer_b)
05439 dialog->timer_b = peer->timer_b;
05440 else
05441 dialog->timer_b = 64 * dialog->timer_t1;
05442
05443 if ((ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
05444 (ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
05445 dialog->noncodeccapability |= AST_RTP_DTMF;
05446 else
05447 dialog->noncodeccapability &= ~AST_RTP_DTMF;
05448 dialog->directmediaha = ast_duplicate_ha_list(peer->directmediaha);
05449 if (peer->call_limit)
05450 ast_set_flag(&dialog->flags[0], SIP_CALL_LIMIT);
05451 if (!dialog->portinuri)
05452 dialog->portinuri = peer->portinuri;
05453 dialog->chanvars = copy_vars(peer->chanvars);
05454 if (peer->fromdomainport)
05455 dialog->fromdomainport = peer->fromdomainport;
05456
05457 return 0;
05458 }
05459
05460
05461 static inline int default_sip_port(enum sip_transport type)
05462 {
05463 return type == SIP_TRANSPORT_TLS ? STANDARD_TLS_PORT : STANDARD_SIP_PORT;
05464 }
05465
05466
05467
05468
05469 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct ast_sockaddr *addr, int newdialog)
05470 {
05471 struct sip_peer *peer;
05472 char *peername, *peername2, *hostn;
05473 char host[MAXHOSTNAMELEN];
05474 char service[MAXHOSTNAMELEN];
05475 int srv_ret = 0;
05476 int tportno;
05477
05478 AST_DECLARE_APP_ARGS(hostport,
05479 AST_APP_ARG(host);
05480 AST_APP_ARG(port);
05481 );
05482
05483 peername = ast_strdupa(opeer);
05484 peername2 = ast_strdupa(opeer);
05485 AST_NONSTANDARD_RAW_ARGS(hostport, peername2, ':');
05486
05487 if (hostport.port)
05488 dialog->portinuri = 1;
05489
05490 dialog->timer_t1 = global_t1;
05491 dialog->timer_b = global_timer_b;
05492 peer = find_peer(peername, NULL, TRUE, FINDPEERS, FALSE, 0);
05493
05494 if (peer) {
05495 int res;
05496 if (newdialog) {
05497 set_socket_transport(&dialog->socket, 0);
05498 }
05499 res = create_addr_from_peer(dialog, peer);
05500 dialog->relatedpeer = ref_peer(peer, "create_addr: setting dialog's relatedpeer pointer");
05501 unref_peer(peer, "create_addr: unref peer from find_peer hashtab lookup");
05502 return res;
05503 } else if (ast_check_digits(peername)) {
05504
05505
05506
05507 ast_log(LOG_WARNING, "Purely numeric hostname (%s), and not a peer--rejecting!\n", peername);
05508 return -1;
05509 } else {
05510 dialog->rtptimeout = global_rtptimeout;
05511 dialog->rtpholdtimeout = global_rtpholdtimeout;
05512 dialog->rtpkeepalive = global_rtpkeepalive;
05513 if (dialog_initialize_rtp(dialog)) {
05514 return -1;
05515 }
05516 }
05517
05518 ast_string_field_set(dialog, tohost, hostport.host);
05519 dialog->allowed_methods &= ~sip_cfg.disallowed_methods;
05520
05521
05522 ref_proxy(dialog, obproxy_get(dialog, NULL));
05523
05524 if (addr) {
05525
05526 ast_sockaddr_copy(&dialog->sa, addr);
05527 } else {
05528
05529
05530
05531
05532
05533
05534 hostn = peername;
05535
05536
05537
05538 if (!hostport.port && sip_cfg.srvlookup) {
05539 snprintf(service, sizeof(service), "_%s._%s.%s",
05540 get_srv_service(dialog->socket.type),
05541 get_srv_protocol(dialog->socket.type), peername);
05542 if ((srv_ret = ast_get_srv(NULL, host, sizeof(host), &tportno,
05543 service)) > 0) {
05544 hostn = host;
05545 }
05546 }
05547
05548 if (ast_sockaddr_resolve_first_transport(&dialog->sa, hostn, 0, dialog->socket.type ? dialog->socket.type : SIP_TRANSPORT_UDP)) {
05549 ast_log(LOG_WARNING, "No such host: %s\n", peername);
05550 return -1;
05551 }
05552
05553 if (srv_ret > 0) {
05554 ast_sockaddr_set_port(&dialog->sa, tportno);
05555 }
05556 }
05557
05558 if (!dialog->socket.type)
05559 set_socket_transport(&dialog->socket, SIP_TRANSPORT_UDP);
05560 if (!dialog->socket.port) {
05561 dialog->socket.port = htons(ast_sockaddr_port(&bindaddr));
05562 }
05563
05564 if (!ast_sockaddr_port(&dialog->sa)) {
05565 ast_sockaddr_set_port(&dialog->sa, default_sip_port(dialog->socket.type));
05566 }
05567 ast_sockaddr_copy(&dialog->recv, &dialog->sa);
05568 return 0;
05569 }
05570
05571
05572
05573
05574 static int auto_congest(const void *arg)
05575 {
05576 struct sip_pvt *p = (struct sip_pvt *)arg;
05577
05578 sip_pvt_lock(p);
05579 p->initid = -1;
05580 if (p->owner) {
05581
05582 if (!ast_channel_trylock(p->owner)) {
05583 append_history(p, "Cong", "Auto-congesting (timer)");
05584 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
05585 ast_channel_unlock(p->owner);
05586 }
05587
05588
05589 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
05590 }
05591 sip_pvt_unlock(p);
05592 dialog_unref(p, "unreffing arg passed into auto_congest callback (p->initid)");
05593 return 0;
05594 }
05595
05596
05597
05598
05599 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
05600 {
05601 int res;
05602 struct sip_pvt *p = ast->tech_pvt;
05603 struct varshead *headp;
05604 struct ast_var_t *current;
05605 const char *referer = NULL;
05606 int cc_core_id;
05607 char uri[SIPBUFSIZE] = "";
05608
05609 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
05610 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
05611 return -1;
05612 }
05613
05614 if (ast_cc_is_recall(ast, &cc_core_id, "SIP")) {
05615 char device_name[AST_CHANNEL_NAME];
05616 struct ast_cc_monitor *recall_monitor;
05617 struct sip_monitor_instance *monitor_instance;
05618 ast_channel_get_device_name(ast, device_name, sizeof(device_name));
05619 if ((recall_monitor = ast_cc_get_monitor_by_recall_core_id(cc_core_id, device_name))) {
05620 monitor_instance = recall_monitor->private_data;
05621 ast_copy_string(uri, monitor_instance->notify_uri, sizeof(uri));
05622 ao2_t_ref(recall_monitor, -1, "Got the URI we need so unreffing monitor");
05623 }
05624 }
05625
05626
05627 headp=&ast->varshead;
05628 AST_LIST_TRAVERSE(headp, current, entries) {
05629
05630 if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
05631 p->options->vxml_url = ast_var_value(current);
05632 } else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
05633 p->options->uri_options = ast_var_value(current);
05634 } else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
05635
05636 p->options->addsipheaders = 1;
05637 } else if (!strcasecmp(ast_var_name(current), "SIPFROMDOMAIN")) {
05638 ast_string_field_set(p, fromdomain, ast_var_value(current));
05639 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER")) {
05640
05641 p->options->transfer = 1;
05642 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REFERER")) {
05643
05644 referer = ast_var_value(current);
05645 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REPLACES")) {
05646
05647 p->options->replaces = ast_var_value(current);
05648 } else if (!strcasecmp(ast_var_name(current), "SIP_MAX_FORWARDS")) {
05649 if (sscanf(ast_var_value(current), "%d", &(p->maxforwards)) != 1) {
05650 ast_log(LOG_WARNING, "The SIP_MAX_FORWARDS channel variable is not a valid integer.\n");
05651 }
05652 }
05653 }
05654
05655
05656 if (p->req_secure_signaling && p->socket.type != SIP_TRANSPORT_TLS) {
05657 ast_log(LOG_WARNING, "Encrypted signaling is required\n");
05658 ast->hangupcause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
05659 return -1;
05660 }
05661
05662 if (ast_test_flag(&p->flags[1], SIP_PAGE2_USE_SRTP)) {
05663 if (ast_test_flag(&p->flags[0], SIP_REINVITE)) {
05664 ast_debug(1, "Direct media not possible when using SRTP, ignoring canreinvite setting\n");
05665 ast_clear_flag(&p->flags[0], SIP_REINVITE);
05666 }
05667
05668 if (p->rtp && !p->srtp && setup_srtp(&p->srtp) < 0) {
05669 ast_log(LOG_WARNING, "SRTP audio setup failed\n");
05670 return -1;
05671 }
05672
05673 if (p->vrtp && !p->vsrtp && setup_srtp(&p->vsrtp) < 0) {
05674 ast_log(LOG_WARNING, "SRTP video setup failed\n");
05675 return -1;
05676 }
05677
05678 if (p->trtp && !p->tsrtp && setup_srtp(&p->tsrtp) < 0) {
05679 ast_log(LOG_WARNING, "SRTP text setup failed\n");
05680 return -1;
05681 }
05682 }
05683
05684 res = 0;
05685 ast_set_flag(&p->flags[0], SIP_OUTGOING);
05686
05687
05688
05689
05690 ast_clear_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_T38);
05691
05692 if (p->options->transfer) {
05693 char buf[SIPBUFSIZE/2];
05694
05695 if (referer) {
05696 if (sipdebug)
05697 ast_debug(3, "Call for %s transfered by %s\n", p->username, referer);
05698 snprintf(buf, sizeof(buf)-1, "-> %s (via %s)", p->cid_name, referer);
05699 } else
05700 snprintf(buf, sizeof(buf)-1, "-> %s", p->cid_name);
05701 ast_string_field_set(p, cid_name, buf);
05702 }
05703 ast_debug(1, "Outgoing Call for %s\n", p->username);
05704
05705 res = update_call_counter(p, INC_CALL_RINGING);
05706
05707 if (res == -1) {
05708 ast->hangupcause = AST_CAUSE_USER_BUSY;
05709 return res;
05710 }
05711 p->callingpres = ast_party_id_presentation(&ast->caller.id);
05712 p->jointcapability = ast_rtp_instance_available_formats(p->rtp, p->capability, p->prefcodec);
05713 p->jointnoncodeccapability = p->noncodeccapability;
05714
05715
05716 if (!(p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
05717 ast_log(LOG_WARNING, "No audio format found to offer. Cancelling call to %s\n", p->username);
05718 res = -1;
05719 } else {
05720 int xmitres;
05721 struct ast_party_connected_line connected;
05722 struct ast_set_party_connected_line update_connected;
05723
05724 sip_pvt_lock(p);
05725
05726
05727 memset(&update_connected, 0, sizeof(update_connected));
05728 ast_party_connected_line_init(&connected);
05729 if (!ast_strlen_zero(p->cid_num)
05730 || (p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
05731 update_connected.id.number = 1;
05732 connected.id.number.valid = 1;
05733 connected.id.number.str = (char *) p->cid_num;
05734 connected.id.number.presentation = p->callingpres;
05735 }
05736 if (!ast_strlen_zero(p->cid_name)
05737 || (p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
05738 update_connected.id.name = 1;
05739 connected.id.name.valid = 1;
05740 connected.id.name.str = (char *) p->cid_name;
05741 connected.id.name.presentation = p->callingpres;
05742 }
05743 if (update_connected.id.number || update_connected.id.name) {
05744 connected.id.tag = (char *) p->cid_tag;
05745 connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
05746 ast_channel_queue_connected_line_update(ast, &connected, &update_connected);
05747 }
05748
05749 xmitres = transmit_invite(p, SIP_INVITE, 1, 2, uri);
05750 if (xmitres == XMIT_ERROR) {
05751 sip_pvt_unlock(p);
05752 return -1;
05753 }
05754 p->invitestate = INV_CALLING;
05755
05756
05757 AST_SCHED_REPLACE_UNREF(p->initid, sched, p->timer_b, auto_congest, p,
05758 dialog_unref(_data, "dialog ptr dec when SCHED_REPLACE del op succeeded"),
05759 dialog_unref(p, "dialog ptr dec when SCHED_REPLACE add failed"),
05760 dialog_ref(p, "dialog ptr inc when SCHED_REPLACE add succeeded") );
05761 sip_pvt_unlock(p);
05762 }
05763 return res;
05764 }
05765
05766
05767
05768 static void sip_registry_destroy(struct sip_registry *reg)
05769 {
05770
05771 ast_debug(3, "Destroying registry entry for %s@%s\n", reg->username, reg->hostname);
05772
05773 if (reg->call) {
05774
05775
05776 reg->call->registry = registry_unref(reg->call->registry, "destroy reg->call->registry");
05777 ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", reg->username, reg->hostname);
05778 dialog_unlink_all(reg->call);
05779 reg->call = dialog_unref(reg->call, "unref reg->call");
05780
05781 }
05782 AST_SCHED_DEL(sched, reg->expire);
05783 AST_SCHED_DEL(sched, reg->timeout);
05784
05785 ast_string_field_free_memory(reg);
05786 ast_atomic_fetchadd_int(®objs, -1);
05787 ast_free(reg);
05788 }
05789
05790
05791 static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi)
05792 {
05793 if (mwi->call) {
05794 mwi->call->mwi = NULL;
05795 sip_destroy(mwi->call);
05796 }
05797
05798 AST_SCHED_DEL(sched, mwi->resub);
05799 ast_string_field_free_memory(mwi);
05800 ast_free(mwi);
05801 }
05802
05803
05804 void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist)
05805 {
05806 struct sip_request *req;
05807
05808
05809 if (p->stimer) {
05810 p->stimer->quit_flag = 1;
05811 stop_session_timer(p);
05812 ast_free(p->stimer);
05813 p->stimer = NULL;
05814 }
05815
05816 if (sip_debug_test_pvt(p))
05817 ast_verbose("Really destroying SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
05818
05819 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
05820 update_call_counter(p, DEC_CALL_LIMIT);
05821 ast_debug(2, "This call did not properly clean up call limits. Call ID %s\n", p->callid);
05822 }
05823
05824
05825 if (p->owner) {
05826 if (lockowner)
05827 ast_channel_lock(p->owner);
05828 ast_debug(1, "Detaching from %s\n", p->owner->name);
05829 p->owner->tech_pvt = NULL;
05830
05831 p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
05832 if (lockowner)
05833 ast_channel_unlock(p->owner);
05834
05835 usleep(1);
05836 }
05837
05838
05839 if (p->relatedpeer && p->relatedpeer->mwipvt == p)
05840 p->relatedpeer->mwipvt = dialog_unref(p->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
05841 if (p->relatedpeer && p->relatedpeer->call == p)
05842 p->relatedpeer->call = dialog_unref(p->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
05843
05844 if (p->relatedpeer)
05845 p->relatedpeer = unref_peer(p->relatedpeer,"unsetting a dialog relatedpeer field in sip_destroy");
05846
05847 if (p->registry) {
05848 if (p->registry->call == p)
05849 p->registry->call = dialog_unref(p->registry->call, "nulling out the registry's call dialog field in unlink_all");
05850 p->registry = registry_unref(p->registry, "delete p->registry");
05851 }
05852
05853 if (p->mwi) {
05854 p->mwi->call = NULL;
05855 p->mwi = NULL;
05856 }
05857
05858 if (dumphistory)
05859 sip_dump_history(p);
05860
05861 if (p->options) {
05862 if (p->options->outboundproxy) {
05863 ao2_ref(p->options->outboundproxy, -1);
05864 }
05865 ast_free(p->options);
05866 p->options = NULL;
05867 }
05868
05869 if (p->notify) {
05870 ast_variables_destroy(p->notify->headers);
05871 ast_free(p->notify->content);
05872 ast_free(p->notify);
05873 p->notify = NULL;
05874 }
05875 if (p->rtp) {
05876 ast_rtp_instance_destroy(p->rtp);
05877 p->rtp = NULL;
05878 }
05879 if (p->vrtp) {
05880 ast_rtp_instance_destroy(p->vrtp);
05881 p->vrtp = NULL;
05882 }
05883 if (p->trtp) {
05884 ast_rtp_instance_destroy(p->trtp);
05885 p->trtp = NULL;
05886 }
05887 if (p->udptl) {
05888 ast_udptl_destroy(p->udptl);
05889 p->udptl = NULL;
05890 }
05891 if (p->refer) {
05892 if (p->refer->refer_call) {
05893 p->refer->refer_call = dialog_unref(p->refer->refer_call, "unref dialog p->refer->refer_call");
05894 }
05895 ast_free(p->refer);
05896 p->refer = NULL;
05897 }
05898 if (p->route) {
05899 free_old_route(p->route);
05900 p->route = NULL;
05901 }
05902 deinit_req(&p->initreq);
05903
05904
05905 if (p->history) {
05906 struct sip_history *hist;
05907 while ( (hist = AST_LIST_REMOVE_HEAD(p->history, list)) ) {
05908 ast_free(hist);
05909 p->history_entries--;
05910 }
05911 ast_free(p->history);
05912 p->history = NULL;
05913 }
05914
05915 while ((req = AST_LIST_REMOVE_HEAD(&p->request_queue, next))) {
05916 ast_free(req);
05917 }
05918
05919 if (p->chanvars) {
05920 ast_variables_destroy(p->chanvars);
05921 p->chanvars = NULL;
05922 }
05923
05924 if (p->srtp) {
05925 sip_srtp_destroy(p->srtp);
05926 p->srtp = NULL;
05927 }
05928
05929 if (p->vsrtp) {
05930 sip_srtp_destroy(p->vsrtp);
05931 p->vsrtp = NULL;
05932 }
05933
05934 if (p->tsrtp) {
05935 sip_srtp_destroy(p->tsrtp);
05936 p->tsrtp = NULL;
05937 }
05938
05939 if (p->directmediaha) {
05940 ast_free_ha(p->directmediaha);
05941 p->directmediaha = NULL;
05942 }
05943
05944 ast_string_field_free_memory(p);
05945
05946 ast_cc_config_params_destroy(p->cc_params);
05947 p->cc_params = NULL;
05948
05949 if (p->epa_entry) {
05950 ao2_ref(p->epa_entry, -1);
05951 p->epa_entry = NULL;
05952 }
05953
05954 if (p->socket.tcptls_session) {
05955 ao2_ref(p->socket.tcptls_session, -1);
05956 p->socket.tcptls_session = NULL;
05957 }
05958
05959 if (p->peerauth) {
05960 ao2_t_ref(p->peerauth, -1, "Removing active peer authentication");
05961 p->peerauth = NULL;
05962 }
05963 }
05964
05965
05966
05967
05968
05969
05970
05971
05972
05973
05974
05975
05976
05977
05978
05979 static int update_call_counter(struct sip_pvt *fup, int event)
05980 {
05981 char name[256];
05982 int *inuse = NULL, *call_limit = NULL, *inringing = NULL;
05983 int outgoing = fup->outgoing_call;
05984 struct sip_peer *p = NULL;
05985
05986 ast_debug(3, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
05987
05988
05989
05990
05991 if (!ast_test_flag(&fup->flags[0], SIP_CALL_LIMIT) && !ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD))
05992 return 0;
05993
05994 ast_copy_string(name, fup->username, sizeof(name));
05995
05996
05997 if (fup->relatedpeer) {
05998 p = ref_peer(fup->relatedpeer, "ref related peer for update_call_counter");
05999 inuse = &p->inUse;
06000 call_limit = &p->call_limit;
06001 inringing = &p->inRinging;
06002 ast_copy_string(name, fup->peername, sizeof(name));
06003 }
06004 if (!p) {
06005 ast_debug(2, "%s is not a local device, no call limit\n", name);
06006 return 0;
06007 }
06008
06009 switch(event) {
06010
06011 case DEC_CALL_LIMIT:
06012
06013 if (inuse) {
06014 sip_pvt_lock(fup);
06015 ao2_lock(p);
06016 if (*inuse > 0) {
06017 if (ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
06018 (*inuse)--;
06019 ast_clear_flag(&fup->flags[0], SIP_INC_COUNT);
06020 }
06021 } else {
06022 *inuse = 0;
06023 }
06024 ao2_unlock(p);
06025 sip_pvt_unlock(fup);
06026 }
06027
06028
06029 if (inringing) {
06030 sip_pvt_lock(fup);
06031 ao2_lock(p);
06032 if (*inringing > 0) {
06033 if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
06034 (*inringing)--;
06035 ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
06036 }
06037 } else {
06038 *inringing = 0;
06039 }
06040 ao2_unlock(p);
06041 sip_pvt_unlock(fup);
06042 }
06043
06044
06045 sip_pvt_lock(fup);
06046 ao2_lock(p);
06047 if (ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD) && sip_cfg.notifyhold) {
06048 ast_clear_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD);
06049 ao2_unlock(p);
06050 sip_pvt_unlock(fup);
06051 sip_peer_hold(fup, FALSE);
06052 } else {
06053 ao2_unlock(p);
06054 sip_pvt_unlock(fup);
06055 }
06056 if (sipdebug)
06057 ast_debug(2, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
06058 break;
06059
06060 case INC_CALL_RINGING:
06061 case INC_CALL_LIMIT:
06062
06063 if (*call_limit > 0 ) {
06064 if (*inuse >= *call_limit) {
06065 ast_log(LOG_NOTICE, "Call %s %s '%s' rejected due to usage limit of %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
06066 unref_peer(p, "update_call_counter: unref peer p, call limit exceeded");
06067 return -1;
06068 }
06069 }
06070 if (inringing && (event == INC_CALL_RINGING)) {
06071 sip_pvt_lock(fup);
06072 ao2_lock(p);
06073 if (!ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
06074 (*inringing)++;
06075 ast_set_flag(&fup->flags[0], SIP_INC_RINGING);
06076 }
06077 ao2_unlock(p);
06078 sip_pvt_unlock(fup);
06079 }
06080 if (inuse) {
06081 sip_pvt_lock(fup);
06082 ao2_lock(p);
06083 if (!ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
06084 (*inuse)++;
06085 ast_set_flag(&fup->flags[0], SIP_INC_COUNT);
06086 }
06087 ao2_unlock(p);
06088 sip_pvt_unlock(fup);
06089 }
06090 if (sipdebug) {
06091 ast_debug(2, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", "peer", name, *inuse, *call_limit);
06092 }
06093 break;
06094
06095 case DEC_CALL_RINGING:
06096 if (inringing) {
06097 sip_pvt_lock(fup);
06098 ao2_lock(p);
06099 if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
06100 if (*inringing > 0) {
06101 (*inringing)--;
06102 }
06103 ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
06104 }
06105 ao2_unlock(p);
06106 sip_pvt_unlock(fup);
06107 }
06108 break;
06109
06110 default:
06111 ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
06112 }
06113
06114 if (p) {
06115 ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", p->name);
06116 unref_peer(p, "update_call_counter: unref_peer from call counter");
06117 }
06118 return 0;
06119 }
06120
06121
06122 static void sip_destroy_fn(void *p)
06123 {
06124 sip_destroy(p);
06125 }
06126
06127
06128
06129
06130
06131
06132 struct sip_pvt *sip_destroy(struct sip_pvt *p)
06133 {
06134 ast_debug(3, "Destroying SIP dialog %s\n", p->callid);
06135 __sip_destroy(p, TRUE, TRUE);
06136 return NULL;
06137 }
06138
06139
06140 int hangup_sip2cause(int cause)
06141 {
06142
06143
06144 switch(cause) {
06145 case 401:
06146 return AST_CAUSE_CALL_REJECTED;
06147 case 403:
06148 return AST_CAUSE_CALL_REJECTED;
06149 case 404:
06150 return AST_CAUSE_UNALLOCATED;
06151 case 405:
06152 return AST_CAUSE_INTERWORKING;
06153 case 407:
06154 return AST_CAUSE_CALL_REJECTED;
06155 case 408:
06156 return AST_CAUSE_NO_USER_RESPONSE;
06157 case 409:
06158 return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
06159 case 410:
06160 return AST_CAUSE_NUMBER_CHANGED;
06161 case 411:
06162 return AST_CAUSE_INTERWORKING;
06163 case 413:
06164 return AST_CAUSE_INTERWORKING;
06165 case 414:
06166 return AST_CAUSE_INTERWORKING;
06167 case 415:
06168 return AST_CAUSE_INTERWORKING;
06169 case 420:
06170 return AST_CAUSE_NO_ROUTE_DESTINATION;
06171 case 480:
06172 return AST_CAUSE_NO_ANSWER;
06173 case 481:
06174 return AST_CAUSE_INTERWORKING;
06175 case 482:
06176 return AST_CAUSE_INTERWORKING;
06177 case 483:
06178 return AST_CAUSE_NO_ANSWER;
06179 case 484:
06180 return AST_CAUSE_INVALID_NUMBER_FORMAT;
06181 case 485:
06182 return AST_CAUSE_UNALLOCATED;
06183 case 486:
06184 return AST_CAUSE_BUSY;
06185 case 487:
06186 return AST_CAUSE_INTERWORKING;
06187 case 488:
06188 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
06189 case 491:
06190 return AST_CAUSE_INTERWORKING;
06191 case 493:
06192 return AST_CAUSE_INTERWORKING;
06193 case 500:
06194 return AST_CAUSE_FAILURE;
06195 case 501:
06196 return AST_CAUSE_FACILITY_REJECTED;
06197 case 502:
06198 return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
06199 case 503:
06200 return AST_CAUSE_CONGESTION;
06201 case 504:
06202 return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
06203 case 505:
06204 return AST_CAUSE_INTERWORKING;
06205 case 600:
06206 return AST_CAUSE_USER_BUSY;
06207 case 603:
06208 return AST_CAUSE_CALL_REJECTED;
06209 case 604:
06210 return AST_CAUSE_UNALLOCATED;
06211 case 606:
06212 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
06213 default:
06214 if (cause < 500 && cause >= 400) {
06215
06216 return AST_CAUSE_INTERWORKING;
06217 } else if (cause < 600 && cause >= 500) {
06218
06219 return AST_CAUSE_CONGESTION;
06220 } else if (cause < 700 && cause >= 600) {
06221
06222 return AST_CAUSE_INTERWORKING;
06223 }
06224 return AST_CAUSE_NORMAL;
06225 }
06226
06227 return 0;
06228 }
06229
06230
06231
06232
06233
06234
06235
06236
06237
06238
06239
06240
06241
06242
06243
06244
06245
06246
06247
06248
06249
06250
06251
06252
06253
06254
06255
06256
06257
06258
06259
06260
06261
06262 const char *hangup_cause2sip(int cause)
06263 {
06264 switch (cause) {
06265 case AST_CAUSE_UNALLOCATED:
06266 case AST_CAUSE_NO_ROUTE_DESTINATION:
06267 case AST_CAUSE_NO_ROUTE_TRANSIT_NET:
06268 return "404 Not Found";
06269 case AST_CAUSE_CONGESTION:
06270 case AST_CAUSE_SWITCH_CONGESTION:
06271 return "503 Service Unavailable";
06272 case AST_CAUSE_NO_USER_RESPONSE:
06273 return "408 Request Timeout";
06274 case AST_CAUSE_NO_ANSWER:
06275 case AST_CAUSE_UNREGISTERED:
06276 return "480 Temporarily unavailable";
06277 case AST_CAUSE_CALL_REJECTED:
06278 return "403 Forbidden";
06279 case AST_CAUSE_NUMBER_CHANGED:
06280 return "410 Gone";
06281 case AST_CAUSE_NORMAL_UNSPECIFIED:
06282 return "480 Temporarily unavailable";
06283 case AST_CAUSE_INVALID_NUMBER_FORMAT:
06284 return "484 Address incomplete";
06285 case AST_CAUSE_USER_BUSY:
06286 return "486 Busy here";
06287 case AST_CAUSE_FAILURE:
06288 return "500 Server internal failure";
06289 case AST_CAUSE_FACILITY_REJECTED:
06290 return "501 Not Implemented";
06291 case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
06292 return "503 Service Unavailable";
06293
06294 case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
06295 return "502 Bad Gateway";
06296 case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL:
06297 return "488 Not Acceptable Here";
06298
06299 case AST_CAUSE_NOTDEFINED:
06300 default:
06301 ast_debug(1, "AST hangup cause %d (no match found in SIP)\n", cause);
06302 return NULL;
06303 }
06304
06305
06306 return 0;
06307 }
06308
06309 static int reinvite_timeout(const void *data)
06310 {
06311 struct sip_pvt *dialog = (struct sip_pvt *) data;
06312 struct ast_channel *owner = sip_pvt_lock_full(dialog);
06313 dialog->reinviteid = -1;
06314 check_pendings(dialog);
06315 if (owner) {
06316 ast_channel_unlock(owner);
06317 ast_channel_unref(owner);
06318 }
06319 ao2_unlock(dialog);
06320 dialog_unref(dialog, "unref for reinvite timeout");
06321 return 0;
06322 }
06323
06324
06325
06326 static int sip_hangup(struct ast_channel *ast)
06327 {
06328 struct sip_pvt *p = ast->tech_pvt;
06329 int needcancel = FALSE;
06330 int needdestroy = 0;
06331 struct ast_channel *oldowner = ast;
06332
06333 if (!p) {
06334 ast_debug(1, "Asked to hangup channel that was not connected\n");
06335 return 0;
06336 }
06337 if (ast_test_flag(ast, AST_FLAG_ANSWERED_ELSEWHERE) || ast->hangupcause == AST_CAUSE_ANSWERED_ELSEWHERE) {
06338 ast_debug(1, "This call was answered elsewhere\n");
06339 if (ast->hangupcause == AST_CAUSE_ANSWERED_ELSEWHERE) {
06340 ast_debug(1, "####### It's the cause code, buddy. The cause code!!!\n");
06341 }
06342 append_history(p, "Cancel", "Call answered elsewhere");
06343 p->answered_elsewhere = TRUE;
06344 }
06345
06346
06347 if (p->owner)
06348 p->hangupcause = p->owner->hangupcause;
06349
06350 if (ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
06351 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
06352 if (sipdebug)
06353 ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
06354 update_call_counter(p, DEC_CALL_LIMIT);
06355 }
06356 ast_debug(4, "SIP Transfer: Not hanging up right now... Rescheduling hangup for %s.\n", p->callid);
06357 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06358 ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
06359 p->needdestroy = 0;
06360 p->owner->tech_pvt = dialog_unref(p->owner->tech_pvt, "unref p->owner->tech_pvt");
06361 sip_pvt_lock(p);
06362 p->owner = NULL;
06363 sip_pvt_unlock(p);
06364 ast_module_unref(ast_module_info->self);
06365 return 0;
06366 }
06367
06368 ast_debug(1, "Hangup call %s, SIP callid %s\n", ast->name, p->callid);
06369
06370 sip_pvt_lock(p);
06371 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
06372 if (sipdebug)
06373 ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
06374 update_call_counter(p, DEC_CALL_LIMIT);
06375 }
06376
06377
06378 if (p->owner != ast) {
06379 ast_log(LOG_WARNING, "Huh? We aren't the owner? Can't hangup call.\n");
06380 sip_pvt_unlock(p);
06381 return 0;
06382 }
06383
06384
06385 if (p->invitestate < INV_COMPLETED && p->owner->_state != AST_STATE_UP) {
06386 needcancel = TRUE;
06387 ast_debug(4, "Hanging up channel in state %s (not UP)\n", ast_state2str(ast->_state));
06388 }
06389
06390 stop_media_flows(p);
06391
06392 append_history(p, needcancel ? "Cancel" : "Hangup", "Cause %s", p->owner ? ast_cause2str(p->hangupcause) : "Unknown");
06393
06394
06395 disable_dsp_detect(p);
06396
06397 p->owner = NULL;
06398 ast->tech_pvt = dialog_unref(ast->tech_pvt, "unref ast->tech_pvt");
06399
06400 ast_module_unref(ast_module_info->self);
06401
06402
06403
06404
06405
06406
06407 if (p->alreadygone)
06408 needdestroy = 1;
06409 else if (p->invitestate != INV_CALLING)
06410 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06411
06412
06413 if (!p->alreadygone && p->initreq.data && !ast_strlen_zero(p->initreq.data->str)) {
06414 if (needcancel) {
06415 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06416
06417 if (p->invitestate == INV_CALLING) {
06418
06419 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
06420
06421 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06422 append_history(p, "DELAY", "Not sending cancel, waiting for timeout");
06423 } else {
06424 struct sip_pkt *cur;
06425
06426 for (cur = p->packets; cur; cur = cur->next) {
06427 __sip_semi_ack(p, cur->seqno, cur->is_resp, cur->method ? cur->method : find_sip_method(cur->data->str));
06428 }
06429 p->invitestate = INV_CANCELLED;
06430
06431 transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
06432
06433
06434 needdestroy = 0;
06435 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06436 }
06437 } else {
06438 const char *res;
06439 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"));
06440 if (p->hangupcause && (res = hangup_cause2sip(p->hangupcause)))
06441 transmit_response_reliable(p, res, &p->initreq);
06442 else
06443 transmit_response_reliable(p, "603 Declined", &p->initreq);
06444 p->invitestate = INV_TERMINATED;
06445 }
06446 } else {
06447 if (p->stimer->st_active == TRUE) {
06448 stop_session_timer(p);
06449 }
06450
06451 if (!p->pendinginvite) {
06452 struct ast_channel *bridge = ast_bridged_channel(oldowner);
06453 char quality_buf[AST_MAX_USER_FIELD], *quality;
06454
06455
06456
06457
06458 while (bridge && ast_channel_trylock(bridge)) {
06459 sip_pvt_unlock(p);
06460 do {
06461 CHANNEL_DEADLOCK_AVOIDANCE(oldowner);
06462 } while (sip_pvt_trylock(p));
06463 bridge = ast_bridged_channel(oldowner);
06464 }
06465
06466 if (p->rtp) {
06467 ast_rtp_instance_set_stats_vars(oldowner, p->rtp);
06468 }
06469
06470 if (bridge) {
06471 struct sip_pvt *q = bridge->tech_pvt;
06472
06473 if (IS_SIP_TECH(bridge->tech) && q && q->rtp) {
06474 ast_rtp_instance_set_stats_vars(bridge, q->rtp);
06475 }
06476 ast_channel_unlock(bridge);
06477 }
06478
06479
06480
06481
06482
06483 if (p->rtp && (quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
06484 if (p->do_history) {
06485 append_history(p, "RTCPaudio", "Quality:%s", quality);
06486 }
06487 pbx_builtin_setvar_helper(oldowner, "RTPAUDIOQOS", quality);
06488 }
06489 if (p->vrtp && (quality = ast_rtp_instance_get_quality(p->vrtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
06490 if (p->do_history) {
06491 append_history(p, "RTCPvideo", "Quality:%s", quality);
06492 }
06493 pbx_builtin_setvar_helper(oldowner, "RTPVIDEOQOS", quality);
06494 }
06495 if (p->trtp && (quality = ast_rtp_instance_get_quality(p->trtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
06496 if (p->do_history) {
06497 append_history(p, "RTCPtext", "Quality:%s", quality);
06498 }
06499 pbx_builtin_setvar_helper(oldowner, "RTPTEXTQOS", quality);
06500 }
06501
06502
06503 if (oldowner->_state == AST_STATE_UP) {
06504 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
06505 }
06506
06507 } else {
06508
06509
06510 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
06511 ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);
06512 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"));
06513 if (sip_cancel_destroy(p)) {
06514 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
06515 }
06516
06517
06518
06519
06520 if (p->ongoing_reinvite && p->reinviteid < 0) {
06521 p->reinviteid = ast_sched_add(sched, 32 * p->timer_t1, reinvite_timeout, dialog_ref(p, "ref for reinvite_timeout"));
06522 }
06523 }
06524 }
06525 }
06526 if (needdestroy) {
06527 pvt_set_needdestroy(p, "hangup");
06528 }
06529 sip_pvt_unlock(p);
06530 return 0;
06531 }
06532
06533
06534 static void try_suggested_sip_codec(struct sip_pvt *p)
06535 {
06536 format_t fmt;
06537 const char *codec;
06538
06539 if (p->outgoing_call) {
06540 codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC_OUTBOUND");
06541 } else if (!(codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC_INBOUND"))) {
06542 codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC");
06543 }
06544
06545 if (!codec)
06546 return;
06547
06548 fmt = ast_getformatbyname(codec);
06549 if (fmt) {
06550 ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC} variable\n", codec);
06551 if (p->jointcapability & fmt) {
06552 p->jointcapability &= fmt;
06553 p->capability &= fmt;
06554 } else
06555 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
06556 } else
06557 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n", codec);
06558 return;
06559 }
06560
06561
06562
06563 static int sip_answer(struct ast_channel *ast)
06564 {
06565 int res = 0;
06566 struct sip_pvt *p = ast->tech_pvt;
06567
06568 sip_pvt_lock(p);
06569 if (ast->_state != AST_STATE_UP) {
06570 try_suggested_sip_codec(p);
06571
06572 ast_setstate(ast, AST_STATE_UP);
06573 ast_debug(1, "SIP answering channel: %s\n", ast->name);
06574 ast_rtp_instance_update_source(p->rtp);
06575 res = transmit_response_with_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL, FALSE, TRUE);
06576 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
06577 }
06578 sip_pvt_unlock(p);
06579 return res;
06580 }
06581
06582
06583 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
06584 {
06585 struct sip_pvt *p = ast->tech_pvt;
06586 int res = 0;
06587
06588 switch (frame->frametype) {
06589 case AST_FRAME_VOICE:
06590 if (!(frame->subclass.codec & ast->nativeformats)) {
06591 char s1[512], s2[512], s3[512];
06592 ast_log(LOG_WARNING, "Asked to transmit frame type %s, while native formats is %s read/write = %s/%s\n",
06593 ast_getformatname(frame->subclass.codec),
06594 ast_getformatname_multiple(s1, sizeof(s1), ast->nativeformats & AST_FORMAT_AUDIO_MASK),
06595 ast_getformatname_multiple(s2, sizeof(s2), ast->readformat),
06596 ast_getformatname_multiple(s3, sizeof(s3), ast->writeformat));
06597 return 0;
06598 }
06599 if (p) {
06600 sip_pvt_lock(p);
06601 if (p->t38.state == T38_ENABLED) {
06602
06603 sip_pvt_unlock(p);
06604 break;
06605 } else if (p->rtp) {
06606
06607 if ((ast->_state != AST_STATE_UP) &&
06608 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06609 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06610 ast_rtp_instance_update_source(p->rtp);
06611 if (!global_prematuremediafilter) {
06612 p->invitestate = INV_EARLY_MEDIA;
06613 transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06614 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06615 }
06616 }
06617 p->lastrtptx = time(NULL);
06618 res = ast_rtp_instance_write(p->rtp, frame);
06619 }
06620 sip_pvt_unlock(p);
06621 }
06622 break;
06623 case AST_FRAME_VIDEO:
06624 if (p) {
06625 sip_pvt_lock(p);
06626 if (p->vrtp) {
06627
06628 if ((ast->_state != AST_STATE_UP) &&
06629 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06630 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06631 p->invitestate = INV_EARLY_MEDIA;
06632 transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06633 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06634 }
06635 p->lastrtptx = time(NULL);
06636 res = ast_rtp_instance_write(p->vrtp, frame);
06637 }
06638 sip_pvt_unlock(p);
06639 }
06640 break;
06641 case AST_FRAME_TEXT:
06642 if (p) {
06643 sip_pvt_lock(p);
06644 if (p->red) {
06645 ast_rtp_red_buffer(p->trtp, frame);
06646 } else {
06647 if (p->trtp) {
06648
06649 if ((ast->_state != AST_STATE_UP) &&
06650 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06651 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06652 p->invitestate = INV_EARLY_MEDIA;
06653 transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06654 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06655 }
06656 p->lastrtptx = time(NULL);
06657 res = ast_rtp_instance_write(p->trtp, frame);
06658 }
06659 }
06660 sip_pvt_unlock(p);
06661 }
06662 break;
06663 case AST_FRAME_IMAGE:
06664 return 0;
06665 break;
06666 case AST_FRAME_MODEM:
06667 if (p) {
06668 sip_pvt_lock(p);
06669
06670
06671
06672
06673 if ((ast->_state == AST_STATE_UP) &&
06674 p->udptl &&
06675 (p->t38.state == T38_ENABLED)) {
06676 res = ast_udptl_write(p->udptl, frame);
06677 }
06678 sip_pvt_unlock(p);
06679 }
06680 break;
06681 default:
06682 ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
06683 return 0;
06684 }
06685
06686 return res;
06687 }
06688
06689
06690
06691 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
06692 {
06693 int ret = -1;
06694 struct sip_pvt *p;
06695
06696 if (newchan && ast_test_flag(newchan, AST_FLAG_ZOMBIE))
06697 ast_debug(1, "New channel is zombie\n");
06698 if (oldchan && ast_test_flag(oldchan, AST_FLAG_ZOMBIE))
06699 ast_debug(1, "Old channel is zombie\n");
06700
06701 if (!newchan || !newchan->tech_pvt) {
06702 if (!newchan)
06703 ast_log(LOG_WARNING, "No new channel! Fixup of %s failed.\n", oldchan->name);
06704 else
06705 ast_log(LOG_WARNING, "No SIP tech_pvt! Fixup of %s failed.\n", oldchan->name);
06706 return -1;
06707 }
06708 p = newchan->tech_pvt;
06709
06710 sip_pvt_lock(p);
06711 append_history(p, "Masq", "Old channel: %s\n", oldchan->name);
06712 append_history(p, "Masq (cont)", "...new owner: %s\n", newchan->name);
06713 if (p->owner != oldchan)
06714 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
06715 else {
06716 p->owner = newchan;
06717
06718
06719
06720
06721
06722
06723 sip_set_rtp_peer(newchan, NULL, NULL, 0, 0, 0);
06724 ret = 0;
06725 }
06726 ast_debug(3, "SIP Fixup: New owner for dialogue %s: %s (Old parent: %s)\n", p->callid, p->owner->name, oldchan->name);
06727
06728 sip_pvt_unlock(p);
06729 return ret;
06730 }
06731
06732 static int sip_senddigit_begin(struct ast_channel *ast, char digit)
06733 {
06734 struct sip_pvt *p = ast->tech_pvt;
06735 int res = 0;
06736
06737 sip_pvt_lock(p);
06738 switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
06739 case SIP_DTMF_INBAND:
06740 res = -1;
06741 break;
06742 case SIP_DTMF_RFC2833:
06743 if (p->rtp)
06744 ast_rtp_instance_dtmf_begin(p->rtp, digit);
06745 break;
06746 default:
06747 break;
06748 }
06749 sip_pvt_unlock(p);
06750
06751 return res;
06752 }
06753
06754
06755
06756 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration)
06757 {
06758 struct sip_pvt *p = ast->tech_pvt;
06759 int res = 0;
06760
06761 sip_pvt_lock(p);
06762 switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
06763 case SIP_DTMF_INFO:
06764 case SIP_DTMF_SHORTINFO:
06765 transmit_info_with_digit(p, digit, duration);
06766 break;
06767 case SIP_DTMF_RFC2833:
06768 if (p->rtp)
06769 ast_rtp_instance_dtmf_end_with_duration(p->rtp, digit, duration);
06770 break;
06771 case SIP_DTMF_INBAND:
06772 res = -1;
06773 break;
06774 }
06775 sip_pvt_unlock(p);
06776
06777 return res;
06778 }
06779
06780
06781 static int sip_transfer(struct ast_channel *ast, const char *dest)
06782 {
06783 struct sip_pvt *p = ast->tech_pvt;
06784 int res;
06785
06786 if (dest == NULL)
06787 dest = "";
06788 sip_pvt_lock(p);
06789 if (ast->_state == AST_STATE_RING)
06790 res = sip_sipredirect(p, dest);
06791 else
06792 res = transmit_refer(p, dest);
06793 sip_pvt_unlock(p);
06794 return res;
06795 }
06796
06797
06798 static int interpret_t38_parameters(struct sip_pvt *p, const struct ast_control_t38_parameters *parameters)
06799 {
06800 int res = 0;
06801
06802 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) || !p->udptl) {
06803 return -1;
06804 }
06805 switch (parameters->request_response) {
06806 case AST_T38_NEGOTIATED:
06807 case AST_T38_REQUEST_NEGOTIATE:
06808
06809 if (!parameters->max_ifp) {
06810 change_t38_state(p, T38_DISABLED);
06811 if (p->t38.state == T38_PEER_REINVITE) {
06812 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"));
06813 transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
06814 }
06815 break;
06816 } else if (p->t38.state == T38_PEER_REINVITE) {
06817 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"));
06818 p->t38.our_parms = *parameters;
06819
06820
06821
06822 if (!p->t38.their_parms.fill_bit_removal) {
06823 p->t38.our_parms.fill_bit_removal = FALSE;
06824 }
06825 if (!p->t38.their_parms.transcoding_mmr) {
06826 p->t38.our_parms.transcoding_mmr = FALSE;
06827 }
06828 if (!p->t38.their_parms.transcoding_jbig) {
06829 p->t38.our_parms.transcoding_jbig = FALSE;
06830 }
06831 p->t38.our_parms.version = MIN(p->t38.our_parms.version, p->t38.their_parms.version);
06832 p->t38.our_parms.rate_management = p->t38.their_parms.rate_management;
06833 ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
06834 change_t38_state(p, T38_ENABLED);
06835 transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
06836 } else if (p->t38.state != T38_ENABLED) {
06837 p->t38.our_parms = *parameters;
06838 ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
06839 change_t38_state(p, T38_LOCAL_REINVITE);
06840 if (!p->pendinginvite) {
06841 transmit_reinvite_with_sdp(p, TRUE, FALSE);
06842 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
06843 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
06844 }
06845 }
06846 break;
06847 case AST_T38_TERMINATED:
06848 case AST_T38_REFUSED:
06849 case AST_T38_REQUEST_TERMINATE:
06850 if (p->t38.state == T38_PEER_REINVITE) {
06851 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"));
06852 change_t38_state(p, T38_DISABLED);
06853 transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
06854 } else if (p->t38.state == T38_ENABLED)
06855 transmit_reinvite_with_sdp(p, FALSE, FALSE);
06856 break;
06857 case AST_T38_REQUEST_PARMS: {
06858 struct ast_control_t38_parameters parameters = p->t38.their_parms;
06859
06860 if (p->t38.state == T38_PEER_REINVITE) {
06861 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"));
06862 parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
06863 parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
06864 ast_queue_control_data(p->owner, AST_CONTROL_T38_PARAMETERS, ¶meters, sizeof(parameters));
06865
06866
06867
06868
06869 res = AST_T38_REQUEST_PARMS;
06870 }
06871 break;
06872 }
06873 default:
06874 res = -1;
06875 break;
06876 }
06877
06878 return res;
06879 }
06880
06881
06882
06883
06884
06885
06886
06887
06888
06889
06890 static int initialize_udptl(struct sip_pvt *p)
06891 {
06892 int natflags = ast_test_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP);
06893
06894 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
06895 return 1;
06896 }
06897
06898
06899 if (p->udptl) {
06900 return 0;
06901 }
06902
06903
06904 if ((p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, &bindaddr))) {
06905 if (p->owner) {
06906 ast_channel_set_fd(p->owner, 5, ast_udptl_fd(p->udptl));
06907 }
06908
06909 ast_udptl_setqos(p->udptl, global_tos_audio, global_cos_audio);
06910 p->t38_maxdatagram = p->relatedpeer ? p->relatedpeer->t38_maxdatagram : global_t38_maxdatagram;
06911 set_t38_capabilities(p);
06912
06913 ast_debug(1, "Setting NAT on UDPTL to %s\n", natflags ? "On" : "Off");
06914 ast_udptl_setnat(p->udptl, natflags);
06915 } else {
06916 ast_log(AST_LOG_WARNING, "UDPTL creation failed - disabling T38 for this dialog\n");
06917 ast_clear_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT);
06918 return 1;
06919 }
06920
06921 return 0;
06922 }
06923
06924
06925
06926
06927
06928
06929 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
06930 {
06931 struct sip_pvt *p = ast->tech_pvt;
06932 int res = 0;
06933
06934 sip_pvt_lock(p);
06935 switch(condition) {
06936 case AST_CONTROL_RINGING:
06937 if (ast->_state == AST_STATE_RING) {
06938 p->invitestate = INV_EARLY_MEDIA;
06939 if (!ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) ||
06940 (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) {
06941
06942 transmit_provisional_response(p, "180 Ringing", &p->initreq, 0);
06943 ast_set_flag(&p->flags[0], SIP_RINGING);
06944 if (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) != SIP_PROG_INBAND_YES)
06945 break;
06946 } else {
06947
06948 }
06949 }
06950 res = -1;
06951 break;
06952 case AST_CONTROL_BUSY:
06953 if (ast->_state != AST_STATE_UP) {
06954 transmit_response_reliable(p, "486 Busy Here", &p->initreq);
06955 p->invitestate = INV_COMPLETED;
06956 sip_alreadygone(p);
06957 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
06958 break;
06959 }
06960 res = -1;
06961 break;
06962 case AST_CONTROL_CONGESTION:
06963 if (ast->_state != AST_STATE_UP) {
06964 transmit_response_reliable(p, "503 Service Unavailable", &p->initreq);
06965 p->invitestate = INV_COMPLETED;
06966 sip_alreadygone(p);
06967 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
06968 break;
06969 }
06970 res = -1;
06971 break;
06972 case AST_CONTROL_INCOMPLETE:
06973 if (ast->_state != AST_STATE_UP) {
06974 switch (ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP)) {
06975 case SIP_PAGE2_ALLOWOVERLAP_YES:
06976 transmit_response_reliable(p, "484 Address Incomplete", &p->initreq);
06977 p->invitestate = INV_COMPLETED;
06978 sip_alreadygone(p);
06979 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
06980 break;
06981 case SIP_PAGE2_ALLOWOVERLAP_DTMF:
06982
06983 break;
06984 default:
06985
06986 transmit_response_reliable(p, "404 Not Found", &p->initreq);
06987 p->invitestate = INV_COMPLETED;
06988 sip_alreadygone(p);
06989 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
06990 break;
06991 }
06992 }
06993 break;
06994 case AST_CONTROL_PROCEEDING:
06995 if ((ast->_state != AST_STATE_UP) &&
06996 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06997 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06998 transmit_response(p, "100 Trying", &p->initreq);
06999 p->invitestate = INV_PROCEEDING;
07000 break;
07001 }
07002 res = -1;
07003 break;
07004 case AST_CONTROL_PROGRESS:
07005 if ((ast->_state != AST_STATE_UP) &&
07006 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
07007 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
07008 p->invitestate = INV_EARLY_MEDIA;
07009 transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
07010 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
07011 break;
07012 }
07013 res = -1;
07014 break;
07015 case AST_CONTROL_HOLD:
07016 ast_rtp_instance_update_source(p->rtp);
07017 ast_moh_start(ast, data, p->mohinterpret);
07018 break;
07019 case AST_CONTROL_UNHOLD:
07020 ast_rtp_instance_update_source(p->rtp);
07021 ast_moh_stop(ast);
07022 break;
07023 case AST_CONTROL_VIDUPDATE:
07024 if (p->vrtp && !p->novideo) {
07025 transmit_info_with_vidupdate(p);
07026
07027 } else
07028 res = -1;
07029 break;
07030 case AST_CONTROL_T38_PARAMETERS:
07031 res = -1;
07032 if (datalen != sizeof(struct ast_control_t38_parameters)) {
07033 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);
07034 } else {
07035 const struct ast_control_t38_parameters *parameters = data;
07036 if (!initialize_udptl(p)) {
07037 res = interpret_t38_parameters(p, parameters);
07038 }
07039 }
07040 break;
07041 case AST_CONTROL_SRCUPDATE:
07042 ast_rtp_instance_update_source(p->rtp);
07043 break;
07044 case AST_CONTROL_SRCCHANGE:
07045 ast_rtp_instance_change_source(p->rtp);
07046 break;
07047 case AST_CONTROL_CONNECTED_LINE:
07048 update_connectedline(p, data, datalen);
07049 break;
07050 case AST_CONTROL_REDIRECTING:
07051 update_redirecting(p, data, datalen);
07052 break;
07053 case AST_CONTROL_AOC:
07054 {
07055 struct ast_aoc_decoded *decoded = ast_aoc_decode((struct ast_aoc_encoded *) data, datalen, ast);
07056 if (!decoded) {
07057 ast_log(LOG_ERROR, "Error decoding indicated AOC data\n");
07058 res = -1;
07059 break;
07060 }
07061 switch (ast_aoc_get_msg_type(decoded)) {
07062 case AST_AOC_REQUEST:
07063 if (ast_aoc_get_termination_request(decoded)) {
07064
07065
07066
07067
07068
07069
07070
07071 ast_debug(1, "AOC-E termination request received on %s. This is not yet supported on sip. Continue with hangup \n", p->owner->name);
07072 ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
07073 }
07074 break;
07075 case AST_AOC_D:
07076 case AST_AOC_E:
07077 if (ast_test_flag(&p->flags[2], SIP_PAGE3_SNOM_AOC)) {
07078 transmit_info_with_aoc(p, decoded);
07079 }
07080 break;
07081 case AST_AOC_S:
07082 default:
07083 break;
07084 }
07085 ast_aoc_destroy_decoded(decoded);
07086 }
07087 break;
07088 case AST_CONTROL_UPDATE_RTP_PEER:
07089 break;
07090 case AST_CONTROL_FLASH:
07091 res = -1;
07092 break;
07093 case -1:
07094 res = -1;
07095 break;
07096 default:
07097 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
07098 res = -1;
07099 break;
07100 }
07101 sip_pvt_unlock(p);
07102 return res;
07103 }
07104
07105
07106
07107
07108
07109
07110
07111
07112
07113
07114
07115
07116 static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title, const char *linkedid)
07117 {
07118 struct ast_channel *tmp;
07119 struct ast_variable *v = NULL;
07120 format_t fmt;
07121 format_t what;
07122 format_t video;
07123 format_t text;
07124 format_t needvideo = 0;
07125 int needtext = 0;
07126 char buf[SIPBUFSIZE];
07127 char *exten;
07128
07129 {
07130 const char *my_name;
07131
07132 if (title) {
07133 my_name = title;
07134 } else {
07135 my_name = ast_strdupa(i->fromdomain);
07136 }
07137
07138 sip_pvt_unlock(i);
07139
07140 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));
07141 }
07142 if (!tmp) {
07143 ast_log(LOG_WARNING, "Unable to allocate AST channel structure for SIP channel\n");
07144 sip_pvt_lock(i);
07145 return NULL;
07146 }
07147 ast_channel_lock(tmp);
07148 sip_pvt_lock(i);
07149 ast_channel_cc_params_init(tmp, i->cc_params);
07150 tmp->caller.id.tag = ast_strdup(i->cid_tag);
07151
07152 tmp->tech = ( ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INFO || ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_SHORTINFO) ? &sip_tech_info : &sip_tech;
07153
07154
07155
07156 if (i->jointcapability) {
07157 what = i->jointcapability;
07158 video = i->jointcapability & AST_FORMAT_VIDEO_MASK;
07159 text = i->jointcapability & AST_FORMAT_TEXT_MASK;
07160 } else if (i->capability) {
07161 what = i->capability;
07162 video = i->capability & AST_FORMAT_VIDEO_MASK;
07163 text = i->capability & AST_FORMAT_TEXT_MASK;
07164 } else {
07165 what = sip_cfg.capability;
07166 video = sip_cfg.capability & AST_FORMAT_VIDEO_MASK;
07167 text = sip_cfg.capability & AST_FORMAT_TEXT_MASK;
07168 }
07169
07170
07171 tmp->nativeformats = ast_codec_choose(&i->prefs, what, 1) | video | text;
07172 ast_debug(3, "*** Our native formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, tmp->nativeformats));
07173 ast_debug(3, "*** Joint capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->jointcapability));
07174 ast_debug(3, "*** Our capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->capability));
07175 ast_debug(3, "*** AST_CODEC_CHOOSE formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, ast_codec_choose(&i->prefs, what, 1)));
07176 if (i->prefcodec)
07177 ast_debug(3, "*** Our preferred formats from the incoming channel are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->prefcodec));
07178
07179
07180 fmt = ast_best_codec(tmp->nativeformats);
07181
07182
07183
07184
07185
07186 if (i->vrtp) {
07187 if (ast_test_flag(&i->flags[1], SIP_PAGE2_VIDEOSUPPORT))
07188 needvideo = AST_FORMAT_VIDEO_MASK;
07189 else if (i->prefcodec)
07190 needvideo = i->prefcodec & AST_FORMAT_VIDEO_MASK;
07191 else
07192 needvideo = i->jointcapability & AST_FORMAT_VIDEO_MASK;
07193 }
07194
07195 if (i->trtp) {
07196 if (i->prefcodec)
07197 needtext = i->prefcodec & AST_FORMAT_TEXT_MASK;
07198 else
07199 needtext = i->jointcapability & AST_FORMAT_TEXT_MASK;
07200 }
07201
07202 if (needvideo)
07203 ast_debug(3, "This channel can handle video! HOLLYWOOD next!\n");
07204 else
07205 ast_debug(3, "This channel will not be able to handle video.\n");
07206
07207 enable_dsp_detect(i);
07208
07209 if ((ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
07210 (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
07211 if (i->rtp) {
07212 ast_rtp_instance_dtmf_mode_set(i->rtp, AST_RTP_DTMF_MODE_INBAND);
07213 }
07214 } else if (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) {
07215 if (i->rtp) {
07216 ast_rtp_instance_dtmf_mode_set(i->rtp, AST_RTP_DTMF_MODE_RFC2833);
07217 }
07218 }
07219
07220
07221
07222
07223 if (i->rtp) {
07224 ast_channel_set_fd(tmp, 0, ast_rtp_instance_fd(i->rtp, 0));
07225 ast_channel_set_fd(tmp, 1, ast_rtp_instance_fd(i->rtp, 1));
07226 ast_rtp_instance_set_write_format(i->rtp, fmt);
07227 ast_rtp_instance_set_read_format(i->rtp, fmt);
07228 }
07229 if (needvideo && i->vrtp) {
07230 ast_channel_set_fd(tmp, 2, ast_rtp_instance_fd(i->vrtp, 0));
07231 ast_channel_set_fd(tmp, 3, ast_rtp_instance_fd(i->vrtp, 1));
07232 }
07233 if (needtext && i->trtp) {
07234 ast_channel_set_fd(tmp, 4, ast_rtp_instance_fd(i->trtp, 0));
07235 }
07236 if (i->udptl) {
07237 ast_channel_set_fd(tmp, 5, ast_udptl_fd(i->udptl));
07238 }
07239
07240 if (state == AST_STATE_RING)
07241 tmp->rings = 1;
07242 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
07243
07244 tmp->writeformat = fmt;
07245 tmp->rawwriteformat = fmt;
07246
07247 tmp->readformat = fmt;
07248 tmp->rawreadformat = fmt;
07249
07250 tmp->tech_pvt = dialog_ref(i, "sip_new: set chan->tech_pvt to i");
07251
07252 tmp->callgroup = i->callgroup;
07253 tmp->pickupgroup = i->pickupgroup;
07254 tmp->caller.id.name.presentation = i->callingpres;
07255 tmp->caller.id.number.presentation = i->callingpres;
07256 if (!ast_strlen_zero(i->parkinglot))
07257 ast_string_field_set(tmp, parkinglot, i->parkinglot);
07258 if (!ast_strlen_zero(i->accountcode))
07259 ast_string_field_set(tmp, accountcode, i->accountcode);
07260 if (i->amaflags)
07261 tmp->amaflags = i->amaflags;
07262 if (!ast_strlen_zero(i->language))
07263 ast_string_field_set(tmp, language, i->language);
07264 i->owner = tmp;
07265 ast_module_ref(ast_module_info->self);
07266 ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
07267
07268
07269
07270
07271 exten = ast_strdupa(i->exten);
07272 sip_pvt_unlock(i);
07273 ast_channel_unlock(tmp);
07274 if (!ast_exists_extension(NULL, i->context, i->exten, 1, i->cid_num)) {
07275 ast_uri_decode(exten);
07276 }
07277 ast_channel_lock(tmp);
07278 sip_pvt_lock(i);
07279 ast_copy_string(tmp->exten, exten, sizeof(tmp->exten));
07280
07281
07282
07283 if (!ast_strlen_zero(i->cid_num)) {
07284 tmp->caller.ani.number.valid = 1;
07285 tmp->caller.ani.number.str = ast_strdup(i->cid_num);
07286 }
07287 if (!ast_strlen_zero(i->rdnis)) {
07288 tmp->redirecting.from.number.valid = 1;
07289 tmp->redirecting.from.number.str = ast_strdup(i->rdnis);
07290 }
07291
07292 if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s")) {
07293 tmp->dialed.number.str = ast_strdup(i->exten);
07294 }
07295
07296 tmp->priority = 1;
07297 if (!ast_strlen_zero(i->uri))
07298 pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
07299 if (!ast_strlen_zero(i->domain))
07300 pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
07301 if (!ast_strlen_zero(i->callid))
07302 pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
07303 if (i->rtp)
07304 ast_jb_configure(tmp, &global_jbconf);
07305
07306
07307 for (v = i->chanvars ; v ; v = v->next) {
07308 char valuebuf[1024];
07309 pbx_builtin_setvar_helper(tmp, v->name, ast_get_encoded_str(v->value, valuebuf, sizeof(valuebuf)));
07310 }
07311
07312 if (i->do_history)
07313 append_history(i, "NewChan", "Channel %s - from %s", tmp->name, i->callid);
07314
07315
07316 if (sip_cfg.callevents)
07317 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
07318 "Channel: %s\r\nUniqueid: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\n",
07319 tmp->name, tmp->uniqueid, "SIP", i->callid, i->fullcontact);
07320
07321 return tmp;
07322 }
07323
07324
07325 static char *get_body_by_line(const char *line, const char *name, int nameLen, char delimiter)
07326 {
07327 if (!strncasecmp(line, name, nameLen) && line[nameLen] == delimiter)
07328 return ast_skip_blanks(line + nameLen + 1);
07329
07330 return "";
07331 }
07332
07333
07334
07335
07336
07337 static const char *get_sdp_iterate(int *start, struct sip_request *req, const char *name)
07338 {
07339 int len = strlen(name);
07340
07341 while (*start < (req->sdp_start + req->sdp_count)) {
07342 const char *r = get_body_by_line(REQ_OFFSET_TO_STR(req, line[(*start)++]), name, len, '=');
07343 if (r[0] != '\0')
07344 return r;
07345 }
07346
07347
07348 (*start)++;
07349
07350 return "";
07351 }
07352
07353
07354
07355
07356
07357
07358 static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value)
07359 {
07360 char type = '\0';
07361 const char *line = NULL;
07362
07363 if (stop > (req->sdp_start + req->sdp_count)) {
07364 stop = req->sdp_start + req->sdp_count;
07365 }
07366
07367 while (*start < stop) {
07368 line = REQ_OFFSET_TO_STR(req, line[(*start)++]);
07369 if (line[1] == '=') {
07370 type = line[0];
07371 *value = ast_skip_blanks(line + 2);
07372 break;
07373 }
07374 }
07375
07376 return type;
07377 }
07378
07379
07380 static char *get_body(struct sip_request *req, char *name, char delimiter)
07381 {
07382 int x;
07383 int len = strlen(name);
07384 char *r;
07385
07386 for (x = 0; x < req->lines; x++) {
07387 r = get_body_by_line(REQ_OFFSET_TO_STR(req, line[x]), name, len, delimiter);
07388 if (r[0] != '\0')
07389 return r;
07390 }
07391
07392 return "";
07393 }
07394
07395
07396 static const char *find_alias(const char *name, const char *_default)
07397 {
07398
07399 static const struct cfalias {
07400 char * const fullname;
07401 char * const shortname;
07402 } aliases[] = {
07403 { "Content-Type", "c" },
07404 { "Content-Encoding", "e" },
07405 { "From", "f" },
07406 { "Call-ID", "i" },
07407 { "Contact", "m" },
07408 { "Content-Length", "l" },
07409 { "Subject", "s" },
07410 { "To", "t" },
07411 { "Supported", "k" },
07412 { "Refer-To", "r" },
07413 { "Referred-By", "b" },
07414 { "Allow-Events", "u" },
07415 { "Event", "o" },
07416 { "Via", "v" },
07417 { "Accept-Contact", "a" },
07418 { "Reject-Contact", "j" },
07419 { "Request-Disposition", "d" },
07420 { "Session-Expires", "x" },
07421 { "Identity", "y" },
07422 { "Identity-Info", "n" },
07423 };
07424 int x;
07425
07426 for (x = 0; x < ARRAY_LEN(aliases); x++) {
07427 if (!strcasecmp(aliases[x].fullname, name))
07428 return aliases[x].shortname;
07429 }
07430
07431 return _default;
07432 }
07433
07434 static const char *__get_header(const struct sip_request *req, const char *name, int *start)
07435 {
07436
07437
07438
07439
07440
07441
07442
07443
07444
07445 const char *sname = find_alias(name, NULL);
07446 int x, len = strlen(name), slen = (sname ? 1 : 0);
07447 for (x = *start; x < req->headers; x++) {
07448 const char *header = REQ_OFFSET_TO_STR(req, header[x]);
07449 int smatch = 0, match = !strncasecmp(header, name, len);
07450 if (slen) {
07451 smatch = !strncasecmp(header, sname, slen);
07452 }
07453 if (match || smatch) {
07454
07455 const char *r = header + (match ? len : slen );
07456 if (sip_cfg.pedanticsipchecking) {
07457 r = ast_skip_blanks(r);
07458 }
07459
07460 if (*r == ':') {
07461 *start = x+1;
07462 return ast_skip_blanks(r+1);
07463 }
07464 }
07465 }
07466
07467
07468 return "";
07469 }
07470
07471
07472
07473
07474 static const char *get_header(const struct sip_request *req, const char *name)
07475 {
07476 int start = 0;
07477 return __get_header(req, name, &start);
07478 }
07479
07480
07481 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect)
07482 {
07483
07484 struct ast_frame *f;
07485
07486 if (!p->rtp) {
07487
07488 return &ast_null_frame;
07489 }
07490
07491 switch(ast->fdno) {
07492 case 0:
07493 f = ast_rtp_instance_read(p->rtp, 0);
07494 break;
07495 case 1:
07496 f = ast_rtp_instance_read(p->rtp, 1);
07497 break;
07498 case 2:
07499 f = ast_rtp_instance_read(p->vrtp, 0);
07500 break;
07501 case 3:
07502 f = ast_rtp_instance_read(p->vrtp, 1);
07503 break;
07504 case 4:
07505 f = ast_rtp_instance_read(p->trtp, 0);
07506 if (sipdebug_text) {
07507 int i;
07508 unsigned char* arr = f->data.ptr;
07509 for (i=0; i < f->datalen; i++)
07510 ast_verbose("%c", (arr[i] > ' ' && arr[i] < '}') ? arr[i] : '.');
07511 ast_verbose(" -> ");
07512 for (i=0; i < f->datalen; i++)
07513 ast_verbose("%02X ", arr[i]);
07514 ast_verbose("\n");
07515 }
07516 break;
07517 case 5:
07518 f = ast_udptl_read(p->udptl);
07519 break;
07520 default:
07521 f = &ast_null_frame;
07522 }
07523
07524 if (f && (f->frametype == AST_FRAME_DTMF_BEGIN || f->frametype == AST_FRAME_DTMF_END) &&
07525 (ast_test_flag(&p->flags[0], SIP_DTMF) != SIP_DTMF_RFC2833)) {
07526 ast_debug(1, "Ignoring DTMF (%c) RTP frame because dtmfmode is not RFC2833\n", f->subclass.integer);
07527 ast_frfree(f);
07528 return &ast_null_frame;
07529 }
07530
07531
07532 if (!p->owner || (f && f->frametype != AST_FRAME_VOICE))
07533 return f;
07534
07535 if (f && f->subclass.codec != (p->owner->nativeformats & AST_FORMAT_AUDIO_MASK)) {
07536 if (!(f->subclass.codec & p->jointcapability)) {
07537 ast_debug(1, "Bogus frame of format '%s' received from '%s'!\n",
07538 ast_getformatname(f->subclass.codec), p->owner->name);
07539 ast_frfree(f);
07540 return &ast_null_frame;
07541 }
07542 ast_debug(1, "Oooh, format changed to %s\n",
07543 ast_getformatname(f->subclass.codec));
07544 p->owner->nativeformats = (p->owner->nativeformats & (AST_FORMAT_VIDEO_MASK | AST_FORMAT_TEXT_MASK)) | f->subclass.codec;
07545 ast_set_read_format(p->owner, p->owner->readformat);
07546 ast_set_write_format(p->owner, p->owner->writeformat);
07547 }
07548
07549 if (f && p->dsp) {
07550 f = ast_dsp_process(p->owner, p->dsp, f);
07551 if (f && f->frametype == AST_FRAME_DTMF) {
07552 if (f->subclass.integer == 'f') {
07553 ast_debug(1, "Fax CNG detected on %s\n", ast->name);
07554 *faxdetect = 1;
07555
07556 if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
07557 ast_dsp_set_features(p->dsp, DSP_FEATURE_DIGIT_DETECT);
07558 } else {
07559 ast_dsp_free(p->dsp);
07560 p->dsp = NULL;
07561 }
07562 } else {
07563 ast_debug(1, "* Detected inband DTMF '%c'\n", f->subclass.integer);
07564 }
07565 }
07566 }
07567
07568 return f;
07569 }
07570
07571
07572 static struct ast_frame *sip_read(struct ast_channel *ast)
07573 {
07574 struct ast_frame *fr;
07575 struct sip_pvt *p = ast->tech_pvt;
07576 int faxdetected = FALSE;
07577
07578 sip_pvt_lock(p);
07579 fr = sip_rtp_read(ast, p, &faxdetected);
07580 p->lastrtprx = time(NULL);
07581
07582
07583 if (faxdetected && ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_CNG)) {
07584 if (strcmp(ast->exten, "fax")) {
07585 const char *target_context = S_OR(ast->macrocontext, ast->context);
07586
07587
07588
07589
07590
07591 sip_pvt_unlock(p);
07592 ast_channel_unlock(ast);
07593 if (ast_exists_extension(ast, target_context, "fax", 1,
07594 S_COR(ast->caller.id.number.valid, ast->caller.id.number.str, NULL))) {
07595 ast_channel_lock(ast);
07596 sip_pvt_lock(p);
07597 ast_verbose(VERBOSE_PREFIX_2 "Redirecting '%s' to fax extension due to CNG detection\n", ast->name);
07598 pbx_builtin_setvar_helper(ast, "FAXEXTEN", ast->exten);
07599 if (ast_async_goto(ast, target_context, "fax", 1)) {
07600 ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", ast->name, target_context);
07601 }
07602 ast_frfree(fr);
07603 fr = &ast_null_frame;
07604 } else {
07605 ast_channel_lock(ast);
07606 sip_pvt_lock(p);
07607 ast_log(LOG_NOTICE, "FAX CNG detected but no fax extension\n");
07608 }
07609 }
07610 }
07611
07612
07613 if (fr && fr->frametype == AST_FRAME_VOICE && p->invitestate != INV_EARLY_MEDIA && ast->_state != AST_STATE_UP) {
07614 ast_frfree(fr);
07615 fr = &ast_null_frame;
07616 }
07617
07618 sip_pvt_unlock(p);
07619
07620 return fr;
07621 }
07622
07623
07624
07625 static char *generate_random_string(char *buf, size_t size)
07626 {
07627 long val[4];
07628 int x;
07629
07630 for (x=0; x<4; x++)
07631 val[x] = ast_random();
07632 snprintf(buf, size, "%08lx%08lx%08lx%08lx", val[0], val[1], val[2], val[3]);
07633
07634 return buf;
07635 }
07636
07637 static char *generate_uri(struct sip_pvt *pvt, char *buf, size_t size)
07638 {
07639 struct ast_str *uri = ast_str_alloca(size);
07640 ast_str_set(&uri, 0, "%s", pvt->socket.type == SIP_TRANSPORT_TLS ? "sips:" : "sip:");
07641
07642
07643
07644 ast_str_append(&uri, 0, "%s", generate_random_string(buf, size));
07645 ast_str_append(&uri, 0, "@%s", ast_sockaddr_stringify_remote(&pvt->ourip));
07646 ast_copy_string(buf, ast_str_buffer(uri), size);
07647 return buf;
07648 }
07649
07650
07651
07652
07653
07654
07655
07656
07657 static void build_callid_pvt(struct sip_pvt *pvt)
07658 {
07659 char buf[33];
07660 const char *host = S_OR(pvt->fromdomain, ast_sockaddr_stringify_remote(&pvt->ourip));
07661
07662 ast_string_field_build(pvt, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
07663 }
07664
07665
07666 #define CONTAINER_UNLINK(container, obj, tag) \
07667 ({ \
07668 int found = 0; \
07669 typeof((obj)) __removed_obj; \
07670 __removed_obj = ao2_t_callback((container), \
07671 OBJ_UNLINK | OBJ_POINTER, ao2_match_by_addr, (obj), (tag)); \
07672 if (__removed_obj) { \
07673 ao2_ref(__removed_obj, -1); \
07674 found = 1; \
07675 } \
07676 found; \
07677 })
07678
07679
07680
07681
07682
07683
07684
07685
07686
07687
07688 static void change_callid_pvt(struct sip_pvt *pvt, const char *callid)
07689 {
07690 int in_dialog_container;
07691
07692 ao2_lock(dialogs);
07693 in_dialog_container = CONTAINER_UNLINK(dialogs, pvt,
07694 "About to change the callid -- remove the old name");
07695 if (callid) {
07696 ast_string_field_set(pvt, callid, callid);
07697 } else {
07698 build_callid_pvt(pvt);
07699 }
07700 if (in_dialog_container) {
07701 ao2_t_link(dialogs, pvt, "New dialog callid -- inserted back into table");
07702 }
07703 ao2_unlock(dialogs);
07704 }
07705
07706
07707 static void build_callid_registry(struct sip_registry *reg, const struct ast_sockaddr *ourip, const char *fromdomain)
07708 {
07709 char buf[33];
07710
07711 const char *host = S_OR(fromdomain, ast_sockaddr_stringify_host_remote(ourip));
07712
07713 ast_string_field_build(reg, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
07714 }
07715
07716
07717 static void make_our_tag(struct sip_pvt *pvt)
07718 {
07719 ast_string_field_build(pvt, tag, "as%08lx", ast_random());
07720 }
07721
07722
07723 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p)
07724 {
07725 struct sip_st_dlg *stp;
07726
07727 if (p->stimer) {
07728 ast_log(LOG_ERROR, "Session-Timer struct already allocated\n");
07729 return p->stimer;
07730 }
07731
07732 if (!(stp = ast_calloc(1, sizeof(struct sip_st_dlg))))
07733 return NULL;
07734
07735 p->stimer = stp;
07736
07737 stp->st_schedid = -1;
07738
07739 return p->stimer;
07740 }
07741
07742
07743
07744
07745
07746 struct sip_pvt *sip_alloc(ast_string_field callid, struct ast_sockaddr *addr,
07747 int useglobal_nat, const int intended_method, struct sip_request *req)
07748 {
07749 struct sip_pvt *p;
07750
07751 if (!(p = ao2_t_alloc(sizeof(*p), sip_destroy_fn, "allocate a dialog(pvt) struct")))
07752 return NULL;
07753
07754 if (ast_string_field_init(p, 512)) {
07755 ao2_t_ref(p, -1, "failed to string_field_init, drop p");
07756 return NULL;
07757 }
07758
07759 if (!(p->cc_params = ast_cc_config_params_init())) {
07760 ao2_t_ref(p, -1, "Yuck, couldn't allocate cc_params struct. Get rid o' p");
07761 return NULL;
07762 }
07763
07764
07765
07766 if (req) {
07767 struct sip_via *via;
07768 const char *cseq = get_header(req, "Cseq");
07769 uint32_t seqno;
07770
07771
07772 via = parse_via(get_header(req, "Via"));
07773 if (via) {
07774
07775
07776 if (!ast_strlen_zero(via->branch) && !strncasecmp(via->branch, "z9hG4bK", 7)) {
07777 ast_string_field_set(p, initviabranch, via->branch);
07778 ast_string_field_set(p, initviasentby, via->sent_by);
07779 }
07780 free_via(via);
07781 }
07782
07783
07784
07785 if (!ast_strlen_zero(cseq) && (sscanf(cseq, "%30u", &seqno) == 1)) {
07786 p->init_icseq = seqno;
07787 }
07788
07789 set_socket_transport(&p->socket, req->socket.type);
07790 } else {
07791 set_socket_transport(&p->socket, SIP_TRANSPORT_UDP);
07792 }
07793
07794 p->socket.fd = -1;
07795 p->method = intended_method;
07796 p->initid = -1;
07797 p->waitid = -1;
07798 p->reinviteid = -1;
07799 p->autokillid = -1;
07800 p->request_queue_sched_id = -1;
07801 p->provisional_keepalive_sched_id = -1;
07802 p->t38id = -1;
07803 p->subscribed = NONE;
07804 p->stateid = -1;
07805 p->sessionversion_remote = -1;
07806 p->session_modify = TRUE;
07807 p->stimer = NULL;
07808 p->prefs = default_prefs;
07809 p->maxforwards = sip_cfg.default_max_forwards;
07810
07811 if (intended_method != SIP_OPTIONS) {
07812 p->timer_t1 = global_t1;
07813 p->timer_b = global_timer_b;
07814 }
07815
07816 if (!addr) {
07817 p->ourip = internip;
07818 } else {
07819 ast_sockaddr_copy(&p->sa, addr);
07820 ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
07821 }
07822
07823
07824 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
07825 ast_copy_flags(&p->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
07826 ast_copy_flags(&p->flags[2], &global_flags[2], SIP_PAGE3_FLAGS_TO_COPY);
07827
07828 p->do_history = recordhistory;
07829
07830 p->branch = ast_random();
07831 make_our_tag(p);
07832 p->ocseq = INITIAL_CSEQ;
07833 p->allowed_methods = UINT_MAX;
07834
07835 if (sip_methods[intended_method].need_rtp) {
07836 p->maxcallbitrate = default_maxcallbitrate;
07837 p->autoframing = global_autoframing;
07838 }
07839
07840 if (useglobal_nat && addr) {
07841
07842 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT_FORCE_RPORT);
07843 ast_sockaddr_copy(&p->recv, addr);
07844
07845 do_setnat(p);
07846 }
07847
07848 if (p->method != SIP_REGISTER) {
07849 ast_string_field_set(p, fromdomain, default_fromdomain);
07850 p->fromdomainport = default_fromdomainport;
07851 }
07852 build_via(p);
07853 if (!callid)
07854 build_callid_pvt(p);
07855 else
07856 ast_string_field_set(p, callid, callid);
07857
07858 ast_string_field_set(p, mohinterpret, default_mohinterpret);
07859 ast_string_field_set(p, mohsuggest, default_mohsuggest);
07860 p->capability = sip_cfg.capability;
07861 p->allowtransfer = sip_cfg.allowtransfer;
07862 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
07863 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
07864 p->noncodeccapability |= AST_RTP_DTMF;
07865 }
07866 ast_string_field_set(p, context, sip_cfg.default_context);
07867 ast_string_field_set(p, parkinglot, default_parkinglot);
07868 ast_string_field_set(p, engine, default_engine);
07869
07870 AST_LIST_HEAD_INIT_NOLOCK(&p->request_queue);
07871
07872
07873
07874 ao2_t_link(dialogs, p, "link pvt into dialogs table");
07875
07876 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");
07877 return p;
07878 }
07879
07880
07881
07882
07883
07884
07885
07886
07887 static int addr_is_multicast(const struct ast_sockaddr *addr)
07888 {
07889 return ((ast_sockaddr_ipv4(addr) & 0xf0000000) == 0xe0000000);
07890 }
07891
07892
07893
07894
07895
07896
07897
07898
07899
07900
07901
07902
07903
07904
07905
07906
07907 static int process_via(struct sip_pvt *p, const struct sip_request *req)
07908 {
07909 struct sip_via *via = parse_via(get_header(req, "Via"));
07910
07911 if (!via) {
07912 ast_log(LOG_ERROR, "error processing via header\n");
07913 return -1;
07914 }
07915
07916 if (via->maddr) {
07917 if (ast_sockaddr_resolve_first_transport(&p->sa, via->maddr, PARSE_PORT_FORBID, p->socket.type)) {
07918 ast_log(LOG_WARNING, "Can't find address for maddr '%s'\n", via->maddr);
07919 ast_log(LOG_ERROR, "error processing via header\n");
07920 free_via(via);
07921 return -1;
07922 }
07923
07924 if (addr_is_multicast(&p->sa)) {
07925 setsockopt(sipsock, IPPROTO_IP, IP_MULTICAST_TTL, &via->ttl, sizeof(via->ttl));
07926 }
07927 }
07928
07929 ast_sockaddr_set_port(&p->sa, via->port ? via->port : STANDARD_SIP_PORT);
07930
07931 free_via(via);
07932 return 0;
07933 }
07934
07935
07936 struct match_req_args {
07937 int method;
07938 const char *callid;
07939 const char *totag;
07940 const char *fromtag;
07941 uint32_t seqno;
07942
07943
07944 const char *ruri;
07945 const char *viabranch;
07946 const char *viasentby;
07947
07948
07949 int authentication_present;
07950 };
07951
07952 enum match_req_res {
07953 SIP_REQ_MATCH,
07954 SIP_REQ_NOT_MATCH,
07955 SIP_REQ_LOOP_DETECTED,
07956 };
07957
07958
07959
07960
07961
07962
07963 static enum match_req_res match_req_to_dialog(struct sip_pvt *sip_pvt_ptr, struct match_req_args *arg)
07964 {
07965 const char *init_ruri = NULL;
07966 if (sip_pvt_ptr->initreq.headers) {
07967 init_ruri = REQ_OFFSET_TO_STR(&sip_pvt_ptr->initreq, rlPart2);
07968 }
07969
07970
07971
07972
07973 if (!ast_strlen_zero(arg->callid) && strcmp(sip_pvt_ptr->callid, arg->callid)) {
07974
07975 return SIP_REQ_NOT_MATCH;
07976 }
07977 if (arg->method == SIP_RESPONSE) {
07978
07979
07980 if (!ast_strlen_zero(sip_pvt_ptr->theirtag) && ast_test_flag(&sip_pvt_ptr->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
07981 if (ast_strlen_zero(arg->totag)) {
07982
07983 return SIP_REQ_NOT_MATCH;
07984 }
07985 if (strcmp(arg->totag, sip_pvt_ptr->theirtag)) {
07986
07987 return SIP_REQ_NOT_MATCH;
07988 }
07989 }
07990
07991 if (strcmp(arg->fromtag, sip_pvt_ptr->tag)) {
07992
07993 return SIP_REQ_NOT_MATCH;
07994 }
07995 } else {
07996
07997
07998
07999 if (!arg->authentication_present && strcmp(arg->fromtag, sip_pvt_ptr->theirtag)) {
08000
08001 return SIP_REQ_NOT_MATCH;
08002 }
08003
08004 if (!ast_strlen_zero(arg->totag) && (strcmp(arg->totag, sip_pvt_ptr->tag))) {
08005
08006 return SIP_REQ_NOT_MATCH;
08007 }
08008 }
08009
08010
08011
08012
08013
08014
08015
08016
08017
08018
08019
08020
08021
08022
08023
08024
08025
08026 if ((arg->method != SIP_RESPONSE) &&
08027 ast_strlen_zero(arg->totag) &&
08028 (sip_pvt_ptr->init_icseq == arg->seqno) &&
08029 !ast_strlen_zero(sip_pvt_ptr->initviabranch) &&
08030 init_ruri) {
08031
08032
08033 if (ast_strlen_zero(arg->viabranch) ||
08034 strcmp(arg->viabranch, sip_pvt_ptr->initviabranch) ||
08035 ast_strlen_zero(arg->viasentby) ||
08036 strcmp(arg->viasentby, sip_pvt_ptr->initviasentby)) {
08037
08038
08039
08040 if ((sip_pvt_ptr->method != arg->method)) {
08041 return SIP_REQ_NOT_MATCH;
08042 }
08043
08044
08045
08046 if (sip_uri_cmp(init_ruri, arg->ruri)) {
08047
08048 return SIP_REQ_NOT_MATCH;
08049 }
08050
08051
08052
08053
08054
08055
08056
08057
08058
08059
08060
08061
08062
08063
08064
08065
08066
08067
08068
08069 return SIP_REQ_LOOP_DETECTED;
08070 }
08071 }
08072
08073
08074
08075
08076
08077
08078 if ((arg->method != SIP_RESPONSE) &&
08079 ast_strlen_zero(arg->totag) &&
08080 arg->authentication_present &&
08081 sip_uri_cmp(init_ruri, arg->ruri)) {
08082
08083
08084 return SIP_REQ_NOT_MATCH;
08085 }
08086
08087 return SIP_REQ_MATCH;
08088 }
08089
08090
08091
08092
08093
08094
08095
08096
08097
08098
08099
08100
08101
08102
08103
08104
08105
08106
08107 static struct ast_channel *sip_pvt_lock_full(struct sip_pvt *pvt)
08108 {
08109 struct ast_channel *chan;
08110
08111
08112
08113
08114 for (;;) {
08115
08116 sip_pvt_lock(pvt);
08117 chan = pvt->owner;
08118 if (chan) {
08119
08120
08121
08122 ast_channel_ref(chan);
08123 } else {
08124
08125 return NULL;
08126 }
08127
08128
08129
08130
08131 sip_pvt_unlock(pvt);
08132
08133
08134 ast_channel_lock(chan);
08135 sip_pvt_lock(pvt);
08136
08137 if (pvt->owner == chan) {
08138
08139 break;
08140 }
08141
08142
08143
08144
08145
08146
08147 ast_channel_unlock(chan);
08148 ast_channel_unref(chan);
08149 sip_pvt_unlock(pvt);
08150 }
08151
08152
08153 return pvt->owner;
08154 }
08155
08156
08157
08158
08159
08160
08161 static struct sip_pvt *find_call(struct sip_request *req, struct ast_sockaddr *addr, const int intended_method)
08162 {
08163 char totag[128];
08164 char fromtag[128];
08165 const char *callid = get_header(req, "Call-ID");
08166 const char *from = get_header(req, "From");
08167 const char *to = get_header(req, "To");
08168 const char *cseq = get_header(req, "Cseq");
08169 struct sip_pvt *sip_pvt_ptr;
08170 uint32_t seqno;
08171
08172
08173 if (ast_strlen_zero(callid) || ast_strlen_zero(to) ||
08174 ast_strlen_zero(from) || ast_strlen_zero(cseq) ||
08175 (sscanf(cseq, "%30u", &seqno) != 1)) {
08176
08177
08178 if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
08179 transmit_response_using_temp(callid, addr, 1, intended_method,
08180 req, "400 Bad Request");
08181 }
08182 return NULL;
08183 }
08184
08185 if (sip_cfg.pedanticsipchecking) {
08186
08187
08188
08189
08190
08191
08192 if (gettag(req, "To", totag, sizeof(totag)))
08193 req->has_to_tag = 1;
08194 gettag(req, "From", fromtag, sizeof(fromtag));
08195
08196 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);
08197
08198
08199 if (ast_strlen_zero(fromtag)) {
08200 ast_debug(5, "%s request has no from tag, dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
08201 return NULL;
08202 }
08203
08204 if (ast_strlen_zero(totag) && (req->method == SIP_ACK || req->method == SIP_BYE || req->method == SIP_INFO )) {
08205 ast_debug(5, "%s must have a to tag. dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
08206 return NULL;
08207 }
08208 }
08209
08210 if (!sip_cfg.pedanticsipchecking) {
08211 struct sip_pvt tmp_dialog = {
08212 .callid = callid,
08213 };
08214 sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find in dialogs");
08215 if (sip_pvt_ptr) {
08216
08217 return sip_pvt_ptr;
08218 }
08219 } else {
08220 struct sip_pvt tmp_dialog = {
08221 .callid = callid,
08222 };
08223 struct match_req_args args = { 0, };
08224 int found;
08225 struct ao2_iterator *iterator = ao2_t_callback(dialogs,
08226 OBJ_POINTER | OBJ_MULTIPLE,
08227 dialog_find_multiple,
08228 &tmp_dialog,
08229 "pedantic ao2_find in dialogs");
08230 struct sip_via *via = NULL;
08231
08232 args.method = req->method;
08233 args.callid = NULL;
08234 args.totag = totag;
08235 args.fromtag = fromtag;
08236 args.seqno = seqno;
08237
08238
08239 if (req->method != SIP_RESPONSE) {
08240 args.ruri = REQ_OFFSET_TO_STR(req, rlPart2);
08241 via = parse_via(get_header(req, "Via"));
08242 if (via) {
08243 args.viasentby = via->sent_by;
08244 args.viabranch = via->branch;
08245 }
08246 if (!ast_strlen_zero(get_header(req, "Authorization")) ||
08247 !ast_strlen_zero(get_header(req, "Proxy-Authorization"))) {
08248 args.authentication_present = 1;
08249 }
08250 }
08251
08252
08253 while (iterator && (sip_pvt_ptr = ao2_iterator_next(iterator))) {
08254 sip_pvt_lock(sip_pvt_ptr);
08255 found = match_req_to_dialog(sip_pvt_ptr, &args);
08256 sip_pvt_unlock(sip_pvt_ptr);
08257
08258 switch (found) {
08259 case SIP_REQ_MATCH:
08260 ao2_iterator_destroy(iterator);
08261 free_via(via);
08262 return sip_pvt_ptr;
08263 case SIP_REQ_LOOP_DETECTED:
08264
08265
08266 transmit_response_using_temp(callid, addr, 1, intended_method, req, "482 (Loop Detected)");
08267 dialog_unref(sip_pvt_ptr, "pvt did not match incoming SIP msg, unref from search.");
08268 ao2_iterator_destroy(iterator);
08269 free_via(via);
08270 return NULL;
08271 case SIP_REQ_NOT_MATCH:
08272 default:
08273 dialog_unref(sip_pvt_ptr, "pvt did not match incoming SIP msg, unref from search");
08274 break;
08275 }
08276 }
08277 if (iterator) {
08278 ao2_iterator_destroy(iterator);
08279 }
08280
08281 free_via(via);
08282 }
08283
08284
08285 if (sip_methods[intended_method].can_create == CAN_CREATE_DIALOG) {
08286 struct sip_pvt *p = NULL;
08287
08288 if (intended_method == SIP_REFER) {
08289
08290 transmit_response_using_temp(callid, addr, 1, intended_method, req, "603 Declined (no dialog)");
08291
08292
08293 } else if (!(p = sip_alloc(callid, addr, 1, intended_method, req))) {
08294
08295
08296
08297
08298
08299
08300
08301
08302 transmit_response_using_temp(callid, addr, 1, intended_method, req, "500 Server internal error");
08303 ast_debug(4, "Failed allocating SIP dialog, sending 500 Server internal error and giving up\n");
08304 }
08305 return p;
08306 } else if( sip_methods[intended_method].can_create == CAN_CREATE_DIALOG_UNSUPPORTED_METHOD) {
08307
08308 transmit_response_using_temp(callid, addr, 1, intended_method, req, "501 Method Not Implemented");
08309 ast_debug(2, "Got a request with unsupported SIP method.\n");
08310 } else if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
08311
08312 transmit_response_using_temp(callid, addr, 1, intended_method, req, "481 Call leg/transaction does not exist");
08313 ast_debug(2, "That's odd... Got a request in unknown dialog. Callid %s\n", callid ? callid : "<unknown>");
08314 }
08315
08316
08317 if (intended_method == SIP_RESPONSE)
08318 ast_debug(2, "That's odd... Got a response on a call we don't know about. Callid %s\n", callid ? callid : "<unknown>");
08319
08320 return NULL;
08321 }
08322
08323
08324 static int sip_register(const char *value, int lineno)
08325 {
08326 struct sip_registry *reg;
08327
08328 if (!(reg = ast_calloc_with_stringfields(1, struct sip_registry, 256))) {
08329 ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry entry\n");
08330 return -1;
08331 }
08332
08333 ast_atomic_fetchadd_int(®objs, 1);
08334 ASTOBJ_INIT(reg);
08335
08336 if (sip_parse_register_line(reg, default_expiry, value, lineno)) {
08337 registry_unref(reg, "failure to parse, unref the reg pointer");
08338 return -1;
08339 }
08340
08341
08342 if (reg->refresh && !reg->expiry && !reg->configured_expiry) {
08343 reg->refresh = reg->expiry = reg->configured_expiry = default_expiry;
08344 }
08345
08346
08347 ASTOBJ_CONTAINER_LINK(®l, reg);
08348
08349
08350 registry_unref(reg, "unref the reg pointer");
08351
08352 return 0;
08353 }
08354
08355
08356 static int sip_subscribe_mwi(const char *value, int lineno)
08357 {
08358 struct sip_subscription_mwi *mwi;
08359 int portnum = 0;
08360 enum sip_transport transport = SIP_TRANSPORT_UDP;
08361 char buf[256] = "";
08362 char *username = NULL, *hostname = NULL, *secret = NULL, *authuser = NULL, *porta = NULL, *mailbox = NULL;
08363
08364 if (!value) {
08365 return -1;
08366 }
08367
08368 ast_copy_string(buf, value, sizeof(buf));
08369
08370 username = buf;
08371
08372 if ((hostname = strrchr(buf, '@'))) {
08373 *hostname++ = '\0';
08374 } else {
08375 return -1;
08376 }
08377
08378 if ((secret = strchr(username, ':'))) {
08379 *secret++ = '\0';
08380 if ((authuser = strchr(secret, ':'))) {
08381 *authuser++ = '\0';
08382 }
08383 }
08384
08385 if ((mailbox = strchr(hostname, '/'))) {
08386 *mailbox++ = '\0';
08387 }
08388
08389 if (ast_strlen_zero(username) || ast_strlen_zero(hostname) || ast_strlen_zero(mailbox)) {
08390 ast_log(LOG_WARNING, "Format for MWI subscription is user[:secret[:authuser]]@host[:port]/mailbox at line %d\n", lineno);
08391 return -1;
08392 }
08393
08394 if ((porta = strchr(hostname, ':'))) {
08395 *porta++ = '\0';
08396 if (!(portnum = atoi(porta))) {
08397 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
08398 return -1;
08399 }
08400 }
08401
08402 if (!(mwi = ast_calloc_with_stringfields(1, struct sip_subscription_mwi, 256))) {
08403 return -1;
08404 }
08405
08406 ASTOBJ_INIT(mwi);
08407 ast_string_field_set(mwi, username, username);
08408 if (secret) {
08409 ast_string_field_set(mwi, secret, secret);
08410 }
08411 if (authuser) {
08412 ast_string_field_set(mwi, authuser, authuser);
08413 }
08414 ast_string_field_set(mwi, hostname, hostname);
08415 ast_string_field_set(mwi, mailbox, mailbox);
08416 mwi->resub = -1;
08417 mwi->portno = portnum;
08418 mwi->transport = transport;
08419
08420 ASTOBJ_CONTAINER_LINK(&submwil, mwi);
08421 ASTOBJ_UNREF(mwi, sip_subscribe_mwi_destroy);
08422
08423 return 0;
08424 }
08425
08426 static void mark_method_allowed(unsigned int *allowed_methods, enum sipmethod method)
08427 {
08428 (*allowed_methods) |= (1 << method);
08429 }
08430
08431 static void mark_method_unallowed(unsigned int *allowed_methods, enum sipmethod method)
08432 {
08433 (*allowed_methods) &= ~(1 << method);
08434 }
08435
08436
08437 static int is_method_allowed(unsigned int *allowed_methods, enum sipmethod method)
08438 {
08439 return ((*allowed_methods) >> method) & 1;
08440 }
08441
08442 static void mark_parsed_methods(unsigned int *methods, char *methods_str)
08443 {
08444 char *method;
08445 for (method = strsep(&methods_str, ","); !ast_strlen_zero(method); method = strsep(&methods_str, ",")) {
08446 int id = find_sip_method(ast_skip_blanks(method));
08447 if (id == SIP_UNKNOWN) {
08448 continue;
08449 }
08450 mark_method_allowed(methods, id);
08451 }
08452 }
08453
08454
08455
08456
08457
08458
08459
08460
08461
08462
08463
08464
08465
08466
08467
08468
08469 static unsigned int parse_allowed_methods(struct sip_request *req)
08470 {
08471 char *allow = ast_strdupa(get_header(req, "Allow"));
08472 unsigned int allowed_methods = SIP_UNKNOWN;
08473
08474 if (ast_strlen_zero(allow)) {
08475
08476
08477
08478
08479 char *contact = ast_strdupa(get_header(req, "Contact"));
08480 char *methods = strstr(contact, ";methods=");
08481
08482 if (ast_strlen_zero(methods)) {
08483
08484
08485
08486
08487
08488
08489
08490
08491
08492
08493
08494 return UINT_MAX;
08495 }
08496 allow = ast_strip_quoted(methods + 9, "\"", "\"");
08497 }
08498 mark_parsed_methods(&allowed_methods, allow);
08499 return allowed_methods;
08500 }
08501
08502
08503
08504
08505
08506
08507
08508
08509
08510
08511 static unsigned int set_pvt_allowed_methods(struct sip_pvt *pvt, struct sip_request *req)
08512 {
08513 pvt->allowed_methods = parse_allowed_methods(req);
08514
08515 if (ast_test_flag(&pvt->flags[1], SIP_PAGE2_RPID_UPDATE)) {
08516 mark_method_allowed(&pvt->allowed_methods, SIP_UPDATE);
08517 }
08518 pvt->allowed_methods &= ~(pvt->disallowed_methods);
08519
08520 return pvt->allowed_methods;
08521 }
08522
08523
08524
08525 static void lws2sws(struct ast_str *data)
08526 {
08527 char *msgbuf = data->str;
08528 int len = ast_str_strlen(data);
08529 int h = 0, t = 0;
08530 int lws = 0;
08531
08532 for (; h < len;) {
08533
08534 if (msgbuf[h] == '\r') {
08535 h++;
08536 continue;
08537 }
08538
08539 if (msgbuf[h] == '\n') {
08540
08541 if (h + 1 == len)
08542 break;
08543
08544 if (msgbuf[h + 1] == ' ' || msgbuf[h + 1] == '\t') {
08545
08546 h++;
08547 continue;
08548 }
08549
08550 msgbuf[t++] = msgbuf[h++];
08551 lws = 0;
08552 continue;
08553 }
08554 if (msgbuf[h] == ' ' || msgbuf[h] == '\t') {
08555 if (lws) {
08556 h++;
08557 continue;
08558 }
08559 msgbuf[t++] = msgbuf[h++];
08560 lws = 1;
08561 continue;
08562 }
08563 msgbuf[t++] = msgbuf[h++];
08564 if (lws)
08565 lws = 0;
08566 }
08567 msgbuf[t] = '\0';
08568 data->used = t;
08569 }
08570
08571
08572
08573
08574 static int parse_request(struct sip_request *req)
08575 {
08576 char *c = req->data->str;
08577 ptrdiff_t *dst = req->header;
08578 int i = 0, lim = SIP_MAX_HEADERS - 1;
08579 unsigned int skipping_headers = 0;
08580 ptrdiff_t current_header_offset = 0;
08581 char *previous_header = "";
08582
08583 req->header[0] = 0;
08584 req->headers = -1;
08585 for (; *c; c++) {
08586 if (*c == '\r') {
08587 *c = '\0';
08588 } else if (*c == '\n') {
08589 *c = '\0';
08590 current_header_offset = (c + 1) - req->data->str;
08591 previous_header = req->data->str + dst[i];
08592 if (skipping_headers) {
08593
08594
08595
08596 if (ast_strlen_zero(previous_header)) {
08597 skipping_headers = 0;
08598 }
08599 dst[i] = current_header_offset;
08600 continue;
08601 }
08602 if (sipdebug) {
08603 ast_debug(4, "%7s %2d [%3d]: %s\n",
08604 req->headers < 0 ? "Header" : "Body",
08605 i, (int) strlen(previous_header), previous_header);
08606 }
08607 if (ast_strlen_zero(previous_header) && req->headers < 0) {
08608 req->headers = i;
08609 dst = req->line;
08610 i = 0;
08611 lim = SIP_MAX_LINES - 1;
08612 } else {
08613 if (i++ == lim) {
08614
08615
08616
08617 if (req->headers != -1) {
08618 break;
08619 } else {
08620 req->headers = i;
08621 dst = req->line;
08622 i = 0;
08623 lim = SIP_MAX_LINES - 1;
08624 skipping_headers = 1;
08625 }
08626 }
08627 }
08628 dst[i] = current_header_offset;
08629 }
08630 }
08631
08632
08633
08634
08635
08636
08637 previous_header = req->data->str + dst[i];
08638 if ((i < lim) && !ast_strlen_zero(previous_header)) {
08639 if (sipdebug) {
08640 ast_debug(4, "%7s %2d [%3d]: %s\n",
08641 req->headers < 0 ? "Header" : "Body",
08642 i, (int) strlen(previous_header), previous_header );
08643 }
08644 i++;
08645 }
08646
08647
08648 if (req->headers >= 0) {
08649 req->lines = i;
08650 } else {
08651 req->headers = i;
08652 req->lines = 0;
08653
08654 req->line[0] = ast_str_strlen(req->data);
08655 }
08656
08657 if (*c) {
08658 ast_log(LOG_WARNING, "Too many lines, skipping <%s>\n", c);
08659 }
08660
08661
08662 return determine_firstline_parts(req);
08663 }
08664
08665
08666
08667
08668
08669
08670
08671
08672
08673 static int find_sdp(struct sip_request *req)
08674 {
08675 const char *content_type;
08676 const char *content_length;
08677 const char *search;
08678 char *boundary;
08679 unsigned int x;
08680 int boundaryisquoted = FALSE;
08681 int found_application_sdp = FALSE;
08682 int found_end_of_headers = FALSE;
08683
08684 content_length = get_header(req, "Content-Length");
08685
08686 if (!ast_strlen_zero(content_length)) {
08687 if (sscanf(content_length, "%30u", &x) != 1) {
08688 ast_log(LOG_WARNING, "Invalid Content-Length: %s\n", content_length);
08689 return 0;
08690 }
08691
08692
08693
08694 if (x == 0)
08695 return 0;
08696 }
08697
08698 content_type = get_header(req, "Content-Type");
08699
08700
08701 if (!strncasecmp(content_type, "application/sdp", 15)) {
08702 req->sdp_start = 0;
08703 req->sdp_count = req->lines;
08704 return req->lines ? 1 : 0;
08705 }
08706
08707
08708 if (strncasecmp(content_type, "multipart/mixed", 15))
08709 return 0;
08710
08711
08712 if ((search = strcasestr(content_type, ";boundary=")))
08713 search += 10;
08714 else if ((search = strcasestr(content_type, "; boundary=")))
08715 search += 11;
08716 else
08717 return 0;
08718
08719 if (ast_strlen_zero(search))
08720 return 0;
08721
08722
08723 if (*search == '\"') {
08724 search++;
08725 boundaryisquoted = TRUE;
08726 }
08727
08728
08729
08730 boundary = ast_strdupa(search - 2);
08731 boundary[0] = boundary[1] = '-';
08732
08733 if (boundaryisquoted)
08734 boundary[strlen(boundary) - 1] = '\0';
08735
08736
08737
08738
08739 for (x = 0; x < (req->lines); x++) {
08740 const char *line = REQ_OFFSET_TO_STR(req, line[x]);
08741 if (!strncasecmp(line, boundary, strlen(boundary))){
08742 if (found_application_sdp && found_end_of_headers) {
08743 req->sdp_count = (x - 1) - req->sdp_start;
08744 return 1;
08745 }
08746 found_application_sdp = FALSE;
08747 }
08748 if (!strcasecmp(line, "Content-Type: application/sdp"))
08749 found_application_sdp = TRUE;
08750
08751 if (ast_strlen_zero(line)) {
08752 if (found_application_sdp && !found_end_of_headers){
08753 req->sdp_start = x;
08754 found_end_of_headers = TRUE;
08755 }
08756 }
08757 }
08758 if (found_application_sdp && found_end_of_headers) {
08759 req->sdp_count = x - req->sdp_start;
08760 return TRUE;
08761 }
08762 return FALSE;
08763 }
08764
08765
08766 static void change_hold_state(struct sip_pvt *dialog, struct sip_request *req, int holdstate, int sendonly)
08767 {
08768 if (sip_cfg.notifyhold && (!holdstate || !ast_test_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD)))
08769 sip_peer_hold(dialog, holdstate);
08770 if (sip_cfg.callevents)
08771 manager_event(EVENT_FLAG_CALL, "Hold",
08772 "Status: %s\r\n"
08773 "Channel: %s\r\n"
08774 "Uniqueid: %s\r\n",
08775 holdstate ? "On" : "Off",
08776 dialog->owner->name,
08777 dialog->owner->uniqueid);
08778 append_history(dialog, holdstate ? "Hold" : "Unhold", "%s", req->data->str);
08779 if (!holdstate) {
08780 ast_clear_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD);
08781 return;
08782 }
08783
08784
08785
08786 ast_clear_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD);
08787
08788 if (sendonly == 1)
08789 ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_ONEDIR);
08790 else if (sendonly == 2)
08791 ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_INACTIVE);
08792 else
08793 ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_ACTIVE);
08794 return;
08795 }
08796
08797
08798 static int get_ip_and_port_from_sdp(struct sip_request *req, const enum media_type media, struct ast_sockaddr *addr)
08799 {
08800 const char *m;
08801 const char *c;
08802 int miterator = req->sdp_start;
08803 int citerator = req->sdp_start;
08804 int x = 0;
08805 int numberofports;
08806 int len;
08807 int af;
08808 char proto[4], host[258] = "";
08809
08810 c = get_sdp_iterate(&citerator, req, "c");
08811 if (sscanf(c, "IN %3s %256s", proto, host) != 2) {
08812 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
08813
08814 }
08815
08816 for (m = get_sdp_iterate(&miterator, req, "m"); !ast_strlen_zero(m); m = get_sdp_iterate(&miterator, req, "m")) {
08817 if ((media == SDP_AUDIO && ((sscanf(m, "audio %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08818 (sscanf(m, "audio %30u RTP/AVP %n", &x, &len) == 1 && len > 0))) ||
08819 (media == SDP_VIDEO && ((sscanf(m, "video %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08820 (sscanf(m, "video %30u RTP/AVP %n", &x, &len) == 1 && len > 0)))) {
08821
08822
08823
08824
08825 c = get_sdp_iterate(&citerator, req, "c");
08826 if (!ast_strlen_zero(c)) {
08827 sscanf(c, "IN %3s %256s", proto, host);
08828 }
08829 break;
08830 }
08831 }
08832
08833 if (!strcmp("IP4", proto)) {
08834 af = AF_INET;
08835 } else if (!strcmp("IP6", proto)) {
08836 af = AF_INET6;
08837 } else {
08838 ast_log(LOG_WARNING, "Unknown protocol '%s'.\n", proto);
08839 return -1;
08840 }
08841
08842 if (ast_strlen_zero(host) || x == 0) {
08843 ast_log(LOG_WARNING, "Failed to read an alternate host or port in SDP. Expect %s problems\n", media == SDP_AUDIO ? "audio" : "video");
08844 return -1;
08845 }
08846
08847 if (ast_sockaddr_resolve_first_af(addr, host, 0, af)) {
08848 ast_log(LOG_WARNING, "Could not look up IP address of alternate hostname. Expect %s problems\n", media == SDP_AUDIO? "audio" : "video");
08849 return -1;
08850 }
08851
08852 return 0;
08853 }
08854
08855
08856
08857
08858
08859
08860
08861 static int sockaddr_is_null_or_any(const struct ast_sockaddr *addr)
08862 {
08863 return ast_sockaddr_isnull(addr) || ast_sockaddr_is_any(addr);
08864 }
08865
08866
08867
08868
08869
08870
08871 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action)
08872 {
08873
08874 int start = req->sdp_start;
08875 int next = start;
08876 int iterator = start;
08877
08878
08879 char type = '\0';
08880 const char *value = NULL;
08881 const char *m = NULL;
08882 const char *nextm = NULL;
08883 int len = -1;
08884
08885
08886 struct ast_sockaddr sessionsa;
08887 struct ast_sockaddr audiosa;
08888 struct ast_sockaddr videosa;
08889 struct ast_sockaddr textsa;
08890 struct ast_sockaddr imagesa;
08891 struct ast_sockaddr *sa = NULL;
08892 struct ast_sockaddr *vsa = NULL;
08893 struct ast_sockaddr *tsa = NULL;
08894 struct ast_sockaddr *isa = NULL;
08895 int portno = -1;
08896 int vportno = -1;
08897 int tportno = -1;
08898 int udptlportno = -1;
08899
08900
08901 format_t peercapability = 0, vpeercapability = 0, tpeercapability = 0;
08902 int peernoncodeccapability = 0, vpeernoncodeccapability = 0, tpeernoncodeccapability = 0;
08903
08904 struct ast_rtp_codecs newaudiortp, newvideortp, newtextrtp;
08905 format_t newjointcapability;
08906 format_t newpeercapability;
08907 int newnoncodeccapability;
08908
08909 const char *codecs;
08910 int codec;
08911
08912
08913 int secure_audio = FALSE;
08914 int secure_video = FALSE;
08915
08916
08917 int sendonly = -1;
08918 int numberofports;
08919 int numberofmediastreams = 0;
08920 int last_rtpmap_codec = 0;
08921 int red_data_pt[10];
08922 int red_num_gen = 0;
08923 char red_fmtp[100] = "empty";
08924 int debug = sip_debug_test_pvt(p);
08925
08926
08927 char buf[SIPBUFSIZE];
08928
08929
08930
08931 if (!p->rtp) {
08932 ast_log(LOG_ERROR, "Got SDP but have no RTP session allocated.\n");
08933 return -1;
08934 }
08935
08936
08937 ast_rtp_codecs_payloads_clear(&newaudiortp, NULL);
08938 ast_rtp_codecs_payloads_clear(&newvideortp, NULL);
08939 ast_rtp_codecs_payloads_clear(&newtextrtp, NULL);
08940
08941
08942 p->lastrtprx = p->lastrtptx = time(NULL);
08943
08944 memset(p->offered_media, 0, sizeof(p->offered_media));
08945
08946
08947 p->novideo = TRUE;
08948 p->notext = TRUE;
08949
08950
08951 nextm = get_sdp_iterate(&next, req, "m");
08952 if (ast_strlen_zero(nextm)) {
08953 ast_log(LOG_WARNING, "Insufficient information for SDP (m= not found)\n");
08954 return -1;
08955 }
08956
08957
08958 while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
08959 int processed = FALSE;
08960 switch (type) {
08961 case 'o':
08962
08963
08964
08965 if (!process_sdp_o(value, p))
08966 return (p->session_modify == FALSE) ? 0 : -1;
08967 break;
08968 case 'c':
08969 if (process_sdp_c(value, &sessionsa)) {
08970 processed = TRUE;
08971 sa = &sessionsa;
08972 vsa = sa;
08973 tsa = sa;
08974 isa = sa;
08975 }
08976 break;
08977 case 'a':
08978 if (process_sdp_a_sendonly(value, &sendonly)) {
08979 processed = TRUE;
08980 }
08981 else if (process_sdp_a_audio(value, p, &newaudiortp, &last_rtpmap_codec))
08982 processed = TRUE;
08983 else if (process_sdp_a_video(value, p, &newvideortp, &last_rtpmap_codec))
08984 processed = TRUE;
08985 else if (process_sdp_a_text(value, p, &newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec))
08986 processed = TRUE;
08987 else if (process_sdp_a_image(value, p))
08988 processed = TRUE;
08989 break;
08990 }
08991
08992 ast_debug(3, "Processing session-level SDP %c=%s... %s\n", type, value, (processed == TRUE)? "OK." : "UNSUPPORTED OR FAILED.");
08993 }
08994
08995
08996 while (!ast_strlen_zero(nextm)) {
08997 int audio = FALSE;
08998 int video = FALSE;
08999 int image = FALSE;
09000 int text = FALSE;
09001 int processed_crypto = FALSE;
09002 char protocol[5] = {0,};
09003 int x;
09004
09005 numberofports = 0;
09006 len = -1;
09007 start = next;
09008 m = nextm;
09009 iterator = next;
09010 nextm = get_sdp_iterate(&next, req, "m");
09011
09012
09013 if (strncmp(m, "audio ", 6) == 0) {
09014 if ((sscanf(m, "audio %30u/%30u RTP/%4s %n", &x, &numberofports, protocol, &len) == 3 && len > 0) ||
09015 (sscanf(m, "audio %30u RTP/%4s %n", &x, protocol, &len) == 2 && len > 0)) {
09016 if (x == 0) {
09017 ast_log(LOG_WARNING, "Ignoring audio media offer because port number is zero\n");
09018 continue;
09019 }
09020
09021
09022 if (numberofports > 1) {
09023 ast_log(LOG_WARNING, "%d ports offered for audio media, not supported by Asterisk. Will try anyway...\n", numberofports);
09024 }
09025
09026 if (!strcmp(protocol, "SAVP")) {
09027 secure_audio = 1;
09028 } else if (strcmp(protocol, "AVP")) {
09029 ast_log(LOG_WARNING, "Unknown RTP profile in audio offer: %s\n", m);
09030 continue;
09031 }
09032
09033 if (p->offered_media[SDP_AUDIO].order_offered) {
09034 ast_log(LOG_WARNING, "Rejecting non-primary audio stream: %s\n", m);
09035 return -1;
09036 }
09037
09038 audio = TRUE;
09039 p->offered_media[SDP_AUDIO].order_offered = ++numberofmediastreams;
09040 portno = x;
09041
09042
09043 codecs = m + len;
09044 ast_copy_string(p->offered_media[SDP_AUDIO].codecs, codecs, sizeof(p->offered_media[SDP_AUDIO].codecs));
09045 for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
09046 if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
09047 ast_log(LOG_WARNING, "Invalid syntax in RTP audio format list: %s\n", codecs);
09048 return -1;
09049 }
09050 if (debug) {
09051 ast_verbose("Found RTP audio format %d\n", codec);
09052 }
09053
09054 ast_rtp_codecs_payloads_set_m_type(&newaudiortp, NULL, codec);
09055 }
09056 } else {
09057 ast_log(LOG_WARNING, "Rejecting audio media offer due to invalid or unsupported syntax: %s\n", m);
09058 return -1;
09059 }
09060 }
09061
09062 else if (strncmp(m, "video ", 6) == 0) {
09063 if ((sscanf(m, "video %30u/%30u RTP/%4s %n", &x, &numberofports, protocol, &len) == 3 && len > 0) ||
09064 (sscanf(m, "video %30u RTP/%4s %n", &x, protocol, &len) == 2 && len > 0)) {
09065 if (x == 0) {
09066 ast_log(LOG_WARNING, "Ignoring video media offer because port number is zero\n");
09067 continue;
09068 }
09069
09070
09071 if (numberofports > 1) {
09072 ast_log(LOG_WARNING, "%d ports offered for video media, not supported by Asterisk. Will try anyway...\n", numberofports);
09073 }
09074
09075 if (!strcmp(protocol, "SAVP")) {
09076 secure_video = 1;
09077 } else if (strcmp(protocol, "AVP")) {
09078 ast_log(LOG_WARNING, "Unknown RTP profile in video offer: %s\n", m);
09079 continue;
09080 }
09081
09082 if (p->offered_media[SDP_VIDEO].order_offered) {
09083 ast_log(LOG_WARNING, "Rejecting non-primary video stream: %s\n", m);
09084 return -1;
09085 }
09086
09087 video = TRUE;
09088 p->novideo = FALSE;
09089 p->offered_media[SDP_VIDEO].order_offered = ++numberofmediastreams;
09090 vportno = x;
09091
09092
09093 codecs = m + len;
09094 ast_copy_string(p->offered_media[SDP_VIDEO].codecs, codecs, sizeof(p->offered_media[SDP_VIDEO].codecs));
09095 for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
09096 if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
09097 ast_log(LOG_WARNING, "Invalid syntax in RTP video format list: %s\n", codecs);
09098 return -1;
09099 }
09100 if (debug) {
09101 ast_verbose("Found RTP video format %d\n", codec);
09102 }
09103 ast_rtp_codecs_payloads_set_m_type(&newvideortp, NULL, codec);
09104 }
09105 } else {
09106 ast_log(LOG_WARNING, "Rejecting video media offer due to invalid or unsupported syntax: %s\n", m);
09107 return -1;
09108 }
09109 }
09110
09111 else if (strncmp(m, "text ", 5) == 0) {
09112 if ((sscanf(m, "text %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
09113 (sscanf(m, "text %30u RTP/AVP %n", &x, &len) == 1 && len > 0)) {
09114 if (x == 0) {
09115 ast_log(LOG_WARNING, "Ignoring text media offer because port number is zero\n");
09116 continue;
09117 }
09118
09119
09120 if (numberofports > 1) {
09121 ast_log(LOG_WARNING, "%d ports offered for text media, not supported by Asterisk. Will try anyway...\n", numberofports);
09122 }
09123
09124 if (p->offered_media[SDP_TEXT].order_offered) {
09125 ast_log(LOG_WARNING, "Rejecting non-primary text stream: %s\n", m);
09126 return -1;
09127 }
09128
09129 text = TRUE;
09130 p->notext = FALSE;
09131 p->offered_media[SDP_TEXT].order_offered = ++numberofmediastreams;
09132 tportno = x;
09133
09134
09135 codecs = m + len;
09136 ast_copy_string(p->offered_media[SDP_TEXT].codecs, codecs, sizeof(p->offered_media[SDP_TEXT].codecs));
09137 for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
09138 if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
09139 ast_log(LOG_WARNING, "Invalid syntax in RTP video format list: %s\n", codecs);
09140 return -1;
09141 }
09142 if (debug) {
09143 ast_verbose("Found RTP text format %d\n", codec);
09144 }
09145 ast_rtp_codecs_payloads_set_m_type(&newtextrtp, NULL, codec);
09146 }
09147 } else {
09148 ast_log(LOG_WARNING, "Rejecting text media offer due to invalid or unsupported syntax: %s\n", m);
09149 return -1;
09150 }
09151 }
09152
09153 else if (strncmp(m, "image ", 6) == 0) {
09154 if (((sscanf(m, "image %30u udptl t38%n", &x, &len) == 1 && len > 0) ||
09155 (sscanf(m, "image %30u UDPTL t38%n", &x, &len) == 1 && len > 0))) {
09156 if (x == 0) {
09157 ast_log(LOG_WARNING, "Ignoring image media offer because port number is zero\n");
09158 continue;
09159 }
09160
09161 if (initialize_udptl(p)) {
09162 ast_log(LOG_WARNING, "Rejecting offer with image stream due to UDPTL initialization failure\n");
09163 return -1;
09164 }
09165
09166 if (p->offered_media[SDP_IMAGE].order_offered) {
09167 ast_log(LOG_WARNING, "Rejecting non-primary image stream: %s\n", m);
09168 return -1;
09169 }
09170
09171 image = TRUE;
09172 if (debug) {
09173 ast_verbose("Got T.38 offer in SDP in dialog %s\n", p->callid);
09174 }
09175
09176 p->offered_media[SDP_IMAGE].order_offered = ++numberofmediastreams;
09177 udptlportno = x;
09178
09179 if (p->t38.state != T38_ENABLED) {
09180 memset(&p->t38.their_parms, 0, sizeof(p->t38.their_parms));
09181
09182
09183
09184 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
09185 }
09186 } else {
09187 ast_log(LOG_WARNING, "Rejecting image media offer due to invalid or unsupported syntax: %s\n", m);
09188 return -1;
09189 }
09190 } else {
09191 ast_log(LOG_WARNING, "Unsupported top-level media type in offer: %s\n", m);
09192 continue;
09193 }
09194
09195
09196 while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
09197 int processed = FALSE;
09198
09199 switch (type) {
09200 case 'c':
09201 if (audio) {
09202 if (process_sdp_c(value, &audiosa)) {
09203 processed = TRUE;
09204 sa = &audiosa;
09205 }
09206 } else if (video) {
09207 if (process_sdp_c(value, &videosa)) {
09208 processed = TRUE;
09209 vsa = &videosa;
09210 }
09211 } else if (text) {
09212 if (process_sdp_c(value, &textsa)) {
09213 processed = TRUE;
09214 tsa = &textsa;
09215 }
09216 } else if (image) {
09217 if (process_sdp_c(value, &imagesa)) {
09218 processed = TRUE;
09219 isa = &imagesa;
09220 }
09221 }
09222 break;
09223 case 'a':
09224
09225 if (audio) {
09226 if (process_sdp_a_sendonly(value, &sendonly)) {
09227 processed = TRUE;
09228 } else if (!processed_crypto && process_crypto(p, p->rtp, &p->srtp, value)) {
09229 processed_crypto = TRUE;
09230 processed = TRUE;
09231 } else if (process_sdp_a_audio(value, p, &newaudiortp, &last_rtpmap_codec)) {
09232 processed = TRUE;
09233 }
09234 }
09235
09236 else if (video) {
09237 if (!processed_crypto && process_crypto(p, p->vrtp, &p->vsrtp, value)) {
09238 processed_crypto = TRUE;
09239 processed = TRUE;
09240 } else if (process_sdp_a_video(value, p, &newvideortp, &last_rtpmap_codec)) {
09241 processed = TRUE;
09242 }
09243 }
09244
09245 else if (text) {
09246 if (process_sdp_a_text(value, p, &newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec)) {
09247 processed = TRUE;
09248 } else if (!processed_crypto && process_crypto(p, p->trtp, &p->tsrtp, value)) {
09249 processed_crypto = TRUE;
09250 processed = TRUE;
09251 }
09252 }
09253
09254 else if (image) {
09255 if (process_sdp_a_image(value, p))
09256 processed = TRUE;
09257 }
09258 break;
09259 }
09260
09261 ast_debug(3, "Processing media-level (%s) SDP %c=%s... %s\n",
09262 (audio == TRUE)? "audio" : (video == TRUE)? "video" : (text == TRUE)? "text" : "image",
09263 type, value,
09264 (processed == TRUE)? "OK." : "UNSUPPORTED OR FAILED.");
09265 }
09266 }
09267
09268
09269 if (!sa && !vsa && !tsa && !isa) {
09270 ast_log(LOG_WARNING, "Insufficient information in SDP (c=)...\n");
09271 return -1;
09272 }
09273
09274 if ((portno == -1) &&
09275 (vportno == -1) &&
09276 (tportno == -1) &&
09277 (udptlportno == -1)) {
09278 ast_log(LOG_WARNING, "Failing due to no acceptable offer found\n");
09279 return -1;
09280 }
09281
09282 if (secure_audio && !(p->srtp && (ast_test_flag(p->srtp, SRTP_CRYPTO_OFFER_OK)))) {
09283 ast_log(LOG_WARNING, "Can't provide secure audio requested in SDP offer\n");
09284 return -1;
09285 }
09286
09287 if (!secure_audio && p->srtp) {
09288 ast_log(LOG_WARNING, "We are requesting SRTP for audio, but they responded without it!\n");
09289 return -1;
09290 }
09291
09292 if (secure_video && !(p->vsrtp && (ast_test_flag(p->vsrtp, SRTP_CRYPTO_OFFER_OK)))) {
09293 ast_log(LOG_WARNING, "Can't provide secure video requested in SDP offer\n");
09294 return -1;
09295 }
09296
09297 if (!p->novideo && !secure_video && p->vsrtp) {
09298 ast_log(LOG_WARNING, "We are requesting SRTP for video, but they responded without it!\n");
09299 return -1;
09300 }
09301
09302 if (!(secure_audio || secure_video) && ast_test_flag(&p->flags[1], SIP_PAGE2_USE_SRTP)) {
09303 ast_log(LOG_WARNING, "Matched device setup to use SRTP, but request was not!\n");
09304 return -1;
09305 }
09306
09307 if (udptlportno == -1) {
09308 change_t38_state(p, T38_DISABLED);
09309 }
09310
09311
09312 ast_rtp_codecs_payload_formats(&newaudiortp, &peercapability, &peernoncodeccapability);
09313 ast_rtp_codecs_payload_formats(&newvideortp, &vpeercapability, &vpeernoncodeccapability);
09314 ast_rtp_codecs_payload_formats(&newtextrtp, &tpeercapability, &tpeernoncodeccapability);
09315
09316 newjointcapability = p->capability & (peercapability | vpeercapability | tpeercapability);
09317 newpeercapability = (peercapability | vpeercapability | tpeercapability);
09318 newnoncodeccapability = p->noncodeccapability & peernoncodeccapability;
09319
09320 if (debug) {
09321
09322 char s1[SIPBUFSIZE], s2[SIPBUFSIZE], s3[SIPBUFSIZE], s4[SIPBUFSIZE], s5[SIPBUFSIZE];
09323
09324 ast_verbose("Capabilities: us - %s, peer - audio=%s/video=%s/text=%s, combined - %s\n",
09325 ast_getformatname_multiple(s1, SIPBUFSIZE, p->capability),
09326 ast_getformatname_multiple(s2, SIPBUFSIZE, peercapability),
09327 ast_getformatname_multiple(s3, SIPBUFSIZE, vpeercapability),
09328 ast_getformatname_multiple(s4, SIPBUFSIZE, tpeercapability),
09329 ast_getformatname_multiple(s5, SIPBUFSIZE, newjointcapability));
09330 }
09331 if (debug) {
09332 struct ast_str *s1 = ast_str_alloca(SIPBUFSIZE);
09333 struct ast_str *s2 = ast_str_alloca(SIPBUFSIZE);
09334 struct ast_str *s3 = ast_str_alloca(SIPBUFSIZE);
09335
09336 ast_verbose("Non-codec capabilities (dtmf): us - %s, peer - %s, combined - %s\n",
09337 ast_rtp_lookup_mime_multiple2(s1, p->noncodeccapability, 0, 0),
09338 ast_rtp_lookup_mime_multiple2(s2, peernoncodeccapability, 0, 0),
09339 ast_rtp_lookup_mime_multiple2(s3, newnoncodeccapability, 0, 0));
09340 }
09341 if (!newjointcapability && udptlportno == -1) {
09342 ast_log(LOG_NOTICE, "No compatible codecs, not accepting this offer!\n");
09343
09344 return -1;
09345 }
09346
09347 if (portno != -1 || vportno != -1 || tportno != -1) {
09348
09349
09350 p->jointcapability = newjointcapability;
09351 p->peercapability = newpeercapability;
09352 p->jointnoncodeccapability = newnoncodeccapability;
09353
09354
09355 if (ast_test_flag(&p->flags[1], SIP_PAGE2_PREFERRED_CODEC)) {
09356 p->jointcapability = ast_codec_choose(&p->prefs, p->jointcapability, 1);
09357 }
09358 }
09359
09360
09361 if (p->rtp) {
09362 if (portno > 0) {
09363 ast_sockaddr_set_port(sa, portno);
09364 ast_rtp_instance_set_remote_address(p->rtp, sa);
09365 if (debug) {
09366 ast_verbose("Peer audio RTP is at port %s\n",
09367 ast_sockaddr_stringify(sa));
09368 }
09369
09370 ast_rtp_codecs_payloads_copy(&newaudiortp, ast_rtp_instance_get_codecs(p->rtp), p->rtp);
09371
09372
09373 ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_RTCP, 1);
09374
09375 if (p->owner) {
09376 ast_channel_set_fd(p->owner, 1, ast_rtp_instance_fd(p->rtp, 1));
09377 }
09378
09379 if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) {
09380 ast_clear_flag(&p->flags[0], SIP_DTMF);
09381 if (newnoncodeccapability & AST_RTP_DTMF) {
09382
09383 ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
09384
09385 ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF, 1);
09386 ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
09387 } else {
09388 ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
09389 }
09390 }
09391 } else if (udptlportno > 0) {
09392 if (debug)
09393 ast_verbose("Got T.38 Re-invite without audio. Keeping RTP active during T.38 session.\n");
09394
09395 if (p->owner) {
09396 ast_channel_set_fd(p->owner, 1, -1);
09397 }
09398
09399 ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_RTCP, 0);
09400 } else {
09401 ast_rtp_instance_stop(p->rtp);
09402 if (debug)
09403 ast_verbose("Peer doesn't provide audio\n");
09404 }
09405 }
09406
09407
09408 if (p->vrtp) {
09409 if (vportno > 0) {
09410 ast_sockaddr_set_port(vsa, vportno);
09411 ast_rtp_instance_set_remote_address(p->vrtp, vsa);
09412 if (debug) {
09413 ast_verbose("Peer video RTP is at port %s\n",
09414 ast_sockaddr_stringify(vsa));
09415 }
09416 ast_rtp_codecs_payloads_copy(&newvideortp, ast_rtp_instance_get_codecs(p->vrtp), p->vrtp);
09417 } else {
09418 ast_rtp_instance_stop(p->vrtp);
09419 if (debug)
09420 ast_verbose("Peer doesn't provide video\n");
09421 }
09422 }
09423
09424
09425 if (p->trtp) {
09426 if (tportno > 0) {
09427 ast_sockaddr_set_port(tsa, tportno);
09428 ast_rtp_instance_set_remote_address(p->trtp, tsa);
09429 if (debug) {
09430 ast_verbose("Peer T.140 RTP is at port %s\n",
09431 ast_sockaddr_stringify(tsa));
09432 }
09433 if ((p->jointcapability & AST_FORMAT_T140RED)) {
09434 p->red = 1;
09435 ast_rtp_red_init(p->trtp, 300, red_data_pt, 2);
09436 } else {
09437 p->red = 0;
09438 }
09439 ast_rtp_codecs_payloads_copy(&newtextrtp, ast_rtp_instance_get_codecs(p->trtp), p->trtp);
09440 } else {
09441 ast_rtp_instance_stop(p->trtp);
09442 if (debug)
09443 ast_verbose("Peer doesn't provide T.140\n");
09444 }
09445 }
09446
09447
09448 if (p->udptl) {
09449 if (udptlportno > 0) {
09450 if (ast_test_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP) && ast_test_flag(&p->flags[1], SIP_PAGE2_UDPTL_DESTINATION)) {
09451 ast_rtp_instance_get_remote_address(p->rtp, isa);
09452 if (!ast_sockaddr_isnull(isa) && debug) {
09453 ast_debug(1, "Peer T.38 UDPTL is set behind NAT and with destination, destination address now %s\n", ast_sockaddr_stringify(isa));
09454 }
09455 }
09456 ast_sockaddr_set_port(isa, udptlportno);
09457 ast_udptl_set_peer(p->udptl, isa);
09458 if (debug)
09459 ast_debug(1,"Peer T.38 UDPTL is at port %s\n", ast_sockaddr_stringify(isa));
09460
09461
09462 if (!ast_udptl_get_far_max_datagram(p->udptl)) {
09463
09464 ast_udptl_set_far_max_datagram(p->udptl, 0);
09465 }
09466
09467
09468 if ((t38action == SDP_T38_ACCEPT) &&
09469 (p->t38.state == T38_LOCAL_REINVITE)) {
09470 change_t38_state(p, T38_ENABLED);
09471 } else if ((t38action == SDP_T38_INITIATE) &&
09472 p->owner && p->lastinvite) {
09473 change_t38_state(p, T38_PEER_REINVITE);
09474
09475 if (ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_T38)) {
09476 ast_channel_lock(p->owner);
09477 if (strcmp(p->owner->exten, "fax")) {
09478 const char *target_context = S_OR(p->owner->macrocontext, p->owner->context);
09479 ast_channel_unlock(p->owner);
09480 if (ast_exists_extension(p->owner, target_context, "fax", 1,
09481 S_COR(p->owner->caller.id.number.valid, p->owner->caller.id.number.str, NULL))) {
09482 ast_verbose(VERBOSE_PREFIX_2 "Redirecting '%s' to fax extension due to peer T.38 re-INVITE\n", p->owner->name);
09483 pbx_builtin_setvar_helper(p->owner, "FAXEXTEN", p->owner->exten);
09484 if (ast_async_goto(p->owner, target_context, "fax", 1)) {
09485 ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", p->owner->name, target_context);
09486 }
09487 } else {
09488 ast_log(LOG_NOTICE, "T.38 re-INVITE detected but no fax extension\n");
09489 }
09490 } else {
09491 ast_channel_unlock(p->owner);
09492 }
09493 }
09494 }
09495 } else {
09496 change_t38_state(p, T38_DISABLED);
09497 ast_udptl_stop(p->udptl);
09498 if (debug)
09499 ast_debug(1, "Peer doesn't provide T.38 UDPTL\n");
09500 }
09501 }
09502
09503 if ((portno == -1) && (p->t38.state != T38_DISABLED)) {
09504 ast_debug(3, "Have T.38 but no audio, accepting offer anyway\n");
09505 return 0;
09506 }
09507
09508
09509 ast_debug(2, "We're settling with these formats: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, p->jointcapability));
09510
09511 if (!p->owner)
09512 return 0;
09513
09514 ast_debug(4, "We have an owner, now see if we need to change this call\n");
09515
09516 if (!(p->owner->nativeformats & p->jointcapability) && (p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
09517 if (debug) {
09518 char s1[SIPBUFSIZE], s2[SIPBUFSIZE];
09519 ast_debug(1, "Oooh, we need to change our audio formats since our peer supports only %s and not %s\n",
09520 ast_getformatname_multiple(s1, SIPBUFSIZE, p->jointcapability),
09521 ast_getformatname_multiple(s2, SIPBUFSIZE, p->owner->nativeformats));
09522 }
09523 p->owner->nativeformats = ast_codec_choose(&p->prefs, p->jointcapability, 1) | (p->capability & vpeercapability) | (p->capability & tpeercapability);
09524 ast_set_read_format(p->owner, p->owner->readformat);
09525 ast_set_write_format(p->owner, p->owner->writeformat);
09526 }
09527
09528 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)) {
09529 ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
09530
09531 ast_queue_frame(p->owner, &ast_null_frame);
09532 change_hold_state(p, req, FALSE, sendonly);
09533 } 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)) {
09534 ast_queue_control_data(p->owner, AST_CONTROL_HOLD,
09535 S_OR(p->mohsuggest, NULL),
09536 !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
09537 if (sendonly)
09538 ast_rtp_instance_stop(p->rtp);
09539
09540
09541 ast_queue_frame(p->owner, &ast_null_frame);
09542 change_hold_state(p, req, TRUE, sendonly);
09543 }
09544
09545 return 0;
09546 }
09547
09548 static int process_sdp_o(const char *o, struct sip_pvt *p)
09549 {
09550 char *o_copy;
09551 char *token;
09552 int64_t rua_version;
09553
09554
09555
09556
09557
09558
09559
09560
09561
09562
09563 p->session_modify = TRUE;
09564
09565 if (ast_strlen_zero(o)) {
09566 ast_log(LOG_WARNING, "SDP syntax error. SDP without an o= line\n");
09567 return FALSE;
09568 }
09569
09570 o_copy = ast_strdupa(o);
09571 token = strsep(&o_copy, " ");
09572 if (!o_copy) {
09573 ast_log(LOG_WARNING, "SDP syntax error in o= line username\n");
09574 return FALSE;
09575 }
09576 token = strsep(&o_copy, " ");
09577 if (!o_copy) {
09578 ast_log(LOG_WARNING, "SDP syntax error in o= line session-id\n");
09579 return FALSE;
09580 }
09581 token = strsep(&o_copy, " ");
09582 if (!o_copy) {
09583 ast_log(LOG_WARNING, "SDP syntax error in o= line\n");
09584 return FALSE;
09585 }
09586 if (!sscanf(token, "%30" SCNd64, &rua_version)) {
09587 ast_log(LOG_WARNING, "SDP syntax error in o= line version\n");
09588 return FALSE;
09589 }
09590
09591
09592
09593
09594
09595
09596
09597
09598
09599
09600
09601
09602
09603
09604
09605
09606
09607
09608
09609 if (ast_test_flag(&p->flags[1], SIP_PAGE2_IGNORESDPVERSION) ||
09610 (p->sessionversion_remote < 0) ||
09611 (p->sessionversion_remote < rua_version)) {
09612 p->sessionversion_remote = rua_version;
09613 } else {
09614 if (p->t38.state == T38_LOCAL_REINVITE) {
09615 p->sessionversion_remote = rua_version;
09616 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);
09617 } else {
09618 p->session_modify = FALSE;
09619 ast_debug(2, "Call %s responded to our reinvite without changing SDP version; ignoring SDP.\n", p->callid);
09620 return FALSE;
09621 }
09622 }
09623
09624 return TRUE;
09625 }
09626
09627 static int process_sdp_c(const char *c, struct ast_sockaddr *addr)
09628 {
09629 char proto[4], host[258];
09630 int af;
09631
09632
09633 if (sscanf(c, "IN %3s %255s", proto, host) == 2) {
09634 if (!strcmp("IP4", proto)) {
09635 af = AF_INET;
09636 } else if (!strcmp("IP6", proto)) {
09637 af = AF_INET6;
09638 } else {
09639 ast_log(LOG_WARNING, "Unknown protocol '%s'.\n", proto);
09640 return FALSE;
09641 }
09642 if (ast_sockaddr_resolve_first_af(addr, host, 0, af)) {
09643 ast_log(LOG_WARNING, "Unable to lookup RTP Audio host in c= line, '%s'\n", c);
09644 return FALSE;
09645 }
09646 return TRUE;
09647 } else {
09648 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
09649 return FALSE;
09650 }
09651 return FALSE;
09652 }
09653
09654 static int process_sdp_a_sendonly(const char *a, int *sendonly)
09655 {
09656 int found = FALSE;
09657
09658 if (!strcasecmp(a, "sendonly")) {
09659 if (*sendonly == -1)
09660 *sendonly = 1;
09661 found = TRUE;
09662 } else if (!strcasecmp(a, "inactive")) {
09663 if (*sendonly == -1)
09664 *sendonly = 2;
09665 found = TRUE;
09666 } else if (!strcasecmp(a, "sendrecv")) {
09667 if (*sendonly == -1)
09668 *sendonly = 0;
09669 found = TRUE;
09670 }
09671 return found;
09672 }
09673
09674 static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newaudiortp, int *last_rtpmap_codec)
09675 {
09676 int found = FALSE;
09677 int codec;
09678 char mimeSubtype[128];
09679 char fmtp_string[64];
09680 unsigned int sample_rate;
09681 int debug = sip_debug_test_pvt(p);
09682
09683 if (!strncasecmp(a, "ptime", 5)) {
09684 char *tmp = strrchr(a, ':');
09685 long int framing = 0;
09686 if (tmp) {
09687 tmp++;
09688 framing = strtol(tmp, NULL, 10);
09689 if (framing == LONG_MIN || framing == LONG_MAX) {
09690 framing = 0;
09691 ast_debug(1, "Can't read framing from SDP: %s\n", a);
09692 }
09693 }
09694 if (framing && p->autoframing) {
09695 struct ast_codec_pref *pref = &ast_rtp_instance_get_codecs(p->rtp)->pref;
09696 int codec_n;
09697 for (codec_n = 0; codec_n < AST_RTP_MAX_PT; codec_n++) {
09698 struct ast_rtp_payload_type format = ast_rtp_codecs_payload_lookup(ast_rtp_instance_get_codecs(p->rtp), codec_n);
09699 if (!format.asterisk_format || !format.code)
09700 continue;
09701 ast_debug(1, "Setting framing for %s to %ld\n", ast_getformatname(format.code), framing);
09702 ast_codec_pref_setsize(pref, format.code, framing);
09703 }
09704 ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(p->rtp), p->rtp, pref);
09705 }
09706 found = TRUE;
09707 } else if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
09708
09709 if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
09710 if (!(ast_rtp_codecs_payloads_set_rtpmap_type_rate(newaudiortp, NULL, codec, "audio", mimeSubtype,
09711 ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0, sample_rate))) {
09712 if (debug)
09713 ast_verbose("Found audio description format %s for ID %d\n", mimeSubtype, codec);
09714
09715 (*last_rtpmap_codec)++;
09716 found = TRUE;
09717 } else {
09718 ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
09719 if (debug)
09720 ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
09721 }
09722 } else {
09723 if (debug)
09724 ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
09725 }
09726 } else if (sscanf(a, "fmtp: %30u %63s", &codec, fmtp_string) == 2) {
09727 struct ast_rtp_payload_type payload;
09728
09729 payload = ast_rtp_codecs_payload_lookup(newaudiortp, codec);
09730 if (payload.code && payload.asterisk_format) {
09731 unsigned int bit_rate;
09732
09733 switch (payload.code) {
09734 case AST_FORMAT_SIREN7:
09735 if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
09736 if (bit_rate != 32000) {
09737 ast_log(LOG_WARNING, "Got Siren7 offer at %d bps, but only 32000 bps supported; ignoring.\n", bit_rate);
09738 ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
09739 } else {
09740 found = TRUE;
09741 }
09742 }
09743 break;
09744 case AST_FORMAT_SIREN14:
09745 if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
09746 if (bit_rate != 48000) {
09747 ast_log(LOG_WARNING, "Got Siren14 offer at %d bps, but only 48000 bps supported; ignoring.\n", bit_rate);
09748 ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
09749 } else {
09750 found = TRUE;
09751 }
09752 }
09753 break;
09754 case AST_FORMAT_G719:
09755 if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
09756 if (bit_rate != 64000) {
09757 ast_log(LOG_WARNING, "Got G.719 offer at %d bps, but only 64000 bps supported; ignoring.\n", bit_rate);
09758 ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
09759 } else {
09760 found = TRUE;
09761 }
09762 }
09763 }
09764 }
09765 }
09766
09767 return found;
09768 }
09769
09770 static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newvideortp, int *last_rtpmap_codec)
09771 {
09772 int found = FALSE;
09773 int codec;
09774 char mimeSubtype[128];
09775 unsigned int sample_rate;
09776 int debug = sip_debug_test_pvt(p);
09777
09778 if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
09779
09780 if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
09781
09782 if (!strncasecmp(mimeSubtype, "H26", 3) || !strncasecmp(mimeSubtype, "MP4", 3)) {
09783 if (!(ast_rtp_codecs_payloads_set_rtpmap_type_rate(newvideortp, NULL, codec, "video", mimeSubtype, 0, sample_rate))) {
09784 if (debug)
09785 ast_verbose("Found video description format %s for ID %d\n", mimeSubtype, codec);
09786
09787 (*last_rtpmap_codec)++;
09788 found = TRUE;
09789 } else {
09790 ast_rtp_codecs_payloads_unset(newvideortp, NULL, codec);
09791 if (debug)
09792 ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
09793 }
09794 }
09795 } else {
09796 if (debug)
09797 ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
09798 }
09799 }
09800
09801 return found;
09802 }
09803
09804 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)
09805 {
09806 int found = FALSE;
09807 int codec;
09808 char mimeSubtype[128];
09809 unsigned int sample_rate;
09810 char *red_cp;
09811 int debug = sip_debug_test_pvt(p);
09812
09813 if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
09814
09815 if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
09816 if (!strncasecmp(mimeSubtype, "T140", 4)) {
09817 if (p->trtp) {
09818
09819 ast_rtp_codecs_payloads_set_rtpmap_type_rate(newtextrtp, NULL, codec, "text", mimeSubtype, 0, sample_rate);
09820 found = TRUE;
09821 }
09822 } else if (!strncasecmp(mimeSubtype, "RED", 3)) {
09823 if (p->trtp) {
09824 ast_rtp_codecs_payloads_set_rtpmap_type_rate(newtextrtp, NULL, codec, "text", mimeSubtype, 0, sample_rate);
09825 sprintf(red_fmtp, "fmtp:%d ", codec);
09826 if (debug)
09827 ast_verbose("RED submimetype has payload type: %d\n", codec);
09828 found = TRUE;
09829 }
09830 }
09831 } else {
09832 if (debug)
09833 ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
09834 }
09835 } else if (!strncmp(a, red_fmtp, strlen(red_fmtp))) {
09836
09837 red_cp = &red_fmtp[strlen(red_fmtp)];
09838 strncpy(red_fmtp, a, 100);
09839
09840 sscanf(red_cp, "%30u", &red_data_pt[*red_num_gen]);
09841 red_cp = strtok(red_cp, "/");
09842 while (red_cp && (*red_num_gen)++ < AST_RED_MAX_GENERATION) {
09843 sscanf(red_cp, "%30u", &red_data_pt[*red_num_gen]);
09844 red_cp = strtok(NULL, "/");
09845 }
09846 red_cp = red_fmtp;
09847 found = TRUE;
09848 }
09849
09850 return found;
09851 }
09852
09853 static int process_sdp_a_image(const char *a, struct sip_pvt *p)
09854 {
09855 int found = FALSE;
09856 char s[256];
09857 unsigned int x;
09858
09859 if (initialize_udptl(p)) {
09860 return found;
09861 }
09862
09863 if ((sscanf(a, "T38FaxMaxBuffer:%30u", &x) == 1)) {
09864 ast_debug(3, "MaxBufferSize:%d\n", x);
09865 found = TRUE;
09866 } else if ((sscanf(a, "T38MaxBitRate:%30u", &x) == 1) || (sscanf(a, "T38FaxMaxRate:%30u", &x) == 1)) {
09867 ast_debug(3, "T38MaxBitRate: %d\n", x);
09868 switch (x) {
09869 case 14400:
09870 p->t38.their_parms.rate = AST_T38_RATE_14400;
09871 break;
09872 case 12000:
09873 p->t38.their_parms.rate = AST_T38_RATE_12000;
09874 break;
09875 case 9600:
09876 p->t38.their_parms.rate = AST_T38_RATE_9600;
09877 break;
09878 case 7200:
09879 p->t38.their_parms.rate = AST_T38_RATE_7200;
09880 break;
09881 case 4800:
09882 p->t38.their_parms.rate = AST_T38_RATE_4800;
09883 break;
09884 case 2400:
09885 p->t38.their_parms.rate = AST_T38_RATE_2400;
09886 break;
09887 }
09888 found = TRUE;
09889 } else if ((sscanf(a, "T38FaxVersion:%30u", &x) == 1)) {
09890 ast_debug(3, "FaxVersion: %u\n", x);
09891 p->t38.their_parms.version = x;
09892 found = TRUE;
09893 } else if ((sscanf(a, "T38FaxMaxDatagram:%30u", &x) == 1) || (sscanf(a, "T38MaxDatagram:%30u", &x) == 1)) {
09894
09895 if (((signed int) p->t38_maxdatagram >= 0) && ((unsigned int) p->t38_maxdatagram > x)) {
09896 ast_debug(1, "Overriding T38FaxMaxDatagram '%d' with '%d'\n", x, p->t38_maxdatagram);
09897 x = p->t38_maxdatagram;
09898 }
09899 ast_debug(3, "FaxMaxDatagram: %u\n", x);
09900 ast_udptl_set_far_max_datagram(p->udptl, x);
09901 found = TRUE;
09902 } else if ((strncmp(a, "T38FaxFillBitRemoval", 20) == 0)) {
09903 if (sscanf(a, "T38FaxFillBitRemoval:%30u", &x) == 1) {
09904 ast_debug(3, "FillBitRemoval: %d\n", x);
09905 if (x == 1) {
09906 p->t38.their_parms.fill_bit_removal = TRUE;
09907 }
09908 } else {
09909 ast_debug(3, "FillBitRemoval\n");
09910 p->t38.their_parms.fill_bit_removal = TRUE;
09911 }
09912 found = TRUE;
09913 } else if ((strncmp(a, "T38FaxTranscodingMMR", 20) == 0)) {
09914 if (sscanf(a, "T38FaxTranscodingMMR:%30u", &x) == 1) {
09915 ast_debug(3, "Transcoding MMR: %d\n", x);
09916 if (x == 1) {
09917 p->t38.their_parms.transcoding_mmr = TRUE;
09918 }
09919 } else {
09920 ast_debug(3, "Transcoding MMR\n");
09921 p->t38.their_parms.transcoding_mmr = TRUE;
09922 }
09923 found = TRUE;
09924 } else if ((strncmp(a, "T38FaxTranscodingJBIG", 21) == 0)) {
09925 if (sscanf(a, "T38FaxTranscodingJBIG:%30u", &x) == 1) {
09926 ast_debug(3, "Transcoding JBIG: %d\n", x);
09927 if (x == 1) {
09928 p->t38.their_parms.transcoding_jbig = TRUE;
09929 }
09930 } else {
09931 ast_debug(3, "Transcoding JBIG\n");
09932 p->t38.their_parms.transcoding_jbig = TRUE;
09933 }
09934 found = TRUE;
09935 } else if ((sscanf(a, "T38FaxRateManagement:%255s", s) == 1)) {
09936 ast_debug(3, "RateManagement: %s\n", s);
09937 if (!strcasecmp(s, "localTCF"))
09938 p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_LOCAL_TCF;
09939 else if (!strcasecmp(s, "transferredTCF"))
09940 p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF;
09941 found = TRUE;
09942 } else if ((sscanf(a, "T38FaxUdpEC:%255s", s) == 1)) {
09943 ast_debug(3, "UDP EC: %s\n", s);
09944 if (!strcasecmp(s, "t38UDPRedundancy")) {
09945 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
09946 } else if (!strcasecmp(s, "t38UDPFEC")) {
09947 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
09948 } else {
09949 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
09950 }
09951 found = TRUE;
09952 }
09953
09954 return found;
09955 }
09956
09957
09958
09959
09960 static int add_supported_header(struct sip_pvt *pvt, struct sip_request *req)
09961 {
09962 int res;
09963 if (st_get_mode(pvt, 0) != SESSION_TIMER_MODE_REFUSE) {
09964 res = add_header(req, "Supported", "replaces, timer");
09965 } else {
09966 res = add_header(req, "Supported", "replaces");
09967 }
09968 return res;
09969 }
09970
09971
09972 static int add_header(struct sip_request *req, const char *var, const char *value)
09973 {
09974 if (req->headers == SIP_MAX_HEADERS) {
09975 ast_log(LOG_WARNING, "Out of SIP header space\n");
09976 return -1;
09977 }
09978
09979 if (req->lines) {
09980 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
09981 return -1;
09982 }
09983
09984 if (sip_cfg.compactheaders) {
09985 var = find_alias(var, var);
09986 }
09987
09988 ast_str_append(&req->data, 0, "%s: %s\r\n", var, value);
09989 req->header[req->headers] = ast_str_strlen(req->data);
09990
09991 req->headers++;
09992
09993 return 0;
09994 }
09995
09996
09997
09998
09999
10000 static int add_header_max_forwards(struct sip_pvt *dialog, struct sip_request *req)
10001 {
10002 char clen[10];
10003
10004 snprintf(clen, sizeof(clen), "%d", dialog->maxforwards);
10005
10006 return add_header(req, "Max-Forwards", clen);
10007 }
10008
10009
10010 static int finalize_content(struct sip_request *req)
10011 {
10012 char clen[10];
10013
10014 if (req->lines) {
10015 ast_log(LOG_WARNING, "finalize_content() called on a message that has already been finalized\n");
10016 return -1;
10017 }
10018
10019 snprintf(clen, sizeof(clen), "%zd", ast_str_strlen(req->content));
10020 add_header(req, "Content-Length", clen);
10021
10022 if (ast_str_strlen(req->content)) {
10023 ast_str_append(&req->data, 0, "\r\n%s", ast_str_buffer(req->content));
10024 }
10025 req->lines = ast_str_strlen(req->content) ? 1 : 0;
10026 return 0;
10027 }
10028
10029
10030 static int add_content(struct sip_request *req, const char *line)
10031 {
10032 if (req->lines) {
10033 ast_log(LOG_WARNING, "Can't add more content when the content has been finalized\n");
10034 return -1;
10035 }
10036
10037 ast_str_append(&req->content, 0, "%s", line);
10038 return 0;
10039 }
10040
10041
10042 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field)
10043 {
10044 const char *tmp = get_header(orig, field);
10045
10046 if (!ast_strlen_zero(tmp))
10047 return add_header(req, field, tmp);
10048 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
10049 return -1;
10050 }
10051
10052
10053 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field)
10054 {
10055 int start = 0;
10056 int copied = 0;
10057 for (;;) {
10058 const char *tmp = __get_header(orig, field, &start);
10059
10060 if (ast_strlen_zero(tmp))
10061 break;
10062
10063 add_header(req, field, tmp);
10064 copied++;
10065 }
10066 return copied ? 0 : -1;
10067 }
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field)
10078 {
10079 int copied = 0;
10080 int start = 0;
10081
10082 for (;;) {
10083 char new[512];
10084 const char *oh = __get_header(orig, field, &start);
10085
10086 if (ast_strlen_zero(oh))
10087 break;
10088
10089 if (!copied) {
10090 char leftmost[512], *others, *rport;
10091
10092
10093 ast_copy_string(leftmost, oh, sizeof(leftmost));
10094 others = strchr(leftmost, ',');
10095 if (others)
10096 *others++ = '\0';
10097
10098
10099 rport = strstr(leftmost, ";rport");
10100 if (rport && *(rport+6) == '=')
10101 rport = NULL;
10102
10103 if (((ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT)) || (rport && ast_test_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT)))) {
10104
10105 char *end;
10106
10107 rport = strstr(leftmost, ";rport");
10108
10109 if (rport) {
10110 end = strchr(rport + 1, ';');
10111 if (end)
10112 memmove(rport, end, strlen(end) + 1);
10113 else
10114 *rport = '\0';
10115 }
10116
10117
10118 snprintf(new, sizeof(new), "%s;received=%s;rport=%d%s%s",
10119 leftmost, ast_sockaddr_stringify_addr_remote(&p->recv),
10120 ast_sockaddr_port(&p->recv),
10121 others ? "," : "", others ? others : "");
10122 } else {
10123
10124 snprintf(new, sizeof(new), "%s;received=%s%s%s",
10125 leftmost, ast_sockaddr_stringify_addr_remote(&p->recv),
10126 others ? "," : "", others ? others : "");
10127 }
10128 oh = new;
10129 }
10130 add_header(req, field, oh);
10131 copied++;
10132 }
10133 if (!copied) {
10134 ast_log(LOG_NOTICE, "No header field '%s' present to copy\n", field);
10135 return -1;
10136 }
10137 return 0;
10138 }
10139
10140
10141 static void add_route(struct sip_request *req, struct sip_route *route)
10142 {
10143 char r[SIPBUFSIZE*2], *p;
10144 int n, rem = sizeof(r);
10145
10146 if (!route)
10147 return;
10148
10149 p = r;
10150 for (;route ; route = route->next) {
10151 n = strlen(route->hop);
10152 if (rem < n+3)
10153 break;
10154 if (p != r) {
10155 *p++ = ',';
10156 --rem;
10157 }
10158 *p++ = '<';
10159 ast_copy_string(p, route->hop, rem);
10160 p += n;
10161 *p++ = '>';
10162 rem -= (n+2);
10163 }
10164 *p = '\0';
10165 add_header(req, "Route", r);
10166 }
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177 static void set_destination(struct sip_pvt *p, char *uri)
10178 {
10179 char *h, *maddr, hostname[256];
10180 int hn;
10181 int debug=sip_debug_test_pvt(p);
10182 int tls_on = FALSE;
10183
10184 if (debug)
10185 ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
10186
10187
10188 h = strchr(uri, '@');
10189 if (h)
10190 ++h;
10191 else {
10192 h = uri;
10193 if (!strncasecmp(h, "sip:", 4)) {
10194 h += 4;
10195 } else if (!strncasecmp(h, "sips:", 5)) {
10196 h += 5;
10197 tls_on = TRUE;
10198 }
10199 }
10200 hn = strcspn(h, ";>") + 1;
10201 if (hn > sizeof(hostname))
10202 hn = sizeof(hostname);
10203 ast_copy_string(hostname, h, hn);
10204
10205 h += hn - 1;
10206
10207
10208
10209 if (ast_sockaddr_resolve_first_transport(&p->sa, hostname, 0, p->socket.type)) {
10210 ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
10211 return;
10212 }
10213
10214
10215 maddr = strstr(h, "maddr=");
10216 if (maddr) {
10217 int port;
10218
10219 maddr += 6;
10220 hn = strspn(maddr, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
10221 "0123456789-.:[]") + 1;
10222 if (hn > sizeof(hostname))
10223 hn = sizeof(hostname);
10224 ast_copy_string(hostname, maddr, hn);
10225
10226 port = ast_sockaddr_port(&p->sa);
10227
10228
10229
10230 if (ast_sockaddr_resolve_first_transport(&p->sa, hostname, PARSE_PORT_FORBID, p->socket.type)) {
10231 ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
10232 return;
10233 }
10234
10235 ast_sockaddr_set_port(&p->sa, port);
10236 }
10237
10238 if (!ast_sockaddr_port(&p->sa)) {
10239 ast_sockaddr_set_port(&p->sa, tls_on ?
10240 STANDARD_TLS_PORT : STANDARD_SIP_PORT);
10241 }
10242
10243 if (debug) {
10244 ast_verbose("set_destination: set destination to %s\n",
10245 ast_sockaddr_stringify(&p->sa));
10246 }
10247 }
10248
10249
10250 static int init_resp(struct sip_request *resp, const char *msg)
10251 {
10252
10253 memset(resp, 0, sizeof(*resp));
10254 resp->method = SIP_RESPONSE;
10255 if (!(resp->data = ast_str_create(SIP_MIN_PACKET)))
10256 goto e_return;
10257 if (!(resp->content = ast_str_create(SIP_MIN_PACKET)))
10258 goto e_free_data;
10259 resp->header[0] = 0;
10260 ast_str_set(&resp->data, 0, "SIP/2.0 %s\r\n", msg);
10261 resp->headers++;
10262 return 0;
10263
10264 e_free_data:
10265 ast_free(resp->data);
10266 resp->data = NULL;
10267 e_return:
10268 return -1;
10269 }
10270
10271
10272 static int init_req(struct sip_request *req, int sipmethod, const char *recip)
10273 {
10274
10275 memset(req, 0, sizeof(*req));
10276 if (!(req->data = ast_str_create(SIP_MIN_PACKET)))
10277 goto e_return;
10278 if (!(req->content = ast_str_create(SIP_MIN_PACKET)))
10279 goto e_free_data;
10280 req->method = sipmethod;
10281 req->header[0] = 0;
10282 ast_str_set(&req->data, 0, "%s %s SIP/2.0\r\n", sip_methods[sipmethod].text, recip);
10283 req->headers++;
10284 return 0;
10285
10286 e_free_data:
10287 ast_free(req->data);
10288 req->data = NULL;
10289 e_return:
10290 return -1;
10291 }
10292
10293
10294 static void deinit_req(struct sip_request *req)
10295 {
10296 if (req->data) {
10297 ast_free(req->data);
10298 req->data = NULL;
10299 }
10300 if (req->content) {
10301 ast_free(req->content);
10302 req->content = NULL;
10303 }
10304 }
10305
10306
10307
10308 static inline int resp_needs_contact(const char *msg, enum sipmethod method) {
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324 switch (method) {
10325
10326 case SIP_INVITE:
10327 case SIP_UPDATE:
10328 case SIP_SUBSCRIBE:
10329 case SIP_NOTIFY:
10330 if ((msg[0] >= '1' && msg[0] <= '3') || !strncmp(msg, "485", 3))
10331 return 1;
10332 break;
10333
10334
10335 case SIP_REGISTER:
10336 case SIP_OPTIONS:
10337 if (msg[0] == '2' || msg[0] == '3' || !strncmp(msg, "485", 3))
10338 return 1;
10339 break;
10340
10341
10342 case SIP_BYE:
10343 case SIP_PRACK:
10344 case SIP_MESSAGE:
10345 case SIP_PUBLISH:
10346 if (msg[0] == '3' || !strncmp(msg, "485", 3))
10347 return 1;
10348 break;
10349
10350
10351 case SIP_REFER:
10352 if (msg[0] >= '2' && msg[0] <= '6')
10353 return 1;
10354 break;
10355
10356
10357 case SIP_ACK:
10358 case SIP_CANCEL:
10359 case SIP_INFO:
10360 case SIP_PING:
10361 default:
10362 return 0;
10363 }
10364 return 0;
10365 }
10366
10367
10368 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req)
10369 {
10370 char newto[256];
10371 const char *ot;
10372
10373 init_resp(resp, msg);
10374 copy_via_headers(p, resp, req, "Via");
10375 if (msg[0] == '1' || msg[0] == '2')
10376 copy_all_header(resp, req, "Record-Route");
10377 copy_header(resp, req, "From");
10378 ot = get_header(req, "To");
10379 if (!strcasestr(ot, "tag=") && strncmp(msg, "100", 3)) {
10380
10381
10382 if (!ast_strlen_zero(p->theirtag) && ast_test_flag(&p->flags[0], SIP_OUTGOING))
10383 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
10384 else if (p->tag && !ast_test_flag(&p->flags[0], SIP_OUTGOING))
10385 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
10386 else
10387 ast_copy_string(newto, ot, sizeof(newto));
10388 ot = newto;
10389 }
10390 add_header(resp, "To", ot);
10391 copy_header(resp, req, "Call-ID");
10392 copy_header(resp, req, "CSeq");
10393 if (!ast_strlen_zero(global_useragent))
10394 add_header(resp, "Server", global_useragent);
10395 add_header(resp, "Allow", ALLOWED_METHODS);
10396 add_supported_header(p, resp);
10397
10398
10399 if (p->method == SIP_INVITE && p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE) {
10400 char se_hdr[256];
10401 snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval,
10402 p->stimer->st_ref == SESSION_TIMER_REFRESHER_US ? "uas" : "uac");
10403 add_header(resp, "Session-Expires", se_hdr);
10404 }
10405
10406 if (msg[0] == '2' && (p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER || p->method == SIP_PUBLISH)) {
10407
10408
10409 char tmp[256];
10410
10411 snprintf(tmp, sizeof(tmp), "%d", p->expiry);
10412 add_header(resp, "Expires", tmp);
10413 if (p->expiry) {
10414 char contact[SIPBUFSIZE];
10415 const char *contact_uri = p->method == SIP_SUBSCRIBE ? p->our_contact : p->fullcontact;
10416 char *brackets = strchr(contact_uri, '<');
10417 snprintf(contact, sizeof(contact), "%s%s%s;expires=%d", brackets ? "" : "<", contact_uri, brackets ? "" : ">", p->expiry);
10418 add_header(resp, "Contact", contact);
10419 }
10420 } else if (!ast_strlen_zero(p->our_contact) && resp_needs_contact(msg, p->method)) {
10421 add_header(resp, "Contact", p->our_contact);
10422 }
10423
10424 if (!ast_strlen_zero(p->url)) {
10425 add_header(resp, "Access-URL", p->url);
10426 ast_string_field_set(p, url, NULL);
10427 }
10428
10429
10430
10431
10432
10433
10434
10435 p->sa = p->recv;
10436
10437 if (process_via(p, req)) {
10438 ast_log(LOG_WARNING, "error processing via header, will send response to originating address\n");
10439 }
10440
10441 return 0;
10442 }
10443
10444
10445 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, uint32_t seqno, int newbranch)
10446 {
10447 struct sip_request *orig = &p->initreq;
10448 char stripped[80];
10449 char tmp[80];
10450 char newto[256];
10451 const char *c;
10452 const char *ot, *of;
10453 int is_strict = FALSE;
10454 int is_outbound = ast_test_flag(&p->flags[0], SIP_OUTGOING);
10455
10456 snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", sip_methods[sipmethod].text);
10457
10458 if (!seqno) {
10459 p->ocseq++;
10460 seqno = p->ocseq;
10461 }
10462
10463
10464 if (sipmethod == SIP_CANCEL) {
10465 p->branch = p->invite_branch;
10466 build_via(p);
10467 } else if (newbranch && (sipmethod == SIP_INVITE)) {
10468 p->branch ^= ast_random();
10469 p->invite_branch = p->branch;
10470 build_via(p);
10471 } else if (newbranch) {
10472 p->branch ^= ast_random();
10473 build_via(p);
10474 }
10475
10476
10477 if (p->route && !ast_strlen_zero(p->route->hop) && strstr(p->route->hop, ";lr") == NULL) {
10478 is_strict = TRUE;
10479 if (sipdebug)
10480 ast_debug(1, "Strict routing enforced for session %s\n", p->callid);
10481 }
10482
10483 if (sipmethod == SIP_CANCEL)
10484 c = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
10485 else if (sipmethod == SIP_ACK) {
10486
10487
10488 if (!ast_strlen_zero(p->okcontacturi))
10489 c = is_strict ? p->route->hop : p->okcontacturi;
10490 else
10491 c = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
10492 } else if (!ast_strlen_zero(p->okcontacturi))
10493 c = is_strict ? p->route->hop : p->okcontacturi;
10494 else if (!ast_strlen_zero(p->uri))
10495 c = p->uri;
10496 else {
10497 char *n;
10498
10499 ast_copy_string(stripped, get_header(orig, is_outbound ? "To" : "From"),
10500 sizeof(stripped));
10501 n = get_in_brackets(stripped);
10502 c = remove_uri_parameters(n);
10503 }
10504 init_req(req, sipmethod, c);
10505
10506 snprintf(tmp, sizeof(tmp), "%u %s", seqno, sip_methods[sipmethod].text);
10507
10508 add_header(req, "Via", p->via);
10509
10510
10511
10512
10513
10514 if (p->route &&
10515 !(sipmethod == SIP_CANCEL ||
10516 (sipmethod == SIP_ACK && (p->invitestate == INV_COMPLETED || p->invitestate == INV_CANCELLED)))) {
10517 set_destination(p, p->route->hop);
10518 add_route(req, is_strict ? p->route->next : p->route);
10519 }
10520 add_header_max_forwards(p, req);
10521
10522 ot = get_header(orig, "To");
10523 of = get_header(orig, "From");
10524
10525
10526
10527 if (!strcasestr(ot, "tag=") && sipmethod != SIP_CANCEL) {
10528
10529
10530 if (is_outbound && !ast_strlen_zero(p->theirtag))
10531 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
10532 else if (!is_outbound)
10533 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
10534 else
10535 snprintf(newto, sizeof(newto), "%s", ot);
10536 ot = newto;
10537 }
10538
10539 if (is_outbound) {
10540 add_header(req, "From", of);
10541 add_header(req, "To", ot);
10542 } else {
10543 add_header(req, "From", ot);
10544 add_header(req, "To", of);
10545 }
10546
10547 if (sipmethod != SIP_BYE && sipmethod != SIP_CANCEL && sipmethod != SIP_MESSAGE)
10548 add_header(req, "Contact", p->our_contact);
10549
10550 copy_header(req, orig, "Call-ID");
10551 add_header(req, "CSeq", tmp);
10552
10553 if (!ast_strlen_zero(global_useragent))
10554 add_header(req, "User-Agent", global_useragent);
10555
10556 if (!ast_strlen_zero(p->url)) {
10557 add_header(req, "Access-URL", p->url);
10558 ast_string_field_set(p, url, NULL);
10559 }
10560
10561
10562
10563
10564
10565
10566
10567
10568 if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE
10569 && sipmethod == SIP_INVITE) {
10570 char se_hdr[256];
10571 snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval,
10572 p->stimer->st_ref == SESSION_TIMER_REFRESHER_US ? "uac" : "uas");
10573 add_header(req, "Session-Expires", se_hdr);
10574 snprintf(se_hdr, sizeof(se_hdr), "%d", st_get_se(p, FALSE));
10575 add_header(req, "Min-SE", se_hdr);
10576 }
10577
10578 return 0;
10579 }
10580
10581
10582 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
10583 {
10584 struct sip_request resp;
10585 uint32_t seqno = 0;
10586
10587 if (reliable && (sscanf(get_header(req, "CSeq"), "%30u ", &seqno) != 1)) {
10588 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
10589 return -1;
10590 }
10591 respprep(&resp, p, msg, req);
10592
10593 if (ast_test_flag(&p->flags[0], SIP_SENDRPID)
10594 && ast_test_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND)
10595 && (!strncmp(msg, "180", 3) || !strncmp(msg, "183", 3))) {
10596 ast_clear_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND);
10597 add_rpid(&resp, p);
10598 }
10599 if (ast_test_flag(&p->flags[0], SIP_OFFER_CC)) {
10600 add_cc_call_info_to_response(p, &resp);
10601 }
10602
10603
10604 if (!strncmp(msg, "302", 3)) {
10605 add_diversion_header(&resp, p);
10606 }
10607
10608
10609
10610 if (p->method == SIP_INVITE && msg[0] != '1') {
10611 char buf[20];
10612
10613 if (ast_test_flag(&p->flags[1], SIP_PAGE2_Q850_REASON)) {
10614 int hangupcause = 0;
10615
10616 if (p->owner && p->owner->hangupcause) {
10617 hangupcause = p->owner->hangupcause;
10618 } else if (p->hangupcause) {
10619 hangupcause = p->hangupcause;
10620 } else {
10621 int respcode;
10622 if (sscanf(msg, "%30d ", &respcode))
10623 hangupcause = hangup_sip2cause(respcode);
10624 }
10625
10626 if (hangupcause) {
10627 sprintf(buf, "Q.850;cause=%i", hangupcause & 0x7f);
10628 add_header(&resp, "Reason", buf);
10629 }
10630 }
10631
10632 if (p->owner && p->owner->hangupcause) {
10633 add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->owner->hangupcause));
10634 snprintf(buf, sizeof(buf), "%d", p->owner->hangupcause);
10635 add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
10636 }
10637 }
10638 return send_response(p, &resp, reliable, seqno);
10639 }
10640
10641 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)
10642 {
10643 struct sip_request resp;
10644
10645 if (need_new_etag) {
10646 create_new_sip_etag(esc_entry, 1);
10647 }
10648 respprep(&resp, p, msg, req);
10649 add_header(&resp, "SIP-ETag", esc_entry->entity_tag);
10650
10651 return send_response(p, &resp, 0, 0);
10652 }
10653
10654 static int temp_pvt_init(void *data)
10655 {
10656 struct sip_pvt *p = data;
10657
10658 p->do_history = 0;
10659 return ast_string_field_init(p, 512);
10660 }
10661
10662 static void temp_pvt_cleanup(void *data)
10663 {
10664 struct sip_pvt *p = data;
10665
10666 ast_string_field_free_memory(p);
10667
10668 ast_free(data);
10669 }
10670
10671
10672 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)
10673 {
10674 struct sip_pvt *p = NULL;
10675
10676 if (!(p = ast_threadstorage_get(&ts_temp_pvt, sizeof(*p)))) {
10677 ast_log(LOG_ERROR, "Failed to get temporary pvt\n");
10678 return -1;
10679 }
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689 p->method = intended_method;
10690
10691 if (!addr) {
10692 ast_sockaddr_copy(&p->ourip, &internip);
10693 } else {
10694 ast_sockaddr_copy(&p->sa, addr);
10695 ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
10696 }
10697
10698 p->branch = ast_random();
10699 make_our_tag(p);
10700 p->ocseq = INITIAL_CSEQ;
10701
10702 if (useglobal_nat && addr) {
10703 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT_FORCE_RPORT);
10704 ast_sockaddr_copy(&p->recv, addr);
10705 do_setnat(p);
10706 }
10707
10708 ast_string_field_set(p, fromdomain, default_fromdomain);
10709 p->fromdomainport = default_fromdomainport;
10710 build_via(p);
10711 ast_string_field_set(p, callid, callid);
10712
10713 copy_socket_data(&p->socket, &req->socket);
10714
10715
10716 __transmit_response(p, msg, req, XMIT_UNRELIABLE);
10717
10718
10719 ast_string_field_init(p, 0);
10720
10721 return 0;
10722 }
10723
10724
10725 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req)
10726 {
10727 return __transmit_response(p, msg, req, XMIT_UNRELIABLE);
10728 }
10729
10730
10731 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported)
10732 {
10733 struct sip_request resp;
10734 respprep(&resp, p, msg, req);
10735 append_date(&resp);
10736 add_header(&resp, "Unsupported", unsupported);
10737 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
10738 }
10739
10740
10741 static int transmit_response_with_minse(struct sip_pvt *p, const char *msg, const struct sip_request *req, int minse_int)
10742 {
10743 struct sip_request resp;
10744 char minse_str[20];
10745
10746 respprep(&resp, p, msg, req);
10747 append_date(&resp);
10748
10749 snprintf(minse_str, sizeof(minse_str), "%d", minse_int);
10750 add_header(&resp, "Min-SE", minse_str);
10751 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
10752 }
10753
10754
10755
10756
10757
10758 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req)
10759 {
10760 return __transmit_response(p, msg, req, req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL);
10761 }
10762
10763
10764 static void append_date(struct sip_request *req)
10765 {
10766 char tmpdat[256];
10767 struct tm tm;
10768 time_t t = time(NULL);
10769
10770 gmtime_r(&t, &tm);
10771 strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
10772 add_header(req, "Date", tmpdat);
10773 }
10774
10775
10776 static int transmit_response_with_retry_after(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *seconds)
10777 {
10778 struct sip_request resp;
10779 respprep(&resp, p, msg, req);
10780 add_header(&resp, "Retry-After", seconds);
10781 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
10782 }
10783
10784
10785 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req)
10786 {
10787 struct sip_request resp;
10788 respprep(&resp, p, msg, req);
10789 append_date(&resp);
10790 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
10791 }
10792
10793
10794 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
10795 {
10796 struct sip_request resp;
10797 respprep(&resp, p, msg, req);
10798 add_header(&resp, "Accept", "application/sdp");
10799 return send_response(p, &resp, reliable, 0);
10800 }
10801
10802
10803 static int transmit_response_with_minexpires(struct sip_pvt *p, const char *msg, const struct sip_request *req)
10804 {
10805 struct sip_request resp;
10806 char tmp[32];
10807
10808 snprintf(tmp, sizeof(tmp), "%d", min_expiry);
10809 respprep(&resp, p, msg, req);
10810 add_header(&resp, "Min-Expires", tmp);
10811 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
10812 }
10813
10814
10815 static int transmit_response_with_auth(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *randdata, enum xmittype reliable, const char *header, int stale)
10816 {
10817 struct sip_request resp;
10818 char tmp[512];
10819 uint32_t seqno = 0;
10820
10821 if (reliable && (sscanf(get_header(req, "CSeq"), "%30u ", &seqno) != 1)) {
10822 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
10823 return -1;
10824 }
10825
10826 get_realm(p, req);
10827
10828
10829
10830 snprintf(tmp, sizeof(tmp), "Digest algorithm=MD5, realm=\"%s\", nonce=\"%s\"%s", p->realm, randdata, stale ? ", stale=true" : "");
10831 respprep(&resp, p, msg, req);
10832 add_header(&resp, header, tmp);
10833 append_history(p, "AuthChal", "Auth challenge sent for %s - nc %d", p->username, p->noncecount);
10834 return send_response(p, &resp, reliable, seqno);
10835 }
10836
10837
10838
10839
10840
10841
10842
10843 static int get_domain(const char *str, char *domain, int len)
10844 {
10845 char tmpf[256];
10846 char *a, *from;
10847
10848 *domain = '\0';
10849 ast_copy_string(tmpf, str, sizeof(tmpf));
10850 from = get_in_brackets(tmpf);
10851 if (!ast_strlen_zero(from)) {
10852 if (strncasecmp(from, "sip:", 4)) {
10853 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", from);
10854 return -1;
10855 }
10856 from += 4;
10857 } else
10858 from = NULL;
10859
10860 if (from) {
10861 int bracket = 0;
10862
10863
10864 if ((a = strchr(from, ';')))
10865 *a = '\0';
10866
10867 for (a = from; *a != '\0'; ++a) {
10868 if (*a == ':' && bracket == 0) {
10869 *a = '\0';
10870 break;
10871 } else if (*a == '[') {
10872 ++bracket;
10873 } else if (*a == ']') {
10874 --bracket;
10875 }
10876 }
10877 if ((a = strchr(from, '@'))) {
10878 *a = '\0';
10879 ast_copy_string(domain, a + 1, len);
10880 } else
10881 ast_copy_string(domain, from, len);
10882 }
10883
10884 return ast_strlen_zero(domain);
10885 }
10886
10887
10888
10889
10890
10891 static void get_realm(struct sip_pvt *p, const struct sip_request *req)
10892 {
10893 char domain[MAXHOSTNAMELEN];
10894
10895 if (!ast_strlen_zero(p->realm))
10896 return;
10897
10898 if (sip_cfg.domainsasrealm &&
10899 !AST_LIST_EMPTY(&domain_list))
10900 {
10901
10902 if (!get_domain(get_header(req, "From"), domain, sizeof(domain))) {
10903 if (check_sip_domain(domain, NULL, 0)) {
10904 ast_string_field_set(p, realm, domain);
10905 return;
10906 }
10907 }
10908
10909 if (!get_domain(get_header(req, "To"), domain, sizeof(domain))) {
10910 if (check_sip_domain(domain, NULL, 0)) {
10911 ast_string_field_set(p, realm, domain);
10912 return;
10913 }
10914 }
10915 }
10916
10917
10918 ast_string_field_set(p, realm, sip_cfg.realm);
10919 }
10920
10921
10922
10923
10924
10925
10926
10927
10928 static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp)
10929 {
10930 int res;
10931
10932 if (!(res = with_sdp ? transmit_response_with_sdp(p, msg, req, XMIT_UNRELIABLE, FALSE, FALSE) : transmit_response(p, msg, req))) {
10933 p->last_provisional = msg;
10934 update_provisional_keepalive(p, with_sdp);
10935 }
10936
10937 return res;
10938 }
10939
10940
10941 static int add_text(struct sip_request *req, const char *text)
10942 {
10943
10944 add_header(req, "Content-Type", "text/plain;charset=UTF-8");
10945 add_content(req, text);
10946 return 0;
10947 }
10948
10949
10950
10951
10952
10953 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode)
10954 {
10955 char tmp[256];
10956 int event;
10957 if (mode) {
10958
10959 if ('0' <= digit && digit <= '9') {
10960 event = digit - '0';
10961 } else if (digit == '*') {
10962 event = 10;
10963 } else if (digit == '#') {
10964 event = 11;
10965 } else if ('A' <= digit && digit <= 'D') {
10966 event = 12 + digit - 'A';
10967 } else if ('a' <= digit && digit <= 'd') {
10968 event = 12 + digit - 'a';
10969 } else {
10970
10971 event = 0;
10972 }
10973 snprintf(tmp, sizeof(tmp), "%d\r\n", event);
10974 add_header(req, "Content-Type", "application/dtmf");
10975 add_content(req, tmp);
10976 } else {
10977
10978 snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=%u\r\n", digit, duration);
10979 add_header(req, "Content-Type", "application/dtmf-relay");
10980 add_content(req, tmp);
10981 }
10982 return 0;
10983 }
10984
10985
10986
10987
10988
10989 static int add_rpid(struct sip_request *req, struct sip_pvt *p)
10990 {
10991 struct ast_str *tmp = ast_str_alloca(256);
10992 char tmp2[256];
10993 char *lid_num = NULL;
10994 char *lid_name = NULL;
10995 int lid_pres;
10996 const char *fromdomain;
10997 const char *privacy = NULL;
10998 const char *screen = NULL;
10999 const char *anonymous_string = "\"Anonymous\" <sip:anonymous@anonymous.invalid>";
11000
11001 if (!ast_test_flag(&p->flags[0], SIP_SENDRPID)) {
11002 return 0;
11003 }
11004
11005 if (p->owner && p->owner->connected.id.number.valid
11006 && p->owner->connected.id.number.str) {
11007 lid_num = p->owner->connected.id.number.str;
11008 }
11009 if (p->owner && p->owner->connected.id.name.valid
11010 && p->owner->connected.id.name.str) {
11011 lid_name = p->owner->connected.id.name.str;
11012 }
11013 lid_pres = (p->owner) ? ast_party_id_presentation(&p->owner->connected.id) : AST_PRES_NUMBER_NOT_AVAILABLE;
11014
11015 if (ast_strlen_zero(lid_num))
11016 return 0;
11017 if (ast_strlen_zero(lid_name))
11018 lid_name = lid_num;
11019 fromdomain = S_OR(p->fromdomain, ast_sockaddr_stringify_host_remote(&p->ourip));
11020
11021 lid_num = ast_uri_encode(lid_num, tmp2, sizeof(tmp2), 0);
11022
11023 if (ast_test_flag(&p->flags[0], SIP_SENDRPID_PAI)) {
11024 if ((lid_pres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
11025 ast_str_set(&tmp, -1, "%s", anonymous_string);
11026 } else {
11027 ast_str_set(&tmp, -1, "\"%s\" <sip:%s@%s>", lid_name, lid_num, fromdomain);
11028 }
11029 add_header(req, "P-Asserted-Identity", ast_str_buffer(tmp));
11030 } else {
11031 ast_str_set(&tmp, -1, "\"%s\" <sip:%s@%s>;party=%s", lid_name, lid_num, fromdomain, p->outgoing_call ? "calling" : "called");
11032
11033 switch (lid_pres) {
11034 case AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED:
11035 case AST_PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN:
11036 privacy = "off";
11037 screen = "no";
11038 break;
11039 case AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN:
11040 case AST_PRES_ALLOWED_NETWORK_NUMBER:
11041 privacy = "off";
11042 screen = "yes";
11043 break;
11044 case AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED:
11045 case AST_PRES_PROHIB_USER_NUMBER_FAILED_SCREEN:
11046 privacy = "full";
11047 screen = "no";
11048 break;
11049 case AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN:
11050 case AST_PRES_PROHIB_NETWORK_NUMBER:
11051 privacy = "full";
11052 screen = "yes";
11053 break;
11054 case AST_PRES_NUMBER_NOT_AVAILABLE:
11055 break;
11056 default:
11057 if ((lid_pres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
11058 privacy = "full";
11059 }
11060 else
11061 privacy = "off";
11062 screen = "no";
11063 break;
11064 }
11065
11066 if (!ast_strlen_zero(privacy) && !ast_strlen_zero(screen)) {
11067 ast_str_append(&tmp, -1, ";privacy=%s;screen=%s", privacy, screen);
11068 }
11069
11070 add_header(req, "Remote-Party-ID", ast_str_buffer(tmp));
11071 }
11072 return 0;
11073 }
11074
11075
11076
11077 static int add_vidupdate(struct sip_request *req)
11078 {
11079 const char *xml_is_a_huge_waste_of_space =
11080 "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
11081 " <media_control>\r\n"
11082 " <vc_primitive>\r\n"
11083 " <to_encoder>\r\n"
11084 " <picture_fast_update>\r\n"
11085 " </picture_fast_update>\r\n"
11086 " </to_encoder>\r\n"
11087 " </vc_primitive>\r\n"
11088 " </media_control>\r\n";
11089 add_header(req, "Content-Type", "application/media_control+xml");
11090 add_content(req, xml_is_a_huge_waste_of_space);
11091 return 0;
11092 }
11093
11094
11095 static void add_codec_to_sdp(const struct sip_pvt *p, format_t codec,
11096 struct ast_str **m_buf, struct ast_str **a_buf,
11097 int debug, int *min_packet_size)
11098 {
11099 int rtp_code;
11100 struct ast_format_list fmt;
11101
11102
11103 if (debug)
11104 ast_verbose("Adding codec 0x%" PRIx64 " (%s) to SDP\n", codec, ast_getformatname(codec));
11105 if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->rtp), 1, codec)) == -1)
11106 return;
11107
11108 if (p->rtp) {
11109 struct ast_codec_pref *pref = &ast_rtp_instance_get_codecs(p->rtp)->pref;
11110 fmt = ast_codec_pref_getsize(pref, codec);
11111 } else
11112 return;
11113 ast_str_append(m_buf, 0, " %d", rtp_code);
11114 ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
11115 ast_rtp_lookup_mime_subtype2(1, codec,
11116 ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0),
11117 ast_rtp_lookup_sample_rate2(1, codec));
11118
11119 switch (codec) {
11120 case AST_FORMAT_G729A:
11121
11122 ast_str_append(a_buf, 0, "a=fmtp:%d annexb=no\r\n", rtp_code);
11123 break;
11124 case AST_FORMAT_G723_1:
11125
11126 ast_str_append(a_buf, 0, "a=fmtp:%d annexa=no\r\n", rtp_code);
11127 break;
11128 case AST_FORMAT_ILBC:
11129
11130 ast_str_append(a_buf, 0, "a=fmtp:%d mode=%d\r\n", rtp_code, fmt.cur_ms);
11131 break;
11132 case AST_FORMAT_SIREN7:
11133
11134 ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=32000\r\n", rtp_code);
11135 break;
11136 case AST_FORMAT_SIREN14:
11137
11138 ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=48000\r\n", rtp_code);
11139 break;
11140 case AST_FORMAT_G719:
11141
11142 ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=64000\r\n", rtp_code);
11143 break;
11144 }
11145
11146 if (fmt.cur_ms && (fmt.cur_ms < *min_packet_size))
11147 *min_packet_size = fmt.cur_ms;
11148
11149
11150 if ((*min_packet_size)==0 && fmt.cur_ms)
11151 *min_packet_size = fmt.cur_ms;
11152 }
11153
11154
11155
11156 static void add_vcodec_to_sdp(const struct sip_pvt *p, format_t codec,
11157 struct ast_str **m_buf, struct ast_str **a_buf,
11158 int debug, int *min_packet_size)
11159 {
11160 int rtp_code;
11161
11162 if (!p->vrtp)
11163 return;
11164
11165 if (debug)
11166 ast_verbose("Adding video codec 0x%" PRIx64 " (%s) to SDP\n", codec, ast_getformatname(codec));
11167
11168 if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->vrtp), 1, codec)) == -1)
11169 return;
11170
11171 ast_str_append(m_buf, 0, " %d", rtp_code);
11172 ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
11173 ast_rtp_lookup_mime_subtype2(1, codec, 0),
11174 ast_rtp_lookup_sample_rate2(1, codec));
11175
11176 }
11177
11178
11179 static void add_tcodec_to_sdp(const struct sip_pvt *p, int codec,
11180 struct ast_str **m_buf, struct ast_str **a_buf,
11181 int debug, int *min_packet_size)
11182 {
11183 int rtp_code;
11184
11185 if (!p->trtp)
11186 return;
11187
11188 if (debug)
11189 ast_verbose("Adding text codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
11190
11191 if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->trtp), 1, codec)) == -1)
11192 return;
11193
11194 ast_str_append(m_buf, 0, " %d", rtp_code);
11195 ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
11196 ast_rtp_lookup_mime_subtype2(1, codec, 0),
11197 ast_rtp_lookup_sample_rate2(1, codec));
11198
11199
11200 if (codec == AST_FORMAT_T140RED) {
11201 int t140code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->trtp), 1, AST_FORMAT_T140);
11202 ast_str_append(a_buf, 0, "a=fmtp:%d %d/%d/%d\r\n", rtp_code,
11203 t140code,
11204 t140code,
11205 t140code);
11206
11207 }
11208 }
11209
11210
11211
11212 static unsigned int t38_get_rate(enum ast_control_t38_rate rate)
11213 {
11214 switch (rate) {
11215 case AST_T38_RATE_2400:
11216 return 2400;
11217 case AST_T38_RATE_4800:
11218 return 4800;
11219 case AST_T38_RATE_7200:
11220 return 7200;
11221 case AST_T38_RATE_9600:
11222 return 9600;
11223 case AST_T38_RATE_12000:
11224 return 12000;
11225 case AST_T38_RATE_14400:
11226 return 14400;
11227 default:
11228 return 0;
11229 }
11230 }
11231
11232
11233 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
11234 struct ast_str **m_buf, struct ast_str **a_buf,
11235 int debug)
11236 {
11237 int rtp_code;
11238
11239 if (debug)
11240 ast_verbose("Adding non-codec 0x%x (%s) to SDP\n", format, ast_rtp_lookup_mime_subtype2(0, format, 0));
11241 if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->rtp), 0, format)) == -1)
11242 return;
11243
11244 ast_str_append(m_buf, 0, " %d", rtp_code);
11245 ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
11246 ast_rtp_lookup_mime_subtype2(0, format, 0),
11247 ast_rtp_lookup_sample_rate2(0, format));
11248 if (format == AST_RTP_DTMF)
11249 ast_str_append(a_buf, 0, "a=fmtp:%d 0-16\r\n", rtp_code);
11250 }
11251
11252
11253
11254
11255 static void get_our_media_address(struct sip_pvt *p, int needvideo, int needtext,
11256 struct ast_sockaddr *addr, struct ast_sockaddr *vaddr,
11257 struct ast_sockaddr *taddr, struct ast_sockaddr *dest,
11258 struct ast_sockaddr *vdest, struct ast_sockaddr *tdest)
11259 {
11260 int use_externip = 0;
11261
11262
11263 ast_rtp_instance_get_local_address(p->rtp, addr);
11264 if (p->vrtp) {
11265 ast_rtp_instance_get_local_address(p->vrtp, vaddr);
11266 }
11267 if (p->trtp) {
11268 ast_rtp_instance_get_local_address(p->trtp, taddr);
11269 }
11270
11271
11272
11273
11274 use_externip = ast_sockaddr_cmp_addr(&p->ourip, addr);
11275
11276
11277
11278 if (!ast_sockaddr_isnull(&p->redirip)) {
11279 ast_sockaddr_copy(dest, &p->redirip);
11280 } else {
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292 ast_sockaddr_copy(dest,
11293 !ast_sockaddr_isnull(&media_address) ? &media_address :
11294 !ast_sockaddr_is_any(addr) && !use_externip ? addr :
11295 &p->ourip);
11296 ast_sockaddr_set_port(dest, ast_sockaddr_port(addr));
11297 }
11298
11299 if (needvideo) {
11300
11301 if (!ast_sockaddr_isnull(&p->vredirip)) {
11302 ast_sockaddr_copy(vdest, &p->vredirip);
11303 } else {
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315 ast_sockaddr_copy(vdest,
11316 !ast_sockaddr_isnull(&media_address) ? &media_address :
11317 !ast_sockaddr_is_any(vaddr) && !use_externip ? vaddr :
11318 &p->ourip);
11319 ast_sockaddr_set_port(vdest, ast_sockaddr_port(vaddr));
11320 }
11321 }
11322
11323 if (needtext) {
11324
11325 if (!ast_sockaddr_isnull(&p->tredirip)) {
11326 ast_sockaddr_copy(tdest, &p->tredirip);
11327 } else {
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339 ast_sockaddr_copy(tdest,
11340 !ast_sockaddr_isnull(&media_address) ? &media_address :
11341 !ast_sockaddr_is_any(taddr) && !use_externip ? taddr :
11342 &p->ourip);
11343 ast_sockaddr_set_port(tdest, ast_sockaddr_port(taddr));
11344 }
11345 }
11346 }
11347
11348 static void get_crypto_attrib(struct sip_srtp *srtp, const char **a_crypto)
11349 {
11350
11351 if (srtp) {
11352 if (!srtp->crypto) {
11353 srtp->crypto = sdp_crypto_setup();
11354 }
11355 if (srtp->crypto && (sdp_crypto_offer(srtp->crypto) >= 0)) {
11356 *a_crypto = sdp_crypto_attrib(srtp->crypto);
11357 }
11358
11359 if (!*a_crypto) {
11360 ast_log(LOG_WARNING, "No SRTP key management enabled\n");
11361 }
11362 }
11363 }
11364
11365
11366
11367
11368
11369
11370
11371 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38)
11372 {
11373 format_t alreadysent = 0;
11374 int doing_directmedia = FALSE;
11375
11376 struct ast_sockaddr addr = { {0,} };
11377 struct ast_sockaddr vaddr = { {0,} };
11378 struct ast_sockaddr taddr = { {0,} };
11379 struct ast_sockaddr udptladdr = { {0,} };
11380 struct ast_sockaddr dest = { {0,} };
11381 struct ast_sockaddr vdest = { {0,} };
11382 struct ast_sockaddr tdest = { {0,} };
11383 struct ast_sockaddr udptldest = { {0,} };
11384
11385
11386 char *version = "v=0\r\n";
11387 char subject[256];
11388 char owner[256];
11389 char connection[256];
11390 char *session_time = "t=0 0\r\n";
11391 char bandwidth[256] = "";
11392 char *hold = "";
11393 struct ast_str *m_audio = ast_str_alloca(256);
11394 struct ast_str *m_video = ast_str_alloca(256);
11395 struct ast_str *m_text = ast_str_alloca(256);
11396 struct ast_str *m_modem = ast_str_alloca(256);
11397 struct ast_str *a_audio = ast_str_alloca(1024);
11398 struct ast_str *a_video = ast_str_alloca(1024);
11399 struct ast_str *a_text = ast_str_alloca(1024);
11400 struct ast_str *a_modem = ast_str_alloca(1024);
11401 const char *a_crypto = NULL;
11402 const char *v_a_crypto = NULL;
11403 const char *t_a_crypto = NULL;
11404
11405 format_t x;
11406 format_t capability = 0;
11407 int needaudio = FALSE;
11408 int needvideo = FALSE;
11409 int needtext = FALSE;
11410 int debug = sip_debug_test_pvt(p);
11411 int min_audio_packet_size = 0;
11412 int min_video_packet_size = 0;
11413 int min_text_packet_size = 0;
11414
11415 char codecbuf[SIPBUFSIZE];
11416 char buf[SIPBUFSIZE];
11417 char dummy_answer[256];
11418
11419
11420 snprintf(subject, sizeof(subject), "s=%s\r\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
11421
11422 if (!p->rtp) {
11423 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
11424 return AST_FAILURE;
11425 }
11426
11427
11428
11429
11430 if (!p->sessionid) {
11431 p->sessionid = (int)ast_random();
11432 p->sessionversion = p->sessionid;
11433 } else {
11434 if (oldsdp == FALSE)
11435 p->sessionversion++;
11436 }
11437
11438 if (add_audio) {
11439 doing_directmedia = (!ast_sockaddr_isnull(&p->redirip) && p->redircodecs) ? TRUE : FALSE;
11440
11441 if ((p->jointcapability & AST_FORMAT_VIDEO_MASK) && !p->novideo) {
11442 if (doing_directmedia && !(p->jointcapability & AST_FORMAT_VIDEO_MASK & p->redircodecs)) {
11443 ast_debug(2, "This call needs video offers, but caller probably did not offer it!\n");
11444 } else if (p->vrtp) {
11445 needvideo = TRUE;
11446 ast_debug(2, "This call needs video offers!\n");
11447 } else {
11448 ast_debug(2, "This call needs video offers, but there's no video support enabled!\n");
11449 }
11450 }
11451
11452 if ((p->jointcapability & AST_FORMAT_TEXT_MASK) && !p->notext) {
11453 if (sipdebug_text)
11454 ast_verbose("We think we can do text\n");
11455 if (p->trtp) {
11456 if (sipdebug_text) {
11457 ast_verbose("And we have a text rtp object\n");
11458 }
11459 needtext = TRUE;
11460 ast_debug(2, "This call needs text offers! \n");
11461 } else {
11462 ast_debug(2, "This call needs text offers, but there's no text support enabled ! \n");
11463 }
11464 }
11465 }
11466
11467 get_our_media_address(p, needvideo, needtext, &addr, &vaddr, &taddr, &dest, &vdest, &tdest);
11468
11469 snprintf(owner, sizeof(owner), "o=%s %d %d IN %s %s\r\n",
11470 ast_strlen_zero(global_sdpowner) ? "-" : global_sdpowner,
11471 p->sessionid, p->sessionversion,
11472 (ast_sockaddr_is_ipv6(&dest) && !ast_sockaddr_is_ipv4_mapped(&dest)) ?
11473 "IP6" : "IP4",
11474 ast_sockaddr_stringify_addr_remote(&dest));
11475
11476 snprintf(connection, sizeof(connection), "c=IN %s %s\r\n",
11477 (ast_sockaddr_is_ipv6(&dest) && !ast_sockaddr_is_ipv4_mapped(&dest)) ?
11478 "IP6" : "IP4",
11479 ast_sockaddr_stringify_addr_remote(&dest));
11480
11481 if (add_audio) {
11482 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_ONEDIR) {
11483 hold = "a=recvonly\r\n";
11484 doing_directmedia = FALSE;
11485 } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_INACTIVE) {
11486 hold = "a=inactive\r\n";
11487 doing_directmedia = FALSE;
11488 } else {
11489 hold = "a=sendrecv\r\n";
11490 }
11491
11492 capability = p->jointcapability;
11493
11494
11495 ast_debug(1, "** Our capability: %s Video flag: %s Text flag: %s\n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), capability),
11496 p->novideo ? "True" : "False", p->notext ? "True" : "False");
11497 ast_debug(1, "** Our prefcodec: %s \n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), p->prefcodec));
11498
11499 if (doing_directmedia) {
11500 capability &= p->redircodecs;
11501 ast_debug(1, "** Our native-bridge filtered capablity: %s\n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), capability));
11502 }
11503
11504
11505 if (capability & AST_FORMAT_AUDIO_MASK)
11506 needaudio = TRUE;
11507
11508 if (debug) {
11509 ast_verbose("Audio is at %s\n", ast_sockaddr_stringify_port(&addr));
11510 }
11511
11512
11513
11514 if (needvideo) {
11515 get_crypto_attrib(p->vsrtp, &v_a_crypto);
11516 ast_str_append(&m_video, 0, "m=video %d RTP/%s", ast_sockaddr_port(&vdest),
11517 v_a_crypto ? "SAVP" : "AVP");
11518
11519
11520 if (p->maxcallbitrate)
11521 snprintf(bandwidth, sizeof(bandwidth), "b=CT:%d\r\n", p->maxcallbitrate);
11522 if (debug) {
11523 ast_verbose("Video is at %s\n", ast_sockaddr_stringify(&vdest));
11524 }
11525 }
11526
11527
11528
11529 if (needtext) {
11530 if (sipdebug_text)
11531 ast_verbose("Lets set up the text sdp\n");
11532 get_crypto_attrib(p->tsrtp, &t_a_crypto);
11533 ast_str_append(&m_text, 0, "m=text %d RTP/%s", ast_sockaddr_port(&tdest),
11534 t_a_crypto ? "SAVP" : "AVP");
11535 if (debug) {
11536 ast_verbose("Text is at %s\n", ast_sockaddr_stringify(&taddr));
11537 }
11538 }
11539
11540
11541
11542
11543
11544
11545 get_crypto_attrib(p->srtp, &a_crypto);
11546 ast_str_append(&m_audio, 0, "m=audio %d RTP/%s", ast_sockaddr_port(&dest),
11547 a_crypto ? "SAVP" : "AVP");
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558 if (capability & p->prefcodec) {
11559 format_t codec = p->prefcodec & AST_FORMAT_AUDIO_MASK;
11560
11561 add_codec_to_sdp(p, codec, &m_audio, &a_audio, debug, &min_audio_packet_size);
11562 alreadysent |= codec;
11563 }
11564
11565
11566 for (x = 0; x < 64; x++) {
11567 format_t codec;
11568
11569 if (!(codec = ast_codec_pref_index(&p->prefs, x)))
11570 break;
11571
11572 if (!(capability & codec))
11573 continue;
11574
11575 if (alreadysent & codec)
11576 continue;
11577
11578 add_codec_to_sdp(p, codec, &m_audio, &a_audio, debug, &min_audio_packet_size);
11579 alreadysent |= codec;
11580 }
11581
11582
11583 for (x = 1ULL; x <= (needtext ? AST_FORMAT_TEXT_MASK : (needvideo ? AST_FORMAT_VIDEO_MASK : AST_FORMAT_AUDIO_MASK)); x <<= 1) {
11584 if (!(capability & x))
11585 continue;
11586
11587 if (alreadysent & x)
11588 continue;
11589
11590 if (x & AST_FORMAT_AUDIO_MASK)
11591 add_codec_to_sdp(p, x, &m_audio, &a_audio, debug, &min_audio_packet_size);
11592 else if (x & AST_FORMAT_VIDEO_MASK)
11593 add_vcodec_to_sdp(p, x, &m_video, &a_video, debug, &min_video_packet_size);
11594 else if (x & AST_FORMAT_TEXT_MASK)
11595 add_tcodec_to_sdp(p, x, &m_text, &a_text, debug, &min_text_packet_size);
11596 }
11597
11598
11599 for (x = 1LL; x <= AST_RTP_MAX; x <<= 1) {
11600 if (!(p->jointnoncodeccapability & x))
11601 continue;
11602
11603 add_noncodec_to_sdp(p, x, &m_audio, &a_audio, debug);
11604 }
11605
11606 ast_debug(3, "-- Done with adding codecs to SDP\n");
11607
11608 if (!p->owner || !ast_internal_timing_enabled(p->owner))
11609 ast_str_append(&a_audio, 0, "a=silenceSupp:off - - - -\r\n");
11610
11611 if (min_audio_packet_size)
11612 ast_str_append(&a_audio, 0, "a=ptime:%d\r\n", min_audio_packet_size);
11613
11614
11615 if (min_video_packet_size)
11616 ast_str_append(&a_video, 0, "a=ptime:%d\r\n", min_video_packet_size);
11617
11618
11619 if (min_text_packet_size)
11620 ast_str_append(&a_text, 0, "a=ptime:%d\r\n", min_text_packet_size);
11621
11622 if (m_audio->len - m_audio->used < 2 || m_video->len - m_video->used < 2 ||
11623 m_text->len - m_text->used < 2 || a_text->len - a_text->used < 2 ||
11624 a_audio->len - a_audio->used < 2 || a_video->len - a_video->used < 2)
11625 ast_log(LOG_WARNING, "SIP SDP may be truncated due to undersized buffer!!\n");
11626 }
11627
11628 if (add_t38) {
11629
11630 ast_udptl_get_us(p->udptl, &udptladdr);
11631
11632
11633 if (!ast_sockaddr_isnull(&p->udptlredirip)) {
11634 ast_sockaddr_copy(&udptldest, &p->udptlredirip);
11635 } else {
11636 ast_sockaddr_copy(&udptldest, &p->ourip);
11637 ast_sockaddr_set_port(&udptldest, ast_sockaddr_port(&udptladdr));
11638 }
11639
11640 if (debug) {
11641 ast_debug(1, "T.38 UDPTL is at %s port %d\n", ast_sockaddr_stringify_addr(&p->ourip), ast_sockaddr_port(&udptladdr));
11642 }
11643
11644
11645
11646
11647 ast_str_append(&m_modem, 0, "m=image %d udptl t38\r\n", ast_sockaddr_port(&udptldest));
11648
11649 if (!ast_sockaddr_cmp(&udptldest, &dest)) {
11650 ast_str_append(&m_modem, 0, "c=IN %s %s\r\n",
11651 (ast_sockaddr_is_ipv6(&dest) && !ast_sockaddr_is_ipv4_mapped(&dest)) ?
11652 "IP6" : "IP4", ast_sockaddr_stringify_addr_remote(&udptldest));
11653 }
11654
11655 ast_str_append(&a_modem, 0, "a=T38FaxVersion:%d\r\n", p->t38.our_parms.version);
11656 ast_str_append(&a_modem, 0, "a=T38MaxBitRate:%d\r\n", t38_get_rate(p->t38.our_parms.rate));
11657 if (p->t38.our_parms.fill_bit_removal) {
11658 ast_str_append(&a_modem, 0, "a=T38FaxFillBitRemoval\r\n");
11659 }
11660 if (p->t38.our_parms.transcoding_mmr) {
11661 ast_str_append(&a_modem, 0, "a=T38FaxTranscodingMMR\r\n");
11662 }
11663 if (p->t38.our_parms.transcoding_jbig) {
11664 ast_str_append(&a_modem, 0, "a=T38FaxTranscodingJBIG\r\n");
11665 }
11666 switch (p->t38.our_parms.rate_management) {
11667 case AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF:
11668 ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:transferredTCF\r\n");
11669 break;
11670 case AST_T38_RATE_MANAGEMENT_LOCAL_TCF:
11671 ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:localTCF\r\n");
11672 break;
11673 }
11674 ast_str_append(&a_modem, 0, "a=T38FaxMaxDatagram:%u\r\n", ast_udptl_get_local_max_datagram(p->udptl));
11675 switch (ast_udptl_get_error_correction_scheme(p->udptl)) {
11676 case UDPTL_ERROR_CORRECTION_NONE:
11677 break;
11678 case UDPTL_ERROR_CORRECTION_FEC:
11679 ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPFEC\r\n");
11680 break;
11681 case UDPTL_ERROR_CORRECTION_REDUNDANCY:
11682 ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPRedundancy\r\n");
11683 break;
11684 }
11685 }
11686
11687 if (needaudio)
11688 ast_str_append(&m_audio, 0, "\r\n");
11689 if (needvideo)
11690 ast_str_append(&m_video, 0, "\r\n");
11691 if (needtext)
11692 ast_str_append(&m_text, 0, "\r\n");
11693
11694 add_header(resp, "Content-Type", "application/sdp");
11695 add_content(resp, version);
11696 add_content(resp, owner);
11697 add_content(resp, subject);
11698 add_content(resp, connection);
11699
11700 if (needvideo) {
11701 add_content(resp, bandwidth);
11702 }
11703 add_content(resp, session_time);
11704
11705 if (p->offered_media[SDP_AUDIO].order_offered ||
11706 p->offered_media[SDP_VIDEO].order_offered ||
11707 p->offered_media[SDP_TEXT].order_offered ||
11708 p->offered_media[SDP_IMAGE].order_offered) {
11709 int i;
11710
11711 for (i = 1; i <= 3; i++) {
11712 if (p->offered_media[SDP_AUDIO].order_offered == i) {
11713 if (needaudio) {
11714 add_content(resp, m_audio->str);
11715 add_content(resp, a_audio->str);
11716 add_content(resp, hold);
11717 if (a_crypto) {
11718 add_content(resp, a_crypto);
11719 }
11720 } else {
11721 snprintf(dummy_answer, sizeof(dummy_answer), "m=audio 0 RTP/AVP %s\r\n", p->offered_media[SDP_AUDIO].codecs);
11722 add_content(resp, dummy_answer);
11723 }
11724 } else if (p->offered_media[SDP_VIDEO].order_offered == i) {
11725 if (needvideo) {
11726 add_content(resp, m_video->str);
11727 add_content(resp, a_video->str);
11728 add_content(resp, hold);
11729 if (v_a_crypto) {
11730 add_content(resp, v_a_crypto);
11731 }
11732 } else {
11733 snprintf(dummy_answer, sizeof(dummy_answer), "m=video 0 RTP/AVP %s\r\n", p->offered_media[SDP_VIDEO].codecs);
11734 add_content(resp, dummy_answer);
11735 }
11736 } else if (p->offered_media[SDP_TEXT].order_offered == i) {
11737 if (needtext) {
11738 add_content(resp, m_text->str);
11739 add_content(resp, a_text->str);
11740 add_content(resp, hold);
11741 if (t_a_crypto) {
11742 add_content(resp, t_a_crypto);
11743 }
11744 } else {
11745 snprintf(dummy_answer, sizeof(dummy_answer), "m=text 0 RTP/AVP %s\r\n", p->offered_media[SDP_TEXT].codecs);
11746 add_content(resp, dummy_answer);
11747 }
11748 } else if (p->offered_media[SDP_IMAGE].order_offered == i) {
11749 if (add_t38) {
11750 add_content(resp, m_modem->str);
11751 add_content(resp, a_modem->str);
11752 } else {
11753 add_content(resp, "m=image 0 udptl t38\r\n");
11754 }
11755 }
11756 }
11757 } else {
11758
11759 if (needaudio) {
11760 add_content(resp, m_audio->str);
11761 add_content(resp, a_audio->str);
11762 add_content(resp, hold);
11763 if (a_crypto) {
11764 add_content(resp, a_crypto);
11765 }
11766 }
11767 if (needvideo) {
11768 add_content(resp, m_video->str);
11769 add_content(resp, a_video->str);
11770 add_content(resp, hold);
11771 if (v_a_crypto) {
11772 add_content(resp, v_a_crypto);
11773 }
11774 }
11775 if (needtext) {
11776 add_content(resp, m_text->str);
11777 add_content(resp, a_text->str);
11778 add_content(resp, hold);
11779 if (t_a_crypto) {
11780 add_content(resp, t_a_crypto);
11781 }
11782 }
11783 if (add_t38) {
11784 add_content(resp, m_modem->str);
11785 add_content(resp, a_modem->str);
11786 }
11787 }
11788
11789
11790 p->lastrtprx = p->lastrtptx = time(NULL);
11791
11792 ast_debug(3, "Done building SDP. Settling with this capability: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, capability));
11793
11794 return AST_SUCCESS;
11795 }
11796
11797
11798 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
11799 {
11800 struct sip_request resp;
11801 uint32_t seqno;
11802
11803 if (sscanf(get_header(req, "CSeq"), "%30u ", &seqno) != 1) {
11804 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
11805 return -1;
11806 }
11807 respprep(&resp, p, msg, req);
11808 if (p->udptl) {
11809 add_sdp(&resp, p, 0, 0, 1);
11810 } else
11811 ast_log(LOG_ERROR, "Can't add SDP to response, since we have no UDPTL session allocated. Call-ID %s\n", p->callid);
11812 if (retrans && !p->pendinginvite)
11813 p->pendinginvite = seqno;
11814 return send_response(p, &resp, retrans, seqno);
11815 }
11816
11817
11818 static void copy_request(struct sip_request *dst, const struct sip_request *src)
11819 {
11820
11821
11822
11823 struct ast_str *duplicate = dst->data;
11824 struct ast_str *duplicate_content = dst->content;
11825
11826
11827
11828 *dst = *src;
11829 dst->data = duplicate;
11830 dst->content = duplicate_content;
11831
11832
11833 if (!dst->data && !(dst->data = ast_str_create(ast_str_strlen(src->data) + 1))) {
11834 return;
11835 }
11836 ast_str_copy_string(&dst->data, src->data);
11837
11838
11839 if (src->content) {
11840 if (!dst->content && !(dst->content = ast_str_create(ast_str_strlen(src->content) + 1))) {
11841 return;
11842 }
11843 ast_str_copy_string(&dst->content, src->content);
11844 }
11845 }
11846
11847 static void add_cc_call_info_to_response(struct sip_pvt *p, struct sip_request *resp)
11848 {
11849 char uri[SIPBUFSIZE];
11850 struct ast_str *header = ast_str_alloca(SIPBUFSIZE);
11851 struct ast_cc_agent *agent = find_sip_cc_agent_by_original_callid(p);
11852 struct sip_cc_agent_pvt *agent_pvt;
11853
11854 if (!agent) {
11855
11856
11857
11858 ast_log(LOG_WARNING, "Can't find SIP CC agent for call '%s' even though OFFER_CC flag was set?\n", p->callid);
11859 return;
11860 }
11861
11862 agent_pvt = agent->private_data;
11863
11864 if (!ast_strlen_zero(agent_pvt->subscribe_uri)) {
11865 ast_copy_string(uri, agent_pvt->subscribe_uri, sizeof(uri));
11866 } else {
11867 generate_uri(p, uri, sizeof(uri));
11868 ast_copy_string(agent_pvt->subscribe_uri, uri, sizeof(agent_pvt->subscribe_uri));
11869 }
11870
11871
11872
11873
11874 ast_str_set(&header, 0, "<%s>;purpose=call-completion;m=%s", uri, "NR");
11875 add_header(resp, "Call-Info", ast_str_buffer(header));
11876 ao2_ref(agent, -1);
11877 }
11878
11879
11880
11881
11882 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)
11883 {
11884 struct sip_request resp;
11885 uint32_t seqno;
11886 if (sscanf(get_header(req, "CSeq"), "%30u ", &seqno) != 1) {
11887 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
11888 return -1;
11889 }
11890 respprep(&resp, p, msg, req);
11891 if (rpid == TRUE) {
11892 add_rpid(&resp, p);
11893 }
11894 if (ast_test_flag(&p->flags[0], SIP_OFFER_CC)) {
11895 add_cc_call_info_to_response(p, &resp);
11896 }
11897 if (p->rtp) {
11898 if (!p->autoframing && !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
11899 ast_debug(1, "Setting framing from config on incoming call\n");
11900 ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(p->rtp), p->rtp, &p->prefs);
11901 }
11902 ast_rtp_instance_activate(p->rtp);
11903 try_suggested_sip_codec(p);
11904 if (p->t38.state == T38_ENABLED) {
11905 add_sdp(&resp, p, oldsdp, TRUE, TRUE);
11906 } else {
11907 add_sdp(&resp, p, oldsdp, TRUE, FALSE);
11908 }
11909 } else
11910 ast_log(LOG_ERROR, "Can't add SDP to response, since we have no RTP session allocated. Call-ID %s\n", p->callid);
11911 if (reliable && !p->pendinginvite)
11912 p->pendinginvite = seqno;
11913 return send_response(p, &resp, reliable, seqno);
11914 }
11915
11916
11917 static int determine_firstline_parts(struct sip_request *req)
11918 {
11919 char *e = ast_skip_blanks(req->data->str);
11920 char *local_rlPart1;
11921
11922 if (!*e)
11923 return -1;
11924 req->rlPart1 = e - req->data->str;
11925 local_rlPart1 = e;
11926 e = ast_skip_nonblanks(e);
11927 if (*e)
11928 *e++ = '\0';
11929
11930 e = ast_skip_blanks(e);
11931 if ( !*e )
11932 return -1;
11933 ast_trim_blanks(e);
11934
11935 if (!strcasecmp(local_rlPart1, "SIP/2.0") ) {
11936 if (strlen(e) < 3)
11937 return -1;
11938 req->rlPart2 = e - req->data->str;
11939 } else {
11940 if ( *e == '<' ) {
11941 ast_debug(3, "Oops. Bogus uri in <> %s\n", e);
11942 e++;
11943 if (!*e)
11944 return -1;
11945 }
11946 req->rlPart2 = e - req->data->str;
11947 e = ast_skip_nonblanks(e);
11948 if (*e)
11949 *e++ = '\0';
11950 e = ast_skip_blanks(e);
11951 if (strcasecmp(e, "SIP/2.0") ) {
11952 ast_debug(3, "Skipping packet - Bad request protocol %s\n", e);
11953 return -1;
11954 }
11955 }
11956 return 1;
11957 }
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp)
11973 {
11974 struct sip_request req;
11975
11976 reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ? SIP_UPDATE : SIP_INVITE, 0, 1);
11977
11978 add_header(&req, "Allow", ALLOWED_METHODS);
11979 add_supported_header(p, &req);
11980 if (sipdebug) {
11981 if (oldsdp == TRUE)
11982 add_header(&req, "X-asterisk-Info", "SIP re-invite (Session-Timers)");
11983 else
11984 add_header(&req, "X-asterisk-Info", "SIP re-invite (External RTP bridge)");
11985 }
11986
11987 if (ast_test_flag(&p->flags[0], SIP_SENDRPID))
11988 add_rpid(&req, p);
11989
11990 if (p->do_history) {
11991 append_history(p, "ReInv", "Re-invite sent");
11992 }
11993 memset(p->offered_media, 0, sizeof(p->offered_media));
11994
11995 try_suggested_sip_codec(p);
11996 if (t38version) {
11997 add_sdp(&req, p, oldsdp, FALSE, TRUE);
11998 } else {
11999 add_sdp(&req, p, oldsdp, TRUE, FALSE);
12000 }
12001
12002
12003 initialize_initreq(p, &req);
12004 p->lastinvite = p->ocseq;
12005 ast_set_flag(&p->flags[0], SIP_OUTGOING);
12006 p->ongoing_reinvite = 1;
12007 return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
12008 }
12009
12010
12011 static char *remove_uri_parameters(char *uri)
12012 {
12013 char *atsign;
12014 atsign = strchr(uri, '@');
12015 if (!atsign) {
12016 atsign = uri;
12017 }
12018 atsign = strchr(atsign, ';');
12019 if (atsign)
12020 *atsign = '\0';
12021 return uri;
12022 }
12023
12024
12025 static void extract_uri(struct sip_pvt *p, struct sip_request *req)
12026 {
12027 char stripped[SIPBUFSIZE];
12028 char *c;
12029
12030 ast_copy_string(stripped, get_header(req, "Contact"), sizeof(stripped));
12031 c = get_in_brackets(stripped);
12032
12033 c = remove_uri_parameters(c);
12034 if (!ast_strlen_zero(c)) {
12035 ast_string_field_set(p, uri, c);
12036 }
12037
12038 }
12039
12040
12041 static void build_contact(struct sip_pvt *p)
12042 {
12043 char tmp[SIPBUFSIZE];
12044 char *user = ast_uri_encode(p->exten, tmp, sizeof(tmp), 0);
12045
12046 if (p->socket.type == SIP_TRANSPORT_UDP) {
12047 ast_string_field_build(p, our_contact, "<sip:%s%s%s>", user,
12048 ast_strlen_zero(user) ? "" : "@", ast_sockaddr_stringify_remote(&p->ourip));
12049 } else {
12050 ast_string_field_build(p, our_contact, "<sip:%s%s%s;transport=%s>", user,
12051 ast_strlen_zero(user) ? "" : "@", ast_sockaddr_stringify_remote(&p->ourip),
12052 get_transport(p->socket.type));
12053 }
12054 }
12055
12056
12057 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, const char * const explicit_uri)
12058 {
12059 struct ast_str *invite = ast_str_alloca(256);
12060 char from[256];
12061 char to[256];
12062 char tmp_n[SIPBUFSIZE/2];
12063 char tmp_l[SIPBUFSIZE/2];
12064 const char *l = NULL;
12065 const char *n = NULL;
12066 const char *d = NULL;
12067 const char *urioptions = "";
12068 int ourport;
12069
12070 if (ast_test_flag(&p->flags[0], SIP_USEREQPHONE)) {
12071 const char *s = p->username;
12072
12073
12074
12075
12076
12077
12078 if (*s == '+')
12079 s++;
12080 for (; *s; s++) {
12081 if (!strchr(AST_DIGIT_ANYNUM, *s) )
12082 break;
12083 }
12084
12085 if (!*s)
12086 urioptions = ";user=phone";
12087 }
12088
12089
12090 snprintf(p->lastmsg, sizeof(p->lastmsg), "Init: %s", sip_methods[sipmethod].text);
12091
12092 d = S_OR(p->fromdomain, ast_sockaddr_stringify_host_remote(&p->ourip));
12093 if (p->owner) {
12094 if ((ast_party_id_presentation(&p->owner->connected.id) & AST_PRES_RESTRICTION) == AST_PRES_ALLOWED) {
12095 l = p->owner->connected.id.number.valid ? p->owner->connected.id.number.str : NULL;
12096 n = p->owner->connected.id.name.valid ? p->owner->connected.id.name.str : NULL;
12097 } else {
12098
12099
12100 l = "anonymous";
12101 n = CALLERID_UNKNOWN;
12102 d = FROMDOMAIN_INVALID;
12103 }
12104 }
12105
12106
12107
12108
12109
12110
12111
12112 if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->mwi_from)) {
12113 l = p->mwi_from;
12114 }
12115
12116 if (ast_strlen_zero(l))
12117 l = default_callerid;
12118 if (ast_strlen_zero(n))
12119 n = l;
12120
12121 if (!ast_strlen_zero(p->fromuser))
12122 l = p->fromuser;
12123 else
12124 ast_string_field_set(p, fromuser, l);
12125
12126
12127 if (!ast_strlen_zero(p->fromname))
12128 n = p->fromname;
12129 else
12130 ast_string_field_set(p, fromname, n);
12131
12132 ast_copy_string(tmp_l, l, sizeof(tmp_l));
12133 if (sip_cfg.pedanticsipchecking) {
12134 ast_escape_quoted(n, tmp_n, sizeof(tmp_n));
12135 n = tmp_n;
12136 ast_uri_encode(l, tmp_l, sizeof(tmp_l), 0);
12137 }
12138
12139 ourport = (p->fromdomainport) ? p->fromdomainport : ast_sockaddr_port(&p->ourip);
12140 if (!sip_standard_port(p->socket.type, ourport)) {
12141 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s:%d>;tag=%s", n, tmp_l, d, ourport, p->tag);
12142 } else {
12143 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=%s", n, tmp_l, d, p->tag);
12144 }
12145
12146 if (!ast_strlen_zero(explicit_uri)) {
12147 ast_str_set(&invite, 0, "%s", explicit_uri);
12148 } else {
12149
12150 if (!ast_strlen_zero(p->fullcontact)) {
12151
12152 ast_str_append(&invite, 0, "%s", p->fullcontact);
12153 } else {
12154
12155 ast_str_append(&invite, 0, "sip:");
12156 if (!ast_strlen_zero(p->username)) {
12157 n = p->username;
12158 if (sip_cfg.pedanticsipchecking) {
12159 ast_uri_encode(n, tmp_n, sizeof(tmp_n), 0);
12160 n = tmp_n;
12161 }
12162 ast_str_append(&invite, 0, "%s@", n);
12163 }
12164 ast_str_append(&invite, 0, "%s", p->tohost);
12165 if (p->portinuri) {
12166 ast_str_append(&invite, 0, ":%d", ast_sockaddr_port(&p->sa));
12167 }
12168 ast_str_append(&invite, 0, "%s", urioptions);
12169 }
12170 }
12171
12172
12173 if (p->options && !ast_strlen_zero(p->options->uri_options))
12174 ast_str_append(&invite, 0, ";%s", p->options->uri_options);
12175
12176
12177
12178
12179 ast_string_field_set(p, uri, invite->str);
12180
12181 if (!ast_strlen_zero(p->todnid)) {
12182
12183 if (!strchr(p->todnid, '@')) {
12184
12185 snprintf(to, sizeof(to), "<sip:%s@%s>%s%s", p->todnid, p->tohost, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
12186 } else {
12187 snprintf(to, sizeof(to), "<sip:%s>%s%s", p->todnid, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
12188 }
12189 } else {
12190 if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->theirtag)) {
12191
12192 snprintf(to, sizeof(to), "<%s%s>;tag=%s", (strncasecmp(p->uri, "sip:", 4) ? "sip:" : ""), p->uri, p->theirtag);
12193 } else if (p->options && p->options->vxml_url) {
12194
12195 snprintf(to, sizeof(to), "<%s>;%s", p->uri, p->options->vxml_url);
12196 } else {
12197 snprintf(to, sizeof(to), "<%s>", p->uri);
12198 }
12199 }
12200
12201 init_req(req, sipmethod, p->uri);
12202
12203 snprintf(tmp_n, sizeof(tmp_n), "%u %s", ++p->ocseq, sip_methods[sipmethod].text);
12204
12205 add_header(req, "Via", p->via);
12206 add_header_max_forwards(p, req);
12207
12208
12209
12210
12211 add_route(req, p->route);
12212
12213 add_header(req, "From", from);
12214 add_header(req, "To", to);
12215 ast_string_field_set(p, exten, l);
12216 build_contact(p);
12217 add_header(req, "Contact", p->our_contact);
12218 add_header(req, "Call-ID", p->callid);
12219 add_header(req, "CSeq", tmp_n);
12220 if (!ast_strlen_zero(global_useragent)) {
12221 add_header(req, "User-Agent", global_useragent);
12222 }
12223 }
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233 static void add_diversion_header(struct sip_request *req, struct sip_pvt *pvt)
12234 {
12235 const char *diverting_number;
12236 const char *diverting_name;
12237 const char *reason;
12238 char header_text[256];
12239
12240 if (!pvt->owner) {
12241 return;
12242 }
12243
12244 diverting_number = pvt->owner->redirecting.from.number.str;
12245 if (!pvt->owner->redirecting.from.number.valid
12246 || ast_strlen_zero(diverting_number)) {
12247 return;
12248 }
12249
12250 reason = sip_reason_code_to_str(pvt->owner->redirecting.reason);
12251
12252
12253 diverting_name = pvt->owner->redirecting.from.name.str;
12254 if (!pvt->owner->redirecting.from.name.valid
12255 || ast_strlen_zero(diverting_name)) {
12256 snprintf(header_text, sizeof(header_text), "<sip:%s@%s>;reason=%s", diverting_number,
12257 ast_sockaddr_stringify_host_remote(&pvt->ourip), reason);
12258 } else {
12259 snprintf(header_text, sizeof(header_text), "\"%s\" <sip:%s@%s>;reason=%s",
12260 diverting_name, diverting_number,
12261 ast_sockaddr_stringify_host_remote(&pvt->ourip), reason);
12262 }
12263
12264 add_header(req, "Diversion", header_text);
12265 }
12266
12267 static int transmit_publish(struct sip_epa_entry *epa_entry, enum sip_publish_type publish_type, const char * const explicit_uri)
12268 {
12269 struct sip_pvt *pvt;
12270 int expires;
12271
12272 epa_entry->publish_type = publish_type;
12273
12274 if (!(pvt = sip_alloc(NULL, NULL, 0, SIP_PUBLISH, NULL))) {
12275 return -1;
12276 }
12277
12278 sip_pvt_lock(pvt);
12279
12280 if (create_addr(pvt, epa_entry->destination, NULL, TRUE)) {
12281 sip_pvt_unlock(pvt);
12282 dialog_unlink_all(pvt);
12283 dialog_unref(pvt, "create_addr failed in transmit_publish. Unref dialog");
12284 return -1;
12285 }
12286 ast_sip_ouraddrfor(&pvt->sa, &pvt->ourip, pvt);
12287 ast_set_flag(&pvt->flags[0], SIP_OUTGOING);
12288 expires = (publish_type == SIP_PUBLISH_REMOVE) ? 0 : DEFAULT_PUBLISH_EXPIRES;
12289 pvt->expiry = expires;
12290
12291
12292 ao2_ref(epa_entry, +1);
12293 pvt->epa_entry = epa_entry;
12294
12295 transmit_invite(pvt, SIP_PUBLISH, FALSE, 2, explicit_uri);
12296 sip_pvt_unlock(pvt);
12297 sip_scheddestroy(pvt, DEFAULT_TRANS_TIMEOUT);
12298 dialog_unref(pvt, "Done with the sip_pvt allocated for transmitting PUBLISH");
12299 return 0;
12300 }
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init, const char * const explicit_uri)
12312 {
12313 struct sip_request req;
12314 struct ast_variable *var;
12315
12316 if (init) {
12317 p->branch ^= ast_random();
12318 p->invite_branch = p->branch;
12319 build_via(p);
12320 }
12321 if (init > 1) {
12322 initreqprep(&req, p, sipmethod, explicit_uri);
12323 } else {
12324
12325 reqprep(&req, p, sipmethod, 0, init ? 0 : 1);
12326 }
12327
12328 if (p->options && p->options->auth) {
12329 add_header(&req, p->options->authheader, p->options->auth);
12330 }
12331 append_date(&req);
12332 if (sipmethod == SIP_REFER) {
12333 if (p->refer) {
12334 char buf[SIPBUFSIZE];
12335 if (!ast_strlen_zero(p->refer->refer_to)) {
12336 add_header(&req, "Refer-To", p->refer->refer_to);
12337 }
12338 if (!ast_strlen_zero(p->refer->referred_by)) {
12339 snprintf(buf, sizeof(buf), "%s <%s>", p->refer->referred_by_name, p->refer->referred_by);
12340 add_header(&req, "Referred-By", buf);
12341 }
12342 }
12343 } else if (sipmethod == SIP_SUBSCRIBE) {
12344 char buf[SIPBUFSIZE];
12345 if (p->subscribed == MWI_NOTIFICATION) {
12346 add_header(&req, "Event", "message-summary");
12347 add_header(&req, "Accept", "application/simple-message-summary");
12348 } else if (p->subscribed == CALL_COMPLETION) {
12349 add_header(&req, "Event", "call-completion");
12350 add_header(&req, "Accept", "application/call-completion");
12351 }
12352 snprintf(buf, sizeof(buf), "%d", p->expiry);
12353 add_header(&req, "Expires", buf);
12354 }
12355
12356
12357
12358 if (p->options && !ast_strlen_zero(p->options->replaces)) {
12359 add_header(&req, "Replaces", p->options->replaces);
12360 add_header(&req, "Require", "replaces");
12361 }
12362
12363
12364 if (st_get_mode(p, 0) == SESSION_TIMER_MODE_ORIGINATE) {
12365 char i2astr[10];
12366
12367 if (!p->stimer->st_interval) {
12368 p->stimer->st_interval = st_get_se(p, TRUE);
12369 }
12370
12371 p->stimer->st_active = TRUE;
12372
12373 snprintf(i2astr, sizeof(i2astr), "%d", p->stimer->st_interval);
12374 add_header(&req, "Session-Expires", i2astr);
12375 snprintf(i2astr, sizeof(i2astr), "%d", st_get_se(p, FALSE));
12376 add_header(&req, "Min-SE", i2astr);
12377 }
12378
12379 add_header(&req, "Allow", ALLOWED_METHODS);
12380 add_supported_header(p, &req);
12381
12382 if (p->options && p->options->addsipheaders && p->owner) {
12383 struct ast_channel *chan = p->owner;
12384 struct varshead *headp;
12385
12386 ast_channel_lock(chan);
12387
12388 headp = &chan->varshead;
12389
12390 if (!headp) {
12391 ast_log(LOG_WARNING, "No Headp for the channel...ooops!\n");
12392 } else {
12393 const struct ast_var_t *current;
12394 AST_LIST_TRAVERSE(headp, current, entries) {
12395
12396 if (!strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
12397 char *content, *end;
12398 const char *header = ast_var_value(current);
12399 char *headdup = ast_strdupa(header);
12400
12401
12402 if (*headdup == '"') {
12403 headdup++;
12404 }
12405 if ((content = strchr(headdup, ':'))) {
12406 *content++ = '\0';
12407 content = ast_skip_blanks(content);
12408
12409 end = content + strlen(content) -1;
12410 if (*end == '"') {
12411 *end = '\0';
12412 }
12413
12414 add_header(&req, headdup, content);
12415 if (sipdebug) {
12416 ast_debug(1, "Adding SIP Header \"%s\" with content :%s: \n", headdup, content);
12417 }
12418 }
12419 }
12420 }
12421 }
12422
12423 ast_channel_unlock(chan);
12424 }
12425 if ((sipmethod == SIP_INVITE || sipmethod == SIP_UPDATE) && ast_test_flag(&p->flags[0], SIP_SENDRPID))
12426 add_rpid(&req, p);
12427 if (sipmethod == SIP_INVITE) {
12428 add_diversion_header(&req, p);
12429 }
12430 if (sdp) {
12431 memset(p->offered_media, 0, sizeof(p->offered_media));
12432 if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
12433 ast_debug(1, "T38 is in state %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
12434 add_sdp(&req, p, FALSE, FALSE, TRUE);
12435 } else if (p->rtp) {
12436 try_suggested_sip_codec(p);
12437 add_sdp(&req, p, FALSE, TRUE, FALSE);
12438 }
12439 } else if (p->notify) {
12440 for (var = p->notify->headers; var; var = var->next) {
12441 add_header(&req, var->name, var->value);
12442 }
12443 if (ast_str_strlen(p->notify->content)) {
12444 add_content(&req, ast_str_buffer(p->notify->content));
12445 }
12446 } else if (sipmethod == SIP_PUBLISH) {
12447 char expires[SIPBUFSIZE];
12448
12449 switch (p->epa_entry->static_data->event) {
12450 case CALL_COMPLETION:
12451 snprintf(expires, sizeof(expires), "%d", p->expiry);
12452 add_header(&req, "Event", "call-completion");
12453 add_header(&req, "Expires", expires);
12454 if (p->epa_entry->publish_type != SIP_PUBLISH_INITIAL) {
12455 add_header(&req, "SIP-If-Match", p->epa_entry->entity_tag);
12456 }
12457
12458 if (!ast_strlen_zero(p->epa_entry->body)) {
12459 add_header(&req, "Content-Type", "application/pidf+xml");
12460 add_content(&req, p->epa_entry->body);
12461 }
12462 default:
12463 break;
12464 }
12465 }
12466
12467 if (!p->initreq.headers || init > 2) {
12468 initialize_initreq(p, &req);
12469 }
12470 if (sipmethod == SIP_INVITE || sipmethod == SIP_SUBSCRIBE) {
12471 p->lastinvite = p->ocseq;
12472 }
12473 return send_request(p, &req, init ? XMIT_CRITICAL : XMIT_RELIABLE, p->ocseq);
12474 }
12475
12476
12477 static int sip_subscribe_mwi_do(const void *data)
12478 {
12479 struct sip_subscription_mwi *mwi = (struct sip_subscription_mwi*)data;
12480
12481 if (!mwi) {
12482 return -1;
12483 }
12484
12485 mwi->resub = -1;
12486 __sip_subscribe_mwi_do(mwi);
12487 ASTOBJ_UNREF(mwi, sip_subscribe_mwi_destroy);
12488
12489 return 0;
12490 }
12491
12492 static void on_dns_update_registry(struct ast_sockaddr *old, struct ast_sockaddr *new, void *data)
12493 {
12494 struct sip_registry *reg = data;
12495 const char *old_str;
12496
12497
12498 if (ast_sockaddr_isnull(new)) {
12499 ast_debug(1, "Empty sockaddr change...ignoring!\n");
12500 return;
12501 }
12502
12503 if (!ast_sockaddr_port(new)) {
12504 ast_sockaddr_set_port(new, reg->portno);
12505 }
12506
12507 old_str = ast_strdupa(ast_sockaddr_stringify(old));
12508
12509 ast_debug(1, "Changing registry %s from %s to %s\n", S_OR(reg->peername, reg->hostname), old_str, ast_sockaddr_stringify(new));
12510 ast_sockaddr_copy(®->us, new);
12511 }
12512
12513 static void on_dns_update_peer(struct ast_sockaddr *old, struct ast_sockaddr *new, void *data)
12514 {
12515 struct sip_peer *peer = data;
12516 const char *old_str;
12517
12518
12519 if (ast_sockaddr_isnull(new)) {
12520 ast_debug(1, "Empty sockaddr change...ignoring!\n");
12521 return;
12522 }
12523
12524 if (!ast_sockaddr_isnull(&peer->addr)) {
12525 ao2_unlink(peers_by_ip, peer);
12526 }
12527
12528 if (!ast_sockaddr_port(new)) {
12529 ast_sockaddr_set_port(new, default_sip_port(peer->socket.type));
12530 }
12531
12532 old_str = ast_strdupa(ast_sockaddr_stringify(old));
12533 ast_debug(1, "Changing peer %s address from %s to %s\n", peer->name, old_str, ast_sockaddr_stringify(new));
12534
12535 ao2_lock(peer);
12536 ast_sockaddr_copy(&peer->addr, new);
12537 ao2_unlock(peer);
12538
12539 ao2_link(peers_by_ip, peer);
12540 }
12541
12542 static void on_dns_update_mwi(struct ast_sockaddr *old, struct ast_sockaddr *new, void *data)
12543 {
12544 struct sip_subscription_mwi *mwi = data;
12545 const char *old_str;
12546
12547
12548 if (ast_sockaddr_isnull(new)) {
12549 ast_debug(1, "Empty sockaddr change...ignoring!\n");
12550 return;
12551 }
12552
12553 old_str = ast_strdupa(ast_sockaddr_stringify(old));
12554 ast_debug(1, "Changing mwi %s from %s to %s\n", mwi->hostname, old_str, ast_sockaddr_stringify(new));
12555 ast_sockaddr_copy(&mwi->us, new);
12556 }
12557
12558
12559 static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi)
12560 {
12561
12562 if (!mwi->dnsmgr) {
12563 char transport[MAXHOSTNAMELEN];
12564 struct sip_subscription_mwi *saved;
12565 snprintf(transport, sizeof(transport), "_%s._%s", get_srv_service(mwi->transport), get_srv_protocol(mwi->transport));
12566
12567 mwi->us.ss.ss_family = get_address_family_filter(mwi->transport);
12568 saved = ASTOBJ_REF(mwi);
12569 ast_dnsmgr_lookup_cb(mwi->hostname, &mwi->us, &mwi->dnsmgr, sip_cfg.srvlookup ? transport : NULL, on_dns_update_mwi, saved);
12570 if (!mwi->dnsmgr) {
12571 ASTOBJ_UNREF(saved, sip_subscribe_mwi_destroy);
12572 }
12573 }
12574
12575
12576 if (mwi->call) {
12577 transmit_invite(mwi->call, SIP_SUBSCRIBE, 0, 0, NULL);
12578 return 0;
12579 }
12580
12581
12582 if (!(mwi->call = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL))) {
12583 return -1;
12584 }
12585
12586 ref_proxy(mwi->call, obproxy_get(mwi->call, NULL));
12587
12588 if (!ast_sockaddr_port(&mwi->us) && mwi->portno) {
12589 ast_sockaddr_set_port(&mwi->us, mwi->portno);
12590 }
12591
12592
12593 if (create_addr(mwi->call, mwi->hostname, &mwi->us, 0)) {
12594 dialog_unlink_all(mwi->call);
12595 mwi->call = dialog_unref(mwi->call, "unref dialog after unlink_all");
12596 return 0;
12597 }
12598
12599 mwi->call->expiry = mwi_expiry;
12600
12601 if (!mwi->dnsmgr && mwi->portno) {
12602 ast_sockaddr_set_port(&mwi->call->sa, mwi->portno);
12603 ast_sockaddr_set_port(&mwi->call->recv, mwi->portno);
12604 } else {
12605 mwi->portno = ast_sockaddr_port(&mwi->call->sa);
12606 }
12607
12608
12609 if (!ast_strlen_zero(mwi->authuser)) {
12610 ast_string_field_set(mwi->call, peername, mwi->authuser);
12611 ast_string_field_set(mwi->call, authname, mwi->authuser);
12612 ast_string_field_set(mwi->call, fromuser, mwi->authuser);
12613 } else {
12614 ast_string_field_set(mwi->call, peername, mwi->username);
12615 ast_string_field_set(mwi->call, authname, mwi->username);
12616 ast_string_field_set(mwi->call, fromuser, mwi->username);
12617 }
12618 ast_string_field_set(mwi->call, username, mwi->username);
12619 if (!ast_strlen_zero(mwi->secret)) {
12620 ast_string_field_set(mwi->call, peersecret, mwi->secret);
12621 }
12622 set_socket_transport(&mwi->call->socket, mwi->transport);
12623 mwi->call->socket.port = htons(mwi->portno);
12624 ast_sip_ouraddrfor(&mwi->call->sa, &mwi->call->ourip, mwi->call);
12625 build_contact(mwi->call);
12626 build_via(mwi->call);
12627
12628
12629 change_callid_pvt(mwi->call, NULL);
12630
12631 ast_set_flag(&mwi->call->flags[0], SIP_OUTGOING);
12632
12633
12634 mwi->call->mwi = ASTOBJ_REF(mwi);
12635
12636 mwi->call->subscribed = MWI_NOTIFICATION;
12637
12638
12639 transmit_invite(mwi->call, SIP_SUBSCRIBE, 0, 2, NULL);
12640
12641 return 0;
12642 }
12643
12644
12645 static int find_calling_channel(void *obj, void *arg, void *data, int flags)
12646 {
12647 struct ast_channel *c = obj;
12648 struct sip_pvt *p = data;
12649 int res;
12650
12651 ast_channel_lock(c);
12652
12653 res = (c->pbx &&
12654 (!strcasecmp(c->macroexten, p->exten) || !strcasecmp(c->exten, p->exten)) &&
12655 (sip_cfg.notifycid == IGNORE_CONTEXT || !strcasecmp(c->context, p->context)));
12656
12657 ast_channel_unlock(c);
12658
12659 return res ? CMP_MATCH | CMP_STOP : 0;
12660 }
12661
12662
12663 static void state_notify_build_xml(int state, int full, const char *exten, const char *context, struct ast_str **tmp, struct sip_pvt *p, int subscribed, const char *mfrom, const char *mto)
12664 {
12665 enum state { NOTIFY_OPEN, NOTIFY_INUSE, NOTIFY_CLOSED } local_state = NOTIFY_OPEN;
12666 const char *statestring = "terminated";
12667 const char *pidfstate = "--";
12668 const char *pidfnote= "Ready";
12669 char hint[AST_MAX_EXTENSION];
12670
12671 switch (state) {
12672 case (AST_EXTENSION_RINGING | AST_EXTENSION_INUSE):
12673 statestring = (sip_cfg.notifyringing) ? "early" : "confirmed";
12674 local_state = NOTIFY_INUSE;
12675 pidfstate = "busy";
12676 pidfnote = "Ringing";
12677 break;
12678 case AST_EXTENSION_RINGING:
12679 statestring = "early";
12680 local_state = NOTIFY_INUSE;
12681 pidfstate = "busy";
12682 pidfnote = "Ringing";
12683 break;
12684 case AST_EXTENSION_INUSE:
12685 statestring = "confirmed";
12686 local_state = NOTIFY_INUSE;
12687 pidfstate = "busy";
12688 pidfnote = "On the phone";
12689 break;
12690 case AST_EXTENSION_BUSY:
12691 statestring = "confirmed";
12692 local_state = NOTIFY_CLOSED;
12693 pidfstate = "busy";
12694 pidfnote = "On the phone";
12695 break;
12696 case AST_EXTENSION_UNAVAILABLE:
12697 statestring = "terminated";
12698 local_state = NOTIFY_CLOSED;
12699 pidfstate = "away";
12700 pidfnote = "Unavailable";
12701 break;
12702 case AST_EXTENSION_ONHOLD:
12703 statestring = "confirmed";
12704 local_state = NOTIFY_CLOSED;
12705 pidfstate = "busy";
12706 pidfnote = "On hold";
12707 break;
12708 case AST_EXTENSION_NOT_INUSE:
12709 default:
12710
12711 break;
12712 }
12713
12714
12715 if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, context, exten)) {
12716 char *hint2 = hint, *individual_hint = NULL;
12717 int hint_count = 0, unavailable_count = 0;
12718
12719 while ((individual_hint = strsep(&hint2, "&"))) {
12720 hint_count++;
12721
12722 if (ast_device_state(individual_hint) == AST_DEVICE_UNAVAILABLE)
12723 unavailable_count++;
12724 }
12725
12726
12727
12728
12729 if (hint_count > 0 && hint_count == unavailable_count) {
12730 local_state = NOTIFY_CLOSED;
12731 pidfstate = "away";
12732 pidfnote = "Not online";
12733 }
12734 }
12735
12736 switch (subscribed) {
12737 case XPIDF_XML:
12738 case CPIM_PIDF_XML:
12739 ast_str_append(tmp, 0,
12740 "<?xml version=\"1.0\"?>\n"
12741 "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n"
12742 "<presence>\n");
12743 ast_str_append(tmp, 0, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
12744 ast_str_append(tmp, 0, "<atom id=\"%s\">\n", exten);
12745 ast_str_append(tmp, 0, "<address uri=\"%s;user=ip\" priority=\"0.800000\">\n", mto);
12746 ast_str_append(tmp, 0, "<status status=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "open" : (local_state == NOTIFY_INUSE) ? "inuse" : "closed");
12747 ast_str_append(tmp, 0, "<msnsubstatus substatus=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "online" : (local_state == NOTIFY_INUSE) ? "onthephone" : "offline");
12748 ast_str_append(tmp, 0, "</address>\n</atom>\n</presence>\n");
12749 break;
12750 case PIDF_XML:
12751 ast_str_append(tmp, 0,
12752 "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"
12753 "<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);
12754 ast_str_append(tmp, 0, "<pp:person><status>\n");
12755 if (pidfstate[0] != '-') {
12756 ast_str_append(tmp, 0, "<ep:activities><ep:%s/></ep:activities>\n", pidfstate);
12757 }
12758 ast_str_append(tmp, 0, "</status></pp:person>\n");
12759 ast_str_append(tmp, 0, "<note>%s</note>\n", pidfnote);
12760 ast_str_append(tmp, 0, "<tuple id=\"%s\">\n", exten);
12761 ast_str_append(tmp, 0, "<contact priority=\"1\">%s</contact>\n", mto);
12762 if (pidfstate[0] == 'b')
12763 ast_str_append(tmp, 0, "<status><basic>open</basic></status>\n");
12764 else
12765 ast_str_append(tmp, 0, "<status><basic>%s</basic></status>\n", (local_state != NOTIFY_CLOSED) ? "open" : "closed");
12766 ast_str_append(tmp, 0, "</tuple>\n</presence>\n");
12767 break;
12768 case DIALOG_INFO_XML:
12769 ast_str_append(tmp, 0, "<?xml version=\"1.0\"?>\n");
12770 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);
12771 if ((state & AST_EXTENSION_RINGING) && sip_cfg.notifyringing) {
12772 const char *local_display = exten;
12773 char *local_target = ast_strdupa(mto);
12774 const char *remote_display = exten;
12775
12776
12777
12778
12779
12780
12781
12782
12783 char *remote_target = ast_strdupa(mto);
12784
12785
12786
12787
12788 if (sip_cfg.notifycid) {
12789 struct ast_channel *caller;
12790
12791 if ((caller = ast_channel_callback(find_calling_channel, NULL, p, 0))) {
12792 char *cid_num;
12793 char *connected_num;
12794 int need;
12795
12796 ast_channel_lock(caller);
12797 cid_num = S_COR(caller->caller.id.number.valid,
12798 caller->caller.id.number.str, "");
12799 need = strlen(cid_num) + strlen(p->fromdomain) + sizeof("sip:@");
12800 remote_target = ast_alloca(need);
12801 snprintf(remote_target, need, "sip:%s@%s", cid_num, p->fromdomain);
12802
12803 remote_display = ast_strdupa(S_COR(caller->caller.id.name.valid,
12804 caller->caller.id.name.str, ""));
12805
12806 connected_num = S_COR(caller->connected.id.number.valid,
12807 caller->connected.id.number.str, "");
12808 need = strlen(connected_num) + strlen(p->fromdomain) + sizeof("sip:@");
12809 local_target = ast_alloca(need);
12810 snprintf(local_target, need, "sip:%s@%s", connected_num, p->fromdomain);
12811
12812 local_display = ast_strdupa(S_COR(caller->connected.id.name.valid,
12813 caller->connected.id.name.str, ""));
12814
12815 ast_channel_unlock(caller);
12816 caller = ast_channel_unref(caller);
12817 }
12818
12819
12820
12821 if (sip_cfg.pedanticsipchecking) {
12822 ast_str_append(tmp, 0, "<dialog id=\"%s\" call-id=\"pickup-%s\" local-tag=\"%s\" remote-tag=\"%s\" direction=\"recipient\">\n",
12823 exten, p->callid, p->theirtag, p->tag);
12824 } else {
12825 ast_str_append(tmp, 0, "<dialog id=\"%s\" call-id=\"pickup-%s\" direction=\"recipient\">\n",
12826 exten, p->callid);
12827 }
12828 ast_str_append(tmp, 0,
12829 "<remote>\n"
12830
12831
12832 "<identity display=\"%s\">%s</identity>\n"
12833 "<target uri=\"%s\"/>\n"
12834 "</remote>\n"
12835 "<local>\n"
12836 "<identity display=\"%s\">%s</identity>\n"
12837 "<target uri=\"%s\"/>\n"
12838 "</local>\n",
12839 remote_display, remote_target, remote_target, local_display, local_target, local_target);
12840 } else {
12841 ast_str_append(tmp, 0, "<dialog id=\"%s\" direction=\"recipient\">\n", exten);
12842 }
12843
12844 } else {
12845 ast_str_append(tmp, 0, "<dialog id=\"%s\">\n", exten);
12846 }
12847 ast_str_append(tmp, 0, "<state>%s</state>\n", statestring);
12848 if (state == AST_EXTENSION_ONHOLD) {
12849 ast_str_append(tmp, 0, "<local>\n<target uri=\"%s\">\n"
12850 "<param pname=\"+sip.rendering\" pvalue=\"no\"/>\n"
12851 "</target>\n</local>\n", mto);
12852 }
12853 ast_str_append(tmp, 0, "</dialog>\n</dialog-info>\n");
12854 break;
12855 case NONE:
12856 default:
12857 break;
12858 }
12859 }
12860
12861 static int transmit_cc_notify(struct ast_cc_agent *agent, struct sip_pvt *subscription, enum sip_cc_notify_state state)
12862 {
12863 struct sip_request req;
12864 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
12865 char uri[SIPBUFSIZE];
12866 char state_str[64];
12867 char subscription_state_hdr[64];
12868
12869 if (state < CC_QUEUED || state > CC_READY) {
12870 ast_log(LOG_WARNING, "Invalid state provided for transmit_cc_notify (%d)\n", state);
12871 return -1;
12872 }
12873
12874 reqprep(&req, subscription, SIP_NOTIFY, 0, TRUE);
12875 snprintf(state_str, sizeof(state_str), "%s\r\n", sip_cc_notify_state_map[state].state_string);
12876 add_header(&req, "Event", "call-completion");
12877 add_header(&req, "Content-Type", "application/call-completion");
12878 snprintf(subscription_state_hdr, sizeof(subscription_state_hdr), "active;expires=%d", subscription->expiry);
12879 add_header(&req, "Subscription-State", subscription_state_hdr);
12880 if (state == CC_READY) {
12881 generate_uri(subscription, agent_pvt->notify_uri, sizeof(agent_pvt->notify_uri));
12882 snprintf(uri, sizeof(uri) - 1, "cc-URI: %s\r\n", agent_pvt->notify_uri);
12883 }
12884 add_content(&req, state_str);
12885 if (state == CC_READY) {
12886 add_content(&req, uri);
12887 }
12888 return send_request(subscription, &req, XMIT_RELIABLE, subscription->ocseq);
12889 }
12890
12891
12892 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout)
12893 {
12894 struct ast_str *tmp = ast_str_alloca(4000);
12895 char from[256], to[256];
12896 char *c, *mfrom, *mto;
12897 struct sip_request req;
12898 const struct cfsubscription_types *subscriptiontype;
12899
12900
12901 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
12902 return 0;
12903 }
12904
12905 memset(from, 0, sizeof(from));
12906 memset(to, 0, sizeof(to));
12907
12908 subscriptiontype = find_subscription_type(p->subscribed);
12909
12910 ast_copy_string(from, get_header(&p->initreq, "From"), sizeof(from));
12911 c = get_in_brackets(from);
12912 if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
12913 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
12914 return -1;
12915 }
12916
12917 mfrom = remove_uri_parameters(c);
12918
12919 ast_copy_string(to, get_header(&p->initreq, "To"), sizeof(to));
12920 c = get_in_brackets(to);
12921 if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
12922 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
12923 return -1;
12924 }
12925 mto = remove_uri_parameters(c);
12926
12927 reqprep(&req, p, SIP_NOTIFY, 0, 1);
12928
12929 switch(state) {
12930 case AST_EXTENSION_DEACTIVATED:
12931 if (timeout)
12932 add_header(&req, "Subscription-State", "terminated;reason=timeout");
12933 else {
12934 add_header(&req, "Subscription-State", "terminated;reason=probation");
12935 add_header(&req, "Retry-After", "60");
12936 }
12937 break;
12938 case AST_EXTENSION_REMOVED:
12939 add_header(&req, "Subscription-State", "terminated;reason=noresource");
12940 break;
12941 default:
12942 if (p->expiry)
12943 add_header(&req, "Subscription-State", "active");
12944 else
12945 add_header(&req, "Subscription-State", "terminated;reason=timeout");
12946 }
12947
12948 switch (p->subscribed) {
12949 case XPIDF_XML:
12950 case CPIM_PIDF_XML:
12951 add_header(&req, "Event", subscriptiontype->event);
12952 state_notify_build_xml(state, full, p->exten, p->context, &tmp, p, p->subscribed, mfrom, mto);
12953 add_header(&req, "Content-Type", subscriptiontype->mediatype);
12954 p->dialogver++;
12955 break;
12956 case PIDF_XML:
12957 add_header(&req, "Event", subscriptiontype->event);
12958 state_notify_build_xml(state, full, p->exten, p->context, &tmp, p, p->subscribed, mfrom, mto);
12959 add_header(&req, "Content-Type", subscriptiontype->mediatype);
12960 p->dialogver++;
12961 break;
12962 case DIALOG_INFO_XML:
12963 add_header(&req, "Event", subscriptiontype->event);
12964 state_notify_build_xml(state, full, p->exten, p->context, &tmp, p, p->subscribed, mfrom, mto);
12965 add_header(&req, "Content-Type", subscriptiontype->mediatype);
12966 p->dialogver++;
12967 break;
12968 case NONE:
12969 default:
12970 break;
12971 }
12972
12973 add_content(&req, tmp->str);
12974
12975 p->pendinginvite = p->ocseq;
12976
12977 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
12978 }
12979
12980
12981
12982
12983
12984
12985
12986 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten)
12987 {
12988 struct sip_request req;
12989 struct ast_str *out = ast_str_alloca(500);
12990 int ourport = (p->fromdomainport) ? p->fromdomainport : ast_sockaddr_port(&p->ourip);
12991 const char *domain;
12992 const char *exten = S_OR(vmexten, default_vmexten);
12993
12994 initreqprep(&req, p, SIP_NOTIFY, NULL);
12995 add_header(&req, "Event", "message-summary");
12996 add_header(&req, "Content-Type", default_notifymime);
12997 ast_str_append(&out, 0, "Messages-Waiting: %s\r\n", newmsgs ? "yes" : "no");
12998
12999
13000 domain = S_OR(p->fromdomain, ast_sockaddr_stringify_host_remote(&p->ourip));
13001
13002 if (!sip_standard_port(p->socket.type, ourport)) {
13003 if (p->socket.type == SIP_TRANSPORT_UDP) {
13004 ast_str_append(&out, 0, "Message-Account: sip:%s@%s:%d\r\n", exten, domain, ourport);
13005 } else {
13006 ast_str_append(&out, 0, "Message-Account: sip:%s@%s:%d;transport=%s\r\n", exten, domain, ourport, get_transport(p->socket.type));
13007 }
13008 } else {
13009 if (p->socket.type == SIP_TRANSPORT_UDP) {
13010 ast_str_append(&out, 0, "Message-Account: sip:%s@%s\r\n", exten, domain);
13011 } else {
13012 ast_str_append(&out, 0, "Message-Account: sip:%s@%s;transport=%s\r\n", exten, domain, get_transport(p->socket.type));
13013 }
13014 }
13015
13016
13017
13018 ast_str_append(&out, 0, "Voice-Message: %d/%d%s\r\n",
13019 newmsgs, oldmsgs, (ast_test_flag(&p->flags[1], SIP_PAGE2_BUGGY_MWI) ? "" : " (0/0)"));
13020
13021 if (p->subscribed) {
13022 if (p->expiry) {
13023 add_header(&req, "Subscription-State", "active");
13024 } else {
13025 add_header(&req, "Subscription-State", "terminated;reason=timeout");
13026 }
13027 }
13028
13029 add_content(&req, out->str);
13030
13031 if (!p->initreq.headers) {
13032 initialize_initreq(p, &req);
13033 }
13034 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
13035 }
13036
13037
13038 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate)
13039 {
13040 struct sip_request req;
13041 char tmp[SIPBUFSIZE/2];
13042
13043 reqprep(&req, p, SIP_NOTIFY, 0, 1);
13044 snprintf(tmp, sizeof(tmp), "refer;id=%d", cseq);
13045 add_header(&req, "Event", tmp);
13046 add_header(&req, "Subscription-state", terminate ? "terminated;reason=noresource" : "active");
13047 add_header(&req, "Content-Type", "message/sipfrag;version=2.0");
13048 add_header(&req, "Allow", ALLOWED_METHODS);
13049 add_supported_header(p, &req);
13050
13051 snprintf(tmp, sizeof(tmp), "SIP/2.0 %s\r\n", message);
13052 add_content(&req, tmp);
13053
13054 if (!p->initreq.headers) {
13055 initialize_initreq(p, &req);
13056 }
13057
13058 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
13059 }
13060
13061 static int manager_sipnotify(struct mansession *s, const struct message *m)
13062 {
13063 const char *channame = astman_get_header(m, "Channel");
13064 struct ast_variable *vars = astman_get_variables(m);
13065 struct sip_pvt *p;
13066 struct ast_variable *header, *var;
13067
13068 if (ast_strlen_zero(channame)) {
13069 astman_send_error(s, m, "SIPNotify requires a channel name");
13070 return 0;
13071 }
13072
13073 if (!strncasecmp(channame, "sip/", 4)) {
13074 channame += 4;
13075 }
13076
13077 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
13078 astman_send_error(s, m, "Unable to build sip pvt data for notify (memory/socket error)");
13079 return 0;
13080 }
13081
13082 if (create_addr(p, channame, NULL, 0)) {
13083
13084 dialog_unlink_all(p);
13085 dialog_unref(p, "unref dialog inside for loop" );
13086
13087 astman_send_error(s, m, "Could not create address");
13088 return 0;
13089 }
13090
13091
13092 ast_set_flag(&p->flags[0], SIP_OUTGOING);
13093 sip_notify_allocate(p);
13094
13095 p->notify->headers = header = ast_variable_new("Subscription-State", "terminated", "");
13096
13097 for (var = vars; var; var = var->next) {
13098 if (!strcasecmp(var->name, "Content")) {
13099 if (ast_str_strlen(p->notify->content))
13100 ast_str_append(&p->notify->content, 0, "\r\n");
13101 ast_str_append(&p->notify->content, 0, "%s", var->value);
13102 } else if (!strcasecmp(var->name, "Content-Length")) {
13103 ast_log(LOG_WARNING, "it is not necessary to specify Content-Length, ignoring\n");
13104 } else {
13105 header->next = ast_variable_new(var->name, var->value, "");
13106 header = header->next;
13107 }
13108 }
13109
13110 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
13111 transmit_invite(p, SIP_NOTIFY, 0, 2, NULL);
13112 dialog_unref(p, "bump down the count of p since we're done with it.");
13113
13114 astman_send_ack(s, m, "Notify Sent");
13115 ast_variables_destroy(vars);
13116 return 0;
13117 }
13118
13119
13120
13121 static void update_redirecting(struct sip_pvt *p, const void *data, size_t datalen)
13122 {
13123 struct sip_request resp;
13124
13125 if (p->owner->_state == AST_STATE_UP || ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
13126 return;
13127 }
13128
13129 respprep(&resp, p, "181 Call is being forwarded", &p->initreq);
13130 add_diversion_header(&resp, p);
13131 send_response(p, &resp, XMIT_UNRELIABLE, 0);
13132 }
13133
13134
13135 static void update_connectedline(struct sip_pvt *p, const void *data, size_t datalen)
13136 {
13137
13138 if (!ast_test_flag(&p->flags[0], SIP_SENDRPID)) {
13139 return;
13140 }
13141 if (!p->owner->connected.id.number.valid
13142 || ast_strlen_zero(p->owner->connected.id.number.str)) {
13143 return;
13144 }
13145
13146 append_history(p, "ConnectedLine", "%s party is now %s <%s>",
13147 ast_test_flag(&p->flags[0], SIP_OUTGOING) ? "Calling" : "Called",
13148 S_COR(p->owner->connected.id.name.valid, p->owner->connected.id.name.str, ""),
13149 S_COR(p->owner->connected.id.number.valid, p->owner->connected.id.number.str, ""));
13150
13151 if (p->owner->_state == AST_STATE_UP || ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
13152 struct sip_request req;
13153
13154 if (!p->pendinginvite && (p->invitestate == INV_CONFIRMED || p->invitestate == INV_TERMINATED)) {
13155 reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ? SIP_UPDATE : SIP_INVITE, 0, 1);
13156
13157 add_header(&req, "Allow", ALLOWED_METHODS);
13158 add_supported_header(p, &req);
13159 add_rpid(&req, p);
13160 add_sdp(&req, p, FALSE, TRUE, FALSE);
13161
13162 initialize_initreq(p, &req);
13163 p->lastinvite = p->ocseq;
13164 ast_set_flag(&p->flags[0], SIP_OUTGOING);
13165 p->invitestate = INV_CALLING;
13166 send_request(p, &req, XMIT_CRITICAL, p->ocseq);
13167 } else if ((is_method_allowed(&p->allowed_methods, SIP_UPDATE)) && (!ast_strlen_zero(p->okcontacturi))) {
13168 reqprep(&req, p, SIP_UPDATE, 0, 1);
13169 add_rpid(&req, p);
13170 add_header(&req, "X-Asterisk-rpid-update", "Yes");
13171 send_request(p, &req, XMIT_CRITICAL, p->ocseq);
13172 } else {
13173
13174 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
13175 }
13176 } else {
13177 ast_set_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND);
13178 if (ast_test_flag(&p->flags[1], SIP_PAGE2_RPID_IMMEDIATE)) {
13179 struct sip_request resp;
13180
13181 if ((p->owner->_state == AST_STATE_RING) && !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT)) {
13182 ast_clear_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND);
13183 respprep(&resp, p, "180 Ringing", &p->initreq);
13184 add_rpid(&resp, p);
13185 send_response(p, &resp, XMIT_UNRELIABLE, 0);
13186 ast_set_flag(&p->flags[0], SIP_RINGING);
13187 } else if (p->owner->_state == AST_STATE_RINGING) {
13188 ast_clear_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND);
13189 respprep(&resp, p, "183 Session Progress", &p->initreq);
13190 add_rpid(&resp, p);
13191 send_response(p, &resp, XMIT_UNRELIABLE, 0);
13192 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
13193 } else {
13194 ast_debug(1, "Unable able to send update to '%s' in state '%s'\n", p->owner->name, ast_state2str(p->owner->_state));
13195 }
13196 }
13197 }
13198 }
13199
13200 static const struct _map_x_s regstatestrings[] = {
13201 { REG_STATE_FAILED, "Failed" },
13202 { REG_STATE_UNREGISTERED, "Unregistered"},
13203 { REG_STATE_REGSENT, "Request Sent"},
13204 { REG_STATE_AUTHSENT, "Auth. Sent"},
13205 { REG_STATE_REGISTERED, "Registered"},
13206 { REG_STATE_REJECTED, "Rejected"},
13207 { REG_STATE_TIMEOUT, "Timeout"},
13208 { REG_STATE_NOAUTH, "No Authentication"},
13209 { -1, NULL }
13210 };
13211
13212
13213 static const char *regstate2str(enum sipregistrystate regstate)
13214 {
13215 return map_x_s(regstatestrings, regstate, "Unknown");
13216 }
13217
13218
13219
13220
13221
13222
13223
13224 static int sip_reregister(const void *data)
13225 {
13226
13227 struct sip_registry *r = (struct sip_registry *) data;
13228
13229
13230 if (!r) {
13231 return 0;
13232 }
13233
13234 if (r->call && r->call->do_history) {
13235 append_history(r->call, "RegistryRenew", "Account: %s@%s", r->username, r->hostname);
13236 }
13237
13238
13239 if (sipdebug) {
13240 ast_log(LOG_NOTICE, " -- Re-registration for %s@%s\n", r->username, r->hostname);
13241 }
13242
13243 r->expire = -1;
13244 r->expiry = r->configured_expiry;
13245 __sip_do_register(r);
13246 registry_unref(r, "unref the re-register scheduled event");
13247 return 0;
13248 }
13249
13250
13251
13252
13253 static int __sip_do_register(struct sip_registry *r)
13254 {
13255 int res;
13256
13257 res = transmit_register(r, SIP_REGISTER, NULL, NULL);
13258 return res;
13259 }
13260
13261
13262
13263
13264
13265
13266
13267 static int sip_reg_timeout(const void *data)
13268 {
13269
13270
13271 struct sip_registry *r = (struct sip_registry *)data;
13272 struct sip_pvt *p;
13273
13274
13275 if (!r) {
13276 return 0;
13277 }
13278
13279 if (r->dnsmgr) {
13280
13281 ast_dnsmgr_refresh(r->dnsmgr);
13282 }
13283
13284
13285
13286
13287
13288 if (r->call) {
13289
13290
13291 p = r->call;
13292 sip_pvt_lock(p);
13293 pvt_set_needdestroy(p, "registration timeout");
13294
13295 __sip_pretend_ack(p);
13296 sip_pvt_unlock(p);
13297
13298
13299
13300 if (p->registry) {
13301 p->registry = registry_unref(p->registry, "p->registry unreffed");
13302 }
13303 r->call = dialog_unref(r->call, "unrefing r->call");
13304 }
13305
13306 r->timeout = -1;
13307 if (global_regattempts_max && r->regattempts >= global_regattempts_max) {
13308
13309
13310
13311 ast_log(LOG_NOTICE, " -- Last Registration Attempt #%d failed, Giving up forever trying to register '%s@%s'\n", r->regattempts, r->username, r->hostname);
13312 r->regstate = REG_STATE_FAILED;
13313 } else {
13314 r->regstate = REG_STATE_UNREGISTERED;
13315 transmit_register(r, SIP_REGISTER, NULL, NULL);
13316 ast_log(LOG_NOTICE, " -- Registration for '%s@%s' timed out, trying again (Attempt #%d)\n", r->username, r->hostname, r->regattempts);
13317 }
13318 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));
13319 registry_unref(r, "unreffing registry_unref r");
13320 return 0;
13321 }
13322
13323 static const char *sip_sanitized_host(const char *host)
13324 {
13325 struct ast_sockaddr addr = { { 0, 0, }, };
13326
13327
13328
13329
13330 if (!ast_sockaddr_parse(&addr, host, PARSE_PORT_FORBID)) {
13331 return host;
13332 }
13333 return ast_sockaddr_stringify_host_remote(&addr);
13334 }
13335
13336
13337
13338
13339 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader)
13340 {
13341 struct sip_request req;
13342 char from[256];
13343 char to[256];
13344 char tmp[80];
13345 char addr[80];
13346 struct sip_pvt *p;
13347 struct sip_peer *peer = NULL;
13348 int res;
13349 int portno = 0;
13350
13351
13352 if (r == NULL || ((auth == NULL) && (r->regstate == REG_STATE_REGSENT || r->regstate == REG_STATE_AUTHSENT))) {
13353 if (r) {
13354 ast_log(LOG_NOTICE, "Strange, trying to register %s@%s when registration already pending\n", r->username, r->hostname);
13355 }
13356 return 0;
13357 }
13358
13359 if (r->dnsmgr == NULL) {
13360 char transport[MAXHOSTNAMELEN];
13361 peer = find_peer(r->hostname, NULL, TRUE, FINDPEERS, FALSE, 0);
13362 snprintf(transport, sizeof(transport), "_%s._%s",get_srv_service(r->transport), get_srv_protocol(r->transport));
13363 r->us.ss.ss_family = get_address_family_filter(r->transport);
13364
13365
13366
13367
13368
13369 if (!obproxy_get(r->call, peer)) {
13370 registry_addref(r, "add reg ref for dnsmgr");
13371 ast_dnsmgr_lookup_cb(peer ? peer->tohost : r->hostname, &r->us, &r->dnsmgr, sip_cfg.srvlookup ? transport : NULL, on_dns_update_registry, r);
13372 if (!r->dnsmgr) {
13373
13374 registry_unref(r, "remove reg ref, dnsmgr disabled");
13375 }
13376 }
13377 if (peer) {
13378 peer = unref_peer(peer, "removing peer ref for dnsmgr_lookup");
13379 }
13380 }
13381
13382 if (r->call) {
13383 if (!auth) {
13384 ast_log(LOG_WARNING, "Already have a REGISTER going on to %s@%s?? \n", r->username, r->hostname);
13385 return 0;
13386 } else {
13387 p = dialog_ref(r->call, "getting a copy of the r->call dialog in transmit_register");
13388 make_our_tag(p);
13389 ast_string_field_set(p, theirtag, NULL);
13390 }
13391 } else {
13392
13393 if (!r->callid_valid) {
13394 build_callid_registry(r, &internip, default_fromdomain);
13395 r->callid_valid = TRUE;
13396 }
13397
13398 if (!(p = sip_alloc( r->callid, NULL, 0, SIP_REGISTER, NULL))) {
13399 ast_log(LOG_WARNING, "Unable to allocate registration transaction (memory or socket error)\n");
13400 return 0;
13401 }
13402
13403 if (p->do_history) {
13404 append_history(p, "RegistryInit", "Account: %s@%s", r->username, r->hostname);
13405 }
13406
13407
13408 if (!ast_sockaddr_isnull(&r->us)) {
13409 if (!ast_sockaddr_port(&r->us) && r->portno) {
13410 ast_sockaddr_set_port(&r->us, r->portno);
13411 }
13412
13413
13414
13415
13416
13417 if ((peer = find_peer(S_OR(r->peername, r->hostname), NULL, TRUE, FINDPEERS, FALSE, 0))) {
13418 if (ast_sockaddr_cmp(&peer->addr, &r->us)) {
13419 on_dns_update_peer(&peer->addr, &r->us, peer);
13420 }
13421 peer = unref_peer(peer, "unref after find_peer");
13422 }
13423 }
13424
13425
13426 if (create_addr(p, S_OR(r->peername, r->hostname), &r->us, 0)) {
13427
13428
13429 dialog_unlink_all(p);
13430 p = dialog_unref(p, "unref dialog after unlink_all");
13431 if (r->timeout > -1) {
13432 AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
13433 registry_unref(_data, "del for REPLACE of registry ptr"),
13434 registry_unref(r, "object ptr dec when SCHED_REPLACE add failed"),
13435 registry_addref(r,"add for REPLACE registry ptr"));
13436 ast_log(LOG_WARNING, "Still have a registration timeout for %s@%s (create_addr() error), %d\n", r->username, r->hostname, r->timeout);
13437 } else {
13438 r->timeout = ast_sched_add(sched, global_reg_timeout * 1000, sip_reg_timeout, registry_addref(r, "add for REPLACE registry ptr"));
13439 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);
13440 }
13441 r->regattempts++;
13442 return 0;
13443 }
13444
13445
13446 ast_string_field_set(r, callid, p->callid);
13447
13448 if (!r->dnsmgr && r->portno) {
13449 ast_sockaddr_set_port(&p->sa, r->portno);
13450 ast_sockaddr_set_port(&p->recv, r->portno);
13451 }
13452 if (!ast_strlen_zero(p->fromdomain)) {
13453 portno = (p->fromdomainport) ? p->fromdomainport : STANDARD_SIP_PORT;
13454 } else if (!ast_strlen_zero(r->regdomain)) {
13455 portno = (r->regdomainport) ? r->regdomainport : STANDARD_SIP_PORT;
13456 } else {
13457 portno = ast_sockaddr_port(&p->sa);
13458 }
13459
13460 ast_set_flag(&p->flags[0], SIP_OUTGOING);
13461 r->call = dialog_ref(p, "copying dialog into registry r->call");
13462 p->registry = registry_addref(r, "transmit_register: addref to p->registry in transmit_register");
13463 if (!ast_strlen_zero(r->secret)) {
13464 ast_string_field_set(p, peersecret, r->secret);
13465 }
13466 if (!ast_strlen_zero(r->md5secret))
13467 ast_string_field_set(p, peermd5secret, r->md5secret);
13468
13469
13470 if (!ast_strlen_zero(r->authuser)) {
13471 ast_string_field_set(p, peername, r->authuser);
13472 ast_string_field_set(p, authname, r->authuser);
13473 } else if (!ast_strlen_zero(r->username)) {
13474 ast_string_field_set(p, peername, r->username);
13475 ast_string_field_set(p, authname, r->username);
13476 ast_string_field_set(p, fromuser, r->username);
13477 }
13478 if (!ast_strlen_zero(r->username)) {
13479 ast_string_field_set(p, username, r->username);
13480 }
13481
13482 if (!ast_strlen_zero(r->callback)) {
13483 ast_string_field_set(p, exten, r->callback);
13484 }
13485
13486
13487 set_socket_transport(&p->socket, r->transport);
13488 if (r->transport == SIP_TRANSPORT_TLS || r->transport == SIP_TRANSPORT_TCP) {
13489 p->socket.port =
13490 htons(ast_sockaddr_port(&sip_tcp_desc.local_address));
13491 }
13492
13493
13494
13495
13496
13497
13498 ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
13499 build_contact(p);
13500 }
13501
13502
13503 if (auth == NULL) {
13504 if (r->timeout > -1) {
13505 ast_log(LOG_WARNING, "Still have a registration timeout, #%d - deleting it\n", r->timeout);
13506 }
13507 AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
13508 registry_unref(_data,"reg ptr unrefed from del in SCHED_REPLACE"),
13509 registry_unref(r,"reg ptr unrefed from add failure in SCHED_REPLACE"),
13510 registry_addref(r,"reg ptr reffed from add in SCHED_REPLACE"));
13511 ast_debug(1, "Scheduled a registration timeout for %s id #%d \n", r->hostname, r->timeout);
13512 }
13513
13514 snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%s", r->username, S_OR(r->regdomain, sip_sanitized_host(p->tohost)), p->tag);
13515 if (!ast_strlen_zero(p->theirtag)) {
13516 snprintf(to, sizeof(to), "<sip:%s@%s>;tag=%s", r->username, S_OR(r->regdomain, sip_sanitized_host(p->tohost)), p->theirtag);
13517 } else {
13518 snprintf(to, sizeof(to), "<sip:%s@%s>", r->username, S_OR(r->regdomain, sip_sanitized_host(p->tohost)));
13519 }
13520
13521
13522
13523 if (portno && portno != STANDARD_SIP_PORT) {
13524 snprintf(addr, sizeof(addr), "sip:%s:%d", S_OR(p->fromdomain,S_OR(r->regdomain, sip_sanitized_host(r->hostname))), portno);
13525 } else {
13526 snprintf(addr, sizeof(addr), "sip:%s", S_OR(p->fromdomain,S_OR(r->regdomain, sip_sanitized_host(r->hostname))));
13527 }
13528
13529 ast_string_field_set(p, uri, addr);
13530
13531 p->branch ^= ast_random();
13532
13533 init_req(&req, sipmethod, addr);
13534
13535
13536 snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, sip_methods[sipmethod].text);
13537 p->ocseq = r->ocseq;
13538
13539 build_via(p);
13540 add_header(&req, "Via", p->via);
13541 add_header_max_forwards(p, &req);
13542 add_header(&req, "From", from);
13543 add_header(&req, "To", to);
13544 add_header(&req, "Call-ID", p->callid);
13545 add_header(&req, "CSeq", tmp);
13546 if (!ast_strlen_zero(global_useragent))
13547 add_header(&req, "User-Agent", global_useragent);
13548
13549 if (auth) {
13550 add_header(&req, authheader, auth);
13551 } else if (!ast_strlen_zero(r->nonce)) {
13552 char digest[1024];
13553
13554
13555
13556
13557
13558
13559 if (sipdebug) {
13560 ast_debug(1, " >>> Re-using Auth data for %s@%s\n", r->username, r->hostname);
13561 }
13562 ast_string_field_set(p, realm, r->realm);
13563 ast_string_field_set(p, nonce, r->nonce);
13564 ast_string_field_set(p, domain, r->authdomain);
13565 ast_string_field_set(p, opaque, r->opaque);
13566 ast_string_field_set(p, qop, r->qop);
13567 p->noncecount = ++r->noncecount;
13568
13569 memset(digest, 0, sizeof(digest));
13570 if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
13571 add_header(&req, "Authorization", digest);
13572 } else {
13573 ast_log(LOG_NOTICE, "No authorization available for authentication of registration to %s@%s\n", r->username, r->hostname);
13574 }
13575 }
13576
13577 snprintf(tmp, sizeof(tmp), "%d", r->expiry);
13578 add_header(&req, "Expires", tmp);
13579 add_header(&req, "Contact", p->our_contact);
13580
13581 initialize_initreq(p, &req);
13582 if (sip_debug_test_pvt(p)) {
13583 ast_verbose("REGISTER %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
13584 }
13585 r->regstate = auth ? REG_STATE_AUTHSENT : REG_STATE_REGSENT;
13586 r->regattempts++;
13587 ast_debug(4, "REGISTER attempt %d to %s@%s\n", r->regattempts, r->username, r->hostname);
13588 res = send_request(p, &req, XMIT_CRITICAL, p->ocseq);
13589 dialog_unref(p, "p is finished here at the end of transmit_register");
13590 return res;
13591 }
13592
13593
13594 static int transmit_message_with_text(struct sip_pvt *p, const char *text)
13595 {
13596 struct sip_request req;
13597
13598 reqprep(&req, p, SIP_MESSAGE, 0, 1);
13599 add_text(&req, text);
13600 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
13601 }
13602
13603
13604 static int sip_refer_allocate(struct sip_pvt *p)
13605 {
13606 p->refer = ast_calloc(1, sizeof(struct sip_refer));
13607 return p->refer ? 1 : 0;
13608 }
13609
13610
13611 static int sip_notify_allocate(struct sip_pvt *p)
13612 {
13613 p->notify = ast_calloc(1, sizeof(struct sip_notify));
13614 if (p->notify) {
13615 p->notify->content = ast_str_create(128);
13616 }
13617 return p->notify ? 1 : 0;
13618 }
13619
13620
13621
13622
13623
13624
13625 static int transmit_refer(struct sip_pvt *p, const char *dest)
13626 {
13627 struct sip_request req = {
13628 .headers = 0,
13629 };
13630 char from[256];
13631 const char *of;
13632 char *c;
13633 char referto[256];
13634 int use_tls=FALSE;
13635
13636 if (sipdebug) {
13637 ast_debug(1, "SIP transfer of %s to %s\n", p->callid, dest);
13638 }
13639
13640
13641 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
13642 of = get_header(&p->initreq, "To");
13643 } else {
13644 of = get_header(&p->initreq, "From");
13645 }
13646
13647 ast_copy_string(from, of, sizeof(from));
13648 of = get_in_brackets(from);
13649 ast_string_field_set(p, from, of);
13650 if (!strncasecmp(of, "sip:", 4)) {
13651 of += 4;
13652 } else if (!strncasecmp(of, "sips:", 5)) {
13653 of += 5;
13654 use_tls = TRUE;
13655 } else {
13656 ast_log(LOG_NOTICE, "From address missing 'sip(s):', assuming sip:\n");
13657 }
13658
13659 if (strchr(dest, '@')) {
13660 c = NULL;
13661 } else if ((c = strchr(of, '@'))) {
13662 *c++ = '\0';
13663 }
13664 if (c) {
13665 snprintf(referto, sizeof(referto), "<sip%s:%s@%s>", use_tls ? "s" : "", dest, c);
13666 } else {
13667 snprintf(referto, sizeof(referto), "<sip%s:%s>", use_tls ? "s" : "", dest);
13668 }
13669
13670
13671 sip_refer_allocate(p);
13672 ast_copy_string(p->refer->refer_to, referto, sizeof(p->refer->refer_to));
13673 ast_copy_string(p->refer->referred_by, p->our_contact, sizeof(p->refer->referred_by));
13674 p->refer->status = REFER_SENT;
13675
13676 reqprep(&req, p, SIP_REFER, 0, 1);
13677
13678 add_header(&req, "Refer-To", referto);
13679 add_header(&req, "Allow", ALLOWED_METHODS);
13680 add_supported_header(p, &req);
13681 if (!ast_strlen_zero(p->our_contact)) {
13682 add_header(&req, "Referred-By", p->our_contact);
13683 }
13684
13685 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695 }
13696
13697
13698 static int transmit_info_with_aoc(struct sip_pvt *p, struct ast_aoc_decoded *decoded)
13699 {
13700 struct sip_request req;
13701 struct ast_str *str = ast_str_alloca(512);
13702 const struct ast_aoc_unit_entry *unit_entry = ast_aoc_get_unit_info(decoded, 0);
13703 enum ast_aoc_charge_type charging = ast_aoc_get_charge_type(decoded);
13704
13705 reqprep(&req, p, SIP_INFO, 0, 1);
13706
13707 if (ast_aoc_get_msg_type(decoded) == AST_AOC_D) {
13708 ast_str_append(&str, 0, "type=active;");
13709 } else if (ast_aoc_get_msg_type(decoded) == AST_AOC_E) {
13710 ast_str_append(&str, 0, "type=terminated;");
13711 } else {
13712
13713 return -1;
13714 }
13715
13716 switch (charging) {
13717 case AST_AOC_CHARGE_FREE:
13718 ast_str_append(&str, 0, "free-of-charge;");
13719 break;
13720 case AST_AOC_CHARGE_CURRENCY:
13721 ast_str_append(&str, 0, "charging;");
13722 ast_str_append(&str, 0, "charging-info=currency;");
13723 ast_str_append(&str, 0, "amount=%u;", ast_aoc_get_currency_amount(decoded));
13724 ast_str_append(&str, 0, "multiplier=%s;", ast_aoc_get_currency_multiplier_decimal(decoded));
13725 if (!ast_strlen_zero(ast_aoc_get_currency_name(decoded))) {
13726 ast_str_append(&str, 0, "currency=%s;", ast_aoc_get_currency_name(decoded));
13727 }
13728 break;
13729 case AST_AOC_CHARGE_UNIT:
13730 ast_str_append(&str, 0, "charging;");
13731 ast_str_append(&str, 0, "charging-info=pulse;");
13732 if (unit_entry) {
13733 ast_str_append(&str, 0, "recorded-units=%u;", unit_entry->amount);
13734 }
13735 break;
13736 default:
13737 ast_str_append(&str, 0, "not-available;");
13738 };
13739
13740 add_header(&req, "AOC", ast_str_buffer(str));
13741
13742 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
13743 }
13744
13745
13746 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration)
13747 {
13748 struct sip_request req;
13749
13750 reqprep(&req, p, SIP_INFO, 0, 1);
13751 add_digit(&req, digit, duration, (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_SHORTINFO));
13752 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
13753 }
13754
13755
13756 static int transmit_info_with_vidupdate(struct sip_pvt *p)
13757 {
13758 struct sip_request req;
13759
13760 reqprep(&req, p, SIP_INFO, 0, 1);
13761 add_vidupdate(&req);
13762 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
13763 }
13764
13765
13766
13767
13768 static int transmit_request(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch)
13769 {
13770 struct sip_request resp;
13771
13772 reqprep(&resp, p, sipmethod, seqno, newbranch);
13773 if (sipmethod == SIP_CANCEL && p->answered_elsewhere) {
13774 add_header(&resp, "Reason", "SIP;cause=200;text=\"Call completed elsewhere\"");
13775 }
13776
13777 if (sipmethod == SIP_ACK) {
13778 p->invitestate = INV_CONFIRMED;
13779 }
13780
13781 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
13782 }
13783
13784
13785 static void auth_headers(enum sip_auth_type code, char **header, char **respheader)
13786 {
13787 if (code == WWW_AUTH) {
13788 *header = "WWW-Authenticate";
13789 *respheader = "Authorization";
13790 } else if (code == PROXY_AUTH) {
13791 *header = "Proxy-Authenticate";
13792 *respheader = "Proxy-Authorization";
13793 } else {
13794 ast_verbose("-- wrong response code %d\n", code);
13795 *header = *respheader = "Invalid";
13796 }
13797 }
13798
13799
13800 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch)
13801 {
13802 struct sip_request resp;
13803
13804 reqprep(&resp, p, sipmethod, seqno, newbranch);
13805 if (!ast_strlen_zero(p->realm)) {
13806 char digest[1024];
13807
13808 memset(digest, 0, sizeof(digest));
13809 if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
13810 char *dummy, *response;
13811 enum sip_auth_type code = p->options ? p->options->auth_type : PROXY_AUTH;
13812 auth_headers(code, &dummy, &response);
13813 add_header(&resp, response, digest);
13814 } else {
13815 ast_log(LOG_WARNING, "No authentication available for call %s\n", p->callid);
13816 }
13817 }
13818
13819
13820 if (sipmethod == SIP_BYE) {
13821 char buf[20];
13822
13823 if (ast_test_flag(&p->flags[1], SIP_PAGE2_Q850_REASON) && p->hangupcause) {
13824 sprintf(buf, "Q.850;cause=%i", p->hangupcause & 0x7f);
13825 add_header(&resp, "Reason", buf);
13826 }
13827
13828 add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->hangupcause));
13829 snprintf(buf, sizeof(buf), "%d", p->hangupcause);
13830 add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
13831 }
13832
13833 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
13834 }
13835
13836
13837 static void destroy_association(struct sip_peer *peer)
13838 {
13839 int realtimeregs = ast_check_realtime("sipregs");
13840 char *tablename = (realtimeregs) ? "sipregs" : "sippeers";
13841
13842 if (!sip_cfg.ignore_regexpire) {
13843 if (peer->rt_fromcontact && sip_cfg.peer_rtupdate) {
13844 ast_update_realtime(tablename, "name", peer->name, "fullcontact", "", "ipaddr", "", "port", "", "regseconds", "0", "regserver", "", "useragent", "", "lastms", "0", SENTINEL);
13845 } else {
13846 ast_db_del("SIP/Registry", peer->name);
13847 ast_db_del("SIP/PeerMethods", peer->name);
13848 }
13849 }
13850 }
13851
13852 static void set_socket_transport(struct sip_socket *socket, int transport)
13853 {
13854
13855 if (socket->type != transport) {
13856 socket->fd = -1;
13857 socket->type = transport;
13858 if (socket->tcptls_session) {
13859 ao2_ref(socket->tcptls_session, -1);
13860 socket->tcptls_session = NULL;
13861 }
13862 }
13863 }
13864
13865
13866 static int expire_register(const void *data)
13867 {
13868 struct sip_peer *peer = (struct sip_peer *)data;
13869
13870 if (!peer) {
13871 return 0;
13872 }
13873
13874 peer->expire = -1;
13875 peer->portinuri = 0;
13876
13877 destroy_association(peer);
13878 set_socket_transport(&peer->socket, peer->default_outbound_transport);
13879
13880 if (peer->socket.tcptls_session) {
13881 ao2_ref(peer->socket.tcptls_session, -1);
13882 peer->socket.tcptls_session = NULL;
13883 }
13884
13885 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
13886 register_peer_exten(peer, FALSE);
13887 ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
13888
13889
13890
13891
13892 if (peer->is_realtime) {
13893 ast_debug(3, "-REALTIME- peer expired registration. Name: %s. Realtime peer objects now %d\n", peer->name, rpeerobjs);
13894 }
13895
13896 if (peer->selfdestruct ||
13897 ast_test_flag(&peer->flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
13898 unlink_peer_from_tables(peer);
13899 } else if (!ast_sockaddr_isnull(&peer->addr)) {
13900
13901
13902
13903 ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
13904 }
13905
13906
13907
13908 memset(&peer->addr, 0, sizeof(peer->addr));
13909
13910 unref_peer(peer, "removing peer ref for expire_register");
13911
13912 return 0;
13913 }
13914
13915
13916 static int sip_poke_peer_s(const void *data)
13917 {
13918 struct sip_peer *peer = (struct sip_peer *)data;
13919 struct sip_peer *foundpeer;
13920
13921 peer->pokeexpire = -1;
13922
13923 foundpeer = ao2_find(peers, peer, OBJ_POINTER);
13924 if (!foundpeer) {
13925 unref_peer(peer, "removing poke peer ref");
13926 return 0;
13927 } else if (foundpeer->name != peer->name) {
13928 unref_peer(foundpeer, "removing above peer ref");
13929 unref_peer(peer, "removing poke peer ref");
13930 return 0;
13931 }
13932
13933 unref_peer(foundpeer, "removing above peer ref");
13934 sip_poke_peer(peer, 0);
13935 unref_peer(peer, "removing poke peer ref");
13936
13937 return 0;
13938 }
13939
13940
13941 static void reg_source_db(struct sip_peer *peer)
13942 {
13943 char data[256];
13944 struct ast_sockaddr sa;
13945 int expire;
13946 char full_addr[128];
13947 AST_DECLARE_APP_ARGS(args,
13948 AST_APP_ARG(addr);
13949 AST_APP_ARG(port);
13950 AST_APP_ARG(expiry_str);
13951 AST_APP_ARG(username);
13952 AST_APP_ARG(contact);
13953 );
13954
13955
13956 if (peer->rt_fromcontact && sip_cfg.peer_rtupdate) {
13957 return;
13958 }
13959 if (ast_db_get("SIP/Registry", peer->name, data, sizeof(data))) {
13960 return;
13961 }
13962
13963 AST_NONSTANDARD_RAW_ARGS(args, data, ':');
13964
13965 snprintf(full_addr, sizeof(full_addr), "%s:%s", args.addr, args.port);
13966
13967 if (!ast_sockaddr_parse(&sa, full_addr, 0)) {
13968 return;
13969 }
13970
13971 if (args.expiry_str) {
13972 expire = atoi(args.expiry_str);
13973 } else {
13974 return;
13975 }
13976
13977 if (args.username) {
13978 ast_string_field_set(peer, username, args.username);
13979 }
13980 if (args.contact) {
13981 ast_string_field_set(peer, fullcontact, args.contact);
13982 }
13983
13984 ast_debug(2, "SIP Seeding peer from astdb: '%s' at %s@%s for %d\n",
13985 peer->name, peer->username, ast_sockaddr_stringify_host(&sa), expire);
13986
13987 ast_sockaddr_copy(&peer->addr, &sa);
13988 if (peer->maxms) {
13989
13990 AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
13991 ast_random() % ((peer->qualifyfreq) ? peer->qualifyfreq : global_qualifyfreq) + 1,
13992 sip_poke_peer_s, peer,
13993 unref_peer(_data, "removing poke peer ref"),
13994 unref_peer(peer, "removing poke peer ref"),
13995 ref_peer(peer, "adding poke peer ref"));
13996 }
13997 AST_SCHED_REPLACE_UNREF(peer->expire, sched, (expire + 10) * 1000, expire_register, peer,
13998 unref_peer(_data, "remove registration ref"),
13999 unref_peer(peer, "remove registration ref"),
14000 ref_peer(peer, "add registration ref"));
14001 register_peer_exten(peer, TRUE);
14002 }
14003
14004
14005 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req)
14006 {
14007 char contact[SIPBUFSIZE];
14008 char *c;
14009
14010
14011 ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
14012 c = get_in_brackets(contact);
14013
14014
14015 ast_string_field_set(pvt, fullcontact, c);
14016
14017
14018 ast_string_field_set(pvt, okcontacturi, c);
14019
14020
14021
14022 return TRUE;
14023 }
14024
14025
14026
14027
14028
14029
14030
14031 static int parse_uri_legacy_check(char *uri, const char *scheme, char **user, char **pass, char **hostport, char **transport)
14032 {
14033 int ret = parse_uri(uri, scheme, user, pass, hostport, transport);
14034 if (sip_cfg.legacy_useroption_parsing) {
14035 char *p;
14036 if ((p = strchr(uri, (int)';'))) {
14037 *p = '\0';
14038 }
14039 }
14040 return ret;
14041 }
14042
14043 static int __set_address_from_contact(const char *fullcontact, struct ast_sockaddr *addr, int tcp)
14044 {
14045 char *hostport, *transport;
14046 char contact_buf[256];
14047 char *contact;
14048
14049
14050 ast_copy_string(contact_buf, fullcontact, sizeof(contact_buf));
14051 contact = contact_buf;
14052
14053
14054
14055
14056
14057
14058
14059
14060 if (parse_uri_legacy_check(contact, "sip:,sips:", &contact, NULL, &hostport,
14061 &transport)) {
14062 ast_log(LOG_WARNING, "Invalid contact uri %s (missing sip: or sips:), attempting to use anyway\n", fullcontact);
14063 }
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074 if (ast_strlen_zero(hostport)) {
14075 ast_log(LOG_WARNING, "Invalid URI: parse_uri failed to acquire hostport\n");
14076 return -1;
14077 }
14078
14079 if (ast_sockaddr_resolve_first_transport(addr, hostport, 0, get_transport_str2enum(transport))) {
14080 ast_log(LOG_WARNING, "Invalid host name in Contact: (can't "
14081 "resolve in DNS) : '%s'\n", hostport);
14082 return -1;
14083 }
14084
14085
14086 if (!ast_sockaddr_port(addr)) {
14087 ast_sockaddr_set_port(addr,
14088 (get_transport_str2enum(transport) ==
14089 SIP_TRANSPORT_TLS ||
14090 !strncasecmp(fullcontact, "sips", 4)) ?
14091 STANDARD_TLS_PORT : STANDARD_SIP_PORT);
14092 }
14093
14094 return 0;
14095 }
14096
14097
14098 static int set_address_from_contact(struct sip_pvt *pvt)
14099 {
14100 if (ast_test_flag(&pvt->flags[0], SIP_NAT_FORCE_RPORT)) {
14101
14102
14103
14104 pvt->sa = pvt->recv;
14105 return 0;
14106 }
14107
14108 return __set_address_from_contact(pvt->fullcontact, &pvt->sa, pvt->socket.type == SIP_TRANSPORT_TLS ? 1 : 0);
14109 }
14110
14111
14112 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *peer, struct sip_request *req)
14113 {
14114 char contact[SIPBUFSIZE];
14115 char data[SIPBUFSIZE];
14116 const char *expires = get_header(req, "Expires");
14117 int expire = atoi(expires);
14118 char *curi = NULL, *hostport = NULL, *transport = NULL;
14119 int transport_type;
14120 const char *useragent;
14121 struct ast_sockaddr oldsin, testsa;
14122 char *firstcuri = NULL;
14123 int start = 0;
14124 int wildcard_found = 0;
14125 int single_binding_found = 0;
14126
14127 ast_copy_string(contact, __get_header(req, "Contact", &start), sizeof(contact));
14128
14129 if (ast_strlen_zero(expires)) {
14130 char *s = strcasestr(contact, ";expires=");
14131 if (s) {
14132 expires = strsep(&s, ";");
14133 if (sscanf(expires + 9, "%30d", &expire) != 1) {
14134 expire = default_expiry;
14135 }
14136 } else {
14137
14138 expire = default_expiry;
14139 }
14140 }
14141
14142 copy_socket_data(&pvt->socket, &req->socket);
14143
14144 do {
14145
14146 curi = contact;
14147 if (strchr(contact, '<') == NULL)
14148 strsep(&curi, ";");
14149 curi = get_in_brackets(contact);
14150 if (!firstcuri) {
14151 firstcuri = ast_strdupa(curi);
14152 }
14153
14154 if (!strcasecmp(curi, "*")) {
14155 wildcard_found = 1;
14156 } else {
14157 single_binding_found = 1;
14158 }
14159
14160 if (wildcard_found && (ast_strlen_zero(expires) || expire != 0 || single_binding_found)) {
14161
14162
14163 return PARSE_REGISTER_FAILED;
14164 }
14165
14166 ast_copy_string(contact, __get_header(req, "Contact", &start), sizeof(contact));
14167 } while (!ast_strlen_zero(contact));
14168 curi = firstcuri;
14169
14170
14171
14172
14173
14174 if (ast_strlen_zero(curi) && ast_strlen_zero(expires)) {
14175
14176 if (peer->expire > -1 && !ast_strlen_zero(peer->fullcontact)) {
14177 pvt->expiry = ast_sched_when(sched, peer->expire);
14178 }
14179 return PARSE_REGISTER_QUERY;
14180 } else if (!strcasecmp(curi, "*") || !expire) {
14181
14182 AST_SCHED_DEL_UNREF(sched, peer->expire,
14183 unref_peer(peer, "remove register expire ref"));
14184 ast_verb(3, "Unregistered SIP '%s'\n", peer->name);
14185 expire_register(ref_peer(peer,"add ref for explicit expire_register"));
14186 return PARSE_REGISTER_UPDATE;
14187 }
14188
14189
14190 ast_string_field_set(peer, fullcontact, curi);
14191
14192
14193 ast_string_field_build(pvt, our_contact, "<%s>", curi);
14194
14195
14196 if (ast_strlen_zero(curi) || parse_uri_legacy_check(curi, "sip:,sips:", &curi, NULL, &hostport, &transport)) {
14197 ast_log(LOG_NOTICE, "Not a valid SIP contact (missing sip:/sips:) trying to use anyway\n");
14198 }
14199
14200
14201 if (!(transport_type = get_transport_str2enum(transport))) {
14202 transport_type = pvt->socket.type;
14203 }
14204
14205
14206
14207
14208 if ((peer->socket.type != transport_type) && (peer->transports & transport_type)) {
14209 set_socket_transport(&peer->socket, transport_type);
14210 }
14211
14212 oldsin = peer->addr;
14213
14214
14215 if (!ast_sockaddr_isnull(&peer->addr) && (!peer->is_realtime || ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS))) {
14216 ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
14217 }
14218
14219 if (!ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) && !ast_test_flag(&peer->flags[0], SIP_NAT_RPORT_PRESENT)) {
14220
14221 ast_debug(1, "Store REGISTER's Contact header for call routing.\n");
14222
14223
14224 if (ast_sockaddr_resolve_first_transport(&testsa, hostport, 0, peer->socket.type)) {
14225 ast_log(LOG_WARNING, "Invalid hostport '%s'\n", hostport);
14226 ast_string_field_set(peer, fullcontact, "");
14227 ast_string_field_set(pvt, our_contact, "");
14228 return PARSE_REGISTER_FAILED;
14229 }
14230
14231
14232
14233 peer->portinuri = ast_sockaddr_port(&testsa) ? TRUE : FALSE;
14234
14235 if (!ast_sockaddr_port(&testsa)) {
14236 ast_sockaddr_set_port(&testsa, default_sip_port(transport_type));
14237 }
14238
14239 ast_sockaddr_copy(&peer->addr, &testsa);
14240 } else {
14241
14242
14243 ast_debug(1, "Store REGISTER's src-IP:port for call routing.\n");
14244 peer->addr = pvt->recv;
14245 }
14246
14247
14248 if (ast_apply_ha(sip_cfg.contact_ha, &peer->addr) != AST_SENSE_ALLOW ||
14249 ast_apply_ha(peer->contactha, &peer->addr) != AST_SENSE_ALLOW) {
14250 ast_log(LOG_WARNING, "Domain '%s' disallowed by contact ACL (violating IP %s)\n", hostport,
14251 ast_sockaddr_stringify_addr(&testsa));
14252 ast_string_field_set(peer, fullcontact, "");
14253 ast_string_field_set(pvt, our_contact, "");
14254 return PARSE_REGISTER_DENIED;
14255 }
14256
14257
14258
14259
14260 if ((peer->socket.type == pvt->socket.type) &&
14261 !ast_sockaddr_cmp(&peer->addr, &pvt->recv)) {
14262 copy_socket_data(&peer->socket, &pvt->socket);
14263 }
14264
14265
14266 if (!peer->is_realtime || ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
14267 ao2_t_link(peers_by_ip, peer, "ao2_link into peers_by_ip table");
14268 }
14269
14270
14271 peer->sipoptions = pvt->sipoptions;
14272
14273 if (!ast_strlen_zero(curi) && ast_strlen_zero(peer->username)) {
14274 ast_string_field_set(peer, username, curi);
14275 }
14276
14277 AST_SCHED_DEL_UNREF(sched, peer->expire,
14278 unref_peer(peer, "remove register expire ref"));
14279
14280 if (expire > max_expiry) {
14281 expire = max_expiry;
14282 }
14283 if (expire < min_expiry) {
14284 expire = min_expiry;
14285 }
14286 if (peer->is_realtime && !ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
14287 peer->expire = -1;
14288 } else {
14289 peer->expire = ast_sched_add(sched, (expire + 10) * 1000, expire_register,
14290 ref_peer(peer, "add registration ref"));
14291 if (peer->expire == -1) {
14292 unref_peer(peer, "remote registration ref");
14293 }
14294 }
14295 pvt->expiry = expire;
14296 snprintf(data, sizeof(data), "%s:%d:%s:%s", ast_sockaddr_stringify(&peer->addr),
14297 expire, peer->username, peer->fullcontact);
14298
14299 if (!peer->rt_fromcontact || !sip_cfg.peer_rtupdate)
14300 ast_db_put("SIP/Registry", peer->name, data);
14301 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));
14302
14303
14304 if (VERBOSITY_ATLEAST(2) && ast_sockaddr_cmp(&peer->addr, &oldsin)) {
14305 ast_verbose(VERBOSE_PREFIX_3 "Registered SIP '%s' at %s\n", peer->name,
14306 ast_sockaddr_stringify(&peer->addr));
14307 }
14308 sip_poke_peer(peer, 0);
14309 register_peer_exten(peer, 1);
14310
14311
14312 useragent = get_header(req, "User-Agent");
14313 if (strcasecmp(useragent, peer->useragent)) {
14314 ast_string_field_set(peer, useragent, useragent);
14315 ast_verb(4, "Saved useragent \"%s\" for peer %s\n", peer->useragent, peer->name);
14316 }
14317 return PARSE_REGISTER_UPDATE;
14318 }
14319
14320
14321 static void free_old_route(struct sip_route *route)
14322 {
14323 struct sip_route *next;
14324
14325 while (route) {
14326 next = route->next;
14327 ast_free(route);
14328 route = next;
14329 }
14330 }
14331
14332
14333 static void list_route(struct sip_route *route)
14334 {
14335 if (!route) {
14336 ast_verbose("list_route: no route\n");
14337 } else {
14338 for (;route; route = route->next)
14339 ast_verbose("list_route: hop: <%s>\n", route->hop);
14340 }
14341 }
14342
14343
14344
14345 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards, int resp)
14346 {
14347 struct sip_route *thishop, *head, *tail;
14348 int start = 0;
14349 int len;
14350 const char *rr, *c;
14351
14352
14353 if (p->route && p->route_persistent) {
14354 ast_debug(1, "build_route: Retaining previous route: <%s>\n", p->route->hop);
14355 return;
14356 }
14357
14358 if (p->route) {
14359 free_old_route(p->route);
14360 p->route = NULL;
14361 }
14362
14363
14364
14365 if ((resp < 100) || (resp > 199)) {
14366 p->route_persistent = 1;
14367 }
14368
14369
14370
14371
14372
14373
14374 head = NULL;
14375 tail = head;
14376
14377 for (;;) {
14378
14379 char rr_copy[256];
14380 char *rr_copy_ptr;
14381 char *rr_iter;
14382 rr = __get_header(req, "Record-Route", &start);
14383 if (*rr == '\0') {
14384 break;
14385 }
14386 ast_copy_string(rr_copy, rr, sizeof(rr_copy));
14387 rr_copy_ptr = rr_copy;
14388 while ((rr_iter = strsep(&rr_copy_ptr, ","))) {
14389 char *uri = get_in_brackets(rr_iter);
14390 len = strlen(uri) + 1;
14391
14392 if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
14393
14394 ast_copy_string(thishop->hop, uri, len);
14395 ast_debug(2, "build_route: Record-Route hop: <%s>\n", thishop->hop);
14396
14397 if (backwards) {
14398
14399 thishop->next = head;
14400 head = thishop;
14401
14402 if (!tail) {
14403 tail = thishop;
14404 }
14405 } else {
14406 thishop->next = NULL;
14407
14408 if (tail) {
14409 tail->next = thishop;
14410 } else {
14411 head = thishop;
14412 }
14413 tail = thishop;
14414 }
14415 }
14416 }
14417 }
14418
14419
14420 if (!head || (!ast_strlen_zero(head->hop) && strstr(head->hop, ";lr") == NULL) ) {
14421
14422
14423 char *contact = ast_strdupa(get_header(req, "Contact"));
14424 if (!ast_strlen_zero(contact)) {
14425 ast_debug(2, "build_route: Contact hop: %s\n", contact);
14426
14427 c = get_in_brackets(contact);
14428 len = strlen(c) + 1;
14429 if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
14430
14431 ast_copy_string(thishop->hop, c, len);
14432 thishop->next = NULL;
14433
14434 if (tail) {
14435 tail->next = thishop;
14436 } else {
14437 head = thishop;
14438 }
14439 }
14440 }
14441 }
14442
14443
14444 p->route = head;
14445
14446
14447 if (sip_debug_test_pvt(p)) {
14448 list_route(p->route);
14449 }
14450 }
14451
14452
14453
14454
14455
14456
14457
14458 static void set_nonce_randdata(struct sip_pvt *p, int forceupdate)
14459 {
14460 if (p->stalenonce || forceupdate || ast_strlen_zero(p->randdata)) {
14461 ast_string_field_build(p, randdata, "%08lx", ast_random());
14462 p->stalenonce = 0;
14463 }
14464 }
14465
14466 AST_THREADSTORAGE(check_auth_buf);
14467 #define CHECK_AUTH_BUF_INITLEN 256
14468
14469
14470
14471
14472
14473
14474 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
14475 const char *secret, const char *md5secret, int sipmethod,
14476 const char *uri, enum xmittype reliable, int ignore)
14477 {
14478 const char *response;
14479 char *reqheader, *respheader;
14480 const char *authtoken;
14481 char a1_hash[256];
14482 char resp_hash[256]="";
14483 char *c;
14484 int wrongnonce = FALSE;
14485 int good_response;
14486 const char *usednonce = p->randdata;
14487 struct ast_str *buf;
14488 int res;
14489
14490
14491 enum keys { K_RESP, K_URI, K_USER, K_NONCE, K_LAST };
14492 struct x {
14493 const char *key;
14494 const char *s;
14495 } *i, keys[] = {
14496 [K_RESP] = { "response=", "" },
14497 [K_URI] = { "uri=", "" },
14498 [K_USER] = { "username=", "" },
14499 [K_NONCE] = { "nonce=", "" },
14500 [K_LAST] = { NULL, NULL}
14501 };
14502
14503
14504 if (ast_strlen_zero(secret) && ast_strlen_zero(md5secret))
14505 return AUTH_SUCCESSFUL;
14506
14507
14508
14509 response = "401 Unauthorized";
14510
14511
14512
14513
14514
14515 auth_headers(WWW_AUTH, &respheader, &reqheader);
14516
14517 authtoken = get_header(req, reqheader);
14518 if (ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
14519
14520
14521 if (!reliable) {
14522
14523
14524 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
14525
14526 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14527 }
14528 return AUTH_CHALLENGE_SENT;
14529 } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
14530
14531 set_nonce_randdata(p, 1);
14532 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
14533
14534 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14535 return AUTH_CHALLENGE_SENT;
14536 }
14537
14538
14539
14540
14541
14542
14543 if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN))) {
14544 return AUTH_SECRET_FAILED;
14545 }
14546
14547
14548 res = ast_str_set(&buf, 0, "%s", authtoken);
14549
14550 if (res == AST_DYNSTR_BUILD_FAILED) {
14551 return AUTH_SECRET_FAILED;
14552 }
14553
14554 c = buf->str;
14555
14556 while(c && *(c = ast_skip_blanks(c)) ) {
14557 for (i = keys; i->key != NULL; i++) {
14558 const char *separator = ",";
14559
14560 if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
14561 continue;
14562 }
14563
14564 c += strlen(i->key);
14565 if (*c == '"') {
14566 c++;
14567 separator = "\"";
14568 }
14569 i->s = c;
14570 strsep(&c, separator);
14571 break;
14572 }
14573 if (i->key == NULL) {
14574 strsep(&c, " ,");
14575 }
14576 }
14577
14578
14579 if (strcmp(username, keys[K_USER].s)) {
14580 ast_log(LOG_WARNING, "username mismatch, have <%s>, digest has <%s>\n",
14581 username, keys[K_USER].s);
14582
14583 return AUTH_USERNAME_MISMATCH;
14584 }
14585
14586
14587
14588 if (strcasecmp(p->randdata, keys[K_NONCE].s) || p->stalenonce) {
14589 wrongnonce = TRUE;
14590 usednonce = keys[K_NONCE].s;
14591 } else {
14592 p->stalenonce = 1;
14593 }
14594
14595 if (!ast_strlen_zero(md5secret)) {
14596 ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
14597 } else {
14598 char a1[256];
14599
14600 snprintf(a1, sizeof(a1), "%s:%s:%s", username, p->realm, secret);
14601 ast_md5_hash(a1_hash, a1);
14602 }
14603
14604
14605 {
14606 char a2[256];
14607 char a2_hash[256];
14608 char resp[256];
14609
14610 snprintf(a2, sizeof(a2), "%s:%s", sip_methods[sipmethod].text,
14611 S_OR(keys[K_URI].s, uri));
14612 ast_md5_hash(a2_hash, a2);
14613 snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, usednonce, a2_hash);
14614 ast_md5_hash(resp_hash, resp);
14615 }
14616
14617 good_response = keys[K_RESP].s &&
14618 !strncasecmp(keys[K_RESP].s, resp_hash, strlen(resp_hash));
14619 if (wrongnonce) {
14620 if (good_response) {
14621 if (sipdebug)
14622 ast_log(LOG_NOTICE, "Correct auth, but based on stale nonce received from '%s'\n", get_header(req, "From"));
14623
14624 set_nonce_randdata(p, 0);
14625 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, TRUE);
14626 } else {
14627
14628 if (!req->ignore) {
14629 if (sipdebug) {
14630 ast_log(LOG_NOTICE, "Bad authentication received from '%s'\n", get_header(req, "To"));
14631 }
14632 set_nonce_randdata(p, 1);
14633 } else {
14634 if (sipdebug) {
14635 ast_log(LOG_NOTICE, "Duplicate authentication received from '%s'\n", get_header(req, "To"));
14636 }
14637 }
14638 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
14639 }
14640
14641
14642 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14643 return AUTH_CHALLENGE_SENT;
14644 }
14645 if (good_response) {
14646 append_history(p, "AuthOK", "Auth challenge successful for %s", username);
14647 return AUTH_SUCCESSFUL;
14648 }
14649
14650
14651
14652
14653
14654
14655 return AUTH_SECRET_FAILED;
14656 }
14657
14658
14659 static void sip_peer_hold(struct sip_pvt *p, int hold)
14660 {
14661 if (!p->relatedpeer) {
14662 return;
14663 }
14664
14665
14666 ast_atomic_fetchadd_int(&p->relatedpeer->onHold, (hold ? +1 : -1));
14667
14668
14669 ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", p->relatedpeer->name);
14670
14671 return;
14672 }
14673
14674
14675 static void mwi_event_cb(const struct ast_event *event, void *userdata)
14676 {
14677 struct sip_peer *peer = userdata;
14678
14679 sip_send_mwi_to_peer(peer, 0);
14680 }
14681
14682 static void network_change_event_subscribe(void)
14683 {
14684 if (!network_change_event_subscription) {
14685 network_change_event_subscription = ast_event_subscribe(AST_EVENT_NETWORK_CHANGE,
14686 network_change_event_cb, "SIP Network Change", NULL, AST_EVENT_IE_END);
14687 }
14688 }
14689
14690 static void network_change_event_unsubscribe(void)
14691 {
14692 if (network_change_event_subscription) {
14693 network_change_event_subscription = ast_event_unsubscribe(network_change_event_subscription);
14694 }
14695 }
14696
14697 static int network_change_event_sched_cb(const void *data)
14698 {
14699 network_change_event_sched_id = -1;
14700 sip_send_all_registers();
14701 sip_send_all_mwi_subscriptions();
14702 return 0;
14703 }
14704
14705 static void network_change_event_cb(const struct ast_event *event, void *userdata)
14706 {
14707 ast_debug(1, "SIP, got a network change event, renewing all SIP registrations.\n");
14708 if (network_change_event_sched_id == -1) {
14709 network_change_event_sched_id = ast_sched_add(sched, 1000, network_change_event_sched_cb, NULL);
14710 }
14711 }
14712
14713 static void cb_extensionstate_destroy(int id, void *data)
14714 {
14715 struct sip_pvt *p = data;
14716
14717 dialog_unref(p, "the extensionstate containing this dialog ptr was destroyed");
14718 }
14719
14720
14721
14722
14723 static int cb_extensionstate(char *context, char* exten, int state, void *data)
14724 {
14725 struct sip_pvt *p = data;
14726
14727 sip_pvt_lock(p);
14728
14729 switch(state) {
14730 case AST_EXTENSION_DEACTIVATED:
14731 case AST_EXTENSION_REMOVED:
14732 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14733 ast_verb(2, "Extension state: Watcher for hint %s %s. Notify User %s\n", exten, state == AST_EXTENSION_DEACTIVATED ? "deactivated" : "removed", p->username);
14734 p->subscribed = NONE;
14735 append_history(p, "Subscribestatus", "%s", state == AST_EXTENSION_REMOVED ? "HintRemoved" : "Deactivated");
14736 break;
14737 default:
14738 p->laststate = state;
14739 break;
14740 }
14741 if (p->subscribed != NONE) {
14742 if (!p->pendinginvite) {
14743 transmit_state_notify(p, state, 1, FALSE);
14744 } else {
14745
14746
14747 ast_set_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
14748 }
14749 }
14750 ast_verb(2, "Extension Changed %s[%s] new state %s for Notify User %s %s\n", exten, context, ast_extension_state2str(state), p->username,
14751 ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE) ? "(queued)" : "");
14752
14753 sip_pvt_unlock(p);
14754
14755 return 0;
14756 }
14757
14758
14759
14760
14761 static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable)
14762 {
14763
14764
14765 const char *response = "401 Unauthorized";
14766 const char *reqheader = "Authorization";
14767 const char *respheader = "WWW-Authenticate";
14768 const char *authtoken;
14769 struct ast_str *buf;
14770 char *c;
14771
14772
14773 enum keys { K_NONCE, K_LAST };
14774 struct x {
14775 const char *key;
14776 const char *s;
14777 } *i, keys[] = {
14778 [K_NONCE] = { "nonce=", "" },
14779 [K_LAST] = { NULL, NULL}
14780 };
14781
14782 authtoken = get_header(req, reqheader);
14783 if (req->ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
14784
14785
14786 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
14787
14788 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14789 return;
14790 } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
14791
14792 set_nonce_randdata(p, 1);
14793 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
14794
14795 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14796 return;
14797 }
14798
14799 if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN))) {
14800 transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
14801 return;
14802 }
14803
14804
14805 if (ast_str_set(&buf, 0, "%s", authtoken) == AST_DYNSTR_BUILD_FAILED) {
14806 transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
14807 return;
14808 }
14809
14810 c = buf->str;
14811
14812 while (c && *(c = ast_skip_blanks(c))) {
14813 for (i = keys; i->key != NULL; i++) {
14814 const char *separator = ",";
14815
14816 if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
14817 continue;
14818 }
14819
14820 c += strlen(i->key);
14821 if (*c == '"') {
14822 c++;
14823 separator = "\"";
14824 }
14825 i->s = c;
14826 strsep(&c, separator);
14827 break;
14828 }
14829 if (i->key == NULL) {
14830 strsep(&c, " ,");
14831 }
14832 }
14833
14834
14835 if (strcasecmp(p->randdata, keys[K_NONCE].s)) {
14836 if (!req->ignore) {
14837 set_nonce_randdata(p, 1);
14838 }
14839 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
14840
14841
14842 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14843 } else {
14844 transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
14845 }
14846 }
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862 static char *terminate_uri(char *uri)
14863 {
14864 char *t = uri;
14865 while (*t && *t > ' ' && *t != ';') {
14866 t++;
14867 }
14868 *t = '\0';
14869 return uri;
14870 }
14871
14872
14873
14874
14875
14876
14877
14878 static void extract_host_from_hostport(char **hostport)
14879 {
14880 char *dont_care;
14881 ast_sockaddr_split_hostport(*hostport, hostport, &dont_care, PARSE_PORT_IGNORE);
14882 }
14883
14884
14885
14886 static void update_peer_lastmsgssent(struct sip_peer *peer, int value, int locked)
14887 {
14888 if (!locked) {
14889 ao2_lock(peer);
14890 }
14891 peer->lastmsgssent = value;
14892 if (!locked) {
14893 ao2_unlock(peer);
14894 }
14895 }
14896
14897
14898
14899
14900
14901
14902
14903 static enum check_auth_result register_verify(struct sip_pvt *p, struct ast_sockaddr *addr,
14904 struct sip_request *req, const char *uri)
14905 {
14906 enum check_auth_result res = AUTH_NOT_FOUND;
14907 struct sip_peer *peer;
14908 char tmp[256];
14909 char *c, *name, *unused_password, *domain;
14910 char *uri2 = ast_strdupa(uri);
14911 int send_mwi = 0;
14912
14913 terminate_uri(uri2);
14914
14915 ast_copy_string(tmp, get_header(req, "To"), sizeof(tmp));
14916
14917 c = get_in_brackets(tmp);
14918 c = remove_uri_parameters(c);
14919
14920 if (parse_uri_legacy_check(c, "sip:,sips:", &name, &unused_password, &domain, NULL)) {
14921 ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, ast_sockaddr_stringify_addr(addr));
14922 return -1;
14923 }
14924
14925 SIP_PEDANTIC_DECODE(name);
14926 SIP_PEDANTIC_DECODE(domain);
14927
14928 extract_host_from_hostport(&domain);
14929
14930 if (ast_strlen_zero(domain)) {
14931
14932 transmit_response(p, "404 Not found", &p->initreq);
14933 return AUTH_UNKNOWN_DOMAIN;
14934 }
14935
14936 if (ast_strlen_zero(name)) {
14937
14938
14939
14940
14941
14942
14943
14944 name = domain;
14945 }
14946
14947
14948
14949
14950
14951 if (!AST_LIST_EMPTY(&domain_list)) {
14952 if (!check_sip_domain(domain, NULL, 0)) {
14953 if (sip_cfg.alwaysauthreject) {
14954 transmit_fake_auth_response(p, SIP_REGISTER, &p->initreq, XMIT_UNRELIABLE);
14955 } else {
14956 transmit_response(p, "404 Not found (unknown domain)", &p->initreq);
14957 }
14958 return AUTH_UNKNOWN_DOMAIN;
14959 }
14960 }
14961
14962 ast_string_field_set(p, exten, name);
14963 build_contact(p);
14964 if (req->ignore) {
14965
14966 const char *expires = get_header(req, "Expires");
14967 int expire = atoi(expires);
14968
14969 if (ast_strlen_zero(expires)) {
14970 if ((expires = strcasestr(get_header(req, "Contact"), ";expires="))) {
14971 expire = atoi(expires + 9);
14972 }
14973 }
14974 if (!ast_strlen_zero(expires) && expire == 0) {
14975 transmit_response_with_date(p, "200 OK", req);
14976 return 0;
14977 }
14978 }
14979 peer = find_peer(name, NULL, TRUE, FINDPEERS, FALSE, 0);
14980
14981 if (!(peer && ast_apply_ha(peer->ha, addr))) {
14982
14983 if (peer) {
14984 unref_peer(peer, "register_verify: unref_peer: from find_peer operation");
14985 peer = NULL;
14986 res = AUTH_ACL_FAILED;
14987 } else {
14988 res = AUTH_NOT_FOUND;
14989 }
14990 }
14991
14992 if (peer) {
14993 ao2_lock(peer);
14994 if (!peer->host_dynamic) {
14995 ast_log(LOG_ERROR, "Peer '%s' is trying to register, but not configured as host=dynamic\n", peer->name);
14996 res = AUTH_PEER_NOT_DYNAMIC;
14997 } else {
14998 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_NAT_FORCE_RPORT);
14999 if (!(res = check_auth(p, req, peer->name, peer->secret, peer->md5secret, SIP_REGISTER, uri2, XMIT_UNRELIABLE, req->ignore))) {
15000 if (sip_cancel_destroy(p))
15001 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
15002
15003 if (check_request_transport(peer, req)) {
15004 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
15005 transmit_response_with_date(p, "403 Forbidden", req);
15006 res = AUTH_BAD_TRANSPORT;
15007 } else {
15008
15009
15010
15011 switch (parse_register_contact(p, peer, req)) {
15012 case PARSE_REGISTER_DENIED:
15013 ast_log(LOG_WARNING, "Registration denied because of contact ACL\n");
15014 transmit_response_with_date(p, "603 Denied", req);
15015 res = 0;
15016 break;
15017 case PARSE_REGISTER_FAILED:
15018 ast_log(LOG_WARNING, "Failed to parse contact info\n");
15019 transmit_response_with_date(p, "400 Bad Request", req);
15020 res = 0;
15021 break;
15022 case PARSE_REGISTER_QUERY:
15023 ast_string_field_set(p, fullcontact, peer->fullcontact);
15024 transmit_response_with_date(p, "200 OK", req);
15025 res = 0;
15026 break;
15027 case PARSE_REGISTER_UPDATE:
15028 ast_string_field_set(p, fullcontact, peer->fullcontact);
15029 update_peer(peer, p->expiry);
15030
15031 transmit_response_with_date(p, "200 OK", req);
15032 send_mwi = 1;
15033 res = 0;
15034 break;
15035 }
15036 }
15037
15038 }
15039 }
15040 ao2_unlock(peer);
15041 }
15042 if (!peer && sip_cfg.autocreatepeer) {
15043
15044 peer = temp_peer(name);
15045 if (peer) {
15046 ao2_t_link(peers, peer, "link peer into peer table");
15047 if (!ast_sockaddr_isnull(&peer->addr)) {
15048 ao2_t_link(peers_by_ip, peer, "link peer into peers-by-ip table");
15049 }
15050 ao2_lock(peer);
15051 if (sip_cancel_destroy(p))
15052 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
15053 switch (parse_register_contact(p, peer, req)) {
15054 case PARSE_REGISTER_DENIED:
15055 ast_log(LOG_WARNING, "Registration denied because of contact ACL\n");
15056 transmit_response_with_date(p, "403 Forbidden (ACL)", req);
15057 res = 0;
15058 break;
15059 case PARSE_REGISTER_FAILED:
15060 ast_log(LOG_WARNING, "Failed to parse contact info\n");
15061 transmit_response_with_date(p, "400 Bad Request", req);
15062 res = 0;
15063 break;
15064 case PARSE_REGISTER_QUERY:
15065 ast_string_field_set(p, fullcontact, peer->fullcontact);
15066 transmit_response_with_date(p, "200 OK", req);
15067 send_mwi = 1;
15068 res = 0;
15069 break;
15070 case PARSE_REGISTER_UPDATE:
15071 ast_string_field_set(p, fullcontact, peer->fullcontact);
15072
15073 transmit_response_with_date(p, "200 OK", req);
15074 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));
15075 send_mwi = 1;
15076 res = 0;
15077 break;
15078 }
15079 ao2_unlock(peer);
15080 }
15081 }
15082 if (!res) {
15083 if (send_mwi) {
15084 sip_send_mwi_to_peer(peer, 0);
15085 } else {
15086 update_peer_lastmsgssent(peer, -1, 0);
15087 }
15088 ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
15089 }
15090 if (res < 0) {
15091 switch (res) {
15092 case AUTH_SECRET_FAILED:
15093
15094 transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
15095 if (global_authfailureevents) {
15096 const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
15097 const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
15098 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
15099 "ChannelType: SIP\r\n"
15100 "Peer: SIP/%s\r\n"
15101 "PeerStatus: Rejected\r\n"
15102 "Cause: AUTH_SECRET_FAILED\r\n"
15103 "Address: %s\r\n"
15104 "Port: %s\r\n",
15105 name, peer_addr, peer_port);
15106 }
15107 break;
15108 case AUTH_USERNAME_MISMATCH:
15109
15110
15111
15112
15113 case AUTH_NOT_FOUND:
15114 case AUTH_PEER_NOT_DYNAMIC:
15115 case AUTH_ACL_FAILED:
15116 if (sip_cfg.alwaysauthreject) {
15117 transmit_fake_auth_response(p, SIP_REGISTER, &p->initreq, XMIT_UNRELIABLE);
15118 if (global_authfailureevents) {
15119 const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
15120 const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
15121 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
15122 "ChannelType: SIP\r\n"
15123 "Peer: SIP/%s\r\n"
15124 "PeerStatus: Rejected\r\n"
15125 "Cause: %s\r\n"
15126 "Address: %s\r\n"
15127 "Port: %s\r\n",
15128 name,
15129 res == AUTH_PEER_NOT_DYNAMIC ? "AUTH_PEER_NOT_DYNAMIC" : "URI_NOT_FOUND",
15130 peer_addr, peer_port);
15131 }
15132 } else {
15133
15134 if (res == AUTH_PEER_NOT_DYNAMIC) {
15135 transmit_response(p, "403 Forbidden", &p->initreq);
15136 if (global_authfailureevents) {
15137 const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
15138 const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
15139 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
15140 "ChannelType: SIP\r\n"
15141 "Peer: SIP/%s\r\n"
15142 "PeerStatus: Rejected\r\n"
15143 "Cause: AUTH_PEER_NOT_DYNAMIC\r\n"
15144 "Address: %s\r\n"
15145 "Port: %s\r\n",
15146 name, peer_addr, peer_port);
15147 }
15148 } else {
15149 transmit_response(p, "404 Not found", &p->initreq);
15150 if (global_authfailureevents) {
15151 const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
15152 const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
15153 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
15154 "ChannelType: SIP\r\n"
15155 "Peer: SIP/%s\r\n"
15156 "PeerStatus: Rejected\r\n"
15157 "Cause: %s\r\n"
15158 "Address: %s\r\n"
15159 "Port: %s\r\n",
15160 name,
15161 (res == AUTH_USERNAME_MISMATCH) ? "AUTH_USERNAME_MISMATCH" : "URI_NOT_FOUND",
15162 peer_addr, peer_port);
15163 }
15164 }
15165 }
15166 break;
15167 case AUTH_BAD_TRANSPORT:
15168 default:
15169 break;
15170 }
15171 }
15172 if (peer) {
15173 unref_peer(peer, "register_verify: unref_peer: tossing stack peer pointer at end of func");
15174 }
15175
15176 return res;
15177 }
15178
15179
15180 static void sip_set_redirstr(struct sip_pvt *p, char *reason) {
15181
15182 if (!strcmp(reason, "unknown")) {
15183 ast_string_field_set(p, redircause, "UNKNOWN");
15184 } else if (!strcmp(reason, "user-busy")) {
15185 ast_string_field_set(p, redircause, "BUSY");
15186 } else if (!strcmp(reason, "no-answer")) {
15187 ast_string_field_set(p, redircause, "NOANSWER");
15188 } else if (!strcmp(reason, "unavailable")) {
15189 ast_string_field_set(p, redircause, "UNREACHABLE");
15190 } else if (!strcmp(reason, "unconditional")) {
15191 ast_string_field_set(p, redircause, "UNCONDITIONAL");
15192 } else if (!strcmp(reason, "time-of-day")) {
15193 ast_string_field_set(p, redircause, "UNKNOWN");
15194 } else if (!strcmp(reason, "do-not-disturb")) {
15195 ast_string_field_set(p, redircause, "UNKNOWN");
15196 } else if (!strcmp(reason, "deflection")) {
15197 ast_string_field_set(p, redircause, "UNKNOWN");
15198 } else if (!strcmp(reason, "follow-me")) {
15199 ast_string_field_set(p, redircause, "UNKNOWN");
15200 } else if (!strcmp(reason, "out-of-service")) {
15201 ast_string_field_set(p, redircause, "UNREACHABLE");
15202 } else if (!strcmp(reason, "away")) {
15203 ast_string_field_set(p, redircause, "UNREACHABLE");
15204 } else {
15205 ast_string_field_set(p, redircause, "UNKNOWN");
15206 }
15207 }
15208
15209
15210
15211
15212
15213 static int get_pai(struct sip_pvt *p, struct sip_request *req)
15214 {
15215 char pai[256];
15216 char privacy[64];
15217 char *cid_num = NULL;
15218 char *cid_name = NULL;
15219 char emptyname[1] = "";
15220 int callingpres = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
15221 char *uri = NULL;
15222 int is_anonymous = 0, do_update = 1, no_name = 0;
15223
15224 ast_copy_string(pai, get_header(req, "P-Asserted-Identity"), sizeof(pai));
15225
15226 if (ast_strlen_zero(pai)) {
15227 return 0;
15228 }
15229
15230
15231 if (get_name_and_number(pai, &cid_name, &cid_num)) {
15232 return 0;
15233 }
15234
15235 if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(cid_num)) {
15236 ast_shrink_phone_number(cid_num);
15237 }
15238
15239 uri = get_in_brackets(pai);
15240 if (!strncasecmp(uri, "sip:anonymous@anonymous.invalid", 31)) {
15241 callingpres = AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
15242
15243
15244
15245 ast_free(cid_num);
15246 is_anonymous = 1;
15247 cid_num = (char *)p->cid_num;
15248 }
15249
15250 ast_copy_string(privacy, get_header(req, "Privacy"), sizeof(privacy));
15251 if (!ast_strlen_zero(privacy) && !strncmp(privacy, "id", 2)) {
15252 callingpres = AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
15253 }
15254 if (!cid_name) {
15255 no_name = 1;
15256 cid_name = (char *)emptyname;
15257 }
15258
15259 if (!strcasecmp(p->cid_num, cid_num) && !strcasecmp(p->cid_name, cid_name) && p->callingpres == callingpres) {
15260 do_update = 0;
15261 } else {
15262
15263 ast_string_field_set(p, cid_num, cid_num);
15264 ast_string_field_set(p, cid_name, cid_name);
15265 p->callingpres = callingpres;
15266
15267 if (p->owner) {
15268 ast_set_callerid(p->owner, cid_num, cid_name, NULL);
15269 p->owner->caller.id.name.presentation = callingpres;
15270 p->owner->caller.id.number.presentation = callingpres;
15271 }
15272 }
15273
15274
15275 if (!is_anonymous) {
15276 ast_free(cid_num);
15277 }
15278 if (!no_name) {
15279 ast_free(cid_name);
15280 }
15281
15282 return do_update;
15283 }
15284
15285
15286
15287
15288
15289 static int get_rpid(struct sip_pvt *p, struct sip_request *oreq)
15290 {
15291 char tmp[256];
15292 struct sip_request *req;
15293 char *cid_num = "";
15294 char *cid_name = "";
15295 int callingpres = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
15296 char *privacy = "";
15297 char *screen = "";
15298 char *start, *end;
15299
15300 if (!ast_test_flag(&p->flags[0], SIP_TRUSTRPID))
15301 return 0;
15302 req = oreq;
15303 if (!req)
15304 req = &p->initreq;
15305 ast_copy_string(tmp, get_header(req, "Remote-Party-ID"), sizeof(tmp));
15306 if (ast_strlen_zero(tmp)) {
15307 return get_pai(p, req);
15308 }
15309
15310 start = tmp;
15311 if (*start == '"') {
15312 *start++ = '\0';
15313 end = strchr(start, '"');
15314 if (!end)
15315 return 0;
15316 *end++ = '\0';
15317 cid_name = start;
15318 start = ast_skip_blanks(end);
15319 }
15320
15321 if (*start != '<')
15322 return 0;
15323 *start++ = '\0';
15324 end = strchr(start, '@');
15325 if (!end)
15326 return 0;
15327 *end++ = '\0';
15328 if (strncasecmp(start, "sip:", 4))
15329 return 0;
15330 cid_num = start + 4;
15331 if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(cid_num))
15332 ast_shrink_phone_number(cid_num);
15333 start = end;
15334
15335 end = strchr(start, '>');
15336 if (!end)
15337 return 0;
15338 *end++ = '\0';
15339 if (*end) {
15340 start = end;
15341 if (*start != ';')
15342 return 0;
15343 *start++ = '\0';
15344 while (!ast_strlen_zero(start)) {
15345 end = strchr(start, ';');
15346 if (end)
15347 *end++ = '\0';
15348 if (!strncasecmp(start, "privacy=", 8))
15349 privacy = start + 8;
15350 else if (!strncasecmp(start, "screen=", 7))
15351 screen = start + 7;
15352 start = end;
15353 }
15354
15355 if (!strcasecmp(privacy, "full")) {
15356 if (!strcasecmp(screen, "yes"))
15357 callingpres = AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN;
15358 else if (!strcasecmp(screen, "no"))
15359 callingpres = AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
15360 } else {
15361 if (!strcasecmp(screen, "yes"))
15362 callingpres = AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN;
15363 else if (!strcasecmp(screen, "no"))
15364 callingpres = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
15365 }
15366 }
15367
15368
15369 if (!strcasecmp(p->cid_num, cid_num) && !strcasecmp(p->cid_name, cid_name) && p->callingpres == callingpres)
15370 return 0;
15371
15372 ast_string_field_set(p, cid_num, cid_num);
15373 ast_string_field_set(p, cid_name, cid_name);
15374 p->callingpres = callingpres;
15375
15376 if (p->owner) {
15377 ast_set_callerid(p->owner, cid_num, cid_name, NULL);
15378 p->owner->caller.id.name.presentation = callingpres;
15379 p->owner->caller.id.number.presentation = callingpres;
15380 }
15381
15382 return 1;
15383 }
15384
15385
15386 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq, char **name, char **number, int *reason)
15387 {
15388 char tmp[256], *exten, *rexten, *rdomain, *rname = NULL;
15389 char *params, *reason_param = NULL;
15390 struct sip_request *req;
15391
15392 req = oreq ? oreq : &p->initreq;
15393
15394 ast_copy_string(tmp, get_header(req, "Diversion"), sizeof(tmp));
15395 if (ast_strlen_zero(tmp))
15396 return -1;
15397
15398 if ((params = strchr(tmp, '>'))) {
15399 params = strchr(params, ';');
15400 }
15401
15402 exten = get_in_brackets(tmp);
15403 if (!strncasecmp(exten, "sip:", 4)) {
15404 exten += 4;
15405 } else if (!strncasecmp(exten, "sips:", 5)) {
15406 exten += 5;
15407 } else {
15408 ast_log(LOG_WARNING, "Huh? Not an RDNIS SIP header (%s)?\n", exten);
15409 return -1;
15410 }
15411
15412
15413 if (params) {
15414 *params = '\0';
15415 params++;
15416 while (*params == ';' || *params == ' ')
15417 params++;
15418
15419 if ((reason_param = strcasestr(params, "reason="))) {
15420 char *end;
15421 reason_param+=7;
15422 if ((end = strchr(reason_param, ';'))) {
15423 *end = '\0';
15424 }
15425
15426 if (*reason_param == '"')
15427 reason_param = ast_strip_quoted(reason_param, "\"", "\"");
15428 if (!ast_strlen_zero(reason_param)) {
15429 sip_set_redirstr(p, reason_param);
15430 if (p->owner) {
15431 pbx_builtin_setvar_helper(p->owner, "__PRIREDIRECTREASON", p->redircause);
15432 pbx_builtin_setvar_helper(p->owner, "__SIPREDIRECTREASON", reason_param);
15433 }
15434 }
15435 }
15436 }
15437
15438 rdomain = exten;
15439 rexten = strsep(&rdomain, "@");
15440 if (p->owner)
15441 pbx_builtin_setvar_helper(p->owner, "__SIPRDNISDOMAIN", rdomain);
15442
15443 if (sip_debug_test_pvt(p))
15444 ast_verbose("RDNIS for this call is %s (reason %s)\n", exten, S_OR(reason_param, ""));
15445
15446
15447
15448 if (*tmp == '\"') {
15449 char *end_quote;
15450 rname = tmp + 1;
15451 end_quote = strchr(rname, '\"');
15452 if (end_quote) {
15453 *end_quote = '\0';
15454 }
15455 }
15456
15457 if (number) {
15458 *number = ast_strdup(rexten);
15459 }
15460
15461 if (name && rname) {
15462 *name = ast_strdup(rname);
15463 }
15464
15465 if (reason && !ast_strlen_zero(reason_param)) {
15466 *reason = sip_reason_str_to_code(reason_param);
15467 }
15468
15469 return 0;
15470 }
15471
15472
15473
15474
15475
15476
15477
15478
15479
15480
15481
15482
15483
15484
15485
15486 static enum sip_get_dest_result get_destination(struct sip_pvt *p, struct sip_request *oreq, int *cc_recall_core_id)
15487 {
15488 char tmp[256] = "", *uri, *unused_password, *domain;
15489 char tmpf[256] = "", *from = NULL;
15490 struct sip_request *req;
15491 char *decoded_uri;
15492
15493 req = oreq;
15494 if (!req) {
15495 req = &p->initreq;
15496 }
15497
15498
15499 if (req->rlPart2)
15500 ast_copy_string(tmp, REQ_OFFSET_TO_STR(req, rlPart2), sizeof(tmp));
15501
15502 uri = ast_strdupa(get_in_brackets(tmp));
15503
15504 if (parse_uri_legacy_check(uri, "sip:,sips:", &uri, &unused_password, &domain, NULL)) {
15505 ast_log(LOG_WARNING, "Not a SIP header (%s)?\n", uri);
15506 return SIP_GET_DEST_INVALID_URI;
15507 }
15508
15509 SIP_PEDANTIC_DECODE(domain);
15510 SIP_PEDANTIC_DECODE(uri);
15511
15512 extract_host_from_hostport(&domain);
15513
15514 if (ast_strlen_zero(uri)) {
15515
15516
15517
15518
15519
15520 uri = "s";
15521 }
15522
15523 ast_string_field_set(p, domain, domain);
15524
15525
15526
15527
15528
15529 ast_copy_string(tmpf, get_header(req, "From"), sizeof(tmpf));
15530 if (!ast_strlen_zero(tmpf)) {
15531 from = get_in_brackets(tmpf);
15532 if (parse_uri_legacy_check(from, "sip:,sips:", &from, NULL, &domain, NULL)) {
15533 ast_log(LOG_WARNING, "Not a SIP header (%s)?\n", from);
15534 return SIP_GET_DEST_INVALID_URI;
15535 }
15536
15537 SIP_PEDANTIC_DECODE(from);
15538 SIP_PEDANTIC_DECODE(domain);
15539
15540 extract_host_from_hostport(&domain);
15541
15542 ast_string_field_set(p, fromdomain, domain);
15543 }
15544
15545 if (!AST_LIST_EMPTY(&domain_list)) {
15546 char domain_context[AST_MAX_EXTENSION];
15547
15548 domain_context[0] = '\0';
15549 if (!check_sip_domain(p->domain, domain_context, sizeof(domain_context))) {
15550 if (!sip_cfg.allow_external_domains && (req->method == SIP_INVITE || req->method == SIP_REFER)) {
15551 ast_debug(1, "Got SIP %s to non-local domain '%s'; refusing request.\n", sip_methods[req->method].text, p->domain);
15552 return SIP_GET_DEST_REFUSED;
15553 }
15554 }
15555
15556
15557 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_HAVEPEERCONTEXT) && !ast_strlen_zero(domain_context)) {
15558 ast_string_field_set(p, context, domain_context);
15559 }
15560 }
15561
15562
15563 if (req->method == SIP_SUBSCRIBE && !ast_strlen_zero(p->subscribecontext)) {
15564 ast_string_field_set(p, context, p->subscribecontext);
15565 }
15566
15567 if (sip_debug_test_pvt(p)) {
15568 ast_verbose("Looking for %s in %s (domain %s)\n", uri, p->context, p->domain);
15569 }
15570
15571
15572
15573 decoded_uri = ast_strdupa(uri);
15574 ast_uri_decode(decoded_uri);
15575
15576
15577 if (req->method == SIP_SUBSCRIBE) {
15578 char hint[AST_MAX_EXTENSION];
15579 int which = 0;
15580 if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, uri) ||
15581 (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, decoded_uri) && (which = 1))) {
15582 if (!oreq) {
15583 ast_string_field_set(p, exten, which ? decoded_uri : uri);
15584 }
15585 return SIP_GET_DEST_EXTEN_FOUND;
15586 } else {
15587 return SIP_GET_DEST_EXTEN_NOT_FOUND;
15588 }
15589 } else {
15590 struct ast_cc_agent *agent;
15591
15592
15593
15594 if (ast_exists_extension(NULL, p->context, uri, 1, S_OR(p->cid_num, from))) {
15595 if (!oreq) {
15596 ast_string_field_set(p, exten, uri);
15597 }
15598 return SIP_GET_DEST_EXTEN_FOUND;
15599 }
15600 if (ast_exists_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from))
15601 || !strcmp(decoded_uri, ast_pickup_ext())) {
15602 if (!oreq) {
15603 ast_string_field_set(p, exten, decoded_uri);
15604 }
15605 return SIP_GET_DEST_EXTEN_FOUND;
15606 }
15607 if ((agent = find_sip_cc_agent_by_notify_uri(tmp))) {
15608 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
15609
15610
15611
15612 ast_string_field_set(p, exten, agent_pvt->original_exten);
15613
15614
15615
15616 ast_cc_agent_recalling(agent->core_id, "SIP caller %s is attempting recall",
15617 agent->device_name);
15618 if (cc_recall_core_id) {
15619 *cc_recall_core_id = agent->core_id;
15620 }
15621 ao2_ref(agent, -1);
15622 return SIP_GET_DEST_EXTEN_FOUND;
15623 }
15624 }
15625
15626 if (ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP)
15627 && (ast_canmatch_extension(NULL, p->context, uri, 1, S_OR(p->cid_num, from))
15628 || ast_canmatch_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from))
15629 || !strncmp(decoded_uri, ast_pickup_ext(), strlen(decoded_uri)))) {
15630
15631 return SIP_GET_DEST_EXTEN_MATCHMORE;
15632 }
15633
15634 return SIP_GET_DEST_EXTEN_NOT_FOUND;
15635 }
15636
15637
15638
15639
15640 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag)
15641 {
15642 struct sip_pvt *sip_pvt_ptr;
15643 struct sip_pvt tmp_dialog = {
15644 .callid = callid,
15645 };
15646
15647 if (totag) {
15648 ast_debug(4, "Looking for callid %s (fromtag %s totag %s)\n", callid, fromtag ? fromtag : "<no fromtag>", totag ? totag : "<no totag>");
15649 }
15650
15651
15652
15653 sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find of dialog in dialogs table");
15654 if (sip_pvt_ptr) {
15655
15656 sip_pvt_lock(sip_pvt_ptr);
15657 if (sip_cfg.pedanticsipchecking) {
15658 unsigned char frommismatch = 0, tomismatch = 0;
15659
15660 if (ast_strlen_zero(fromtag)) {
15661 sip_pvt_unlock(sip_pvt_ptr);
15662 ast_debug(4, "Matched %s call for callid=%s - no from tag specified, pedantic check fails\n",
15663 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
15664 return NULL;
15665 }
15666
15667 if (ast_strlen_zero(totag)) {
15668 sip_pvt_unlock(sip_pvt_ptr);
15669 ast_debug(4, "Matched %s call for callid=%s - no to tag specified, pedantic check fails\n",
15670 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
15671 return NULL;
15672 }
15673
15674
15675
15676
15677
15678
15679
15680
15681
15682
15683
15684
15685
15686
15687 frommismatch = !!strcmp(fromtag, sip_pvt_ptr->theirtag);
15688 tomismatch = !!strcmp(totag, sip_pvt_ptr->tag);
15689
15690 if (frommismatch || tomismatch) {
15691 sip_pvt_unlock(sip_pvt_ptr);
15692 if (frommismatch) {
15693 ast_debug(4, "Matched %s call for callid=%s - pedantic from tag check fails; their tag is %s our tag is %s\n",
15694 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid,
15695 fromtag, sip_pvt_ptr->theirtag);
15696 }
15697 if (tomismatch) {
15698 ast_debug(4, "Matched %s call for callid=%s - pedantic to tag check fails; their tag is %s our tag is %s\n",
15699 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid,
15700 totag, sip_pvt_ptr->tag);
15701 }
15702 return NULL;
15703 }
15704 }
15705
15706 if (totag)
15707 ast_debug(4, "Matched %s call - their tag is %s Our tag is %s\n",
15708 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING",
15709 sip_pvt_ptr->theirtag, sip_pvt_ptr->tag);
15710
15711
15712 while (sip_pvt_ptr->owner && ast_channel_trylock(sip_pvt_ptr->owner)) {
15713 sip_pvt_unlock(sip_pvt_ptr);
15714 usleep(1);
15715 sip_pvt_lock(sip_pvt_ptr);
15716 }
15717 }
15718
15719 return sip_pvt_ptr;
15720 }
15721
15722
15723
15724
15725
15726
15727
15728
15729 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req)
15730 {
15731
15732 const char *p_referred_by = NULL;
15733 char *h_refer_to = NULL;
15734 char *h_referred_by = NULL;
15735 char *refer_to;
15736 const char *p_refer_to;
15737 char *referred_by_uri = NULL;
15738 char *ptr;
15739 struct sip_request *req = NULL;
15740 const char *transfer_context = NULL;
15741 struct sip_refer *referdata;
15742
15743
15744 req = outgoing_req;
15745 referdata = transferer->refer;
15746
15747 if (!req) {
15748 req = &transferer->initreq;
15749 }
15750
15751 p_refer_to = get_header(req, "Refer-To");
15752 if (ast_strlen_zero(p_refer_to)) {
15753 ast_log(LOG_WARNING, "Refer-To Header missing. Skipping transfer.\n");
15754 return -2;
15755 }
15756 h_refer_to = ast_strdupa(p_refer_to);
15757 refer_to = get_in_brackets(h_refer_to);
15758 if (!strncasecmp(refer_to, "sip:", 4)) {
15759 refer_to += 4;
15760 } else if (!strncasecmp(refer_to, "sips:", 5)) {
15761 refer_to += 5;
15762 } else {
15763 ast_log(LOG_WARNING, "Can't transfer to non-sip: URI. (Refer-to: %s)?\n", refer_to);
15764 return -3;
15765 }
15766
15767
15768 p_referred_by = get_header(req, "Referred-By");
15769
15770
15771 if (transferer->owner) {
15772 struct ast_channel *peer = ast_bridged_channel(transferer->owner);
15773 if (peer) {
15774 pbx_builtin_setvar_helper(peer, "SIPREFERRINGCONTEXT", transferer->context);
15775 pbx_builtin_setvar_helper(peer, "SIPREFERREDBYHDR", p_referred_by);
15776 }
15777 }
15778
15779 if (!ast_strlen_zero(p_referred_by)) {
15780 char *lessthan;
15781 h_referred_by = ast_strdupa(p_referred_by);
15782
15783
15784 ast_copy_string(referdata->referred_by_name, h_referred_by, sizeof(referdata->referred_by_name));
15785 if ((lessthan = strchr(referdata->referred_by_name, '<'))) {
15786 *(lessthan - 1) = '\0';
15787 }
15788
15789 referred_by_uri = get_in_brackets(h_referred_by);
15790
15791 if (!strncasecmp(referred_by_uri, "sip:", 4)) {
15792 referred_by_uri += 4;
15793 } else if (!strncasecmp(referred_by_uri, "sips:", 5)) {
15794 referred_by_uri += 5;
15795 } else {
15796 ast_log(LOG_WARNING, "Huh? Not a sip: header (Referred-by: %s). Skipping.\n", referred_by_uri);
15797 referred_by_uri = NULL;
15798 }
15799 }
15800
15801
15802 if ((ptr = strcasestr(refer_to, "replaces="))) {
15803 char *to = NULL, *from = NULL;
15804
15805
15806 referdata->attendedtransfer = 1;
15807 ast_copy_string(referdata->replaces_callid, ptr+9, sizeof(referdata->replaces_callid));
15808 ast_uri_decode(referdata->replaces_callid);
15809 if ((ptr = strchr(referdata->replaces_callid, ';'))) {
15810 *ptr++ = '\0';
15811 }
15812
15813 if (ptr) {
15814
15815 to = strcasestr(ptr, "to-tag=");
15816 from = strcasestr(ptr, "from-tag=");
15817 }
15818
15819
15820 if (to) {
15821 ptr = to + 7;
15822 if ((to = strchr(ptr, '&'))) {
15823 *to = '\0';
15824 }
15825 if ((to = strchr(ptr, ';'))) {
15826 *to = '\0';
15827 }
15828 ast_copy_string(referdata->replaces_callid_totag, ptr, sizeof(referdata->replaces_callid_totag));
15829 }
15830
15831 if (from) {
15832 ptr = from + 9;
15833 if ((to = strchr(ptr, '&'))) {
15834 *to = '\0';
15835 }
15836 if ((to = strchr(ptr, ';'))) {
15837 *to = '\0';
15838 }
15839 ast_copy_string(referdata->replaces_callid_fromtag, ptr, sizeof(referdata->replaces_callid_fromtag));
15840 }
15841
15842 if (!strcmp(referdata->replaces_callid, transferer->callid) &&
15843 (!sip_cfg.pedanticsipchecking ||
15844 (!strcmp(referdata->replaces_callid_fromtag, transferer->theirtag) &&
15845 !strcmp(referdata->replaces_callid_totag, transferer->tag)))) {
15846 ast_log(LOG_WARNING, "Got an attempt to replace own Call-ID on %s\n", transferer->callid);
15847 return -4;
15848 }
15849
15850 if (!sip_cfg.pedanticsipchecking) {
15851 ast_debug(2, "Attended transfer: Will use Replace-Call-ID : %s (No check of from/to tags)\n", referdata->replaces_callid );
15852 } else {
15853 ast_debug(2, "Attended transfer: Will use Replace-Call-ID : %s F-tag: %s T-tag: %s\n", referdata->replaces_callid, referdata->replaces_callid_fromtag ? referdata->replaces_callid_fromtag : "<none>", referdata->replaces_callid_totag ? referdata->replaces_callid_totag : "<none>" );
15854 }
15855 }
15856
15857 if ((ptr = strchr(refer_to, '@'))) {
15858 char *urioption = NULL, *domain;
15859 int bracket = 0;
15860 *ptr++ = '\0';
15861
15862 if ((urioption = strchr(ptr, ';'))) {
15863 *urioption++ = '\0';
15864 }
15865
15866 domain = ptr;
15867
15868
15869 for (; *ptr != '\0'; ++ptr) {
15870 if (*ptr == ':' && bracket == 0) {
15871 *ptr = '\0';
15872 break;
15873 } else if (*ptr == '[') {
15874 ++bracket;
15875 } else if (*ptr == ']') {
15876 --bracket;
15877 }
15878 }
15879
15880 SIP_PEDANTIC_DECODE(domain);
15881 SIP_PEDANTIC_DECODE(urioption);
15882
15883
15884 ast_copy_string(referdata->refer_to_domain, domain, sizeof(referdata->refer_to_domain));
15885 if (urioption) {
15886 ast_copy_string(referdata->refer_to_urioption, urioption, sizeof(referdata->refer_to_urioption));
15887 }
15888 }
15889
15890 if ((ptr = strchr(refer_to, ';')))
15891 *ptr = '\0';
15892
15893 SIP_PEDANTIC_DECODE(refer_to);
15894 ast_copy_string(referdata->refer_to, refer_to, sizeof(referdata->refer_to));
15895
15896 if (referred_by_uri) {
15897 if ((ptr = strchr(referred_by_uri, ';')))
15898 *ptr = '\0';
15899 SIP_PEDANTIC_DECODE(referred_by_uri);
15900 ast_copy_string(referdata->referred_by, referred_by_uri, sizeof(referdata->referred_by));
15901 } else {
15902 referdata->referred_by[0] = '\0';
15903 }
15904
15905
15906 if (transferer->owner)
15907 transfer_context = pbx_builtin_getvar_helper(transferer->owner, "TRANSFER_CONTEXT");
15908
15909
15910 if (ast_strlen_zero(transfer_context)) {
15911 transfer_context = S_OR(transferer->owner->macrocontext,
15912 S_OR(transferer->context, sip_cfg.default_context));
15913 }
15914
15915 ast_copy_string(referdata->refer_to_context, transfer_context, sizeof(referdata->refer_to_context));
15916
15917
15918 if (referdata->attendedtransfer || ast_exists_extension(NULL, transfer_context, refer_to, 1, NULL) ) {
15919 if (sip_debug_test_pvt(transferer)) {
15920 ast_verbose("SIP transfer to extension %s@%s by %s\n", refer_to, transfer_context, referred_by_uri);
15921 }
15922
15923 return 0;
15924 }
15925 if (sip_debug_test_pvt(transferer))
15926 ast_verbose("Failed SIP Transfer to non-existing extension %s in context %s\n n", refer_to, transfer_context);
15927
15928
15929 return -1;
15930 }
15931
15932
15933
15934
15935
15936 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq)
15937 {
15938 char tmp[256] = "", *c, *a;
15939 struct sip_request *req = oreq ? oreq : &p->initreq;
15940 struct sip_refer *referdata = NULL;
15941 const char *transfer_context = NULL;
15942
15943 if (!p->refer && !sip_refer_allocate(p))
15944 return -1;
15945
15946 referdata = p->refer;
15947
15948 ast_copy_string(tmp, get_header(req, "Also"), sizeof(tmp));
15949 c = get_in_brackets(tmp);
15950
15951 if (parse_uri_legacy_check(c, "sip:,sips:", &c, NULL, &a, NULL)) {
15952 ast_log(LOG_WARNING, "Huh? Not a SIP header in Also: transfer (%s)?\n", c);
15953 return -1;
15954 }
15955
15956 SIP_PEDANTIC_DECODE(c);
15957 SIP_PEDANTIC_DECODE(a);
15958
15959 if (!ast_strlen_zero(a)) {
15960 ast_copy_string(referdata->refer_to_domain, a, sizeof(referdata->refer_to_domain));
15961 }
15962
15963 if (sip_debug_test_pvt(p))
15964 ast_verbose("Looking for %s in %s\n", c, p->context);
15965
15966 if (p->owner)
15967 transfer_context = pbx_builtin_getvar_helper(p->owner, "TRANSFER_CONTEXT");
15968
15969
15970 if (ast_strlen_zero(transfer_context)) {
15971 transfer_context = S_OR(p->owner->macrocontext,
15972 S_OR(p->context, sip_cfg.default_context));
15973 }
15974 if (ast_exists_extension(NULL, transfer_context, c, 1, NULL)) {
15975
15976 ast_debug(1, "SIP Bye-also transfer to Extension %s@%s \n", c, transfer_context);
15977 ast_copy_string(referdata->refer_to, c, sizeof(referdata->refer_to));
15978 ast_copy_string(referdata->referred_by, "", sizeof(referdata->referred_by));
15979 ast_copy_string(referdata->refer_contact, "", sizeof(referdata->refer_contact));
15980
15981 ast_string_field_set(p, context, transfer_context);
15982 return 0;
15983 } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
15984 return 1;
15985 }
15986
15987 return -1;
15988 }
15989
15990
15991
15992
15993
15994
15995
15996
15997
15998
15999
16000 static attribute_unused void check_via_response(struct sip_pvt *p, struct sip_request *req)
16001 {
16002 char via[256];
16003 char *cur, *opts;
16004
16005 ast_copy_string(via, get_header(req, "Via"), sizeof(via));
16006
16007
16008 opts = strchr(via, ',');
16009 if (opts)
16010 *opts = '\0';
16011
16012
16013 opts = strchr(via, ';');
16014 if (!opts)
16015 return;
16016 *opts++ = '\0';
16017 while ( (cur = strsep(&opts, ";")) ) {
16018 if (!strncmp(cur, "rport=", 6)) {
16019 int port = strtol(cur+6, NULL, 10);
16020
16021 ast_sockaddr_set_port(&p->ourip, port);
16022 } else if (!strncmp(cur, "received=", 9)) {
16023 if (ast_parse_arg(cur + 9, PARSE_ADDR, &p->ourip))
16024 ;
16025 }
16026 }
16027 }
16028
16029
16030 static void check_via(struct sip_pvt *p, struct sip_request *req)
16031 {
16032 char via[512];
16033 char *c, *maddr;
16034 struct ast_sockaddr tmp = { { 0, } };
16035 uint16_t port;
16036
16037 ast_copy_string(via, get_header(req, "Via"), sizeof(via));
16038
16039
16040 c = strchr(via, ',');
16041 if (c)
16042 *c = '\0';
16043
16044
16045 c = strstr(via, ";rport");
16046 if (c && (c[6] != '=')) {
16047 ast_set_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT);
16048 ast_set_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT);
16049 }
16050
16051
16052 maddr = strstr(via, "maddr=");
16053 if (maddr) {
16054 maddr += 6;
16055 c = maddr + strspn(maddr, "abcdefghijklmnopqrstuvwxyz"
16056 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-.:[]");
16057 *c = '\0';
16058 }
16059
16060 c = strchr(via, ';');
16061 if (c)
16062 *c = '\0';
16063
16064 c = strchr(via, ' ');
16065 if (c) {
16066 *c = '\0';
16067 c = ast_skip_blanks(c+1);
16068 if (strcasecmp(via, "SIP/2.0/UDP") && strcasecmp(via, "SIP/2.0/TCP") && strcasecmp(via, "SIP/2.0/TLS")) {
16069 ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
16070 return;
16071 }
16072
16073 if (maddr && ast_sockaddr_resolve_first(&p->sa, maddr, 0)) {
16074 p->sa = p->recv;
16075 }
16076
16077 if (ast_sockaddr_resolve_first(&tmp, c, 0)) {
16078 ast_log(LOG_WARNING, "Could not resolve socket address for '%s'\n", c);
16079 }
16080 port = ast_sockaddr_port(&tmp);
16081 ast_sockaddr_set_port(&p->sa,
16082 port != 0 ? port : STANDARD_SIP_PORT);
16083
16084 if (sip_debug_test_pvt(p)) {
16085 ast_verbose("Sending to %s (%s)\n",
16086 ast_sockaddr_stringify(sip_real_dst(p)),
16087 sip_nat_mode(p));
16088 }
16089 }
16090 }
16091
16092
16093 static enum check_auth_result check_peer_ok(struct sip_pvt *p, char *of,
16094 struct sip_request *req, int sipmethod, struct ast_sockaddr *addr,
16095 struct sip_peer **authpeer,
16096 enum xmittype reliable, char *calleridname, char *uri2)
16097 {
16098 enum check_auth_result res;
16099 int debug = sip_debug_test_addr(addr);
16100 struct sip_peer *peer;
16101
16102 if (sipmethod == SIP_SUBSCRIBE) {
16103
16104
16105
16106 peer = find_peer(of, NULL, TRUE, FINDALLDEVICES, FALSE, 0);
16107 } else {
16108
16109 peer = find_peer(of, NULL, TRUE, FINDUSERS, FALSE, 0);
16110
16111
16112 if (!peer) {
16113 peer = find_peer(NULL, &p->recv, TRUE, FINDPEERS, FALSE, p->socket.type);
16114 }
16115 }
16116
16117 if (!peer) {
16118 if (debug) {
16119 ast_verbose("No matching peer for '%s' from '%s'\n",
16120 of, ast_sockaddr_stringify(&p->recv));
16121 }
16122 return AUTH_DONT_KNOW;
16123 }
16124
16125 if (!ast_apply_ha(peer->ha, addr)) {
16126 ast_debug(2, "Found peer '%s' for '%s', but fails host access\n", peer->name, of);
16127 unref_peer(peer, "unref_peer: check_peer_ok: from find_peer call, early return of AUTH_ACL_FAILED");
16128 return AUTH_ACL_FAILED;
16129 }
16130 if (debug)
16131 ast_verbose("Found peer '%s' for '%s' from %s\n",
16132 peer->name, of, ast_sockaddr_stringify(&p->recv));
16133
16134
16135
16136 if (p->rtp) {
16137 ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(p->rtp), p->rtp, &peer->prefs);
16138 p->autoframing = peer->autoframing;
16139 }
16140
16141
16142 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
16143 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
16144 ast_copy_flags(&p->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
16145
16146 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) && p->udptl) {
16147 p->t38_maxdatagram = peer->t38_maxdatagram;
16148 set_t38_capabilities(p);
16149 }
16150
16151
16152
16153 if (p->sipoptions)
16154 peer->sipoptions = p->sipoptions;
16155
16156 do_setnat(p);
16157
16158 ast_string_field_set(p, peersecret, peer->secret);
16159 ast_string_field_set(p, peermd5secret, peer->md5secret);
16160 ast_string_field_set(p, subscribecontext, peer->subscribecontext);
16161 ast_string_field_set(p, mohinterpret, peer->mohinterpret);
16162 ast_string_field_set(p, mohsuggest, peer->mohsuggest);
16163 if (!ast_strlen_zero(peer->parkinglot)) {
16164 ast_string_field_set(p, parkinglot, peer->parkinglot);
16165 }
16166 ast_string_field_set(p, engine, peer->engine);
16167 p->disallowed_methods = peer->disallowed_methods;
16168 set_pvt_allowed_methods(p, req);
16169 ast_cc_copy_config_params(p->cc_params, peer->cc_params);
16170 if (peer->callingpres)
16171 p->callingpres = peer->callingpres;
16172 if (peer->maxms && peer->lastms)
16173 p->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
16174 else
16175 p->timer_t1 = peer->timer_t1;
16176
16177
16178 if (peer->timer_b)
16179 p->timer_b = peer->timer_b;
16180 else
16181 p->timer_b = 64 * p->timer_t1;
16182
16183 p->allowtransfer = peer->allowtransfer;
16184
16185 if (ast_test_flag(&peer->flags[0], SIP_INSECURE_INVITE)) {
16186
16187 ast_string_field_set(p, peersecret, NULL);
16188 ast_string_field_set(p, peermd5secret, NULL);
16189 }
16190 if (!(res = check_auth(p, req, peer->name, p->peersecret, p->peermd5secret, sipmethod, uri2, reliable, req->ignore))) {
16191 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
16192 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
16193 ast_copy_flags(&p->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
16194
16195 if (peer->call_limit)
16196 ast_set_flag(&p->flags[0], SIP_CALL_LIMIT);
16197 ast_string_field_set(p, peername, peer->name);
16198 ast_string_field_set(p, authname, peer->name);
16199
16200 if (sipmethod == SIP_INVITE) {
16201
16202 ast_variables_destroy(p->chanvars);
16203 p->chanvars = copy_vars(peer->chanvars);
16204 }
16205
16206 if (authpeer) {
16207 ao2_t_ref(peer, 1, "copy pointer into (*authpeer)");
16208 (*authpeer) = peer;
16209 }
16210
16211 if (!ast_strlen_zero(peer->username)) {
16212 ast_string_field_set(p, username, peer->username);
16213
16214
16215 ast_string_field_set(p, authname, peer->username);
16216 }
16217 if (!get_rpid(p, req)) {
16218 if (!ast_strlen_zero(peer->cid_num)) {
16219 char *tmp = ast_strdupa(peer->cid_num);
16220 if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
16221 ast_shrink_phone_number(tmp);
16222 ast_string_field_set(p, cid_num, tmp);
16223 }
16224 if (!ast_strlen_zero(peer->cid_name))
16225 ast_string_field_set(p, cid_name, peer->cid_name);
16226 if (peer->callingpres)
16227 p->callingpres = peer->callingpres;
16228 }
16229 if (!ast_strlen_zero(peer->cid_tag)) {
16230 ast_string_field_set(p, cid_tag, peer->cid_tag);
16231 }
16232 ast_string_field_set(p, fullcontact, peer->fullcontact);
16233
16234 if (!ast_strlen_zero(peer->context)) {
16235 ast_string_field_set(p, context, peer->context);
16236 }
16237 if (!ast_strlen_zero(peer->mwi_from)) {
16238 ast_string_field_set(p, mwi_from, peer->mwi_from);
16239 }
16240
16241 ast_string_field_set(p, peersecret, peer->secret);
16242 ast_string_field_set(p, peermd5secret, peer->md5secret);
16243 ast_string_field_set(p, language, peer->language);
16244 ast_string_field_set(p, accountcode, peer->accountcode);
16245 p->amaflags = peer->amaflags;
16246 p->callgroup = peer->callgroup;
16247 p->pickupgroup = peer->pickupgroup;
16248 p->capability = peer->capability;
16249 p->prefs = peer->prefs;
16250 p->jointcapability = peer->capability;
16251 if (peer->maxforwards > 0) {
16252 p->maxforwards = peer->maxforwards;
16253 }
16254 if (p->peercapability)
16255 p->jointcapability &= p->peercapability;
16256 p->maxcallbitrate = peer->maxcallbitrate;
16257 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
16258 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
16259 p->noncodeccapability |= AST_RTP_DTMF;
16260 else
16261 p->noncodeccapability &= ~AST_RTP_DTMF;
16262 p->jointnoncodeccapability = p->noncodeccapability;
16263 p->rtptimeout = peer->rtptimeout;
16264 p->rtpholdtimeout = peer->rtpholdtimeout;
16265 p->rtpkeepalive = peer->rtpkeepalive;
16266 if (!dialog_initialize_rtp(p)) {
16267 if (p->rtp) {
16268 ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(p->rtp), p->rtp, &peer->prefs);
16269 p->autoframing = peer->autoframing;
16270 }
16271 } else {
16272 res = AUTH_RTP_FAILED;
16273 }
16274 }
16275 unref_peer(peer, "check_peer_ok: unref_peer: tossing temp ptr to peer from find_peer");
16276 return res;
16277 }
16278
16279
16280
16281
16282
16283
16284
16285 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
16286 int sipmethod, const char *uri, enum xmittype reliable,
16287 struct ast_sockaddr *addr, struct sip_peer **authpeer)
16288 {
16289 char from[256] = "", *of, *name, *unused_password, *domain;
16290 enum check_auth_result res = AUTH_DONT_KNOW;
16291 char calleridname[50];
16292 char *uri2 = ast_strdupa(uri);
16293
16294 terminate_uri(uri2);
16295
16296 ast_copy_string(from, get_header(req, "From"), sizeof(from));
16297
16298
16299
16300 if (!(of = (char *) get_calleridname(from, calleridname, sizeof(calleridname)))) {
16301 ast_log(LOG_ERROR, "FROM header can not be parsed \n");
16302 return res;
16303 }
16304
16305 if (calleridname[0]) {
16306 ast_string_field_set(p, cid_name, calleridname);
16307 }
16308
16309 if (ast_strlen_zero(p->exten)) {
16310 char *t = uri2;
16311 if (!strncasecmp(t, "sip:", 4))
16312 t+= 4;
16313 else if (!strncasecmp(t, "sips:", 5))
16314 t += 5;
16315 ast_string_field_set(p, exten, t);
16316 t = strchr(p->exten, '@');
16317 if (t)
16318 *t = '\0';
16319
16320 if (ast_strlen_zero(p->our_contact))
16321 build_contact(p);
16322 }
16323
16324 of = get_in_brackets(of);
16325
16326
16327 ast_string_field_set(p, from, of);
16328
16329 if (parse_uri_legacy_check(of, "sip:,sips:", &name, &unused_password, &domain, NULL)) {
16330 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
16331 }
16332
16333 SIP_PEDANTIC_DECODE(name);
16334 SIP_PEDANTIC_DECODE(domain);
16335
16336 extract_host_from_hostport(&domain);
16337
16338 if (ast_strlen_zero(domain)) {
16339
16340 ast_log(LOG_ERROR, "Empty domain name in FROM header\n");
16341 return res;
16342 }
16343
16344 if (ast_strlen_zero(name)) {
16345
16346
16347
16348 name = domain;
16349 } else {
16350
16351 char *tmp = ast_strdupa(name);
16352
16353
16354
16355 tmp = strsep(&tmp, ";");
16356 if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp)) {
16357 ast_shrink_phone_number(tmp);
16358 }
16359 ast_string_field_set(p, cid_num, tmp);
16360 }
16361
16362 if (global_match_auth_username) {
16363
16364
16365
16366
16367
16368
16369
16370
16371 const char *hdr = get_header(req, "Authorization");
16372 if (ast_strlen_zero(hdr)) {
16373 hdr = get_header(req, "Proxy-Authorization");
16374 }
16375
16376 if (!ast_strlen_zero(hdr) && (hdr = strstr(hdr, "username=\""))) {
16377 ast_copy_string(from, hdr + strlen("username=\""), sizeof(from));
16378 name = from;
16379 name = strsep(&name, "\"");
16380 }
16381 }
16382
16383 res = check_peer_ok(p, name, req, sipmethod, addr,
16384 authpeer, reliable, calleridname, uri2);
16385 if (res != AUTH_DONT_KNOW) {
16386 return res;
16387 }
16388
16389
16390 if (sip_cfg.allowguest) {
16391
16392 get_rpid(p, req);
16393 p->rtptimeout = global_rtptimeout;
16394 p->rtpholdtimeout = global_rtpholdtimeout;
16395 p->rtpkeepalive = global_rtpkeepalive;
16396 if (!dialog_initialize_rtp(p)) {
16397 res = AUTH_SUCCESSFUL;
16398 } else {
16399 res = AUTH_RTP_FAILED;
16400 }
16401 } else if (sip_cfg.alwaysauthreject) {
16402 res = AUTH_FAKE_AUTH;
16403 } else {
16404 res = AUTH_SECRET_FAILED;
16405 }
16406
16407 if (ast_test_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT)) {
16408 ast_set_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT);
16409 }
16410
16411 return res;
16412 }
16413
16414
16415
16416
16417 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, const char *uri, enum xmittype reliable, struct ast_sockaddr *addr)
16418 {
16419 return check_user_full(p, req, sipmethod, uri, reliable, addr, NULL);
16420 }
16421
16422
16423
16424
16425
16426
16427
16428
16429
16430 static int get_msg_text(char *buf, int len, struct sip_request *req)
16431 {
16432 int x;
16433 int linelen;
16434
16435 buf[0] = '\0';
16436 --len;
16437 for (x = 0; len && x < req->lines; ++x) {
16438 const char *line = REQ_OFFSET_TO_STR(req, line[x]);
16439 strncat(buf, line, len);
16440 linelen = strlen(buf);
16441 buf += linelen;
16442 len -= linelen;
16443 if (len) {
16444 strcat(buf, "\n");
16445 ++buf;
16446 --len;
16447 }
16448 }
16449 return 0;
16450 }
16451
16452
16453
16454
16455
16456 static void receive_message(struct sip_pvt *p, struct sip_request *req)
16457 {
16458 char buf[1400];
16459 char *bufp;
16460 struct ast_frame f;
16461 const char *content_type = get_header(req, "Content-Type");
16462
16463 if (strncmp(content_type, "text/plain", strlen("text/plain"))) {
16464 transmit_response(p, "415 Unsupported Media Type", req);
16465 if (!p->owner)
16466 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16467 return;
16468 }
16469
16470 if (get_msg_text(buf, sizeof(buf), req)) {
16471 ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
16472 transmit_response(p, "500 Internal Server Error", req);
16473 if (!p->owner) {
16474 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16475 }
16476 return;
16477 }
16478
16479
16480
16481 bufp = buf + strlen(buf);
16482 while (--bufp >= buf && *bufp == '\n') {
16483 *bufp = '\0';
16484 }
16485
16486 if (p->owner) {
16487 if (sip_debug_test_pvt(p))
16488 ast_verbose("SIP Text message received: '%s'\n", buf);
16489 memset(&f, 0, sizeof(f));
16490 f.frametype = AST_FRAME_TEXT;
16491 f.subclass.integer = 0;
16492 f.offset = 0;
16493 f.data.ptr = buf;
16494 f.datalen = strlen(buf) + 1;
16495 ast_queue_frame(p->owner, &f);
16496 transmit_response(p, "202 Accepted", req);
16497 return;
16498 }
16499
16500
16501 ast_log(LOG_WARNING, "Received message to %s from %s, dropped it...\n Content-Type:%s\n Message: %s\n", get_header(req, "To"), get_header(req, "From"), content_type, buf);
16502 transmit_response(p, "405 Method Not Allowed", req);
16503 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16504 return;
16505 }
16506
16507
16508 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16509 {
16510 #define FORMAT "%-25.25s %-15.15s %-15.15s \n"
16511 #define FORMAT2 "%-25.25s %-15.15s %-15.15s \n"
16512 char ilimits[40];
16513 char iused[40];
16514 int showall = FALSE;
16515 struct ao2_iterator i;
16516 struct sip_peer *peer;
16517
16518 switch (cmd) {
16519 case CLI_INIT:
16520 e->command = "sip show inuse";
16521 e->usage =
16522 "Usage: sip show inuse [all]\n"
16523 " List all SIP devices usage counters and limits.\n"
16524 " Add option \"all\" to show all devices, not only those with a limit.\n";
16525 return NULL;
16526 case CLI_GENERATE:
16527 return NULL;
16528 }
16529
16530 if (a->argc < 3)
16531 return CLI_SHOWUSAGE;
16532
16533 if (a->argc == 4 && !strcmp(a->argv[3], "all"))
16534 showall = TRUE;
16535
16536 ast_cli(a->fd, FORMAT, "* Peer name", "In use", "Limit");
16537
16538 i = ao2_iterator_init(peers, 0);
16539 while ((peer = ao2_t_iterator_next(&i, "iterate thru peer table"))) {
16540 ao2_lock(peer);
16541 if (peer->call_limit)
16542 snprintf(ilimits, sizeof(ilimits), "%d", peer->call_limit);
16543 else
16544 ast_copy_string(ilimits, "N/A", sizeof(ilimits));
16545 snprintf(iused, sizeof(iused), "%d/%d/%d", peer->inUse, peer->inRinging, peer->onHold);
16546 if (showall || peer->call_limit)
16547 ast_cli(a->fd, FORMAT2, peer->name, iused, ilimits);
16548 ao2_unlock(peer);
16549 unref_peer(peer, "toss iterator pointer");
16550 }
16551 ao2_iterator_destroy(&i);
16552
16553 return CLI_SUCCESS;
16554 #undef FORMAT
16555 #undef FORMAT2
16556 }
16557
16558
16559
16560 static char *transfermode2str(enum transfermodes mode)
16561 {
16562 if (mode == TRANSFER_OPENFORALL)
16563 return "open";
16564 else if (mode == TRANSFER_CLOSED)
16565 return "closed";
16566 return "strict";
16567 }
16568
16569
16570
16571
16572
16573
16574
16575 static const struct _map_x_s stmodes[] = {
16576 { SESSION_TIMER_MODE_ACCEPT, "Accept"},
16577 { SESSION_TIMER_MODE_ORIGINATE, "Originate"},
16578 { SESSION_TIMER_MODE_REFUSE, "Refuse"},
16579 { -1, NULL},
16580 };
16581
16582 static const char *stmode2str(enum st_mode m)
16583 {
16584 return map_x_s(stmodes, m, "Unknown");
16585 }
16586
16587 static enum st_mode str2stmode(const char *s)
16588 {
16589 return map_s_x(stmodes, s, -1);
16590 }
16591
16592
16593 static const struct _map_x_s strefresher_params[] = {
16594 { SESSION_TIMER_REFRESHER_PARAM_UNKNOWN, "unknown" },
16595 { SESSION_TIMER_REFRESHER_PARAM_UAC, "uac" },
16596 { SESSION_TIMER_REFRESHER_PARAM_UAS, "uas" },
16597 { -1, NULL },
16598 };
16599
16600 static const struct _map_x_s strefreshers[] = {
16601 { SESSION_TIMER_REFRESHER_AUTO, "auto" },
16602 { SESSION_TIMER_REFRESHER_US, "us" },
16603 { SESSION_TIMER_REFRESHER_THEM, "them" },
16604 { -1, NULL },
16605 };
16606
16607 static const char *strefresherparam2str(enum st_refresher r)
16608 {
16609 return map_x_s(strefresher_params, r, "Unknown");
16610 }
16611
16612 static enum st_refresher str2strefresherparam(const char *s)
16613 {
16614 return map_s_x(strefresher_params, s, -1);
16615 }
16616
16617 static const char *strefresher2str(enum st_refresher r)
16618 {
16619 return map_x_s(strefreshers, r, "Unknown");
16620 }
16621
16622 static int peer_status(struct sip_peer *peer, char *status, int statuslen)
16623 {
16624 int res = 0;
16625 if (peer->maxms) {
16626 if (peer->lastms < 0) {
16627 ast_copy_string(status, "UNREACHABLE", statuslen);
16628 } else if (peer->lastms > peer->maxms) {
16629 snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
16630 res = 1;
16631 } else if (peer->lastms) {
16632 snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
16633 res = 1;
16634 } else {
16635 ast_copy_string(status, "UNKNOWN", statuslen);
16636 }
16637 } else {
16638 ast_copy_string(status, "Unmonitored", statuslen);
16639
16640 res = -1;
16641 }
16642 return res;
16643 }
16644
16645
16646 static char *sip_show_tcp(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16647 {
16648 struct sip_threadinfo *th;
16649 struct ao2_iterator i;
16650
16651 #define FORMAT2 "%-47.47s %9.9s %6.6s\n"
16652 #define FORMAT "%-47.47s %-9.9s %-6.6s\n"
16653
16654 switch (cmd) {
16655 case CLI_INIT:
16656 e->command = "sip show tcp";
16657 e->usage =
16658 "Usage: sip show tcp\n"
16659 " Lists all active TCP/TLS sessions.\n";
16660 return NULL;
16661 case CLI_GENERATE:
16662 return NULL;
16663 }
16664
16665 if (a->argc != 3)
16666 return CLI_SHOWUSAGE;
16667
16668 ast_cli(a->fd, FORMAT2, "Address", "Transport", "Type");
16669
16670 i = ao2_iterator_init(threadt, 0);
16671 while ((th = ao2_t_iterator_next(&i, "iterate through tcp threads for 'sip show tcp'"))) {
16672 ast_cli(a->fd, FORMAT,
16673 ast_sockaddr_stringify(&th->tcptls_session->remote_address),
16674 get_transport(th->type),
16675 (th->tcptls_session->client ? "Client" : "Server"));
16676 ao2_t_ref(th, -1, "decrement ref from iterator");
16677 }
16678 ao2_iterator_destroy(&i);
16679
16680 return CLI_SUCCESS;
16681 #undef FORMAT
16682 #undef FORMAT2
16683 }
16684
16685
16686 static char *sip_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16687 {
16688 regex_t regexbuf;
16689 int havepattern = FALSE;
16690 struct ao2_iterator user_iter;
16691 struct sip_peer *user;
16692
16693 #define FORMAT "%-25.25s %-15.15s %-15.15s %-15.15s %-5.5s%-10.10s\n"
16694
16695 switch (cmd) {
16696 case CLI_INIT:
16697 e->command = "sip show users";
16698 e->usage =
16699 "Usage: sip show users [like <pattern>]\n"
16700 " Lists all known SIP users.\n"
16701 " Optional regular expression pattern is used to filter the user list.\n";
16702 return NULL;
16703 case CLI_GENERATE:
16704 return NULL;
16705 }
16706
16707 switch (a->argc) {
16708 case 5:
16709 if (!strcasecmp(a->argv[3], "like")) {
16710 if (regcomp(®exbuf, a->argv[4], REG_EXTENDED | REG_NOSUB))
16711 return CLI_SHOWUSAGE;
16712 havepattern = TRUE;
16713 } else
16714 return CLI_SHOWUSAGE;
16715 case 3:
16716 break;
16717 default:
16718 return CLI_SHOWUSAGE;
16719 }
16720
16721 ast_cli(a->fd, FORMAT, "Username", "Secret", "Accountcode", "Def.Context", "ACL", "ForcerPort");
16722
16723 user_iter = ao2_iterator_init(peers, 0);
16724 while ((user = ao2_t_iterator_next(&user_iter, "iterate thru peers table"))) {
16725 ao2_lock(user);
16726 if (!(user->type & SIP_TYPE_USER)) {
16727 ao2_unlock(user);
16728 unref_peer(user, "sip show users");
16729 continue;
16730 }
16731
16732 if (havepattern && regexec(®exbuf, user->name, 0, NULL, 0)) {
16733 ao2_unlock(user);
16734 unref_peer(user, "sip show users");
16735 continue;
16736 }
16737
16738 ast_cli(a->fd, FORMAT, user->name,
16739 user->secret,
16740 user->accountcode,
16741 user->context,
16742 AST_CLI_YESNO(user->ha != NULL),
16743 AST_CLI_YESNO(ast_test_flag(&user->flags[0], SIP_NAT_FORCE_RPORT)));
16744 ao2_unlock(user);
16745 unref_peer(user, "sip show users");
16746 }
16747 ao2_iterator_destroy(&user_iter);
16748
16749 if (havepattern)
16750 regfree(®exbuf);
16751
16752 return CLI_SUCCESS;
16753 #undef FORMAT
16754 }
16755
16756
16757 static int manager_show_registry(struct mansession *s, const struct message *m)
16758 {
16759 const char *id = astman_get_header(m, "ActionID");
16760 char idtext[256] = "";
16761 int total = 0;
16762
16763 if (!ast_strlen_zero(id))
16764 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
16765
16766 astman_send_listack(s, m, "Registrations will follow", "start");
16767
16768 ASTOBJ_CONTAINER_TRAVERSE(®l, 1, do {
16769 ASTOBJ_RDLOCK(iterator);
16770 astman_append(s,
16771 "Event: RegistryEntry\r\n"
16772 "%s"
16773 "Host: %s\r\n"
16774 "Port: %d\r\n"
16775 "Username: %s\r\n"
16776 "Domain: %s\r\n"
16777 "DomainPort: %d\r\n"
16778 "Refresh: %d\r\n"
16779 "State: %s\r\n"
16780 "RegistrationTime: %ld\r\n"
16781 "\r\n",
16782 idtext,
16783 iterator->hostname,
16784 iterator->portno ? iterator->portno : STANDARD_SIP_PORT,
16785 iterator->username,
16786 S_OR(iterator->regdomain,iterator->hostname),
16787 iterator->regdomainport ? iterator->regdomainport : STANDARD_SIP_PORT,
16788 iterator->refresh,
16789 regstate2str(iterator->regstate),
16790 (long) iterator->regtime.tv_sec);
16791 ASTOBJ_UNLOCK(iterator);
16792 total++;
16793 } while(0));
16794
16795 astman_append(s,
16796 "Event: RegistrationsComplete\r\n"
16797 "EventList: Complete\r\n"
16798 "ListItems: %d\r\n"
16799 "%s"
16800 "\r\n", total, idtext);
16801
16802 return 0;
16803 }
16804
16805
16806
16807 static int manager_sip_show_peers(struct mansession *s, const struct message *m)
16808 {
16809 const char *id = astman_get_header(m, "ActionID");
16810 const char *a[] = {"sip", "show", "peers"};
16811 char idtext[256] = "";
16812 int total = 0;
16813
16814 if (!ast_strlen_zero(id))
16815 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
16816
16817 astman_send_listack(s, m, "Peer status list will follow", "start");
16818
16819 _sip_show_peers(-1, &total, s, m, 3, a);
16820
16821 astman_append(s,
16822 "Event: PeerlistComplete\r\n"
16823 "EventList: Complete\r\n"
16824 "ListItems: %d\r\n"
16825 "%s"
16826 "\r\n", total, idtext);
16827 return 0;
16828 }
16829
16830
16831 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16832 {
16833 switch (cmd) {
16834 case CLI_INIT:
16835 e->command = "sip show peers";
16836 e->usage =
16837 "Usage: sip show peers [like <pattern>]\n"
16838 " Lists all known SIP peers.\n"
16839 " Optional regular expression pattern is used to filter the peer list.\n";
16840 return NULL;
16841 case CLI_GENERATE:
16842 return NULL;
16843 }
16844
16845 return _sip_show_peers(a->fd, NULL, NULL, NULL, a->argc, (const char **) a->argv);
16846 }
16847
16848 int peercomparefunc(const void *a, const void *b);
16849
16850 int peercomparefunc(const void *a, const void *b)
16851 {
16852 struct sip_peer **ap = (struct sip_peer **)a;
16853 struct sip_peer **bp = (struct sip_peer **)b;
16854 return strcmp((*ap)->name, (*bp)->name);
16855 }
16856
16857
16858
16859 static char *_sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[])
16860 {
16861 regex_t regexbuf;
16862 int havepattern = FALSE;
16863 struct sip_peer *peer;
16864 struct ao2_iterator* it_peers;
16865
16866
16867 #define FORMAT2 "%-25.25s %-39.39s %-3.3s %-10.10s %-3.3s %-8s %-10s %s\n"
16868
16869 char name[256];
16870 int total_peers = 0;
16871 int peers_mon_online = 0;
16872 int peers_mon_offline = 0;
16873 int peers_unmon_offline = 0;
16874 int peers_unmon_online = 0;
16875 const char *id;
16876 char idtext[256] = "";
16877 int realtimepeers;
16878 struct sip_peer **peerarray;
16879 int k;
16880
16881 realtimepeers = ast_check_realtime("sippeers");
16882
16883 if (s) {
16884 id = astman_get_header(m, "ActionID");
16885 if (!ast_strlen_zero(id))
16886 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
16887 }
16888
16889 switch (argc) {
16890 case 5:
16891 if (!strcasecmp(argv[3], "like")) {
16892 if (regcomp(®exbuf, argv[4], REG_EXTENDED | REG_NOSUB))
16893 return CLI_SHOWUSAGE;
16894 havepattern = TRUE;
16895 } else
16896 return CLI_SHOWUSAGE;
16897 case 3:
16898 break;
16899 default:
16900 return CLI_SHOWUSAGE;
16901 }
16902
16903 if (!s) {
16904
16905 ast_cli(fd, FORMAT2, "Name/username", "Host", "Dyn", "Forcerport", "ACL", "Port", "Status", (realtimepeers ? "Realtime" : ""));
16906 }
16907
16908 ao2_lock(peers);
16909 if (!(it_peers = ao2_callback(peers, OBJ_MULTIPLE, NULL, NULL))) {
16910 ast_log(AST_LOG_ERROR, "Unable to create iterator for peers container for sip show peers\n");
16911 ao2_unlock(peers);
16912 return CLI_FAILURE;
16913 }
16914 if (!(peerarray = ast_calloc(sizeof(struct sip_peer *), ao2_container_count(peers)))) {
16915 ast_log(AST_LOG_ERROR, "Unable to allocate peer array for sip show peers\n");
16916 ao2_iterator_destroy(it_peers);
16917 ao2_unlock(peers);
16918 return CLI_FAILURE;
16919 }
16920 ao2_unlock(peers);
16921
16922 while ((peer = ao2_t_iterator_next(it_peers, "iterate thru peers table"))) {
16923 ao2_lock(peer);
16924
16925 if (!(peer->type & SIP_TYPE_PEER)) {
16926 ao2_unlock(peer);
16927 unref_peer(peer, "unref peer because it's actually a user");
16928 continue;
16929 }
16930
16931 if (havepattern && regexec(®exbuf, peer->name, 0, NULL, 0)) {
16932 ao2_unlock(peer);
16933 unref_peer(peer, "toss iterator peer ptr before continue");
16934 continue;
16935 }
16936
16937 peerarray[total_peers++] = peer;
16938 ao2_unlock(peer);
16939 }
16940 ao2_iterator_destroy(it_peers);
16941
16942 qsort(peerarray, total_peers, sizeof(struct sip_peer *), peercomparefunc);
16943
16944 for(k=0; k < total_peers; k++) {
16945 char status[20] = "";
16946 char srch[2000];
16947 char pstatus;
16948
16949
16950
16951
16952
16953
16954 char *tmp_port;
16955 char *tmp_host;
16956
16957 peer = peerarray[k];
16958
16959 tmp_port = ast_sockaddr_isnull(&peer->addr) ?
16960 "0" : ast_strdupa(ast_sockaddr_stringify_port(&peer->addr));
16961
16962 tmp_host = ast_sockaddr_isnull(&peer->addr) ?
16963 "(Unspecified)" : ast_strdupa(ast_sockaddr_stringify_addr(&peer->addr));
16964
16965 ao2_lock(peer);
16966 if (havepattern && regexec(®exbuf, peer->name, 0, NULL, 0)) {
16967 ao2_unlock(peer);
16968 peer = peerarray[k] = unref_peer(peer, "toss iterator peer ptr before continue");
16969 continue;
16970 }
16971
16972 if (!ast_strlen_zero(peer->username) && !s)
16973 snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
16974 else
16975 ast_copy_string(name, peer->name, sizeof(name));
16976
16977 pstatus = peer_status(peer, status, sizeof(status));
16978 if (pstatus == 1)
16979 peers_mon_online++;
16980 else if (pstatus == 0)
16981 peers_mon_offline++;
16982 else {
16983 if (ast_sockaddr_isnull(&peer->addr) ||
16984 !ast_sockaddr_port(&peer->addr)) {
16985 peers_unmon_offline++;
16986 } else {
16987 peers_unmon_online++;
16988 }
16989 }
16990
16991 snprintf(srch, sizeof(srch), FORMAT2, name,
16992 tmp_host,
16993 peer->host_dynamic ? " D " : " ",
16994 ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) ? " N " : " ",
16995 peer->ha ? " A " : " ",
16996 tmp_port, status,
16997 realtimepeers ? (peer->is_realtime ? "Cached RT":"") : "");
16998
16999 if (!s) {
17000 ast_cli(fd, FORMAT2, name,
17001 tmp_host,
17002 peer->host_dynamic ? " D " : " ",
17003 ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) ? " N " : " ",
17004 peer->ha ? " A " : " ",
17005 tmp_port, status,
17006 realtimepeers ? (peer->is_realtime ? "Cached RT":"") : "");
17007 } else {
17008
17009 astman_append(s,
17010 "Event: PeerEntry\r\n%s"
17011 "Channeltype: SIP\r\n"
17012 "ObjectName: %s\r\n"
17013 "ChanObjectType: peer\r\n"
17014 "IPaddress: %s\r\n"
17015 "IPport: %s\r\n"
17016 "Dynamic: %s\r\n"
17017 "Forcerport: %s\r\n"
17018 "VideoSupport: %s\r\n"
17019 "TextSupport: %s\r\n"
17020 "ACL: %s\r\n"
17021 "Status: %s\r\n"
17022 "RealtimeDevice: %s\r\n\r\n",
17023 idtext,
17024 peer->name,
17025 ast_sockaddr_isnull(&peer->addr) ? "-none-" : tmp_host,
17026 ast_sockaddr_isnull(&peer->addr) ? "0" : tmp_port,
17027 peer->host_dynamic ? "yes" : "no",
17028 ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) ? "yes" : "no",
17029 ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "yes" : "no",
17030 ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT) ? "yes" : "no",
17031 peer->ha ? "yes" : "no",
17032 status,
17033 realtimepeers ? (peer->is_realtime ? "yes":"no") : "no");
17034 }
17035 ao2_unlock(peer);
17036 peer = peerarray[k] = unref_peer(peer, "toss iterator peer ptr");
17037 }
17038
17039 if (!s)
17040 ast_cli(fd, "%d sip peers [Monitored: %d online, %d offline Unmonitored: %d online, %d offline]\n",
17041 total_peers, peers_mon_online, peers_mon_offline, peers_unmon_online, peers_unmon_offline);
17042
17043 if (havepattern)
17044 regfree(®exbuf);
17045
17046 if (total)
17047 *total = total_peers;
17048
17049 ast_free(peerarray);
17050
17051 return CLI_SUCCESS;
17052 #undef FORMAT2
17053 }
17054
17055 static int peer_dump_func(void *userobj, void *arg, int flags)
17056 {
17057 struct sip_peer *peer = userobj;
17058 int refc = ao2_t_ref(userobj, 0, "");
17059 struct ast_cli_args *a = (struct ast_cli_args *) arg;
17060
17061 ast_cli(a->fd, "name: %s\ntype: peer\nobjflags: %d\nrefcount: %d\n\n",
17062 peer->name, 0, refc);
17063 return 0;
17064 }
17065
17066 static int dialog_dump_func(void *userobj, void *arg, int flags)
17067 {
17068 struct sip_pvt *pvt = userobj;
17069 int refc = ao2_t_ref(userobj, 0, "");
17070 struct ast_cli_args *a = (struct ast_cli_args *) arg;
17071
17072 ast_cli(a->fd, "name: %s\ntype: dialog\nobjflags: %d\nrefcount: %d\n\n",
17073 pvt->callid, 0, refc);
17074 return 0;
17075 }
17076
17077
17078
17079 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17080 {
17081 char tmp[256];
17082
17083 switch (cmd) {
17084 case CLI_INIT:
17085 e->command = "sip show objects";
17086 e->usage =
17087 "Usage: sip show objects\n"
17088 " Lists status of known SIP objects\n";
17089 return NULL;
17090 case CLI_GENERATE:
17091 return NULL;
17092 }
17093
17094 if (a->argc != 3)
17095 return CLI_SHOWUSAGE;
17096 ast_cli(a->fd, "-= Peer objects: %d static, %d realtime, %d autocreate =-\n\n", speerobjs, rpeerobjs, apeerobjs);
17097 ao2_t_callback(peers, OBJ_NODATA, peer_dump_func, a, "initiate ao2_callback to dump peers");
17098 ast_cli(a->fd, "-= Peer objects by IP =-\n\n");
17099 ao2_t_callback(peers_by_ip, OBJ_NODATA, peer_dump_func, a, "initiate ao2_callback to dump peers_by_ip");
17100 ast_cli(a->fd, "-= Registry objects: %d =-\n\n", regobjs);
17101 ASTOBJ_CONTAINER_DUMP(a->fd, tmp, sizeof(tmp), ®l);
17102 ast_cli(a->fd, "-= Dialog objects:\n\n");
17103 ao2_t_callback(dialogs, OBJ_NODATA, dialog_dump_func, a, "initiate ao2_callback to dump dialogs");
17104 return CLI_SUCCESS;
17105 }
17106
17107 static void print_group(int fd, ast_group_t group, int crlf)
17108 {
17109 char buf[256];
17110 ast_cli(fd, crlf ? "%s\r\n" : "%s\n", ast_print_group(buf, sizeof(buf), group) );
17111 }
17112
17113
17114 static const struct _map_x_s dtmfstr[] = {
17115 { SIP_DTMF_RFC2833, "rfc2833" },
17116 { SIP_DTMF_INFO, "info" },
17117 { SIP_DTMF_SHORTINFO, "shortinfo" },
17118 { SIP_DTMF_INBAND, "inband" },
17119 { SIP_DTMF_AUTO, "auto" },
17120 { -1, NULL },
17121 };
17122
17123
17124 static const char *dtmfmode2str(int mode)
17125 {
17126 return map_x_s(dtmfstr, mode, "<error>");
17127 }
17128
17129
17130 static int str2dtmfmode(const char *str)
17131 {
17132 return map_s_x(dtmfstr, str, -1);
17133 }
17134
17135 static const struct _map_x_s insecurestr[] = {
17136 { SIP_INSECURE_PORT, "port" },
17137 { SIP_INSECURE_INVITE, "invite" },
17138 { SIP_INSECURE_PORT | SIP_INSECURE_INVITE, "port,invite" },
17139 { 0, "no" },
17140 { -1, NULL },
17141 };
17142
17143
17144 static const char *insecure2str(int mode)
17145 {
17146 return map_x_s(insecurestr, mode, "<error>");
17147 }
17148
17149 static const struct _map_x_s allowoverlapstr[] = {
17150 { SIP_PAGE2_ALLOWOVERLAP_YES, "Yes" },
17151 { SIP_PAGE2_ALLOWOVERLAP_DTMF, "DTMF" },
17152 { SIP_PAGE2_ALLOWOVERLAP_NO, "No" },
17153 { -1, NULL },
17154 };
17155
17156
17157 static const char *allowoverlap2str(int mode)
17158 {
17159 return map_x_s(allowoverlapstr, mode, "<error>");
17160 }
17161
17162
17163
17164
17165 static void cleanup_stale_contexts(char *new, char *old)
17166 {
17167 char *oldcontext, *newcontext, *stalecontext, *stringp, newlist[AST_MAX_CONTEXT];
17168
17169 while ((oldcontext = strsep(&old, "&"))) {
17170 stalecontext = '\0';
17171 ast_copy_string(newlist, new, sizeof(newlist));
17172 stringp = newlist;
17173 while ((newcontext = strsep(&stringp, "&"))) {
17174 if (!strcmp(newcontext, oldcontext)) {
17175
17176 stalecontext = '\0';
17177 break;
17178 } else if (strcmp(newcontext, oldcontext)) {
17179 stalecontext = oldcontext;
17180 }
17181
17182 }
17183 if (stalecontext)
17184 ast_context_destroy(ast_context_find(stalecontext), "SIP");
17185 }
17186 }
17187
17188
17189
17190
17191
17192
17193
17194
17195
17196
17197
17198 static int dialog_needdestroy(void *dialogobj, void *arg, int flags)
17199 {
17200 struct sip_pvt *dialog = dialogobj;
17201 time_t *t = arg;
17202
17203 if (sip_pvt_trylock(dialog)) {
17204
17205
17206 return 0;
17207 }
17208
17209
17210 check_rtp_timeout(dialog, *t);
17211
17212
17213 if (dialog->rtp && ast_rtp_instance_get_bridged(dialog->rtp)) {
17214 ast_debug(2, "Bridge still active. Delaying destroy of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
17215 sip_pvt_unlock(dialog);
17216 return 0;
17217 }
17218
17219 if (dialog->vrtp && ast_rtp_instance_get_bridged(dialog->vrtp)) {
17220 ast_debug(2, "Bridge still active. Delaying destroy of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
17221 sip_pvt_unlock(dialog);
17222 return 0;
17223 }
17224
17225
17226
17227
17228 if (dialog->needdestroy && !dialog->packets && !dialog->owner) {
17229
17230 if (dialog->rtp && ast_rtp_instance_get_bridged(dialog->rtp)) {
17231 ast_debug(2, "Bridge still active. Delaying destruction of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
17232 sip_pvt_unlock(dialog);
17233 return 0;
17234 }
17235
17236 if (dialog->vrtp && ast_rtp_instance_get_bridged(dialog->vrtp)) {
17237 ast_debug(2, "Bridge still active. Delaying destroy of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
17238 sip_pvt_unlock(dialog);
17239 return 0;
17240 }
17241
17242 sip_pvt_unlock(dialog);
17243
17244
17245 ao2_t_link(dialogs_to_destroy, dialog, "Link dialog for destruction");
17246 return 0;
17247 }
17248
17249 sip_pvt_unlock(dialog);
17250
17251 return 0;
17252 }
17253
17254
17255
17256
17257
17258
17259
17260
17261
17262
17263
17264 static int dialog_unlink_callback(void *obj, void *arg, int flags)
17265 {
17266 struct sip_pvt *dialog = obj;
17267
17268 dialog_unlink_all(dialog);
17269
17270 return CMP_MATCH;
17271 }
17272
17273
17274
17275 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17276 {
17277 struct sip_peer *peer, *pi;
17278 int prunepeer = FALSE;
17279 int multi = FALSE;
17280 const char *name = NULL;
17281 regex_t regexbuf;
17282 int havepattern = 0;
17283 struct ao2_iterator i;
17284 static const char * const choices[] = { "all", "like", NULL };
17285 char *cmplt;
17286
17287 if (cmd == CLI_INIT) {
17288 e->command = "sip prune realtime [peer|all]";
17289 e->usage =
17290 "Usage: sip prune realtime [peer [<name>|all|like <pattern>]|all]\n"
17291 " Prunes object(s) from the cache.\n"
17292 " Optional regular expression pattern is used to filter the objects.\n";
17293 return NULL;
17294 } else if (cmd == CLI_GENERATE) {
17295 if (a->pos == 4 && !strcasecmp(a->argv[3], "peer")) {
17296 cmplt = ast_cli_complete(a->word, choices, a->n);
17297 if (!cmplt)
17298 cmplt = complete_sip_peer(a->word, a->n - sizeof(choices), SIP_PAGE2_RTCACHEFRIENDS);
17299 return cmplt;
17300 }
17301 if (a->pos == 5 && !strcasecmp(a->argv[4], "like"))
17302 return complete_sip_peer(a->word, a->n, SIP_PAGE2_RTCACHEFRIENDS);
17303 return NULL;
17304 }
17305 switch (a->argc) {
17306 case 4:
17307 name = a->argv[3];
17308
17309 if (!strcasecmp(name, "peer") || !strcasecmp(name, "like"))
17310 return CLI_SHOWUSAGE;
17311 prunepeer = TRUE;
17312 if (!strcasecmp(name, "all")) {
17313 multi = TRUE;
17314 name = NULL;
17315 }
17316
17317 break;
17318 case 5:
17319
17320 name = a->argv[4];
17321 if (!strcasecmp(a->argv[3], "peer"))
17322 prunepeer = TRUE;
17323 else if (!strcasecmp(a->argv[3], "like")) {
17324 prunepeer = TRUE;
17325 multi = TRUE;
17326 } else
17327 return CLI_SHOWUSAGE;
17328 if (!strcasecmp(name, "like"))
17329 return CLI_SHOWUSAGE;
17330 if (!multi && !strcasecmp(name, "all")) {
17331 multi = TRUE;
17332 name = NULL;
17333 }
17334 break;
17335 case 6:
17336 name = a->argv[5];
17337 multi = TRUE;
17338
17339 if (strcasecmp(a->argv[4], "like"))
17340 return CLI_SHOWUSAGE;
17341 if (!strcasecmp(a->argv[3], "peer")) {
17342 prunepeer = TRUE;
17343 } else
17344 return CLI_SHOWUSAGE;
17345 break;
17346 default:
17347 return CLI_SHOWUSAGE;
17348 }
17349
17350 if (multi && name) {
17351 if (regcomp(®exbuf, name, REG_EXTENDED | REG_NOSUB)) {
17352 return CLI_SHOWUSAGE;
17353 }
17354 havepattern = 1;
17355 }
17356
17357 if (multi) {
17358 if (prunepeer) {
17359 int pruned = 0;
17360
17361 i = ao2_iterator_init(peers, 0);
17362 while ((pi = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
17363 ao2_lock(pi);
17364 if (name && regexec(®exbuf, pi->name, 0, NULL, 0)) {
17365 ao2_unlock(pi);
17366 unref_peer(pi, "toss iterator peer ptr before continue");
17367 continue;
17368 };
17369 if (ast_test_flag(&pi->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
17370 pi->the_mark = 1;
17371 pruned++;
17372 }
17373 ao2_unlock(pi);
17374 unref_peer(pi, "toss iterator peer ptr");
17375 }
17376 ao2_iterator_destroy(&i);
17377 if (pruned) {
17378 unlink_marked_peers_from_tables();
17379 ast_cli(a->fd, "%d peers pruned.\n", pruned);
17380 } else
17381 ast_cli(a->fd, "No peers found to prune.\n");
17382 }
17383 } else {
17384 if (prunepeer) {
17385 struct sip_peer tmp;
17386 ast_copy_string(tmp.name, name, sizeof(tmp.name));
17387 if ((peer = ao2_t_find(peers, &tmp, OBJ_POINTER | OBJ_UNLINK, "finding to unlink from peers"))) {
17388 if (!ast_sockaddr_isnull(&peer->addr)) {
17389 ao2_t_unlink(peers_by_ip, peer, "unlinking peer from peers_by_ip also");
17390 }
17391 if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
17392 ast_cli(a->fd, "Peer '%s' is not a Realtime peer, cannot be pruned.\n", name);
17393
17394 ao2_t_link(peers, peer, "link peer into peer table");
17395 if (!ast_sockaddr_isnull(&peer->addr)) {
17396 ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
17397 }
17398 } else
17399 ast_cli(a->fd, "Peer '%s' pruned.\n", name);
17400 unref_peer(peer, "sip_prune_realtime: unref_peer: tossing temp peer ptr");
17401 } else
17402 ast_cli(a->fd, "Peer '%s' not found.\n", name);
17403 }
17404 }
17405
17406 if (havepattern) {
17407 regfree(®exbuf);
17408 }
17409
17410 return CLI_SUCCESS;
17411 }
17412
17413
17414 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref)
17415 {
17416 int x;
17417 format_t codec;
17418
17419 for(x = 0; x < 64 ; x++) {
17420 codec = ast_codec_pref_index(pref, x);
17421 if (!codec)
17422 break;
17423 ast_cli(fd, "%s", ast_getformatname(codec));
17424 ast_cli(fd, ":%d", pref->framing[x]);
17425 if (x < 31 && ast_codec_pref_index(pref, x + 1))
17426 ast_cli(fd, ",");
17427 }
17428 if (!x)
17429 ast_cli(fd, "none");
17430 }
17431
17432
17433 static const char *domain_mode_to_text(const enum domain_mode mode)
17434 {
17435 switch (mode) {
17436 case SIP_DOMAIN_AUTO:
17437 return "[Automatic]";
17438 case SIP_DOMAIN_CONFIG:
17439 return "[Configured]";
17440 }
17441
17442 return "";
17443 }
17444
17445
17446 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17447 {
17448 struct domain *d;
17449 #define FORMAT "%-40.40s %-20.20s %-16.16s\n"
17450
17451 switch (cmd) {
17452 case CLI_INIT:
17453 e->command = "sip show domains";
17454 e->usage =
17455 "Usage: sip show domains\n"
17456 " Lists all configured SIP local domains.\n"
17457 " Asterisk only responds to SIP messages to local domains.\n";
17458 return NULL;
17459 case CLI_GENERATE:
17460 return NULL;
17461 }
17462
17463 if (AST_LIST_EMPTY(&domain_list)) {
17464 ast_cli(a->fd, "SIP Domain support not enabled.\n\n");
17465 return CLI_SUCCESS;
17466 } else {
17467 ast_cli(a->fd, FORMAT, "Our local SIP domains:", "Context", "Set by");
17468 AST_LIST_LOCK(&domain_list);
17469 AST_LIST_TRAVERSE(&domain_list, d, list)
17470 ast_cli(a->fd, FORMAT, d->domain, S_OR(d->context, "(default)"),
17471 domain_mode_to_text(d->mode));
17472 AST_LIST_UNLOCK(&domain_list);
17473 ast_cli(a->fd, "\n");
17474 return CLI_SUCCESS;
17475 }
17476 }
17477 #undef FORMAT
17478
17479
17480 static int manager_sip_show_peer(struct mansession *s, const struct message *m)
17481 {
17482 const char *a[4];
17483 const char *peer;
17484
17485 peer = astman_get_header(m, "Peer");
17486 if (ast_strlen_zero(peer)) {
17487 astman_send_error(s, m, "Peer: <name> missing.");
17488 return 0;
17489 }
17490 a[0] = "sip";
17491 a[1] = "show";
17492 a[2] = "peer";
17493 a[3] = peer;
17494
17495 _sip_show_peer(1, -1, s, m, 4, a);
17496 astman_append(s, "\r\n" );
17497 return 0;
17498 }
17499
17500
17501 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17502 {
17503 switch (cmd) {
17504 case CLI_INIT:
17505 e->command = "sip show peer";
17506 e->usage =
17507 "Usage: sip show peer <name> [load]\n"
17508 " Shows all details on one SIP peer and the current status.\n"
17509 " Option \"load\" forces lookup of peer in realtime storage.\n";
17510 return NULL;
17511 case CLI_GENERATE:
17512 return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
17513 }
17514 return _sip_show_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
17515 }
17516
17517
17518 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
17519 {
17520 struct sip_peer *peer;
17521 int load_realtime;
17522
17523 if (argc < 4)
17524 return CLI_SHOWUSAGE;
17525
17526 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
17527 if ((peer = find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0))) {
17528 sip_poke_peer(peer, 1);
17529 unref_peer(peer, "qualify: done with peer");
17530 } else if (type == 0) {
17531 ast_cli(fd, "Peer '%s' not found\n", argv[3]);
17532 } else {
17533 astman_send_error(s, m, "Peer not found");
17534 }
17535 return CLI_SUCCESS;
17536 }
17537
17538
17539 static int manager_sip_qualify_peer(struct mansession *s, const struct message *m)
17540 {
17541 const char *a[4];
17542 const char *peer;
17543
17544 peer = astman_get_header(m, "Peer");
17545 if (ast_strlen_zero(peer)) {
17546 astman_send_error(s, m, "Peer: <name> missing.");
17547 return 0;
17548 }
17549 a[0] = "sip";
17550 a[1] = "qualify";
17551 a[2] = "peer";
17552 a[3] = peer;
17553
17554 _sip_qualify_peer(1, -1, s, m, 4, a);
17555 astman_append(s, "\r\n\r\n" );
17556 return 0;
17557 }
17558
17559
17560 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17561 {
17562 switch (cmd) {
17563 case CLI_INIT:
17564 e->command = "sip qualify peer";
17565 e->usage =
17566 "Usage: sip qualify peer <name> [load]\n"
17567 " Requests a response from one SIP peer and the current status.\n"
17568 " Option \"load\" forces lookup of peer in realtime storage.\n";
17569 return NULL;
17570 case CLI_GENERATE:
17571 return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
17572 }
17573 return _sip_qualify_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
17574 }
17575
17576
17577 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer)
17578 {
17579 struct sip_mailbox *mailbox;
17580
17581 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
17582 ast_str_append(mailbox_str, 0, "%s%s%s%s",
17583 mailbox->mailbox,
17584 ast_strlen_zero(mailbox->context) ? "" : "@",
17585 S_OR(mailbox->context, ""),
17586 AST_LIST_NEXT(mailbox, entry) ? "," : "");
17587 }
17588 }
17589
17590 static struct _map_x_s faxecmodes[] = {
17591 { SIP_PAGE2_T38SUPPORT_UDPTL, "None"},
17592 { SIP_PAGE2_T38SUPPORT_UDPTL_FEC, "FEC"},
17593 { SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY, "Redundancy"},
17594 { -1, NULL},
17595 };
17596
17597 static const char *faxec2str(int faxec)
17598 {
17599 return map_x_s(faxecmodes, faxec, "Unknown");
17600 }
17601
17602
17603 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
17604 {
17605 char status[30] = "";
17606 char cbuf[256];
17607 struct sip_peer *peer;
17608 char codec_buf[512];
17609 struct ast_codec_pref *pref;
17610 struct ast_variable *v;
17611 int x = 0, load_realtime;
17612 format_t codec = 0;
17613 int realtimepeers;
17614
17615 realtimepeers = ast_check_realtime("sippeers");
17616
17617 if (argc < 4)
17618 return CLI_SHOWUSAGE;
17619
17620 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
17621 peer = find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0);
17622
17623 if (s) {
17624 if (peer) {
17625 const char *id = astman_get_header(m, "ActionID");
17626
17627 astman_append(s, "Response: Success\r\n");
17628 if (!ast_strlen_zero(id))
17629 astman_append(s, "ActionID: %s\r\n", id);
17630 } else {
17631 snprintf (cbuf, sizeof(cbuf), "Peer %s not found.", argv[3]);
17632 astman_send_error(s, m, cbuf);
17633 return CLI_SUCCESS;
17634 }
17635 }
17636 if (peer && type==0 ) {
17637 struct ast_str *mailbox_str = ast_str_alloca(512);
17638 struct sip_auth_container *credentials;
17639
17640 ao2_lock(peer);
17641 credentials = peer->auth;
17642 if (credentials) {
17643 ao2_t_ref(credentials, +1, "Ref peer auth for show");
17644 }
17645 ao2_unlock(peer);
17646
17647 ast_cli(fd, "\n\n");
17648 ast_cli(fd, " * Name : %s\n", peer->name);
17649 if (realtimepeers) {
17650 ast_cli(fd, " Realtime peer: %s\n", peer->is_realtime ? "Yes, cached" : "No");
17651 }
17652 ast_cli(fd, " Secret : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
17653 ast_cli(fd, " MD5Secret : %s\n", ast_strlen_zero(peer->md5secret)?"<Not set>":"<Set>");
17654 ast_cli(fd, " Remote Secret: %s\n", ast_strlen_zero(peer->remotesecret)?"<Not set>":"<Set>");
17655 if (credentials) {
17656 struct sip_auth *auth;
17657
17658 AST_LIST_TRAVERSE(&credentials->list, auth, node) {
17659 ast_cli(fd, " Realm-auth : Realm %-15.15s User %-10.20s %s\n",
17660 auth->realm,
17661 auth->username,
17662 !ast_strlen_zero(auth->secret)
17663 ? "<Secret set>"
17664 : (!ast_strlen_zero(auth->md5secret)
17665 ? "<MD5secret set>" : "<Not set>"));
17666 }
17667 ao2_t_ref(credentials, -1, "Unref peer auth for show");
17668 }
17669 ast_cli(fd, " Context : %s\n", peer->context);
17670 ast_cli(fd, " Subscr.Cont. : %s\n", S_OR(peer->subscribecontext, "<Not set>") );
17671 ast_cli(fd, " Language : %s\n", peer->language);
17672 if (!ast_strlen_zero(peer->accountcode))
17673 ast_cli(fd, " Accountcode : %s\n", peer->accountcode);
17674 ast_cli(fd, " AMA flags : %s\n", ast_cdr_flags2str(peer->amaflags));
17675 ast_cli(fd, " Transfer mode: %s\n", transfermode2str(peer->allowtransfer));
17676 ast_cli(fd, " CallingPres : %s\n", ast_describe_caller_presentation(peer->callingpres));
17677 if (!ast_strlen_zero(peer->fromuser))
17678 ast_cli(fd, " FromUser : %s\n", peer->fromuser);
17679 if (!ast_strlen_zero(peer->fromdomain))
17680 ast_cli(fd, " FromDomain : %s Port %d\n", peer->fromdomain, (peer->fromdomainport) ? peer->fromdomainport : STANDARD_SIP_PORT);
17681 ast_cli(fd, " Callgroup : ");
17682 print_group(fd, peer->callgroup, 0);
17683 ast_cli(fd, " Pickupgroup : ");
17684 print_group(fd, peer->pickupgroup, 0);
17685 peer_mailboxes_to_str(&mailbox_str, peer);
17686 ast_cli(fd, " MOH Suggest : %s\n", peer->mohsuggest);
17687 ast_cli(fd, " Mailbox : %s\n", mailbox_str->str);
17688 ast_cli(fd, " VM Extension : %s\n", peer->vmexten);
17689 ast_cli(fd, " LastMsgsSent : %d/%d\n", (peer->lastmsgssent & 0x7fff0000) >> 16, peer->lastmsgssent & 0xffff);
17690 ast_cli(fd, " Call limit : %d\n", peer->call_limit);
17691 ast_cli(fd, " Max forwards : %d\n", peer->maxforwards);
17692 if (peer->busy_level)
17693 ast_cli(fd, " Busy level : %d\n", peer->busy_level);
17694 ast_cli(fd, " Dynamic : %s\n", AST_CLI_YESNO(peer->host_dynamic));
17695 ast_cli(fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
17696 ast_cli(fd, " MaxCallBR : %d kbps\n", peer->maxcallbitrate);
17697 ast_cli(fd, " Expire : %ld\n", ast_sched_when(sched, peer->expire));
17698 ast_cli(fd, " Insecure : %s\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
17699 ast_cli(fd, " Force rport : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT)));
17700 ast_cli(fd, " ACL : %s\n", AST_CLI_YESNO(peer->ha != NULL));
17701 ast_cli(fd, " DirectMedACL : %s\n", AST_CLI_YESNO(peer->directmediaha != NULL));
17702 ast_cli(fd, " T.38 support : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
17703 ast_cli(fd, " T.38 EC mode : %s\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
17704 ast_cli(fd, " T.38 MaxDtgrm: %d\n", peer->t38_maxdatagram);
17705 ast_cli(fd, " DirectMedia : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)));
17706 ast_cli(fd, " PromiscRedir : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)));
17707 ast_cli(fd, " User=Phone : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)));
17708 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)));
17709 ast_cli(fd, " Text Support : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)));
17710 ast_cli(fd, " Ign SDP ver : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_IGNORESDPVERSION)));
17711 ast_cli(fd, " Trust RPID : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_TRUSTRPID)));
17712 ast_cli(fd, " Send RPID : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_SENDRPID)));
17713 ast_cli(fd, " Subscriptions: %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
17714 ast_cli(fd, " Overlap dial : %s\n", allowoverlap2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWOVERLAP)));
17715 if (peer->outboundproxy)
17716 ast_cli(fd, " Outb. proxy : %s %s\n", ast_strlen_zero(peer->outboundproxy->name) ? "<not set>" : peer->outboundproxy->name,
17717 peer->outboundproxy->force ? "(forced)" : "");
17718
17719
17720 ast_cli(fd, " DTMFmode : %s\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
17721 ast_cli(fd, " Timer T1 : %d\n", peer->timer_t1);
17722 ast_cli(fd, " Timer B : %d\n", peer->timer_b);
17723 ast_cli(fd, " ToHost : %s\n", peer->tohost);
17724 ast_cli(fd, " Addr->IP : %s\n", ast_sockaddr_stringify(&peer->addr));
17725 ast_cli(fd, " Defaddr->IP : %s\n", ast_sockaddr_stringify(&peer->defaddr));
17726 ast_cli(fd, " Prim.Transp. : %s\n", get_transport(peer->socket.type));
17727 ast_cli(fd, " Allowed.Trsp : %s\n", get_transport_list(peer->transports));
17728 if (!ast_strlen_zero(sip_cfg.regcontext))
17729 ast_cli(fd, " Reg. exten : %s\n", peer->regexten);
17730 ast_cli(fd, " Def. Username: %s\n", peer->username);
17731 ast_cli(fd, " SIP Options : ");
17732 if (peer->sipoptions) {
17733 int lastoption = -1;
17734 for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
17735 if (sip_options[x].id != lastoption) {
17736 if (peer->sipoptions & sip_options[x].id)
17737 ast_cli(fd, "%s ", sip_options[x].text);
17738 lastoption = x;
17739 }
17740 }
17741 } else
17742 ast_cli(fd, "(none)");
17743
17744 ast_cli(fd, "\n");
17745 ast_cli(fd, " Codecs : ");
17746 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
17747 ast_cli(fd, "%s\n", codec_buf);
17748 ast_cli(fd, " Codec Order : (");
17749 print_codec_to_cli(fd, &peer->prefs);
17750 ast_cli(fd, ")\n");
17751
17752 ast_cli(fd, " Auto-Framing : %s \n", AST_CLI_YESNO(peer->autoframing));
17753 ast_cli(fd, " Status : ");
17754 peer_status(peer, status, sizeof(status));
17755 ast_cli(fd, "%s\n", status);
17756 ast_cli(fd, " Useragent : %s\n", peer->useragent);
17757 ast_cli(fd, " Reg. Contact : %s\n", peer->fullcontact);
17758 ast_cli(fd, " Qualify Freq : %d ms\n", peer->qualifyfreq);
17759 if (peer->chanvars) {
17760 ast_cli(fd, " Variables :\n");
17761 for (v = peer->chanvars ; v ; v = v->next)
17762 ast_cli(fd, " %s = %s\n", v->name, v->value);
17763 }
17764
17765 ast_cli(fd, " Sess-Timers : %s\n", stmode2str(peer->stimer.st_mode_oper));
17766 ast_cli(fd, " Sess-Refresh : %s\n", strefresherparam2str(peer->stimer.st_ref));
17767 ast_cli(fd, " Sess-Expires : %d secs\n", peer->stimer.st_max_se);
17768 ast_cli(fd, " Min-Sess : %d secs\n", peer->stimer.st_min_se);
17769 ast_cli(fd, " RTP Engine : %s\n", peer->engine);
17770 ast_cli(fd, " Parkinglot : %s\n", peer->parkinglot);
17771 ast_cli(fd, " Use Reason : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_Q850_REASON)));
17772 ast_cli(fd, " Encryption : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_USE_SRTP)));
17773 ast_cli(fd, "\n");
17774 peer = unref_peer(peer, "sip_show_peer: unref_peer: done with peer ptr");
17775 } else if (peer && type == 1) {
17776 char buffer[256];
17777 struct ast_str *mailbox_str = ast_str_alloca(512);
17778 astman_append(s, "Channeltype: SIP\r\n");
17779 astman_append(s, "ObjectName: %s\r\n", peer->name);
17780 astman_append(s, "ChanObjectType: peer\r\n");
17781 astman_append(s, "SecretExist: %s\r\n", ast_strlen_zero(peer->secret)?"N":"Y");
17782 astman_append(s, "RemoteSecretExist: %s\r\n", ast_strlen_zero(peer->remotesecret)?"N":"Y");
17783 astman_append(s, "MD5SecretExist: %s\r\n", ast_strlen_zero(peer->md5secret)?"N":"Y");
17784 astman_append(s, "Context: %s\r\n", peer->context);
17785 astman_append(s, "Language: %s\r\n", peer->language);
17786 if (!ast_strlen_zero(peer->accountcode))
17787 astman_append(s, "Accountcode: %s\r\n", peer->accountcode);
17788 astman_append(s, "AMAflags: %s\r\n", ast_cdr_flags2str(peer->amaflags));
17789 astman_append(s, "CID-CallingPres: %s\r\n", ast_describe_caller_presentation(peer->callingpres));
17790 if (!ast_strlen_zero(peer->fromuser))
17791 astman_append(s, "SIP-FromUser: %s\r\n", peer->fromuser);
17792 if (!ast_strlen_zero(peer->fromdomain))
17793 astman_append(s, "SIP-FromDomain: %s\r\nSip-FromDomain-Port: %d\r\n", peer->fromdomain, (peer->fromdomainport) ? peer->fromdomainport : STANDARD_SIP_PORT);
17794 astman_append(s, "Callgroup: ");
17795 astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->callgroup));
17796 astman_append(s, "Pickupgroup: ");
17797 astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->pickupgroup));
17798 astman_append(s, "MOHSuggest: %s\r\n", peer->mohsuggest);
17799 peer_mailboxes_to_str(&mailbox_str, peer);
17800 astman_append(s, "VoiceMailbox: %s\r\n", mailbox_str->str);
17801 astman_append(s, "TransferMode: %s\r\n", transfermode2str(peer->allowtransfer));
17802 astman_append(s, "LastMsgsSent: %d\r\n", peer->lastmsgssent);
17803 astman_append(s, "Maxforwards: %d\r\n", peer->maxforwards);
17804 astman_append(s, "Call-limit: %d\r\n", peer->call_limit);
17805 astman_append(s, "Busy-level: %d\r\n", peer->busy_level);
17806 astman_append(s, "MaxCallBR: %d kbps\r\n", peer->maxcallbitrate);
17807 astman_append(s, "Dynamic: %s\r\n", peer->host_dynamic?"Y":"N");
17808 astman_append(s, "Callerid: %s\r\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, ""));
17809 astman_append(s, "RegExpire: %ld seconds\r\n", ast_sched_when(sched, peer->expire));
17810 astman_append(s, "SIP-AuthInsecure: %s\r\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
17811 astman_append(s, "SIP-Forcerport: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT)?"Y":"N"));
17812 astman_append(s, "ACL: %s\r\n", (peer->ha?"Y":"N"));
17813 astman_append(s, "SIP-CanReinvite: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)?"Y":"N"));
17814 astman_append(s, "SIP-DirectMedia: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)?"Y":"N"));
17815 astman_append(s, "SIP-PromiscRedir: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)?"Y":"N"));
17816 astman_append(s, "SIP-UserPhone: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)?"Y":"N"));
17817 astman_append(s, "SIP-VideoSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)?"Y":"N"));
17818 astman_append(s, "SIP-TextSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)?"Y":"N"));
17819 astman_append(s, "SIP-T.38Support: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)?"Y":"N"));
17820 astman_append(s, "SIP-T.38EC: %s\r\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
17821 astman_append(s, "SIP-T.38MaxDtgrm: %d\r\n", peer->t38_maxdatagram);
17822 astman_append(s, "SIP-Sess-Timers: %s\r\n", stmode2str(peer->stimer.st_mode_oper));
17823 astman_append(s, "SIP-Sess-Refresh: %s\r\n", strefresherparam2str(peer->stimer.st_ref));
17824 astman_append(s, "SIP-Sess-Expires: %d\r\n", peer->stimer.st_max_se);
17825 astman_append(s, "SIP-Sess-Min: %d\r\n", peer->stimer.st_min_se);
17826 astman_append(s, "SIP-RTP-Engine: %s\r\n", peer->engine);
17827 astman_append(s, "SIP-Encryption: %s\r\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_USE_SRTP) ? "Y" : "N");
17828
17829
17830 astman_append(s, "SIP-DTMFmode: %s\r\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
17831 astman_append(s, "ToHost: %s\r\n", peer->tohost);
17832 astman_append(s, "Address-IP: %s\r\nAddress-Port: %d\r\n", ast_sockaddr_stringify_addr(&peer->addr), ast_sockaddr_port(&peer->addr));
17833 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));
17834 astman_append(s, "Default-Username: %s\r\n", peer->username);
17835 if (!ast_strlen_zero(sip_cfg.regcontext))
17836 astman_append(s, "RegExtension: %s\r\n", peer->regexten);
17837 astman_append(s, "Codecs: ");
17838 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
17839 astman_append(s, "%s\r\n", codec_buf);
17840 astman_append(s, "CodecOrder: ");
17841 pref = &peer->prefs;
17842 for(x = 0; x < 64 ; x++) {
17843 codec = ast_codec_pref_index(pref, x);
17844 if (!codec)
17845 break;
17846 astman_append(s, "%s", ast_getformatname(codec));
17847 if (x < 63 && ast_codec_pref_index(pref, x+1))
17848 astman_append(s, ",");
17849 }
17850
17851 astman_append(s, "\r\n");
17852 astman_append(s, "Status: ");
17853 peer_status(peer, status, sizeof(status));
17854 astman_append(s, "%s\r\n", status);
17855 astman_append(s, "SIP-Useragent: %s\r\n", peer->useragent);
17856 astman_append(s, "Reg-Contact: %s\r\n", peer->fullcontact);
17857 astman_append(s, "QualifyFreq: %d ms\r\n", peer->qualifyfreq);
17858 astman_append(s, "Parkinglot: %s\r\n", peer->parkinglot);
17859 if (peer->chanvars) {
17860 for (v = peer->chanvars ; v ; v = v->next) {
17861 astman_append(s, "ChanVariable: %s=%s\r\n", v->name, v->value);
17862 }
17863 }
17864 astman_append(s, "SIP-Use-Reason-Header: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_Q850_REASON)) ? "Y" : "N");
17865
17866 peer = unref_peer(peer, "sip_show_peer: unref_peer: done with peer");
17867
17868 } else {
17869 ast_cli(fd, "Peer %s not found.\n", argv[3]);
17870 ast_cli(fd, "\n");
17871 }
17872
17873 return CLI_SUCCESS;
17874 }
17875
17876
17877 static char *complete_sip_user(const char *word, int state)
17878 {
17879 char *result = NULL;
17880 int wordlen = strlen(word);
17881 int which = 0;
17882 struct ao2_iterator user_iter;
17883 struct sip_peer *user;
17884
17885 user_iter = ao2_iterator_init(peers, 0);
17886 while ((user = ao2_t_iterator_next(&user_iter, "iterate thru peers table"))) {
17887 ao2_lock(user);
17888 if (!(user->type & SIP_TYPE_USER)) {
17889 ao2_unlock(user);
17890 unref_peer(user, "complete sip user");
17891 continue;
17892 }
17893
17894 if (!strncasecmp(word, user->name, wordlen) && ++which > state) {
17895 result = ast_strdup(user->name);
17896 }
17897 ao2_unlock(user);
17898 unref_peer(user, "complete sip user");
17899 if (result) {
17900 break;
17901 }
17902 }
17903 ao2_iterator_destroy(&user_iter);
17904 return result;
17905 }
17906
17907 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state)
17908 {
17909 if (pos == 3)
17910 return complete_sip_user(word, state);
17911
17912 return NULL;
17913 }
17914
17915
17916 static char *sip_show_user(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17917 {
17918 char cbuf[256];
17919 struct sip_peer *user;
17920 struct ast_variable *v;
17921 int load_realtime;
17922
17923 switch (cmd) {
17924 case CLI_INIT:
17925 e->command = "sip show user";
17926 e->usage =
17927 "Usage: sip show user <name> [load]\n"
17928 " Shows all details on one SIP user and the current status.\n"
17929 " Option \"load\" forces lookup of peer in realtime storage.\n";
17930 return NULL;
17931 case CLI_GENERATE:
17932 return complete_sip_show_user(a->line, a->word, a->pos, a->n);
17933 }
17934
17935 if (a->argc < 4)
17936 return CLI_SHOWUSAGE;
17937
17938
17939 load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? TRUE : FALSE;
17940
17941 if ((user = find_peer(a->argv[3], NULL, load_realtime, FINDUSERS, FALSE, 0))) {
17942 ao2_lock(user);
17943 ast_cli(a->fd, "\n\n");
17944 ast_cli(a->fd, " * Name : %s\n", user->name);
17945 ast_cli(a->fd, " Secret : %s\n", ast_strlen_zero(user->secret)?"<Not set>":"<Set>");
17946 ast_cli(a->fd, " MD5Secret : %s\n", ast_strlen_zero(user->md5secret)?"<Not set>":"<Set>");
17947 ast_cli(a->fd, " Context : %s\n", user->context);
17948 ast_cli(a->fd, " Language : %s\n", user->language);
17949 if (!ast_strlen_zero(user->accountcode))
17950 ast_cli(a->fd, " Accountcode : %s\n", user->accountcode);
17951 ast_cli(a->fd, " AMA flags : %s\n", ast_cdr_flags2str(user->amaflags));
17952 ast_cli(a->fd, " Transfer mode: %s\n", transfermode2str(user->allowtransfer));
17953 ast_cli(a->fd, " MaxCallBR : %d kbps\n", user->maxcallbitrate);
17954 ast_cli(a->fd, " CallingPres : %s\n", ast_describe_caller_presentation(user->callingpres));
17955 ast_cli(a->fd, " Call limit : %d\n", user->call_limit);
17956 ast_cli(a->fd, " Callgroup : ");
17957 print_group(a->fd, user->callgroup, 0);
17958 ast_cli(a->fd, " Pickupgroup : ");
17959 print_group(a->fd, user->pickupgroup, 0);
17960 ast_cli(a->fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), user->cid_name, user->cid_num, "<unspecified>"));
17961 ast_cli(a->fd, " ACL : %s\n", AST_CLI_YESNO(user->ha != NULL));
17962 ast_cli(a->fd, " Sess-Timers : %s\n", stmode2str(user->stimer.st_mode_oper));
17963 ast_cli(a->fd, " Sess-Refresh : %s\n", strefresherparam2str(user->stimer.st_ref));
17964 ast_cli(a->fd, " Sess-Expires : %d secs\n", user->stimer.st_max_se);
17965 ast_cli(a->fd, " Sess-Min-SE : %d secs\n", user->stimer.st_min_se);
17966 ast_cli(a->fd, " RTP Engine : %s\n", user->engine);
17967
17968 ast_cli(a->fd, " Codec Order : (");
17969 print_codec_to_cli(a->fd, &user->prefs);
17970 ast_cli(a->fd, ")\n");
17971
17972 ast_cli(a->fd, " Auto-Framing: %s \n", AST_CLI_YESNO(user->autoframing));
17973 if (user->chanvars) {
17974 ast_cli(a->fd, " Variables :\n");
17975 for (v = user->chanvars ; v ; v = v->next)
17976 ast_cli(a->fd, " %s = %s\n", v->name, v->value);
17977 }
17978
17979 ast_cli(a->fd, "\n");
17980
17981 ao2_unlock(user);
17982 unref_peer(user, "sip show user");
17983 } else {
17984 ast_cli(a->fd, "User %s not found.\n", a->argv[3]);
17985 ast_cli(a->fd, "\n");
17986 }
17987
17988 return CLI_SUCCESS;
17989 }
17990
17991
17992 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17993 {
17994 struct ast_str *cbuf;
17995 struct ast_cb_names cbnames = {9, { "retrans_pkt",
17996 "__sip_autodestruct",
17997 "expire_register",
17998 "auto_congest",
17999 "sip_reg_timeout",
18000 "sip_poke_peer_s",
18001 "sip_poke_noanswer",
18002 "sip_reregister",
18003 "sip_reinvite_retry"},
18004 { retrans_pkt,
18005 __sip_autodestruct,
18006 expire_register,
18007 auto_congest,
18008 sip_reg_timeout,
18009 sip_poke_peer_s,
18010 sip_poke_noanswer,
18011 sip_reregister,
18012 sip_reinvite_retry}};
18013
18014 switch (cmd) {
18015 case CLI_INIT:
18016 e->command = "sip show sched";
18017 e->usage =
18018 "Usage: sip show sched\n"
18019 " Shows stats on what's in the sched queue at the moment\n";
18020 return NULL;
18021 case CLI_GENERATE:
18022 return NULL;
18023 }
18024
18025 cbuf = ast_str_alloca(2048);
18026
18027 ast_cli(a->fd, "\n");
18028 ast_sched_report(sched, &cbuf, &cbnames);
18029 ast_cli(a->fd, "%s", cbuf->str);
18030
18031 return CLI_SUCCESS;
18032 }
18033
18034
18035 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18036 {
18037 #define FORMAT2 "%-39.39s %-6.6s %-12.12s %8.8s %-20.20s %-25.25s\n"
18038 #define FORMAT "%-39.39s %-6.6s %-12.12s %8d %-20.20s %-25.25s\n"
18039 char host[80];
18040 char user[80];
18041 char tmpdat[256];
18042 struct ast_tm tm;
18043 int counter = 0;
18044
18045 switch (cmd) {
18046 case CLI_INIT:
18047 e->command = "sip show registry";
18048 e->usage =
18049 "Usage: sip show registry\n"
18050 " Lists all registration requests and status.\n";
18051 return NULL;
18052 case CLI_GENERATE:
18053 return NULL;
18054 }
18055
18056 if (a->argc != 3)
18057 return CLI_SHOWUSAGE;
18058 ast_cli(a->fd, FORMAT2, "Host", "dnsmgr", "Username", "Refresh", "State", "Reg.Time");
18059
18060 ASTOBJ_CONTAINER_TRAVERSE(®l, 1, do {
18061 ASTOBJ_RDLOCK(iterator);
18062 snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
18063 snprintf(user, sizeof(user), "%s", iterator->username);
18064 if (!ast_strlen_zero(iterator->regdomain)) {
18065 snprintf(tmpdat, sizeof(tmpdat), "%s", user);
18066 snprintf(user, sizeof(user), "%s@%s", tmpdat, iterator->regdomain);}
18067 if (iterator->regdomainport) {
18068 snprintf(tmpdat, sizeof(tmpdat), "%s", user);
18069 snprintf(user, sizeof(user), "%s:%d", tmpdat, iterator->regdomainport);}
18070 if (iterator->regtime.tv_sec) {
18071 ast_localtime(&iterator->regtime, &tm, NULL);
18072 ast_strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T", &tm);
18073 } else
18074 tmpdat[0] = '\0';
18075 ast_cli(a->fd, FORMAT, host, (iterator->dnsmgr) ? "Y" : "N", user, iterator->refresh, regstate2str(iterator->regstate), tmpdat);
18076 ASTOBJ_UNLOCK(iterator);
18077 counter++;
18078 } while(0));
18079 ast_cli(a->fd, "%d SIP registrations.\n", counter);
18080 return CLI_SUCCESS;
18081 #undef FORMAT
18082 #undef FORMAT2
18083 }
18084
18085
18086
18087
18088
18089 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18090 {
18091 struct sip_peer *peer;
18092 int load_realtime = 0;
18093
18094 switch (cmd) {
18095 case CLI_INIT:
18096 e->command = "sip unregister";
18097 e->usage =
18098 "Usage: sip unregister <peer>\n"
18099 " Unregister (force expiration) a SIP peer from the registry\n";
18100 return NULL;
18101 case CLI_GENERATE:
18102 return complete_sip_unregister(a->line, a->word, a->pos, a->n);
18103 }
18104
18105 if (a->argc != 3)
18106 return CLI_SHOWUSAGE;
18107
18108 if ((peer = find_peer(a->argv[2], NULL, load_realtime, FINDPEERS, TRUE, 0))) {
18109 if (peer->expire > 0) {
18110 AST_SCHED_DEL_UNREF(sched, peer->expire,
18111 unref_peer(peer, "remove register expire ref"));
18112 expire_register(ref_peer(peer, "ref for expire_register"));
18113 ast_cli(a->fd, "Unregistered peer \'%s\'\n\n", a->argv[2]);
18114 } else {
18115 ast_cli(a->fd, "Peer %s not registered\n", a->argv[2]);
18116 }
18117 unref_peer(peer, "sip_unregister: unref_peer via sip_unregister: done with peer from find_peer call");
18118 } else {
18119 ast_cli(a->fd, "Peer unknown: \'%s\'. Not unregistered.\n", a->argv[2]);
18120 }
18121
18122 return CLI_SUCCESS;
18123 }
18124
18125
18126 static int show_chanstats_cb(void *__cur, void *__arg, int flags)
18127 {
18128 #define FORMAT2 "%-15.15s %-11.11s %-8.8s %-10.10s %-10.10s ( %%) %-6.6s %-10.10s %-10.10s ( %%) %-6.6s\n"
18129 #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"
18130 struct sip_pvt *cur = __cur;
18131 struct ast_rtp_instance_stats stats;
18132 char durbuf[10];
18133 int duration;
18134 int durh, durm, durs;
18135 struct ast_channel *c;
18136 struct __show_chan_arg *arg = __arg;
18137 int fd = arg->fd;
18138
18139 sip_pvt_lock(cur);
18140 c = cur->owner;
18141
18142 if (cur->subscribed != NONE) {
18143
18144 sip_pvt_unlock(cur);
18145 return 0;
18146 }
18147
18148 if (!cur->rtp) {
18149 if (sipdebug) {
18150 ast_cli(fd, "%-15.15s %-11.11s (inv state: %s) -- %s\n",
18151 ast_sockaddr_stringify_addr(&cur->sa), cur->callid,
18152 invitestate2string[cur->invitestate].desc,
18153 "-- No RTP active");
18154 }
18155 sip_pvt_unlock(cur);
18156 return 0;
18157 }
18158
18159 if (ast_rtp_instance_get_stats(cur->rtp, &stats, AST_RTP_INSTANCE_STAT_ALL)) {
18160 sip_pvt_unlock(cur);
18161 ast_log(LOG_WARNING, "Could not get RTP stats.\n");
18162 return 0;
18163 }
18164
18165 if (c && c->cdr && !ast_tvzero(c->cdr->start)) {
18166 duration = (int)(ast_tvdiff_ms(ast_tvnow(), c->cdr->start) / 1000);
18167 durh = duration / 3600;
18168 durm = (duration % 3600) / 60;
18169 durs = duration % 60;
18170 snprintf(durbuf, sizeof(durbuf), "%02d:%02d:%02d", durh, durm, durs);
18171 } else {
18172 durbuf[0] = '\0';
18173 }
18174
18175 ast_cli(fd, FORMAT,
18176 ast_sockaddr_stringify_addr(&cur->sa),
18177 cur->callid,
18178 durbuf,
18179 stats.rxcount > (unsigned int) 100000 ? (unsigned int) (stats.rxcount)/(unsigned int) 1000 : stats.rxcount,
18180 stats.rxcount > (unsigned int) 100000 ? "K":" ",
18181 stats.rxploss,
18182 (stats.rxcount + stats.rxploss) > 0 ? (double) stats.rxploss / (stats.rxcount + stats.rxploss) * 100 : 0,
18183 stats.rxjitter,
18184 stats.txcount > (unsigned int) 100000 ? (unsigned int) (stats.txcount)/(unsigned int) 1000 : stats.txcount,
18185 stats.txcount > (unsigned int) 100000 ? "K":" ",
18186 stats.txploss,
18187 stats.txcount > 0 ? (double) stats.txploss / stats.txcount * 100 : 0,
18188 stats.txjitter
18189 );
18190 arg->numchans++;
18191 sip_pvt_unlock(cur);
18192
18193 return 0;
18194 }
18195
18196
18197 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18198 {
18199 struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
18200
18201 switch (cmd) {
18202 case CLI_INIT:
18203 e->command = "sip show channelstats";
18204 e->usage =
18205 "Usage: sip show channelstats\n"
18206 " Lists all currently active SIP channel's RTCP statistics.\n"
18207 " Note that calls in the much optimized RTP P2P bridge mode will not show any packets here.";
18208 return NULL;
18209 case CLI_GENERATE:
18210 return NULL;
18211 }
18212
18213 if (a->argc != 3)
18214 return CLI_SHOWUSAGE;
18215
18216 ast_cli(a->fd, FORMAT2, "Peer", "Call ID", "Duration", "Recv: Pack", "Lost", "Jitter", "Send: Pack", "Lost", "Jitter");
18217
18218 ao2_t_callback(dialogs, OBJ_NODATA, show_chanstats_cb, &arg, "callback to sip show chanstats");
18219 ast_cli(a->fd, "%d active SIP channel%s\n", arg.numchans, (arg.numchans != 1) ? "s" : "");
18220 return CLI_SUCCESS;
18221 }
18222 #undef FORMAT
18223 #undef FORMAT2
18224
18225
18226 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18227 {
18228 int realtimepeers;
18229 int realtimeregs;
18230 char codec_buf[SIPBUFSIZE];
18231 const char *msg;
18232 struct sip_auth_container *credentials;
18233
18234 switch (cmd) {
18235 case CLI_INIT:
18236 e->command = "sip show settings";
18237 e->usage =
18238 "Usage: sip show settings\n"
18239 " Provides detailed list of the configuration of the SIP channel.\n";
18240 return NULL;
18241 case CLI_GENERATE:
18242 return NULL;
18243 }
18244
18245 if (a->argc != 3)
18246 return CLI_SHOWUSAGE;
18247
18248 realtimepeers = ast_check_realtime("sippeers");
18249 realtimeregs = ast_check_realtime("sipregs");
18250
18251 ast_mutex_lock(&authl_lock);
18252 credentials = authl;
18253 if (credentials) {
18254 ao2_t_ref(credentials, +1, "Ref global auth for show");
18255 }
18256 ast_mutex_unlock(&authl_lock);
18257
18258 ast_cli(a->fd, "\n\nGlobal Settings:\n");
18259 ast_cli(a->fd, "----------------\n");
18260 ast_cli(a->fd, " UDP Bindaddress: %s\n", ast_sockaddr_stringify(&bindaddr));
18261 if (ast_sockaddr_is_ipv6(&bindaddr) && ast_sockaddr_is_any(&bindaddr)) {
18262 ast_cli(a->fd, " ** Additional Info:\n");
18263 ast_cli(a->fd, " [::] may include IPv4 in addition to IPv6, if such a feature is enabled in the OS.\n");
18264 }
18265 ast_cli(a->fd, " TCP SIP Bindaddress: %s\n",
18266 sip_cfg.tcp_enabled != FALSE ?
18267 ast_sockaddr_stringify(&sip_tcp_desc.local_address) :
18268 "Disabled");
18269 ast_cli(a->fd, " TLS SIP Bindaddress: %s\n",
18270 default_tls_cfg.enabled != FALSE ?
18271 ast_sockaddr_stringify(&sip_tls_desc.local_address) :
18272 "Disabled");
18273 ast_cli(a->fd, " Videosupport: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT)));
18274 ast_cli(a->fd, " Textsupport: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT)));
18275 ast_cli(a->fd, " Ignore SDP sess. ver.: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION)));
18276 ast_cli(a->fd, " AutoCreate Peer: %s\n", AST_CLI_YESNO(sip_cfg.autocreatepeer));
18277 ast_cli(a->fd, " Match Auth Username: %s\n", AST_CLI_YESNO(global_match_auth_username));
18278 ast_cli(a->fd, " Allow unknown access: %s\n", AST_CLI_YESNO(sip_cfg.allowguest));
18279 ast_cli(a->fd, " Allow subscriptions: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
18280 ast_cli(a->fd, " Allow overlap dialing: %s\n", allowoverlap2str(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP)));
18281 ast_cli(a->fd, " Allow promisc. redir: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_PROMISCREDIR)));
18282 ast_cli(a->fd, " Enable call counters: %s\n", AST_CLI_YESNO(global_callcounter));
18283 ast_cli(a->fd, " SIP domain support: %s\n", AST_CLI_YESNO(!AST_LIST_EMPTY(&domain_list)));
18284 ast_cli(a->fd, " Realm. auth: %s\n", AST_CLI_YESNO(credentials != NULL));
18285 if (credentials) {
18286 struct sip_auth *auth;
18287
18288 AST_LIST_TRAVERSE(&credentials->list, auth, node) {
18289 ast_cli(a->fd, " Realm. auth entry: Realm %-15.15s User %-10.20s %s\n",
18290 auth->realm,
18291 auth->username,
18292 !ast_strlen_zero(auth->secret)
18293 ? "<Secret set>"
18294 : (!ast_strlen_zero(auth->md5secret)
18295 ? "<MD5secret set>" : "<Not set>"));
18296 }
18297 ao2_t_ref(credentials, -1, "Unref global auth for show");
18298 }
18299 ast_cli(a->fd, " Our auth realm %s\n", sip_cfg.realm);
18300 ast_cli(a->fd, " Use domains as realms: %s\n", AST_CLI_YESNO(sip_cfg.domainsasrealm));
18301 ast_cli(a->fd, " Call to non-local dom.: %s\n", AST_CLI_YESNO(sip_cfg.allow_external_domains));
18302 ast_cli(a->fd, " URI user is phone no: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_USEREQPHONE)));
18303 ast_cli(a->fd, " Always auth rejects: %s\n", AST_CLI_YESNO(sip_cfg.alwaysauthreject));
18304 ast_cli(a->fd, " Direct RTP setup: %s\n", AST_CLI_YESNO(sip_cfg.directrtpsetup));
18305 ast_cli(a->fd, " User Agent: %s\n", global_useragent);
18306 ast_cli(a->fd, " SDP Session Name: %s\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
18307 ast_cli(a->fd, " SDP Owner Name: %s\n", ast_strlen_zero(global_sdpowner) ? "-" : global_sdpowner);
18308 ast_cli(a->fd, " Reg. context: %s\n", S_OR(sip_cfg.regcontext, "(not set)"));
18309 ast_cli(a->fd, " Regexten on Qualify: %s\n", AST_CLI_YESNO(sip_cfg.regextenonqualify));
18310 ast_cli(a->fd, " Legacy userfield parse: %s\n", AST_CLI_YESNO(sip_cfg.legacy_useroption_parsing));
18311 ast_cli(a->fd, " Caller ID: %s\n", default_callerid);
18312 if ((default_fromdomainport) && (default_fromdomainport != STANDARD_SIP_PORT)) {
18313 ast_cli(a->fd, " From: Domain: %s:%d\n", default_fromdomain, default_fromdomainport);
18314 } else {
18315 ast_cli(a->fd, " From: Domain: %s\n", default_fromdomain);
18316 }
18317 ast_cli(a->fd, " Record SIP history: %s\n", AST_CLI_ONOFF(recordhistory));
18318 ast_cli(a->fd, " Call Events: %s\n", AST_CLI_ONOFF(sip_cfg.callevents));
18319 ast_cli(a->fd, " Auth. Failure Events: %s\n", AST_CLI_ONOFF(global_authfailureevents));
18320
18321 ast_cli(a->fd, " T.38 support: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
18322 ast_cli(a->fd, " T.38 EC mode: %s\n", faxec2str(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
18323 ast_cli(a->fd, " T.38 MaxDtgrm: %d\n", global_t38_maxdatagram);
18324 if (!realtimepeers && !realtimeregs)
18325 ast_cli(a->fd, " SIP realtime: Disabled\n" );
18326 else
18327 ast_cli(a->fd, " SIP realtime: Enabled\n" );
18328 ast_cli(a->fd, " Qualify Freq : %d ms\n", global_qualifyfreq);
18329 ast_cli(a->fd, " Q.850 Reason header: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_Q850_REASON)));
18330 ast_cli(a->fd, " Store SIP_CAUSE: %s\n", AST_CLI_YESNO(global_store_sip_cause));
18331 ast_cli(a->fd, "\nNetwork QoS Settings:\n");
18332 ast_cli(a->fd, "---------------------------\n");
18333 ast_cli(a->fd, " IP ToS SIP: %s\n", ast_tos2str(global_tos_sip));
18334 ast_cli(a->fd, " IP ToS RTP audio: %s\n", ast_tos2str(global_tos_audio));
18335 ast_cli(a->fd, " IP ToS RTP video: %s\n", ast_tos2str(global_tos_video));
18336 ast_cli(a->fd, " IP ToS RTP text: %s\n", ast_tos2str(global_tos_text));
18337 ast_cli(a->fd, " 802.1p CoS SIP: %d\n", global_cos_sip);
18338 ast_cli(a->fd, " 802.1p CoS RTP audio: %d\n", global_cos_audio);
18339 ast_cli(a->fd, " 802.1p CoS RTP video: %d\n", global_cos_video);
18340 ast_cli(a->fd, " 802.1p CoS RTP text: %d\n", global_cos_text);
18341 ast_cli(a->fd, " Jitterbuffer enabled: %s\n", AST_CLI_YESNO(ast_test_flag(&global_jbconf, AST_JB_ENABLED)));
18342 if (ast_test_flag(&global_jbconf, AST_JB_ENABLED)) {
18343 ast_cli(a->fd, " Jitterbuffer forced: %s\n", AST_CLI_YESNO(ast_test_flag(&global_jbconf, AST_JB_FORCED)));
18344 ast_cli(a->fd, " Jitterbuffer max size: %ld\n", global_jbconf.max_size);
18345 ast_cli(a->fd, " Jitterbuffer resync: %ld\n", global_jbconf.resync_threshold);
18346 ast_cli(a->fd, " Jitterbuffer impl: %s\n", global_jbconf.impl);
18347 if (!strcasecmp(global_jbconf.impl, "adaptive")) {
18348 ast_cli(a->fd, " Jitterbuffer tgt extra: %ld\n", global_jbconf.target_extra);
18349 }
18350 ast_cli(a->fd, " Jitterbuffer log: %s\n", AST_CLI_YESNO(ast_test_flag(&global_jbconf, AST_JB_LOG)));
18351 }
18352
18353 ast_cli(a->fd, "\nNetwork Settings:\n");
18354 ast_cli(a->fd, "---------------------------\n");
18355
18356 if (localaddr == NULL)
18357 msg = "Disabled, no localnet list";
18358 else if (ast_sockaddr_isnull(&externaddr))
18359 msg = "Disabled";
18360 else if (!ast_strlen_zero(externhost))
18361 msg = "Enabled using externhost";
18362 else
18363 msg = "Enabled using externaddr";
18364 ast_cli(a->fd, " SIP address remapping: %s\n", msg);
18365 ast_cli(a->fd, " Externhost: %s\n", S_OR(externhost, "<none>"));
18366 ast_cli(a->fd, " Externaddr: %s\n", ast_sockaddr_stringify(&externaddr));
18367 ast_cli(a->fd, " Externrefresh: %d\n", externrefresh);
18368 {
18369 struct ast_ha *d;
18370 const char *prefix = "Localnet:";
18371
18372 for (d = localaddr; d ; prefix = "", d = d->next) {
18373 const char *addr = ast_strdupa(ast_sockaddr_stringify_addr(&d->addr));
18374 const char *mask = ast_strdupa(ast_sockaddr_stringify_addr(&d->netmask));
18375 ast_cli(a->fd, " %-24s%s/%s\n", prefix, addr, mask);
18376 }
18377 }
18378 ast_cli(a->fd, "\nGlobal Signalling Settings:\n");
18379 ast_cli(a->fd, "---------------------------\n");
18380 ast_cli(a->fd, " Codecs: ");
18381 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, sip_cfg.capability);
18382 ast_cli(a->fd, "%s\n", codec_buf);
18383 ast_cli(a->fd, " Codec Order: ");
18384 print_codec_to_cli(a->fd, &default_prefs);
18385 ast_cli(a->fd, "\n");
18386 ast_cli(a->fd, " Relax DTMF: %s\n", AST_CLI_YESNO(global_relaxdtmf));
18387 ast_cli(a->fd, " RFC2833 Compensation: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_RFC2833_COMPENSATE)));
18388 ast_cli(a->fd, " Symmetric RTP: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_SYMMETRICRTP)));
18389 ast_cli(a->fd, " Compact SIP headers: %s\n", AST_CLI_YESNO(sip_cfg.compactheaders));
18390 ast_cli(a->fd, " RTP Keepalive: %d %s\n", global_rtpkeepalive, global_rtpkeepalive ? "" : "(Disabled)" );
18391 ast_cli(a->fd, " RTP Timeout: %d %s\n", global_rtptimeout, global_rtptimeout ? "" : "(Disabled)" );
18392 ast_cli(a->fd, " RTP Hold Timeout: %d %s\n", global_rtpholdtimeout, global_rtpholdtimeout ? "" : "(Disabled)");
18393 ast_cli(a->fd, " MWI NOTIFY mime type: %s\n", default_notifymime);
18394 ast_cli(a->fd, " DNS SRV lookup: %s\n", AST_CLI_YESNO(sip_cfg.srvlookup));
18395 ast_cli(a->fd, " Pedantic SIP support: %s\n", AST_CLI_YESNO(sip_cfg.pedanticsipchecking));
18396 ast_cli(a->fd, " Reg. min duration %d secs\n", min_expiry);
18397 ast_cli(a->fd, " Reg. max duration: %d secs\n", max_expiry);
18398 ast_cli(a->fd, " Reg. default duration: %d secs\n", default_expiry);
18399 ast_cli(a->fd, " Outbound reg. timeout: %d secs\n", global_reg_timeout);
18400 ast_cli(a->fd, " Outbound reg. attempts: %d\n", global_regattempts_max);
18401 ast_cli(a->fd, " Notify ringing state: %s\n", AST_CLI_YESNO(sip_cfg.notifyringing));
18402 if (sip_cfg.notifyringing) {
18403 ast_cli(a->fd, " Include CID: %s%s\n",
18404 AST_CLI_YESNO(sip_cfg.notifycid),
18405 sip_cfg.notifycid == IGNORE_CONTEXT ? " (Ignoring context)" : "");
18406 }
18407 ast_cli(a->fd, " Notify hold state: %s\n", AST_CLI_YESNO(sip_cfg.notifyhold));
18408 ast_cli(a->fd, " SIP Transfer mode: %s\n", transfermode2str(sip_cfg.allowtransfer));
18409 ast_cli(a->fd, " Max Call Bitrate: %d kbps\n", default_maxcallbitrate);
18410 ast_cli(a->fd, " Auto-Framing: %s\n", AST_CLI_YESNO(global_autoframing));
18411 ast_cli(a->fd, " Outb. proxy: %s %s\n", ast_strlen_zero(sip_cfg.outboundproxy.name) ? "<not set>" : sip_cfg.outboundproxy.name,
18412 sip_cfg.outboundproxy.force ? "(forced)" : "");
18413 ast_cli(a->fd, " Session Timers: %s\n", stmode2str(global_st_mode));
18414 ast_cli(a->fd, " Session Refresher: %s\n", strefresherparam2str(global_st_refresher));
18415 ast_cli(a->fd, " Session Expires: %d secs\n", global_max_se);
18416 ast_cli(a->fd, " Session Min-SE: %d secs\n", global_min_se);
18417 ast_cli(a->fd, " Timer T1: %d\n", global_t1);
18418 ast_cli(a->fd, " Timer T1 minimum: %d\n", global_t1min);
18419 ast_cli(a->fd, " Timer B: %d\n", global_timer_b);
18420 ast_cli(a->fd, " No premature media: %s\n", AST_CLI_YESNO(global_prematuremediafilter));
18421 ast_cli(a->fd, " Max forwards: %d\n", sip_cfg.default_max_forwards);
18422
18423 ast_cli(a->fd, "\nDefault Settings:\n");
18424 ast_cli(a->fd, "-----------------\n");
18425 ast_cli(a->fd, " Allowed transports: %s\n", get_transport_list(default_transports));
18426 ast_cli(a->fd, " Outbound transport: %s\n", get_transport(default_primary_transport));
18427 ast_cli(a->fd, " Context: %s\n", sip_cfg.default_context);
18428 ast_cli(a->fd, " Force rport: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_NAT_FORCE_RPORT)));
18429 ast_cli(a->fd, " DTMF: %s\n", dtmfmode2str(ast_test_flag(&global_flags[0], SIP_DTMF)));
18430 ast_cli(a->fd, " Qualify: %d\n", default_qualify);
18431 ast_cli(a->fd, " Use ClientCode: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_USECLIENTCODE)));
18432 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)));
18433 ast_cli(a->fd, " Language: %s\n", default_language);
18434 ast_cli(a->fd, " MOH Interpret: %s\n", default_mohinterpret);
18435 ast_cli(a->fd, " MOH Suggest: %s\n", default_mohsuggest);
18436 ast_cli(a->fd, " Voice Mail Extension: %s\n", default_vmexten);
18437
18438
18439 if (realtimepeers || realtimeregs) {
18440 ast_cli(a->fd, "\nRealtime SIP Settings:\n");
18441 ast_cli(a->fd, "----------------------\n");
18442 ast_cli(a->fd, " Realtime Peers: %s\n", AST_CLI_YESNO(realtimepeers));
18443 ast_cli(a->fd, " Realtime Regs: %s\n", AST_CLI_YESNO(realtimeregs));
18444 ast_cli(a->fd, " Cache Friends: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)));
18445 ast_cli(a->fd, " Update: %s\n", AST_CLI_YESNO(sip_cfg.peer_rtupdate));
18446 ast_cli(a->fd, " Ignore Reg. Expire: %s\n", AST_CLI_YESNO(sip_cfg.ignore_regexpire));
18447 ast_cli(a->fd, " Save sys. name: %s\n", AST_CLI_YESNO(sip_cfg.rtsave_sysname));
18448 ast_cli(a->fd, " Auto Clear: %d (%s)\n", sip_cfg.rtautoclear, ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR) ? "Enabled" : "Disabled");
18449 }
18450 ast_cli(a->fd, "\n----\n");
18451 return CLI_SUCCESS;
18452 }
18453
18454 static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18455 {
18456 #define FORMAT "%-30.30s %-12.12s %-10.10s %-10.10s\n"
18457 char host[80];
18458
18459 switch (cmd) {
18460 case CLI_INIT:
18461 e->command = "sip show mwi";
18462 e->usage =
18463 "Usage: sip show mwi\n"
18464 " Provides a list of MWI subscriptions and status.\n";
18465 return NULL;
18466 case CLI_GENERATE:
18467 return NULL;
18468 }
18469
18470 ast_cli(a->fd, FORMAT, "Host", "Username", "Mailbox", "Subscribed");
18471
18472 ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
18473 ASTOBJ_RDLOCK(iterator);
18474 snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
18475 ast_cli(a->fd, FORMAT, host, iterator->username, iterator->mailbox, AST_CLI_YESNO(iterator->subscribed));
18476 ASTOBJ_UNLOCK(iterator);
18477 } while(0));
18478
18479 return CLI_SUCCESS;
18480 #undef FORMAT
18481 }
18482
18483
18484
18485 static const char *subscription_type2str(enum subscriptiontype subtype)
18486 {
18487 int i;
18488
18489 for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
18490 if (subscription_types[i].type == subtype) {
18491 return subscription_types[i].text;
18492 }
18493 }
18494 return subscription_types[0].text;
18495 }
18496
18497
18498 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype)
18499 {
18500 int i;
18501
18502 for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
18503 if (subscription_types[i].type == subtype) {
18504 return &subscription_types[i];
18505 }
18506 }
18507 return &subscription_types[0];
18508 }
18509
18510
18511
18512
18513
18514
18515
18516
18517 #define FORMAT4 "%-15.15s %-15.15s %-15.15s %-15.15s %-13.13s %-15.15s %-10.10s %-6.6d\n"
18518 #define FORMAT3 "%-15.15s %-15.15s %-15.15s %-15.15s %-13.13s %-15.15s %-10.10s %-6.6s\n"
18519 #define FORMAT2 "%-15.15s %-15.15s %-15.15s %-15.15s %-7.7s %-15.15s %-10.10s %-10.10s\n"
18520 #define FORMAT "%-15.15s %-15.15s %-15.15s %-15.15s %-3.3s %-3.3s %-15.15s %-10.10s %-10.10s\n"
18521
18522
18523 static int show_channels_cb(void *__cur, void *__arg, int flags)
18524 {
18525 struct sip_pvt *cur = __cur;
18526 struct __show_chan_arg *arg = __arg;
18527 const struct ast_sockaddr *dst;
18528
18529 sip_pvt_lock(cur);
18530 dst = sip_real_dst(cur);
18531
18532
18533 if (cur->subscribed == NONE && !arg->subscriptions) {
18534
18535 const char *referstatus = cur->refer ? referstatus2str(cur->refer->status) : "";
18536 char formatbuf[SIPBUFSIZE/2];
18537
18538 ast_cli(arg->fd, FORMAT, ast_sockaddr_stringify_addr(dst),
18539 S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
18540 cur->callid,
18541 ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0),
18542 AST_CLI_YESNO(ast_test_flag(&cur->flags[1], SIP_PAGE2_CALL_ONHOLD)),
18543 cur->needdestroy ? "(d)" : "",
18544 cur->lastmsg ,
18545 referstatus,
18546 cur->relatedpeer ? cur->relatedpeer->name : "<guest>"
18547 );
18548 arg->numchans++;
18549 }
18550 if (cur->subscribed != NONE && arg->subscriptions) {
18551 struct ast_str *mailbox_str = ast_str_alloca(512);
18552 if (cur->subscribed == MWI_NOTIFICATION && cur->relatedpeer)
18553 peer_mailboxes_to_str(&mailbox_str, cur->relatedpeer);
18554 ast_cli(arg->fd, FORMAT4, ast_sockaddr_stringify_addr(dst),
18555 S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
18556 cur->callid,
18557
18558 cur->subscribed == MWI_NOTIFICATION ? "--" : cur->subscribeuri,
18559 cur->subscribed == MWI_NOTIFICATION ? "<none>" : ast_extension_state2str(cur->laststate),
18560 subscription_type2str(cur->subscribed),
18561 cur->subscribed == MWI_NOTIFICATION ? S_OR(mailbox_str->str, "<none>") : "<none>",
18562 cur->expiry
18563 );
18564 arg->numchans++;
18565 }
18566 sip_pvt_unlock(cur);
18567 return 0;
18568 }
18569
18570
18571
18572
18573
18574
18575 static char *sip_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18576 {
18577 struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
18578
18579
18580 if (cmd == CLI_INIT) {
18581 e->command = "sip show {channels|subscriptions}";
18582 e->usage =
18583 "Usage: sip show channels\n"
18584 " Lists all currently active SIP calls (dialogs).\n"
18585 "Usage: sip show subscriptions\n"
18586 " Lists active SIP subscriptions.\n";
18587 return NULL;
18588 } else if (cmd == CLI_GENERATE)
18589 return NULL;
18590
18591 if (a->argc != e->args)
18592 return CLI_SHOWUSAGE;
18593 arg.subscriptions = !strcasecmp(a->argv[e->args - 1], "subscriptions");
18594 if (!arg.subscriptions)
18595 ast_cli(arg.fd, FORMAT2, "Peer", "User/ANR", "Call ID", "Format", "Hold", "Last Message", "Expiry", "Peer");
18596 else
18597 ast_cli(arg.fd, FORMAT3, "Peer", "User", "Call ID", "Extension", "Last state", "Type", "Mailbox", "Expiry");
18598
18599
18600 ao2_t_callback(dialogs, OBJ_NODATA, show_channels_cb, &arg, "callback to show channels");
18601
18602
18603 ast_cli(arg.fd, "%d active SIP %s%s\n", arg.numchans,
18604 (arg.subscriptions ? "subscription" : "dialog"),
18605 ESS(arg.numchans));
18606 return CLI_SUCCESS;
18607 #undef FORMAT
18608 #undef FORMAT2
18609 #undef FORMAT3
18610 }
18611
18612
18613
18614
18615
18616
18617 static char *complete_sipch(const char *line, const char *word, int pos, int state)
18618 {
18619 int which=0;
18620 struct sip_pvt *cur;
18621 char *c = NULL;
18622 int wordlen = strlen(word);
18623 struct ao2_iterator i;
18624
18625 if (pos != 3) {
18626 return NULL;
18627 }
18628
18629 i = ao2_iterator_init(dialogs, 0);
18630 while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
18631 sip_pvt_lock(cur);
18632 if (!strncasecmp(word, cur->callid, wordlen) && ++which > state) {
18633 c = ast_strdup(cur->callid);
18634 sip_pvt_unlock(cur);
18635 dialog_unref(cur, "drop ref in iterator loop break");
18636 break;
18637 }
18638 sip_pvt_unlock(cur);
18639 dialog_unref(cur, "drop ref in iterator loop");
18640 }
18641 ao2_iterator_destroy(&i);
18642 return c;
18643 }
18644
18645
18646
18647 static char *complete_sip_peer(const char *word, int state, int flags2)
18648 {
18649 char *result = NULL;
18650 int wordlen = strlen(word);
18651 int which = 0;
18652 struct ao2_iterator i = ao2_iterator_init(peers, 0);
18653 struct sip_peer *peer;
18654
18655 while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
18656
18657 if (!strncasecmp(word, peer->name, wordlen) &&
18658 (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
18659 ++which > state)
18660 result = ast_strdup(peer->name);
18661 unref_peer(peer, "toss iterator peer ptr before break");
18662 if (result) {
18663 break;
18664 }
18665 }
18666 ao2_iterator_destroy(&i);
18667 return result;
18668 }
18669
18670
18671 static char *complete_sip_registered_peer(const char *word, int state, int flags2)
18672 {
18673 char *result = NULL;
18674 int wordlen = strlen(word);
18675 int which = 0;
18676 struct ao2_iterator i;
18677 struct sip_peer *peer;
18678
18679 i = ao2_iterator_init(peers, 0);
18680 while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
18681 if (!strncasecmp(word, peer->name, wordlen) &&
18682 (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
18683 ++which > state && peer->expire > 0)
18684 result = ast_strdup(peer->name);
18685 if (result) {
18686 unref_peer(peer, "toss iterator peer ptr before break");
18687 break;
18688 }
18689 unref_peer(peer, "toss iterator peer ptr");
18690 }
18691 ao2_iterator_destroy(&i);
18692 return result;
18693 }
18694
18695
18696 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state)
18697 {
18698 if (pos == 3)
18699 return complete_sipch(line, word, pos, state);
18700
18701 return NULL;
18702 }
18703
18704
18705 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state)
18706 {
18707 if (pos == 3) {
18708 return complete_sip_peer(word, state, 0);
18709 }
18710
18711 return NULL;
18712 }
18713
18714
18715 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state)
18716 {
18717 if (pos == 2)
18718 return complete_sip_registered_peer(word, state, 0);
18719
18720 return NULL;
18721 }
18722
18723
18724 static char *complete_sipnotify(const char *line, const char *word, int pos, int state)
18725 {
18726 char *c = NULL;
18727
18728 if (pos == 2) {
18729 int which = 0;
18730 char *cat = NULL;
18731 int wordlen = strlen(word);
18732
18733
18734
18735 if (!notify_types)
18736 return NULL;
18737
18738 while ( (cat = ast_category_browse(notify_types, cat)) ) {
18739 if (!strncasecmp(word, cat, wordlen) && ++which > state) {
18740 c = ast_strdup(cat);
18741 break;
18742 }
18743 }
18744 return c;
18745 }
18746
18747 if (pos > 2)
18748 return complete_sip_peer(word, state, 0);
18749
18750 return NULL;
18751 }
18752
18753
18754 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18755 {
18756 struct sip_pvt *cur;
18757 size_t len;
18758 int found = 0;
18759 struct ao2_iterator i;
18760
18761 switch (cmd) {
18762 case CLI_INIT:
18763 e->command = "sip show channel";
18764 e->usage =
18765 "Usage: sip show channel <call-id>\n"
18766 " Provides detailed status on a given SIP dialog (identified by SIP call-id).\n";
18767 return NULL;
18768 case CLI_GENERATE:
18769 return complete_sipch(a->line, a->word, a->pos, a->n);
18770 }
18771
18772 if (a->argc != 4)
18773 return CLI_SHOWUSAGE;
18774 len = strlen(a->argv[3]);
18775
18776 i = ao2_iterator_init(dialogs, 0);
18777 while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
18778 sip_pvt_lock(cur);
18779
18780 if (!strncasecmp(cur->callid, a->argv[3], len)) {
18781 char formatbuf[SIPBUFSIZE/2];
18782 ast_cli(a->fd, "\n");
18783 if (cur->subscribed != NONE)
18784 ast_cli(a->fd, " * Subscription (type: %s)\n", subscription_type2str(cur->subscribed));
18785 else
18786 ast_cli(a->fd, " * SIP Call\n");
18787 ast_cli(a->fd, " Curr. trans. direction: %s\n", ast_test_flag(&cur->flags[0], SIP_OUTGOING) ? "Outgoing" : "Incoming");
18788 ast_cli(a->fd, " Call-ID: %s\n", cur->callid);
18789 ast_cli(a->fd, " Owner channel ID: %s\n", cur->owner ? cur->owner->name : "<none>");
18790 ast_cli(a->fd, " Our Codec Capability: %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->capability));
18791 ast_cli(a->fd, " Non-Codec Capability (DTMF): %d\n", cur->noncodeccapability);
18792 ast_cli(a->fd, " Their Codec Capability: %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->peercapability));
18793 ast_cli(a->fd, " Joint Codec Capability: %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->jointcapability));
18794 ast_cli(a->fd, " Format: %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0) );
18795 ast_cli(a->fd, " T.38 support %s\n", AST_CLI_YESNO(cur->udptl != NULL));
18796 ast_cli(a->fd, " Video support %s\n", AST_CLI_YESNO(cur->vrtp != NULL));
18797 ast_cli(a->fd, " MaxCallBR: %d kbps\n", cur->maxcallbitrate);
18798 ast_cli(a->fd, " Theoretical Address: %s\n", ast_sockaddr_stringify(&cur->sa));
18799 ast_cli(a->fd, " Received Address: %s\n", ast_sockaddr_stringify(&cur->recv));
18800 ast_cli(a->fd, " SIP Transfer mode: %s\n", transfermode2str(cur->allowtransfer));
18801 ast_cli(a->fd, " Force rport: %s\n", AST_CLI_YESNO(ast_test_flag(&cur->flags[0], SIP_NAT_FORCE_RPORT)));
18802 if (ast_sockaddr_isnull(&cur->redirip)) {
18803 ast_cli(a->fd,
18804 " Audio IP: %s (local)\n",
18805 ast_sockaddr_stringify_addr(&cur->ourip));
18806 } else {
18807 ast_cli(a->fd,
18808 " Audio IP: %s (Outside bridge)\n",
18809 ast_sockaddr_stringify_addr(&cur->redirip));
18810 }
18811 ast_cli(a->fd, " Our Tag: %s\n", cur->tag);
18812 ast_cli(a->fd, " Their Tag: %s\n", cur->theirtag);
18813 ast_cli(a->fd, " SIP User agent: %s\n", cur->useragent);
18814 if (!ast_strlen_zero(cur->username))
18815 ast_cli(a->fd, " Username: %s\n", cur->username);
18816 if (!ast_strlen_zero(cur->peername))
18817 ast_cli(a->fd, " Peername: %s\n", cur->peername);
18818 if (!ast_strlen_zero(cur->uri))
18819 ast_cli(a->fd, " Original uri: %s\n", cur->uri);
18820 if (!ast_strlen_zero(cur->cid_num))
18821 ast_cli(a->fd, " Caller-ID: %s\n", cur->cid_num);
18822 ast_cli(a->fd, " Need Destroy: %s\n", AST_CLI_YESNO(cur->needdestroy));
18823 ast_cli(a->fd, " Last Message: %s\n", cur->lastmsg);
18824 ast_cli(a->fd, " Promiscuous Redir: %s\n", AST_CLI_YESNO(ast_test_flag(&cur->flags[0], SIP_PROMISCREDIR)));
18825 ast_cli(a->fd, " Route: %s\n", cur->route ? cur->route->hop : "N/A");
18826 ast_cli(a->fd, " DTMF Mode: %s\n", dtmfmode2str(ast_test_flag(&cur->flags[0], SIP_DTMF)));
18827 ast_cli(a->fd, " SIP Options: ");
18828 if (cur->sipoptions) {
18829 int x;
18830 for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
18831 if (cur->sipoptions & sip_options[x].id)
18832 ast_cli(a->fd, "%s ", sip_options[x].text);
18833 }
18834 ast_cli(a->fd, "\n");
18835 } else
18836 ast_cli(a->fd, "(none)\n");
18837
18838 if (!cur->stimer)
18839 ast_cli(a->fd, " Session-Timer: Uninitiallized\n");
18840 else {
18841 ast_cli(a->fd, " Session-Timer: %s\n", cur->stimer->st_active ? "Active" : "Inactive");
18842 if (cur->stimer->st_active == TRUE) {
18843 ast_cli(a->fd, " S-Timer Interval: %d\n", cur->stimer->st_interval);
18844 ast_cli(a->fd, " S-Timer Refresher: %s\n", strefresher2str(cur->stimer->st_ref));
18845 ast_cli(a->fd, " S-Timer Expirys: %d\n", cur->stimer->st_expirys);
18846 ast_cli(a->fd, " S-Timer Sched Id: %d\n", cur->stimer->st_schedid);
18847 ast_cli(a->fd, " S-Timer Peer Sts: %s\n", cur->stimer->st_active_peer_ua ? "Active" : "Inactive");
18848 ast_cli(a->fd, " S-Timer Cached Min-SE: %d\n", cur->stimer->st_cached_min_se);
18849 ast_cli(a->fd, " S-Timer Cached SE: %d\n", cur->stimer->st_cached_max_se);
18850 ast_cli(a->fd, " S-Timer Cached Ref: %s\n", strefresherparam2str(cur->stimer->st_cached_ref));
18851 ast_cli(a->fd, " S-Timer Cached Mode: %s\n", stmode2str(cur->stimer->st_cached_mode));
18852 }
18853 }
18854
18855 ast_cli(a->fd, "\n\n");
18856
18857 found++;
18858 }
18859
18860 sip_pvt_unlock(cur);
18861
18862 ao2_t_ref(cur, -1, "toss dialog ptr set by iterator_next");
18863 }
18864 ao2_iterator_destroy(&i);
18865
18866 if (!found)
18867 ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
18868
18869 return CLI_SUCCESS;
18870 }
18871
18872
18873 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18874 {
18875 struct sip_pvt *cur;
18876 size_t len;
18877 int found = 0;
18878 struct ao2_iterator i;
18879
18880 switch (cmd) {
18881 case CLI_INIT:
18882 e->command = "sip show history";
18883 e->usage =
18884 "Usage: sip show history <call-id>\n"
18885 " Provides detailed dialog history on a given SIP call (specified by call-id).\n";
18886 return NULL;
18887 case CLI_GENERATE:
18888 return complete_sip_show_history(a->line, a->word, a->pos, a->n);
18889 }
18890
18891 if (a->argc != 4)
18892 return CLI_SHOWUSAGE;
18893
18894 if (!recordhistory)
18895 ast_cli(a->fd, "\n***Note: History recording is currently DISABLED. Use 'sip set history on' to ENABLE.\n");
18896
18897 len = strlen(a->argv[3]);
18898
18899 i = ao2_iterator_init(dialogs, 0);
18900 while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
18901 sip_pvt_lock(cur);
18902 if (!strncasecmp(cur->callid, a->argv[3], len)) {
18903 struct sip_history *hist;
18904 int x = 0;
18905
18906 ast_cli(a->fd, "\n");
18907 if (cur->subscribed != NONE)
18908 ast_cli(a->fd, " * Subscription\n");
18909 else
18910 ast_cli(a->fd, " * SIP Call\n");
18911 if (cur->history)
18912 AST_LIST_TRAVERSE(cur->history, hist, list)
18913 ast_cli(a->fd, "%d. %s\n", ++x, hist->event);
18914 if (x == 0)
18915 ast_cli(a->fd, "Call '%s' has no history\n", cur->callid);
18916 found++;
18917 }
18918 sip_pvt_unlock(cur);
18919 ao2_t_ref(cur, -1, "toss dialog ptr from iterator_next");
18920 }
18921 ao2_iterator_destroy(&i);
18922
18923 if (!found)
18924 ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
18925
18926 return CLI_SUCCESS;
18927 }
18928
18929
18930 static void sip_dump_history(struct sip_pvt *dialog)
18931 {
18932 int x = 0;
18933 struct sip_history *hist;
18934 static int errmsg = 0;
18935
18936 if (!dialog)
18937 return;
18938
18939 if (!option_debug && !sipdebug) {
18940 if (!errmsg) {
18941 ast_log(LOG_NOTICE, "You must have debugging enabled (SIP or Asterisk) in order to dump SIP history.\n");
18942 errmsg = 1;
18943 }
18944 return;
18945 }
18946
18947 ast_debug(1, "\n---------- SIP HISTORY for '%s' \n", dialog->callid);
18948 if (dialog->subscribed)
18949 ast_debug(1, " * Subscription\n");
18950 else
18951 ast_debug(1, " * SIP Call\n");
18952 if (dialog->history)
18953 AST_LIST_TRAVERSE(dialog->history, hist, list)
18954 ast_debug(1, " %-3.3d. %s\n", ++x, hist->event);
18955 if (!x)
18956 ast_debug(1, "Call '%s' has no history\n", dialog->callid);
18957 ast_debug(1, "\n---------- END SIP HISTORY for '%s' \n", dialog->callid);
18958 }
18959
18960
18961
18962 static void handle_request_info(struct sip_pvt *p, struct sip_request *req)
18963 {
18964 char buf[1024] = "";
18965 unsigned int event;
18966 const char *c = get_header(req, "Content-Type");
18967
18968
18969 if (!strcasecmp(c, "application/dtmf-relay") ||
18970 !strcasecmp(c, "application/vnd.nortelnetworks.digits") ||
18971 !strcasecmp(c, "application/dtmf")) {
18972 unsigned int duration = 0;
18973
18974 if (!p->owner) {
18975 transmit_response(p, "481 Call leg/transaction does not exist", req);
18976 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18977 return;
18978 }
18979
18980
18981
18982 if (strcasecmp(c, "application/dtmf")) {
18983 const char *msg_body;
18984
18985 if ( ast_strlen_zero(msg_body = get_body(req, "Signal", '='))
18986 && ast_strlen_zero(msg_body = get_body(req, "d", '='))) {
18987 ast_log(LOG_WARNING, "Unable to retrieve DTMF signal for INFO message on "
18988 "call %s\n", p->callid);
18989 transmit_response(p, "200 OK", req);
18990 return;
18991 }
18992 ast_copy_string(buf, msg_body, sizeof(buf));
18993
18994 if (!ast_strlen_zero((msg_body = get_body(req, "Duration", '=')))) {
18995 sscanf(msg_body, "%30u", &duration);
18996 }
18997 } else {
18998
18999 get_msg_text(buf, sizeof(buf), req);
19000 }
19001
19002
19003 if (ast_strlen_zero(buf)) {
19004 transmit_response(p, "200 OK", req);
19005 return;
19006 }
19007
19008 if (!duration) {
19009 duration = 100;
19010 }
19011
19012 if (buf[0] == '*') {
19013 event = 10;
19014 } else if (buf[0] == '#') {
19015 event = 11;
19016 } else if (buf[0] == '!') {
19017 event = 16;
19018 } else if ('A' <= buf[0] && buf[0] <= 'D') {
19019 event = 12 + buf[0] - 'A';
19020 } else if ('a' <= buf[0] && buf[0] <= 'd') {
19021 event = 12 + buf[0] - 'a';
19022 } else if ((sscanf(buf, "%30u", &event) != 1) || event > 16) {
19023 ast_log(AST_LOG_WARNING, "Unable to convert DTMF event signal code to a valid "
19024 "value for INFO message on call %s\n", p->callid);
19025 transmit_response(p, "200 OK", req);
19026 return;
19027 }
19028
19029 if (event == 16) {
19030
19031 struct ast_frame f = { AST_FRAME_CONTROL, { AST_CONTROL_FLASH, } };
19032 ast_queue_frame(p->owner, &f);
19033 if (sipdebug) {
19034 ast_verbose("* DTMF-relay event received: FLASH\n");
19035 }
19036 } else {
19037
19038 struct ast_frame f = { AST_FRAME_DTMF, };
19039 if (event < 10) {
19040 f.subclass.integer = '0' + event;
19041 } else if (event == 10) {
19042 f.subclass.integer = '*';
19043 } else if (event == 11) {
19044 f.subclass.integer = '#';
19045 } else {
19046 f.subclass.integer = 'A' + (event - 12);
19047 }
19048 f.len = duration;
19049 ast_queue_frame(p->owner, &f);
19050 if (sipdebug) {
19051 ast_verbose("* DTMF-relay event received: %c\n", (int) f.subclass.integer);
19052 }
19053 }
19054 transmit_response(p, "200 OK", req);
19055 return;
19056 } else if (!strcasecmp(c, "application/media_control+xml")) {
19057
19058 if (p->owner)
19059 ast_queue_control(p->owner, AST_CONTROL_VIDUPDATE);
19060 transmit_response(p, "200 OK", req);
19061 return;
19062 } else if (!ast_strlen_zero(c = get_header(req, "X-ClientCode"))) {
19063
19064 if (ast_test_flag(&p->flags[0], SIP_USECLIENTCODE)) {
19065 if (p->owner && p->owner->cdr)
19066 ast_cdr_setuserfield(p->owner, c);
19067 if (p->owner && ast_bridged_channel(p->owner) && ast_bridged_channel(p->owner)->cdr)
19068 ast_cdr_setuserfield(ast_bridged_channel(p->owner), c);
19069 transmit_response(p, "200 OK", req);
19070 } else {
19071 transmit_response(p, "403 Forbidden", req);
19072 }
19073 return;
19074 } else if (!ast_strlen_zero(c = get_header(req, "Record"))) {
19075
19076
19077
19078
19079
19080
19081
19082 struct ast_call_feature *feat;
19083 int j;
19084 struct ast_frame f = { AST_FRAME_DTMF, };
19085
19086 if (!p->owner) {
19087 transmit_response(p, "481 Call leg/transaction does not exist", req);
19088 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19089 return;
19090 }
19091
19092
19093 ast_rdlock_call_features();
19094 feat = ast_find_call_feature("automon");
19095 if (!feat || ast_strlen_zero(feat->exten)) {
19096 ast_log(LOG_WARNING, "Recording requested, but no One Touch Monitor registered. (See features.conf)\n");
19097
19098 transmit_response(p, "403 Forbidden", req);
19099 ast_unlock_call_features();
19100 return;
19101 }
19102
19103 f.len = 100;
19104 for (j=0; j < strlen(feat->exten); j++) {
19105 f.subclass.integer = feat->exten[j];
19106 ast_queue_frame(p->owner, &f);
19107 if (sipdebug)
19108 ast_verbose("* DTMF-relay event faked: %c\n", f.subclass.integer);
19109 }
19110 ast_unlock_call_features();
19111
19112 ast_debug(1, "Got a Request to Record the channel, state %s\n", c);
19113 transmit_response(p, "200 OK", req);
19114 return;
19115 } else if (ast_strlen_zero(c = get_header(req, "Content-Length")) || !strcasecmp(c, "0")) {
19116
19117 transmit_response(p, "200 OK", req);
19118 return;
19119 }
19120
19121
19122
19123
19124 ast_log(LOG_WARNING, "Unable to parse INFO message from %s. Content %s\n", p->callid, buf);
19125 transmit_response(p, "415 Unsupported media type", req);
19126 return;
19127 }
19128
19129
19130 static char *sip_do_debug_ip(int fd, const char *arg)
19131 {
19132 if (ast_sockaddr_resolve_first_af(&debugaddr, arg, 0, 0)) {
19133 return CLI_SHOWUSAGE;
19134 }
19135
19136 ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_sockaddr_stringify_addr(&debugaddr));
19137 sipdebug |= sip_debug_console;
19138
19139 return CLI_SUCCESS;
19140 }
19141
19142
19143 static char *sip_do_debug_peer(int fd, const char *arg)
19144 {
19145 struct sip_peer *peer = find_peer(arg, NULL, TRUE, FINDPEERS, FALSE, 0);
19146 if (!peer)
19147 ast_cli(fd, "No such peer '%s'\n", arg);
19148 else if (ast_sockaddr_isnull(&peer->addr))
19149 ast_cli(fd, "Unable to get IP address of peer '%s'\n", arg);
19150 else {
19151 ast_sockaddr_copy(&debugaddr, &peer->addr);
19152 ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_sockaddr_stringify_addr(&debugaddr));
19153 sipdebug |= sip_debug_console;
19154 }
19155 if (peer)
19156 unref_peer(peer, "sip_do_debug_peer: unref_peer, from find_peer call");
19157 return CLI_SUCCESS;
19158 }
19159
19160
19161 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
19162 {
19163 int oldsipdebug = sipdebug & sip_debug_console;
19164 const char *what;
19165
19166 if (cmd == CLI_INIT) {
19167 e->command = "sip set debug {on|off|ip|peer}";
19168 e->usage =
19169 "Usage: sip set debug {off|on|ip addr[:port]|peer peername}\n"
19170 " Globally disables dumping of SIP packets,\n"
19171 " or enables it either globally or for a (single)\n"
19172 " IP address or registered peer.\n";
19173 return NULL;
19174 } else if (cmd == CLI_GENERATE) {
19175 if (a->pos == 4 && !strcasecmp(a->argv[3], "peer"))
19176 return complete_sip_peer(a->word, a->n, 0);
19177 return NULL;
19178 }
19179
19180 what = a->argv[e->args-1];
19181 if (a->argc == e->args) {
19182 if (!strcasecmp(what, "on")) {
19183 sipdebug |= sip_debug_console;
19184 sipdebug_text = 1;
19185 memset(&debugaddr, 0, sizeof(debugaddr));
19186 ast_cli(a->fd, "SIP Debugging %senabled\n", oldsipdebug ? "re-" : "");
19187 return CLI_SUCCESS;
19188 } else if (!strcasecmp(what, "off")) {
19189 sipdebug &= ~sip_debug_console;
19190 sipdebug_text = 0;
19191 ast_cli(a->fd, "SIP Debugging Disabled\n");
19192 return CLI_SUCCESS;
19193 }
19194 } else if (a->argc == e->args +1) {
19195 if (!strcasecmp(what, "ip"))
19196 return sip_do_debug_ip(a->fd, a->argv[e->args]);
19197 else if (!strcasecmp(what, "peer"))
19198 return sip_do_debug_peer(a->fd, a->argv[e->args]);
19199 }
19200 return CLI_SHOWUSAGE;
19201 }
19202
19203
19204 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
19205 {
19206 struct ast_variable *varlist;
19207 int i;
19208
19209 switch (cmd) {
19210 case CLI_INIT:
19211 e->command = "sip notify";
19212 e->usage =
19213 "Usage: sip notify <type> <peer> [<peer>...]\n"
19214 " Send a NOTIFY message to a SIP peer or peers\n"
19215 " Message types are defined in sip_notify.conf\n";
19216 return NULL;
19217 case CLI_GENERATE:
19218 return complete_sipnotify(a->line, a->word, a->pos, a->n);
19219 }
19220
19221 if (a->argc < 4)
19222 return CLI_SHOWUSAGE;
19223
19224 if (!notify_types) {
19225 ast_cli(a->fd, "No %s file found, or no types listed there\n", notify_config);
19226 return CLI_FAILURE;
19227 }
19228
19229 varlist = ast_variable_browse(notify_types, a->argv[2]);
19230
19231 if (!varlist) {
19232 ast_cli(a->fd, "Unable to find notify type '%s'\n", a->argv[2]);
19233 return CLI_FAILURE;
19234 }
19235
19236 for (i = 3; i < a->argc; i++) {
19237 struct sip_pvt *p;
19238 char buf[512];
19239 struct ast_variable *header, *var;
19240
19241 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
19242 ast_log(LOG_WARNING, "Unable to build sip pvt data for notify (memory/socket error)\n");
19243 return CLI_FAILURE;
19244 }
19245
19246 if (create_addr(p, a->argv[i], NULL, 1)) {
19247
19248 dialog_unlink_all(p);
19249 dialog_unref(p, "unref dialog inside for loop" );
19250
19251 ast_cli(a->fd, "Could not create address for '%s'\n", a->argv[i]);
19252 continue;
19253 }
19254
19255
19256 ast_set_flag(&p->flags[0], SIP_OUTGOING);
19257 sip_notify_allocate(p);
19258 p->notify->headers = header = ast_variable_new("Subscription-State", "terminated", "");
19259
19260 for (var = varlist; var; var = var->next) {
19261 ast_copy_string(buf, var->value, sizeof(buf));
19262 ast_unescape_semicolon(buf);
19263
19264 if (!strcasecmp(var->name, "Content")) {
19265 if (ast_str_strlen(p->notify->content))
19266 ast_str_append(&p->notify->content, 0, "\r\n");
19267 ast_str_append(&p->notify->content, 0, "%s", buf);
19268 } else if (!strcasecmp(var->name, "Content-Length")) {
19269 ast_log(LOG_WARNING, "it is not necessary to specify Content-Length in sip_notify.conf, ignoring\n");
19270 } else {
19271 header->next = ast_variable_new(var->name, buf, "");
19272 header = header->next;
19273 }
19274 }
19275
19276
19277 ast_cli(a->fd, "Sending NOTIFY of type '%s' to '%s'\n", a->argv[2], a->argv[i]);
19278 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
19279 transmit_invite(p, SIP_NOTIFY, 0, 2, NULL);
19280 dialog_unref(p, "bump down the count of p since we're done with it.");
19281 }
19282
19283 return CLI_SUCCESS;
19284 }
19285
19286
19287 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
19288 {
19289 switch (cmd) {
19290 case CLI_INIT:
19291 e->command = "sip set history {on|off}";
19292 e->usage =
19293 "Usage: sip set history {on|off}\n"
19294 " Enables/Disables recording of SIP dialog history for debugging purposes.\n"
19295 " Use 'sip show history' to view the history of a call number.\n";
19296 return NULL;
19297 case CLI_GENERATE:
19298 return NULL;
19299 }
19300
19301 if (a->argc != e->args)
19302 return CLI_SHOWUSAGE;
19303
19304 if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
19305 recordhistory = TRUE;
19306 ast_cli(a->fd, "SIP History Recording Enabled (use 'sip show history')\n");
19307 } else if (!strncasecmp(a->argv[e->args - 1], "off", 3)) {
19308 recordhistory = FALSE;
19309 ast_cli(a->fd, "SIP History Recording Disabled\n");
19310 } else {
19311 return CLI_SHOWUSAGE;
19312 }
19313 return CLI_SUCCESS;
19314 }
19315
19316
19317 static int do_register_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code)
19318 {
19319 char *header, *respheader;
19320 char digest[1024];
19321
19322 p->authtries++;
19323 auth_headers(code, &header, &respheader);
19324 memset(digest, 0, sizeof(digest));
19325 if (reply_digest(p, req, header, SIP_REGISTER, digest, sizeof(digest))) {
19326
19327
19328 if (sip_debug_test_pvt(p) && p->registry)
19329 ast_verbose("No authentication challenge, sending blank registration to domain/host name %s\n", p->registry->hostname);
19330
19331 return -1;
19332 }
19333 if (p->do_history)
19334 append_history(p, "RegistryAuth", "Try: %d", p->authtries);
19335 if (sip_debug_test_pvt(p) && p->registry)
19336 ast_verbose("Responding to challenge, registration to domain/host name %s\n", p->registry->hostname);
19337 return transmit_register(p->registry, SIP_REGISTER, digest, respheader);
19338 }
19339
19340
19341 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code, int sipmethod, int init)
19342 {
19343 char *header, *respheader;
19344 char digest[1024];
19345
19346 if (!p->options && !(p->options = ast_calloc(1, sizeof(*p->options))))
19347 return -2;
19348
19349 p->authtries++;
19350 auth_headers(code, &header, &respheader);
19351 ast_debug(2, "Auth attempt %d on %s\n", p->authtries, sip_methods[sipmethod].text);
19352 memset(digest, 0, sizeof(digest));
19353 if (reply_digest(p, req, header, sipmethod, digest, sizeof(digest) )) {
19354
19355 return -1;
19356 }
19357
19358 p->options->auth = digest;
19359 p->options->authheader = respheader;
19360 return transmit_invite(p, sipmethod, sipmethod == SIP_INVITE, init, NULL);
19361 }
19362
19363
19364
19365
19366
19367 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len)
19368 {
19369 char tmp[512];
19370 char *c;
19371 char oldnonce[256];
19372
19373
19374 const struct x {
19375 const char *key;
19376 const ast_string_field *field;
19377 } *i, keys[] = {
19378 { "realm=", &p->realm },
19379 { "nonce=", &p->nonce },
19380 { "opaque=", &p->opaque },
19381 { "qop=", &p->qop },
19382 { "domain=", &p->domain },
19383 { NULL, 0 },
19384 };
19385
19386 ast_copy_string(tmp, get_header(req, header), sizeof(tmp));
19387 if (ast_strlen_zero(tmp))
19388 return -1;
19389 if (strncasecmp(tmp, "Digest ", strlen("Digest "))) {
19390 ast_log(LOG_WARNING, "missing Digest.\n");
19391 return -1;
19392 }
19393 c = tmp + strlen("Digest ");
19394 ast_copy_string(oldnonce, p->nonce, sizeof(oldnonce));
19395 while (c && *(c = ast_skip_blanks(c))) {
19396 for (i = keys; i->key != NULL; i++) {
19397 char *src, *separator;
19398 if (strncasecmp(c, i->key, strlen(i->key)) != 0)
19399 continue;
19400
19401 c += strlen(i->key);
19402 if (*c == '"') {
19403 src = ++c;
19404 separator = "\"";
19405 } else {
19406 src = c;
19407 separator = ",";
19408 }
19409 strsep(&c, separator);
19410 ast_string_field_ptr_set(p, i->field, src);
19411 break;
19412 }
19413 if (i->key == NULL)
19414 strsep(&c, ",");
19415 }
19416
19417 if (strcmp(p->nonce, oldnonce))
19418 p->noncecount = 0;
19419
19420
19421 if (p->registry) {
19422 struct sip_registry *r = p->registry;
19423
19424 if (strcmp(r->nonce, p->nonce)) {
19425 ast_string_field_set(r, realm, p->realm);
19426 ast_string_field_set(r, nonce, p->nonce);
19427 ast_string_field_set(r, authdomain, p->domain);
19428 ast_string_field_set(r, opaque, p->opaque);
19429 ast_string_field_set(r, qop, p->qop);
19430 r->noncecount = 0;
19431 }
19432 }
19433 return build_reply_digest(p, sipmethod, digest, digest_len);
19434 }
19435
19436
19437
19438
19439
19440
19441 static int build_reply_digest(struct sip_pvt *p, int method, char* digest, int digest_len)
19442 {
19443 char a1[256];
19444 char a2[256];
19445 char a1_hash[256];
19446 char a2_hash[256];
19447 char resp[256];
19448 char resp_hash[256];
19449 char uri[256];
19450 char opaque[256] = "";
19451 char cnonce[80];
19452 const char *username;
19453 const char *secret;
19454 const char *md5secret;
19455 struct sip_auth *auth;
19456 struct sip_auth_container *credentials;
19457
19458 if (!ast_strlen_zero(p->domain))
19459 snprintf(uri, sizeof(uri), "%s:%s", p->socket.type == SIP_TRANSPORT_TLS ? "sips" : "sip", p->domain);
19460 else if (!ast_strlen_zero(p->uri))
19461 ast_copy_string(uri, p->uri, sizeof(uri));
19462 else
19463 snprintf(uri, sizeof(uri), "%s:%s@%s", p->socket.type == SIP_TRANSPORT_TLS ? "sips" : "sip", p->username, ast_sockaddr_stringify_host_remote(&p->sa));
19464
19465 snprintf(cnonce, sizeof(cnonce), "%08lx", ast_random());
19466
19467
19468 ao2_lock(p);
19469 credentials = p->peerauth;
19470 if (credentials) {
19471 ao2_t_ref(credentials, +1, "Ref peer auth for digest");
19472 }
19473 ao2_unlock(p);
19474 auth = find_realm_authentication(credentials, p->realm);
19475 if (!auth) {
19476
19477 if (credentials) {
19478 ao2_t_ref(credentials, -1, "Unref peer auth for digest");
19479 }
19480 ast_mutex_lock(&authl_lock);
19481 credentials = authl;
19482 if (credentials) {
19483 ao2_t_ref(credentials, +1, "Ref global auth for digest");
19484 }
19485 ast_mutex_unlock(&authl_lock);
19486 auth = find_realm_authentication(credentials, p->realm);
19487 }
19488
19489 if (auth) {
19490 ast_debug(3, "use realm [%s] from peer [%s][%s]\n", auth->username, p->peername, p->username);
19491 username = auth->username;
19492 secret = auth->secret;
19493 md5secret = auth->md5secret;
19494 if (sipdebug)
19495 ast_debug(1, "Using realm %s authentication for call %s\n", p->realm, p->callid);
19496 } else {
19497
19498 username = p->authname;
19499 secret = p->relatedpeer
19500 && !ast_strlen_zero(p->relatedpeer->remotesecret)
19501 ? p->relatedpeer->remotesecret : p->peersecret;
19502 md5secret = p->peermd5secret;
19503 }
19504 if (ast_strlen_zero(username)) {
19505
19506 if (credentials) {
19507 ao2_t_ref(credentials, -1, "Unref auth for digest");
19508 }
19509 return -1;
19510 }
19511
19512
19513 snprintf(a1, sizeof(a1), "%s:%s:%s", username, p->realm, secret);
19514 snprintf(a2, sizeof(a2), "%s:%s", sip_methods[method].text, uri);
19515 if (!ast_strlen_zero(md5secret))
19516 ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
19517 else
19518 ast_md5_hash(a1_hash, a1);
19519 ast_md5_hash(a2_hash, a2);
19520
19521 p->noncecount++;
19522 if (!ast_strlen_zero(p->qop))
19523 snprintf(resp, sizeof(resp), "%s:%s:%08x:%s:%s:%s", a1_hash, p->nonce, p->noncecount, cnonce, "auth", a2_hash);
19524 else
19525 snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, p->nonce, a2_hash);
19526 ast_md5_hash(resp_hash, resp);
19527
19528
19529 if (!ast_strlen_zero(p->opaque)) {
19530 snprintf(opaque, sizeof(opaque), ", opaque=\"%s\"", p->opaque);
19531 }
19532
19533
19534 if (!ast_strlen_zero(p->qop))
19535 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);
19536 else
19537 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);
19538
19539 append_history(p, "AuthResp", "Auth response sent for %s in realm %s - nc %d", username, p->realm, p->noncecount);
19540
19541 if (credentials) {
19542 ao2_t_ref(credentials, -1, "Unref auth for digest");
19543 }
19544 return 0;
19545 }
19546
19547
19548 static int func_header_read(struct ast_channel *chan, const char *function, char *data, char *buf, size_t len)
19549 {
19550 struct sip_pvt *p;
19551 const char *content = NULL;
19552 AST_DECLARE_APP_ARGS(args,
19553 AST_APP_ARG(header);
19554 AST_APP_ARG(number);
19555 );
19556 int i, number, start = 0;
19557
19558 if (ast_strlen_zero(data)) {
19559 ast_log(LOG_WARNING, "This function requires a header name.\n");
19560 return -1;
19561 }
19562
19563 ast_channel_lock(chan);
19564 if (!IS_SIP_TECH(chan->tech)) {
19565 ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
19566 ast_channel_unlock(chan);
19567 return -1;
19568 }
19569
19570 AST_STANDARD_APP_ARGS(args, data);
19571 if (!args.number) {
19572 number = 1;
19573 } else {
19574 sscanf(args.number, "%30d", &number);
19575 if (number < 1)
19576 number = 1;
19577 }
19578
19579 p = chan->tech_pvt;
19580
19581
19582 if (!p) {
19583 ast_channel_unlock(chan);
19584 return -1;
19585 }
19586
19587 for (i = 0; i < number; i++)
19588 content = __get_header(&p->initreq, args.header, &start);
19589
19590 if (ast_strlen_zero(content)) {
19591 ast_channel_unlock(chan);
19592 return -1;
19593 }
19594
19595 ast_copy_string(buf, content, len);
19596 ast_channel_unlock(chan);
19597
19598 return 0;
19599 }
19600
19601 static struct ast_custom_function sip_header_function = {
19602 .name = "SIP_HEADER",
19603 .read = func_header_read,
19604 };
19605
19606
19607 static int func_check_sipdomain(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
19608 {
19609 if (ast_strlen_zero(data)) {
19610 ast_log(LOG_WARNING, "CHECKSIPDOMAIN requires an argument - A domain name\n");
19611 return -1;
19612 }
19613 if (check_sip_domain(data, NULL, 0))
19614 ast_copy_string(buf, data, len);
19615 else
19616 buf[0] = '\0';
19617 return 0;
19618 }
19619
19620 static struct ast_custom_function checksipdomain_function = {
19621 .name = "CHECKSIPDOMAIN",
19622 .read = func_check_sipdomain,
19623 };
19624
19625
19626 static int function_sippeer(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
19627 {
19628 struct sip_peer *peer;
19629 char *colname;
19630
19631 if ((colname = strchr(data, ':'))) {
19632 static int deprecation_warning = 0;
19633 *colname++ = '\0';
19634 if (deprecation_warning++ % 10 == 0)
19635 ast_log(LOG_WARNING, "SIPPEER(): usage of ':' to separate arguments is deprecated. Please use ',' instead.\n");
19636 } else if ((colname = strchr(data, ',')))
19637 *colname++ = '\0';
19638 else
19639 colname = "ip";
19640
19641 if (!(peer = find_peer(data, NULL, TRUE, FINDPEERS, FALSE, 0)))
19642 return -1;
19643
19644 if (!strcasecmp(colname, "ip")) {
19645 ast_copy_string(buf, ast_sockaddr_stringify_addr(&peer->addr), len);
19646 } else if (!strcasecmp(colname, "port")) {
19647 snprintf(buf, len, "%d", ast_sockaddr_port(&peer->addr));
19648 } else if (!strcasecmp(colname, "status")) {
19649 peer_status(peer, buf, len);
19650 } else if (!strcasecmp(colname, "language")) {
19651 ast_copy_string(buf, peer->language, len);
19652 } else if (!strcasecmp(colname, "regexten")) {
19653 ast_copy_string(buf, peer->regexten, len);
19654 } else if (!strcasecmp(colname, "limit")) {
19655 snprintf(buf, len, "%d", peer->call_limit);
19656 } else if (!strcasecmp(colname, "busylevel")) {
19657 snprintf(buf, len, "%d", peer->busy_level);
19658 } else if (!strcasecmp(colname, "curcalls")) {
19659 snprintf(buf, len, "%d", peer->inUse);
19660 } else if (!strcasecmp(colname, "maxforwards")) {
19661 snprintf(buf, len, "%d", peer->maxforwards);
19662 } else if (!strcasecmp(colname, "accountcode")) {
19663 ast_copy_string(buf, peer->accountcode, len);
19664 } else if (!strcasecmp(colname, "callgroup")) {
19665 ast_print_group(buf, len, peer->callgroup);
19666 } else if (!strcasecmp(colname, "pickupgroup")) {
19667 ast_print_group(buf, len, peer->pickupgroup);
19668 } else if (!strcasecmp(colname, "useragent")) {
19669 ast_copy_string(buf, peer->useragent, len);
19670 } else if (!strcasecmp(colname, "mailbox")) {
19671 struct ast_str *mailbox_str = ast_str_alloca(512);
19672 peer_mailboxes_to_str(&mailbox_str, peer);
19673 ast_copy_string(buf, mailbox_str->str, len);
19674 } else if (!strcasecmp(colname, "context")) {
19675 ast_copy_string(buf, peer->context, len);
19676 } else if (!strcasecmp(colname, "expire")) {
19677 snprintf(buf, len, "%d", peer->expire);
19678 } else if (!strcasecmp(colname, "dynamic")) {
19679 ast_copy_string(buf, peer->host_dynamic ? "yes" : "no", len);
19680 } else if (!strcasecmp(colname, "callerid_name")) {
19681 ast_copy_string(buf, peer->cid_name, len);
19682 } else if (!strcasecmp(colname, "callerid_num")) {
19683 ast_copy_string(buf, peer->cid_num, len);
19684 } else if (!strcasecmp(colname, "codecs")) {
19685 ast_getformatname_multiple(buf, len -1, peer->capability);
19686 } else if (!strcasecmp(colname, "encryption")) {
19687 snprintf(buf, len, "%d", ast_test_flag(&peer->flags[1], SIP_PAGE2_USE_SRTP));
19688 } else if (!strncasecmp(colname, "chanvar[", 8)) {
19689 char *chanvar=colname + 8;
19690 struct ast_variable *v;
19691
19692 chanvar = strsep(&chanvar, "]");
19693 for (v = peer->chanvars ; v ; v = v->next) {
19694 if (!strcasecmp(v->name, chanvar)) {
19695 ast_copy_string(buf, v->value, len);
19696 }
19697 }
19698 } else if (!strncasecmp(colname, "codec[", 6)) {
19699 char *codecnum;
19700 format_t codec = 0;
19701
19702 codecnum = colname + 6;
19703 codecnum = strsep(&codecnum, "]");
19704 if((codec = ast_codec_pref_index(&peer->prefs, atoi(codecnum)))) {
19705 ast_copy_string(buf, ast_getformatname(codec), len);
19706 } else {
19707 buf[0] = '\0';
19708 }
19709 } else {
19710 buf[0] = '\0';
19711 }
19712
19713 unref_peer(peer, "unref_peer from function_sippeer, just before return");
19714
19715 return 0;
19716 }
19717
19718
19719 static struct ast_custom_function sippeer_function = {
19720 .name = "SIPPEER",
19721 .read = function_sippeer,
19722 };
19723
19724
19725 static int function_sipchaninfo_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
19726 {
19727 struct sip_pvt *p;
19728 static int deprecated = 0;
19729
19730 *buf = 0;
19731
19732 if (!data) {
19733 ast_log(LOG_WARNING, "This function requires a parameter name.\n");
19734 return -1;
19735 }
19736
19737 ast_channel_lock(chan);
19738 if (!IS_SIP_TECH(chan->tech)) {
19739 ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
19740 ast_channel_unlock(chan);
19741 return -1;
19742 }
19743
19744 if (deprecated++ % 20 == 0) {
19745
19746 ast_log(LOG_WARNING, "SIPCHANINFO() is deprecated. Please transition to using CHANNEL().\n");
19747 }
19748
19749 p = chan->tech_pvt;
19750
19751
19752 if (!p) {
19753 ast_channel_unlock(chan);
19754 return -1;
19755 }
19756
19757 if (!strcasecmp(data, "peerip")) {
19758 ast_copy_string(buf, ast_sockaddr_stringify_addr(&p->sa), len);
19759 } else if (!strcasecmp(data, "recvip")) {
19760 ast_copy_string(buf, ast_sockaddr_stringify_addr(&p->recv), len);
19761 } else if (!strcasecmp(data, "from")) {
19762 ast_copy_string(buf, p->from, len);
19763 } else if (!strcasecmp(data, "uri")) {
19764 ast_copy_string(buf, p->uri, len);
19765 } else if (!strcasecmp(data, "useragent")) {
19766 ast_copy_string(buf, p->useragent, len);
19767 } else if (!strcasecmp(data, "peername")) {
19768 ast_copy_string(buf, p->peername, len);
19769 } else if (!strcasecmp(data, "t38passthrough")) {
19770 if (p->t38.state == T38_DISABLED) {
19771 ast_copy_string(buf, "0", len);
19772 } else {
19773 ast_copy_string(buf, "1", len);
19774 }
19775 } else {
19776 ast_channel_unlock(chan);
19777 return -1;
19778 }
19779 ast_channel_unlock(chan);
19780
19781 return 0;
19782 }
19783
19784
19785 static struct ast_custom_function sipchaninfo_function = {
19786 .name = "SIPCHANINFO",
19787 .read = function_sipchaninfo_read,
19788 };
19789
19790
19791
19792
19793 static void change_redirecting_information(struct sip_pvt *p, struct sip_request *req,
19794 struct ast_party_redirecting *redirecting,
19795 struct ast_set_party_redirecting *update_redirecting, int set_call_forward)
19796 {
19797 char *redirecting_from_name = NULL;
19798 char *redirecting_from_number = NULL;
19799 char *redirecting_to_name = NULL;
19800 char *redirecting_to_number = NULL;
19801 int reason = AST_REDIRECTING_REASON_UNCONDITIONAL;
19802 int is_response = req->method == SIP_RESPONSE;
19803 int res = 0;
19804
19805 res = get_rdnis(p, req, &redirecting_from_name, &redirecting_from_number, &reason);
19806 if (res == -1) {
19807 if (is_response) {
19808 get_name_and_number(get_header(req, "TO"), &redirecting_from_name, &redirecting_from_number);
19809 } else {
19810 return;
19811 }
19812 }
19813
19814
19815
19816
19817
19818 if (is_response) {
19819 parse_moved_contact(p, req, &redirecting_to_name, &redirecting_to_number, set_call_forward);
19820 } else {
19821 get_name_and_number(get_header(req, "TO"), &redirecting_to_name, &redirecting_to_number);
19822 }
19823
19824 if (!ast_strlen_zero(redirecting_from_number)) {
19825 ast_debug(3, "Got redirecting from number %s\n", redirecting_from_number);
19826 update_redirecting->from.number = 1;
19827 redirecting->from.number.valid = 1;
19828 ast_free(redirecting->from.number.str);
19829 redirecting->from.number.str = redirecting_from_number;
19830 }
19831 if (!ast_strlen_zero(redirecting_from_name)) {
19832 ast_debug(3, "Got redirecting from name %s\n", redirecting_from_name);
19833 update_redirecting->from.name = 1;
19834 redirecting->from.name.valid = 1;
19835 ast_free(redirecting->from.name.str);
19836 redirecting->from.name.str = redirecting_from_name;
19837 }
19838 if (!ast_strlen_zero(p->cid_tag)) {
19839 ast_free(redirecting->from.tag);
19840 redirecting->from.tag = ast_strdup(p->cid_tag);
19841 ast_free(redirecting->to.tag);
19842 redirecting->to.tag = ast_strdup(p->cid_tag);
19843 }
19844 if (!ast_strlen_zero(redirecting_to_number)) {
19845 ast_debug(3, "Got redirecting to number %s\n", redirecting_to_number);
19846 update_redirecting->to.number = 1;
19847 redirecting->to.number.valid = 1;
19848 ast_free(redirecting->to.number.str);
19849 redirecting->to.number.str = redirecting_to_number;
19850 }
19851 if (!ast_strlen_zero(redirecting_to_name)) {
19852 ast_debug(3, "Got redirecting to name %s\n", redirecting_from_number);
19853 update_redirecting->to.name = 1;
19854 redirecting->to.name.valid = 1;
19855 ast_free(redirecting->to.name.str);
19856 redirecting->to.name.str = redirecting_to_name;
19857 }
19858 redirecting->reason = reason;
19859 }
19860
19861
19862
19863
19864
19865
19866
19867 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req, char **name, char **number, int set_call_forward)
19868 {
19869 char contact[SIPBUFSIZE];
19870 char *contact_name = NULL;
19871 char *contact_number = NULL;
19872 char *separator, *trans;
19873 char *domain;
19874 enum sip_transport transport = SIP_TRANSPORT_UDP;
19875
19876 ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
19877 if ((separator = strchr(contact, ',')))
19878 *separator = '\0';
19879
19880 contact_number = get_in_brackets(contact);
19881 if ((trans = strcasestr(contact_number, ";transport="))) {
19882 trans += 11;
19883
19884 if ((separator = strchr(trans, ';')))
19885 *separator = '\0';
19886
19887 if (!strncasecmp(trans, "tcp", 3))
19888 transport = SIP_TRANSPORT_TCP;
19889 else if (!strncasecmp(trans, "tls", 3))
19890 transport = SIP_TRANSPORT_TLS;
19891 else {
19892 if (strncasecmp(trans, "udp", 3))
19893 ast_debug(1, "received contact with an invalid transport, '%s'\n", contact_number);
19894
19895 transport = SIP_TRANSPORT_UDP;
19896 }
19897 }
19898 contact_number = remove_uri_parameters(contact_number);
19899
19900 if (p->socket.tcptls_session) {
19901 ao2_ref(p->socket.tcptls_session, -1);
19902 p->socket.tcptls_session = NULL;
19903 }
19904
19905 set_socket_transport(&p->socket, transport);
19906
19907 if (set_call_forward && ast_test_flag(&p->flags[0], SIP_PROMISCREDIR)) {
19908 char *host = NULL;
19909 if (!strncasecmp(contact_number, "sip:", 4))
19910 contact_number += 4;
19911 else if (!strncasecmp(contact_number, "sips:", 5))
19912 contact_number += 5;
19913 separator = strchr(contact_number, '/');
19914 if (separator)
19915 *separator = '\0';
19916 if ((host = strchr(contact_number, '@'))) {
19917 *host++ = '\0';
19918 ast_debug(2, "Found promiscuous redirection to 'SIP/%s::::%s@%s'\n", contact_number, get_transport(transport), host);
19919 if (p->owner)
19920 ast_string_field_build(p->owner, call_forward, "SIP/%s::::%s@%s", contact_number, get_transport(transport), host);
19921 } else {
19922 ast_debug(2, "Found promiscuous redirection to 'SIP/::::%s@%s'\n", get_transport(transport), contact_number);
19923 if (p->owner)
19924 ast_string_field_build(p->owner, call_forward, "SIP/::::%s@%s", get_transport(transport), contact_number);
19925 }
19926 } else {
19927 separator = strchr(contact, '@');
19928 if (separator) {
19929 *separator++ = '\0';
19930 domain = separator;
19931 } else {
19932
19933 domain = contact;
19934 }
19935 separator = strchr(contact, '/');
19936 if (separator)
19937 *separator = '\0';
19938
19939 if (!strncasecmp(contact_number, "sip:", 4))
19940 contact_number += 4;
19941 else if (!strncasecmp(contact_number, "sips:", 5))
19942 contact_number += 5;
19943 separator = strchr(contact_number, ';');
19944 if (separator)
19945 *separator = '\0';
19946 ast_uri_decode(contact_number);
19947 if (set_call_forward) {
19948 ast_debug(2, "Received 302 Redirect to extension '%s' (domain %s)\n", contact_number, domain);
19949 if (p->owner) {
19950 pbx_builtin_setvar_helper(p->owner, "SIPDOMAIN", domain);
19951 ast_string_field_set(p->owner, call_forward, contact_number);
19952 }
19953 }
19954 }
19955
19956
19957
19958 if (*contact == '\"') {
19959 contact_name = contact + 1;
19960 if (!(separator = (char *)find_closing_quote(contact_name, NULL))) {
19961 ast_log(LOG_NOTICE, "No closing quote on name in Contact header? %s\n", contact);
19962 }
19963 *separator = '\0';
19964 }
19965
19966 if (name && !ast_strlen_zero(contact_name)) {
19967 *name = ast_strdup(contact_name);
19968 }
19969 if (number) {
19970 *number = ast_strdup(contact_number);
19971 }
19972 }
19973
19974
19975
19976
19977
19978
19979 static void check_pendings(struct sip_pvt *p)
19980 {
19981 if (ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
19982 if (p->reinviteid > -1) {
19983
19984 return;
19985 } else if (p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA) {
19986
19987 p->invitestate = INV_CANCELLED;
19988 transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
19989
19990 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
19991 ast_clear_flag(&p->flags[0], SIP_PENDINGBYE);
19992 }
19993
19994
19995 } else {
19996
19997
19998
19999 if (p->pendinginvite && !p->ongoing_reinvite)
20000 return;
20001
20002 if (p->owner) {
20003 ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
20004 }
20005
20006 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, TRUE);
20007 ast_clear_flag(&p->flags[0], SIP_PENDINGBYE);
20008 }
20009 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20010 } else if (ast_test_flag(&p->flags[0], SIP_NEEDREINVITE)) {
20011
20012 if (p->pendinginvite || p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA || p->waitid > 0) {
20013 ast_debug(2, "NOT Sending pending reinvite (yet) on '%s'\n", p->callid);
20014 } else {
20015 ast_debug(2, "Sending pending reinvite on '%s'\n", p->callid);
20016
20017 transmit_reinvite_with_sdp(p, (p->t38.state == T38_LOCAL_REINVITE ? TRUE : FALSE), FALSE);
20018 ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);
20019 }
20020 }
20021 }
20022
20023
20024
20025
20026
20027 static int sip_reinvite_retry(const void *data)
20028 {
20029 struct sip_pvt *p = (struct sip_pvt *) data;
20030 struct ast_channel *owner;
20031
20032 sip_pvt_lock(p);
20033 while ((owner = p->owner) && ast_channel_trylock(owner)) {
20034 sip_pvt_unlock(p);
20035 usleep(1);
20036 sip_pvt_lock(p);
20037 }
20038 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
20039 p->waitid = -1;
20040 check_pendings(p);
20041 sip_pvt_unlock(p);
20042 if (owner) {
20043 ast_channel_unlock(owner);
20044 }
20045 dialog_unref(p, "unref the dialog ptr from sip_reinvite_retry, because it held a dialog ptr");
20046 return 0;
20047 }
20048
20049
20050
20051
20052
20053
20054 static void handle_response_update(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
20055 {
20056 if (p->options) {
20057 p->options->auth_type = (resp == 401 ? WWW_AUTH : PROXY_AUTH);
20058 }
20059 if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp, SIP_UPDATE, 1)) {
20060 ast_log(LOG_NOTICE, "Failed to authenticate on UPDATE to '%s'\n", get_header(&p->initreq, "From"));
20061 }
20062 }
20063
20064 static void cc_handle_publish_error(struct sip_pvt *pvt, const int resp, struct sip_request *req, struct sip_epa_entry *epa_entry)
20065 {
20066 struct cc_epa_entry *cc_entry = epa_entry->instance_data;
20067 struct sip_monitor_instance *monitor_instance = ao2_callback(sip_monitor_instances, 0,
20068 find_sip_monitor_instance_by_suspension_entry, epa_entry);
20069 const char *min_expires;
20070
20071 if (!monitor_instance) {
20072 ast_log(LOG_WARNING, "Can't find monitor_instance corresponding to epa_entry %p.\n", epa_entry);
20073 return;
20074 }
20075
20076 if (resp != 423) {
20077 ast_cc_monitor_failed(cc_entry->core_id, monitor_instance->device_name,
20078 "Received error response to our PUBLISH");
20079 ao2_ref(monitor_instance, -1);
20080 return;
20081 }
20082
20083
20084
20085
20086
20087
20088
20089
20090
20091 min_expires = get_header(req, "Min-Expires");
20092 if (ast_strlen_zero(min_expires)) {
20093 pvt->expiry *= 2;
20094 if (pvt->expiry < 0) {
20095
20096 ast_cc_monitor_failed(cc_entry->core_id, monitor_instance->device_name,
20097 "PUBLISH expiry overflowed");
20098 ao2_ref(monitor_instance, -1);
20099 return;
20100 }
20101 } else if (sscanf(min_expires, "%d", &pvt->expiry) != 1) {
20102 ast_cc_monitor_failed(cc_entry->core_id, monitor_instance->device_name,
20103 "Min-Expires has non-numeric value");
20104 ao2_ref(monitor_instance, -1);
20105 return;
20106 }
20107
20108
20109
20110 transmit_invite(pvt, SIP_PUBLISH, FALSE, 0, NULL);
20111 ao2_ref(monitor_instance, -1);
20112 }
20113
20114 static void handle_response_publish(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
20115 {
20116 struct sip_epa_entry *epa_entry = p->epa_entry;
20117 const char *etag = get_header(req, "Sip-ETag");
20118
20119 ast_assert(epa_entry != NULL);
20120
20121 if (resp == 401 || resp == 407) {
20122 ast_string_field_set(p, theirtag, NULL);
20123 if (p->options) {
20124 p->options->auth_type = (resp == 401 ? WWW_AUTH : PROXY_AUTH);
20125 }
20126 if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp, SIP_PUBLISH, 0)) {
20127 ast_log(LOG_NOTICE, "Failed to authenticate on PUBLISH to '%s'\n", get_header(&p->initreq, "From"));
20128 pvt_set_needdestroy(p, "Failed to authenticate on PUBLISH");
20129 sip_alreadygone(p);
20130 }
20131 return;
20132 }
20133
20134 if (resp == 501 || resp == 405) {
20135 mark_method_unallowed(&p->allowed_methods, SIP_PUBLISH);
20136 }
20137
20138 if (resp == 200) {
20139 p->authtries = 0;
20140
20141
20142
20143 if (!ast_strlen_zero(etag)) {
20144 ast_copy_string(epa_entry->entity_tag, etag, sizeof(epa_entry->entity_tag));
20145 }
20146
20147
20148
20149
20150 if (epa_entry->static_data->handle_ok) {
20151 epa_entry->static_data->handle_ok(p, req, epa_entry);
20152 }
20153 } else {
20154
20155
20156
20157
20158 if (epa_entry->static_data->handle_error) {
20159 epa_entry->static_data->handle_error(p, resp, req, epa_entry);
20160 }
20161 }
20162 }
20163
20164
20165
20166
20167
20168
20169
20170
20171
20172
20173
20174
20175 static void sip_queue_hangup_cause(struct sip_pvt *p, int cause)
20176 {
20177 struct ast_channel *owner = p->owner;
20178 const char *name = ast_strdupa(owner->name);
20179
20180
20181 ast_channel_ref(owner);
20182 ast_channel_unlock(owner);
20183 sip_pvt_unlock(p);
20184 ast_set_hangupsource(owner, name, 0);
20185 if (cause) {
20186 ast_queue_hangup_with_cause(owner, cause);
20187 } else {
20188 ast_queue_hangup(owner);
20189 }
20190 ast_channel_unref(owner);
20191
20192
20193 owner = sip_pvt_lock_full(p);
20194 if (owner) {
20195 ast_channel_unref(owner);
20196 }
20197 }
20198
20199
20200 static void handle_response_invite(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
20201 {
20202 int outgoing = ast_test_flag(&p->flags[0], SIP_OUTGOING);
20203 int res = 0;
20204 int xmitres = 0;
20205 int reinvite = ast_test_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
20206 char *p_hdrval;
20207 int rtn;
20208 struct ast_party_connected_line connected;
20209 struct ast_set_party_connected_line update_connected;
20210
20211 if (reinvite)
20212 ast_debug(4, "SIP response %d to RE-invite on %s call %s\n", resp, outgoing ? "outgoing" : "incoming", p->callid);
20213 else
20214 ast_debug(4, "SIP response %d to standard invite\n", resp);
20215
20216 if (p->alreadygone) {
20217 ast_debug(1, "Got response on call that is already terminated: %s (ignoring)\n", p->callid);
20218 return;
20219 }
20220
20221
20222
20223 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"));
20224
20225
20226
20227
20228 if (resp > 100 && resp < 200 && resp!=101 && resp != 180 && resp != 181 && resp != 182 && resp != 183)
20229 resp = 183;
20230
20231
20232 if (resp >= 100 && resp < 200 && p->invitestate == INV_CALLING)
20233 p->invitestate = INV_PROCEEDING;
20234
20235
20236 if (resp >= 300 && (p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA ))
20237 p->invitestate = INV_COMPLETED;
20238
20239 if ((resp >= 200 && reinvite)) {
20240 p->ongoing_reinvite = 0;
20241 if (p->reinviteid > -1) {
20242 AST_SCHED_DEL_UNREF(sched, p->reinviteid, dialog_unref(p, "unref dialog for reinvite timeout because of a final response"));
20243 }
20244 }
20245
20246
20247 if ((resp == 200 || resp >= 300) && p->pendinginvite && seqno == p->pendinginvite) {
20248 p->pendinginvite = 0;
20249 }
20250
20251
20252
20253
20254 if (!reinvite) {
20255 set_pvt_allowed_methods(p, req);
20256 }
20257
20258 switch (resp) {
20259 case 100:
20260 case 101:
20261 if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p))
20262 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
20263 check_pendings(p);
20264 break;
20265
20266 case 180:
20267 case 182:
20268 if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p))
20269 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
20270
20271
20272
20273 parse_ok_contact(p, req);
20274 if (!reinvite) {
20275 build_route(p, req, 1, resp);
20276 }
20277 if (!req->ignore && p->owner) {
20278 if (get_rpid(p, req)) {
20279
20280 ast_party_connected_line_init(&connected);
20281 memset(&update_connected, 0, sizeof(update_connected));
20282
20283 update_connected.id.number = 1;
20284 connected.id.number.valid = 1;
20285 connected.id.number.str = (char *) p->cid_num;
20286 connected.id.number.presentation = p->callingpres;
20287
20288 update_connected.id.name = 1;
20289 connected.id.name.valid = 1;
20290 connected.id.name.str = (char *) p->cid_name;
20291 connected.id.name.presentation = p->callingpres;
20292
20293 connected.id.tag = (char *) p->cid_tag;
20294 connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
20295 ast_channel_queue_connected_line_update(p->owner, &connected,
20296 &update_connected);
20297 }
20298 sip_handle_cc(p, req, AST_CC_CCNR);
20299 ast_queue_control(p->owner, AST_CONTROL_RINGING);
20300 if (p->owner->_state != AST_STATE_UP) {
20301 ast_setstate(p->owner, AST_STATE_RINGING);
20302 }
20303 }
20304 if (find_sdp(req)) {
20305 if (p->invitestate != INV_CANCELLED)
20306 p->invitestate = INV_EARLY_MEDIA;
20307 res = process_sdp(p, req, SDP_T38_NONE);
20308 if (!req->ignore && p->owner) {
20309
20310 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
20311 }
20312 ast_rtp_instance_activate(p->rtp);
20313 }
20314 check_pendings(p);
20315 break;
20316
20317 case 181:
20318 if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
20319 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
20320
20321
20322
20323 parse_ok_contact(p, req);
20324 if (!reinvite) {
20325 build_route(p, req, 1, resp);
20326 }
20327 if (!req->ignore && p->owner) {
20328 struct ast_party_redirecting redirecting;
20329 struct ast_set_party_redirecting update_redirecting;
20330
20331 ast_party_redirecting_init(&redirecting);
20332 memset(&update_redirecting, 0, sizeof(update_redirecting));
20333 change_redirecting_information(p, req, &redirecting, &update_redirecting,
20334 FALSE);
20335 ast_channel_queue_redirecting_update(p->owner, &redirecting,
20336 &update_redirecting);
20337 ast_party_redirecting_free(&redirecting);
20338 sip_handle_cc(p, req, AST_CC_CCNR);
20339 }
20340 check_pendings(p);
20341 break;
20342
20343 case 183:
20344 if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
20345 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
20346
20347
20348
20349 parse_ok_contact(p, req);
20350 if (!reinvite) {
20351 build_route(p, req, 1, resp);
20352 }
20353 if (!req->ignore && p->owner) {
20354 if (get_rpid(p, req)) {
20355
20356 ast_party_connected_line_init(&connected);
20357 memset(&update_connected, 0, sizeof(update_connected));
20358
20359 update_connected.id.number = 1;
20360 connected.id.number.valid = 1;
20361 connected.id.number.str = (char *) p->cid_num;
20362 connected.id.number.presentation = p->callingpres;
20363
20364 update_connected.id.name = 1;
20365 connected.id.name.valid = 1;
20366 connected.id.name.str = (char *) p->cid_name;
20367 connected.id.name.presentation = p->callingpres;
20368
20369 connected.id.tag = (char *) p->cid_tag;
20370 connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
20371 ast_channel_queue_connected_line_update(p->owner, &connected,
20372 &update_connected);
20373 }
20374 sip_handle_cc(p, req, AST_CC_CCNR);
20375 }
20376 if (find_sdp(req)) {
20377 if (p->invitestate != INV_CANCELLED)
20378 p->invitestate = INV_EARLY_MEDIA;
20379 res = process_sdp(p, req, SDP_T38_NONE);
20380 if (!req->ignore && p->owner) {
20381
20382 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
20383 }
20384 ast_rtp_instance_activate(p->rtp);
20385 } else {
20386
20387
20388
20389
20390 if (!req->ignore && p->owner) {
20391 ast_queue_control(p->owner, AST_CONTROL_RINGING);
20392 }
20393 }
20394 check_pendings(p);
20395 break;
20396
20397 case 200:
20398 if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
20399 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
20400 p->authtries = 0;
20401 if (find_sdp(req)) {
20402 if ((res = process_sdp(p, req, SDP_T38_ACCEPT)) && !req->ignore)
20403 if (!reinvite) {
20404
20405
20406 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
20407 }
20408 ast_rtp_instance_activate(p->rtp);
20409 }
20410
20411 if (!req->ignore && p->owner) {
20412 int rpid_changed;
20413
20414 rpid_changed = get_rpid(p, req);
20415 if (rpid_changed || !reinvite) {
20416
20417 ast_party_connected_line_init(&connected);
20418 memset(&update_connected, 0, sizeof(update_connected));
20419 if (rpid_changed
20420 || !ast_strlen_zero(p->cid_num)
20421 || (p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
20422 update_connected.id.number = 1;
20423 connected.id.number.valid = 1;
20424 connected.id.number.str = (char *) p->cid_num;
20425 connected.id.number.presentation = p->callingpres;
20426 }
20427 if (rpid_changed
20428 || !ast_strlen_zero(p->cid_name)
20429 || (p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
20430 update_connected.id.name = 1;
20431 connected.id.name.valid = 1;
20432 connected.id.name.str = (char *) p->cid_name;
20433 connected.id.name.presentation = p->callingpres;
20434 }
20435 if (update_connected.id.number || update_connected.id.name) {
20436 connected.id.tag = (char *) p->cid_tag;
20437 connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
20438 ast_channel_queue_connected_line_update(p->owner, &connected,
20439 &update_connected);
20440 }
20441 }
20442 }
20443
20444
20445
20446
20447 if (outgoing) {
20448 update_call_counter(p, DEC_CALL_RINGING);
20449 parse_ok_contact(p, req);
20450
20451 if (!reinvite) {
20452 build_route(p, req, 1, resp);
20453 }
20454 if(set_address_from_contact(p)) {
20455
20456
20457 if (!p->route && !req->ignore)
20458 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
20459 }
20460
20461 }
20462
20463 if (!req->ignore && p->owner) {
20464 if (!reinvite) {
20465 ast_queue_control(p->owner, AST_CONTROL_ANSWER);
20466 if (sip_cfg.callevents)
20467 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
20468 "Channel: %s\r\nChanneltype: %s\r\nUniqueid: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
20469 p->owner->name, "SIP", p->owner->uniqueid, p->callid, p->fullcontact, p->peername);
20470 } else {
20471 if (p->t38.state == T38_DISABLED) {
20472 ast_queue_control(p->owner, AST_CONTROL_UPDATE_RTP_PEER);
20473 } else {
20474 ast_queue_frame(p->owner, &ast_null_frame);
20475 }
20476 }
20477 } else {
20478
20479
20480
20481 if (!req->ignore)
20482 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
20483 }
20484
20485
20486 if (st_get_mode(p, 0) != SESSION_TIMER_MODE_REFUSE && p->outgoing_call == TRUE && !reinvite) {
20487 p_hdrval = (char*)get_header(req, "Session-Expires");
20488 if (!ast_strlen_zero(p_hdrval)) {
20489
20490 enum st_refresher_param st_ref_param;
20491 int tmp_st_interval = 0;
20492 rtn = parse_session_expires(p_hdrval, &tmp_st_interval, &st_ref_param);
20493 if (rtn != 0) {
20494 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
20495 }
20496 if (st_ref_param == SESSION_TIMER_REFRESHER_PARAM_UAC) {
20497 p->stimer->st_ref = SESSION_TIMER_REFRESHER_US;
20498 } else if (st_ref_param == SESSION_TIMER_REFRESHER_PARAM_UAS) {
20499 p->stimer->st_ref = SESSION_TIMER_REFRESHER_THEM;
20500 } else {
20501 ast_log(LOG_WARNING, "Unknown refresher on %s\n", p->callid);
20502 }
20503 if (tmp_st_interval) {
20504 p->stimer->st_interval = tmp_st_interval;
20505 }
20506 p->stimer->st_active = TRUE;
20507 p->stimer->st_active_peer_ua = TRUE;
20508 start_session_timer(p);
20509 } else {
20510
20511 if (st_get_mode(p, 0) == SESSION_TIMER_MODE_ORIGINATE) {
20512 p->stimer->st_ref = SESSION_TIMER_REFRESHER_US;
20513 p->stimer->st_active_peer_ua = FALSE;
20514 start_session_timer(p);
20515 }
20516 }
20517 }
20518
20519
20520
20521 p->invitestate = INV_TERMINATED;
20522 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
20523 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, TRUE);
20524 check_pendings(p);
20525 break;
20526
20527 case 407:
20528 case 401:
20529
20530 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
20531 if (p->options)
20532 p->options->auth_type = resp;
20533
20534
20535 ast_string_field_set(p, theirtag, NULL);
20536 if (!req->ignore) {
20537 if (p->authtries < MAX_AUTHTRIES)
20538 p->invitestate = INV_CALLING;
20539 if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, SIP_INVITE, 1)) {
20540 ast_log(LOG_NOTICE, "Failed to authenticate on INVITE to '%s'\n", get_header(&p->initreq, "From"));
20541 pvt_set_needdestroy(p, "failed to authenticate on INVITE");
20542 sip_alreadygone(p);
20543 if (p->owner)
20544 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
20545 }
20546 }
20547 break;
20548
20549 case 403:
20550
20551 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
20552 ast_log(LOG_WARNING, "Received response: \"Forbidden\" from '%s'\n", get_header(&p->initreq, "From"));
20553 if (!req->ignore && p->owner) {
20554 sip_queue_hangup_cause(p, hangup_sip2cause(resp));
20555 }
20556 break;
20557
20558 case 404:
20559 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
20560 if (p->owner && !req->ignore) {
20561 sip_queue_hangup_cause(p, hangup_sip2cause(resp));
20562 }
20563 break;
20564
20565 case 481:
20566
20567 ast_log(LOG_WARNING, "Re-invite to non-existing call leg on other UA. SIP dialog '%s'. Giving up.\n", p->callid);
20568 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
20569 if (p->owner) {
20570 ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
20571 }
20572 break;
20573
20574 case 422:
20575 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
20576 ast_string_field_set(p, theirtag, NULL);
20577 proc_422_rsp(p, req);
20578 break;
20579
20580 case 428:
20581 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
20582 append_history(p, "Identity", "SIP identity is required. Not supported by Asterisk.");
20583 ast_log(LOG_WARNING, "SIP identity required by proxy. SIP dialog '%s'. Giving up.\n", p->callid);
20584 if (p->owner && !req->ignore) {
20585 ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
20586 }
20587 break;
20588
20589 case 487:
20590
20591
20592
20593 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
20594 if (p->owner && !req->ignore) {
20595 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_NORMAL_CLEARING);
20596 append_history(p, "Hangup", "Got 487 on CANCEL request from us. Queued AST hangup request");
20597 } else if (!req->ignore) {
20598 update_call_counter(p, DEC_CALL_LIMIT);
20599 append_history(p, "Hangup", "Got 487 on CANCEL request from us on call without owner. Killing this dialog.");
20600 }
20601 check_pendings(p);
20602 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20603 break;
20604 case 415:
20605 case 488:
20606 case 606:
20607 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
20608 if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
20609 change_t38_state(p, T38_DISABLED);
20610
20611
20612
20613
20614 transmit_reinvite_with_sdp(p, FALSE, FALSE);
20615 } else {
20616
20617 if (p->owner && !req->ignore) {
20618 ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
20619 }
20620 }
20621 break;
20622 case 491:
20623 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
20624 if (p->owner && !req->ignore) {
20625 if (p->owner->_state != AST_STATE_UP) {
20626 ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
20627 } else {
20628
20629
20630
20631 int wait;
20632
20633
20634 if (p->outgoing_call) {
20635 wait = 2100 + ast_random() % 2000;
20636 } else {
20637 wait = ast_random() % 2000;
20638 }
20639 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."));
20640 ast_log(LOG_WARNING, "just did sched_add waitid(%d) for sip_reinvite_retry for dialog %s in handle_response_invite\n", p->waitid, p->callid);
20641 ast_debug(2, "Reinvite race. Waiting %d secs before retry\n", wait);
20642 }
20643 }
20644 break;
20645
20646 case 408:
20647 case 405:
20648 case 501:
20649 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
20650 if (p->owner) {
20651 ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
20652 }
20653 break;
20654 }
20655 if (xmitres == XMIT_ERROR)
20656 ast_log(LOG_WARNING, "Could not transmit message in dialog %s\n", p->callid);
20657 }
20658
20659
20660
20661
20662 static void handle_response_notify(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
20663 {
20664 switch (resp) {
20665 case 200:
20666
20667 if (p->owner) {
20668 if (p->refer) {
20669 ast_log(LOG_NOTICE, "Got OK on REFER Notify message\n");
20670 } else {
20671 ast_log(LOG_WARNING, "Notify answer on an owned channel? - %s\n", p->owner->name);
20672 }
20673 } else {
20674 if (p->subscribed == NONE && !p->refer) {
20675 ast_debug(4, "Got 200 accepted on NOTIFY %s\n", p->callid);
20676 pvt_set_needdestroy(p, "received 200 response");
20677 }
20678 if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
20679
20680 ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
20681 cb_extensionstate((char *)p->context, (char *)p->exten, p->laststate, (void *) p);
20682 }
20683 }
20684 break;
20685 case 401:
20686 case 407:
20687 if (!p->notify) {
20688 break;
20689 }
20690 ast_string_field_set(p, theirtag, NULL);
20691 if (ast_strlen_zero(p->authname)) {
20692 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));
20693 pvt_set_needdestroy(p, "unable to authenticate NOTIFY");
20694 }
20695 if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_NOTIFY, 0)) {
20696 ast_log(LOG_NOTICE, "Failed to authenticate on NOTIFY to '%s'\n", get_header(&p->initreq, "From"));
20697 pvt_set_needdestroy(p, "failed to authenticate NOTIFY");
20698 }
20699 break;
20700 case 481:
20701 pvt_set_needdestroy(p, "Received 481 response for NOTIFY");
20702 break;
20703 }
20704 }
20705
20706
20707 static void handle_response_subscribe(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
20708 {
20709 if (p->subscribed == CALL_COMPLETION) {
20710 struct sip_monitor_instance *monitor_instance;
20711
20712 if (resp < 300) {
20713 return;
20714 }
20715
20716
20717 monitor_instance = ao2_callback(sip_monitor_instances, 0,
20718 find_sip_monitor_instance_by_subscription_pvt, p);
20719 if (monitor_instance) {
20720 ast_cc_monitor_failed(monitor_instance->core_id,
20721 monitor_instance->device_name,
20722 "Received error response to our SUBSCRIBE");
20723 }
20724 return;
20725 }
20726
20727 if (p->subscribed != MWI_NOTIFICATION) {
20728 return;
20729 }
20730 if (!p->mwi) {
20731 return;
20732 }
20733
20734 switch (resp) {
20735 case 200:
20736 ast_debug(3, "Got 200 OK on subscription for MWI\n");
20737 set_pvt_allowed_methods(p, req);
20738 if (p->options) {
20739 if (p->options->outboundproxy) {
20740 ao2_ref(p->options->outboundproxy, -1);
20741 }
20742 ast_free(p->options);
20743 p->options = NULL;
20744 }
20745 p->mwi->subscribed = 1;
20746 if ((p->mwi->resub = ast_sched_add(sched, mwi_expiry * 1000, sip_subscribe_mwi_do, ASTOBJ_REF(p->mwi))) < 0) {
20747 ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
20748 }
20749 break;
20750 case 401:
20751 case 407:
20752 ast_string_field_set(p, theirtag, NULL);
20753 if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_SUBSCRIBE, 0)) {
20754 ast_log(LOG_NOTICE, "Failed to authenticate on SUBSCRIBE to '%s'\n", get_header(&p->initreq, "From"));
20755 p->mwi->call = NULL;
20756 ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
20757 pvt_set_needdestroy(p, "failed to authenticate SUBSCRIBE");
20758 }
20759 break;
20760 case 403:
20761 transmit_response_with_date(p, "200 OK", req);
20762 ast_log(LOG_WARNING, "Authentication failed while trying to subscribe for MWI.\n");
20763 p->mwi->call = NULL;
20764 ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
20765 pvt_set_needdestroy(p, "received 403 response");
20766 sip_alreadygone(p);
20767 break;
20768 case 404:
20769 ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side said that a mailbox may not have been configured.\n");
20770 p->mwi->call = NULL;
20771 ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
20772 pvt_set_needdestroy(p, "received 404 response");
20773 break;
20774 case 481:
20775 ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side said that our dialog did not exist.\n");
20776 p->mwi->call = NULL;
20777 ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
20778 pvt_set_needdestroy(p, "received 481 response");
20779 break;
20780 case 500:
20781 case 501:
20782 ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side may have suffered a heart attack.\n");
20783 p->mwi->call = NULL;
20784 ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
20785 pvt_set_needdestroy(p, "received 500/501 response");
20786 break;
20787 }
20788 }
20789
20790
20791
20792
20793 static void handle_response_refer(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
20794 {
20795 enum ast_control_transfer message = AST_TRANSFER_FAILED;
20796
20797
20798 if (!p->refer)
20799 return;
20800
20801 switch (resp) {
20802 case 202:
20803
20804
20805 p->refer->status = REFER_ACCEPTED;
20806
20807 ast_debug(3, "Got 202 accepted on transfer\n");
20808
20809 break;
20810
20811 case 401:
20812 case 407:
20813 if (ast_strlen_zero(p->authname)) {
20814 ast_log(LOG_WARNING, "Asked to authenticate REFER to %s but we have no matching peer or realm auth!\n",
20815 ast_sockaddr_stringify(&p->recv));
20816 if (p->owner) {
20817 ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
20818 }
20819 pvt_set_needdestroy(p, "unable to authenticate REFER");
20820 }
20821 if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_REFER, 0)) {
20822 ast_log(LOG_NOTICE, "Failed to authenticate on REFER to '%s'\n", get_header(&p->initreq, "From"));
20823 p->refer->status = REFER_NOAUTH;
20824 if (p->owner) {
20825 ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
20826 }
20827 pvt_set_needdestroy(p, "failed to authenticate REFER");
20828 }
20829 break;
20830
20831 case 405:
20832
20833
20834 ast_log(LOG_NOTICE, "SIP transfer to %s failed, REFER not allowed. \n", p->refer->refer_to);
20835 pvt_set_needdestroy(p, "received 405 response");
20836 p->refer->status = REFER_FAILED;
20837 if (p->owner) {
20838 ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
20839 }
20840 break;
20841
20842 case 481:
20843
20844
20845
20846
20847 ast_log(LOG_WARNING, "Remote host can't match REFER request to call '%s'. Giving up.\n", p->callid);
20848 if (p->owner)
20849 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
20850 pvt_set_needdestroy(p, "received 481 response");
20851 break;
20852
20853 case 500:
20854 case 501:
20855
20856
20857 ast_log(LOG_NOTICE, "SIP transfer to %s failed, call miserably fails. \n", p->refer->refer_to);
20858 pvt_set_needdestroy(p, "received 500/501 response");
20859 p->refer->status = REFER_FAILED;
20860 if (p->owner) {
20861 ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
20862 }
20863 break;
20864 case 603:
20865 ast_log(LOG_NOTICE, "SIP transfer to %s declined, call miserably fails. \n", p->refer->refer_to);
20866 p->refer->status = REFER_FAILED;
20867 pvt_set_needdestroy(p, "received 603 response");
20868 if (p->owner) {
20869 ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
20870 }
20871 break;
20872 default:
20873
20874
20875
20876
20877 if (resp < 299) {
20878 ast_log(LOG_WARNING, "SIP transfer to %s had unxpected 2xx response (%d), confusion is possible. \n", p->refer->refer_to, resp);
20879 } else {
20880 ast_log(LOG_WARNING, "SIP transfer to %s with response (%d). \n", p->refer->refer_to, resp);
20881 }
20882
20883 p->refer->status = REFER_FAILED;
20884 pvt_set_needdestroy(p, "received failure response");
20885 if (p->owner) {
20886 ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
20887 }
20888 break;
20889 }
20890 }
20891
20892
20893 static int handle_response_register(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
20894 {
20895 int expires, expires_ms;
20896 struct sip_registry *r;
20897 r=p->registry;
20898
20899 switch (resp) {
20900 case 401:
20901 if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
20902 ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s@%s' (Tries %d)\n", p->registry->username, p->registry->hostname, p->authtries);
20903 pvt_set_needdestroy(p, "failed to authenticate REGISTER");
20904 }
20905 break;
20906 case 403:
20907 ast_log(LOG_WARNING, "Forbidden - wrong password on authentication for REGISTER for '%s' to '%s'\n", p->registry->username, p->registry->hostname);
20908 AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 403"));
20909 r->regstate = REG_STATE_NOAUTH;
20910 pvt_set_needdestroy(p, "received 403 response");
20911 break;
20912 case 404:
20913 ast_log(LOG_WARNING, "Got 404 Not found on SIP register to service %s@%s, giving up\n", p->registry->username, p->registry->hostname);
20914 pvt_set_needdestroy(p, "received 404 response");
20915 if (r->call)
20916 r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 404");
20917 r->regstate = REG_STATE_REJECTED;
20918 AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 404"));
20919 break;
20920 case 407:
20921 if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
20922 ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s' (tries '%d')\n", get_header(&p->initreq, "From"), p->authtries);
20923 pvt_set_needdestroy(p, "failed to authenticate REGISTER");
20924 }
20925 break;
20926 case 408:
20927
20928 if (r) {
20929 r->regattempts = 0;
20930 } else {
20931 ast_log(LOG_WARNING, "Got a 408 response to our REGISTER on call %s after we had destroyed the registry object\n", p->callid);
20932 }
20933 break;
20934 case 423:
20935 r->expiry = atoi(get_header(req, "Min-Expires"));
20936 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);
20937 AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 423"));
20938 if (r->call) {
20939 r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 423");
20940 pvt_set_needdestroy(p, "received 423 response");
20941 }
20942 if (r->expiry > max_expiry) {
20943 ast_log(LOG_WARNING, "Required expiration time from %s@%s is too high, giving up\n", p->registry->username, p->registry->hostname);
20944 r->expiry = r->configured_expiry;
20945 r->regstate = REG_STATE_REJECTED;
20946 } else {
20947 r->regstate = REG_STATE_UNREGISTERED;
20948 transmit_register(r, SIP_REGISTER, NULL, NULL);
20949 }
20950 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));
20951 break;
20952 case 479:
20953 ast_log(LOG_WARNING, "Got error 479 on register to %s@%s, giving up (check config)\n", p->registry->username, p->registry->hostname);
20954 pvt_set_needdestroy(p, "received 479 response");
20955 if (r->call)
20956 r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 479");
20957 r->regstate = REG_STATE_REJECTED;
20958 AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 479"));
20959 break;
20960 case 200:
20961 if (!r) {
20962 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));
20963 pvt_set_needdestroy(p, "received erroneous 200 response");
20964 return 0;
20965 }
20966
20967 r->regstate = REG_STATE_REGISTERED;
20968 r->regtime = ast_tvnow();
20969 manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelType: SIP\r\nDomain: %s\r\nStatus: %s\r\n", r->hostname, regstate2str(r->regstate));
20970 r->regattempts = 0;
20971 ast_debug(1, "Registration successful\n");
20972 if (r->timeout > -1) {
20973 ast_debug(1, "Cancelling timeout %d\n", r->timeout);
20974 }
20975 AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 200"));
20976 if (r->call)
20977 r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 200");
20978 p->registry = registry_unref(p->registry, "unref registry entry p->registry");
20979
20980 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20981
20982
20983
20984
20985
20986
20987 expires = 0;
20988
20989
20990 if (!ast_strlen_zero(get_header(req, "Contact"))) {
20991 const char *contact = NULL;
20992 const char *tmptmp = NULL;
20993 int start = 0;
20994 for(;;) {
20995 contact = __get_header(req, "Contact", &start);
20996
20997 if(!ast_strlen_zero(contact)) {
20998 if( (tmptmp=strstr(contact, p->our_contact))) {
20999 contact=tmptmp;
21000 break;
21001 }
21002 } else
21003 break;
21004 }
21005 tmptmp = strcasestr(contact, "expires=");
21006 if (tmptmp) {
21007 if (sscanf(tmptmp + 8, "%30d;", &expires) != 1)
21008 expires = 0;
21009 }
21010
21011 }
21012 if (!expires)
21013 expires=atoi(get_header(req, "expires"));
21014 if (!expires)
21015 expires=default_expiry;
21016
21017 expires_ms = expires * 1000;
21018 if (expires <= EXPIRY_GUARD_LIMIT)
21019 expires_ms -= MAX((expires_ms * EXPIRY_GUARD_PCT), EXPIRY_GUARD_MIN);
21020 else
21021 expires_ms -= EXPIRY_GUARD_SECS * 1000;
21022 if (sipdebug)
21023 ast_log(LOG_NOTICE, "Outbound Registration: Expiry for %s is %d sec (Scheduling reregistration in %d s)\n", r->hostname, expires, expires_ms/1000);
21024
21025 r->refresh= (int) expires_ms / 1000;
21026
21027
21028 AST_SCHED_REPLACE_UNREF(r->expire, sched, expires_ms, sip_reregister, r,
21029 registry_unref(_data,"unref in REPLACE del fail"),
21030 registry_unref(r,"unref in REPLACE add fail"),
21031 registry_addref(r,"The Addition side of REPLACE"));
21032 }
21033 return 1;
21034 }
21035
21036
21037 static void handle_response_peerpoke(struct sip_pvt *p, int resp, struct sip_request *req)
21038 {
21039 struct sip_peer *peer = p->relatedpeer ;
21040 int statechanged, is_reachable, was_reachable;
21041 int pingtime = ast_tvdiff_ms(ast_tvnow(), peer->ps);
21042
21043
21044
21045
21046
21047
21048 if (pingtime < 1) {
21049 pingtime = 1;
21050 }
21051
21052 if (!peer->maxms) {
21053 pvt_set_needdestroy(p, "got OPTIONS response but qualify is not enabled");
21054 return;
21055 }
21056
21057
21058
21059
21060
21061 was_reachable = peer->lastms > 0 && peer->lastms <= peer->maxms;
21062 is_reachable = pingtime <= peer->maxms;
21063 statechanged = peer->lastms == 0
21064 || was_reachable != is_reachable;
21065
21066 peer->lastms = pingtime;
21067 peer->call = dialog_unref(peer->call, "unref dialog peer->call");
21068 if (statechanged) {
21069 const char *s = is_reachable ? "Reachable" : "Lagged";
21070 char str_lastms[20];
21071 snprintf(str_lastms, sizeof(str_lastms), "%d", pingtime);
21072
21073 ast_log(LOG_NOTICE, "Peer '%s' is now %s. (%dms / %dms)\n",
21074 peer->name, s, pingtime, peer->maxms);
21075 ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
21076 if (sip_cfg.peer_rtupdate) {
21077 ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", str_lastms, SENTINEL);
21078 }
21079 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
21080 "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: %s\r\nTime: %d\r\n",
21081 peer->name, s, pingtime);
21082 if (is_reachable && sip_cfg.regextenonqualify)
21083 register_peer_exten(peer, TRUE);
21084 }
21085
21086 pvt_set_needdestroy(p, "got OPTIONS response");
21087
21088
21089 AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
21090 is_reachable ? peer->qualifyfreq : DEFAULT_FREQ_NOTOK,
21091 sip_poke_peer_s, peer,
21092 unref_peer(_data, "removing poke peer ref"),
21093 unref_peer(peer, "removing poke peer ref"),
21094 ref_peer(peer, "adding poke peer ref"));
21095 }
21096
21097
21098
21099
21100
21101
21102
21103
21104 static void handle_response_info(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
21105 {
21106 int sipmethod = SIP_INFO;
21107
21108 switch (resp) {
21109 case 401:
21110 case 407:
21111 ast_log(LOG_WARNING, "Host '%s' requests authentication (%d) for '%s'\n",
21112 ast_sockaddr_stringify(&p->sa), resp, sip_methods[sipmethod].text);
21113 break;
21114 case 405:
21115 case 501:
21116 mark_method_unallowed(&p->allowed_methods, sipmethod);
21117 if (p->relatedpeer) {
21118 mark_method_allowed(&p->relatedpeer->disallowed_methods, sipmethod);
21119 }
21120 ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n",
21121 ast_sockaddr_stringify(&p->sa), sip_methods[sipmethod].text);
21122 break;
21123 default:
21124 if (300 <= resp && resp < 700) {
21125 ast_verb(3, "Got SIP %s response %d \"%s\" back from host '%s'\n",
21126 sip_methods[sipmethod].text, resp, rest, ast_sockaddr_stringify(&p->sa));
21127 }
21128 break;
21129 }
21130 }
21131
21132
21133
21134
21135
21136
21137
21138
21139
21140 static void handle_response_message(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
21141 {
21142 int sipmethod = SIP_MESSAGE;
21143
21144
21145
21146 switch (resp) {
21147 case 401:
21148 case 407:
21149 ast_log(LOG_WARNING, "Host '%s' requests authentication (%d) for '%s'\n",
21150 ast_sockaddr_stringify(&p->sa), resp, sip_methods[sipmethod].text);
21151 break;
21152 case 405:
21153 case 501:
21154 mark_method_unallowed(&p->allowed_methods, sipmethod);
21155 if (p->relatedpeer) {
21156 mark_method_allowed(&p->relatedpeer->disallowed_methods, sipmethod);
21157 }
21158 ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n",
21159 ast_sockaddr_stringify(&p->sa), sip_methods[sipmethod].text);
21160 break;
21161 default:
21162 if (100 <= resp && resp < 200) {
21163
21164 } else if (200 <= resp && resp < 300) {
21165 p->authtries = 0;
21166 } else if (300 <= resp && resp < 700) {
21167 ast_verb(3, "Got SIP %s response %d \"%s\" back from host '%s'\n",
21168 sip_methods[sipmethod].text, resp, rest, ast_sockaddr_stringify(&p->sa));
21169 }
21170 break;
21171 }
21172 }
21173
21174
21175 static void stop_media_flows(struct sip_pvt *p)
21176 {
21177
21178 if (p->rtp)
21179 ast_rtp_instance_stop(p->rtp);
21180 if (p->vrtp)
21181 ast_rtp_instance_stop(p->vrtp);
21182 if (p->trtp)
21183 ast_rtp_instance_stop(p->trtp);
21184 if (p->udptl)
21185 ast_udptl_stop(p->udptl);
21186 }
21187
21188
21189
21190 static void handle_response(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
21191 {
21192 struct ast_channel *owner;
21193 int sipmethod;
21194 const char *c = get_header(req, "Cseq");
21195
21196 char *c_copy = ast_strdupa(c);
21197
21198 const char *msg = ast_skip_blanks(ast_skip_nonblanks(c_copy));
21199
21200 if (!msg)
21201 msg = "";
21202
21203 sipmethod = find_sip_method(msg);
21204
21205 owner = p->owner;
21206 if (owner) {
21207 const char *rp = NULL, *rh = NULL;
21208
21209 owner->hangupcause = 0;
21210 if (ast_test_flag(&p->flags[1], SIP_PAGE2_Q850_REASON) && (rh = get_header(req, "Reason"))) {
21211 rh = ast_skip_blanks(rh);
21212 if (!strncasecmp(rh, "Q.850", 5)) {
21213 rp = strstr(rh, "cause=");
21214 if (rp && sscanf(rp + 6, "%30d", &owner->hangupcause) == 1) {
21215 owner->hangupcause &= 0x7f;
21216 if (req->debug)
21217 ast_verbose("Using Reason header for cause code: %d\n", owner->hangupcause);
21218 }
21219 }
21220 }
21221
21222 if (!owner->hangupcause)
21223 owner->hangupcause = hangup_sip2cause(resp);
21224 }
21225
21226 if (p->socket.type == SIP_TRANSPORT_UDP) {
21227 int ack_res = FALSE;
21228
21229
21230 if ((resp >= 100) && (resp <= 199)) {
21231
21232 if (sipmethod == SIP_INVITE) {
21233 ack_res = __sip_semi_ack(p, seqno, 0, sipmethod);
21234 }
21235 } else {
21236 ack_res = __sip_ack(p, seqno, 0, sipmethod);
21237 }
21238
21239 if (ack_res == FALSE) {
21240
21241 if (sipmethod == SIP_INVITE && resp >= 200) {
21242 transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, resp < 300 ? TRUE: FALSE);
21243 }
21244
21245 append_history(p, "Ignore", "Ignoring this retransmit\n");
21246 return;
21247 }
21248 }
21249
21250
21251 if (!p->owner && sipmethod == SIP_NOTIFY && p->pendinginvite) {
21252 p->pendinginvite = 0;
21253 }
21254
21255
21256 if (ast_strlen_zero(p->theirtag) || (resp >= 200)) {
21257 char tag[128];
21258
21259 gettag(req, "To", tag, sizeof(tag));
21260 ast_string_field_set(p, theirtag, tag);
21261 }
21262
21263
21264
21265
21266
21267
21268
21269
21270
21271
21272
21273
21274
21275
21276
21277 if ((resp == 404 || resp == 408 || resp == 481) && sipmethod == SIP_BYE) {
21278 pvt_set_needdestroy(p, "received 4XX response to a BYE");
21279 return;
21280 }
21281
21282 if (p->relatedpeer && sipmethod == SIP_OPTIONS) {
21283
21284
21285
21286 if (resp != 100)
21287 handle_response_peerpoke(p, resp, req);
21288 } else if (sipmethod == SIP_REFER && resp >= 200) {
21289 handle_response_refer(p, resp, rest, req, seqno);
21290 } else if (sipmethod == SIP_PUBLISH) {
21291
21292
21293
21294 handle_response_publish(p, resp, rest, req, seqno);
21295 } else if (sipmethod == SIP_INFO) {
21296
21297 handle_response_info(p, resp, rest, req, seqno);
21298 } else if (sipmethod == SIP_MESSAGE) {
21299
21300 handle_response_message(p, resp, rest, req, seqno);
21301 } else if (sipmethod == SIP_NOTIFY) {
21302
21303 handle_response_notify(p, resp, rest, req, seqno);
21304 } else if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
21305 switch(resp) {
21306 case 100:
21307 case 101:
21308 case 183:
21309 case 180:
21310 case 182:
21311 case 181:
21312 if (sipmethod == SIP_INVITE)
21313 handle_response_invite(p, resp, rest, req, seqno);
21314 break;
21315 case 200:
21316 p->authtries = 0;
21317 if (sipmethod == SIP_INVITE) {
21318 handle_response_invite(p, resp, rest, req, seqno);
21319 } else if (sipmethod == SIP_REGISTER) {
21320 handle_response_register(p, resp, rest, req, seqno);
21321 } else if (sipmethod == SIP_SUBSCRIBE) {
21322 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
21323 handle_response_subscribe(p, resp, rest, req, seqno);
21324 } else if (sipmethod == SIP_BYE) {
21325 pvt_set_needdestroy(p, "received 200 response");
21326 ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
21327 }
21328 break;
21329 case 401:
21330 case 407:
21331 if (sipmethod == SIP_INVITE)
21332 handle_response_invite(p, resp, rest, req, seqno);
21333 else if (sipmethod == SIP_SUBSCRIBE)
21334 handle_response_subscribe(p, resp, rest, req, seqno);
21335 else if (p->registry && sipmethod == SIP_REGISTER)
21336 handle_response_register(p, resp, rest, req, seqno);
21337 else if (sipmethod == SIP_UPDATE) {
21338 handle_response_update(p, resp, rest, req, seqno);
21339 } else if (sipmethod == SIP_BYE) {
21340 if (p->options)
21341 p->options->auth_type = resp;
21342 if (ast_strlen_zero(p->authname)) {
21343 ast_log(LOG_WARNING, "Asked to authenticate %s, to %s but we have no matching peer!\n",
21344 msg, ast_sockaddr_stringify(&p->recv));
21345 pvt_set_needdestroy(p, "unable to authenticate BYE");
21346 } else if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp, sipmethod, 0)) {
21347 ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
21348 pvt_set_needdestroy(p, "failed to authenticate BYE");
21349 }
21350 } else {
21351 ast_log(LOG_WARNING, "Got authentication request (%d) on %s to '%s'\n", resp, sip_methods[sipmethod].text, get_header(req, "To"));
21352 pvt_set_needdestroy(p, "received 407 response");
21353 }
21354 break;
21355 case 403:
21356 if (sipmethod == SIP_INVITE)
21357 handle_response_invite(p, resp, rest, req, seqno);
21358 else if (sipmethod == SIP_SUBSCRIBE)
21359 handle_response_subscribe(p, resp, rest, req, seqno);
21360 else if (p->registry && sipmethod == SIP_REGISTER)
21361 handle_response_register(p, resp, rest, req, seqno);
21362 else {
21363 ast_log(LOG_WARNING, "Forbidden - maybe wrong password on authentication for %s\n", msg);
21364 pvt_set_needdestroy(p, "received 403 response");
21365 }
21366 break;
21367 case 404:
21368 if (p->registry && sipmethod == SIP_REGISTER)
21369 handle_response_register(p, resp, rest, req, seqno);
21370 else if (sipmethod == SIP_INVITE)
21371 handle_response_invite(p, resp, rest, req, seqno);
21372 else if (sipmethod == SIP_SUBSCRIBE)
21373 handle_response_subscribe(p, resp, rest, req, seqno);
21374 else if (owner)
21375 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
21376 break;
21377 case 423:
21378 if (sipmethod == SIP_REGISTER)
21379 handle_response_register(p, resp, rest, req, seqno);
21380 break;
21381 case 408:
21382 if (sipmethod == SIP_INVITE)
21383 handle_response_invite(p, resp, rest, req, seqno);
21384 else if (sipmethod == SIP_REGISTER)
21385 handle_response_register(p, resp, rest, req, seqno);
21386 else if (sipmethod == SIP_BYE) {
21387 pvt_set_needdestroy(p, "received 408 response");
21388 ast_debug(4, "Got timeout on bye. Thanks for the answer. Now, kill this call\n");
21389 } else {
21390 if (owner)
21391 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
21392 pvt_set_needdestroy(p, "received 408 response");
21393 }
21394 break;
21395
21396 case 428:
21397 case 422:
21398 if (sipmethod == SIP_INVITE) {
21399 handle_response_invite(p, resp, rest, req, seqno);
21400 }
21401 break;
21402
21403 case 481:
21404 if (sipmethod == SIP_INVITE) {
21405 handle_response_invite(p, resp, rest, req, seqno);
21406 } else if (sipmethod == SIP_SUBSCRIBE) {
21407 handle_response_subscribe(p, resp, rest, req, seqno);
21408 } else if (sipmethod == SIP_BYE) {
21409
21410
21411 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
21412 } else if (sipmethod == SIP_CANCEL) {
21413
21414
21415 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
21416 } else {
21417 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
21418
21419 }
21420 break;
21421 case 487:
21422 if (sipmethod == SIP_INVITE)
21423 handle_response_invite(p, resp, rest, req, seqno);
21424 break;
21425 case 415:
21426 case 488:
21427 case 606:
21428 if (sipmethod == SIP_INVITE)
21429 handle_response_invite(p, resp, rest, req, seqno);
21430 break;
21431 case 491:
21432 if (sipmethod == SIP_INVITE)
21433 handle_response_invite(p, resp, rest, req, seqno);
21434 else {
21435 ast_debug(1, "Got 491 on %s, unsupported. Call ID %s\n", sip_methods[sipmethod].text, p->callid);
21436 pvt_set_needdestroy(p, "received 491 response");
21437 }
21438 break;
21439 case 405:
21440 case 501:
21441 mark_method_unallowed(&p->allowed_methods, sipmethod);
21442 if (p->relatedpeer) {
21443 mark_method_allowed(&p->relatedpeer->disallowed_methods, sipmethod);
21444 }
21445 if (sipmethod == SIP_INVITE)
21446 handle_response_invite(p, resp, rest, req, seqno);
21447 else
21448 ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n", ast_sockaddr_stringify(&p->sa), msg);
21449 break;
21450 default:
21451 if ((resp >= 300) && (resp < 700)) {
21452
21453 if ((resp != 487))
21454 ast_verb(3, "Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_sockaddr_stringify(&p->sa));
21455
21456 if (sipmethod == SIP_INVITE)
21457 stop_media_flows(p);
21458
21459
21460 switch(resp) {
21461 case 300:
21462 case 301:
21463 case 302:
21464 case 305:
21465 if (p->owner) {
21466 struct ast_party_redirecting redirecting;
21467 struct ast_set_party_redirecting update_redirecting;
21468
21469 ast_party_redirecting_init(&redirecting);
21470 memset(&update_redirecting, 0, sizeof(update_redirecting));
21471 change_redirecting_information(p, req, &redirecting,
21472 &update_redirecting, TRUE);
21473 ast_channel_set_redirecting(p->owner, &redirecting,
21474 &update_redirecting);
21475 ast_party_redirecting_free(&redirecting);
21476 }
21477
21478 case 486:
21479 case 600:
21480 case 603:
21481 if (p->owner) {
21482 sip_handle_cc(p, req, AST_CC_CCBS);
21483 ast_queue_control(p->owner, AST_CONTROL_BUSY);
21484 }
21485 break;
21486 case 482:
21487 case 480:
21488 case 404:
21489 case 410:
21490 case 400:
21491 case 500:
21492 if (sipmethod == SIP_SUBSCRIBE) {
21493 handle_response_subscribe(p, resp, rest, req, seqno);
21494 break;
21495 }
21496
21497 case 502:
21498 case 503:
21499 case 504:
21500 if (owner)
21501 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
21502 break;
21503 case 484:
21504 if (owner && sipmethod != SIP_BYE) {
21505 switch (ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP)) {
21506 case SIP_PAGE2_ALLOWOVERLAP_YES:
21507 ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
21508 break;
21509 default:
21510 ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(404));
21511 break;
21512 }
21513 }
21514 break;
21515 default:
21516
21517 if (owner && sipmethod != SIP_BYE)
21518 ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
21519 break;
21520 }
21521
21522 if (sipmethod == SIP_INVITE)
21523 transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
21524 sip_alreadygone(p);
21525 if (!p->owner) {
21526 pvt_set_needdestroy(p, "transaction completed");
21527 }
21528 } else if ((resp >= 100) && (resp < 200)) {
21529 if (sipmethod == SIP_INVITE) {
21530 if (!req->ignore && sip_cancel_destroy(p))
21531 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
21532 if (find_sdp(req))
21533 process_sdp(p, req, SDP_T38_NONE);
21534 if (p->owner) {
21535
21536 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
21537 }
21538 }
21539 } else
21540 ast_log(LOG_NOTICE, "Don't know how to handle a %d %s response from %s\n", resp, rest, p->owner ? p->owner->name : ast_sockaddr_stringify(&p->sa));
21541 }
21542 } else {
21543
21544
21545 if (req->debug)
21546 ast_verbose("SIP Response message for INCOMING dialog %s arrived\n", msg);
21547
21548 if (sipmethod == SIP_INVITE && resp == 200) {
21549
21550
21551 char tag[128];
21552
21553 gettag(req, "To", tag, sizeof(tag));
21554 ast_string_field_set(p, theirtag, tag);
21555 }
21556
21557 switch(resp) {
21558 case 200:
21559 if (sipmethod == SIP_INVITE) {
21560 handle_response_invite(p, resp, rest, req, seqno);
21561 } else if (sipmethod == SIP_CANCEL) {
21562 ast_debug(1, "Got 200 OK on CANCEL\n");
21563
21564
21565 } else if (sipmethod == SIP_BYE) {
21566 pvt_set_needdestroy(p, "transaction completed");
21567 }
21568 break;
21569 case 401:
21570 case 407:
21571 if (sipmethod == SIP_INVITE)
21572 handle_response_invite(p, resp, rest, req, seqno);
21573 else if (sipmethod == SIP_BYE) {
21574 if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, sipmethod, 0)) {
21575 ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
21576 pvt_set_needdestroy(p, "failed to authenticate BYE");
21577 }
21578 }
21579 break;
21580 case 481:
21581 if (sipmethod == SIP_INVITE) {
21582
21583 handle_response_invite(p, resp, rest, req, seqno);
21584 } else if (sipmethod == SIP_BYE) {
21585 pvt_set_needdestroy(p, "received 481 response");
21586 } else if (sipdebug) {
21587 ast_debug(1, "Remote host can't match request %s to call '%s'. Giving up\n", sip_methods[sipmethod].text, p->callid);
21588 }
21589 break;
21590 case 501:
21591 if (sipmethod == SIP_INVITE)
21592 handle_response_invite(p, resp, rest, req, seqno);
21593 break;
21594 default:
21595 if ((resp >= 100) && (resp < 200)) {
21596 if (sipmethod == SIP_INVITE) {
21597 if (!req->ignore && sip_cancel_destroy(p))
21598 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
21599 }
21600 }
21601 if ((resp >= 300) && (resp < 700)) {
21602 if ((resp != 487))
21603 ast_verb(3, "Incoming call: Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_sockaddr_stringify(&p->sa));
21604 switch(resp) {
21605 case 415:
21606 case 488:
21607 case 603:
21608 case 500:
21609 case 502:
21610 case 503:
21611 case 504:
21612
21613
21614 if (sipmethod == SIP_INVITE && sip_cancel_destroy(p))
21615 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
21616 break;
21617 }
21618 }
21619 break;
21620 }
21621 }
21622 }
21623
21624
21625
21626
21627
21628
21629
21630 static void *sip_park_thread(void *stuff)
21631 {
21632 struct ast_channel *transferee, *transferer;
21633 struct sip_dual *d;
21634 int ext;
21635 int res;
21636
21637 d = stuff;
21638 transferee = d->chan1;
21639 transferer = d->chan2;
21640
21641 ast_debug(4, "SIP Park: Transferer channel %s, Transferee %s\n", transferer->name, transferee->name);
21642
21643 res = ast_park_call_exten(transferee, transferer, d->park_exten, d->park_context, 0, &ext);
21644
21645 #ifdef WHEN_WE_KNOW_THAT_THE_CLIENT_SUPPORTS_MESSAGE
21646 if (res) {
21647 transmit_message_with_text(transferer->tech_pvt, "Unable to park call.\n");
21648 } else {
21649
21650 sprintf(buf, "Call parked on extension '%d'", ext);
21651 transmit_message_with_text(transferer->tech_pvt, buf);
21652 }
21653 #endif
21654
21655
21656
21657 if (!res) {
21658
21659 append_history(transferer->tech_pvt, "SIPpark", "Parked call on %d", ext);
21660 transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "200 OK", TRUE);
21661 transferer->hangupcause = AST_CAUSE_NORMAL_CLEARING;
21662 ast_hangup(transferer);
21663 ast_debug(1, "SIP Call parked on extension '%d'\n", ext);
21664 } else {
21665 transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "503 Service Unavailable", TRUE);
21666 append_history(transferer->tech_pvt, "SIPpark", "Parking failed\n");
21667 ast_debug(1, "SIP Call parked failed \n");
21668
21669 }
21670 deinit_req(&d->req);
21671 ast_free(d->park_exten);
21672 ast_free(d->park_context);
21673 ast_free(d);
21674 return NULL;
21675 }
21676
21677
21678 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)
21679 {
21680 struct sip_dual *d;
21681 struct ast_channel *transferee, *transferer;
21682 pthread_t th;
21683
21684 transferee = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan1->accountcode, chan1->exten, chan1->context, chan1->linkedid, chan1->amaflags, "Parking/%s", chan1->name);
21685 transferer = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan2->accountcode, chan2->exten, chan2->context, chan2->linkedid, chan2->amaflags, "SIPPeer/%s", chan2->name);
21686 d = ast_calloc(1, sizeof(*d));
21687 if (!transferee || !transferer || !d) {
21688 if (transferee) {
21689 ast_hangup(transferee);
21690 }
21691 if (transferer) {
21692 ast_hangup(transferer);
21693 }
21694 ast_free(d);
21695 return -1;
21696 }
21697 d->park_exten = ast_strdup(park_exten);
21698 d->park_context = ast_strdup(park_context);
21699 if (!d->park_exten || !d->park_context) {
21700 ast_hangup(transferee);
21701 ast_hangup(transferer);
21702 ast_free(d->park_exten);
21703 ast_free(d->park_context);
21704 ast_free(d);
21705 return -1;
21706 }
21707
21708
21709 transferee->readformat = chan1->readformat;
21710 transferee->writeformat = chan1->writeformat;
21711
21712
21713 if (ast_channel_masquerade(transferee, chan1)) {
21714 ast_hangup(transferee);
21715 ast_hangup(transferer);
21716 ast_free(d->park_exten);
21717 ast_free(d->park_context);
21718 ast_free(d);
21719 return -1;
21720 }
21721
21722
21723 ast_copy_string(transferee->context, chan1->context, sizeof(transferee->context));
21724 ast_copy_string(transferee->exten, chan1->exten, sizeof(transferee->exten));
21725 transferee->priority = chan1->priority;
21726
21727 ast_do_masquerade(transferee);
21728
21729
21730
21731
21732
21733 transferer->readformat = chan2->readformat;
21734 transferer->writeformat = chan2->writeformat;
21735 ast_string_field_set(transferer, parkinglot, chan2->parkinglot);
21736
21737
21738 if (ast_channel_masquerade(transferer, chan2)) {
21739 ast_hangup(transferer);
21740 ast_free(d->park_exten);
21741 ast_free(d->park_context);
21742 ast_free(d);
21743 return -1;
21744 }
21745
21746
21747 ast_copy_string(transferer->context, chan2->context, sizeof(transferer->context));
21748 ast_copy_string(transferer->exten, chan2->exten, sizeof(transferer->exten));
21749 transferer->priority = chan2->priority;
21750
21751 ast_do_masquerade(transferer);
21752
21753
21754 copy_request(&d->req, req);
21755 d->chan1 = transferee;
21756 d->chan2 = transferer;
21757 d->seqno = seqno;
21758 if (ast_pthread_create_detached_background(&th, NULL, sip_park_thread, d) < 0) {
21759
21760 deinit_req(&d->req);
21761 ast_free(d->park_exten);
21762 ast_free(d->park_context);
21763 ast_free(d);
21764
21765 return -1;
21766 }
21767 return 0;
21768 }
21769
21770
21771
21772
21773
21774 static void *sip_pickup_thread(void *stuff)
21775 {
21776 struct ast_channel *chan;
21777 chan = stuff;
21778
21779 if (ast_pickup_call(chan)) {
21780 chan->hangupcause = AST_CAUSE_CALL_REJECTED;
21781 } else {
21782 chan->hangupcause = AST_CAUSE_NORMAL_CLEARING;
21783 }
21784 ast_hangup(chan);
21785 ast_channel_unref(chan);
21786 chan = NULL;
21787 return NULL;
21788 }
21789
21790
21791
21792
21793 static int sip_pickup(struct ast_channel *chan)
21794 {
21795 pthread_t threadid;
21796
21797 ast_channel_ref(chan);
21798
21799 if (ast_pthread_create_detached_background(&threadid, NULL, sip_pickup_thread, chan)) {
21800 ast_debug(1, "Unable to start Group pickup thread on channel %s\n", chan->name);
21801 ast_channel_unref(chan);
21802 return -1;
21803 }
21804 ast_debug(1, "Started Group pickup thread on channel %s\n", chan->name);
21805 return 0;
21806 }
21807
21808
21809
21810
21811
21812 static void ast_quiet_chan(struct ast_channel *chan)
21813 {
21814 if (chan && chan->_state == AST_STATE_UP) {
21815 if (ast_test_flag(chan, AST_FLAG_MOH))
21816 ast_moh_stop(chan);
21817 else if (chan->generatordata)
21818 ast_deactivate_generator(chan);
21819 }
21820 }
21821
21822
21823
21824 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target)
21825 {
21826 int res = 0;
21827 struct ast_channel *peera = NULL,
21828 *peerb = NULL,
21829 *peerc = NULL,
21830 *peerd = NULL;
21831
21832
21833
21834
21835 ast_debug(4, "Sip transfer:--------------------\n");
21836 if (transferer->chan1)
21837 ast_debug(4, "-- Transferer to PBX channel: %s State %s\n", transferer->chan1->name, ast_state2str(transferer->chan1->_state));
21838 else
21839 ast_debug(4, "-- No transferer first channel - odd??? \n");
21840 if (target->chan1)
21841 ast_debug(4, "-- Transferer to PBX second channel (target): %s State %s\n", target->chan1->name, ast_state2str(target->chan1->_state));
21842 else
21843 ast_debug(4, "-- No target first channel ---\n");
21844 if (transferer->chan2)
21845 ast_debug(4, "-- Bridged call to transferee: %s State %s\n", transferer->chan2->name, ast_state2str(transferer->chan2->_state));
21846 else
21847 ast_debug(4, "-- No bridged call to transferee\n");
21848 if (target->chan2)
21849 ast_debug(4, "-- Bridged call to transfer target: %s State %s\n", target->chan2 ? target->chan2->name : "<none>", target->chan2 ? ast_state2str(target->chan2->_state) : "(none)");
21850 else
21851 ast_debug(4, "-- No target second channel ---\n");
21852 ast_debug(4, "-- END Sip transfer:--------------------\n");
21853 if (transferer->chan2) {
21854 peera = transferer->chan1;
21855 peerb = target->chan1;
21856 peerc = transferer->chan2;
21857 peerd = target->chan2;
21858 ast_debug(3, "SIP transfer: Four channels to handle\n");
21859 } else if (target->chan2) {
21860 peera = target->chan1;
21861 peerb = transferer->chan1;
21862 peerc = target->chan2;
21863 peerd = transferer->chan2;
21864 ast_debug(3, "SIP transfer: Three channels to handle\n");
21865 }
21866
21867 if (peera && peerb && peerc && (peerb != peerc)) {
21868 ast_quiet_chan(peera);
21869 ast_quiet_chan(peerb);
21870 ast_quiet_chan(peerc);
21871 if (peerd)
21872 ast_quiet_chan(peerd);
21873
21874 ast_debug(4, "SIP transfer: trying to masquerade %s into %s\n", peerc->name, peerb->name);
21875 if (ast_channel_masquerade(peerb, peerc)) {
21876 ast_log(LOG_WARNING, "Failed to masquerade %s into %s\n", peerb->name, peerc->name);
21877 res = -1;
21878 } else
21879 ast_debug(4, "SIP transfer: Succeeded to masquerade channels.\n");
21880 return res;
21881 } else {
21882 ast_log(LOG_NOTICE, "SIP Transfer attempted with no appropriate bridged calls to transfer\n");
21883 if (transferer->chan1)
21884 ast_softhangup_nolock(transferer->chan1, AST_SOFTHANGUP_DEV);
21885 if (target->chan1)
21886 ast_softhangup_nolock(target->chan1, AST_SOFTHANGUP_DEV);
21887 return -1;
21888 }
21889 return 0;
21890 }
21891
21892
21893
21894
21895
21896
21897 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize)
21898 {
21899 const char *thetag;
21900
21901 if (!tagbuf)
21902 return NULL;
21903 tagbuf[0] = '\0';
21904 thetag = get_header(req, header);
21905 thetag = strcasestr(thetag, ";tag=");
21906 if (thetag) {
21907 thetag += 5;
21908 ast_copy_string(tagbuf, thetag, tagbufsize);
21909 return strsep(&tagbuf, ";");
21910 }
21911 return NULL;
21912 }
21913
21914 static int handle_cc_notify(struct sip_pvt *pvt, struct sip_request *req)
21915 {
21916 struct sip_monitor_instance *monitor_instance = ao2_callback(sip_monitor_instances, 0,
21917 find_sip_monitor_instance_by_subscription_pvt, pvt);
21918 const char *status = get_body(req, "cc-state", ':');
21919 struct cc_epa_entry *cc_entry;
21920 char *uri;
21921
21922 if (!monitor_instance) {
21923 transmit_response(pvt, "400 Bad Request", req);
21924 return -1;
21925 }
21926
21927 if (ast_strlen_zero(status)) {
21928 ao2_ref(monitor_instance, -1);
21929 transmit_response(pvt, "400 Bad Request", req);
21930 return -1;
21931 }
21932
21933 if (!strcmp(status, "queued")) {
21934
21935
21936
21937
21938 ast_cc_monitor_request_acked(monitor_instance->core_id, "SIP endpoint %s accepted request", monitor_instance->device_name);
21939 transmit_response(pvt, "200 OK", req);
21940 ao2_ref(monitor_instance, -1);
21941 return 0;
21942 }
21943
21944
21945 uri = get_body(req, "cc-URI", ':');
21946 if (ast_strlen_zero(uri)) {
21947 uri = get_in_brackets((char *)get_header(req, "From"));
21948 }
21949
21950 ast_string_field_set(monitor_instance, notify_uri, uri);
21951 if (monitor_instance->suspension_entry) {
21952 cc_entry = monitor_instance->suspension_entry->instance_data;
21953 if (cc_entry->current_state == CC_CLOSED) {
21954
21955
21956
21957
21958
21959 construct_pidf_body(CC_CLOSED, monitor_instance->suspension_entry->body,
21960 sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
21961 transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_INITIAL, monitor_instance->notify_uri);
21962 } else {
21963 ast_cc_monitor_callee_available(monitor_instance->core_id, "SIP monitored callee has become available");
21964 }
21965 } else {
21966 ast_cc_monitor_callee_available(monitor_instance->core_id, "SIP monitored callee has become available");
21967 }
21968 ao2_ref(monitor_instance, -1);
21969 transmit_response(pvt, "200 OK", req);
21970
21971 return 0;
21972 }
21973
21974
21975 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e)
21976 {
21977
21978
21979 int res = 0;
21980 const char *event = get_header(req, "Event");
21981 char *sep;
21982
21983 if( (sep = strchr(event, ';')) ) {
21984 *sep++ = '\0';
21985 }
21986
21987 if (sipdebug)
21988 ast_debug(2, "Got NOTIFY Event: %s\n", event);
21989
21990 if (!strcmp(event, "refer")) {
21991
21992
21993
21994
21995
21996 char buf[1024];
21997 char *cmd, *code;
21998 int respcode;
21999 int success = TRUE;
22000
22001
22002
22003
22004
22005
22006
22007
22008 if (strncasecmp(get_header(req, "Content-Type"), "message/sipfrag", strlen("message/sipfrag"))) {
22009
22010 transmit_response(p, "400 Bad request", req);
22011 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22012 return -1;
22013 }
22014
22015
22016 if (get_msg_text(buf, sizeof(buf), req)) {
22017 ast_log(LOG_WARNING, "Unable to retrieve attachment from NOTIFY %s\n", p->callid);
22018 transmit_response(p, "400 Bad request", req);
22019 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22020 return -1;
22021 }
22022
22023
22024
22025
22026
22027
22028
22029
22030
22031
22032
22033
22034
22035
22036
22037
22038
22039
22040
22041
22042
22043 ast_debug(3, "* SIP Transfer NOTIFY Attachment: \n---%s\n---\n", buf);
22044 cmd = ast_skip_blanks(buf);
22045 code = cmd;
22046
22047 while(*code && (*code > 32)) {
22048 code++;
22049 }
22050 *code++ = '\0';
22051 code = ast_skip_blanks(code);
22052 sep = code;
22053 sep++;
22054 while(*sep && (*sep > 32)) {
22055 sep++;
22056 }
22057 *sep++ = '\0';
22058 respcode = atoi(code);
22059 switch (respcode) {
22060 case 200:
22061
22062 break;
22063 case 301:
22064 case 302:
22065
22066 success = FALSE;
22067 break;
22068 case 503:
22069 case 603:
22070
22071 success = FALSE;
22072 break;
22073 case 0:
22074
22075 ast_log(LOG_NOTICE, "Error parsing sipfrag in NOTIFY in response to REFER.\n");
22076 success = FALSE;
22077 break;
22078 default:
22079 if (respcode < 200) {
22080
22081 success = -1;
22082 } else {
22083 ast_log(LOG_NOTICE, "Got unknown code '%d' in NOTIFY in response to REFER.\n", respcode);
22084 success = FALSE;
22085 }
22086 break;
22087 }
22088 if (success == FALSE) {
22089 ast_log(LOG_NOTICE, "Transfer failed. Sorry. Nothing further to do with this call\n");
22090 }
22091
22092 if (p->owner && success != -1) {
22093 enum ast_control_transfer message = success ? AST_TRANSFER_SUCCESS : AST_TRANSFER_FAILED;
22094 ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
22095 }
22096
22097 transmit_response(p, "200 OK", req);
22098 } else if (!strcmp(event, "message-summary")) {
22099 const char *mailbox = NULL;
22100 char *c = ast_strdupa(get_body(req, "Voice-Message", ':'));
22101
22102 if (!p->mwi) {
22103 struct sip_peer *peer = find_peer(NULL, &p->recv, TRUE, FINDPEERS, FALSE, p->socket.type);
22104
22105 if (peer) {
22106 mailbox = ast_strdupa(peer->unsolicited_mailbox);
22107 unref_peer(peer, "removing unsolicited mwi ref");
22108 }
22109 } else {
22110 mailbox = p->mwi->mailbox;
22111 }
22112
22113 if (!ast_strlen_zero(mailbox) && !ast_strlen_zero(c)) {
22114 char *old = strsep(&c, " ");
22115 char *new = strsep(&old, "/");
22116 struct ast_event *event;
22117
22118 if ((event = ast_event_new(AST_EVENT_MWI,
22119 AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox,
22120 AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, "SIP_Remote",
22121 AST_EVENT_IE_NEWMSGS, AST_EVENT_IE_PLTYPE_UINT, atoi(new),
22122 AST_EVENT_IE_OLDMSGS, AST_EVENT_IE_PLTYPE_UINT, atoi(old),
22123 AST_EVENT_IE_END))) {
22124 ast_event_queue_and_cache(event);
22125 }
22126 transmit_response(p, "200 OK", req);
22127 } else {
22128 transmit_response(p, "489 Bad event", req);
22129 res = -1;
22130 }
22131 } else if (!strcmp(event, "keep-alive")) {
22132
22133
22134 transmit_response(p, "200 OK", req);
22135 } else if (!strcmp(event, "call-completion")) {
22136 res = handle_cc_notify(p, req);
22137 } else {
22138
22139 transmit_response(p, "489 Bad event", req);
22140 res = -1;
22141 }
22142
22143 if (!p->lastinvite)
22144 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22145
22146 return res;
22147 }
22148
22149
22150
22151
22152 static int handle_request_options(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e)
22153 {
22154 const char *msg;
22155 enum sip_get_dest_result gotdest;
22156 int res;
22157
22158 if (p->lastinvite) {
22159
22160 transmit_response_with_allow(p, "200 OK", req, 0);
22161 return 0;
22162 }
22163
22164 if (sip_cfg.auth_options_requests) {
22165
22166 copy_request(&p->initreq, req);
22167 set_pvt_allowed_methods(p, req);
22168 res = check_user(p, req, SIP_OPTIONS, e, XMIT_UNRELIABLE, addr);
22169 if (res == AUTH_CHALLENGE_SENT) {
22170 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22171 return 0;
22172 }
22173 if (res < 0) {
22174 if (res == AUTH_FAKE_AUTH) {
22175 ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", get_header(req, "From"));
22176 transmit_fake_auth_response(p, SIP_OPTIONS, req, XMIT_UNRELIABLE);
22177 } else {
22178 ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", get_header(req, "From"));
22179 transmit_response(p, "403 Forbidden", req);
22180 }
22181 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22182 return 0;
22183 }
22184 }
22185
22186
22187 gotdest = get_destination(p, req, NULL);
22188 build_contact(p);
22189
22190 if (ast_strlen_zero(p->context))
22191 ast_string_field_set(p, context, sip_cfg.default_context);
22192
22193 if (ast_shutting_down()) {
22194 msg = "503 Unavailable";
22195 } else {
22196 msg = "404 Not Found";
22197 switch (gotdest) {
22198 case SIP_GET_DEST_INVALID_URI:
22199 msg = "416 Unsupported URI scheme";
22200 break;
22201 case SIP_GET_DEST_EXTEN_MATCHMORE:
22202 case SIP_GET_DEST_REFUSED:
22203 case SIP_GET_DEST_EXTEN_NOT_FOUND:
22204
22205 break;
22206 case SIP_GET_DEST_EXTEN_FOUND:
22207 msg = "200 OK";
22208 break;
22209 }
22210 }
22211 transmit_response_with_allow(p, msg, req, 0);
22212
22213
22214
22215 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22216
22217 return 0;
22218 }
22219
22220
22221
22222
22223
22224
22225
22226
22227
22228
22229
22230
22231
22232 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, uint32_t seqno, struct ast_sockaddr *addr, int *nounlock)
22233 {
22234 int earlyreplace = 0;
22235 int oneleggedreplace = 0;
22236 struct ast_channel *c = p->owner;
22237 struct ast_channel *replacecall = p->refer->refer_call->owner;
22238 struct ast_channel *targetcall;
22239
22240
22241 if (replacecall->_state == AST_STATE_RING)
22242 earlyreplace = 1;
22243
22244
22245 if (!(targetcall = ast_bridged_channel(replacecall))) {
22246
22247 if (!earlyreplace) {
22248 ast_debug(2, " Attended transfer attempted to replace call with no bridge (maybe ringing). Channel %s!\n", replacecall->name);
22249 oneleggedreplace = 1;
22250 }
22251 }
22252 if (targetcall && targetcall->_state == AST_STATE_RINGING)
22253 ast_debug(4, "SIP transfer: Target channel is in ringing state\n");
22254
22255 if (targetcall)
22256 ast_debug(4, "SIP transfer: Invite Replace incoming channel should bridge to channel %s while hanging up channel %s\n", targetcall->name, replacecall->name);
22257 else
22258 ast_debug(4, "SIP transfer: Invite Replace incoming channel should replace and hang up channel %s (one call leg)\n", replacecall->name);
22259
22260 if (req->ignore) {
22261 ast_log(LOG_NOTICE, "Ignoring this INVITE with replaces in a stupid way.\n");
22262
22263
22264
22265 transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE, FALSE);
22266
22267 if (c) {
22268 *nounlock = 1;
22269 ast_channel_unlock(c);
22270 }
22271 ast_channel_unlock(replacecall);
22272 sip_pvt_unlock(p->refer->refer_call);
22273 return 1;
22274 }
22275 if (!c) {
22276
22277 ast_log(LOG_ERROR, "Unable to create new channel. Invite/replace failed.\n");
22278 transmit_response_reliable(p, "503 Service Unavailable", req);
22279 append_history(p, "Xfer", "INVITE/Replace Failed. No new channel.");
22280 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22281 ast_channel_unlock(replacecall);
22282 sip_pvt_unlock(p->refer->refer_call);
22283 return 1;
22284 }
22285 append_history(p, "Xfer", "INVITE/Replace received");
22286
22287
22288
22289
22290
22291
22292
22293
22294
22295
22296
22297 transmit_response(p, "100 Trying", req);
22298 ast_setstate(c, AST_STATE_RING);
22299
22300
22301
22302
22303
22304 transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE, FALSE);
22305
22306 ast_setstate(c, AST_STATE_UP);
22307
22308
22309 ast_quiet_chan(replacecall);
22310 ast_quiet_chan(targetcall);
22311 ast_debug(4, "Invite/Replaces: preparing to masquerade %s into %s\n", c->name, replacecall->name);
22312
22313
22314 if (! earlyreplace && ! oneleggedreplace )
22315 ast_set_flag(&p->refer->refer_call->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
22316
22317
22318 if(ast_channel_masquerade(replacecall, c))
22319 ast_log(LOG_ERROR, "Failed to masquerade C into Replacecall\n");
22320 else
22321 ast_debug(4, "Invite/Replaces: Going to masquerade %s into %s\n", c->name, replacecall->name);
22322
22323
22324
22325
22326
22327 ast_channel_ref(c);
22328 ast_channel_unlock(replacecall);
22329 ast_channel_unlock(c);
22330 sip_pvt_unlock(p->refer->refer_call);
22331 sip_pvt_unlock(p);
22332 if (ast_do_masquerade(replacecall)) {
22333 ast_log(LOG_WARNING, "Failed to perform masquerade with INVITE replaces\n");
22334 }
22335 ast_channel_lock(c);
22336 if (earlyreplace || oneleggedreplace ) {
22337 c->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
22338 }
22339 ast_setstate(c, AST_STATE_DOWN);
22340 ast_channel_unlock(c);
22341
22342
22343 c->tech_pvt = dialog_unref(c->tech_pvt, "unref dialog c->tech_pvt");
22344
22345
22346 ast_hangup(c);
22347
22348 *nounlock = 1;
22349
22350 sip_pvt_lock(p);
22351 ast_channel_unref(c);
22352 return 0;
22353 }
22354
22355
22356 static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context)
22357 {
22358 struct ast_str *str = ast_str_alloca(AST_MAX_EXTENSION + AST_MAX_CONTEXT + 2);
22359 struct ast_app *pickup = pbx_findapp("Pickup");
22360
22361 if (!pickup) {
22362 ast_log(LOG_ERROR, "Unable to perform pickup: Application 'Pickup' not loaded (app_directed_pickup.so).\n");
22363 return -1;
22364 }
22365
22366 ast_str_set(&str, 0, "%s@%s", extension, sip_cfg.notifycid == IGNORE_CONTEXT ? "PICKUPMARK" : context);
22367
22368 ast_debug(2, "About to call Pickup(%s)\n", str->str);
22369
22370
22371
22372
22373 pbx_exec(channel, pickup, str->str);
22374
22375 return 0;
22376 }
22377
22378
22379 static int sip_t38_abort(const void *data)
22380 {
22381 struct sip_pvt *p = (struct sip_pvt *) data;
22382
22383 sip_pvt_lock(p);
22384
22385
22386
22387
22388
22389 if (p->t38id != -1) {
22390 change_t38_state(p, T38_DISABLED);
22391 transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
22392 p->t38id = -1;
22393 dialog_unref(p, "unref the dialog ptr from sip_t38_abort, because it held a dialog ptr");
22394 }
22395 sip_pvt_unlock(p);
22396 return 0;
22397 }
22398
22399
22400
22401
22402
22403
22404
22405
22406
22407
22408
22409
22410 static int handle_request_update(struct sip_pvt *p, struct sip_request *req)
22411 {
22412 if (ast_strlen_zero(get_header(req, "X-Asterisk-rpid-update"))) {
22413 transmit_response(p, "501 Method Not Implemented", req);
22414 return 0;
22415 }
22416 if (!p->owner) {
22417 transmit_response(p, "481 Call/Transaction Does Not Exist", req);
22418 return 0;
22419 }
22420 if (get_rpid(p, req)) {
22421 struct ast_party_connected_line connected;
22422 struct ast_set_party_connected_line update_connected;
22423
22424 ast_party_connected_line_init(&connected);
22425 memset(&update_connected, 0, sizeof(update_connected));
22426
22427 update_connected.id.number = 1;
22428 connected.id.number.valid = 1;
22429 connected.id.number.str = (char *) p->cid_num;
22430 connected.id.number.presentation = p->callingpres;
22431
22432 update_connected.id.name = 1;
22433 connected.id.name.valid = 1;
22434 connected.id.name.str = (char *) p->cid_name;
22435 connected.id.name.presentation = p->callingpres;
22436
22437 connected.id.tag = (char *) p->cid_tag;
22438 connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
22439 ast_channel_queue_connected_line_update(p->owner, &connected, &update_connected);
22440 }
22441 transmit_response(p, "200 OK", req);
22442 return 0;
22443 }
22444
22445
22446
22447
22448
22449
22450
22451
22452 static int handle_request_invite(struct sip_pvt *p, struct sip_request *req, int debug, uint32_t seqno, struct ast_sockaddr *addr, int *recount, const char *e, int *nounlock)
22453 {
22454 int res = 1;
22455 int gotdest;
22456 const char *p_replaces;
22457 char *replace_id = NULL;
22458 int refer_locked = 0;
22459 const char *required;
22460 unsigned int required_profile = 0;
22461 struct ast_channel *c = NULL;
22462 struct sip_peer *authpeer = NULL;
22463 int reinvite = 0;
22464 int rtn;
22465 struct ast_party_redirecting redirecting;
22466 struct ast_set_party_redirecting update_redirecting;
22467
22468 const char *p_uac_se_hdr;
22469 const char *p_uac_min_se;
22470 int uac_max_se = -1;
22471 int uac_min_se = -1;
22472 int st_active = FALSE;
22473 int st_interval = 0;
22474 enum st_refresher tmp_st_ref = SESSION_TIMER_REFRESHER_AUTO;
22475 int dlg_min_se = -1;
22476 struct {
22477 char exten[AST_MAX_EXTENSION];
22478 char context[AST_MAX_CONTEXT];
22479 } pickup = {
22480 .exten = "",
22481 };
22482
22483
22484 if (!p->sipoptions) {
22485 const char *supported = get_header(req, "Supported");
22486 if (!ast_strlen_zero(supported)) {
22487 p->sipoptions = parse_sip_options(supported, NULL, 0);
22488 }
22489 }
22490
22491
22492 required = get_header(req, "Require");
22493 if (!ast_strlen_zero(required)) {
22494 char unsupported[256] = { 0, };
22495 required_profile = parse_sip_options(required, unsupported, ARRAY_LEN(unsupported));
22496
22497
22498
22499 if (!ast_strlen_zero(unsupported)) {
22500 transmit_response_with_unsupported(p, "420 Bad extension (unsupported)", req, unsupported);
22501 ast_log(LOG_WARNING, "Received SIP INVITE with unsupported required extension: required:%s unsupported:%s\n", required, unsupported);
22502 p->invitestate = INV_COMPLETED;
22503 if (!p->lastinvite)
22504 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22505 res = -1;
22506 goto request_invite_cleanup;
22507 }
22508 }
22509
22510
22511
22512 p->sipoptions |= required_profile;
22513 p->reqsipoptions = required_profile;
22514
22515
22516 if (ast_test_flag(&p->flags[0], SIP_OUTGOING) && p->owner && (p->invitestate != INV_TERMINATED && p->invitestate != INV_CONFIRMED) && p->owner->_state != AST_STATE_UP) {
22517
22518
22519
22520
22521
22522 int different;
22523 const char *initial_rlPart2 = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
22524 const char *this_rlPart2 = REQ_OFFSET_TO_STR(req, rlPart2);
22525 if (sip_cfg.pedanticsipchecking)
22526 different = sip_uri_cmp(initial_rlPart2, this_rlPart2);
22527 else
22528 different = strcmp(initial_rlPart2, this_rlPart2);
22529 if (!different) {
22530 transmit_response(p, "482 Loop Detected", req);
22531 p->invitestate = INV_COMPLETED;
22532 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22533 res = 0;
22534 goto request_invite_cleanup;
22535 } else {
22536
22537
22538
22539
22540
22541
22542
22543 char *uri = ast_strdupa(this_rlPart2);
22544 char *at = strchr(uri, '@');
22545 char *peerorhost;
22546 ast_debug(2, "Potential spiral detected. Original RURI was %s, new RURI is %s\n", initial_rlPart2, this_rlPart2);
22547 transmit_response(p, "100 Trying", req);
22548 if (at) {
22549 *at = '\0';
22550 }
22551
22552 if ((peerorhost = strchr(uri, ':'))) {
22553 *peerorhost++ = '\0';
22554 }
22555 ast_string_field_set(p, theirtag, NULL);
22556
22557
22558 ast_string_field_set(p->owner, call_forward, peerorhost);
22559 ast_queue_control(p->owner, AST_CONTROL_BUSY);
22560 res = 0;
22561 goto request_invite_cleanup;
22562 }
22563 }
22564
22565 if (!req->ignore && p->pendinginvite) {
22566 if (!ast_test_flag(&p->flags[0], SIP_OUTGOING) && (p->invitestate == INV_COMPLETED || p->invitestate == INV_TERMINATED)) {
22567
22568
22569
22570
22571
22572
22573
22574
22575
22576
22577 __sip_ack(p, p->pendinginvite, 1, 0);
22578 } else {
22579
22580 p->glareinvite = seqno;
22581 if (p->rtp && find_sdp(req)) {
22582 struct ast_sockaddr addr;
22583 if (get_ip_and_port_from_sdp(req, SDP_AUDIO, &addr)) {
22584 ast_log(LOG_WARNING, "Failed to set an alternate media source on glared reinvite. Audio may not work properly on this call.\n");
22585 } else {
22586 ast_rtp_instance_set_alt_remote_address(p->rtp, &addr);
22587 }
22588 if (p->vrtp) {
22589 if (get_ip_and_port_from_sdp(req, SDP_VIDEO, &addr)) {
22590 ast_log(LOG_WARNING, "Failed to set an alternate media source on glared reinvite. Video may not work properly on this call.\n");
22591 } else {
22592 ast_rtp_instance_set_alt_remote_address(p->vrtp, &addr);
22593 }
22594 }
22595 }
22596 transmit_response_reliable(p, "491 Request Pending", req);
22597 check_via(p, req);
22598 ast_debug(1, "Got INVITE on call where we already have pending INVITE, deferring that - %s\n", p->callid);
22599
22600 res = 0;
22601 goto request_invite_cleanup;
22602 }
22603 }
22604
22605 p_replaces = get_header(req, "Replaces");
22606 if (!ast_strlen_zero(p_replaces)) {
22607
22608 char *ptr;
22609 char *fromtag = NULL;
22610 char *totag = NULL;
22611 char *start, *to;
22612 int error = 0;
22613
22614 if (p->owner) {
22615 ast_debug(3, "INVITE w Replaces on existing call? Refusing action. [%s]\n", p->callid);
22616 transmit_response_reliable(p, "400 Bad request", req);
22617 check_via(p, req);
22618 copy_request(&p->initreq, req);
22619
22620 res = -1;
22621 goto request_invite_cleanup;
22622 }
22623
22624 if (sipdebug)
22625 ast_debug(3, "INVITE part of call transfer. Replaces [%s]\n", p_replaces);
22626
22627 replace_id = ast_strdupa(p_replaces);
22628 ast_uri_decode(replace_id);
22629
22630 if (!p->refer && !sip_refer_allocate(p)) {
22631 transmit_response_reliable(p, "500 Server Internal Error", req);
22632 append_history(p, "Xfer", "INVITE/Replace Failed. Out of memory.");
22633 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22634 p->invitestate = INV_COMPLETED;
22635 check_via(p, req);
22636 copy_request(&p->initreq, req);
22637 res = -1;
22638 goto request_invite_cleanup;
22639 }
22640
22641
22642
22643
22644
22645
22646
22647
22648
22649
22650 replace_id = ast_skip_blanks(replace_id);
22651
22652 start = replace_id;
22653 while ( (ptr = strsep(&start, ";")) ) {
22654 ptr = ast_skip_blanks(ptr);
22655 if ( (to = strcasestr(ptr, "to-tag=") ) )
22656 totag = to + 7;
22657 else if ( (to = strcasestr(ptr, "from-tag=") ) ) {
22658 fromtag = to + 9;
22659 fromtag = strsep(&fromtag, "&");
22660 }
22661 }
22662
22663 if (sipdebug)
22664 ast_debug(4, "Invite/replaces: Will use Replace-Call-ID : %s Fromtag: %s Totag: %s\n",
22665 replace_id,
22666 fromtag ? fromtag : "<no from tag>",
22667 totag ? totag : "<no to tag>");
22668
22669
22670
22671
22672
22673 if (strncmp(replace_id, "pickup-", 7) == 0) {
22674 struct sip_pvt *subscription = NULL;
22675 replace_id += 7;
22676
22677 if ((subscription = get_sip_pvt_byid_locked(replace_id, totag, fromtag)) == NULL) {
22678 ast_log(LOG_NOTICE, "Unable to find subscription with call-id: %s\n", replace_id);
22679 transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
22680 error = 1;
22681 } else {
22682 ast_log(LOG_NOTICE, "Trying to pick up %s@%s\n", subscription->exten, subscription->context);
22683 ast_copy_string(pickup.exten, subscription->exten, sizeof(pickup.exten));
22684 ast_copy_string(pickup.context, subscription->context, sizeof(pickup.context));
22685 sip_pvt_unlock(subscription);
22686 if (subscription->owner) {
22687 ast_channel_unlock(subscription->owner);
22688 }
22689 subscription = dialog_unref(subscription, "unref dialog subscription");
22690 }
22691 }
22692
22693
22694 if (!error && ast_strlen_zero(pickup.exten) && (p->refer->refer_call = get_sip_pvt_byid_locked(replace_id, totag, fromtag)) == NULL) {
22695 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existent call id (%s)!\n", replace_id);
22696 transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
22697 error = 1;
22698 } else {
22699 refer_locked = 1;
22700 }
22701
22702
22703
22704
22705
22706 if (p->refer->refer_call == p) {
22707 ast_log(LOG_NOTICE, "INVITE with replaces into it's own call id (%s == %s)!\n", replace_id, p->callid);
22708 transmit_response_reliable(p, "400 Bad request", req);
22709 error = 1;
22710 }
22711
22712 if (!error && ast_strlen_zero(pickup.exten) && !p->refer->refer_call->owner) {
22713
22714 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existing call id (%s)!\n", replace_id);
22715
22716 transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replace)", req);
22717 error = 1;
22718 }
22719
22720 if (!error && ast_strlen_zero(pickup.exten) && p->refer->refer_call->owner->_state != AST_STATE_RINGING && p->refer->refer_call->owner->_state != AST_STATE_RING && p->refer->refer_call->owner->_state != AST_STATE_UP) {
22721 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-ringing or active call id (%s)!\n", replace_id);
22722 transmit_response_reliable(p, "603 Declined (Replaces)", req);
22723 error = 1;
22724 }
22725
22726 if (error) {
22727 append_history(p, "Xfer", "INVITE/Replace Failed.");
22728 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22729 sip_pvt_unlock(p);
22730 if (p->refer->refer_call) {
22731 sip_pvt_unlock(p->refer->refer_call);
22732 if (p->refer->refer_call->owner) {
22733 ast_channel_unlock(p->refer->refer_call->owner);
22734 }
22735 p->refer->refer_call = dialog_unref(p->refer->refer_call, "unref dialog p->refer->refer_call");
22736 }
22737 refer_locked = 0;
22738 p->invitestate = INV_COMPLETED;
22739 check_via(p, req);
22740 copy_request(&p->initreq, req);
22741 res = -1;
22742 goto request_invite_cleanup;
22743 }
22744 }
22745
22746
22747
22748
22749 if (!req->ignore) {
22750 int newcall = (p->initreq.headers ? TRUE : FALSE);
22751
22752 if (sip_cancel_destroy(p))
22753 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
22754
22755 p->pendinginvite = seqno;
22756 check_via(p, req);
22757
22758 copy_request(&p->initreq, req);
22759 if (sipdebug)
22760 ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
22761 if (!p->owner) {
22762 if (debug)
22763 ast_verbose("Using INVITE request as basis request - %s\n", p->callid);
22764 if (newcall)
22765 append_history(p, "Invite", "New call: %s", p->callid);
22766 parse_ok_contact(p, req);
22767 } else {
22768 ast_clear_flag(&p->flags[0], SIP_OUTGOING);
22769 if (get_rpid(p, req)) {
22770 struct ast_party_connected_line connected;
22771 struct ast_set_party_connected_line update_connected;
22772
22773 ast_party_connected_line_init(&connected);
22774 memset(&update_connected, 0, sizeof(update_connected));
22775
22776 update_connected.id.number = 1;
22777 connected.id.number.valid = 1;
22778 connected.id.number.str = (char *) p->cid_num;
22779 connected.id.number.presentation = p->callingpres;
22780
22781 update_connected.id.name = 1;
22782 connected.id.name.valid = 1;
22783 connected.id.name.str = (char *) p->cid_name;
22784 connected.id.name.presentation = p->callingpres;
22785
22786 connected.id.tag = (char *) p->cid_tag;
22787 connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
22788 ast_channel_queue_connected_line_update(p->owner, &connected,
22789 &update_connected);
22790 }
22791
22792 if (find_sdp(req)) {
22793 if (process_sdp(p, req, SDP_T38_INITIATE)) {
22794 if (!ast_strlen_zero(get_header(req, "Content-Encoding"))) {
22795
22796
22797
22798 transmit_response_reliable(p, "415 Unsupported Media type", req);
22799 } else {
22800 transmit_response_reliable(p, "488 Not acceptable here", req);
22801 }
22802 if (!p->lastinvite)
22803 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22804 res = -1;
22805 goto request_invite_cleanup;
22806 }
22807 ast_queue_control(p->owner, AST_CONTROL_SRCUPDATE);
22808 } else {
22809 p->jointcapability = p->capability;
22810 ast_debug(1, "Hm.... No sdp for the moment\n");
22811
22812
22813
22814 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
22815 ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
22816
22817 ast_queue_frame(p->owner, &ast_null_frame);
22818 change_hold_state(p, req, FALSE, 0);
22819 }
22820 }
22821 if (p->do_history)
22822 append_history(p, "ReInv", "Re-invite received");
22823 }
22824 } else if (debug)
22825 ast_verbose("Ignoring this INVITE request\n");
22826
22827 if (!p->lastinvite && !req->ignore && !p->owner) {
22828
22829
22830 int cc_recall_core_id = -1;
22831 set_pvt_allowed_methods(p, req);
22832 res = check_user_full(p, req, SIP_INVITE, e, XMIT_RELIABLE, addr, &authpeer);
22833 if (res == AUTH_CHALLENGE_SENT) {
22834 p->invitestate = INV_COMPLETED;
22835 res = 0;
22836 goto request_invite_cleanup;
22837 }
22838 if (res < 0) {
22839 if (res == AUTH_FAKE_AUTH) {
22840 ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", get_header(req, "From"));
22841 transmit_fake_auth_response(p, SIP_INVITE, req, XMIT_RELIABLE);
22842 } else {
22843 ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", get_header(req, "From"));
22844 transmit_response_reliable(p, "403 Forbidden", req);
22845 }
22846 p->invitestate = INV_COMPLETED;
22847 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22848 res = 0;
22849 goto request_invite_cleanup;
22850 }
22851
22852
22853 if (p->relatedpeer) {
22854 p->relatedpeer = unref_peer(p->relatedpeer,"unsetting the relatedpeer field in the dialog, before it is set to something else.");
22855 }
22856 if (authpeer) {
22857 p->relatedpeer = ref_peer(authpeer, "setting dialog's relatedpeer pointer");
22858 }
22859
22860 req->authenticated = 1;
22861
22862
22863 if (find_sdp(req)) {
22864 if (process_sdp(p, req, SDP_T38_INITIATE)) {
22865
22866
22867
22868 if (!ast_strlen_zero(get_header(req, "Content-Encoding"))) {
22869 transmit_response_reliable(p, "415 Unsupported Media type", req);
22870 } else {
22871
22872 transmit_response_reliable(p, "488 Not acceptable here", req);
22873 }
22874 p->invitestate = INV_COMPLETED;
22875 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22876 ast_debug(1, "No compatible codecs for this SIP call.\n");
22877 res = -1;
22878 goto request_invite_cleanup;
22879 }
22880 } else {
22881 p->jointcapability = p->capability;
22882 ast_debug(2, "No SDP in Invite, third party call control\n");
22883 }
22884
22885
22886
22887 if (p->owner)
22888 ast_queue_frame(p->owner, &ast_null_frame);
22889
22890
22891
22892 if (ast_strlen_zero(p->context))
22893 ast_string_field_set(p, context, sip_cfg.default_context);
22894
22895
22896
22897 ast_debug(1, "Checking SIP call limits for device %s\n", p->username);
22898 if ((res = update_call_counter(p, INC_CALL_LIMIT))) {
22899 if (res < 0) {
22900 ast_log(LOG_NOTICE, "Failed to place call for device %s, too many calls\n", p->username);
22901 transmit_response_reliable(p, "480 Temporarily Unavailable (Call limit) ", req);
22902 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22903 p->invitestate = INV_COMPLETED;
22904 }
22905 res = 0;
22906 goto request_invite_cleanup;
22907 }
22908 gotdest = get_destination(p, NULL, &cc_recall_core_id);
22909 extract_uri(p, req);
22910 build_contact(p);
22911
22912 if (p->rtp) {
22913 ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
22914 ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
22915 }
22916
22917 if (!replace_id && (gotdest != SIP_GET_DEST_EXTEN_FOUND)) {
22918 switch(gotdest) {
22919 case SIP_GET_DEST_INVALID_URI:
22920 transmit_response_reliable(p, "416 Unsupported URI scheme", req);
22921 break;
22922 case SIP_GET_DEST_EXTEN_MATCHMORE:
22923 if (ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP)
22924 == SIP_PAGE2_ALLOWOVERLAP_YES) {
22925 transmit_response_reliable(p, "484 Address Incomplete", req);
22926 break;
22927 }
22928
22929
22930
22931
22932
22933
22934
22935
22936
22937 case SIP_GET_DEST_EXTEN_NOT_FOUND:
22938 {
22939 char *decoded_exten = ast_strdupa(p->exten);
22940 transmit_response_reliable(p, "404 Not Found", req);
22941 ast_uri_decode(decoded_exten);
22942 ast_log(LOG_NOTICE, "Call from '%s' (%s) to extension"
22943 " '%s' rejected because extension not found in context '%s'.\n",
22944 S_OR(p->username, p->peername), ast_sockaddr_stringify(&p->recv), decoded_exten, p->context);
22945 }
22946 break;
22947 case SIP_GET_DEST_REFUSED:
22948 default:
22949 transmit_response_reliable(p, "403 Forbidden", req);
22950 }
22951
22952 p->invitestate = INV_COMPLETED;
22953 update_call_counter(p, DEC_CALL_LIMIT);
22954 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22955 res = 0;
22956 goto request_invite_cleanup;
22957 } else {
22958
22959
22960
22961 if (ast_strlen_zero(p->exten))
22962 ast_string_field_set(p, exten, "s");
22963
22964
22965 make_our_tag(p);
22966
22967
22968 c = sip_new(p, AST_STATE_DOWN, S_OR(p->peername, NULL), NULL);
22969 if (cc_recall_core_id != -1) {
22970 ast_setup_cc_recall_datastore(c, cc_recall_core_id);
22971 ast_cc_agent_set_interfaces_chanvar(c);
22972 }
22973 *recount = 1;
22974
22975
22976 build_route(p, req, 0, 0);
22977
22978 if (c) {
22979 ast_party_redirecting_init(&redirecting);
22980 memset(&update_redirecting, 0, sizeof(update_redirecting));
22981 change_redirecting_information(p, req, &redirecting, &update_redirecting,
22982 FALSE);
22983 ast_channel_set_redirecting(c, &redirecting, &update_redirecting);
22984 ast_party_redirecting_free(&redirecting);
22985 }
22986 }
22987 } else {
22988 ast_party_redirecting_init(&redirecting);
22989 memset(&update_redirecting, 0, sizeof(update_redirecting));
22990 if (sipdebug) {
22991 if (!req->ignore)
22992 ast_debug(2, "Got a SIP re-invite for call %s\n", p->callid);
22993 else
22994 ast_debug(2, "Got a SIP re-transmit of INVITE for call %s\n", p->callid);
22995 }
22996 if (!req->ignore)
22997 reinvite = 1;
22998 c = p->owner;
22999 change_redirecting_information(p, req, &redirecting, &update_redirecting, FALSE);
23000 if (c) {
23001 ast_channel_set_redirecting(c, &redirecting, &update_redirecting);
23002 }
23003 ast_party_redirecting_free(&redirecting);
23004 }
23005
23006
23007 if ((p->sipoptions & SIP_OPT_TIMER) && !ast_strlen_zero(get_header(req, "Session-Expires"))) {
23008 enum st_refresher_param st_ref_param;
23009
23010
23011
23012 ast_debug(2, "Incoming INVITE with 'timer' option supported and \"Session-Expires\" header.\n");
23013
23014
23015 if (!p->stimer)
23016 sip_st_alloc(p);
23017
23018
23019 p_uac_se_hdr = get_header(req, "Session-Expires");
23020 rtn = parse_session_expires(p_uac_se_hdr, &uac_max_se, &st_ref_param);
23021 tmp_st_ref = (st_ref_param == SESSION_TIMER_REFRESHER_PARAM_UAC) ? SESSION_TIMER_REFRESHER_THEM : SESSION_TIMER_REFRESHER_US;
23022 if (rtn != 0) {
23023 transmit_response_reliable(p, "400 Session-Expires Invalid Syntax", req);
23024 p->invitestate = INV_COMPLETED;
23025 if (!p->lastinvite) {
23026 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
23027 }
23028 res = -1;
23029 goto request_invite_cleanup;
23030 }
23031
23032
23033 p_uac_min_se = get_header(req, "Min-SE");
23034 if (!ast_strlen_zero(p_uac_min_se)) {
23035 rtn = parse_minse(p_uac_min_se, &uac_min_se);
23036 if (rtn != 0) {
23037 transmit_response_reliable(p, "400 Min-SE Invalid Syntax", req);
23038 p->invitestate = INV_COMPLETED;
23039 if (!p->lastinvite) {
23040 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
23041 }
23042 res = -1;
23043 goto request_invite_cleanup;
23044 }
23045 }
23046
23047 dlg_min_se = st_get_se(p, FALSE);
23048 switch (st_get_mode(p, 1)) {
23049 case SESSION_TIMER_MODE_ACCEPT:
23050 case SESSION_TIMER_MODE_ORIGINATE:
23051 if (uac_max_se > 0 && uac_max_se < dlg_min_se) {
23052 transmit_response_with_minse(p, "422 Session Interval Too Small", req, dlg_min_se);
23053 p->invitestate = INV_COMPLETED;
23054 if (!p->lastinvite) {
23055 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
23056 }
23057 res = -1;
23058 goto request_invite_cleanup;
23059 }
23060
23061 p->stimer->st_active_peer_ua = TRUE;
23062 st_active = TRUE;
23063 if (st_ref_param == SESSION_TIMER_REFRESHER_PARAM_UNKNOWN) {
23064 tmp_st_ref = st_get_refresher(p);
23065 }
23066
23067 if (uac_max_se > 0) {
23068 int dlg_max_se = st_get_se(p, TRUE);
23069 if (dlg_max_se >= uac_min_se) {
23070 st_interval = (uac_max_se < dlg_max_se) ? uac_max_se : dlg_max_se;
23071 } else {
23072 st_interval = uac_max_se;
23073 }
23074 } else {
23075
23076 st_interval = global_max_se;
23077 }
23078 break;
23079
23080 case SESSION_TIMER_MODE_REFUSE:
23081 if (p->reqsipoptions & SIP_OPT_TIMER) {
23082 transmit_response_with_unsupported(p, "420 Option Disabled", req, required);
23083 ast_log(LOG_WARNING, "Received SIP INVITE with supported but disabled option: %s\n", required);
23084 p->invitestate = INV_COMPLETED;
23085 if (!p->lastinvite) {
23086 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
23087 }
23088 res = -1;
23089 goto request_invite_cleanup;
23090 }
23091 break;
23092
23093 default:
23094 ast_log(LOG_ERROR, "Internal Error %d at %s:%d\n", st_get_mode(p, 1), __FILE__, __LINE__);
23095 break;
23096 }
23097 } else {
23098
23099
23100
23101 switch (st_get_mode(p, 1)) {
23102 case SESSION_TIMER_MODE_ORIGINATE:
23103 st_active = TRUE;
23104 st_interval = st_get_se(p, TRUE);
23105 tmp_st_ref = SESSION_TIMER_REFRESHER_US;
23106 p->stimer->st_active_peer_ua = FALSE;
23107 break;
23108
23109 default:
23110 break;
23111 }
23112 }
23113
23114 if (reinvite == 0) {
23115
23116 if (st_active == TRUE) {
23117 p->stimer->st_active = TRUE;
23118 p->stimer->st_interval = st_interval;
23119 p->stimer->st_ref = tmp_st_ref;
23120 start_session_timer(p);
23121 }
23122 } else {
23123 if (p->stimer->st_active == TRUE) {
23124
23125
23126
23127 ast_debug (2, "Restarting session-timers on a refresh - %s\n", p->callid);
23128
23129
23130 if (st_interval > 0) {
23131 p->stimer->st_interval = st_interval;
23132 p->stimer->st_ref = tmp_st_ref;
23133 }
23134
23135 restart_session_timer(p);
23136 if (p->stimer->st_expirys > 0) {
23137 p->stimer->st_expirys--;
23138 }
23139 }
23140 }
23141
23142 if (!req->ignore && p)
23143 p->lastinvite = seqno;
23144
23145 if (c && replace_id) {
23146 if (!ast_strlen_zero(pickup.exten)) {
23147 append_history(p, "Xfer", "INVITE/Replace received");
23148
23149
23150 transmit_response(p, "100 Trying", req);
23151 p->invitestate = INV_PROCEEDING;
23152 ast_setstate(c, AST_STATE_RING);
23153
23154
23155 ast_channel_unlock(c);
23156 *nounlock = 1;
23157
23158
23159
23160
23161
23162
23163 sip_pvt_unlock(p);
23164 do_magic_pickup(c, pickup.exten, pickup.context);
23165
23166 ast_hangup(c);
23167 sip_pvt_lock(p);
23168
23169 res = 0;
23170 goto request_invite_cleanup;
23171 } else {
23172
23173 if (sipdebug)
23174 ast_debug(4, "Sending this call to the invite/replcaes handler %s\n", p->callid);
23175 res = handle_invite_replaces(p, req, debug, seqno, addr, nounlock);
23176 refer_locked = 0;
23177 goto request_invite_cleanup;
23178 }
23179 }
23180
23181
23182 if (c) {
23183 enum ast_channel_state c_state = c->_state;
23184
23185 if (c_state != AST_STATE_UP && reinvite &&
23186 (p->invitestate == INV_TERMINATED || p->invitestate == INV_CONFIRMED)) {
23187
23188
23189
23190
23191
23192
23193
23194
23195
23196 c_state = AST_STATE_UP;
23197 }
23198
23199 switch(c_state) {
23200 case AST_STATE_DOWN:
23201 ast_debug(2, "%s: New call is still down.... Trying... \n", c->name);
23202 transmit_provisional_response(p, "100 Trying", req, 0);
23203 p->invitestate = INV_PROCEEDING;
23204 ast_setstate(c, AST_STATE_RING);
23205 if (strcmp(p->exten, ast_pickup_ext())) {
23206 enum ast_pbx_result result;
23207
23208 result = ast_pbx_start(c);
23209
23210 switch(result) {
23211 case AST_PBX_FAILED:
23212 ast_log(LOG_WARNING, "Failed to start PBX :(\n");
23213 p->invitestate = INV_COMPLETED;
23214 transmit_response_reliable(p, "503 Unavailable", req);
23215 break;
23216 case AST_PBX_CALL_LIMIT:
23217 ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
23218 p->invitestate = INV_COMPLETED;
23219 transmit_response_reliable(p, "480 Temporarily Unavailable", req);
23220 break;
23221 case AST_PBX_SUCCESS:
23222
23223 break;
23224 }
23225
23226 if (result) {
23227
23228
23229 ast_channel_unlock(c);
23230 *nounlock = 1;
23231 sip_pvt_unlock(p);
23232 ast_hangup(c);
23233 sip_pvt_lock(p);
23234 c = NULL;
23235 }
23236 } else {
23237 if (sip_pickup(c)) {
23238 ast_log(LOG_WARNING, "Failed to start Group pickup by %s\n", c->name);
23239 transmit_response_reliable(p, "480 Temporarily Unavailable", req);
23240 sip_alreadygone(p);
23241 c->hangupcause = AST_CAUSE_FAILURE;
23242
23243
23244 ast_channel_unlock(c);
23245 *nounlock = 1;
23246
23247 p->invitestate = INV_COMPLETED;
23248 sip_pvt_unlock(p);
23249 ast_hangup(c);
23250 sip_pvt_lock(p);
23251 c = NULL;
23252 }
23253 }
23254 break;
23255 case AST_STATE_RING:
23256 transmit_provisional_response(p, "100 Trying", req, 0);
23257 p->invitestate = INV_PROCEEDING;
23258 break;
23259 case AST_STATE_RINGING:
23260 transmit_provisional_response(p, "180 Ringing", req, 0);
23261 p->invitestate = INV_PROCEEDING;
23262 break;
23263 case AST_STATE_UP:
23264 ast_debug(2, "%s: This call is UP.... \n", c->name);
23265
23266 transmit_response(p, "100 Trying", req);
23267
23268 if (p->t38.state == T38_PEER_REINVITE) {
23269 if (p->t38id > -1) {
23270
23271 AST_SCHED_DEL_UNREF(sched, p->t38id, dialog_unref(p, "remove ref for t38id"));
23272 }
23273 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."));
23274 } else if (p->t38.state == T38_ENABLED) {
23275 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
23276 transmit_response_with_t38_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL)));
23277 } else if (p->t38.state == T38_DISABLED) {
23278
23279 if (p->srtp && !ast_test_flag(p->srtp, SRTP_CRYPTO_OFFER_OK)) {
23280 ast_log(LOG_WARNING, "Target does not support required crypto\n");
23281 transmit_response_reliable(p, "488 Not Acceptable Here (crypto)", req);
23282 } else {
23283 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
23284 transmit_response_with_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL)), p->session_modify == TRUE ? FALSE : TRUE, FALSE);
23285 ast_queue_control(p->owner, AST_CONTROL_UPDATE_RTP_PEER);
23286 }
23287 }
23288
23289 p->invitestate = INV_TERMINATED;
23290 break;
23291 default:
23292 ast_log(LOG_WARNING, "Don't know how to handle INVITE in state %d\n", c->_state);
23293 transmit_response(p, "100 Trying", req);
23294 break;
23295 }
23296 } else {
23297 if (p && (p->autokillid == -1)) {
23298 const char *msg;
23299
23300 if (!p->jointcapability)
23301 msg = "488 Not Acceptable Here (codec error)";
23302 else {
23303 ast_log(LOG_NOTICE, "Unable to create/find SIP channel for this INVITE\n");
23304 msg = "503 Unavailable";
23305 }
23306 transmit_response_reliable(p, msg, req);
23307 p->invitestate = INV_COMPLETED;
23308 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
23309 }
23310 }
23311
23312 request_invite_cleanup:
23313
23314 if (refer_locked && p->refer && p->refer->refer_call) {
23315 sip_pvt_unlock(p->refer->refer_call);
23316 if (p->refer->refer_call->owner) {
23317 ast_channel_unlock(p->refer->refer_call->owner);
23318 }
23319 p->refer->refer_call = dialog_unref(p->refer->refer_call, "unref dialog p->refer->refer_call");
23320 }
23321 if (authpeer) {
23322 authpeer = unref_peer(authpeer, "unref_peer, from handle_request_invite authpeer");
23323 }
23324
23325 return res;
23326 }
23327
23328
23329
23330
23331
23332
23333
23334
23335
23336
23337
23338
23339
23340
23341 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, uint32_t seqno, int *nounlock)
23342 {
23343 struct sip_dual target;
23344
23345 int res = 0;
23346 struct sip_pvt *targetcall_pvt;
23347 struct ast_party_connected_line connected_to_transferee;
23348 struct ast_party_connected_line connected_to_target;
23349 char transferer_linkedid[32];
23350 struct ast_channel *chans[2];
23351
23352
23353 if (!(targetcall_pvt = get_sip_pvt_byid_locked(transferer->refer->replaces_callid, transferer->refer->replaces_callid_totag,
23354 transferer->refer->replaces_callid_fromtag))) {
23355 if (transferer->refer->localtransfer) {
23356
23357
23358
23359 transmit_notify_with_sipfrag(transferer, seqno, "481 Call leg/transaction does not exist", TRUE);
23360 append_history(transferer, "Xfer", "Refer failed");
23361 ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
23362 transferer->refer->status = REFER_FAILED;
23363 return -1;
23364 }
23365
23366 ast_debug(3, "SIP attended transfer: Not our call - generating INVITE with replaces\n");
23367 return 0;
23368 }
23369
23370
23371 append_history(transferer, "Xfer", "Refer accepted");
23372 if (!targetcall_pvt->owner) {
23373 ast_debug(4, "SIP attended transfer: Error: No owner of target call\n");
23374
23375 transmit_notify_with_sipfrag(transferer, seqno, "503 Service Unavailable", TRUE);
23376 append_history(transferer, "Xfer", "Refer failed");
23377 ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
23378 transferer->refer->status = REFER_FAILED;
23379 sip_pvt_unlock(targetcall_pvt);
23380 if (targetcall_pvt)
23381 ao2_t_ref(targetcall_pvt, -1, "Drop targetcall_pvt pointer");
23382 return -1;
23383 }
23384
23385
23386 target.chan1 = targetcall_pvt->owner;
23387 target.chan2 = ast_bridged_channel(targetcall_pvt->owner);
23388
23389 if (!target.chan2 || !(target.chan2->_state == AST_STATE_UP || target.chan2->_state == AST_STATE_RINGING) ) {
23390
23391 if (target.chan2)
23392 ast_debug(4, "SIP attended transfer: Error: Wrong state of target call: %s\n", ast_state2str(target.chan2->_state));
23393 else if (target.chan1->_state != AST_STATE_RING)
23394 ast_debug(4, "SIP attended transfer: Error: No target channel\n");
23395 else
23396 ast_debug(4, "SIP attended transfer: Attempting transfer in ringing state\n");
23397 }
23398
23399
23400 if (sipdebug) {
23401 if (current->chan2)
23402 ast_debug(4, "SIP attended transfer: trying to bridge %s and %s\n", target.chan1->name, current->chan2->name);
23403 else
23404 ast_debug(4, "SIP attended transfer: trying to make %s take over (masq) %s\n", target.chan1->name, current->chan1->name);
23405 }
23406
23407 ast_set_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
23408
23409 ast_copy_string(transferer_linkedid, transferer->owner->linkedid, sizeof(transferer_linkedid));
23410
23411
23412 chans[0] = transferer->owner;
23413 chans[1] = target.chan1;
23414 ast_manager_event_multichan(EVENT_FLAG_CALL, "Transfer", 2, chans,
23415 "TransferMethod: SIP\r\n"
23416 "TransferType: Attended\r\n"
23417 "Channel: %s\r\n"
23418 "Uniqueid: %s\r\n"
23419 "SIP-Callid: %s\r\n"
23420 "TargetChannel: %s\r\n"
23421 "TargetUniqueid: %s\r\n",
23422 transferer->owner->name,
23423 transferer->owner->uniqueid,
23424 transferer->callid,
23425 target.chan1->name,
23426 target.chan1->uniqueid);
23427 ast_party_connected_line_init(&connected_to_transferee);
23428 ast_party_connected_line_init(&connected_to_target);
23429
23430 ast_party_connected_line_copy(&connected_to_transferee, ¤t->chan1->connected);
23431
23432 ast_party_connected_line_copy(&connected_to_target, &target.chan1->connected);
23433 connected_to_target.source = connected_to_transferee.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
23434 res = attempt_transfer(current, &target);
23435 if (res) {
23436
23437 transmit_notify_with_sipfrag(transferer, seqno, "486 Busy Here", TRUE);
23438 append_history(transferer, "Xfer", "Refer failed");
23439 ast_clear_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
23440
23441 sip_pvt_unlock(targetcall_pvt);
23442 ast_channel_unlock(target.chan1);
23443 } else {
23444
23445 const char *xfersound = pbx_builtin_getvar_helper(target.chan1, "ATTENDED_TRANSFER_COMPLETE_SOUND");
23446
23447
23448 ast_cel_report_event(target.chan1, AST_CEL_ATTENDEDTRANSFER, NULL, transferer_linkedid, target.chan2);
23449
23450
23451 transmit_notify_with_sipfrag(transferer, seqno, "200 OK", TRUE);
23452 append_history(transferer, "Xfer", "Refer succeeded");
23453 transferer->refer->status = REFER_200OK;
23454 if (target.chan2 && !ast_strlen_zero(xfersound) && ast_streamfile(target.chan2, xfersound, target.chan2->language) >= 0) {
23455 ast_waitstream(target.chan2, "");
23456 }
23457
23458
23459
23460
23461
23462
23463
23464
23465
23466
23467
23468 ast_channel_ref(current->chan1);
23469 ast_channel_unlock(current->chan1);
23470 ast_channel_unlock(target.chan1);
23471 *nounlock = 1;
23472 sip_pvt_unlock(targetcall_pvt);
23473 sip_pvt_unlock(transferer);
23474
23475 ast_do_masquerade(target.chan1);
23476
23477 ast_indicate(target.chan1, AST_CONTROL_UNHOLD);
23478 if (target.chan2) {
23479 ast_indicate(target.chan2, AST_CONTROL_UNHOLD);
23480 }
23481
23482 if (current->chan2 && current->chan2->_state == AST_STATE_RING) {
23483 ast_indicate(target.chan1, AST_CONTROL_RINGING);
23484 }
23485
23486 if (target.chan2) {
23487 ast_channel_queue_connected_line_update(target.chan1, &connected_to_transferee, NULL);
23488 ast_channel_queue_connected_line_update(target.chan2, &connected_to_target, NULL);
23489 } else {
23490
23491
23492
23493
23494
23495
23496
23497 struct ast_control_read_action_payload *frame_payload;
23498 int payload_size;
23499 int frame_size;
23500 unsigned char connected_line_data[1024];
23501 payload_size = ast_connected_line_build_data(connected_line_data,
23502 sizeof(connected_line_data), &connected_to_target, NULL);
23503 frame_size = payload_size + sizeof(*frame_payload);
23504 if (payload_size != -1) {
23505 frame_payload = ast_alloca(frame_size);
23506 frame_payload->payload_size = payload_size;
23507 memcpy(frame_payload->payload, connected_line_data, payload_size);
23508 frame_payload->action = AST_FRAME_READ_ACTION_CONNECTED_LINE_MACRO;
23509 ast_queue_control_data(target.chan1, AST_CONTROL_READ_ACTION, frame_payload, frame_size);
23510 }
23511
23512
23513
23514
23515 ast_channel_queue_connected_line_update(target.chan1, &connected_to_transferee, NULL);
23516
23517 }
23518 sip_pvt_lock(transferer);
23519
23520 ast_channel_unref(current->chan1);
23521 }
23522
23523
23524 ast_party_connected_line_free(&connected_to_target);
23525 ast_party_connected_line_free(&connected_to_transferee);
23526 if (targetcall_pvt)
23527 ao2_t_ref(targetcall_pvt, -1, "drop targetcall_pvt");
23528 return 1;
23529 }
23530
23531
23532
23533
23534
23535
23536
23537
23538
23539
23540
23541
23542
23543
23544
23545
23546
23547
23548
23549
23550
23551
23552
23553
23554
23555
23556
23557
23558
23559
23560
23561
23562
23563
23564
23565
23566
23567
23568
23569
23570
23571
23572
23573
23574
23575
23576
23577
23578
23579
23580
23581
23582
23583
23584
23585
23586
23587
23588
23589
23590
23591
23592
23593
23594
23595 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, uint32_t seqno, int *nounlock)
23596 {
23597
23598
23599
23600
23601 struct sip_dual current = { 0, };
23602 struct ast_channel *chans[2] = { 0, };
23603 char *refer_to = NULL;
23604 char *refer_to_domain = NULL;
23605 char *refer_to_context = NULL;
23606 char *referred_by = NULL;
23607 char *callid = NULL;
23608 int localtransfer = 0;
23609 int attendedtransfer = 0;
23610 int res = 0;
23611
23612 if (req->debug) {
23613 ast_verbose("Call %s got a SIP call transfer from %s: (REFER)!\n",
23614 p->callid,
23615 ast_test_flag(&p->flags[0], SIP_OUTGOING) ? "callee" : "caller");
23616 }
23617
23618 if (!p->owner) {
23619
23620
23621 ast_debug(3, "Call %s: Declined REFER, outside of dialog...\n", p->callid);
23622 transmit_response(p, "603 Declined (No dialog)", req);
23623 if (!req->ignore) {
23624 append_history(p, "Xfer", "Refer failed. Outside of dialog.");
23625 sip_alreadygone(p);
23626 pvt_set_needdestroy(p, "outside of dialog");
23627 }
23628 res = 0;
23629 goto handle_refer_cleanup;
23630 }
23631
23632
23633 if (p->allowtransfer == TRANSFER_CLOSED ) {
23634
23635 transmit_response(p, "603 Declined (policy)", req);
23636 append_history(p, "Xfer", "Refer failed. Allowtransfer == closed.");
23637
23638 res = 0;
23639 goto handle_refer_cleanup;
23640 }
23641
23642 if (!req->ignore && ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
23643
23644 transmit_response(p, "491 Request pending", req);
23645 append_history(p, "Xfer", "Refer failed. Request pending.");
23646 res = 0;
23647 goto handle_refer_cleanup;
23648 }
23649
23650
23651 if (!p->refer && !sip_refer_allocate(p)) {
23652 transmit_response(p, "500 Internal Server Error", req);
23653 append_history(p, "Xfer", "Refer failed. Memory allocation error.");
23654 res = -3;
23655 goto handle_refer_cleanup;
23656 }
23657
23658 res = get_refer_info(p, req);
23659
23660 p->refer->status = REFER_SENT;
23661
23662 if (res != 0) {
23663 switch (res) {
23664 case -2:
23665 transmit_response(p, "400 Bad Request (Refer-to missing)", req);
23666 append_history(p, "Xfer", "Refer failed. Refer-to missing.");
23667 if (req->debug) {
23668 ast_debug(1, "SIP transfer to black hole can't be handled (no refer-to: )\n");
23669 }
23670 break;
23671 case -3:
23672 transmit_response(p, "603 Declined (Non sip: uri)", req);
23673 append_history(p, "Xfer", "Refer failed. Non SIP uri");
23674 if (req->debug) {
23675 ast_debug(1, "SIP transfer to non-SIP uri denied\n");
23676 }
23677 break;
23678 default:
23679
23680 transmit_response(p, "202 Accepted", req);
23681 append_history(p, "Xfer", "Refer failed. Bad extension.");
23682 transmit_notify_with_sipfrag(p, seqno, "404 Not found", TRUE);
23683 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
23684 if (req->debug) {
23685 ast_debug(1, "SIP transfer to bad extension: %s\n", p->refer->refer_to);
23686 }
23687 break;
23688 }
23689 res = 0;
23690 goto handle_refer_cleanup;
23691 }
23692 if (ast_strlen_zero(p->context)) {
23693 ast_string_field_set(p, context, sip_cfg.default_context);
23694 }
23695
23696
23697 if (sip_cfg.allow_external_domains && check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
23698 p->refer->localtransfer = 1;
23699 if (sipdebug) {
23700 ast_debug(3, "This SIP transfer is local : %s\n", p->refer->refer_to_domain);
23701 }
23702 } else if (AST_LIST_EMPTY(&domain_list) || check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
23703
23704 p->refer->localtransfer = 1;
23705 } else if (sipdebug) {
23706 ast_debug(3, "This SIP transfer is to a remote SIP extension (remote domain %s)\n", p->refer->refer_to_domain);
23707 }
23708
23709
23710
23711 if (req->ignore) {
23712 goto handle_refer_cleanup;
23713 }
23714
23715
23716
23717
23718
23719
23720
23721
23722
23723
23724
23725
23726
23727
23728
23729
23730
23731
23732
23733
23734
23735
23736
23737
23738
23739
23740 chans[0] = current.chan1 = p->owner;
23741
23742
23743 chans[1] = current.chan2 = ast_bridged_channel(current.chan1);
23744
23745 ast_channel_ref(current.chan1);
23746 if (current.chan2) {
23747 ast_channel_ref(current.chan2);
23748 }
23749
23750 if (sipdebug) {
23751 ast_debug(3, "SIP %s transfer: Transferer channel %s, transferee channel %s\n",
23752 p->refer->attendedtransfer ? "attended" : "blind",
23753 current.chan1->name,
23754 current.chan2 ? current.chan2->name : "<none>");
23755 }
23756
23757 if (!current.chan2 && !p->refer->attendedtransfer) {
23758
23759
23760
23761 if (sipdebug) {
23762 ast_debug(3, "Refused SIP transfer on non-bridged channel.\n");
23763 }
23764 p->refer->status = REFER_FAILED;
23765 append_history(p, "Xfer", "Refer failed. Non-bridged channel.");
23766 transmit_response(p, "603 Declined", req);
23767 res = -1;
23768 goto handle_refer_cleanup;
23769 }
23770
23771 if (current.chan2) {
23772 if (sipdebug) {
23773 ast_debug(4, "Got SIP transfer, applying to bridged peer '%s'\n", current.chan2->name);
23774 }
23775 ast_queue_control(current.chan1, AST_CONTROL_UNHOLD);
23776 }
23777
23778 ast_set_flag(&p->flags[0], SIP_GOTREFER);
23779
23780
23781 transmit_response(p, "202 Accepted", req);
23782
23783
23784 if (p->refer->attendedtransfer) {
23785
23786 if ((res = local_attended_transfer(p, ¤t, req, seqno, nounlock))) {
23787 goto handle_refer_cleanup;
23788 }
23789
23790 if (sipdebug) {
23791 ast_debug(4, "SIP attended transfer: Still not our call - generating INVITE with replaces\n");
23792 }
23793
23794 }
23795
23796
23797 refer_to = ast_strdupa(p->refer->refer_to);
23798 refer_to_domain = ast_strdupa(p->refer->refer_to_domain);
23799 refer_to_context = ast_strdupa(p->refer->refer_to_context);
23800 referred_by = ast_strdupa(p->refer->referred_by);
23801 callid = ast_strdupa(p->callid);
23802 localtransfer = p->refer->localtransfer;
23803 attendedtransfer = p->refer->attendedtransfer;
23804
23805 if (!*nounlock) {
23806 ast_channel_unlock(p->owner);
23807 *nounlock = 1;
23808 }
23809 sip_pvt_unlock(p);
23810
23811
23812 if (localtransfer && ast_parking_ext_valid(refer_to, current.chan1, refer_to_context)) {
23813 sip_pvt_lock(p);
23814 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
23815 p->refer->status = REFER_200OK;
23816 append_history(p, "Xfer", "REFER to call parking.");
23817 sip_pvt_unlock(p);
23818
23819 ast_manager_event_multichan(EVENT_FLAG_CALL, "Transfer", 2, chans,
23820 "TransferMethod: SIP\r\n"
23821 "TransferType: Blind\r\n"
23822 "Channel: %s\r\n"
23823 "Uniqueid: %s\r\n"
23824 "SIP-Callid: %s\r\n"
23825 "TargetChannel: %s\r\n"
23826 "TargetUniqueid: %s\r\n"
23827 "TransferExten: %s\r\n"
23828 "Transfer2Parking: Yes\r\n",
23829 current.chan1->name,
23830 current.chan1->uniqueid,
23831 callid,
23832 current.chan2->name,
23833 current.chan2->uniqueid,
23834 refer_to);
23835
23836 if (sipdebug) {
23837 ast_debug(4, "SIP transfer to parking: trying to park %s. Parked by %s\n", current.chan2->name, current.chan1->name);
23838 }
23839
23840
23841 if (sip_park(current.chan2, current.chan1, req, seqno, refer_to, refer_to_context)) {
23842 sip_pvt_lock(p);
23843 transmit_notify_with_sipfrag(p, seqno, "500 Internal Server Error", TRUE);
23844 } else {
23845 sip_pvt_lock(p);
23846 }
23847 goto handle_refer_cleanup;
23848 }
23849
23850
23851
23852
23853 if (current.chan1 && current.chan2) {
23854 ast_debug(3, "chan1->name: %s\n", current.chan1->name);
23855 pbx_builtin_setvar_helper(current.chan1, "BLINDTRANSFER", current.chan2->name);
23856 }
23857
23858 if (current.chan2) {
23859 pbx_builtin_setvar_helper(current.chan2, "BLINDTRANSFER", current.chan1->name);
23860 pbx_builtin_setvar_helper(current.chan2, "SIPDOMAIN", refer_to_domain);
23861 pbx_builtin_setvar_helper(current.chan2, "SIPTRANSFER", "yes");
23862
23863 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER", "yes");
23864
23865 if (!ast_strlen_zero(referred_by)) {
23866 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REFERER", referred_by);
23867 }
23868 }
23869
23870 sip_pvt_lock(p);
23871
23872 if (!ast_strlen_zero(p->refer->replaces_callid)) {
23873 char tempheader[SIPBUFSIZE];
23874 snprintf(tempheader, sizeof(tempheader), "%s%s%s%s%s", p->refer->replaces_callid,
23875 p->refer->replaces_callid_totag ? ";to-tag=" : "",
23876 p->refer->replaces_callid_totag,
23877 p->refer->replaces_callid_fromtag ? ";from-tag=" : "",
23878 p->refer->replaces_callid_fromtag);
23879
23880 if (current.chan2) {
23881 sip_pvt_unlock(p);
23882 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REPLACES", tempheader);
23883 sip_pvt_lock(p);
23884 }
23885 }
23886
23887
23888
23889
23890 if (!p->refer->attendedtransfer) {
23891 transmit_notify_with_sipfrag(p, seqno, "180 Ringing", FALSE);
23892 }
23893
23894
23895
23896
23897
23898 if (!current.chan2) {
23899
23900
23901
23902
23903
23904
23905
23906 p->refer->status = REFER_FAILED;
23907 transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable (can't handle one-legged xfers)", TRUE);
23908 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
23909 append_history(p, "Xfer", "Refer failed (only bridged calls).");
23910 res = -1;
23911 goto handle_refer_cleanup;
23912 }
23913 ast_set_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
23914
23915
23916
23917
23918
23919
23920
23921 sip_pvt_unlock(p);
23922 ast_indicate(current.chan2, AST_CONTROL_UNHOLD);
23923 res = ast_async_goto(current.chan2, refer_to_context, refer_to, 1);
23924
23925 if (!res) {
23926 ast_manager_event_multichan(EVENT_FLAG_CALL, "Transfer", 2, chans,
23927 "TransferMethod: SIP\r\n"
23928 "TransferType: Blind\r\n"
23929 "Channel: %s\r\n"
23930 "Uniqueid: %s\r\n"
23931 "SIP-Callid: %s\r\n"
23932 "TargetChannel: %s\r\n"
23933 "TargetUniqueid: %s\r\n"
23934 "TransferExten: %s\r\n"
23935 "TransferContext: %s\r\n",
23936 current.chan1->name,
23937 current.chan1->uniqueid,
23938 callid,
23939 current.chan2->name,
23940 current.chan2->uniqueid,
23941 refer_to,
23942 refer_to_context);
23943
23944 ast_debug(3, "%s transfer succeeded. Telling transferer.\n", attendedtransfer? "Attended" : "Blind");
23945
23946
23947 ast_channel_lock(current.chan1);
23948 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);
23949 ast_channel_unlock(current.chan1);
23950
23951 sip_pvt_lock(p);
23952 transmit_notify_with_sipfrag(p, seqno, "200 Ok", TRUE);
23953 if (p->refer->localtransfer) {
23954 p->refer->status = REFER_200OK;
23955 }
23956 if (p->owner) {
23957 p->owner->hangupcause = AST_CAUSE_NORMAL_CLEARING;
23958 }
23959 append_history(p, "Xfer", "Refer succeeded.");
23960 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
23961
23962
23963 res = 0;
23964 } else {
23965 sip_pvt_lock(p);
23966 ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
23967 ast_debug(3, "%s transfer failed. Resuming original call.\n", p->refer->attendedtransfer? "Attended" : "Blind");
23968 append_history(p, "Xfer", "Refer failed.");
23969
23970 p->refer->status = REFER_FAILED;
23971 transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable", TRUE);
23972 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
23973 res = -1;
23974 }
23975
23976 handle_refer_cleanup:
23977 if (current.chan1) {
23978 ast_channel_unref(current.chan1);
23979 }
23980 if (current.chan2) {
23981 ast_channel_unref(current.chan2);
23982 }
23983
23984
23985 return res;
23986 }
23987
23988
23989 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req)
23990 {
23991
23992 check_via(p, req);
23993 sip_alreadygone(p);
23994
23995 if (p->owner && p->owner->_state == AST_STATE_UP) {
23996
23997 transmit_response(p, "200 OK", req);
23998 ast_debug(1, "Got CANCEL on an answered call. Ignoring... \n");
23999 return 0;
24000 }
24001
24002
24003
24004
24005
24006
24007 if (p->invitestate == INV_TERMINATED || p->invitestate == INV_COMPLETED) {
24008 __sip_pretend_ack(p);
24009 }
24010 if (p->invitestate != INV_TERMINATED)
24011 p->invitestate = INV_CANCELLED;
24012
24013 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD))
24014 update_call_counter(p, DEC_CALL_LIMIT);
24015
24016 stop_media_flows(p);
24017 if (p->owner) {
24018 sip_queue_hangup_cause(p, 0);
24019 } else {
24020 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
24021 }
24022 if (ast_str_strlen(p->initreq.data) > 0) {
24023 struct sip_pkt *pkt, *prev_pkt;
24024
24025
24026
24027
24028
24029
24030
24031
24032
24033
24034
24035 for (pkt = p->packets, prev_pkt = NULL; pkt; prev_pkt = pkt, pkt = pkt->next) {
24036 if (pkt->seqno == p->lastinvite && pkt->response_code == 487) {
24037 AST_SCHED_DEL(sched, pkt->retransid);
24038 UNLINK(pkt, p->packets, prev_pkt);
24039 dialog_unref(pkt->owner, "unref packet->owner from dialog");
24040 if (pkt->data) {
24041 ast_free(pkt->data);
24042 }
24043 ast_free(pkt);
24044 break;
24045 }
24046 }
24047 transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
24048 transmit_response(p, "200 OK", req);
24049 return 1;
24050 } else {
24051 transmit_response(p, "481 Call Leg Does Not Exist", req);
24052 return 0;
24053 }
24054 }
24055
24056
24057 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req)
24058 {
24059 struct ast_channel *c=NULL;
24060 int res;
24061 struct ast_channel *bridged_to;
24062 const char *required;
24063
24064
24065 if (p->pendinginvite && !ast_test_flag(&p->flags[0], SIP_OUTGOING) && !req->ignore) {
24066 transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
24067 }
24068
24069 __sip_pretend_ack(p);
24070
24071 p->invitestate = INV_TERMINATED;
24072
24073 copy_request(&p->initreq, req);
24074 if (sipdebug)
24075 ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
24076 check_via(p, req);
24077 sip_alreadygone(p);
24078
24079
24080 if (p->do_history || p->owner) {
24081 char quality_buf[AST_MAX_USER_FIELD], *quality;
24082 struct ast_channel *bridge = p->owner ? ast_bridged_channel(p->owner) : NULL;
24083
24084
24085
24086
24087 while (bridge && ast_channel_trylock(bridge)) {
24088 ast_channel_unlock(p->owner);
24089 do {
24090
24091 sip_pvt_unlock(p);
24092 usleep(1);
24093 sip_pvt_lock(p);
24094 } while (p->owner && ast_channel_trylock(p->owner));
24095 bridge = p->owner ? ast_bridged_channel(p->owner) : NULL;
24096 }
24097
24098
24099 if (p->rtp && (quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
24100 if (p->do_history) {
24101 append_history(p, "RTCPaudio", "Quality:%s", quality);
24102
24103 if ((quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY_JITTER, quality_buf, sizeof(quality_buf)))) {
24104 append_history(p, "RTCPaudioJitter", "Quality:%s", quality);
24105 }
24106 if ((quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY_LOSS, quality_buf, sizeof(quality_buf)))) {
24107 append_history(p, "RTCPaudioLoss", "Quality:%s", quality);
24108 }
24109 if ((quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY_RTT, quality_buf, sizeof(quality_buf)))) {
24110 append_history(p, "RTCPaudioRTT", "Quality:%s", quality);
24111 }
24112 }
24113
24114 if (p->owner) {
24115 ast_rtp_instance_set_stats_vars(p->owner, p->rtp);
24116 }
24117
24118 }
24119
24120 if (bridge) {
24121 struct sip_pvt *q = bridge->tech_pvt;
24122
24123 if (IS_SIP_TECH(bridge->tech) && q && q->rtp) {
24124 ast_rtp_instance_set_stats_vars(bridge, q->rtp);
24125 }
24126 ast_channel_unlock(bridge);
24127 }
24128
24129 if (p->vrtp && (quality = ast_rtp_instance_get_quality(p->vrtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
24130 if (p->do_history) {
24131 append_history(p, "RTCPvideo", "Quality:%s", quality);
24132 }
24133 if (p->owner) {
24134 pbx_builtin_setvar_helper(p->owner, "RTPVIDEOQOS", quality);
24135 }
24136 }
24137 if (p->trtp && (quality = ast_rtp_instance_get_quality(p->trtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
24138 if (p->do_history) {
24139 append_history(p, "RTCPtext", "Quality:%s", quality);
24140 }
24141 if (p->owner) {
24142 pbx_builtin_setvar_helper(p->owner, "RTPTEXTQOS", quality);
24143 }
24144 }
24145 }
24146
24147 stop_media_flows(p);
24148 stop_session_timer(p);
24149
24150 if (!ast_strlen_zero(get_header(req, "Also"))) {
24151 ast_log(LOG_NOTICE, "Client '%s' using deprecated BYE/Also transfer method. Ask vendor to support REFER instead\n",
24152 ast_sockaddr_stringify(&p->recv));
24153 if (ast_strlen_zero(p->context))
24154 ast_string_field_set(p, context, sip_cfg.default_context);
24155 res = get_also_info(p, req);
24156 if (!res) {
24157 c = p->owner;
24158 if (c) {
24159 bridged_to = ast_bridged_channel(c);
24160 if (bridged_to) {
24161
24162 ast_queue_control(c, AST_CONTROL_UNHOLD);
24163 ast_channel_unlock(c);
24164 ast_async_goto(bridged_to, p->context, p->refer->refer_to, 1);
24165 ast_channel_lock(c);
24166 } else
24167 ast_queue_hangup(p->owner);
24168 }
24169 } else {
24170 ast_log(LOG_WARNING, "Invalid transfer information from '%s'\n", ast_sockaddr_stringify(&p->recv));
24171 if (p->owner)
24172 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
24173 }
24174 } else if (p->owner) {
24175 sip_queue_hangup_cause(p, 0);
24176 sip_scheddestroy_final(p, DEFAULT_TRANS_TIMEOUT);
24177 ast_debug(3, "Received bye, issuing owner hangup\n");
24178 } else {
24179 sip_scheddestroy_final(p, DEFAULT_TRANS_TIMEOUT);
24180 ast_debug(3, "Received bye, no owner, selfdestruct soon.\n");
24181 }
24182 ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
24183
24184
24185 required = get_header(req, "Require");
24186 if (!ast_strlen_zero(required)) {
24187 char unsupported[256] = { 0, };
24188 parse_sip_options(required, unsupported, ARRAY_LEN(unsupported));
24189
24190
24191 if (!ast_strlen_zero(unsupported)) {
24192 transmit_response_with_unsupported(p, "420 Bad extension (unsupported)", req, unsupported);
24193 ast_log(LOG_WARNING, "Received SIP BYE with unsupported required extension: required:%s unsupported:%s\n", required, unsupported);
24194 } else {
24195 transmit_response(p, "200 OK", req);
24196 }
24197 } else {
24198 transmit_response(p, "200 OK", req);
24199 }
24200
24201 return 1;
24202 }
24203
24204
24205 static int handle_request_message(struct sip_pvt *p, struct sip_request *req)
24206 {
24207 if (!req->ignore) {
24208 if (req->debug)
24209 ast_verbose("Receiving message!\n");
24210 receive_message(p, req);
24211 } else
24212 transmit_response(p, "202 Accepted", req);
24213 return 1;
24214 }
24215
24216 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)
24217 {
24218 int etag_present = !ast_strlen_zero(etag);
24219 int body_present = req->lines > 0;
24220
24221 ast_assert(expires_int != NULL);
24222
24223 if (ast_strlen_zero(expires)) {
24224
24225
24226
24227
24228 *expires_int = DEFAULT_PUBLISH_EXPIRES;
24229 } else if (sscanf(expires, "%30d", expires_int) != 1) {
24230 return SIP_PUBLISH_UNKNOWN;
24231 }
24232
24233 if (*expires_int == 0) {
24234 return SIP_PUBLISH_REMOVE;
24235 } else if (!etag_present && body_present) {
24236 return SIP_PUBLISH_INITIAL;
24237 } else if (etag_present && !body_present) {
24238 return SIP_PUBLISH_REFRESH;
24239 } else if (etag_present && body_present) {
24240 return SIP_PUBLISH_MODIFY;
24241 }
24242
24243 return SIP_PUBLISH_UNKNOWN;
24244 }
24245
24246 #ifdef HAVE_LIBXML2
24247 static void get_pidf_body(struct sip_request *req, char *pidf_body, size_t size)
24248 {
24249 int i;
24250 struct ast_str *str = ast_str_alloca(size);
24251 for (i = 0; i < req->lines; ++i) {
24252 ast_str_append(&str, 0, "%s", REQ_OFFSET_TO_STR(req, line[i]));
24253 }
24254 ast_copy_string(pidf_body, ast_str_buffer(str), size);
24255 }
24256
24257 static int pidf_validate_tuple(struct ast_xml_node *tuple_node)
24258 {
24259 const char *id;
24260 int status_found = FALSE;
24261 struct ast_xml_node *tuple_children;
24262 struct ast_xml_node *tuple_children_iterator;
24263
24264 if (!(id = ast_xml_get_attribute(tuple_node, "id"))) {
24265 ast_log(LOG_WARNING, "Tuple XML element has no attribute 'id'\n");
24266 return FALSE;
24267 }
24268
24269 ast_xml_free_attr(id);
24270
24271 if (!(tuple_children = ast_xml_node_get_children(tuple_node))) {
24272
24273 ast_log(LOG_WARNING, "Tuple XML element has no child elements\n");
24274 return FALSE;
24275 }
24276 for (tuple_children_iterator = tuple_children; tuple_children_iterator;
24277 tuple_children_iterator = ast_xml_node_get_next(tuple_children_iterator)) {
24278
24279
24280
24281
24282 if (strcmp(ast_xml_node_get_name(tuple_children_iterator), "status")) {
24283
24284 continue;
24285 }
24286 if (status_found == TRUE) {
24287
24288 ast_log(LOG_WARNING, "Multiple status elements found in tuple. Only one allowed\n");
24289 return FALSE;
24290 }
24291 status_found = TRUE;
24292 }
24293 return status_found;
24294 }
24295
24296
24297 static int pidf_validate_presence(struct ast_xml_doc *doc)
24298 {
24299 struct ast_xml_node *presence_node = ast_xml_get_root(doc);
24300 struct ast_xml_node *child_nodes;
24301 struct ast_xml_node *node_iterator;
24302 struct ast_xml_ns *ns;
24303 const char *entity;
24304 const char *namespace;
24305 const char presence_namespace[] = "urn:ietf:params:xml:ns:pidf";
24306
24307 if (!presence_node) {
24308 ast_log(LOG_WARNING, "Unable to retrieve root node of the XML document\n");
24309 return FALSE;
24310 }
24311
24312
24313
24314 if (strcmp(ast_xml_node_get_name(presence_node), "presence")) {
24315 ast_log(LOG_WARNING, "Root node of PIDF document is not 'presence'. Invalid\n");
24316 return FALSE;
24317 }
24318
24319
24320
24321
24322 if (!(entity = ast_xml_get_attribute(presence_node, "entity"))) {
24323 ast_log(LOG_WARNING, "Presence element of PIDF document has no 'entity' attribute\n");
24324 return FALSE;
24325 }
24326
24327 ast_xml_free_attr(entity);
24328
24329 if (!(ns = ast_xml_find_namespace(doc, presence_node, NULL))) {
24330 ast_log(LOG_WARNING, "Couldn't find default namespace...\n");
24331 return FALSE;
24332 }
24333
24334 namespace = ast_xml_get_ns_href(ns);
24335 if (ast_strlen_zero(namespace) || strcmp(namespace, presence_namespace)) {
24336 ast_log(LOG_WARNING, "PIDF document has invalid namespace value %s\n", namespace);
24337 return FALSE;
24338 }
24339
24340 if (!(child_nodes = ast_xml_node_get_children(presence_node))) {
24341 ast_log(LOG_WARNING, "PIDF document has no elements as children of 'presence'. Invalid\n");
24342 return FALSE;
24343 }
24344
24345
24346
24347
24348
24349
24350
24351
24352
24353 for (node_iterator = child_nodes; node_iterator;
24354 node_iterator = ast_xml_node_get_next(node_iterator)) {
24355 if (strcmp(ast_xml_node_get_name(node_iterator), "tuple")) {
24356
24357 continue;
24358 }
24359 if (pidf_validate_tuple(node_iterator) == FALSE) {
24360 ast_log(LOG_WARNING, "Unable to validate tuple\n");
24361 return FALSE;
24362 }
24363 }
24364
24365 return TRUE;
24366 }
24367
24368
24369
24370
24371
24372
24373
24374
24375
24376
24377
24378
24379
24380
24381
24382
24383 static int sip_pidf_validate(struct sip_request *req, struct ast_xml_doc **pidf_doc)
24384 {
24385 struct ast_xml_doc *doc;
24386 int content_length;
24387 const char *content_length_str = get_header(req, "Content-Length");
24388 const char *content_type = get_header(req, "Content-Type");
24389 char pidf_body[SIPBUFSIZE];
24390 int res;
24391
24392 if (ast_strlen_zero(content_type) || strcmp(content_type, "application/pidf+xml")) {
24393 ast_log(LOG_WARNING, "Content type is not PIDF\n");
24394 return FALSE;
24395 }
24396
24397 if (ast_strlen_zero(content_length_str)) {
24398 ast_log(LOG_WARNING, "No content length. Can't determine bounds of PIDF document\n");
24399 return FALSE;
24400 }
24401
24402 if (sscanf(content_length_str, "%30d", &content_length) != 1) {
24403 ast_log(LOG_WARNING, "Invalid content length provided\n");
24404 return FALSE;
24405 }
24406
24407 if (content_length > sizeof(pidf_body)) {
24408 ast_log(LOG_WARNING, "Content length of PIDF document truncated to %d bytes\n", (int) sizeof(pidf_body));
24409 content_length = sizeof(pidf_body);
24410 }
24411
24412 get_pidf_body(req, pidf_body, content_length);
24413
24414 if (!(doc = ast_xml_read_memory(pidf_body, content_length))) {
24415 ast_log(LOG_WARNING, "Unable to open XML PIDF document. Is it malformed?\n");
24416 return FALSE;
24417 }
24418
24419 res = pidf_validate_presence(doc);
24420 if (res == TRUE) {
24421 *pidf_doc = doc;
24422 } else {
24423 ast_xml_close(doc);
24424 }
24425 return res;
24426 }
24427
24428 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)
24429 {
24430 const char *uri = REQ_OFFSET_TO_STR(req, rlPart2);
24431 struct ast_cc_agent *agent;
24432 struct sip_cc_agent_pvt *agent_pvt;
24433 struct ast_xml_doc *pidf_doc = NULL;
24434 const char *basic_status = NULL;
24435 struct ast_xml_node *presence_node;
24436 struct ast_xml_node *presence_children;
24437 struct ast_xml_node *tuple_node;
24438 struct ast_xml_node *tuple_children;
24439 struct ast_xml_node *status_node;
24440 struct ast_xml_node *status_children;
24441 struct ast_xml_node *basic_node;
24442 int res = 0;
24443
24444 if (!((agent = find_sip_cc_agent_by_notify_uri(uri)) || (agent = find_sip_cc_agent_by_subscribe_uri(uri)))) {
24445 ast_log(LOG_WARNING, "Could not find agent using uri '%s'\n", uri);
24446 transmit_response(pvt, "412 Conditional Request Failed", req);
24447 return -1;
24448 }
24449
24450 agent_pvt = agent->private_data;
24451
24452 if (sip_pidf_validate(req, &pidf_doc) == FALSE) {
24453 res = -1;
24454 goto cc_publish_cleanup;
24455 }
24456
24457
24458
24459
24460
24461
24462
24463 presence_node = ast_xml_get_root(pidf_doc);
24464 if (!(presence_children = ast_xml_node_get_children(presence_node))) {
24465 ast_log(LOG_WARNING, "No tuples within presence element.\n");
24466 res = -1;
24467 goto cc_publish_cleanup;
24468 }
24469
24470 if (!(tuple_node = ast_xml_find_element(presence_children, "tuple", NULL, NULL))) {
24471 ast_log(LOG_NOTICE, "Couldn't find tuple node?\n");
24472 res = -1;
24473 goto cc_publish_cleanup;
24474 }
24475
24476
24477
24478
24479 tuple_children = ast_xml_node_get_children(tuple_node);
24480
24481 status_node = ast_xml_find_element(tuple_children, "status", NULL, NULL);
24482
24483 if (!(status_children = ast_xml_node_get_children(status_node))) {
24484 ast_log(LOG_WARNING, "No basic elements within status element.\n");
24485 res = -1;
24486 goto cc_publish_cleanup;
24487 }
24488
24489 if (!(basic_node = ast_xml_find_element(status_children, "basic", NULL, NULL))) {
24490 ast_log(LOG_WARNING, "Couldn't find basic node?\n");
24491 res = -1;
24492 goto cc_publish_cleanup;
24493 }
24494
24495 basic_status = ast_xml_get_text(basic_node);
24496
24497 if (ast_strlen_zero(basic_status)) {
24498 ast_log(LOG_NOTICE, "NOthing in basic node?\n");
24499 res = -1;
24500 goto cc_publish_cleanup;
24501 }
24502
24503 if (!strcmp(basic_status, "open")) {
24504 agent_pvt->is_available = TRUE;
24505 ast_cc_agent_caller_available(agent->core_id, "Received PUBLISH stating SIP caller %s is available",
24506 agent->device_name);
24507 } else if (!strcmp(basic_status, "closed")) {
24508 agent_pvt->is_available = FALSE;
24509 ast_cc_agent_caller_busy(agent->core_id, "Received PUBLISH stating SIP caller %s is busy",
24510 agent->device_name);
24511 } else {
24512 ast_log(LOG_NOTICE, "Invalid content in basic element: %s\n", basic_status);
24513 }
24514
24515 cc_publish_cleanup:
24516 if (basic_status) {
24517 ast_xml_free_text(basic_status);
24518 }
24519 if (pidf_doc) {
24520 ast_xml_close(pidf_doc);
24521 }
24522 ao2_ref(agent, -1);
24523 if (res) {
24524 transmit_response(pvt, "400 Bad Request", req);
24525 }
24526 return res;
24527 }
24528
24529 #endif
24530
24531 static int handle_sip_publish_initial(struct sip_pvt *p, struct sip_request *req, struct event_state_compositor *esc, const int expires)
24532 {
24533 struct sip_esc_entry *esc_entry = create_esc_entry(esc, req, expires);
24534 int res = 0;
24535
24536 if (!esc_entry) {
24537 transmit_response(p, "503 Internal Server Failure", req);
24538 return -1;
24539 }
24540
24541 if (esc->callbacks->initial_handler) {
24542 res = esc->callbacks->initial_handler(p, req, esc, esc_entry);
24543 }
24544
24545 if (!res) {
24546 transmit_response_with_sip_etag(p, "200 OK", req, esc_entry, 0);
24547 }
24548
24549 ao2_ref(esc_entry, -1);
24550 return res;
24551 }
24552
24553 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)
24554 {
24555 struct sip_esc_entry *esc_entry = get_esc_entry(etag, esc);
24556 int expires_ms = expires * 1000;
24557 int res = 0;
24558
24559 if (!esc_entry) {
24560 transmit_response(p, "412 Conditional Request Failed", req);
24561 return -1;
24562 }
24563
24564 AST_SCHED_REPLACE_UNREF(esc_entry->sched_id, sched, expires_ms, publish_expire, esc_entry,
24565 ao2_ref(_data, -1),
24566 ao2_ref(esc_entry, -1),
24567 ao2_ref(esc_entry, +1));
24568
24569 if (esc->callbacks->refresh_handler) {
24570 res = esc->callbacks->refresh_handler(p, req, esc, esc_entry);
24571 }
24572
24573 if (!res) {
24574 transmit_response_with_sip_etag(p, "200 OK", req, esc_entry, 1);
24575 }
24576
24577 ao2_ref(esc_entry, -1);
24578 return res;
24579 }
24580
24581 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)
24582 {
24583 struct sip_esc_entry *esc_entry = get_esc_entry(etag, esc);
24584 int expires_ms = expires * 1000;
24585 int res = 0;
24586
24587 if (!esc_entry) {
24588 transmit_response(p, "412 Conditional Request Failed", req);
24589 return -1;
24590 }
24591
24592 AST_SCHED_REPLACE_UNREF(esc_entry->sched_id, sched, expires_ms, publish_expire, esc_entry,
24593 ao2_ref(_data, -1),
24594 ao2_ref(esc_entry, -1),
24595 ao2_ref(esc_entry, +1));
24596
24597 if (esc->callbacks->modify_handler) {
24598 res = esc->callbacks->modify_handler(p, req, esc, esc_entry);
24599 }
24600
24601 if (!res) {
24602 transmit_response_with_sip_etag(p, "200 OK", req, esc_entry, 1);
24603 }
24604
24605 ao2_ref(esc_entry, -1);
24606 return res;
24607 }
24608
24609 static int handle_sip_publish_remove(struct sip_pvt *p, struct sip_request *req, struct event_state_compositor *esc, const char * const etag)
24610 {
24611 struct sip_esc_entry *esc_entry = get_esc_entry(etag, esc);
24612 int res = 0;
24613
24614 if (!esc_entry) {
24615 transmit_response(p, "412 Conditional Request Failed", req);
24616 return -1;
24617 }
24618
24619 AST_SCHED_DEL(sched, esc_entry->sched_id);
24620
24621 ao2_ref(esc_entry, -1);
24622
24623 if (esc->callbacks->remove_handler) {
24624 res = esc->callbacks->remove_handler(p, req, esc, esc_entry);
24625 }
24626
24627 if (!res) {
24628 transmit_response_with_sip_etag(p, "200 OK", req, esc_entry, 1);
24629 }
24630
24631
24632 ao2_unlink(esc->compositor, esc_entry);
24633 ao2_ref(esc_entry, -1);
24634 return res;
24635 }
24636
24637 static int handle_request_publish(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const uint32_t seqno, const char *uri)
24638 {
24639 const char *etag = get_header(req, "SIP-If-Match");
24640 const char *event = get_header(req, "Event");
24641 struct event_state_compositor *esc;
24642 enum sip_publish_type publish_type;
24643 const char *expires_str = get_header(req, "Expires");
24644 int expires_int;
24645 int auth_result;
24646 int handler_result = -1;
24647
24648 if (ast_strlen_zero(event)) {
24649 transmit_response(p, "489 Bad Event", req);
24650 pvt_set_needdestroy(p, "missing Event: header");
24651 return -1;
24652 }
24653
24654 if (!(esc = get_esc(event))) {
24655 transmit_response(p, "489 Bad Event", req);
24656 pvt_set_needdestroy(p, "unknown event package in publish");
24657 return -1;
24658 }
24659
24660 auth_result = check_user(p, req, SIP_PUBLISH, uri, XMIT_RELIABLE, addr);
24661 if (auth_result == AUTH_CHALLENGE_SENT) {
24662 p->lastinvite = seqno;
24663 return 0;
24664 } else if (auth_result < 0) {
24665 if (auth_result == AUTH_FAKE_AUTH) {
24666 ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", get_header(req, "From"));
24667 transmit_fake_auth_response(p, SIP_INVITE, req, XMIT_RELIABLE);
24668 } else {
24669 ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", get_header(req, "From"));
24670 transmit_response_reliable(p, "403 Forbidden", req);
24671 }
24672 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
24673 ast_string_field_set(p, theirtag, NULL);
24674 return 0;
24675 } else if (auth_result == AUTH_SUCCESSFUL && p->lastinvite) {
24676
24677 __sip_ack(p, p->lastinvite, 1, 0);
24678 }
24679
24680 publish_type = determine_sip_publish_type(req, event, etag, expires_str, &expires_int);
24681
24682 if (expires_int > max_expiry) {
24683 expires_int = max_expiry;
24684 } else if (expires_int < min_expiry && expires_int > 0) {
24685 transmit_response_with_minexpires(p, "423 Interval too small", req);
24686 pvt_set_needdestroy(p, "Expires is less that the min expires allowed.");
24687 return 0;
24688 }
24689 p->expiry = expires_int;
24690
24691
24692
24693
24694 switch (publish_type) {
24695 case SIP_PUBLISH_UNKNOWN:
24696 transmit_response(p, "400 Bad Request", req);
24697 break;
24698 case SIP_PUBLISH_INITIAL:
24699 handler_result = handle_sip_publish_initial(p, req, esc, expires_int);
24700 break;
24701 case SIP_PUBLISH_REFRESH:
24702 handler_result = handle_sip_publish_refresh(p, req, esc, etag, expires_int);
24703 break;
24704 case SIP_PUBLISH_MODIFY:
24705 handler_result = handle_sip_publish_modify(p, req, esc, etag, expires_int);
24706 break;
24707 case SIP_PUBLISH_REMOVE:
24708 handler_result = handle_sip_publish_remove(p, req, esc, etag);
24709 break;
24710 default:
24711 transmit_response(p, "400 Impossible Condition", req);
24712 break;
24713 }
24714 if (!handler_result && p->expiry > 0) {
24715 sip_scheddestroy(p, (p->expiry + 10) * 1000);
24716 } else {
24717 pvt_set_needdestroy(p, "forcing expiration");
24718 }
24719
24720 return handler_result;
24721 }
24722
24723
24724
24725
24726
24727
24728
24729 static void add_peer_mwi_subs(struct sip_peer *peer)
24730 {
24731 struct sip_mailbox *mailbox;
24732
24733 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
24734 if (mailbox->event_sub) {
24735 ast_event_unsubscribe(mailbox->event_sub);
24736 }
24737
24738 mailbox->event_sub = ast_event_subscribe(AST_EVENT_MWI, mwi_event_cb, "SIP mbox event", peer,
24739 AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox->mailbox,
24740 AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, S_OR(mailbox->context, "default"),
24741 AST_EVENT_IE_END);
24742 }
24743 }
24744
24745 static int handle_cc_subscribe(struct sip_pvt *p, struct sip_request *req)
24746 {
24747 const char *uri = REQ_OFFSET_TO_STR(req, rlPart2);
24748 char *param_separator;
24749 struct ast_cc_agent *agent;
24750 struct sip_cc_agent_pvt *agent_pvt;
24751 const char *expires_str = get_header(req, "Expires");
24752 int expires = -1;
24753
24754 if (!ast_strlen_zero(expires_str)) {
24755 sscanf(expires_str, "%d", &expires);
24756 }
24757
24758 if ((param_separator = strchr(uri, ';'))) {
24759 *param_separator = '\0';
24760 }
24761
24762 p->subscribed = CALL_COMPLETION;
24763
24764 if (!(agent = find_sip_cc_agent_by_subscribe_uri(uri))) {
24765 if (!expires) {
24766
24767
24768
24769
24770
24771
24772 transmit_response(p, "200 OK", req);
24773 return 0;
24774 }
24775 ast_log(LOG_WARNING, "Invalid URI '%s' in CC subscribe\n", uri);
24776 transmit_response(p, "404 Not Found", req);
24777 return -1;
24778 }
24779
24780 agent_pvt = agent->private_data;
24781
24782 if (!expires) {
24783
24784
24785
24786 ast_cc_failed(agent->core_id, "CC is being canceled by %s", agent->device_name);
24787 transmit_response(p, "200 OK", req);
24788 ao2_ref(agent, -1);
24789 return 0;
24790 }
24791
24792 agent_pvt->subscribe_pvt = dialog_ref(p, "SIP CC agent gains reference to subscription dialog");
24793 ast_cc_agent_accept_request(agent->core_id, "SIP caller %s has requested CC via SUBSCRIBE",
24794 agent->device_name);
24795
24796
24797
24798
24799 ao2_ref(agent, -1);
24800 return 0;
24801 }
24802
24803
24804 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e)
24805 {
24806 int gotdest = 0;
24807 int res = 0;
24808 int firststate;
24809 struct sip_peer *authpeer = NULL;
24810 const char *eventheader = get_header(req, "Event");
24811 int resubscribe = (p->subscribed != NONE) && !req->ignore;
24812 char *event_end;
24813 ptrdiff_t event_len = 0;
24814
24815 if (p->initreq.headers) {
24816
24817 if (p->initreq.method != SIP_SUBSCRIBE) {
24818
24819
24820 transmit_response(p, "403 Forbidden (within dialog)", req);
24821
24822 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);
24823 return 0;
24824 } else if (req->debug) {
24825 if (resubscribe)
24826 ast_debug(1, "Got a re-subscribe on existing subscription %s\n", p->callid);
24827 else
24828 ast_debug(1, "Got a new subscription %s (possibly with auth) or retransmission\n", p->callid);
24829 }
24830 }
24831
24832
24833
24834
24835 if (!sip_cfg.allowsubscribe) {
24836 transmit_response(p, "403 Forbidden (policy)", req);
24837 pvt_set_needdestroy(p, "forbidden");
24838 return 0;
24839 }
24840
24841 if (!req->ignore && !resubscribe) {
24842 const char *to = get_header(req, "To");
24843 char totag[128];
24844 set_pvt_allowed_methods(p, req);
24845
24846
24847 if (!ast_strlen_zero(to) && gettag(req, "To", totag, sizeof(totag))) {
24848 if (req->debug)
24849 ast_verbose("Received resubscription for a dialog we no longer know about. Telling remote side to subscribe again.\n");
24850 transmit_response(p, "481 Subscription does not exist", req);
24851 pvt_set_needdestroy(p, "subscription does not exist");
24852 return 0;
24853 }
24854
24855
24856 if (req->debug)
24857 ast_verbose("Creating new subscription\n");
24858
24859 copy_request(&p->initreq, req);
24860 if (sipdebug)
24861 ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
24862 check_via(p, req);
24863 build_route(p, req, 0, 0);
24864 } else if (req->debug && req->ignore)
24865 ast_verbose("Ignoring this SUBSCRIBE request\n");
24866
24867
24868 if (ast_strlen_zero(eventheader)) {
24869 transmit_response(p, "489 Bad Event", req);
24870 ast_debug(2, "Received SIP subscribe for unknown event package: <none>\n");
24871 pvt_set_needdestroy(p, "unknown event package in subscribe");
24872 return 0;
24873 }
24874
24875 event_end = strchr(eventheader, ';');
24876 if (event_end) {
24877 event_len = event_end - eventheader;
24878 }
24879
24880
24881
24882
24883 if (p->subscribed == NONE || resubscribe) {
24884 res = check_user_full(p, req, SIP_SUBSCRIBE, e, 0, addr, &authpeer);
24885
24886
24887 if (res == AUTH_CHALLENGE_SENT)
24888 return 0;
24889 if (res != AUTH_SUCCESSFUL) {
24890 if (res == AUTH_FAKE_AUTH) {
24891 ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", get_header(req, "From"));
24892 transmit_fake_auth_response(p, SIP_SUBSCRIBE, req, XMIT_UNRELIABLE);
24893 } else {
24894 ast_log(LOG_NOTICE, "Failed to authenticate device %s for SUBSCRIBE\n", get_header(req, "From"));
24895 transmit_response_reliable(p, "403 Forbidden", req);
24896 }
24897
24898 pvt_set_needdestroy(p, "authentication failed");
24899 return 0;
24900 }
24901 }
24902
24903
24904
24905
24906
24907
24908 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
24909 transmit_response(p, "403 Forbidden (policy)", req);
24910 pvt_set_needdestroy(p, "subscription not allowed");
24911 if (authpeer) {
24912 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 1)");
24913 }
24914 return 0;
24915 }
24916
24917 if (strncmp(eventheader, "message-summary", MAX(event_len, 15)) && strncmp(eventheader, "call-completion", MAX(event_len, 15))) {
24918
24919 gotdest = get_destination(p, NULL, NULL);
24920 }
24921
24922
24923 parse_ok_contact(p, req);
24924
24925 build_contact(p);
24926 if (gotdest != SIP_GET_DEST_EXTEN_FOUND) {
24927 if (gotdest == SIP_GET_DEST_INVALID_URI) {
24928 transmit_response(p, "416 Unsupported URI scheme", req);
24929 } else {
24930 transmit_response(p, "404 Not Found", req);
24931 }
24932 pvt_set_needdestroy(p, "subscription target not found");
24933 if (authpeer) {
24934 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
24935 }
24936 return 0;
24937 }
24938
24939
24940 if (ast_strlen_zero(p->tag))
24941 make_our_tag(p);
24942
24943 if (!strncmp(eventheader, "presence", MAX(event_len, 8)) || !strncmp(eventheader, "dialog", MAX(event_len, 6))) {
24944 unsigned int pidf_xml;
24945 const char *accept;
24946 int start = 0;
24947 enum subscriptiontype subscribed = NONE;
24948 const char *unknown_acceptheader = NULL;
24949
24950
24951 accept = __get_header(req, "Accept", &start);
24952 while ((subscribed == NONE) && !ast_strlen_zero(accept)) {
24953 pidf_xml = strstr(accept, "application/pidf+xml") ? 1 : 0;
24954
24955
24956
24957 if (pidf_xml && strstr(p->useragent, "Polycom")) {
24958 subscribed = XPIDF_XML;
24959 } else if (pidf_xml) {
24960 subscribed = PIDF_XML;
24961 } else if (strstr(accept, "application/dialog-info+xml")) {
24962 subscribed = DIALOG_INFO_XML;
24963
24964 } else if (strstr(accept, "application/cpim-pidf+xml")) {
24965 subscribed = CPIM_PIDF_XML;
24966 } else if (strstr(accept, "application/xpidf+xml")) {
24967 subscribed = XPIDF_XML;
24968 } else {
24969 unknown_acceptheader = accept;
24970 }
24971
24972 accept = __get_header(req, "Accept", &start);
24973 }
24974
24975 if (!start) {
24976 if (p->subscribed == NONE) {
24977 transmit_response(p, "489 Bad Event", req);
24978 ast_log(LOG_WARNING,"SUBSCRIBE failure: no Accept header: pvt: "
24979 "stateid: %d, laststate: %d, dialogver: %u, subscribecont: "
24980 "'%s', subscribeuri: '%s'\n",
24981 p->stateid,
24982 p->laststate,
24983 p->dialogver,
24984 p->subscribecontext,
24985 p->subscribeuri);
24986 pvt_set_needdestroy(p, "no Accept header");
24987 if (authpeer) {
24988 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
24989 }
24990 return 0;
24991 }
24992
24993
24994 } else if (subscribed == NONE) {
24995
24996 char mybuf[200];
24997 if (!ast_strlen_zero(unknown_acceptheader)) {
24998 snprintf(mybuf, sizeof(mybuf), "489 Bad Event (format %s)", unknown_acceptheader);
24999 } else {
25000 snprintf(mybuf, sizeof(mybuf), "489 Bad Event");
25001 }
25002 transmit_response(p, mybuf, req);
25003 ast_log(LOG_WARNING,"SUBSCRIBE failure: unrecognized format:"
25004 "'%s' pvt: subscribed: %d, stateid: %d, laststate: %d,"
25005 "dialogver: %u, subscribecont: '%s', subscribeuri: '%s'\n",
25006 unknown_acceptheader,
25007 (int)p->subscribed,
25008 p->stateid,
25009 p->laststate,
25010 p->dialogver,
25011 p->subscribecontext,
25012 p->subscribeuri);
25013 pvt_set_needdestroy(p, "unrecognized format");
25014 if (authpeer) {
25015 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
25016 }
25017 return 0;
25018 } else {
25019 p->subscribed = subscribed;
25020 }
25021 } else if (!strncmp(eventheader, "message-summary", MAX(event_len, 15))) {
25022 int start = 0;
25023 int found_supported = 0;
25024 const char *acceptheader;
25025
25026 acceptheader = __get_header(req, "Accept", &start);
25027 while (!found_supported && !ast_strlen_zero(acceptheader)) {
25028 found_supported = strcmp(acceptheader, "application/simple-message-summary") ? 0 : 1;
25029 if (!found_supported && (option_debug > 2)) {
25030 ast_log(LOG_DEBUG, "Received SIP mailbox subscription for unknown format: %s\n", acceptheader);
25031 }
25032 acceptheader = __get_header(req, "Accept", &start);
25033 }
25034 if (start && !found_supported) {
25035
25036 transmit_response(p, "406 Not Acceptable", req);
25037 ast_debug(2, "Received SIP mailbox subscription for unknown format: %s\n", acceptheader);
25038 pvt_set_needdestroy(p, "unknown format");
25039 if (authpeer) {
25040 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 3)");
25041 }
25042 return 0;
25043 }
25044
25045
25046
25047
25048
25049 if (!authpeer || AST_LIST_EMPTY(&authpeer->mailboxes)) {
25050 if (!authpeer) {
25051 transmit_response(p, "404 Not found", req);
25052 } else {
25053 transmit_response(p, "404 Not found (no mailbox)", req);
25054 ast_log(LOG_NOTICE, "Received SIP subscribe for peer without mailbox: %s\n", S_OR(authpeer->name, ""));
25055 }
25056 pvt_set_needdestroy(p, "received 404 response");
25057 if (authpeer) {
25058 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 3)");
25059 }
25060 return 0;
25061 }
25062
25063 p->subscribed = MWI_NOTIFICATION;
25064 if (ast_test_flag(&authpeer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY)) {
25065 ao2_unlock(p);
25066 add_peer_mwi_subs(authpeer);
25067 ao2_lock(p);
25068 }
25069 if (authpeer->mwipvt != p) {
25070
25071 if (authpeer->mwipvt) {
25072 dialog_unlink_all(authpeer->mwipvt);
25073 authpeer->mwipvt = dialog_unref(authpeer->mwipvt, "unref dialog authpeer->mwipvt");
25074 }
25075 authpeer->mwipvt = dialog_ref(p, "setting peers' mwipvt to p");
25076 }
25077 if (p->relatedpeer != authpeer) {
25078 if (p->relatedpeer) {
25079 unref_peer(p->relatedpeer, "Unref previously stored relatedpeer ptr");
25080 }
25081 p->relatedpeer = ref_peer(authpeer, "setting dialog's relatedpeer pointer");
25082 }
25083
25084 } else if (!strncmp(eventheader, "call-completion", MAX(event_len, 15))) {
25085 handle_cc_subscribe(p, req);
25086 } else {
25087 transmit_response(p, "489 Bad Event", req);
25088 ast_debug(2, "Received SIP subscribe for unknown event package: %s\n", eventheader);
25089 pvt_set_needdestroy(p, "unknown event package");
25090 if (authpeer) {
25091 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 5)");
25092 }
25093 return 0;
25094 }
25095
25096
25097 if (p->subscribed != MWI_NOTIFICATION && p->subscribed != CALL_COMPLETION && !resubscribe) {
25098 if (p->stateid != -1) {
25099 ast_extension_state_del(p->stateid, cb_extensionstate);
25100 }
25101 dialog_ref(p, "copying dialog ptr into extension state struct");
25102 p->stateid = ast_extension_state_add_destroy(p->context, p->exten,
25103 cb_extensionstate, cb_extensionstate_destroy, p);
25104 if (p->stateid == -1) {
25105 dialog_unref(p, "copying dialog ptr into extension state struct failed");
25106 }
25107 }
25108
25109 if (!req->ignore) {
25110 p->lastinvite = seqno;
25111 }
25112 if (!p->needdestroy) {
25113 p->expiry = atoi(get_header(req, "Expires"));
25114
25115
25116 if (p->expiry > max_expiry) {
25117 p->expiry = max_expiry;
25118 } else if (p->expiry < min_expiry && p->expiry > 0) {
25119 transmit_response_with_minexpires(p, "423 Interval too small", req);
25120 ast_log(LOG_WARNING, "Received subscription for extension \"%s\" context \"%s\" "
25121 "with Expire header less that 'minexpire' limit. Received \"Expire: %d\" min is %d\n",
25122 p->exten, p->context, p->expiry, min_expiry);
25123 pvt_set_needdestroy(p, "Expires is less that the min expires allowed.");
25124 if (authpeer) {
25125 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 6)");
25126 }
25127 return 0;
25128 }
25129
25130 if (sipdebug) {
25131 const char *action = p->expiry > 0 ? "Adding" : "Removing";
25132 if (p->subscribed == MWI_NOTIFICATION && p->relatedpeer) {
25133 ast_debug(2, "%s subscription for mailbox notification - peer %s\n",
25134 action, p->relatedpeer->name);
25135 } else if (p->subscribed == CALL_COMPLETION) {
25136 ast_debug(2, "%s CC subscription for peer %s\n", action, p->username);
25137 } else {
25138 ast_debug(2, "%s subscription for extension %s context %s for peer %s\n",
25139 action, p->exten, p->context, p->username);
25140 }
25141 }
25142 if (p->autokillid > -1 && sip_cancel_destroy(p))
25143 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
25144 if (p->expiry > 0)
25145 sip_scheddestroy(p, (p->expiry + 10) * 1000);
25146
25147 if (p->subscribed == MWI_NOTIFICATION) {
25148 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
25149 transmit_response(p, "200 OK", req);
25150 if (p->relatedpeer) {
25151 struct sip_peer *peer = p->relatedpeer;
25152 ref_peer(peer, "ensure a peer ref is held during MWI sending");
25153 ao2_unlock(p);
25154 sip_send_mwi_to_peer(peer, 0);
25155 ao2_lock(p);
25156 unref_peer(peer, "release a peer ref now that MWI is sent");
25157 }
25158 } else if (p->subscribed != CALL_COMPLETION) {
25159 sip_pvt_unlock(p);
25160 firststate = ast_extension_state(NULL, p->context, p->exten);
25161 sip_pvt_lock(p);
25162
25163 if (firststate < 0) {
25164 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));
25165 transmit_response(p, "404 Not found", req);
25166 pvt_set_needdestroy(p, "no extension for SUBSCRIBE");
25167 if (authpeer) {
25168 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 6)");
25169 }
25170 return 0;
25171 }
25172 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
25173 transmit_response(p, "200 OK", req);
25174 transmit_state_notify(p, firststate, 1, FALSE);
25175 append_history(p, "Subscribestatus", "%s", ast_extension_state2str(firststate));
25176
25177 ast_string_field_build(p, subscribeuri, "%s@%s", p->exten, p->context);
25178
25179
25180 }
25181 if (!p->expiry) {
25182 pvt_set_needdestroy(p, "forcing expiration");
25183 }
25184 }
25185
25186 if (authpeer) {
25187 unref_peer(authpeer, "unref pointer into (*authpeer)");
25188 }
25189 return 1;
25190 }
25191
25192
25193 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e)
25194 {
25195 enum check_auth_result res;
25196
25197
25198
25199 if (p->initreq.headers && p->initreq.method != SIP_REGISTER) {
25200 ast_log(LOG_WARNING, "Ignoring spurious REGISTER with Call-ID: %s\n", p->callid);
25201 return -1;
25202 }
25203
25204
25205 copy_request(&p->initreq, req);
25206 if (sipdebug)
25207 ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
25208 check_via(p, req);
25209 if ((res = register_verify(p, addr, req, e)) < 0) {
25210 const char *reason;
25211
25212 switch (res) {
25213 case AUTH_SECRET_FAILED:
25214 reason = "Wrong password";
25215 break;
25216 case AUTH_USERNAME_MISMATCH:
25217 reason = "Username/auth name mismatch";
25218 break;
25219 case AUTH_NOT_FOUND:
25220 reason = "No matching peer found";
25221 break;
25222 case AUTH_UNKNOWN_DOMAIN:
25223 reason = "Not a local domain";
25224 break;
25225 case AUTH_PEER_NOT_DYNAMIC:
25226 reason = "Peer is not supposed to register";
25227 break;
25228 case AUTH_ACL_FAILED:
25229 reason = "Device does not match ACL";
25230 break;
25231 case AUTH_BAD_TRANSPORT:
25232 reason = "Device not configured to use this transport type";
25233 break;
25234 default:
25235 reason = "Unknown failure";
25236 break;
25237 }
25238 ast_log(LOG_NOTICE, "Registration from '%s' failed for '%s' - %s\n",
25239 get_header(req, "To"), ast_sockaddr_stringify(addr),
25240 reason);
25241 append_history(p, "RegRequest", "Failed : Account %s : %s", get_header(req, "To"), reason);
25242 } else {
25243 req->authenticated = 1;
25244 append_history(p, "RegRequest", "Succeeded : Account %s", get_header(req, "To"));
25245 }
25246
25247 if (res < 1) {
25248
25249
25250 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
25251 }
25252 return res;
25253 }
25254
25255
25256
25257
25258
25259
25260
25261
25262 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int *recount, int *nounlock)
25263 {
25264
25265
25266 const char *cmd;
25267 const char *cseq;
25268 const char *useragent;
25269 const char *via;
25270 const char *callid;
25271 int via_pos = 0;
25272 uint32_t seqno;
25273 int len;
25274 int respid;
25275 int res = 0;
25276 int debug = sip_debug_test_pvt(p);
25277 const char *e;
25278 int error = 0;
25279 int oldmethod = p->method;
25280 int acked = 0;
25281
25282
25283
25284
25285 cseq = get_header(req, "Cseq");
25286 cmd = REQ_OFFSET_TO_STR(req, header[0]);
25287
25288 via = __get_header(req, "Via", &via_pos);
25289
25290 callid = get_header(req, "Call-ID");
25291
25292
25293 if (ast_strlen_zero(cmd) || ast_strlen_zero(cseq) || ast_strlen_zero(via)) {
25294 ast_log(LOG_ERROR, "Dropping this SIP message with Call-ID '%s', it's incomplete.\n", callid);
25295 error = 1;
25296 }
25297 if (!error && sscanf(cseq, "%30u%n", &seqno, &len) != 1) {
25298 ast_log(LOG_ERROR, "No seqno in '%s'. Dropping incomplete message.\n", cmd);
25299 error = 1;
25300 }
25301 if (error) {
25302 if (!p->initreq.headers) {
25303 pvt_set_needdestroy(p, "no headers");
25304 }
25305 return -1;
25306 }
25307
25308
25309 cmd = REQ_OFFSET_TO_STR(req, rlPart1);
25310 e = ast_skip_blanks(REQ_OFFSET_TO_STR(req, rlPart2));
25311
25312
25313 useragent = get_header(req, "User-Agent");
25314 if (!ast_strlen_zero(useragent))
25315 ast_string_field_set(p, useragent, useragent);
25316
25317
25318 if (req->method == SIP_RESPONSE) {
25319
25320
25321
25322
25323
25324
25325 if (ast_strlen_zero(e)) {
25326 return 0;
25327 }
25328 if (sscanf(e, "%30d %n", &respid, &len) != 1) {
25329 ast_log(LOG_WARNING, "Invalid response: '%s'\n", e);
25330 return 0;
25331 }
25332 if (respid <= 0) {
25333 ast_log(LOG_WARNING, "Invalid SIP response code: '%d'\n", respid);
25334 return 0;
25335 }
25336
25337
25338
25339 if (!ast_strlen_zero(__get_header(req, "via", &via_pos))) {
25340 ast_log(LOG_WARNING, "Misrouted SIP response '%s' with Call-ID '%s', too many vias\n", e, callid);
25341 return 0;
25342 }
25343 if (p->ocseq && (p->ocseq < seqno)) {
25344 ast_debug(1, "Ignoring out of order response %u (expecting %u)\n", seqno, p->ocseq);
25345 return -1;
25346 } else {
25347 char causevar[256], causeval[256];
25348
25349 if ((respid == 200) || ((respid >= 300) && (respid <= 399))) {
25350 extract_uri(p, req);
25351 }
25352
25353 handle_response(p, respid, e + len, req, seqno);
25354
25355 if (global_store_sip_cause && p->owner) {
25356 struct ast_channel *owner = p->owner;
25357
25358 snprintf(causevar, sizeof(causevar), "MASTER_CHANNEL(HASH(SIP_CAUSE,%s))", owner->name);
25359 snprintf(causeval, sizeof(causeval), "SIP %s", REQ_OFFSET_TO_STR(req, rlPart2));
25360
25361 ast_channel_ref(owner);
25362 sip_pvt_unlock(p);
25363 ast_channel_unlock(owner);
25364 *nounlock = 1;
25365 pbx_builtin_setvar_helper(owner, causevar, causeval);
25366 ast_channel_unref(owner);
25367 sip_pvt_lock(p);
25368 }
25369 }
25370 return 0;
25371 }
25372
25373
25374
25375
25376
25377 p->method = req->method;
25378 ast_debug(4, "**** Received %s (%d) - Command in SIP %s\n", sip_methods[p->method].text, sip_methods[p->method].id, cmd);
25379
25380 if (p->icseq && (p->icseq > seqno) ) {
25381 if (p->pendinginvite && seqno == p->pendinginvite && (req->method == SIP_ACK || req->method == SIP_CANCEL)) {
25382 ast_debug(2, "Got CANCEL or ACK on INVITE with transactions in between.\n");
25383 } else {
25384 ast_debug(1, "Ignoring too old SIP packet packet %u (expecting >= %u)\n", seqno, p->icseq);
25385 if (req->method == SIP_INVITE) {
25386 unsigned int ran = (ast_random() % 10) + 1;
25387 char seconds[4];
25388 snprintf(seconds, sizeof(seconds), "%u", ran);
25389 transmit_response_with_retry_after(p, "500 Server error", req, seconds);
25390 } else if (req->method != SIP_ACK) {
25391 transmit_response(p, "500 Server error", req);
25392 }
25393 return -1;
25394 }
25395 } else if (p->icseq &&
25396 p->icseq == seqno &&
25397 req->method != SIP_ACK &&
25398 (p->method != SIP_CANCEL || p->alreadygone)) {
25399
25400
25401
25402 req->ignore = 1;
25403 ast_debug(3, "Ignoring SIP message because of retransmit (%s Seqno %u, ours %u)\n", sip_methods[p->method].text, p->icseq, seqno);
25404 }
25405
25406
25407
25408 if (!p->pendinginvite && (req->method == SIP_CANCEL)) {
25409 transmit_response(p, "481 Call/Transaction Does Not Exist", req);
25410 return res;
25411 }
25412
25413 if (seqno >= p->icseq)
25414
25415
25416
25417 p->icseq = seqno;
25418
25419
25420 if (ast_strlen_zero(p->theirtag)) {
25421 char tag[128];
25422
25423 gettag(req, "From", tag, sizeof(tag));
25424 ast_string_field_set(p, theirtag, tag);
25425 }
25426 snprintf(p->lastmsg, sizeof(p->lastmsg), "Rx: %s", cmd);
25427
25428 if (sip_cfg.pedanticsipchecking) {
25429
25430
25431
25432
25433 if (!p->initreq.headers && req->has_to_tag) {
25434
25435 if (!req->ignore && req->method == SIP_INVITE) {
25436
25437
25438
25439
25440
25441
25442 char totag[128];
25443 gettag(req, "To", totag, sizeof(totag));
25444 ast_string_field_set(p, tag, totag);
25445 p->pendinginvite = p->icseq;
25446 transmit_response_reliable(p, "481 Call/Transaction Does Not Exist", req);
25447
25448 return res;
25449 } else if (req->method != SIP_ACK) {
25450 transmit_response(p, "481 Call/Transaction Does Not Exist", req);
25451 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
25452 return res;
25453 }
25454
25455 }
25456 }
25457
25458 if (!e && (p->method == SIP_INVITE || p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER || p->method == SIP_NOTIFY || p->method == SIP_PUBLISH)) {
25459 transmit_response(p, "400 Bad request", req);
25460 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
25461 return -1;
25462 }
25463
25464
25465 switch (p->method) {
25466 case SIP_OPTIONS:
25467 res = handle_request_options(p, req, addr, e);
25468 break;
25469 case SIP_INVITE:
25470 res = handle_request_invite(p, req, debug, seqno, addr, recount, e, nounlock);
25471 break;
25472 case SIP_REFER:
25473 res = handle_request_refer(p, req, debug, seqno, nounlock);
25474 break;
25475 case SIP_CANCEL:
25476 res = handle_request_cancel(p, req);
25477 break;
25478 case SIP_BYE:
25479 res = handle_request_bye(p, req);
25480 break;
25481 case SIP_MESSAGE:
25482 res = handle_request_message(p, req);
25483 break;
25484 case SIP_PUBLISH:
25485 res = handle_request_publish(p, req, addr, seqno, e);
25486 break;
25487 case SIP_SUBSCRIBE:
25488 res = handle_request_subscribe(p, req, addr, seqno, e);
25489 break;
25490 case SIP_REGISTER:
25491 res = handle_request_register(p, req, addr, e);
25492 break;
25493 case SIP_INFO:
25494 if (req->debug)
25495 ast_verbose("Receiving INFO!\n");
25496 if (!req->ignore)
25497 handle_request_info(p, req);
25498 else
25499 transmit_response(p, "200 OK", req);
25500 break;
25501 case SIP_NOTIFY:
25502 res = handle_request_notify(p, req, addr, seqno, e);
25503 break;
25504 case SIP_UPDATE:
25505 res = handle_request_update(p, req);
25506 break;
25507 case SIP_ACK:
25508
25509 if (seqno == p->pendinginvite) {
25510 p->invitestate = INV_TERMINATED;
25511 p->pendinginvite = 0;
25512 acked = __sip_ack(p, seqno, 1 , 0);
25513 if (find_sdp(req)) {
25514 if (process_sdp(p, req, SDP_T38_NONE)) {
25515 return -1;
25516 }
25517 if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
25518 ast_queue_control(p->owner, AST_CONTROL_SRCCHANGE);
25519 }
25520 }
25521 check_pendings(p);
25522 } else if (p->glareinvite == seqno) {
25523
25524 p->glareinvite = 0;
25525 acked = __sip_ack(p, seqno, 1, 0);
25526 }
25527 if (!acked) {
25528
25529
25530 p->method = oldmethod;
25531 }
25532 if (!p->lastinvite && ast_strlen_zero(p->randdata)) {
25533 pvt_set_needdestroy(p, "unmatched ACK");
25534 }
25535 break;
25536 default:
25537 transmit_response_with_allow(p, "501 Method Not Implemented", req, 0);
25538 ast_log(LOG_NOTICE, "Unknown SIP command '%s' from '%s'\n",
25539 cmd, ast_sockaddr_stringify(&p->sa));
25540
25541 if (!p->initreq.headers) {
25542 pvt_set_needdestroy(p, "unimplemented method");
25543 }
25544 break;
25545 }
25546 return res;
25547 }
25548
25549
25550
25551
25552
25553
25554 static int sipsock_read(int *id, int fd, short events, void *ignore)
25555 {
25556 struct sip_request req;
25557 struct ast_sockaddr addr;
25558 int res;
25559 static char readbuf[65535];
25560
25561 memset(&req, 0, sizeof(req));
25562 res = ast_recvfrom(fd, readbuf, sizeof(readbuf) - 1, 0, &addr);
25563 if (res < 0) {
25564 #if !defined(__FreeBSD__)
25565 if (errno == EAGAIN)
25566 ast_log(LOG_NOTICE, "SIP: Received packet with bad UDP checksum\n");
25567 else
25568 #endif
25569 if (errno != ECONNREFUSED)
25570 ast_log(LOG_WARNING, "Recv error: %s\n", strerror(errno));
25571 return 1;
25572 }
25573
25574 readbuf[res] = '\0';
25575
25576 if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
25577 return 1;
25578 }
25579
25580 if (ast_str_set(&req.data, 0, "%s", readbuf) == AST_DYNSTR_BUILD_FAILED) {
25581 return -1;
25582 }
25583
25584 req.socket.fd = sipsock;
25585 set_socket_transport(&req.socket, SIP_TRANSPORT_UDP);
25586 req.socket.tcptls_session = NULL;
25587 req.socket.port = htons(ast_sockaddr_port(&bindaddr));
25588
25589 handle_request_do(&req, &addr);
25590 deinit_req(&req);
25591
25592 return 1;
25593 }
25594
25595
25596
25597
25598
25599 static int handle_request_do(struct sip_request *req, struct ast_sockaddr *addr)
25600 {
25601 struct sip_pvt *p;
25602 struct ast_channel *owner_chan_ref = NULL;
25603 int recount = 0;
25604 int nounlock = 0;
25605
25606 if (sip_debug_test_addr(addr))
25607 req->debug = 1;
25608 if (sip_cfg.pedanticsipchecking)
25609 lws2sws(req->data);
25610 if (req->debug) {
25611 ast_verbose("\n<--- SIP read from %s:%s --->\n%s\n<------------->\n",
25612 get_transport(req->socket.type), ast_sockaddr_stringify(addr), req->data->str);
25613 }
25614
25615 if (parse_request(req) == -1) {
25616 ast_str_reset(req->data);
25617 return 1;
25618 }
25619 req->method = find_sip_method(REQ_OFFSET_TO_STR(req, rlPart1));
25620
25621 if (req->debug)
25622 ast_verbose("--- (%d headers %d lines)%s ---\n", req->headers, req->lines, (req->headers + req->lines == 0) ? " Nat keepalive" : "");
25623
25624 if (req->headers < 2) {
25625 ast_str_reset(req->data);
25626 return 1;
25627 }
25628
25629
25630 ast_mutex_lock(&netlock);
25631
25632
25633 p = find_call(req, addr, req->method);
25634 if (p == NULL) {
25635 ast_debug(1, "Invalid SIP message - rejected , no callid, len %zu\n", ast_str_strlen(req->data));
25636 ast_mutex_unlock(&netlock);
25637 return 1;
25638 }
25639
25640
25641
25642 owner_chan_ref = sip_pvt_lock_full(p);
25643
25644 copy_socket_data(&p->socket, &req->socket);
25645 ast_sockaddr_copy(&p->recv, addr);
25646
25647
25648 if (p->owner) {
25649 req->authenticated = 1;
25650 }
25651
25652 if (p->do_history)
25653 append_history(p, "Rx", "%s / %s / %s", req->data->str, get_header(req, "CSeq"), REQ_OFFSET_TO_STR(req, rlPart2));
25654
25655 if (handle_incoming(p, req, addr, &recount, &nounlock) == -1) {
25656
25657 ast_debug(1, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
25658 }
25659
25660 if (recount) {
25661 ast_update_use_count();
25662 }
25663
25664 if (p->owner && !nounlock) {
25665 ast_channel_unlock(p->owner);
25666 }
25667 if (owner_chan_ref) {
25668 ast_channel_unref(owner_chan_ref);
25669 }
25670 sip_pvt_unlock(p);
25671 ao2_t_ref(p, -1, "throw away dialog ptr from find_call at end of routine");
25672 ast_mutex_unlock(&netlock);
25673
25674 return 1;
25675 }
25676
25677
25678
25679
25680
25681
25682
25683 static int sip_standard_port(enum sip_transport type, int port)
25684 {
25685 if (type & SIP_TRANSPORT_TLS)
25686 return port == STANDARD_TLS_PORT;
25687 else
25688 return port == STANDARD_SIP_PORT;
25689 }
25690
25691 static int threadinfo_locate_cb(void *obj, void *arg, int flags)
25692 {
25693 struct sip_threadinfo *th = obj;
25694 struct ast_sockaddr *s = arg;
25695
25696 if (!ast_sockaddr_cmp(s, &th->tcptls_session->remote_address)) {
25697 return CMP_MATCH | CMP_STOP;
25698 }
25699
25700 return 0;
25701 }
25702
25703
25704
25705
25706
25707
25708 static struct ast_tcptls_session_instance *sip_tcp_locate(struct ast_sockaddr *s)
25709 {
25710 struct sip_threadinfo *th;
25711 struct ast_tcptls_session_instance *tcptls_instance = NULL;
25712
25713 if ((th = ao2_callback(threadt, 0, threadinfo_locate_cb, s))) {
25714 tcptls_instance = (ao2_ref(th->tcptls_session, +1), th->tcptls_session);
25715 ao2_t_ref(th, -1, "decrement ref from callback");
25716 }
25717
25718 return tcptls_instance;
25719 }
25720
25721
25722
25723
25724
25725
25726 int get_address_family_filter(unsigned int transport)
25727 {
25728 const struct ast_sockaddr *addr = NULL;
25729
25730 if ((transport == SIP_TRANSPORT_UDP) || !transport) {
25731 addr = &bindaddr;
25732 }
25733 else if (transport == SIP_TRANSPORT_TCP) {
25734 addr = &sip_tcp_desc.local_address;
25735 }
25736 else if (transport == SIP_TRANSPORT_TLS) {
25737 addr = &sip_tls_desc.local_address;
25738 }
25739
25740 if (ast_sockaddr_is_ipv6(addr) && ast_sockaddr_is_any(addr)) {
25741 return 0;
25742 }
25743
25744 return addr->ss.ss_family;
25745 }
25746
25747
25748 static int sip_prepare_socket(struct sip_pvt *p)
25749 {
25750 struct sip_socket *s = &p->socket;
25751 static const char name[] = "SIP socket";
25752 struct sip_threadinfo *th = NULL;
25753 struct ast_tcptls_session_instance *tcptls_session;
25754 struct ast_tcptls_session_args *ca;
25755 struct ast_sockaddr sa_tmp;
25756 pthread_t launched;
25757
25758
25759 if ((s->fd != -1) && (s->type == SIP_TRANSPORT_UDP)) {
25760 return s->fd;
25761 }
25762 if ((s->type & (SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS)) &&
25763 (s->tcptls_session) &&
25764 (s->tcptls_session->fd != -1)) {
25765 return s->tcptls_session->fd;
25766 }
25767
25768
25769
25770
25771 if (p->outboundproxy && p->outboundproxy->transport) {
25772 s->type = p->outboundproxy->transport;
25773 }
25774
25775 if (s->type == SIP_TRANSPORT_UDP) {
25776 s->fd = sipsock;
25777 return s->fd;
25778 }
25779
25780
25781
25782
25783
25784
25785
25786
25787
25788
25789
25790 ast_sockaddr_copy(&sa_tmp, sip_real_dst(p));
25791 if ((tcptls_session = sip_tcp_locate(&sa_tmp))) {
25792 s->fd = tcptls_session->fd;
25793 if (s->tcptls_session) {
25794 ao2_ref(s->tcptls_session, -1);
25795 s->tcptls_session = NULL;
25796 }
25797 s->tcptls_session = tcptls_session;
25798 return s->fd;
25799
25800 } else if (s->tcptls_session) {
25801 return s->fd;
25802 }
25803
25804
25805
25806 if (!(ca = ao2_alloc(sizeof(*ca), sip_tcptls_client_args_destructor)) ||
25807 !(ca->name = ast_strdup(name))) {
25808 goto create_tcptls_session_fail;
25809 }
25810 ca->accept_fd = -1;
25811 ast_sockaddr_copy(&ca->remote_address,sip_real_dst(p));
25812
25813 if (s->type == SIP_TRANSPORT_TLS) {
25814 if (!(ca->tls_cfg = ast_calloc(1, sizeof(*ca->tls_cfg)))) {
25815 goto create_tcptls_session_fail;
25816 }
25817 memcpy(ca->tls_cfg, &default_tls_cfg, sizeof(*ca->tls_cfg));
25818
25819 if (!(ca->tls_cfg->certfile = ast_strdup(default_tls_cfg.certfile)) ||
25820 !(ca->tls_cfg->pvtfile = ast_strdup(default_tls_cfg.pvtfile)) ||
25821 !(ca->tls_cfg->cipher = ast_strdup(default_tls_cfg.cipher)) ||
25822 !(ca->tls_cfg->cafile = ast_strdup(default_tls_cfg.cafile)) ||
25823 !(ca->tls_cfg->capath = ast_strdup(default_tls_cfg.capath))) {
25824
25825 goto create_tcptls_session_fail;
25826 }
25827
25828
25829 if (!ast_strlen_zero(p->tohost)) {
25830 ast_copy_string(ca->hostname, p->tohost, sizeof(ca->hostname));
25831 }
25832 }
25833
25834
25835 if (!(s->tcptls_session = ast_tcptls_client_create(ca))) {
25836 goto create_tcptls_session_fail;
25837 }
25838
25839 s->fd = s->tcptls_session->fd;
25840
25841
25842
25843
25844
25845 if (!(th = sip_threadinfo_create(s->tcptls_session, s->type))) {
25846 goto create_tcptls_session_fail;
25847 }
25848
25849
25850 ao2_ref(s->tcptls_session, +1);
25851
25852 if (ast_pthread_create_detached_background(&launched, NULL, sip_tcp_worker_fn, s->tcptls_session)) {
25853 ast_debug(1, "Unable to launch '%s'.", ca->name);
25854 ao2_ref(s->tcptls_session, -1);
25855 goto create_tcptls_session_fail;
25856 }
25857
25858 return s->fd;
25859
25860 create_tcptls_session_fail:
25861 if (ca) {
25862 ao2_t_ref(ca, -1, "failed to create client, getting rid of client tcptls_session arguments");
25863 }
25864 if (s->tcptls_session) {
25865 ast_tcptls_close_session_file(s->tcptls_session);
25866 s->fd = -1;
25867 ao2_ref(s->tcptls_session, -1);
25868 s->tcptls_session = NULL;
25869 }
25870 if (th) {
25871 ao2_t_unlink(threadt, th, "Removing tcptls thread info object, thread failed to open");
25872 }
25873
25874 return -1;
25875 }
25876
25877
25878
25879
25880
25881 static int get_cached_mwi(struct sip_peer *peer, int *new, int *old)
25882 {
25883 struct sip_mailbox *mailbox;
25884 int in_cache;
25885
25886 in_cache = 0;
25887 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
25888 struct ast_event *event;
25889 event = ast_event_get_cached(AST_EVENT_MWI,
25890 AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox->mailbox,
25891 AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, S_OR(mailbox->context, "default"),
25892 AST_EVENT_IE_END);
25893 if (!event)
25894 continue;
25895 *new += ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
25896 *old += ast_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS);
25897 ast_event_destroy(event);
25898 in_cache = 1;
25899 }
25900
25901 return in_cache;
25902 }
25903
25904
25905
25906
25907 static int sip_send_mwi_to_peer(struct sip_peer *peer, int cache_only)
25908 {
25909
25910 struct sip_pvt *p;
25911 int newmsgs = 0, oldmsgs = 0;
25912 const char *vmexten = NULL;
25913
25914 ao2_lock(peer);
25915
25916 if (peer->vmexten) {
25917 vmexten = ast_strdupa(peer->vmexten);
25918 }
25919
25920 if (ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY) && !peer->mwipvt) {
25921 update_peer_lastmsgssent(peer, -1, 1);
25922 ao2_unlock(peer);
25923 return 0;
25924 }
25925
25926
25927 if (ast_sockaddr_isnull(&peer->addr) && ast_sockaddr_isnull(&peer->defaddr)) {
25928 update_peer_lastmsgssent(peer, -1, 1);
25929 ao2_unlock(peer);
25930 return 0;
25931 }
25932
25933
25934 if (!get_cached_mwi(peer, &newmsgs, &oldmsgs) && !cache_only) {
25935
25936 struct ast_str *mailbox_str = ast_str_alloca(512);
25937 peer_mailboxes_to_str(&mailbox_str, peer);
25938 ao2_unlock(peer);
25939
25940 if (ast_strlen_zero(mailbox_str->str)) {
25941 update_peer_lastmsgssent(peer, -1, 0);
25942 return 0;
25943 }
25944 ast_app_inboxcount(mailbox_str->str, &newmsgs, &oldmsgs);
25945 ao2_lock(peer);
25946 }
25947
25948 if (peer->mwipvt) {
25949
25950 p = dialog_ref(peer->mwipvt, "sip_send_mwi_to_peer: Setting dialog ptr p from peer->mwipvt");
25951 ao2_unlock(peer);
25952 } else {
25953 ao2_unlock(peer);
25954
25955 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
25956 update_peer_lastmsgssent(peer, -1, 0);
25957 return -1;
25958 }
25959
25960
25961
25962
25963
25964 set_socket_transport(&p->socket, 0);
25965 if (create_addr_from_peer(p, peer)) {
25966
25967 dialog_unlink_all(p);
25968 dialog_unref(p, "unref dialog p just created via sip_alloc");
25969 update_peer_lastmsgssent(peer, -1, 0);
25970 return 0;
25971 }
25972
25973 ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
25974 build_via(p);
25975
25976 ao2_lock(peer);
25977 if (!ast_strlen_zero(peer->mwi_from)) {
25978 ast_string_field_set(p, mwi_from, peer->mwi_from);
25979 } else if (!ast_strlen_zero(default_mwi_from)) {
25980 ast_string_field_set(p, mwi_from, default_mwi_from);
25981 }
25982 ao2_unlock(peer);
25983
25984
25985 change_callid_pvt(p, NULL);
25986
25987
25988 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
25989 }
25990
25991
25992
25993 sip_pvt_lock(p);
25994
25995
25996 ast_set_flag(&p->flags[0], SIP_OUTGOING);
25997
25998 transmit_notify_with_mwi(p, newmsgs, oldmsgs, vmexten);
25999 sip_pvt_unlock(p);
26000 dialog_unref(p, "unref dialog ptr p just before it goes out of scope at the end of sip_send_mwi_to_peer.");
26001
26002 update_peer_lastmsgssent(peer, ((newmsgs > 0x7fff ? 0x7fff0000 : (newmsgs << 16)) | (oldmsgs > 0xffff ? 0xffff : oldmsgs)), 0);
26003
26004 return 0;
26005 }
26006
26007
26008 static void check_rtp_timeout(struct sip_pvt *dialog, time_t t)
26009 {
26010
26011 if (!dialog->rtp || !dialog->owner)
26012 return;
26013
26014
26015 if (dialog->owner->_state != AST_STATE_UP || !ast_sockaddr_isnull(&dialog->redirip))
26016 return;
26017
26018
26019 if (dialog->t38.state == T38_ENABLED)
26020 return;
26021
26022
26023 if (!ast_rtp_instance_get_keepalive(dialog->rtp) && !ast_rtp_instance_get_timeout(dialog->rtp) && !ast_rtp_instance_get_hold_timeout(dialog->rtp)) {
26024 return;
26025 }
26026
26027
26028 if (dialog->lastrtptx && ast_rtp_instance_get_keepalive(dialog->rtp) &&
26029 (t > dialog->lastrtptx + ast_rtp_instance_get_keepalive(dialog->rtp))) {
26030
26031 dialog->lastrtptx = time(NULL);
26032 ast_rtp_instance_sendcng(dialog->rtp, 0);
26033 }
26034
26035
26036
26037
26038
26039
26040
26041
26042 if (dialog->lastrtprx && (ast_rtp_instance_get_timeout(dialog->rtp) || ast_rtp_instance_get_hold_timeout(dialog->rtp)) && (t > dialog->lastrtprx + ast_rtp_instance_get_timeout(dialog->rtp))) {
26043 if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD) || (ast_rtp_instance_get_hold_timeout(dialog->rtp) && (t > dialog->lastrtprx + ast_rtp_instance_get_hold_timeout(dialog->rtp)))) {
26044
26045 if (ast_rtp_instance_get_timeout(dialog->rtp)) {
26046 if (!dialog->owner || ast_channel_trylock(dialog->owner)) {
26047
26048
26049
26050
26051 return;
26052 }
26053 ast_log(LOG_NOTICE, "Disconnecting call '%s' for lack of RTP activity in %ld seconds\n",
26054 dialog->owner->name, (long) (t - dialog->lastrtprx));
26055
26056 ast_softhangup_nolock(dialog->owner, AST_SOFTHANGUP_DEV);
26057 ast_channel_unlock(dialog->owner);
26058
26059
26060
26061
26062 ast_rtp_instance_set_timeout(dialog->rtp, 0);
26063 ast_rtp_instance_set_hold_timeout(dialog->rtp, 0);
26064 if (dialog->vrtp) {
26065 ast_rtp_instance_set_timeout(dialog->vrtp, 0);
26066 ast_rtp_instance_set_hold_timeout(dialog->vrtp, 0);
26067 }
26068 }
26069 }
26070 }
26071 }
26072
26073
26074
26075
26076
26077 static void *do_monitor(void *data)
26078 {
26079 int res;
26080 time_t t;
26081 int reloading;
26082
26083
26084 if (sipsock > -1)
26085 sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
26086
26087
26088 for(;;) {
26089
26090 ast_mutex_lock(&sip_reload_lock);
26091 reloading = sip_reloading;
26092 sip_reloading = FALSE;
26093 ast_mutex_unlock(&sip_reload_lock);
26094 if (reloading) {
26095 ast_verb(1, "Reloading SIP\n");
26096 sip_do_reload(sip_reloadreason);
26097
26098
26099 if (sipsock > -1) {
26100 if (sipsock_read_id)
26101 sipsock_read_id = ast_io_change(io, sipsock_read_id, sipsock, NULL, 0, NULL);
26102 else
26103 sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
26104 } else if (sipsock_read_id) {
26105 ast_io_remove(io, sipsock_read_id);
26106 sipsock_read_id = NULL;
26107 }
26108 }
26109
26110
26111 t = time(NULL);
26112
26113
26114
26115
26116
26117
26118
26119
26120
26121
26122 ao2_t_callback(dialogs, OBJ_NODATA | OBJ_MULTIPLE, dialog_needdestroy, &t,
26123 "callback to monitor dialog status");
26124 if (ao2_container_count(dialogs_to_destroy)) {
26125
26126 ao2_t_callback(dialogs_to_destroy, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE,
26127 dialog_unlink_callback, NULL, "callback to dialog_unlink_all");
26128 }
26129
26130
26131
26132
26133
26134
26135
26136 pthread_testcancel();
26137
26138 res = ast_sched_wait(sched);
26139 if ((res < 0) || (res > 1000))
26140 res = 1000;
26141 res = ast_io_wait(io, res);
26142 if (res > 20)
26143 ast_debug(1, "chan_sip: ast_io_wait ran %d all at once\n", res);
26144 ast_mutex_lock(&monlock);
26145 res = ast_sched_runq(sched);
26146 if (res >= 20)
26147 ast_debug(1, "chan_sip: ast_sched_runq ran %d all at once\n", res);
26148 if (global_store_sip_cause && res >= 100)
26149 ast_log(LOG_WARNING, "scheduler delays detected, setting 'storesipcause' to 'no' in %s will improve performance\n", config);
26150 ast_mutex_unlock(&monlock);
26151 }
26152
26153
26154 return NULL;
26155 }
26156
26157
26158 static int restart_monitor(void)
26159 {
26160
26161 if (monitor_thread == AST_PTHREADT_STOP)
26162 return 0;
26163 ast_mutex_lock(&monlock);
26164 if (monitor_thread == pthread_self()) {
26165 ast_mutex_unlock(&monlock);
26166 ast_log(LOG_WARNING, "Cannot kill myself\n");
26167 return -1;
26168 }
26169 if (monitor_thread != AST_PTHREADT_NULL) {
26170
26171 pthread_kill(monitor_thread, SIGURG);
26172 } else {
26173
26174 if (ast_pthread_create_background(&monitor_thread, NULL, do_monitor, NULL) < 0) {
26175 ast_mutex_unlock(&monlock);
26176 ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
26177 return -1;
26178 }
26179 }
26180 ast_mutex_unlock(&monlock);
26181 return 0;
26182 }
26183
26184
26185
26186 static void restart_session_timer(struct sip_pvt *p)
26187 {
26188 if (!p->stimer) {
26189 ast_log(LOG_WARNING, "Null stimer in restart_session_timer - %s\n", p->callid);
26190 return;
26191 }
26192
26193 if (p->stimer->st_active == TRUE) {
26194 ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
26195 AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
26196 dialog_unref(p, "Removing session timer ref"));
26197 start_session_timer(p);
26198 }
26199 }
26200
26201
26202
26203 static void stop_session_timer(struct sip_pvt *p)
26204 {
26205 if (!p->stimer) {
26206 ast_log(LOG_WARNING, "Null stimer in stop_session_timer - %s\n", p->callid);
26207 return;
26208 }
26209
26210 if (p->stimer->st_active == TRUE) {
26211 p->stimer->st_active = FALSE;
26212 ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
26213 AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
26214 dialog_unref(p, "removing session timer ref"));
26215 }
26216 }
26217
26218
26219
26220 static void start_session_timer(struct sip_pvt *p)
26221 {
26222 if (!p->stimer) {
26223 ast_log(LOG_WARNING, "Null stimer in start_session_timer - %s\n", p->callid);
26224 return;
26225 }
26226
26227 if (p->stimer->st_schedid > -1) {
26228
26229 ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
26230 AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
26231 dialog_unref(p, "unref stimer->st_schedid from dialog"));
26232 }
26233
26234 p->stimer->st_schedid = ast_sched_add(sched, p->stimer->st_interval * 1000 / 2, proc_session_timer,
26235 dialog_ref(p, "adding session timer ref"));
26236 if (p->stimer->st_schedid < 0) {
26237 dialog_unref(p, "removing session timer ref");
26238 ast_log(LOG_ERROR, "ast_sched_add failed - %s\n", p->callid);
26239 } else {
26240 p->stimer->st_active = TRUE;
26241 ast_debug(2, "Session timer started: %d - %s\n", p->stimer->st_schedid, p->callid);
26242 }
26243 }
26244
26245
26246
26247 static int proc_session_timer(const void *vp)
26248 {
26249 struct sip_pvt *p = (struct sip_pvt *) vp;
26250 int res = 0;
26251
26252 if (!p->stimer) {
26253 ast_log(LOG_WARNING, "Null stimer in proc_session_timer - %s\n", p->callid);
26254 goto return_unref;
26255 }
26256
26257 ast_debug(2, "Session timer expired: %d - %s\n", p->stimer->st_schedid, p->callid);
26258
26259 if (!p->owner) {
26260 goto return_unref;
26261 }
26262
26263 if ((p->stimer->st_active != TRUE) || (p->owner->_state != AST_STATE_UP)) {
26264 goto return_unref;
26265 }
26266
26267 if (p->stimer->st_ref == SESSION_TIMER_REFRESHER_US) {
26268 res = 1;
26269 transmit_reinvite_with_sdp(p, FALSE, TRUE);
26270 } else {
26271 p->stimer->st_expirys++;
26272 if (p->stimer->st_expirys >= 2) {
26273 if (p->stimer->quit_flag) {
26274 goto return_unref;
26275 }
26276 ast_log(LOG_WARNING, "Session-Timer expired - %s\n", p->callid);
26277 sip_pvt_lock(p);
26278 while (p->owner && ast_channel_trylock(p->owner)) {
26279 sip_pvt_unlock(p);
26280 usleep(1);
26281 if (p->stimer && p->stimer->quit_flag) {
26282 goto return_unref;
26283 }
26284 sip_pvt_lock(p);
26285 }
26286
26287 ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
26288 ast_channel_unlock(p->owner);
26289 sip_pvt_unlock(p);
26290 } else {
26291 res = 1;
26292 }
26293 }
26294
26295 return_unref:
26296 if (!res) {
26297
26298 if (p->stimer) {
26299 ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
26300 p->stimer->st_schedid = -1;
26301 stop_session_timer(p);
26302 }
26303
26304
26305
26306 dialog_unref(p, "removing session timer ref");
26307 }
26308
26309 return res;
26310 }
26311
26312
26313
26314 int parse_minse (const char *p_hdrval, int *const p_interval)
26315 {
26316 if (ast_strlen_zero(p_hdrval)) {
26317 ast_log(LOG_WARNING, "Null Min-SE header\n");
26318 return -1;
26319 }
26320
26321 *p_interval = 0;
26322 p_hdrval = ast_skip_blanks(p_hdrval);
26323 if (!sscanf(p_hdrval, "%30d", p_interval)) {
26324 ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
26325 return -1;
26326 }
26327
26328 ast_debug(2, "Received Min-SE: %d\n", *p_interval);
26329 return 0;
26330 }
26331
26332
26333
26334 int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher_param *const p_ref)
26335 {
26336 char *p_token;
26337 int ref_idx;
26338 char *p_se_hdr;
26339
26340 if (ast_strlen_zero(p_hdrval)) {
26341 ast_log(LOG_WARNING, "Null Session-Expires header\n");
26342 return -1;
26343 }
26344
26345 *p_ref = SESSION_TIMER_REFRESHER_PARAM_UNKNOWN;
26346 *p_interval = 0;
26347
26348 p_se_hdr = ast_strdupa(p_hdrval);
26349 p_se_hdr = ast_skip_blanks(p_se_hdr);
26350
26351 while ((p_token = strsep(&p_se_hdr, ";"))) {
26352 p_token = ast_skip_blanks(p_token);
26353 if (!sscanf(p_token, "%30d", p_interval)) {
26354 ast_log(LOG_WARNING, "Parsing of Session-Expires failed\n");
26355 return -1;
26356 }
26357
26358 ast_debug(2, "Session-Expires: %d\n", *p_interval);
26359
26360 if (!p_se_hdr)
26361 continue;
26362
26363 p_se_hdr = ast_skip_blanks(p_se_hdr);
26364 ref_idx = strlen("refresher=");
26365 if (!strncasecmp(p_se_hdr, "refresher=", ref_idx)) {
26366 p_se_hdr += ref_idx;
26367 p_se_hdr = ast_skip_blanks(p_se_hdr);
26368
26369 if (!strncasecmp(p_se_hdr, "uac", strlen("uac"))) {
26370 *p_ref = SESSION_TIMER_REFRESHER_PARAM_UAC;
26371 ast_debug(2, "Refresher: UAC\n");
26372 } else if (!strncasecmp(p_se_hdr, "uas", strlen("uas"))) {
26373 *p_ref = SESSION_TIMER_REFRESHER_PARAM_UAS;
26374 ast_debug(2, "Refresher: UAS\n");
26375 } else {
26376 ast_log(LOG_WARNING, "Invalid refresher value %s\n", p_se_hdr);
26377 return -1;
26378 }
26379 break;
26380 }
26381 }
26382 return 0;
26383 }
26384
26385
26386
26387
26388
26389
26390
26391
26392
26393 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp)
26394 {
26395 int rtn;
26396 const char *p_hdrval;
26397 int minse;
26398
26399 p_hdrval = get_header(rsp, "Min-SE");
26400 if (ast_strlen_zero(p_hdrval)) {
26401 ast_log(LOG_WARNING, "422 response without a Min-SE header %s\n", p_hdrval);
26402 return;
26403 }
26404 rtn = parse_minse(p_hdrval, &minse);
26405 if (rtn != 0) {
26406 ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
26407 return;
26408 }
26409 p->stimer->st_interval = minse;
26410 transmit_invite(p, SIP_INVITE, 1, 2, NULL);
26411 }
26412
26413
26414
26415
26416
26417
26418 int st_get_se(struct sip_pvt *p, int max)
26419 {
26420 if (max == TRUE) {
26421 if (p->stimer->st_cached_max_se) {
26422 return p->stimer->st_cached_max_se;
26423 }
26424 if (p->relatedpeer) {
26425 p->stimer->st_cached_max_se = p->relatedpeer->stimer.st_max_se;
26426 return (p->stimer->st_cached_max_se);
26427 }
26428 p->stimer->st_cached_max_se = global_max_se;
26429 return (p->stimer->st_cached_max_se);
26430 }
26431
26432 if (p->stimer->st_cached_min_se) {
26433 return p->stimer->st_cached_min_se;
26434 }
26435 if (p->relatedpeer) {
26436 p->stimer->st_cached_min_se = p->relatedpeer->stimer.st_min_se;
26437 return (p->stimer->st_cached_min_se);
26438 }
26439 p->stimer->st_cached_min_se = global_min_se;
26440 return (p->stimer->st_cached_min_se);
26441 }
26442
26443
26444
26445
26446
26447
26448
26449
26450 enum st_refresher st_get_refresher(struct sip_pvt *p)
26451 {
26452 if (p->stimer->st_cached_ref != SESSION_TIMER_REFRESHER_AUTO) {
26453 return p->stimer->st_cached_ref;
26454 }
26455
26456 if (p->relatedpeer) {
26457 p->stimer->st_cached_ref = (p->relatedpeer->stimer.st_ref == SESSION_TIMER_REFRESHER_PARAM_UAC) ? SESSION_TIMER_REFRESHER_THEM : SESSION_TIMER_REFRESHER_US;
26458 return p->stimer->st_cached_ref;
26459 }
26460
26461 p->stimer->st_cached_ref = (global_st_refresher == SESSION_TIMER_REFRESHER_PARAM_UAC) ? SESSION_TIMER_REFRESHER_THEM : SESSION_TIMER_REFRESHER_US;
26462 return p->stimer->st_cached_ref;
26463 }
26464
26465
26466
26467
26468
26469
26470
26471
26472 enum st_mode st_get_mode(struct sip_pvt *p, int no_cached)
26473 {
26474 if (!p->stimer) {
26475 sip_st_alloc(p);
26476 if (!p->stimer) {
26477 return SESSION_TIMER_MODE_INVALID;
26478 }
26479 }
26480
26481 if (!no_cached && p->stimer->st_cached_mode != SESSION_TIMER_MODE_INVALID)
26482 return p->stimer->st_cached_mode;
26483
26484 if (p->relatedpeer) {
26485 p->stimer->st_cached_mode = p->relatedpeer->stimer.st_mode_oper;
26486 return p->stimer->st_cached_mode;
26487 }
26488
26489 p->stimer->st_cached_mode = global_st_mode;
26490 return global_st_mode;
26491 }
26492
26493
26494
26495 static int sip_poke_noanswer(const void *data)
26496 {
26497 struct sip_peer *peer = (struct sip_peer *)data;
26498
26499 peer->pokeexpire = -1;
26500
26501 if (peer->lastms > -1) {
26502 ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE! Last qualify: %d\n", peer->name, peer->lastms);
26503 if (sip_cfg.peer_rtupdate) {
26504 ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", "-1", SENTINEL);
26505 }
26506 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer->name, -1);
26507 if (sip_cfg.regextenonqualify) {
26508 register_peer_exten(peer, FALSE);
26509 }
26510 }
26511
26512 if (peer->call) {
26513 dialog_unlink_all(peer->call);
26514 peer->call = dialog_unref(peer->call, "unref dialog peer->call");
26515
26516 }
26517
26518
26519 if (peer->lastms > -1) {
26520 peer->lastms = -1;
26521 ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
26522 }
26523
26524
26525 AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
26526 DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer,
26527 unref_peer(_data, "removing poke peer ref"),
26528 unref_peer(peer, "removing poke peer ref"),
26529 ref_peer(peer, "adding poke peer ref"));
26530
26531
26532 unref_peer(peer, "release peer poke noanswer ref");
26533
26534 return 0;
26535 }
26536
26537
26538
26539
26540
26541
26542 static int sip_poke_peer(struct sip_peer *peer, int force)
26543 {
26544 struct sip_pvt *p;
26545 int xmitres = 0;
26546
26547 if ((!peer->maxms && !force) || ast_sockaddr_isnull(&peer->addr)) {
26548
26549
26550 AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
26551 unref_peer(peer, "removing poke peer ref"));
26552
26553 peer->lastms = 0;
26554 if (peer->call) {
26555 peer->call = dialog_unref(peer->call, "unref dialog peer->call");
26556 }
26557 return 0;
26558 }
26559 if (peer->call) {
26560 if (sipdebug) {
26561 ast_log(LOG_NOTICE, "Still have a QUALIFY dialog active, deleting\n");
26562 }
26563 dialog_unlink_all(peer->call);
26564 peer->call = dialog_unref(peer->call, "unref dialog peer->call");
26565
26566 }
26567 if (!(p = sip_alloc(NULL, NULL, 0, SIP_OPTIONS, NULL))) {
26568 return -1;
26569 }
26570 peer->call = dialog_ref(p, "copy sip alloc from p to peer->call");
26571
26572 p->sa = peer->addr;
26573 p->recv = peer->addr;
26574 copy_socket_data(&p->socket, &peer->socket);
26575 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
26576 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
26577 ast_copy_flags(&p->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
26578
26579
26580 if (!ast_strlen_zero(peer->fullcontact)) {
26581 ast_string_field_set(p, fullcontact, peer->fullcontact);
26582 }
26583
26584 if (!ast_strlen_zero(peer->fromuser)) {
26585 ast_string_field_set(p, fromuser, peer->fromuser);
26586 }
26587
26588 if (!ast_strlen_zero(peer->tohost)) {
26589 ast_string_field_set(p, tohost, peer->tohost);
26590 } else {
26591 ast_string_field_set(p, tohost, ast_sockaddr_stringify_host_remote(&peer->addr));
26592 }
26593
26594
26595 ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
26596 build_via(p);
26597
26598
26599 change_callid_pvt(p, NULL);
26600
26601 AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
26602 unref_peer(peer, "removing poke peer ref"));
26603
26604 if (p->relatedpeer)
26605 p->relatedpeer = unref_peer(p->relatedpeer,"unsetting the relatedpeer field in the dialog, before it is set to something else.");
26606 p->relatedpeer = ref_peer(peer, "setting the relatedpeer field in the dialog");
26607 ast_set_flag(&p->flags[0], SIP_OUTGOING);
26608 #ifdef VOCAL_DATA_HACK
26609 ast_copy_string(p->username, "__VOCAL_DATA_SHOULD_READ_THE_SIP_SPEC__", sizeof(p->username));
26610 xmitres = transmit_invite(p, SIP_INVITE, 0, 2, NULL);
26611 #else
26612 xmitres = transmit_invite(p, SIP_OPTIONS, 0, 2, NULL);
26613 #endif
26614 peer->ps = ast_tvnow();
26615 if (xmitres == XMIT_ERROR) {
26616
26617 sip_poke_noanswer(ref_peer(peer, "add ref for peerexpire (fake, for sip_poke_noanswer to remove)"));
26618 } else if (!force) {
26619 AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, peer->maxms * 2, sip_poke_noanswer, peer,
26620 unref_peer(_data, "removing poke peer ref"),
26621 unref_peer(peer, "removing poke peer ref"),
26622 ref_peer(peer, "adding poke peer ref"));
26623 }
26624 dialog_unref(p, "unref dialog at end of sip_poke_peer, obtained from sip_alloc, just before it goes out of scope");
26625 return 0;
26626 }
26627
26628
26629
26630
26631
26632
26633
26634
26635
26636
26637
26638
26639
26640
26641
26642
26643
26644
26645
26646
26647
26648
26649
26650
26651
26652
26653
26654
26655
26656
26657
26658
26659
26660
26661 static int sip_devicestate(void *data)
26662 {
26663 char *host;
26664 char *tmp;
26665 struct sip_peer *p;
26666
26667 int res = AST_DEVICE_INVALID;
26668
26669
26670 host = ast_strdupa(data ? data : "");
26671 if ((tmp = strchr(host, '@')))
26672 host = tmp + 1;
26673
26674 ast_debug(3, "Checking device state for peer %s\n", host);
26675
26676
26677
26678
26679
26680
26681
26682
26683 if ((p = find_peer(host, NULL, FALSE, FINDALLDEVICES, TRUE, 0))) {
26684 if (!(ast_sockaddr_isnull(&p->addr) && ast_sockaddr_isnull(&p->defaddr))) {
26685
26686
26687
26688
26689
26690
26691
26692
26693
26694
26695
26696 if (p->onHold)
26697
26698 res = AST_DEVICE_ONHOLD;
26699 else if (p->inRinging) {
26700 if (p->inRinging == p->inUse)
26701 res = AST_DEVICE_RINGING;
26702 else
26703 res = AST_DEVICE_RINGINUSE;
26704 } else if (p->call_limit && (p->inUse == p->call_limit))
26705
26706 res = AST_DEVICE_BUSY;
26707 else if (p->call_limit && p->busy_level && p->inUse >= p->busy_level)
26708
26709 res = AST_DEVICE_BUSY;
26710 else if (p->call_limit && p->inUse)
26711
26712 res = AST_DEVICE_INUSE;
26713 else if (p->maxms && ((p->lastms > p->maxms) || (p->lastms < 0)))
26714
26715 res = AST_DEVICE_UNAVAILABLE;
26716 else
26717 res = AST_DEVICE_NOT_INUSE;
26718 } else {
26719
26720 res = AST_DEVICE_UNAVAILABLE;
26721 }
26722 unref_peer(p, "unref_peer, from sip_devicestate, release ref from find_peer");
26723 }
26724
26725 return res;
26726 }
26727
26728
26729
26730
26731
26732
26733
26734
26735
26736
26737
26738 static struct ast_channel *sip_request_call(const char *type, format_t format, const struct ast_channel *requestor, void *data, int *cause)
26739 {
26740 struct sip_pvt *p;
26741 struct ast_channel *tmpc = NULL;
26742 char *ext = NULL, *host;
26743 char tmp[256];
26744 char *dest = data;
26745 char *dnid;
26746 char *secret = NULL;
26747 char *md5secret = NULL;
26748 char *authname = NULL;
26749 char *trans = NULL;
26750 char dialstring[256];
26751 char *remote_address;
26752 enum sip_transport transport = 0;
26753 format_t oldformat = format;
26754 AST_DECLARE_APP_ARGS(args,
26755 AST_APP_ARG(peerorhost);
26756 AST_APP_ARG(exten);
26757 AST_APP_ARG(remote_address);
26758 );
26759
26760
26761
26762
26763
26764
26765
26766
26767 format &= AST_FORMAT_AUDIO_MASK;
26768 if (!format) {
26769 ast_log(LOG_NOTICE, "Asked to get a channel of unsupported format %s while capability is %s\n", ast_getformatname(oldformat), ast_getformatname(sip_cfg.capability));
26770 *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
26771 return NULL;
26772 }
26773 ast_debug(1, "Asked to create a SIP channel with formats: %s\n", ast_getformatname_multiple(tmp, sizeof(tmp), oldformat));
26774
26775 if (ast_strlen_zero(dest)) {
26776 ast_log(LOG_ERROR, "Unable to create channel with empty destination.\n");
26777 *cause = AST_CAUSE_CHANNEL_UNACCEPTABLE;
26778 return NULL;
26779 }
26780
26781 if (!(p = sip_alloc(NULL, NULL, 0, SIP_INVITE, NULL))) {
26782 ast_log(LOG_ERROR, "Unable to build sip pvt data for '%s' (Out of memory or socket error)\n", dest);
26783 *cause = AST_CAUSE_SWITCH_CONGESTION;
26784 return NULL;
26785 }
26786
26787 p->outgoing_call = TRUE;
26788
26789 snprintf(dialstring, sizeof(dialstring), "%s/%s", type, dest);
26790 ast_string_field_set(p, dialstring, dialstring);
26791
26792 if (!(p->options = ast_calloc(1, sizeof(*p->options)))) {
26793 dialog_unlink_all(p);
26794 dialog_unref(p, "unref dialog p from mem fail");
26795
26796 ast_log(LOG_ERROR, "Unable to build option SIP data structure - Out of memory\n");
26797 *cause = AST_CAUSE_SWITCH_CONGESTION;
26798 return NULL;
26799 }
26800
26801
26802 ast_copy_string(tmp, dest, sizeof(tmp));
26803
26804
26805 dnid = strchr(tmp, '!');
26806 if (dnid != NULL) {
26807 *dnid++ = '\0';
26808 ast_string_field_set(p, todnid, dnid);
26809 }
26810
26811
26812 AST_NONSTANDARD_APP_ARGS(args, tmp, '/');
26813
26814
26815 host = strchr(args.peerorhost, '@');
26816 if (host) {
26817 *host++ = '\0';
26818 ext = args.peerorhost;
26819 secret = strchr(ext, ':');
26820 }
26821 if (secret) {
26822 *secret++ = '\0';
26823 md5secret = strchr(secret, ':');
26824 }
26825 if (md5secret) {
26826 *md5secret++ = '\0';
26827 authname = strchr(md5secret, ':');
26828 }
26829 if (authname) {
26830 *authname++ = '\0';
26831 trans = strchr(authname, ':');
26832 }
26833 if (trans) {
26834 *trans++ = '\0';
26835 if (!strcasecmp(trans, "tcp"))
26836 transport = SIP_TRANSPORT_TCP;
26837 else if (!strcasecmp(trans, "tls"))
26838 transport = SIP_TRANSPORT_TLS;
26839 else {
26840 if (strcasecmp(trans, "udp"))
26841 ast_log(LOG_WARNING, "'%s' is not a valid transport option to Dial() for SIP calls, using udp by default.\n", trans);
26842 transport = SIP_TRANSPORT_UDP;
26843 }
26844 } else {
26845 transport = SIP_TRANSPORT_UDP;
26846 }
26847
26848 if (!host) {
26849 ext = args.exten;
26850 host = args.peerorhost;
26851 remote_address = args.remote_address;
26852 } else {
26853 remote_address = args.remote_address;
26854 if (!ast_strlen_zero(args.exten)) {
26855 ast_log(LOG_NOTICE, "Conflicting extension values given. Using '%s' and not '%s'\n", ext, args.exten);
26856 }
26857 }
26858
26859 if (!ast_strlen_zero(remote_address)) {
26860 p->options->outboundproxy = proxy_from_config(remote_address, 0, NULL);
26861 if (!p->options->outboundproxy) {
26862 ast_log(LOG_WARNING, "Unable to parse outboundproxy %s. We will not use this remote IP address\n", remote_address);
26863 }
26864 }
26865
26866 set_socket_transport(&p->socket, transport);
26867
26868
26869
26870
26871
26872
26873 if (create_addr(p, host, NULL, 1)) {
26874 *cause = AST_CAUSE_UNREGISTERED;
26875 ast_debug(3, "Cant create SIP call - target device not registered\n");
26876 dialog_unlink_all(p);
26877 dialog_unref(p, "unref dialog p UNREGISTERED");
26878
26879 return NULL;
26880 }
26881 if (ast_strlen_zero(p->peername) && ext)
26882 ast_string_field_set(p, peername, ext);
26883
26884 ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
26885 build_via(p);
26886
26887
26888 change_callid_pvt(p, NULL);
26889
26890
26891
26892
26893
26894
26895 if (ext) {
26896 ast_string_field_set(p, username, ext);
26897 ast_string_field_set(p, fullcontact, NULL);
26898 }
26899 if (secret && !ast_strlen_zero(secret))
26900 ast_string_field_set(p, peersecret, secret);
26901
26902 if (md5secret && !ast_strlen_zero(md5secret))
26903 ast_string_field_set(p, peermd5secret, md5secret);
26904
26905 if (authname && !ast_strlen_zero(authname))
26906 ast_string_field_set(p, authname, authname);
26907 #if 0
26908 printf("Setting up to call extension '%s' at '%s'\n", ext ? ext : "<none>", host);
26909 #endif
26910 p->prefcodec = oldformat;
26911 p->jointcapability = oldformat & p->capability;
26912 sip_pvt_lock(p);
26913 tmpc = sip_new(p, AST_STATE_DOWN, host, requestor ? requestor->linkedid : NULL);
26914 if (sip_cfg.callevents)
26915 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
26916 "Channel: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
26917 p->owner? p->owner->name : "", "SIP", p->callid, p->fullcontact, p->peername);
26918 sip_pvt_unlock(p);
26919 if (!tmpc) {
26920 dialog_unlink_all(p);
26921
26922 } else {
26923 ast_channel_unlock(tmpc);
26924 }
26925 dialog_unref(p, "toss pvt ptr at end of sip_request_call");
26926 ast_update_use_count();
26927 restart_monitor();
26928 return tmpc;
26929 }
26930
26931
26932 static void set_insecure_flags (struct ast_flags *flags, const char *value, int lineno)
26933 {
26934 if (ast_strlen_zero(value))
26935 return;
26936
26937 if (!ast_false(value)) {
26938 char buf[64];
26939 char *word, *next;
26940
26941 ast_copy_string(buf, value, sizeof(buf));
26942 next = buf;
26943 while ((word = strsep(&next, ","))) {
26944 if (!strcasecmp(word, "port"))
26945 ast_set_flag(&flags[0], SIP_INSECURE_PORT);
26946 else if (!strcasecmp(word, "invite"))
26947 ast_set_flag(&flags[0], SIP_INSECURE_INVITE);
26948 else
26949 ast_log(LOG_WARNING, "Unknown insecure mode '%s' on line %d\n", value, lineno);
26950 }
26951 }
26952 }
26953
26954
26955
26956
26957
26958 static int handle_t38_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v,
26959 int *maxdatagram)
26960 {
26961 int res = 1;
26962
26963 if (!strcasecmp(v->name, "t38pt_udptl")) {
26964 char *buf = ast_strdupa(v->value);
26965 char *word, *next = buf;
26966
26967 ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT);
26968
26969 while ((word = strsep(&next, ","))) {
26970 if (ast_true(word) || !strcasecmp(word, "fec")) {
26971 ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
26972 ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_FEC);
26973 } else if (!strcasecmp(word, "redundancy")) {
26974 ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
26975 ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY);
26976 } else if (!strcasecmp(word, "none")) {
26977 ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
26978 ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL);
26979 } else if (!strncasecmp(word, "maxdatagram=", 12)) {
26980 if (sscanf(&word[12], "%30u", maxdatagram) != 1) {
26981 ast_log(LOG_WARNING, "Invalid maxdatagram '%s' at line %d of %s\n", v->value, v->lineno, config);
26982 *maxdatagram = global_t38_maxdatagram;
26983 }
26984 }
26985 }
26986 } else if (!strcasecmp(v->name, "t38pt_usertpsource")) {
26987 ast_set_flag(&mask[1], SIP_PAGE2_UDPTL_DESTINATION);
26988 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_UDPTL_DESTINATION);
26989 } else {
26990 res = 0;
26991 }
26992
26993 return res;
26994 }
26995
26996
26997
26998
26999
27000
27001
27002
27003 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v)
27004 {
27005 int res = 1;
27006
27007 if (!strcasecmp(v->name, "trustrpid")) {
27008 ast_set_flag(&mask[0], SIP_TRUSTRPID);
27009 ast_set2_flag(&flags[0], ast_true(v->value), SIP_TRUSTRPID);
27010 } else if (!strcasecmp(v->name, "sendrpid")) {
27011 ast_set_flag(&mask[0], SIP_SENDRPID);
27012 if (!strcasecmp(v->value, "pai")) {
27013 ast_set_flag(&flags[0], SIP_SENDRPID_PAI);
27014 } else if (!strcasecmp(v->value, "rpid")) {
27015 ast_set_flag(&flags[0], SIP_SENDRPID_RPID);
27016 } else if (ast_true(v->value)) {
27017 ast_set_flag(&flags[0], SIP_SENDRPID_RPID);
27018 }
27019 } else if (!strcasecmp(v->name, "rpid_update")) {
27020 ast_set_flag(&mask[1], SIP_PAGE2_RPID_UPDATE);
27021 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RPID_UPDATE);
27022 } else if (!strcasecmp(v->name, "rpid_immediate")) {
27023 ast_set_flag(&mask[1], SIP_PAGE2_RPID_IMMEDIATE);
27024 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RPID_IMMEDIATE);
27025 } else if (!strcasecmp(v->name, "g726nonstandard")) {
27026 ast_set_flag(&mask[0], SIP_G726_NONSTANDARD);
27027 ast_set2_flag(&flags[0], ast_true(v->value), SIP_G726_NONSTANDARD);
27028 } else if (!strcasecmp(v->name, "useclientcode")) {
27029 ast_set_flag(&mask[0], SIP_USECLIENTCODE);
27030 ast_set2_flag(&flags[0], ast_true(v->value), SIP_USECLIENTCODE);
27031 } else if (!strcasecmp(v->name, "dtmfmode")) {
27032 ast_set_flag(&mask[0], SIP_DTMF);
27033 ast_clear_flag(&flags[0], SIP_DTMF);
27034 if (!strcasecmp(v->value, "inband"))
27035 ast_set_flag(&flags[0], SIP_DTMF_INBAND);
27036 else if (!strcasecmp(v->value, "rfc2833"))
27037 ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
27038 else if (!strcasecmp(v->value, "info"))
27039 ast_set_flag(&flags[0], SIP_DTMF_INFO);
27040 else if (!strcasecmp(v->value, "shortinfo"))
27041 ast_set_flag(&flags[0], SIP_DTMF_SHORTINFO);
27042 else if (!strcasecmp(v->value, "auto"))
27043 ast_set_flag(&flags[0], SIP_DTMF_AUTO);
27044 else {
27045 ast_log(LOG_WARNING, "Unknown dtmf mode '%s' on line %d, using rfc2833\n", v->value, v->lineno);
27046 ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
27047 }
27048 } else if (!strcasecmp(v->name, "nat")) {
27049 ast_set_flag(&mask[0], SIP_NAT_FORCE_RPORT);
27050 ast_set_flag(&flags[0], SIP_NAT_FORCE_RPORT);
27051 if (!strcasecmp(v->value, "no")) {
27052 ast_clear_flag(&flags[0], SIP_NAT_FORCE_RPORT);
27053 } else if (!strcasecmp(v->value, "yes")) {
27054
27055 ast_set_flag(&mask[1], SIP_PAGE2_SYMMETRICRTP);
27056 ast_set_flag(&flags[1], SIP_PAGE2_SYMMETRICRTP);
27057 } else if (!strcasecmp(v->value, "comedia")) {
27058 ast_clear_flag(&flags[0], SIP_NAT_FORCE_RPORT);
27059 ast_set_flag(&mask[1], SIP_PAGE2_SYMMETRICRTP);
27060 ast_set_flag(&flags[1], SIP_PAGE2_SYMMETRICRTP);
27061 }
27062 } else if (!strcasecmp(v->name, "directmedia") || !strcasecmp(v->name, "canreinvite")) {
27063 ast_set_flag(&mask[0], SIP_REINVITE);
27064 ast_clear_flag(&flags[0], SIP_REINVITE);
27065 if (ast_true(v->value)) {
27066 ast_set_flag(&flags[0], SIP_DIRECT_MEDIA | SIP_DIRECT_MEDIA_NAT);
27067 } else if (!ast_false(v->value)) {
27068 char buf[64];
27069 char *word, *next = buf;
27070
27071 ast_copy_string(buf, v->value, sizeof(buf));
27072 while ((word = strsep(&next, ","))) {
27073 if (!strcasecmp(word, "update")) {
27074 ast_set_flag(&flags[0], SIP_REINVITE_UPDATE | SIP_DIRECT_MEDIA);
27075 } else if (!strcasecmp(word, "nonat")) {
27076 ast_set_flag(&flags[0], SIP_DIRECT_MEDIA);
27077 ast_clear_flag(&flags[0], SIP_DIRECT_MEDIA_NAT);
27078 } else if (!strcasecmp(word, "outgoing")) {
27079 ast_set_flag(&flags[0], SIP_DIRECT_MEDIA);
27080 ast_set_flag(&mask[2], SIP_PAGE3_DIRECT_MEDIA_OUTGOING);
27081 ast_set_flag(&flags[2], SIP_PAGE3_DIRECT_MEDIA_OUTGOING);
27082 } else {
27083 ast_log(LOG_WARNING, "Unknown directmedia mode '%s' on line %d\n", v->value, v->lineno);
27084 }
27085 }
27086 }
27087 } else if (!strcasecmp(v->name, "insecure")) {
27088 ast_set_flag(&mask[0], SIP_INSECURE);
27089 ast_clear_flag(&flags[0], SIP_INSECURE);
27090 set_insecure_flags(&flags[0], v->value, v->lineno);
27091 } else if (!strcasecmp(v->name, "progressinband")) {
27092 ast_set_flag(&mask[0], SIP_PROG_INBAND);
27093 ast_clear_flag(&flags[0], SIP_PROG_INBAND);
27094 if (ast_true(v->value))
27095 ast_set_flag(&flags[0], SIP_PROG_INBAND_YES);
27096 else if (strcasecmp(v->value, "never"))
27097 ast_set_flag(&flags[0], SIP_PROG_INBAND_NO);
27098 } else if (!strcasecmp(v->name, "promiscredir")) {
27099 ast_set_flag(&mask[0], SIP_PROMISCREDIR);
27100 ast_set2_flag(&flags[0], ast_true(v->value), SIP_PROMISCREDIR);
27101 } else if (!strcasecmp(v->name, "videosupport")) {
27102 if (!strcasecmp(v->value, "always")) {
27103 ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
27104 ast_set_flag(&flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
27105 } else {
27106 ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT);
27107 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_VIDEOSUPPORT);
27108 }
27109 } else if (!strcasecmp(v->name, "textsupport")) {
27110 ast_set_flag(&mask[1], SIP_PAGE2_TEXTSUPPORT);
27111 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_TEXTSUPPORT);
27112 res = 1;
27113 } else if (!strcasecmp(v->name, "allowoverlap")) {
27114 ast_set_flag(&mask[1], SIP_PAGE2_ALLOWOVERLAP);
27115 ast_clear_flag(&flags[1], SIP_PAGE2_ALLOWOVERLAP);
27116 if (ast_true(v->value)) {
27117 ast_set_flag(&flags[1], SIP_PAGE2_ALLOWOVERLAP_YES);
27118 } else if (!strcasecmp(v->value, "dtmf")){
27119 ast_set_flag(&flags[1], SIP_PAGE2_ALLOWOVERLAP_DTMF);
27120 }
27121 } else if (!strcasecmp(v->name, "allowsubscribe")) {
27122 ast_set_flag(&mask[1], SIP_PAGE2_ALLOWSUBSCRIBE);
27123 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWSUBSCRIBE);
27124 } else if (!strcasecmp(v->name, "ignoresdpversion")) {
27125 ast_set_flag(&mask[1], SIP_PAGE2_IGNORESDPVERSION);
27126 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_IGNORESDPVERSION);
27127 } else if (!strcasecmp(v->name, "faxdetect")) {
27128 ast_set_flag(&mask[1], SIP_PAGE2_FAX_DETECT);
27129 if (ast_true(v->value)) {
27130 ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_BOTH);
27131 } else if (ast_false(v->value)) {
27132 ast_clear_flag(&flags[1], SIP_PAGE2_FAX_DETECT_BOTH);
27133 } else {
27134 char *buf = ast_strdupa(v->value);
27135 char *word, *next = buf;
27136
27137 while ((word = strsep(&next, ","))) {
27138 if (!strcasecmp(word, "cng")) {
27139 ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_CNG);
27140 } else if (!strcasecmp(word, "t38")) {
27141 ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_T38);
27142 } else {
27143 ast_log(LOG_WARNING, "Unknown faxdetect mode '%s' on line %d.\n", word, v->lineno);
27144 }
27145 }
27146 }
27147 } else if (!strcasecmp(v->name, "rfc2833compensate")) {
27148 ast_set_flag(&mask[1], SIP_PAGE2_RFC2833_COMPENSATE);
27149 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RFC2833_COMPENSATE);
27150 } else if (!strcasecmp(v->name, "buggymwi")) {
27151 ast_set_flag(&mask[1], SIP_PAGE2_BUGGY_MWI);
27152 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_BUGGY_MWI);
27153 } else
27154 res = 0;
27155
27156 return res;
27157 }
27158
27159
27160 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context)
27161 {
27162 struct domain *d;
27163
27164 if (ast_strlen_zero(domain)) {
27165 ast_log(LOG_WARNING, "Zero length domain.\n");
27166 return 1;
27167 }
27168
27169 if (!(d = ast_calloc(1, sizeof(*d))))
27170 return 0;
27171
27172 ast_copy_string(d->domain, domain, sizeof(d->domain));
27173
27174 if (!ast_strlen_zero(context))
27175 ast_copy_string(d->context, context, sizeof(d->context));
27176
27177 d->mode = mode;
27178
27179 AST_LIST_LOCK(&domain_list);
27180 AST_LIST_INSERT_TAIL(&domain_list, d, list);
27181 AST_LIST_UNLOCK(&domain_list);
27182
27183 if (sipdebug)
27184 ast_debug(1, "Added local SIP domain '%s'\n", domain);
27185
27186 return 1;
27187 }
27188
27189
27190 static int check_sip_domain(const char *domain, char *context, size_t len)
27191 {
27192 struct domain *d;
27193 int result = 0;
27194
27195 AST_LIST_LOCK(&domain_list);
27196 AST_LIST_TRAVERSE(&domain_list, d, list) {
27197 if (strcasecmp(d->domain, domain)) {
27198 continue;
27199 }
27200
27201 if (len && !ast_strlen_zero(d->context))
27202 ast_copy_string(context, d->context, len);
27203
27204 result = 1;
27205 break;
27206 }
27207 AST_LIST_UNLOCK(&domain_list);
27208
27209 return result;
27210 }
27211
27212
27213 static void clear_sip_domains(void)
27214 {
27215 struct domain *d;
27216
27217 AST_LIST_LOCK(&domain_list);
27218 while ((d = AST_LIST_REMOVE_HEAD(&domain_list, list)))
27219 ast_free(d);
27220 AST_LIST_UNLOCK(&domain_list);
27221 }
27222
27223
27224
27225
27226
27227
27228
27229
27230
27231 static void destroy_realm_authentication(void *obj)
27232 {
27233 struct sip_auth_container *credentials = obj;
27234 struct sip_auth *auth;
27235
27236 while ((auth = AST_LIST_REMOVE_HEAD(&credentials->list, node))) {
27237 ast_free(auth);
27238 }
27239 }
27240
27241
27242
27243
27244
27245
27246
27247
27248
27249
27250
27251 static void add_realm_authentication(struct sip_auth_container **credentials, const char *configuration, int lineno)
27252 {
27253 char *authcopy;
27254 char *username=NULL, *realm=NULL, *secret=NULL, *md5secret=NULL;
27255 struct sip_auth *auth;
27256
27257 if (ast_strlen_zero(configuration)) {
27258
27259 return;
27260 }
27261
27262 ast_debug(1, "Auth config :: %s\n", configuration);
27263
27264 authcopy = ast_strdupa(configuration);
27265 username = authcopy;
27266
27267
27268 realm = strrchr(username, '@');
27269 if (realm)
27270 *realm++ = '\0';
27271 if (ast_strlen_zero(username) || ast_strlen_zero(realm)) {
27272 ast_log(LOG_WARNING, "Format for authentication entry is user[:secret]@realm at line %d\n", lineno);
27273 return;
27274 }
27275
27276
27277 if ((secret = strchr(username, ':'))) {
27278 *secret++ = '\0';
27279 } else if ((md5secret = strchr(username, '#'))) {
27280 *md5secret++ = '\0';
27281 }
27282
27283
27284 if (!*credentials) {
27285 *credentials = ao2_t_alloc(sizeof(**credentials), destroy_realm_authentication,
27286 "Create realm auth container.");
27287 if (!*credentials) {
27288
27289 return;
27290 }
27291 }
27292
27293
27294 auth = ast_calloc(1, sizeof(*auth));
27295 if (!auth) {
27296 return;
27297 }
27298 ast_copy_string(auth->realm, realm, sizeof(auth->realm));
27299 ast_copy_string(auth->username, username, sizeof(auth->username));
27300 if (secret)
27301 ast_copy_string(auth->secret, secret, sizeof(auth->secret));
27302 if (md5secret)
27303 ast_copy_string(auth->md5secret, md5secret, sizeof(auth->md5secret));
27304
27305
27306 AST_LIST_INSERT_TAIL(&(*credentials)->list, auth, node);
27307
27308 ast_verb(3, "Added authentication for realm %s\n", realm);
27309 }
27310
27311
27312
27313
27314
27315
27316
27317
27318
27319
27320 static struct sip_auth *find_realm_authentication(struct sip_auth_container *credentials, const char *realm)
27321 {
27322 struct sip_auth *auth;
27323
27324 if (credentials) {
27325 AST_LIST_TRAVERSE(&credentials->list, auth, node) {
27326 if (!strcasecmp(auth->realm, realm)) {
27327 break;
27328 }
27329 }
27330 } else {
27331 auth = NULL;
27332 }
27333
27334 return auth;
27335 }
27336
27337
27338
27339
27340 static struct ast_variable *add_var(const char *buf, struct ast_variable *list)
27341 {
27342 struct ast_variable *tmpvar = NULL;
27343 char *varname = ast_strdupa(buf), *varval = NULL;
27344
27345 if ((varval = strchr(varname, '='))) {
27346 *varval++ = '\0';
27347 if ((tmpvar = ast_variable_new(varname, varval, ""))) {
27348 tmpvar->next = list;
27349 list = tmpvar;
27350 }
27351 }
27352 return list;
27353 }
27354
27355
27356 static void set_peer_defaults(struct sip_peer *peer)
27357 {
27358 if (peer->expire == 0) {
27359
27360
27361
27362 peer->expire = -1;
27363 peer->pokeexpire = -1;
27364 set_socket_transport(&peer->socket, SIP_TRANSPORT_UDP);
27365 }
27366 peer->type = SIP_TYPE_PEER;
27367 ast_copy_flags(&peer->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
27368 ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
27369 ast_copy_flags(&peer->flags[2], &global_flags[2], SIP_PAGE3_FLAGS_TO_COPY);
27370 ast_string_field_set(peer, context, sip_cfg.default_context);
27371 ast_string_field_set(peer, subscribecontext, sip_cfg.default_subscribecontext);
27372 ast_string_field_set(peer, language, default_language);
27373 ast_string_field_set(peer, mohinterpret, default_mohinterpret);
27374 ast_string_field_set(peer, mohsuggest, default_mohsuggest);
27375 ast_string_field_set(peer, engine, default_engine);
27376 ast_sockaddr_setnull(&peer->addr);
27377 ast_sockaddr_setnull(&peer->defaddr);
27378 peer->capability = sip_cfg.capability;
27379 peer->maxcallbitrate = default_maxcallbitrate;
27380 peer->rtptimeout = global_rtptimeout;
27381 peer->rtpholdtimeout = global_rtpholdtimeout;
27382 peer->rtpkeepalive = global_rtpkeepalive;
27383 peer->allowtransfer = sip_cfg.allowtransfer;
27384 peer->autoframing = global_autoframing;
27385 peer->t38_maxdatagram = global_t38_maxdatagram;
27386 peer->qualifyfreq = global_qualifyfreq;
27387 if (global_callcounter)
27388 peer->call_limit=INT_MAX;
27389 ast_string_field_set(peer, vmexten, default_vmexten);
27390 ast_string_field_set(peer, secret, "");
27391 ast_string_field_set(peer, remotesecret, "");
27392 ast_string_field_set(peer, md5secret, "");
27393 ast_string_field_set(peer, cid_num, "");
27394 ast_string_field_set(peer, cid_name, "");
27395 ast_string_field_set(peer, cid_tag, "");
27396 ast_string_field_set(peer, fromdomain, "");
27397 ast_string_field_set(peer, fromuser, "");
27398 ast_string_field_set(peer, regexten, "");
27399 peer->callgroup = 0;
27400 peer->pickupgroup = 0;
27401 peer->maxms = default_qualify;
27402 peer->prefs = default_prefs;
27403 peer->stimer.st_mode_oper = global_st_mode;
27404 peer->stimer.st_ref = global_st_refresher;
27405 peer->stimer.st_min_se = global_min_se;
27406 peer->stimer.st_max_se = global_max_se;
27407 peer->timer_t1 = global_t1;
27408 peer->timer_b = global_timer_b;
27409 clear_peer_mailboxes(peer);
27410 peer->disallowed_methods = sip_cfg.disallowed_methods;
27411 peer->transports = default_transports;
27412 peer->default_outbound_transport = default_primary_transport;
27413 }
27414
27415
27416 static struct sip_peer *temp_peer(const char *name)
27417 {
27418 struct sip_peer *peer;
27419
27420 if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct")))
27421 return NULL;
27422
27423 if (ast_string_field_init(peer, 512)) {
27424 ao2_t_ref(peer, -1, "failed to string_field_init, drop peer");
27425 return NULL;
27426 }
27427
27428 if (!(peer->cc_params = ast_cc_config_params_init())) {
27429 ao2_t_ref(peer, -1, "failed to allocate cc_params for peer");
27430 return NULL;
27431 }
27432
27433 ast_atomic_fetchadd_int(&apeerobjs, 1);
27434 set_peer_defaults(peer);
27435
27436 ast_copy_string(peer->name, name, sizeof(peer->name));
27437
27438 peer->selfdestruct = TRUE;
27439 peer->host_dynamic = TRUE;
27440 peer->prefs = default_prefs;
27441 reg_source_db(peer);
27442
27443 return peer;
27444 }
27445
27446
27447 static void add_peer_mailboxes(struct sip_peer *peer, const char *value)
27448 {
27449 char *next, *mbox, *context;
27450
27451 next = ast_strdupa(value);
27452
27453 while ((mbox = context = strsep(&next, ","))) {
27454 struct sip_mailbox *mailbox;
27455 int duplicate = 0;
27456
27457 mbox = ast_strip(mbox);
27458 strsep(&context, "@");
27459
27460 if (ast_strlen_zero(mbox)) {
27461 continue;
27462 }
27463
27464
27465 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
27466 if (!strcmp(mailbox->mailbox, mbox) && !strcmp(S_OR(mailbox->context, ""), S_OR(context, ""))) {
27467 duplicate = 1;
27468 break;
27469 }
27470 }
27471 if (duplicate) {
27472 continue;
27473 }
27474
27475 if (!(mailbox = ast_calloc(1, sizeof(*mailbox) + strlen(mbox) + strlen(S_OR(context, ""))))) {
27476 continue;
27477 }
27478
27479 if (!ast_strlen_zero(context)) {
27480 mailbox->context = mailbox->mailbox + strlen(mbox) + 1;
27481 strcpy(mailbox->context, context);
27482 }
27483 strcpy(mailbox->mailbox, mbox);
27484
27485 AST_LIST_INSERT_TAIL(&peer->mailboxes, mailbox, entry);
27486 }
27487 }
27488
27489
27490 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only)
27491 {
27492 struct sip_peer *peer = NULL;
27493 struct ast_ha *oldha = NULL;
27494 struct ast_ha *olddirectmediaha = NULL;
27495 int found = 0;
27496 int firstpass = 1;
27497 uint16_t port = 0;
27498 int format = 0;
27499 int timerb_set = 0, timert1_set = 0;
27500 time_t regseconds = 0;
27501 struct ast_flags peerflags[3] = {{(0)}};
27502 struct ast_flags mask[3] = {{(0)}};
27503 char callback[256] = "";
27504 struct sip_peer tmp_peer;
27505 const char *srvlookup = NULL;
27506 static int deprecation_warning = 1;
27507 int alt_fullcontact = alt ? 1 : 0, headercount = 0;
27508 struct ast_str *fullcontact = ast_str_alloca(512);
27509
27510 if (!realtime || ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
27511
27512
27513
27514
27515
27516 ast_copy_string(tmp_peer.name, name, sizeof(tmp_peer.name));
27517 peer = ao2_t_find(peers, &tmp_peer, OBJ_POINTER | OBJ_UNLINK, "find and unlink peer from peers table");
27518 }
27519
27520 if (peer) {
27521
27522 found++;
27523
27524
27525 if (!ast_sockaddr_isnull(&peer->addr)) {
27526 ao2_t_unlink(peers_by_ip, peer, "ao2_unlink peer from peers_by_ip table");
27527 }
27528 if (!(peer->the_mark))
27529 firstpass = 0;
27530 } else {
27531 if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct")))
27532 return NULL;
27533
27534 if (ast_string_field_init(peer, 512)) {
27535 ao2_t_ref(peer, -1, "failed to string_field_init, drop peer");
27536 return NULL;
27537 }
27538
27539 if (!(peer->cc_params = ast_cc_config_params_init())) {
27540 ao2_t_ref(peer, -1, "failed to allocate cc_params for peer");
27541 return NULL;
27542 }
27543
27544 if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
27545 ast_atomic_fetchadd_int(&rpeerobjs, 1);
27546 ast_debug(3, "-REALTIME- peer built. Name: %s. Peer objects: %d\n", name, rpeerobjs);
27547 } else
27548 ast_atomic_fetchadd_int(&speerobjs, 1);
27549 }
27550
27551
27552 if (firstpass) {
27553 peer->lastmsgssent = -1;
27554 oldha = peer->ha;
27555 peer->ha = NULL;
27556 olddirectmediaha = peer->directmediaha;
27557 peer->directmediaha = NULL;
27558 set_peer_defaults(peer);
27559 peer->type = 0;
27560 }
27561
27562
27563 ast_copy_string(peer->name, name, sizeof(peer->name));
27564
27565
27566 if (peer->chanvars) {
27567 ast_variables_destroy(peer->chanvars);
27568 peer->chanvars = NULL;
27569
27570 }
27571
27572 if (found)
27573 peer->portinuri = 0;
27574
27575
27576 ao2_lock(peer);
27577 if (peer->auth) {
27578 ao2_t_ref(peer->auth, -1, "Removing old peer authentication");
27579 peer->auth = NULL;
27580 }
27581 ao2_unlock(peer);
27582
27583
27584 peer->default_outbound_transport = 0;
27585 peer->transports = 0;
27586
27587 if (!devstate_only) {
27588 struct sip_mailbox *mailbox;
27589 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
27590 mailbox->delme = 1;
27591 }
27592 }
27593
27594 for (; v || ((v = alt) && !(alt=NULL)); v = v->next) {
27595 if (!devstate_only) {
27596 if (handle_common_options(&peerflags[0], &mask[0], v)) {
27597 continue;
27598 }
27599 if (handle_t38_options(&peerflags[0], &mask[0], v, &peer->t38_maxdatagram)) {
27600 continue;
27601 }
27602 if (!strcasecmp(v->name, "transport")) {
27603 char *val = ast_strdupa(v->value);
27604 char *trans;
27605
27606 peer->transports = peer->default_outbound_transport = 0;
27607 while ((trans = strsep(&val, ","))) {
27608 trans = ast_skip_blanks(trans);
27609
27610 if (!strncasecmp(trans, "udp", 3)) {
27611 peer->transports |= SIP_TRANSPORT_UDP;
27612 } else if (sip_cfg.tcp_enabled && !strncasecmp(trans, "tcp", 3)) {
27613 peer->transports |= SIP_TRANSPORT_TCP;
27614 } else if (default_tls_cfg.enabled && !strncasecmp(trans, "tls", 3)) {
27615 peer->transports |= SIP_TRANSPORT_TLS;
27616 } else if (!strncasecmp(trans, "tcp", 3) || !strncasecmp(trans, "tls", 3)) {
27617 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);
27618 } else {
27619 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);
27620 }
27621
27622 if (!peer->default_outbound_transport) {
27623 peer->default_outbound_transport = peer->transports;
27624 }
27625 }
27626 } else if (realtime && !strcasecmp(v->name, "regseconds")) {
27627 ast_get_time_t(v->value, ®seconds, 0, NULL);
27628 } else if (realtime && !strcasecmp(v->name, "name")) {
27629 ast_copy_string(peer->name, v->value, sizeof(peer->name));
27630 } else if (realtime && !strcasecmp(v->name, "useragent")) {
27631 ast_string_field_set(peer, useragent, v->value);
27632 } else if (!strcasecmp(v->name, "type")) {
27633 if (!strcasecmp(v->value, "peer")) {
27634 peer->type |= SIP_TYPE_PEER;
27635 } else if (!strcasecmp(v->value, "user")) {
27636 peer->type |= SIP_TYPE_USER;
27637 } else if (!strcasecmp(v->value, "friend")) {
27638 peer->type = SIP_TYPE_USER | SIP_TYPE_PEER;
27639 }
27640 } else if (!strcasecmp(v->name, "remotesecret")) {
27641 ast_string_field_set(peer, remotesecret, v->value);
27642 } else if (!strcasecmp(v->name, "secret")) {
27643 ast_string_field_set(peer, secret, v->value);
27644 } else if (!strcasecmp(v->name, "md5secret")) {
27645 ast_string_field_set(peer, md5secret, v->value);
27646 } else if (!strcasecmp(v->name, "auth")) {
27647 add_realm_authentication(&peer->auth, v->value, v->lineno);
27648 } else if (!strcasecmp(v->name, "callerid")) {
27649 char cid_name[80] = { '\0' }, cid_num[80] = { '\0' };
27650
27651 ast_callerid_split(v->value, cid_name, sizeof(cid_name), cid_num, sizeof(cid_num));
27652 ast_string_field_set(peer, cid_name, cid_name);
27653 ast_string_field_set(peer, cid_num, cid_num);
27654 } else if (!strcasecmp(v->name, "mwi_from")) {
27655 ast_string_field_set(peer, mwi_from, v->value);
27656 } else if (!strcasecmp(v->name, "fullname")) {
27657 ast_string_field_set(peer, cid_name, v->value);
27658 } else if (!strcasecmp(v->name, "trunkname")) {
27659
27660 ast_string_field_set(peer, cid_name, "");
27661 } else if (!strcasecmp(v->name, "cid_number")) {
27662 ast_string_field_set(peer, cid_num, v->value);
27663 } else if (!strcasecmp(v->name, "cid_tag")) {
27664 ast_string_field_set(peer, cid_tag, v->value);
27665 } else if (!strcasecmp(v->name, "context")) {
27666 ast_string_field_set(peer, context, v->value);
27667 ast_set_flag(&peer->flags[1], SIP_PAGE2_HAVEPEERCONTEXT);
27668 } else if (!strcasecmp(v->name, "subscribecontext")) {
27669 ast_string_field_set(peer, subscribecontext, v->value);
27670 } else if (!strcasecmp(v->name, "fromdomain")) {
27671 char *fromdomainport;
27672 ast_string_field_set(peer, fromdomain, v->value);
27673 if ((fromdomainport = strchr(peer->fromdomain, ':'))) {
27674 *fromdomainport++ = '\0';
27675 if (!(peer->fromdomainport = port_str2int(fromdomainport, 0))) {
27676 ast_log(LOG_NOTICE, "'%s' is not a valid port number for fromdomain.\n",fromdomainport);
27677 }
27678 } else {
27679 peer->fromdomainport = STANDARD_SIP_PORT;
27680 }
27681 } else if (!strcasecmp(v->name, "usereqphone")) {
27682 ast_set2_flag(&peer->flags[0], ast_true(v->value), SIP_USEREQPHONE);
27683 } else if (!strcasecmp(v->name, "fromuser")) {
27684 ast_string_field_set(peer, fromuser, v->value);
27685 } else if (!strcasecmp(v->name, "outboundproxy")) {
27686 struct sip_proxy *proxy;
27687 if (ast_strlen_zero(v->value)) {
27688 ast_log(LOG_WARNING, "no value given for outbound proxy on line %d of sip.conf\n", v->lineno);
27689 continue;
27690 }
27691 proxy = proxy_from_config(v->value, v->lineno, peer->outboundproxy);
27692 if (!proxy) {
27693 ast_log(LOG_WARNING, "failure parsing the outbound proxy on line %d of sip.conf.\n", v->lineno);
27694 continue;
27695 }
27696 peer->outboundproxy = proxy;
27697 } else if (!strcasecmp(v->name, "host")) {
27698 if (!strcasecmp(v->value, "dynamic")) {
27699
27700 if (!found || !peer->host_dynamic) {
27701
27702
27703 ast_sockaddr_setnull(&peer->addr);
27704 }
27705 peer->host_dynamic = TRUE;
27706 } else {
27707
27708 AST_SCHED_DEL_UNREF(sched, peer->expire,
27709 unref_peer(peer, "removing register expire ref"));
27710 peer->host_dynamic = FALSE;
27711 srvlookup = v->value;
27712 }
27713 } else if (!strcasecmp(v->name, "defaultip")) {
27714 if (!ast_strlen_zero(v->value) && ast_get_ip(&peer->defaddr, v->value)) {
27715 unref_peer(peer, "unref_peer: from build_peer defaultip");
27716 return NULL;
27717 }
27718 } else if (!strcasecmp(v->name, "permit") || !strcasecmp(v->name, "deny")) {
27719 int ha_error = 0;
27720 if (!ast_strlen_zero(v->value)) {
27721 peer->ha = ast_append_ha(v->name, v->value, peer->ha, &ha_error);
27722 }
27723 if (ha_error) {
27724 ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
27725 }
27726 } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny")) {
27727 int ha_error = 0;
27728 if (!ast_strlen_zero(v->value)) {
27729 peer->contactha = ast_append_ha(v->name + 7, v->value, peer->contactha, &ha_error);
27730 }
27731 if (ha_error) {
27732 ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
27733 }
27734 } else if (!strcasecmp(v->name, "directmediapermit") || !strcasecmp(v->name, "directmediadeny")) {
27735 int ha_error = 0;
27736 peer->directmediaha = ast_append_ha(v->name + 11, v->value, peer->directmediaha, &ha_error);
27737 if (ha_error) {
27738 ast_log(LOG_ERROR, "Bad directmedia ACL entry in configuration line %d : %s\n", v->lineno, v->value);
27739 }
27740 } else if (!strcasecmp(v->name, "port")) {
27741 peer->portinuri = 1;
27742 if (!(port = port_str2int(v->value, 0))) {
27743 if (realtime) {
27744
27745 peer->portinuri = 0;
27746 } else {
27747 ast_log(LOG_WARNING, "Invalid peer port configuration at line %d : %s\n", v->lineno, v->value);
27748 }
27749 }
27750 } else if (!strcasecmp(v->name, "callingpres")) {
27751 peer->callingpres = ast_parse_caller_presentation(v->value);
27752 if (peer->callingpres == -1) {
27753 peer->callingpres = atoi(v->value);
27754 }
27755 } else if (!strcasecmp(v->name, "username") || !strcmp(v->name, "defaultuser")) {
27756 ast_string_field_set(peer, username, v->value);
27757 if (!strcasecmp(v->name, "username")) {
27758 if (deprecation_warning) {
27759 ast_log(LOG_NOTICE, "The 'username' field for sip peers has been deprecated in favor of the term 'defaultuser'\n");
27760 deprecation_warning = 0;
27761 }
27762 peer->deprecated_username = 1;
27763 }
27764 } else if (!strcasecmp(v->name, "language")) {
27765 ast_string_field_set(peer, language, v->value);
27766 } else if (!strcasecmp(v->name, "regexten")) {
27767 ast_string_field_set(peer, regexten, v->value);
27768 } else if (!strcasecmp(v->name, "callbackextension")) {
27769 ast_copy_string(callback, v->value, sizeof(callback));
27770 } else if (!strcasecmp(v->name, "amaflags")) {
27771 format = ast_cdr_amaflags2int(v->value);
27772 if (format < 0) {
27773 ast_log(LOG_WARNING, "Invalid AMA Flags for peer: %s at line %d\n", v->value, v->lineno);
27774 } else {
27775 peer->amaflags = format;
27776 }
27777 } else if (!strcasecmp(v->name, "maxforwards")) {
27778 if (sscanf(v->value, "%30d", &peer->maxforwards) != 1
27779 || peer->maxforwards < 1 || 255 < peer->maxforwards) {
27780 ast_log(LOG_WARNING, "'%s' is not a valid maxforwards value at line %d. Using default.\n", v->value, v->lineno);
27781 peer->maxforwards = sip_cfg.default_max_forwards;
27782 }
27783 } else if (!strcasecmp(v->name, "accountcode")) {
27784 ast_string_field_set(peer, accountcode, v->value);
27785 } else if (!strcasecmp(v->name, "mohinterpret")) {
27786 ast_string_field_set(peer, mohinterpret, v->value);
27787 } else if (!strcasecmp(v->name, "mohsuggest")) {
27788 ast_string_field_set(peer, mohsuggest, v->value);
27789 } else if (!strcasecmp(v->name, "parkinglot")) {
27790 ast_string_field_set(peer, parkinglot, v->value);
27791 } else if (!strcasecmp(v->name, "rtp_engine")) {
27792 ast_string_field_set(peer, engine, v->value);
27793 } else if (!strcasecmp(v->name, "mailbox")) {
27794 add_peer_mailboxes(peer, v->value);
27795 } else if (!strcasecmp(v->name, "hasvoicemail")) {
27796
27797
27798 if (ast_true(v->value) && AST_LIST_EMPTY(&peer->mailboxes)) {
27799 add_peer_mailboxes(peer, name);
27800 }
27801 } else if (!strcasecmp(v->name, "subscribemwi")) {
27802 ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_SUBSCRIBEMWIONLY);
27803 } else if (!strcasecmp(v->name, "vmexten")) {
27804 ast_string_field_set(peer, vmexten, v->value);
27805 } else if (!strcasecmp(v->name, "callgroup")) {
27806 peer->callgroup = ast_get_group(v->value);
27807 } else if (!strcasecmp(v->name, "allowtransfer")) {
27808 peer->allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
27809 } else if (!strcasecmp(v->name, "pickupgroup")) {
27810 peer->pickupgroup = ast_get_group(v->value);
27811 } else if (!strcasecmp(v->name, "allow")) {
27812 int error = ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, TRUE);
27813 if (error) {
27814 ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
27815 }
27816 } else if (!strcasecmp(v->name, "disallow")) {
27817 int error = ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, FALSE);
27818 if (error) {
27819 ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
27820 }
27821 } else if (!strcasecmp(v->name, "preferred_codec_only")) {
27822 ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_PREFERRED_CODEC);
27823 } else if (!strcasecmp(v->name, "autoframing")) {
27824 peer->autoframing = ast_true(v->value);
27825 } else if (!strcasecmp(v->name, "rtptimeout")) {
27826 if ((sscanf(v->value, "%30d", &peer->rtptimeout) != 1) || (peer->rtptimeout < 0)) {
27827 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
27828 peer->rtptimeout = global_rtptimeout;
27829 }
27830 } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
27831 if ((sscanf(v->value, "%30d", &peer->rtpholdtimeout) != 1) || (peer->rtpholdtimeout < 0)) {
27832 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
27833 peer->rtpholdtimeout = global_rtpholdtimeout;
27834 }
27835 } else if (!strcasecmp(v->name, "rtpkeepalive")) {
27836 if ((sscanf(v->value, "%30d", &peer->rtpkeepalive) != 1) || (peer->rtpkeepalive < 0)) {
27837 ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d. Using default.\n", v->value, v->lineno);
27838 peer->rtpkeepalive = global_rtpkeepalive;
27839 }
27840 } else if (!strcasecmp(v->name, "timert1")) {
27841 if ((sscanf(v->value, "%30d", &peer->timer_t1) != 1) || (peer->timer_t1 < 200) || (peer->timer_t1 < global_t1min)) {
27842 ast_log(LOG_WARNING, "'%s' is not a valid T1 time at line %d. Using default.\n", v->value, v->lineno);
27843 peer->timer_t1 = global_t1min;
27844 }
27845 timert1_set = 1;
27846 } else if (!strcasecmp(v->name, "timerb")) {
27847 if ((sscanf(v->value, "%30d", &peer->timer_b) != 1) || (peer->timer_b < 200)) {
27848 ast_log(LOG_WARNING, "'%s' is not a valid Timer B time at line %d. Using default.\n", v->value, v->lineno);
27849 peer->timer_b = global_timer_b;
27850 }
27851 timerb_set = 1;
27852 } else if (!strcasecmp(v->name, "setvar")) {
27853 peer->chanvars = add_var(v->value, peer->chanvars);
27854 } else if (!strcasecmp(v->name, "header")) {
27855 char tmp[4096];
27856 snprintf(tmp, sizeof(tmp), "__SIPADDHEADERpre%2d=%s", ++headercount, v->value);
27857 peer->chanvars = add_var(tmp, peer->chanvars);
27858 } else if (!strcasecmp(v->name, "qualifyfreq")) {
27859 int i;
27860 if (sscanf(v->value, "%30d", &i) == 1) {
27861 peer->qualifyfreq = i * 1000;
27862 } else {
27863 ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
27864 peer->qualifyfreq = global_qualifyfreq;
27865 }
27866 } else if (!strcasecmp(v->name, "maxcallbitrate")) {
27867 peer->maxcallbitrate = atoi(v->value);
27868 if (peer->maxcallbitrate < 0) {
27869 peer->maxcallbitrate = default_maxcallbitrate;
27870 }
27871 } else if (!strcasecmp(v->name, "session-timers")) {
27872 int i = (int) str2stmode(v->value);
27873 if (i < 0) {
27874 ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
27875 peer->stimer.st_mode_oper = global_st_mode;
27876 } else {
27877 peer->stimer.st_mode_oper = i;
27878 }
27879 } else if (!strcasecmp(v->name, "session-expires")) {
27880 if (sscanf(v->value, "%30d", &peer->stimer.st_max_se) != 1) {
27881 ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
27882 peer->stimer.st_max_se = global_max_se;
27883 }
27884 } else if (!strcasecmp(v->name, "session-minse")) {
27885 if (sscanf(v->value, "%30d", &peer->stimer.st_min_se) != 1) {
27886 ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
27887 peer->stimer.st_min_se = global_min_se;
27888 }
27889 if (peer->stimer.st_min_se < 90) {
27890 ast_log(LOG_WARNING, "session-minse '%s' at line %d of %s is not allowed to be < 90 secs\n", v->value, v->lineno, config);
27891 peer->stimer.st_min_se = global_min_se;
27892 }
27893 } else if (!strcasecmp(v->name, "session-refresher")) {
27894 int i = (int) str2strefresherparam(v->value);
27895 if (i < 0) {
27896 ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
27897 peer->stimer.st_ref = global_st_refresher;
27898 } else {
27899 peer->stimer.st_ref = i;
27900 }
27901 } else if (!strcasecmp(v->name, "disallowed_methods")) {
27902 char *disallow = ast_strdupa(v->value);
27903 mark_parsed_methods(&peer->disallowed_methods, disallow);
27904 } else if (!strcasecmp(v->name, "unsolicited_mailbox")) {
27905 ast_string_field_set(peer, unsolicited_mailbox, v->value);
27906 } else if (!strcasecmp(v->name, "use_q850_reason")) {
27907 ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_Q850_REASON);
27908 } else if (!strcasecmp(v->name, "encryption")) {
27909 ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_USE_SRTP);
27910 } else if (!strcasecmp(v->name, "snom_aoc_enabled")) {
27911 ast_set2_flag(&peer->flags[2], ast_true(v->value), SIP_PAGE3_SNOM_AOC);
27912 }
27913 }
27914
27915
27916 if (realtime && !strcasecmp(v->name, "lastms")) {
27917 sscanf(v->value, "%30d", &peer->lastms);
27918 } else if (realtime && !strcasecmp(v->name, "ipaddr") && !ast_strlen_zero(v->value) ) {
27919 ast_sockaddr_parse(&peer->addr, v->value, PARSE_PORT_FORBID);
27920 } else if (realtime && !strcasecmp(v->name, "fullcontact")) {
27921 if (alt_fullcontact && !alt) {
27922
27923
27924
27925
27926
27927 alt_fullcontact = 0;
27928 ast_str_reset(fullcontact);
27929 }
27930
27931 if (fullcontact->used > 0) {
27932 ast_str_append(&fullcontact, 0, ";%s", v->value);
27933 } else {
27934 ast_str_set(&fullcontact, 0, "%s", v->value);
27935 }
27936 } else if (!strcasecmp(v->name, "qualify")) {
27937 if (!strcasecmp(v->value, "no")) {
27938 peer->maxms = 0;
27939 } else if (!strcasecmp(v->value, "yes")) {
27940 peer->maxms = default_qualify ? default_qualify : DEFAULT_MAXMS;
27941 } else if (sscanf(v->value, "%30d", &peer->maxms) != 1) {
27942 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);
27943 peer->maxms = 0;
27944 }
27945 if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && peer->maxms > 0) {
27946
27947
27948
27949
27950 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);
27951 peer->maxms = 0;
27952 }
27953 } else if (!strcasecmp(v->name, "callcounter")) {
27954 peer->call_limit = ast_true(v->value) ? INT_MAX : 0;
27955 } else if (!strcasecmp(v->name, "call-limit")) {
27956 peer->call_limit = atoi(v->value);
27957 if (peer->call_limit < 0) {
27958 peer->call_limit = 0;
27959 }
27960 } else if (!strcasecmp(v->name, "busylevel")) {
27961 peer->busy_level = atoi(v->value);
27962 if (peer->busy_level < 0) {
27963 peer->busy_level = 0;
27964 }
27965 } else if (ast_cc_is_config_param(v->name)) {
27966 ast_cc_set_param(peer->cc_params, v->name, v->value);
27967 }
27968 }
27969
27970 if (!devstate_only) {
27971 struct sip_mailbox *mailbox;
27972 AST_LIST_TRAVERSE_SAFE_BEGIN(&peer->mailboxes, mailbox, entry) {
27973 if (mailbox->delme) {
27974 AST_LIST_REMOVE_CURRENT(entry);
27975 destroy_mailbox(mailbox);
27976 }
27977 }
27978 AST_LIST_TRAVERSE_SAFE_END;
27979 }
27980
27981 if (!can_parse_xml && (ast_get_cc_agent_policy(peer->cc_params) == AST_CC_AGENT_NATIVE)) {
27982 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);
27983 ast_set_cc_agent_policy(peer->cc_params, AST_CC_AGENT_NEVER);
27984 }
27985
27986
27987
27988 if (peer->timer_b < peer->timer_t1 * 64) {
27989 if (timerb_set && timert1_set) {
27990 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);
27991 } else if (timerb_set) {
27992 if ((peer->timer_t1 = peer->timer_b / 64) < global_t1min) {
27993 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);
27994 peer->timer_t1 = global_t1min;
27995 peer->timer_b = peer->timer_t1 * 64;
27996 }
27997 peer->timer_t1 = peer->timer_b / 64;
27998 } else {
27999 peer->timer_b = peer->timer_t1 * 64;
28000 }
28001 }
28002
28003 if (!peer->default_outbound_transport) {
28004
28005 peer->transports = default_transports;
28006
28007 peer->default_outbound_transport = default_primary_transport;
28008 }
28009
28010
28011
28012
28013
28014 if (((peer->socket.type != peer->default_outbound_transport) && (peer->expire == -1)) ||
28015 !(peer->socket.type & peer->transports) || !(peer->socket.type)) {
28016
28017 set_socket_transport(&peer->socket, peer->default_outbound_transport);
28018 }
28019
28020 if (ast_str_strlen(fullcontact)) {
28021 ast_string_field_set(peer, fullcontact, ast_str_buffer(fullcontact));
28022 peer->rt_fromcontact = TRUE;
28023
28024
28025
28026
28027
28028
28029
28030
28031 if (!ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) || ast_sockaddr_isnull(&peer->addr)) {
28032 __set_address_from_contact(fullcontact->str, &peer->addr, 0);
28033 }
28034 }
28035
28036 if (srvlookup && peer->dnsmgr == NULL) {
28037 char transport[MAXHOSTNAMELEN];
28038 char _srvlookup[MAXHOSTNAMELEN];
28039 char *params;
28040
28041 ast_copy_string(_srvlookup, srvlookup, sizeof(_srvlookup));
28042 if ((params = strchr(_srvlookup, ';'))) {
28043 *params++ = '\0';
28044 }
28045
28046 snprintf(transport, sizeof(transport), "_%s._%s", get_srv_service(peer->socket.type), get_srv_protocol(peer->socket.type));
28047
28048 peer->addr.ss.ss_family = get_address_family_filter(peer->socket.type);
28049 if (ast_dnsmgr_lookup_cb(_srvlookup, &peer->addr, &peer->dnsmgr, sip_cfg.srvlookup && !peer->portinuri ? transport : NULL,
28050 on_dns_update_peer, ref_peer(peer, "Store peer on dnsmgr"))) {
28051 ast_log(LOG_ERROR, "srvlookup failed for host: %s, on peer %s, removing peer\n", _srvlookup, peer->name);
28052 unref_peer(peer, "dnsmgr lookup failed, getting rid of peer dnsmgr ref");
28053 unref_peer(peer, "getting rid of a peer pointer");
28054 return NULL;
28055 }
28056 if (!peer->dnsmgr) {
28057
28058 unref_peer(peer, "dnsmgr disabled, unref peer");
28059 }
28060
28061 ast_string_field_set(peer, tohost, srvlookup);
28062
28063 if (global_dynamic_exclude_static && !ast_sockaddr_isnull(&peer->addr)) {
28064 int ha_error = 0;
28065 sip_cfg.contact_ha = ast_append_ha("deny", ast_sockaddr_stringify_addr(&peer->addr),
28066 sip_cfg.contact_ha, &ha_error);
28067 if (ha_error) {
28068 ast_log(LOG_ERROR, "Bad or unresolved host/IP entry in configuration for peer %s, cannot add to contact ACL\n", peer->name);
28069 }
28070 }
28071 } else if (peer->dnsmgr && !peer->host_dynamic) {
28072
28073 ast_dnsmgr_refresh(peer->dnsmgr);
28074 }
28075
28076 if (port && !realtime && peer->host_dynamic) {
28077 ast_sockaddr_set_port(&peer->defaddr, port);
28078 } else if (port) {
28079 ast_sockaddr_set_port(&peer->addr, port);
28080 }
28081
28082 if (ast_sockaddr_port(&peer->addr) == 0) {
28083 ast_sockaddr_set_port(&peer->addr,
28084 (peer->socket.type & SIP_TRANSPORT_TLS) ?
28085 STANDARD_TLS_PORT : STANDARD_SIP_PORT);
28086 }
28087 if (ast_sockaddr_port(&peer->defaddr) == 0) {
28088 ast_sockaddr_set_port(&peer->defaddr,
28089 (peer->socket.type & SIP_TRANSPORT_TLS) ?
28090 STANDARD_TLS_PORT : STANDARD_SIP_PORT);
28091 }
28092 if (!peer->socket.port) {
28093 peer->socket.port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
28094 }
28095
28096 if (!sip_cfg.ignore_regexpire && peer->host_dynamic && realtime) {
28097 time_t nowtime = time(NULL);
28098
28099 if ((nowtime - regseconds) > 0) {
28100 destroy_association(peer);
28101 memset(&peer->addr, 0, sizeof(peer->addr));
28102 peer->lastms = -1;
28103 ast_debug(1, "Bah, we're expired (%d/%d/%d)!\n", (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
28104 }
28105 }
28106
28107
28108 if (!devstate_only && realtime && peer->lastms > 0) {
28109 ref_peer(peer, "schedule qualify");
28110 sip_poke_peer(peer, 0);
28111 }
28112
28113 ast_copy_flags(&peer->flags[0], &peerflags[0], mask[0].flags);
28114 ast_copy_flags(&peer->flags[1], &peerflags[1], mask[1].flags);
28115 ast_copy_flags(&peer->flags[2], &peerflags[2], mask[2].flags);
28116 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
28117 sip_cfg.allowsubscribe = TRUE;
28118 }
28119
28120 if (peer->host_dynamic && (!peer->is_realtime || !sip_cfg.peer_rtupdate)) {
28121 reg_source_db(peer);
28122 }
28123
28124
28125
28126 if (!devstate_only && !ast_test_flag(&peer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY) &&
28127 !AST_LIST_EMPTY(&peer->mailboxes)) {
28128 add_peer_mwi_subs(peer);
28129
28130
28131
28132 sip_send_mwi_to_peer(peer, 1);
28133 }
28134
28135 peer->the_mark = 0;
28136
28137 ast_free_ha(oldha);
28138 ast_free_ha(olddirectmediaha);
28139 if (!ast_strlen_zero(callback)) {
28140 char *reg_string;
28141 if (ast_asprintf(®_string, "%s?%s:%s@%s/%s", peer->name, peer->username, !ast_strlen_zero(peer->remotesecret) ? peer->remotesecret : peer->secret, peer->tohost, callback) >= 0) {
28142 sip_register(reg_string, 0);
28143 ast_free(reg_string);
28144 }
28145 }
28146 return peer;
28147 }
28148
28149 static int peer_markall_func(void *device, void *arg, int flags)
28150 {
28151 struct sip_peer *peer = device;
28152 peer->the_mark = 1;
28153 return 0;
28154 }
28155
28156 static void display_nat_warning(const char *cat, int reason, struct ast_flags *flags) {
28157 int global_nat, specific_nat;
28158
28159 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))) {
28160 ast_log(LOG_WARNING, "!!! PLEASE NOTE: Setting 'nat' for a peer/user that differs from the global setting can make\n");
28161 ast_log(LOG_WARNING, "!!! the name of that peer/user discoverable by an attacker. Replies for non-existent peers/users\n");
28162 ast_log(LOG_WARNING, "!!! will be sent to a different port than replies for an existing peer/user. If at all possible,\n");
28163 ast_log(LOG_WARNING, "!!! use the global 'nat' setting and do not set 'nat' per peer/user.\n");
28164 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));
28165 }
28166 }
28167
28168 static void cleanup_all_regs(void)
28169 {
28170
28171
28172 ASTOBJ_CONTAINER_TRAVERSE(®l, 1, do {
28173 ASTOBJ_WRLOCK(iterator);
28174 if (iterator->call) {
28175 ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", iterator->username, iterator->hostname);
28176
28177 dialog_unlink_all(iterator->call);
28178 iterator->call = dialog_unref(iterator->call, "remove iterator->call from registry traversal");
28179 }
28180 if (iterator->expire > -1) {
28181 AST_SCHED_DEL_UNREF(sched, iterator->expire, registry_unref(iterator, "reg ptr unref from reload config"));
28182 }
28183 if (iterator->timeout > -1) {
28184 AST_SCHED_DEL_UNREF(sched, iterator->timeout, registry_unref(iterator, "reg ptr unref from reload config"));
28185 }
28186 if (iterator->dnsmgr) {
28187 ast_dnsmgr_release(iterator->dnsmgr);
28188 iterator->dnsmgr = NULL;
28189 registry_unref(iterator, "reg ptr unref from dnsmgr");
28190 }
28191 ASTOBJ_UNLOCK(iterator);
28192 } while(0));
28193 }
28194
28195
28196
28197
28198
28199
28200
28201 static int reload_config(enum channelreloadreason reason)
28202 {
28203 struct ast_config *cfg, *ucfg;
28204 struct ast_variable *v;
28205 struct sip_peer *peer;
28206 char *cat, *stringp, *context, *oldregcontext;
28207 char newcontexts[AST_MAX_CONTEXT], oldcontexts[AST_MAX_CONTEXT];
28208 struct ast_flags dummy[2];
28209 struct ast_flags config_flags = { reason == CHANNEL_MODULE_LOAD ? 0 : ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) ? 0 : CONFIG_FLAG_FILEUNCHANGED };
28210 int auto_sip_domains = FALSE;
28211 struct ast_sockaddr old_bindaddr = bindaddr;
28212 int registry_count = 0, peer_count = 0, timerb_set = 0, timert1_set = 0;
28213 int subscribe_network_change = 1;
28214 time_t run_start, run_end;
28215 int bindport = 0;
28216
28217 run_start = time(0);
28218 ast_unload_realtime("sipregs");
28219 ast_unload_realtime("sippeers");
28220 cfg = ast_config_load(config, config_flags);
28221
28222
28223 if (!cfg) {
28224 ast_log(LOG_NOTICE, "Unable to load config %s\n", config);
28225 return -1;
28226 } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
28227 ucfg = ast_config_load("users.conf", config_flags);
28228 if (ucfg == CONFIG_STATUS_FILEUNCHANGED) {
28229 return 1;
28230 } else if (ucfg == CONFIG_STATUS_FILEINVALID) {
28231 ast_log(LOG_ERROR, "Contents of users.conf are invalid and cannot be parsed\n");
28232 return 1;
28233 }
28234
28235 ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
28236 if ((cfg = ast_config_load(config, config_flags)) == CONFIG_STATUS_FILEINVALID) {
28237 ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed\n", config);
28238 ast_config_destroy(ucfg);
28239 return 1;
28240 }
28241 if (!cfg) {
28242
28243 ast_log(LOG_NOTICE, "Unable to load config %s\n", config);
28244 return -1;
28245 }
28246 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
28247 ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed\n", config);
28248 return 1;
28249 } else {
28250 ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
28251 if ((ucfg = ast_config_load("users.conf", config_flags)) == CONFIG_STATUS_FILEINVALID) {
28252 ast_log(LOG_ERROR, "Contents of users.conf are invalid and cannot be parsed\n");
28253 ast_config_destroy(cfg);
28254 return 1;
28255 }
28256 }
28257
28258 ast_free_ha(sip_cfg.contact_ha);
28259 sip_cfg.contact_ha = NULL;
28260
28261 default_tls_cfg.enabled = FALSE;
28262
28263 if (reason != CHANNEL_MODULE_LOAD) {
28264 ast_debug(4, "--------------- SIP reload started\n");
28265
28266 clear_sip_domains();
28267 ast_mutex_lock(&authl_lock);
28268 if (authl) {
28269 ao2_t_ref(authl, -1, "Removing old global authentication");
28270 authl = NULL;
28271 }
28272 ast_mutex_unlock(&authl_lock);
28273
28274
28275 cleanup_all_regs();
28276
28277 ASTOBJ_CONTAINER_DESTROYALL(®l, sip_registry_destroy);
28278 ast_debug(4, "--------------- Done destroying registry list\n");
28279 ao2_t_callback(peers, OBJ_NODATA, peer_markall_func, NULL, "callback to mark all peers");
28280 }
28281
28282
28283 if (reason != CHANNEL_MODULE_LOAD) {
28284 ast_free(default_tls_cfg.certfile);
28285 ast_free(default_tls_cfg.pvtfile);
28286 ast_free(default_tls_cfg.cipher);
28287 ast_free(default_tls_cfg.cafile);
28288 ast_free(default_tls_cfg.capath);
28289 }
28290 default_tls_cfg.certfile = ast_strdup(AST_CERTFILE);
28291 default_tls_cfg.pvtfile = ast_strdup("");
28292 default_tls_cfg.cipher = ast_strdup("");
28293 default_tls_cfg.cafile = ast_strdup("");
28294 default_tls_cfg.capath = ast_strdup("");
28295
28296
28297 ast_copy_string(oldcontexts, sip_cfg.regcontext, sizeof(oldcontexts));
28298 oldregcontext = oldcontexts;
28299
28300
28301
28302 sipdebug &= sip_debug_console;
28303 ast_clear_flag(&global_flags[0], AST_FLAGS_ALL);
28304 ast_clear_flag(&global_flags[1], AST_FLAGS_ALL);
28305 ast_clear_flag(&global_flags[2], AST_FLAGS_ALL);
28306
28307
28308 ast_sockaddr_parse(&bindaddr, "0.0.0.0:0", 0);
28309 memset(&internip, 0, sizeof(internip));
28310
28311
28312 ast_free_ha(localaddr);
28313 memset(&localaddr, 0, sizeof(localaddr));
28314 memset(&externaddr, 0, sizeof(externaddr));
28315 memset(&media_address, 0, sizeof(media_address));
28316 memset(&default_prefs, 0 , sizeof(default_prefs));
28317 memset(&sip_cfg.outboundproxy, 0, sizeof(struct sip_proxy));
28318 sip_cfg.outboundproxy.force = FALSE;
28319 default_transports = SIP_TRANSPORT_UDP;
28320 default_primary_transport = SIP_TRANSPORT_UDP;
28321 ourport_tcp = STANDARD_SIP_PORT;
28322 ourport_tls = STANDARD_TLS_PORT;
28323 externtcpport = STANDARD_SIP_PORT;
28324 externtlsport = STANDARD_TLS_PORT;
28325 sip_cfg.srvlookup = DEFAULT_SRVLOOKUP;
28326 global_tos_sip = DEFAULT_TOS_SIP;
28327 global_tos_audio = DEFAULT_TOS_AUDIO;
28328 global_tos_video = DEFAULT_TOS_VIDEO;
28329 global_tos_text = DEFAULT_TOS_TEXT;
28330 global_cos_sip = DEFAULT_COS_SIP;
28331 global_cos_audio = DEFAULT_COS_AUDIO;
28332 global_cos_video = DEFAULT_COS_VIDEO;
28333 global_cos_text = DEFAULT_COS_TEXT;
28334
28335 externhost[0] = '\0';
28336 externexpire = 0;
28337 externrefresh = 10;
28338
28339
28340 sip_cfg.allow_external_domains = DEFAULT_ALLOW_EXT_DOM;
28341 sip_cfg.regcontext[0] = '\0';
28342 sip_cfg.capability = DEFAULT_CAPABILITY;
28343 sip_cfg.regextenonqualify = DEFAULT_REGEXTENONQUALIFY;
28344 sip_cfg.legacy_useroption_parsing = DEFAULT_LEGACY_USEROPTION_PARSING;
28345 sip_cfg.notifyringing = DEFAULT_NOTIFYRINGING;
28346 sip_cfg.notifycid = DEFAULT_NOTIFYCID;
28347 sip_cfg.notifyhold = FALSE;
28348 sip_cfg.directrtpsetup = FALSE;
28349 sip_cfg.alwaysauthreject = DEFAULT_ALWAYSAUTHREJECT;
28350 sip_cfg.auth_options_requests = DEFAULT_AUTH_OPTIONS;
28351 sip_cfg.allowsubscribe = FALSE;
28352 sip_cfg.disallowed_methods = SIP_UNKNOWN;
28353 sip_cfg.contact_ha = NULL;
28354 snprintf(global_useragent, sizeof(global_useragent), "%s %s", DEFAULT_USERAGENT, ast_get_version());
28355 snprintf(global_sdpsession, sizeof(global_sdpsession), "%s %s", DEFAULT_SDPSESSION, ast_get_version());
28356 snprintf(global_sdpowner, sizeof(global_sdpowner), "%s", DEFAULT_SDPOWNER);
28357 global_prematuremediafilter = TRUE;
28358 ast_copy_string(default_notifymime, DEFAULT_NOTIFYMIME, sizeof(default_notifymime));
28359 ast_copy_string(sip_cfg.realm, S_OR(ast_config_AST_SYSTEM_NAME, DEFAULT_REALM), sizeof(sip_cfg.realm));
28360 sip_cfg.domainsasrealm = DEFAULT_DOMAINSASREALM;
28361 ast_copy_string(default_callerid, DEFAULT_CALLERID, sizeof(default_callerid));
28362 ast_copy_string(default_mwi_from, DEFAULT_MWI_FROM, sizeof(default_mwi_from));
28363 sip_cfg.compactheaders = DEFAULT_COMPACTHEADERS;
28364 global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
28365 global_regattempts_max = 0;
28366 sip_cfg.pedanticsipchecking = DEFAULT_PEDANTIC;
28367 sip_cfg.autocreatepeer = DEFAULT_AUTOCREATEPEER;
28368 global_autoframing = 0;
28369 sip_cfg.allowguest = DEFAULT_ALLOWGUEST;
28370 global_callcounter = DEFAULT_CALLCOUNTER;
28371 global_match_auth_username = FALSE;
28372 global_rtptimeout = 0;
28373 global_rtpholdtimeout = 0;
28374 global_rtpkeepalive = DEFAULT_RTPKEEPALIVE;
28375 sip_cfg.allowtransfer = TRANSFER_OPENFORALL;
28376 sip_cfg.rtautoclear = 120;
28377 ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE);
28378 ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP_YES);
28379 sip_cfg.peer_rtupdate = TRUE;
28380 global_dynamic_exclude_static = 0;
28381 sip_cfg.tcp_enabled = FALSE;
28382
28383
28384 global_st_mode = SESSION_TIMER_MODE_ACCEPT;
28385 global_st_refresher = SESSION_TIMER_REFRESHER_PARAM_UAS;
28386 global_min_se = DEFAULT_MIN_SE;
28387 global_max_se = DEFAULT_MAX_SE;
28388
28389
28390 global_qualify_gap = DEFAULT_QUALIFY_GAP;
28391 global_qualify_peers = DEFAULT_QUALIFY_PEERS;
28392
28393
28394 ast_copy_string(sip_cfg.default_context, DEFAULT_CONTEXT, sizeof(sip_cfg.default_context));
28395 sip_cfg.default_subscribecontext[0] = '\0';
28396 sip_cfg.default_max_forwards = DEFAULT_MAX_FORWARDS;
28397 default_language[0] = '\0';
28398 default_fromdomain[0] = '\0';
28399 default_fromdomainport = 0;
28400 default_qualify = DEFAULT_QUALIFY;
28401 default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
28402 ast_copy_string(default_mohinterpret, DEFAULT_MOHINTERPRET, sizeof(default_mohinterpret));
28403 ast_copy_string(default_mohsuggest, DEFAULT_MOHSUGGEST, sizeof(default_mohsuggest));
28404 ast_copy_string(default_vmexten, DEFAULT_VMEXTEN, sizeof(default_vmexten));
28405 ast_set_flag(&global_flags[0], SIP_DTMF_RFC2833);
28406 ast_set_flag(&global_flags[0], SIP_DIRECT_MEDIA);
28407 ast_set_flag(&global_flags[0], SIP_NAT_FORCE_RPORT);
28408 ast_copy_string(default_engine, DEFAULT_ENGINE, sizeof(default_engine));
28409 ast_copy_string(default_parkinglot, DEFAULT_PARKINGLOT, sizeof(default_parkinglot));
28410
28411
28412 dumphistory = FALSE;
28413 recordhistory = FALSE;
28414 sipdebug &= ~sip_debug_config;
28415
28416
28417 global_relaxdtmf = FALSE;
28418 sip_cfg.callevents = DEFAULT_CALLEVENTS;
28419 global_authfailureevents = FALSE;
28420 global_t1 = DEFAULT_TIMER_T1;
28421 global_timer_b = 64 * DEFAULT_TIMER_T1;
28422 global_t1min = DEFAULT_T1MIN;
28423 global_qualifyfreq = DEFAULT_QUALIFYFREQ;
28424 global_t38_maxdatagram = -1;
28425 global_shrinkcallerid = 1;
28426 authlimit = DEFAULT_AUTHLIMIT;
28427 authtimeout = DEFAULT_AUTHTIMEOUT;
28428 global_store_sip_cause = DEFAULT_STORE_SIP_CAUSE;
28429
28430 sip_cfg.matchexternaddrlocally = DEFAULT_MATCHEXTERNADDRLOCALLY;
28431
28432
28433 memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
28434
28435 ast_clear_flag(&global_flags[1], SIP_PAGE2_FAX_DETECT);
28436 ast_clear_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT | SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
28437 ast_clear_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT);
28438 ast_clear_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION);
28439
28440
28441
28442 for (v = ast_variable_browse(cfg, "general"); v; v = v->next) {
28443 if (handle_common_options(&global_flags[0], &dummy[0], v)) {
28444 continue;
28445 }
28446 if (handle_t38_options(&global_flags[0], &dummy[0], v, &global_t38_maxdatagram)) {
28447 continue;
28448 }
28449
28450 if (!ast_jb_read_conf(&global_jbconf, v->name, v->value))
28451 continue;
28452
28453
28454 if (!ast_tls_read_conf(&default_tls_cfg, &sip_tls_desc, v->name, v->value)) {
28455 continue;
28456 }
28457
28458 if (!strcasecmp(v->name, "context")) {
28459 ast_copy_string(sip_cfg.default_context, v->value, sizeof(sip_cfg.default_context));
28460 } else if (!strcasecmp(v->name, "subscribecontext")) {
28461 ast_copy_string(sip_cfg.default_subscribecontext, v->value, sizeof(sip_cfg.default_subscribecontext));
28462 } else if (!strcasecmp(v->name, "callcounter")) {
28463 global_callcounter = ast_true(v->value) ? 1 : 0;
28464 } else if (!strcasecmp(v->name, "allowguest")) {
28465 sip_cfg.allowguest = ast_true(v->value) ? 1 : 0;
28466 } else if (!strcasecmp(v->name, "realm")) {
28467 ast_copy_string(sip_cfg.realm, v->value, sizeof(sip_cfg.realm));
28468 } else if (!strcasecmp(v->name, "domainsasrealm")) {
28469 sip_cfg.domainsasrealm = ast_true(v->value);
28470 } else if (!strcasecmp(v->name, "useragent")) {
28471 ast_copy_string(global_useragent, v->value, sizeof(global_useragent));
28472 ast_debug(1, "Setting SIP channel User-Agent Name to %s\n", global_useragent);
28473 } else if (!strcasecmp(v->name, "sdpsession")) {
28474 ast_copy_string(global_sdpsession, v->value, sizeof(global_sdpsession));
28475 } else if (!strcasecmp(v->name, "sdpowner")) {
28476
28477 if (!strstr(v->value, " ")) {
28478 ast_copy_string(global_sdpowner, v->value, sizeof(global_sdpowner));
28479 } else {
28480 ast_log(LOG_WARNING, "'%s' must not contain spaces at line %d. Using default.\n", v->value, v->lineno);
28481 }
28482 } else if (!strcasecmp(v->name, "allowtransfer")) {
28483 sip_cfg.allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
28484 } else if (!strcasecmp(v->name, "rtcachefriends")) {
28485 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTCACHEFRIENDS);
28486 } else if (!strcasecmp(v->name, "rtsavesysname")) {
28487 sip_cfg.rtsave_sysname = ast_true(v->value);
28488 } else if (!strcasecmp(v->name, "rtupdate")) {
28489 sip_cfg.peer_rtupdate = ast_true(v->value);
28490 } else if (!strcasecmp(v->name, "ignoreregexpire")) {
28491 sip_cfg.ignore_regexpire = ast_true(v->value);
28492 } else if (!strcasecmp(v->name, "timert1")) {
28493
28494
28495
28496 global_t1 = atoi(v->value);
28497 } else if (!strcasecmp(v->name, "timerb")) {
28498 int tmp = atoi(v->value);
28499 if (tmp < 500) {
28500 global_timer_b = global_t1 * 64;
28501 ast_log(LOG_WARNING, "Invalid value for timerb ('%s'). Setting to default ('%d').\n", v->value, global_timer_b);
28502 }
28503 timerb_set = 1;
28504 } else if (!strcasecmp(v->name, "t1min")) {
28505 global_t1min = atoi(v->value);
28506 } else if (!strcasecmp(v->name, "transport")) {
28507 char *val = ast_strdupa(v->value);
28508 char *trans;
28509
28510 default_transports = default_primary_transport = 0;
28511 while ((trans = strsep(&val, ","))) {
28512 trans = ast_skip_blanks(trans);
28513
28514 if (!strncasecmp(trans, "udp", 3)) {
28515 default_transports |= SIP_TRANSPORT_UDP;
28516 } else if (!strncasecmp(trans, "tcp", 3)) {
28517 default_transports |= SIP_TRANSPORT_TCP;
28518 } else if (!strncasecmp(trans, "tls", 3)) {
28519 default_transports |= SIP_TRANSPORT_TLS;
28520 } else {
28521 ast_log(LOG_NOTICE, "'%s' is not a valid transport type. if no other is specified, udp will be used.\n", trans);
28522 }
28523 if (default_primary_transport == 0) {
28524 default_primary_transport = default_transports;
28525 }
28526 }
28527 } else if (!strcasecmp(v->name, "tcpenable")) {
28528 if (!ast_false(v->value)) {
28529 ast_debug(2, "Enabling TCP socket for listening\n");
28530 sip_cfg.tcp_enabled = TRUE;
28531 }
28532 } else if (!strcasecmp(v->name, "tcpbindaddr")) {
28533 if (ast_parse_arg(v->value, PARSE_ADDR,
28534 &sip_tcp_desc.local_address)) {
28535 ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n",
28536 v->name, v->value, v->lineno, config);
28537 }
28538 ast_debug(2, "Setting TCP socket address to %s\n",
28539 ast_sockaddr_stringify(&sip_tcp_desc.local_address));
28540 } else if (!strcasecmp(v->name, "dynamic_exclude_static") || !strcasecmp(v->name, "dynamic_excludes_static")) {
28541 global_dynamic_exclude_static = ast_true(v->value);
28542 } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny")) {
28543 int ha_error = 0;
28544 sip_cfg.contact_ha = ast_append_ha(v->name + 7, v->value, sip_cfg.contact_ha, &ha_error);
28545 if (ha_error) {
28546 ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
28547 }
28548 } else if (!strcasecmp(v->name, "rtautoclear")) {
28549 int i = atoi(v->value);
28550 if (i > 0) {
28551 sip_cfg.rtautoclear = i;
28552 } else {
28553 i = 0;
28554 }
28555 ast_set2_flag(&global_flags[1], i || ast_true(v->value), SIP_PAGE2_RTAUTOCLEAR);
28556 } else if (!strcasecmp(v->name, "usereqphone")) {
28557 ast_set2_flag(&global_flags[0], ast_true(v->value), SIP_USEREQPHONE);
28558 } else if (!strcasecmp(v->name, "prematuremedia")) {
28559 global_prematuremediafilter = ast_true(v->value);
28560 } else if (!strcasecmp(v->name, "relaxdtmf")) {
28561 global_relaxdtmf = ast_true(v->value);
28562 } else if (!strcasecmp(v->name, "vmexten")) {
28563 ast_copy_string(default_vmexten, v->value, sizeof(default_vmexten));
28564 } else if (!strcasecmp(v->name, "rtptimeout")) {
28565 if ((sscanf(v->value, "%30d", &global_rtptimeout) != 1) || (global_rtptimeout < 0)) {
28566 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
28567 global_rtptimeout = 0;
28568 }
28569 } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
28570 if ((sscanf(v->value, "%30d", &global_rtpholdtimeout) != 1) || (global_rtpholdtimeout < 0)) {
28571 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
28572 global_rtpholdtimeout = 0;
28573 }
28574 } else if (!strcasecmp(v->name, "rtpkeepalive")) {
28575 if ((sscanf(v->value, "%30d", &global_rtpkeepalive) != 1) || (global_rtpkeepalive < 0)) {
28576 ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d. Using default.\n", v->value, v->lineno);
28577 global_rtpkeepalive = DEFAULT_RTPKEEPALIVE;
28578 }
28579 } else if (!strcasecmp(v->name, "compactheaders")) {
28580 sip_cfg.compactheaders = ast_true(v->value);
28581 } else if (!strcasecmp(v->name, "notifymimetype")) {
28582 ast_copy_string(default_notifymime, v->value, sizeof(default_notifymime));
28583 } else if (!strcasecmp(v->name, "directrtpsetup")) {
28584 sip_cfg.directrtpsetup = ast_true(v->value);
28585 } else if (!strcasecmp(v->name, "notifyringing")) {
28586 sip_cfg.notifyringing = ast_true(v->value);
28587 } else if (!strcasecmp(v->name, "notifyhold")) {
28588 sip_cfg.notifyhold = ast_true(v->value);
28589 } else if (!strcasecmp(v->name, "notifycid")) {
28590 if (!strcasecmp(v->value, "ignore-context")) {
28591 sip_cfg.notifycid = IGNORE_CONTEXT;
28592 } else {
28593 sip_cfg.notifycid = ast_true(v->value) ? ENABLED : DISABLED;
28594 }
28595 } else if (!strcasecmp(v->name, "alwaysauthreject")) {
28596 sip_cfg.alwaysauthreject = ast_true(v->value);
28597 } else if (!strcasecmp(v->name, "auth_options_requests")) {
28598 if (ast_true(v->value)) {
28599 sip_cfg.auth_options_requests = 1;
28600 }
28601 } else if (!strcasecmp(v->name, "mohinterpret")) {
28602 ast_copy_string(default_mohinterpret, v->value, sizeof(default_mohinterpret));
28603 } else if (!strcasecmp(v->name, "mohsuggest")) {
28604 ast_copy_string(default_mohsuggest, v->value, sizeof(default_mohsuggest));
28605 } else if (!strcasecmp(v->name, "language")) {
28606 ast_copy_string(default_language, v->value, sizeof(default_language));
28607 } else if (!strcasecmp(v->name, "regcontext")) {
28608 ast_copy_string(newcontexts, v->value, sizeof(newcontexts));
28609 stringp = newcontexts;
28610
28611 cleanup_stale_contexts(stringp, oldregcontext);
28612
28613 while ((context = strsep(&stringp, "&"))) {
28614 ast_copy_string(used_context, context, sizeof(used_context));
28615 ast_context_find_or_create(NULL, NULL, context, "SIP");
28616 }
28617 ast_copy_string(sip_cfg.regcontext, v->value, sizeof(sip_cfg.regcontext));
28618 } else if (!strcasecmp(v->name, "regextenonqualify")) {
28619 sip_cfg.regextenonqualify = ast_true(v->value);
28620 } else if (!strcasecmp(v->name, "legacy_useroption_parsing")) {
28621 sip_cfg.legacy_useroption_parsing = ast_true(v->value);
28622 } else if (!strcasecmp(v->name, "callerid")) {
28623 ast_copy_string(default_callerid, v->value, sizeof(default_callerid));
28624 } else if (!strcasecmp(v->name, "mwi_from")) {
28625 ast_copy_string(default_mwi_from, v->value, sizeof(default_mwi_from));
28626 } else if (!strcasecmp(v->name, "fromdomain")) {
28627 char *fromdomainport;
28628 ast_copy_string(default_fromdomain, v->value, sizeof(default_fromdomain));
28629 if ((fromdomainport = strchr(default_fromdomain, ':'))) {
28630 *fromdomainport++ = '\0';
28631 if (!(default_fromdomainport = port_str2int(fromdomainport, 0))) {
28632 ast_log(LOG_NOTICE, "'%s' is not a valid port number for fromdomain.\n",fromdomainport);
28633 }
28634 } else {
28635 default_fromdomainport = STANDARD_SIP_PORT;
28636 }
28637 } else if (!strcasecmp(v->name, "outboundproxy")) {
28638 struct sip_proxy *proxy;
28639 if (ast_strlen_zero(v->value)) {
28640 ast_log(LOG_WARNING, "no value given for outbound proxy on line %d of sip.conf\n", v->lineno);
28641 continue;
28642 }
28643 proxy = proxy_from_config(v->value, v->lineno, &sip_cfg.outboundproxy);
28644 if (!proxy) {
28645 ast_log(LOG_WARNING, "failure parsing the outbound proxy on line %d of sip.conf.\n", v->lineno);
28646 continue;
28647 }
28648 } else if (!strcasecmp(v->name, "autocreatepeer")) {
28649 sip_cfg.autocreatepeer = ast_true(v->value);
28650 } else if (!strcasecmp(v->name, "match_auth_username")) {
28651 global_match_auth_username = ast_true(v->value);
28652 } else if (!strcasecmp(v->name, "srvlookup")) {
28653 sip_cfg.srvlookup = ast_true(v->value);
28654 } else if (!strcasecmp(v->name, "pedantic")) {
28655 sip_cfg.pedanticsipchecking = ast_true(v->value);
28656 } else if (!strcasecmp(v->name, "maxexpirey") || !strcasecmp(v->name, "maxexpiry")) {
28657 max_expiry = atoi(v->value);
28658 if (max_expiry < 1) {
28659 max_expiry = DEFAULT_MAX_EXPIRY;
28660 }
28661 } else if (!strcasecmp(v->name, "minexpirey") || !strcasecmp(v->name, "minexpiry")) {
28662 min_expiry = atoi(v->value);
28663 if (min_expiry < 1) {
28664 min_expiry = DEFAULT_MIN_EXPIRY;
28665 }
28666 } else if (!strcasecmp(v->name, "defaultexpiry") || !strcasecmp(v->name, "defaultexpirey")) {
28667 default_expiry = atoi(v->value);
28668 if (default_expiry < 1) {
28669 default_expiry = DEFAULT_DEFAULT_EXPIRY;
28670 }
28671 } else if (!strcasecmp(v->name, "mwiexpiry") || !strcasecmp(v->name, "mwiexpirey")) {
28672 mwi_expiry = atoi(v->value);
28673 if (mwi_expiry < 1) {
28674 mwi_expiry = DEFAULT_MWI_EXPIRY;
28675 }
28676 } else if (!strcasecmp(v->name, "tcpauthtimeout")) {
28677 if (ast_parse_arg(v->value, PARSE_INT32|PARSE_DEFAULT|PARSE_IN_RANGE,
28678 &authtimeout, DEFAULT_AUTHTIMEOUT, 1, INT_MAX)) {
28679 ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n",
28680 v->name, v->value, v->lineno, config);
28681 }
28682 } else if (!strcasecmp(v->name, "tcpauthlimit")) {
28683 if (ast_parse_arg(v->value, PARSE_INT32|PARSE_DEFAULT|PARSE_IN_RANGE,
28684 &authlimit, DEFAULT_AUTHLIMIT, 1, INT_MAX)) {
28685 ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n",
28686 v->name, v->value, v->lineno, config);
28687 }
28688 } else if (!strcasecmp(v->name, "sipdebug")) {
28689 if (ast_true(v->value))
28690 sipdebug |= sip_debug_config;
28691 } else if (!strcasecmp(v->name, "dumphistory")) {
28692 dumphistory = ast_true(v->value);
28693 } else if (!strcasecmp(v->name, "recordhistory")) {
28694 recordhistory = ast_true(v->value);
28695 } else if (!strcasecmp(v->name, "registertimeout")) {
28696 global_reg_timeout = atoi(v->value);
28697 if (global_reg_timeout < 1) {
28698 global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
28699 }
28700 } else if (!strcasecmp(v->name, "registerattempts")) {
28701 global_regattempts_max = atoi(v->value);
28702 } else if (!strcasecmp(v->name, "bindaddr") || !strcasecmp(v->name, "udpbindaddr")) {
28703 if (ast_parse_arg(v->value, PARSE_ADDR, &bindaddr)) {
28704 ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
28705 }
28706 } else if (!strcasecmp(v->name, "localnet")) {
28707 struct ast_ha *na;
28708 int ha_error = 0;
28709
28710 if (!(na = ast_append_ha("d", v->value, localaddr, &ha_error))) {
28711 ast_log(LOG_WARNING, "Invalid localnet value: %s\n", v->value);
28712 } else {
28713 localaddr = na;
28714 }
28715 if (ha_error) {
28716 ast_log(LOG_ERROR, "Bad localnet configuration value line %d : %s\n", v->lineno, v->value);
28717 }
28718 } else if (!strcasecmp(v->name, "media_address")) {
28719 if (ast_parse_arg(v->value, PARSE_ADDR, &media_address))
28720 ast_log(LOG_WARNING, "Invalid address for media_address keyword: %s\n", v->value);
28721 } else if (!strcasecmp(v->name, "externaddr") || !strcasecmp(v->name, "externip")) {
28722 if (ast_parse_arg(v->value, PARSE_ADDR, &externaddr)) {
28723 ast_log(LOG_WARNING,
28724 "Invalid address for externaddr keyword: %s\n",
28725 v->value);
28726 }
28727 externexpire = 0;
28728 } else if (!strcasecmp(v->name, "externhost")) {
28729 ast_copy_string(externhost, v->value, sizeof(externhost));
28730 if (ast_sockaddr_resolve_first(&externaddr, externhost, 0)) {
28731 ast_log(LOG_WARNING, "Invalid address for externhost keyword: %s\n", externhost);
28732 }
28733 externexpire = time(NULL);
28734 } else if (!strcasecmp(v->name, "externrefresh")) {
28735 if (sscanf(v->value, "%30d", &externrefresh) != 1) {
28736 ast_log(LOG_WARNING, "Invalid externrefresh value '%s', must be an integer >0 at line %d\n", v->value, v->lineno);
28737 externrefresh = 10;
28738 }
28739 } else if (!strcasecmp(v->name, "externtcpport")) {
28740 if (!(externtcpport = port_str2int(v->value, 0))) {
28741 ast_log(LOG_WARNING, "Invalid externtcpport value, must be a positive integer between 1 and 65535 at line %d\n", v->lineno);
28742 externtcpport = 0;
28743 }
28744 } else if (!strcasecmp(v->name, "externtlsport")) {
28745 if (!(externtlsport = port_str2int(v->value, STANDARD_TLS_PORT))) {
28746 ast_log(LOG_WARNING, "Invalid externtlsport value, must be a positive integer between 1 and 65535 at line %d\n", v->lineno);
28747 }
28748 } else if (!strcasecmp(v->name, "allow")) {
28749 int error = ast_parse_allow_disallow(&default_prefs, &sip_cfg.capability, v->value, TRUE);
28750 if (error) {
28751 ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
28752 }
28753 } else if (!strcasecmp(v->name, "disallow")) {
28754 int error = ast_parse_allow_disallow(&default_prefs, &sip_cfg.capability, v->value, FALSE);
28755 if (error) {
28756 ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
28757 }
28758 } else if (!strcasecmp(v->name, "preferred_codec_only")) {
28759 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_PREFERRED_CODEC);
28760 } else if (!strcasecmp(v->name, "autoframing")) {
28761 global_autoframing = ast_true(v->value);
28762 } else if (!strcasecmp(v->name, "allowexternaldomains")) {
28763 sip_cfg.allow_external_domains = ast_true(v->value);
28764 } else if (!strcasecmp(v->name, "autodomain")) {
28765 auto_sip_domains = ast_true(v->value);
28766 } else if (!strcasecmp(v->name, "domain")) {
28767 char *domain = ast_strdupa(v->value);
28768 char *cntx = strchr(domain, ',');
28769
28770 if (cntx) {
28771 *cntx++ = '\0';
28772 }
28773
28774 if (ast_strlen_zero(cntx)) {
28775 ast_debug(1, "No context specified at line %d for domain '%s'\n", v->lineno, domain);
28776 }
28777 if (ast_strlen_zero(domain)) {
28778 ast_log(LOG_WARNING, "Empty domain specified at line %d\n", v->lineno);
28779 } else {
28780 add_sip_domain(ast_strip(domain), SIP_DOMAIN_CONFIG, cntx ? ast_strip(cntx) : "");
28781 }
28782 } else if (!strcasecmp(v->name, "register")) {
28783 if (sip_register(v->value, v->lineno) == 0) {
28784 registry_count++;
28785 }
28786 } else if (!strcasecmp(v->name, "mwi")) {
28787 sip_subscribe_mwi(v->value, v->lineno);
28788 } else if (!strcasecmp(v->name, "tos_sip")) {
28789 if (ast_str2tos(v->value, &global_tos_sip)) {
28790 ast_log(LOG_WARNING, "Invalid tos_sip value at line %d, refer to QoS documentation\n", v->lineno);
28791 }
28792 } else if (!strcasecmp(v->name, "tos_audio")) {
28793 if (ast_str2tos(v->value, &global_tos_audio)) {
28794 ast_log(LOG_WARNING, "Invalid tos_audio value at line %d, refer to QoS documentation\n", v->lineno);
28795 }
28796 } else if (!strcasecmp(v->name, "tos_video")) {
28797 if (ast_str2tos(v->value, &global_tos_video)) {
28798 ast_log(LOG_WARNING, "Invalid tos_video value at line %d, refer to QoS documentation\n", v->lineno);
28799 }
28800 } else if (!strcasecmp(v->name, "tos_text")) {
28801 if (ast_str2tos(v->value, &global_tos_text)) {
28802 ast_log(LOG_WARNING, "Invalid tos_text value at line %d, refer to QoS documentation\n", v->lineno);
28803 }
28804 } else if (!strcasecmp(v->name, "cos_sip")) {
28805 if (ast_str2cos(v->value, &global_cos_sip)) {
28806 ast_log(LOG_WARNING, "Invalid cos_sip value at line %d, refer to QoS documentation\n", v->lineno);
28807 }
28808 } else if (!strcasecmp(v->name, "cos_audio")) {
28809 if (ast_str2cos(v->value, &global_cos_audio)) {
28810 ast_log(LOG_WARNING, "Invalid cos_audio value at line %d, refer to QoS documentation\n", v->lineno);
28811 }
28812 } else if (!strcasecmp(v->name, "cos_video")) {
28813 if (ast_str2cos(v->value, &global_cos_video)) {
28814 ast_log(LOG_WARNING, "Invalid cos_video value at line %d, refer to QoS documentation\n", v->lineno);
28815 }
28816 } else if (!strcasecmp(v->name, "cos_text")) {
28817 if (ast_str2cos(v->value, &global_cos_text)) {
28818 ast_log(LOG_WARNING, "Invalid cos_text value at line %d, refer to QoS documentation\n", v->lineno);
28819 }
28820 } else if (!strcasecmp(v->name, "bindport")) {
28821 if (sscanf(v->value, "%5d", &bindport) != 1) {
28822 ast_log(LOG_WARNING, "Invalid port number '%s' at line %d of %s\n", v->value, v->lineno, config);
28823 }
28824 } else if (!strcasecmp(v->name, "qualify")) {
28825 if (!strcasecmp(v->value, "no")) {
28826 default_qualify = 0;
28827 } else if (!strcasecmp(v->value, "yes")) {
28828 default_qualify = DEFAULT_MAXMS;
28829 } else if (sscanf(v->value, "%30d", &default_qualify) != 1) {
28830 ast_log(LOG_WARNING, "Qualification default should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", v->lineno);
28831 default_qualify = 0;
28832 }
28833 } else if (!strcasecmp(v->name, "qualifyfreq")) {
28834 int i;
28835 if (sscanf(v->value, "%30d", &i) == 1) {
28836 global_qualifyfreq = i * 1000;
28837 } else {
28838 ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
28839 global_qualifyfreq = DEFAULT_QUALIFYFREQ;
28840 }
28841 } else if (!strcasecmp(v->name, "callevents")) {
28842 sip_cfg.callevents = ast_true(v->value);
28843 } else if (!strcasecmp(v->name, "authfailureevents")) {
28844 global_authfailureevents = ast_true(v->value);
28845 } else if (!strcasecmp(v->name, "maxcallbitrate")) {
28846 default_maxcallbitrate = atoi(v->value);
28847 if (default_maxcallbitrate < 0)
28848 default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
28849 } else if (!strcasecmp(v->name, "matchexternaddrlocally") || !strcasecmp(v->name, "matchexterniplocally")) {
28850 sip_cfg.matchexternaddrlocally = ast_true(v->value);
28851 } else if (!strcasecmp(v->name, "session-timers")) {
28852 int i = (int) str2stmode(v->value);
28853 if (i < 0) {
28854 ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
28855 global_st_mode = SESSION_TIMER_MODE_ACCEPT;
28856 } else {
28857 global_st_mode = i;
28858 }
28859 } else if (!strcasecmp(v->name, "session-expires")) {
28860 if (sscanf(v->value, "%30d", &global_max_se) != 1) {
28861 ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
28862 global_max_se = DEFAULT_MAX_SE;
28863 }
28864 } else if (!strcasecmp(v->name, "session-minse")) {
28865 if (sscanf(v->value, "%30d", &global_min_se) != 1) {
28866 ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
28867 global_min_se = DEFAULT_MIN_SE;
28868 }
28869 if (global_min_se < 90) {
28870 ast_log(LOG_WARNING, "session-minse '%s' at line %d of %s is not allowed to be < 90 secs\n", v->value, v->lineno, config);
28871 global_min_se = DEFAULT_MIN_SE;
28872 }
28873 } else if (!strcasecmp(v->name, "session-refresher")) {
28874 int i = (int) str2strefresherparam(v->value);
28875 if (i < 0) {
28876 ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
28877 global_st_refresher = SESSION_TIMER_REFRESHER_PARAM_UAS;
28878 } else {
28879 global_st_refresher = i;
28880 }
28881 } else if (!strcasecmp(v->name, "storesipcause")) {
28882 global_store_sip_cause = ast_true(v->value);
28883 } else if (!strcasecmp(v->name, "qualifygap")) {
28884 if (sscanf(v->value, "%30d", &global_qualify_gap) != 1) {
28885 ast_log(LOG_WARNING, "Invalid qualifygap '%s' at line %d of %s\n", v->value, v->lineno, config);
28886 global_qualify_gap = DEFAULT_QUALIFY_GAP;
28887 }
28888 } else if (!strcasecmp(v->name, "qualifypeers")) {
28889 if (sscanf(v->value, "%30d", &global_qualify_peers) != 1) {
28890 ast_log(LOG_WARNING, "Invalid pokepeers '%s' at line %d of %s\n", v->value, v->lineno, config);
28891 global_qualify_peers = DEFAULT_QUALIFY_PEERS;
28892 }
28893 } else if (!strcasecmp(v->name, "disallowed_methods")) {
28894 char *disallow = ast_strdupa(v->value);
28895 mark_parsed_methods(&sip_cfg.disallowed_methods, disallow);
28896 } else if (!strcasecmp(v->name, "shrinkcallerid")) {
28897 if (ast_true(v->value)) {
28898 global_shrinkcallerid = 1;
28899 } else if (ast_false(v->value)) {
28900 global_shrinkcallerid = 0;
28901 } else {
28902 ast_log(LOG_WARNING, "shrinkcallerid value %s is not valid at line %d.\n", v->value, v->lineno);
28903 }
28904 } else if (!strcasecmp(v->name, "use_q850_reason")) {
28905 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_Q850_REASON);
28906 } else if (!strcasecmp(v->name, "maxforwards")) {
28907 if (sscanf(v->value, "%30d", &sip_cfg.default_max_forwards) != 1
28908 || sip_cfg.default_max_forwards < 1 || 255 < sip_cfg.default_max_forwards) {
28909 ast_log(LOG_WARNING, "'%s' is not a valid maxforwards value at line %d. Using default.\n", v->value, v->lineno);
28910 sip_cfg.default_max_forwards = DEFAULT_MAX_FORWARDS;
28911 }
28912 } else if (!strcasecmp(v->name, "subscribe_network_change_event")) {
28913 if (ast_true(v->value)) {
28914 subscribe_network_change = 1;
28915 } else if (ast_false(v->value)) {
28916 subscribe_network_change = 0;
28917 } else {
28918 ast_log(LOG_WARNING, "subscribe_network_change_event value %s is not valid at line %d.\n", v->value, v->lineno);
28919 }
28920 } else if (!strcasecmp(v->name, "snom_aoc_enabled")) {
28921 ast_set2_flag(&global_flags[2], ast_true(v->value), SIP_PAGE3_SNOM_AOC);
28922 } else if (!strcasecmp(v->name, "parkinglot")) {
28923 ast_copy_string(default_parkinglot, v->value, sizeof(default_parkinglot));
28924 }
28925 }
28926
28927 if (subscribe_network_change) {
28928 network_change_event_subscribe();
28929 } else {
28930 network_change_event_unsubscribe();
28931 }
28932
28933 if (global_t1 < global_t1min) {
28934 ast_log(LOG_WARNING, "'t1min' (%d) cannot be greater than 't1timer' (%d). Resetting 't1timer' to the value of 't1min'\n", global_t1min, global_t1);
28935 global_t1 = global_t1min;
28936 }
28937
28938 if (global_timer_b < global_t1 * 64) {
28939 if (timerb_set && timert1_set) {
28940 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);
28941 } else if (timerb_set) {
28942 if ((global_t1 = global_timer_b / 64) < global_t1min) {
28943 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);
28944 global_t1 = global_t1min;
28945 global_timer_b = global_t1 * 64;
28946 }
28947 } else {
28948 global_timer_b = global_t1 * 64;
28949 }
28950 }
28951 if (!sip_cfg.allow_external_domains && AST_LIST_EMPTY(&domain_list)) {
28952 ast_log(LOG_WARNING, "To disallow external domains, you need to configure local SIP domains.\n");
28953 sip_cfg.allow_external_domains = 1;
28954 }
28955
28956 if (!sip_cfg.tcp_enabled && (default_transports & SIP_TRANSPORT_TCP)) {
28957 ast_log(LOG_WARNING, "Cannot use 'tcp' transport with tcpenable=no. Removing from available transports.\n");
28958 default_primary_transport &= ~SIP_TRANSPORT_TCP;
28959 default_transports &= ~SIP_TRANSPORT_TCP;
28960 }
28961 if (!default_tls_cfg.enabled && (default_transports & SIP_TRANSPORT_TLS)) {
28962 ast_log(LOG_WARNING, "Cannot use 'tls' transport with tlsenable=no. Removing from available transports.\n");
28963 default_primary_transport &= ~SIP_TRANSPORT_TLS;
28964 default_transports &= ~SIP_TRANSPORT_TLS;
28965 }
28966 if (!default_transports) {
28967 ast_log(LOG_WARNING, "No valid transports available, falling back to 'udp'.\n");
28968 default_transports = default_primary_transport = SIP_TRANSPORT_UDP;
28969 } else if (!default_primary_transport) {
28970 ast_log(LOG_WARNING, "No valid default transport. Selecting 'udp' as default.\n");
28971 default_primary_transport = SIP_TRANSPORT_UDP;
28972 }
28973
28974
28975 for (v = ast_variable_browse(cfg, "authentication"); v ; v = v->next) {
28976
28977 if (!strcasecmp(v->name, "auth")) {
28978 add_realm_authentication(&authl, v->value, v->lineno);
28979 }
28980 }
28981
28982 if (bindport) {
28983 if (ast_sockaddr_port(&bindaddr)) {
28984 ast_log(LOG_WARNING, "bindport is also specified in bindaddr. "
28985 "Using %d.\n", bindport);
28986 }
28987 ast_sockaddr_set_port(&bindaddr, bindport);
28988 }
28989
28990 if (!ast_sockaddr_port(&bindaddr)) {
28991 ast_sockaddr_set_port(&bindaddr, STANDARD_SIP_PORT);
28992 }
28993
28994
28995 ast_sockaddr_copy(&internip, &bindaddr);
28996 if (ast_find_ourip(&internip, &bindaddr, 0)) {
28997 ast_log(LOG_WARNING, "Unable to get own IP address, SIP disabled\n");
28998 ast_config_destroy(cfg);
28999 return 0;
29000 }
29001
29002 ast_mutex_lock(&netlock);
29003 if ((sipsock > -1) && (ast_sockaddr_cmp(&old_bindaddr, &bindaddr))) {
29004 close(sipsock);
29005 sipsock = -1;
29006 }
29007 if (sipsock < 0) {
29008 sipsock = socket(ast_sockaddr_is_ipv6(&bindaddr) ?
29009 AF_INET6 : AF_INET, SOCK_DGRAM, 0);
29010 if (sipsock < 0) {
29011 ast_log(LOG_WARNING, "Unable to create SIP socket: %s\n", strerror(errno));
29012 ast_config_destroy(cfg);
29013 ast_mutex_unlock(&netlock);
29014 return -1;
29015 } else {
29016
29017 const int reuseFlag = 1;
29018
29019 setsockopt(sipsock, SOL_SOCKET, SO_REUSEADDR,
29020 (const char*)&reuseFlag,
29021 sizeof reuseFlag);
29022
29023 ast_enable_packet_fragmentation(sipsock);
29024
29025 if (ast_bind(sipsock, &bindaddr) < 0) {
29026 ast_log(LOG_WARNING, "Failed to bind to %s: %s\n",
29027 ast_sockaddr_stringify(&bindaddr), strerror(errno));
29028 close(sipsock);
29029 sipsock = -1;
29030 } else {
29031 ast_verb(2, "SIP Listening on %s\n", ast_sockaddr_stringify(&bindaddr));
29032 ast_set_qos(sipsock, global_tos_sip, global_cos_sip, "SIP");
29033 }
29034 }
29035 } else {
29036 ast_set_qos(sipsock, global_tos_sip, global_cos_sip, "SIP");
29037 }
29038 ast_mutex_unlock(&netlock);
29039
29040
29041 if (sip_cfg.tcp_enabled) {
29042 if (ast_sockaddr_isnull(&sip_tcp_desc.local_address)) {
29043 ast_sockaddr_copy(&sip_tcp_desc.local_address, &bindaddr);
29044 }
29045 if (!ast_sockaddr_port(&sip_tcp_desc.local_address)) {
29046 ast_sockaddr_set_port(&sip_tcp_desc.local_address, STANDARD_SIP_PORT);
29047 }
29048 } else {
29049 ast_sockaddr_setnull(&sip_tcp_desc.local_address);
29050 }
29051 ast_tcptls_server_start(&sip_tcp_desc);
29052 if (sip_cfg.tcp_enabled && sip_tcp_desc.accept_fd == -1) {
29053
29054 ast_log(LOG_ERROR, "SIP TCP Server start failed. Not listening on TCP socket.\n");
29055 } else {
29056 ast_debug(2, "SIP TCP server started\n");
29057 }
29058
29059
29060 memcpy(sip_tls_desc.tls_cfg, &default_tls_cfg, sizeof(default_tls_cfg));
29061
29062 if (ast_ssl_setup(sip_tls_desc.tls_cfg)) {
29063 if (ast_sockaddr_isnull(&sip_tls_desc.local_address)) {
29064 ast_sockaddr_copy(&sip_tls_desc.local_address, &bindaddr);
29065 ast_sockaddr_set_port(&sip_tls_desc.local_address,
29066 STANDARD_TLS_PORT);
29067 }
29068 if (!ast_sockaddr_port(&sip_tls_desc.local_address)) {
29069 ast_sockaddr_set_port(&sip_tls_desc.local_address,
29070 STANDARD_TLS_PORT);
29071 }
29072 ast_tcptls_server_start(&sip_tls_desc);
29073 if (default_tls_cfg.enabled && sip_tls_desc.accept_fd == -1) {
29074 ast_log(LOG_ERROR, "TLS Server start failed. Not listening on TLS socket.\n");
29075 sip_tls_desc.tls_cfg = NULL;
29076 }
29077 } else if (sip_tls_desc.tls_cfg->enabled) {
29078 sip_tls_desc.tls_cfg = NULL;
29079 ast_log(LOG_WARNING, "SIP TLS server did not load because of errors.\n");
29080 }
29081
29082 if (ucfg) {
29083 struct ast_variable *gen;
29084 int genhassip, genregistersip;
29085 const char *hassip, *registersip;
29086
29087 genhassip = ast_true(ast_variable_retrieve(ucfg, "general", "hassip"));
29088 genregistersip = ast_true(ast_variable_retrieve(ucfg, "general", "registersip"));
29089 gen = ast_variable_browse(ucfg, "general");
29090 cat = ast_category_browse(ucfg, NULL);
29091 while (cat) {
29092 if (strcasecmp(cat, "general")) {
29093 hassip = ast_variable_retrieve(ucfg, cat, "hassip");
29094 registersip = ast_variable_retrieve(ucfg, cat, "registersip");
29095 if (ast_true(hassip) || (!hassip && genhassip)) {
29096 peer = build_peer(cat, gen, ast_variable_browse(ucfg, cat), 0, 0);
29097 if (peer) {
29098
29099 peer->type = SIP_TYPE_USER | SIP_TYPE_PEER;
29100 ao2_t_link(peers, peer, "link peer into peer table");
29101 if ((peer->type & SIP_TYPE_PEER) && !ast_sockaddr_isnull(&peer->addr)) {
29102 ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
29103 }
29104
29105 unref_peer(peer, "unref_peer: from reload_config");
29106 peer_count++;
29107 }
29108 }
29109 if (ast_true(registersip) || (!registersip && genregistersip)) {
29110 char tmp[256];
29111 const char *host = ast_variable_retrieve(ucfg, cat, "host");
29112 const char *username = ast_variable_retrieve(ucfg, cat, "username");
29113 const char *secret = ast_variable_retrieve(ucfg, cat, "secret");
29114 const char *contact = ast_variable_retrieve(ucfg, cat, "contact");
29115 const char *authuser = ast_variable_retrieve(ucfg, cat, "authuser");
29116 if (!host) {
29117 host = ast_variable_retrieve(ucfg, "general", "host");
29118 }
29119 if (!username) {
29120 username = ast_variable_retrieve(ucfg, "general", "username");
29121 }
29122 if (!secret) {
29123 secret = ast_variable_retrieve(ucfg, "general", "secret");
29124 }
29125 if (!contact) {
29126 contact = "s";
29127 }
29128 if (!ast_strlen_zero(username) && !ast_strlen_zero(host)) {
29129 if (!ast_strlen_zero(secret)) {
29130 if (!ast_strlen_zero(authuser)) {
29131 snprintf(tmp, sizeof(tmp), "%s?%s:%s:%s@%s/%s", cat, username, secret, authuser, host, contact);
29132 } else {
29133 snprintf(tmp, sizeof(tmp), "%s?%s:%s@%s/%s", cat, username, secret, host, contact);
29134 }
29135 } else if (!ast_strlen_zero(authuser)) {
29136 snprintf(tmp, sizeof(tmp), "%s?%s::%s@%s/%s", cat, username, authuser, host, contact);
29137 } else {
29138 snprintf(tmp, sizeof(tmp), "%s?%s@%s/%s", cat, username, host, contact);
29139 }
29140 if (sip_register(tmp, 0) == 0) {
29141 registry_count++;
29142 }
29143 }
29144 }
29145 }
29146 cat = ast_category_browse(ucfg, cat);
29147 }
29148 ast_config_destroy(ucfg);
29149 }
29150
29151
29152 cat = NULL;
29153 while ( (cat = ast_category_browse(cfg, cat)) ) {
29154 const char *utype;
29155 if (!strcasecmp(cat, "general") || !strcasecmp(cat, "authentication"))
29156 continue;
29157 utype = ast_variable_retrieve(cfg, cat, "type");
29158 if (!utype) {
29159 ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
29160 continue;
29161 } else {
29162 if (!strcasecmp(utype, "user")) {
29163 ;
29164 } else if (!strcasecmp(utype, "friend")) {
29165 ;
29166 } else if (!strcasecmp(utype, "peer")) {
29167 ;
29168 } else {
29169 ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, "sip.conf");
29170 continue;
29171 }
29172 peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0, 0);
29173 if (peer) {
29174 display_nat_warning(cat, reason, &peer->flags[0]);
29175 ao2_t_link(peers, peer, "link peer into peers table");
29176 if ((peer->type & SIP_TYPE_PEER) && !ast_sockaddr_isnull(&peer->addr)) {
29177 ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
29178 }
29179 unref_peer(peer, "unref the result of the build_peer call. Now, the links from the tables are the only ones left.");
29180 peer_count++;
29181 }
29182 }
29183 }
29184
29185
29186
29187
29188
29189
29190 if (auto_sip_domains) {
29191 char temp[MAXHOSTNAMELEN];
29192
29193
29194 if (!ast_sockaddr_isnull(&bindaddr) && !ast_sockaddr_is_any(&bindaddr)) {
29195 add_sip_domain(ast_sockaddr_stringify_addr(&bindaddr),
29196 SIP_DOMAIN_AUTO, NULL);
29197 } else if (!ast_sockaddr_isnull(&internip) && !ast_sockaddr_is_any(&internip)) {
29198
29199 add_sip_domain(ast_sockaddr_stringify_addr(&internip),
29200 SIP_DOMAIN_AUTO, NULL);
29201 } else {
29202 ast_log(LOG_NOTICE, "Can't add wildcard IP address to domain list, please add IP address to domain manually.\n");
29203 }
29204
29205
29206 if (!ast_sockaddr_isnull(&sip_tcp_desc.local_address) &&
29207 !ast_sockaddr_cmp(&bindaddr, &sip_tcp_desc.local_address)) {
29208 add_sip_domain(ast_sockaddr_stringify_addr(&sip_tcp_desc.local_address),
29209 SIP_DOMAIN_AUTO, NULL);
29210 }
29211
29212
29213 if (!ast_sockaddr_isnull(&sip_tls_desc.local_address) &&
29214 !ast_sockaddr_cmp(&bindaddr, &sip_tls_desc.local_address) &&
29215 !ast_sockaddr_cmp(&sip_tcp_desc.local_address,
29216 &sip_tls_desc.local_address)) {
29217 add_sip_domain(ast_sockaddr_stringify_addr(&sip_tcp_desc.local_address),
29218 SIP_DOMAIN_AUTO, NULL);
29219 }
29220
29221
29222 if (!ast_sockaddr_isnull(&externaddr)) {
29223 add_sip_domain(ast_sockaddr_stringify_addr(&externaddr),
29224 SIP_DOMAIN_AUTO, NULL);
29225 }
29226
29227
29228 if (!ast_strlen_zero(externhost)) {
29229 add_sip_domain(externhost, SIP_DOMAIN_AUTO, NULL);
29230 }
29231
29232
29233 if (!gethostname(temp, sizeof(temp))) {
29234 add_sip_domain(temp, SIP_DOMAIN_AUTO, NULL);
29235 }
29236 }
29237
29238
29239 ast_config_destroy(cfg);
29240
29241
29242 if (notify_types)
29243 ast_config_destroy(notify_types);
29244 if ((notify_types = ast_config_load(notify_config, config_flags)) == CONFIG_STATUS_FILEINVALID) {
29245 ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed.\n", notify_config);
29246 notify_types = NULL;
29247 }
29248
29249
29250 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);
29251 run_end = time(0);
29252 ast_debug(4, "SIP reload_config done...Runtime= %d sec\n", (int)(run_end-run_start));
29253
29254 return 0;
29255 }
29256
29257 static int apply_directmedia_ha(struct sip_pvt *p1, struct sip_pvt *p2, const char *op)
29258 {
29259 struct ast_sockaddr us = { { 0, }, }, them = { { 0, }, };
29260 int res = AST_SENSE_ALLOW;
29261
29262 ast_rtp_instance_get_remote_address(p1->rtp, &them);
29263 ast_rtp_instance_get_local_address(p1->rtp, &us);
29264
29265
29266
29267 if (!p2->relatedpeer) {
29268 return res;
29269 }
29270
29271 if ((res = ast_apply_ha(p2->relatedpeer->directmediaha, &them)) == AST_SENSE_DENY) {
29272 const char *us_addr = ast_strdupa(ast_sockaddr_stringify(&us));
29273 const char *them_addr = ast_strdupa(ast_sockaddr_stringify(&them));
29274
29275 ast_debug(3, "Reinvite %s to %s denied by directmedia ACL on %s\n",
29276 op, them_addr, us_addr);
29277 }
29278
29279 return res;
29280 }
29281
29282 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan)
29283 {
29284 struct sip_pvt *p;
29285 struct ast_channel *opp_chan;
29286 struct sip_pvt *opp;
29287 struct ast_udptl *udptl = NULL;
29288
29289 p = chan->tech_pvt;
29290 if (!p) {
29291 return NULL;
29292 }
29293
29294 if (!(opp_chan = ast_bridged_channel(chan))) {
29295 return NULL;
29296 } else if (((opp_chan->tech != &sip_tech) && (opp_chan->tech != &sip_tech_info)) ||
29297 (!(opp = opp_chan->tech_pvt))) {
29298 return NULL;
29299 }
29300
29301 sip_pvt_lock(p);
29302 while (sip_pvt_trylock(opp)) {
29303 sip_pvt_unlock(p);
29304 usleep(1);
29305 sip_pvt_lock(p);
29306 }
29307
29308 if (p->udptl && ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
29309 if (apply_directmedia_ha(p, opp, "UDPTL T.38 data")) {
29310 udptl = p->udptl;
29311 }
29312 }
29313
29314 sip_pvt_unlock(opp);
29315 sip_pvt_unlock(p);
29316 return udptl;
29317 }
29318
29319 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl)
29320 {
29321 struct sip_pvt *p;
29322
29323
29324 ast_channel_lock(chan);
29325 p = chan->tech_pvt;
29326 if (!p) {
29327 ast_channel_unlock(chan);
29328 return -1;
29329 }
29330 sip_pvt_lock(p);
29331 if (p->owner != chan) {
29332
29333 ast_debug(1, "The private is not owned by channel %s anymore.\n", chan->name);
29334 sip_pvt_unlock(p);
29335 ast_channel_unlock(chan);
29336 return 0;
29337 }
29338
29339 if (udptl) {
29340 ast_udptl_get_peer(udptl, &p->udptlredirip);
29341 } else {
29342 memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
29343 }
29344 if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
29345 if (!p->pendinginvite) {
29346 ast_debug(3, "Sending reinvite on SIP '%s' - It's UDPTL soon redirected to IP %s\n",
29347 p->callid, ast_sockaddr_stringify(udptl ? &p->udptlredirip : &p->ourip));
29348 transmit_reinvite_with_sdp(p, TRUE, FALSE);
29349 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
29350 ast_debug(3, "Deferring reinvite on SIP '%s' - It's UDPTL will be redirected to IP %s\n",
29351 p->callid, ast_sockaddr_stringify(udptl ? &p->udptlredirip : &p->ourip));
29352 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
29353 }
29354 }
29355
29356 p->lastrtprx = p->lastrtptx = time(NULL);
29357 sip_pvt_unlock(p);
29358 ast_channel_unlock(chan);
29359 return 0;
29360 }
29361
29362 static enum ast_rtp_glue_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
29363 {
29364 struct sip_pvt *p = NULL;
29365 struct ast_channel *opp_chan;
29366 struct sip_pvt *opp = NULL;
29367 enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_LOCAL;
29368
29369 if (!(p = chan->tech_pvt)) {
29370 return AST_RTP_GLUE_RESULT_FORBID;
29371 }
29372
29373 if ((opp_chan = ast_bridged_channel(chan)) && (((opp_chan->tech != &sip_tech) && (opp_chan->tech != &sip_tech_info)) ||
29374 (!(opp = opp_chan->tech_pvt)))) {
29375 return AST_RTP_GLUE_RESULT_FORBID;
29376 }
29377
29378 sip_pvt_lock(p);
29379 while (opp && sip_pvt_trylock(opp)) {
29380 sip_pvt_unlock(p);
29381 usleep(1);
29382 sip_pvt_lock(p);
29383 }
29384
29385 if (!(p->rtp)) {
29386 if (opp) {
29387 sip_pvt_unlock(opp);
29388 }
29389 sip_pvt_unlock(p);
29390 return AST_RTP_GLUE_RESULT_FORBID;
29391 }
29392
29393 ao2_ref(p->rtp, +1);
29394 *instance = p->rtp;
29395
29396 if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
29397 res = AST_RTP_GLUE_RESULT_REMOTE;
29398 if (opp && !apply_directmedia_ha(p, opp, "audio")) {
29399 res = AST_RTP_GLUE_RESULT_FORBID;
29400 }
29401 } else if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA_NAT)) {
29402 res = AST_RTP_GLUE_RESULT_REMOTE;
29403 } else if (ast_test_flag(&global_jbconf, AST_JB_FORCED)) {
29404 res = AST_RTP_GLUE_RESULT_FORBID;
29405 }
29406
29407 if (opp) {
29408 sip_pvt_unlock(opp);
29409 }
29410
29411 if (p->srtp) {
29412 res = AST_RTP_GLUE_RESULT_FORBID;
29413 }
29414
29415 sip_pvt_unlock(p);
29416
29417 return res;
29418 }
29419
29420 static enum ast_rtp_glue_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
29421 {
29422 struct sip_pvt *p = NULL;
29423 struct ast_channel *opp_chan;
29424 struct sip_pvt *opp = NULL;
29425 enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_FORBID;
29426
29427 if (!(p = chan->tech_pvt)) {
29428 return AST_RTP_GLUE_RESULT_FORBID;
29429 }
29430
29431 if ((opp_chan = ast_bridged_channel(chan)) && (((opp_chan->tech != &sip_tech) && (opp_chan->tech != &sip_tech_info)) ||
29432 (!(opp = opp_chan->tech_pvt)))) {
29433 return AST_RTP_GLUE_RESULT_FORBID;
29434 }
29435
29436 sip_pvt_lock(p);
29437 while (opp && sip_pvt_trylock(opp)) {
29438 sip_pvt_unlock(p);
29439 usleep(1);
29440 sip_pvt_lock(p);
29441 }
29442
29443 if (!(p->vrtp)) {
29444 if (opp) {
29445 sip_pvt_unlock(opp);
29446 }
29447 sip_pvt_unlock(p);
29448 return AST_RTP_GLUE_RESULT_FORBID;
29449 }
29450
29451 ao2_ref(p->vrtp, +1);
29452 *instance = p->vrtp;
29453
29454 if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
29455 res = AST_RTP_GLUE_RESULT_REMOTE;
29456 if (opp && !apply_directmedia_ha(p, opp, "video")) {
29457 res = AST_RTP_GLUE_RESULT_FORBID;
29458 }
29459 }
29460
29461 if (opp) {
29462 sip_pvt_unlock(opp);
29463 }
29464 sip_pvt_unlock(p);
29465
29466 return res;
29467 }
29468
29469 static enum ast_rtp_glue_result sip_get_trtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
29470 {
29471 struct sip_pvt *p = NULL;
29472 struct ast_channel *opp_chan;
29473 struct sip_pvt *opp = NULL;
29474 enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_FORBID;
29475
29476 if (!(p = chan->tech_pvt)) {
29477 return AST_RTP_GLUE_RESULT_FORBID;
29478 }
29479
29480 if ((opp_chan = ast_bridged_channel(chan)) && (((opp_chan->tech != &sip_tech) && (opp_chan->tech != &sip_tech_info)) ||
29481 (!(opp = opp_chan->tech_pvt)))) {
29482 return AST_RTP_GLUE_RESULT_FORBID;
29483 }
29484
29485 sip_pvt_lock(p);
29486 while (opp && sip_pvt_trylock(opp)) {
29487 sip_pvt_unlock(p);
29488 usleep(1);
29489 sip_pvt_lock(p);
29490 }
29491
29492 if (!(p->trtp)) {
29493 if (opp) {
29494 sip_pvt_unlock(opp);
29495 }
29496 sip_pvt_unlock(p);
29497 return AST_RTP_GLUE_RESULT_FORBID;
29498 }
29499
29500 ao2_ref(p->trtp, +1);
29501 *instance = p->trtp;
29502
29503 if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
29504 res = AST_RTP_GLUE_RESULT_REMOTE;
29505 if (opp && !apply_directmedia_ha(p, opp, "text")) {
29506 res = AST_RTP_GLUE_RESULT_FORBID;
29507 }
29508 }
29509
29510 if (opp) {
29511 sip_pvt_unlock(opp);
29512 }
29513 sip_pvt_unlock(p);
29514
29515 return res;
29516 }
29517
29518 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, format_t codecs, int nat_active)
29519 {
29520 struct sip_pvt *p;
29521 int changed = 0;
29522
29523
29524 ast_channel_lock(chan);
29525 p = chan->tech_pvt;
29526 if (!p) {
29527 ast_channel_unlock(chan);
29528 return -1;
29529 }
29530 sip_pvt_lock(p);
29531 if (p->owner != chan) {
29532
29533 ast_debug(1, "The private is not owned by channel %s anymore.\n", chan->name);
29534 sip_pvt_unlock(p);
29535 ast_channel_unlock(chan);
29536 return 0;
29537 }
29538
29539
29540 if ((instance || vinstance || tinstance) &&
29541 !ast_bridged_channel(chan) &&
29542 !sip_cfg.directrtpsetup) {
29543 sip_pvt_unlock(p);
29544 ast_channel_unlock(chan);
29545 return 0;
29546 }
29547
29548 if (p->alreadygone) {
29549
29550 sip_pvt_unlock(p);
29551 ast_channel_unlock(chan);
29552 return 0;
29553 }
29554
29555
29556
29557
29558 if (nat_active && !ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA_NAT)) {
29559 sip_pvt_unlock(p);
29560 ast_channel_unlock(chan);
29561 return 0;
29562 }
29563
29564 if (instance) {
29565 changed |= ast_rtp_instance_get_and_cmp_remote_address(instance, &p->redirip);
29566
29567 if (p->rtp) {
29568
29569 ast_channel_set_fd(chan, 1, -1);
29570
29571 ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_RTCP, 0);
29572 }
29573 } else if (!ast_sockaddr_isnull(&p->redirip)) {
29574 memset(&p->redirip, 0, sizeof(p->redirip));
29575 changed = 1;
29576
29577 if (p->rtp) {
29578
29579
29580 ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_RTCP, 1);
29581
29582 ast_channel_set_fd(chan, 1, ast_rtp_instance_fd(p->rtp, 1));
29583 }
29584 }
29585
29586 if (vinstance) {
29587 changed |= ast_rtp_instance_get_and_cmp_remote_address(vinstance, &p->vredirip);
29588
29589 if (p->vrtp) {
29590
29591 ast_channel_set_fd(chan, 3, -1);
29592
29593 ast_rtp_instance_set_prop(p->vrtp, AST_RTP_PROPERTY_RTCP, 0);
29594 }
29595 } else if (!ast_sockaddr_isnull(&p->vredirip)) {
29596 memset(&p->vredirip, 0, sizeof(p->vredirip));
29597 changed = 1;
29598
29599 if (p->vrtp) {
29600
29601
29602 ast_rtp_instance_set_prop(p->vrtp, AST_RTP_PROPERTY_RTCP, 1);
29603
29604 ast_channel_set_fd(chan, 3, ast_rtp_instance_fd(p->vrtp, 1));
29605 }
29606 }
29607
29608 if (tinstance) {
29609 changed |= ast_rtp_instance_get_and_cmp_remote_address(tinstance, &p->tredirip);
29610 } else if (!ast_sockaddr_isnull(&p->tredirip)) {
29611 memset(&p->tredirip, 0, sizeof(p->tredirip));
29612 changed = 1;
29613 }
29614 if (codecs && (p->redircodecs != codecs)) {
29615 p->redircodecs = codecs;
29616 changed = 1;
29617 }
29618
29619 if (ast_test_flag(&p->flags[2], SIP_PAGE3_DIRECT_MEDIA_OUTGOING) && !p->outgoing_call) {
29620
29621
29622
29623
29624 ast_clear_flag(&p->flags[2], SIP_PAGE3_DIRECT_MEDIA_OUTGOING);
29625 sip_pvt_unlock(p);
29626 ast_channel_unlock(chan);
29627 return 0;
29628 }
29629
29630 if (changed && !ast_test_flag(&p->flags[0], SIP_GOTREFER) && !ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
29631 if (chan->_state != AST_STATE_UP) {
29632 if (p->do_history)
29633 append_history(p, "ExtInv", "Initial invite sent with remote bridge proposal.");
29634 ast_debug(1, "Early remote bridge setting SIP '%s' - Sending media to %s\n", p->callid, ast_sockaddr_stringify(instance ? &p->redirip : &p->ourip));
29635 } else if (!p->pendinginvite) {
29636 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));
29637 transmit_reinvite_with_sdp(p, FALSE, FALSE);
29638 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
29639 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));
29640
29641 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
29642 }
29643 }
29644
29645 p->lastrtprx = p->lastrtptx = time(NULL);
29646 sip_pvt_unlock(p);
29647 ast_channel_unlock(chan);
29648 return 0;
29649 }
29650
29651 static format_t sip_get_codec(struct ast_channel *chan)
29652 {
29653 struct sip_pvt *p = chan->tech_pvt;
29654 return p->peercapability ? p->peercapability : p->capability;
29655 }
29656
29657 static struct ast_rtp_glue sip_rtp_glue = {
29658 .type = "SIP",
29659 .get_rtp_info = sip_get_rtp_peer,
29660 .get_vrtp_info = sip_get_vrtp_peer,
29661 .get_trtp_info = sip_get_trtp_peer,
29662 .update_peer = sip_set_rtp_peer,
29663 .get_codec = sip_get_codec,
29664 };
29665
29666 static char *app_dtmfmode = "SIPDtmfMode";
29667 static char *app_sipaddheader = "SIPAddHeader";
29668 static char *app_sipremoveheader = "SIPRemoveHeader";
29669
29670
29671 static int sip_dtmfmode(struct ast_channel *chan, const char *data)
29672 {
29673 struct sip_pvt *p;
29674 const char *mode = data;
29675
29676 if (!data) {
29677 ast_log(LOG_WARNING, "This application requires the argument: info, inband, rfc2833\n");
29678 return 0;
29679 }
29680 ast_channel_lock(chan);
29681 if (!IS_SIP_TECH(chan->tech)) {
29682 ast_log(LOG_WARNING, "Call this application only on SIP incoming calls\n");
29683 ast_channel_unlock(chan);
29684 return 0;
29685 }
29686 p = chan->tech_pvt;
29687 if (!p) {
29688 ast_channel_unlock(chan);
29689 return 0;
29690 }
29691 sip_pvt_lock(p);
29692 if (!strcasecmp(mode, "info")) {
29693 ast_clear_flag(&p->flags[0], SIP_DTMF);
29694 ast_set_flag(&p->flags[0], SIP_DTMF_INFO);
29695 p->jointnoncodeccapability &= ~AST_RTP_DTMF;
29696 } else if (!strcasecmp(mode, "shortinfo")) {
29697 ast_clear_flag(&p->flags[0], SIP_DTMF);
29698 ast_set_flag(&p->flags[0], SIP_DTMF_SHORTINFO);
29699 p->jointnoncodeccapability &= ~AST_RTP_DTMF;
29700 } else if (!strcasecmp(mode, "rfc2833")) {
29701 ast_clear_flag(&p->flags[0], SIP_DTMF);
29702 ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
29703 p->jointnoncodeccapability |= AST_RTP_DTMF;
29704 } else if (!strcasecmp(mode, "inband")) {
29705 ast_clear_flag(&p->flags[0], SIP_DTMF);
29706 ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
29707 p->jointnoncodeccapability &= ~AST_RTP_DTMF;
29708 } else {
29709 ast_log(LOG_WARNING, "I don't know about this dtmf mode: %s\n", mode);
29710 }
29711 if (p->rtp)
29712 ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
29713 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
29714 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
29715 enable_dsp_detect(p);
29716 } else {
29717 disable_dsp_detect(p);
29718 }
29719 sip_pvt_unlock(p);
29720 ast_channel_unlock(chan);
29721 return 0;
29722 }
29723
29724
29725 static int sip_addheader(struct ast_channel *chan, const char *data)
29726 {
29727 int no = 0;
29728 int ok = FALSE;
29729 char varbuf[30];
29730 const char *inbuf = data;
29731 char *subbuf;
29732
29733 if (ast_strlen_zero(inbuf)) {
29734 ast_log(LOG_WARNING, "This application requires the argument: Header\n");
29735 return 0;
29736 }
29737 ast_channel_lock(chan);
29738
29739
29740 while (!ok && no <= 50) {
29741 no++;
29742 snprintf(varbuf, sizeof(varbuf), "__SIPADDHEADER%.2d", no);
29743
29744
29745 if ((pbx_builtin_getvar_helper(chan, (const char *) varbuf + 2) == (const char *) NULL)) {
29746 ok = TRUE;
29747 }
29748 }
29749 if (ok) {
29750 size_t len = strlen(inbuf);
29751 subbuf = ast_alloca(len + 1);
29752 ast_get_encoded_str(inbuf, subbuf, len + 1);
29753 pbx_builtin_setvar_helper(chan, varbuf, subbuf);
29754 if (sipdebug) {
29755 ast_debug(1, "SIP Header added \"%s\" as %s\n", inbuf, varbuf);
29756 }
29757 } else {
29758 ast_log(LOG_WARNING, "Too many SIP headers added, max 50\n");
29759 }
29760 ast_channel_unlock(chan);
29761 return 0;
29762 }
29763
29764
29765 static int sip_removeheader(struct ast_channel *chan, const char *data)
29766 {
29767 struct ast_var_t *newvariable;
29768 struct varshead *headp;
29769 int removeall = 0;
29770 char *inbuf = (char *) data;
29771
29772 if (ast_strlen_zero(inbuf)) {
29773 removeall = 1;
29774 }
29775 ast_channel_lock(chan);
29776
29777 headp=&chan->varshead;
29778 AST_LIST_TRAVERSE_SAFE_BEGIN (headp, newvariable, entries) {
29779 if (strncasecmp(ast_var_name(newvariable), "SIPADDHEADER", strlen("SIPADDHEADER")) == 0) {
29780 if (removeall || (!strncasecmp(ast_var_value(newvariable),inbuf,strlen(inbuf)))) {
29781 if (sipdebug)
29782 ast_debug(1,"removing SIP Header \"%s\" as %s\n",
29783 ast_var_value(newvariable),
29784 ast_var_name(newvariable));
29785 AST_LIST_REMOVE_CURRENT(entries);
29786 ast_var_delete(newvariable);
29787 }
29788 }
29789 }
29790 AST_LIST_TRAVERSE_SAFE_END;
29791
29792 ast_channel_unlock(chan);
29793 return 0;
29794 }
29795
29796
29797
29798
29799
29800
29801
29802 static int sip_sipredirect(struct sip_pvt *p, const char *dest)
29803 {
29804 char *cdest;
29805 char *extension, *domain;
29806
29807 cdest = ast_strdupa(dest);
29808
29809 extension = strsep(&cdest, "@");
29810 domain = cdest;
29811 if (ast_strlen_zero(extension)) {
29812 ast_log(LOG_ERROR, "Missing mandatory argument: extension\n");
29813 return 0;
29814 }
29815
29816
29817 if (!domain) {
29818 char *local_to_header;
29819 char to_header[256];
29820
29821 ast_copy_string(to_header, get_header(&p->initreq, "To"), sizeof(to_header));
29822 if (ast_strlen_zero(to_header)) {
29823 ast_log(LOG_ERROR, "Cannot retrieve the 'To' header from the original SIP request!\n");
29824 return 0;
29825 }
29826 if (((local_to_header = strcasestr(to_header, "sip:")) || (local_to_header = strcasestr(to_header, "sips:")))
29827 && (local_to_header = strchr(local_to_header, '@'))) {
29828 char ldomain[256];
29829
29830 memset(ldomain, 0, sizeof(ldomain));
29831 local_to_header++;
29832
29833 sscanf(local_to_header, "%256[^<>; ]", ldomain);
29834 if (ast_strlen_zero(ldomain)) {
29835 ast_log(LOG_ERROR, "Can't find the host address\n");
29836 return 0;
29837 }
29838 domain = ast_strdupa(ldomain);
29839 }
29840 }
29841
29842 ast_string_field_build(p, our_contact, "Transfer <sip:%s@%s>", extension, domain);
29843 transmit_response_reliable(p, "302 Moved Temporarily", &p->initreq);
29844
29845 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
29846 sip_alreadygone(p);
29847
29848 if (p->owner) {
29849 enum ast_control_transfer message = AST_TRANSFER_SUCCESS;
29850 ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
29851 }
29852
29853 return 0;
29854 }
29855
29856 static int sip_is_xml_parsable(void)
29857 {
29858 #ifdef HAVE_LIBXML2
29859 return TRUE;
29860 #else
29861 return FALSE;
29862 #endif
29863 }
29864
29865
29866 static void sip_poke_all_peers(void)
29867 {
29868 int ms = 0, num = 0;
29869 struct ao2_iterator i;
29870 struct sip_peer *peer;
29871
29872 if (!speerobjs) {
29873 return;
29874 }
29875
29876 i = ao2_iterator_init(peers, 0);
29877 while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
29878 ao2_lock(peer);
29879
29880 if (peer->maxms) {
29881 if (num == global_qualify_peers) {
29882 ms += global_qualify_gap;
29883 num = 0;
29884 } else {
29885 num++;
29886 }
29887 AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, ms, sip_poke_peer_s, peer,
29888 unref_peer(_data, "removing poke peer ref"),
29889 unref_peer(peer, "removing poke peer ref"),
29890 ref_peer(peer, "adding poke peer ref"));
29891 }
29892 ao2_unlock(peer);
29893 unref_peer(peer, "toss iterator peer ptr");
29894 }
29895 ao2_iterator_destroy(&i);
29896 }
29897
29898
29899 static void sip_send_all_registers(void)
29900 {
29901 int ms;
29902 int regspacing;
29903 if (!regobjs)
29904 return;
29905 regspacing = default_expiry * 1000/regobjs;
29906 if (regspacing > 100) {
29907 regspacing = 100;
29908 }
29909 ms = regspacing;
29910 ASTOBJ_CONTAINER_TRAVERSE(®l, 1, do {
29911 ASTOBJ_WRLOCK(iterator);
29912 ms += regspacing;
29913 AST_SCHED_REPLACE_UNREF(iterator->expire, sched, ms, sip_reregister, iterator,
29914 registry_unref(_data, "REPLACE sched del decs the refcount"),
29915 registry_unref(iterator, "REPLACE sched add failure decs the refcount"),
29916 registry_addref(iterator, "REPLACE sched add incs the refcount"));
29917 ASTOBJ_UNLOCK(iterator);
29918 } while (0)
29919 );
29920 }
29921
29922
29923 static void sip_send_all_mwi_subscriptions(void)
29924 {
29925 ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
29926 struct sip_subscription_mwi *saved;
29927 ASTOBJ_WRLOCK(iterator);
29928 AST_SCHED_DEL(sched, iterator->resub);
29929 saved = ASTOBJ_REF(iterator);
29930 if ((iterator->resub = ast_sched_add(sched, 1, sip_subscribe_mwi_do, saved)) < 0) {
29931 ASTOBJ_UNREF(saved, sip_subscribe_mwi_destroy);
29932 }
29933 ASTOBJ_UNLOCK(iterator);
29934 } while (0));
29935 }
29936
29937
29938 static int setup_srtp(struct sip_srtp **srtp)
29939 {
29940 if (!ast_rtp_engine_srtp_is_registered()) {
29941 ast_log(LOG_ERROR, "No SRTP module loaded, can't setup SRTP session.\n");
29942 return -1;
29943 }
29944
29945 if (!(*srtp = sip_srtp_alloc())) {
29946 return -1;
29947 }
29948
29949 return 0;
29950 }
29951
29952 static int process_crypto(struct sip_pvt *p, struct ast_rtp_instance *rtp, struct sip_srtp **srtp, const char *a)
29953 {
29954
29955 if (!rtp) {
29956 ast_debug(3, "Received offer with crypto line for media stream that is not enabled\n");
29957 return FALSE;
29958 }
29959
29960 if (strncasecmp(a, "crypto:", 7)) {
29961 return FALSE;
29962 }
29963 if (!*srtp) {
29964 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
29965 ast_log(LOG_WARNING, "Ignoring unexpected crypto attribute in SDP answer\n");
29966 return FALSE;
29967 }
29968
29969 if (setup_srtp(srtp) < 0) {
29970 return FALSE;
29971 }
29972 }
29973
29974 if (!(*srtp)->crypto && !((*srtp)->crypto = sdp_crypto_setup())) {
29975 return FALSE;
29976 }
29977
29978 if (sdp_crypto_process((*srtp)->crypto, a, rtp) < 0) {
29979 return FALSE;
29980 }
29981
29982 ast_set_flag(*srtp, SRTP_CRYPTO_OFFER_OK);
29983
29984 return TRUE;
29985 }
29986
29987
29988 static int sip_do_reload(enum channelreloadreason reason)
29989 {
29990 time_t start_poke, end_poke;
29991
29992 reload_config(reason);
29993 ast_sched_dump(sched);
29994
29995 start_poke = time(0);
29996
29997 unlink_marked_peers_from_tables();
29998
29999 ast_debug(4, "--------------- Done destroying pruned peers\n");
30000
30001
30002 sip_poke_all_peers();
30003
30004
30005 sip_send_all_registers();
30006
30007 sip_send_all_mwi_subscriptions();
30008
30009 end_poke = time(0);
30010
30011 ast_debug(4, "do_reload finished. peer poke/prune reg contact time = %d sec.\n", (int)(end_poke-start_poke));
30012
30013 ast_debug(4, "--------------- SIP reload done\n");
30014
30015 return 0;
30016 }
30017
30018
30019 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
30020 {
30021
30022 switch (cmd) {
30023 case CLI_INIT:
30024 e->command = "sip reload";
30025 e->usage =
30026 "Usage: sip reload\n"
30027 " Reloads SIP configuration from sip.conf\n";
30028 return NULL;
30029 case CLI_GENERATE:
30030 return NULL;
30031 }
30032
30033 ast_mutex_lock(&sip_reload_lock);
30034 if (sip_reloading) {
30035 ast_verbose("Previous SIP reload not yet done\n");
30036 } else {
30037 sip_reloading = TRUE;
30038 sip_reloadreason = (a && a->fd) ? CHANNEL_CLI_RELOAD : CHANNEL_MODULE_RELOAD;
30039 }
30040 ast_mutex_unlock(&sip_reload_lock);
30041 restart_monitor();
30042
30043 return CLI_SUCCESS;
30044 }
30045
30046
30047 static int reload(void)
30048 {
30049 if (sip_reload(0, 0, NULL))
30050 return 0;
30051 return 1;
30052 }
30053
30054
30055
30056
30057
30058 static int ast_sockaddr_resolve_first_af(struct ast_sockaddr *addr,
30059 const char* name, int flag, int family)
30060 {
30061 struct ast_sockaddr *addrs;
30062 int addrs_cnt;
30063
30064 addrs_cnt = ast_sockaddr_resolve(&addrs, name, flag, family);
30065 if (addrs_cnt <= 0) {
30066 return 1;
30067 }
30068 if (addrs_cnt > 1) {
30069 ast_debug(1, "Multiple addresses, using the first one only\n");
30070 }
30071
30072 ast_sockaddr_copy(addr, &addrs[0]);
30073
30074 ast_free(addrs);
30075 return 0;
30076 }
30077
30078
30079
30080
30081
30082 static int ast_sockaddr_resolve_first(struct ast_sockaddr *addr,
30083 const char* name, int flag)
30084 {
30085 return ast_sockaddr_resolve_first_af(addr, name, flag, get_address_family_filter(SIP_TRANSPORT_UDP));
30086 }
30087
30088
30089
30090
30091
30092 static int ast_sockaddr_resolve_first_transport(struct ast_sockaddr *addr,
30093 const char* name, int flag, unsigned int transport)
30094 {
30095 return ast_sockaddr_resolve_first_af(addr, name, flag, get_address_family_filter(transport));
30096 }
30097
30098
30099
30100
30101 static int peer_hash_cb(const void *obj, const int flags)
30102 {
30103 const struct sip_peer *peer = obj;
30104
30105 return ast_str_case_hash(peer->name);
30106 }
30107
30108
30109
30110
30111 static int peer_cmp_cb(void *obj, void *arg, int flags)
30112 {
30113 struct sip_peer *peer = obj, *peer2 = arg;
30114
30115 return !strcasecmp(peer->name, peer2->name) ? CMP_MATCH | CMP_STOP : 0;
30116 }
30117
30118
30119
30120
30121
30122
30123 static int peer_iphash_cb(const void *obj, const int flags)
30124 {
30125 const struct sip_peer *peer = obj;
30126 int ret = 0;
30127
30128 if (ast_sockaddr_isnull(&peer->addr)) {
30129 ast_log(LOG_ERROR, "Empty address\n");
30130 }
30131
30132 ret = ast_sockaddr_hash(&peer->addr);
30133
30134 if (ret < 0) {
30135 ret = -ret;
30136 }
30137
30138 return ret;
30139 }
30140
30141
30142
30143
30144
30145
30146
30147
30148
30149
30150
30151
30152
30153
30154
30155
30156
30157
30158
30159 static int peer_ipcmp_cb(void *obj, void *arg, int flags)
30160 {
30161 struct sip_peer *peer = obj, *peer2 = arg;
30162
30163 if (ast_sockaddr_cmp_addr(&peer->addr, &peer2->addr)) {
30164
30165 return 0;
30166 }
30167
30168
30169 if ((peer->transports & peer2->transports) & (SIP_TRANSPORT_TLS | SIP_TRANSPORT_TCP)) {
30170
30171 return CMP_MATCH | CMP_STOP;
30172 } else if (ast_test_flag(&peer2->flags[0], SIP_INSECURE_PORT)) {
30173
30174
30175 return ast_test_flag(&peer->flags[0], SIP_INSECURE_PORT) ?
30176 (CMP_MATCH | CMP_STOP) : 0;
30177 }
30178
30179
30180 return ast_sockaddr_port(&peer->addr) == ast_sockaddr_port(&peer2->addr) ?
30181 (CMP_MATCH | CMP_STOP) : 0;
30182 }
30183
30184
30185 static int threadt_hash_cb(const void *obj, const int flags)
30186 {
30187 const struct sip_threadinfo *th = obj;
30188
30189 return ast_sockaddr_hash(&th->tcptls_session->remote_address);
30190 }
30191
30192 static int threadt_cmp_cb(void *obj, void *arg, int flags)
30193 {
30194 struct sip_threadinfo *th = obj, *th2 = arg;
30195
30196 return (th->tcptls_session == th2->tcptls_session) ? CMP_MATCH | CMP_STOP : 0;
30197 }
30198
30199
30200
30201
30202 static int dialog_hash_cb(const void *obj, const int flags)
30203 {
30204 const struct sip_pvt *pvt = obj;
30205
30206 return ast_str_case_hash(pvt->callid);
30207 }
30208
30209
30210
30211
30212 static int dialog_find_multiple(void *obj, void *arg, int flags)
30213 {
30214 struct sip_pvt *pvt = obj, *pvt2 = arg;
30215
30216 return !strcasecmp(pvt->callid, pvt2->callid) ? CMP_MATCH : 0;
30217 }
30218
30219
30220
30221
30222 static int dialog_cmp_cb(void *obj, void *arg, int flags)
30223 {
30224 struct sip_pvt *pvt = obj, *pvt2 = arg;
30225
30226 return !strcasecmp(pvt->callid, pvt2->callid) ? CMP_MATCH | CMP_STOP : 0;
30227 }
30228
30229
30230 static struct ast_cli_entry cli_sip[] = {
30231 AST_CLI_DEFINE(sip_show_channels, "List active SIP channels or subscriptions"),
30232 AST_CLI_DEFINE(sip_show_channelstats, "List statistics for active SIP channels"),
30233 AST_CLI_DEFINE(sip_show_domains, "List our local SIP domains"),
30234 AST_CLI_DEFINE(sip_show_inuse, "List all inuse/limits"),
30235 AST_CLI_DEFINE(sip_show_objects, "List all SIP object allocations"),
30236 AST_CLI_DEFINE(sip_show_peers, "List defined SIP peers"),
30237 AST_CLI_DEFINE(sip_show_registry, "List SIP registration status"),
30238 AST_CLI_DEFINE(sip_unregister, "Unregister (force expiration) a SIP peer from the registry"),
30239 AST_CLI_DEFINE(sip_show_settings, "Show SIP global settings"),
30240 AST_CLI_DEFINE(sip_show_mwi, "Show MWI subscriptions"),
30241 AST_CLI_DEFINE(sip_cli_notify, "Send a notify packet to a SIP peer"),
30242 AST_CLI_DEFINE(sip_show_channel, "Show detailed SIP channel info"),
30243 AST_CLI_DEFINE(sip_show_history, "Show SIP dialog history"),
30244 AST_CLI_DEFINE(sip_show_peer, "Show details on specific SIP peer"),
30245 AST_CLI_DEFINE(sip_show_users, "List defined SIP users"),
30246 AST_CLI_DEFINE(sip_show_user, "Show details on specific SIP user"),
30247 AST_CLI_DEFINE(sip_qualify_peer, "Send an OPTIONS packet to a peer"),
30248 AST_CLI_DEFINE(sip_show_sched, "Present a report on the status of the scheduler queue"),
30249 AST_CLI_DEFINE(sip_prune_realtime, "Prune cached Realtime users/peers"),
30250 AST_CLI_DEFINE(sip_do_debug, "Enable/Disable SIP debugging"),
30251 AST_CLI_DEFINE(sip_set_history, "Enable/Disable SIP history"),
30252 AST_CLI_DEFINE(sip_reload, "Reload SIP configuration"),
30253 AST_CLI_DEFINE(sip_show_tcp, "List TCP Connections")
30254 };
30255
30256
30257 static void sip_register_tests(void)
30258 {
30259 sip_config_parser_register_tests();
30260 sip_request_parser_register_tests();
30261 sip_dialplan_function_register_tests();
30262 }
30263
30264
30265 static void sip_unregister_tests(void)
30266 {
30267 sip_config_parser_unregister_tests();
30268 sip_request_parser_unregister_tests();
30269 sip_dialplan_function_unregister_tests();
30270 }
30271
30272 #ifdef TEST_FRAMEWORK
30273 AST_TEST_DEFINE(test_sip_mwi_subscribe_parse)
30274 {
30275 int found = 0;
30276 enum ast_test_result_state res = AST_TEST_PASS;
30277 const char *mwi1 = "1234@mysipprovider.com/1234";
30278 const char *mwi2 = "1234:password@mysipprovider.com/1234";
30279 const char *mwi3 = "1234:password@mysipprovider.com:5061/1234";
30280 const char *mwi4 = "1234:password:authuser@mysipprovider.com/1234";
30281 const char *mwi5 = "1234:password:authuser@mysipprovider.com:5061/1234";
30282 const char *mwi6 = "1234:password";
30283
30284 switch (cmd) {
30285 case TEST_INIT:
30286 info->name = "sip_mwi_subscribe_parse_test";
30287 info->category = "/channels/chan_sip/";
30288 info->summary = "SIP MWI subscribe line parse unit test";
30289 info->description =
30290 "Tests the parsing of mwi subscription lines (e.g., mwi => from sip.conf)";
30291 return AST_TEST_NOT_RUN;
30292 case TEST_EXECUTE:
30293 break;
30294 }
30295
30296 if (sip_subscribe_mwi(mwi1, 1)) {
30297 res = AST_TEST_FAIL;
30298 } else {
30299 found = 0;
30300 res = AST_TEST_FAIL;
30301 ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
30302 ASTOBJ_WRLOCK(iterator);
30303 if (
30304 !strcmp(iterator->hostname, "mysipprovider.com") &&
30305 !strcmp(iterator->username, "1234") &&
30306 !strcmp(iterator->secret, "") &&
30307 !strcmp(iterator->authuser, "") &&
30308 !strcmp(iterator->mailbox, "1234") &&
30309 iterator->portno == 0) {
30310 found = 1;
30311 res = AST_TEST_PASS;
30312 }
30313 ASTOBJ_UNLOCK(iterator);
30314 } while(0));
30315 if (!found) {
30316 ast_test_status_update(test, "sip_subscribe_mwi test 1 failed\n");
30317 }
30318 }
30319
30320 if (sip_subscribe_mwi(mwi2, 1)) {
30321 res = AST_TEST_FAIL;
30322 } else {
30323 found = 0;
30324 res = AST_TEST_FAIL;
30325 ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
30326 ASTOBJ_WRLOCK(iterator);
30327 if (
30328 !strcmp(iterator->hostname, "mysipprovider.com") &&
30329 !strcmp(iterator->username, "1234") &&
30330 !strcmp(iterator->secret, "password") &&
30331 !strcmp(iterator->authuser, "") &&
30332 !strcmp(iterator->mailbox, "1234") &&
30333 iterator->portno == 0) {
30334 found = 1;
30335 res = AST_TEST_PASS;
30336 }
30337 ASTOBJ_UNLOCK(iterator);
30338 } while(0));
30339 if (!found) {
30340 ast_test_status_update(test, "sip_subscribe_mwi test 2 failed\n");
30341 }
30342 }
30343
30344 if (sip_subscribe_mwi(mwi3, 1)) {
30345 res = AST_TEST_FAIL;
30346 } else {
30347 found = 0;
30348 res = AST_TEST_FAIL;
30349 ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
30350 ASTOBJ_WRLOCK(iterator);
30351 if (
30352 !strcmp(iterator->hostname, "mysipprovider.com") &&
30353 !strcmp(iterator->username, "1234") &&
30354 !strcmp(iterator->secret, "password") &&
30355 !strcmp(iterator->authuser, "") &&
30356 !strcmp(iterator->mailbox, "1234") &&
30357 iterator->portno == 5061) {
30358 found = 1;
30359 res = AST_TEST_PASS;
30360 }
30361 ASTOBJ_UNLOCK(iterator);
30362 } while(0));
30363 if (!found) {
30364 ast_test_status_update(test, "sip_subscribe_mwi test 3 failed\n");
30365 }
30366 }
30367
30368 if (sip_subscribe_mwi(mwi4, 1)) {
30369 res = AST_TEST_FAIL;
30370 } else {
30371 found = 0;
30372 res = AST_TEST_FAIL;
30373 ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
30374 ASTOBJ_WRLOCK(iterator);
30375 if (
30376 !strcmp(iterator->hostname, "mysipprovider.com") &&
30377 !strcmp(iterator->username, "1234") &&
30378 !strcmp(iterator->secret, "password") &&
30379 !strcmp(iterator->authuser, "authuser") &&
30380 !strcmp(iterator->mailbox, "1234") &&
30381 iterator->portno == 0) {
30382 found = 1;
30383 res = AST_TEST_PASS;
30384 }
30385 ASTOBJ_UNLOCK(iterator);
30386 } while(0));
30387 if (!found) {
30388 ast_test_status_update(test, "sip_subscribe_mwi test 4 failed\n");
30389 }
30390 }
30391
30392 if (sip_subscribe_mwi(mwi5, 1)) {
30393 res = AST_TEST_FAIL;
30394 } else {
30395 found = 0;
30396 res = AST_TEST_FAIL;
30397 ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
30398 ASTOBJ_WRLOCK(iterator);
30399 if (
30400 !strcmp(iterator->hostname, "mysipprovider.com") &&
30401 !strcmp(iterator->username, "1234") &&
30402 !strcmp(iterator->secret, "password") &&
30403 !strcmp(iterator->authuser, "authuser") &&
30404 !strcmp(iterator->mailbox, "1234") &&
30405 iterator->portno == 5061) {
30406 found = 1;
30407 res = AST_TEST_PASS;
30408 }
30409 ASTOBJ_UNLOCK(iterator);
30410 } while(0));
30411 if (!found) {
30412 ast_test_status_update(test, "sip_subscribe_mwi test 5 failed\n");
30413 }
30414 }
30415
30416 if (sip_subscribe_mwi(mwi6, 1)) {
30417 res = AST_TEST_PASS;
30418 } else {
30419 res = AST_TEST_FAIL;
30420 }
30421 return res;
30422 }
30423
30424 AST_TEST_DEFINE(test_sip_peers_get)
30425 {
30426 struct sip_peer *peer;
30427 struct ast_data *node;
30428 struct ast_data_query query = {
30429 .path = "/asterisk/channel/sip/peers",
30430 .search = "peers/peer/name=test_peer_data_provider"
30431 };
30432
30433 switch (cmd) {
30434 case TEST_INIT:
30435 info->name = "sip_peers_get_data_test";
30436 info->category = "/main/data/sip/peers/";
30437 info->summary = "SIP peers data providers unit test";
30438 info->description =
30439 "Tests whether the SIP peers data provider implementation works as expected.";
30440 return AST_TEST_NOT_RUN;
30441 case TEST_EXECUTE:
30442 break;
30443 }
30444
30445
30446 peer = build_peer("test_peer_data_provider", NULL, NULL, 0, 0);
30447 if (!peer) {
30448 return AST_TEST_FAIL;
30449 }
30450 peer->type = SIP_TYPE_USER;
30451 peer->call_limit = 10;
30452 ao2_link(peers, peer);
30453
30454
30455 node = ast_data_get(&query);
30456 if (!node) {
30457 ao2_unlink(peers, peer);
30458 ao2_ref(peer, -1);
30459 return AST_TEST_FAIL;
30460 }
30461
30462
30463 if (strcmp(ast_data_retrieve_string(node, "peer/name"), "test_peer_data_provider")) {
30464 ao2_unlink(peers, peer);
30465 ao2_ref(peer, -1);
30466 ast_data_free(node);
30467 return AST_TEST_FAIL;
30468 }
30469
30470 if (strcmp(ast_data_retrieve_string(node, "peer/type"), "user")) {
30471 ao2_unlink(peers, peer);
30472 ao2_ref(peer, -1);
30473 ast_data_free(node);
30474 return AST_TEST_FAIL;
30475 }
30476
30477 if (ast_data_retrieve_int(node, "peer/call_limit") != 10) {
30478 ao2_unlink(peers, peer);
30479 ao2_ref(peer, -1);
30480 ast_data_free(node);
30481 return AST_TEST_FAIL;
30482 }
30483
30484
30485 ast_data_free(node);
30486
30487 ao2_unlink(peers, peer);
30488 ao2_ref(peer, -1);
30489
30490 return AST_TEST_PASS;
30491 }
30492
30493 #endif
30494
30495 #define DATA_EXPORT_SIP_PEER(MEMBER) \
30496 MEMBER(sip_peer, name, AST_DATA_STRING) \
30497 MEMBER(sip_peer, secret, AST_DATA_PASSWORD) \
30498 MEMBER(sip_peer, md5secret, AST_DATA_PASSWORD) \
30499 MEMBER(sip_peer, remotesecret, AST_DATA_PASSWORD) \
30500 MEMBER(sip_peer, context, AST_DATA_STRING) \
30501 MEMBER(sip_peer, subscribecontext, AST_DATA_STRING) \
30502 MEMBER(sip_peer, username, AST_DATA_STRING) \
30503 MEMBER(sip_peer, accountcode, AST_DATA_STRING) \
30504 MEMBER(sip_peer, tohost, AST_DATA_STRING) \
30505 MEMBER(sip_peer, regexten, AST_DATA_STRING) \
30506 MEMBER(sip_peer, fromuser, AST_DATA_STRING) \
30507 MEMBER(sip_peer, fromdomain, AST_DATA_STRING) \
30508 MEMBER(sip_peer, fullcontact, AST_DATA_STRING) \
30509 MEMBER(sip_peer, cid_num, AST_DATA_STRING) \
30510 MEMBER(sip_peer, cid_name, AST_DATA_STRING) \
30511 MEMBER(sip_peer, vmexten, AST_DATA_STRING) \
30512 MEMBER(sip_peer, language, AST_DATA_STRING) \
30513 MEMBER(sip_peer, mohinterpret, AST_DATA_STRING) \
30514 MEMBER(sip_peer, mohsuggest, AST_DATA_STRING) \
30515 MEMBER(sip_peer, parkinglot, AST_DATA_STRING) \
30516 MEMBER(sip_peer, useragent, AST_DATA_STRING) \
30517 MEMBER(sip_peer, mwi_from, AST_DATA_STRING) \
30518 MEMBER(sip_peer, engine, AST_DATA_STRING) \
30519 MEMBER(sip_peer, unsolicited_mailbox, AST_DATA_STRING) \
30520 MEMBER(sip_peer, is_realtime, AST_DATA_BOOLEAN) \
30521 MEMBER(sip_peer, host_dynamic, AST_DATA_BOOLEAN) \
30522 MEMBER(sip_peer, autoframing, AST_DATA_BOOLEAN) \
30523 MEMBER(sip_peer, inUse, AST_DATA_INTEGER) \
30524 MEMBER(sip_peer, inRinging, AST_DATA_INTEGER) \
30525 MEMBER(sip_peer, onHold, AST_DATA_INTEGER) \
30526 MEMBER(sip_peer, call_limit, AST_DATA_INTEGER) \
30527 MEMBER(sip_peer, t38_maxdatagram, AST_DATA_INTEGER) \
30528 MEMBER(sip_peer, maxcallbitrate, AST_DATA_INTEGER) \
30529 MEMBER(sip_peer, rtptimeout, AST_DATA_SECONDS) \
30530 MEMBER(sip_peer, rtpholdtimeout, AST_DATA_SECONDS) \
30531 MEMBER(sip_peer, rtpkeepalive, AST_DATA_SECONDS) \
30532 MEMBER(sip_peer, lastms, AST_DATA_MILLISECONDS) \
30533 MEMBER(sip_peer, maxms, AST_DATA_MILLISECONDS) \
30534 MEMBER(sip_peer, qualifyfreq, AST_DATA_MILLISECONDS) \
30535 MEMBER(sip_peer, timer_t1, AST_DATA_MILLISECONDS) \
30536 MEMBER(sip_peer, timer_b, AST_DATA_MILLISECONDS)
30537
30538 AST_DATA_STRUCTURE(sip_peer, DATA_EXPORT_SIP_PEER);
30539
30540 static int peers_data_provider_get(const struct ast_data_search *search,
30541 struct ast_data *data_root)
30542 {
30543 struct sip_peer *peer;
30544 struct ao2_iterator i;
30545 struct ast_data *data_peer, *data_peer_mailboxes = NULL, *data_peer_mailbox, *enum_node;
30546 struct ast_data *data_sip_options;
30547 int total_mailboxes, x;
30548 struct sip_mailbox *mailbox;
30549
30550 i = ao2_iterator_init(peers, 0);
30551 while ((peer = ao2_iterator_next(&i))) {
30552 ao2_lock(peer);
30553
30554 data_peer = ast_data_add_node(data_root, "peer");
30555 if (!data_peer) {
30556 ao2_unlock(peer);
30557 ao2_ref(peer, -1);
30558 continue;
30559 }
30560
30561 ast_data_add_structure(sip_peer, data_peer, peer);
30562
30563
30564 enum_node = ast_data_add_node(data_peer, "allowtransfer");
30565 if (!enum_node) {
30566 ao2_unlock(peer);
30567 ao2_ref(peer, -1);
30568 continue;
30569 }
30570 ast_data_add_str(enum_node, "text", transfermode2str(peer->allowtransfer));
30571 ast_data_add_int(enum_node, "value", peer->allowtransfer);
30572
30573
30574 ast_data_add_str(data_peer, "transports", get_transport_list(peer->transports));
30575
30576
30577 if ((peer->type & SIP_TYPE_USER) && (peer->type & SIP_TYPE_PEER)) {
30578 ast_data_add_str(data_peer, "type", "friend");
30579 } else if (peer->type & SIP_TYPE_PEER) {
30580 ast_data_add_str(data_peer, "type", "peer");
30581 } else if (peer->type & SIP_TYPE_USER) {
30582 ast_data_add_str(data_peer, "type", "user");
30583 }
30584
30585
30586 total_mailboxes = 0;
30587 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
30588 if (!total_mailboxes) {
30589 data_peer_mailboxes = ast_data_add_node(data_peer, "mailboxes");
30590 if (!data_peer_mailboxes) {
30591 break;
30592 }
30593 total_mailboxes++;
30594 }
30595
30596 data_peer_mailbox = ast_data_add_node(data_peer_mailboxes, "mailbox");
30597 if (!data_peer_mailbox) {
30598 continue;
30599 }
30600 ast_data_add_str(data_peer_mailbox, "mailbox", mailbox->mailbox);
30601 ast_data_add_str(data_peer_mailbox, "context", mailbox->context);
30602 }
30603
30604
30605 enum_node = ast_data_add_node(data_peer, "amaflags");
30606 if (!enum_node) {
30607 ao2_unlock(peer);
30608 ao2_ref(peer, -1);
30609 continue;
30610 }
30611 ast_data_add_int(enum_node, "value", peer->amaflags);
30612 ast_data_add_str(enum_node, "text", ast_cdr_flags2str(peer->amaflags));
30613
30614
30615 data_sip_options = ast_data_add_node(data_peer, "sipoptions");
30616 if (!data_sip_options) {
30617 ao2_unlock(peer);
30618 ao2_ref(peer, -1);
30619 continue;
30620 }
30621 for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
30622 ast_data_add_bool(data_sip_options, sip_options[x].text, peer->sipoptions & sip_options[x].id);
30623 }
30624
30625
30626 enum_node = ast_data_add_node(data_peer, "callingpres");
30627 if (!enum_node) {
30628 ao2_unlock(peer);
30629 ao2_ref(peer, -1);
30630 continue;
30631 }
30632 ast_data_add_int(enum_node, "value", peer->callingpres);
30633 ast_data_add_str(enum_node, "text", ast_describe_caller_presentation(peer->callingpres));
30634
30635
30636 ast_data_add_codecs(data_peer, "codecs", peer->capability);
30637
30638 if (!ast_data_search_match(search, data_peer)) {
30639 ast_data_remove_node(data_root, data_peer);
30640 }
30641
30642 ao2_unlock(peer);
30643 ao2_ref(peer, -1);
30644 }
30645 ao2_iterator_destroy(&i);
30646
30647 return 0;
30648 }
30649
30650 static const struct ast_data_handler peers_data_provider = {
30651 .version = AST_DATA_HANDLER_VERSION,
30652 .get = peers_data_provider_get
30653 };
30654
30655 static const struct ast_data_entry sip_data_providers[] = {
30656 AST_DATA_ENTRY("asterisk/channel/sip/peers", &peers_data_provider),
30657 };
30658
30659
30660 static int load_module(void)
30661 {
30662 ast_verbose("SIP channel loading...\n");
30663
30664
30665
30666 peers = ao2_t_container_alloc(HASH_PEER_SIZE, peer_hash_cb, peer_cmp_cb, "allocate peers");
30667 peers_by_ip = ao2_t_container_alloc(HASH_PEER_SIZE, peer_iphash_cb, peer_ipcmp_cb, "allocate peers_by_ip");
30668 dialogs = ao2_t_container_alloc(HASH_DIALOG_SIZE, dialog_hash_cb, dialog_cmp_cb, "allocate dialogs");
30669 dialogs_to_destroy = ao2_t_container_alloc(1, NULL, NULL, "allocate dialogs_to_destroy");
30670 threadt = ao2_t_container_alloc(HASH_DIALOG_SIZE, threadt_hash_cb, threadt_cmp_cb, "allocate threadt table");
30671 if (!peers || !peers_by_ip || !dialogs || !dialogs_to_destroy || !threadt) {
30672 ast_log(LOG_ERROR, "Unable to create primary SIP container(s)\n");
30673 return AST_MODULE_LOAD_FAILURE;
30674 }
30675
30676 ASTOBJ_CONTAINER_INIT(®l);
30677 ASTOBJ_CONTAINER_INIT(&submwil);
30678
30679 if (!(sched = sched_context_create())) {
30680 ast_log(LOG_ERROR, "Unable to create scheduler context\n");
30681 return AST_MODULE_LOAD_FAILURE;
30682 }
30683
30684 if (!(io = io_context_create())) {
30685 ast_log(LOG_ERROR, "Unable to create I/O context\n");
30686 sched_context_destroy(sched);
30687 return AST_MODULE_LOAD_FAILURE;
30688 }
30689
30690 sip_reloadreason = CHANNEL_MODULE_LOAD;
30691
30692 can_parse_xml = sip_is_xml_parsable();
30693 if (reload_config(sip_reloadreason)) {
30694 return AST_MODULE_LOAD_DECLINE;
30695 }
30696
30697
30698
30699
30700
30701 memcpy(&sip_tech_info, &sip_tech, sizeof(sip_tech));
30702 memset((void *) &sip_tech_info.send_digit_begin, 0, sizeof(sip_tech_info.send_digit_begin));
30703
30704
30705 if (ast_channel_register(&sip_tech)) {
30706 ast_log(LOG_ERROR, "Unable to register channel type 'SIP'\n");
30707 io_context_destroy(io);
30708 sched_context_destroy(sched);
30709 return AST_MODULE_LOAD_FAILURE;
30710 }
30711
30712 #ifdef TEST_FRAMEWORK
30713 AST_TEST_REGISTER(test_sip_peers_get);
30714 AST_TEST_REGISTER(test_sip_mwi_subscribe_parse);
30715 #endif
30716
30717
30718 ast_data_register_multiple(sip_data_providers, ARRAY_LEN(sip_data_providers));
30719
30720
30721 ast_cli_register_multiple(cli_sip, ARRAY_LEN(cli_sip));
30722
30723
30724 ast_udptl_proto_register(&sip_udptl);
30725
30726
30727 ast_rtp_glue_register(&sip_rtp_glue);
30728
30729
30730 ast_register_application_xml(app_dtmfmode, sip_dtmfmode);
30731 ast_register_application_xml(app_sipaddheader, sip_addheader);
30732 ast_register_application_xml(app_sipremoveheader, sip_removeheader);
30733
30734
30735 ast_custom_function_register(&sip_header_function);
30736 ast_custom_function_register(&sippeer_function);
30737 ast_custom_function_register(&sipchaninfo_function);
30738 ast_custom_function_register(&checksipdomain_function);
30739
30740
30741 ast_manager_register_xml("SIPpeers", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peers);
30742 ast_manager_register_xml("SIPshowpeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peer);
30743 ast_manager_register_xml("SIPqualifypeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_qualify_peer);
30744 ast_manager_register_xml("SIPshowregistry", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_show_registry);
30745 ast_manager_register_xml("SIPnotify", EVENT_FLAG_SYSTEM, manager_sipnotify);
30746 sip_poke_all_peers();
30747 sip_send_all_registers();
30748 sip_send_all_mwi_subscriptions();
30749 initialize_escs();
30750
30751 if (sip_epa_register(&cc_epa_static_data)) {
30752 return AST_MODULE_LOAD_DECLINE;
30753 }
30754
30755 if (sip_reqresp_parser_init() == -1) {
30756 ast_log(LOG_ERROR, "Unable to initialize the SIP request and response parser\n");
30757 return AST_MODULE_LOAD_DECLINE;
30758 }
30759
30760 if (can_parse_xml) {
30761
30762
30763
30764 if (ast_cc_agent_register(&sip_cc_agent_callbacks)) {
30765 return AST_MODULE_LOAD_DECLINE;
30766 }
30767 }
30768 if (ast_cc_monitor_register(&sip_cc_monitor_callbacks)) {
30769 return AST_MODULE_LOAD_DECLINE;
30770 }
30771 if (!(sip_monitor_instances = ao2_container_alloc(37, sip_monitor_instance_hash_fn, sip_monitor_instance_cmp_fn))) {
30772 return AST_MODULE_LOAD_DECLINE;
30773 }
30774
30775
30776 restart_monitor();
30777
30778 ast_realtime_require_field(ast_check_realtime("sipregs") ? "sipregs" : "sippeers",
30779 "name", RQ_CHAR, 10,
30780 "ipaddr", RQ_CHAR, INET6_ADDRSTRLEN - 1,
30781 "port", RQ_UINTEGER2, 5,
30782 "regseconds", RQ_INTEGER4, 11,
30783 "defaultuser", RQ_CHAR, 10,
30784 "fullcontact", RQ_CHAR, 35,
30785 "regserver", RQ_CHAR, 20,
30786 "useragent", RQ_CHAR, 20,
30787 "lastms", RQ_INTEGER4, 11,
30788 SENTINEL);
30789
30790
30791 sip_register_tests();
30792 network_change_event_subscribe();
30793
30794 return AST_MODULE_LOAD_SUCCESS;
30795 }
30796
30797
30798 static int unload_module(void)
30799 {
30800 struct sip_pvt *p;
30801 struct sip_threadinfo *th;
30802 struct ast_context *con;
30803 struct ao2_iterator i;
30804 int wait_count;
30805
30806 network_change_event_unsubscribe();
30807
30808 ast_sched_dump(sched);
30809
30810
30811 ast_channel_unregister(&sip_tech);
30812
30813
30814 ast_custom_function_unregister(&sipchaninfo_function);
30815 ast_custom_function_unregister(&sippeer_function);
30816 ast_custom_function_unregister(&sip_header_function);
30817 ast_custom_function_unregister(&checksipdomain_function);
30818
30819
30820 ast_unregister_application(app_dtmfmode);
30821 ast_unregister_application(app_sipaddheader);
30822 ast_unregister_application(app_sipremoveheader);
30823
30824 #ifdef TEST_FRAMEWORK
30825 AST_TEST_UNREGISTER(test_sip_peers_get);
30826 AST_TEST_UNREGISTER(test_sip_mwi_subscribe_parse);
30827 #endif
30828
30829 ast_data_unregister(NULL);
30830
30831
30832 ast_cli_unregister_multiple(cli_sip, ARRAY_LEN(cli_sip));
30833
30834
30835 ast_udptl_proto_unregister(&sip_udptl);
30836
30837
30838 ast_rtp_glue_unregister(&sip_rtp_glue);
30839
30840
30841 ast_manager_unregister("SIPpeers");
30842 ast_manager_unregister("SIPshowpeer");
30843 ast_manager_unregister("SIPqualifypeer");
30844 ast_manager_unregister("SIPshowregistry");
30845 ast_manager_unregister("SIPnotify");
30846
30847
30848 if (sip_tcp_desc.master) {
30849 ast_tcptls_server_stop(&sip_tcp_desc);
30850 }
30851 if (sip_tls_desc.master) {
30852 ast_tcptls_server_stop(&sip_tls_desc);
30853 }
30854 ast_ssl_teardown(sip_tls_desc.tls_cfg);
30855
30856
30857 i = ao2_iterator_init(threadt, 0);
30858 while ((th = ao2_t_iterator_next(&i, "iterate through tcp threads for 'sip show tcp'"))) {
30859 pthread_t thread = th->threadid;
30860 th->stop = 1;
30861 pthread_kill(thread, SIGURG);
30862 ao2_t_ref(th, -1, "decrement ref from iterator");
30863 }
30864 ao2_iterator_destroy(&i);
30865
30866
30867 i = ao2_iterator_init(dialogs, 0);
30868 while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
30869 if (p->owner)
30870 ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
30871 ao2_t_ref(p, -1, "toss dialog ptr from iterator_next");
30872 }
30873 ao2_iterator_destroy(&i);
30874
30875 unlink_all_peers_from_tables();
30876
30877 ast_mutex_lock(&monlock);
30878 if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP) && (monitor_thread != AST_PTHREADT_NULL)) {
30879 pthread_cancel(monitor_thread);
30880 pthread_kill(monitor_thread, SIGURG);
30881 pthread_join(monitor_thread, NULL);
30882 }
30883 monitor_thread = AST_PTHREADT_STOP;
30884 ast_mutex_unlock(&monlock);
30885
30886
30887 i = ao2_iterator_init(dialogs, 0);
30888 while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
30889 dialog_unlink_all(p);
30890 ao2_t_ref(p, -1, "throw away iterator result");
30891 }
30892 ao2_iterator_destroy(&i);
30893
30894
30895 ast_free_ha(localaddr);
30896
30897 ast_mutex_lock(&authl_lock);
30898 if (authl) {
30899 ao2_t_ref(authl, -1, "Removing global authentication");
30900 authl = NULL;
30901 }
30902 ast_mutex_unlock(&authl_lock);
30903
30904 sip_epa_unregister_all();
30905 destroy_escs();
30906
30907 ast_free(default_tls_cfg.certfile);
30908 ast_free(default_tls_cfg.pvtfile);
30909 ast_free(default_tls_cfg.cipher);
30910 ast_free(default_tls_cfg.cafile);
30911 ast_free(default_tls_cfg.capath);
30912
30913 cleanup_all_regs();
30914 ASTOBJ_CONTAINER_DESTROYALL(®l, sip_registry_destroy);
30915 ASTOBJ_CONTAINER_DESTROY(®l);
30916
30917 ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
30918 ASTOBJ_WRLOCK(iterator);
30919 if (iterator->dnsmgr) {
30920 ast_dnsmgr_release(iterator->dnsmgr);
30921 iterator->dnsmgr = NULL;
30922 ASTOBJ_UNREF(iterator, sip_subscribe_mwi_destroy);
30923 }
30924 ASTOBJ_UNLOCK(iterator);
30925 } while(0));
30926 ASTOBJ_CONTAINER_DESTROYALL(&submwil, sip_subscribe_mwi_destroy);
30927 ASTOBJ_CONTAINER_DESTROY(&submwil);
30928
30929
30930
30931
30932
30933
30934
30935
30936 wait_count = 1000;
30937 while (ao2_container_count(threadt) && --wait_count) {
30938 sched_yield();
30939 }
30940 if (!wait_count) {
30941 ast_debug(2, "TCP/TLS thread container did not become empty :(\n");
30942 }
30943
30944 ao2_t_ref(peers, -1, "unref the peers table");
30945 ao2_t_ref(peers_by_ip, -1, "unref the peers_by_ip table");
30946 ao2_t_ref(dialogs, -1, "unref the dialogs table");
30947 ao2_t_ref(dialogs_to_destroy, -1, "unref dialogs_to_destroy");
30948 ao2_t_ref(threadt, -1, "unref the thread table");
30949 ao2_t_ref(sip_monitor_instances, -1, "unref the sip_monitor_instances table");
30950
30951 clear_sip_domains();
30952 ast_free_ha(sip_cfg.contact_ha);
30953 close(sipsock);
30954 sched_context_destroy(sched);
30955 con = ast_context_find(used_context);
30956 if (con) {
30957 ast_context_destroy(con, "SIP");
30958 }
30959 ast_unload_realtime("sipregs");
30960 ast_unload_realtime("sippeers");
30961 ast_cc_monitor_unregister(&sip_cc_monitor_callbacks);
30962 ast_cc_agent_unregister(&sip_cc_agent_callbacks);
30963
30964 sip_reqresp_parser_exit();
30965 sip_unregister_tests();
30966
30967 return 0;
30968 }
30969
30970 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Session Initiation Protocol (SIP)",
30971 .load = load_module,
30972 .unload = unload_module,
30973 .reload = reload,
30974 .load_pri = AST_MODPRI_CHANNEL_DRIVER,
30975 .nonoptreq = "res_crypto,chan_local",
30976 );