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: 378781 $")
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
02507
02508
02509
02510
02511
02512
02513
02514
02515
02516
02517
02518
02519
02520
02521
02522
02523 static int sip_tls_read(struct sip_request *req, struct sip_request *reqcpy, struct ast_tcptls_session_instance *tcptls_session,
02524 int authenticated, time_t start, struct sip_threadinfo *me)
02525 {
02526 int res, content_length, after_poll = 1, need_poll = 1;
02527 size_t datalen = ast_str_strlen(req->data);
02528 char buf[1024] = "";
02529 int timeout = -1;
02530
02531
02532 while (datalen < 4 || strncmp(REQ_OFFSET_TO_STR(req, data->used - 4), "\r\n\r\n", 4)) {
02533 if (!tcptls_session->client && !authenticated) {
02534 if ((timeout = sip_check_authtimeout(start)) < 0) {
02535 ast_debug(2, "SIP TLS server failed to determine authentication timeout\n");
02536 return -1;
02537 }
02538
02539 if (timeout == 0) {
02540 ast_debug(2, "SIP TLS server timed out\n");
02541 return -1;
02542 }
02543 } else {
02544 timeout = -1;
02545 }
02546
02547
02548
02549
02550 if (need_poll) {
02551 need_poll = 0;
02552 after_poll = 1;
02553 res = ast_wait_for_input(tcptls_session->fd, timeout);
02554 if (res < 0) {
02555 ast_debug(2, "SIP TLS server :: ast_wait_for_input returned %d\n", res);
02556 return -1;
02557 } else if (res == 0) {
02558
02559 ast_debug(2, "SIP TLS server timed out\n");
02560 return -1;
02561 }
02562 }
02563
02564 ast_mutex_lock(&tcptls_session->lock);
02565 if (!fgets(buf, sizeof(buf), tcptls_session->f)) {
02566 ast_mutex_unlock(&tcptls_session->lock);
02567 if (after_poll) {
02568 return -1;
02569 } else {
02570 need_poll = 1;
02571 continue;
02572 }
02573 }
02574 ast_mutex_unlock(&tcptls_session->lock);
02575 after_poll = 0;
02576 if (me->stop) {
02577 return -1;
02578 }
02579 ast_str_append(&req->data, 0, "%s", buf);
02580
02581 datalen = ast_str_strlen(req->data);
02582 if (datalen > SIP_MAX_PACKET_SIZE) {
02583 ast_log(LOG_WARNING, "Rejecting TLS packet from '%s' because way too large: %zu\n",
02584 ast_sockaddr_stringify(&tcptls_session->remote_address), datalen);
02585 return -1;
02586 }
02587 }
02588 copy_request(reqcpy, req);
02589 parse_request(reqcpy);
02590
02591 if (sscanf(get_header(reqcpy, "Content-Length"), "%30d", &content_length)) {
02592 while (content_length > 0) {
02593 size_t bytes_read;
02594 if (!tcptls_session->client && !authenticated) {
02595 if ((timeout = sip_check_authtimeout(start)) < 0) {
02596 return -1;
02597 }
02598
02599 if (timeout == 0) {
02600 ast_debug(2, "SIP TLS server timed out\n");
02601 return -1;
02602 }
02603 } else {
02604 timeout = -1;
02605 }
02606
02607 if (need_poll) {
02608 need_poll = 0;
02609 after_poll = 1;
02610 res = ast_wait_for_input(tcptls_session->fd, timeout);
02611 if (res < 0) {
02612 ast_debug(2, "SIP TLS server :: ast_wait_for_input returned %d\n", res);
02613 return -1;
02614 } else if (res == 0) {
02615
02616 ast_debug(2, "SIP TLS server timed out\n");
02617 return -1;
02618 }
02619 }
02620
02621 ast_mutex_lock(&tcptls_session->lock);
02622 if (!(bytes_read = fread(buf, 1, MIN(sizeof(buf) - 1, content_length), tcptls_session->f))) {
02623 ast_mutex_unlock(&tcptls_session->lock);
02624 if (after_poll) {
02625 return -1;
02626 } else {
02627 need_poll = 1;
02628 continue;
02629 }
02630 }
02631 buf[bytes_read] = '\0';
02632 ast_mutex_unlock(&tcptls_session->lock);
02633 after_poll = 0;
02634 if (me->stop) {
02635 return -1;
02636 }
02637 content_length -= strlen(buf);
02638 ast_str_append(&req->data, 0, "%s", buf);
02639
02640 datalen = ast_str_strlen(req->data);
02641 if (datalen > SIP_MAX_PACKET_SIZE) {
02642 ast_log(LOG_WARNING, "Rejecting TLS packet from '%s' because way too large: %zu\n",
02643 ast_sockaddr_stringify(&tcptls_session->remote_address), datalen);
02644 return -1;
02645 }
02646 }
02647 }
02648
02649
02650 return 0;
02651 }
02652
02653
02654
02655
02656 enum message_integrity {
02657
02658
02659
02660
02661 MESSAGE_INVALID,
02662
02663
02664
02665 MESSAGE_FRAGMENT,
02666
02667
02668
02669
02670 MESSAGE_FRAGMENT_COMPLETE,
02671
02672
02673
02674 MESSAGE_COMPLETE,
02675 };
02676
02677
02678
02679
02680
02681
02682
02683
02684 static int read_raw_content_length(const char *message)
02685 {
02686 char *content_length_str;
02687 int content_length = -1;
02688
02689 struct ast_str *msg_copy;
02690 char *msg;
02691
02692
02693 if (!(msg_copy = ast_str_create(strlen(message) + 1))) {
02694 return -1;
02695 }
02696 ast_str_set(&msg_copy, 0, "%s", message);
02697
02698 if (sip_cfg.pedanticsipchecking) {
02699 lws2sws(msg_copy);
02700 }
02701
02702 msg = ast_str_buffer(msg_copy);
02703
02704
02705 if ((content_length_str = strcasestr(msg, "\nContent-Length:"))) {
02706 content_length_str += sizeof("\nContent-Length:") - 1;
02707 } else if ((content_length_str = strcasestr(msg, "\nl:"))) {
02708 content_length_str += sizeof("\nl:") - 1;
02709 } else {
02710
02711
02712
02713
02714
02715 goto done;
02716 }
02717
02718
02719 if (!strchr(content_length_str, '\n')) {
02720 goto done;
02721 }
02722
02723 if (sscanf(content_length_str, "%30d", &content_length) != 1) {
02724 content_length = -1;
02725 }
02726
02727 done:
02728 ast_free(msg_copy);
02729 return content_length;
02730 }
02731
02732
02733
02734
02735
02736
02737
02738
02739
02740
02741
02742
02743
02744 static enum message_integrity check_message_integrity(struct ast_str **request, struct ast_str **overflow)
02745 {
02746 char *message = ast_str_buffer(*request);
02747 char *body;
02748 int content_length;
02749 int message_len = ast_str_strlen(*request);
02750 int body_len;
02751
02752
02753
02754
02755
02756
02757 body = strstr(message, "\r\n\r\n");
02758 if (!body) {
02759
02760
02761
02762 return MESSAGE_FRAGMENT;
02763 }
02764 body += sizeof("\r\n\r\n") - 1;
02765 body_len = message_len - (body - message);
02766
02767 body[-1] = '\0';
02768 content_length = read_raw_content_length(message);
02769 body[-1] = '\n';
02770
02771 if (content_length < 0) {
02772 return MESSAGE_INVALID;
02773 } else if (content_length == 0) {
02774
02775
02776
02777
02778 if (body_len == 0) {
02779 return MESSAGE_COMPLETE;
02780 } else {
02781 ast_str_append(overflow, 0, "%s", body);
02782 ast_str_truncate(*request, message_len - body_len);
02783 return MESSAGE_FRAGMENT_COMPLETE;
02784 }
02785 }
02786
02787
02788
02789 if (body_len < content_length) {
02790
02791 return MESSAGE_FRAGMENT;
02792 } else if (body_len > content_length) {
02793
02794
02795
02796 ast_str_append(overflow, 0, "%s", body + content_length);
02797 ast_str_truncate(*request, message_len - (body_len - content_length));
02798 return MESSAGE_FRAGMENT_COMPLETE;
02799 } else {
02800
02801 return MESSAGE_COMPLETE;
02802 }
02803 }
02804
02805
02806
02807
02808
02809
02810
02811
02812
02813 static int sip_tcp_read(struct sip_request *req, struct ast_tcptls_session_instance *tcptls_session,
02814 int authenticated, time_t start)
02815 {
02816 enum message_integrity message_integrity = MESSAGE_FRAGMENT;
02817
02818 while (message_integrity == MESSAGE_FRAGMENT) {
02819 size_t datalen;
02820
02821 if (ast_str_strlen(tcptls_session->overflow_buf) == 0) {
02822 char readbuf[4097];
02823 int timeout;
02824 int res;
02825 if (!tcptls_session->client && !authenticated) {
02826 if ((timeout = sip_check_authtimeout(start)) < 0) {
02827 return -1;
02828 }
02829
02830 if (timeout == 0) {
02831 ast_debug(2, "SIP TCP server timed out\n");
02832 return -1;
02833 }
02834 } else {
02835 timeout = -1;
02836 }
02837 res = ast_wait_for_input(tcptls_session->fd, timeout);
02838 if (res < 0) {
02839 ast_debug(2, "SIP TCP server :: ast_wait_for_input returned %d\n", res);
02840 return -1;
02841 } else if (res == 0) {
02842 ast_debug(2, "SIP TCP server timed out\n");
02843 return -1;
02844 }
02845
02846 res = recv(tcptls_session->fd, readbuf, sizeof(readbuf) - 1, 0);
02847 if (res < 0) {
02848 ast_debug(2, "SIP TCP server error when receiving data\n");
02849 return -1;
02850 } else if (res == 0) {
02851 ast_debug(2, "SIP TCP server has shut down\n");
02852 return -1;
02853 }
02854 readbuf[res] = '\0';
02855 ast_str_append(&req->data, 0, "%s", readbuf);
02856 } else {
02857 ast_str_append(&req->data, 0, "%s", ast_str_buffer(tcptls_session->overflow_buf));
02858 ast_str_reset(tcptls_session->overflow_buf);
02859 }
02860
02861 datalen = ast_str_strlen(req->data);
02862 if (datalen > SIP_MAX_PACKET_SIZE) {
02863 ast_log(LOG_WARNING, "Rejecting TCP packet from '%s' because way too large: %zu\n",
02864 ast_sockaddr_stringify(&tcptls_session->remote_address), datalen);
02865 return -1;
02866 }
02867
02868 message_integrity = check_message_integrity(&req->data, &tcptls_session->overflow_buf);
02869 }
02870
02871 return 0;
02872 }
02873
02874
02875
02876
02877 static void *_sip_tcp_helper_thread(struct ast_tcptls_session_instance *tcptls_session)
02878 {
02879 int res, timeout = -1, authenticated = 0, flags;
02880 time_t start;
02881 struct sip_request req = { 0, } , reqcpy = { 0, };
02882 struct sip_threadinfo *me = NULL;
02883 char buf[1024] = "";
02884 struct pollfd fds[2] = { { 0 }, { 0 }, };
02885 struct ast_tcptls_session_args *ca = NULL;
02886
02887
02888
02889
02890
02891
02892
02893
02894
02895
02896
02897
02898 if (!tcptls_session->client) {
02899 if (ast_atomic_fetchadd_int(&unauth_sessions, +1) >= authlimit) {
02900
02901 goto cleanup;
02902 }
02903
02904 if ((flags = fcntl(tcptls_session->fd, F_GETFL)) == -1) {
02905 ast_log(LOG_ERROR, "error setting socket to non blocking mode, fcntl() failed: %s\n", strerror(errno));
02906 goto cleanup;
02907 }
02908
02909 flags |= O_NONBLOCK;
02910 if (fcntl(tcptls_session->fd, F_SETFL, flags) == -1) {
02911 ast_log(LOG_ERROR, "error setting socket to non blocking mode, fcntl() failed: %s\n", strerror(errno));
02912 goto cleanup;
02913 }
02914
02915 if (!(me = sip_threadinfo_create(tcptls_session, tcptls_session->ssl ? SIP_TRANSPORT_TLS : SIP_TRANSPORT_TCP))) {
02916 goto cleanup;
02917 }
02918 ao2_t_ref(me, +1, "Adding threadinfo ref for tcp_helper_thread");
02919 } else {
02920 struct sip_threadinfo tmp = {
02921 .tcptls_session = tcptls_session,
02922 };
02923
02924 if ((!(ca = tcptls_session->parent)) ||
02925 (!(me = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread"))) ||
02926 (!(tcptls_session = ast_tcptls_client_start(tcptls_session)))) {
02927 goto cleanup;
02928 }
02929 }
02930
02931 flags = 1;
02932 if (setsockopt(tcptls_session->fd, SOL_SOCKET, SO_KEEPALIVE, &flags, sizeof(flags))) {
02933 ast_log(LOG_ERROR, "error enabling TCP keep-alives on sip socket: %s\n", strerror(errno));
02934 goto cleanup;
02935 }
02936
02937 me->threadid = pthread_self();
02938 ast_debug(2, "Starting thread for %s server\n", tcptls_session->ssl ? "TLS" : "TCP");
02939
02940
02941 fds[0].fd = tcptls_session->fd;
02942 fds[1].fd = me->alert_pipe[0];
02943 fds[0].events = fds[1].events = POLLIN | POLLPRI;
02944
02945 if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
02946 goto cleanup;
02947 }
02948 if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET))) {
02949 goto cleanup;
02950 }
02951
02952 if(time(&start) == -1) {
02953 ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
02954 goto cleanup;
02955 }
02956
02957 for (;;) {
02958 struct ast_str *str_save;
02959
02960 if (!tcptls_session->client && req.authenticated && !authenticated) {
02961 authenticated = 1;
02962 ast_atomic_fetchadd_int(&unauth_sessions, -1);
02963 }
02964
02965
02966 if (!tcptls_session->client && !authenticated ) {
02967 if ((timeout = sip_check_authtimeout(start)) < 0) {
02968 goto cleanup;
02969 }
02970
02971 if (timeout == 0) {
02972 ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "TLS": "TCP");
02973 goto cleanup;
02974 }
02975 } else {
02976 timeout = -1;
02977 }
02978
02979 if (ast_str_strlen(tcptls_session->overflow_buf) == 0) {
02980 res = ast_poll(fds, 2, timeout);
02981 if (res < 0) {
02982 ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", tcptls_session->ssl ? "TLS": "TCP", res);
02983 goto cleanup;
02984 } else if (res == 0) {
02985
02986 ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "TLS": "TCP");
02987 goto cleanup;
02988 }
02989 }
02990
02991
02992
02993
02994
02995 if (fds[0].revents || (ast_str_strlen(tcptls_session->overflow_buf) > 0)) {
02996 fds[0].revents = 0;
02997
02998
02999 str_save = req.data;
03000 memset(&req, 0, sizeof(req));
03001 req.data = str_save;
03002 ast_str_reset(req.data);
03003
03004 str_save = reqcpy.data;
03005 memset(&reqcpy, 0, sizeof(reqcpy));
03006 reqcpy.data = str_save;
03007 ast_str_reset(reqcpy.data);
03008
03009 memset(buf, 0, sizeof(buf));
03010
03011 if (tcptls_session->ssl) {
03012 set_socket_transport(&req.socket, SIP_TRANSPORT_TLS);
03013 req.socket.port = htons(ourport_tls);
03014 } else {
03015 set_socket_transport(&req.socket, SIP_TRANSPORT_TCP);
03016 req.socket.port = htons(ourport_tcp);
03017 }
03018 req.socket.fd = tcptls_session->fd;
03019
03020 if (tcptls_session->ssl) {
03021 res = sip_tls_read(&req, &reqcpy, tcptls_session, authenticated, start, me);
03022 } else {
03023 res = sip_tcp_read(&req, tcptls_session, authenticated, start);
03024 }
03025
03026 if (res < 0) {
03027 goto cleanup;
03028 }
03029
03030 req.socket.tcptls_session = tcptls_session;
03031 handle_request_do(&req, &tcptls_session->remote_address);
03032 }
03033
03034 if (fds[1].revents) {
03035 enum sip_tcptls_alert alert;
03036 struct tcptls_packet *packet;
03037
03038 fds[1].revents = 0;
03039
03040 if (read(me->alert_pipe[0], &alert, sizeof(alert)) == -1) {
03041 ast_log(LOG_ERROR, "read() failed: %s\n", strerror(errno));
03042 continue;
03043 }
03044
03045 switch (alert) {
03046 case TCPTLS_ALERT_STOP:
03047 goto cleanup;
03048 case TCPTLS_ALERT_DATA:
03049 ao2_lock(me);
03050 if (!(packet = AST_LIST_REMOVE_HEAD(&me->packet_q, entry))) {
03051 ast_log(LOG_WARNING, "TCPTLS thread alert_pipe indicated packet should be sent, but frame_q is empty\n");
03052 }
03053 ao2_unlock(me);
03054
03055 if (packet) {
03056 if (ast_tcptls_server_write(tcptls_session, ast_str_buffer(packet->data), packet->len) == -1) {
03057 ast_log(LOG_WARNING, "Failure to write to tcp/tls socket\n");
03058 }
03059 ao2_t_ref(packet, -1, "tcptls packet sent, this is no longer needed");
03060 }
03061 break;
03062 default:
03063 ast_log(LOG_ERROR, "Unknown tcptls thread alert '%d'\n", alert);
03064 }
03065 }
03066 }
03067
03068 ast_debug(2, "Shutting down thread for %s server\n", tcptls_session->ssl ? "TLS" : "TCP");
03069
03070 cleanup:
03071 if (tcptls_session && !tcptls_session->client && !authenticated) {
03072 ast_atomic_fetchadd_int(&unauth_sessions, -1);
03073 }
03074
03075 if (me) {
03076 ao2_t_unlink(threadt, me, "Removing tcptls helper thread, thread is closing");
03077 ao2_t_ref(me, -1, "Removing tcp_helper_threads threadinfo ref");
03078 }
03079 deinit_req(&reqcpy);
03080 deinit_req(&req);
03081
03082
03083 if (ca) {
03084 ao2_t_ref(ca, -1, "closing tcptls thread, getting rid of client tcptls_session arguments");
03085 }
03086
03087 if (tcptls_session) {
03088 ast_mutex_lock(&tcptls_session->lock);
03089 ast_tcptls_close_session_file(tcptls_session);
03090 tcptls_session->parent = NULL;
03091 ast_mutex_unlock(&tcptls_session->lock);
03092
03093 ao2_ref(tcptls_session, -1);
03094 tcptls_session = NULL;
03095 }
03096 return NULL;
03097 }
03098
03099 #ifdef REF_DEBUG
03100 #define ref_peer(arg1,arg2) _ref_peer((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
03101 #define unref_peer(arg1,arg2) _unref_peer((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
03102 static struct sip_peer *_ref_peer(struct sip_peer *peer, char *tag, char *file, int line, const char *func)
03103 {
03104 if (peer)
03105 __ao2_ref_debug(peer, 1, tag, file, line, func);
03106 else
03107 ast_log(LOG_ERROR, "Attempt to Ref a null peer pointer\n");
03108 return peer;
03109 }
03110
03111 static struct sip_peer *_unref_peer(struct sip_peer *peer, char *tag, char *file, int line, const char *func)
03112 {
03113 if (peer)
03114 __ao2_ref_debug(peer, -1, tag, file, line, func);
03115 return NULL;
03116 }
03117 #else
03118
03119
03120
03121
03122
03123 static void *unref_peer(struct sip_peer *peer, char *tag)
03124 {
03125 ao2_t_ref(peer, -1, tag);
03126 return NULL;
03127 }
03128
03129 static struct sip_peer *ref_peer(struct sip_peer *peer, char *tag)
03130 {
03131 ao2_t_ref(peer, 1, tag);
03132 return peer;
03133 }
03134 #endif
03135
03136 static void peer_sched_cleanup(struct sip_peer *peer)
03137 {
03138 if (peer->pokeexpire != -1) {
03139 AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
03140 unref_peer(peer, "removing poke peer ref"));
03141 }
03142 if (peer->expire != -1) {
03143 AST_SCHED_DEL_UNREF(sched, peer->expire,
03144 unref_peer(peer, "remove register expire ref"));
03145 }
03146 }
03147
03148 typedef enum {
03149 SIP_PEERS_MARKED,
03150 SIP_PEERS_ALL,
03151 } peer_unlink_flag_t;
03152
03153
03154
03155 static int match_and_cleanup_peer_sched(void *peerobj, void *arg, int flags)
03156 {
03157 struct sip_peer *peer = peerobj;
03158 peer_unlink_flag_t which = *(peer_unlink_flag_t *)arg;
03159
03160 if (which == SIP_PEERS_ALL || peer->the_mark) {
03161 peer_sched_cleanup(peer);
03162 if (peer->dnsmgr) {
03163 ast_dnsmgr_release(peer->dnsmgr);
03164 peer->dnsmgr = NULL;
03165 unref_peer(peer, "Release peer from dnsmgr");
03166 }
03167 return CMP_MATCH;
03168 }
03169 return 0;
03170 }
03171
03172 static void unlink_peers_from_tables(peer_unlink_flag_t flag)
03173 {
03174 ao2_t_callback(peers, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE,
03175 match_and_cleanup_peer_sched, &flag, "initiating callback to remove marked peers");
03176 ao2_t_callback(peers_by_ip, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE,
03177 match_and_cleanup_peer_sched, &flag, "initiating callback to remove marked peers");
03178 }
03179
03180
03181 static void unlink_marked_peers_from_tables(void)
03182 {
03183 unlink_peers_from_tables(SIP_PEERS_MARKED);
03184 }
03185
03186 static void unlink_all_peers_from_tables(void)
03187 {
03188 unlink_peers_from_tables(SIP_PEERS_ALL);
03189 }
03190
03191
03192 static void unlink_peer_from_tables(struct sip_peer *peer)
03193 {
03194 ao2_t_unlink(peers, peer, "ao2_unlink of peer from peers table");
03195 if (!ast_sockaddr_isnull(&peer->addr)) {
03196 ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
03197 }
03198 }
03199
03200
03201
03202
03203
03204
03205
03206
03207
03208
03209
03210
03211 static void ref_proxy(struct sip_pvt *pvt, struct sip_proxy *proxy)
03212 {
03213 struct sip_proxy *old_obproxy = pvt->outboundproxy;
03214
03215
03216
03217 if (proxy && proxy != &sip_cfg.outboundproxy) {
03218 ao2_ref(proxy, +1);
03219 }
03220 pvt->outboundproxy = proxy;
03221 if (old_obproxy && old_obproxy != &sip_cfg.outboundproxy) {
03222 ao2_ref(old_obproxy, -1);
03223 }
03224 }
03225
03226
03227
03228
03229
03230
03231
03232
03233 void dialog_unlink_all(struct sip_pvt *dialog)
03234 {
03235 struct sip_pkt *cp;
03236 struct ast_channel *owner;
03237
03238 dialog_ref(dialog, "Let's bump the count in the unlink so it doesn't accidentally become dead before we are done");
03239
03240 ao2_t_unlink(dialogs, dialog, "unlinking dialog via ao2_unlink");
03241
03242
03243 owner = sip_pvt_lock_full(dialog);
03244 if (owner) {
03245 ast_debug(1, "Detaching from channel %s\n", owner->name);
03246 owner->tech_pvt = dialog_unref(owner->tech_pvt, "resetting channel dialog ptr in unlink_all");
03247 ast_channel_unlock(owner);
03248 ast_channel_unref(owner);
03249 dialog->owner = NULL;
03250 }
03251 sip_pvt_unlock(dialog);
03252
03253 if (dialog->registry) {
03254 if (dialog->registry->call == dialog) {
03255 dialog->registry->call = dialog_unref(dialog->registry->call, "nulling out the registry's call dialog field in unlink_all");
03256 }
03257 dialog->registry = registry_unref(dialog->registry, "delete dialog->registry");
03258 }
03259 if (dialog->stateid != -1) {
03260 ast_extension_state_del(dialog->stateid, cb_extensionstate);
03261 dialog->stateid = -1;
03262 }
03263
03264 if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog) {
03265 dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
03266 }
03267 if (dialog->relatedpeer && dialog->relatedpeer->call == dialog) {
03268 dialog->relatedpeer->call = dialog_unref(dialog->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
03269 }
03270
03271
03272 while((cp = dialog->packets)) {
03273 dialog->packets = dialog->packets->next;
03274 AST_SCHED_DEL(sched, cp->retransid);
03275 dialog_unref(cp->owner, "remove all current packets in this dialog, and the pointer to the dialog too as part of __sip_destroy");
03276 if (cp->data) {
03277 ast_free(cp->data);
03278 }
03279 ast_free(cp);
03280 }
03281
03282 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"));
03283
03284 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"));
03285
03286 if (dialog->autokillid > -1) {
03287 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"));
03288 }
03289
03290 if (dialog->request_queue_sched_id > -1) {
03291 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"));
03292 }
03293
03294 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"));
03295
03296 if (dialog->t38id > -1) {
03297 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"));
03298 }
03299
03300 if (dialog->stimer) {
03301 stop_session_timer(dialog);
03302 }
03303
03304 dialog_unref(dialog, "Let's unbump the count in the unlink so the poor pvt can disappear if it is time");
03305 }
03306
03307 void *registry_unref(struct sip_registry *reg, char *tag)
03308 {
03309 ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount - 1);
03310 ASTOBJ_UNREF(reg, sip_registry_destroy);
03311 return NULL;
03312 }
03313
03314
03315 static struct sip_registry *registry_addref(struct sip_registry *reg, char *tag)
03316 {
03317 ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount + 1);
03318 return ASTOBJ_REF(reg);
03319 }
03320
03321
03322 static struct ast_udptl_protocol sip_udptl = {
03323 .type = "SIP",
03324 .get_udptl_info = sip_get_udptl_peer,
03325 .set_udptl_peer = sip_set_udptl_peer,
03326 };
03327
03328 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
03329 __attribute__((format(printf, 2, 3)));
03330
03331
03332
03333 static const char *referstatus2str(enum referstatus rstatus)
03334 {
03335 return map_x_s(referstatusstrings, rstatus, "");
03336 }
03337
03338 static inline void pvt_set_needdestroy(struct sip_pvt *pvt, const char *reason)
03339 {
03340 if (pvt->final_destruction_scheduled) {
03341 return;
03342 }
03343 append_history(pvt, "NeedDestroy", "Setting needdestroy because %s", reason);
03344 pvt->needdestroy = 1;
03345 }
03346
03347
03348
03349
03350 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
03351 {
03352 if (p->initreq.headers) {
03353 ast_debug(1, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
03354 } else {
03355 ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
03356 }
03357
03358 copy_request(&p->initreq, req);
03359 parse_request(&p->initreq);
03360 if (req->debug) {
03361 ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
03362 }
03363 }
03364
03365
03366 static void sip_alreadygone(struct sip_pvt *dialog)
03367 {
03368 ast_debug(3, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
03369 dialog->alreadygone = 1;
03370 }
03371
03372
03373 static int proxy_update(struct sip_proxy *proxy)
03374 {
03375
03376
03377 if (!ast_sockaddr_parse(&proxy->ip, proxy->name, 0)) {
03378
03379
03380 proxy->ip.ss.ss_family = get_address_family_filter(SIP_TRANSPORT_UDP);
03381 if (ast_get_ip_or_srv(&proxy->ip, proxy->name, sip_cfg.srvlookup ? "_sip._udp" : NULL) < 0) {
03382 ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
03383 return FALSE;
03384 }
03385
03386 }
03387
03388 ast_sockaddr_set_port(&proxy->ip, proxy->port);
03389
03390 proxy->last_dnsupdate = time(NULL);
03391 return TRUE;
03392 }
03393
03394
03395
03396
03397 static struct sip_proxy *proxy_from_config(const char *proxy, int sipconf_lineno, struct sip_proxy *dest)
03398 {
03399 char *mutable_proxy, *sep, *name;
03400 int allocated = 0;
03401
03402 if (!dest) {
03403 dest = ao2_alloc(sizeof(struct sip_proxy), NULL);
03404 if (!dest) {
03405 ast_log(LOG_WARNING, "Unable to allocate config storage for proxy\n");
03406 return NULL;
03407 }
03408 allocated = 1;
03409 }
03410
03411
03412 mutable_proxy = ast_skip_blanks(ast_strdupa(proxy));
03413 sep = strchr(mutable_proxy, ',');
03414 if (sep) {
03415 *sep++ = '\0';
03416 dest->force = !strncasecmp(ast_skip_blanks(sep), "force", 5);
03417 } else {
03418 dest->force = FALSE;
03419 }
03420
03421 sip_parse_host(mutable_proxy, sipconf_lineno, &name, &dest->port, &dest->transport);
03422
03423
03424 if (ast_strlen_zero(name)) {
03425 if (allocated) {
03426 ao2_ref(dest, -1);
03427 } else {
03428 dest->name[0] = '\0';
03429 }
03430 return NULL;
03431 }
03432 ast_copy_string(dest->name, name, sizeof(dest->name));
03433
03434
03435 proxy_update(dest);
03436
03437 return dest;
03438 }
03439
03440
03441
03442
03443
03444 unsigned int port_str2int(const char *pt, unsigned int standard)
03445 {
03446 int port = standard;
03447 if (ast_strlen_zero(pt) || (sscanf(pt, "%30d", &port) != 1) || (port < 1) || (port > 65535)) {
03448 port = standard;
03449 }
03450
03451 return port;
03452 }
03453
03454
03455 static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
03456 {
03457 if (dialog && dialog->options && dialog->options->outboundproxy) {
03458 if (sipdebug) {
03459 ast_debug(1, "OBPROXY: Applying dialplan set OBproxy to this call\n");
03460 }
03461 append_history(dialog, "OBproxy", "Using dialplan obproxy %s", dialog->options->outboundproxy->name);
03462 return dialog->options->outboundproxy;
03463 }
03464 if (peer && peer->outboundproxy) {
03465 if (sipdebug) {
03466 ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
03467 }
03468 append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
03469 return peer->outboundproxy;
03470 }
03471 if (sip_cfg.outboundproxy.name[0]) {
03472 if (sipdebug) {
03473 ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
03474 }
03475 append_history(dialog, "OBproxy", "Using global obproxy %s", sip_cfg.outboundproxy.name);
03476 return &sip_cfg.outboundproxy;
03477 }
03478 if (sipdebug) {
03479 ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
03480 }
03481 return NULL;
03482 }
03483
03484
03485
03486
03487
03488
03489
03490 static int method_match(enum sipmethod id, const char *name)
03491 {
03492 int len = strlen(sip_methods[id].text);
03493 int l_name = name ? strlen(name) : 0;
03494
03495 return (l_name >= len && name && name[len] < 33 &&
03496 !strncasecmp(sip_methods[id].text, name, len));
03497 }
03498
03499
03500 static int find_sip_method(const char *msg)
03501 {
03502 int i, res = 0;
03503
03504 if (ast_strlen_zero(msg)) {
03505 return 0;
03506 }
03507 for (i = 1; i < ARRAY_LEN(sip_methods) && !res; i++) {
03508 if (method_match(i, msg)) {
03509 res = sip_methods[i].id;
03510 }
03511 }
03512 return res;
03513 }
03514
03515
03516 static inline int sip_debug_test_addr(const struct ast_sockaddr *addr)
03517 {
03518
03519 if (!sipdebug) {
03520 return 0;
03521 }
03522
03523
03524 if (ast_sockaddr_isnull(&debugaddr)) {
03525 return 1;
03526 }
03527
03528
03529
03530
03531 if (ast_sockaddr_port(&debugaddr)) {
03532 return !ast_sockaddr_cmp(&debugaddr, addr);
03533 } else {
03534 return !ast_sockaddr_cmp_addr(&debugaddr, addr);
03535 }
03536 }
03537
03538
03539 static const struct ast_sockaddr *sip_real_dst(const struct sip_pvt *p)
03540 {
03541 if (p->outboundproxy) {
03542 return &p->outboundproxy->ip;
03543 }
03544
03545 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;
03546 }
03547
03548
03549 static const char *sip_nat_mode(const struct sip_pvt *p)
03550 {
03551 return ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) ? "NAT" : "no NAT";
03552 }
03553
03554
03555 static inline int sip_debug_test_pvt(struct sip_pvt *p)
03556 {
03557 if (!sipdebug) {
03558 return 0;
03559 }
03560 return sip_debug_test_addr(sip_real_dst(p));
03561 }
03562
03563
03564 static int get_transport_str2enum(const char *transport)
03565 {
03566 int res = 0;
03567
03568 if (ast_strlen_zero(transport)) {
03569 return res;
03570 }
03571
03572 if (!strcasecmp(transport, "udp")) {
03573 res |= SIP_TRANSPORT_UDP;
03574 }
03575 if (!strcasecmp(transport, "tcp")) {
03576 res |= SIP_TRANSPORT_TCP;
03577 }
03578 if (!strcasecmp(transport, "tls")) {
03579 res |= SIP_TRANSPORT_TLS;
03580 }
03581
03582 return res;
03583 }
03584
03585
03586 static inline const char *get_transport_list(unsigned int transports) {
03587 switch (transports) {
03588 case SIP_TRANSPORT_UDP:
03589 return "UDP";
03590 case SIP_TRANSPORT_TCP:
03591 return "TCP";
03592 case SIP_TRANSPORT_TLS:
03593 return "TLS";
03594 case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TCP:
03595 return "TCP,UDP";
03596 case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TLS:
03597 return "TLS,UDP";
03598 case SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS:
03599 return "TLS,TCP";
03600 default:
03601 return transports ?
03602 "TLS,TCP,UDP" : "UNKNOWN";
03603 }
03604 }
03605
03606
03607 static inline const char *get_transport(enum sip_transport t)
03608 {
03609 switch (t) {
03610 case SIP_TRANSPORT_UDP:
03611 return "UDP";
03612 case SIP_TRANSPORT_TCP:
03613 return "TCP";
03614 case SIP_TRANSPORT_TLS:
03615 return "TLS";
03616 }
03617
03618 return "UNKNOWN";
03619 }
03620
03621
03622 static inline const char *get_srv_protocol(enum sip_transport t)
03623 {
03624 switch (t) {
03625 case SIP_TRANSPORT_UDP:
03626 return "udp";
03627 case SIP_TRANSPORT_TLS:
03628 case SIP_TRANSPORT_TCP:
03629 return "tcp";
03630 }
03631
03632 return "udp";
03633 }
03634
03635
03636 static inline const char *get_srv_service(enum sip_transport t)
03637 {
03638 switch (t) {
03639 case SIP_TRANSPORT_TCP:
03640 case SIP_TRANSPORT_UDP:
03641 return "sip";
03642 case SIP_TRANSPORT_TLS:
03643 return "sips";
03644 }
03645 return "sip";
03646 }
03647
03648
03649
03650
03651
03652
03653
03654 static inline const char *get_transport_pvt(struct sip_pvt *p)
03655 {
03656 if (p->outboundproxy && p->outboundproxy->transport) {
03657 set_socket_transport(&p->socket, p->outboundproxy->transport);
03658 }
03659
03660 return get_transport(p->socket.type);
03661 }
03662
03663
03664
03665
03666
03667
03668
03669
03670
03671
03672
03673
03674 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data)
03675 {
03676 int res = 0;
03677 const struct ast_sockaddr *dst = sip_real_dst(p);
03678
03679 ast_debug(2, "Trying to put '%.11s' onto %s socket destined for %s\n", ast_str_buffer(data), get_transport_pvt(p), ast_sockaddr_stringify(dst));
03680
03681 if (sip_prepare_socket(p) < 0) {
03682 return XMIT_ERROR;
03683 }
03684
03685 if (p->socket.type == SIP_TRANSPORT_UDP) {
03686 res = ast_sendto(p->socket.fd, ast_str_buffer(data), ast_str_strlen(data), 0, dst);
03687 } else if (p->socket.tcptls_session) {
03688 res = sip_tcptls_write(p->socket.tcptls_session, ast_str_buffer(data), ast_str_strlen(data));
03689 } else {
03690 ast_debug(2, "Socket type is TCP but no tcptls_session is present to write to\n");
03691 return XMIT_ERROR;
03692 }
03693
03694 if (res == -1) {
03695 switch (errno) {
03696 case EBADF:
03697 case EHOSTUNREACH:
03698 case ENETDOWN:
03699 case ENETUNREACH:
03700 case ECONNREFUSED:
03701 res = XMIT_ERROR;
03702 }
03703 }
03704 if (res != ast_str_strlen(data)) {
03705 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));
03706 }
03707
03708 return res;
03709 }
03710
03711
03712 static void build_via(struct sip_pvt *p)
03713 {
03714
03715 const char *rport = (ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) || ast_test_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT)) ? ";rport" : "";
03716
03717
03718 snprintf(p->via, sizeof(p->via), "SIP/2.0/%s %s;branch=z9hG4bK%08x%s",
03719 get_transport_pvt(p),
03720 ast_sockaddr_stringify_remote(&p->ourip),
03721 (int) p->branch, rport);
03722 }
03723
03724
03725
03726
03727
03728
03729
03730
03731 static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p)
03732 {
03733 struct ast_sockaddr theirs;
03734
03735
03736
03737
03738
03739
03740
03741
03742
03743
03744
03745
03746
03747 int want_remap = 0;
03748
03749 ast_sockaddr_copy(us, &internip);
03750
03751 ast_ouraddrfor(them, us);
03752 ast_sockaddr_copy(&theirs, them);
03753
03754 if (ast_sockaddr_is_ipv6(&theirs)) {
03755 if (localaddr && !ast_sockaddr_isnull(&externaddr) && !ast_sockaddr_is_any(&bindaddr)) {
03756 ast_log(LOG_WARNING, "Address remapping activated in sip.conf "
03757 "but we're using IPv6, which doesn't need it. Please "
03758 "remove \"localnet\" and/or \"externaddr\" settings.\n");
03759 }
03760 } else {
03761 want_remap = localaddr &&
03762 !ast_sockaddr_isnull(&externaddr) &&
03763 ast_apply_ha(localaddr, &theirs) == AST_SENSE_ALLOW ;
03764 }
03765
03766 if (want_remap &&
03767 (!sip_cfg.matchexternaddrlocally || !ast_apply_ha(localaddr, us)) ) {
03768
03769 if (externexpire && time(NULL) >= externexpire) {
03770 if (ast_sockaddr_resolve_first(&externaddr, externhost, 0)) {
03771 ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
03772 }
03773 externexpire = time(NULL) + externrefresh;
03774 }
03775 if (!ast_sockaddr_isnull(&externaddr)) {
03776 ast_sockaddr_copy(us, &externaddr);
03777 switch (p->socket.type) {
03778 case SIP_TRANSPORT_TCP:
03779 if (!externtcpport && ast_sockaddr_port(&externaddr)) {
03780
03781 externtcpport = ast_sockaddr_port(&externaddr);
03782 }
03783 ast_sockaddr_set_port(us, externtcpport);
03784 break;
03785 case SIP_TRANSPORT_TLS:
03786 ast_sockaddr_set_port(us, externtlsport);
03787 break;
03788 case SIP_TRANSPORT_UDP:
03789 if (!ast_sockaddr_port(&externaddr)) {
03790 ast_sockaddr_set_port(us, ast_sockaddr_port(&bindaddr));
03791 }
03792 break;
03793 default:
03794 break;
03795 }
03796 }
03797 ast_debug(1, "Target address %s is not local, substituting externaddr\n",
03798 ast_sockaddr_stringify(them));
03799 } else {
03800
03801 switch (p->socket.type) {
03802 case SIP_TRANSPORT_TCP:
03803 if (!ast_sockaddr_is_any(&sip_tcp_desc.local_address)) {
03804 ast_sockaddr_copy(us,
03805 &sip_tcp_desc.local_address);
03806 } else {
03807 ast_sockaddr_set_port(us,
03808 ast_sockaddr_port(&sip_tcp_desc.local_address));
03809 }
03810 break;
03811 case SIP_TRANSPORT_TLS:
03812 if (!ast_sockaddr_is_any(&sip_tls_desc.local_address)) {
03813 ast_sockaddr_copy(us,
03814 &sip_tls_desc.local_address);
03815 } else {
03816 ast_sockaddr_set_port(us,
03817 ast_sockaddr_port(&sip_tls_desc.local_address));
03818 }
03819 break;
03820 case SIP_TRANSPORT_UDP:
03821
03822 default:
03823 if (!ast_sockaddr_is_any(&bindaddr)) {
03824 ast_sockaddr_copy(us, &bindaddr);
03825 }
03826 if (!ast_sockaddr_port(us)) {
03827 ast_sockaddr_set_port(us, ast_sockaddr_port(&bindaddr));
03828 }
03829 }
03830 }
03831 ast_debug(3, "Setting SIP_TRANSPORT_%s with address %s\n", get_transport(p->socket.type), ast_sockaddr_stringify(us));
03832 }
03833
03834
03835 static __attribute__((format(printf, 2, 0))) void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
03836 {
03837 char buf[80], *c = buf;
03838 struct sip_history *hist;
03839 int l;
03840
03841 vsnprintf(buf, sizeof(buf), fmt, ap);
03842 strsep(&c, "\r\n");
03843 l = strlen(buf) + 1;
03844 if (!(hist = ast_calloc(1, sizeof(*hist) + l))) {
03845 return;
03846 }
03847 if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
03848 ast_free(hist);
03849 return;
03850 }
03851 memcpy(hist->event, buf, l);
03852 if (p->history_entries == MAX_HISTORY_ENTRIES) {
03853 struct sip_history *oldest;
03854 oldest = AST_LIST_REMOVE_HEAD(p->history, list);
03855 p->history_entries--;
03856 ast_free(oldest);
03857 }
03858 AST_LIST_INSERT_TAIL(p->history, hist, list);
03859 p->history_entries++;
03860 }
03861
03862
03863 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
03864 {
03865 va_list ap;
03866
03867 if (!p) {
03868 return;
03869 }
03870
03871 if (!p->do_history && !recordhistory && !dumphistory) {
03872 return;
03873 }
03874
03875 va_start(ap, fmt);
03876 append_history_va(p, fmt, ap);
03877 va_end(ap);
03878
03879 return;
03880 }
03881
03882
03883 static int retrans_pkt(const void *data)
03884 {
03885 struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
03886 int reschedule = DEFAULT_RETRANS;
03887 int xmitres = 0;
03888
03889 int64_t diff = pkt->retrans_stop_time - ast_tvdiff_ms(ast_tvnow(), pkt->time_sent);
03890
03891
03892
03893
03894 if ((diff <= 0) || (diff > pkt->retrans_stop_time)) {
03895 pkt->retrans_stop = 1;
03896 }
03897
03898
03899 sip_pvt_lock(pkt->owner);
03900
03901 if (!pkt->retrans_stop) {
03902 pkt->retrans++;
03903 if (!pkt->timer_t1) {
03904 if (sipdebug) {
03905 ast_debug(4, "SIP TIMER: Not rescheduling id #%d:%s (Method %d) (No timer T1)\n",
03906 pkt->retransid,
03907 sip_methods[pkt->method].text,
03908 pkt->method);
03909 }
03910 } else {
03911 int siptimer_a;
03912
03913 if (sipdebug) {
03914 ast_debug(4, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n",
03915 pkt->retransid,
03916 pkt->retrans,
03917 sip_methods[pkt->method].text,
03918 pkt->method);
03919 }
03920 if (!pkt->timer_a) {
03921 pkt->timer_a = 2 ;
03922 } else {
03923 pkt->timer_a = 2 * pkt->timer_a;
03924 }
03925
03926
03927 siptimer_a = pkt->timer_t1 * pkt->timer_a;
03928 if (pkt->method != SIP_INVITE && siptimer_a > 4000) {
03929 siptimer_a = 4000;
03930 }
03931
03932
03933 reschedule = siptimer_a;
03934 ast_debug(4, "** SIP timers: Rescheduling retransmission %d to %d ms (t1 %d ms (Retrans id #%d)) \n",
03935 pkt->retrans + 1,
03936 siptimer_a,
03937 pkt->timer_t1,
03938 pkt->retransid);
03939 }
03940
03941 if (sip_debug_test_pvt(pkt->owner)) {
03942 const struct ast_sockaddr *dst = sip_real_dst(pkt->owner);
03943 ast_verbose("Retransmitting #%d (%s) to %s:\n%s\n---\n",
03944 pkt->retrans, sip_nat_mode(pkt->owner),
03945 ast_sockaddr_stringify(dst),
03946 ast_str_buffer(pkt->data));
03947 }
03948
03949 append_history(pkt->owner, "ReTx", "%d %s", reschedule, ast_str_buffer(pkt->data));
03950 xmitres = __sip_xmit(pkt->owner, pkt->data);
03951
03952
03953
03954
03955
03956
03957 if (xmitres != XMIT_ERROR) {
03958 if (reschedule >= diff) {
03959 pkt->retrans_stop = 1;
03960 reschedule = diff;
03961 }
03962 sip_pvt_unlock(pkt->owner);
03963 return reschedule;
03964 }
03965 }
03966
03967
03968
03969
03970 pkt->retransid = -1;
03971
03972 if (pkt->method != SIP_OPTIONS && xmitres == 0) {
03973 if (pkt->is_fatal || sipdebug) {
03974 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"
03975 "Packet timed out after %dms with no response\n",
03976 pkt->owner->callid,
03977 pkt->seqno,
03978 pkt->is_fatal ? "Critical" : "Non-critical",
03979 pkt->is_resp ? "Response" : "Request",
03980 (int) ast_tvdiff_ms(ast_tvnow(), pkt->time_sent));
03981 }
03982 } else if (pkt->method == SIP_OPTIONS && sipdebug) {
03983 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);
03984 }
03985
03986 if (xmitres == XMIT_ERROR) {
03987 ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission on Call ID %s\n", pkt->owner->callid);
03988 append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03989 } else {
03990 append_history(pkt->owner, "MaxRetries", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03991 }
03992
03993 if (pkt->is_fatal) {
03994 while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
03995 sip_pvt_unlock(pkt->owner);
03996 usleep(1);
03997 sip_pvt_lock(pkt->owner);
03998 }
03999 if (pkt->owner->owner && !pkt->owner->owner->hangupcause) {
04000 pkt->owner->owner->hangupcause = AST_CAUSE_NO_USER_RESPONSE;
04001 }
04002 if (pkt->owner->owner) {
04003 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);
04004
04005 if (pkt->is_resp &&
04006 (pkt->response_code >= 200) &&
04007 (pkt->response_code < 300) &&
04008 pkt->owner->pendinginvite &&
04009 ast_test_flag(&pkt->owner->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
04010
04011
04012
04013
04014
04015
04016
04017 pkt->owner->invitestate = INV_TERMINATED;
04018 pkt->owner->pendinginvite = 0;
04019 } else {
04020
04021 sip_alreadygone(pkt->owner);
04022 }
04023 ast_queue_hangup_with_cause(pkt->owner->owner, AST_CAUSE_NO_USER_RESPONSE);
04024 ast_channel_unlock(pkt->owner->owner);
04025 } else {
04026
04027
04028
04029 if (pkt->method != SIP_OPTIONS && pkt->method != SIP_REGISTER) {
04030 pvt_set_needdestroy(pkt->owner, "no response to critical packet");
04031 sip_alreadygone(pkt->owner);
04032 append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
04033 }
04034 }
04035 }
04036
04037 if (pkt->method == SIP_BYE) {
04038
04039 sip_alreadygone(pkt->owner);
04040 if (pkt->owner->owner) {
04041 ast_channel_unlock(pkt->owner->owner);
04042 }
04043 append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
04044 pvt_set_needdestroy(pkt->owner, "no response to BYE");
04045 }
04046
04047
04048 for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
04049 if (cur == pkt) {
04050 UNLINK(cur, pkt->owner->packets, prev);
04051 sip_pvt_unlock(pkt->owner);
04052 if (pkt->owner) {
04053 pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
04054 }
04055 if (pkt->data) {
04056 ast_free(pkt->data);
04057 }
04058 pkt->data = NULL;
04059 ast_free(pkt);
04060 return 0;
04061 }
04062 }
04063
04064 ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
04065 sip_pvt_unlock(pkt->owner);
04066 return 0;
04067 }
04068
04069
04070
04071
04072
04073
04074 static enum sip_result __sip_reliable_xmit(struct sip_pvt *p, uint32_t seqno, int resp, struct ast_str *data, int fatal, int sipmethod)
04075 {
04076 struct sip_pkt *pkt = NULL;
04077 int siptimer_a = DEFAULT_RETRANS;
04078 int xmitres = 0;
04079 int respid;
04080
04081 if (sipmethod == SIP_INVITE) {
04082
04083 p->pendinginvite = seqno;
04084 }
04085
04086
04087
04088
04089 if (!(p->socket.type & SIP_TRANSPORT_UDP)) {
04090 xmitres = __sip_xmit(p, data);
04091 if (xmitres == XMIT_ERROR) {
04092 append_history(p, "XmitErr", "%s", fatal ? "(Critical)" : "(Non-critical)");
04093 return AST_FAILURE;
04094 } else {
04095 return AST_SUCCESS;
04096 }
04097 }
04098
04099 if (!(pkt = ast_calloc(1, sizeof(*pkt)))) {
04100 return AST_FAILURE;
04101 }
04102
04103 if (!(pkt->data = ast_str_create(ast_str_strlen(data)))) {
04104 ast_free(pkt);
04105 return AST_FAILURE;
04106 }
04107 ast_str_set(&pkt->data, 0, "%s%s", ast_str_buffer(data), "\0");
04108
04109 pkt->method = sipmethod;
04110 pkt->seqno = seqno;
04111 pkt->is_resp = resp;
04112 pkt->is_fatal = fatal;
04113 pkt->owner = dialog_ref(p, "__sip_reliable_xmit: setting pkt->owner");
04114 pkt->next = p->packets;
04115 p->packets = pkt;
04116 if (resp) {
04117
04118 if (sscanf(ast_str_buffer(pkt->data), "SIP/2.0 %30u", &respid) == 1) {
04119 pkt->response_code = respid;
04120 }
04121 }
04122 pkt->timer_t1 = p->timer_t1;
04123 pkt->retransid = -1;
04124 if (pkt->timer_t1) {
04125 siptimer_a = pkt->timer_t1;
04126 }
04127
04128 pkt->time_sent = ast_tvnow();
04129 pkt->retrans_stop_time = 64 * (pkt->timer_t1 ? pkt->timer_t1 : DEFAULT_TIMER_T1);
04130
04131
04132 AST_SCHED_REPLACE_VARIABLE(pkt->retransid, sched, siptimer_a, retrans_pkt, pkt, 1);
04133 if (sipdebug) {
04134 ast_debug(4, "*** SIP TIMER: Initializing retransmit timer on packet: Id #%d\n", pkt->retransid);
04135 }
04136
04137 xmitres = __sip_xmit(pkt->owner, pkt->data);
04138
04139 if (xmitres == XMIT_ERROR) {
04140 append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
04141 ast_log(LOG_ERROR, "Serious Network Trouble; __sip_xmit returns error for pkt data\n");
04142 AST_SCHED_DEL(sched, pkt->retransid);
04143 p->packets = pkt->next;
04144 pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
04145 ast_free(pkt->data);
04146 ast_free(pkt);
04147 return AST_FAILURE;
04148 } else {
04149
04150
04151
04152
04153 if (monitor_thread != AST_PTHREADT_NULL) {
04154 pthread_kill(monitor_thread, SIGURG);
04155 }
04156 return AST_SUCCESS;
04157 }
04158 }
04159
04160
04161
04162
04163
04164
04165 static int __sip_autodestruct(const void *data)
04166 {
04167 struct sip_pvt *p = (struct sip_pvt *)data;
04168 struct ast_channel *owner;
04169
04170
04171 if (p->subscribed && p->subscribed != MWI_NOTIFICATION && p->subscribed != CALL_COMPLETION) {
04172 transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE);
04173 p->subscribed = NONE;
04174 append_history(p, "Subscribestatus", "timeout");
04175 ast_debug(3, "Re-scheduled destruction of SIP subscription %s\n", p->callid ? p->callid : "<unknown>");
04176 return 10000;
04177 }
04178
04179
04180 if (p->packets) {
04181 if (!p->needdestroy) {
04182 char method_str[31];
04183 ast_debug(3, "Re-scheduled destruction of SIP call %s\n", p->callid ? p->callid : "<unknown>");
04184 append_history(p, "ReliableXmit", "timeout");
04185 if (sscanf(p->lastmsg, "Tx: %30s", method_str) == 1 || sscanf(p->lastmsg, "Rx: %30s", method_str) == 1) {
04186 if (p->ongoing_reinvite || method_match(SIP_CANCEL, method_str) || method_match(SIP_BYE, method_str)) {
04187 pvt_set_needdestroy(p, "autodestruct");
04188 }
04189 }
04190 return 10000;
04191 } else {
04192
04193 __sip_pretend_ack(p);
04194 }
04195 }
04196
04197
04198 p->autokillid = -1;
04199
04200
04201
04202
04203 owner = sip_pvt_lock_full(p);
04204 if (owner) {
04205 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);
04206 ast_queue_hangup_with_cause(owner, AST_CAUSE_PROTOCOL_ERROR);
04207 ast_channel_unlock(owner);
04208 ast_channel_unref(owner);
04209 sip_pvt_unlock(p);
04210 return 10000;
04211 } else if (p->refer && !p->alreadygone) {
04212 ast_debug(3, "Finally hanging up channel after transfer: %s\n", p->callid);
04213 stop_media_flows(p);
04214 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
04215 append_history(p, "ReferBYE", "Sending BYE on transferer call leg %s", p->callid);
04216 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
04217 } else {
04218 append_history(p, "AutoDestroy", "%s", p->callid);
04219 ast_debug(3, "Auto destroying SIP dialog '%s'\n", p->callid);
04220 sip_pvt_unlock(p);
04221 dialog_unlink_all(p);
04222 sip_pvt_lock(p);
04223
04224
04225
04226 }
04227
04228 sip_pvt_unlock(p);
04229
04230 dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
04231
04232 return 0;
04233 }
04234
04235
04236
04237
04238 void sip_scheddestroy_final(struct sip_pvt *p, int ms)
04239 {
04240 if (p->final_destruction_scheduled) {
04241 return;
04242 }
04243
04244 sip_scheddestroy(p, ms);
04245 if (p->autokillid != -1) {
04246 p->final_destruction_scheduled = 1;
04247 }
04248 }
04249
04250
04251 void sip_scheddestroy(struct sip_pvt *p, int ms)
04252 {
04253 if (p->final_destruction_scheduled) {
04254 return;
04255 }
04256
04257 if (ms < 0) {
04258 if (p->timer_t1 == 0) {
04259 p->timer_t1 = global_t1;
04260 }
04261 if (p->timer_b == 0) {
04262 p->timer_b = global_timer_b;
04263 }
04264 ms = p->timer_t1 * 64;
04265 }
04266 if (sip_debug_test_pvt(p)) {
04267 ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
04268 }
04269 if (sip_cancel_destroy(p)) {
04270 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
04271 }
04272
04273 if (p->do_history) {
04274 append_history(p, "SchedDestroy", "%d ms", ms);
04275 }
04276 p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, dialog_ref(p, "setting ref as passing into ast_sched_add for __sip_autodestruct"));
04277
04278 if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_schedid > 0) {
04279 stop_session_timer(p);
04280 }
04281 }
04282
04283
04284
04285
04286
04287 int sip_cancel_destroy(struct sip_pvt *p)
04288 {
04289 if (p->final_destruction_scheduled) {
04290 return 0;
04291 }
04292
04293 if (p->autokillid > -1) {
04294 append_history(p, "CancelDestroy", "");
04295 AST_SCHED_DEL_UNREF(sched, p->autokillid, dialog_unref(p, "remove ref for autokillid"));
04296 }
04297 return 0;
04298 }
04299
04300
04301
04302 int __sip_ack(struct sip_pvt *p, uint32_t seqno, int resp, int sipmethod)
04303 {
04304 struct sip_pkt *cur, *prev = NULL;
04305 const char *msg = "Not Found";
04306 int res = FALSE;
04307
04308
04309
04310
04311
04312
04313 if (p->outboundproxy && !p->outboundproxy->force){
04314 ref_proxy(p, NULL);
04315 }
04316
04317 for (cur = p->packets; cur; prev = cur, cur = cur->next) {
04318 if (cur->seqno != seqno || cur->is_resp != resp) {
04319 continue;
04320 }
04321 if (cur->is_resp || cur->method == sipmethod) {
04322 res = TRUE;
04323 msg = "Found";
04324 if (!resp && (seqno == p->pendinginvite)) {
04325 ast_debug(1, "Acked pending invite %u\n", p->pendinginvite);
04326 p->pendinginvite = 0;
04327 }
04328 if (cur->retransid > -1) {
04329 if (sipdebug)
04330 ast_debug(4, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
04331 }
04332
04333
04334
04335
04336
04337
04338
04339
04340
04341
04342
04343
04344
04345
04346
04347
04348 while (cur->retransid > -1 && ast_sched_del(sched, cur->retransid)) {
04349 sip_pvt_unlock(p);
04350 usleep(1);
04351 sip_pvt_lock(p);
04352 }
04353 UNLINK(cur, p->packets, prev);
04354 dialog_unref(cur->owner, "unref pkt cur->owner dialog from sip ack before freeing pkt");
04355 if (cur->data) {
04356 ast_free(cur->data);
04357 }
04358 ast_free(cur);
04359 break;
04360 }
04361 }
04362 ast_debug(1, "Stopping retransmission on '%s' of %s %u: Match %s\n",
04363 p->callid, resp ? "Response" : "Request", seqno, msg);
04364 return res;
04365 }
04366
04367
04368
04369 void __sip_pretend_ack(struct sip_pvt *p)
04370 {
04371 struct sip_pkt *cur = NULL;
04372
04373 while (p->packets) {
04374 int method;
04375 if (cur == p->packets) {
04376 ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
04377 return;
04378 }
04379 cur = p->packets;
04380 method = (cur->method) ? cur->method : find_sip_method(ast_str_buffer(cur->data));
04381 __sip_ack(p, cur->seqno, cur->is_resp, method);
04382 }
04383 }
04384
04385
04386 int __sip_semi_ack(struct sip_pvt *p, uint32_t seqno, int resp, int sipmethod)
04387 {
04388 struct sip_pkt *cur;
04389 int res = FALSE;
04390
04391 for (cur = p->packets; cur; cur = cur->next) {
04392 if (cur->seqno == seqno && cur->is_resp == resp &&
04393 (cur->is_resp || method_match(sipmethod, ast_str_buffer(cur->data)))) {
04394
04395 if (cur->retransid > -1) {
04396 if (sipdebug)
04397 ast_debug(4, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
04398 }
04399 AST_SCHED_DEL(sched, cur->retransid);
04400 res = TRUE;
04401 break;
04402 }
04403 }
04404 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");
04405 return res;
04406 }
04407
04408
04409
04410 static void parse_copy(struct sip_request *dst, const struct sip_request *src)
04411 {
04412 copy_request(dst, src);
04413 parse_request(dst);
04414 }
04415
04416
04417 static void add_blank(struct sip_request *req)
04418 {
04419 if (!req->lines) {
04420
04421 ast_str_append(&req->data, 0, "\r\n");
04422 }
04423 }
04424
04425 static int send_provisional_keepalive_full(struct sip_pvt *pvt, int with_sdp)
04426 {
04427 const char *msg = NULL;
04428 struct ast_channel *chan;
04429 int res = 0;
04430
04431 chan = sip_pvt_lock_full(pvt);
04432
04433 if (!pvt->last_provisional || !strncasecmp(pvt->last_provisional, "100", 3)) {
04434 msg = "183 Session Progress";
04435 }
04436
04437 if (pvt->invitestate < INV_COMPLETED) {
04438 if (with_sdp) {
04439 transmit_response_with_sdp(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq, XMIT_UNRELIABLE, FALSE, FALSE);
04440 } else {
04441 transmit_response(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq);
04442 }
04443 res = PROVIS_KEEPALIVE_TIMEOUT;
04444 }
04445
04446 if (chan) {
04447 ast_channel_unlock(chan);
04448 chan = ast_channel_unref(chan);
04449 }
04450
04451 if (!res) {
04452 pvt->provisional_keepalive_sched_id = -1;
04453 }
04454
04455 sip_pvt_unlock(pvt);
04456
04457 #if 0
04458
04459
04460
04461
04462
04463
04464
04465
04466 if (!res) {
04467 dialog_unref(pvt, "dialog ref for provisional keepalive");
04468 }
04469 #endif
04470
04471 return res;
04472 }
04473
04474 static int send_provisional_keepalive(const void *data) {
04475 struct sip_pvt *pvt = (struct sip_pvt *) data;
04476
04477 return send_provisional_keepalive_full(pvt, 0);
04478 }
04479
04480 static int send_provisional_keepalive_with_sdp(const void *data) {
04481 struct sip_pvt *pvt = (void *)data;
04482
04483 return send_provisional_keepalive_full(pvt, 1);
04484 }
04485
04486 static void update_provisional_keepalive(struct sip_pvt *pvt, int with_sdp)
04487 {
04488 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"));
04489
04490 pvt->provisional_keepalive_sched_id = ast_sched_add(sched, PROVIS_KEEPALIVE_TIMEOUT,
04491 with_sdp ? send_provisional_keepalive_with_sdp : send_provisional_keepalive, dialog_ref(pvt, "Increment refcount to pass dialog pointer to sched callback"));
04492 }
04493
04494 static void add_required_respheader(struct sip_request *req)
04495 {
04496 struct ast_str *str;
04497 int i;
04498
04499 if (!req->reqsipoptions) {
04500 return;
04501 }
04502
04503 str = ast_str_create(32);
04504
04505 for (i = 0; i < ARRAY_LEN(sip_options); ++i) {
04506 if (!(req->reqsipoptions & sip_options[i].id)) {
04507 continue;
04508 }
04509 if (ast_str_strlen(str) > 0) {
04510 ast_str_append(&str, 0, ", ");
04511 }
04512 ast_str_append(&str, 0, "%s", sip_options[i].text);
04513 }
04514
04515 if (ast_str_strlen(str) > 0) {
04516 add_header(req, "Require", ast_str_buffer(str));
04517 }
04518
04519 ast_free(str);
04520 }
04521
04522
04523 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno)
04524 {
04525 int res;
04526
04527 finalize_content(req);
04528 add_blank(req);
04529 if (sip_debug_test_pvt(p)) {
04530 const struct ast_sockaddr *dst = sip_real_dst(p);
04531
04532 ast_verbose("\n<--- %sTransmitting (%s) to %s --->\n%s\n<------------>\n",
04533 reliable ? "Reliably " : "", sip_nat_mode(p),
04534 ast_sockaddr_stringify(dst),
04535 ast_str_buffer(req->data));
04536 }
04537 if (p->do_history) {
04538 struct sip_request tmp = { .rlPart1 = 0, };
04539 parse_copy(&tmp, req);
04540 append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", ast_str_buffer(tmp.data), get_header(&tmp, "CSeq"),
04541 (tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? REQ_OFFSET_TO_STR(&tmp, rlPart2) : sip_methods[tmp.method].text);
04542 deinit_req(&tmp);
04543 }
04544
04545
04546 if (p->initreq.method == SIP_INVITE && reliable == XMIT_CRITICAL) {
04547 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"));
04548 }
04549
04550 res = (reliable) ?
04551 __sip_reliable_xmit(p, seqno, 1, req->data, (reliable == XMIT_CRITICAL), req->method) :
04552 __sip_xmit(p, req->data);
04553 deinit_req(req);
04554 if (res > 0) {
04555 return 0;
04556 }
04557 return res;
04558 }
04559
04560
04561
04562
04563
04564
04565 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno)
04566 {
04567 int res;
04568
04569
04570
04571
04572 if (p->outboundproxy) {
04573 p->sa = p->outboundproxy->ip;
04574 }
04575
04576 finalize_content(req);
04577 add_blank(req);
04578 if (sip_debug_test_pvt(p)) {
04579 if (ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT)) {
04580 ast_verbose("%sTransmitting (NAT) to %s:\n%s\n---\n", reliable ? "Reliably " : "", ast_sockaddr_stringify(&p->recv), ast_str_buffer(req->data));
04581 } else {
04582 ast_verbose("%sTransmitting (no NAT) to %s:\n%s\n---\n", reliable ? "Reliably " : "", ast_sockaddr_stringify(&p->sa), ast_str_buffer(req->data));
04583 }
04584 }
04585 if (p->do_history) {
04586 struct sip_request tmp = { .rlPart1 = 0, };
04587 parse_copy(&tmp, req);
04588 append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", ast_str_buffer(tmp.data), get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
04589 deinit_req(&tmp);
04590 }
04591 res = (reliable) ?
04592 __sip_reliable_xmit(p, seqno, 0, req->data, (reliable == XMIT_CRITICAL), req->method) :
04593 __sip_xmit(p, req->data);
04594 deinit_req(req);
04595 return res;
04596 }
04597
04598 static void enable_dsp_detect(struct sip_pvt *p)
04599 {
04600 int features = 0;
04601
04602 if (p->dsp) {
04603 return;
04604 }
04605
04606 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
04607 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
04608 if (p->rtp) {
04609 ast_rtp_instance_dtmf_mode_set(p->rtp, AST_RTP_DTMF_MODE_INBAND);
04610 }
04611 features |= DSP_FEATURE_DIGIT_DETECT;
04612 }
04613
04614 if (ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_CNG)) {
04615 features |= DSP_FEATURE_FAX_DETECT;
04616 }
04617
04618 if (!features) {
04619 return;
04620 }
04621
04622 if (!(p->dsp = ast_dsp_new())) {
04623 return;
04624 }
04625
04626 ast_dsp_set_features(p->dsp, features);
04627 if (global_relaxdtmf) {
04628 ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
04629 }
04630 }
04631
04632 static void disable_dsp_detect(struct sip_pvt *p)
04633 {
04634 if (p->dsp) {
04635 ast_dsp_free(p->dsp);
04636 p->dsp = NULL;
04637 }
04638 }
04639
04640
04641 static int sip_setoption(struct ast_channel *chan, int option, void *data, int datalen)
04642 {
04643 int res = -1;
04644 struct sip_pvt *p = chan->tech_pvt;
04645
04646 if (!p) {
04647 ast_log(LOG_ERROR, "Attempt to Ref a null pointer. sip private structure is gone!\n");
04648 return -1;
04649 }
04650
04651 sip_pvt_lock(p);
04652
04653 switch (option) {
04654 case AST_OPTION_FORMAT_READ:
04655 if (p->rtp) {
04656 res = ast_rtp_instance_set_read_format(p->rtp, *(int *) data);
04657 }
04658 break;
04659 case AST_OPTION_FORMAT_WRITE:
04660 if (p->rtp) {
04661 res = ast_rtp_instance_set_write_format(p->rtp, *(int *) data);
04662 }
04663 break;
04664 case AST_OPTION_MAKE_COMPATIBLE:
04665 if (p->rtp) {
04666 res = ast_rtp_instance_make_compatible(chan, p->rtp, (struct ast_channel *) data);
04667 }
04668 break;
04669 case AST_OPTION_DIGIT_DETECT:
04670 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
04671 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
04672 char *cp = (char *) data;
04673
04674 ast_debug(1, "%sabling digit detection on %s\n", *cp ? "En" : "Dis", chan->name);
04675 if (*cp) {
04676 enable_dsp_detect(p);
04677 } else {
04678 disable_dsp_detect(p);
04679 }
04680 res = 0;
04681 }
04682 break;
04683 case AST_OPTION_SECURE_SIGNALING:
04684 p->req_secure_signaling = *(unsigned int *) data;
04685 res = 0;
04686 break;
04687 case AST_OPTION_SECURE_MEDIA:
04688 ast_set2_flag(&p->flags[1], *(unsigned int *) data, SIP_PAGE2_USE_SRTP);
04689 res = 0;
04690 break;
04691 default:
04692 break;
04693 }
04694
04695 sip_pvt_unlock(p);
04696
04697 return res;
04698 }
04699
04700
04701 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen)
04702 {
04703 int res = -1;
04704 enum ast_t38_state state = T38_STATE_UNAVAILABLE;
04705 struct sip_pvt *p = (struct sip_pvt *) chan->tech_pvt;
04706 char *cp;
04707
04708 sip_pvt_lock(p);
04709
04710 switch (option) {
04711 case AST_OPTION_T38_STATE:
04712
04713 if (*datalen != sizeof(enum ast_t38_state)) {
04714 ast_log(LOG_ERROR, "Invalid datalen for AST_OPTION_T38_STATE option. Expected %d, got %d\n", (int)sizeof(enum ast_t38_state), *datalen);
04715 break;
04716 }
04717
04718
04719 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
04720 switch (p->t38.state) {
04721 case T38_LOCAL_REINVITE:
04722 case T38_PEER_REINVITE:
04723 state = T38_STATE_NEGOTIATING;
04724 break;
04725 case T38_ENABLED:
04726 state = T38_STATE_NEGOTIATED;
04727 break;
04728 default:
04729 state = T38_STATE_UNKNOWN;
04730 }
04731 }
04732
04733 *((enum ast_t38_state *) data) = state;
04734 res = 0;
04735
04736 break;
04737 case AST_OPTION_DIGIT_DETECT:
04738 cp = (char *) data;
04739 *cp = p->dsp ? 1 : 0;
04740 ast_debug(1, "Reporting digit detection %sabled on %s\n", *cp ? "en" : "dis", chan->name);
04741 break;
04742 case AST_OPTION_SECURE_SIGNALING:
04743 *((unsigned int *) data) = p->req_secure_signaling;
04744 res = 0;
04745 break;
04746 case AST_OPTION_SECURE_MEDIA:
04747 *((unsigned int *) data) = ast_test_flag(&p->flags[1], SIP_PAGE2_USE_SRTP) ? 1 : 0;
04748 res = 0;
04749 break;
04750 case AST_OPTION_DEVICE_NAME:
04751 if (p && p->outgoing_call) {
04752 cp = (char *) data;
04753 ast_copy_string(cp, p->dialstring, *datalen);
04754 res = 0;
04755 }
04756
04757
04758
04759 break;
04760 default:
04761 break;
04762 }
04763
04764 sip_pvt_unlock(p);
04765
04766 return res;
04767 }
04768
04769
04770
04771
04772
04773 const char *find_closing_quote(const char *start, const char *lim)
04774 {
04775 char last_char = '\0';
04776 const char *s;
04777 for (s = start; *s && s != lim; last_char = *s++) {
04778 if (*s == '"' && last_char != '\\')
04779 break;
04780 }
04781 return s;
04782 }
04783
04784
04785 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
04786 {
04787 struct sip_pvt *p = chan->tech_pvt;
04788
04789 if (subclass != AST_HTML_URL)
04790 return -1;
04791
04792 ast_string_field_build(p, url, "<%s>;mode=active", data);
04793
04794 if (sip_debug_test_pvt(p))
04795 ast_debug(1, "Send URL %s, state = %d!\n", data, chan->_state);
04796
04797 switch (chan->_state) {
04798 case AST_STATE_RING:
04799 transmit_response(p, "100 Trying", &p->initreq);
04800 break;
04801 case AST_STATE_RINGING:
04802 transmit_response(p, "180 Ringing", &p->initreq);
04803 break;
04804 case AST_STATE_UP:
04805 if (!p->pendinginvite) {
04806 transmit_reinvite_with_sdp(p, FALSE, FALSE);
04807 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
04808 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
04809 }
04810 break;
04811 default:
04812 ast_log(LOG_WARNING, "Don't know how to send URI when state is %d!\n", chan->_state);
04813 }
04814
04815 return 0;
04816 }
04817
04818
04819 static const char *sip_get_callid(struct ast_channel *chan)
04820 {
04821 return chan->tech_pvt ? ((struct sip_pvt *) chan->tech_pvt)->callid : "";
04822 }
04823
04824
04825
04826
04827
04828
04829 static int sip_sendtext(struct ast_channel *ast, const char *text)
04830 {
04831 struct sip_pvt *dialog = ast->tech_pvt;
04832 int debug;
04833
04834 if (!dialog) {
04835 return -1;
04836 }
04837
04838
04839 if (!text) {
04840 return 0;
04841 }
04842 if(!is_method_allowed(&dialog->allowed_methods, SIP_MESSAGE)) {
04843 ast_debug(2, "Trying to send MESSAGE to device that does not support it.\n");
04844 return(0);
04845 }
04846
04847 debug = sip_debug_test_pvt(dialog);
04848 if (debug) {
04849 ast_verbose("Sending text %s on %s\n", text, ast->name);
04850 }
04851
04852 transmit_message_with_text(dialog, text);
04853 return 0;
04854 }
04855
04856
04857
04858
04859
04860
04861 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)
04862 {
04863 char port[10];
04864 char ipaddr[INET6_ADDRSTRLEN];
04865 char regseconds[20];
04866 char *tablename = NULL;
04867 char str_lastms[20];
04868
04869 const char *sysname = ast_config_AST_SYSTEM_NAME;
04870 char *syslabel = NULL;
04871
04872 time_t nowtime = time(NULL) + expirey;
04873 const char *fc = fullcontact ? "fullcontact" : NULL;
04874
04875 int realtimeregs = ast_check_realtime("sipregs");
04876
04877 tablename = realtimeregs ? "sipregs" : "sippeers";
04878
04879
04880 snprintf(str_lastms, sizeof(str_lastms), "%d", lastms);
04881 snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime);
04882 ast_copy_string(ipaddr, ast_sockaddr_isnull(addr) ? "" : ast_sockaddr_stringify_addr(addr), sizeof(ipaddr));
04883 ast_copy_string(port, ast_sockaddr_port(addr) ? ast_sockaddr_stringify_port(addr) : "", sizeof(port));
04884
04885 if (ast_strlen_zero(sysname))
04886 sysname = NULL;
04887 else if (sip_cfg.rtsave_sysname)
04888 syslabel = "regserver";
04889
04890
04891
04892
04893
04894
04895
04896 if (fc) {
04897 ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
04898 "port", port, "regseconds", regseconds,
04899 deprecated_username ? "username" : "defaultuser", defaultuser,
04900 "useragent", useragent, "lastms", str_lastms,
04901 fc, fullcontact, syslabel, sysname, SENTINEL);
04902 } else {
04903 ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
04904 "port", port, "regseconds", regseconds,
04905 "useragent", useragent, "lastms", str_lastms,
04906 deprecated_username ? "username" : "defaultuser", defaultuser,
04907 syslabel, sysname, SENTINEL);
04908 }
04909 }
04910
04911
04912 static void register_peer_exten(struct sip_peer *peer, int onoff)
04913 {
04914 char multi[256];
04915 char *stringp, *ext, *context;
04916 struct pbx_find_info q = { .stacklen = 0 };
04917
04918
04919
04920
04921
04922 if (ast_strlen_zero(sip_cfg.regcontext))
04923 return;
04924
04925 ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
04926 stringp = multi;
04927 while ((ext = strsep(&stringp, "&"))) {
04928 if ((context = strchr(ext, '@'))) {
04929 *context++ = '\0';
04930 if (!ast_context_find(context)) {
04931 ast_log(LOG_WARNING, "Context %s must exist in regcontext= in sip.conf!\n", context);
04932 continue;
04933 }
04934 } else {
04935 context = sip_cfg.regcontext;
04936 }
04937 if (onoff) {
04938 if (!ast_exists_extension(NULL, context, ext, 1, NULL)) {
04939 ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
04940 ast_strdup(peer->name), ast_free_ptr, "SIP");
04941 }
04942 } else if (pbx_find_extension(NULL, NULL, &q, context, ext, 1, NULL, "", E_MATCH)) {
04943 ast_context_remove_extension(context, ext, 1, NULL);
04944 }
04945 }
04946 }
04947
04948
04949 static void destroy_mailbox(struct sip_mailbox *mailbox)
04950 {
04951 if (mailbox->event_sub)
04952 ast_event_unsubscribe(mailbox->event_sub);
04953 ast_free(mailbox);
04954 }
04955
04956
04957 static void clear_peer_mailboxes(struct sip_peer *peer)
04958 {
04959 struct sip_mailbox *mailbox;
04960
04961 while ((mailbox = AST_LIST_REMOVE_HEAD(&peer->mailboxes, entry)))
04962 destroy_mailbox(mailbox);
04963 }
04964
04965 static void sip_destroy_peer_fn(void *peer)
04966 {
04967 sip_destroy_peer(peer);
04968 }
04969
04970
04971 static void sip_destroy_peer(struct sip_peer *peer)
04972 {
04973 ast_debug(3, "Destroying SIP peer %s\n", peer->name);
04974
04975
04976
04977
04978
04979
04980 clear_peer_mailboxes(peer);
04981
04982 if (peer->outboundproxy) {
04983 ao2_ref(peer->outboundproxy, -1);
04984 peer->outboundproxy = NULL;
04985 }
04986
04987
04988 if (peer->call) {
04989 dialog_unlink_all(peer->call);
04990 peer->call = dialog_unref(peer->call, "peer->call is being unset");
04991 }
04992
04993 if (peer->mwipvt) {
04994 dialog_unlink_all(peer->mwipvt);
04995 peer->mwipvt = dialog_unref(peer->mwipvt, "unreffing peer->mwipvt");
04996 }
04997
04998 if (peer->chanvars) {
04999 ast_variables_destroy(peer->chanvars);
05000 peer->chanvars = NULL;
05001 }
05002
05003 register_peer_exten(peer, FALSE);
05004 ast_free_ha(peer->ha);
05005 ast_free_ha(peer->directmediaha);
05006 if (peer->selfdestruct)
05007 ast_atomic_fetchadd_int(&apeerobjs, -1);
05008 else if (!ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && peer->is_realtime) {
05009 ast_atomic_fetchadd_int(&rpeerobjs, -1);
05010 ast_debug(3, "-REALTIME- peer Destroyed. Name: %s. Realtime Peer objects: %d\n", peer->name, rpeerobjs);
05011 } else
05012 ast_atomic_fetchadd_int(&speerobjs, -1);
05013 if (peer->auth) {
05014 ao2_t_ref(peer->auth, -1, "Removing peer authentication");
05015 peer->auth = NULL;
05016 }
05017
05018 if (peer->socket.tcptls_session) {
05019 ao2_ref(peer->socket.tcptls_session, -1);
05020 peer->socket.tcptls_session = NULL;
05021 }
05022
05023 ast_cc_config_params_destroy(peer->cc_params);
05024
05025 ast_string_field_free_memory(peer);
05026 }
05027
05028
05029 static void update_peer(struct sip_peer *p, int expire)
05030 {
05031 int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
05032 if (sip_cfg.peer_rtupdate &&
05033 (p->is_realtime || rtcachefriends)) {
05034 realtime_update_peer(p->name, &p->addr, p->username, p->fullcontact, p->useragent, expire, p->deprecated_username, p->lastms);
05035 }
05036 }
05037
05038 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *cfg)
05039 {
05040 struct ast_variable *var = NULL;
05041 struct ast_flags flags = {0};
05042 char *cat = NULL;
05043 const char *insecure;
05044 while ((cat = ast_category_browse(cfg, cat))) {
05045 insecure = ast_variable_retrieve(cfg, cat, "insecure");
05046 set_insecure_flags(&flags, insecure, -1);
05047 if (ast_test_flag(&flags, SIP_INSECURE_PORT)) {
05048 var = ast_category_root(cfg, cat);
05049 break;
05050 }
05051 }
05052 return var;
05053 }
05054
05055 static struct ast_variable *get_insecure_variable_from_sippeers(const char *column, const char *value)
05056 {
05057 struct ast_config *peerlist;
05058 struct ast_variable *var = NULL;
05059 if ((peerlist = ast_load_realtime_multientry("sippeers", column, value, "insecure LIKE", "%port%", SENTINEL))) {
05060 if ((var = get_insecure_variable_from_config(peerlist))) {
05061
05062
05063 var = ast_variables_dup(var);
05064 }
05065 ast_config_destroy(peerlist);
05066 }
05067 return var;
05068 }
05069
05070
05071
05072
05073
05074
05075 static struct ast_variable *get_insecure_variable_from_sipregs(const char *column, const char *value, struct ast_variable **var)
05076 {
05077 struct ast_variable *varregs = NULL;
05078 struct ast_config *regs, *peers;
05079 char *regscat;
05080 const char *regname;
05081
05082 if (!(regs = ast_load_realtime_multientry("sipregs", column, value, SENTINEL))) {
05083 return NULL;
05084 }
05085
05086
05087 if (!(peers = ast_load_realtime_multientry("sippeers", "insecure LIKE", "%port%", SENTINEL))) {
05088 ast_config_destroy(regs);
05089 return NULL;
05090 }
05091
05092
05093
05094 regscat = NULL;
05095 while ((regscat = ast_category_browse(regs, regscat)) && (regname = ast_variable_retrieve(regs, regscat, "name"))) {
05096 char *peerscat;
05097 const char *peername;
05098
05099 peerscat = NULL;
05100 while ((peerscat = ast_category_browse(peers, peerscat)) && (peername = ast_variable_retrieve(peers, peerscat, "name"))) {
05101 if (!strcasecmp(regname, peername)) {
05102
05103
05104 const char *insecure = ast_variable_retrieve(peers, peerscat, "insecure");
05105 struct ast_flags flags = {0};
05106 set_insecure_flags(&flags, insecure, -1);
05107 if (ast_test_flag(&flags, SIP_INSECURE_PORT)) {
05108
05109 if ((varregs = ast_variables_dup(ast_category_root(regs, regscat)))) {
05110 if (!(*var = ast_variables_dup(ast_category_root(peers, peerscat)))) {
05111 ast_variables_destroy(varregs);
05112 varregs = NULL;
05113 }
05114 }
05115 goto done;
05116 }
05117 }
05118 }
05119 }
05120
05121 done:
05122 ast_config_destroy(regs);
05123 ast_config_destroy(peers);
05124 return varregs;
05125 }
05126
05127 static const char *get_name_from_variable(const struct ast_variable *var)
05128 {
05129
05130
05131
05132
05133
05134
05135
05136
05137 const struct ast_variable *tmp;
05138 for (tmp = var; tmp; tmp = tmp->next) {
05139 if (!strcasecmp(tmp->name, "name")) {
05140 if (!ast_strlen_zero(tmp->value)) {
05141 return tmp->value;
05142 }
05143 break;
05144 }
05145 }
05146 return NULL;
05147 }
05148
05149
05150
05151 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)
05152 {
05153
05154 if ((*var = ast_load_realtime("sippeers", "name", *name, "host", "dynamic", SENTINEL))) {
05155 ;
05156
05157 } else if (addr && !(*var = ast_load_realtime("sippeers", "name", *name, "host", ipaddr, SENTINEL))) {
05158 ;
05159
05160 } else if ((*var = ast_load_realtime("sippeers", "name", *name, SENTINEL))) {
05161
05162
05163
05164
05165
05166
05167 if (addr) {
05168 struct ast_variable *tmp;
05169 for (tmp = *var; tmp; tmp = tmp->next) {
05170 if (!strcasecmp(tmp->name, "host")) {
05171 struct ast_sockaddr *addrs = NULL;
05172
05173 if (ast_sockaddr_resolve(&addrs,
05174 tmp->value,
05175 PARSE_PORT_FORBID,
05176 get_address_family_filter(SIP_TRANSPORT_UDP)) <= 0 ||
05177 ast_sockaddr_cmp(&addrs[0], addr)) {
05178
05179 ast_variables_destroy(*var);
05180 *var = NULL;
05181 }
05182 ast_free(addrs);
05183 break;
05184 }
05185 }
05186 }
05187 }
05188
05189
05190 if (*var) {
05191 if (varregs) {
05192 *varregs = ast_load_realtime("sipregs", "name", *name, SENTINEL);
05193 }
05194 return 1;
05195 }
05196 return 0;
05197 }
05198
05199
05200
05201
05202
05203
05204
05205 static struct ast_variable *realtime_peer_get_sippeer_helper(const char **name, struct ast_variable **varregs) {
05206 struct ast_variable *var = NULL;
05207 const char *old_name = *name;
05208 *name = get_name_from_variable(*varregs);
05209 if (!*name || !(var = ast_load_realtime("sippeers", "name", *name, SENTINEL))) {
05210 if (!*name) {
05211 ast_log(LOG_WARNING, "Found sipreg but it has no name\n");
05212 }
05213 ast_variables_destroy(*varregs);
05214 *varregs = NULL;
05215 *name = old_name;
05216 }
05217 return var;
05218 }
05219
05220
05221
05222
05223 static int realtime_peer_by_addr(const char **name, struct ast_sockaddr *addr, const char *ipaddr, struct ast_variable **var, struct ast_variable **varregs)
05224 {
05225 char portstring[6];
05226 ast_copy_string(portstring, ast_sockaddr_stringify_port(addr), sizeof(portstring));
05227
05228
05229 *name = NULL;
05230
05231
05232 if ((*var = ast_load_realtime("sippeers", "host", ipaddr, "port", portstring, SENTINEL))) {
05233 ;
05234
05235 } else if (varregs && (*varregs = ast_load_realtime("sipregs", "ipaddr", ipaddr, "port", portstring, SENTINEL)) &&
05236 (*var = realtime_peer_get_sippeer_helper(name, varregs))) {
05237 ;
05238
05239 } else if (!varregs && (*var = ast_load_realtime("sippeers", "ipaddr", ipaddr, "port", portstring, SENTINEL))) {
05240 ;
05241
05242 } else if ((*var = get_insecure_variable_from_sippeers("host", ipaddr))) {
05243 ;
05244
05245
05246
05247
05248 } else if (varregs && (*varregs = get_insecure_variable_from_sipregs("ipaddr", ipaddr, var))) {
05249 ;
05250
05251 } else if (!varregs && (*var = get_insecure_variable_from_sippeers("ipaddr", ipaddr))) {
05252 ;
05253 }
05254
05255
05256 if (!*var) {
05257 return 0;
05258 }
05259
05260
05261
05262
05263 if (!*name && !(*name = get_name_from_variable(*var))) {
05264 ast_log(LOG_WARNING, "Found peer for IP %s but it has no name\n", ipaddr);
05265 ast_variables_destroy(*var);
05266 *var = NULL;
05267 if (varregs && *varregs) {
05268 ast_variables_destroy(*varregs);
05269 *varregs = NULL;
05270 }
05271 return 0;
05272 }
05273
05274
05275
05276
05277 if (varregs && !*varregs) {
05278 *varregs = ast_load_realtime("sipregs", "name", *name, SENTINEL);
05279 }
05280 return 1;
05281 }
05282
05283
05284
05285
05286
05287
05288
05289
05290
05291
05292 static struct sip_peer *realtime_peer(const char *newpeername, struct ast_sockaddr *addr, int devstate_only, int which_objects)
05293 {
05294 struct sip_peer *peer = NULL;
05295 struct ast_variable *var = NULL;
05296 struct ast_variable *varregs = NULL;
05297 char ipaddr[INET6_ADDRSTRLEN];
05298 int realtimeregs = ast_check_realtime("sipregs");
05299
05300 if (addr) {
05301 ast_copy_string(ipaddr, ast_sockaddr_stringify_addr(addr), sizeof(ipaddr));
05302 } else {
05303 ipaddr[0] = '\0';
05304 }
05305
05306 if (newpeername && realtime_peer_by_name(&newpeername, addr, ipaddr, &var, realtimeregs ? &varregs : NULL)) {
05307 ;
05308 } else if (addr && realtime_peer_by_addr(&newpeername, addr, ipaddr, &var, realtimeregs ? &varregs : NULL)) {
05309 ;
05310 } else {
05311 return NULL;
05312 }
05313
05314
05315
05316 if (which_objects == FINDUSERS) {
05317 struct ast_variable *tmp;
05318 for (tmp = var; tmp; tmp = tmp->next) {
05319 if (!strcasecmp(tmp->name, "type") && (!strcasecmp(tmp->value, "peer"))) {
05320 goto cleanup;
05321 }
05322 }
05323 }
05324
05325
05326 peer = build_peer(newpeername, var, varregs, TRUE, devstate_only);
05327 if (!peer) {
05328 goto cleanup;
05329 }
05330
05331
05332
05333 if (peer->type == 0) {
05334 if (which_objects == FINDUSERS) {
05335 peer->type = SIP_TYPE_USER;
05336 } else if (which_objects == FINDPEERS) {
05337 peer->type = SIP_TYPE_PEER;
05338 } else {
05339 peer->type = SIP_TYPE_PEER | SIP_TYPE_USER;
05340 }
05341 }
05342
05343 ast_debug(3, "-REALTIME- loading peer from database to memory. Name: %s. Peer objects: %d\n", peer->name, rpeerobjs);
05344
05345 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && !devstate_only) {
05346
05347 ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
05348 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
05349 AST_SCHED_REPLACE_UNREF(peer->expire, sched, sip_cfg.rtautoclear * 1000, expire_register, peer,
05350 unref_peer(_data, "remove registration ref"),
05351 unref_peer(peer, "remove registration ref"),
05352 ref_peer(peer, "add registration ref"));
05353 }
05354 ao2_t_link(peers, peer, "link peer into peers table");
05355 if (!ast_sockaddr_isnull(&peer->addr)) {
05356 ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
05357 }
05358 }
05359 peer->is_realtime = 1;
05360
05361 cleanup:
05362 ast_variables_destroy(var);
05363 ast_variables_destroy(varregs);
05364 return peer;
05365 }
05366
05367
05368 static int find_by_name(void *obj, void *arg, void *data, int flags)
05369 {
05370 struct sip_peer *search = obj, *match = arg;
05371 int *which_objects = data;
05372
05373
05374 if (strcmp(search->name, match->name)) {
05375 return 0;
05376 }
05377
05378 switch (*which_objects) {
05379 case FINDUSERS:
05380 if (!(search->type & SIP_TYPE_USER)) {
05381 return 0;
05382 }
05383 break;
05384 case FINDPEERS:
05385 if (!(search->type & SIP_TYPE_PEER)) {
05386 return 0;
05387 }
05388 break;
05389 case FINDALLDEVICES:
05390 break;
05391 }
05392
05393 return CMP_MATCH | CMP_STOP;
05394 }
05395
05396
05397
05398
05399
05400
05401
05402
05403
05404
05405
05406
05407
05408
05409 static struct sip_peer *find_peer(const char *peer, struct ast_sockaddr *addr, int realtime, int which_objects, int devstate_only, int transport)
05410 {
05411 struct sip_peer *p = NULL;
05412 struct sip_peer tmp_peer;
05413
05414 if (peer) {
05415 ast_copy_string(tmp_peer.name, peer, sizeof(tmp_peer.name));
05416 p = ao2_t_callback_data(peers, OBJ_POINTER, find_by_name, &tmp_peer, &which_objects, "ao2_find in peers table");
05417 } else if (addr) {
05418 ast_sockaddr_copy(&tmp_peer.addr, addr);
05419 tmp_peer.flags[0].flags = 0;
05420 tmp_peer.transports = transport;
05421 p = ao2_t_find(peers_by_ip, &tmp_peer, OBJ_POINTER, "ao2_find in peers_by_ip table");
05422 if (!p) {
05423 ast_set_flag(&tmp_peer.flags[0], SIP_INSECURE_PORT);
05424 p = ao2_t_find(peers_by_ip, &tmp_peer, OBJ_POINTER, "ao2_find in peers_by_ip table 2");
05425 if (p) {
05426 return p;
05427 }
05428 }
05429 }
05430
05431 if (!p && (realtime || devstate_only)) {
05432 p = realtime_peer(peer, addr, devstate_only, which_objects);
05433 if (p) {
05434 switch (which_objects) {
05435 case FINDUSERS:
05436 if (!(p->type & SIP_TYPE_USER)) {
05437 unref_peer(p, "Wrong type of realtime SIP endpoint");
05438 return NULL;
05439 }
05440 break;
05441 case FINDPEERS:
05442 if (!(p->type & SIP_TYPE_PEER)) {
05443 unref_peer(p, "Wrong type of realtime SIP endpoint");
05444 return NULL;
05445 }
05446 break;
05447 case FINDALLDEVICES:
05448 break;
05449 }
05450 }
05451 }
05452
05453 return p;
05454 }
05455
05456
05457 static void do_setnat(struct sip_pvt *p)
05458 {
05459 const char *mode;
05460 int natflags;
05461
05462 natflags = ast_test_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP);
05463 mode = natflags ? "On" : "Off";
05464
05465 if (p->rtp) {
05466 ast_debug(1, "Setting NAT on RTP to %s\n", mode);
05467 ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_NAT, natflags);
05468 }
05469 if (p->vrtp) {
05470 ast_debug(1, "Setting NAT on VRTP to %s\n", mode);
05471 ast_rtp_instance_set_prop(p->vrtp, AST_RTP_PROPERTY_NAT, natflags);
05472 }
05473 if (p->udptl) {
05474 ast_debug(1, "Setting NAT on UDPTL to %s\n", mode);
05475 ast_udptl_setnat(p->udptl, natflags);
05476 }
05477 if (p->trtp) {
05478 ast_debug(1, "Setting NAT on TRTP to %s\n", mode);
05479 ast_rtp_instance_set_prop(p->trtp, AST_RTP_PROPERTY_NAT, natflags);
05480 }
05481 }
05482
05483
05484 static void change_t38_state(struct sip_pvt *p, int state)
05485 {
05486 int old = p->t38.state;
05487 struct ast_channel *chan = p->owner;
05488 struct ast_control_t38_parameters parameters = { .request_response = 0 };
05489
05490
05491 if (old == state)
05492 return;
05493
05494 p->t38.state = state;
05495 ast_debug(2, "T38 state changed to %d on channel %s\n", p->t38.state, chan ? chan->name : "<none>");
05496
05497
05498 if (!chan)
05499 return;
05500
05501
05502 switch (state) {
05503 case T38_PEER_REINVITE:
05504 parameters = p->t38.their_parms;
05505 parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
05506 parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
05507 ast_udptl_set_tag(p->udptl, "%s", chan->name);
05508 break;
05509 case T38_ENABLED:
05510 parameters = p->t38.their_parms;
05511 parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
05512 parameters.request_response = AST_T38_NEGOTIATED;
05513 ast_udptl_set_tag(p->udptl, "%s", chan->name);
05514 break;
05515 case T38_DISABLED:
05516 if (old == T38_ENABLED) {
05517 parameters.request_response = AST_T38_TERMINATED;
05518 } else if (old == T38_LOCAL_REINVITE) {
05519 parameters.request_response = AST_T38_REFUSED;
05520 }
05521 break;
05522 case T38_LOCAL_REINVITE:
05523
05524 break;
05525 }
05526
05527
05528 if (parameters.request_response)
05529 ast_queue_control_data(chan, AST_CONTROL_T38_PARAMETERS, ¶meters, sizeof(parameters));
05530 }
05531
05532
05533 static void set_t38_capabilities(struct sip_pvt *p)
05534 {
05535 if (p->udptl) {
05536 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY) {
05537 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
05538 } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_FEC) {
05539 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
05540 } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL) {
05541 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
05542 }
05543 }
05544 }
05545
05546 static void copy_socket_data(struct sip_socket *to_sock, const struct sip_socket *from_sock)
05547 {
05548 if (to_sock->tcptls_session) {
05549 ao2_ref(to_sock->tcptls_session, -1);
05550 to_sock->tcptls_session = NULL;
05551 }
05552
05553 if (from_sock->tcptls_session) {
05554 ao2_ref(from_sock->tcptls_session, +1);
05555 }
05556
05557 *to_sock = *from_sock;
05558 }
05559
05560
05561
05562
05563 static int dialog_initialize_rtp(struct sip_pvt *dialog)
05564 {
05565 struct ast_sockaddr bindaddr_tmp;
05566
05567 if (!sip_methods[dialog->method].need_rtp) {
05568 return 0;
05569 }
05570
05571 ast_sockaddr_copy(&bindaddr_tmp, &bindaddr);
05572 if (!(dialog->rtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr_tmp, NULL))) {
05573 return -1;
05574 }
05575
05576 if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS) ||
05577 (ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT) && (dialog->capability & AST_FORMAT_VIDEO_MASK))) {
05578 if (!(dialog->vrtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr_tmp, NULL))) {
05579 return -1;
05580 }
05581 ast_rtp_instance_set_timeout(dialog->vrtp, dialog->rtptimeout);
05582 ast_rtp_instance_set_hold_timeout(dialog->vrtp, dialog->rtpholdtimeout);
05583 ast_rtp_instance_set_keepalive(dialog->vrtp, dialog->rtpkeepalive);
05584
05585 ast_rtp_instance_set_prop(dialog->vrtp, AST_RTP_PROPERTY_RTCP, 1);
05586 ast_rtp_instance_set_qos(dialog->vrtp, global_tos_video, global_cos_video, "SIP VIDEO");
05587 }
05588
05589 if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_TEXTSUPPORT)) {
05590 if (!(dialog->trtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr_tmp, NULL))) {
05591 return -1;
05592 }
05593
05594 ast_rtp_instance_set_keepalive(dialog->trtp, dialog->rtpkeepalive);
05595
05596 ast_rtp_instance_set_prop(dialog->trtp, AST_RTP_PROPERTY_RTCP, 1);
05597 }
05598
05599 ast_rtp_instance_set_timeout(dialog->rtp, dialog->rtptimeout);
05600 ast_rtp_instance_set_hold_timeout(dialog->rtp, dialog->rtpholdtimeout);
05601 ast_rtp_instance_set_keepalive(dialog->rtp, dialog->rtpkeepalive);
05602
05603 ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_RTCP, 1);
05604 ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
05605 ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
05606
05607 ast_rtp_instance_set_qos(dialog->rtp, global_tos_audio, global_cos_audio, "SIP RTP");
05608
05609 do_setnat(dialog);
05610
05611 return 0;
05612 }
05613
05614
05615
05616
05617
05618
05619
05620
05621 static int create_addr_from_peer(struct sip_pvt *dialog, struct sip_peer *peer)
05622 {
05623 struct sip_auth_container *credentials;
05624
05625
05626
05627
05628 if (dialog->socket.type && check_request_transport(peer, dialog))
05629 return -1;
05630 copy_socket_data(&dialog->socket, &peer->socket);
05631
05632 if (!(ast_sockaddr_isnull(&peer->addr) && ast_sockaddr_isnull(&peer->defaddr)) &&
05633 (!peer->maxms || ((peer->lastms >= 0) && (peer->lastms <= peer->maxms)))) {
05634 dialog->sa = ast_sockaddr_isnull(&peer->addr) ? peer->defaddr : peer->addr;
05635 dialog->recv = dialog->sa;
05636 } else
05637 return -1;
05638
05639
05640 ast_copy_flags(&dialog->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
05641 ast_copy_flags(&dialog->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
05642 ast_copy_flags(&dialog->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
05643 dialog->capability = peer->capability;
05644 dialog->prefs = peer->prefs;
05645 dialog->amaflags = peer->amaflags;
05646
05647 ast_string_field_set(dialog, engine, peer->engine);
05648
05649 dialog->rtptimeout = peer->rtptimeout;
05650 dialog->rtpholdtimeout = peer->rtpholdtimeout;
05651 dialog->rtpkeepalive = peer->rtpkeepalive;
05652 if (dialog_initialize_rtp(dialog)) {
05653 return -1;
05654 }
05655
05656 if (dialog->rtp) {
05657 ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
05658 ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
05659
05660 ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(dialog->rtp), dialog->rtp, &dialog->prefs);
05661 dialog->autoframing = peer->autoframing;
05662 }
05663
05664
05665 ast_string_field_set(dialog, peername, peer->name);
05666 ast_string_field_set(dialog, authname, peer->username);
05667 ast_string_field_set(dialog, username, peer->username);
05668 ast_string_field_set(dialog, peersecret, peer->secret);
05669 ast_string_field_set(dialog, peermd5secret, peer->md5secret);
05670 ast_string_field_set(dialog, mohsuggest, peer->mohsuggest);
05671 ast_string_field_set(dialog, mohinterpret, peer->mohinterpret);
05672 ast_string_field_set(dialog, tohost, peer->tohost);
05673 ast_string_field_set(dialog, fullcontact, peer->fullcontact);
05674 ast_string_field_set(dialog, accountcode, peer->accountcode);
05675 ast_string_field_set(dialog, context, peer->context);
05676 ast_string_field_set(dialog, cid_num, peer->cid_num);
05677 ast_string_field_set(dialog, cid_name, peer->cid_name);
05678 ast_string_field_set(dialog, cid_tag, peer->cid_tag);
05679 ast_string_field_set(dialog, mwi_from, peer->mwi_from);
05680 if (!ast_strlen_zero(peer->parkinglot)) {
05681 ast_string_field_set(dialog, parkinglot, peer->parkinglot);
05682 }
05683 ast_string_field_set(dialog, engine, peer->engine);
05684 ref_proxy(dialog, obproxy_get(dialog, peer));
05685 dialog->callgroup = peer->callgroup;
05686 dialog->pickupgroup = peer->pickupgroup;
05687 dialog->allowtransfer = peer->allowtransfer;
05688 dialog->jointnoncodeccapability = dialog->noncodeccapability;
05689
05690
05691 ao2_lock(peer);
05692 credentials = peer->auth;
05693 if (credentials) {
05694 ao2_t_ref(credentials, +1, "Ref peer auth for dialog");
05695 }
05696 ao2_unlock(peer);
05697 ao2_lock(dialog);
05698 if (dialog->peerauth) {
05699 ao2_t_ref(dialog->peerauth, -1, "Unref old dialog peer auth");
05700 }
05701 dialog->peerauth = credentials;
05702 ao2_unlock(dialog);
05703
05704 dialog->maxcallbitrate = peer->maxcallbitrate;
05705 dialog->disallowed_methods = peer->disallowed_methods;
05706 ast_cc_copy_config_params(dialog->cc_params, peer->cc_params);
05707 if (ast_strlen_zero(dialog->tohost))
05708 ast_string_field_set(dialog, tohost, ast_sockaddr_stringify_host_remote(&dialog->sa));
05709 if (!ast_strlen_zero(peer->fromdomain)) {
05710 ast_string_field_set(dialog, fromdomain, peer->fromdomain);
05711 if (!dialog->initreq.headers) {
05712 char *new_callid;
05713 char *tmpcall = ast_strdupa(dialog->callid);
05714
05715 new_callid = strchr(tmpcall, '@');
05716 if (new_callid) {
05717 int callid_size;
05718
05719 *new_callid = '\0';
05720
05721
05722 callid_size = strlen(tmpcall) + strlen(peer->fromdomain) + 2;
05723 new_callid = ast_alloca(callid_size);
05724 snprintf(new_callid, callid_size, "%s@%s", tmpcall, peer->fromdomain);
05725 change_callid_pvt(dialog, new_callid);
05726 }
05727 }
05728 }
05729 if (!ast_strlen_zero(peer->fromuser))
05730 ast_string_field_set(dialog, fromuser, peer->fromuser);
05731 if (!ast_strlen_zero(peer->language))
05732 ast_string_field_set(dialog, language, peer->language);
05733
05734
05735
05736
05737 if (peer->maxms && peer->lastms)
05738 dialog->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
05739 else
05740 dialog->timer_t1 = peer->timer_t1;
05741
05742
05743
05744 if (peer->timer_b)
05745 dialog->timer_b = peer->timer_b;
05746 else
05747 dialog->timer_b = 64 * dialog->timer_t1;
05748
05749 if ((ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
05750 (ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
05751 dialog->noncodeccapability |= AST_RTP_DTMF;
05752 else
05753 dialog->noncodeccapability &= ~AST_RTP_DTMF;
05754 dialog->directmediaha = ast_duplicate_ha_list(peer->directmediaha);
05755 if (peer->call_limit)
05756 ast_set_flag(&dialog->flags[0], SIP_CALL_LIMIT);
05757 if (!dialog->portinuri)
05758 dialog->portinuri = peer->portinuri;
05759 dialog->chanvars = copy_vars(peer->chanvars);
05760 if (peer->fromdomainport)
05761 dialog->fromdomainport = peer->fromdomainport;
05762
05763 return 0;
05764 }
05765
05766
05767 static inline int default_sip_port(enum sip_transport type)
05768 {
05769 return type == SIP_TRANSPORT_TLS ? STANDARD_TLS_PORT : STANDARD_SIP_PORT;
05770 }
05771
05772
05773
05774
05775 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct ast_sockaddr *addr, int newdialog)
05776 {
05777 struct sip_peer *peer;
05778 char *peername, *peername2, *hostn;
05779 char host[MAXHOSTNAMELEN];
05780 char service[MAXHOSTNAMELEN];
05781 int srv_ret = 0;
05782 int tportno;
05783
05784 AST_DECLARE_APP_ARGS(hostport,
05785 AST_APP_ARG(host);
05786 AST_APP_ARG(port);
05787 );
05788
05789 peername = ast_strdupa(opeer);
05790 peername2 = ast_strdupa(opeer);
05791 AST_NONSTANDARD_RAW_ARGS(hostport, peername2, ':');
05792
05793 if (hostport.port)
05794 dialog->portinuri = 1;
05795
05796 dialog->timer_t1 = global_t1;
05797 dialog->timer_b = global_timer_b;
05798 peer = find_peer(peername, NULL, TRUE, FINDPEERS, FALSE, 0);
05799
05800 if (peer) {
05801 int res;
05802 if (newdialog) {
05803 set_socket_transport(&dialog->socket, 0);
05804 }
05805 res = create_addr_from_peer(dialog, peer);
05806 dialog->relatedpeer = ref_peer(peer, "create_addr: setting dialog's relatedpeer pointer");
05807 unref_peer(peer, "create_addr: unref peer from find_peer hashtab lookup");
05808 return res;
05809 } else if (ast_check_digits(peername)) {
05810
05811
05812
05813 ast_log(LOG_WARNING, "Purely numeric hostname (%s), and not a peer--rejecting!\n", peername);
05814 return -1;
05815 } else {
05816 dialog->rtptimeout = global_rtptimeout;
05817 dialog->rtpholdtimeout = global_rtpholdtimeout;
05818 dialog->rtpkeepalive = global_rtpkeepalive;
05819 if (dialog_initialize_rtp(dialog)) {
05820 return -1;
05821 }
05822 }
05823
05824 ast_string_field_set(dialog, tohost, hostport.host);
05825 dialog->allowed_methods &= ~sip_cfg.disallowed_methods;
05826
05827
05828 ref_proxy(dialog, obproxy_get(dialog, NULL));
05829
05830 if (addr) {
05831
05832 ast_sockaddr_copy(&dialog->sa, addr);
05833 } else {
05834
05835
05836
05837
05838
05839
05840 hostn = peername;
05841
05842
05843
05844 if (!hostport.port && sip_cfg.srvlookup) {
05845 snprintf(service, sizeof(service), "_%s._%s.%s",
05846 get_srv_service(dialog->socket.type),
05847 get_srv_protocol(dialog->socket.type), peername);
05848 if ((srv_ret = ast_get_srv(NULL, host, sizeof(host), &tportno,
05849 service)) > 0) {
05850 hostn = host;
05851 }
05852 }
05853
05854 if (ast_sockaddr_resolve_first_transport(&dialog->sa, hostn, 0, dialog->socket.type ? dialog->socket.type : SIP_TRANSPORT_UDP)) {
05855 ast_log(LOG_WARNING, "No such host: %s\n", peername);
05856 return -1;
05857 }
05858
05859 if (srv_ret > 0) {
05860 ast_sockaddr_set_port(&dialog->sa, tportno);
05861 }
05862 }
05863
05864 if (!dialog->socket.type)
05865 set_socket_transport(&dialog->socket, SIP_TRANSPORT_UDP);
05866 if (!dialog->socket.port) {
05867 dialog->socket.port = htons(ast_sockaddr_port(&bindaddr));
05868 }
05869
05870 if (!ast_sockaddr_port(&dialog->sa)) {
05871 ast_sockaddr_set_port(&dialog->sa, default_sip_port(dialog->socket.type));
05872 }
05873 ast_sockaddr_copy(&dialog->recv, &dialog->sa);
05874 return 0;
05875 }
05876
05877
05878
05879
05880 static int auto_congest(const void *arg)
05881 {
05882 struct sip_pvt *p = (struct sip_pvt *)arg;
05883
05884 sip_pvt_lock(p);
05885 p->initid = -1;
05886 if (p->owner) {
05887
05888 if (!ast_channel_trylock(p->owner)) {
05889 append_history(p, "Cong", "Auto-congesting (timer)");
05890 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
05891 ast_channel_unlock(p->owner);
05892 }
05893
05894
05895 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
05896 }
05897 sip_pvt_unlock(p);
05898 dialog_unref(p, "unreffing arg passed into auto_congest callback (p->initid)");
05899 return 0;
05900 }
05901
05902
05903
05904
05905 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
05906 {
05907 int res;
05908 struct sip_pvt *p = ast->tech_pvt;
05909 struct varshead *headp;
05910 struct ast_var_t *current;
05911 const char *referer = NULL;
05912 int cc_core_id;
05913 char uri[SIPBUFSIZE] = "";
05914
05915 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
05916 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
05917 return -1;
05918 }
05919
05920 if (ast_cc_is_recall(ast, &cc_core_id, "SIP")) {
05921 char device_name[AST_CHANNEL_NAME];
05922 struct ast_cc_monitor *recall_monitor;
05923 struct sip_monitor_instance *monitor_instance;
05924 ast_channel_get_device_name(ast, device_name, sizeof(device_name));
05925 if ((recall_monitor = ast_cc_get_monitor_by_recall_core_id(cc_core_id, device_name))) {
05926 monitor_instance = recall_monitor->private_data;
05927 ast_copy_string(uri, monitor_instance->notify_uri, sizeof(uri));
05928 ao2_t_ref(recall_monitor, -1, "Got the URI we need so unreffing monitor");
05929 }
05930 }
05931
05932
05933 headp=&ast->varshead;
05934 AST_LIST_TRAVERSE(headp, current, entries) {
05935
05936 if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
05937 p->options->vxml_url = ast_var_value(current);
05938 } else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
05939 p->options->uri_options = ast_var_value(current);
05940 } else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
05941
05942 p->options->addsipheaders = 1;
05943 } else if (!strcasecmp(ast_var_name(current), "SIPFROMDOMAIN")) {
05944 ast_string_field_set(p, fromdomain, ast_var_value(current));
05945 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER")) {
05946
05947 p->options->transfer = 1;
05948 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REFERER")) {
05949
05950 referer = ast_var_value(current);
05951 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REPLACES")) {
05952
05953 p->options->replaces = ast_var_value(current);
05954 } else if (!strcasecmp(ast_var_name(current), "SIP_MAX_FORWARDS")) {
05955 if (sscanf(ast_var_value(current), "%d", &(p->maxforwards)) != 1) {
05956 ast_log(LOG_WARNING, "The SIP_MAX_FORWARDS channel variable is not a valid integer.\n");
05957 }
05958 }
05959 }
05960
05961
05962 if (p->req_secure_signaling && p->socket.type != SIP_TRANSPORT_TLS) {
05963 ast_log(LOG_WARNING, "Encrypted signaling is required\n");
05964 ast->hangupcause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
05965 return -1;
05966 }
05967
05968 if (ast_test_flag(&p->flags[1], SIP_PAGE2_USE_SRTP)) {
05969 if (ast_test_flag(&p->flags[0], SIP_REINVITE)) {
05970 ast_debug(1, "Direct media not possible when using SRTP, ignoring canreinvite setting\n");
05971 ast_clear_flag(&p->flags[0], SIP_REINVITE);
05972 }
05973
05974 if (p->rtp && !p->srtp && setup_srtp(&p->srtp) < 0) {
05975 ast_log(LOG_WARNING, "SRTP audio setup failed\n");
05976 return -1;
05977 }
05978
05979 if (p->vrtp && !p->vsrtp && setup_srtp(&p->vsrtp) < 0) {
05980 ast_log(LOG_WARNING, "SRTP video setup failed\n");
05981 return -1;
05982 }
05983
05984 if (p->trtp && !p->tsrtp && setup_srtp(&p->tsrtp) < 0) {
05985 ast_log(LOG_WARNING, "SRTP text setup failed\n");
05986 return -1;
05987 }
05988 }
05989
05990 res = 0;
05991 ast_set_flag(&p->flags[0], SIP_OUTGOING);
05992
05993
05994
05995
05996 ast_clear_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_T38);
05997
05998 if (p->options->transfer) {
05999 char buf[SIPBUFSIZE/2];
06000
06001 if (referer) {
06002 if (sipdebug)
06003 ast_debug(3, "Call for %s transfered by %s\n", p->username, referer);
06004 snprintf(buf, sizeof(buf)-1, "-> %s (via %s)", p->cid_name, referer);
06005 } else
06006 snprintf(buf, sizeof(buf)-1, "-> %s", p->cid_name);
06007 ast_string_field_set(p, cid_name, buf);
06008 }
06009 ast_debug(1, "Outgoing Call for %s\n", p->username);
06010
06011 res = update_call_counter(p, INC_CALL_RINGING);
06012
06013 if (res == -1) {
06014 ast->hangupcause = AST_CAUSE_USER_BUSY;
06015 return res;
06016 }
06017 p->callingpres = ast_party_id_presentation(&ast->caller.id);
06018 p->jointcapability = ast_rtp_instance_available_formats(p->rtp, p->capability, p->prefcodec);
06019 p->jointnoncodeccapability = p->noncodeccapability;
06020
06021
06022 if (!(p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
06023 ast_log(LOG_WARNING, "No audio format found to offer. Cancelling call to %s\n", p->username);
06024 res = -1;
06025 } else {
06026 int xmitres;
06027 struct ast_party_connected_line connected;
06028 struct ast_set_party_connected_line update_connected;
06029
06030 sip_pvt_lock(p);
06031
06032
06033 memset(&update_connected, 0, sizeof(update_connected));
06034 ast_party_connected_line_init(&connected);
06035 if (!ast_strlen_zero(p->cid_num)
06036 || (p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
06037 update_connected.id.number = 1;
06038 connected.id.number.valid = 1;
06039 connected.id.number.str = (char *) p->cid_num;
06040 connected.id.number.presentation = p->callingpres;
06041 }
06042 if (!ast_strlen_zero(p->cid_name)
06043 || (p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
06044 update_connected.id.name = 1;
06045 connected.id.name.valid = 1;
06046 connected.id.name.str = (char *) p->cid_name;
06047 connected.id.name.presentation = p->callingpres;
06048 }
06049 if (update_connected.id.number || update_connected.id.name) {
06050 connected.id.tag = (char *) p->cid_tag;
06051 connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
06052 ast_channel_queue_connected_line_update(ast, &connected, &update_connected);
06053 }
06054
06055 xmitres = transmit_invite(p, SIP_INVITE, 1, 2, uri);
06056 if (xmitres == XMIT_ERROR) {
06057 sip_pvt_unlock(p);
06058 return -1;
06059 }
06060 p->invitestate = INV_CALLING;
06061
06062
06063 AST_SCHED_REPLACE_UNREF(p->initid, sched, p->timer_b, auto_congest, p,
06064 dialog_unref(_data, "dialog ptr dec when SCHED_REPLACE del op succeeded"),
06065 dialog_unref(p, "dialog ptr dec when SCHED_REPLACE add failed"),
06066 dialog_ref(p, "dialog ptr inc when SCHED_REPLACE add succeeded") );
06067 sip_pvt_unlock(p);
06068 }
06069 return res;
06070 }
06071
06072
06073
06074 static void sip_registry_destroy(struct sip_registry *reg)
06075 {
06076
06077 ast_debug(3, "Destroying registry entry for %s@%s\n", reg->username, reg->hostname);
06078
06079 if (reg->call) {
06080
06081
06082 reg->call->registry = registry_unref(reg->call->registry, "destroy reg->call->registry");
06083 ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", reg->username, reg->hostname);
06084 dialog_unlink_all(reg->call);
06085 reg->call = dialog_unref(reg->call, "unref reg->call");
06086
06087 }
06088 AST_SCHED_DEL(sched, reg->expire);
06089 AST_SCHED_DEL(sched, reg->timeout);
06090
06091 ast_string_field_free_memory(reg);
06092 ast_atomic_fetchadd_int(®objs, -1);
06093 ast_free(reg);
06094 }
06095
06096
06097 static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi)
06098 {
06099 if (mwi->call) {
06100 mwi->call->mwi = NULL;
06101 sip_destroy(mwi->call);
06102 }
06103
06104 AST_SCHED_DEL(sched, mwi->resub);
06105 ast_string_field_free_memory(mwi);
06106 ast_free(mwi);
06107 }
06108
06109
06110 void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist)
06111 {
06112 struct sip_request *req;
06113
06114
06115 if (p->stimer) {
06116 p->stimer->quit_flag = 1;
06117 stop_session_timer(p);
06118 ast_free(p->stimer);
06119 p->stimer = NULL;
06120 }
06121
06122 if (sip_debug_test_pvt(p))
06123 ast_verbose("Really destroying SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
06124
06125 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
06126 update_call_counter(p, DEC_CALL_LIMIT);
06127 ast_debug(2, "This call did not properly clean up call limits. Call ID %s\n", p->callid);
06128 }
06129
06130
06131 if (p->owner) {
06132 if (lockowner)
06133 ast_channel_lock(p->owner);
06134 ast_debug(1, "Detaching from %s\n", p->owner->name);
06135 p->owner->tech_pvt = NULL;
06136
06137 p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
06138 if (lockowner)
06139 ast_channel_unlock(p->owner);
06140
06141 usleep(1);
06142 }
06143
06144
06145 if (p->relatedpeer && p->relatedpeer->mwipvt == p)
06146 p->relatedpeer->mwipvt = dialog_unref(p->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
06147 if (p->relatedpeer && p->relatedpeer->call == p)
06148 p->relatedpeer->call = dialog_unref(p->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
06149
06150 if (p->relatedpeer)
06151 p->relatedpeer = unref_peer(p->relatedpeer,"unsetting a dialog relatedpeer field in sip_destroy");
06152
06153 if (p->registry) {
06154 if (p->registry->call == p)
06155 p->registry->call = dialog_unref(p->registry->call, "nulling out the registry's call dialog field in unlink_all");
06156 p->registry = registry_unref(p->registry, "delete p->registry");
06157 }
06158
06159 if (p->mwi) {
06160 p->mwi->call = NULL;
06161 p->mwi = NULL;
06162 }
06163
06164 if (dumphistory)
06165 sip_dump_history(p);
06166
06167 if (p->options) {
06168 if (p->options->outboundproxy) {
06169 ao2_ref(p->options->outboundproxy, -1);
06170 }
06171 ast_free(p->options);
06172 p->options = NULL;
06173 }
06174
06175 if (p->notify) {
06176 ast_variables_destroy(p->notify->headers);
06177 ast_free(p->notify->content);
06178 ast_free(p->notify);
06179 p->notify = NULL;
06180 }
06181 if (p->rtp) {
06182 ast_rtp_instance_destroy(p->rtp);
06183 p->rtp = NULL;
06184 }
06185 if (p->vrtp) {
06186 ast_rtp_instance_destroy(p->vrtp);
06187 p->vrtp = NULL;
06188 }
06189 if (p->trtp) {
06190 ast_rtp_instance_destroy(p->trtp);
06191 p->trtp = NULL;
06192 }
06193 if (p->udptl) {
06194 ast_udptl_destroy(p->udptl);
06195 p->udptl = NULL;
06196 }
06197 if (p->refer) {
06198 if (p->refer->refer_call) {
06199 p->refer->refer_call = dialog_unref(p->refer->refer_call, "unref dialog p->refer->refer_call");
06200 }
06201 ast_free(p->refer);
06202 p->refer = NULL;
06203 }
06204 if (p->route) {
06205 free_old_route(p->route);
06206 p->route = NULL;
06207 }
06208 deinit_req(&p->initreq);
06209
06210
06211 if (p->history) {
06212 struct sip_history *hist;
06213 while ( (hist = AST_LIST_REMOVE_HEAD(p->history, list)) ) {
06214 ast_free(hist);
06215 p->history_entries--;
06216 }
06217 ast_free(p->history);
06218 p->history = NULL;
06219 }
06220
06221 while ((req = AST_LIST_REMOVE_HEAD(&p->request_queue, next))) {
06222 ast_free(req);
06223 }
06224
06225 if (p->chanvars) {
06226 ast_variables_destroy(p->chanvars);
06227 p->chanvars = NULL;
06228 }
06229
06230 if (p->srtp) {
06231 sip_srtp_destroy(p->srtp);
06232 p->srtp = NULL;
06233 }
06234
06235 if (p->vsrtp) {
06236 sip_srtp_destroy(p->vsrtp);
06237 p->vsrtp = NULL;
06238 }
06239
06240 if (p->tsrtp) {
06241 sip_srtp_destroy(p->tsrtp);
06242 p->tsrtp = NULL;
06243 }
06244
06245 if (p->directmediaha) {
06246 ast_free_ha(p->directmediaha);
06247 p->directmediaha = NULL;
06248 }
06249
06250 ast_string_field_free_memory(p);
06251
06252 ast_cc_config_params_destroy(p->cc_params);
06253 p->cc_params = NULL;
06254
06255 if (p->epa_entry) {
06256 ao2_ref(p->epa_entry, -1);
06257 p->epa_entry = NULL;
06258 }
06259
06260 if (p->socket.tcptls_session) {
06261 ao2_ref(p->socket.tcptls_session, -1);
06262 p->socket.tcptls_session = NULL;
06263 }
06264
06265 if (p->peerauth) {
06266 ao2_t_ref(p->peerauth, -1, "Removing active peer authentication");
06267 p->peerauth = NULL;
06268 }
06269 }
06270
06271
06272
06273
06274
06275
06276
06277
06278
06279
06280
06281
06282
06283
06284
06285 static int update_call_counter(struct sip_pvt *fup, int event)
06286 {
06287 char name[256];
06288 int *inuse = NULL, *call_limit = NULL, *inringing = NULL;
06289 int outgoing = fup->outgoing_call;
06290 struct sip_peer *p = NULL;
06291
06292 ast_debug(3, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
06293
06294
06295
06296
06297 if (!ast_test_flag(&fup->flags[0], SIP_CALL_LIMIT) && !ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD))
06298 return 0;
06299
06300 ast_copy_string(name, fup->username, sizeof(name));
06301
06302
06303 if (fup->relatedpeer) {
06304 p = ref_peer(fup->relatedpeer, "ref related peer for update_call_counter");
06305 inuse = &p->inUse;
06306 call_limit = &p->call_limit;
06307 inringing = &p->inRinging;
06308 ast_copy_string(name, fup->peername, sizeof(name));
06309 }
06310 if (!p) {
06311 ast_debug(2, "%s is not a local device, no call limit\n", name);
06312 return 0;
06313 }
06314
06315 switch(event) {
06316
06317 case DEC_CALL_LIMIT:
06318
06319 if (inuse) {
06320 sip_pvt_lock(fup);
06321 ao2_lock(p);
06322 if (*inuse > 0) {
06323 if (ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
06324 (*inuse)--;
06325 ast_clear_flag(&fup->flags[0], SIP_INC_COUNT);
06326 }
06327 } else {
06328 *inuse = 0;
06329 }
06330 ao2_unlock(p);
06331 sip_pvt_unlock(fup);
06332 }
06333
06334
06335 if (inringing) {
06336 sip_pvt_lock(fup);
06337 ao2_lock(p);
06338 if (*inringing > 0) {
06339 if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
06340 (*inringing)--;
06341 ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
06342 }
06343 } else {
06344 *inringing = 0;
06345 }
06346 ao2_unlock(p);
06347 sip_pvt_unlock(fup);
06348 }
06349
06350
06351 sip_pvt_lock(fup);
06352 ao2_lock(p);
06353 if (ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD) && sip_cfg.notifyhold) {
06354 ast_clear_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD);
06355 ao2_unlock(p);
06356 sip_pvt_unlock(fup);
06357 sip_peer_hold(fup, FALSE);
06358 } else {
06359 ao2_unlock(p);
06360 sip_pvt_unlock(fup);
06361 }
06362 if (sipdebug)
06363 ast_debug(2, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
06364 break;
06365
06366 case INC_CALL_RINGING:
06367 case INC_CALL_LIMIT:
06368
06369 if (*call_limit > 0 ) {
06370 if (*inuse >= *call_limit) {
06371 ast_log(LOG_NOTICE, "Call %s %s '%s' rejected due to usage limit of %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
06372 unref_peer(p, "update_call_counter: unref peer p, call limit exceeded");
06373 return -1;
06374 }
06375 }
06376 if (inringing && (event == INC_CALL_RINGING)) {
06377 sip_pvt_lock(fup);
06378 ao2_lock(p);
06379 if (!ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
06380 (*inringing)++;
06381 ast_set_flag(&fup->flags[0], SIP_INC_RINGING);
06382 }
06383 ao2_unlock(p);
06384 sip_pvt_unlock(fup);
06385 }
06386 if (inuse) {
06387 sip_pvt_lock(fup);
06388 ao2_lock(p);
06389 if (!ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
06390 (*inuse)++;
06391 ast_set_flag(&fup->flags[0], SIP_INC_COUNT);
06392 }
06393 ao2_unlock(p);
06394 sip_pvt_unlock(fup);
06395 }
06396 if (sipdebug) {
06397 ast_debug(2, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", "peer", name, *inuse, *call_limit);
06398 }
06399 break;
06400
06401 case DEC_CALL_RINGING:
06402 if (inringing) {
06403 sip_pvt_lock(fup);
06404 ao2_lock(p);
06405 if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
06406 if (*inringing > 0) {
06407 (*inringing)--;
06408 }
06409 ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
06410 }
06411 ao2_unlock(p);
06412 sip_pvt_unlock(fup);
06413 }
06414 break;
06415
06416 default:
06417 ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
06418 }
06419
06420 if (p) {
06421 ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "SIP/%s", p->name);
06422 unref_peer(p, "update_call_counter: unref_peer from call counter");
06423 }
06424 return 0;
06425 }
06426
06427
06428 static void sip_destroy_fn(void *p)
06429 {
06430 sip_destroy(p);
06431 }
06432
06433
06434
06435
06436
06437
06438 struct sip_pvt *sip_destroy(struct sip_pvt *p)
06439 {
06440 ast_debug(3, "Destroying SIP dialog %s\n", p->callid);
06441 __sip_destroy(p, TRUE, TRUE);
06442 return NULL;
06443 }
06444
06445
06446 int hangup_sip2cause(int cause)
06447 {
06448
06449
06450 switch(cause) {
06451 case 401:
06452 return AST_CAUSE_CALL_REJECTED;
06453 case 403:
06454 return AST_CAUSE_CALL_REJECTED;
06455 case 404:
06456 return AST_CAUSE_UNALLOCATED;
06457 case 405:
06458 return AST_CAUSE_INTERWORKING;
06459 case 407:
06460 return AST_CAUSE_CALL_REJECTED;
06461 case 408:
06462 return AST_CAUSE_NO_USER_RESPONSE;
06463 case 409:
06464 return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
06465 case 410:
06466 return AST_CAUSE_NUMBER_CHANGED;
06467 case 411:
06468 return AST_CAUSE_INTERWORKING;
06469 case 413:
06470 return AST_CAUSE_INTERWORKING;
06471 case 414:
06472 return AST_CAUSE_INTERWORKING;
06473 case 415:
06474 return AST_CAUSE_INTERWORKING;
06475 case 420:
06476 return AST_CAUSE_NO_ROUTE_DESTINATION;
06477 case 480:
06478 return AST_CAUSE_NO_ANSWER;
06479 case 481:
06480 return AST_CAUSE_INTERWORKING;
06481 case 482:
06482 return AST_CAUSE_INTERWORKING;
06483 case 483:
06484 return AST_CAUSE_NO_ANSWER;
06485 case 484:
06486 return AST_CAUSE_INVALID_NUMBER_FORMAT;
06487 case 485:
06488 return AST_CAUSE_UNALLOCATED;
06489 case 486:
06490 return AST_CAUSE_BUSY;
06491 case 487:
06492 return AST_CAUSE_INTERWORKING;
06493 case 488:
06494 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
06495 case 491:
06496 return AST_CAUSE_INTERWORKING;
06497 case 493:
06498 return AST_CAUSE_INTERWORKING;
06499 case 500:
06500 return AST_CAUSE_FAILURE;
06501 case 501:
06502 return AST_CAUSE_FACILITY_REJECTED;
06503 case 502:
06504 return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
06505 case 503:
06506 return AST_CAUSE_CONGESTION;
06507 case 504:
06508 return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
06509 case 505:
06510 return AST_CAUSE_INTERWORKING;
06511 case 600:
06512 return AST_CAUSE_USER_BUSY;
06513 case 603:
06514 return AST_CAUSE_CALL_REJECTED;
06515 case 604:
06516 return AST_CAUSE_UNALLOCATED;
06517 case 606:
06518 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
06519 default:
06520 if (cause < 500 && cause >= 400) {
06521
06522 return AST_CAUSE_INTERWORKING;
06523 } else if (cause < 600 && cause >= 500) {
06524
06525 return AST_CAUSE_CONGESTION;
06526 } else if (cause < 700 && cause >= 600) {
06527
06528 return AST_CAUSE_INTERWORKING;
06529 }
06530 return AST_CAUSE_NORMAL;
06531 }
06532
06533 return 0;
06534 }
06535
06536
06537
06538
06539
06540
06541
06542
06543
06544
06545
06546
06547
06548
06549
06550
06551
06552
06553
06554
06555
06556
06557
06558
06559
06560
06561
06562
06563
06564
06565
06566
06567
06568 const char *hangup_cause2sip(int cause)
06569 {
06570 switch (cause) {
06571 case AST_CAUSE_UNALLOCATED:
06572 case AST_CAUSE_NO_ROUTE_DESTINATION:
06573 case AST_CAUSE_NO_ROUTE_TRANSIT_NET:
06574 return "404 Not Found";
06575 case AST_CAUSE_CONGESTION:
06576 case AST_CAUSE_SWITCH_CONGESTION:
06577 return "503 Service Unavailable";
06578 case AST_CAUSE_NO_USER_RESPONSE:
06579 return "408 Request Timeout";
06580 case AST_CAUSE_NO_ANSWER:
06581 case AST_CAUSE_UNREGISTERED:
06582 return "480 Temporarily unavailable";
06583 case AST_CAUSE_CALL_REJECTED:
06584 return "403 Forbidden";
06585 case AST_CAUSE_NUMBER_CHANGED:
06586 return "410 Gone";
06587 case AST_CAUSE_NORMAL_UNSPECIFIED:
06588 return "480 Temporarily unavailable";
06589 case AST_CAUSE_INVALID_NUMBER_FORMAT:
06590 return "484 Address incomplete";
06591 case AST_CAUSE_USER_BUSY:
06592 return "486 Busy here";
06593 case AST_CAUSE_FAILURE:
06594 return "500 Server internal failure";
06595 case AST_CAUSE_FACILITY_REJECTED:
06596 return "501 Not Implemented";
06597 case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
06598 return "503 Service Unavailable";
06599
06600 case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
06601 return "502 Bad Gateway";
06602 case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL:
06603 return "488 Not Acceptable Here";
06604
06605 case AST_CAUSE_NOTDEFINED:
06606 default:
06607 ast_debug(1, "AST hangup cause %d (no match found in SIP)\n", cause);
06608 return NULL;
06609 }
06610
06611
06612 return 0;
06613 }
06614
06615 static int reinvite_timeout(const void *data)
06616 {
06617 struct sip_pvt *dialog = (struct sip_pvt *) data;
06618 struct ast_channel *owner = sip_pvt_lock_full(dialog);
06619 dialog->reinviteid = -1;
06620 check_pendings(dialog);
06621 if (owner) {
06622 ast_channel_unlock(owner);
06623 ast_channel_unref(owner);
06624 }
06625 ao2_unlock(dialog);
06626 dialog_unref(dialog, "unref for reinvite timeout");
06627 return 0;
06628 }
06629
06630
06631
06632 static int sip_hangup(struct ast_channel *ast)
06633 {
06634 struct sip_pvt *p = ast->tech_pvt;
06635 int needcancel = FALSE;
06636 int needdestroy = 0;
06637 struct ast_channel *oldowner = ast;
06638
06639 if (!p) {
06640 ast_debug(1, "Asked to hangup channel that was not connected\n");
06641 return 0;
06642 }
06643 if (ast_test_flag(ast, AST_FLAG_ANSWERED_ELSEWHERE) || ast->hangupcause == AST_CAUSE_ANSWERED_ELSEWHERE) {
06644 ast_debug(1, "This call was answered elsewhere\n");
06645 if (ast->hangupcause == AST_CAUSE_ANSWERED_ELSEWHERE) {
06646 ast_debug(1, "####### It's the cause code, buddy. The cause code!!!\n");
06647 }
06648 append_history(p, "Cancel", "Call answered elsewhere");
06649 p->answered_elsewhere = TRUE;
06650 }
06651
06652
06653 if (p->owner)
06654 p->hangupcause = p->owner->hangupcause;
06655
06656 if (ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
06657 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
06658 if (sipdebug)
06659 ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
06660 update_call_counter(p, DEC_CALL_LIMIT);
06661 }
06662 ast_debug(4, "SIP Transfer: Not hanging up right now... Rescheduling hangup for %s.\n", p->callid);
06663 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06664 ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
06665 p->needdestroy = 0;
06666 p->owner->tech_pvt = dialog_unref(p->owner->tech_pvt, "unref p->owner->tech_pvt");
06667 sip_pvt_lock(p);
06668 p->owner = NULL;
06669 sip_pvt_unlock(p);
06670 ast_module_unref(ast_module_info->self);
06671 return 0;
06672 }
06673
06674 ast_debug(1, "Hangup call %s, SIP callid %s\n", ast->name, p->callid);
06675
06676 sip_pvt_lock(p);
06677 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
06678 if (sipdebug)
06679 ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
06680 update_call_counter(p, DEC_CALL_LIMIT);
06681 }
06682
06683
06684 if (p->owner != ast) {
06685 ast_log(LOG_WARNING, "Huh? We aren't the owner? Can't hangup call.\n");
06686 sip_pvt_unlock(p);
06687 return 0;
06688 }
06689
06690
06691 if (p->invitestate < INV_COMPLETED && p->owner->_state != AST_STATE_UP) {
06692 needcancel = TRUE;
06693 ast_debug(4, "Hanging up channel in state %s (not UP)\n", ast_state2str(ast->_state));
06694 }
06695
06696 stop_media_flows(p);
06697
06698 append_history(p, needcancel ? "Cancel" : "Hangup", "Cause %s", p->owner ? ast_cause2str(p->hangupcause) : "Unknown");
06699
06700
06701 disable_dsp_detect(p);
06702
06703 p->owner = NULL;
06704 ast->tech_pvt = dialog_unref(ast->tech_pvt, "unref ast->tech_pvt");
06705
06706 ast_module_unref(ast_module_info->self);
06707
06708
06709
06710
06711
06712
06713 if (p->alreadygone)
06714 needdestroy = 1;
06715 else if (p->invitestate != INV_CALLING)
06716 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06717
06718
06719 if (!p->alreadygone && p->initreq.data && ast_str_strlen(p->initreq.data)) {
06720 if (needcancel) {
06721 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06722
06723 if (p->invitestate == INV_CALLING) {
06724
06725 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
06726
06727 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06728 append_history(p, "DELAY", "Not sending cancel, waiting for timeout");
06729 } else {
06730 struct sip_pkt *cur;
06731
06732 for (cur = p->packets; cur; cur = cur->next) {
06733 __sip_semi_ack(p, cur->seqno, cur->is_resp, cur->method ? cur->method : find_sip_method(ast_str_buffer(cur->data)));
06734 }
06735 p->invitestate = INV_CANCELLED;
06736
06737 transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
06738
06739
06740 needdestroy = 0;
06741 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06742 }
06743 } else {
06744 const char *res;
06745 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"));
06746 if (p->hangupcause && (res = hangup_cause2sip(p->hangupcause)))
06747 transmit_response_reliable(p, res, &p->initreq);
06748 else
06749 transmit_response_reliable(p, "603 Declined", &p->initreq);
06750 p->invitestate = INV_TERMINATED;
06751 }
06752 } else {
06753 if (p->stimer->st_active == TRUE) {
06754 stop_session_timer(p);
06755 }
06756
06757 if (!p->pendinginvite) {
06758 struct ast_channel *bridge = ast_bridged_channel(oldowner);
06759 char quality_buf[AST_MAX_USER_FIELD], *quality;
06760
06761
06762
06763
06764 while (bridge && ast_channel_trylock(bridge)) {
06765 sip_pvt_unlock(p);
06766 do {
06767 CHANNEL_DEADLOCK_AVOIDANCE(oldowner);
06768 } while (sip_pvt_trylock(p));
06769 bridge = ast_bridged_channel(oldowner);
06770 }
06771
06772 if (p->rtp) {
06773 ast_rtp_instance_set_stats_vars(oldowner, p->rtp);
06774 }
06775
06776 if (bridge) {
06777 struct sip_pvt *q = bridge->tech_pvt;
06778
06779 if (IS_SIP_TECH(bridge->tech) && q && q->rtp) {
06780 ast_rtp_instance_set_stats_vars(bridge, q->rtp);
06781 }
06782 ast_channel_unlock(bridge);
06783 }
06784
06785
06786
06787
06788
06789 if (p->rtp && (quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
06790 if (p->do_history) {
06791 append_history(p, "RTCPaudio", "Quality:%s", quality);
06792 }
06793 pbx_builtin_setvar_helper(oldowner, "RTPAUDIOQOS", quality);
06794 }
06795 if (p->vrtp && (quality = ast_rtp_instance_get_quality(p->vrtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
06796 if (p->do_history) {
06797 append_history(p, "RTCPvideo", "Quality:%s", quality);
06798 }
06799 pbx_builtin_setvar_helper(oldowner, "RTPVIDEOQOS", quality);
06800 }
06801 if (p->trtp && (quality = ast_rtp_instance_get_quality(p->trtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
06802 if (p->do_history) {
06803 append_history(p, "RTCPtext", "Quality:%s", quality);
06804 }
06805 pbx_builtin_setvar_helper(oldowner, "RTPTEXTQOS", quality);
06806 }
06807
06808
06809 if (oldowner->_state == AST_STATE_UP) {
06810 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
06811 }
06812
06813 } else {
06814
06815
06816 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
06817 ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);
06818 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"));
06819 if (sip_cancel_destroy(p)) {
06820 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
06821 }
06822
06823
06824
06825
06826 if (p->ongoing_reinvite && p->reinviteid < 0) {
06827 p->reinviteid = ast_sched_add(sched, 32 * p->timer_t1, reinvite_timeout, dialog_ref(p, "ref for reinvite_timeout"));
06828 }
06829 }
06830 }
06831 }
06832 if (needdestroy) {
06833 pvt_set_needdestroy(p, "hangup");
06834 }
06835 sip_pvt_unlock(p);
06836 return 0;
06837 }
06838
06839
06840 static void try_suggested_sip_codec(struct sip_pvt *p)
06841 {
06842 format_t fmt;
06843 const char *codec;
06844
06845 if (p->outgoing_call) {
06846 codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC_OUTBOUND");
06847 } else if (!(codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC_INBOUND"))) {
06848 codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC");
06849 }
06850
06851 if (!codec)
06852 return;
06853
06854 fmt = ast_getformatbyname(codec);
06855 if (fmt) {
06856 ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC} variable\n", codec);
06857 if (p->jointcapability & fmt) {
06858 p->jointcapability &= fmt;
06859 p->capability &= fmt;
06860 } else
06861 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
06862 } else
06863 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n", codec);
06864 return;
06865 }
06866
06867
06868
06869 static int sip_answer(struct ast_channel *ast)
06870 {
06871 int res = 0;
06872 struct sip_pvt *p = ast->tech_pvt;
06873
06874 sip_pvt_lock(p);
06875 if (ast->_state != AST_STATE_UP) {
06876 try_suggested_sip_codec(p);
06877
06878 ast_setstate(ast, AST_STATE_UP);
06879 ast_debug(1, "SIP answering channel: %s\n", ast->name);
06880 ast_rtp_instance_update_source(p->rtp);
06881 res = transmit_response_with_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL, FALSE, TRUE);
06882 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
06883 }
06884 sip_pvt_unlock(p);
06885 return res;
06886 }
06887
06888
06889 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
06890 {
06891 struct sip_pvt *p = ast->tech_pvt;
06892 int res = 0;
06893
06894 switch (frame->frametype) {
06895 case AST_FRAME_VOICE:
06896 if (!(frame->subclass.codec & ast->nativeformats)) {
06897 char s1[512], s2[512], s3[512];
06898 ast_log(LOG_WARNING, "Asked to transmit frame type %s, while native formats is %s read/write = %s/%s\n",
06899 ast_getformatname(frame->subclass.codec),
06900 ast_getformatname_multiple(s1, sizeof(s1), ast->nativeformats & AST_FORMAT_AUDIO_MASK),
06901 ast_getformatname_multiple(s2, sizeof(s2), ast->readformat),
06902 ast_getformatname_multiple(s3, sizeof(s3), ast->writeformat));
06903 return 0;
06904 }
06905 if (p) {
06906 sip_pvt_lock(p);
06907 if (p->t38.state == T38_ENABLED) {
06908
06909 sip_pvt_unlock(p);
06910 break;
06911 } else if (p->rtp) {
06912
06913 if ((ast->_state != AST_STATE_UP) &&
06914 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06915 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06916 ast_rtp_instance_update_source(p->rtp);
06917 if (!global_prematuremediafilter) {
06918 p->invitestate = INV_EARLY_MEDIA;
06919 transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06920 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06921 }
06922 }
06923 p->lastrtptx = time(NULL);
06924 res = ast_rtp_instance_write(p->rtp, frame);
06925 }
06926 sip_pvt_unlock(p);
06927 }
06928 break;
06929 case AST_FRAME_VIDEO:
06930 if (p) {
06931 sip_pvt_lock(p);
06932 if (p->vrtp) {
06933
06934 if ((ast->_state != AST_STATE_UP) &&
06935 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06936 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06937 p->invitestate = INV_EARLY_MEDIA;
06938 transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06939 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06940 }
06941 p->lastrtptx = time(NULL);
06942 res = ast_rtp_instance_write(p->vrtp, frame);
06943 }
06944 sip_pvt_unlock(p);
06945 }
06946 break;
06947 case AST_FRAME_TEXT:
06948 if (p) {
06949 sip_pvt_lock(p);
06950 if (p->red) {
06951 ast_rtp_red_buffer(p->trtp, frame);
06952 } else {
06953 if (p->trtp) {
06954
06955 if ((ast->_state != AST_STATE_UP) &&
06956 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06957 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06958 p->invitestate = INV_EARLY_MEDIA;
06959 transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06960 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06961 }
06962 p->lastrtptx = time(NULL);
06963 res = ast_rtp_instance_write(p->trtp, frame);
06964 }
06965 }
06966 sip_pvt_unlock(p);
06967 }
06968 break;
06969 case AST_FRAME_IMAGE:
06970 return 0;
06971 break;
06972 case AST_FRAME_MODEM:
06973 if (p) {
06974 sip_pvt_lock(p);
06975
06976
06977
06978
06979 if ((ast->_state == AST_STATE_UP) &&
06980 p->udptl &&
06981 (p->t38.state == T38_ENABLED)) {
06982 res = ast_udptl_write(p->udptl, frame);
06983 }
06984 sip_pvt_unlock(p);
06985 }
06986 break;
06987 default:
06988 ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
06989 return 0;
06990 }
06991
06992 return res;
06993 }
06994
06995
06996
06997 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
06998 {
06999 int ret = -1;
07000 struct sip_pvt *p;
07001
07002 if (newchan && ast_test_flag(newchan, AST_FLAG_ZOMBIE))
07003 ast_debug(1, "New channel is zombie\n");
07004 if (oldchan && ast_test_flag(oldchan, AST_FLAG_ZOMBIE))
07005 ast_debug(1, "Old channel is zombie\n");
07006
07007 if (!newchan || !newchan->tech_pvt) {
07008 if (!newchan)
07009 ast_log(LOG_WARNING, "No new channel! Fixup of %s failed.\n", oldchan->name);
07010 else
07011 ast_log(LOG_WARNING, "No SIP tech_pvt! Fixup of %s failed.\n", oldchan->name);
07012 return -1;
07013 }
07014 p = newchan->tech_pvt;
07015
07016 sip_pvt_lock(p);
07017 append_history(p, "Masq", "Old channel: %s\n", oldchan->name);
07018 append_history(p, "Masq (cont)", "...new owner: %s\n", newchan->name);
07019 if (p->owner != oldchan)
07020 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
07021 else {
07022 p->owner = newchan;
07023
07024
07025
07026
07027
07028
07029 sip_set_rtp_peer(newchan, NULL, NULL, 0, 0, 0);
07030 ret = 0;
07031 }
07032 ast_debug(3, "SIP Fixup: New owner for dialogue %s: %s (Old parent: %s)\n", p->callid, p->owner->name, oldchan->name);
07033
07034 sip_pvt_unlock(p);
07035 return ret;
07036 }
07037
07038 static int sip_senddigit_begin(struct ast_channel *ast, char digit)
07039 {
07040 struct sip_pvt *p = ast->tech_pvt;
07041 int res = 0;
07042
07043 sip_pvt_lock(p);
07044 switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
07045 case SIP_DTMF_INBAND:
07046 res = -1;
07047 break;
07048 case SIP_DTMF_RFC2833:
07049 if (p->rtp)
07050 ast_rtp_instance_dtmf_begin(p->rtp, digit);
07051 break;
07052 default:
07053 break;
07054 }
07055 sip_pvt_unlock(p);
07056
07057 return res;
07058 }
07059
07060
07061
07062 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration)
07063 {
07064 struct sip_pvt *p = ast->tech_pvt;
07065 int res = 0;
07066
07067 sip_pvt_lock(p);
07068 switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
07069 case SIP_DTMF_INFO:
07070 case SIP_DTMF_SHORTINFO:
07071 transmit_info_with_digit(p, digit, duration);
07072 break;
07073 case SIP_DTMF_RFC2833:
07074 if (p->rtp)
07075 ast_rtp_instance_dtmf_end_with_duration(p->rtp, digit, duration);
07076 break;
07077 case SIP_DTMF_INBAND:
07078 res = -1;
07079 break;
07080 }
07081 sip_pvt_unlock(p);
07082
07083 return res;
07084 }
07085
07086
07087 static int sip_transfer(struct ast_channel *ast, const char *dest)
07088 {
07089 struct sip_pvt *p = ast->tech_pvt;
07090 int res;
07091
07092 if (dest == NULL)
07093 dest = "";
07094 sip_pvt_lock(p);
07095 if (ast->_state == AST_STATE_RING)
07096 res = sip_sipredirect(p, dest);
07097 else
07098 res = transmit_refer(p, dest);
07099 sip_pvt_unlock(p);
07100 return res;
07101 }
07102
07103
07104 static int interpret_t38_parameters(struct sip_pvt *p, const struct ast_control_t38_parameters *parameters)
07105 {
07106 int res = 0;
07107
07108 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) || !p->udptl) {
07109 return -1;
07110 }
07111 switch (parameters->request_response) {
07112 case AST_T38_NEGOTIATED:
07113 case AST_T38_REQUEST_NEGOTIATE:
07114
07115 if (!parameters->max_ifp) {
07116 change_t38_state(p, T38_DISABLED);
07117 if (p->t38.state == T38_PEER_REINVITE) {
07118 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"));
07119 transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
07120 }
07121 break;
07122 } else if (p->t38.state == T38_PEER_REINVITE) {
07123 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"));
07124 p->t38.our_parms = *parameters;
07125
07126
07127
07128 if (!p->t38.their_parms.fill_bit_removal) {
07129 p->t38.our_parms.fill_bit_removal = FALSE;
07130 }
07131 if (!p->t38.their_parms.transcoding_mmr) {
07132 p->t38.our_parms.transcoding_mmr = FALSE;
07133 }
07134 if (!p->t38.their_parms.transcoding_jbig) {
07135 p->t38.our_parms.transcoding_jbig = FALSE;
07136 }
07137 p->t38.our_parms.version = MIN(p->t38.our_parms.version, p->t38.their_parms.version);
07138 p->t38.our_parms.rate_management = p->t38.their_parms.rate_management;
07139 ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
07140 change_t38_state(p, T38_ENABLED);
07141 transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
07142 } else if (p->t38.state != T38_ENABLED) {
07143 p->t38.our_parms = *parameters;
07144 ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
07145 change_t38_state(p, T38_LOCAL_REINVITE);
07146 if (!p->pendinginvite) {
07147 transmit_reinvite_with_sdp(p, TRUE, FALSE);
07148 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
07149 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
07150 }
07151 }
07152 break;
07153 case AST_T38_TERMINATED:
07154 case AST_T38_REFUSED:
07155 case AST_T38_REQUEST_TERMINATE:
07156 if (p->t38.state == T38_PEER_REINVITE) {
07157 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"));
07158 change_t38_state(p, T38_DISABLED);
07159 transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
07160 } else if (p->t38.state == T38_ENABLED)
07161 transmit_reinvite_with_sdp(p, FALSE, FALSE);
07162 break;
07163 case AST_T38_REQUEST_PARMS: {
07164 struct ast_control_t38_parameters parameters = p->t38.their_parms;
07165
07166 if (p->t38.state == T38_PEER_REINVITE) {
07167 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"));
07168 parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
07169 parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
07170 ast_queue_control_data(p->owner, AST_CONTROL_T38_PARAMETERS, ¶meters, sizeof(parameters));
07171
07172
07173
07174
07175 res = AST_T38_REQUEST_PARMS;
07176 }
07177 break;
07178 }
07179 default:
07180 res = -1;
07181 break;
07182 }
07183
07184 return res;
07185 }
07186
07187
07188
07189
07190
07191
07192
07193
07194
07195
07196 static int initialize_udptl(struct sip_pvt *p)
07197 {
07198 int natflags = ast_test_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP);
07199
07200 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
07201 return 1;
07202 }
07203
07204
07205 if (p->udptl) {
07206 return 0;
07207 }
07208
07209
07210 if ((p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, &bindaddr))) {
07211 if (p->owner) {
07212 ast_channel_set_fd(p->owner, 5, ast_udptl_fd(p->udptl));
07213 }
07214
07215 ast_udptl_setqos(p->udptl, global_tos_audio, global_cos_audio);
07216 p->t38_maxdatagram = p->relatedpeer ? p->relatedpeer->t38_maxdatagram : global_t38_maxdatagram;
07217 set_t38_capabilities(p);
07218
07219 ast_debug(1, "Setting NAT on UDPTL to %s\n", natflags ? "On" : "Off");
07220 ast_udptl_setnat(p->udptl, natflags);
07221 } else {
07222 ast_log(AST_LOG_WARNING, "UDPTL creation failed - disabling T38 for this dialog\n");
07223 ast_clear_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT);
07224 return 1;
07225 }
07226
07227 return 0;
07228 }
07229
07230
07231
07232
07233
07234
07235 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
07236 {
07237 struct sip_pvt *p = ast->tech_pvt;
07238 int res = 0;
07239
07240 sip_pvt_lock(p);
07241 switch(condition) {
07242 case AST_CONTROL_RINGING:
07243 if (ast->_state == AST_STATE_RING) {
07244 p->invitestate = INV_EARLY_MEDIA;
07245 if (!ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) ||
07246 (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) {
07247
07248 transmit_provisional_response(p, "180 Ringing", &p->initreq, 0);
07249 ast_set_flag(&p->flags[0], SIP_RINGING);
07250 if (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) != SIP_PROG_INBAND_YES)
07251 break;
07252 } else {
07253
07254 }
07255 }
07256 res = -1;
07257 break;
07258 case AST_CONTROL_BUSY:
07259 if (ast->_state != AST_STATE_UP) {
07260 transmit_response_reliable(p, "486 Busy Here", &p->initreq);
07261 p->invitestate = INV_COMPLETED;
07262 sip_alreadygone(p);
07263 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
07264 break;
07265 }
07266 res = -1;
07267 break;
07268 case AST_CONTROL_CONGESTION:
07269 if (ast->_state != AST_STATE_UP) {
07270 transmit_response_reliable(p, "503 Service Unavailable", &p->initreq);
07271 p->invitestate = INV_COMPLETED;
07272 sip_alreadygone(p);
07273 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
07274 break;
07275 }
07276 res = -1;
07277 break;
07278 case AST_CONTROL_INCOMPLETE:
07279 if (ast->_state != AST_STATE_UP) {
07280 switch (ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP)) {
07281 case SIP_PAGE2_ALLOWOVERLAP_YES:
07282 transmit_response_reliable(p, "484 Address Incomplete", &p->initreq);
07283 p->invitestate = INV_COMPLETED;
07284 sip_alreadygone(p);
07285 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
07286 break;
07287 case SIP_PAGE2_ALLOWOVERLAP_DTMF:
07288
07289 break;
07290 default:
07291
07292 transmit_response_reliable(p, "404 Not Found", &p->initreq);
07293 p->invitestate = INV_COMPLETED;
07294 sip_alreadygone(p);
07295 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
07296 break;
07297 }
07298 }
07299 break;
07300 case AST_CONTROL_PROCEEDING:
07301 if ((ast->_state != AST_STATE_UP) &&
07302 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
07303 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
07304 transmit_response(p, "100 Trying", &p->initreq);
07305 p->invitestate = INV_PROCEEDING;
07306 break;
07307 }
07308 res = -1;
07309 break;
07310 case AST_CONTROL_PROGRESS:
07311 if ((ast->_state != AST_STATE_UP) &&
07312 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
07313 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
07314 p->invitestate = INV_EARLY_MEDIA;
07315 transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
07316 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
07317 break;
07318 }
07319 res = -1;
07320 break;
07321 case AST_CONTROL_HOLD:
07322 ast_rtp_instance_update_source(p->rtp);
07323 ast_moh_start(ast, data, p->mohinterpret);
07324 break;
07325 case AST_CONTROL_UNHOLD:
07326 ast_rtp_instance_update_source(p->rtp);
07327 ast_moh_stop(ast);
07328 break;
07329 case AST_CONTROL_VIDUPDATE:
07330 if (p->vrtp && !p->novideo) {
07331 transmit_info_with_vidupdate(p);
07332
07333 } else
07334 res = -1;
07335 break;
07336 case AST_CONTROL_T38_PARAMETERS:
07337 res = -1;
07338 if (datalen != sizeof(struct ast_control_t38_parameters)) {
07339 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);
07340 } else {
07341 const struct ast_control_t38_parameters *parameters = data;
07342 if (!initialize_udptl(p)) {
07343 res = interpret_t38_parameters(p, parameters);
07344 }
07345 }
07346 break;
07347 case AST_CONTROL_SRCUPDATE:
07348 ast_rtp_instance_update_source(p->rtp);
07349 break;
07350 case AST_CONTROL_SRCCHANGE:
07351 ast_rtp_instance_change_source(p->rtp);
07352 break;
07353 case AST_CONTROL_CONNECTED_LINE:
07354 update_connectedline(p, data, datalen);
07355 break;
07356 case AST_CONTROL_REDIRECTING:
07357 update_redirecting(p, data, datalen);
07358 break;
07359 case AST_CONTROL_AOC:
07360 {
07361 struct ast_aoc_decoded *decoded = ast_aoc_decode((struct ast_aoc_encoded *) data, datalen, ast);
07362 if (!decoded) {
07363 ast_log(LOG_ERROR, "Error decoding indicated AOC data\n");
07364 res = -1;
07365 break;
07366 }
07367 switch (ast_aoc_get_msg_type(decoded)) {
07368 case AST_AOC_REQUEST:
07369 if (ast_aoc_get_termination_request(decoded)) {
07370
07371
07372
07373
07374
07375
07376
07377 ast_debug(1, "AOC-E termination request received on %s. This is not yet supported on sip. Continue with hangup \n", p->owner->name);
07378 ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
07379 }
07380 break;
07381 case AST_AOC_D:
07382 case AST_AOC_E:
07383 if (ast_test_flag(&p->flags[2], SIP_PAGE3_SNOM_AOC)) {
07384 transmit_info_with_aoc(p, decoded);
07385 }
07386 break;
07387 case AST_AOC_S:
07388 default:
07389 break;
07390 }
07391 ast_aoc_destroy_decoded(decoded);
07392 }
07393 break;
07394 case AST_CONTROL_UPDATE_RTP_PEER:
07395 break;
07396 case AST_CONTROL_FLASH:
07397 res = -1;
07398 break;
07399 case -1:
07400 res = -1;
07401 break;
07402 default:
07403 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
07404 res = -1;
07405 break;
07406 }
07407 sip_pvt_unlock(p);
07408 return res;
07409 }
07410
07411
07412
07413
07414
07415
07416
07417
07418
07419
07420
07421
07422 static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title, const char *linkedid)
07423 {
07424 struct ast_channel *tmp;
07425 struct ast_variable *v = NULL;
07426 format_t fmt;
07427 format_t what;
07428 format_t video;
07429 format_t text;
07430 format_t needvideo = 0;
07431 int needtext = 0;
07432 char buf[SIPBUFSIZE];
07433 char *exten;
07434
07435 {
07436 const char *my_name;
07437
07438 if (title) {
07439 my_name = title;
07440 } else {
07441 my_name = ast_strdupa(i->fromdomain);
07442 }
07443
07444 sip_pvt_unlock(i);
07445
07446 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));
07447 }
07448 if (!tmp) {
07449 ast_log(LOG_WARNING, "Unable to allocate AST channel structure for SIP channel\n");
07450 sip_pvt_lock(i);
07451 return NULL;
07452 }
07453 ast_channel_lock(tmp);
07454 sip_pvt_lock(i);
07455 ast_channel_cc_params_init(tmp, i->cc_params);
07456 tmp->caller.id.tag = ast_strdup(i->cid_tag);
07457
07458 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;
07459
07460
07461
07462 if (i->jointcapability) {
07463 what = i->jointcapability;
07464 video = i->jointcapability & AST_FORMAT_VIDEO_MASK;
07465 text = i->jointcapability & AST_FORMAT_TEXT_MASK;
07466 } else if (i->capability) {
07467 what = i->capability;
07468 video = i->capability & AST_FORMAT_VIDEO_MASK;
07469 text = i->capability & AST_FORMAT_TEXT_MASK;
07470 } else {
07471 what = sip_cfg.capability;
07472 video = sip_cfg.capability & AST_FORMAT_VIDEO_MASK;
07473 text = sip_cfg.capability & AST_FORMAT_TEXT_MASK;
07474 }
07475
07476
07477 tmp->nativeformats = ast_codec_choose(&i->prefs, what, 1) | video | text;
07478 ast_debug(3, "*** Our native formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, tmp->nativeformats));
07479 ast_debug(3, "*** Joint capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->jointcapability));
07480 ast_debug(3, "*** Our capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->capability));
07481 ast_debug(3, "*** AST_CODEC_CHOOSE formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, ast_codec_choose(&i->prefs, what, 1)));
07482 if (i->prefcodec)
07483 ast_debug(3, "*** Our preferred formats from the incoming channel are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->prefcodec));
07484
07485
07486 fmt = ast_best_codec(tmp->nativeformats);
07487
07488
07489
07490
07491
07492 if (i->vrtp) {
07493 if (ast_test_flag(&i->flags[1], SIP_PAGE2_VIDEOSUPPORT))
07494 needvideo = AST_FORMAT_VIDEO_MASK;
07495 else if (i->prefcodec)
07496 needvideo = i->prefcodec & AST_FORMAT_VIDEO_MASK;
07497 else
07498 needvideo = i->jointcapability & AST_FORMAT_VIDEO_MASK;
07499 }
07500
07501 if (i->trtp) {
07502 if (i->prefcodec)
07503 needtext = i->prefcodec & AST_FORMAT_TEXT_MASK;
07504 else
07505 needtext = i->jointcapability & AST_FORMAT_TEXT_MASK;
07506 }
07507
07508 if (needvideo)
07509 ast_debug(3, "This channel can handle video! HOLLYWOOD next!\n");
07510 else
07511 ast_debug(3, "This channel will not be able to handle video.\n");
07512
07513 enable_dsp_detect(i);
07514
07515 if ((ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
07516 (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
07517 if (i->rtp) {
07518 ast_rtp_instance_dtmf_mode_set(i->rtp, AST_RTP_DTMF_MODE_INBAND);
07519 }
07520 } else if (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) {
07521 if (i->rtp) {
07522 ast_rtp_instance_dtmf_mode_set(i->rtp, AST_RTP_DTMF_MODE_RFC2833);
07523 }
07524 }
07525
07526
07527
07528
07529 if (i->rtp) {
07530 ast_channel_set_fd(tmp, 0, ast_rtp_instance_fd(i->rtp, 0));
07531 ast_channel_set_fd(tmp, 1, ast_rtp_instance_fd(i->rtp, 1));
07532 ast_rtp_instance_set_write_format(i->rtp, fmt);
07533 ast_rtp_instance_set_read_format(i->rtp, fmt);
07534 }
07535 if (needvideo && i->vrtp) {
07536 ast_channel_set_fd(tmp, 2, ast_rtp_instance_fd(i->vrtp, 0));
07537 ast_channel_set_fd(tmp, 3, ast_rtp_instance_fd(i->vrtp, 1));
07538 }
07539 if (needtext && i->trtp) {
07540 ast_channel_set_fd(tmp, 4, ast_rtp_instance_fd(i->trtp, 0));
07541 }
07542 if (i->udptl) {
07543 ast_channel_set_fd(tmp, 5, ast_udptl_fd(i->udptl));
07544 }
07545
07546 if (state == AST_STATE_RING)
07547 tmp->rings = 1;
07548 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
07549
07550 tmp->writeformat = fmt;
07551 tmp->rawwriteformat = fmt;
07552
07553 tmp->readformat = fmt;
07554 tmp->rawreadformat = fmt;
07555
07556 tmp->tech_pvt = dialog_ref(i, "sip_new: set chan->tech_pvt to i");
07557
07558 tmp->callgroup = i->callgroup;
07559 tmp->pickupgroup = i->pickupgroup;
07560 tmp->caller.id.name.presentation = i->callingpres;
07561 tmp->caller.id.number.presentation = i->callingpres;
07562 if (!ast_strlen_zero(i->parkinglot))
07563 ast_string_field_set(tmp, parkinglot, i->parkinglot);
07564 if (!ast_strlen_zero(i->accountcode))
07565 ast_string_field_set(tmp, accountcode, i->accountcode);
07566 if (i->amaflags)
07567 tmp->amaflags = i->amaflags;
07568 if (!ast_strlen_zero(i->language))
07569 ast_string_field_set(tmp, language, i->language);
07570 i->owner = tmp;
07571 ast_module_ref(ast_module_info->self);
07572 ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
07573
07574
07575
07576
07577 exten = ast_strdupa(i->exten);
07578 sip_pvt_unlock(i);
07579 ast_channel_unlock(tmp);
07580 if (!ast_exists_extension(NULL, i->context, i->exten, 1, i->cid_num)) {
07581 ast_uri_decode(exten);
07582 }
07583 ast_channel_lock(tmp);
07584 sip_pvt_lock(i);
07585 ast_copy_string(tmp->exten, exten, sizeof(tmp->exten));
07586
07587
07588
07589 if (!ast_strlen_zero(i->cid_num)) {
07590 tmp->caller.ani.number.valid = 1;
07591 tmp->caller.ani.number.str = ast_strdup(i->cid_num);
07592 }
07593 if (!ast_strlen_zero(i->rdnis)) {
07594 tmp->redirecting.from.number.valid = 1;
07595 tmp->redirecting.from.number.str = ast_strdup(i->rdnis);
07596 }
07597
07598 if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s")) {
07599 tmp->dialed.number.str = ast_strdup(i->exten);
07600 }
07601
07602 tmp->priority = 1;
07603 if (!ast_strlen_zero(i->uri))
07604 pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
07605 if (!ast_strlen_zero(i->domain))
07606 pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
07607 if (!ast_strlen_zero(i->callid))
07608 pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
07609 if (i->rtp)
07610 ast_jb_configure(tmp, &global_jbconf);
07611
07612 if (!i->relatedpeer) {
07613 tmp->flags |= AST_FLAG_DISABLE_DEVSTATE_CACHE;
07614 }
07615
07616 for (v = i->chanvars ; v ; v = v->next) {
07617 char valuebuf[1024];
07618 pbx_builtin_setvar_helper(tmp, v->name, ast_get_encoded_str(v->value, valuebuf, sizeof(valuebuf)));
07619 }
07620
07621 if (i->do_history)
07622 append_history(i, "NewChan", "Channel %s - from %s", tmp->name, i->callid);
07623
07624
07625 if (sip_cfg.callevents)
07626 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
07627 "Channel: %s\r\nUniqueid: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\n",
07628 tmp->name, tmp->uniqueid, "SIP", i->callid, i->fullcontact);
07629
07630 return tmp;
07631 }
07632
07633
07634 static char *get_body_by_line(const char *line, const char *name, int nameLen, char delimiter)
07635 {
07636 if (!strncasecmp(line, name, nameLen) && line[nameLen] == delimiter)
07637 return ast_skip_blanks(line + nameLen + 1);
07638
07639 return "";
07640 }
07641
07642
07643
07644
07645
07646 static const char *get_sdp_iterate(int *start, struct sip_request *req, const char *name)
07647 {
07648 int len = strlen(name);
07649
07650 while (*start < (req->sdp_start + req->sdp_count)) {
07651 const char *r = get_body_by_line(REQ_OFFSET_TO_STR(req, line[(*start)++]), name, len, '=');
07652 if (r[0] != '\0')
07653 return r;
07654 }
07655
07656
07657 (*start)++;
07658
07659 return "";
07660 }
07661
07662
07663
07664
07665
07666
07667 static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value)
07668 {
07669 char type = '\0';
07670 const char *line = NULL;
07671
07672 if (stop > (req->sdp_start + req->sdp_count)) {
07673 stop = req->sdp_start + req->sdp_count;
07674 }
07675
07676 while (*start < stop) {
07677 line = REQ_OFFSET_TO_STR(req, line[(*start)++]);
07678 if (line[1] == '=') {
07679 type = line[0];
07680 *value = ast_skip_blanks(line + 2);
07681 break;
07682 }
07683 }
07684
07685 return type;
07686 }
07687
07688
07689 static char *get_body(struct sip_request *req, char *name, char delimiter)
07690 {
07691 int x;
07692 int len = strlen(name);
07693 char *r;
07694
07695 for (x = 0; x < req->lines; x++) {
07696 r = get_body_by_line(REQ_OFFSET_TO_STR(req, line[x]), name, len, delimiter);
07697 if (r[0] != '\0')
07698 return r;
07699 }
07700
07701 return "";
07702 }
07703
07704
07705 static const char *find_alias(const char *name, const char *_default)
07706 {
07707
07708 static const struct cfalias {
07709 char * const fullname;
07710 char * const shortname;
07711 } aliases[] = {
07712 { "Content-Type", "c" },
07713 { "Content-Encoding", "e" },
07714 { "From", "f" },
07715 { "Call-ID", "i" },
07716 { "Contact", "m" },
07717 { "Content-Length", "l" },
07718 { "Subject", "s" },
07719 { "To", "t" },
07720 { "Supported", "k" },
07721 { "Refer-To", "r" },
07722 { "Referred-By", "b" },
07723 { "Allow-Events", "u" },
07724 { "Event", "o" },
07725 { "Via", "v" },
07726 { "Accept-Contact", "a" },
07727 { "Reject-Contact", "j" },
07728 { "Request-Disposition", "d" },
07729 { "Session-Expires", "x" },
07730 { "Identity", "y" },
07731 { "Identity-Info", "n" },
07732 };
07733 int x;
07734
07735 for (x = 0; x < ARRAY_LEN(aliases); x++) {
07736 if (!strcasecmp(aliases[x].fullname, name))
07737 return aliases[x].shortname;
07738 }
07739
07740 return _default;
07741 }
07742
07743 static const char *__get_header(const struct sip_request *req, const char *name, int *start)
07744 {
07745
07746
07747
07748
07749
07750
07751
07752
07753
07754 const char *sname = find_alias(name, NULL);
07755 int x, len = strlen(name), slen = (sname ? 1 : 0);
07756 for (x = *start; x < req->headers; x++) {
07757 const char *header = REQ_OFFSET_TO_STR(req, header[x]);
07758 int smatch = 0, match = !strncasecmp(header, name, len);
07759 if (slen) {
07760 smatch = !strncasecmp(header, sname, slen);
07761 }
07762 if (match || smatch) {
07763
07764 const char *r = header + (match ? len : slen );
07765 if (sip_cfg.pedanticsipchecking) {
07766 r = ast_skip_blanks(r);
07767 }
07768
07769 if (*r == ':') {
07770 *start = x+1;
07771 return ast_skip_blanks(r+1);
07772 }
07773 }
07774 }
07775
07776
07777 return "";
07778 }
07779
07780
07781
07782
07783 static const char *get_header(const struct sip_request *req, const char *name)
07784 {
07785 int start = 0;
07786 return __get_header(req, name, &start);
07787 }
07788
07789
07790 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect)
07791 {
07792
07793 struct ast_frame *f;
07794
07795 if (!p->rtp) {
07796
07797 return &ast_null_frame;
07798 }
07799
07800 switch(ast->fdno) {
07801 case 0:
07802 f = ast_rtp_instance_read(p->rtp, 0);
07803 break;
07804 case 1:
07805 f = ast_rtp_instance_read(p->rtp, 1);
07806 break;
07807 case 2:
07808 f = ast_rtp_instance_read(p->vrtp, 0);
07809 break;
07810 case 3:
07811 f = ast_rtp_instance_read(p->vrtp, 1);
07812 break;
07813 case 4:
07814 f = ast_rtp_instance_read(p->trtp, 0);
07815 if (sipdebug_text) {
07816 int i;
07817 unsigned char* arr = f->data.ptr;
07818 for (i=0; i < f->datalen; i++)
07819 ast_verbose("%c", (arr[i] > ' ' && arr[i] < '}') ? arr[i] : '.');
07820 ast_verbose(" -> ");
07821 for (i=0; i < f->datalen; i++)
07822 ast_verbose("%02X ", arr[i]);
07823 ast_verbose("\n");
07824 }
07825 break;
07826 case 5:
07827 f = ast_udptl_read(p->udptl);
07828 break;
07829 default:
07830 f = &ast_null_frame;
07831 }
07832
07833 if (f && (f->frametype == AST_FRAME_DTMF_BEGIN || f->frametype == AST_FRAME_DTMF_END) &&
07834 (ast_test_flag(&p->flags[0], SIP_DTMF) != SIP_DTMF_RFC2833)) {
07835 ast_debug(1, "Ignoring DTMF (%c) RTP frame because dtmfmode is not RFC2833\n", f->subclass.integer);
07836 ast_frfree(f);
07837 return &ast_null_frame;
07838 }
07839
07840
07841 if (!p->owner || (f && f->frametype != AST_FRAME_VOICE))
07842 return f;
07843
07844 if (f && f->subclass.codec != (p->owner->nativeformats & AST_FORMAT_AUDIO_MASK)) {
07845 if (!(f->subclass.codec & p->jointcapability)) {
07846 ast_debug(1, "Bogus frame of format '%s' received from '%s'!\n",
07847 ast_getformatname(f->subclass.codec), p->owner->name);
07848 ast_frfree(f);
07849 return &ast_null_frame;
07850 }
07851 ast_debug(1, "Oooh, format changed to %s\n",
07852 ast_getformatname(f->subclass.codec));
07853 p->owner->nativeformats = (p->owner->nativeformats & (AST_FORMAT_VIDEO_MASK | AST_FORMAT_TEXT_MASK)) | f->subclass.codec;
07854 ast_set_read_format(p->owner, p->owner->readformat);
07855 ast_set_write_format(p->owner, p->owner->writeformat);
07856 }
07857
07858 if (f && p->dsp) {
07859 f = ast_dsp_process(p->owner, p->dsp, f);
07860 if (f && f->frametype == AST_FRAME_DTMF) {
07861 if (f->subclass.integer == 'f') {
07862 ast_debug(1, "Fax CNG detected on %s\n", ast->name);
07863 *faxdetect = 1;
07864
07865 if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
07866 ast_dsp_set_features(p->dsp, DSP_FEATURE_DIGIT_DETECT);
07867 } else {
07868 ast_dsp_free(p->dsp);
07869 p->dsp = NULL;
07870 }
07871 } else {
07872 ast_debug(1, "* Detected inband DTMF '%c'\n", f->subclass.integer);
07873 }
07874 }
07875 }
07876
07877 return f;
07878 }
07879
07880
07881 static struct ast_frame *sip_read(struct ast_channel *ast)
07882 {
07883 struct ast_frame *fr;
07884 struct sip_pvt *p = ast->tech_pvt;
07885 int faxdetected = FALSE;
07886
07887 sip_pvt_lock(p);
07888 fr = sip_rtp_read(ast, p, &faxdetected);
07889 p->lastrtprx = time(NULL);
07890
07891
07892 if (faxdetected && ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_CNG)) {
07893 if (strcmp(ast->exten, "fax")) {
07894 const char *target_context = S_OR(ast->macrocontext, ast->context);
07895
07896
07897
07898
07899
07900 sip_pvt_unlock(p);
07901 ast_channel_unlock(ast);
07902 if (ast_exists_extension(ast, target_context, "fax", 1,
07903 S_COR(ast->caller.id.number.valid, ast->caller.id.number.str, NULL))) {
07904 ast_channel_lock(ast);
07905 sip_pvt_lock(p);
07906 ast_verbose(VERBOSE_PREFIX_2 "Redirecting '%s' to fax extension due to CNG detection\n", ast->name);
07907 pbx_builtin_setvar_helper(ast, "FAXEXTEN", ast->exten);
07908 if (ast_async_goto(ast, target_context, "fax", 1)) {
07909 ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", ast->name, target_context);
07910 }
07911 ast_frfree(fr);
07912 fr = &ast_null_frame;
07913 } else {
07914 ast_channel_lock(ast);
07915 sip_pvt_lock(p);
07916 ast_log(LOG_NOTICE, "FAX CNG detected but no fax extension\n");
07917 }
07918 }
07919 }
07920
07921
07922 if (fr && fr->frametype == AST_FRAME_VOICE && p->invitestate != INV_EARLY_MEDIA && ast->_state != AST_STATE_UP) {
07923 ast_frfree(fr);
07924 fr = &ast_null_frame;
07925 }
07926
07927 sip_pvt_unlock(p);
07928
07929 return fr;
07930 }
07931
07932
07933
07934 static char *generate_random_string(char *buf, size_t size)
07935 {
07936 long val[4];
07937 int x;
07938
07939 for (x=0; x<4; x++)
07940 val[x] = ast_random();
07941 snprintf(buf, size, "%08lx%08lx%08lx%08lx", val[0], val[1], val[2], val[3]);
07942
07943 return buf;
07944 }
07945
07946 static char *generate_uri(struct sip_pvt *pvt, char *buf, size_t size)
07947 {
07948 struct ast_str *uri = ast_str_alloca(size);
07949 ast_str_set(&uri, 0, "%s", pvt->socket.type == SIP_TRANSPORT_TLS ? "sips:" : "sip:");
07950
07951
07952
07953 ast_str_append(&uri, 0, "%s", generate_random_string(buf, size));
07954 ast_str_append(&uri, 0, "@%s", ast_sockaddr_stringify_remote(&pvt->ourip));
07955 ast_copy_string(buf, ast_str_buffer(uri), size);
07956 return buf;
07957 }
07958
07959
07960
07961
07962
07963
07964
07965
07966 static void build_callid_pvt(struct sip_pvt *pvt)
07967 {
07968 char buf[33];
07969 const char *host = S_OR(pvt->fromdomain, ast_sockaddr_stringify_remote(&pvt->ourip));
07970
07971 ast_string_field_build(pvt, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
07972 }
07973
07974
07975 #define CONTAINER_UNLINK(container, obj, tag) \
07976 ({ \
07977 int found = 0; \
07978 typeof((obj)) __removed_obj; \
07979 __removed_obj = ao2_t_callback((container), \
07980 OBJ_UNLINK | OBJ_POINTER, ao2_match_by_addr, (obj), (tag)); \
07981 if (__removed_obj) { \
07982 ao2_ref(__removed_obj, -1); \
07983 found = 1; \
07984 } \
07985 found; \
07986 })
07987
07988
07989
07990
07991
07992
07993
07994
07995
07996
07997 static void change_callid_pvt(struct sip_pvt *pvt, const char *callid)
07998 {
07999 int in_dialog_container;
08000
08001 ao2_lock(dialogs);
08002 in_dialog_container = CONTAINER_UNLINK(dialogs, pvt,
08003 "About to change the callid -- remove the old name");
08004 if (callid) {
08005 ast_string_field_set(pvt, callid, callid);
08006 } else {
08007 build_callid_pvt(pvt);
08008 }
08009 if (in_dialog_container) {
08010 ao2_t_link(dialogs, pvt, "New dialog callid -- inserted back into table");
08011 }
08012 ao2_unlock(dialogs);
08013 }
08014
08015
08016 static void build_callid_registry(struct sip_registry *reg, const struct ast_sockaddr *ourip, const char *fromdomain)
08017 {
08018 char buf[33];
08019
08020 const char *host = S_OR(fromdomain, ast_sockaddr_stringify_host_remote(ourip));
08021
08022 ast_string_field_build(reg, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
08023 }
08024
08025
08026 static void make_our_tag(struct sip_pvt *pvt)
08027 {
08028 ast_string_field_build(pvt, tag, "as%08lx", ast_random());
08029 }
08030
08031
08032 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p)
08033 {
08034 struct sip_st_dlg *stp;
08035
08036 if (p->stimer) {
08037 ast_log(LOG_ERROR, "Session-Timer struct already allocated\n");
08038 return p->stimer;
08039 }
08040
08041 if (!(stp = ast_calloc(1, sizeof(struct sip_st_dlg))))
08042 return NULL;
08043
08044 p->stimer = stp;
08045
08046 stp->st_schedid = -1;
08047
08048 return p->stimer;
08049 }
08050
08051
08052
08053
08054
08055 struct sip_pvt *sip_alloc(ast_string_field callid, struct ast_sockaddr *addr,
08056 int useglobal_nat, const int intended_method, struct sip_request *req)
08057 {
08058 struct sip_pvt *p;
08059
08060 if (!(p = ao2_t_alloc(sizeof(*p), sip_destroy_fn, "allocate a dialog(pvt) struct")))
08061 return NULL;
08062
08063 if (ast_string_field_init(p, 512)) {
08064 ao2_t_ref(p, -1, "failed to string_field_init, drop p");
08065 return NULL;
08066 }
08067
08068 if (!(p->cc_params = ast_cc_config_params_init())) {
08069 ao2_t_ref(p, -1, "Yuck, couldn't allocate cc_params struct. Get rid o' p");
08070 return NULL;
08071 }
08072
08073
08074
08075 if (req) {
08076 struct sip_via *via;
08077 const char *cseq = get_header(req, "Cseq");
08078 uint32_t seqno;
08079
08080
08081 via = parse_via(get_header(req, "Via"));
08082 if (via) {
08083
08084
08085 if (!ast_strlen_zero(via->branch) && !strncasecmp(via->branch, "z9hG4bK", 7)) {
08086 ast_string_field_set(p, initviabranch, via->branch);
08087 ast_string_field_set(p, initviasentby, via->sent_by);
08088 }
08089 free_via(via);
08090 }
08091
08092
08093
08094 if (!ast_strlen_zero(cseq) && (sscanf(cseq, "%30u", &seqno) == 1)) {
08095 p->init_icseq = seqno;
08096 }
08097
08098 set_socket_transport(&p->socket, req->socket.type);
08099 } else {
08100 set_socket_transport(&p->socket, SIP_TRANSPORT_UDP);
08101 }
08102
08103 p->socket.fd = -1;
08104 p->method = intended_method;
08105 p->initid = -1;
08106 p->waitid = -1;
08107 p->reinviteid = -1;
08108 p->autokillid = -1;
08109 p->request_queue_sched_id = -1;
08110 p->provisional_keepalive_sched_id = -1;
08111 p->t38id = -1;
08112 p->subscribed = NONE;
08113 p->stateid = -1;
08114 p->sessionversion_remote = -1;
08115 p->session_modify = TRUE;
08116 p->stimer = NULL;
08117 p->prefs = default_prefs;
08118 p->maxforwards = sip_cfg.default_max_forwards;
08119
08120 if (intended_method != SIP_OPTIONS) {
08121 p->timer_t1 = global_t1;
08122 p->timer_b = global_timer_b;
08123 }
08124
08125 if (!addr) {
08126 p->ourip = internip;
08127 } else {
08128 ast_sockaddr_copy(&p->sa, addr);
08129 ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
08130 }
08131
08132
08133 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
08134 ast_copy_flags(&p->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
08135 ast_copy_flags(&p->flags[2], &global_flags[2], SIP_PAGE3_FLAGS_TO_COPY);
08136
08137 p->do_history = recordhistory;
08138
08139 p->branch = ast_random();
08140 make_our_tag(p);
08141 p->ocseq = INITIAL_CSEQ;
08142 p->allowed_methods = UINT_MAX;
08143
08144 if (sip_methods[intended_method].need_rtp) {
08145 p->maxcallbitrate = default_maxcallbitrate;
08146 p->autoframing = global_autoframing;
08147 }
08148
08149 if (useglobal_nat && addr) {
08150
08151 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT_FORCE_RPORT);
08152 ast_sockaddr_copy(&p->recv, addr);
08153
08154 do_setnat(p);
08155 }
08156
08157 if (p->method != SIP_REGISTER) {
08158 ast_string_field_set(p, fromdomain, default_fromdomain);
08159 p->fromdomainport = default_fromdomainport;
08160 }
08161 build_via(p);
08162 if (!callid)
08163 build_callid_pvt(p);
08164 else
08165 ast_string_field_set(p, callid, callid);
08166
08167 ast_string_field_set(p, mohinterpret, default_mohinterpret);
08168 ast_string_field_set(p, mohsuggest, default_mohsuggest);
08169 p->capability = sip_cfg.capability;
08170 p->allowtransfer = sip_cfg.allowtransfer;
08171 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
08172 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
08173 p->noncodeccapability |= AST_RTP_DTMF;
08174 }
08175 ast_string_field_set(p, context, sip_cfg.default_context);
08176 ast_string_field_set(p, parkinglot, default_parkinglot);
08177 ast_string_field_set(p, engine, default_engine);
08178
08179 AST_LIST_HEAD_INIT_NOLOCK(&p->request_queue);
08180
08181
08182
08183 ao2_t_link(dialogs, p, "link pvt into dialogs table");
08184
08185 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");
08186 return p;
08187 }
08188
08189
08190
08191
08192
08193
08194
08195
08196 static int addr_is_multicast(const struct ast_sockaddr *addr)
08197 {
08198 return ((ast_sockaddr_ipv4(addr) & 0xf0000000) == 0xe0000000);
08199 }
08200
08201
08202
08203
08204
08205
08206
08207
08208
08209
08210
08211
08212
08213
08214
08215
08216 static int process_via(struct sip_pvt *p, const struct sip_request *req)
08217 {
08218 struct sip_via *via = parse_via(get_header(req, "Via"));
08219
08220 if (!via) {
08221 ast_log(LOG_ERROR, "error processing via header\n");
08222 return -1;
08223 }
08224
08225 if (via->maddr) {
08226 if (ast_sockaddr_resolve_first_transport(&p->sa, via->maddr, PARSE_PORT_FORBID, p->socket.type)) {
08227 ast_log(LOG_WARNING, "Can't find address for maddr '%s'\n", via->maddr);
08228 ast_log(LOG_ERROR, "error processing via header\n");
08229 free_via(via);
08230 return -1;
08231 }
08232
08233 if (addr_is_multicast(&p->sa)) {
08234 setsockopt(sipsock, IPPROTO_IP, IP_MULTICAST_TTL, &via->ttl, sizeof(via->ttl));
08235 }
08236 }
08237
08238 ast_sockaddr_set_port(&p->sa, via->port ? via->port : STANDARD_SIP_PORT);
08239
08240 free_via(via);
08241 return 0;
08242 }
08243
08244
08245 struct match_req_args {
08246 int method;
08247 const char *callid;
08248 const char *totag;
08249 const char *fromtag;
08250 uint32_t seqno;
08251
08252
08253 const char *ruri;
08254 const char *viabranch;
08255 const char *viasentby;
08256
08257
08258 int authentication_present;
08259 };
08260
08261 enum match_req_res {
08262 SIP_REQ_MATCH,
08263 SIP_REQ_NOT_MATCH,
08264 SIP_REQ_LOOP_DETECTED,
08265 };
08266
08267
08268
08269
08270
08271
08272 static enum match_req_res match_req_to_dialog(struct sip_pvt *sip_pvt_ptr, struct match_req_args *arg)
08273 {
08274 const char *init_ruri = NULL;
08275 if (sip_pvt_ptr->initreq.headers) {
08276 init_ruri = REQ_OFFSET_TO_STR(&sip_pvt_ptr->initreq, rlPart2);
08277 }
08278
08279
08280
08281
08282 if (!ast_strlen_zero(arg->callid) && strcmp(sip_pvt_ptr->callid, arg->callid)) {
08283
08284 return SIP_REQ_NOT_MATCH;
08285 }
08286 if (arg->method == SIP_RESPONSE) {
08287
08288
08289 if (!ast_strlen_zero(sip_pvt_ptr->theirtag) && ast_test_flag(&sip_pvt_ptr->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
08290 if (ast_strlen_zero(arg->totag)) {
08291
08292 return SIP_REQ_NOT_MATCH;
08293 }
08294 if (strcmp(arg->totag, sip_pvt_ptr->theirtag)) {
08295
08296 return SIP_REQ_NOT_MATCH;
08297 }
08298 }
08299
08300 if (strcmp(arg->fromtag, sip_pvt_ptr->tag)) {
08301
08302 return SIP_REQ_NOT_MATCH;
08303 }
08304 } else {
08305
08306
08307
08308 if (!arg->authentication_present && strcmp(arg->fromtag, sip_pvt_ptr->theirtag)) {
08309
08310 return SIP_REQ_NOT_MATCH;
08311 }
08312
08313 if (!ast_strlen_zero(arg->totag) && (strcmp(arg->totag, sip_pvt_ptr->tag))) {
08314
08315 return SIP_REQ_NOT_MATCH;
08316 }
08317 }
08318
08319
08320
08321
08322
08323
08324
08325
08326
08327
08328
08329
08330
08331
08332
08333
08334
08335 if ((arg->method != SIP_RESPONSE) &&
08336 ast_strlen_zero(arg->totag) &&
08337 (sip_pvt_ptr->init_icseq == arg->seqno) &&
08338 !ast_strlen_zero(sip_pvt_ptr->initviabranch) &&
08339 init_ruri) {
08340
08341
08342 if (ast_strlen_zero(arg->viabranch) ||
08343 strcmp(arg->viabranch, sip_pvt_ptr->initviabranch) ||
08344 ast_strlen_zero(arg->viasentby) ||
08345 strcmp(arg->viasentby, sip_pvt_ptr->initviasentby)) {
08346
08347
08348
08349 if ((sip_pvt_ptr->method != arg->method)) {
08350 return SIP_REQ_NOT_MATCH;
08351 }
08352
08353
08354
08355 if (sip_uri_cmp(init_ruri, arg->ruri)) {
08356
08357 return SIP_REQ_NOT_MATCH;
08358 }
08359
08360
08361
08362
08363
08364
08365
08366
08367
08368
08369
08370
08371
08372
08373
08374
08375
08376
08377
08378 return SIP_REQ_LOOP_DETECTED;
08379 }
08380 }
08381
08382
08383
08384
08385
08386
08387 if ((arg->method != SIP_RESPONSE) &&
08388 ast_strlen_zero(arg->totag) &&
08389 arg->authentication_present &&
08390 sip_uri_cmp(init_ruri, arg->ruri)) {
08391
08392
08393 return SIP_REQ_NOT_MATCH;
08394 }
08395
08396 return SIP_REQ_MATCH;
08397 }
08398
08399
08400
08401
08402
08403
08404
08405
08406
08407
08408
08409
08410
08411
08412
08413
08414
08415
08416 static struct ast_channel *sip_pvt_lock_full(struct sip_pvt *pvt)
08417 {
08418 struct ast_channel *chan;
08419
08420
08421
08422
08423 for (;;) {
08424
08425 sip_pvt_lock(pvt);
08426 chan = pvt->owner;
08427 if (chan) {
08428
08429
08430
08431 ast_channel_ref(chan);
08432 } else {
08433
08434 return NULL;
08435 }
08436
08437
08438
08439
08440 sip_pvt_unlock(pvt);
08441
08442
08443 ast_channel_lock(chan);
08444 sip_pvt_lock(pvt);
08445
08446 if (pvt->owner == chan) {
08447
08448 break;
08449 }
08450
08451
08452
08453
08454
08455
08456 ast_channel_unlock(chan);
08457 ast_channel_unref(chan);
08458 sip_pvt_unlock(pvt);
08459 }
08460
08461
08462 return pvt->owner;
08463 }
08464
08465
08466
08467
08468
08469
08470 static struct sip_pvt *find_call(struct sip_request *req, struct ast_sockaddr *addr, const int intended_method)
08471 {
08472 char totag[128];
08473 char fromtag[128];
08474 const char *callid = get_header(req, "Call-ID");
08475 const char *from = get_header(req, "From");
08476 const char *to = get_header(req, "To");
08477 const char *cseq = get_header(req, "Cseq");
08478 struct sip_pvt *sip_pvt_ptr;
08479 uint32_t seqno;
08480
08481
08482 if (ast_strlen_zero(callid) || ast_strlen_zero(to) ||
08483 ast_strlen_zero(from) || ast_strlen_zero(cseq) ||
08484 (sscanf(cseq, "%30u", &seqno) != 1)) {
08485
08486
08487 if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
08488 transmit_response_using_temp(callid, addr, 1, intended_method,
08489 req, "400 Bad Request");
08490 }
08491 return NULL;
08492 }
08493
08494 if (sip_cfg.pedanticsipchecking) {
08495
08496
08497
08498
08499
08500
08501 if (gettag(req, "To", totag, sizeof(totag)))
08502 req->has_to_tag = 1;
08503 gettag(req, "From", fromtag, sizeof(fromtag));
08504
08505 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);
08506
08507
08508 if (ast_strlen_zero(fromtag)) {
08509 ast_debug(5, "%s request has no from tag, dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
08510 return NULL;
08511 }
08512
08513 if (ast_strlen_zero(totag) && (req->method == SIP_ACK || req->method == SIP_BYE || req->method == SIP_INFO )) {
08514 ast_debug(5, "%s must have a to tag. dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
08515 return NULL;
08516 }
08517 }
08518
08519 if (!sip_cfg.pedanticsipchecking) {
08520 struct sip_pvt tmp_dialog = {
08521 .callid = callid,
08522 };
08523 sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find in dialogs");
08524 if (sip_pvt_ptr) {
08525
08526 return sip_pvt_ptr;
08527 }
08528 } else {
08529 struct sip_pvt tmp_dialog = {
08530 .callid = callid,
08531 };
08532 struct match_req_args args = { 0, };
08533 int found;
08534 struct ao2_iterator *iterator = ao2_t_callback(dialogs,
08535 OBJ_POINTER | OBJ_MULTIPLE,
08536 dialog_find_multiple,
08537 &tmp_dialog,
08538 "pedantic ao2_find in dialogs");
08539 struct sip_via *via = NULL;
08540
08541 args.method = req->method;
08542 args.callid = NULL;
08543 args.totag = totag;
08544 args.fromtag = fromtag;
08545 args.seqno = seqno;
08546
08547
08548 if (req->method != SIP_RESPONSE) {
08549 args.ruri = REQ_OFFSET_TO_STR(req, rlPart2);
08550 via = parse_via(get_header(req, "Via"));
08551 if (via) {
08552 args.viasentby = via->sent_by;
08553 args.viabranch = via->branch;
08554 }
08555 if (!ast_strlen_zero(get_header(req, "Authorization")) ||
08556 !ast_strlen_zero(get_header(req, "Proxy-Authorization"))) {
08557 args.authentication_present = 1;
08558 }
08559 }
08560
08561
08562 while (iterator && (sip_pvt_ptr = ao2_iterator_next(iterator))) {
08563 sip_pvt_lock(sip_pvt_ptr);
08564 found = match_req_to_dialog(sip_pvt_ptr, &args);
08565 sip_pvt_unlock(sip_pvt_ptr);
08566
08567 switch (found) {
08568 case SIP_REQ_MATCH:
08569 ao2_iterator_destroy(iterator);
08570 free_via(via);
08571 return sip_pvt_ptr;
08572 case SIP_REQ_LOOP_DETECTED:
08573
08574
08575 transmit_response_using_temp(callid, addr, 1, intended_method, req, "482 (Loop Detected)");
08576 dialog_unref(sip_pvt_ptr, "pvt did not match incoming SIP msg, unref from search.");
08577 ao2_iterator_destroy(iterator);
08578 free_via(via);
08579 return NULL;
08580 case SIP_REQ_NOT_MATCH:
08581 default:
08582 dialog_unref(sip_pvt_ptr, "pvt did not match incoming SIP msg, unref from search");
08583 break;
08584 }
08585 }
08586 if (iterator) {
08587 ao2_iterator_destroy(iterator);
08588 }
08589
08590 free_via(via);
08591 }
08592
08593
08594 if (sip_methods[intended_method].can_create == CAN_CREATE_DIALOG) {
08595 struct sip_pvt *p = NULL;
08596
08597 if (intended_method == SIP_REFER) {
08598
08599 transmit_response_using_temp(callid, addr, 1, intended_method, req, "603 Declined (no dialog)");
08600
08601
08602 } else if (!(p = sip_alloc(callid, addr, 1, intended_method, req))) {
08603
08604
08605
08606
08607
08608
08609
08610
08611 transmit_response_using_temp(callid, addr, 1, intended_method, req, "500 Server internal error");
08612 ast_debug(4, "Failed allocating SIP dialog, sending 500 Server internal error and giving up\n");
08613 }
08614 return p;
08615 } else if( sip_methods[intended_method].can_create == CAN_CREATE_DIALOG_UNSUPPORTED_METHOD) {
08616
08617 transmit_response_using_temp(callid, addr, 1, intended_method, req, "501 Method Not Implemented");
08618 ast_debug(2, "Got a request with unsupported SIP method.\n");
08619 } else if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
08620
08621 transmit_response_using_temp(callid, addr, 1, intended_method, req, "481 Call leg/transaction does not exist");
08622 ast_debug(2, "That's odd... Got a request in unknown dialog. Callid %s\n", callid ? callid : "<unknown>");
08623 }
08624
08625
08626 if (intended_method == SIP_RESPONSE)
08627 ast_debug(2, "That's odd... Got a response on a call we don't know about. Callid %s\n", callid ? callid : "<unknown>");
08628
08629 return NULL;
08630 }
08631
08632
08633 static int sip_register(const char *value, int lineno)
08634 {
08635 struct sip_registry *reg;
08636
08637 if (!(reg = ast_calloc_with_stringfields(1, struct sip_registry, 256))) {
08638 ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry entry\n");
08639 return -1;
08640 }
08641
08642 ast_atomic_fetchadd_int(®objs, 1);
08643 ASTOBJ_INIT(reg);
08644
08645 if (sip_parse_register_line(reg, default_expiry, value, lineno)) {
08646 registry_unref(reg, "failure to parse, unref the reg pointer");
08647 return -1;
08648 }
08649
08650
08651 if (reg->refresh && !reg->expiry && !reg->configured_expiry) {
08652 reg->refresh = reg->expiry = reg->configured_expiry = default_expiry;
08653 }
08654
08655
08656 ASTOBJ_CONTAINER_LINK(®l, reg);
08657
08658
08659 registry_unref(reg, "unref the reg pointer");
08660
08661 return 0;
08662 }
08663
08664
08665 static int sip_subscribe_mwi(const char *value, int lineno)
08666 {
08667 struct sip_subscription_mwi *mwi;
08668 int portnum = 0;
08669 enum sip_transport transport = SIP_TRANSPORT_UDP;
08670 char buf[256] = "";
08671 char *username = NULL, *hostname = NULL, *secret = NULL, *authuser = NULL, *porta = NULL, *mailbox = NULL;
08672
08673 if (!value) {
08674 return -1;
08675 }
08676
08677 ast_copy_string(buf, value, sizeof(buf));
08678
08679 username = buf;
08680
08681 if ((hostname = strrchr(buf, '@'))) {
08682 *hostname++ = '\0';
08683 } else {
08684 return -1;
08685 }
08686
08687 if ((secret = strchr(username, ':'))) {
08688 *secret++ = '\0';
08689 if ((authuser = strchr(secret, ':'))) {
08690 *authuser++ = '\0';
08691 }
08692 }
08693
08694 if ((mailbox = strchr(hostname, '/'))) {
08695 *mailbox++ = '\0';
08696 }
08697
08698 if (ast_strlen_zero(username) || ast_strlen_zero(hostname) || ast_strlen_zero(mailbox)) {
08699 ast_log(LOG_WARNING, "Format for MWI subscription is user[:secret[:authuser]]@host[:port]/mailbox at line %d\n", lineno);
08700 return -1;
08701 }
08702
08703 if ((porta = strchr(hostname, ':'))) {
08704 *porta++ = '\0';
08705 if (!(portnum = atoi(porta))) {
08706 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
08707 return -1;
08708 }
08709 }
08710
08711 if (!(mwi = ast_calloc_with_stringfields(1, struct sip_subscription_mwi, 256))) {
08712 return -1;
08713 }
08714
08715 ASTOBJ_INIT(mwi);
08716 ast_string_field_set(mwi, username, username);
08717 if (secret) {
08718 ast_string_field_set(mwi, secret, secret);
08719 }
08720 if (authuser) {
08721 ast_string_field_set(mwi, authuser, authuser);
08722 }
08723 ast_string_field_set(mwi, hostname, hostname);
08724 ast_string_field_set(mwi, mailbox, mailbox);
08725 mwi->resub = -1;
08726 mwi->portno = portnum;
08727 mwi->transport = transport;
08728
08729 ASTOBJ_CONTAINER_LINK(&submwil, mwi);
08730 ASTOBJ_UNREF(mwi, sip_subscribe_mwi_destroy);
08731
08732 return 0;
08733 }
08734
08735 static void mark_method_allowed(unsigned int *allowed_methods, enum sipmethod method)
08736 {
08737 (*allowed_methods) |= (1 << method);
08738 }
08739
08740 static void mark_method_unallowed(unsigned int *allowed_methods, enum sipmethod method)
08741 {
08742 (*allowed_methods) &= ~(1 << method);
08743 }
08744
08745
08746 static int is_method_allowed(unsigned int *allowed_methods, enum sipmethod method)
08747 {
08748 return ((*allowed_methods) >> method) & 1;
08749 }
08750
08751 static void mark_parsed_methods(unsigned int *methods, char *methods_str)
08752 {
08753 char *method;
08754 for (method = strsep(&methods_str, ","); !ast_strlen_zero(method); method = strsep(&methods_str, ",")) {
08755 int id = find_sip_method(ast_skip_blanks(method));
08756 if (id == SIP_UNKNOWN) {
08757 continue;
08758 }
08759 mark_method_allowed(methods, id);
08760 }
08761 }
08762
08763
08764
08765
08766
08767
08768
08769
08770
08771
08772
08773
08774
08775
08776
08777
08778 static unsigned int parse_allowed_methods(struct sip_request *req)
08779 {
08780 char *allow = ast_strdupa(get_header(req, "Allow"));
08781 unsigned int allowed_methods = SIP_UNKNOWN;
08782
08783 if (ast_strlen_zero(allow)) {
08784
08785
08786
08787
08788 char *contact = ast_strdupa(get_header(req, "Contact"));
08789 char *methods = strstr(contact, ";methods=");
08790
08791 if (ast_strlen_zero(methods)) {
08792
08793
08794
08795
08796
08797
08798
08799
08800
08801
08802
08803 return UINT_MAX;
08804 }
08805 allow = ast_strip_quoted(methods + 9, "\"", "\"");
08806 }
08807 mark_parsed_methods(&allowed_methods, allow);
08808 return allowed_methods;
08809 }
08810
08811
08812
08813
08814
08815
08816
08817
08818
08819
08820 static unsigned int set_pvt_allowed_methods(struct sip_pvt *pvt, struct sip_request *req)
08821 {
08822 pvt->allowed_methods = parse_allowed_methods(req);
08823
08824 if (ast_test_flag(&pvt->flags[1], SIP_PAGE2_RPID_UPDATE)) {
08825 mark_method_allowed(&pvt->allowed_methods, SIP_UPDATE);
08826 }
08827 pvt->allowed_methods &= ~(pvt->disallowed_methods);
08828
08829 return pvt->allowed_methods;
08830 }
08831
08832
08833
08834 static void lws2sws(struct ast_str *data)
08835 {
08836 char *msgbuf = data->str;
08837 int len = ast_str_strlen(data);
08838 int h = 0, t = 0;
08839 int lws = 0;
08840
08841 for (; h < len;) {
08842
08843 if (msgbuf[h] == '\r') {
08844 h++;
08845 continue;
08846 }
08847
08848 if (msgbuf[h] == '\n') {
08849
08850 if (h + 1 == len)
08851 break;
08852
08853 if (msgbuf[h + 1] == ' ' || msgbuf[h + 1] == '\t') {
08854
08855 h++;
08856 continue;
08857 }
08858
08859 msgbuf[t++] = msgbuf[h++];
08860 lws = 0;
08861 continue;
08862 }
08863 if (msgbuf[h] == ' ' || msgbuf[h] == '\t') {
08864 if (lws) {
08865 h++;
08866 continue;
08867 }
08868 msgbuf[t++] = msgbuf[h++];
08869 lws = 1;
08870 continue;
08871 }
08872 msgbuf[t++] = msgbuf[h++];
08873 if (lws)
08874 lws = 0;
08875 }
08876 msgbuf[t] = '\0';
08877 data->used = t;
08878 }
08879
08880
08881
08882
08883 static int parse_request(struct sip_request *req)
08884 {
08885 char *c = req->data->str;
08886 ptrdiff_t *dst = req->header;
08887 int i = 0, lim = SIP_MAX_HEADERS - 1;
08888 unsigned int skipping_headers = 0;
08889 ptrdiff_t current_header_offset = 0;
08890 char *previous_header = "";
08891
08892 req->header[0] = 0;
08893 req->headers = -1;
08894 for (; *c; c++) {
08895 if (*c == '\r') {
08896 *c = '\0';
08897 } else if (*c == '\n') {
08898 *c = '\0';
08899 current_header_offset = (c + 1) - ast_str_buffer(req->data);
08900 previous_header = ast_str_buffer(req->data) + dst[i];
08901 if (skipping_headers) {
08902
08903
08904
08905 if (ast_strlen_zero(previous_header)) {
08906 skipping_headers = 0;
08907 }
08908 dst[i] = current_header_offset;
08909 continue;
08910 }
08911 if (sipdebug) {
08912 ast_debug(4, "%7s %2d [%3d]: %s\n",
08913 req->headers < 0 ? "Header" : "Body",
08914 i, (int) strlen(previous_header), previous_header);
08915 }
08916 if (ast_strlen_zero(previous_header) && req->headers < 0) {
08917 req->headers = i;
08918 dst = req->line;
08919 i = 0;
08920 lim = SIP_MAX_LINES - 1;
08921 } else {
08922 if (i++ == lim) {
08923
08924
08925
08926 if (req->headers != -1) {
08927 break;
08928 } else {
08929 req->headers = i;
08930 dst = req->line;
08931 i = 0;
08932 lim = SIP_MAX_LINES - 1;
08933 skipping_headers = 1;
08934 }
08935 }
08936 }
08937 dst[i] = current_header_offset;
08938 }
08939 }
08940
08941
08942
08943
08944
08945
08946 previous_header = ast_str_buffer(req->data) + dst[i];
08947 if ((i < lim) && !ast_strlen_zero(previous_header)) {
08948 if (sipdebug) {
08949 ast_debug(4, "%7s %2d [%3d]: %s\n",
08950 req->headers < 0 ? "Header" : "Body",
08951 i, (int) strlen(previous_header), previous_header );
08952 }
08953 i++;
08954 }
08955
08956
08957 if (req->headers >= 0) {
08958 req->lines = i;
08959 } else {
08960 req->headers = i;
08961 req->lines = 0;
08962
08963 req->line[0] = ast_str_strlen(req->data);
08964 }
08965
08966 if (*c) {
08967 ast_log(LOG_WARNING, "Too many lines, skipping <%s>\n", c);
08968 }
08969
08970
08971 return determine_firstline_parts(req);
08972 }
08973
08974
08975
08976
08977
08978
08979
08980
08981
08982 static int find_sdp(struct sip_request *req)
08983 {
08984 const char *content_type;
08985 const char *content_length;
08986 const char *search;
08987 char *boundary;
08988 unsigned int x;
08989 int boundaryisquoted = FALSE;
08990 int found_application_sdp = FALSE;
08991 int found_end_of_headers = FALSE;
08992
08993 content_length = get_header(req, "Content-Length");
08994
08995 if (!ast_strlen_zero(content_length)) {
08996 if (sscanf(content_length, "%30u", &x) != 1) {
08997 ast_log(LOG_WARNING, "Invalid Content-Length: %s\n", content_length);
08998 return 0;
08999 }
09000
09001
09002
09003 if (x == 0)
09004 return 0;
09005 }
09006
09007 content_type = get_header(req, "Content-Type");
09008
09009
09010 if (!strncasecmp(content_type, "application/sdp", 15)) {
09011 req->sdp_start = 0;
09012 req->sdp_count = req->lines;
09013 return req->lines ? 1 : 0;
09014 }
09015
09016
09017 if (strncasecmp(content_type, "multipart/mixed", 15))
09018 return 0;
09019
09020
09021 if ((search = strcasestr(content_type, ";boundary=")))
09022 search += 10;
09023 else if ((search = strcasestr(content_type, "; boundary=")))
09024 search += 11;
09025 else
09026 return 0;
09027
09028 if (ast_strlen_zero(search))
09029 return 0;
09030
09031
09032 if (*search == '\"') {
09033 search++;
09034 boundaryisquoted = TRUE;
09035 }
09036
09037
09038
09039 boundary = ast_strdupa(search - 2);
09040 boundary[0] = boundary[1] = '-';
09041
09042 if (boundaryisquoted)
09043 boundary[strlen(boundary) - 1] = '\0';
09044
09045
09046
09047
09048 for (x = 0; x < (req->lines); x++) {
09049 const char *line = REQ_OFFSET_TO_STR(req, line[x]);
09050 if (!strncasecmp(line, boundary, strlen(boundary))){
09051 if (found_application_sdp && found_end_of_headers) {
09052 req->sdp_count = (x - 1) - req->sdp_start;
09053 return 1;
09054 }
09055 found_application_sdp = FALSE;
09056 }
09057 if (!strcasecmp(line, "Content-Type: application/sdp"))
09058 found_application_sdp = TRUE;
09059
09060 if (ast_strlen_zero(line)) {
09061 if (found_application_sdp && !found_end_of_headers){
09062 req->sdp_start = x;
09063 found_end_of_headers = TRUE;
09064 }
09065 }
09066 }
09067 if (found_application_sdp && found_end_of_headers) {
09068 req->sdp_count = x - req->sdp_start;
09069 return TRUE;
09070 }
09071 return FALSE;
09072 }
09073
09074
09075 static void change_hold_state(struct sip_pvt *dialog, struct sip_request *req, int holdstate, int sendonly)
09076 {
09077 if (sip_cfg.notifyhold && (!holdstate || !ast_test_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD)))
09078 sip_peer_hold(dialog, holdstate);
09079 if (sip_cfg.callevents)
09080 manager_event(EVENT_FLAG_CALL, "Hold",
09081 "Status: %s\r\n"
09082 "Channel: %s\r\n"
09083 "Uniqueid: %s\r\n",
09084 holdstate ? "On" : "Off",
09085 dialog->owner->name,
09086 dialog->owner->uniqueid);
09087 append_history(dialog, holdstate ? "Hold" : "Unhold", "%s", ast_str_buffer(req->data));
09088 if (!holdstate) {
09089 ast_clear_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD);
09090 return;
09091 }
09092
09093
09094
09095 ast_clear_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD);
09096
09097 if (sendonly == 1)
09098 ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_ONEDIR);
09099 else if (sendonly == 2)
09100 ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_INACTIVE);
09101 else
09102 ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_ACTIVE);
09103 return;
09104 }
09105
09106
09107 static int get_ip_and_port_from_sdp(struct sip_request *req, const enum media_type media, struct ast_sockaddr *addr)
09108 {
09109 const char *m;
09110 const char *c;
09111 int miterator = req->sdp_start;
09112 int citerator = req->sdp_start;
09113 int x = 0;
09114 int numberofports;
09115 int len;
09116 int af;
09117 char proto[4], host[258] = "";
09118
09119 c = get_sdp_iterate(&citerator, req, "c");
09120 if (sscanf(c, "IN %3s %256s", proto, host) != 2) {
09121 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
09122
09123 }
09124
09125 for (m = get_sdp_iterate(&miterator, req, "m"); !ast_strlen_zero(m); m = get_sdp_iterate(&miterator, req, "m")) {
09126 if ((media == SDP_AUDIO && ((sscanf(m, "audio %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
09127 (sscanf(m, "audio %30u RTP/AVP %n", &x, &len) == 1 && len > 0))) ||
09128 (media == SDP_VIDEO && ((sscanf(m, "video %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
09129 (sscanf(m, "video %30u RTP/AVP %n", &x, &len) == 1 && len > 0)))) {
09130
09131
09132
09133
09134 c = get_sdp_iterate(&citerator, req, "c");
09135 if (!ast_strlen_zero(c)) {
09136 sscanf(c, "IN %3s %256s", proto, host);
09137 }
09138 break;
09139 }
09140 }
09141
09142 if (!strcmp("IP4", proto)) {
09143 af = AF_INET;
09144 } else if (!strcmp("IP6", proto)) {
09145 af = AF_INET6;
09146 } else {
09147 ast_log(LOG_WARNING, "Unknown protocol '%s'.\n", proto);
09148 return -1;
09149 }
09150
09151 if (ast_strlen_zero(host) || x == 0) {
09152 ast_log(LOG_WARNING, "Failed to read an alternate host or port in SDP. Expect %s problems\n", media == SDP_AUDIO ? "audio" : "video");
09153 return -1;
09154 }
09155
09156 if (ast_sockaddr_resolve_first_af(addr, host, 0, af)) {
09157 ast_log(LOG_WARNING, "Could not look up IP address of alternate hostname. Expect %s problems\n", media == SDP_AUDIO? "audio" : "video");
09158 return -1;
09159 }
09160
09161 return 0;
09162 }
09163
09164
09165
09166
09167
09168
09169
09170 static int sockaddr_is_null_or_any(const struct ast_sockaddr *addr)
09171 {
09172 return ast_sockaddr_isnull(addr) || ast_sockaddr_is_any(addr);
09173 }
09174
09175
09176
09177
09178
09179
09180 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action)
09181 {
09182
09183 int start = req->sdp_start;
09184 int next = start;
09185 int iterator = start;
09186
09187
09188 char type = '\0';
09189 const char *value = NULL;
09190 const char *m = NULL;
09191 const char *nextm = NULL;
09192 int len = -1;
09193
09194
09195 struct ast_sockaddr sessionsa;
09196 struct ast_sockaddr audiosa;
09197 struct ast_sockaddr videosa;
09198 struct ast_sockaddr textsa;
09199 struct ast_sockaddr imagesa;
09200 struct ast_sockaddr *sa = NULL;
09201 struct ast_sockaddr *vsa = NULL;
09202 struct ast_sockaddr *tsa = NULL;
09203 struct ast_sockaddr *isa = NULL;
09204 int portno = -1;
09205 int vportno = -1;
09206 int tportno = -1;
09207 int udptlportno = -1;
09208
09209
09210 format_t peercapability = 0, vpeercapability = 0, tpeercapability = 0;
09211 int peernoncodeccapability = 0, vpeernoncodeccapability = 0, tpeernoncodeccapability = 0;
09212
09213 struct ast_rtp_codecs newaudiortp, newvideortp, newtextrtp;
09214 format_t newjointcapability;
09215 format_t newpeercapability;
09216 int newnoncodeccapability;
09217
09218 const char *codecs;
09219 int codec;
09220
09221
09222 int secure_audio = FALSE;
09223 int secure_video = FALSE;
09224
09225
09226 int sendonly = -1;
09227 int numberofports;
09228 int numberofmediastreams = 0;
09229 int last_rtpmap_codec = 0;
09230 int red_data_pt[10];
09231 int red_num_gen = 0;
09232 char red_fmtp[100] = "empty";
09233 int debug = sip_debug_test_pvt(p);
09234
09235
09236 char buf[SIPBUFSIZE];
09237
09238
09239
09240 if (!p->rtp) {
09241 ast_log(LOG_ERROR, "Got SDP but have no RTP session allocated.\n");
09242 return -1;
09243 }
09244
09245
09246 ast_rtp_codecs_payloads_clear(&newaudiortp, NULL);
09247 ast_rtp_codecs_payloads_clear(&newvideortp, NULL);
09248 ast_rtp_codecs_payloads_clear(&newtextrtp, NULL);
09249
09250
09251 p->lastrtprx = p->lastrtptx = time(NULL);
09252
09253 memset(p->offered_media, 0, sizeof(p->offered_media));
09254
09255
09256 p->novideo = TRUE;
09257 p->notext = TRUE;
09258
09259
09260 nextm = get_sdp_iterate(&next, req, "m");
09261 if (ast_strlen_zero(nextm)) {
09262 ast_log(LOG_WARNING, "Insufficient information for SDP (m= not found)\n");
09263 return -1;
09264 }
09265
09266
09267 while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
09268 int processed = FALSE;
09269 switch (type) {
09270 case 'o':
09271
09272
09273
09274 if (!process_sdp_o(value, p)) {
09275 return (p->session_modify == FALSE) ? 0 : -1;
09276 }
09277 processed = TRUE;
09278 break;
09279 case 'c':
09280 if (process_sdp_c(value, &sessionsa)) {
09281 processed = TRUE;
09282 sa = &sessionsa;
09283 vsa = sa;
09284 tsa = sa;
09285 isa = sa;
09286 }
09287 break;
09288 case 'a':
09289 if (process_sdp_a_sendonly(value, &sendonly)) {
09290 processed = TRUE;
09291 }
09292 else if (process_sdp_a_audio(value, p, &newaudiortp, &last_rtpmap_codec))
09293 processed = TRUE;
09294 else if (process_sdp_a_video(value, p, &newvideortp, &last_rtpmap_codec))
09295 processed = TRUE;
09296 else if (process_sdp_a_text(value, p, &newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec))
09297 processed = TRUE;
09298 else if (process_sdp_a_image(value, p))
09299 processed = TRUE;
09300 break;
09301 }
09302
09303 ast_debug(3, "Processing session-level SDP %c=%s... %s\n", type, value, (processed == TRUE)? "OK." : "UNSUPPORTED OR FAILED.");
09304 }
09305
09306
09307 while (!ast_strlen_zero(nextm)) {
09308 int audio = FALSE;
09309 int video = FALSE;
09310 int image = FALSE;
09311 int text = FALSE;
09312 int processed_crypto = FALSE;
09313 char protocol[5] = {0,};
09314 int x;
09315
09316 numberofports = 0;
09317 len = -1;
09318 start = next;
09319 m = nextm;
09320 iterator = next;
09321 nextm = get_sdp_iterate(&next, req, "m");
09322
09323
09324 if (strncmp(m, "audio ", 6) == 0) {
09325 if ((sscanf(m, "audio %30u/%30u RTP/%4s %n", &x, &numberofports, protocol, &len) == 3 && len > 0) ||
09326 (sscanf(m, "audio %30u RTP/%4s %n", &x, protocol, &len) == 2 && len > 0)) {
09327 if (x == 0) {
09328 ast_log(LOG_WARNING, "Ignoring audio media offer because port number is zero\n");
09329 continue;
09330 }
09331
09332
09333 if (numberofports > 1) {
09334 ast_log(LOG_WARNING, "%d ports offered for audio media, not supported by Asterisk. Will try anyway...\n", numberofports);
09335 }
09336
09337 if (!strcmp(protocol, "SAVP")) {
09338 secure_audio = 1;
09339 } else if (strcmp(protocol, "AVP")) {
09340 ast_log(LOG_WARNING, "Unknown RTP profile in audio offer: %s\n", m);
09341 continue;
09342 }
09343
09344 if (p->offered_media[SDP_AUDIO].order_offered) {
09345 ast_log(LOG_WARNING, "Rejecting non-primary audio stream: %s\n", m);
09346 return -1;
09347 }
09348
09349 audio = TRUE;
09350 p->offered_media[SDP_AUDIO].order_offered = ++numberofmediastreams;
09351 portno = x;
09352
09353
09354 codecs = m + len;
09355 ast_copy_string(p->offered_media[SDP_AUDIO].codecs, codecs, sizeof(p->offered_media[SDP_AUDIO].codecs));
09356 for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
09357 if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
09358 ast_log(LOG_WARNING, "Invalid syntax in RTP audio format list: %s\n", codecs);
09359 return -1;
09360 }
09361 if (debug) {
09362 ast_verbose("Found RTP audio format %d\n", codec);
09363 }
09364
09365 ast_rtp_codecs_payloads_set_m_type(&newaudiortp, NULL, codec);
09366 }
09367 } else {
09368 ast_log(LOG_WARNING, "Rejecting audio media offer due to invalid or unsupported syntax: %s\n", m);
09369 return -1;
09370 }
09371 }
09372
09373 else if (strncmp(m, "video ", 6) == 0) {
09374 if ((sscanf(m, "video %30u/%30u RTP/%4s %n", &x, &numberofports, protocol, &len) == 3 && len > 0) ||
09375 (sscanf(m, "video %30u RTP/%4s %n", &x, protocol, &len) == 2 && len > 0)) {
09376 if (x == 0) {
09377 ast_log(LOG_WARNING, "Ignoring video media offer because port number is zero\n");
09378 continue;
09379 }
09380
09381
09382 if (numberofports > 1) {
09383 ast_log(LOG_WARNING, "%d ports offered for video media, not supported by Asterisk. Will try anyway...\n", numberofports);
09384 }
09385
09386 if (!strcmp(protocol, "SAVP")) {
09387 secure_video = 1;
09388 } else if (strcmp(protocol, "AVP")) {
09389 ast_log(LOG_WARNING, "Unknown RTP profile in video offer: %s\n", m);
09390 continue;
09391 }
09392
09393 if (p->offered_media[SDP_VIDEO].order_offered) {
09394 ast_log(LOG_WARNING, "Rejecting non-primary video stream: %s\n", m);
09395 return -1;
09396 }
09397
09398 video = TRUE;
09399 p->novideo = FALSE;
09400 p->offered_media[SDP_VIDEO].order_offered = ++numberofmediastreams;
09401 vportno = x;
09402
09403
09404 codecs = m + len;
09405 ast_copy_string(p->offered_media[SDP_VIDEO].codecs, codecs, sizeof(p->offered_media[SDP_VIDEO].codecs));
09406 for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
09407 if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
09408 ast_log(LOG_WARNING, "Invalid syntax in RTP video format list: %s\n", codecs);
09409 return -1;
09410 }
09411 if (debug) {
09412 ast_verbose("Found RTP video format %d\n", codec);
09413 }
09414 ast_rtp_codecs_payloads_set_m_type(&newvideortp, NULL, codec);
09415 }
09416 } else {
09417 ast_log(LOG_WARNING, "Rejecting video media offer due to invalid or unsupported syntax: %s\n", m);
09418 return -1;
09419 }
09420 }
09421
09422 else if (strncmp(m, "text ", 5) == 0) {
09423 if ((sscanf(m, "text %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
09424 (sscanf(m, "text %30u RTP/AVP %n", &x, &len) == 1 && len > 0)) {
09425 if (x == 0) {
09426 ast_log(LOG_WARNING, "Ignoring text media offer because port number is zero\n");
09427 continue;
09428 }
09429
09430
09431 if (numberofports > 1) {
09432 ast_log(LOG_WARNING, "%d ports offered for text media, not supported by Asterisk. Will try anyway...\n", numberofports);
09433 }
09434
09435 if (p->offered_media[SDP_TEXT].order_offered) {
09436 ast_log(LOG_WARNING, "Rejecting non-primary text stream: %s\n", m);
09437 return -1;
09438 }
09439
09440 text = TRUE;
09441 p->notext = FALSE;
09442 p->offered_media[SDP_TEXT].order_offered = ++numberofmediastreams;
09443 tportno = x;
09444
09445
09446 codecs = m + len;
09447 ast_copy_string(p->offered_media[SDP_TEXT].codecs, codecs, sizeof(p->offered_media[SDP_TEXT].codecs));
09448 for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
09449 if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
09450 ast_log(LOG_WARNING, "Invalid syntax in RTP video format list: %s\n", codecs);
09451 return -1;
09452 }
09453 if (debug) {
09454 ast_verbose("Found RTP text format %d\n", codec);
09455 }
09456 ast_rtp_codecs_payloads_set_m_type(&newtextrtp, NULL, codec);
09457 }
09458 } else {
09459 ast_log(LOG_WARNING, "Rejecting text media offer due to invalid or unsupported syntax: %s\n", m);
09460 return -1;
09461 }
09462 }
09463
09464 else if (strncmp(m, "image ", 6) == 0) {
09465 if (((sscanf(m, "image %30u udptl t38%n", &x, &len) == 1 && len > 0) ||
09466 (sscanf(m, "image %30u UDPTL t38%n", &x, &len) == 1 && len > 0))) {
09467 if (x == 0) {
09468 ast_log(LOG_WARNING, "Ignoring image media offer because port number is zero\n");
09469 continue;
09470 }
09471
09472 if (initialize_udptl(p)) {
09473 ast_log(LOG_WARNING, "Rejecting offer with image stream due to UDPTL initialization failure\n");
09474 return -1;
09475 }
09476
09477 if (p->offered_media[SDP_IMAGE].order_offered) {
09478 ast_log(LOG_WARNING, "Rejecting non-primary image stream: %s\n", m);
09479 return -1;
09480 }
09481
09482 image = TRUE;
09483 if (debug) {
09484 ast_verbose("Got T.38 offer in SDP in dialog %s\n", p->callid);
09485 }
09486
09487 p->offered_media[SDP_IMAGE].order_offered = ++numberofmediastreams;
09488 udptlportno = x;
09489
09490 if (p->t38.state != T38_ENABLED) {
09491 memset(&p->t38.their_parms, 0, sizeof(p->t38.their_parms));
09492
09493
09494
09495 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
09496 }
09497 } else {
09498 ast_log(LOG_WARNING, "Rejecting image media offer due to invalid or unsupported syntax: %s\n", m);
09499 return -1;
09500 }
09501 } else {
09502 ast_log(LOG_WARNING, "Unsupported top-level media type in offer: %s\n", m);
09503 continue;
09504 }
09505
09506
09507 while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
09508 int processed = FALSE;
09509
09510 switch (type) {
09511 case 'c':
09512 if (audio) {
09513 if (process_sdp_c(value, &audiosa)) {
09514 processed = TRUE;
09515 sa = &audiosa;
09516 }
09517 } else if (video) {
09518 if (process_sdp_c(value, &videosa)) {
09519 processed = TRUE;
09520 vsa = &videosa;
09521 }
09522 } else if (text) {
09523 if (process_sdp_c(value, &textsa)) {
09524 processed = TRUE;
09525 tsa = &textsa;
09526 }
09527 } else if (image) {
09528 if (process_sdp_c(value, &imagesa)) {
09529 processed = TRUE;
09530 isa = &imagesa;
09531 }
09532 }
09533 break;
09534 case 'a':
09535
09536 if (audio) {
09537 if (process_sdp_a_sendonly(value, &sendonly)) {
09538 processed = TRUE;
09539 } else if (!processed_crypto && process_crypto(p, p->rtp, &p->srtp, value)) {
09540 processed_crypto = TRUE;
09541 processed = TRUE;
09542 } else if (process_sdp_a_audio(value, p, &newaudiortp, &last_rtpmap_codec)) {
09543 processed = TRUE;
09544 }
09545 }
09546
09547 else if (video) {
09548 if (!processed_crypto && process_crypto(p, p->vrtp, &p->vsrtp, value)) {
09549 processed_crypto = TRUE;
09550 processed = TRUE;
09551 } else if (process_sdp_a_video(value, p, &newvideortp, &last_rtpmap_codec)) {
09552 processed = TRUE;
09553 }
09554 }
09555
09556 else if (text) {
09557 if (process_sdp_a_text(value, p, &newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec)) {
09558 processed = TRUE;
09559 } else if (!processed_crypto && process_crypto(p, p->trtp, &p->tsrtp, value)) {
09560 processed_crypto = TRUE;
09561 processed = TRUE;
09562 }
09563 }
09564
09565 else if (image) {
09566 if (process_sdp_a_image(value, p))
09567 processed = TRUE;
09568 }
09569 break;
09570 }
09571
09572 ast_debug(3, "Processing media-level (%s) SDP %c=%s... %s\n",
09573 (audio == TRUE)? "audio" : (video == TRUE)? "video" : (text == TRUE)? "text" : "image",
09574 type, value,
09575 (processed == TRUE)? "OK." : "UNSUPPORTED OR FAILED.");
09576 }
09577 }
09578
09579
09580 if (!sa && !vsa && !tsa && !isa) {
09581 ast_log(LOG_WARNING, "Insufficient information in SDP (c=)...\n");
09582 return -1;
09583 }
09584
09585 if ((portno == -1) &&
09586 (vportno == -1) &&
09587 (tportno == -1) &&
09588 (udptlportno == -1)) {
09589 ast_log(LOG_WARNING, "Failing due to no acceptable offer found\n");
09590 return -1;
09591 }
09592
09593 if (secure_audio && !(p->srtp && (ast_test_flag(p->srtp, SRTP_CRYPTO_OFFER_OK)))) {
09594 ast_log(LOG_WARNING, "Can't provide secure audio requested in SDP offer\n");
09595 return -1;
09596 }
09597
09598 if (!secure_audio && p->srtp) {
09599 ast_log(LOG_WARNING, "We are requesting SRTP for audio, but they responded without it!\n");
09600 return -1;
09601 }
09602
09603 if (secure_video && !(p->vsrtp && (ast_test_flag(p->vsrtp, SRTP_CRYPTO_OFFER_OK)))) {
09604 ast_log(LOG_WARNING, "Can't provide secure video requested in SDP offer\n");
09605 return -1;
09606 }
09607
09608 if (!p->novideo && !secure_video && p->vsrtp) {
09609 ast_log(LOG_WARNING, "We are requesting SRTP for video, but they responded without it!\n");
09610 return -1;
09611 }
09612
09613 if (!(secure_audio || secure_video) && ast_test_flag(&p->flags[1], SIP_PAGE2_USE_SRTP)) {
09614 ast_log(LOG_WARNING, "Matched device setup to use SRTP, but request was not!\n");
09615 return -1;
09616 }
09617
09618 if (udptlportno == -1) {
09619 change_t38_state(p, T38_DISABLED);
09620 }
09621
09622
09623 ast_rtp_codecs_payload_formats(&newaudiortp, &peercapability, &peernoncodeccapability);
09624 ast_rtp_codecs_payload_formats(&newvideortp, &vpeercapability, &vpeernoncodeccapability);
09625 ast_rtp_codecs_payload_formats(&newtextrtp, &tpeercapability, &tpeernoncodeccapability);
09626
09627 newjointcapability = p->capability & (peercapability | vpeercapability | tpeercapability);
09628 newpeercapability = (peercapability | vpeercapability | tpeercapability);
09629 newnoncodeccapability = p->noncodeccapability & peernoncodeccapability;
09630
09631 if (debug) {
09632
09633 char s1[SIPBUFSIZE], s2[SIPBUFSIZE], s3[SIPBUFSIZE], s4[SIPBUFSIZE], s5[SIPBUFSIZE];
09634
09635 ast_verbose("Capabilities: us - %s, peer - audio=%s/video=%s/text=%s, combined - %s\n",
09636 ast_getformatname_multiple(s1, SIPBUFSIZE, p->capability),
09637 ast_getformatname_multiple(s2, SIPBUFSIZE, peercapability),
09638 ast_getformatname_multiple(s3, SIPBUFSIZE, vpeercapability),
09639 ast_getformatname_multiple(s4, SIPBUFSIZE, tpeercapability),
09640 ast_getformatname_multiple(s5, SIPBUFSIZE, newjointcapability));
09641 }
09642 if (debug) {
09643 struct ast_str *s1 = ast_str_alloca(SIPBUFSIZE);
09644 struct ast_str *s2 = ast_str_alloca(SIPBUFSIZE);
09645 struct ast_str *s3 = ast_str_alloca(SIPBUFSIZE);
09646
09647 ast_verbose("Non-codec capabilities (dtmf): us - %s, peer - %s, combined - %s\n",
09648 ast_rtp_lookup_mime_multiple2(s1, p->noncodeccapability, 0, 0),
09649 ast_rtp_lookup_mime_multiple2(s2, peernoncodeccapability, 0, 0),
09650 ast_rtp_lookup_mime_multiple2(s3, newnoncodeccapability, 0, 0));
09651 }
09652 if (!newjointcapability && udptlportno == -1) {
09653 ast_log(LOG_NOTICE, "No compatible codecs, not accepting this offer!\n");
09654
09655 return -1;
09656 }
09657
09658 if (portno != -1 || vportno != -1 || tportno != -1) {
09659
09660
09661 p->jointcapability = newjointcapability;
09662 p->peercapability = newpeercapability;
09663 p->jointnoncodeccapability = newnoncodeccapability;
09664
09665
09666 if (ast_test_flag(&p->flags[1], SIP_PAGE2_PREFERRED_CODEC)) {
09667 p->jointcapability = ast_codec_choose(&p->prefs, p->jointcapability, 1);
09668 }
09669 }
09670
09671
09672 if (p->rtp) {
09673 if (portno > 0) {
09674 ast_sockaddr_set_port(sa, portno);
09675 ast_rtp_instance_set_remote_address(p->rtp, sa);
09676 if (debug) {
09677 ast_verbose("Peer audio RTP is at port %s\n",
09678 ast_sockaddr_stringify(sa));
09679 }
09680
09681 ast_rtp_codecs_payloads_copy(&newaudiortp, ast_rtp_instance_get_codecs(p->rtp), p->rtp);
09682
09683
09684 ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_RTCP, 1);
09685
09686 if (p->owner) {
09687 ast_channel_set_fd(p->owner, 1, ast_rtp_instance_fd(p->rtp, 1));
09688 }
09689
09690 if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) {
09691 ast_clear_flag(&p->flags[0], SIP_DTMF);
09692 if (newnoncodeccapability & AST_RTP_DTMF) {
09693
09694 ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
09695
09696 ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF, 1);
09697 ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
09698 } else {
09699 ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
09700 }
09701 }
09702 } else if (udptlportno > 0) {
09703 if (debug)
09704 ast_verbose("Got T.38 Re-invite without audio. Keeping RTP active during T.38 session.\n");
09705
09706 if (p->owner) {
09707 ast_channel_set_fd(p->owner, 1, -1);
09708 }
09709
09710 ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_RTCP, 0);
09711 } else {
09712 ast_rtp_instance_stop(p->rtp);
09713 if (debug)
09714 ast_verbose("Peer doesn't provide audio\n");
09715 }
09716 }
09717
09718
09719 if (p->vrtp) {
09720 if (vportno > 0) {
09721 ast_sockaddr_set_port(vsa, vportno);
09722 ast_rtp_instance_set_remote_address(p->vrtp, vsa);
09723 if (debug) {
09724 ast_verbose("Peer video RTP is at port %s\n",
09725 ast_sockaddr_stringify(vsa));
09726 }
09727 ast_rtp_codecs_payloads_copy(&newvideortp, ast_rtp_instance_get_codecs(p->vrtp), p->vrtp);
09728 } else {
09729 ast_rtp_instance_stop(p->vrtp);
09730 if (debug)
09731 ast_verbose("Peer doesn't provide video\n");
09732 }
09733 }
09734
09735
09736 if (p->trtp) {
09737 if (tportno > 0) {
09738 ast_sockaddr_set_port(tsa, tportno);
09739 ast_rtp_instance_set_remote_address(p->trtp, tsa);
09740 if (debug) {
09741 ast_verbose("Peer T.140 RTP is at port %s\n",
09742 ast_sockaddr_stringify(tsa));
09743 }
09744 if ((p->jointcapability & AST_FORMAT_T140RED)) {
09745 p->red = 1;
09746 ast_rtp_red_init(p->trtp, 300, red_data_pt, 2);
09747 } else {
09748 p->red = 0;
09749 }
09750 ast_rtp_codecs_payloads_copy(&newtextrtp, ast_rtp_instance_get_codecs(p->trtp), p->trtp);
09751 } else {
09752 ast_rtp_instance_stop(p->trtp);
09753 if (debug)
09754 ast_verbose("Peer doesn't provide T.140\n");
09755 }
09756 }
09757
09758
09759 if (p->udptl) {
09760 if (udptlportno > 0) {
09761 if (ast_test_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP) && ast_test_flag(&p->flags[1], SIP_PAGE2_UDPTL_DESTINATION)) {
09762 ast_rtp_instance_get_remote_address(p->rtp, isa);
09763 if (!ast_sockaddr_isnull(isa) && debug) {
09764 ast_debug(1, "Peer T.38 UDPTL is set behind NAT and with destination, destination address now %s\n", ast_sockaddr_stringify(isa));
09765 }
09766 }
09767 ast_sockaddr_set_port(isa, udptlportno);
09768 ast_udptl_set_peer(p->udptl, isa);
09769 if (debug)
09770 ast_debug(1,"Peer T.38 UDPTL is at port %s\n", ast_sockaddr_stringify(isa));
09771
09772
09773 if (!ast_udptl_get_far_max_datagram(p->udptl)) {
09774
09775 ast_udptl_set_far_max_datagram(p->udptl, 0);
09776 }
09777
09778
09779 if ((t38action == SDP_T38_ACCEPT) &&
09780 (p->t38.state == T38_LOCAL_REINVITE)) {
09781 change_t38_state(p, T38_ENABLED);
09782 } else if ((t38action == SDP_T38_INITIATE) &&
09783 p->owner && p->lastinvite) {
09784 change_t38_state(p, T38_PEER_REINVITE);
09785
09786 if (ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_T38)) {
09787 ast_channel_lock(p->owner);
09788 if (strcmp(p->owner->exten, "fax")) {
09789 const char *target_context = S_OR(p->owner->macrocontext, p->owner->context);
09790 ast_channel_unlock(p->owner);
09791 if (ast_exists_extension(p->owner, target_context, "fax", 1,
09792 S_COR(p->owner->caller.id.number.valid, p->owner->caller.id.number.str, NULL))) {
09793 ast_verbose(VERBOSE_PREFIX_2 "Redirecting '%s' to fax extension due to peer T.38 re-INVITE\n", p->owner->name);
09794 pbx_builtin_setvar_helper(p->owner, "FAXEXTEN", p->owner->exten);
09795 if (ast_async_goto(p->owner, target_context, "fax", 1)) {
09796 ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", p->owner->name, target_context);
09797 }
09798 } else {
09799 ast_log(LOG_NOTICE, "T.38 re-INVITE detected but no fax extension\n");
09800 }
09801 } else {
09802 ast_channel_unlock(p->owner);
09803 }
09804 }
09805 }
09806 } else {
09807 change_t38_state(p, T38_DISABLED);
09808 ast_udptl_stop(p->udptl);
09809 if (debug)
09810 ast_debug(1, "Peer doesn't provide T.38 UDPTL\n");
09811 }
09812 }
09813
09814 if ((portno == -1) && (p->t38.state != T38_DISABLED)) {
09815 ast_debug(3, "Have T.38 but no audio, accepting offer anyway\n");
09816 return 0;
09817 }
09818
09819
09820 ast_debug(2, "We're settling with these formats: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, p->jointcapability));
09821
09822 if (!p->owner)
09823 return 0;
09824
09825 ast_debug(4, "We have an owner, now see if we need to change this call\n");
09826
09827 if (!(p->owner->nativeformats & p->jointcapability) && (p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
09828 if (debug) {
09829 char s1[SIPBUFSIZE], s2[SIPBUFSIZE];
09830 ast_debug(1, "Oooh, we need to change our audio formats since our peer supports only %s and not %s\n",
09831 ast_getformatname_multiple(s1, SIPBUFSIZE, p->jointcapability),
09832 ast_getformatname_multiple(s2, SIPBUFSIZE, p->owner->nativeformats));
09833 }
09834 p->owner->nativeformats = ast_codec_choose(&p->prefs, p->jointcapability, 1) | (p->capability & vpeercapability) | (p->capability & tpeercapability);
09835 ast_set_read_format(p->owner, p->owner->readformat);
09836 ast_set_write_format(p->owner, p->owner->writeformat);
09837 }
09838
09839 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)) {
09840 ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
09841
09842 ast_queue_frame(p->owner, &ast_null_frame);
09843 change_hold_state(p, req, FALSE, sendonly);
09844 } 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)) {
09845 ast_queue_control_data(p->owner, AST_CONTROL_HOLD,
09846 S_OR(p->mohsuggest, NULL),
09847 !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
09848 if (sendonly)
09849 ast_rtp_instance_stop(p->rtp);
09850
09851
09852 ast_queue_frame(p->owner, &ast_null_frame);
09853 change_hold_state(p, req, TRUE, sendonly);
09854 }
09855
09856 return 0;
09857 }
09858
09859 static int process_sdp_o(const char *o, struct sip_pvt *p)
09860 {
09861 char *o_copy;
09862 char *token;
09863 int64_t rua_version;
09864
09865
09866
09867
09868
09869
09870
09871
09872
09873
09874 p->session_modify = TRUE;
09875
09876 if (ast_strlen_zero(o)) {
09877 ast_log(LOG_WARNING, "SDP syntax error. SDP without an o= line\n");
09878 return FALSE;
09879 }
09880
09881 o_copy = ast_strdupa(o);
09882 token = strsep(&o_copy, " ");
09883 if (!o_copy) {
09884 ast_log(LOG_WARNING, "SDP syntax error in o= line username\n");
09885 return FALSE;
09886 }
09887 token = strsep(&o_copy, " ");
09888 if (!o_copy) {
09889 ast_log(LOG_WARNING, "SDP syntax error in o= line session-id\n");
09890 return FALSE;
09891 }
09892 token = strsep(&o_copy, " ");
09893 if (!o_copy) {
09894 ast_log(LOG_WARNING, "SDP syntax error in o= line\n");
09895 return FALSE;
09896 }
09897 if (!sscanf(token, "%30" SCNd64, &rua_version)) {
09898 ast_log(LOG_WARNING, "SDP syntax error in o= line version\n");
09899 return FALSE;
09900 }
09901
09902
09903
09904
09905
09906
09907
09908
09909
09910
09911
09912
09913
09914
09915
09916
09917
09918
09919
09920 if (ast_test_flag(&p->flags[1], SIP_PAGE2_IGNORESDPVERSION) ||
09921 (p->sessionversion_remote < 0) ||
09922 (p->sessionversion_remote < rua_version)) {
09923 p->sessionversion_remote = rua_version;
09924 } else {
09925 if (p->t38.state == T38_LOCAL_REINVITE) {
09926 p->sessionversion_remote = rua_version;
09927 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);
09928 } else {
09929 p->session_modify = FALSE;
09930 ast_debug(2, "Call %s responded to our reinvite without changing SDP version; ignoring SDP.\n", p->callid);
09931 return FALSE;
09932 }
09933 }
09934
09935 return TRUE;
09936 }
09937
09938 static int process_sdp_c(const char *c, struct ast_sockaddr *addr)
09939 {
09940 char proto[4], host[258];
09941 int af;
09942
09943
09944 if (sscanf(c, "IN %3s %255s", proto, host) == 2) {
09945 if (!strcmp("IP4", proto)) {
09946 af = AF_INET;
09947 } else if (!strcmp("IP6", proto)) {
09948 af = AF_INET6;
09949 } else {
09950 ast_log(LOG_WARNING, "Unknown protocol '%s'.\n", proto);
09951 return FALSE;
09952 }
09953 if (ast_sockaddr_resolve_first_af(addr, host, 0, af)) {
09954 ast_log(LOG_WARNING, "Unable to lookup RTP Audio host in c= line, '%s'\n", c);
09955 return FALSE;
09956 }
09957 return TRUE;
09958 } else {
09959 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
09960 return FALSE;
09961 }
09962 return FALSE;
09963 }
09964
09965 static int process_sdp_a_sendonly(const char *a, int *sendonly)
09966 {
09967 int found = FALSE;
09968
09969 if (!strcasecmp(a, "sendonly")) {
09970 if (*sendonly == -1)
09971 *sendonly = 1;
09972 found = TRUE;
09973 } else if (!strcasecmp(a, "inactive")) {
09974 if (*sendonly == -1)
09975 *sendonly = 2;
09976 found = TRUE;
09977 } else if (!strcasecmp(a, "sendrecv")) {
09978 if (*sendonly == -1)
09979 *sendonly = 0;
09980 found = TRUE;
09981 }
09982 return found;
09983 }
09984
09985 static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newaudiortp, int *last_rtpmap_codec)
09986 {
09987 int found = FALSE;
09988 int codec;
09989 char mimeSubtype[128];
09990 char fmtp_string[64];
09991 unsigned int sample_rate;
09992 int debug = sip_debug_test_pvt(p);
09993
09994 if (!strncasecmp(a, "ptime", 5)) {
09995 char *tmp = strrchr(a, ':');
09996 long int framing = 0;
09997 if (tmp) {
09998 tmp++;
09999 framing = strtol(tmp, NULL, 10);
10000 if (framing == LONG_MIN || framing == LONG_MAX) {
10001 framing = 0;
10002 ast_debug(1, "Can't read framing from SDP: %s\n", a);
10003 }
10004 }
10005 if (framing && p->autoframing) {
10006 struct ast_codec_pref *pref = &ast_rtp_instance_get_codecs(p->rtp)->pref;
10007 int codec_n;
10008 for (codec_n = 0; codec_n < AST_RTP_MAX_PT; codec_n++) {
10009 struct ast_rtp_payload_type format = ast_rtp_codecs_payload_lookup(ast_rtp_instance_get_codecs(p->rtp), codec_n);
10010 if (!format.asterisk_format || !format.code)
10011 continue;
10012 ast_debug(1, "Setting framing for %s to %ld\n", ast_getformatname(format.code), framing);
10013 ast_codec_pref_setsize(pref, format.code, framing);
10014 }
10015 ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(p->rtp), p->rtp, pref);
10016 }
10017 found = TRUE;
10018 } else if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
10019
10020 if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
10021 if (!(ast_rtp_codecs_payloads_set_rtpmap_type_rate(newaudiortp, NULL, codec, "audio", mimeSubtype,
10022 ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0, sample_rate))) {
10023 if (debug)
10024 ast_verbose("Found audio description format %s for ID %d\n", mimeSubtype, codec);
10025
10026 (*last_rtpmap_codec)++;
10027 found = TRUE;
10028 } else {
10029 ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
10030 if (debug)
10031 ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
10032 }
10033 } else {
10034 if (debug)
10035 ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
10036 }
10037 } else if (sscanf(a, "fmtp: %30u %63s", &codec, fmtp_string) == 2) {
10038 struct ast_rtp_payload_type payload;
10039
10040 payload = ast_rtp_codecs_payload_lookup(newaudiortp, codec);
10041 if (payload.code && payload.asterisk_format) {
10042 unsigned int bit_rate;
10043
10044 switch (payload.code) {
10045 case AST_FORMAT_SIREN7:
10046 if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
10047 if (bit_rate != 32000) {
10048 ast_log(LOG_WARNING, "Got Siren7 offer at %d bps, but only 32000 bps supported; ignoring.\n", bit_rate);
10049 ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
10050 } else {
10051 found = TRUE;
10052 }
10053 }
10054 break;
10055 case AST_FORMAT_SIREN14:
10056 if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
10057 if (bit_rate != 48000) {
10058 ast_log(LOG_WARNING, "Got Siren14 offer at %d bps, but only 48000 bps supported; ignoring.\n", bit_rate);
10059 ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
10060 } else {
10061 found = TRUE;
10062 }
10063 }
10064 break;
10065 case AST_FORMAT_G719:
10066 if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
10067 if (bit_rate != 64000) {
10068 ast_log(LOG_WARNING, "Got G.719 offer at %d bps, but only 64000 bps supported; ignoring.\n", bit_rate);
10069 ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
10070 } else {
10071 found = TRUE;
10072 }
10073 }
10074 }
10075 }
10076 }
10077
10078 return found;
10079 }
10080
10081 static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newvideortp, int *last_rtpmap_codec)
10082 {
10083 int found = FALSE;
10084 int codec;
10085 char mimeSubtype[128];
10086 unsigned int sample_rate;
10087 int debug = sip_debug_test_pvt(p);
10088
10089 if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
10090
10091 if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
10092
10093 if (!strncasecmp(mimeSubtype, "H26", 3) || !strncasecmp(mimeSubtype, "MP4", 3)) {
10094 if (!(ast_rtp_codecs_payloads_set_rtpmap_type_rate(newvideortp, NULL, codec, "video", mimeSubtype, 0, sample_rate))) {
10095 if (debug)
10096 ast_verbose("Found video description format %s for ID %d\n", mimeSubtype, codec);
10097
10098 (*last_rtpmap_codec)++;
10099 found = TRUE;
10100 } else {
10101 ast_rtp_codecs_payloads_unset(newvideortp, NULL, codec);
10102 if (debug)
10103 ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
10104 }
10105 }
10106 } else {
10107 if (debug)
10108 ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
10109 }
10110 }
10111
10112 return found;
10113 }
10114
10115 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)
10116 {
10117 int found = FALSE;
10118 int codec;
10119 char mimeSubtype[128];
10120 unsigned int sample_rate;
10121 char *red_cp;
10122 int debug = sip_debug_test_pvt(p);
10123
10124 if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
10125
10126 if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
10127 if (!strncasecmp(mimeSubtype, "T140", 4)) {
10128 if (p->trtp) {
10129
10130 ast_rtp_codecs_payloads_set_rtpmap_type_rate(newtextrtp, NULL, codec, "text", mimeSubtype, 0, sample_rate);
10131 found = TRUE;
10132 }
10133 } else if (!strncasecmp(mimeSubtype, "RED", 3)) {
10134 if (p->trtp) {
10135 ast_rtp_codecs_payloads_set_rtpmap_type_rate(newtextrtp, NULL, codec, "text", mimeSubtype, 0, sample_rate);
10136 sprintf(red_fmtp, "fmtp:%d ", codec);
10137 if (debug)
10138 ast_verbose("RED submimetype has payload type: %d\n", codec);
10139 found = TRUE;
10140 }
10141 }
10142 } else {
10143 if (debug)
10144 ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
10145 }
10146 } else if (!strncmp(a, red_fmtp, strlen(red_fmtp))) {
10147
10148 red_cp = &red_fmtp[strlen(red_fmtp)];
10149 strncpy(red_fmtp, a, 100);
10150
10151 sscanf(red_cp, "%30u", &red_data_pt[*red_num_gen]);
10152 red_cp = strtok(red_cp, "/");
10153 while (red_cp && (*red_num_gen)++ < AST_RED_MAX_GENERATION) {
10154 sscanf(red_cp, "%30u", &red_data_pt[*red_num_gen]);
10155 red_cp = strtok(NULL, "/");
10156 }
10157 red_cp = red_fmtp;
10158 found = TRUE;
10159 }
10160
10161 return found;
10162 }
10163
10164 static int process_sdp_a_image(const char *a, struct sip_pvt *p)
10165 {
10166 int found = FALSE;
10167 char s[256];
10168 unsigned int x;
10169
10170 if (initialize_udptl(p)) {
10171 return found;
10172 }
10173
10174 if ((sscanf(a, "T38FaxMaxBuffer:%30u", &x) == 1)) {
10175 ast_debug(3, "MaxBufferSize:%d\n", x);
10176 found = TRUE;
10177 } else if ((sscanf(a, "T38MaxBitRate:%30u", &x) == 1) || (sscanf(a, "T38FaxMaxRate:%30u", &x) == 1)) {
10178 ast_debug(3, "T38MaxBitRate: %d\n", x);
10179 switch (x) {
10180 case 14400:
10181 p->t38.their_parms.rate = AST_T38_RATE_14400;
10182 break;
10183 case 12000:
10184 p->t38.their_parms.rate = AST_T38_RATE_12000;
10185 break;
10186 case 9600:
10187 p->t38.their_parms.rate = AST_T38_RATE_9600;
10188 break;
10189 case 7200:
10190 p->t38.their_parms.rate = AST_T38_RATE_7200;
10191 break;
10192 case 4800:
10193 p->t38.their_parms.rate = AST_T38_RATE_4800;
10194 break;
10195 case 2400:
10196 p->t38.their_parms.rate = AST_T38_RATE_2400;
10197 break;
10198 }
10199 found = TRUE;
10200 } else if ((sscanf(a, "T38FaxVersion:%30u", &x) == 1)) {
10201 ast_debug(3, "FaxVersion: %u\n", x);
10202 p->t38.their_parms.version = x;
10203 found = TRUE;
10204 } else if ((sscanf(a, "T38FaxMaxDatagram:%30u", &x) == 1) || (sscanf(a, "T38MaxDatagram:%30u", &x) == 1)) {
10205
10206 if (((signed int) p->t38_maxdatagram >= 0) && ((unsigned int) p->t38_maxdatagram > x)) {
10207 ast_debug(1, "Overriding T38FaxMaxDatagram '%d' with '%d'\n", x, p->t38_maxdatagram);
10208 x = p->t38_maxdatagram;
10209 }
10210 ast_debug(3, "FaxMaxDatagram: %u\n", x);
10211 ast_udptl_set_far_max_datagram(p->udptl, x);
10212 found = TRUE;
10213 } else if ((strncmp(a, "T38FaxFillBitRemoval", 20) == 0)) {
10214 if (sscanf(a, "T38FaxFillBitRemoval:%30u", &x) == 1) {
10215 ast_debug(3, "FillBitRemoval: %d\n", x);
10216 if (x == 1) {
10217 p->t38.their_parms.fill_bit_removal = TRUE;
10218 }
10219 } else {
10220 ast_debug(3, "FillBitRemoval\n");
10221 p->t38.their_parms.fill_bit_removal = TRUE;
10222 }
10223 found = TRUE;
10224 } else if ((strncmp(a, "T38FaxTranscodingMMR", 20) == 0)) {
10225 if (sscanf(a, "T38FaxTranscodingMMR:%30u", &x) == 1) {
10226 ast_debug(3, "Transcoding MMR: %d\n", x);
10227 if (x == 1) {
10228 p->t38.their_parms.transcoding_mmr = TRUE;
10229 }
10230 } else {
10231 ast_debug(3, "Transcoding MMR\n");
10232 p->t38.their_parms.transcoding_mmr = TRUE;
10233 }
10234 found = TRUE;
10235 } else if ((strncmp(a, "T38FaxTranscodingJBIG", 21) == 0)) {
10236 if (sscanf(a, "T38FaxTranscodingJBIG:%30u", &x) == 1) {
10237 ast_debug(3, "Transcoding JBIG: %d\n", x);
10238 if (x == 1) {
10239 p->t38.their_parms.transcoding_jbig = TRUE;
10240 }
10241 } else {
10242 ast_debug(3, "Transcoding JBIG\n");
10243 p->t38.their_parms.transcoding_jbig = TRUE;
10244 }
10245 found = TRUE;
10246 } else if ((sscanf(a, "T38FaxRateManagement:%255s", s) == 1)) {
10247 ast_debug(3, "RateManagement: %s\n", s);
10248 if (!strcasecmp(s, "localTCF"))
10249 p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_LOCAL_TCF;
10250 else if (!strcasecmp(s, "transferredTCF"))
10251 p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF;
10252 found = TRUE;
10253 } else if ((sscanf(a, "T38FaxUdpEC:%255s", s) == 1)) {
10254 ast_debug(3, "UDP EC: %s\n", s);
10255 if (!strcasecmp(s, "t38UDPRedundancy")) {
10256 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
10257 } else if (!strcasecmp(s, "t38UDPFEC")) {
10258 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
10259 } else {
10260 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
10261 }
10262 found = TRUE;
10263 }
10264
10265 return found;
10266 }
10267
10268
10269
10270
10271 static int add_supported_header(struct sip_pvt *pvt, struct sip_request *req)
10272 {
10273 int res;
10274 if (st_get_mode(pvt, 0) != SESSION_TIMER_MODE_REFUSE) {
10275 res = add_header(req, "Supported", "replaces, timer");
10276 } else {
10277 res = add_header(req, "Supported", "replaces");
10278 }
10279 return res;
10280 }
10281
10282
10283 static int add_header(struct sip_request *req, const char *var, const char *value)
10284 {
10285 if (req->headers == SIP_MAX_HEADERS) {
10286 ast_log(LOG_WARNING, "Out of SIP header space\n");
10287 return -1;
10288 }
10289
10290 if (req->lines) {
10291 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
10292 return -1;
10293 }
10294
10295 if (sip_cfg.compactheaders) {
10296 var = find_alias(var, var);
10297 }
10298
10299 ast_str_append(&req->data, 0, "%s: %s\r\n", var, value);
10300 req->header[req->headers] = ast_str_strlen(req->data);
10301
10302 req->headers++;
10303
10304 return 0;
10305 }
10306
10307
10308
10309
10310
10311 static int add_header_max_forwards(struct sip_pvt *dialog, struct sip_request *req)
10312 {
10313 char clen[10];
10314
10315 snprintf(clen, sizeof(clen), "%d", dialog->maxforwards);
10316
10317 return add_header(req, "Max-Forwards", clen);
10318 }
10319
10320
10321 static int finalize_content(struct sip_request *req)
10322 {
10323 char clen[10];
10324
10325 if (req->lines) {
10326 ast_log(LOG_WARNING, "finalize_content() called on a message that has already been finalized\n");
10327 return -1;
10328 }
10329
10330 snprintf(clen, sizeof(clen), "%zd", ast_str_strlen(req->content));
10331 add_header(req, "Content-Length", clen);
10332
10333 if (ast_str_strlen(req->content)) {
10334 ast_str_append(&req->data, 0, "\r\n%s", ast_str_buffer(req->content));
10335 }
10336 req->lines = ast_str_strlen(req->content) ? 1 : 0;
10337 return 0;
10338 }
10339
10340
10341 static int add_content(struct sip_request *req, const char *line)
10342 {
10343 if (req->lines) {
10344 ast_log(LOG_WARNING, "Can't add more content when the content has been finalized\n");
10345 return -1;
10346 }
10347
10348 ast_str_append(&req->content, 0, "%s", line);
10349 return 0;
10350 }
10351
10352
10353 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field)
10354 {
10355 const char *tmp = get_header(orig, field);
10356
10357 if (!ast_strlen_zero(tmp))
10358 return add_header(req, field, tmp);
10359 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
10360 return -1;
10361 }
10362
10363
10364 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field)
10365 {
10366 int start = 0;
10367 int copied = 0;
10368 for (;;) {
10369 const char *tmp = __get_header(orig, field, &start);
10370
10371 if (ast_strlen_zero(tmp))
10372 break;
10373
10374 add_header(req, field, tmp);
10375 copied++;
10376 }
10377 return copied ? 0 : -1;
10378 }
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field)
10389 {
10390 int copied = 0;
10391 int start = 0;
10392
10393 for (;;) {
10394 char new[512];
10395 const char *oh = __get_header(orig, field, &start);
10396
10397 if (ast_strlen_zero(oh))
10398 break;
10399
10400 if (!copied) {
10401 char leftmost[512], *others, *rport;
10402
10403
10404 ast_copy_string(leftmost, oh, sizeof(leftmost));
10405 others = strchr(leftmost, ',');
10406 if (others)
10407 *others++ = '\0';
10408
10409
10410 rport = strstr(leftmost, ";rport");
10411 if (rport && *(rport+6) == '=')
10412 rport = NULL;
10413
10414 if (((ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT)) || (rport && ast_test_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT)))) {
10415
10416 char *end;
10417
10418 rport = strstr(leftmost, ";rport");
10419
10420 if (rport) {
10421 end = strchr(rport + 1, ';');
10422 if (end)
10423 memmove(rport, end, strlen(end) + 1);
10424 else
10425 *rport = '\0';
10426 }
10427
10428
10429 snprintf(new, sizeof(new), "%s;received=%s;rport=%d%s%s",
10430 leftmost, ast_sockaddr_stringify_addr_remote(&p->recv),
10431 ast_sockaddr_port(&p->recv),
10432 others ? "," : "", others ? others : "");
10433 } else {
10434
10435 snprintf(new, sizeof(new), "%s;received=%s%s%s",
10436 leftmost, ast_sockaddr_stringify_addr_remote(&p->recv),
10437 others ? "," : "", others ? others : "");
10438 }
10439 oh = new;
10440 }
10441 add_header(req, field, oh);
10442 copied++;
10443 }
10444 if (!copied) {
10445 ast_log(LOG_NOTICE, "No header field '%s' present to copy\n", field);
10446 return -1;
10447 }
10448 return 0;
10449 }
10450
10451
10452 static void add_route(struct sip_request *req, struct sip_route *route)
10453 {
10454 char r[SIPBUFSIZE*2], *p;
10455 int n, rem = sizeof(r);
10456
10457 if (!route)
10458 return;
10459
10460 p = r;
10461 for (;route ; route = route->next) {
10462 n = strlen(route->hop);
10463 if (rem < n+3)
10464 break;
10465 if (p != r) {
10466 *p++ = ',';
10467 --rem;
10468 }
10469 *p++ = '<';
10470 ast_copy_string(p, route->hop, rem);
10471 p += n;
10472 *p++ = '>';
10473 rem -= (n+2);
10474 }
10475 *p = '\0';
10476 add_header(req, "Route", r);
10477 }
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488 static void set_destination(struct sip_pvt *p, char *uri)
10489 {
10490 char *h, *maddr, hostname[256];
10491 int hn;
10492 int debug=sip_debug_test_pvt(p);
10493 int tls_on = FALSE;
10494
10495 if (debug)
10496 ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
10497
10498
10499 h = strchr(uri, '@');
10500 if (h)
10501 ++h;
10502 else {
10503 h = uri;
10504 if (!strncasecmp(h, "sip:", 4)) {
10505 h += 4;
10506 } else if (!strncasecmp(h, "sips:", 5)) {
10507 h += 5;
10508 tls_on = TRUE;
10509 }
10510 }
10511 hn = strcspn(h, ";>") + 1;
10512 if (hn > sizeof(hostname))
10513 hn = sizeof(hostname);
10514 ast_copy_string(hostname, h, hn);
10515
10516 h += hn - 1;
10517
10518
10519
10520 if (ast_sockaddr_resolve_first_transport(&p->sa, hostname, 0, p->socket.type)) {
10521 ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
10522 return;
10523 }
10524
10525
10526 maddr = strstr(h, "maddr=");
10527 if (maddr) {
10528 int port;
10529
10530 maddr += 6;
10531 hn = strspn(maddr, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
10532 "0123456789-.:[]") + 1;
10533 if (hn > sizeof(hostname))
10534 hn = sizeof(hostname);
10535 ast_copy_string(hostname, maddr, hn);
10536
10537 port = ast_sockaddr_port(&p->sa);
10538
10539
10540
10541 if (ast_sockaddr_resolve_first_transport(&p->sa, hostname, PARSE_PORT_FORBID, p->socket.type)) {
10542 ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
10543 return;
10544 }
10545
10546 ast_sockaddr_set_port(&p->sa, port);
10547 }
10548
10549 if (!ast_sockaddr_port(&p->sa)) {
10550 ast_sockaddr_set_port(&p->sa, tls_on ?
10551 STANDARD_TLS_PORT : STANDARD_SIP_PORT);
10552 }
10553
10554 if (debug) {
10555 ast_verbose("set_destination: set destination to %s\n",
10556 ast_sockaddr_stringify(&p->sa));
10557 }
10558 }
10559
10560
10561 static int init_resp(struct sip_request *resp, const char *msg)
10562 {
10563
10564 memset(resp, 0, sizeof(*resp));
10565 resp->method = SIP_RESPONSE;
10566 if (!(resp->data = ast_str_create(SIP_MIN_PACKET)))
10567 goto e_return;
10568 if (!(resp->content = ast_str_create(SIP_MIN_PACKET)))
10569 goto e_free_data;
10570 resp->header[0] = 0;
10571 ast_str_set(&resp->data, 0, "SIP/2.0 %s\r\n", msg);
10572 resp->headers++;
10573 return 0;
10574
10575 e_free_data:
10576 ast_free(resp->data);
10577 resp->data = NULL;
10578 e_return:
10579 return -1;
10580 }
10581
10582
10583 static int init_req(struct sip_request *req, int sipmethod, const char *recip)
10584 {
10585
10586 memset(req, 0, sizeof(*req));
10587 if (!(req->data = ast_str_create(SIP_MIN_PACKET)))
10588 goto e_return;
10589 if (!(req->content = ast_str_create(SIP_MIN_PACKET)))
10590 goto e_free_data;
10591 req->method = sipmethod;
10592 req->header[0] = 0;
10593 ast_str_set(&req->data, 0, "%s %s SIP/2.0\r\n", sip_methods[sipmethod].text, recip);
10594 req->headers++;
10595 return 0;
10596
10597 e_free_data:
10598 ast_free(req->data);
10599 req->data = NULL;
10600 e_return:
10601 return -1;
10602 }
10603
10604
10605 static void deinit_req(struct sip_request *req)
10606 {
10607 if (req->data) {
10608 ast_free(req->data);
10609 req->data = NULL;
10610 }
10611 if (req->content) {
10612 ast_free(req->content);
10613 req->content = NULL;
10614 }
10615 }
10616
10617
10618
10619 static inline int resp_needs_contact(const char *msg, enum sipmethod method) {
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635 switch (method) {
10636
10637 case SIP_INVITE:
10638 case SIP_UPDATE:
10639 case SIP_SUBSCRIBE:
10640 case SIP_NOTIFY:
10641 if ((msg[0] >= '1' && msg[0] <= '3') || !strncmp(msg, "485", 3))
10642 return 1;
10643 break;
10644
10645
10646 case SIP_REGISTER:
10647 case SIP_OPTIONS:
10648 if (msg[0] == '2' || msg[0] == '3' || !strncmp(msg, "485", 3))
10649 return 1;
10650 break;
10651
10652
10653 case SIP_BYE:
10654 case SIP_PRACK:
10655 case SIP_MESSAGE:
10656 case SIP_PUBLISH:
10657 if (msg[0] == '3' || !strncmp(msg, "485", 3))
10658 return 1;
10659 break;
10660
10661
10662 case SIP_REFER:
10663 if (msg[0] >= '2' && msg[0] <= '6')
10664 return 1;
10665 break;
10666
10667
10668 case SIP_ACK:
10669 case SIP_CANCEL:
10670 case SIP_INFO:
10671 case SIP_PING:
10672 default:
10673 return 0;
10674 }
10675 return 0;
10676 }
10677
10678
10679 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req)
10680 {
10681 char newto[256];
10682 const char *ot;
10683
10684 init_resp(resp, msg);
10685 copy_via_headers(p, resp, req, "Via");
10686 if (msg[0] == '1' || msg[0] == '2')
10687 copy_all_header(resp, req, "Record-Route");
10688 copy_header(resp, req, "From");
10689 ot = get_header(req, "To");
10690 if (!strcasestr(ot, "tag=") && strncmp(msg, "100", 3)) {
10691
10692
10693 if (!ast_strlen_zero(p->theirtag) && ast_test_flag(&p->flags[0], SIP_OUTGOING))
10694 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
10695 else if (p->tag && !ast_test_flag(&p->flags[0], SIP_OUTGOING))
10696 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
10697 else
10698 ast_copy_string(newto, ot, sizeof(newto));
10699 ot = newto;
10700 }
10701 add_header(resp, "To", ot);
10702 copy_header(resp, req, "Call-ID");
10703 copy_header(resp, req, "CSeq");
10704 if (!ast_strlen_zero(global_useragent))
10705 add_header(resp, "Server", global_useragent);
10706 add_header(resp, "Allow", ALLOWED_METHODS);
10707 add_supported_header(p, resp);
10708
10709
10710 if (p->method == SIP_INVITE && p->stimer && p->stimer->st_active == TRUE) {
10711 char se_hdr[256];
10712 snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval,
10713 p->stimer->st_ref == SESSION_TIMER_REFRESHER_US ? "uas" : "uac");
10714 add_header(resp, "Session-Expires", se_hdr);
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725 if (p->stimer->st_ref == SESSION_TIMER_REFRESHER_THEM ||
10726 (p->stimer->st_ref == SESSION_TIMER_REFRESHER_US &&
10727 p->stimer->st_active_peer_ua == TRUE)) {
10728 resp->reqsipoptions |= SIP_OPT_TIMER;
10729 }
10730 }
10731
10732 if (msg[0] == '2' && (p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER || p->method == SIP_PUBLISH)) {
10733
10734
10735 char tmp[256];
10736
10737 snprintf(tmp, sizeof(tmp), "%d", p->expiry);
10738 add_header(resp, "Expires", tmp);
10739 if (p->expiry) {
10740 char contact[SIPBUFSIZE];
10741 const char *contact_uri = p->method == SIP_SUBSCRIBE ? p->our_contact : p->fullcontact;
10742 char *brackets = strchr(contact_uri, '<');
10743 snprintf(contact, sizeof(contact), "%s%s%s;expires=%d", brackets ? "" : "<", contact_uri, brackets ? "" : ">", p->expiry);
10744 add_header(resp, "Contact", contact);
10745 }
10746 } else if (!ast_strlen_zero(p->our_contact) && resp_needs_contact(msg, p->method)) {
10747 add_header(resp, "Contact", p->our_contact);
10748 }
10749
10750 if (!ast_strlen_zero(p->url)) {
10751 add_header(resp, "Access-URL", p->url);
10752 ast_string_field_set(p, url, NULL);
10753 }
10754
10755
10756
10757
10758
10759
10760
10761 p->sa = p->recv;
10762
10763 if (process_via(p, req)) {
10764 ast_log(LOG_WARNING, "error processing via header, will send response to originating address\n");
10765 }
10766
10767 return 0;
10768 }
10769
10770
10771 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, uint32_t seqno, int newbranch)
10772 {
10773 struct sip_request *orig = &p->initreq;
10774 char stripped[80];
10775 char tmp[80];
10776 char newto[256];
10777 const char *c;
10778 const char *ot, *of;
10779 int is_strict = FALSE;
10780 int is_outbound = ast_test_flag(&p->flags[0], SIP_OUTGOING);
10781
10782 snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", sip_methods[sipmethod].text);
10783
10784 if (!seqno) {
10785 p->ocseq++;
10786 seqno = p->ocseq;
10787 }
10788
10789
10790 if (sipmethod == SIP_CANCEL) {
10791 p->branch = p->invite_branch;
10792 build_via(p);
10793 } else if (newbranch && (sipmethod == SIP_INVITE)) {
10794 p->branch ^= ast_random();
10795 p->invite_branch = p->branch;
10796 build_via(p);
10797 } else if (newbranch) {
10798 p->branch ^= ast_random();
10799 build_via(p);
10800 }
10801
10802
10803 if (p->route && !ast_strlen_zero(p->route->hop) && strstr(p->route->hop, ";lr") == NULL) {
10804 is_strict = TRUE;
10805 if (sipdebug)
10806 ast_debug(1, "Strict routing enforced for session %s\n", p->callid);
10807 }
10808
10809 if (sipmethod == SIP_CANCEL)
10810 c = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
10811 else if (sipmethod == SIP_ACK) {
10812
10813
10814 if (!ast_strlen_zero(p->okcontacturi))
10815 c = is_strict ? p->route->hop : p->okcontacturi;
10816 else
10817 c = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
10818 } else if (!ast_strlen_zero(p->okcontacturi))
10819 c = is_strict ? p->route->hop : p->okcontacturi;
10820 else if (!ast_strlen_zero(p->uri))
10821 c = p->uri;
10822 else {
10823 char *n;
10824
10825 ast_copy_string(stripped, get_header(orig, is_outbound ? "To" : "From"),
10826 sizeof(stripped));
10827 n = get_in_brackets(stripped);
10828 c = remove_uri_parameters(n);
10829 }
10830 init_req(req, sipmethod, c);
10831
10832 snprintf(tmp, sizeof(tmp), "%u %s", seqno, sip_methods[sipmethod].text);
10833
10834 add_header(req, "Via", p->via);
10835
10836
10837
10838
10839
10840 if (p->route &&
10841 !(sipmethod == SIP_CANCEL ||
10842 (sipmethod == SIP_ACK && (p->invitestate == INV_COMPLETED || p->invitestate == INV_CANCELLED)))) {
10843 set_destination(p, p->route->hop);
10844 add_route(req, is_strict ? p->route->next : p->route);
10845 }
10846 add_header_max_forwards(p, req);
10847
10848 ot = get_header(orig, "To");
10849 of = get_header(orig, "From");
10850
10851
10852
10853 if (!strcasestr(ot, "tag=") && sipmethod != SIP_CANCEL) {
10854
10855
10856 if (is_outbound && !ast_strlen_zero(p->theirtag))
10857 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
10858 else if (!is_outbound)
10859 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
10860 else
10861 snprintf(newto, sizeof(newto), "%s", ot);
10862 ot = newto;
10863 }
10864
10865 if (is_outbound) {
10866 add_header(req, "From", of);
10867 add_header(req, "To", ot);
10868 } else {
10869 add_header(req, "From", ot);
10870 add_header(req, "To", of);
10871 }
10872
10873 if (sipmethod != SIP_BYE && sipmethod != SIP_CANCEL && sipmethod != SIP_MESSAGE)
10874 add_header(req, "Contact", p->our_contact);
10875
10876 copy_header(req, orig, "Call-ID");
10877 add_header(req, "CSeq", tmp);
10878
10879 if (!ast_strlen_zero(global_useragent))
10880 add_header(req, "User-Agent", global_useragent);
10881
10882 if (!ast_strlen_zero(p->url)) {
10883 add_header(req, "Access-URL", p->url);
10884 ast_string_field_set(p, url, NULL);
10885 }
10886
10887
10888
10889
10890
10891
10892
10893
10894 if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE
10895 && sipmethod == SIP_INVITE) {
10896 char se_hdr[256];
10897 snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval,
10898 p->stimer->st_ref == SESSION_TIMER_REFRESHER_US ? "uac" : "uas");
10899 add_header(req, "Session-Expires", se_hdr);
10900 snprintf(se_hdr, sizeof(se_hdr), "%d", st_get_se(p, FALSE));
10901 add_header(req, "Min-SE", se_hdr);
10902 }
10903
10904 return 0;
10905 }
10906
10907
10908 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
10909 {
10910 struct sip_request resp;
10911 uint32_t seqno = 0;
10912
10913 if (reliable && (sscanf(get_header(req, "CSeq"), "%30u ", &seqno) != 1)) {
10914 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
10915 return -1;
10916 }
10917 respprep(&resp, p, msg, req);
10918
10919 if (ast_test_flag(&p->flags[0], SIP_SENDRPID)
10920 && ast_test_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND)
10921 && (!strncmp(msg, "180", 3) || !strncmp(msg, "183", 3))) {
10922 ast_clear_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND);
10923 add_rpid(&resp, p);
10924 }
10925 if (ast_test_flag(&p->flags[0], SIP_OFFER_CC)) {
10926 add_cc_call_info_to_response(p, &resp);
10927 }
10928
10929
10930 if (!strncmp(msg, "302", 3)) {
10931 add_diversion_header(&resp, p);
10932 }
10933
10934
10935
10936 if (p->method == SIP_INVITE && msg[0] != '1') {
10937 char buf[20];
10938
10939 if (ast_test_flag(&p->flags[1], SIP_PAGE2_Q850_REASON)) {
10940 int hangupcause = 0;
10941
10942 if (p->owner && p->owner->hangupcause) {
10943 hangupcause = p->owner->hangupcause;
10944 } else if (p->hangupcause) {
10945 hangupcause = p->hangupcause;
10946 } else {
10947 int respcode;
10948 if (sscanf(msg, "%30d ", &respcode))
10949 hangupcause = hangup_sip2cause(respcode);
10950 }
10951
10952 if (hangupcause) {
10953 sprintf(buf, "Q.850;cause=%i", hangupcause & 0x7f);
10954 add_header(&resp, "Reason", buf);
10955 }
10956 }
10957
10958 if (p->owner && p->owner->hangupcause) {
10959 add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->owner->hangupcause));
10960 snprintf(buf, sizeof(buf), "%d", p->owner->hangupcause);
10961 add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
10962 }
10963 }
10964 return send_response(p, &resp, reliable, seqno);
10965 }
10966
10967 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)
10968 {
10969 struct sip_request resp;
10970
10971 if (need_new_etag) {
10972 create_new_sip_etag(esc_entry, 1);
10973 }
10974 respprep(&resp, p, msg, req);
10975 add_header(&resp, "SIP-ETag", esc_entry->entity_tag);
10976
10977 return send_response(p, &resp, 0, 0);
10978 }
10979
10980 static int temp_pvt_init(void *data)
10981 {
10982 struct sip_pvt *p = data;
10983
10984 p->do_history = 0;
10985 return ast_string_field_init(p, 512);
10986 }
10987
10988 static void temp_pvt_cleanup(void *data)
10989 {
10990 struct sip_pvt *p = data;
10991
10992 ast_string_field_free_memory(p);
10993
10994 ast_free(data);
10995 }
10996
10997
10998 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)
10999 {
11000 struct sip_pvt *p = NULL;
11001
11002 if (!(p = ast_threadstorage_get(&ts_temp_pvt, sizeof(*p)))) {
11003 ast_log(LOG_ERROR, "Failed to get temporary pvt\n");
11004 return -1;
11005 }
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015 p->method = intended_method;
11016
11017 if (!addr) {
11018 ast_sockaddr_copy(&p->ourip, &internip);
11019 } else {
11020 ast_sockaddr_copy(&p->sa, addr);
11021 ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
11022 }
11023
11024 p->branch = ast_random();
11025 make_our_tag(p);
11026 p->ocseq = INITIAL_CSEQ;
11027
11028 if (useglobal_nat && addr) {
11029 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT_FORCE_RPORT);
11030 ast_sockaddr_copy(&p->recv, addr);
11031 do_setnat(p);
11032 }
11033
11034 ast_string_field_set(p, fromdomain, default_fromdomain);
11035 p->fromdomainport = default_fromdomainport;
11036 build_via(p);
11037 ast_string_field_set(p, callid, callid);
11038
11039 copy_socket_data(&p->socket, &req->socket);
11040
11041
11042 __transmit_response(p, msg, req, XMIT_UNRELIABLE);
11043
11044
11045 ast_string_field_init(p, 0);
11046
11047 return 0;
11048 }
11049
11050
11051 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req)
11052 {
11053 return __transmit_response(p, msg, req, XMIT_UNRELIABLE);
11054 }
11055
11056
11057 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported)
11058 {
11059 struct sip_request resp;
11060 respprep(&resp, p, msg, req);
11061 append_date(&resp);
11062 add_header(&resp, "Unsupported", unsupported);
11063 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
11064 }
11065
11066
11067 static int transmit_response_with_minse(struct sip_pvt *p, const char *msg, const struct sip_request *req, int minse_int)
11068 {
11069 struct sip_request resp;
11070 char minse_str[20];
11071
11072 respprep(&resp, p, msg, req);
11073 append_date(&resp);
11074
11075 snprintf(minse_str, sizeof(minse_str), "%d", minse_int);
11076 add_header(&resp, "Min-SE", minse_str);
11077 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
11078 }
11079
11080
11081
11082
11083
11084 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req)
11085 {
11086 return __transmit_response(p, msg, req, req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL);
11087 }
11088
11089
11090 static void append_date(struct sip_request *req)
11091 {
11092 char tmpdat[256];
11093 struct tm tm;
11094 time_t t = time(NULL);
11095
11096 gmtime_r(&t, &tm);
11097 strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
11098 add_header(req, "Date", tmpdat);
11099 }
11100
11101
11102 static int transmit_response_with_retry_after(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *seconds)
11103 {
11104 struct sip_request resp;
11105 respprep(&resp, p, msg, req);
11106 add_header(&resp, "Retry-After", seconds);
11107 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
11108 }
11109
11110
11111 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req)
11112 {
11113 struct sip_request resp;
11114 respprep(&resp, p, msg, req);
11115 append_date(&resp);
11116 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
11117 }
11118
11119
11120 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
11121 {
11122 struct sip_request resp;
11123 respprep(&resp, p, msg, req);
11124 add_header(&resp, "Accept", "application/sdp");
11125 return send_response(p, &resp, reliable, 0);
11126 }
11127
11128
11129 static int transmit_response_with_minexpires(struct sip_pvt *p, const char *msg, const struct sip_request *req)
11130 {
11131 struct sip_request resp;
11132 char tmp[32];
11133
11134 snprintf(tmp, sizeof(tmp), "%d", min_expiry);
11135 respprep(&resp, p, msg, req);
11136 add_header(&resp, "Min-Expires", tmp);
11137 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
11138 }
11139
11140
11141 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)
11142 {
11143 struct sip_request resp;
11144 char tmp[512];
11145 uint32_t seqno = 0;
11146
11147 if (reliable && (sscanf(get_header(req, "CSeq"), "%30u ", &seqno) != 1)) {
11148 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
11149 return -1;
11150 }
11151
11152 get_realm(p, req);
11153
11154
11155
11156 snprintf(tmp, sizeof(tmp), "Digest algorithm=MD5, realm=\"%s\", nonce=\"%s\"%s", p->realm, randdata, stale ? ", stale=true" : "");
11157 respprep(&resp, p, msg, req);
11158 add_header(&resp, header, tmp);
11159 append_history(p, "AuthChal", "Auth challenge sent for %s - nc %d", p->username, p->noncecount);
11160 return send_response(p, &resp, reliable, seqno);
11161 }
11162
11163
11164
11165
11166
11167
11168
11169 static int get_domain(const char *str, char *domain, int len)
11170 {
11171 char tmpf[256];
11172 char *a, *from;
11173
11174 *domain = '\0';
11175 ast_copy_string(tmpf, str, sizeof(tmpf));
11176 from = get_in_brackets(tmpf);
11177 if (!ast_strlen_zero(from)) {
11178 if (strncasecmp(from, "sip:", 4)) {
11179 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", from);
11180 return -1;
11181 }
11182 from += 4;
11183 } else
11184 from = NULL;
11185
11186 if (from) {
11187 int bracket = 0;
11188
11189
11190 if ((a = strchr(from, ';')))
11191 *a = '\0';
11192
11193 for (a = from; *a != '\0'; ++a) {
11194 if (*a == ':' && bracket == 0) {
11195 *a = '\0';
11196 break;
11197 } else if (*a == '[') {
11198 ++bracket;
11199 } else if (*a == ']') {
11200 --bracket;
11201 }
11202 }
11203 if ((a = strchr(from, '@'))) {
11204 *a = '\0';
11205 ast_copy_string(domain, a + 1, len);
11206 } else
11207 ast_copy_string(domain, from, len);
11208 }
11209
11210 return ast_strlen_zero(domain);
11211 }
11212
11213
11214
11215
11216
11217 static void get_realm(struct sip_pvt *p, const struct sip_request *req)
11218 {
11219 char domain[MAXHOSTNAMELEN];
11220
11221 if (!ast_strlen_zero(p->realm))
11222 return;
11223
11224 if (sip_cfg.domainsasrealm &&
11225 !AST_LIST_EMPTY(&domain_list))
11226 {
11227
11228 if (!get_domain(get_header(req, "From"), domain, sizeof(domain))) {
11229 if (check_sip_domain(domain, NULL, 0)) {
11230 ast_string_field_set(p, realm, domain);
11231 return;
11232 }
11233 }
11234
11235 if (!get_domain(get_header(req, "To"), domain, sizeof(domain))) {
11236 if (check_sip_domain(domain, NULL, 0)) {
11237 ast_string_field_set(p, realm, domain);
11238 return;
11239 }
11240 }
11241 }
11242
11243
11244 ast_string_field_set(p, realm, sip_cfg.realm);
11245 }
11246
11247
11248
11249
11250
11251
11252
11253
11254 static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp)
11255 {
11256 int res;
11257
11258 if (!(res = with_sdp ? transmit_response_with_sdp(p, msg, req, XMIT_UNRELIABLE, FALSE, FALSE) : transmit_response(p, msg, req))) {
11259 p->last_provisional = msg;
11260 update_provisional_keepalive(p, with_sdp);
11261 }
11262
11263 return res;
11264 }
11265
11266
11267 static int add_text(struct sip_request *req, const char *text)
11268 {
11269
11270 add_header(req, "Content-Type", "text/plain;charset=UTF-8");
11271 add_content(req, text);
11272 return 0;
11273 }
11274
11275
11276
11277
11278
11279 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode)
11280 {
11281 char tmp[256];
11282 int event;
11283 if (mode) {
11284
11285 if ('0' <= digit && digit <= '9') {
11286 event = digit - '0';
11287 } else if (digit == '*') {
11288 event = 10;
11289 } else if (digit == '#') {
11290 event = 11;
11291 } else if ('A' <= digit && digit <= 'D') {
11292 event = 12 + digit - 'A';
11293 } else if ('a' <= digit && digit <= 'd') {
11294 event = 12 + digit - 'a';
11295 } else {
11296
11297 event = 0;
11298 }
11299 snprintf(tmp, sizeof(tmp), "%d\r\n", event);
11300 add_header(req, "Content-Type", "application/dtmf");
11301 add_content(req, tmp);
11302 } else {
11303
11304 snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=%u\r\n", digit, duration);
11305 add_header(req, "Content-Type", "application/dtmf-relay");
11306 add_content(req, tmp);
11307 }
11308 return 0;
11309 }
11310
11311
11312
11313
11314
11315 static int add_rpid(struct sip_request *req, struct sip_pvt *p)
11316 {
11317 struct ast_str *tmp = ast_str_alloca(256);
11318 char tmp2[256];
11319 char *lid_num = NULL;
11320 char *lid_name = NULL;
11321 int lid_pres;
11322 const char *fromdomain;
11323 const char *privacy = NULL;
11324 const char *screen = NULL;
11325 const char *anonymous_string = "\"Anonymous\" <sip:anonymous@anonymous.invalid>";
11326
11327 if (!ast_test_flag(&p->flags[0], SIP_SENDRPID)) {
11328 return 0;
11329 }
11330
11331 if (p->owner && p->owner->connected.id.number.valid
11332 && p->owner->connected.id.number.str) {
11333 lid_num = p->owner->connected.id.number.str;
11334 }
11335 if (p->owner && p->owner->connected.id.name.valid
11336 && p->owner->connected.id.name.str) {
11337 lid_name = p->owner->connected.id.name.str;
11338 }
11339 lid_pres = (p->owner) ? ast_party_id_presentation(&p->owner->connected.id) : AST_PRES_NUMBER_NOT_AVAILABLE;
11340
11341 if (ast_strlen_zero(lid_num))
11342 return 0;
11343 if (ast_strlen_zero(lid_name))
11344 lid_name = lid_num;
11345 fromdomain = S_OR(p->fromdomain, ast_sockaddr_stringify_host_remote(&p->ourip));
11346
11347 lid_num = ast_uri_encode(lid_num, tmp2, sizeof(tmp2), 0);
11348
11349 if (ast_test_flag(&p->flags[0], SIP_SENDRPID_PAI)) {
11350 if ((lid_pres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
11351 ast_str_set(&tmp, -1, "%s", anonymous_string);
11352 } else {
11353 ast_str_set(&tmp, -1, "\"%s\" <sip:%s@%s>", lid_name, lid_num, fromdomain);
11354 }
11355 add_header(req, "P-Asserted-Identity", ast_str_buffer(tmp));
11356 } else {
11357 ast_str_set(&tmp, -1, "\"%s\" <sip:%s@%s>;party=%s", lid_name, lid_num, fromdomain, p->outgoing_call ? "calling" : "called");
11358
11359 switch (lid_pres) {
11360 case AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED:
11361 case AST_PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN:
11362 privacy = "off";
11363 screen = "no";
11364 break;
11365 case AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN:
11366 case AST_PRES_ALLOWED_NETWORK_NUMBER:
11367 privacy = "off";
11368 screen = "yes";
11369 break;
11370 case AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED:
11371 case AST_PRES_PROHIB_USER_NUMBER_FAILED_SCREEN:
11372 privacy = "full";
11373 screen = "no";
11374 break;
11375 case AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN:
11376 case AST_PRES_PROHIB_NETWORK_NUMBER:
11377 privacy = "full";
11378 screen = "yes";
11379 break;
11380 case AST_PRES_NUMBER_NOT_AVAILABLE:
11381 break;
11382 default:
11383 if ((lid_pres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
11384 privacy = "full";
11385 }
11386 else
11387 privacy = "off";
11388 screen = "no";
11389 break;
11390 }
11391
11392 if (!ast_strlen_zero(privacy) && !ast_strlen_zero(screen)) {
11393 ast_str_append(&tmp, -1, ";privacy=%s;screen=%s", privacy, screen);
11394 }
11395
11396 add_header(req, "Remote-Party-ID", ast_str_buffer(tmp));
11397 }
11398 return 0;
11399 }
11400
11401
11402
11403 static int add_vidupdate(struct sip_request *req)
11404 {
11405 const char *xml_is_a_huge_waste_of_space =
11406 "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
11407 " <media_control>\r\n"
11408 " <vc_primitive>\r\n"
11409 " <to_encoder>\r\n"
11410 " <picture_fast_update>\r\n"
11411 " </picture_fast_update>\r\n"
11412 " </to_encoder>\r\n"
11413 " </vc_primitive>\r\n"
11414 " </media_control>\r\n";
11415 add_header(req, "Content-Type", "application/media_control+xml");
11416 add_content(req, xml_is_a_huge_waste_of_space);
11417 return 0;
11418 }
11419
11420
11421 static void add_codec_to_sdp(const struct sip_pvt *p, format_t codec,
11422 struct ast_str **m_buf, struct ast_str **a_buf,
11423 int debug, int *min_packet_size)
11424 {
11425 int rtp_code;
11426 struct ast_format_list fmt;
11427
11428
11429 if (debug)
11430 ast_verbose("Adding codec 0x%" PRIx64 " (%s) to SDP\n", codec, ast_getformatname(codec));
11431 if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->rtp), 1, codec)) == -1)
11432 return;
11433
11434 if (p->rtp) {
11435 struct ast_codec_pref *pref = &ast_rtp_instance_get_codecs(p->rtp)->pref;
11436 fmt = ast_codec_pref_getsize(pref, codec);
11437 } else
11438 return;
11439 ast_str_append(m_buf, 0, " %d", rtp_code);
11440 ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
11441 ast_rtp_lookup_mime_subtype2(1, codec,
11442 ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0),
11443 ast_rtp_lookup_sample_rate2(1, codec));
11444
11445 switch (codec) {
11446 case AST_FORMAT_G729A:
11447
11448 ast_str_append(a_buf, 0, "a=fmtp:%d annexb=no\r\n", rtp_code);
11449 break;
11450 case AST_FORMAT_G723_1:
11451
11452 ast_str_append(a_buf, 0, "a=fmtp:%d annexa=no\r\n", rtp_code);
11453 break;
11454 case AST_FORMAT_ILBC:
11455
11456 ast_str_append(a_buf, 0, "a=fmtp:%d mode=%d\r\n", rtp_code, fmt.cur_ms);
11457 break;
11458 case AST_FORMAT_SIREN7:
11459
11460 ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=32000\r\n", rtp_code);
11461 break;
11462 case AST_FORMAT_SIREN14:
11463
11464 ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=48000\r\n", rtp_code);
11465 break;
11466 case AST_FORMAT_G719:
11467
11468 ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=64000\r\n", rtp_code);
11469 break;
11470 }
11471
11472 if (fmt.cur_ms && (fmt.cur_ms < *min_packet_size))
11473 *min_packet_size = fmt.cur_ms;
11474
11475
11476 if ((*min_packet_size)==0 && fmt.cur_ms)
11477 *min_packet_size = fmt.cur_ms;
11478 }
11479
11480
11481
11482 static void add_vcodec_to_sdp(const struct sip_pvt *p, format_t codec,
11483 struct ast_str **m_buf, struct ast_str **a_buf,
11484 int debug, int *min_packet_size)
11485 {
11486 int rtp_code;
11487
11488 if (!p->vrtp)
11489 return;
11490
11491 if (debug)
11492 ast_verbose("Adding video codec 0x%" PRIx64 " (%s) to SDP\n", codec, ast_getformatname(codec));
11493
11494 if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->vrtp), 1, codec)) == -1)
11495 return;
11496
11497 ast_str_append(m_buf, 0, " %d", rtp_code);
11498 ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
11499 ast_rtp_lookup_mime_subtype2(1, codec, 0),
11500 ast_rtp_lookup_sample_rate2(1, codec));
11501
11502 }
11503
11504
11505 static void add_tcodec_to_sdp(const struct sip_pvt *p, int codec,
11506 struct ast_str **m_buf, struct ast_str **a_buf,
11507 int debug, int *min_packet_size)
11508 {
11509 int rtp_code;
11510
11511 if (!p->trtp)
11512 return;
11513
11514 if (debug)
11515 ast_verbose("Adding text codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
11516
11517 if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->trtp), 1, codec)) == -1)
11518 return;
11519
11520 ast_str_append(m_buf, 0, " %d", rtp_code);
11521 ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
11522 ast_rtp_lookup_mime_subtype2(1, codec, 0),
11523 ast_rtp_lookup_sample_rate2(1, codec));
11524
11525
11526 if (codec == AST_FORMAT_T140RED) {
11527 int t140code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->trtp), 1, AST_FORMAT_T140);
11528 ast_str_append(a_buf, 0, "a=fmtp:%d %d/%d/%d\r\n", rtp_code,
11529 t140code,
11530 t140code,
11531 t140code);
11532
11533 }
11534 }
11535
11536
11537
11538 static unsigned int t38_get_rate(enum ast_control_t38_rate rate)
11539 {
11540 switch (rate) {
11541 case AST_T38_RATE_2400:
11542 return 2400;
11543 case AST_T38_RATE_4800:
11544 return 4800;
11545 case AST_T38_RATE_7200:
11546 return 7200;
11547 case AST_T38_RATE_9600:
11548 return 9600;
11549 case AST_T38_RATE_12000:
11550 return 12000;
11551 case AST_T38_RATE_14400:
11552 return 14400;
11553 default:
11554 return 0;
11555 }
11556 }
11557
11558
11559 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
11560 struct ast_str **m_buf, struct ast_str **a_buf,
11561 int debug)
11562 {
11563 int rtp_code;
11564
11565 if (debug)
11566 ast_verbose("Adding non-codec 0x%x (%s) to SDP\n", format, ast_rtp_lookup_mime_subtype2(0, format, 0));
11567 if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->rtp), 0, format)) == -1)
11568 return;
11569
11570 ast_str_append(m_buf, 0, " %d", rtp_code);
11571 ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
11572 ast_rtp_lookup_mime_subtype2(0, format, 0),
11573 ast_rtp_lookup_sample_rate2(0, format));
11574 if (format == AST_RTP_DTMF)
11575 ast_str_append(a_buf, 0, "a=fmtp:%d 0-16\r\n", rtp_code);
11576 }
11577
11578
11579
11580
11581 static void get_our_media_address(struct sip_pvt *p, int needvideo, int needtext,
11582 struct ast_sockaddr *addr, struct ast_sockaddr *vaddr,
11583 struct ast_sockaddr *taddr, struct ast_sockaddr *dest,
11584 struct ast_sockaddr *vdest, struct ast_sockaddr *tdest)
11585 {
11586 int use_externip = 0;
11587
11588
11589 ast_rtp_instance_get_local_address(p->rtp, addr);
11590 if (p->vrtp) {
11591 ast_rtp_instance_get_local_address(p->vrtp, vaddr);
11592 }
11593 if (p->trtp) {
11594 ast_rtp_instance_get_local_address(p->trtp, taddr);
11595 }
11596
11597
11598
11599
11600 use_externip = ast_sockaddr_cmp_addr(&p->ourip, addr);
11601
11602
11603
11604 if (!ast_sockaddr_isnull(&p->redirip)) {
11605 ast_sockaddr_copy(dest, &p->redirip);
11606 } else {
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618 ast_sockaddr_copy(dest,
11619 !ast_sockaddr_isnull(&media_address) ? &media_address :
11620 !ast_sockaddr_is_any(addr) && !use_externip ? addr :
11621 &p->ourip);
11622 ast_sockaddr_set_port(dest, ast_sockaddr_port(addr));
11623 }
11624
11625 if (needvideo) {
11626
11627 if (!ast_sockaddr_isnull(&p->vredirip)) {
11628 ast_sockaddr_copy(vdest, &p->vredirip);
11629 } else {
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641 ast_sockaddr_copy(vdest,
11642 !ast_sockaddr_isnull(&media_address) ? &media_address :
11643 !ast_sockaddr_is_any(vaddr) && !use_externip ? vaddr :
11644 &p->ourip);
11645 ast_sockaddr_set_port(vdest, ast_sockaddr_port(vaddr));
11646 }
11647 }
11648
11649 if (needtext) {
11650
11651 if (!ast_sockaddr_isnull(&p->tredirip)) {
11652 ast_sockaddr_copy(tdest, &p->tredirip);
11653 } else {
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665 ast_sockaddr_copy(tdest,
11666 !ast_sockaddr_isnull(&media_address) ? &media_address :
11667 !ast_sockaddr_is_any(taddr) && !use_externip ? taddr :
11668 &p->ourip);
11669 ast_sockaddr_set_port(tdest, ast_sockaddr_port(taddr));
11670 }
11671 }
11672 }
11673
11674 static void get_crypto_attrib(struct sip_srtp *srtp, const char **a_crypto)
11675 {
11676
11677 if (srtp) {
11678 if (!srtp->crypto) {
11679 srtp->crypto = sdp_crypto_setup();
11680 }
11681 if (srtp->crypto && (sdp_crypto_offer(srtp->crypto) >= 0)) {
11682 *a_crypto = sdp_crypto_attrib(srtp->crypto);
11683 }
11684
11685 if (!*a_crypto) {
11686 ast_log(LOG_WARNING, "No SRTP key management enabled\n");
11687 }
11688 }
11689 }
11690
11691
11692
11693
11694
11695
11696
11697 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38)
11698 {
11699 format_t alreadysent = 0;
11700 int doing_directmedia = FALSE;
11701
11702 struct ast_sockaddr addr = { {0,} };
11703 struct ast_sockaddr vaddr = { {0,} };
11704 struct ast_sockaddr taddr = { {0,} };
11705 struct ast_sockaddr udptladdr = { {0,} };
11706 struct ast_sockaddr dest = { {0,} };
11707 struct ast_sockaddr vdest = { {0,} };
11708 struct ast_sockaddr tdest = { {0,} };
11709 struct ast_sockaddr udptldest = { {0,} };
11710
11711
11712 char *version = "v=0\r\n";
11713 char subject[256];
11714 char owner[256];
11715 char connection[256];
11716 char *session_time = "t=0 0\r\n";
11717 char bandwidth[256] = "";
11718 char *hold = "";
11719 struct ast_str *m_audio = ast_str_alloca(256);
11720 struct ast_str *m_video = ast_str_alloca(256);
11721 struct ast_str *m_text = ast_str_alloca(256);
11722 struct ast_str *m_modem = ast_str_alloca(256);
11723 struct ast_str *a_audio = ast_str_alloca(1024);
11724 struct ast_str *a_video = ast_str_alloca(1024);
11725 struct ast_str *a_text = ast_str_alloca(1024);
11726 struct ast_str *a_modem = ast_str_alloca(1024);
11727 const char *a_crypto = NULL;
11728 const char *v_a_crypto = NULL;
11729 const char *t_a_crypto = NULL;
11730
11731 format_t x;
11732 format_t capability = 0;
11733 int needaudio = FALSE;
11734 int needvideo = FALSE;
11735 int needtext = FALSE;
11736 int debug = sip_debug_test_pvt(p);
11737 int min_audio_packet_size = 0;
11738 int min_video_packet_size = 0;
11739 int min_text_packet_size = 0;
11740
11741 char codecbuf[SIPBUFSIZE];
11742 char buf[SIPBUFSIZE];
11743 char dummy_answer[256];
11744
11745
11746 snprintf(subject, sizeof(subject), "s=%s\r\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
11747
11748 if (!p->rtp) {
11749 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
11750 return AST_FAILURE;
11751 }
11752
11753
11754
11755
11756 if (!p->sessionid) {
11757 p->sessionid = (int)ast_random();
11758 p->sessionversion = p->sessionid;
11759 } else {
11760 if (oldsdp == FALSE)
11761 p->sessionversion++;
11762 }
11763
11764 if (add_audio) {
11765 doing_directmedia = (!ast_sockaddr_isnull(&p->redirip) && p->redircodecs) ? TRUE : FALSE;
11766
11767 if ((p->jointcapability & AST_FORMAT_VIDEO_MASK) && !p->novideo) {
11768 if (doing_directmedia && !(p->jointcapability & AST_FORMAT_VIDEO_MASK & p->redircodecs)) {
11769 ast_debug(2, "This call needs video offers, but caller probably did not offer it!\n");
11770 } else if (p->vrtp) {
11771 needvideo = TRUE;
11772 ast_debug(2, "This call needs video offers!\n");
11773 } else {
11774 ast_debug(2, "This call needs video offers, but there's no video support enabled!\n");
11775 }
11776 }
11777
11778 if ((p->jointcapability & AST_FORMAT_TEXT_MASK) && !p->notext) {
11779 if (sipdebug_text)
11780 ast_verbose("We think we can do text\n");
11781 if (p->trtp) {
11782 if (sipdebug_text) {
11783 ast_verbose("And we have a text rtp object\n");
11784 }
11785 needtext = TRUE;
11786 ast_debug(2, "This call needs text offers! \n");
11787 } else {
11788 ast_debug(2, "This call needs text offers, but there's no text support enabled ! \n");
11789 }
11790 }
11791 }
11792
11793 get_our_media_address(p, needvideo, needtext, &addr, &vaddr, &taddr, &dest, &vdest, &tdest);
11794
11795 snprintf(owner, sizeof(owner), "o=%s %d %d IN %s %s\r\n",
11796 ast_strlen_zero(global_sdpowner) ? "-" : global_sdpowner,
11797 p->sessionid, p->sessionversion,
11798 (ast_sockaddr_is_ipv6(&dest) && !ast_sockaddr_is_ipv4_mapped(&dest)) ?
11799 "IP6" : "IP4",
11800 ast_sockaddr_stringify_addr_remote(&dest));
11801
11802 snprintf(connection, sizeof(connection), "c=IN %s %s\r\n",
11803 (ast_sockaddr_is_ipv6(&dest) && !ast_sockaddr_is_ipv4_mapped(&dest)) ?
11804 "IP6" : "IP4",
11805 ast_sockaddr_stringify_addr_remote(&dest));
11806
11807 if (add_audio) {
11808 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_ONEDIR) {
11809 hold = "a=recvonly\r\n";
11810 doing_directmedia = FALSE;
11811 } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_INACTIVE) {
11812 hold = "a=inactive\r\n";
11813 doing_directmedia = FALSE;
11814 } else {
11815 hold = "a=sendrecv\r\n";
11816 }
11817
11818 capability = p->jointcapability;
11819
11820
11821 ast_debug(1, "** Our capability: %s Video flag: %s Text flag: %s\n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), capability),
11822 p->novideo ? "True" : "False", p->notext ? "True" : "False");
11823 ast_debug(1, "** Our prefcodec: %s \n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), p->prefcodec));
11824
11825 if (doing_directmedia) {
11826 capability &= p->redircodecs;
11827 ast_debug(1, "** Our native-bridge filtered capablity: %s\n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), capability));
11828 }
11829
11830
11831 if (capability & AST_FORMAT_AUDIO_MASK)
11832 needaudio = TRUE;
11833
11834 if (debug) {
11835 ast_verbose("Audio is at %s\n", ast_sockaddr_stringify_port(&addr));
11836 }
11837
11838
11839
11840 if (needvideo) {
11841 get_crypto_attrib(p->vsrtp, &v_a_crypto);
11842 ast_str_append(&m_video, 0, "m=video %d RTP/%s", ast_sockaddr_port(&vdest),
11843 v_a_crypto ? "SAVP" : "AVP");
11844
11845
11846 if (p->maxcallbitrate)
11847 snprintf(bandwidth, sizeof(bandwidth), "b=CT:%d\r\n", p->maxcallbitrate);
11848 if (debug) {
11849 ast_verbose("Video is at %s\n", ast_sockaddr_stringify(&vdest));
11850 }
11851 }
11852
11853
11854
11855 if (needtext) {
11856 if (sipdebug_text)
11857 ast_verbose("Lets set up the text sdp\n");
11858 get_crypto_attrib(p->tsrtp, &t_a_crypto);
11859 ast_str_append(&m_text, 0, "m=text %d RTP/%s", ast_sockaddr_port(&tdest),
11860 t_a_crypto ? "SAVP" : "AVP");
11861 if (debug) {
11862 ast_verbose("Text is at %s\n", ast_sockaddr_stringify(&taddr));
11863 }
11864 }
11865
11866
11867
11868
11869
11870
11871 get_crypto_attrib(p->srtp, &a_crypto);
11872 ast_str_append(&m_audio, 0, "m=audio %d RTP/%s", ast_sockaddr_port(&dest),
11873 a_crypto ? "SAVP" : "AVP");
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884 if (capability & p->prefcodec) {
11885 format_t codec = p->prefcodec & AST_FORMAT_AUDIO_MASK;
11886
11887 add_codec_to_sdp(p, codec, &m_audio, &a_audio, debug, &min_audio_packet_size);
11888 alreadysent |= codec;
11889 }
11890
11891
11892 for (x = 0; x < 64; x++) {
11893 format_t codec;
11894
11895 if (!(codec = ast_codec_pref_index(&p->prefs, x)))
11896 break;
11897
11898 if (!(capability & codec))
11899 continue;
11900
11901 if (alreadysent & codec)
11902 continue;
11903
11904 add_codec_to_sdp(p, codec, &m_audio, &a_audio, debug, &min_audio_packet_size);
11905 alreadysent |= codec;
11906 }
11907
11908
11909 for (x = 1ULL; x <= (needtext ? AST_FORMAT_TEXT_MASK : (needvideo ? AST_FORMAT_VIDEO_MASK : AST_FORMAT_AUDIO_MASK)); x <<= 1) {
11910 if (!(capability & x))
11911 continue;
11912
11913 if (alreadysent & x)
11914 continue;
11915
11916 if (x & AST_FORMAT_AUDIO_MASK)
11917 add_codec_to_sdp(p, x, &m_audio, &a_audio, debug, &min_audio_packet_size);
11918 else if (x & AST_FORMAT_VIDEO_MASK)
11919 add_vcodec_to_sdp(p, x, &m_video, &a_video, debug, &min_video_packet_size);
11920 else if (x & AST_FORMAT_TEXT_MASK)
11921 add_tcodec_to_sdp(p, x, &m_text, &a_text, debug, &min_text_packet_size);
11922 }
11923
11924
11925 for (x = 1LL; x <= AST_RTP_MAX; x <<= 1) {
11926 if (!(p->jointnoncodeccapability & x))
11927 continue;
11928
11929 add_noncodec_to_sdp(p, x, &m_audio, &a_audio, debug);
11930 }
11931
11932 ast_debug(3, "-- Done with adding codecs to SDP\n");
11933
11934 if (!p->owner || !ast_internal_timing_enabled(p->owner))
11935 ast_str_append(&a_audio, 0, "a=silenceSupp:off - - - -\r\n");
11936
11937 if (min_audio_packet_size)
11938 ast_str_append(&a_audio, 0, "a=ptime:%d\r\n", min_audio_packet_size);
11939
11940
11941 if (min_video_packet_size)
11942 ast_str_append(&a_video, 0, "a=ptime:%d\r\n", min_video_packet_size);
11943
11944
11945 if (min_text_packet_size)
11946 ast_str_append(&a_text, 0, "a=ptime:%d\r\n", min_text_packet_size);
11947
11948 if (ast_str_size(m_audio) - ast_str_strlen(m_audio) < 2 || ast_str_size(m_video) - ast_str_strlen(m_video) < 2 ||
11949 ast_str_size(m_text) - ast_str_strlen(m_text) < 2 || ast_str_size(a_text) - ast_str_strlen(a_text) < 2 ||
11950 ast_str_size(a_audio) - ast_str_strlen(a_audio) < 2 || ast_str_size(a_video) - ast_str_strlen(a_video) < 2)
11951 ast_log(LOG_WARNING, "SIP SDP may be truncated due to undersized buffer!!\n");
11952 }
11953
11954 if (add_t38) {
11955
11956 ast_udptl_get_us(p->udptl, &udptladdr);
11957
11958
11959 if (!ast_sockaddr_isnull(&p->udptlredirip)) {
11960 ast_sockaddr_copy(&udptldest, &p->udptlredirip);
11961 } else {
11962 ast_sockaddr_copy(&udptldest, &p->ourip);
11963 ast_sockaddr_set_port(&udptldest, ast_sockaddr_port(&udptladdr));
11964 }
11965
11966 if (debug) {
11967 ast_debug(1, "T.38 UDPTL is at %s port %d\n", ast_sockaddr_stringify_addr(&p->ourip), ast_sockaddr_port(&udptladdr));
11968 }
11969
11970
11971
11972
11973 ast_str_append(&m_modem, 0, "m=image %d udptl t38\r\n", ast_sockaddr_port(&udptldest));
11974
11975 if (!ast_sockaddr_cmp(&udptldest, &dest)) {
11976 ast_str_append(&m_modem, 0, "c=IN %s %s\r\n",
11977 (ast_sockaddr_is_ipv6(&dest) && !ast_sockaddr_is_ipv4_mapped(&dest)) ?
11978 "IP6" : "IP4", ast_sockaddr_stringify_addr_remote(&udptldest));
11979 }
11980
11981 ast_str_append(&a_modem, 0, "a=T38FaxVersion:%d\r\n", p->t38.our_parms.version);
11982 ast_str_append(&a_modem, 0, "a=T38MaxBitRate:%d\r\n", t38_get_rate(p->t38.our_parms.rate));
11983 if (p->t38.our_parms.fill_bit_removal) {
11984 ast_str_append(&a_modem, 0, "a=T38FaxFillBitRemoval\r\n");
11985 }
11986 if (p->t38.our_parms.transcoding_mmr) {
11987 ast_str_append(&a_modem, 0, "a=T38FaxTranscodingMMR\r\n");
11988 }
11989 if (p->t38.our_parms.transcoding_jbig) {
11990 ast_str_append(&a_modem, 0, "a=T38FaxTranscodingJBIG\r\n");
11991 }
11992 switch (p->t38.our_parms.rate_management) {
11993 case AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF:
11994 ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:transferredTCF\r\n");
11995 break;
11996 case AST_T38_RATE_MANAGEMENT_LOCAL_TCF:
11997 ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:localTCF\r\n");
11998 break;
11999 }
12000 ast_str_append(&a_modem, 0, "a=T38FaxMaxDatagram:%u\r\n", ast_udptl_get_local_max_datagram(p->udptl));
12001 switch (ast_udptl_get_error_correction_scheme(p->udptl)) {
12002 case UDPTL_ERROR_CORRECTION_NONE:
12003 break;
12004 case UDPTL_ERROR_CORRECTION_FEC:
12005 ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPFEC\r\n");
12006 break;
12007 case UDPTL_ERROR_CORRECTION_REDUNDANCY:
12008 ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPRedundancy\r\n");
12009 break;
12010 }
12011 }
12012
12013 if (needaudio)
12014 ast_str_append(&m_audio, 0, "\r\n");
12015 if (needvideo)
12016 ast_str_append(&m_video, 0, "\r\n");
12017 if (needtext)
12018 ast_str_append(&m_text, 0, "\r\n");
12019
12020 add_header(resp, "Content-Type", "application/sdp");
12021 add_content(resp, version);
12022 add_content(resp, owner);
12023 add_content(resp, subject);
12024 add_content(resp, connection);
12025
12026 if (needvideo) {
12027 add_content(resp, bandwidth);
12028 }
12029 add_content(resp, session_time);
12030
12031 if (p->offered_media[SDP_AUDIO].order_offered ||
12032 p->offered_media[SDP_VIDEO].order_offered ||
12033 p->offered_media[SDP_TEXT].order_offered ||
12034 p->offered_media[SDP_IMAGE].order_offered) {
12035 int i;
12036
12037 for (i = 1; i <= 3; i++) {
12038 if (p->offered_media[SDP_AUDIO].order_offered == i) {
12039 if (needaudio) {
12040 add_content(resp, ast_str_buffer(m_audio));
12041 add_content(resp, ast_str_buffer(a_audio));
12042 add_content(resp, hold);
12043 if (a_crypto) {
12044 add_content(resp, a_crypto);
12045 }
12046 } else {
12047 snprintf(dummy_answer, sizeof(dummy_answer), "m=audio 0 RTP/AVP %s\r\n", p->offered_media[SDP_AUDIO].codecs);
12048 add_content(resp, dummy_answer);
12049 }
12050 } else if (p->offered_media[SDP_VIDEO].order_offered == i) {
12051 if (needvideo) {
12052 add_content(resp, ast_str_buffer(m_video));
12053 add_content(resp, ast_str_buffer(a_video));
12054 add_content(resp, hold);
12055 if (v_a_crypto) {
12056 add_content(resp, v_a_crypto);
12057 }
12058 } else {
12059 snprintf(dummy_answer, sizeof(dummy_answer), "m=video 0 RTP/AVP %s\r\n", p->offered_media[SDP_VIDEO].codecs);
12060 add_content(resp, dummy_answer);
12061 }
12062 } else if (p->offered_media[SDP_TEXT].order_offered == i) {
12063 if (needtext) {
12064 add_content(resp, ast_str_buffer(m_text));
12065 add_content(resp, ast_str_buffer(a_text));
12066 add_content(resp, hold);
12067 if (t_a_crypto) {
12068 add_content(resp, t_a_crypto);
12069 }
12070 } else {
12071 snprintf(dummy_answer, sizeof(dummy_answer), "m=text 0 RTP/AVP %s\r\n", p->offered_media[SDP_TEXT].codecs);
12072 add_content(resp, dummy_answer);
12073 }
12074 } else if (p->offered_media[SDP_IMAGE].order_offered == i) {
12075 if (add_t38) {
12076 add_content(resp, ast_str_buffer(m_modem));
12077 add_content(resp, ast_str_buffer(a_modem));
12078 } else {
12079 add_content(resp, "m=image 0 udptl t38\r\n");
12080 }
12081 }
12082 }
12083 } else {
12084
12085 if (needaudio) {
12086 add_content(resp, ast_str_buffer(m_audio));
12087 add_content(resp, ast_str_buffer(a_audio));
12088 add_content(resp, hold);
12089 if (a_crypto) {
12090 add_content(resp, a_crypto);
12091 }
12092 }
12093 if (needvideo) {
12094 add_content(resp, ast_str_buffer(m_video));
12095 add_content(resp, ast_str_buffer(a_video));
12096 add_content(resp, hold);
12097 if (v_a_crypto) {
12098 add_content(resp, v_a_crypto);
12099 }
12100 }
12101 if (needtext) {
12102 add_content(resp, ast_str_buffer(m_text));
12103 add_content(resp, ast_str_buffer(a_text));
12104 add_content(resp, hold);
12105 if (t_a_crypto) {
12106 add_content(resp, t_a_crypto);
12107 }
12108 }
12109 if (add_t38) {
12110 add_content(resp, ast_str_buffer(m_modem));
12111 add_content(resp, ast_str_buffer(a_modem));
12112 }
12113 }
12114
12115
12116 p->lastrtprx = p->lastrtptx = time(NULL);
12117
12118 ast_debug(3, "Done building SDP. Settling with this capability: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, capability));
12119
12120 return AST_SUCCESS;
12121 }
12122
12123
12124 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
12125 {
12126 struct sip_request resp;
12127 uint32_t seqno;
12128
12129 if (sscanf(get_header(req, "CSeq"), "%30u ", &seqno) != 1) {
12130 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
12131 return -1;
12132 }
12133 respprep(&resp, p, msg, req);
12134 if (p->udptl) {
12135 add_sdp(&resp, p, 0, 0, 1);
12136 } else
12137 ast_log(LOG_ERROR, "Can't add SDP to response, since we have no UDPTL session allocated. Call-ID %s\n", p->callid);
12138 if (retrans && !p->pendinginvite)
12139 p->pendinginvite = seqno;
12140 return send_response(p, &resp, retrans, seqno);
12141 }
12142
12143
12144 static void copy_request(struct sip_request *dst, const struct sip_request *src)
12145 {
12146
12147
12148
12149 struct ast_str *duplicate = dst->data;
12150 struct ast_str *duplicate_content = dst->content;
12151
12152
12153
12154 *dst = *src;
12155 dst->data = duplicate;
12156 dst->content = duplicate_content;
12157
12158
12159 if (!dst->data && !(dst->data = ast_str_create(ast_str_strlen(src->data) + 1))) {
12160 return;
12161 }
12162 ast_str_copy_string(&dst->data, src->data);
12163
12164
12165 if (src->content) {
12166 if (!dst->content && !(dst->content = ast_str_create(ast_str_strlen(src->content) + 1))) {
12167 return;
12168 }
12169 ast_str_copy_string(&dst->content, src->content);
12170 }
12171 }
12172
12173 static void add_cc_call_info_to_response(struct sip_pvt *p, struct sip_request *resp)
12174 {
12175 char uri[SIPBUFSIZE];
12176 struct ast_str *header = ast_str_alloca(SIPBUFSIZE);
12177 struct ast_cc_agent *agent = find_sip_cc_agent_by_original_callid(p);
12178 struct sip_cc_agent_pvt *agent_pvt;
12179
12180 if (!agent) {
12181
12182
12183
12184 ast_log(LOG_WARNING, "Can't find SIP CC agent for call '%s' even though OFFER_CC flag was set?\n", p->callid);
12185 return;
12186 }
12187
12188 agent_pvt = agent->private_data;
12189
12190 if (!ast_strlen_zero(agent_pvt->subscribe_uri)) {
12191 ast_copy_string(uri, agent_pvt->subscribe_uri, sizeof(uri));
12192 } else {
12193 generate_uri(p, uri, sizeof(uri));
12194 ast_copy_string(agent_pvt->subscribe_uri, uri, sizeof(agent_pvt->subscribe_uri));
12195 }
12196
12197
12198
12199
12200 ast_str_set(&header, 0, "<%s>;purpose=call-completion;m=%s", uri, "NR");
12201 add_header(resp, "Call-Info", ast_str_buffer(header));
12202 ao2_ref(agent, -1);
12203 }
12204
12205
12206
12207
12208 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)
12209 {
12210 struct sip_request resp;
12211 uint32_t seqno;
12212 if (sscanf(get_header(req, "CSeq"), "%30u ", &seqno) != 1) {
12213 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
12214 return -1;
12215 }
12216 respprep(&resp, p, msg, req);
12217 if (rpid == TRUE) {
12218 add_rpid(&resp, p);
12219 }
12220 if (ast_test_flag(&p->flags[0], SIP_OFFER_CC)) {
12221 add_cc_call_info_to_response(p, &resp);
12222 }
12223 if (p->rtp) {
12224 if (!p->autoframing && !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
12225 ast_debug(1, "Setting framing from config on incoming call\n");
12226 ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(p->rtp), p->rtp, &p->prefs);
12227 }
12228 ast_rtp_instance_activate(p->rtp);
12229 try_suggested_sip_codec(p);
12230 if (p->t38.state == T38_ENABLED) {
12231 add_sdp(&resp, p, oldsdp, TRUE, TRUE);
12232 } else {
12233 add_sdp(&resp, p, oldsdp, TRUE, FALSE);
12234 }
12235 } else
12236 ast_log(LOG_ERROR, "Can't add SDP to response, since we have no RTP session allocated. Call-ID %s\n", p->callid);
12237 if (reliable && !p->pendinginvite)
12238 p->pendinginvite = seqno;
12239 add_required_respheader(&resp);
12240 return send_response(p, &resp, reliable, seqno);
12241 }
12242
12243
12244 static int determine_firstline_parts(struct sip_request *req)
12245 {
12246 char *e = ast_skip_blanks(req->data->str);
12247 char *local_rlPart1;
12248
12249 if (!*e)
12250 return -1;
12251 req->rlPart1 = e - req->data->str;
12252 local_rlPart1 = e;
12253 e = ast_skip_nonblanks(e);
12254 if (*e)
12255 *e++ = '\0';
12256
12257 e = ast_skip_blanks(e);
12258 if ( !*e )
12259 return -1;
12260 ast_trim_blanks(e);
12261
12262 if (!strcasecmp(local_rlPart1, "SIP/2.0") ) {
12263 if (strlen(e) < 3)
12264 return -1;
12265 req->rlPart2 = e - req->data->str;
12266 } else {
12267 if ( *e == '<' ) {
12268 ast_debug(3, "Oops. Bogus uri in <> %s\n", e);
12269 e++;
12270 if (!*e)
12271 return -1;
12272 }
12273 req->rlPart2 = e - req->data->str;
12274 e = ast_skip_nonblanks(e);
12275 if (*e)
12276 *e++ = '\0';
12277 e = ast_skip_blanks(e);
12278 if (strcasecmp(e, "SIP/2.0") ) {
12279 ast_debug(3, "Skipping packet - Bad request protocol %s\n", e);
12280 return -1;
12281 }
12282 }
12283 return 1;
12284 }
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp)
12300 {
12301 struct sip_request req;
12302
12303 reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ? SIP_UPDATE : SIP_INVITE, 0, 1);
12304
12305 add_header(&req, "Allow", ALLOWED_METHODS);
12306 add_supported_header(p, &req);
12307 if (sipdebug) {
12308 if (oldsdp == TRUE)
12309 add_header(&req, "X-asterisk-Info", "SIP re-invite (Session-Timers)");
12310 else
12311 add_header(&req, "X-asterisk-Info", "SIP re-invite (External RTP bridge)");
12312 }
12313
12314 if (ast_test_flag(&p->flags[0], SIP_SENDRPID))
12315 add_rpid(&req, p);
12316
12317 if (p->do_history) {
12318 append_history(p, "ReInv", "Re-invite sent");
12319 }
12320 memset(p->offered_media, 0, sizeof(p->offered_media));
12321
12322 try_suggested_sip_codec(p);
12323 if (t38version) {
12324 add_sdp(&req, p, oldsdp, FALSE, TRUE);
12325 } else {
12326 add_sdp(&req, p, oldsdp, TRUE, FALSE);
12327 }
12328
12329
12330 initialize_initreq(p, &req);
12331 p->lastinvite = p->ocseq;
12332 ast_set_flag(&p->flags[0], SIP_OUTGOING);
12333 p->ongoing_reinvite = 1;
12334 return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
12335 }
12336
12337
12338 static char *remove_uri_parameters(char *uri)
12339 {
12340 char *atsign;
12341 atsign = strchr(uri, '@');
12342 if (!atsign) {
12343 atsign = uri;
12344 }
12345 atsign = strchr(atsign, ';');
12346 if (atsign)
12347 *atsign = '\0';
12348 return uri;
12349 }
12350
12351
12352 static void extract_uri(struct sip_pvt *p, struct sip_request *req)
12353 {
12354 char stripped[SIPBUFSIZE];
12355 char *c;
12356
12357 ast_copy_string(stripped, get_header(req, "Contact"), sizeof(stripped));
12358 c = get_in_brackets(stripped);
12359
12360 c = remove_uri_parameters(c);
12361 if (!ast_strlen_zero(c)) {
12362 ast_string_field_set(p, uri, c);
12363 }
12364
12365 }
12366
12367
12368 static void build_contact(struct sip_pvt *p)
12369 {
12370 char tmp[SIPBUFSIZE];
12371 char *user = ast_uri_encode(p->exten, tmp, sizeof(tmp), 0);
12372
12373 if (p->socket.type == SIP_TRANSPORT_UDP) {
12374 ast_string_field_build(p, our_contact, "<sip:%s%s%s>", user,
12375 ast_strlen_zero(user) ? "" : "@", ast_sockaddr_stringify_remote(&p->ourip));
12376 } else {
12377 ast_string_field_build(p, our_contact, "<sip:%s%s%s;transport=%s>", user,
12378 ast_strlen_zero(user) ? "" : "@", ast_sockaddr_stringify_remote(&p->ourip),
12379 get_transport(p->socket.type));
12380 }
12381 }
12382
12383
12384 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, const char * const explicit_uri)
12385 {
12386 struct ast_str *invite = ast_str_alloca(256);
12387 char from[256];
12388 char to[256];
12389 char tmp_n[SIPBUFSIZE/2];
12390 char tmp_l[SIPBUFSIZE/2];
12391 const char *l = NULL;
12392 const char *n = NULL;
12393 const char *d = NULL;
12394 const char *urioptions = "";
12395 int ourport;
12396
12397 if (ast_test_flag(&p->flags[0], SIP_USEREQPHONE)) {
12398 const char *s = p->username;
12399
12400
12401
12402
12403
12404
12405 if (*s == '+')
12406 s++;
12407 for (; *s; s++) {
12408 if (!strchr(AST_DIGIT_ANYNUM, *s) )
12409 break;
12410 }
12411
12412 if (!*s)
12413 urioptions = ";user=phone";
12414 }
12415
12416
12417 snprintf(p->lastmsg, sizeof(p->lastmsg), "Init: %s", sip_methods[sipmethod].text);
12418
12419 d = S_OR(p->fromdomain, ast_sockaddr_stringify_host_remote(&p->ourip));
12420 if (p->owner) {
12421 if ((ast_party_id_presentation(&p->owner->connected.id) & AST_PRES_RESTRICTION) == AST_PRES_ALLOWED) {
12422 l = p->owner->connected.id.number.valid ? p->owner->connected.id.number.str : NULL;
12423 n = p->owner->connected.id.name.valid ? p->owner->connected.id.name.str : NULL;
12424 } else {
12425
12426
12427 l = "anonymous";
12428 n = CALLERID_UNKNOWN;
12429 d = FROMDOMAIN_INVALID;
12430 }
12431 }
12432
12433
12434
12435
12436
12437
12438
12439 if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->mwi_from)) {
12440 l = p->mwi_from;
12441 }
12442
12443 if (ast_strlen_zero(l))
12444 l = default_callerid;
12445 if (ast_strlen_zero(n))
12446 n = l;
12447
12448 if (!ast_strlen_zero(p->fromuser))
12449 l = p->fromuser;
12450 else
12451 ast_string_field_set(p, fromuser, l);
12452
12453
12454 if (!ast_strlen_zero(p->fromname))
12455 n = p->fromname;
12456 else
12457 ast_string_field_set(p, fromname, n);
12458
12459 ast_copy_string(tmp_l, l, sizeof(tmp_l));
12460 if (sip_cfg.pedanticsipchecking) {
12461 ast_escape_quoted(n, tmp_n, sizeof(tmp_n));
12462 n = tmp_n;
12463 ast_uri_encode(l, tmp_l, sizeof(tmp_l), 0);
12464 }
12465
12466 ourport = (p->fromdomainport) ? p->fromdomainport : ast_sockaddr_port(&p->ourip);
12467 if (!sip_standard_port(p->socket.type, ourport)) {
12468 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s:%d>;tag=%s", n, tmp_l, d, ourport, p->tag);
12469 } else {
12470 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=%s", n, tmp_l, d, p->tag);
12471 }
12472
12473 if (!ast_strlen_zero(explicit_uri)) {
12474 ast_str_set(&invite, 0, "%s", explicit_uri);
12475 } else {
12476
12477 if (!ast_strlen_zero(p->fullcontact)) {
12478
12479 ast_str_append(&invite, 0, "%s", p->fullcontact);
12480 } else {
12481
12482 ast_str_append(&invite, 0, "sip:");
12483 if (!ast_strlen_zero(p->username)) {
12484 n = p->username;
12485 if (sip_cfg.pedanticsipchecking) {
12486 ast_uri_encode(n, tmp_n, sizeof(tmp_n), 0);
12487 n = tmp_n;
12488 }
12489 ast_str_append(&invite, 0, "%s@", n);
12490 }
12491 ast_str_append(&invite, 0, "%s", p->tohost);
12492 if (p->portinuri) {
12493 ast_str_append(&invite, 0, ":%d", ast_sockaddr_port(&p->sa));
12494 }
12495 ast_str_append(&invite, 0, "%s", urioptions);
12496 }
12497 }
12498
12499
12500 if (p->options && !ast_strlen_zero(p->options->uri_options))
12501 ast_str_append(&invite, 0, ";%s", p->options->uri_options);
12502
12503
12504
12505
12506 ast_string_field_set(p, uri, ast_str_buffer(invite));
12507
12508 if (!ast_strlen_zero(p->todnid)) {
12509
12510 if (!strchr(p->todnid, '@')) {
12511
12512 snprintf(to, sizeof(to), "<sip:%s@%s>%s%s", p->todnid, p->tohost, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
12513 } else {
12514 snprintf(to, sizeof(to), "<sip:%s>%s%s", p->todnid, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
12515 }
12516 } else {
12517 if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->theirtag)) {
12518
12519 snprintf(to, sizeof(to), "<%s%s>;tag=%s", (strncasecmp(p->uri, "sip:", 4) ? "sip:" : ""), p->uri, p->theirtag);
12520 } else if (p->options && p->options->vxml_url) {
12521
12522 snprintf(to, sizeof(to), "<%s>;%s", p->uri, p->options->vxml_url);
12523 } else {
12524 snprintf(to, sizeof(to), "<%s>", p->uri);
12525 }
12526 }
12527
12528 init_req(req, sipmethod, p->uri);
12529
12530 snprintf(tmp_n, sizeof(tmp_n), "%u %s", ++p->ocseq, sip_methods[sipmethod].text);
12531
12532 add_header(req, "Via", p->via);
12533 add_header_max_forwards(p, req);
12534
12535
12536
12537
12538 add_route(req, p->route);
12539
12540 add_header(req, "From", from);
12541 add_header(req, "To", to);
12542 ast_string_field_set(p, exten, l);
12543 build_contact(p);
12544 add_header(req, "Contact", p->our_contact);
12545 add_header(req, "Call-ID", p->callid);
12546 add_header(req, "CSeq", tmp_n);
12547 if (!ast_strlen_zero(global_useragent)) {
12548 add_header(req, "User-Agent", global_useragent);
12549 }
12550 }
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560 static void add_diversion_header(struct sip_request *req, struct sip_pvt *pvt)
12561 {
12562 const char *diverting_number;
12563 const char *diverting_name;
12564 const char *reason;
12565 char header_text[256];
12566
12567 if (!pvt->owner) {
12568 return;
12569 }
12570
12571 diverting_number = pvt->owner->redirecting.from.number.str;
12572 if (!pvt->owner->redirecting.from.number.valid
12573 || ast_strlen_zero(diverting_number)) {
12574 return;
12575 }
12576
12577 reason = sip_reason_code_to_str(pvt->owner->redirecting.reason);
12578
12579
12580 diverting_name = pvt->owner->redirecting.from.name.str;
12581 if (!pvt->owner->redirecting.from.name.valid
12582 || ast_strlen_zero(diverting_name)) {
12583 snprintf(header_text, sizeof(header_text), "<sip:%s@%s>;reason=%s", diverting_number,
12584 ast_sockaddr_stringify_host_remote(&pvt->ourip), reason);
12585 } else {
12586 snprintf(header_text, sizeof(header_text), "\"%s\" <sip:%s@%s>;reason=%s",
12587 diverting_name, diverting_number,
12588 ast_sockaddr_stringify_host_remote(&pvt->ourip), reason);
12589 }
12590
12591 add_header(req, "Diversion", header_text);
12592 }
12593
12594 static int transmit_publish(struct sip_epa_entry *epa_entry, enum sip_publish_type publish_type, const char * const explicit_uri)
12595 {
12596 struct sip_pvt *pvt;
12597 int expires;
12598
12599 epa_entry->publish_type = publish_type;
12600
12601 if (!(pvt = sip_alloc(NULL, NULL, 0, SIP_PUBLISH, NULL))) {
12602 return -1;
12603 }
12604
12605 sip_pvt_lock(pvt);
12606
12607 if (create_addr(pvt, epa_entry->destination, NULL, TRUE)) {
12608 sip_pvt_unlock(pvt);
12609 dialog_unlink_all(pvt);
12610 dialog_unref(pvt, "create_addr failed in transmit_publish. Unref dialog");
12611 return -1;
12612 }
12613 ast_sip_ouraddrfor(&pvt->sa, &pvt->ourip, pvt);
12614 ast_set_flag(&pvt->flags[0], SIP_OUTGOING);
12615 expires = (publish_type == SIP_PUBLISH_REMOVE) ? 0 : DEFAULT_PUBLISH_EXPIRES;
12616 pvt->expiry = expires;
12617
12618
12619 ao2_ref(epa_entry, +1);
12620 pvt->epa_entry = epa_entry;
12621
12622 transmit_invite(pvt, SIP_PUBLISH, FALSE, 2, explicit_uri);
12623 sip_pvt_unlock(pvt);
12624 sip_scheddestroy(pvt, DEFAULT_TRANS_TIMEOUT);
12625 dialog_unref(pvt, "Done with the sip_pvt allocated for transmitting PUBLISH");
12626 return 0;
12627 }
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init, const char * const explicit_uri)
12639 {
12640 struct sip_request req;
12641 struct ast_variable *var;
12642
12643 if (init) {
12644 p->branch ^= ast_random();
12645 p->invite_branch = p->branch;
12646 build_via(p);
12647 }
12648 if (init > 1) {
12649 initreqprep(&req, p, sipmethod, explicit_uri);
12650 } else {
12651
12652 reqprep(&req, p, sipmethod, 0, init ? 0 : 1);
12653 }
12654
12655 if (p->options && p->options->auth) {
12656 add_header(&req, p->options->authheader, p->options->auth);
12657 }
12658 append_date(&req);
12659 if (sipmethod == SIP_REFER) {
12660 if (p->refer) {
12661 char buf[SIPBUFSIZE];
12662 if (!ast_strlen_zero(p->refer->refer_to)) {
12663 add_header(&req, "Refer-To", p->refer->refer_to);
12664 }
12665 if (!ast_strlen_zero(p->refer->referred_by)) {
12666 snprintf(buf, sizeof(buf), "%s <%s>", p->refer->referred_by_name, p->refer->referred_by);
12667 add_header(&req, "Referred-By", buf);
12668 }
12669 }
12670 } else if (sipmethod == SIP_SUBSCRIBE) {
12671 char buf[SIPBUFSIZE];
12672 if (p->subscribed == MWI_NOTIFICATION) {
12673 add_header(&req, "Event", "message-summary");
12674 add_header(&req, "Accept", "application/simple-message-summary");
12675 } else if (p->subscribed == CALL_COMPLETION) {
12676 add_header(&req, "Event", "call-completion");
12677 add_header(&req, "Accept", "application/call-completion");
12678 }
12679 snprintf(buf, sizeof(buf), "%d", p->expiry);
12680 add_header(&req, "Expires", buf);
12681 }
12682
12683
12684
12685 if (p->options && !ast_strlen_zero(p->options->replaces)) {
12686 add_header(&req, "Replaces", p->options->replaces);
12687 add_header(&req, "Require", "replaces");
12688 }
12689
12690
12691 if (st_get_mode(p, 0) == SESSION_TIMER_MODE_ORIGINATE) {
12692 char i2astr[10];
12693
12694 if (!p->stimer->st_interval) {
12695 p->stimer->st_interval = st_get_se(p, TRUE);
12696 }
12697
12698 p->stimer->st_active = TRUE;
12699
12700 snprintf(i2astr, sizeof(i2astr), "%d", p->stimer->st_interval);
12701 add_header(&req, "Session-Expires", i2astr);
12702 snprintf(i2astr, sizeof(i2astr), "%d", st_get_se(p, FALSE));
12703 add_header(&req, "Min-SE", i2astr);
12704 }
12705
12706 add_header(&req, "Allow", ALLOWED_METHODS);
12707 add_supported_header(p, &req);
12708
12709 if (p->options && p->options->addsipheaders && p->owner) {
12710 struct ast_channel *chan = p->owner;
12711 struct varshead *headp;
12712
12713 ast_channel_lock(chan);
12714
12715 headp = &chan->varshead;
12716
12717 if (!headp) {
12718 ast_log(LOG_WARNING, "No Headp for the channel...ooops!\n");
12719 } else {
12720 const struct ast_var_t *current;
12721 AST_LIST_TRAVERSE(headp, current, entries) {
12722
12723 if (!strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
12724 char *content, *end;
12725 const char *header = ast_var_value(current);
12726 char *headdup = ast_strdupa(header);
12727
12728
12729 if (*headdup == '"') {
12730 headdup++;
12731 }
12732 if ((content = strchr(headdup, ':'))) {
12733 *content++ = '\0';
12734 content = ast_skip_blanks(content);
12735
12736 end = content + strlen(content) -1;
12737 if (*end == '"') {
12738 *end = '\0';
12739 }
12740
12741 add_header(&req, headdup, content);
12742 if (sipdebug) {
12743 ast_debug(1, "Adding SIP Header \"%s\" with content :%s: \n", headdup, content);
12744 }
12745 }
12746 }
12747 }
12748 }
12749
12750 ast_channel_unlock(chan);
12751 }
12752 if ((sipmethod == SIP_INVITE || sipmethod == SIP_UPDATE) && ast_test_flag(&p->flags[0], SIP_SENDRPID))
12753 add_rpid(&req, p);
12754 if (sipmethod == SIP_INVITE) {
12755 add_diversion_header(&req, p);
12756 }
12757 if (sdp) {
12758 memset(p->offered_media, 0, sizeof(p->offered_media));
12759 if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
12760 ast_debug(1, "T38 is in state %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
12761 add_sdp(&req, p, FALSE, FALSE, TRUE);
12762 } else if (p->rtp) {
12763 try_suggested_sip_codec(p);
12764 add_sdp(&req, p, FALSE, TRUE, FALSE);
12765 }
12766 } else if (p->notify) {
12767 for (var = p->notify->headers; var; var = var->next) {
12768 add_header(&req, var->name, var->value);
12769 }
12770 if (ast_str_strlen(p->notify->content)) {
12771 add_content(&req, ast_str_buffer(p->notify->content));
12772 }
12773 } else if (sipmethod == SIP_PUBLISH) {
12774 char expires[SIPBUFSIZE];
12775
12776 switch (p->epa_entry->static_data->event) {
12777 case CALL_COMPLETION:
12778 snprintf(expires, sizeof(expires), "%d", p->expiry);
12779 add_header(&req, "Event", "call-completion");
12780 add_header(&req, "Expires", expires);
12781 if (p->epa_entry->publish_type != SIP_PUBLISH_INITIAL) {
12782 add_header(&req, "SIP-If-Match", p->epa_entry->entity_tag);
12783 }
12784
12785 if (!ast_strlen_zero(p->epa_entry->body)) {
12786 add_header(&req, "Content-Type", "application/pidf+xml");
12787 add_content(&req, p->epa_entry->body);
12788 }
12789 default:
12790 break;
12791 }
12792 }
12793
12794 if (!p->initreq.headers || init > 2) {
12795 initialize_initreq(p, &req);
12796 }
12797 if (sipmethod == SIP_INVITE || sipmethod == SIP_SUBSCRIBE) {
12798 p->lastinvite = p->ocseq;
12799 }
12800 return send_request(p, &req, init ? XMIT_CRITICAL : XMIT_RELIABLE, p->ocseq);
12801 }
12802
12803
12804 static int sip_subscribe_mwi_do(const void *data)
12805 {
12806 struct sip_subscription_mwi *mwi = (struct sip_subscription_mwi*)data;
12807
12808 if (!mwi) {
12809 return -1;
12810 }
12811
12812 mwi->resub = -1;
12813 __sip_subscribe_mwi_do(mwi);
12814 ASTOBJ_UNREF(mwi, sip_subscribe_mwi_destroy);
12815
12816 return 0;
12817 }
12818
12819 static void on_dns_update_registry(struct ast_sockaddr *old, struct ast_sockaddr *new, void *data)
12820 {
12821 struct sip_registry *reg = data;
12822 const char *old_str;
12823
12824
12825 if (ast_sockaddr_isnull(new)) {
12826 ast_debug(1, "Empty sockaddr change...ignoring!\n");
12827 return;
12828 }
12829
12830 if (!ast_sockaddr_port(new)) {
12831 ast_sockaddr_set_port(new, reg->portno);
12832 }
12833
12834 old_str = ast_strdupa(ast_sockaddr_stringify(old));
12835
12836 ast_debug(1, "Changing registry %s from %s to %s\n", S_OR(reg->peername, reg->hostname), old_str, ast_sockaddr_stringify(new));
12837 ast_sockaddr_copy(®->us, new);
12838 }
12839
12840 static void on_dns_update_peer(struct ast_sockaddr *old, struct ast_sockaddr *new, void *data)
12841 {
12842 struct sip_peer *peer = data;
12843 const char *old_str;
12844
12845
12846 if (ast_sockaddr_isnull(new)) {
12847 ast_debug(1, "Empty sockaddr change...ignoring!\n");
12848 return;
12849 }
12850
12851 if (!ast_sockaddr_isnull(&peer->addr)) {
12852 ao2_unlink(peers_by_ip, peer);
12853 }
12854
12855 if (!ast_sockaddr_port(new)) {
12856 ast_sockaddr_set_port(new, default_sip_port(peer->socket.type));
12857 }
12858
12859 old_str = ast_strdupa(ast_sockaddr_stringify(old));
12860 ast_debug(1, "Changing peer %s address from %s to %s\n", peer->name, old_str, ast_sockaddr_stringify(new));
12861
12862 ao2_lock(peer);
12863 ast_sockaddr_copy(&peer->addr, new);
12864 ao2_unlock(peer);
12865
12866 ao2_link(peers_by_ip, peer);
12867 }
12868
12869 static void on_dns_update_mwi(struct ast_sockaddr *old, struct ast_sockaddr *new, void *data)
12870 {
12871 struct sip_subscription_mwi *mwi = data;
12872 const char *old_str;
12873
12874
12875 if (ast_sockaddr_isnull(new)) {
12876 ast_debug(1, "Empty sockaddr change...ignoring!\n");
12877 return;
12878 }
12879
12880 old_str = ast_strdupa(ast_sockaddr_stringify(old));
12881 ast_debug(1, "Changing mwi %s from %s to %s\n", mwi->hostname, old_str, ast_sockaddr_stringify(new));
12882 ast_sockaddr_copy(&mwi->us, new);
12883 }
12884
12885
12886 static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi)
12887 {
12888
12889 if (!mwi->dnsmgr) {
12890 char transport[MAXHOSTNAMELEN];
12891 struct sip_subscription_mwi *saved;
12892 snprintf(transport, sizeof(transport), "_%s._%s", get_srv_service(mwi->transport), get_srv_protocol(mwi->transport));
12893
12894 mwi->us.ss.ss_family = get_address_family_filter(mwi->transport);
12895 saved = ASTOBJ_REF(mwi);
12896 ast_dnsmgr_lookup_cb(mwi->hostname, &mwi->us, &mwi->dnsmgr, sip_cfg.srvlookup ? transport : NULL, on_dns_update_mwi, saved);
12897 if (!mwi->dnsmgr) {
12898 ASTOBJ_UNREF(saved, sip_subscribe_mwi_destroy);
12899 }
12900 }
12901
12902
12903 if (mwi->call) {
12904 transmit_invite(mwi->call, SIP_SUBSCRIBE, 0, 0, NULL);
12905 return 0;
12906 }
12907
12908
12909 if (!(mwi->call = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL))) {
12910 return -1;
12911 }
12912
12913 ref_proxy(mwi->call, obproxy_get(mwi->call, NULL));
12914
12915 if (!ast_sockaddr_port(&mwi->us) && mwi->portno) {
12916 ast_sockaddr_set_port(&mwi->us, mwi->portno);
12917 }
12918
12919
12920 if (create_addr(mwi->call, mwi->hostname, &mwi->us, 0)) {
12921 dialog_unlink_all(mwi->call);
12922 mwi->call = dialog_unref(mwi->call, "unref dialog after unlink_all");
12923 return 0;
12924 }
12925
12926 mwi->call->expiry = mwi_expiry;
12927
12928 if (!mwi->dnsmgr && mwi->portno) {
12929 ast_sockaddr_set_port(&mwi->call->sa, mwi->portno);
12930 ast_sockaddr_set_port(&mwi->call->recv, mwi->portno);
12931 } else {
12932 mwi->portno = ast_sockaddr_port(&mwi->call->sa);
12933 }
12934
12935
12936 if (!ast_strlen_zero(mwi->authuser)) {
12937 ast_string_field_set(mwi->call, peername, mwi->authuser);
12938 ast_string_field_set(mwi->call, authname, mwi->authuser);
12939 ast_string_field_set(mwi->call, fromuser, mwi->authuser);
12940 } else {
12941 ast_string_field_set(mwi->call, peername, mwi->username);
12942 ast_string_field_set(mwi->call, authname, mwi->username);
12943 ast_string_field_set(mwi->call, fromuser, mwi->username);
12944 }
12945 ast_string_field_set(mwi->call, username, mwi->username);
12946 if (!ast_strlen_zero(mwi->secret)) {
12947 ast_string_field_set(mwi->call, peersecret, mwi->secret);
12948 }
12949 set_socket_transport(&mwi->call->socket, mwi->transport);
12950 mwi->call->socket.port = htons(mwi->portno);
12951 ast_sip_ouraddrfor(&mwi->call->sa, &mwi->call->ourip, mwi->call);
12952 build_contact(mwi->call);
12953 build_via(mwi->call);
12954
12955
12956 change_callid_pvt(mwi->call, NULL);
12957
12958 ast_set_flag(&mwi->call->flags[0], SIP_OUTGOING);
12959
12960
12961 mwi->call->mwi = ASTOBJ_REF(mwi);
12962
12963 mwi->call->subscribed = MWI_NOTIFICATION;
12964
12965
12966 transmit_invite(mwi->call, SIP_SUBSCRIBE, 0, 2, NULL);
12967
12968 return 0;
12969 }
12970
12971
12972 static int find_calling_channel(void *obj, void *arg, void *data, int flags)
12973 {
12974 struct ast_channel *c = obj;
12975 struct sip_pvt *p = data;
12976 int res;
12977
12978 ast_channel_lock(c);
12979
12980 res = (c->pbx &&
12981 (!strcasecmp(c->macroexten, p->exten) || !strcasecmp(c->exten, p->exten)) &&
12982 (sip_cfg.notifycid == IGNORE_CONTEXT || !strcasecmp(c->context, p->context)));
12983
12984 ast_channel_unlock(c);
12985
12986 return res ? CMP_MATCH | CMP_STOP : 0;
12987 }
12988
12989
12990 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)
12991 {
12992 enum state { NOTIFY_OPEN, NOTIFY_INUSE, NOTIFY_CLOSED } local_state = NOTIFY_OPEN;
12993 const char *statestring = "terminated";
12994 const char *pidfstate = "--";
12995 const char *pidfnote= "Ready";
12996 char hint[AST_MAX_EXTENSION];
12997
12998 switch (state) {
12999 case (AST_EXTENSION_RINGING | AST_EXTENSION_INUSE):
13000 statestring = (sip_cfg.notifyringing) ? "early" : "confirmed";
13001 local_state = NOTIFY_INUSE;
13002 pidfstate = "busy";
13003 pidfnote = "Ringing";
13004 break;
13005 case AST_EXTENSION_RINGING:
13006 statestring = "early";
13007 local_state = NOTIFY_INUSE;
13008 pidfstate = "busy";
13009 pidfnote = "Ringing";
13010 break;
13011 case AST_EXTENSION_INUSE:
13012 statestring = "confirmed";
13013 local_state = NOTIFY_INUSE;
13014 pidfstate = "busy";
13015 pidfnote = "On the phone";
13016 break;
13017 case AST_EXTENSION_BUSY:
13018 statestring = "confirmed";
13019 local_state = NOTIFY_CLOSED;
13020 pidfstate = "busy";
13021 pidfnote = "On the phone";
13022 break;
13023 case AST_EXTENSION_UNAVAILABLE:
13024 statestring = "terminated";
13025 local_state = NOTIFY_CLOSED;
13026 pidfstate = "away";
13027 pidfnote = "Unavailable";
13028 break;
13029 case AST_EXTENSION_ONHOLD:
13030 statestring = "confirmed";
13031 local_state = NOTIFY_CLOSED;
13032 pidfstate = "busy";
13033 pidfnote = "On hold";
13034 break;
13035 case AST_EXTENSION_NOT_INUSE:
13036 default:
13037
13038 break;
13039 }
13040
13041
13042 if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, context, exten)) {
13043 char *hint2 = hint, *individual_hint = NULL;
13044 int hint_count = 0, unavailable_count = 0;
13045
13046 while ((individual_hint = strsep(&hint2, "&"))) {
13047 hint_count++;
13048
13049 if (ast_device_state(individual_hint) == AST_DEVICE_UNAVAILABLE)
13050 unavailable_count++;
13051 }
13052
13053
13054
13055
13056 if (hint_count > 0 && hint_count == unavailable_count) {
13057 local_state = NOTIFY_CLOSED;
13058 pidfstate = "away";
13059 pidfnote = "Not online";
13060 }
13061 }
13062
13063 switch (subscribed) {
13064 case XPIDF_XML:
13065 case CPIM_PIDF_XML:
13066 ast_str_append(tmp, 0,
13067 "<?xml version=\"1.0\"?>\n"
13068 "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n"
13069 "<presence>\n");
13070 ast_str_append(tmp, 0, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
13071 ast_str_append(tmp, 0, "<atom id=\"%s\">\n", exten);
13072 ast_str_append(tmp, 0, "<address uri=\"%s;user=ip\" priority=\"0.800000\">\n", mto);
13073 ast_str_append(tmp, 0, "<status status=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "open" : (local_state == NOTIFY_INUSE) ? "inuse" : "closed");
13074 ast_str_append(tmp, 0, "<msnsubstatus substatus=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "online" : (local_state == NOTIFY_INUSE) ? "onthephone" : "offline");
13075 ast_str_append(tmp, 0, "</address>\n</atom>\n</presence>\n");
13076 break;
13077 case PIDF_XML:
13078 ast_str_append(tmp, 0,
13079 "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"
13080 "<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);
13081 ast_str_append(tmp, 0, "<pp:person><status>\n");
13082 if (pidfstate[0] != '-') {
13083 ast_str_append(tmp, 0, "<ep:activities><ep:%s/></ep:activities>\n", pidfstate);
13084 }
13085 ast_str_append(tmp, 0, "</status></pp:person>\n");
13086 ast_str_append(tmp, 0, "<note>%s</note>\n", pidfnote);
13087 ast_str_append(tmp, 0, "<tuple id=\"%s\">\n", exten);
13088 ast_str_append(tmp, 0, "<contact priority=\"1\">%s</contact>\n", mto);
13089 if (pidfstate[0] == 'b')
13090 ast_str_append(tmp, 0, "<status><basic>open</basic></status>\n");
13091 else
13092 ast_str_append(tmp, 0, "<status><basic>%s</basic></status>\n", (local_state != NOTIFY_CLOSED) ? "open" : "closed");
13093 ast_str_append(tmp, 0, "</tuple>\n</presence>\n");
13094 break;
13095 case DIALOG_INFO_XML:
13096 ast_str_append(tmp, 0, "<?xml version=\"1.0\"?>\n");
13097 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);
13098 if ((state & AST_EXTENSION_RINGING) && sip_cfg.notifyringing) {
13099 const char *local_display = exten;
13100 char *local_target = ast_strdupa(mto);
13101 const char *remote_display = exten;
13102
13103
13104
13105
13106
13107
13108
13109
13110 char *remote_target = ast_strdupa(mto);
13111
13112
13113
13114
13115 if (sip_cfg.notifycid) {
13116 struct ast_channel *caller;
13117
13118 if ((caller = ast_channel_callback(find_calling_channel, NULL, p, 0))) {
13119 char *cid_num;
13120 char *connected_num;
13121 int need;
13122
13123 ast_channel_lock(caller);
13124 cid_num = S_COR(caller->caller.id.number.valid,
13125 caller->caller.id.number.str, "");
13126 need = strlen(cid_num) + strlen(p->fromdomain) + sizeof("sip:@");
13127 remote_target = ast_alloca(need);
13128 snprintf(remote_target, need, "sip:%s@%s", cid_num, p->fromdomain);
13129
13130 remote_display = ast_strdupa(S_COR(caller->caller.id.name.valid,
13131 caller->caller.id.name.str, ""));
13132
13133 connected_num = S_COR(caller->connected.id.number.valid,
13134 caller->connected.id.number.str, "");
13135 need = strlen(connected_num) + strlen(p->fromdomain) + sizeof("sip:@");
13136 local_target = ast_alloca(need);
13137 snprintf(local_target, need, "sip:%s@%s", connected_num, p->fromdomain);
13138
13139 local_display = ast_strdupa(S_COR(caller->connected.id.name.valid,
13140 caller->connected.id.name.str, ""));
13141
13142 ast_channel_unlock(caller);
13143 caller = ast_channel_unref(caller);
13144 }
13145
13146
13147
13148 if (sip_cfg.pedanticsipchecking) {
13149 ast_str_append(tmp, 0, "<dialog id=\"%s\" call-id=\"pickup-%s\" local-tag=\"%s\" remote-tag=\"%s\" direction=\"recipient\">\n",
13150 exten, p->callid, p->theirtag, p->tag);
13151 } else {
13152 ast_str_append(tmp, 0, "<dialog id=\"%s\" call-id=\"pickup-%s\" direction=\"recipient\">\n",
13153 exten, p->callid);
13154 }
13155 ast_str_append(tmp, 0,
13156 "<remote>\n"
13157
13158
13159 "<identity display=\"%s\">%s</identity>\n"
13160 "<target uri=\"%s\"/>\n"
13161 "</remote>\n"
13162 "<local>\n"
13163 "<identity display=\"%s\">%s</identity>\n"
13164 "<target uri=\"%s\"/>\n"
13165 "</local>\n",
13166 remote_display, remote_target, remote_target, local_display, local_target, local_target);
13167 } else {
13168 ast_str_append(tmp, 0, "<dialog id=\"%s\" direction=\"recipient\">\n", exten);
13169 }
13170
13171 } else {
13172 ast_str_append(tmp, 0, "<dialog id=\"%s\">\n", exten);
13173 }
13174 ast_str_append(tmp, 0, "<state>%s</state>\n", statestring);
13175 if (state == AST_EXTENSION_ONHOLD) {
13176 ast_str_append(tmp, 0, "<local>\n<target uri=\"%s\">\n"
13177 "<param pname=\"+sip.rendering\" pvalue=\"no\"/>\n"
13178 "</target>\n</local>\n", mto);
13179 }
13180 ast_str_append(tmp, 0, "</dialog>\n</dialog-info>\n");
13181 break;
13182 case NONE:
13183 default:
13184 break;
13185 }
13186 }
13187
13188 static int transmit_cc_notify(struct ast_cc_agent *agent, struct sip_pvt *subscription, enum sip_cc_notify_state state)
13189 {
13190 struct sip_request req;
13191 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
13192 char uri[SIPBUFSIZE];
13193 char state_str[64];
13194 char subscription_state_hdr[64];
13195
13196 if (state < CC_QUEUED || state > CC_READY) {
13197 ast_log(LOG_WARNING, "Invalid state provided for transmit_cc_notify (%d)\n", state);
13198 return -1;
13199 }
13200
13201 reqprep(&req, subscription, SIP_NOTIFY, 0, TRUE);
13202 snprintf(state_str, sizeof(state_str), "%s\r\n", sip_cc_notify_state_map[state].state_string);
13203 add_header(&req, "Event", "call-completion");
13204 add_header(&req, "Content-Type", "application/call-completion");
13205 snprintf(subscription_state_hdr, sizeof(subscription_state_hdr), "active;expires=%d", subscription->expiry);
13206 add_header(&req, "Subscription-State", subscription_state_hdr);
13207 if (state == CC_READY) {
13208 generate_uri(subscription, agent_pvt->notify_uri, sizeof(agent_pvt->notify_uri));
13209 snprintf(uri, sizeof(uri) - 1, "cc-URI: %s\r\n", agent_pvt->notify_uri);
13210 }
13211 add_content(&req, state_str);
13212 if (state == CC_READY) {
13213 add_content(&req, uri);
13214 }
13215 return send_request(subscription, &req, XMIT_RELIABLE, subscription->ocseq);
13216 }
13217
13218
13219 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout)
13220 {
13221 struct ast_str *tmp = ast_str_alloca(4000);
13222 char from[256], to[256];
13223 char *c, *mfrom, *mto;
13224 struct sip_request req;
13225 const struct cfsubscription_types *subscriptiontype;
13226
13227
13228 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
13229 return 0;
13230 }
13231
13232 memset(from, 0, sizeof(from));
13233 memset(to, 0, sizeof(to));
13234
13235 subscriptiontype = find_subscription_type(p->subscribed);
13236
13237 ast_copy_string(from, get_header(&p->initreq, "From"), sizeof(from));
13238 c = get_in_brackets(from);
13239 if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
13240 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
13241 return -1;
13242 }
13243
13244 mfrom = remove_uri_parameters(c);
13245
13246 ast_copy_string(to, get_header(&p->initreq, "To"), sizeof(to));
13247 c = get_in_brackets(to);
13248 if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
13249 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
13250 return -1;
13251 }
13252 mto = remove_uri_parameters(c);
13253
13254 reqprep(&req, p, SIP_NOTIFY, 0, 1);
13255
13256 switch(state) {
13257 case AST_EXTENSION_DEACTIVATED:
13258 if (timeout)
13259 add_header(&req, "Subscription-State", "terminated;reason=timeout");
13260 else {
13261 add_header(&req, "Subscription-State", "terminated;reason=probation");
13262 add_header(&req, "Retry-After", "60");
13263 }
13264 break;
13265 case AST_EXTENSION_REMOVED:
13266 add_header(&req, "Subscription-State", "terminated;reason=noresource");
13267 break;
13268 default:
13269 if (p->expiry)
13270 add_header(&req, "Subscription-State", "active");
13271 else
13272 add_header(&req, "Subscription-State", "terminated;reason=timeout");
13273 }
13274
13275 switch (p->subscribed) {
13276 case XPIDF_XML:
13277 case CPIM_PIDF_XML:
13278 add_header(&req, "Event", subscriptiontype->event);
13279 state_notify_build_xml(state, full, p->exten, p->context, &tmp, p, p->subscribed, mfrom, mto);
13280 add_header(&req, "Content-Type", subscriptiontype->mediatype);
13281 p->dialogver++;
13282 break;
13283 case PIDF_XML:
13284 add_header(&req, "Event", subscriptiontype->event);
13285 state_notify_build_xml(state, full, p->exten, p->context, &tmp, p, p->subscribed, mfrom, mto);
13286 add_header(&req, "Content-Type", subscriptiontype->mediatype);
13287 p->dialogver++;
13288 break;
13289 case DIALOG_INFO_XML:
13290 add_header(&req, "Event", subscriptiontype->event);
13291 state_notify_build_xml(state, full, p->exten, p->context, &tmp, p, p->subscribed, mfrom, mto);
13292 add_header(&req, "Content-Type", subscriptiontype->mediatype);
13293 p->dialogver++;
13294 break;
13295 case NONE:
13296 default:
13297 break;
13298 }
13299
13300 add_content(&req, ast_str_buffer(tmp));
13301
13302 p->pendinginvite = p->ocseq;
13303
13304 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
13305 }
13306
13307
13308
13309
13310
13311
13312
13313 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten)
13314 {
13315 struct sip_request req;
13316 struct ast_str *out = ast_str_alloca(500);
13317 int ourport = (p->fromdomainport) ? p->fromdomainport : ast_sockaddr_port(&p->ourip);
13318 const char *domain;
13319 const char *exten = S_OR(vmexten, default_vmexten);
13320
13321 initreqprep(&req, p, SIP_NOTIFY, NULL);
13322 add_header(&req, "Event", "message-summary");
13323 add_header(&req, "Content-Type", default_notifymime);
13324 ast_str_append(&out, 0, "Messages-Waiting: %s\r\n", newmsgs ? "yes" : "no");
13325
13326
13327 domain = S_OR(p->fromdomain, ast_sockaddr_stringify_host_remote(&p->ourip));
13328
13329 if (!sip_standard_port(p->socket.type, ourport)) {
13330 if (p->socket.type == SIP_TRANSPORT_UDP) {
13331 ast_str_append(&out, 0, "Message-Account: sip:%s@%s:%d\r\n", exten, domain, ourport);
13332 } else {
13333 ast_str_append(&out, 0, "Message-Account: sip:%s@%s:%d;transport=%s\r\n", exten, domain, ourport, get_transport(p->socket.type));
13334 }
13335 } else {
13336 if (p->socket.type == SIP_TRANSPORT_UDP) {
13337 ast_str_append(&out, 0, "Message-Account: sip:%s@%s\r\n", exten, domain);
13338 } else {
13339 ast_str_append(&out, 0, "Message-Account: sip:%s@%s;transport=%s\r\n", exten, domain, get_transport(p->socket.type));
13340 }
13341 }
13342
13343
13344
13345 ast_str_append(&out, 0, "Voice-Message: %d/%d%s\r\n",
13346 newmsgs, oldmsgs, (ast_test_flag(&p->flags[1], SIP_PAGE2_BUGGY_MWI) ? "" : " (0/0)"));
13347
13348 if (p->subscribed) {
13349 if (p->expiry) {
13350 add_header(&req, "Subscription-State", "active");
13351 } else {
13352 add_header(&req, "Subscription-State", "terminated;reason=timeout");
13353 }
13354 }
13355
13356 add_content(&req, ast_str_buffer(out));
13357
13358 if (!p->initreq.headers) {
13359 initialize_initreq(p, &req);
13360 }
13361 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
13362 }
13363
13364
13365 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate)
13366 {
13367 struct sip_request req;
13368 char tmp[SIPBUFSIZE/2];
13369
13370 reqprep(&req, p, SIP_NOTIFY, 0, 1);
13371 snprintf(tmp, sizeof(tmp), "refer;id=%d", cseq);
13372 add_header(&req, "Event", tmp);
13373 add_header(&req, "Subscription-state", terminate ? "terminated;reason=noresource" : "active");
13374 add_header(&req, "Content-Type", "message/sipfrag;version=2.0");
13375 add_header(&req, "Allow", ALLOWED_METHODS);
13376 add_supported_header(p, &req);
13377
13378 snprintf(tmp, sizeof(tmp), "SIP/2.0 %s\r\n", message);
13379 add_content(&req, tmp);
13380
13381 if (!p->initreq.headers) {
13382 initialize_initreq(p, &req);
13383 }
13384
13385 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
13386 }
13387
13388 static int manager_sipnotify(struct mansession *s, const struct message *m)
13389 {
13390 const char *channame = astman_get_header(m, "Channel");
13391 struct ast_variable *vars = astman_get_variables(m);
13392 struct sip_pvt *p;
13393 struct ast_variable *header, *var;
13394
13395 if (ast_strlen_zero(channame)) {
13396 astman_send_error(s, m, "SIPNotify requires a channel name");
13397 return 0;
13398 }
13399
13400 if (!strncasecmp(channame, "sip/", 4)) {
13401 channame += 4;
13402 }
13403
13404 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
13405 astman_send_error(s, m, "Unable to build sip pvt data for notify (memory/socket error)");
13406 return 0;
13407 }
13408
13409 if (create_addr(p, channame, NULL, 0)) {
13410
13411 dialog_unlink_all(p);
13412 dialog_unref(p, "unref dialog inside for loop" );
13413
13414 astman_send_error(s, m, "Could not create address");
13415 return 0;
13416 }
13417
13418
13419 ast_set_flag(&p->flags[0], SIP_OUTGOING);
13420 sip_notify_allocate(p);
13421
13422 p->notify->headers = header = ast_variable_new("Subscription-State", "terminated", "");
13423
13424 for (var = vars; var; var = var->next) {
13425 if (!strcasecmp(var->name, "Content")) {
13426 if (ast_str_strlen(p->notify->content))
13427 ast_str_append(&p->notify->content, 0, "\r\n");
13428 ast_str_append(&p->notify->content, 0, "%s", var->value);
13429 } else if (!strcasecmp(var->name, "Content-Length")) {
13430 ast_log(LOG_WARNING, "it is not necessary to specify Content-Length, ignoring\n");
13431 } else {
13432 header->next = ast_variable_new(var->name, var->value, "");
13433 header = header->next;
13434 }
13435 }
13436
13437 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
13438 transmit_invite(p, SIP_NOTIFY, 0, 2, NULL);
13439 dialog_unref(p, "bump down the count of p since we're done with it.");
13440
13441 astman_send_ack(s, m, "Notify Sent");
13442 ast_variables_destroy(vars);
13443 return 0;
13444 }
13445
13446
13447
13448 static void update_redirecting(struct sip_pvt *p, const void *data, size_t datalen)
13449 {
13450 struct sip_request resp;
13451
13452 if (p->owner->_state == AST_STATE_UP || ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
13453 return;
13454 }
13455
13456 respprep(&resp, p, "181 Call is being forwarded", &p->initreq);
13457 add_diversion_header(&resp, p);
13458 send_response(p, &resp, XMIT_UNRELIABLE, 0);
13459 }
13460
13461
13462 static void update_connectedline(struct sip_pvt *p, const void *data, size_t datalen)
13463 {
13464
13465 if (!ast_test_flag(&p->flags[0], SIP_SENDRPID)) {
13466 return;
13467 }
13468 if (!p->owner->connected.id.number.valid
13469 || ast_strlen_zero(p->owner->connected.id.number.str)) {
13470 return;
13471 }
13472
13473 append_history(p, "ConnectedLine", "%s party is now %s <%s>",
13474 ast_test_flag(&p->flags[0], SIP_OUTGOING) ? "Calling" : "Called",
13475 S_COR(p->owner->connected.id.name.valid, p->owner->connected.id.name.str, ""),
13476 S_COR(p->owner->connected.id.number.valid, p->owner->connected.id.number.str, ""));
13477
13478 if (p->owner->_state == AST_STATE_UP || ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
13479 struct sip_request req;
13480
13481 if (!p->pendinginvite && (p->invitestate == INV_CONFIRMED || p->invitestate == INV_TERMINATED)) {
13482 reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ? SIP_UPDATE : SIP_INVITE, 0, 1);
13483
13484 add_header(&req, "Allow", ALLOWED_METHODS);
13485 add_supported_header(p, &req);
13486 add_rpid(&req, p);
13487 add_sdp(&req, p, FALSE, TRUE, FALSE);
13488
13489 initialize_initreq(p, &req);
13490 p->lastinvite = p->ocseq;
13491 ast_set_flag(&p->flags[0], SIP_OUTGOING);
13492 p->invitestate = INV_CALLING;
13493 send_request(p, &req, XMIT_CRITICAL, p->ocseq);
13494 } else if ((is_method_allowed(&p->allowed_methods, SIP_UPDATE)) && (!ast_strlen_zero(p->okcontacturi))) {
13495 reqprep(&req, p, SIP_UPDATE, 0, 1);
13496 add_rpid(&req, p);
13497 add_header(&req, "X-Asterisk-rpid-update", "Yes");
13498 send_request(p, &req, XMIT_CRITICAL, p->ocseq);
13499 } else {
13500
13501 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
13502 }
13503 } else {
13504 ast_set_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND);
13505 if (ast_test_flag(&p->flags[1], SIP_PAGE2_RPID_IMMEDIATE)) {
13506 struct sip_request resp;
13507
13508 if ((p->owner->_state == AST_STATE_RING) && !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT)) {
13509 ast_clear_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND);
13510 respprep(&resp, p, "180 Ringing", &p->initreq);
13511 add_rpid(&resp, p);
13512 send_response(p, &resp, XMIT_UNRELIABLE, 0);
13513 ast_set_flag(&p->flags[0], SIP_RINGING);
13514 } else if (p->owner->_state == AST_STATE_RINGING) {
13515 ast_clear_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND);
13516 respprep(&resp, p, "183 Session Progress", &p->initreq);
13517 add_rpid(&resp, p);
13518 send_response(p, &resp, XMIT_UNRELIABLE, 0);
13519 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
13520 } else {
13521 ast_debug(1, "Unable able to send update to '%s' in state '%s'\n", p->owner->name, ast_state2str(p->owner->_state));
13522 }
13523 }
13524 }
13525 }
13526
13527 static const struct _map_x_s regstatestrings[] = {
13528 { REG_STATE_FAILED, "Failed" },
13529 { REG_STATE_UNREGISTERED, "Unregistered"},
13530 { REG_STATE_REGSENT, "Request Sent"},
13531 { REG_STATE_AUTHSENT, "Auth. Sent"},
13532 { REG_STATE_REGISTERED, "Registered"},
13533 { REG_STATE_REJECTED, "Rejected"},
13534 { REG_STATE_TIMEOUT, "Timeout"},
13535 { REG_STATE_NOAUTH, "No Authentication"},
13536 { -1, NULL }
13537 };
13538
13539
13540 static const char *regstate2str(enum sipregistrystate regstate)
13541 {
13542 return map_x_s(regstatestrings, regstate, "Unknown");
13543 }
13544
13545
13546
13547
13548
13549
13550
13551 static int sip_reregister(const void *data)
13552 {
13553
13554 struct sip_registry *r = (struct sip_registry *) data;
13555
13556
13557 if (!r) {
13558 return 0;
13559 }
13560
13561 if (r->call && r->call->do_history) {
13562 append_history(r->call, "RegistryRenew", "Account: %s@%s", r->username, r->hostname);
13563 }
13564
13565
13566 if (sipdebug) {
13567 ast_log(LOG_NOTICE, " -- Re-registration for %s@%s\n", r->username, r->hostname);
13568 }
13569
13570 r->expire = -1;
13571 r->expiry = r->configured_expiry;
13572 __sip_do_register(r);
13573 registry_unref(r, "unref the re-register scheduled event");
13574 return 0;
13575 }
13576
13577
13578
13579
13580 static int __sip_do_register(struct sip_registry *r)
13581 {
13582 int res;
13583
13584 res = transmit_register(r, SIP_REGISTER, NULL, NULL);
13585 return res;
13586 }
13587
13588
13589
13590
13591
13592
13593
13594 static int sip_reg_timeout(const void *data)
13595 {
13596
13597
13598 struct sip_registry *r = (struct sip_registry *)data;
13599 struct sip_pvt *p;
13600
13601
13602 if (!r) {
13603 return 0;
13604 }
13605
13606 if (r->dnsmgr) {
13607
13608 ast_dnsmgr_refresh(r->dnsmgr);
13609 }
13610
13611
13612
13613
13614
13615 if (r->call) {
13616
13617
13618 p = r->call;
13619 sip_pvt_lock(p);
13620 pvt_set_needdestroy(p, "registration timeout");
13621
13622 __sip_pretend_ack(p);
13623 sip_pvt_unlock(p);
13624
13625
13626
13627 if (p->registry) {
13628 p->registry = registry_unref(p->registry, "p->registry unreffed");
13629 }
13630 r->call = dialog_unref(r->call, "unrefing r->call");
13631 }
13632
13633 r->timeout = -1;
13634 if (global_regattempts_max && r->regattempts >= global_regattempts_max) {
13635
13636
13637
13638 ast_log(LOG_NOTICE, " -- Last Registration Attempt #%d failed, Giving up forever trying to register '%s@%s'\n", r->regattempts, r->username, r->hostname);
13639 r->regstate = REG_STATE_FAILED;
13640 } else {
13641 r->regstate = REG_STATE_UNREGISTERED;
13642 transmit_register(r, SIP_REGISTER, NULL, NULL);
13643 ast_log(LOG_NOTICE, " -- Registration for '%s@%s' timed out, trying again (Attempt #%d)\n", r->username, r->hostname, r->regattempts);
13644 }
13645 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));
13646 registry_unref(r, "unreffing registry_unref r");
13647 return 0;
13648 }
13649
13650 static const char *sip_sanitized_host(const char *host)
13651 {
13652 struct ast_sockaddr addr = { { 0, 0, }, };
13653
13654
13655
13656
13657 if (!ast_sockaddr_parse(&addr, host, PARSE_PORT_FORBID)) {
13658 return host;
13659 }
13660 return ast_sockaddr_stringify_host_remote(&addr);
13661 }
13662
13663
13664
13665
13666 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader)
13667 {
13668 struct sip_request req;
13669 char from[256];
13670 char to[256];
13671 char tmp[80];
13672 char addr[80];
13673 struct sip_pvt *p;
13674 struct sip_peer *peer = NULL;
13675 int res;
13676 int portno = 0;
13677
13678
13679 if (r == NULL || ((auth == NULL) && (r->regstate == REG_STATE_REGSENT || r->regstate == REG_STATE_AUTHSENT))) {
13680 if (r) {
13681 ast_log(LOG_NOTICE, "Strange, trying to register %s@%s when registration already pending\n", r->username, r->hostname);
13682 }
13683 return 0;
13684 }
13685
13686 if (r->dnsmgr == NULL) {
13687 char transport[MAXHOSTNAMELEN];
13688 peer = find_peer(r->hostname, NULL, TRUE, FINDPEERS, FALSE, 0);
13689 snprintf(transport, sizeof(transport), "_%s._%s",get_srv_service(r->transport), get_srv_protocol(r->transport));
13690 r->us.ss.ss_family = get_address_family_filter(r->transport);
13691
13692
13693
13694
13695
13696 if (!obproxy_get(r->call, peer)) {
13697 registry_addref(r, "add reg ref for dnsmgr");
13698 ast_dnsmgr_lookup_cb(peer ? peer->tohost : r->hostname, &r->us, &r->dnsmgr, sip_cfg.srvlookup ? transport : NULL, on_dns_update_registry, r);
13699 if (!r->dnsmgr) {
13700
13701 registry_unref(r, "remove reg ref, dnsmgr disabled");
13702 }
13703 }
13704 if (peer) {
13705 peer = unref_peer(peer, "removing peer ref for dnsmgr_lookup");
13706 }
13707 }
13708
13709 if (r->call) {
13710 if (!auth) {
13711 ast_log(LOG_WARNING, "Already have a REGISTER going on to %s@%s?? \n", r->username, r->hostname);
13712 return 0;
13713 } else {
13714 p = dialog_ref(r->call, "getting a copy of the r->call dialog in transmit_register");
13715 make_our_tag(p);
13716 ast_string_field_set(p, theirtag, NULL);
13717 }
13718 } else {
13719
13720 if (!r->callid_valid) {
13721 build_callid_registry(r, &internip, default_fromdomain);
13722 r->callid_valid = TRUE;
13723 }
13724
13725 if (!(p = sip_alloc( r->callid, NULL, 0, SIP_REGISTER, NULL))) {
13726 ast_log(LOG_WARNING, "Unable to allocate registration transaction (memory or socket error)\n");
13727 return 0;
13728 }
13729
13730 if (p->do_history) {
13731 append_history(p, "RegistryInit", "Account: %s@%s", r->username, r->hostname);
13732 }
13733
13734
13735 if (!ast_sockaddr_isnull(&r->us)) {
13736 if (!ast_sockaddr_port(&r->us) && r->portno) {
13737 ast_sockaddr_set_port(&r->us, r->portno);
13738 }
13739
13740
13741
13742
13743
13744 if ((peer = find_peer(S_OR(r->peername, r->hostname), NULL, TRUE, FINDPEERS, FALSE, 0))) {
13745 if (ast_sockaddr_cmp(&peer->addr, &r->us)) {
13746 on_dns_update_peer(&peer->addr, &r->us, peer);
13747 }
13748 peer = unref_peer(peer, "unref after find_peer");
13749 }
13750 }
13751
13752
13753 if (create_addr(p, S_OR(r->peername, r->hostname), &r->us, 0)) {
13754
13755
13756 dialog_unlink_all(p);
13757 p = dialog_unref(p, "unref dialog after unlink_all");
13758 if (r->timeout > -1) {
13759 AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
13760 registry_unref(_data, "del for REPLACE of registry ptr"),
13761 registry_unref(r, "object ptr dec when SCHED_REPLACE add failed"),
13762 registry_addref(r,"add for REPLACE registry ptr"));
13763 ast_log(LOG_WARNING, "Still have a registration timeout for %s@%s (create_addr() error), %d\n", r->username, r->hostname, r->timeout);
13764 } else {
13765 r->timeout = ast_sched_add(sched, global_reg_timeout * 1000, sip_reg_timeout, registry_addref(r, "add for REPLACE registry ptr"));
13766 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);
13767 }
13768 r->regattempts++;
13769 return 0;
13770 }
13771
13772
13773 ast_string_field_set(r, callid, p->callid);
13774
13775 if (!r->dnsmgr && r->portno) {
13776 ast_sockaddr_set_port(&p->sa, r->portno);
13777 ast_sockaddr_set_port(&p->recv, r->portno);
13778 }
13779 if (!ast_strlen_zero(p->fromdomain)) {
13780 portno = (p->fromdomainport) ? p->fromdomainport : STANDARD_SIP_PORT;
13781 } else if (!ast_strlen_zero(r->regdomain)) {
13782 portno = (r->regdomainport) ? r->regdomainport : STANDARD_SIP_PORT;
13783 } else {
13784 portno = ast_sockaddr_port(&p->sa);
13785 }
13786
13787 ast_set_flag(&p->flags[0], SIP_OUTGOING);
13788 r->call = dialog_ref(p, "copying dialog into registry r->call");
13789 p->registry = registry_addref(r, "transmit_register: addref to p->registry in transmit_register");
13790 if (!ast_strlen_zero(r->secret)) {
13791 ast_string_field_set(p, peersecret, r->secret);
13792 }
13793 if (!ast_strlen_zero(r->md5secret))
13794 ast_string_field_set(p, peermd5secret, r->md5secret);
13795
13796
13797 if (!ast_strlen_zero(r->authuser)) {
13798 ast_string_field_set(p, peername, r->authuser);
13799 ast_string_field_set(p, authname, r->authuser);
13800 } else if (!ast_strlen_zero(r->username)) {
13801 ast_string_field_set(p, peername, r->username);
13802 ast_string_field_set(p, authname, r->username);
13803 ast_string_field_set(p, fromuser, r->username);
13804 }
13805 if (!ast_strlen_zero(r->username)) {
13806 ast_string_field_set(p, username, r->username);
13807 }
13808
13809 if (!ast_strlen_zero(r->callback)) {
13810 ast_string_field_set(p, exten, r->callback);
13811 }
13812
13813
13814 set_socket_transport(&p->socket, r->transport);
13815 if (r->transport == SIP_TRANSPORT_TLS || r->transport == SIP_TRANSPORT_TCP) {
13816 p->socket.port =
13817 htons(ast_sockaddr_port(&sip_tcp_desc.local_address));
13818 }
13819
13820
13821
13822
13823
13824
13825 ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
13826 build_contact(p);
13827 }
13828
13829
13830 if (auth == NULL) {
13831 if (r->timeout > -1) {
13832 ast_log(LOG_WARNING, "Still have a registration timeout, #%d - deleting it\n", r->timeout);
13833 }
13834 AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
13835 registry_unref(_data,"reg ptr unrefed from del in SCHED_REPLACE"),
13836 registry_unref(r,"reg ptr unrefed from add failure in SCHED_REPLACE"),
13837 registry_addref(r,"reg ptr reffed from add in SCHED_REPLACE"));
13838 ast_debug(1, "Scheduled a registration timeout for %s id #%d \n", r->hostname, r->timeout);
13839 }
13840
13841 snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%s", r->username, S_OR(r->regdomain, sip_sanitized_host(p->tohost)), p->tag);
13842 if (!ast_strlen_zero(p->theirtag)) {
13843 snprintf(to, sizeof(to), "<sip:%s@%s>;tag=%s", r->username, S_OR(r->regdomain, sip_sanitized_host(p->tohost)), p->theirtag);
13844 } else {
13845 snprintf(to, sizeof(to), "<sip:%s@%s>", r->username, S_OR(r->regdomain, sip_sanitized_host(p->tohost)));
13846 }
13847
13848
13849
13850 if (portno && portno != STANDARD_SIP_PORT) {
13851 snprintf(addr, sizeof(addr), "sip:%s:%d", S_OR(p->fromdomain,S_OR(r->regdomain, sip_sanitized_host(r->hostname))), portno);
13852 } else {
13853 snprintf(addr, sizeof(addr), "sip:%s", S_OR(p->fromdomain,S_OR(r->regdomain, sip_sanitized_host(r->hostname))));
13854 }
13855
13856 ast_string_field_set(p, uri, addr);
13857
13858 p->branch ^= ast_random();
13859
13860 init_req(&req, sipmethod, addr);
13861
13862
13863 snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, sip_methods[sipmethod].text);
13864 p->ocseq = r->ocseq;
13865
13866 build_via(p);
13867 add_header(&req, "Via", p->via);
13868 add_header_max_forwards(p, &req);
13869 add_header(&req, "From", from);
13870 add_header(&req, "To", to);
13871 add_header(&req, "Call-ID", p->callid);
13872 add_header(&req, "CSeq", tmp);
13873 if (!ast_strlen_zero(global_useragent))
13874 add_header(&req, "User-Agent", global_useragent);
13875
13876 if (auth) {
13877 add_header(&req, authheader, auth);
13878 } else if (!ast_strlen_zero(r->nonce)) {
13879 char digest[1024];
13880
13881
13882
13883
13884
13885
13886 if (sipdebug) {
13887 ast_debug(1, " >>> Re-using Auth data for %s@%s\n", r->username, r->hostname);
13888 }
13889 ast_string_field_set(p, realm, r->realm);
13890 ast_string_field_set(p, nonce, r->nonce);
13891 ast_string_field_set(p, domain, r->authdomain);
13892 ast_string_field_set(p, opaque, r->opaque);
13893 ast_string_field_set(p, qop, r->qop);
13894 p->noncecount = ++r->noncecount;
13895
13896 memset(digest, 0, sizeof(digest));
13897 if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
13898 add_header(&req, "Authorization", digest);
13899 } else {
13900 ast_log(LOG_NOTICE, "No authorization available for authentication of registration to %s@%s\n", r->username, r->hostname);
13901 }
13902 }
13903
13904 snprintf(tmp, sizeof(tmp), "%d", r->expiry);
13905 add_header(&req, "Expires", tmp);
13906 add_header(&req, "Contact", p->our_contact);
13907
13908 initialize_initreq(p, &req);
13909 if (sip_debug_test_pvt(p)) {
13910 ast_verbose("REGISTER %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
13911 }
13912 r->regstate = auth ? REG_STATE_AUTHSENT : REG_STATE_REGSENT;
13913 r->regattempts++;
13914 ast_debug(4, "REGISTER attempt %d to %s@%s\n", r->regattempts, r->username, r->hostname);
13915 res = send_request(p, &req, XMIT_CRITICAL, p->ocseq);
13916 dialog_unref(p, "p is finished here at the end of transmit_register");
13917 return res;
13918 }
13919
13920
13921 static int transmit_message_with_text(struct sip_pvt *p, const char *text)
13922 {
13923 struct sip_request req;
13924
13925 reqprep(&req, p, SIP_MESSAGE, 0, 1);
13926 add_text(&req, text);
13927 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
13928 }
13929
13930
13931 static int sip_refer_allocate(struct sip_pvt *p)
13932 {
13933 p->refer = ast_calloc(1, sizeof(struct sip_refer));
13934 return p->refer ? 1 : 0;
13935 }
13936
13937
13938 static int sip_notify_allocate(struct sip_pvt *p)
13939 {
13940 p->notify = ast_calloc(1, sizeof(struct sip_notify));
13941 if (p->notify) {
13942 p->notify->content = ast_str_create(128);
13943 }
13944 return p->notify ? 1 : 0;
13945 }
13946
13947
13948
13949
13950
13951
13952 static int transmit_refer(struct sip_pvt *p, const char *dest)
13953 {
13954 struct sip_request req = {
13955 .headers = 0,
13956 };
13957 char from[256];
13958 const char *of;
13959 char *c;
13960 char referto[256];
13961 int use_tls=FALSE;
13962
13963 if (sipdebug) {
13964 ast_debug(1, "SIP transfer of %s to %s\n", p->callid, dest);
13965 }
13966
13967
13968 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
13969 of = get_header(&p->initreq, "To");
13970 } else {
13971 of = get_header(&p->initreq, "From");
13972 }
13973
13974 ast_copy_string(from, of, sizeof(from));
13975 of = get_in_brackets(from);
13976 ast_string_field_set(p, from, of);
13977 if (!strncasecmp(of, "sip:", 4)) {
13978 of += 4;
13979 } else if (!strncasecmp(of, "sips:", 5)) {
13980 of += 5;
13981 use_tls = TRUE;
13982 } else {
13983 ast_log(LOG_NOTICE, "From address missing 'sip(s):', assuming sip:\n");
13984 }
13985
13986 if (strchr(dest, '@')) {
13987 c = NULL;
13988 } else if ((c = strchr(of, '@'))) {
13989 *c++ = '\0';
13990 }
13991 if (c) {
13992 snprintf(referto, sizeof(referto), "<sip%s:%s@%s>", use_tls ? "s" : "", dest, c);
13993 } else {
13994 snprintf(referto, sizeof(referto), "<sip%s:%s>", use_tls ? "s" : "", dest);
13995 }
13996
13997
13998 sip_refer_allocate(p);
13999 ast_copy_string(p->refer->refer_to, referto, sizeof(p->refer->refer_to));
14000 ast_copy_string(p->refer->referred_by, p->our_contact, sizeof(p->refer->referred_by));
14001 p->refer->status = REFER_SENT;
14002
14003 reqprep(&req, p, SIP_REFER, 0, 1);
14004
14005 add_header(&req, "Refer-To", referto);
14006 add_header(&req, "Allow", ALLOWED_METHODS);
14007 add_supported_header(p, &req);
14008 if (!ast_strlen_zero(p->our_contact)) {
14009 add_header(&req, "Referred-By", p->our_contact);
14010 }
14011
14012 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022 }
14023
14024
14025 static int transmit_info_with_aoc(struct sip_pvt *p, struct ast_aoc_decoded *decoded)
14026 {
14027 struct sip_request req;
14028 struct ast_str *str = ast_str_alloca(512);
14029 const struct ast_aoc_unit_entry *unit_entry = ast_aoc_get_unit_info(decoded, 0);
14030 enum ast_aoc_charge_type charging = ast_aoc_get_charge_type(decoded);
14031
14032 reqprep(&req, p, SIP_INFO, 0, 1);
14033
14034 if (ast_aoc_get_msg_type(decoded) == AST_AOC_D) {
14035 ast_str_append(&str, 0, "type=active;");
14036 } else if (ast_aoc_get_msg_type(decoded) == AST_AOC_E) {
14037 ast_str_append(&str, 0, "type=terminated;");
14038 } else {
14039
14040 return -1;
14041 }
14042
14043 switch (charging) {
14044 case AST_AOC_CHARGE_FREE:
14045 ast_str_append(&str, 0, "free-of-charge;");
14046 break;
14047 case AST_AOC_CHARGE_CURRENCY:
14048 ast_str_append(&str, 0, "charging;");
14049 ast_str_append(&str, 0, "charging-info=currency;");
14050 ast_str_append(&str, 0, "amount=%u;", ast_aoc_get_currency_amount(decoded));
14051 ast_str_append(&str, 0, "multiplier=%s;", ast_aoc_get_currency_multiplier_decimal(decoded));
14052 if (!ast_strlen_zero(ast_aoc_get_currency_name(decoded))) {
14053 ast_str_append(&str, 0, "currency=%s;", ast_aoc_get_currency_name(decoded));
14054 }
14055 break;
14056 case AST_AOC_CHARGE_UNIT:
14057 ast_str_append(&str, 0, "charging;");
14058 ast_str_append(&str, 0, "charging-info=pulse;");
14059 if (unit_entry) {
14060 ast_str_append(&str, 0, "recorded-units=%u;", unit_entry->amount);
14061 }
14062 break;
14063 default:
14064 ast_str_append(&str, 0, "not-available;");
14065 };
14066
14067 add_header(&req, "AOC", ast_str_buffer(str));
14068
14069 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
14070 }
14071
14072
14073 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration)
14074 {
14075 struct sip_request req;
14076
14077 reqprep(&req, p, SIP_INFO, 0, 1);
14078 add_digit(&req, digit, duration, (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_SHORTINFO));
14079 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
14080 }
14081
14082
14083 static int transmit_info_with_vidupdate(struct sip_pvt *p)
14084 {
14085 struct sip_request req;
14086
14087 reqprep(&req, p, SIP_INFO, 0, 1);
14088 add_vidupdate(&req);
14089 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
14090 }
14091
14092
14093
14094
14095 static int transmit_request(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch)
14096 {
14097 struct sip_request resp;
14098
14099 reqprep(&resp, p, sipmethod, seqno, newbranch);
14100 if (sipmethod == SIP_CANCEL && p->answered_elsewhere) {
14101 add_header(&resp, "Reason", "SIP;cause=200;text=\"Call completed elsewhere\"");
14102 }
14103
14104 if (sipmethod == SIP_ACK) {
14105 p->invitestate = INV_CONFIRMED;
14106 }
14107
14108 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
14109 }
14110
14111
14112 static void auth_headers(enum sip_auth_type code, char **header, char **respheader)
14113 {
14114 if (code == WWW_AUTH) {
14115 *header = "WWW-Authenticate";
14116 *respheader = "Authorization";
14117 } else if (code == PROXY_AUTH) {
14118 *header = "Proxy-Authenticate";
14119 *respheader = "Proxy-Authorization";
14120 } else {
14121 ast_verbose("-- wrong response code %d\n", code);
14122 *header = *respheader = "Invalid";
14123 }
14124 }
14125
14126
14127 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch)
14128 {
14129 struct sip_request resp;
14130
14131 reqprep(&resp, p, sipmethod, seqno, newbranch);
14132 if (!ast_strlen_zero(p->realm)) {
14133 char digest[1024];
14134
14135 memset(digest, 0, sizeof(digest));
14136 if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
14137 char *dummy, *response;
14138 enum sip_auth_type code = p->options ? p->options->auth_type : PROXY_AUTH;
14139 auth_headers(code, &dummy, &response);
14140 add_header(&resp, response, digest);
14141 } else {
14142 ast_log(LOG_WARNING, "No authentication available for call %s\n", p->callid);
14143 }
14144 }
14145
14146
14147 if (sipmethod == SIP_BYE) {
14148 char buf[20];
14149
14150 if (ast_test_flag(&p->flags[1], SIP_PAGE2_Q850_REASON) && p->hangupcause) {
14151 sprintf(buf, "Q.850;cause=%i", p->hangupcause & 0x7f);
14152 add_header(&resp, "Reason", buf);
14153 }
14154
14155 add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->hangupcause));
14156 snprintf(buf, sizeof(buf), "%d", p->hangupcause);
14157 add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
14158 }
14159
14160 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
14161 }
14162
14163
14164 static void destroy_association(struct sip_peer *peer)
14165 {
14166 int realtimeregs = ast_check_realtime("sipregs");
14167 char *tablename = (realtimeregs) ? "sipregs" : "sippeers";
14168
14169 if (!sip_cfg.ignore_regexpire) {
14170 if (peer->rt_fromcontact && sip_cfg.peer_rtupdate) {
14171 ast_update_realtime(tablename, "name", peer->name, "fullcontact", "", "ipaddr", "", "port", "", "regseconds", "0", "regserver", "", "useragent", "", "lastms", "0", SENTINEL);
14172 } else {
14173 ast_db_del("SIP/Registry", peer->name);
14174 ast_db_del("SIP/PeerMethods", peer->name);
14175 }
14176 }
14177 }
14178
14179 static void set_socket_transport(struct sip_socket *socket, int transport)
14180 {
14181
14182 if (socket->type != transport) {
14183 socket->fd = -1;
14184 socket->type = transport;
14185 if (socket->tcptls_session) {
14186 ao2_ref(socket->tcptls_session, -1);
14187 socket->tcptls_session = NULL;
14188 }
14189 }
14190 }
14191
14192
14193 static int expire_register(const void *data)
14194 {
14195 struct sip_peer *peer = (struct sip_peer *)data;
14196
14197 if (!peer) {
14198 return 0;
14199 }
14200
14201 peer->expire = -1;
14202 peer->portinuri = 0;
14203
14204 destroy_association(peer);
14205 set_socket_transport(&peer->socket, peer->default_outbound_transport);
14206
14207 if (peer->socket.tcptls_session) {
14208 ao2_ref(peer->socket.tcptls_session, -1);
14209 peer->socket.tcptls_session = NULL;
14210 }
14211
14212 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
14213 register_peer_exten(peer, FALSE);
14214 ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "SIP/%s", peer->name);
14215
14216
14217
14218
14219 if (peer->is_realtime) {
14220 ast_debug(3, "-REALTIME- peer expired registration. Name: %s. Realtime peer objects now %d\n", peer->name, rpeerobjs);
14221 }
14222
14223 if (peer->selfdestruct ||
14224 ast_test_flag(&peer->flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
14225 unlink_peer_from_tables(peer);
14226 } else if (!ast_sockaddr_isnull(&peer->addr)) {
14227
14228
14229
14230 ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
14231 }
14232
14233
14234
14235 memset(&peer->addr, 0, sizeof(peer->addr));
14236
14237 unref_peer(peer, "removing peer ref for expire_register");
14238
14239 return 0;
14240 }
14241
14242
14243 static int sip_poke_peer_s(const void *data)
14244 {
14245 struct sip_peer *peer = (struct sip_peer *)data;
14246 struct sip_peer *foundpeer;
14247
14248 peer->pokeexpire = -1;
14249
14250 foundpeer = ao2_find(peers, peer, OBJ_POINTER);
14251 if (!foundpeer) {
14252 unref_peer(peer, "removing poke peer ref");
14253 return 0;
14254 } else if (foundpeer->name != peer->name) {
14255 unref_peer(foundpeer, "removing above peer ref");
14256 unref_peer(peer, "removing poke peer ref");
14257 return 0;
14258 }
14259
14260 unref_peer(foundpeer, "removing above peer ref");
14261 sip_poke_peer(peer, 0);
14262 unref_peer(peer, "removing poke peer ref");
14263
14264 return 0;
14265 }
14266
14267
14268 static void reg_source_db(struct sip_peer *peer)
14269 {
14270 char data[256];
14271 struct ast_sockaddr sa;
14272 int expire;
14273 char full_addr[128];
14274 AST_DECLARE_APP_ARGS(args,
14275 AST_APP_ARG(addr);
14276 AST_APP_ARG(port);
14277 AST_APP_ARG(expiry_str);
14278 AST_APP_ARG(username);
14279 AST_APP_ARG(contact);
14280 );
14281
14282
14283 if (peer->rt_fromcontact && sip_cfg.peer_rtupdate) {
14284 return;
14285 }
14286 if (ast_db_get("SIP/Registry", peer->name, data, sizeof(data))) {
14287 return;
14288 }
14289
14290 AST_NONSTANDARD_RAW_ARGS(args, data, ':');
14291
14292 snprintf(full_addr, sizeof(full_addr), "%s:%s", args.addr, args.port);
14293
14294 if (!ast_sockaddr_parse(&sa, full_addr, 0)) {
14295 return;
14296 }
14297
14298 if (args.expiry_str) {
14299 expire = atoi(args.expiry_str);
14300 } else {
14301 return;
14302 }
14303
14304 if (args.username) {
14305 ast_string_field_set(peer, username, args.username);
14306 }
14307 if (args.contact) {
14308 ast_string_field_set(peer, fullcontact, args.contact);
14309 }
14310
14311 ast_debug(2, "SIP Seeding peer from astdb: '%s' at %s@%s for %d\n",
14312 peer->name, peer->username, ast_sockaddr_stringify_host(&sa), expire);
14313
14314 ast_sockaddr_copy(&peer->addr, &sa);
14315 if (peer->maxms) {
14316
14317 AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
14318 ast_random() % ((peer->qualifyfreq) ? peer->qualifyfreq : global_qualifyfreq) + 1,
14319 sip_poke_peer_s, peer,
14320 unref_peer(_data, "removing poke peer ref"),
14321 unref_peer(peer, "removing poke peer ref"),
14322 ref_peer(peer, "adding poke peer ref"));
14323 }
14324 AST_SCHED_REPLACE_UNREF(peer->expire, sched, (expire + 10) * 1000, expire_register, peer,
14325 unref_peer(_data, "remove registration ref"),
14326 unref_peer(peer, "remove registration ref"),
14327 ref_peer(peer, "add registration ref"));
14328 register_peer_exten(peer, TRUE);
14329 }
14330
14331
14332 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req)
14333 {
14334 char contact[SIPBUFSIZE];
14335 char *c;
14336
14337
14338 ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
14339 c = get_in_brackets(contact);
14340
14341
14342 ast_string_field_set(pvt, fullcontact, c);
14343
14344
14345 ast_string_field_set(pvt, okcontacturi, c);
14346
14347
14348
14349 return TRUE;
14350 }
14351
14352
14353
14354
14355
14356
14357
14358 static int parse_uri_legacy_check(char *uri, const char *scheme, char **user, char **pass, char **hostport, char **transport)
14359 {
14360 int ret = parse_uri(uri, scheme, user, pass, hostport, transport);
14361 if (sip_cfg.legacy_useroption_parsing) {
14362 char *p;
14363 if ((p = strchr(uri, (int)';'))) {
14364 *p = '\0';
14365 }
14366 }
14367 return ret;
14368 }
14369
14370 static int __set_address_from_contact(const char *fullcontact, struct ast_sockaddr *addr, int tcp)
14371 {
14372 char *hostport, *transport;
14373 char contact_buf[256];
14374 char *contact;
14375
14376
14377 ast_copy_string(contact_buf, fullcontact, sizeof(contact_buf));
14378 contact = contact_buf;
14379
14380
14381
14382
14383
14384
14385
14386
14387 if (parse_uri_legacy_check(contact, "sip:,sips:", &contact, NULL, &hostport,
14388 &transport)) {
14389 ast_log(LOG_WARNING, "Invalid contact uri %s (missing sip: or sips:), attempting to use anyway\n", fullcontact);
14390 }
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401 if (ast_strlen_zero(hostport)) {
14402 ast_log(LOG_WARNING, "Invalid URI: parse_uri failed to acquire hostport\n");
14403 return -1;
14404 }
14405
14406 if (ast_sockaddr_resolve_first_transport(addr, hostport, 0, get_transport_str2enum(transport))) {
14407 ast_log(LOG_WARNING, "Invalid host name in Contact: (can't "
14408 "resolve in DNS) : '%s'\n", hostport);
14409 return -1;
14410 }
14411
14412
14413 if (!ast_sockaddr_port(addr)) {
14414 ast_sockaddr_set_port(addr,
14415 (get_transport_str2enum(transport) ==
14416 SIP_TRANSPORT_TLS ||
14417 !strncasecmp(fullcontact, "sips", 4)) ?
14418 STANDARD_TLS_PORT : STANDARD_SIP_PORT);
14419 }
14420
14421 return 0;
14422 }
14423
14424
14425 static int set_address_from_contact(struct sip_pvt *pvt)
14426 {
14427 if (ast_test_flag(&pvt->flags[0], SIP_NAT_FORCE_RPORT)) {
14428
14429
14430
14431 pvt->sa = pvt->recv;
14432 return 0;
14433 }
14434
14435 return __set_address_from_contact(pvt->fullcontact, &pvt->sa, pvt->socket.type == SIP_TRANSPORT_TLS ? 1 : 0);
14436 }
14437
14438
14439 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *peer, struct sip_request *req)
14440 {
14441 char contact[SIPBUFSIZE];
14442 char data[SIPBUFSIZE];
14443 const char *expires = get_header(req, "Expires");
14444 int expire = atoi(expires);
14445 char *curi = NULL, *hostport = NULL, *transport = NULL;
14446 int transport_type;
14447 const char *useragent;
14448 struct ast_sockaddr oldsin, testsa;
14449 char *firstcuri = NULL;
14450 int start = 0;
14451 int wildcard_found = 0;
14452 int single_binding_found = 0;
14453
14454 ast_copy_string(contact, __get_header(req, "Contact", &start), sizeof(contact));
14455
14456 if (ast_strlen_zero(expires)) {
14457 char *s = strcasestr(contact, ";expires=");
14458 if (s) {
14459 expires = strsep(&s, ";");
14460 if (sscanf(expires + 9, "%30d", &expire) != 1) {
14461 expire = default_expiry;
14462 }
14463 } else {
14464
14465 expire = default_expiry;
14466 }
14467 }
14468
14469 copy_socket_data(&pvt->socket, &req->socket);
14470
14471 do {
14472
14473 curi = contact;
14474 if (strchr(contact, '<') == NULL)
14475 strsep(&curi, ";");
14476 curi = get_in_brackets(contact);
14477 if (!firstcuri) {
14478 firstcuri = ast_strdupa(curi);
14479 }
14480
14481 if (!strcasecmp(curi, "*")) {
14482 wildcard_found = 1;
14483 } else {
14484 single_binding_found = 1;
14485 }
14486
14487 if (wildcard_found && (ast_strlen_zero(expires) || expire != 0 || single_binding_found)) {
14488
14489
14490 return PARSE_REGISTER_FAILED;
14491 }
14492
14493 ast_copy_string(contact, __get_header(req, "Contact", &start), sizeof(contact));
14494 } while (!ast_strlen_zero(contact));
14495 curi = firstcuri;
14496
14497
14498
14499
14500
14501 if (ast_strlen_zero(curi) && ast_strlen_zero(expires)) {
14502
14503 if (peer->expire > -1 && !ast_strlen_zero(peer->fullcontact)) {
14504 pvt->expiry = ast_sched_when(sched, peer->expire);
14505 }
14506 return PARSE_REGISTER_QUERY;
14507 } else if (!strcasecmp(curi, "*") || !expire) {
14508
14509 AST_SCHED_DEL_UNREF(sched, peer->expire,
14510 unref_peer(peer, "remove register expire ref"));
14511 ast_verb(3, "Unregistered SIP '%s'\n", peer->name);
14512 expire_register(ref_peer(peer,"add ref for explicit expire_register"));
14513 return PARSE_REGISTER_UPDATE;
14514 }
14515
14516
14517 ast_string_field_set(peer, fullcontact, curi);
14518
14519
14520 ast_string_field_build(pvt, our_contact, "<%s>", curi);
14521
14522
14523 if (ast_strlen_zero(curi) || parse_uri_legacy_check(curi, "sip:,sips:", &curi, NULL, &hostport, &transport)) {
14524 ast_log(LOG_NOTICE, "Not a valid SIP contact (missing sip:/sips:) trying to use anyway\n");
14525 }
14526
14527
14528 if (!(transport_type = get_transport_str2enum(transport))) {
14529 transport_type = pvt->socket.type;
14530 }
14531
14532
14533
14534
14535 if ((peer->socket.type != transport_type) && (peer->transports & transport_type)) {
14536 set_socket_transport(&peer->socket, transport_type);
14537 }
14538
14539 oldsin = peer->addr;
14540
14541
14542 if (!ast_sockaddr_isnull(&peer->addr) && (!peer->is_realtime || ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS))) {
14543 ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
14544 }
14545
14546 if (!ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) && !ast_test_flag(&peer->flags[0], SIP_NAT_RPORT_PRESENT)) {
14547
14548 ast_debug(1, "Store REGISTER's Contact header for call routing.\n");
14549
14550
14551 if (ast_sockaddr_resolve_first_transport(&testsa, hostport, 0, peer->socket.type)) {
14552 ast_log(LOG_WARNING, "Invalid hostport '%s'\n", hostport);
14553 ast_string_field_set(peer, fullcontact, "");
14554 ast_string_field_set(pvt, our_contact, "");
14555 return PARSE_REGISTER_FAILED;
14556 }
14557
14558
14559
14560 peer->portinuri = ast_sockaddr_port(&testsa) ? TRUE : FALSE;
14561
14562 if (!ast_sockaddr_port(&testsa)) {
14563 ast_sockaddr_set_port(&testsa, default_sip_port(transport_type));
14564 }
14565
14566 ast_sockaddr_copy(&peer->addr, &testsa);
14567 } else {
14568
14569
14570 ast_debug(1, "Store REGISTER's src-IP:port for call routing.\n");
14571 peer->addr = pvt->recv;
14572 }
14573
14574
14575 if (ast_apply_ha(sip_cfg.contact_ha, &peer->addr) != AST_SENSE_ALLOW ||
14576 ast_apply_ha(peer->contactha, &peer->addr) != AST_SENSE_ALLOW) {
14577 ast_log(LOG_WARNING, "Domain '%s' disallowed by contact ACL (violating IP %s)\n", hostport,
14578 ast_sockaddr_stringify_addr(&testsa));
14579 ast_string_field_set(peer, fullcontact, "");
14580 ast_string_field_set(pvt, our_contact, "");
14581 return PARSE_REGISTER_DENIED;
14582 }
14583
14584
14585
14586
14587 if ((peer->socket.type == pvt->socket.type) &&
14588 !ast_sockaddr_cmp(&peer->addr, &pvt->recv)) {
14589 copy_socket_data(&peer->socket, &pvt->socket);
14590 }
14591
14592
14593 if (!peer->is_realtime || ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
14594 ao2_t_link(peers_by_ip, peer, "ao2_link into peers_by_ip table");
14595 }
14596
14597
14598 peer->sipoptions = pvt->sipoptions;
14599
14600 if (!ast_strlen_zero(curi) && ast_strlen_zero(peer->username)) {
14601 ast_string_field_set(peer, username, curi);
14602 }
14603
14604 AST_SCHED_DEL_UNREF(sched, peer->expire,
14605 unref_peer(peer, "remove register expire ref"));
14606
14607 if (expire > max_expiry) {
14608 expire = max_expiry;
14609 }
14610 if (expire < min_expiry) {
14611 expire = min_expiry;
14612 }
14613 if (peer->is_realtime && !ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
14614 peer->expire = -1;
14615 } else {
14616 peer->expire = ast_sched_add(sched, (expire + 10) * 1000, expire_register,
14617 ref_peer(peer, "add registration ref"));
14618 if (peer->expire == -1) {
14619 unref_peer(peer, "remote registration ref");
14620 }
14621 }
14622 pvt->expiry = expire;
14623 snprintf(data, sizeof(data), "%s:%d:%s:%s", ast_sockaddr_stringify(&peer->addr),
14624 expire, peer->username, peer->fullcontact);
14625
14626 if (!peer->rt_fromcontact || !sip_cfg.peer_rtupdate)
14627 ast_db_put("SIP/Registry", peer->name, data);
14628 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));
14629
14630
14631 if (VERBOSITY_ATLEAST(2) && ast_sockaddr_cmp(&peer->addr, &oldsin)) {
14632 ast_verbose(VERBOSE_PREFIX_3 "Registered SIP '%s' at %s\n", peer->name,
14633 ast_sockaddr_stringify(&peer->addr));
14634 }
14635 sip_poke_peer(peer, 0);
14636 register_peer_exten(peer, 1);
14637
14638
14639 useragent = get_header(req, "User-Agent");
14640 if (strcasecmp(useragent, peer->useragent)) {
14641 ast_string_field_set(peer, useragent, useragent);
14642 ast_verb(4, "Saved useragent \"%s\" for peer %s\n", peer->useragent, peer->name);
14643 }
14644 return PARSE_REGISTER_UPDATE;
14645 }
14646
14647
14648 static void free_old_route(struct sip_route *route)
14649 {
14650 struct sip_route *next;
14651
14652 while (route) {
14653 next = route->next;
14654 ast_free(route);
14655 route = next;
14656 }
14657 }
14658
14659
14660 static void list_route(struct sip_route *route)
14661 {
14662 if (!route) {
14663 ast_verbose("list_route: no route\n");
14664 } else {
14665 for (;route; route = route->next)
14666 ast_verbose("list_route: hop: <%s>\n", route->hop);
14667 }
14668 }
14669
14670
14671
14672 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards, int resp)
14673 {
14674 struct sip_route *thishop, *head, *tail;
14675 int start = 0;
14676 int len;
14677 const char *rr, *c;
14678
14679
14680 if (p->route && p->route_persistent) {
14681 ast_debug(1, "build_route: Retaining previous route: <%s>\n", p->route->hop);
14682 return;
14683 }
14684
14685 if (p->route) {
14686 free_old_route(p->route);
14687 p->route = NULL;
14688 }
14689
14690
14691
14692 if ((resp < 100) || (resp > 199)) {
14693 p->route_persistent = 1;
14694 }
14695
14696
14697
14698
14699
14700
14701 head = NULL;
14702 tail = head;
14703
14704 for (;;) {
14705
14706 char rr_copy[256];
14707 char *rr_copy_ptr;
14708 char *rr_iter;
14709 rr = __get_header(req, "Record-Route", &start);
14710 if (*rr == '\0') {
14711 break;
14712 }
14713 ast_copy_string(rr_copy, rr, sizeof(rr_copy));
14714 rr_copy_ptr = rr_copy;
14715 while ((rr_iter = strsep(&rr_copy_ptr, ","))) {
14716 char *uri = get_in_brackets(rr_iter);
14717 len = strlen(uri) + 1;
14718
14719 if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
14720
14721 ast_copy_string(thishop->hop, uri, len);
14722 ast_debug(2, "build_route: Record-Route hop: <%s>\n", thishop->hop);
14723
14724 if (backwards) {
14725
14726 thishop->next = head;
14727 head = thishop;
14728
14729 if (!tail) {
14730 tail = thishop;
14731 }
14732 } else {
14733 thishop->next = NULL;
14734
14735 if (tail) {
14736 tail->next = thishop;
14737 } else {
14738 head = thishop;
14739 }
14740 tail = thishop;
14741 }
14742 }
14743 }
14744 }
14745
14746
14747 if (!head || (!ast_strlen_zero(head->hop) && strstr(head->hop, ";lr") == NULL) ) {
14748
14749
14750 char *contact = ast_strdupa(get_header(req, "Contact"));
14751 if (!ast_strlen_zero(contact)) {
14752 ast_debug(2, "build_route: Contact hop: %s\n", contact);
14753
14754 c = get_in_brackets(contact);
14755 len = strlen(c) + 1;
14756 if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
14757
14758 ast_copy_string(thishop->hop, c, len);
14759 thishop->next = NULL;
14760
14761 if (tail) {
14762 tail->next = thishop;
14763 } else {
14764 head = thishop;
14765 }
14766 }
14767 }
14768 }
14769
14770
14771 p->route = head;
14772
14773
14774 if (sip_debug_test_pvt(p)) {
14775 list_route(p->route);
14776 }
14777 }
14778
14779
14780
14781
14782
14783
14784
14785 static void set_nonce_randdata(struct sip_pvt *p, int forceupdate)
14786 {
14787 if (p->stalenonce || forceupdate || ast_strlen_zero(p->randdata)) {
14788 ast_string_field_build(p, randdata, "%08lx", ast_random());
14789 p->stalenonce = 0;
14790 }
14791 }
14792
14793 AST_THREADSTORAGE(check_auth_buf);
14794 #define CHECK_AUTH_BUF_INITLEN 256
14795
14796
14797
14798
14799
14800
14801 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
14802 const char *secret, const char *md5secret, int sipmethod,
14803 const char *uri, enum xmittype reliable, int ignore)
14804 {
14805 const char *response;
14806 char *reqheader, *respheader;
14807 const char *authtoken;
14808 char a1_hash[256];
14809 char resp_hash[256]="";
14810 char *c;
14811 int wrongnonce = FALSE;
14812 int good_response;
14813 const char *usednonce = p->randdata;
14814 struct ast_str *buf;
14815 int res;
14816
14817
14818 enum keys { K_RESP, K_URI, K_USER, K_NONCE, K_LAST };
14819 struct x {
14820 const char *key;
14821 const char *s;
14822 } *i, keys[] = {
14823 [K_RESP] = { "response=", "" },
14824 [K_URI] = { "uri=", "" },
14825 [K_USER] = { "username=", "" },
14826 [K_NONCE] = { "nonce=", "" },
14827 [K_LAST] = { NULL, NULL}
14828 };
14829
14830
14831 if (ast_strlen_zero(secret) && ast_strlen_zero(md5secret))
14832 return AUTH_SUCCESSFUL;
14833
14834
14835
14836 response = "401 Unauthorized";
14837
14838
14839
14840
14841
14842 auth_headers(WWW_AUTH, &respheader, &reqheader);
14843
14844 authtoken = get_header(req, reqheader);
14845 if (ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
14846
14847
14848 if (!reliable) {
14849
14850
14851 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
14852
14853 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14854 }
14855 return AUTH_CHALLENGE_SENT;
14856 } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
14857
14858 set_nonce_randdata(p, 1);
14859 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
14860
14861 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14862 return AUTH_CHALLENGE_SENT;
14863 }
14864
14865
14866
14867
14868
14869
14870 if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN))) {
14871 return AUTH_SECRET_FAILED;
14872 }
14873
14874
14875 res = ast_str_set(&buf, 0, "%s", authtoken);
14876
14877 if (res == AST_DYNSTR_BUILD_FAILED) {
14878 return AUTH_SECRET_FAILED;
14879 }
14880
14881 c = buf->str;
14882
14883 while(c && *(c = ast_skip_blanks(c)) ) {
14884 for (i = keys; i->key != NULL; i++) {
14885 const char *separator = ",";
14886
14887 if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
14888 continue;
14889 }
14890
14891 c += strlen(i->key);
14892 if (*c == '"') {
14893 c++;
14894 separator = "\"";
14895 }
14896 i->s = c;
14897 strsep(&c, separator);
14898 break;
14899 }
14900 if (i->key == NULL) {
14901 strsep(&c, " ,");
14902 }
14903 }
14904
14905
14906 if (strcmp(username, keys[K_USER].s)) {
14907 ast_log(LOG_WARNING, "username mismatch, have <%s>, digest has <%s>\n",
14908 username, keys[K_USER].s);
14909
14910 return AUTH_USERNAME_MISMATCH;
14911 }
14912
14913
14914
14915 if (strcasecmp(p->randdata, keys[K_NONCE].s) || p->stalenonce) {
14916 wrongnonce = TRUE;
14917 usednonce = keys[K_NONCE].s;
14918 } else {
14919 p->stalenonce = 1;
14920 }
14921
14922 if (!ast_strlen_zero(md5secret)) {
14923 ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
14924 } else {
14925 char a1[256];
14926
14927 snprintf(a1, sizeof(a1), "%s:%s:%s", username, p->realm, secret);
14928 ast_md5_hash(a1_hash, a1);
14929 }
14930
14931
14932 {
14933 char a2[256];
14934 char a2_hash[256];
14935 char resp[256];
14936
14937 snprintf(a2, sizeof(a2), "%s:%s", sip_methods[sipmethod].text,
14938 S_OR(keys[K_URI].s, uri));
14939 ast_md5_hash(a2_hash, a2);
14940 snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, usednonce, a2_hash);
14941 ast_md5_hash(resp_hash, resp);
14942 }
14943
14944 good_response = keys[K_RESP].s &&
14945 !strncasecmp(keys[K_RESP].s, resp_hash, strlen(resp_hash));
14946 if (wrongnonce) {
14947 if (good_response) {
14948 if (sipdebug)
14949 ast_log(LOG_NOTICE, "Correct auth, but based on stale nonce received from '%s'\n", get_header(req, "From"));
14950
14951 set_nonce_randdata(p, 0);
14952 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, TRUE);
14953 } else {
14954
14955 if (!req->ignore) {
14956 if (sipdebug) {
14957 ast_log(LOG_NOTICE, "Bad authentication received from '%s'\n", get_header(req, "To"));
14958 }
14959 set_nonce_randdata(p, 1);
14960 } else {
14961 if (sipdebug) {
14962 ast_log(LOG_NOTICE, "Duplicate authentication received from '%s'\n", get_header(req, "To"));
14963 }
14964 }
14965 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
14966 }
14967
14968
14969 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14970 return AUTH_CHALLENGE_SENT;
14971 }
14972 if (good_response) {
14973 append_history(p, "AuthOK", "Auth challenge successful for %s", username);
14974 return AUTH_SUCCESSFUL;
14975 }
14976
14977
14978
14979
14980
14981
14982 return AUTH_SECRET_FAILED;
14983 }
14984
14985
14986 static void sip_peer_hold(struct sip_pvt *p, int hold)
14987 {
14988 if (!p->relatedpeer) {
14989 return;
14990 }
14991
14992
14993 ast_atomic_fetchadd_int(&p->relatedpeer->onHold, (hold ? +1 : -1));
14994
14995
14996 ast_devstate_changed(AST_DEVICE_UNKNOWN, (p->owner->flags & AST_FLAG_DISABLE_DEVSTATE_CACHE ? AST_DEVSTATE_NOT_CACHABLE : AST_DEVSTATE_CACHABLE),
14997 "SIP/%s", p->relatedpeer->name);
14998
14999 return;
15000 }
15001
15002
15003 static void mwi_event_cb(const struct ast_event *event, void *userdata)
15004 {
15005 struct sip_peer *peer = userdata;
15006
15007 sip_send_mwi_to_peer(peer, 0);
15008 }
15009
15010 static void network_change_event_subscribe(void)
15011 {
15012 if (!network_change_event_subscription) {
15013 network_change_event_subscription = ast_event_subscribe(AST_EVENT_NETWORK_CHANGE,
15014 network_change_event_cb, "SIP Network Change", NULL, AST_EVENT_IE_END);
15015 }
15016 }
15017
15018 static void network_change_event_unsubscribe(void)
15019 {
15020 if (network_change_event_subscription) {
15021 network_change_event_subscription = ast_event_unsubscribe(network_change_event_subscription);
15022 }
15023 }
15024
15025 static int network_change_event_sched_cb(const void *data)
15026 {
15027 network_change_event_sched_id = -1;
15028 sip_send_all_registers();
15029 sip_send_all_mwi_subscriptions();
15030 return 0;
15031 }
15032
15033 static void network_change_event_cb(const struct ast_event *event, void *userdata)
15034 {
15035 ast_debug(1, "SIP, got a network change event, renewing all SIP registrations.\n");
15036 if (network_change_event_sched_id == -1) {
15037 network_change_event_sched_id = ast_sched_add(sched, 1000, network_change_event_sched_cb, NULL);
15038 }
15039 }
15040
15041 static void cb_extensionstate_destroy(int id, void *data)
15042 {
15043 struct sip_pvt *p = data;
15044
15045 dialog_unref(p, "the extensionstate containing this dialog ptr was destroyed");
15046 }
15047
15048
15049
15050
15051 static int cb_extensionstate(char *context, char* exten, int state, void *data)
15052 {
15053 struct sip_pvt *p = data;
15054
15055 sip_pvt_lock(p);
15056
15057 switch(state) {
15058 case AST_EXTENSION_DEACTIVATED:
15059 case AST_EXTENSION_REMOVED:
15060 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15061 ast_verb(2, "Extension state: Watcher for hint %s %s. Notify User %s\n", exten, state == AST_EXTENSION_DEACTIVATED ? "deactivated" : "removed", p->username);
15062 p->subscribed = NONE;
15063 append_history(p, "Subscribestatus", "%s", state == AST_EXTENSION_REMOVED ? "HintRemoved" : "Deactivated");
15064 break;
15065 default:
15066 p->laststate = state;
15067 break;
15068 }
15069 if (p->subscribed != NONE) {
15070 if (!p->pendinginvite) {
15071 transmit_state_notify(p, state, 1, FALSE);
15072 } else {
15073
15074
15075 ast_set_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
15076 }
15077 }
15078 ast_verb(2, "Extension Changed %s[%s] new state %s for Notify User %s %s\n", exten, context, ast_extension_state2str(state), p->username,
15079 ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE) ? "(queued)" : "");
15080
15081 sip_pvt_unlock(p);
15082
15083 return 0;
15084 }
15085
15086
15087
15088
15089 static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable)
15090 {
15091
15092
15093 const char *response = "401 Unauthorized";
15094 const char *reqheader = "Authorization";
15095 const char *respheader = "WWW-Authenticate";
15096 const char *authtoken;
15097 struct ast_str *buf;
15098 char *c;
15099
15100
15101 enum keys { K_NONCE, K_LAST };
15102 struct x {
15103 const char *key;
15104 const char *s;
15105 } *i, keys[] = {
15106 [K_NONCE] = { "nonce=", "" },
15107 [K_LAST] = { NULL, NULL}
15108 };
15109
15110 authtoken = get_header(req, reqheader);
15111 if (req->ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
15112
15113
15114 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
15115
15116 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15117 return;
15118 } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
15119
15120 set_nonce_randdata(p, 1);
15121 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
15122
15123 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15124 return;
15125 }
15126
15127 if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN))) {
15128 transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
15129 return;
15130 }
15131
15132
15133 if (ast_str_set(&buf, 0, "%s", authtoken) == AST_DYNSTR_BUILD_FAILED) {
15134 transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
15135 return;
15136 }
15137
15138 c = buf->str;
15139
15140 while (c && *(c = ast_skip_blanks(c))) {
15141 for (i = keys; i->key != NULL; i++) {
15142 const char *separator = ",";
15143
15144 if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
15145 continue;
15146 }
15147
15148 c += strlen(i->key);
15149 if (*c == '"') {
15150 c++;
15151 separator = "\"";
15152 }
15153 i->s = c;
15154 strsep(&c, separator);
15155 break;
15156 }
15157 if (i->key == NULL) {
15158 strsep(&c, " ,");
15159 }
15160 }
15161
15162
15163 if (strcasecmp(p->randdata, keys[K_NONCE].s)) {
15164 if (!req->ignore) {
15165 set_nonce_randdata(p, 1);
15166 }
15167 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
15168
15169
15170 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15171 } else {
15172 transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
15173 }
15174 }
15175
15176
15177
15178
15179
15180
15181
15182
15183
15184
15185
15186
15187
15188
15189
15190 static char *terminate_uri(char *uri)
15191 {
15192 char *t = uri;
15193 while (*t && *t > ' ' && *t != ';') {
15194 t++;
15195 }
15196 *t = '\0';
15197 return uri;
15198 }
15199
15200
15201
15202
15203
15204
15205
15206 static void extract_host_from_hostport(char **hostport)
15207 {
15208 char *dont_care;
15209 ast_sockaddr_split_hostport(*hostport, hostport, &dont_care, PARSE_PORT_IGNORE);
15210 }
15211
15212
15213
15214 static void update_peer_lastmsgssent(struct sip_peer *peer, int value, int locked)
15215 {
15216 if (!locked) {
15217 ao2_lock(peer);
15218 }
15219 peer->lastmsgssent = value;
15220 if (!locked) {
15221 ao2_unlock(peer);
15222 }
15223 }
15224
15225
15226
15227
15228
15229
15230
15231 static enum check_auth_result register_verify(struct sip_pvt *p, struct ast_sockaddr *addr,
15232 struct sip_request *req, const char *uri)
15233 {
15234 enum check_auth_result res = AUTH_NOT_FOUND;
15235 struct sip_peer *peer;
15236 char tmp[256];
15237 char *c, *name, *unused_password, *domain;
15238 char *uri2 = ast_strdupa(uri);
15239 int send_mwi = 0;
15240
15241 terminate_uri(uri2);
15242
15243 ast_copy_string(tmp, get_header(req, "To"), sizeof(tmp));
15244
15245 c = get_in_brackets(tmp);
15246 c = remove_uri_parameters(c);
15247
15248 if (parse_uri_legacy_check(c, "sip:,sips:", &name, &unused_password, &domain, NULL)) {
15249 ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, ast_sockaddr_stringify_addr(addr));
15250 return -1;
15251 }
15252
15253 SIP_PEDANTIC_DECODE(name);
15254 SIP_PEDANTIC_DECODE(domain);
15255
15256 extract_host_from_hostport(&domain);
15257
15258 if (ast_strlen_zero(domain)) {
15259
15260 transmit_response(p, "404 Not found", &p->initreq);
15261 return AUTH_UNKNOWN_DOMAIN;
15262 }
15263
15264 if (ast_strlen_zero(name)) {
15265
15266
15267
15268
15269
15270
15271
15272 name = domain;
15273 }
15274
15275
15276
15277
15278
15279 if (!AST_LIST_EMPTY(&domain_list)) {
15280 if (!check_sip_domain(domain, NULL, 0)) {
15281 if (sip_cfg.alwaysauthreject) {
15282 transmit_fake_auth_response(p, SIP_REGISTER, &p->initreq, XMIT_UNRELIABLE);
15283 } else {
15284 transmit_response(p, "404 Not found (unknown domain)", &p->initreq);
15285 }
15286 return AUTH_UNKNOWN_DOMAIN;
15287 }
15288 }
15289
15290 ast_string_field_set(p, exten, name);
15291 build_contact(p);
15292 if (req->ignore) {
15293
15294 const char *expires = get_header(req, "Expires");
15295 int expire = atoi(expires);
15296
15297 if (ast_strlen_zero(expires)) {
15298 if ((expires = strcasestr(get_header(req, "Contact"), ";expires="))) {
15299 expire = atoi(expires + 9);
15300 }
15301 }
15302 if (!ast_strlen_zero(expires) && expire == 0) {
15303 transmit_response_with_date(p, "200 OK", req);
15304 return 0;
15305 }
15306 }
15307 peer = find_peer(name, NULL, TRUE, FINDPEERS, FALSE, 0);
15308
15309 if (!(peer && ast_apply_ha(peer->ha, addr))) {
15310
15311 if (peer) {
15312 unref_peer(peer, "register_verify: unref_peer: from find_peer operation");
15313 peer = NULL;
15314 res = AUTH_ACL_FAILED;
15315 } else {
15316 res = AUTH_NOT_FOUND;
15317 }
15318 }
15319
15320 if (peer) {
15321 ao2_lock(peer);
15322 if (!peer->host_dynamic) {
15323 ast_log(LOG_ERROR, "Peer '%s' is trying to register, but not configured as host=dynamic\n", peer->name);
15324 res = AUTH_PEER_NOT_DYNAMIC;
15325 } else {
15326 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_NAT_FORCE_RPORT);
15327 if (!(res = check_auth(p, req, peer->name, peer->secret, peer->md5secret, SIP_REGISTER, uri2, XMIT_UNRELIABLE, req->ignore))) {
15328 if (sip_cancel_destroy(p))
15329 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
15330
15331 if (check_request_transport(peer, req)) {
15332 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
15333 transmit_response_with_date(p, "403 Forbidden", req);
15334 res = AUTH_BAD_TRANSPORT;
15335 } else {
15336
15337
15338
15339 switch (parse_register_contact(p, peer, req)) {
15340 case PARSE_REGISTER_DENIED:
15341 ast_log(LOG_WARNING, "Registration denied because of contact ACL\n");
15342 transmit_response_with_date(p, "603 Denied", req);
15343 res = 0;
15344 break;
15345 case PARSE_REGISTER_FAILED:
15346 ast_log(LOG_WARNING, "Failed to parse contact info\n");
15347 transmit_response_with_date(p, "400 Bad Request", req);
15348 res = 0;
15349 break;
15350 case PARSE_REGISTER_QUERY:
15351 ast_string_field_set(p, fullcontact, peer->fullcontact);
15352 transmit_response_with_date(p, "200 OK", req);
15353 res = 0;
15354 break;
15355 case PARSE_REGISTER_UPDATE:
15356 ast_string_field_set(p, fullcontact, peer->fullcontact);
15357 update_peer(peer, p->expiry);
15358
15359 transmit_response_with_date(p, "200 OK", req);
15360 send_mwi = 1;
15361 res = 0;
15362 break;
15363 }
15364 }
15365
15366 }
15367 }
15368 ao2_unlock(peer);
15369 }
15370 if (!peer && sip_cfg.autocreatepeer) {
15371
15372 peer = temp_peer(name);
15373 if (peer) {
15374 ao2_t_link(peers, peer, "link peer into peer table");
15375 if (!ast_sockaddr_isnull(&peer->addr)) {
15376 ao2_t_link(peers_by_ip, peer, "link peer into peers-by-ip table");
15377 }
15378 ao2_lock(peer);
15379 if (sip_cancel_destroy(p))
15380 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
15381 switch (parse_register_contact(p, peer, req)) {
15382 case PARSE_REGISTER_DENIED:
15383 ast_log(LOG_WARNING, "Registration denied because of contact ACL\n");
15384 transmit_response_with_date(p, "403 Forbidden (ACL)", req);
15385 res = 0;
15386 break;
15387 case PARSE_REGISTER_FAILED:
15388 ast_log(LOG_WARNING, "Failed to parse contact info\n");
15389 transmit_response_with_date(p, "400 Bad Request", req);
15390 res = 0;
15391 break;
15392 case PARSE_REGISTER_QUERY:
15393 ast_string_field_set(p, fullcontact, peer->fullcontact);
15394 transmit_response_with_date(p, "200 OK", req);
15395 send_mwi = 1;
15396 res = 0;
15397 break;
15398 case PARSE_REGISTER_UPDATE:
15399 ast_string_field_set(p, fullcontact, peer->fullcontact);
15400
15401 transmit_response_with_date(p, "200 OK", req);
15402 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));
15403 send_mwi = 1;
15404 res = 0;
15405 break;
15406 }
15407 ao2_unlock(peer);
15408 }
15409 }
15410 if (!res) {
15411 if (send_mwi) {
15412 sip_send_mwi_to_peer(peer, 0);
15413 } else {
15414 update_peer_lastmsgssent(peer, -1, 0);
15415 }
15416 ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "SIP/%s", peer->name);
15417 }
15418 if (res < 0) {
15419 switch (res) {
15420 case AUTH_SECRET_FAILED:
15421
15422 transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
15423 if (global_authfailureevents) {
15424 const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
15425 const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
15426 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
15427 "ChannelType: SIP\r\n"
15428 "Peer: SIP/%s\r\n"
15429 "PeerStatus: Rejected\r\n"
15430 "Cause: AUTH_SECRET_FAILED\r\n"
15431 "Address: %s\r\n"
15432 "Port: %s\r\n",
15433 name, peer_addr, peer_port);
15434 }
15435 break;
15436 case AUTH_USERNAME_MISMATCH:
15437
15438
15439
15440
15441 case AUTH_NOT_FOUND:
15442 case AUTH_PEER_NOT_DYNAMIC:
15443 case AUTH_ACL_FAILED:
15444 if (sip_cfg.alwaysauthreject) {
15445 transmit_fake_auth_response(p, SIP_REGISTER, &p->initreq, XMIT_UNRELIABLE);
15446 if (global_authfailureevents) {
15447 const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
15448 const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
15449 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
15450 "ChannelType: SIP\r\n"
15451 "Peer: SIP/%s\r\n"
15452 "PeerStatus: Rejected\r\n"
15453 "Cause: %s\r\n"
15454 "Address: %s\r\n"
15455 "Port: %s\r\n",
15456 name,
15457 res == AUTH_PEER_NOT_DYNAMIC ? "AUTH_PEER_NOT_DYNAMIC" : "URI_NOT_FOUND",
15458 peer_addr, peer_port);
15459 }
15460 } else {
15461
15462 if (res == AUTH_PEER_NOT_DYNAMIC) {
15463 transmit_response(p, "403 Forbidden", &p->initreq);
15464 if (global_authfailureevents) {
15465 const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
15466 const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
15467 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
15468 "ChannelType: SIP\r\n"
15469 "Peer: SIP/%s\r\n"
15470 "PeerStatus: Rejected\r\n"
15471 "Cause: AUTH_PEER_NOT_DYNAMIC\r\n"
15472 "Address: %s\r\n"
15473 "Port: %s\r\n",
15474 name, peer_addr, peer_port);
15475 }
15476 } else {
15477 transmit_response(p, "404 Not found", &p->initreq);
15478 if (global_authfailureevents) {
15479 const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
15480 const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
15481 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
15482 "ChannelType: SIP\r\n"
15483 "Peer: SIP/%s\r\n"
15484 "PeerStatus: Rejected\r\n"
15485 "Cause: %s\r\n"
15486 "Address: %s\r\n"
15487 "Port: %s\r\n",
15488 name,
15489 (res == AUTH_USERNAME_MISMATCH) ? "AUTH_USERNAME_MISMATCH" : "URI_NOT_FOUND",
15490 peer_addr, peer_port);
15491 }
15492 }
15493 }
15494 break;
15495 case AUTH_BAD_TRANSPORT:
15496 default:
15497 break;
15498 }
15499 }
15500 if (peer) {
15501 unref_peer(peer, "register_verify: unref_peer: tossing stack peer pointer at end of func");
15502 }
15503
15504 return res;
15505 }
15506
15507
15508 static void sip_set_redirstr(struct sip_pvt *p, char *reason) {
15509
15510 if (!strcmp(reason, "unknown")) {
15511 ast_string_field_set(p, redircause, "UNKNOWN");
15512 } else if (!strcmp(reason, "user-busy")) {
15513 ast_string_field_set(p, redircause, "BUSY");
15514 } else if (!strcmp(reason, "no-answer")) {
15515 ast_string_field_set(p, redircause, "NOANSWER");
15516 } else if (!strcmp(reason, "unavailable")) {
15517 ast_string_field_set(p, redircause, "UNREACHABLE");
15518 } else if (!strcmp(reason, "unconditional")) {
15519 ast_string_field_set(p, redircause, "UNCONDITIONAL");
15520 } else if (!strcmp(reason, "time-of-day")) {
15521 ast_string_field_set(p, redircause, "UNKNOWN");
15522 } else if (!strcmp(reason, "do-not-disturb")) {
15523 ast_string_field_set(p, redircause, "UNKNOWN");
15524 } else if (!strcmp(reason, "deflection")) {
15525 ast_string_field_set(p, redircause, "UNKNOWN");
15526 } else if (!strcmp(reason, "follow-me")) {
15527 ast_string_field_set(p, redircause, "UNKNOWN");
15528 } else if (!strcmp(reason, "out-of-service")) {
15529 ast_string_field_set(p, redircause, "UNREACHABLE");
15530 } else if (!strcmp(reason, "away")) {
15531 ast_string_field_set(p, redircause, "UNREACHABLE");
15532 } else {
15533 ast_string_field_set(p, redircause, "UNKNOWN");
15534 }
15535 }
15536
15537
15538
15539
15540
15541 static int get_pai(struct sip_pvt *p, struct sip_request *req)
15542 {
15543 char pai[256];
15544 char privacy[64];
15545 char *cid_num = NULL;
15546 char *cid_name = NULL;
15547 char emptyname[1] = "";
15548 int callingpres = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
15549 char *uri = NULL;
15550 int is_anonymous = 0, do_update = 1, no_name = 0;
15551
15552 ast_copy_string(pai, get_header(req, "P-Asserted-Identity"), sizeof(pai));
15553
15554 if (ast_strlen_zero(pai)) {
15555 return 0;
15556 }
15557
15558
15559 if (get_name_and_number(pai, &cid_name, &cid_num)) {
15560 return 0;
15561 }
15562
15563 if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(cid_num)) {
15564 ast_shrink_phone_number(cid_num);
15565 }
15566
15567 uri = get_in_brackets(pai);
15568 if (!strncasecmp(uri, "sip:anonymous@anonymous.invalid", 31)) {
15569 callingpres = AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
15570
15571
15572
15573 ast_free(cid_num);
15574 is_anonymous = 1;
15575 cid_num = (char *)p->cid_num;
15576 }
15577
15578 ast_copy_string(privacy, get_header(req, "Privacy"), sizeof(privacy));
15579 if (!ast_strlen_zero(privacy) && !strncmp(privacy, "id", 2)) {
15580 callingpres = AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
15581 }
15582 if (!cid_name) {
15583 no_name = 1;
15584 cid_name = (char *)emptyname;
15585 }
15586
15587 if (!strcasecmp(p->cid_num, cid_num) && !strcasecmp(p->cid_name, cid_name) && p->callingpres == callingpres) {
15588 do_update = 0;
15589 } else {
15590
15591 ast_string_field_set(p, cid_num, cid_num);
15592 ast_string_field_set(p, cid_name, cid_name);
15593 p->callingpres = callingpres;
15594
15595 if (p->owner) {
15596 ast_set_callerid(p->owner, cid_num, cid_name, NULL);
15597 p->owner->caller.id.name.presentation = callingpres;
15598 p->owner->caller.id.number.presentation = callingpres;
15599 }
15600 }
15601
15602
15603 if (!is_anonymous) {
15604 ast_free(cid_num);
15605 }
15606 if (!no_name) {
15607 ast_free(cid_name);
15608 }
15609
15610 return do_update;
15611 }
15612
15613
15614
15615
15616
15617 static int get_rpid(struct sip_pvt *p, struct sip_request *oreq)
15618 {
15619 char tmp[256];
15620 struct sip_request *req;
15621 char *cid_num = "";
15622 char *cid_name = "";
15623 int callingpres = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
15624 char *privacy = "";
15625 char *screen = "";
15626 char *start, *end;
15627
15628 if (!ast_test_flag(&p->flags[0], SIP_TRUSTRPID))
15629 return 0;
15630 req = oreq;
15631 if (!req)
15632 req = &p->initreq;
15633 ast_copy_string(tmp, get_header(req, "Remote-Party-ID"), sizeof(tmp));
15634 if (ast_strlen_zero(tmp)) {
15635 return get_pai(p, req);
15636 }
15637
15638 start = tmp;
15639 if (*start == '"') {
15640 *start++ = '\0';
15641 end = strchr(start, '"');
15642 if (!end)
15643 return 0;
15644 *end++ = '\0';
15645 cid_name = start;
15646 start = ast_skip_blanks(end);
15647 }
15648
15649 if (*start != '<')
15650 return 0;
15651 *start++ = '\0';
15652 end = strchr(start, '@');
15653 if (!end)
15654 return 0;
15655 *end++ = '\0';
15656 if (strncasecmp(start, "sip:", 4))
15657 return 0;
15658 cid_num = start + 4;
15659 if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(cid_num))
15660 ast_shrink_phone_number(cid_num);
15661 start = end;
15662
15663 end = strchr(start, '>');
15664 if (!end)
15665 return 0;
15666 *end++ = '\0';
15667 if (*end) {
15668 start = end;
15669 if (*start != ';')
15670 return 0;
15671 *start++ = '\0';
15672 while (!ast_strlen_zero(start)) {
15673 end = strchr(start, ';');
15674 if (end)
15675 *end++ = '\0';
15676 if (!strncasecmp(start, "privacy=", 8))
15677 privacy = start + 8;
15678 else if (!strncasecmp(start, "screen=", 7))
15679 screen = start + 7;
15680 start = end;
15681 }
15682
15683 if (!strcasecmp(privacy, "full")) {
15684 if (!strcasecmp(screen, "yes"))
15685 callingpres = AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN;
15686 else if (!strcasecmp(screen, "no"))
15687 callingpres = AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
15688 } else {
15689 if (!strcasecmp(screen, "yes"))
15690 callingpres = AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN;
15691 else if (!strcasecmp(screen, "no"))
15692 callingpres = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
15693 }
15694 }
15695
15696
15697 if (!strcasecmp(p->cid_num, cid_num) && !strcasecmp(p->cid_name, cid_name) && p->callingpres == callingpres)
15698 return 0;
15699
15700 ast_string_field_set(p, cid_num, cid_num);
15701 ast_string_field_set(p, cid_name, cid_name);
15702 p->callingpres = callingpres;
15703
15704 if (p->owner) {
15705 ast_set_callerid(p->owner, cid_num, cid_name, NULL);
15706 p->owner->caller.id.name.presentation = callingpres;
15707 p->owner->caller.id.number.presentation = callingpres;
15708 }
15709
15710 return 1;
15711 }
15712
15713
15714 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq, char **name, char **number, int *reason)
15715 {
15716 char tmp[256], *exten, *rexten, *rdomain, *rname = NULL;
15717 char *params, *reason_param = NULL;
15718 struct sip_request *req;
15719
15720 req = oreq ? oreq : &p->initreq;
15721
15722 ast_copy_string(tmp, get_header(req, "Diversion"), sizeof(tmp));
15723 if (ast_strlen_zero(tmp))
15724 return -1;
15725
15726 if ((params = strchr(tmp, '>'))) {
15727 params = strchr(params, ';');
15728 }
15729
15730 exten = get_in_brackets(tmp);
15731 if (!strncasecmp(exten, "sip:", 4)) {
15732 exten += 4;
15733 } else if (!strncasecmp(exten, "sips:", 5)) {
15734 exten += 5;
15735 } else {
15736 ast_log(LOG_WARNING, "Huh? Not an RDNIS SIP header (%s)?\n", exten);
15737 return -1;
15738 }
15739
15740
15741 if (params) {
15742 *params = '\0';
15743 params++;
15744 while (*params == ';' || *params == ' ')
15745 params++;
15746
15747 if ((reason_param = strcasestr(params, "reason="))) {
15748 char *end;
15749 reason_param+=7;
15750 if ((end = strchr(reason_param, ';'))) {
15751 *end = '\0';
15752 }
15753
15754 if (*reason_param == '"')
15755 reason_param = ast_strip_quoted(reason_param, "\"", "\"");
15756 if (!ast_strlen_zero(reason_param)) {
15757 sip_set_redirstr(p, reason_param);
15758 if (p->owner) {
15759 pbx_builtin_setvar_helper(p->owner, "__PRIREDIRECTREASON", p->redircause);
15760 pbx_builtin_setvar_helper(p->owner, "__SIPREDIRECTREASON", reason_param);
15761 }
15762 }
15763 }
15764 }
15765
15766 rdomain = exten;
15767 rexten = strsep(&rdomain, "@");
15768 if (p->owner)
15769 pbx_builtin_setvar_helper(p->owner, "__SIPRDNISDOMAIN", rdomain);
15770
15771 if (sip_debug_test_pvt(p))
15772 ast_verbose("RDNIS for this call is %s (reason %s)\n", exten, S_OR(reason_param, ""));
15773
15774
15775
15776 if (*tmp == '\"') {
15777 char *end_quote;
15778 rname = tmp + 1;
15779 end_quote = strchr(rname, '\"');
15780 if (end_quote) {
15781 *end_quote = '\0';
15782 }
15783 }
15784
15785 if (number) {
15786 *number = ast_strdup(rexten);
15787 }
15788
15789 if (name && rname) {
15790 *name = ast_strdup(rname);
15791 }
15792
15793 if (reason && !ast_strlen_zero(reason_param)) {
15794 *reason = sip_reason_str_to_code(reason_param);
15795 }
15796
15797 return 0;
15798 }
15799
15800
15801
15802
15803
15804
15805
15806
15807
15808
15809
15810
15811
15812
15813
15814 static enum sip_get_dest_result get_destination(struct sip_pvt *p, struct sip_request *oreq, int *cc_recall_core_id)
15815 {
15816 char tmp[256] = "", *uri, *unused_password, *domain;
15817 char tmpf[256] = "", *from = NULL;
15818 struct sip_request *req;
15819 char *decoded_uri;
15820
15821 req = oreq;
15822 if (!req) {
15823 req = &p->initreq;
15824 }
15825
15826
15827 if (req->rlPart2)
15828 ast_copy_string(tmp, REQ_OFFSET_TO_STR(req, rlPart2), sizeof(tmp));
15829
15830 uri = ast_strdupa(get_in_brackets(tmp));
15831
15832 if (parse_uri_legacy_check(uri, "sip:,sips:", &uri, &unused_password, &domain, NULL)) {
15833 ast_log(LOG_WARNING, "Not a SIP header (%s)?\n", uri);
15834 return SIP_GET_DEST_INVALID_URI;
15835 }
15836
15837 SIP_PEDANTIC_DECODE(domain);
15838 SIP_PEDANTIC_DECODE(uri);
15839
15840 extract_host_from_hostport(&domain);
15841
15842 if (ast_strlen_zero(uri)) {
15843
15844
15845
15846
15847
15848 uri = "s";
15849 }
15850
15851 ast_string_field_set(p, domain, domain);
15852
15853
15854
15855
15856
15857 ast_copy_string(tmpf, get_header(req, "From"), sizeof(tmpf));
15858 if (!ast_strlen_zero(tmpf)) {
15859 from = get_in_brackets(tmpf);
15860 if (parse_uri_legacy_check(from, "sip:,sips:", &from, NULL, &domain, NULL)) {
15861 ast_log(LOG_WARNING, "Not a SIP header (%s)?\n", from);
15862 return SIP_GET_DEST_INVALID_URI;
15863 }
15864
15865 SIP_PEDANTIC_DECODE(from);
15866 SIP_PEDANTIC_DECODE(domain);
15867
15868 extract_host_from_hostport(&domain);
15869
15870 ast_string_field_set(p, fromdomain, domain);
15871 }
15872
15873 if (!AST_LIST_EMPTY(&domain_list)) {
15874 char domain_context[AST_MAX_EXTENSION];
15875
15876 domain_context[0] = '\0';
15877 if (!check_sip_domain(p->domain, domain_context, sizeof(domain_context))) {
15878 if (!sip_cfg.allow_external_domains && (req->method == SIP_INVITE || req->method == SIP_REFER)) {
15879 ast_debug(1, "Got SIP %s to non-local domain '%s'; refusing request.\n", sip_methods[req->method].text, p->domain);
15880 return SIP_GET_DEST_REFUSED;
15881 }
15882 }
15883
15884
15885 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_HAVEPEERCONTEXT) && !ast_strlen_zero(domain_context)) {
15886 ast_string_field_set(p, context, domain_context);
15887 }
15888 }
15889
15890
15891 if (req->method == SIP_SUBSCRIBE && !ast_strlen_zero(p->subscribecontext)) {
15892 ast_string_field_set(p, context, p->subscribecontext);
15893 }
15894
15895 if (sip_debug_test_pvt(p)) {
15896 ast_verbose("Looking for %s in %s (domain %s)\n", uri, p->context, p->domain);
15897 }
15898
15899
15900
15901 decoded_uri = ast_strdupa(uri);
15902 ast_uri_decode(decoded_uri);
15903
15904
15905 if (req->method == SIP_SUBSCRIBE) {
15906 char hint[AST_MAX_EXTENSION];
15907 int which = 0;
15908 if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, uri) ||
15909 (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, decoded_uri) && (which = 1))) {
15910 if (!oreq) {
15911 ast_string_field_set(p, exten, which ? decoded_uri : uri);
15912 }
15913 return SIP_GET_DEST_EXTEN_FOUND;
15914 } else {
15915 return SIP_GET_DEST_EXTEN_NOT_FOUND;
15916 }
15917 } else {
15918 struct ast_cc_agent *agent;
15919
15920
15921
15922 if (ast_exists_extension(NULL, p->context, uri, 1, S_OR(p->cid_num, from))) {
15923 if (!oreq) {
15924 ast_string_field_set(p, exten, uri);
15925 }
15926 return SIP_GET_DEST_EXTEN_FOUND;
15927 }
15928 if (ast_exists_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from))
15929 || !strcmp(decoded_uri, ast_pickup_ext())) {
15930 if (!oreq) {
15931 ast_string_field_set(p, exten, decoded_uri);
15932 }
15933 return SIP_GET_DEST_EXTEN_FOUND;
15934 }
15935 if ((agent = find_sip_cc_agent_by_notify_uri(tmp))) {
15936 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
15937
15938
15939
15940 ast_string_field_set(p, exten, agent_pvt->original_exten);
15941
15942
15943
15944 ast_cc_agent_recalling(agent->core_id, "SIP caller %s is attempting recall",
15945 agent->device_name);
15946 if (cc_recall_core_id) {
15947 *cc_recall_core_id = agent->core_id;
15948 }
15949 ao2_ref(agent, -1);
15950 return SIP_GET_DEST_EXTEN_FOUND;
15951 }
15952 }
15953
15954 if (ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP)
15955 && (ast_canmatch_extension(NULL, p->context, uri, 1, S_OR(p->cid_num, from))
15956 || ast_canmatch_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from))
15957 || !strncmp(decoded_uri, ast_pickup_ext(), strlen(decoded_uri)))) {
15958
15959 return SIP_GET_DEST_EXTEN_MATCHMORE;
15960 }
15961
15962 return SIP_GET_DEST_EXTEN_NOT_FOUND;
15963 }
15964
15965
15966
15967
15968 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag)
15969 {
15970 struct sip_pvt *sip_pvt_ptr;
15971 struct sip_pvt tmp_dialog = {
15972 .callid = callid,
15973 };
15974
15975 if (totag) {
15976 ast_debug(4, "Looking for callid %s (fromtag %s totag %s)\n", callid, fromtag ? fromtag : "<no fromtag>", totag ? totag : "<no totag>");
15977 }
15978
15979
15980
15981 sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find of dialog in dialogs table");
15982 if (sip_pvt_ptr) {
15983
15984 sip_pvt_lock(sip_pvt_ptr);
15985 if (sip_cfg.pedanticsipchecking) {
15986 unsigned char frommismatch = 0, tomismatch = 0;
15987
15988 if (ast_strlen_zero(fromtag)) {
15989 sip_pvt_unlock(sip_pvt_ptr);
15990 ast_debug(4, "Matched %s call for callid=%s - no from tag specified, pedantic check fails\n",
15991 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
15992 return NULL;
15993 }
15994
15995 if (ast_strlen_zero(totag)) {
15996 sip_pvt_unlock(sip_pvt_ptr);
15997 ast_debug(4, "Matched %s call for callid=%s - no to tag specified, pedantic check fails\n",
15998 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
15999 return NULL;
16000 }
16001
16002
16003
16004
16005
16006
16007
16008
16009
16010
16011
16012
16013
16014
16015 frommismatch = !!strcmp(fromtag, sip_pvt_ptr->theirtag);
16016 tomismatch = !!strcmp(totag, sip_pvt_ptr->tag);
16017
16018 if (frommismatch || tomismatch) {
16019 sip_pvt_unlock(sip_pvt_ptr);
16020 if (frommismatch) {
16021 ast_debug(4, "Matched %s call for callid=%s - pedantic from tag check fails; their tag is %s our tag is %s\n",
16022 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid,
16023 fromtag, sip_pvt_ptr->theirtag);
16024 }
16025 if (tomismatch) {
16026 ast_debug(4, "Matched %s call for callid=%s - pedantic to tag check fails; their tag is %s our tag is %s\n",
16027 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid,
16028 totag, sip_pvt_ptr->tag);
16029 }
16030 return NULL;
16031 }
16032 }
16033
16034 if (totag)
16035 ast_debug(4, "Matched %s call - their tag is %s Our tag is %s\n",
16036 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING",
16037 sip_pvt_ptr->theirtag, sip_pvt_ptr->tag);
16038
16039
16040 while (sip_pvt_ptr->owner && ast_channel_trylock(sip_pvt_ptr->owner)) {
16041 sip_pvt_unlock(sip_pvt_ptr);
16042 usleep(1);
16043 sip_pvt_lock(sip_pvt_ptr);
16044 }
16045 }
16046
16047 return sip_pvt_ptr;
16048 }
16049
16050
16051
16052
16053
16054
16055
16056
16057 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req)
16058 {
16059
16060 const char *p_referred_by = NULL;
16061 char *h_refer_to = NULL;
16062 char *h_referred_by = NULL;
16063 char *refer_to;
16064 const char *p_refer_to;
16065 char *referred_by_uri = NULL;
16066 char *ptr;
16067 struct sip_request *req = NULL;
16068 const char *transfer_context = NULL;
16069 struct sip_refer *referdata;
16070
16071
16072 req = outgoing_req;
16073 referdata = transferer->refer;
16074
16075 if (!req) {
16076 req = &transferer->initreq;
16077 }
16078
16079 p_refer_to = get_header(req, "Refer-To");
16080 if (ast_strlen_zero(p_refer_to)) {
16081 ast_log(LOG_WARNING, "Refer-To Header missing. Skipping transfer.\n");
16082 return -2;
16083 }
16084 h_refer_to = ast_strdupa(p_refer_to);
16085 refer_to = get_in_brackets(h_refer_to);
16086 if (!strncasecmp(refer_to, "sip:", 4)) {
16087 refer_to += 4;
16088 } else if (!strncasecmp(refer_to, "sips:", 5)) {
16089 refer_to += 5;
16090 } else {
16091 ast_log(LOG_WARNING, "Can't transfer to non-sip: URI. (Refer-to: %s)?\n", refer_to);
16092 return -3;
16093 }
16094
16095
16096 p_referred_by = get_header(req, "Referred-By");
16097
16098
16099 if (transferer->owner) {
16100 struct ast_channel *peer = ast_bridged_channel(transferer->owner);
16101 if (peer) {
16102 pbx_builtin_setvar_helper(peer, "SIPREFERRINGCONTEXT", transferer->context);
16103 pbx_builtin_setvar_helper(peer, "SIPREFERREDBYHDR", p_referred_by);
16104 }
16105 }
16106
16107 if (!ast_strlen_zero(p_referred_by)) {
16108 char *lessthan;
16109 h_referred_by = ast_strdupa(p_referred_by);
16110
16111
16112 ast_copy_string(referdata->referred_by_name, h_referred_by, sizeof(referdata->referred_by_name));
16113 if ((lessthan = strchr(referdata->referred_by_name, '<'))) {
16114 *(lessthan - 1) = '\0';
16115 }
16116
16117 referred_by_uri = get_in_brackets(h_referred_by);
16118
16119 if (!strncasecmp(referred_by_uri, "sip:", 4)) {
16120 referred_by_uri += 4;
16121 } else if (!strncasecmp(referred_by_uri, "sips:", 5)) {
16122 referred_by_uri += 5;
16123 } else {
16124 ast_log(LOG_WARNING, "Huh? Not a sip: header (Referred-by: %s). Skipping.\n", referred_by_uri);
16125 referred_by_uri = NULL;
16126 }
16127 }
16128
16129
16130 if ((ptr = strcasestr(refer_to, "replaces="))) {
16131 char *to = NULL, *from = NULL;
16132
16133
16134 referdata->attendedtransfer = 1;
16135 ast_copy_string(referdata->replaces_callid, ptr+9, sizeof(referdata->replaces_callid));
16136 ast_uri_decode(referdata->replaces_callid);
16137 if ((ptr = strchr(referdata->replaces_callid, ';'))) {
16138 *ptr++ = '\0';
16139 }
16140
16141 if (ptr) {
16142
16143 to = strcasestr(ptr, "to-tag=");
16144 from = strcasestr(ptr, "from-tag=");
16145 }
16146
16147
16148 if (to) {
16149 ptr = to + 7;
16150 if ((to = strchr(ptr, '&'))) {
16151 *to = '\0';
16152 }
16153 if ((to = strchr(ptr, ';'))) {
16154 *to = '\0';
16155 }
16156 ast_copy_string(referdata->replaces_callid_totag, ptr, sizeof(referdata->replaces_callid_totag));
16157 }
16158
16159 if (from) {
16160 ptr = from + 9;
16161 if ((to = strchr(ptr, '&'))) {
16162 *to = '\0';
16163 }
16164 if ((to = strchr(ptr, ';'))) {
16165 *to = '\0';
16166 }
16167 ast_copy_string(referdata->replaces_callid_fromtag, ptr, sizeof(referdata->replaces_callid_fromtag));
16168 }
16169
16170 if (!strcmp(referdata->replaces_callid, transferer->callid) &&
16171 (!sip_cfg.pedanticsipchecking ||
16172 (!strcmp(referdata->replaces_callid_fromtag, transferer->theirtag) &&
16173 !strcmp(referdata->replaces_callid_totag, transferer->tag)))) {
16174 ast_log(LOG_WARNING, "Got an attempt to replace own Call-ID on %s\n", transferer->callid);
16175 return -4;
16176 }
16177
16178 if (!sip_cfg.pedanticsipchecking) {
16179 ast_debug(2, "Attended transfer: Will use Replace-Call-ID : %s (No check of from/to tags)\n", referdata->replaces_callid );
16180 } else {
16181 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>" );
16182 }
16183 }
16184
16185 if ((ptr = strchr(refer_to, '@'))) {
16186 char *urioption = NULL, *domain;
16187 int bracket = 0;
16188 *ptr++ = '\0';
16189
16190 if ((urioption = strchr(ptr, ';'))) {
16191 *urioption++ = '\0';
16192 }
16193
16194 domain = ptr;
16195
16196
16197 for (; *ptr != '\0'; ++ptr) {
16198 if (*ptr == ':' && bracket == 0) {
16199 *ptr = '\0';
16200 break;
16201 } else if (*ptr == '[') {
16202 ++bracket;
16203 } else if (*ptr == ']') {
16204 --bracket;
16205 }
16206 }
16207
16208 SIP_PEDANTIC_DECODE(domain);
16209 SIP_PEDANTIC_DECODE(urioption);
16210
16211
16212 ast_copy_string(referdata->refer_to_domain, domain, sizeof(referdata->refer_to_domain));
16213 if (urioption) {
16214 ast_copy_string(referdata->refer_to_urioption, urioption, sizeof(referdata->refer_to_urioption));
16215 }
16216 }
16217
16218 if ((ptr = strchr(refer_to, ';')))
16219 *ptr = '\0';
16220
16221 SIP_PEDANTIC_DECODE(refer_to);
16222 ast_copy_string(referdata->refer_to, refer_to, sizeof(referdata->refer_to));
16223
16224 if (referred_by_uri) {
16225 if ((ptr = strchr(referred_by_uri, ';')))
16226 *ptr = '\0';
16227 SIP_PEDANTIC_DECODE(referred_by_uri);
16228 ast_copy_string(referdata->referred_by, referred_by_uri, sizeof(referdata->referred_by));
16229 } else {
16230 referdata->referred_by[0] = '\0';
16231 }
16232
16233
16234 if (transferer->owner)
16235 transfer_context = pbx_builtin_getvar_helper(transferer->owner, "TRANSFER_CONTEXT");
16236
16237
16238 if (ast_strlen_zero(transfer_context)) {
16239 transfer_context = S_OR(transferer->owner->macrocontext,
16240 S_OR(transferer->context, sip_cfg.default_context));
16241 }
16242
16243 ast_copy_string(referdata->refer_to_context, transfer_context, sizeof(referdata->refer_to_context));
16244
16245
16246 if (referdata->attendedtransfer || ast_exists_extension(NULL, transfer_context, refer_to, 1, NULL) ) {
16247 if (sip_debug_test_pvt(transferer)) {
16248 ast_verbose("SIP transfer to extension %s@%s by %s\n", refer_to, transfer_context, referred_by_uri);
16249 }
16250
16251 return 0;
16252 }
16253 if (sip_debug_test_pvt(transferer))
16254 ast_verbose("Failed SIP Transfer to non-existing extension %s in context %s\n n", refer_to, transfer_context);
16255
16256
16257 return -1;
16258 }
16259
16260
16261
16262
16263
16264 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq)
16265 {
16266 char tmp[256] = "", *c, *a;
16267 struct sip_request *req = oreq ? oreq : &p->initreq;
16268 struct sip_refer *referdata = NULL;
16269 const char *transfer_context = NULL;
16270
16271 if (!p->refer && !sip_refer_allocate(p))
16272 return -1;
16273
16274 referdata = p->refer;
16275
16276 ast_copy_string(tmp, get_header(req, "Also"), sizeof(tmp));
16277 c = get_in_brackets(tmp);
16278
16279 if (parse_uri_legacy_check(c, "sip:,sips:", &c, NULL, &a, NULL)) {
16280 ast_log(LOG_WARNING, "Huh? Not a SIP header in Also: transfer (%s)?\n", c);
16281 return -1;
16282 }
16283
16284 SIP_PEDANTIC_DECODE(c);
16285 SIP_PEDANTIC_DECODE(a);
16286
16287 if (!ast_strlen_zero(a)) {
16288 ast_copy_string(referdata->refer_to_domain, a, sizeof(referdata->refer_to_domain));
16289 }
16290
16291 if (sip_debug_test_pvt(p))
16292 ast_verbose("Looking for %s in %s\n", c, p->context);
16293
16294 if (p->owner)
16295 transfer_context = pbx_builtin_getvar_helper(p->owner, "TRANSFER_CONTEXT");
16296
16297
16298 if (ast_strlen_zero(transfer_context)) {
16299 transfer_context = S_OR(p->owner->macrocontext,
16300 S_OR(p->context, sip_cfg.default_context));
16301 }
16302 if (ast_exists_extension(NULL, transfer_context, c, 1, NULL)) {
16303
16304 ast_debug(1, "SIP Bye-also transfer to Extension %s@%s \n", c, transfer_context);
16305 ast_copy_string(referdata->refer_to, c, sizeof(referdata->refer_to));
16306 ast_copy_string(referdata->referred_by, "", sizeof(referdata->referred_by));
16307 ast_copy_string(referdata->refer_contact, "", sizeof(referdata->refer_contact));
16308
16309 ast_string_field_set(p, context, transfer_context);
16310 return 0;
16311 } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
16312 return 1;
16313 }
16314
16315 return -1;
16316 }
16317
16318
16319
16320
16321
16322
16323
16324
16325
16326
16327
16328 static attribute_unused void check_via_response(struct sip_pvt *p, struct sip_request *req)
16329 {
16330 char via[256];
16331 char *cur, *opts;
16332
16333 ast_copy_string(via, get_header(req, "Via"), sizeof(via));
16334
16335
16336 opts = strchr(via, ',');
16337 if (opts)
16338 *opts = '\0';
16339
16340
16341 opts = strchr(via, ';');
16342 if (!opts)
16343 return;
16344 *opts++ = '\0';
16345 while ( (cur = strsep(&opts, ";")) ) {
16346 if (!strncmp(cur, "rport=", 6)) {
16347 int port = strtol(cur+6, NULL, 10);
16348
16349 ast_sockaddr_set_port(&p->ourip, port);
16350 } else if (!strncmp(cur, "received=", 9)) {
16351 if (ast_parse_arg(cur + 9, PARSE_ADDR, &p->ourip))
16352 ;
16353 }
16354 }
16355 }
16356
16357
16358 static void check_via(struct sip_pvt *p, struct sip_request *req)
16359 {
16360 char via[512];
16361 char *c, *maddr;
16362 struct ast_sockaddr tmp = { { 0, } };
16363 uint16_t port;
16364
16365 ast_copy_string(via, get_header(req, "Via"), sizeof(via));
16366
16367
16368 c = strchr(via, ',');
16369 if (c)
16370 *c = '\0';
16371
16372
16373 c = strstr(via, ";rport");
16374 if (c && (c[6] != '=')) {
16375 ast_set_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT);
16376 ast_set_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT);
16377 }
16378
16379
16380 maddr = strstr(via, "maddr=");
16381 if (maddr) {
16382 maddr += 6;
16383 c = maddr + strspn(maddr, "abcdefghijklmnopqrstuvwxyz"
16384 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-.:[]");
16385 *c = '\0';
16386 }
16387
16388 c = strchr(via, ';');
16389 if (c)
16390 *c = '\0';
16391
16392 c = strchr(via, ' ');
16393 if (c) {
16394 *c = '\0';
16395 c = ast_skip_blanks(c+1);
16396 if (strcasecmp(via, "SIP/2.0/UDP") && strcasecmp(via, "SIP/2.0/TCP") && strcasecmp(via, "SIP/2.0/TLS")) {
16397 ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
16398 return;
16399 }
16400
16401 if (maddr && ast_sockaddr_resolve_first(&p->sa, maddr, 0)) {
16402 p->sa = p->recv;
16403 }
16404
16405 if (ast_sockaddr_resolve_first(&tmp, c, 0)) {
16406 ast_log(LOG_WARNING, "Could not resolve socket address for '%s'\n", c);
16407 port = STANDARD_SIP_PORT;
16408 } else if (!(port = ast_sockaddr_port(&tmp))) {
16409 port = STANDARD_SIP_PORT;
16410 }
16411
16412 ast_sockaddr_set_port(&p->sa, port);
16413
16414 if (sip_debug_test_pvt(p)) {
16415 ast_verbose("Sending to %s (%s)\n",
16416 ast_sockaddr_stringify(sip_real_dst(p)),
16417 sip_nat_mode(p));
16418 }
16419 }
16420 }
16421
16422
16423 static enum check_auth_result check_peer_ok(struct sip_pvt *p, char *of,
16424 struct sip_request *req, int sipmethod, struct ast_sockaddr *addr,
16425 struct sip_peer **authpeer,
16426 enum xmittype reliable, char *calleridname, char *uri2)
16427 {
16428 enum check_auth_result res;
16429 int debug = sip_debug_test_addr(addr);
16430 struct sip_peer *peer;
16431
16432 if (sipmethod == SIP_SUBSCRIBE) {
16433
16434
16435
16436 peer = find_peer(of, NULL, TRUE, FINDALLDEVICES, FALSE, 0);
16437 } else {
16438
16439 peer = find_peer(of, NULL, TRUE, FINDUSERS, FALSE, 0);
16440
16441
16442 if (!peer) {
16443 peer = find_peer(NULL, &p->recv, TRUE, FINDPEERS, FALSE, p->socket.type);
16444 }
16445 }
16446
16447 if (!peer) {
16448 if (debug) {
16449 ast_verbose("No matching peer for '%s' from '%s'\n",
16450 of, ast_sockaddr_stringify(&p->recv));
16451 }
16452 return AUTH_DONT_KNOW;
16453 }
16454
16455 if (!ast_apply_ha(peer->ha, addr)) {
16456 ast_debug(2, "Found peer '%s' for '%s', but fails host access\n", peer->name, of);
16457 unref_peer(peer, "unref_peer: check_peer_ok: from find_peer call, early return of AUTH_ACL_FAILED");
16458 return AUTH_ACL_FAILED;
16459 }
16460 if (debug)
16461 ast_verbose("Found peer '%s' for '%s' from %s\n",
16462 peer->name, of, ast_sockaddr_stringify(&p->recv));
16463
16464
16465
16466 if (p->rtp) {
16467 ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(p->rtp), p->rtp, &peer->prefs);
16468 p->autoframing = peer->autoframing;
16469 }
16470
16471
16472 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
16473 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
16474 ast_copy_flags(&p->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
16475
16476 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) && p->udptl) {
16477 p->t38_maxdatagram = peer->t38_maxdatagram;
16478 set_t38_capabilities(p);
16479 }
16480
16481
16482
16483 if (p->sipoptions)
16484 peer->sipoptions = p->sipoptions;
16485
16486 do_setnat(p);
16487
16488 ast_string_field_set(p, peersecret, peer->secret);
16489 ast_string_field_set(p, peermd5secret, peer->md5secret);
16490 ast_string_field_set(p, subscribecontext, peer->subscribecontext);
16491 ast_string_field_set(p, mohinterpret, peer->mohinterpret);
16492 ast_string_field_set(p, mohsuggest, peer->mohsuggest);
16493 if (!ast_strlen_zero(peer->parkinglot)) {
16494 ast_string_field_set(p, parkinglot, peer->parkinglot);
16495 }
16496 ast_string_field_set(p, engine, peer->engine);
16497 p->disallowed_methods = peer->disallowed_methods;
16498 set_pvt_allowed_methods(p, req);
16499 ast_cc_copy_config_params(p->cc_params, peer->cc_params);
16500 if (peer->callingpres)
16501 p->callingpres = peer->callingpres;
16502 if (peer->maxms && peer->lastms)
16503 p->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
16504 else
16505 p->timer_t1 = peer->timer_t1;
16506
16507
16508 if (peer->timer_b)
16509 p->timer_b = peer->timer_b;
16510 else
16511 p->timer_b = 64 * p->timer_t1;
16512
16513 p->allowtransfer = peer->allowtransfer;
16514
16515 if (ast_test_flag(&peer->flags[0], SIP_INSECURE_INVITE)) {
16516
16517 ast_string_field_set(p, peersecret, NULL);
16518 ast_string_field_set(p, peermd5secret, NULL);
16519 }
16520 if (!(res = check_auth(p, req, peer->name, p->peersecret, p->peermd5secret, sipmethod, uri2, reliable, req->ignore))) {
16521 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
16522 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
16523 ast_copy_flags(&p->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
16524
16525 if (peer->call_limit)
16526 ast_set_flag(&p->flags[0], SIP_CALL_LIMIT);
16527 ast_string_field_set(p, peername, peer->name);
16528 ast_string_field_set(p, authname, peer->name);
16529
16530 if (sipmethod == SIP_INVITE) {
16531
16532 ast_variables_destroy(p->chanvars);
16533 p->chanvars = copy_vars(peer->chanvars);
16534 }
16535
16536 if (authpeer) {
16537 ao2_t_ref(peer, 1, "copy pointer into (*authpeer)");
16538 (*authpeer) = peer;
16539 }
16540
16541 if (!ast_strlen_zero(peer->username)) {
16542 ast_string_field_set(p, username, peer->username);
16543
16544
16545 ast_string_field_set(p, authname, peer->username);
16546 }
16547 if (!get_rpid(p, req)) {
16548 if (!ast_strlen_zero(peer->cid_num)) {
16549 char *tmp = ast_strdupa(peer->cid_num);
16550 if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
16551 ast_shrink_phone_number(tmp);
16552 ast_string_field_set(p, cid_num, tmp);
16553 }
16554 if (!ast_strlen_zero(peer->cid_name))
16555 ast_string_field_set(p, cid_name, peer->cid_name);
16556 if (peer->callingpres)
16557 p->callingpres = peer->callingpres;
16558 }
16559 if (!ast_strlen_zero(peer->cid_tag)) {
16560 ast_string_field_set(p, cid_tag, peer->cid_tag);
16561 }
16562 ast_string_field_set(p, fullcontact, peer->fullcontact);
16563
16564 if (!ast_strlen_zero(peer->context)) {
16565 ast_string_field_set(p, context, peer->context);
16566 }
16567 if (!ast_strlen_zero(peer->mwi_from)) {
16568 ast_string_field_set(p, mwi_from, peer->mwi_from);
16569 }
16570
16571 ast_string_field_set(p, peersecret, peer->secret);
16572 ast_string_field_set(p, peermd5secret, peer->md5secret);
16573 ast_string_field_set(p, language, peer->language);
16574 ast_string_field_set(p, accountcode, peer->accountcode);
16575 p->amaflags = peer->amaflags;
16576 p->callgroup = peer->callgroup;
16577 p->pickupgroup = peer->pickupgroup;
16578 p->capability = peer->capability;
16579 p->prefs = peer->prefs;
16580 p->jointcapability = peer->capability;
16581 if (peer->maxforwards > 0) {
16582 p->maxforwards = peer->maxforwards;
16583 }
16584 if (p->peercapability)
16585 p->jointcapability &= p->peercapability;
16586 p->maxcallbitrate = peer->maxcallbitrate;
16587 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
16588 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
16589 p->noncodeccapability |= AST_RTP_DTMF;
16590 else
16591 p->noncodeccapability &= ~AST_RTP_DTMF;
16592 p->jointnoncodeccapability = p->noncodeccapability;
16593 p->rtptimeout = peer->rtptimeout;
16594 p->rtpholdtimeout = peer->rtpholdtimeout;
16595 p->rtpkeepalive = peer->rtpkeepalive;
16596 if (!dialog_initialize_rtp(p)) {
16597 if (p->rtp) {
16598 ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(p->rtp), p->rtp, &peer->prefs);
16599 p->autoframing = peer->autoframing;
16600 }
16601 } else {
16602 res = AUTH_RTP_FAILED;
16603 }
16604 }
16605 unref_peer(peer, "check_peer_ok: unref_peer: tossing temp ptr to peer from find_peer");
16606 return res;
16607 }
16608
16609
16610
16611
16612
16613
16614
16615 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
16616 int sipmethod, const char *uri, enum xmittype reliable,
16617 struct ast_sockaddr *addr, struct sip_peer **authpeer)
16618 {
16619 char from[256] = "", *of, *name, *unused_password, *domain;
16620 enum check_auth_result res = AUTH_DONT_KNOW;
16621 char calleridname[50];
16622 char *uri2 = ast_strdupa(uri);
16623
16624 terminate_uri(uri2);
16625
16626 ast_copy_string(from, get_header(req, "From"), sizeof(from));
16627
16628
16629
16630 if (!(of = (char *) get_calleridname(from, calleridname, sizeof(calleridname)))) {
16631 ast_log(LOG_ERROR, "FROM header can not be parsed \n");
16632 return res;
16633 }
16634
16635 if (calleridname[0]) {
16636 ast_string_field_set(p, cid_name, calleridname);
16637 }
16638
16639 if (ast_strlen_zero(p->exten)) {
16640 char *t = uri2;
16641 if (!strncasecmp(t, "sip:", 4))
16642 t+= 4;
16643 else if (!strncasecmp(t, "sips:", 5))
16644 t += 5;
16645 ast_string_field_set(p, exten, t);
16646 t = strchr(p->exten, '@');
16647 if (t)
16648 *t = '\0';
16649
16650 if (ast_strlen_zero(p->our_contact))
16651 build_contact(p);
16652 }
16653
16654 of = get_in_brackets(of);
16655
16656
16657 ast_string_field_set(p, from, of);
16658
16659 if (parse_uri_legacy_check(of, "sip:,sips:", &name, &unused_password, &domain, NULL)) {
16660 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
16661 }
16662
16663 SIP_PEDANTIC_DECODE(name);
16664 SIP_PEDANTIC_DECODE(domain);
16665
16666 extract_host_from_hostport(&domain);
16667
16668 if (ast_strlen_zero(domain)) {
16669
16670 ast_log(LOG_ERROR, "Empty domain name in FROM header\n");
16671 return res;
16672 }
16673
16674 if (ast_strlen_zero(name)) {
16675
16676
16677
16678 name = domain;
16679 } else {
16680
16681 char *tmp = ast_strdupa(name);
16682
16683
16684
16685 tmp = strsep(&tmp, ";");
16686 if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp)) {
16687 ast_shrink_phone_number(tmp);
16688 }
16689 ast_string_field_set(p, cid_num, tmp);
16690 }
16691
16692 if (global_match_auth_username) {
16693
16694
16695
16696
16697
16698
16699
16700
16701 const char *hdr = get_header(req, "Authorization");
16702 if (ast_strlen_zero(hdr)) {
16703 hdr = get_header(req, "Proxy-Authorization");
16704 }
16705
16706 if (!ast_strlen_zero(hdr) && (hdr = strstr(hdr, "username=\""))) {
16707 ast_copy_string(from, hdr + strlen("username=\""), sizeof(from));
16708 name = from;
16709 name = strsep(&name, "\"");
16710 }
16711 }
16712
16713 res = check_peer_ok(p, name, req, sipmethod, addr,
16714 authpeer, reliable, calleridname, uri2);
16715 if (res != AUTH_DONT_KNOW) {
16716 return res;
16717 }
16718
16719
16720 if (sip_cfg.allowguest) {
16721
16722 get_rpid(p, req);
16723 p->rtptimeout = global_rtptimeout;
16724 p->rtpholdtimeout = global_rtpholdtimeout;
16725 p->rtpkeepalive = global_rtpkeepalive;
16726 if (!dialog_initialize_rtp(p)) {
16727 res = AUTH_SUCCESSFUL;
16728 } else {
16729 res = AUTH_RTP_FAILED;
16730 }
16731 } else if (sip_cfg.alwaysauthreject) {
16732 res = AUTH_FAKE_AUTH;
16733 } else {
16734 res = AUTH_SECRET_FAILED;
16735 }
16736
16737 if (ast_test_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT)) {
16738 ast_set_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT);
16739 }
16740
16741 return res;
16742 }
16743
16744
16745
16746
16747 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, const char *uri, enum xmittype reliable, struct ast_sockaddr *addr)
16748 {
16749 return check_user_full(p, req, sipmethod, uri, reliable, addr, NULL);
16750 }
16751
16752
16753
16754
16755
16756
16757
16758
16759
16760 static int get_msg_text(char *buf, int len, struct sip_request *req)
16761 {
16762 int x;
16763 int linelen;
16764
16765 buf[0] = '\0';
16766 --len;
16767 for (x = 0; len && x < req->lines; ++x) {
16768 const char *line = REQ_OFFSET_TO_STR(req, line[x]);
16769 strncat(buf, line, len);
16770 linelen = strlen(buf);
16771 buf += linelen;
16772 len -= linelen;
16773 if (len) {
16774 strcat(buf, "\n");
16775 ++buf;
16776 --len;
16777 }
16778 }
16779 return 0;
16780 }
16781
16782
16783
16784
16785
16786 static void receive_message(struct sip_pvt *p, struct sip_request *req)
16787 {
16788 char buf[1400];
16789 char *bufp;
16790 struct ast_frame f;
16791 const char *content_type = get_header(req, "Content-Type");
16792
16793 if (strncmp(content_type, "text/plain", strlen("text/plain"))) {
16794 transmit_response(p, "415 Unsupported Media Type", req);
16795 if (!p->owner)
16796 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16797 return;
16798 }
16799
16800 if (get_msg_text(buf, sizeof(buf), req)) {
16801 ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
16802 transmit_response(p, "500 Internal Server Error", req);
16803 if (!p->owner) {
16804 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16805 }
16806 return;
16807 }
16808
16809
16810
16811 bufp = buf + strlen(buf);
16812 while (--bufp >= buf && *bufp == '\n') {
16813 *bufp = '\0';
16814 }
16815
16816 if (p->owner) {
16817 if (sip_debug_test_pvt(p))
16818 ast_verbose("SIP Text message received: '%s'\n", buf);
16819 memset(&f, 0, sizeof(f));
16820 f.frametype = AST_FRAME_TEXT;
16821 f.subclass.integer = 0;
16822 f.offset = 0;
16823 f.data.ptr = buf;
16824 f.datalen = strlen(buf) + 1;
16825 ast_queue_frame(p->owner, &f);
16826 transmit_response(p, "202 Accepted", req);
16827 return;
16828 }
16829
16830
16831 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);
16832 transmit_response(p, "405 Method Not Allowed", req);
16833 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16834 return;
16835 }
16836
16837
16838 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16839 {
16840 #define FORMAT "%-25.25s %-15.15s %-15.15s \n"
16841 #define FORMAT2 "%-25.25s %-15.15s %-15.15s \n"
16842 char ilimits[40];
16843 char iused[40];
16844 int showall = FALSE;
16845 struct ao2_iterator i;
16846 struct sip_peer *peer;
16847
16848 switch (cmd) {
16849 case CLI_INIT:
16850 e->command = "sip show inuse";
16851 e->usage =
16852 "Usage: sip show inuse [all]\n"
16853 " List all SIP devices usage counters and limits.\n"
16854 " Add option \"all\" to show all devices, not only those with a limit.\n";
16855 return NULL;
16856 case CLI_GENERATE:
16857 return NULL;
16858 }
16859
16860 if (a->argc < 3)
16861 return CLI_SHOWUSAGE;
16862
16863 if (a->argc == 4 && !strcmp(a->argv[3], "all"))
16864 showall = TRUE;
16865
16866 ast_cli(a->fd, FORMAT, "* Peer name", "In use", "Limit");
16867
16868 i = ao2_iterator_init(peers, 0);
16869 while ((peer = ao2_t_iterator_next(&i, "iterate thru peer table"))) {
16870 ao2_lock(peer);
16871 if (peer->call_limit)
16872 snprintf(ilimits, sizeof(ilimits), "%d", peer->call_limit);
16873 else
16874 ast_copy_string(ilimits, "N/A", sizeof(ilimits));
16875 snprintf(iused, sizeof(iused), "%d/%d/%d", peer->inUse, peer->inRinging, peer->onHold);
16876 if (showall || peer->call_limit)
16877 ast_cli(a->fd, FORMAT2, peer->name, iused, ilimits);
16878 ao2_unlock(peer);
16879 unref_peer(peer, "toss iterator pointer");
16880 }
16881 ao2_iterator_destroy(&i);
16882
16883 return CLI_SUCCESS;
16884 #undef FORMAT
16885 #undef FORMAT2
16886 }
16887
16888
16889
16890 static char *transfermode2str(enum transfermodes mode)
16891 {
16892 if (mode == TRANSFER_OPENFORALL)
16893 return "open";
16894 else if (mode == TRANSFER_CLOSED)
16895 return "closed";
16896 return "strict";
16897 }
16898
16899
16900
16901
16902
16903
16904
16905 static const struct _map_x_s stmodes[] = {
16906 { SESSION_TIMER_MODE_ACCEPT, "Accept"},
16907 { SESSION_TIMER_MODE_ORIGINATE, "Originate"},
16908 { SESSION_TIMER_MODE_REFUSE, "Refuse"},
16909 { -1, NULL},
16910 };
16911
16912 static const char *stmode2str(enum st_mode m)
16913 {
16914 return map_x_s(stmodes, m, "Unknown");
16915 }
16916
16917 static enum st_mode str2stmode(const char *s)
16918 {
16919 return map_s_x(stmodes, s, -1);
16920 }
16921
16922
16923 static const struct _map_x_s strefresher_params[] = {
16924 { SESSION_TIMER_REFRESHER_PARAM_UNKNOWN, "unknown" },
16925 { SESSION_TIMER_REFRESHER_PARAM_UAC, "uac" },
16926 { SESSION_TIMER_REFRESHER_PARAM_UAS, "uas" },
16927 { -1, NULL },
16928 };
16929
16930 static const struct _map_x_s strefreshers[] = {
16931 { SESSION_TIMER_REFRESHER_AUTO, "auto" },
16932 { SESSION_TIMER_REFRESHER_US, "us" },
16933 { SESSION_TIMER_REFRESHER_THEM, "them" },
16934 { -1, NULL },
16935 };
16936
16937 static const char *strefresherparam2str(enum st_refresher r)
16938 {
16939 return map_x_s(strefresher_params, r, "Unknown");
16940 }
16941
16942 static enum st_refresher str2strefresherparam(const char *s)
16943 {
16944 return map_s_x(strefresher_params, s, -1);
16945 }
16946
16947 static const char *strefresher2str(enum st_refresher r)
16948 {
16949 return map_x_s(strefreshers, r, "Unknown");
16950 }
16951
16952 static int peer_status(struct sip_peer *peer, char *status, int statuslen)
16953 {
16954 int res = 0;
16955 if (peer->maxms) {
16956 if (peer->lastms < 0) {
16957 ast_copy_string(status, "UNREACHABLE", statuslen);
16958 } else if (peer->lastms > peer->maxms) {
16959 snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
16960 res = 1;
16961 } else if (peer->lastms) {
16962 snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
16963 res = 1;
16964 } else {
16965 ast_copy_string(status, "UNKNOWN", statuslen);
16966 }
16967 } else {
16968 ast_copy_string(status, "Unmonitored", statuslen);
16969
16970 res = -1;
16971 }
16972 return res;
16973 }
16974
16975
16976 static char *sip_show_tcp(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16977 {
16978 struct sip_threadinfo *th;
16979 struct ao2_iterator i;
16980
16981 #define FORMAT2 "%-47.47s %9.9s %6.6s\n"
16982 #define FORMAT "%-47.47s %-9.9s %-6.6s\n"
16983
16984 switch (cmd) {
16985 case CLI_INIT:
16986 e->command = "sip show tcp";
16987 e->usage =
16988 "Usage: sip show tcp\n"
16989 " Lists all active TCP/TLS sessions.\n";
16990 return NULL;
16991 case CLI_GENERATE:
16992 return NULL;
16993 }
16994
16995 if (a->argc != 3)
16996 return CLI_SHOWUSAGE;
16997
16998 ast_cli(a->fd, FORMAT2, "Address", "Transport", "Type");
16999
17000 i = ao2_iterator_init(threadt, 0);
17001 while ((th = ao2_t_iterator_next(&i, "iterate through tcp threads for 'sip show tcp'"))) {
17002 ast_cli(a->fd, FORMAT,
17003 ast_sockaddr_stringify(&th->tcptls_session->remote_address),
17004 get_transport(th->type),
17005 (th->tcptls_session->client ? "Client" : "Server"));
17006 ao2_t_ref(th, -1, "decrement ref from iterator");
17007 }
17008 ao2_iterator_destroy(&i);
17009
17010 return CLI_SUCCESS;
17011 #undef FORMAT
17012 #undef FORMAT2
17013 }
17014
17015
17016 static char *sip_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17017 {
17018 regex_t regexbuf;
17019 int havepattern = FALSE;
17020 struct ao2_iterator user_iter;
17021 struct sip_peer *user;
17022
17023 #define FORMAT "%-25.25s %-15.15s %-15.15s %-15.15s %-5.5s%-10.10s\n"
17024
17025 switch (cmd) {
17026 case CLI_INIT:
17027 e->command = "sip show users";
17028 e->usage =
17029 "Usage: sip show users [like <pattern>]\n"
17030 " Lists all known SIP users.\n"
17031 " Optional regular expression pattern is used to filter the user list.\n";
17032 return NULL;
17033 case CLI_GENERATE:
17034 return NULL;
17035 }
17036
17037 switch (a->argc) {
17038 case 5:
17039 if (!strcasecmp(a->argv[3], "like")) {
17040 if (regcomp(®exbuf, a->argv[4], REG_EXTENDED | REG_NOSUB))
17041 return CLI_SHOWUSAGE;
17042 havepattern = TRUE;
17043 } else
17044 return CLI_SHOWUSAGE;
17045 case 3:
17046 break;
17047 default:
17048 return CLI_SHOWUSAGE;
17049 }
17050
17051 ast_cli(a->fd, FORMAT, "Username", "Secret", "Accountcode", "Def.Context", "ACL", "ForcerPort");
17052
17053 user_iter = ao2_iterator_init(peers, 0);
17054 while ((user = ao2_t_iterator_next(&user_iter, "iterate thru peers table"))) {
17055 ao2_lock(user);
17056 if (!(user->type & SIP_TYPE_USER)) {
17057 ao2_unlock(user);
17058 unref_peer(user, "sip show users");
17059 continue;
17060 }
17061
17062 if (havepattern && regexec(®exbuf, user->name, 0, NULL, 0)) {
17063 ao2_unlock(user);
17064 unref_peer(user, "sip show users");
17065 continue;
17066 }
17067
17068 ast_cli(a->fd, FORMAT, user->name,
17069 user->secret,
17070 user->accountcode,
17071 user->context,
17072 AST_CLI_YESNO(user->ha != NULL),
17073 AST_CLI_YESNO(ast_test_flag(&user->flags[0], SIP_NAT_FORCE_RPORT)));
17074 ao2_unlock(user);
17075 unref_peer(user, "sip show users");
17076 }
17077 ao2_iterator_destroy(&user_iter);
17078
17079 if (havepattern)
17080 regfree(®exbuf);
17081
17082 return CLI_SUCCESS;
17083 #undef FORMAT
17084 }
17085
17086
17087 static int manager_show_registry(struct mansession *s, const struct message *m)
17088 {
17089 const char *id = astman_get_header(m, "ActionID");
17090 char idtext[256] = "";
17091 int total = 0;
17092
17093 if (!ast_strlen_zero(id))
17094 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
17095
17096 astman_send_listack(s, m, "Registrations will follow", "start");
17097
17098 ASTOBJ_CONTAINER_TRAVERSE(®l, 1, do {
17099 ASTOBJ_RDLOCK(iterator);
17100 astman_append(s,
17101 "Event: RegistryEntry\r\n"
17102 "%s"
17103 "Host: %s\r\n"
17104 "Port: %d\r\n"
17105 "Username: %s\r\n"
17106 "Domain: %s\r\n"
17107 "DomainPort: %d\r\n"
17108 "Refresh: %d\r\n"
17109 "State: %s\r\n"
17110 "RegistrationTime: %ld\r\n"
17111 "\r\n",
17112 idtext,
17113 iterator->hostname,
17114 iterator->portno ? iterator->portno : STANDARD_SIP_PORT,
17115 iterator->username,
17116 S_OR(iterator->regdomain,iterator->hostname),
17117 iterator->regdomainport ? iterator->regdomainport : STANDARD_SIP_PORT,
17118 iterator->refresh,
17119 regstate2str(iterator->regstate),
17120 (long) iterator->regtime.tv_sec);
17121 ASTOBJ_UNLOCK(iterator);
17122 total++;
17123 } while(0));
17124
17125 astman_append(s,
17126 "Event: RegistrationsComplete\r\n"
17127 "EventList: Complete\r\n"
17128 "ListItems: %d\r\n"
17129 "%s"
17130 "\r\n", total, idtext);
17131
17132 return 0;
17133 }
17134
17135
17136
17137 static int manager_sip_show_peers(struct mansession *s, const struct message *m)
17138 {
17139 const char *id = astman_get_header(m, "ActionID");
17140 const char *a[] = {"sip", "show", "peers"};
17141 char idtext[256] = "";
17142 int total = 0;
17143
17144 if (!ast_strlen_zero(id))
17145 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
17146
17147 astman_send_listack(s, m, "Peer status list will follow", "start");
17148
17149 _sip_show_peers(-1, &total, s, m, 3, a);
17150
17151 astman_append(s,
17152 "Event: PeerlistComplete\r\n"
17153 "EventList: Complete\r\n"
17154 "ListItems: %d\r\n"
17155 "%s"
17156 "\r\n", total, idtext);
17157 return 0;
17158 }
17159
17160
17161 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17162 {
17163 switch (cmd) {
17164 case CLI_INIT:
17165 e->command = "sip show peers";
17166 e->usage =
17167 "Usage: sip show peers [like <pattern>]\n"
17168 " Lists all known SIP peers.\n"
17169 " Optional regular expression pattern is used to filter the peer list.\n";
17170 return NULL;
17171 case CLI_GENERATE:
17172 return NULL;
17173 }
17174
17175 return _sip_show_peers(a->fd, NULL, NULL, NULL, a->argc, (const char **) a->argv);
17176 }
17177
17178 int peercomparefunc(const void *a, const void *b);
17179
17180 int peercomparefunc(const void *a, const void *b)
17181 {
17182 struct sip_peer **ap = (struct sip_peer **)a;
17183 struct sip_peer **bp = (struct sip_peer **)b;
17184 return strcmp((*ap)->name, (*bp)->name);
17185 }
17186
17187
17188
17189 static char *_sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[])
17190 {
17191 regex_t regexbuf;
17192 int havepattern = FALSE;
17193 struct sip_peer *peer;
17194 struct ao2_iterator* it_peers;
17195
17196
17197 #define FORMAT2 "%-25.25s %-39.39s %-3.3s %-10.10s %-3.3s %-8s %-10s %s\n"
17198
17199 char name[256];
17200 int total_peers = 0;
17201 int peers_mon_online = 0;
17202 int peers_mon_offline = 0;
17203 int peers_unmon_offline = 0;
17204 int peers_unmon_online = 0;
17205 const char *id;
17206 char idtext[256] = "";
17207 int realtimepeers;
17208 struct sip_peer **peerarray;
17209 int k;
17210
17211 realtimepeers = ast_check_realtime("sippeers");
17212
17213 if (s) {
17214 id = astman_get_header(m, "ActionID");
17215 if (!ast_strlen_zero(id))
17216 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
17217 }
17218
17219 switch (argc) {
17220 case 5:
17221 if (!strcasecmp(argv[3], "like")) {
17222 if (regcomp(®exbuf, argv[4], REG_EXTENDED | REG_NOSUB))
17223 return CLI_SHOWUSAGE;
17224 havepattern = TRUE;
17225 } else
17226 return CLI_SHOWUSAGE;
17227 case 3:
17228 break;
17229 default:
17230 return CLI_SHOWUSAGE;
17231 }
17232
17233 if (!s) {
17234
17235 ast_cli(fd, FORMAT2, "Name/username", "Host", "Dyn", "Forcerport", "ACL", "Port", "Status", (realtimepeers ? "Realtime" : ""));
17236 }
17237
17238 ao2_lock(peers);
17239 if (!(it_peers = ao2_callback(peers, OBJ_MULTIPLE, NULL, NULL))) {
17240 ast_log(AST_LOG_ERROR, "Unable to create iterator for peers container for sip show peers\n");
17241 ao2_unlock(peers);
17242 return CLI_FAILURE;
17243 }
17244 if (!(peerarray = ast_calloc(sizeof(struct sip_peer *), ao2_container_count(peers)))) {
17245 ast_log(AST_LOG_ERROR, "Unable to allocate peer array for sip show peers\n");
17246 ao2_iterator_destroy(it_peers);
17247 ao2_unlock(peers);
17248 return CLI_FAILURE;
17249 }
17250 ao2_unlock(peers);
17251
17252 while ((peer = ao2_t_iterator_next(it_peers, "iterate thru peers table"))) {
17253 ao2_lock(peer);
17254
17255 if (!(peer->type & SIP_TYPE_PEER)) {
17256 ao2_unlock(peer);
17257 unref_peer(peer, "unref peer because it's actually a user");
17258 continue;
17259 }
17260
17261 if (havepattern && regexec(®exbuf, peer->name, 0, NULL, 0)) {
17262 ao2_unlock(peer);
17263 unref_peer(peer, "toss iterator peer ptr before continue");
17264 continue;
17265 }
17266
17267 peerarray[total_peers++] = peer;
17268 ao2_unlock(peer);
17269 }
17270 ao2_iterator_destroy(it_peers);
17271
17272 qsort(peerarray, total_peers, sizeof(struct sip_peer *), peercomparefunc);
17273
17274 for(k=0; k < total_peers; k++) {
17275 char status[20] = "";
17276 char srch[2000];
17277 char pstatus;
17278
17279
17280
17281
17282
17283
17284 char *tmp_port;
17285 char *tmp_host;
17286
17287 peer = peerarray[k];
17288
17289 tmp_port = ast_sockaddr_isnull(&peer->addr) ?
17290 "0" : ast_strdupa(ast_sockaddr_stringify_port(&peer->addr));
17291
17292 tmp_host = ast_sockaddr_isnull(&peer->addr) ?
17293 "(Unspecified)" : ast_strdupa(ast_sockaddr_stringify_addr(&peer->addr));
17294
17295 ao2_lock(peer);
17296 if (havepattern && regexec(®exbuf, peer->name, 0, NULL, 0)) {
17297 ao2_unlock(peer);
17298 peer = peerarray[k] = unref_peer(peer, "toss iterator peer ptr before continue");
17299 continue;
17300 }
17301
17302 if (!ast_strlen_zero(peer->username) && !s)
17303 snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
17304 else
17305 ast_copy_string(name, peer->name, sizeof(name));
17306
17307 pstatus = peer_status(peer, status, sizeof(status));
17308 if (pstatus == 1)
17309 peers_mon_online++;
17310 else if (pstatus == 0)
17311 peers_mon_offline++;
17312 else {
17313 if (ast_sockaddr_isnull(&peer->addr) ||
17314 !ast_sockaddr_port(&peer->addr)) {
17315 peers_unmon_offline++;
17316 } else {
17317 peers_unmon_online++;
17318 }
17319 }
17320
17321 snprintf(srch, sizeof(srch), FORMAT2, name,
17322 tmp_host,
17323 peer->host_dynamic ? " D " : " ",
17324 ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) ? " N " : " ",
17325 peer->ha ? " A " : " ",
17326 tmp_port, status,
17327 realtimepeers ? (peer->is_realtime ? "Cached RT":"") : "");
17328
17329 if (!s) {
17330 ast_cli(fd, FORMAT2, name,
17331 tmp_host,
17332 peer->host_dynamic ? " D " : " ",
17333 ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) ? " N " : " ",
17334 peer->ha ? " A " : " ",
17335 tmp_port, status,
17336 realtimepeers ? (peer->is_realtime ? "Cached RT":"") : "");
17337 } else {
17338
17339 astman_append(s,
17340 "Event: PeerEntry\r\n%s"
17341 "Channeltype: SIP\r\n"
17342 "ObjectName: %s\r\n"
17343 "ChanObjectType: peer\r\n"
17344 "IPaddress: %s\r\n"
17345 "IPport: %s\r\n"
17346 "Dynamic: %s\r\n"
17347 "Forcerport: %s\r\n"
17348 "VideoSupport: %s\r\n"
17349 "TextSupport: %s\r\n"
17350 "ACL: %s\r\n"
17351 "Status: %s\r\n"
17352 "RealtimeDevice: %s\r\n\r\n",
17353 idtext,
17354 peer->name,
17355 ast_sockaddr_isnull(&peer->addr) ? "-none-" : tmp_host,
17356 ast_sockaddr_isnull(&peer->addr) ? "0" : tmp_port,
17357 peer->host_dynamic ? "yes" : "no",
17358 ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) ? "yes" : "no",
17359 ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "yes" : "no",
17360 ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT) ? "yes" : "no",
17361 peer->ha ? "yes" : "no",
17362 status,
17363 realtimepeers ? (peer->is_realtime ? "yes":"no") : "no");
17364 }
17365 ao2_unlock(peer);
17366 peer = peerarray[k] = unref_peer(peer, "toss iterator peer ptr");
17367 }
17368
17369 if (!s)
17370 ast_cli(fd, "%d sip peers [Monitored: %d online, %d offline Unmonitored: %d online, %d offline]\n",
17371 total_peers, peers_mon_online, peers_mon_offline, peers_unmon_online, peers_unmon_offline);
17372
17373 if (havepattern)
17374 regfree(®exbuf);
17375
17376 if (total)
17377 *total = total_peers;
17378
17379 ast_free(peerarray);
17380
17381 return CLI_SUCCESS;
17382 #undef FORMAT2
17383 }
17384
17385 static int peer_dump_func(void *userobj, void *arg, int flags)
17386 {
17387 struct sip_peer *peer = userobj;
17388 int refc = ao2_t_ref(userobj, 0, "");
17389 struct ast_cli_args *a = (struct ast_cli_args *) arg;
17390
17391 ast_cli(a->fd, "name: %s\ntype: peer\nobjflags: %d\nrefcount: %d\n\n",
17392 peer->name, 0, refc);
17393 return 0;
17394 }
17395
17396 static int dialog_dump_func(void *userobj, void *arg, int flags)
17397 {
17398 struct sip_pvt *pvt = userobj;
17399 int refc = ao2_t_ref(userobj, 0, "");
17400 struct ast_cli_args *a = (struct ast_cli_args *) arg;
17401
17402 ast_cli(a->fd, "name: %s\ntype: dialog\nobjflags: %d\nrefcount: %d\n\n",
17403 pvt->callid, 0, refc);
17404 return 0;
17405 }
17406
17407
17408
17409 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17410 {
17411 char tmp[256];
17412
17413 switch (cmd) {
17414 case CLI_INIT:
17415 e->command = "sip show objects";
17416 e->usage =
17417 "Usage: sip show objects\n"
17418 " Lists status of known SIP objects\n";
17419 return NULL;
17420 case CLI_GENERATE:
17421 return NULL;
17422 }
17423
17424 if (a->argc != 3)
17425 return CLI_SHOWUSAGE;
17426 ast_cli(a->fd, "-= Peer objects: %d static, %d realtime, %d autocreate =-\n\n", speerobjs, rpeerobjs, apeerobjs);
17427 ao2_t_callback(peers, OBJ_NODATA, peer_dump_func, a, "initiate ao2_callback to dump peers");
17428 ast_cli(a->fd, "-= Peer objects by IP =-\n\n");
17429 ao2_t_callback(peers_by_ip, OBJ_NODATA, peer_dump_func, a, "initiate ao2_callback to dump peers_by_ip");
17430 ast_cli(a->fd, "-= Registry objects: %d =-\n\n", regobjs);
17431 ASTOBJ_CONTAINER_DUMP(a->fd, tmp, sizeof(tmp), ®l);
17432 ast_cli(a->fd, "-= Dialog objects:\n\n");
17433 ao2_t_callback(dialogs, OBJ_NODATA, dialog_dump_func, a, "initiate ao2_callback to dump dialogs");
17434 return CLI_SUCCESS;
17435 }
17436
17437 static void print_group(int fd, ast_group_t group, int crlf)
17438 {
17439 char buf[256];
17440 ast_cli(fd, crlf ? "%s\r\n" : "%s\n", ast_print_group(buf, sizeof(buf), group) );
17441 }
17442
17443
17444 static const struct _map_x_s dtmfstr[] = {
17445 { SIP_DTMF_RFC2833, "rfc2833" },
17446 { SIP_DTMF_INFO, "info" },
17447 { SIP_DTMF_SHORTINFO, "shortinfo" },
17448 { SIP_DTMF_INBAND, "inband" },
17449 { SIP_DTMF_AUTO, "auto" },
17450 { -1, NULL },
17451 };
17452
17453
17454 static const char *dtmfmode2str(int mode)
17455 {
17456 return map_x_s(dtmfstr, mode, "<error>");
17457 }
17458
17459
17460 static int str2dtmfmode(const char *str)
17461 {
17462 return map_s_x(dtmfstr, str, -1);
17463 }
17464
17465 static const struct _map_x_s insecurestr[] = {
17466 { SIP_INSECURE_PORT, "port" },
17467 { SIP_INSECURE_INVITE, "invite" },
17468 { SIP_INSECURE_PORT | SIP_INSECURE_INVITE, "port,invite" },
17469 { 0, "no" },
17470 { -1, NULL },
17471 };
17472
17473
17474 static const char *insecure2str(int mode)
17475 {
17476 return map_x_s(insecurestr, mode, "<error>");
17477 }
17478
17479 static const struct _map_x_s allowoverlapstr[] = {
17480 { SIP_PAGE2_ALLOWOVERLAP_YES, "Yes" },
17481 { SIP_PAGE2_ALLOWOVERLAP_DTMF, "DTMF" },
17482 { SIP_PAGE2_ALLOWOVERLAP_NO, "No" },
17483 { -1, NULL },
17484 };
17485
17486
17487 static const char *allowoverlap2str(int mode)
17488 {
17489 return map_x_s(allowoverlapstr, mode, "<error>");
17490 }
17491
17492
17493
17494
17495 static void cleanup_stale_contexts(char *new, char *old)
17496 {
17497 char *oldcontext, *newcontext, *stalecontext, *stringp, newlist[AST_MAX_CONTEXT];
17498
17499 while ((oldcontext = strsep(&old, "&"))) {
17500 stalecontext = '\0';
17501 ast_copy_string(newlist, new, sizeof(newlist));
17502 stringp = newlist;
17503 while ((newcontext = strsep(&stringp, "&"))) {
17504 if (!strcmp(newcontext, oldcontext)) {
17505
17506 stalecontext = '\0';
17507 break;
17508 } else if (strcmp(newcontext, oldcontext)) {
17509 stalecontext = oldcontext;
17510 }
17511
17512 }
17513 if (stalecontext)
17514 ast_context_destroy(ast_context_find(stalecontext), "SIP");
17515 }
17516 }
17517
17518
17519
17520
17521
17522
17523
17524
17525
17526
17527
17528 static int dialog_needdestroy(void *dialogobj, void *arg, int flags)
17529 {
17530 struct sip_pvt *dialog = dialogobj;
17531 time_t *t = arg;
17532
17533 if (sip_pvt_trylock(dialog)) {
17534
17535
17536 return 0;
17537 }
17538
17539
17540 check_rtp_timeout(dialog, *t);
17541
17542
17543 if (dialog->rtp && ast_rtp_instance_get_bridged(dialog->rtp)) {
17544 ast_debug(2, "Bridge still active. Delaying destroy of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
17545 sip_pvt_unlock(dialog);
17546 return 0;
17547 }
17548
17549 if (dialog->vrtp && ast_rtp_instance_get_bridged(dialog->vrtp)) {
17550 ast_debug(2, "Bridge still active. Delaying destroy of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
17551 sip_pvt_unlock(dialog);
17552 return 0;
17553 }
17554
17555
17556
17557
17558 if (dialog->needdestroy && !dialog->packets && !dialog->owner) {
17559
17560 if (dialog->rtp && ast_rtp_instance_get_bridged(dialog->rtp)) {
17561 ast_debug(2, "Bridge still active. Delaying destruction of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
17562 sip_pvt_unlock(dialog);
17563 return 0;
17564 }
17565
17566 if (dialog->vrtp && ast_rtp_instance_get_bridged(dialog->vrtp)) {
17567 ast_debug(2, "Bridge still active. Delaying destroy of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
17568 sip_pvt_unlock(dialog);
17569 return 0;
17570 }
17571
17572 sip_pvt_unlock(dialog);
17573
17574
17575 ao2_t_link(dialogs_to_destroy, dialog, "Link dialog for destruction");
17576 return 0;
17577 }
17578
17579 sip_pvt_unlock(dialog);
17580
17581 return 0;
17582 }
17583
17584
17585
17586
17587
17588
17589
17590
17591
17592
17593
17594 static int dialog_unlink_callback(void *obj, void *arg, int flags)
17595 {
17596 struct sip_pvt *dialog = obj;
17597
17598 dialog_unlink_all(dialog);
17599
17600 return CMP_MATCH;
17601 }
17602
17603
17604
17605 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17606 {
17607 struct sip_peer *peer, *pi;
17608 int prunepeer = FALSE;
17609 int multi = FALSE;
17610 const char *name = NULL;
17611 regex_t regexbuf;
17612 int havepattern = 0;
17613 struct ao2_iterator i;
17614 static const char * const choices[] = { "all", "like", NULL };
17615 char *cmplt;
17616
17617 if (cmd == CLI_INIT) {
17618 e->command = "sip prune realtime [peer|all]";
17619 e->usage =
17620 "Usage: sip prune realtime [peer [<name>|all|like <pattern>]|all]\n"
17621 " Prunes object(s) from the cache.\n"
17622 " Optional regular expression pattern is used to filter the objects.\n";
17623 return NULL;
17624 } else if (cmd == CLI_GENERATE) {
17625 if (a->pos == 4 && !strcasecmp(a->argv[3], "peer")) {
17626 cmplt = ast_cli_complete(a->word, choices, a->n);
17627 if (!cmplt)
17628 cmplt = complete_sip_peer(a->word, a->n - sizeof(choices), SIP_PAGE2_RTCACHEFRIENDS);
17629 return cmplt;
17630 }
17631 if (a->pos == 5 && !strcasecmp(a->argv[4], "like"))
17632 return complete_sip_peer(a->word, a->n, SIP_PAGE2_RTCACHEFRIENDS);
17633 return NULL;
17634 }
17635 switch (a->argc) {
17636 case 4:
17637 name = a->argv[3];
17638
17639 if (!strcasecmp(name, "peer") || !strcasecmp(name, "like"))
17640 return CLI_SHOWUSAGE;
17641 prunepeer = TRUE;
17642 if (!strcasecmp(name, "all")) {
17643 multi = TRUE;
17644 name = NULL;
17645 }
17646
17647 break;
17648 case 5:
17649
17650 name = a->argv[4];
17651 if (!strcasecmp(a->argv[3], "peer"))
17652 prunepeer = TRUE;
17653 else if (!strcasecmp(a->argv[3], "like")) {
17654 prunepeer = TRUE;
17655 multi = TRUE;
17656 } else
17657 return CLI_SHOWUSAGE;
17658 if (!strcasecmp(name, "like"))
17659 return CLI_SHOWUSAGE;
17660 if (!multi && !strcasecmp(name, "all")) {
17661 multi = TRUE;
17662 name = NULL;
17663 }
17664 break;
17665 case 6:
17666 name = a->argv[5];
17667 multi = TRUE;
17668
17669 if (strcasecmp(a->argv[4], "like"))
17670 return CLI_SHOWUSAGE;
17671 if (!strcasecmp(a->argv[3], "peer")) {
17672 prunepeer = TRUE;
17673 } else
17674 return CLI_SHOWUSAGE;
17675 break;
17676 default:
17677 return CLI_SHOWUSAGE;
17678 }
17679
17680 if (multi && name) {
17681 if (regcomp(®exbuf, name, REG_EXTENDED | REG_NOSUB)) {
17682 return CLI_SHOWUSAGE;
17683 }
17684 havepattern = 1;
17685 }
17686
17687 if (multi) {
17688 if (prunepeer) {
17689 int pruned = 0;
17690
17691 i = ao2_iterator_init(peers, 0);
17692 while ((pi = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
17693 ao2_lock(pi);
17694 if (name && regexec(®exbuf, pi->name, 0, NULL, 0)) {
17695 ao2_unlock(pi);
17696 unref_peer(pi, "toss iterator peer ptr before continue");
17697 continue;
17698 };
17699 if (ast_test_flag(&pi->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
17700 pi->the_mark = 1;
17701 pruned++;
17702 }
17703 ao2_unlock(pi);
17704 unref_peer(pi, "toss iterator peer ptr");
17705 }
17706 ao2_iterator_destroy(&i);
17707 if (pruned) {
17708 unlink_marked_peers_from_tables();
17709 ast_cli(a->fd, "%d peers pruned.\n", pruned);
17710 } else
17711 ast_cli(a->fd, "No peers found to prune.\n");
17712 }
17713 } else {
17714 if (prunepeer) {
17715 struct sip_peer tmp;
17716 ast_copy_string(tmp.name, name, sizeof(tmp.name));
17717 if ((peer = ao2_t_find(peers, &tmp, OBJ_POINTER | OBJ_UNLINK, "finding to unlink from peers"))) {
17718 if (!ast_sockaddr_isnull(&peer->addr)) {
17719 ao2_t_unlink(peers_by_ip, peer, "unlinking peer from peers_by_ip also");
17720 }
17721 if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
17722 ast_cli(a->fd, "Peer '%s' is not a Realtime peer, cannot be pruned.\n", name);
17723
17724 ao2_t_link(peers, peer, "link peer into peer table");
17725 if (!ast_sockaddr_isnull(&peer->addr)) {
17726 ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
17727 }
17728 } else
17729 ast_cli(a->fd, "Peer '%s' pruned.\n", name);
17730 unref_peer(peer, "sip_prune_realtime: unref_peer: tossing temp peer ptr");
17731 } else
17732 ast_cli(a->fd, "Peer '%s' not found.\n", name);
17733 }
17734 }
17735
17736 if (havepattern) {
17737 regfree(®exbuf);
17738 }
17739
17740 return CLI_SUCCESS;
17741 }
17742
17743
17744 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref)
17745 {
17746 int x;
17747 format_t codec;
17748
17749 for(x = 0; x < 64 ; x++) {
17750 codec = ast_codec_pref_index(pref, x);
17751 if (!codec)
17752 break;
17753 ast_cli(fd, "%s", ast_getformatname(codec));
17754 ast_cli(fd, ":%d", pref->framing[x]);
17755 if (x < 31 && ast_codec_pref_index(pref, x + 1))
17756 ast_cli(fd, ",");
17757 }
17758 if (!x)
17759 ast_cli(fd, "none");
17760 }
17761
17762
17763 static const char *domain_mode_to_text(const enum domain_mode mode)
17764 {
17765 switch (mode) {
17766 case SIP_DOMAIN_AUTO:
17767 return "[Automatic]";
17768 case SIP_DOMAIN_CONFIG:
17769 return "[Configured]";
17770 }
17771
17772 return "";
17773 }
17774
17775
17776 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17777 {
17778 struct domain *d;
17779 #define FORMAT "%-40.40s %-20.20s %-16.16s\n"
17780
17781 switch (cmd) {
17782 case CLI_INIT:
17783 e->command = "sip show domains";
17784 e->usage =
17785 "Usage: sip show domains\n"
17786 " Lists all configured SIP local domains.\n"
17787 " Asterisk only responds to SIP messages to local domains.\n";
17788 return NULL;
17789 case CLI_GENERATE:
17790 return NULL;
17791 }
17792
17793 if (AST_LIST_EMPTY(&domain_list)) {
17794 ast_cli(a->fd, "SIP Domain support not enabled.\n\n");
17795 return CLI_SUCCESS;
17796 } else {
17797 ast_cli(a->fd, FORMAT, "Our local SIP domains:", "Context", "Set by");
17798 AST_LIST_LOCK(&domain_list);
17799 AST_LIST_TRAVERSE(&domain_list, d, list)
17800 ast_cli(a->fd, FORMAT, d->domain, S_OR(d->context, "(default)"),
17801 domain_mode_to_text(d->mode));
17802 AST_LIST_UNLOCK(&domain_list);
17803 ast_cli(a->fd, "\n");
17804 return CLI_SUCCESS;
17805 }
17806 }
17807 #undef FORMAT
17808
17809
17810 static int manager_sip_show_peer(struct mansession *s, const struct message *m)
17811 {
17812 const char *a[4];
17813 const char *peer;
17814
17815 peer = astman_get_header(m, "Peer");
17816 if (ast_strlen_zero(peer)) {
17817 astman_send_error(s, m, "Peer: <name> missing.");
17818 return 0;
17819 }
17820 a[0] = "sip";
17821 a[1] = "show";
17822 a[2] = "peer";
17823 a[3] = peer;
17824
17825 _sip_show_peer(1, -1, s, m, 4, a);
17826 astman_append(s, "\r\n" );
17827 return 0;
17828 }
17829
17830
17831 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17832 {
17833 switch (cmd) {
17834 case CLI_INIT:
17835 e->command = "sip show peer";
17836 e->usage =
17837 "Usage: sip show peer <name> [load]\n"
17838 " Shows all details on one SIP peer and the current status.\n"
17839 " Option \"load\" forces lookup of peer in realtime storage.\n";
17840 return NULL;
17841 case CLI_GENERATE:
17842 return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
17843 }
17844 return _sip_show_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
17845 }
17846
17847
17848 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
17849 {
17850 struct sip_peer *peer;
17851 int load_realtime;
17852
17853 if (argc < 4)
17854 return CLI_SHOWUSAGE;
17855
17856 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
17857 if ((peer = find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0))) {
17858 sip_poke_peer(peer, 1);
17859 unref_peer(peer, "qualify: done with peer");
17860 } else if (type == 0) {
17861 ast_cli(fd, "Peer '%s' not found\n", argv[3]);
17862 } else {
17863 astman_send_error(s, m, "Peer not found");
17864 }
17865 return CLI_SUCCESS;
17866 }
17867
17868
17869 static int manager_sip_qualify_peer(struct mansession *s, const struct message *m)
17870 {
17871 const char *a[4];
17872 const char *peer;
17873
17874 peer = astman_get_header(m, "Peer");
17875 if (ast_strlen_zero(peer)) {
17876 astman_send_error(s, m, "Peer: <name> missing.");
17877 return 0;
17878 }
17879 a[0] = "sip";
17880 a[1] = "qualify";
17881 a[2] = "peer";
17882 a[3] = peer;
17883
17884 _sip_qualify_peer(1, -1, s, m, 4, a);
17885 astman_append(s, "\r\n\r\n" );
17886 return 0;
17887 }
17888
17889
17890 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17891 {
17892 switch (cmd) {
17893 case CLI_INIT:
17894 e->command = "sip qualify peer";
17895 e->usage =
17896 "Usage: sip qualify peer <name> [load]\n"
17897 " Requests a response from one SIP peer and the current status.\n"
17898 " Option \"load\" forces lookup of peer in realtime storage.\n";
17899 return NULL;
17900 case CLI_GENERATE:
17901 return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
17902 }
17903 return _sip_qualify_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
17904 }
17905
17906
17907 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer)
17908 {
17909 struct sip_mailbox *mailbox;
17910
17911 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
17912 ast_str_append(mailbox_str, 0, "%s%s%s%s",
17913 mailbox->mailbox,
17914 ast_strlen_zero(mailbox->context) ? "" : "@",
17915 S_OR(mailbox->context, ""),
17916 AST_LIST_NEXT(mailbox, entry) ? "," : "");
17917 }
17918 }
17919
17920 static struct _map_x_s faxecmodes[] = {
17921 { SIP_PAGE2_T38SUPPORT_UDPTL, "None"},
17922 { SIP_PAGE2_T38SUPPORT_UDPTL_FEC, "FEC"},
17923 { SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY, "Redundancy"},
17924 { -1, NULL},
17925 };
17926
17927 static const char *faxec2str(int faxec)
17928 {
17929 return map_x_s(faxecmodes, faxec, "Unknown");
17930 }
17931
17932
17933 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
17934 {
17935 char status[30] = "";
17936 char cbuf[256];
17937 struct sip_peer *peer;
17938 char codec_buf[512];
17939 struct ast_codec_pref *pref;
17940 struct ast_variable *v;
17941 int x = 0, load_realtime;
17942 format_t codec = 0;
17943 int realtimepeers;
17944
17945 realtimepeers = ast_check_realtime("sippeers");
17946
17947 if (argc < 4)
17948 return CLI_SHOWUSAGE;
17949
17950 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
17951 peer = find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0);
17952
17953 if (s) {
17954 if (peer) {
17955 const char *id = astman_get_header(m, "ActionID");
17956
17957 astman_append(s, "Response: Success\r\n");
17958 if (!ast_strlen_zero(id))
17959 astman_append(s, "ActionID: %s\r\n", id);
17960 } else {
17961 snprintf (cbuf, sizeof(cbuf), "Peer %s not found.", argv[3]);
17962 astman_send_error(s, m, cbuf);
17963 return CLI_SUCCESS;
17964 }
17965 }
17966 if (peer && type==0 ) {
17967 struct ast_str *mailbox_str = ast_str_alloca(512);
17968 struct sip_auth_container *credentials;
17969
17970 ao2_lock(peer);
17971 credentials = peer->auth;
17972 if (credentials) {
17973 ao2_t_ref(credentials, +1, "Ref peer auth for show");
17974 }
17975 ao2_unlock(peer);
17976
17977 ast_cli(fd, "\n\n");
17978 ast_cli(fd, " * Name : %s\n", peer->name);
17979 if (realtimepeers) {
17980 ast_cli(fd, " Realtime peer: %s\n", peer->is_realtime ? "Yes, cached" : "No");
17981 }
17982 ast_cli(fd, " Secret : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
17983 ast_cli(fd, " MD5Secret : %s\n", ast_strlen_zero(peer->md5secret)?"<Not set>":"<Set>");
17984 ast_cli(fd, " Remote Secret: %s\n", ast_strlen_zero(peer->remotesecret)?"<Not set>":"<Set>");
17985 if (credentials) {
17986 struct sip_auth *auth;
17987
17988 AST_LIST_TRAVERSE(&credentials->list, auth, node) {
17989 ast_cli(fd, " Realm-auth : Realm %-15.15s User %-10.20s %s\n",
17990 auth->realm,
17991 auth->username,
17992 !ast_strlen_zero(auth->secret)
17993 ? "<Secret set>"
17994 : (!ast_strlen_zero(auth->md5secret)
17995 ? "<MD5secret set>" : "<Not set>"));
17996 }
17997 ao2_t_ref(credentials, -1, "Unref peer auth for show");
17998 }
17999 ast_cli(fd, " Context : %s\n", peer->context);
18000 ast_cli(fd, " Subscr.Cont. : %s\n", S_OR(peer->subscribecontext, "<Not set>") );
18001 ast_cli(fd, " Language : %s\n", peer->language);
18002 if (!ast_strlen_zero(peer->accountcode))
18003 ast_cli(fd, " Accountcode : %s\n", peer->accountcode);
18004 ast_cli(fd, " AMA flags : %s\n", ast_cdr_flags2str(peer->amaflags));
18005 ast_cli(fd, " Transfer mode: %s\n", transfermode2str(peer->allowtransfer));
18006 ast_cli(fd, " CallingPres : %s\n", ast_describe_caller_presentation(peer->callingpres));
18007 if (!ast_strlen_zero(peer->fromuser))
18008 ast_cli(fd, " FromUser : %s\n", peer->fromuser);
18009 if (!ast_strlen_zero(peer->fromdomain))
18010 ast_cli(fd, " FromDomain : %s Port %d\n", peer->fromdomain, (peer->fromdomainport) ? peer->fromdomainport : STANDARD_SIP_PORT);
18011 ast_cli(fd, " Callgroup : ");
18012 print_group(fd, peer->callgroup, 0);
18013 ast_cli(fd, " Pickupgroup : ");
18014 print_group(fd, peer->pickupgroup, 0);
18015 peer_mailboxes_to_str(&mailbox_str, peer);
18016 ast_cli(fd, " MOH Suggest : %s\n", peer->mohsuggest);
18017 ast_cli(fd, " Mailbox : %s\n", ast_str_buffer(mailbox_str));
18018 ast_cli(fd, " VM Extension : %s\n", peer->vmexten);
18019 ast_cli(fd, " LastMsgsSent : %d/%d\n", (peer->lastmsgssent & 0x7fff0000) >> 16, peer->lastmsgssent & 0xffff);
18020 ast_cli(fd, " Call limit : %d\n", peer->call_limit);
18021 ast_cli(fd, " Max forwards : %d\n", peer->maxforwards);
18022 if (peer->busy_level)
18023 ast_cli(fd, " Busy level : %d\n", peer->busy_level);
18024 ast_cli(fd, " Dynamic : %s\n", AST_CLI_YESNO(peer->host_dynamic));
18025 ast_cli(fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
18026 ast_cli(fd, " MaxCallBR : %d kbps\n", peer->maxcallbitrate);
18027 ast_cli(fd, " Expire : %ld\n", ast_sched_when(sched, peer->expire));
18028 ast_cli(fd, " Insecure : %s\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
18029 ast_cli(fd, " Force rport : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT)));
18030 ast_cli(fd, " ACL : %s\n", AST_CLI_YESNO(peer->ha != NULL));
18031 ast_cli(fd, " DirectMedACL : %s\n", AST_CLI_YESNO(peer->directmediaha != NULL));
18032 ast_cli(fd, " T.38 support : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
18033 ast_cli(fd, " T.38 EC mode : %s\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
18034 ast_cli(fd, " T.38 MaxDtgrm: %d\n", peer->t38_maxdatagram);
18035 ast_cli(fd, " DirectMedia : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)));
18036 ast_cli(fd, " PromiscRedir : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)));
18037 ast_cli(fd, " User=Phone : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)));
18038 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)));
18039 ast_cli(fd, " Text Support : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)));
18040 ast_cli(fd, " Ign SDP ver : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_IGNORESDPVERSION)));
18041 ast_cli(fd, " Trust RPID : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_TRUSTRPID)));
18042 ast_cli(fd, " Send RPID : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_SENDRPID)));
18043 ast_cli(fd, " Subscriptions: %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
18044 ast_cli(fd, " Overlap dial : %s\n", allowoverlap2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWOVERLAP)));
18045 if (peer->outboundproxy)
18046 ast_cli(fd, " Outb. proxy : %s %s\n", ast_strlen_zero(peer->outboundproxy->name) ? "<not set>" : peer->outboundproxy->name,
18047 peer->outboundproxy->force ? "(forced)" : "");
18048
18049
18050 ast_cli(fd, " DTMFmode : %s\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
18051 ast_cli(fd, " Timer T1 : %d\n", peer->timer_t1);
18052 ast_cli(fd, " Timer B : %d\n", peer->timer_b);
18053 ast_cli(fd, " ToHost : %s\n", peer->tohost);
18054 ast_cli(fd, " Addr->IP : %s\n", ast_sockaddr_stringify(&peer->addr));
18055 ast_cli(fd, " Defaddr->IP : %s\n", ast_sockaddr_stringify(&peer->defaddr));
18056 ast_cli(fd, " Prim.Transp. : %s\n", get_transport(peer->socket.type));
18057 ast_cli(fd, " Allowed.Trsp : %s\n", get_transport_list(peer->transports));
18058 if (!ast_strlen_zero(sip_cfg.regcontext))
18059 ast_cli(fd, " Reg. exten : %s\n", peer->regexten);
18060 ast_cli(fd, " Def. Username: %s\n", peer->username);
18061 ast_cli(fd, " SIP Options : ");
18062 if (peer->sipoptions) {
18063 int lastoption = -1;
18064 for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
18065 if (sip_options[x].id != lastoption) {
18066 if (peer->sipoptions & sip_options[x].id)
18067 ast_cli(fd, "%s ", sip_options[x].text);
18068 lastoption = x;
18069 }
18070 }
18071 } else
18072 ast_cli(fd, "(none)");
18073
18074 ast_cli(fd, "\n");
18075 ast_cli(fd, " Codecs : ");
18076 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
18077 ast_cli(fd, "%s\n", codec_buf);
18078 ast_cli(fd, " Codec Order : (");
18079 print_codec_to_cli(fd, &peer->prefs);
18080 ast_cli(fd, ")\n");
18081
18082 ast_cli(fd, " Auto-Framing : %s \n", AST_CLI_YESNO(peer->autoframing));
18083 ast_cli(fd, " Status : ");
18084 peer_status(peer, status, sizeof(status));
18085 ast_cli(fd, "%s\n", status);
18086 ast_cli(fd, " Useragent : %s\n", peer->useragent);
18087 ast_cli(fd, " Reg. Contact : %s\n", peer->fullcontact);
18088 ast_cli(fd, " Qualify Freq : %d ms\n", peer->qualifyfreq);
18089 if (peer->chanvars) {
18090 ast_cli(fd, " Variables :\n");
18091 for (v = peer->chanvars ; v ; v = v->next)
18092 ast_cli(fd, " %s = %s\n", v->name, v->value);
18093 }
18094
18095 ast_cli(fd, " Sess-Timers : %s\n", stmode2str(peer->stimer.st_mode_oper));
18096 ast_cli(fd, " Sess-Refresh : %s\n", strefresherparam2str(peer->stimer.st_ref));
18097 ast_cli(fd, " Sess-Expires : %d secs\n", peer->stimer.st_max_se);
18098 ast_cli(fd, " Min-Sess : %d secs\n", peer->stimer.st_min_se);
18099 ast_cli(fd, " RTP Engine : %s\n", peer->engine);
18100 ast_cli(fd, " Parkinglot : %s\n", peer->parkinglot);
18101 ast_cli(fd, " Use Reason : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_Q850_REASON)));
18102 ast_cli(fd, " Encryption : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_USE_SRTP)));
18103 ast_cli(fd, "\n");
18104 peer = unref_peer(peer, "sip_show_peer: unref_peer: done with peer ptr");
18105 } else if (peer && type == 1) {
18106 char buffer[256];
18107 struct ast_str *mailbox_str = ast_str_alloca(512);
18108 astman_append(s, "Channeltype: SIP\r\n");
18109 astman_append(s, "ObjectName: %s\r\n", peer->name);
18110 astman_append(s, "ChanObjectType: peer\r\n");
18111 astman_append(s, "SecretExist: %s\r\n", ast_strlen_zero(peer->secret)?"N":"Y");
18112 astman_append(s, "RemoteSecretExist: %s\r\n", ast_strlen_zero(peer->remotesecret)?"N":"Y");
18113 astman_append(s, "MD5SecretExist: %s\r\n", ast_strlen_zero(peer->md5secret)?"N":"Y");
18114 astman_append(s, "Context: %s\r\n", peer->context);
18115 astman_append(s, "Language: %s\r\n", peer->language);
18116 if (!ast_strlen_zero(peer->accountcode))
18117 astman_append(s, "Accountcode: %s\r\n", peer->accountcode);
18118 astman_append(s, "AMAflags: %s\r\n", ast_cdr_flags2str(peer->amaflags));
18119 astman_append(s, "CID-CallingPres: %s\r\n", ast_describe_caller_presentation(peer->callingpres));
18120 if (!ast_strlen_zero(peer->fromuser))
18121 astman_append(s, "SIP-FromUser: %s\r\n", peer->fromuser);
18122 if (!ast_strlen_zero(peer->fromdomain))
18123 astman_append(s, "SIP-FromDomain: %s\r\nSip-FromDomain-Port: %d\r\n", peer->fromdomain, (peer->fromdomainport) ? peer->fromdomainport : STANDARD_SIP_PORT);
18124 astman_append(s, "Callgroup: ");
18125 astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->callgroup));
18126 astman_append(s, "Pickupgroup: ");
18127 astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->pickupgroup));
18128 astman_append(s, "MOHSuggest: %s\r\n", peer->mohsuggest);
18129 peer_mailboxes_to_str(&mailbox_str, peer);
18130 astman_append(s, "VoiceMailbox: %s\r\n", ast_str_buffer(mailbox_str));
18131 astman_append(s, "TransferMode: %s\r\n", transfermode2str(peer->allowtransfer));
18132 astman_append(s, "LastMsgsSent: %d\r\n", peer->lastmsgssent);
18133 astman_append(s, "Maxforwards: %d\r\n", peer->maxforwards);
18134 astman_append(s, "Call-limit: %d\r\n", peer->call_limit);
18135 astman_append(s, "Busy-level: %d\r\n", peer->busy_level);
18136 astman_append(s, "MaxCallBR: %d kbps\r\n", peer->maxcallbitrate);
18137 astman_append(s, "Dynamic: %s\r\n", peer->host_dynamic?"Y":"N");
18138 astman_append(s, "Callerid: %s\r\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, ""));
18139 astman_append(s, "RegExpire: %ld seconds\r\n", ast_sched_when(sched, peer->expire));
18140 astman_append(s, "SIP-AuthInsecure: %s\r\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
18141 astman_append(s, "SIP-Forcerport: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT)?"Y":"N"));
18142 astman_append(s, "ACL: %s\r\n", (peer->ha?"Y":"N"));
18143 astman_append(s, "SIP-CanReinvite: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)?"Y":"N"));
18144 astman_append(s, "SIP-DirectMedia: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)?"Y":"N"));
18145 astman_append(s, "SIP-PromiscRedir: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)?"Y":"N"));
18146 astman_append(s, "SIP-UserPhone: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)?"Y":"N"));
18147 astman_append(s, "SIP-VideoSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)?"Y":"N"));
18148 astman_append(s, "SIP-TextSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)?"Y":"N"));
18149 astman_append(s, "SIP-T.38Support: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)?"Y":"N"));
18150 astman_append(s, "SIP-T.38EC: %s\r\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
18151 astman_append(s, "SIP-T.38MaxDtgrm: %d\r\n", peer->t38_maxdatagram);
18152 astman_append(s, "SIP-Sess-Timers: %s\r\n", stmode2str(peer->stimer.st_mode_oper));
18153 astman_append(s, "SIP-Sess-Refresh: %s\r\n", strefresherparam2str(peer->stimer.st_ref));
18154 astman_append(s, "SIP-Sess-Expires: %d\r\n", peer->stimer.st_max_se);
18155 astman_append(s, "SIP-Sess-Min: %d\r\n", peer->stimer.st_min_se);
18156 astman_append(s, "SIP-RTP-Engine: %s\r\n", peer->engine);
18157 astman_append(s, "SIP-Encryption: %s\r\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_USE_SRTP) ? "Y" : "N");
18158
18159
18160 astman_append(s, "SIP-DTMFmode: %s\r\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
18161 astman_append(s, "ToHost: %s\r\n", peer->tohost);
18162 astman_append(s, "Address-IP: %s\r\nAddress-Port: %d\r\n", ast_sockaddr_stringify_addr(&peer->addr), ast_sockaddr_port(&peer->addr));
18163 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));
18164 astman_append(s, "Default-Username: %s\r\n", peer->username);
18165 if (!ast_strlen_zero(sip_cfg.regcontext))
18166 astman_append(s, "RegExtension: %s\r\n", peer->regexten);
18167 astman_append(s, "Codecs: ");
18168 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
18169 astman_append(s, "%s\r\n", codec_buf);
18170 astman_append(s, "CodecOrder: ");
18171 pref = &peer->prefs;
18172 for(x = 0; x < 64 ; x++) {
18173 codec = ast_codec_pref_index(pref, x);
18174 if (!codec)
18175 break;
18176 astman_append(s, "%s", ast_getformatname(codec));
18177 if (x < 63 && ast_codec_pref_index(pref, x+1))
18178 astman_append(s, ",");
18179 }
18180
18181 astman_append(s, "\r\n");
18182 astman_append(s, "Status: ");
18183 peer_status(peer, status, sizeof(status));
18184 astman_append(s, "%s\r\n", status);
18185 astman_append(s, "SIP-Useragent: %s\r\n", peer->useragent);
18186 astman_append(s, "Reg-Contact: %s\r\n", peer->fullcontact);
18187 astman_append(s, "QualifyFreq: %d ms\r\n", peer->qualifyfreq);
18188 astman_append(s, "Parkinglot: %s\r\n", peer->parkinglot);
18189 if (peer->chanvars) {
18190 for (v = peer->chanvars ; v ; v = v->next) {
18191 astman_append(s, "ChanVariable: %s=%s\r\n", v->name, v->value);
18192 }
18193 }
18194 astman_append(s, "SIP-Use-Reason-Header: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_Q850_REASON)) ? "Y" : "N");
18195
18196 peer = unref_peer(peer, "sip_show_peer: unref_peer: done with peer");
18197
18198 } else {
18199 ast_cli(fd, "Peer %s not found.\n", argv[3]);
18200 ast_cli(fd, "\n");
18201 }
18202
18203 return CLI_SUCCESS;
18204 }
18205
18206
18207 static char *complete_sip_user(const char *word, int state)
18208 {
18209 char *result = NULL;
18210 int wordlen = strlen(word);
18211 int which = 0;
18212 struct ao2_iterator user_iter;
18213 struct sip_peer *user;
18214
18215 user_iter = ao2_iterator_init(peers, 0);
18216 while ((user = ao2_t_iterator_next(&user_iter, "iterate thru peers table"))) {
18217 ao2_lock(user);
18218 if (!(user->type & SIP_TYPE_USER)) {
18219 ao2_unlock(user);
18220 unref_peer(user, "complete sip user");
18221 continue;
18222 }
18223
18224 if (!strncasecmp(word, user->name, wordlen) && ++which > state) {
18225 result = ast_strdup(user->name);
18226 }
18227 ao2_unlock(user);
18228 unref_peer(user, "complete sip user");
18229 if (result) {
18230 break;
18231 }
18232 }
18233 ao2_iterator_destroy(&user_iter);
18234 return result;
18235 }
18236
18237 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state)
18238 {
18239 if (pos == 3)
18240 return complete_sip_user(word, state);
18241
18242 return NULL;
18243 }
18244
18245
18246 static char *sip_show_user(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18247 {
18248 char cbuf[256];
18249 struct sip_peer *user;
18250 struct ast_variable *v;
18251 int load_realtime;
18252
18253 switch (cmd) {
18254 case CLI_INIT:
18255 e->command = "sip show user";
18256 e->usage =
18257 "Usage: sip show user <name> [load]\n"
18258 " Shows all details on one SIP user and the current status.\n"
18259 " Option \"load\" forces lookup of peer in realtime storage.\n";
18260 return NULL;
18261 case CLI_GENERATE:
18262 return complete_sip_show_user(a->line, a->word, a->pos, a->n);
18263 }
18264
18265 if (a->argc < 4)
18266 return CLI_SHOWUSAGE;
18267
18268
18269 load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? TRUE : FALSE;
18270
18271 if ((user = find_peer(a->argv[3], NULL, load_realtime, FINDUSERS, FALSE, 0))) {
18272 ao2_lock(user);
18273 ast_cli(a->fd, "\n\n");
18274 ast_cli(a->fd, " * Name : %s\n", user->name);
18275 ast_cli(a->fd, " Secret : %s\n", ast_strlen_zero(user->secret)?"<Not set>":"<Set>");
18276 ast_cli(a->fd, " MD5Secret : %s\n", ast_strlen_zero(user->md5secret)?"<Not set>":"<Set>");
18277 ast_cli(a->fd, " Context : %s\n", user->context);
18278 ast_cli(a->fd, " Language : %s\n", user->language);
18279 if (!ast_strlen_zero(user->accountcode))
18280 ast_cli(a->fd, " Accountcode : %s\n", user->accountcode);
18281 ast_cli(a->fd, " AMA flags : %s\n", ast_cdr_flags2str(user->amaflags));
18282 ast_cli(a->fd, " Transfer mode: %s\n", transfermode2str(user->allowtransfer));
18283 ast_cli(a->fd, " MaxCallBR : %d kbps\n", user->maxcallbitrate);
18284 ast_cli(a->fd, " CallingPres : %s\n", ast_describe_caller_presentation(user->callingpres));
18285 ast_cli(a->fd, " Call limit : %d\n", user->call_limit);
18286 ast_cli(a->fd, " Callgroup : ");
18287 print_group(a->fd, user->callgroup, 0);
18288 ast_cli(a->fd, " Pickupgroup : ");
18289 print_group(a->fd, user->pickupgroup, 0);
18290 ast_cli(a->fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), user->cid_name, user->cid_num, "<unspecified>"));
18291 ast_cli(a->fd, " ACL : %s\n", AST_CLI_YESNO(user->ha != NULL));
18292 ast_cli(a->fd, " Sess-Timers : %s\n", stmode2str(user->stimer.st_mode_oper));
18293 ast_cli(a->fd, " Sess-Refresh : %s\n", strefresherparam2str(user->stimer.st_ref));
18294 ast_cli(a->fd, " Sess-Expires : %d secs\n", user->stimer.st_max_se);
18295 ast_cli(a->fd, " Sess-Min-SE : %d secs\n", user->stimer.st_min_se);
18296 ast_cli(a->fd, " RTP Engine : %s\n", user->engine);
18297
18298 ast_cli(a->fd, " Codec Order : (");
18299 print_codec_to_cli(a->fd, &user->prefs);
18300 ast_cli(a->fd, ")\n");
18301
18302 ast_cli(a->fd, " Auto-Framing: %s \n", AST_CLI_YESNO(user->autoframing));
18303 if (user->chanvars) {
18304 ast_cli(a->fd, " Variables :\n");
18305 for (v = user->chanvars ; v ; v = v->next)
18306 ast_cli(a->fd, " %s = %s\n", v->name, v->value);
18307 }
18308
18309 ast_cli(a->fd, "\n");
18310
18311 ao2_unlock(user);
18312 unref_peer(user, "sip show user");
18313 } else {
18314 ast_cli(a->fd, "User %s not found.\n", a->argv[3]);
18315 ast_cli(a->fd, "\n");
18316 }
18317
18318 return CLI_SUCCESS;
18319 }
18320
18321
18322 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18323 {
18324 struct ast_str *cbuf;
18325 struct ast_cb_names cbnames = {9, { "retrans_pkt",
18326 "__sip_autodestruct",
18327 "expire_register",
18328 "auto_congest",
18329 "sip_reg_timeout",
18330 "sip_poke_peer_s",
18331 "sip_poke_noanswer",
18332 "sip_reregister",
18333 "sip_reinvite_retry"},
18334 { retrans_pkt,
18335 __sip_autodestruct,
18336 expire_register,
18337 auto_congest,
18338 sip_reg_timeout,
18339 sip_poke_peer_s,
18340 sip_poke_noanswer,
18341 sip_reregister,
18342 sip_reinvite_retry}};
18343
18344 switch (cmd) {
18345 case CLI_INIT:
18346 e->command = "sip show sched";
18347 e->usage =
18348 "Usage: sip show sched\n"
18349 " Shows stats on what's in the sched queue at the moment\n";
18350 return NULL;
18351 case CLI_GENERATE:
18352 return NULL;
18353 }
18354
18355 cbuf = ast_str_alloca(2048);
18356
18357 ast_cli(a->fd, "\n");
18358 ast_sched_report(sched, &cbuf, &cbnames);
18359 ast_cli(a->fd, "%s", ast_str_buffer(cbuf));
18360
18361 return CLI_SUCCESS;
18362 }
18363
18364
18365 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18366 {
18367 #define FORMAT2 "%-39.39s %-6.6s %-12.12s %8.8s %-20.20s %-25.25s\n"
18368 #define FORMAT "%-39.39s %-6.6s %-12.12s %8d %-20.20s %-25.25s\n"
18369 char host[80];
18370 char user[80];
18371 char tmpdat[256];
18372 struct ast_tm tm;
18373 int counter = 0;
18374
18375 switch (cmd) {
18376 case CLI_INIT:
18377 e->command = "sip show registry";
18378 e->usage =
18379 "Usage: sip show registry\n"
18380 " Lists all registration requests and status.\n";
18381 return NULL;
18382 case CLI_GENERATE:
18383 return NULL;
18384 }
18385
18386 if (a->argc != 3)
18387 return CLI_SHOWUSAGE;
18388 ast_cli(a->fd, FORMAT2, "Host", "dnsmgr", "Username", "Refresh", "State", "Reg.Time");
18389
18390 ASTOBJ_CONTAINER_TRAVERSE(®l, 1, do {
18391 ASTOBJ_RDLOCK(iterator);
18392 snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
18393 snprintf(user, sizeof(user), "%s", iterator->username);
18394 if (!ast_strlen_zero(iterator->regdomain)) {
18395 snprintf(tmpdat, sizeof(tmpdat), "%s", user);
18396 snprintf(user, sizeof(user), "%s@%s", tmpdat, iterator->regdomain);}
18397 if (iterator->regdomainport) {
18398 snprintf(tmpdat, sizeof(tmpdat), "%s", user);
18399 snprintf(user, sizeof(user), "%s:%d", tmpdat, iterator->regdomainport);}
18400 if (iterator->regtime.tv_sec) {
18401 ast_localtime(&iterator->regtime, &tm, NULL);
18402 ast_strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T", &tm);
18403 } else
18404 tmpdat[0] = '\0';
18405 ast_cli(a->fd, FORMAT, host, (iterator->dnsmgr) ? "Y" : "N", user, iterator->refresh, regstate2str(iterator->regstate), tmpdat);
18406 ASTOBJ_UNLOCK(iterator);
18407 counter++;
18408 } while(0));
18409 ast_cli(a->fd, "%d SIP registrations.\n", counter);
18410 return CLI_SUCCESS;
18411 #undef FORMAT
18412 #undef FORMAT2
18413 }
18414
18415
18416
18417
18418
18419 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18420 {
18421 struct sip_peer *peer;
18422 int load_realtime = 0;
18423
18424 switch (cmd) {
18425 case CLI_INIT:
18426 e->command = "sip unregister";
18427 e->usage =
18428 "Usage: sip unregister <peer>\n"
18429 " Unregister (force expiration) a SIP peer from the registry\n";
18430 return NULL;
18431 case CLI_GENERATE:
18432 return complete_sip_unregister(a->line, a->word, a->pos, a->n);
18433 }
18434
18435 if (a->argc != 3)
18436 return CLI_SHOWUSAGE;
18437
18438 if ((peer = find_peer(a->argv[2], NULL, load_realtime, FINDPEERS, TRUE, 0))) {
18439 if (peer->expire > 0) {
18440 AST_SCHED_DEL_UNREF(sched, peer->expire,
18441 unref_peer(peer, "remove register expire ref"));
18442 expire_register(ref_peer(peer, "ref for expire_register"));
18443 ast_cli(a->fd, "Unregistered peer \'%s\'\n\n", a->argv[2]);
18444 } else {
18445 ast_cli(a->fd, "Peer %s not registered\n", a->argv[2]);
18446 }
18447 unref_peer(peer, "sip_unregister: unref_peer via sip_unregister: done with peer from find_peer call");
18448 } else {
18449 ast_cli(a->fd, "Peer unknown: \'%s\'. Not unregistered.\n", a->argv[2]);
18450 }
18451
18452 return CLI_SUCCESS;
18453 }
18454
18455
18456 static int show_chanstats_cb(void *__cur, void *__arg, int flags)
18457 {
18458 #define FORMAT2 "%-15.15s %-11.11s %-8.8s %-10.10s %-10.10s ( %%) %-6.6s %-10.10s %-10.10s ( %%) %-6.6s\n"
18459 #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"
18460 struct sip_pvt *cur = __cur;
18461 struct ast_rtp_instance_stats stats;
18462 char durbuf[10];
18463 int duration;
18464 int durh, durm, durs;
18465 struct ast_channel *c;
18466 struct __show_chan_arg *arg = __arg;
18467 int fd = arg->fd;
18468
18469 sip_pvt_lock(cur);
18470 c = cur->owner;
18471
18472 if (cur->subscribed != NONE) {
18473
18474 sip_pvt_unlock(cur);
18475 return 0;
18476 }
18477
18478 if (!cur->rtp) {
18479 if (sipdebug) {
18480 ast_cli(fd, "%-15.15s %-11.11s (inv state: %s) -- %s\n",
18481 ast_sockaddr_stringify_addr(&cur->sa), cur->callid,
18482 invitestate2string[cur->invitestate].desc,
18483 "-- No RTP active");
18484 }
18485 sip_pvt_unlock(cur);
18486 return 0;
18487 }
18488
18489 if (ast_rtp_instance_get_stats(cur->rtp, &stats, AST_RTP_INSTANCE_STAT_ALL)) {
18490 sip_pvt_unlock(cur);
18491 ast_log(LOG_WARNING, "Could not get RTP stats.\n");
18492 return 0;
18493 }
18494
18495 if (c && c->cdr && !ast_tvzero(c->cdr->start)) {
18496 duration = (int)(ast_tvdiff_ms(ast_tvnow(), c->cdr->start) / 1000);
18497 durh = duration / 3600;
18498 durm = (duration % 3600) / 60;
18499 durs = duration % 60;
18500 snprintf(durbuf, sizeof(durbuf), "%02d:%02d:%02d", durh, durm, durs);
18501 } else {
18502 durbuf[0] = '\0';
18503 }
18504
18505 ast_cli(fd, FORMAT,
18506 ast_sockaddr_stringify_addr(&cur->sa),
18507 cur->callid,
18508 durbuf,
18509 stats.rxcount > (unsigned int) 100000 ? (unsigned int) (stats.rxcount)/(unsigned int) 1000 : stats.rxcount,
18510 stats.rxcount > (unsigned int) 100000 ? "K":" ",
18511 stats.rxploss,
18512 (stats.rxcount + stats.rxploss) > 0 ? (double) stats.rxploss / (stats.rxcount + stats.rxploss) * 100 : 0,
18513 stats.rxjitter,
18514 stats.txcount > (unsigned int) 100000 ? (unsigned int) (stats.txcount)/(unsigned int) 1000 : stats.txcount,
18515 stats.txcount > (unsigned int) 100000 ? "K":" ",
18516 stats.txploss,
18517 stats.txcount > 0 ? (double) stats.txploss / stats.txcount * 100 : 0,
18518 stats.txjitter
18519 );
18520 arg->numchans++;
18521 sip_pvt_unlock(cur);
18522
18523 return 0;
18524 }
18525
18526
18527 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18528 {
18529 struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
18530
18531 switch (cmd) {
18532 case CLI_INIT:
18533 e->command = "sip show channelstats";
18534 e->usage =
18535 "Usage: sip show channelstats\n"
18536 " Lists all currently active SIP channel's RTCP statistics.\n"
18537 " Note that calls in the much optimized RTP P2P bridge mode will not show any packets here.";
18538 return NULL;
18539 case CLI_GENERATE:
18540 return NULL;
18541 }
18542
18543 if (a->argc != 3)
18544 return CLI_SHOWUSAGE;
18545
18546 ast_cli(a->fd, FORMAT2, "Peer", "Call ID", "Duration", "Recv: Pack", "Lost", "Jitter", "Send: Pack", "Lost", "Jitter");
18547
18548 ao2_t_callback(dialogs, OBJ_NODATA, show_chanstats_cb, &arg, "callback to sip show chanstats");
18549 ast_cli(a->fd, "%d active SIP channel%s\n", arg.numchans, (arg.numchans != 1) ? "s" : "");
18550 return CLI_SUCCESS;
18551 }
18552 #undef FORMAT
18553 #undef FORMAT2
18554
18555
18556 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18557 {
18558 int realtimepeers;
18559 int realtimeregs;
18560 char codec_buf[SIPBUFSIZE];
18561 const char *msg;
18562 struct sip_auth_container *credentials;
18563
18564 switch (cmd) {
18565 case CLI_INIT:
18566 e->command = "sip show settings";
18567 e->usage =
18568 "Usage: sip show settings\n"
18569 " Provides detailed list of the configuration of the SIP channel.\n";
18570 return NULL;
18571 case CLI_GENERATE:
18572 return NULL;
18573 }
18574
18575 if (a->argc != 3)
18576 return CLI_SHOWUSAGE;
18577
18578 realtimepeers = ast_check_realtime("sippeers");
18579 realtimeregs = ast_check_realtime("sipregs");
18580
18581 ast_mutex_lock(&authl_lock);
18582 credentials = authl;
18583 if (credentials) {
18584 ao2_t_ref(credentials, +1, "Ref global auth for show");
18585 }
18586 ast_mutex_unlock(&authl_lock);
18587
18588 ast_cli(a->fd, "\n\nGlobal Settings:\n");
18589 ast_cli(a->fd, "----------------\n");
18590 ast_cli(a->fd, " UDP Bindaddress: %s\n", ast_sockaddr_stringify(&bindaddr));
18591 if (ast_sockaddr_is_ipv6(&bindaddr) && ast_sockaddr_is_any(&bindaddr)) {
18592 ast_cli(a->fd, " ** Additional Info:\n");
18593 ast_cli(a->fd, " [::] may include IPv4 in addition to IPv6, if such a feature is enabled in the OS.\n");
18594 }
18595 ast_cli(a->fd, " TCP SIP Bindaddress: %s\n",
18596 sip_cfg.tcp_enabled != FALSE ?
18597 ast_sockaddr_stringify(&sip_tcp_desc.local_address) :
18598 "Disabled");
18599 ast_cli(a->fd, " TLS SIP Bindaddress: %s\n",
18600 default_tls_cfg.enabled != FALSE ?
18601 ast_sockaddr_stringify(&sip_tls_desc.local_address) :
18602 "Disabled");
18603 ast_cli(a->fd, " Videosupport: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT)));
18604 ast_cli(a->fd, " Textsupport: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT)));
18605 ast_cli(a->fd, " Ignore SDP sess. ver.: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION)));
18606 ast_cli(a->fd, " AutoCreate Peer: %s\n", AST_CLI_YESNO(sip_cfg.autocreatepeer));
18607 ast_cli(a->fd, " Match Auth Username: %s\n", AST_CLI_YESNO(global_match_auth_username));
18608 ast_cli(a->fd, " Allow unknown access: %s\n", AST_CLI_YESNO(sip_cfg.allowguest));
18609 ast_cli(a->fd, " Allow subscriptions: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
18610 ast_cli(a->fd, " Allow overlap dialing: %s\n", allowoverlap2str(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP)));
18611 ast_cli(a->fd, " Allow promisc. redir: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_PROMISCREDIR)));
18612 ast_cli(a->fd, " Enable call counters: %s\n", AST_CLI_YESNO(global_callcounter));
18613 ast_cli(a->fd, " SIP domain support: %s\n", AST_CLI_YESNO(!AST_LIST_EMPTY(&domain_list)));
18614 ast_cli(a->fd, " Realm. auth: %s\n", AST_CLI_YESNO(credentials != NULL));
18615 if (credentials) {
18616 struct sip_auth *auth;
18617
18618 AST_LIST_TRAVERSE(&credentials->list, auth, node) {
18619 ast_cli(a->fd, " Realm. auth entry: Realm %-15.15s User %-10.20s %s\n",
18620 auth->realm,
18621 auth->username,
18622 !ast_strlen_zero(auth->secret)
18623 ? "<Secret set>"
18624 : (!ast_strlen_zero(auth->md5secret)
18625 ? "<MD5secret set>" : "<Not set>"));
18626 }
18627 ao2_t_ref(credentials, -1, "Unref global auth for show");
18628 }
18629 ast_cli(a->fd, " Our auth realm %s\n", sip_cfg.realm);
18630 ast_cli(a->fd, " Use domains as realms: %s\n", AST_CLI_YESNO(sip_cfg.domainsasrealm));
18631 ast_cli(a->fd, " Call to non-local dom.: %s\n", AST_CLI_YESNO(sip_cfg.allow_external_domains));
18632 ast_cli(a->fd, " URI user is phone no: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_USEREQPHONE)));
18633 ast_cli(a->fd, " Always auth rejects: %s\n", AST_CLI_YESNO(sip_cfg.alwaysauthreject));
18634 ast_cli(a->fd, " Direct RTP setup: %s\n", AST_CLI_YESNO(sip_cfg.directrtpsetup));
18635 ast_cli(a->fd, " User Agent: %s\n", global_useragent);
18636 ast_cli(a->fd, " SDP Session Name: %s\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
18637 ast_cli(a->fd, " SDP Owner Name: %s\n", ast_strlen_zero(global_sdpowner) ? "-" : global_sdpowner);
18638 ast_cli(a->fd, " Reg. context: %s\n", S_OR(sip_cfg.regcontext, "(not set)"));
18639 ast_cli(a->fd, " Regexten on Qualify: %s\n", AST_CLI_YESNO(sip_cfg.regextenonqualify));
18640 ast_cli(a->fd, " Legacy userfield parse: %s\n", AST_CLI_YESNO(sip_cfg.legacy_useroption_parsing));
18641 ast_cli(a->fd, " Caller ID: %s\n", default_callerid);
18642 if ((default_fromdomainport) && (default_fromdomainport != STANDARD_SIP_PORT)) {
18643 ast_cli(a->fd, " From: Domain: %s:%d\n", default_fromdomain, default_fromdomainport);
18644 } else {
18645 ast_cli(a->fd, " From: Domain: %s\n", default_fromdomain);
18646 }
18647 ast_cli(a->fd, " Record SIP history: %s\n", AST_CLI_ONOFF(recordhistory));
18648 ast_cli(a->fd, " Call Events: %s\n", AST_CLI_ONOFF(sip_cfg.callevents));
18649 ast_cli(a->fd, " Auth. Failure Events: %s\n", AST_CLI_ONOFF(global_authfailureevents));
18650
18651 ast_cli(a->fd, " T.38 support: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
18652 ast_cli(a->fd, " T.38 EC mode: %s\n", faxec2str(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
18653 ast_cli(a->fd, " T.38 MaxDtgrm: %d\n", global_t38_maxdatagram);
18654 if (!realtimepeers && !realtimeregs)
18655 ast_cli(a->fd, " SIP realtime: Disabled\n" );
18656 else
18657 ast_cli(a->fd, " SIP realtime: Enabled\n" );
18658 ast_cli(a->fd, " Qualify Freq : %d ms\n", global_qualifyfreq);
18659 ast_cli(a->fd, " Q.850 Reason header: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_Q850_REASON)));
18660 ast_cli(a->fd, " Store SIP_CAUSE: %s\n", AST_CLI_YESNO(global_store_sip_cause));
18661 ast_cli(a->fd, "\nNetwork QoS Settings:\n");
18662 ast_cli(a->fd, "---------------------------\n");
18663 ast_cli(a->fd, " IP ToS SIP: %s\n", ast_tos2str(global_tos_sip));
18664 ast_cli(a->fd, " IP ToS RTP audio: %s\n", ast_tos2str(global_tos_audio));
18665 ast_cli(a->fd, " IP ToS RTP video: %s\n", ast_tos2str(global_tos_video));
18666 ast_cli(a->fd, " IP ToS RTP text: %s\n", ast_tos2str(global_tos_text));
18667 ast_cli(a->fd, " 802.1p CoS SIP: %d\n", global_cos_sip);
18668 ast_cli(a->fd, " 802.1p CoS RTP audio: %d\n", global_cos_audio);
18669 ast_cli(a->fd, " 802.1p CoS RTP video: %d\n", global_cos_video);
18670 ast_cli(a->fd, " 802.1p CoS RTP text: %d\n", global_cos_text);
18671 ast_cli(a->fd, " Jitterbuffer enabled: %s\n", AST_CLI_YESNO(ast_test_flag(&global_jbconf, AST_JB_ENABLED)));
18672 if (ast_test_flag(&global_jbconf, AST_JB_ENABLED)) {
18673 ast_cli(a->fd, " Jitterbuffer forced: %s\n", AST_CLI_YESNO(ast_test_flag(&global_jbconf, AST_JB_FORCED)));
18674 ast_cli(a->fd, " Jitterbuffer max size: %ld\n", global_jbconf.max_size);
18675 ast_cli(a->fd, " Jitterbuffer resync: %ld\n", global_jbconf.resync_threshold);
18676 ast_cli(a->fd, " Jitterbuffer impl: %s\n", global_jbconf.impl);
18677 if (!strcasecmp(global_jbconf.impl, "adaptive")) {
18678 ast_cli(a->fd, " Jitterbuffer tgt extra: %ld\n", global_jbconf.target_extra);
18679 }
18680 ast_cli(a->fd, " Jitterbuffer log: %s\n", AST_CLI_YESNO(ast_test_flag(&global_jbconf, AST_JB_LOG)));
18681 }
18682
18683 ast_cli(a->fd, "\nNetwork Settings:\n");
18684 ast_cli(a->fd, "---------------------------\n");
18685
18686 if (localaddr == NULL)
18687 msg = "Disabled, no localnet list";
18688 else if (ast_sockaddr_isnull(&externaddr))
18689 msg = "Disabled";
18690 else if (!ast_strlen_zero(externhost))
18691 msg = "Enabled using externhost";
18692 else
18693 msg = "Enabled using externaddr";
18694 ast_cli(a->fd, " SIP address remapping: %s\n", msg);
18695 ast_cli(a->fd, " Externhost: %s\n", S_OR(externhost, "<none>"));
18696 ast_cli(a->fd, " Externaddr: %s\n", ast_sockaddr_stringify(&externaddr));
18697 ast_cli(a->fd, " Externrefresh: %d\n", externrefresh);
18698 {
18699 struct ast_ha *d;
18700 const char *prefix = "Localnet:";
18701
18702 for (d = localaddr; d ; prefix = "", d = d->next) {
18703 const char *addr = ast_strdupa(ast_sockaddr_stringify_addr(&d->addr));
18704 const char *mask = ast_strdupa(ast_sockaddr_stringify_addr(&d->netmask));
18705 ast_cli(a->fd, " %-24s%s/%s\n", prefix, addr, mask);
18706 }
18707 }
18708 ast_cli(a->fd, "\nGlobal Signalling Settings:\n");
18709 ast_cli(a->fd, "---------------------------\n");
18710 ast_cli(a->fd, " Codecs: ");
18711 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, sip_cfg.capability);
18712 ast_cli(a->fd, "%s\n", codec_buf);
18713 ast_cli(a->fd, " Codec Order: ");
18714 print_codec_to_cli(a->fd, &default_prefs);
18715 ast_cli(a->fd, "\n");
18716 ast_cli(a->fd, " Relax DTMF: %s\n", AST_CLI_YESNO(global_relaxdtmf));
18717 ast_cli(a->fd, " RFC2833 Compensation: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_RFC2833_COMPENSATE)));
18718 ast_cli(a->fd, " Symmetric RTP: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_SYMMETRICRTP)));
18719 ast_cli(a->fd, " Compact SIP headers: %s\n", AST_CLI_YESNO(sip_cfg.compactheaders));
18720 ast_cli(a->fd, " RTP Keepalive: %d %s\n", global_rtpkeepalive, global_rtpkeepalive ? "" : "(Disabled)" );
18721 ast_cli(a->fd, " RTP Timeout: %d %s\n", global_rtptimeout, global_rtptimeout ? "" : "(Disabled)" );
18722 ast_cli(a->fd, " RTP Hold Timeout: %d %s\n", global_rtpholdtimeout, global_rtpholdtimeout ? "" : "(Disabled)");
18723 ast_cli(a->fd, " MWI NOTIFY mime type: %s\n", default_notifymime);
18724 ast_cli(a->fd, " DNS SRV lookup: %s\n", AST_CLI_YESNO(sip_cfg.srvlookup));
18725 ast_cli(a->fd, " Pedantic SIP support: %s\n", AST_CLI_YESNO(sip_cfg.pedanticsipchecking));
18726 ast_cli(a->fd, " Reg. min duration %d secs\n", min_expiry);
18727 ast_cli(a->fd, " Reg. max duration: %d secs\n", max_expiry);
18728 ast_cli(a->fd, " Reg. default duration: %d secs\n", default_expiry);
18729 ast_cli(a->fd, " Outbound reg. timeout: %d secs\n", global_reg_timeout);
18730 ast_cli(a->fd, " Outbound reg. attempts: %d\n", global_regattempts_max);
18731 ast_cli(a->fd, " Notify ringing state: %s\n", AST_CLI_YESNO(sip_cfg.notifyringing));
18732 if (sip_cfg.notifyringing) {
18733 ast_cli(a->fd, " Include CID: %s%s\n",
18734 AST_CLI_YESNO(sip_cfg.notifycid),
18735 sip_cfg.notifycid == IGNORE_CONTEXT ? " (Ignoring context)" : "");
18736 }
18737 ast_cli(a->fd, " Notify hold state: %s\n", AST_CLI_YESNO(sip_cfg.notifyhold));
18738 ast_cli(a->fd, " SIP Transfer mode: %s\n", transfermode2str(sip_cfg.allowtransfer));
18739 ast_cli(a->fd, " Max Call Bitrate: %d kbps\n", default_maxcallbitrate);
18740 ast_cli(a->fd, " Auto-Framing: %s\n", AST_CLI_YESNO(global_autoframing));
18741 ast_cli(a->fd, " Outb. proxy: %s %s\n", ast_strlen_zero(sip_cfg.outboundproxy.name) ? "<not set>" : sip_cfg.outboundproxy.name,
18742 sip_cfg.outboundproxy.force ? "(forced)" : "");
18743 ast_cli(a->fd, " Session Timers: %s\n", stmode2str(global_st_mode));
18744 ast_cli(a->fd, " Session Refresher: %s\n", strefresherparam2str(global_st_refresher));
18745 ast_cli(a->fd, " Session Expires: %d secs\n", global_max_se);
18746 ast_cli(a->fd, " Session Min-SE: %d secs\n", global_min_se);
18747 ast_cli(a->fd, " Timer T1: %d\n", global_t1);
18748 ast_cli(a->fd, " Timer T1 minimum: %d\n", global_t1min);
18749 ast_cli(a->fd, " Timer B: %d\n", global_timer_b);
18750 ast_cli(a->fd, " No premature media: %s\n", AST_CLI_YESNO(global_prematuremediafilter));
18751 ast_cli(a->fd, " Max forwards: %d\n", sip_cfg.default_max_forwards);
18752
18753 ast_cli(a->fd, "\nDefault Settings:\n");
18754 ast_cli(a->fd, "-----------------\n");
18755 ast_cli(a->fd, " Allowed transports: %s\n", get_transport_list(default_transports));
18756 ast_cli(a->fd, " Outbound transport: %s\n", get_transport(default_primary_transport));
18757 ast_cli(a->fd, " Context: %s\n", sip_cfg.default_context);
18758 ast_cli(a->fd, " Force rport: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_NAT_FORCE_RPORT)));
18759 ast_cli(a->fd, " DTMF: %s\n", dtmfmode2str(ast_test_flag(&global_flags[0], SIP_DTMF)));
18760 ast_cli(a->fd, " Qualify: %d\n", default_qualify);
18761 ast_cli(a->fd, " Use ClientCode: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_USECLIENTCODE)));
18762 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)));
18763 ast_cli(a->fd, " Language: %s\n", default_language);
18764 ast_cli(a->fd, " MOH Interpret: %s\n", default_mohinterpret);
18765 ast_cli(a->fd, " MOH Suggest: %s\n", default_mohsuggest);
18766 ast_cli(a->fd, " Voice Mail Extension: %s\n", default_vmexten);
18767
18768
18769 if (realtimepeers || realtimeregs) {
18770 ast_cli(a->fd, "\nRealtime SIP Settings:\n");
18771 ast_cli(a->fd, "----------------------\n");
18772 ast_cli(a->fd, " Realtime Peers: %s\n", AST_CLI_YESNO(realtimepeers));
18773 ast_cli(a->fd, " Realtime Regs: %s\n", AST_CLI_YESNO(realtimeregs));
18774 ast_cli(a->fd, " Cache Friends: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)));
18775 ast_cli(a->fd, " Update: %s\n", AST_CLI_YESNO(sip_cfg.peer_rtupdate));
18776 ast_cli(a->fd, " Ignore Reg. Expire: %s\n", AST_CLI_YESNO(sip_cfg.ignore_regexpire));
18777 ast_cli(a->fd, " Save sys. name: %s\n", AST_CLI_YESNO(sip_cfg.rtsave_sysname));
18778 ast_cli(a->fd, " Auto Clear: %d (%s)\n", sip_cfg.rtautoclear, ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR) ? "Enabled" : "Disabled");
18779 }
18780 ast_cli(a->fd, "\n----\n");
18781 return CLI_SUCCESS;
18782 }
18783
18784 static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18785 {
18786 #define FORMAT "%-30.30s %-12.12s %-10.10s %-10.10s\n"
18787 char host[80];
18788
18789 switch (cmd) {
18790 case CLI_INIT:
18791 e->command = "sip show mwi";
18792 e->usage =
18793 "Usage: sip show mwi\n"
18794 " Provides a list of MWI subscriptions and status.\n";
18795 return NULL;
18796 case CLI_GENERATE:
18797 return NULL;
18798 }
18799
18800 ast_cli(a->fd, FORMAT, "Host", "Username", "Mailbox", "Subscribed");
18801
18802 ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
18803 ASTOBJ_RDLOCK(iterator);
18804 snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
18805 ast_cli(a->fd, FORMAT, host, iterator->username, iterator->mailbox, AST_CLI_YESNO(iterator->subscribed));
18806 ASTOBJ_UNLOCK(iterator);
18807 } while(0));
18808
18809 return CLI_SUCCESS;
18810 #undef FORMAT
18811 }
18812
18813
18814
18815 static const char *subscription_type2str(enum subscriptiontype subtype)
18816 {
18817 int i;
18818
18819 for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
18820 if (subscription_types[i].type == subtype) {
18821 return subscription_types[i].text;
18822 }
18823 }
18824 return subscription_types[0].text;
18825 }
18826
18827
18828 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype)
18829 {
18830 int i;
18831
18832 for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
18833 if (subscription_types[i].type == subtype) {
18834 return &subscription_types[i];
18835 }
18836 }
18837 return &subscription_types[0];
18838 }
18839
18840
18841
18842
18843
18844
18845
18846
18847 #define FORMAT4 "%-15.15s %-15.15s %-15.15s %-15.15s %-13.13s %-15.15s %-10.10s %-6.6d\n"
18848 #define FORMAT3 "%-15.15s %-15.15s %-15.15s %-15.15s %-13.13s %-15.15s %-10.10s %-6.6s\n"
18849 #define FORMAT2 "%-15.15s %-15.15s %-15.15s %-15.15s %-7.7s %-15.15s %-10.10s %-10.10s\n"
18850 #define FORMAT "%-15.15s %-15.15s %-15.15s %-15.15s %-3.3s %-3.3s %-15.15s %-10.10s %-10.10s\n"
18851
18852
18853 static int show_channels_cb(void *__cur, void *__arg, int flags)
18854 {
18855 struct sip_pvt *cur = __cur;
18856 struct __show_chan_arg *arg = __arg;
18857 const struct ast_sockaddr *dst;
18858
18859 sip_pvt_lock(cur);
18860 dst = sip_real_dst(cur);
18861
18862
18863 if (cur->subscribed == NONE && !arg->subscriptions) {
18864
18865 const char *referstatus = cur->refer ? referstatus2str(cur->refer->status) : "";
18866 char formatbuf[SIPBUFSIZE/2];
18867
18868 ast_cli(arg->fd, FORMAT, ast_sockaddr_stringify_addr(dst),
18869 S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
18870 cur->callid,
18871 ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0),
18872 AST_CLI_YESNO(ast_test_flag(&cur->flags[1], SIP_PAGE2_CALL_ONHOLD)),
18873 cur->needdestroy ? "(d)" : "",
18874 cur->lastmsg ,
18875 referstatus,
18876 cur->relatedpeer ? cur->relatedpeer->name : "<guest>"
18877 );
18878 arg->numchans++;
18879 }
18880 if (cur->subscribed != NONE && arg->subscriptions) {
18881 struct ast_str *mailbox_str = ast_str_alloca(512);
18882 if (cur->subscribed == MWI_NOTIFICATION && cur->relatedpeer)
18883 peer_mailboxes_to_str(&mailbox_str, cur->relatedpeer);
18884 ast_cli(arg->fd, FORMAT4, ast_sockaddr_stringify_addr(dst),
18885 S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
18886 cur->callid,
18887
18888 cur->subscribed == MWI_NOTIFICATION ? "--" : cur->subscribeuri,
18889 cur->subscribed == MWI_NOTIFICATION ? "<none>" : ast_extension_state2str(cur->laststate),
18890 subscription_type2str(cur->subscribed),
18891 cur->subscribed == MWI_NOTIFICATION ? S_OR(ast_str_buffer(mailbox_str), "<none>") : "<none>",
18892 cur->expiry
18893 );
18894 arg->numchans++;
18895 }
18896 sip_pvt_unlock(cur);
18897 return 0;
18898 }
18899
18900
18901
18902
18903
18904
18905 static char *sip_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18906 {
18907 struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
18908
18909
18910 if (cmd == CLI_INIT) {
18911 e->command = "sip show {channels|subscriptions}";
18912 e->usage =
18913 "Usage: sip show channels\n"
18914 " Lists all currently active SIP calls (dialogs).\n"
18915 "Usage: sip show subscriptions\n"
18916 " Lists active SIP subscriptions.\n";
18917 return NULL;
18918 } else if (cmd == CLI_GENERATE)
18919 return NULL;
18920
18921 if (a->argc != e->args)
18922 return CLI_SHOWUSAGE;
18923 arg.subscriptions = !strcasecmp(a->argv[e->args - 1], "subscriptions");
18924 if (!arg.subscriptions)
18925 ast_cli(arg.fd, FORMAT2, "Peer", "User/ANR", "Call ID", "Format", "Hold", "Last Message", "Expiry", "Peer");
18926 else
18927 ast_cli(arg.fd, FORMAT3, "Peer", "User", "Call ID", "Extension", "Last state", "Type", "Mailbox", "Expiry");
18928
18929
18930 ao2_t_callback(dialogs, OBJ_NODATA, show_channels_cb, &arg, "callback to show channels");
18931
18932
18933 ast_cli(arg.fd, "%d active SIP %s%s\n", arg.numchans,
18934 (arg.subscriptions ? "subscription" : "dialog"),
18935 ESS(arg.numchans));
18936 return CLI_SUCCESS;
18937 #undef FORMAT
18938 #undef FORMAT2
18939 #undef FORMAT3
18940 }
18941
18942
18943
18944
18945
18946
18947 static char *complete_sipch(const char *line, const char *word, int pos, int state)
18948 {
18949 int which=0;
18950 struct sip_pvt *cur;
18951 char *c = NULL;
18952 int wordlen = strlen(word);
18953 struct ao2_iterator i;
18954
18955 if (pos != 3) {
18956 return NULL;
18957 }
18958
18959 i = ao2_iterator_init(dialogs, 0);
18960 while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
18961 sip_pvt_lock(cur);
18962 if (!strncasecmp(word, cur->callid, wordlen) && ++which > state) {
18963 c = ast_strdup(cur->callid);
18964 sip_pvt_unlock(cur);
18965 dialog_unref(cur, "drop ref in iterator loop break");
18966 break;
18967 }
18968 sip_pvt_unlock(cur);
18969 dialog_unref(cur, "drop ref in iterator loop");
18970 }
18971 ao2_iterator_destroy(&i);
18972 return c;
18973 }
18974
18975
18976
18977 static char *complete_sip_peer(const char *word, int state, int flags2)
18978 {
18979 char *result = NULL;
18980 int wordlen = strlen(word);
18981 int which = 0;
18982 struct ao2_iterator i = ao2_iterator_init(peers, 0);
18983 struct sip_peer *peer;
18984
18985 while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
18986
18987 if (!strncasecmp(word, peer->name, wordlen) &&
18988 (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
18989 ++which > state)
18990 result = ast_strdup(peer->name);
18991 unref_peer(peer, "toss iterator peer ptr before break");
18992 if (result) {
18993 break;
18994 }
18995 }
18996 ao2_iterator_destroy(&i);
18997 return result;
18998 }
18999
19000
19001 static char *complete_sip_registered_peer(const char *word, int state, int flags2)
19002 {
19003 char *result = NULL;
19004 int wordlen = strlen(word);
19005 int which = 0;
19006 struct ao2_iterator i;
19007 struct sip_peer *peer;
19008
19009 i = ao2_iterator_init(peers, 0);
19010 while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
19011 if (!strncasecmp(word, peer->name, wordlen) &&
19012 (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
19013 ++which > state && peer->expire > 0)
19014 result = ast_strdup(peer->name);
19015 if (result) {
19016 unref_peer(peer, "toss iterator peer ptr before break");
19017 break;
19018 }
19019 unref_peer(peer, "toss iterator peer ptr");
19020 }
19021 ao2_iterator_destroy(&i);
19022 return result;
19023 }
19024
19025
19026 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state)
19027 {
19028 if (pos == 3)
19029 return complete_sipch(line, word, pos, state);
19030
19031 return NULL;
19032 }
19033
19034
19035 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state)
19036 {
19037 if (pos == 3) {
19038 return complete_sip_peer(word, state, 0);
19039 }
19040
19041 return NULL;
19042 }
19043
19044
19045 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state)
19046 {
19047 if (pos == 2)
19048 return complete_sip_registered_peer(word, state, 0);
19049
19050 return NULL;
19051 }
19052
19053
19054 static char *complete_sipnotify(const char *line, const char *word, int pos, int state)
19055 {
19056 char *c = NULL;
19057
19058 if (pos == 2) {
19059 int which = 0;
19060 char *cat = NULL;
19061 int wordlen = strlen(word);
19062
19063
19064
19065 if (!notify_types)
19066 return NULL;
19067
19068 while ( (cat = ast_category_browse(notify_types, cat)) ) {
19069 if (!strncasecmp(word, cat, wordlen) && ++which > state) {
19070 c = ast_strdup(cat);
19071 break;
19072 }
19073 }
19074 return c;
19075 }
19076
19077 if (pos > 2)
19078 return complete_sip_peer(word, state, 0);
19079
19080 return NULL;
19081 }
19082
19083
19084 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
19085 {
19086 struct sip_pvt *cur;
19087 size_t len;
19088 int found = 0;
19089 struct ao2_iterator i;
19090
19091 switch (cmd) {
19092 case CLI_INIT:
19093 e->command = "sip show channel";
19094 e->usage =
19095 "Usage: sip show channel <call-id>\n"
19096 " Provides detailed status on a given SIP dialog (identified by SIP call-id).\n";
19097 return NULL;
19098 case CLI_GENERATE:
19099 return complete_sipch(a->line, a->word, a->pos, a->n);
19100 }
19101
19102 if (a->argc != 4)
19103 return CLI_SHOWUSAGE;
19104 len = strlen(a->argv[3]);
19105
19106 i = ao2_iterator_init(dialogs, 0);
19107 while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
19108 sip_pvt_lock(cur);
19109
19110 if (!strncasecmp(cur->callid, a->argv[3], len)) {
19111 char formatbuf[SIPBUFSIZE/2];
19112 ast_cli(a->fd, "\n");
19113 if (cur->subscribed != NONE)
19114 ast_cli(a->fd, " * Subscription (type: %s)\n", subscription_type2str(cur->subscribed));
19115 else
19116 ast_cli(a->fd, " * SIP Call\n");
19117 ast_cli(a->fd, " Curr. trans. direction: %s\n", ast_test_flag(&cur->flags[0], SIP_OUTGOING) ? "Outgoing" : "Incoming");
19118 ast_cli(a->fd, " Call-ID: %s\n", cur->callid);
19119 ast_cli(a->fd, " Owner channel ID: %s\n", cur->owner ? cur->owner->name : "<none>");
19120 ast_cli(a->fd, " Our Codec Capability: %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->capability));
19121 ast_cli(a->fd, " Non-Codec Capability (DTMF): %d\n", cur->noncodeccapability);
19122 ast_cli(a->fd, " Their Codec Capability: %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->peercapability));
19123 ast_cli(a->fd, " Joint Codec Capability: %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->jointcapability));
19124 ast_cli(a->fd, " Format: %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0) );
19125 ast_cli(a->fd, " T.38 support %s\n", AST_CLI_YESNO(cur->udptl != NULL));
19126 ast_cli(a->fd, " Video support %s\n", AST_CLI_YESNO(cur->vrtp != NULL));
19127 ast_cli(a->fd, " MaxCallBR: %d kbps\n", cur->maxcallbitrate);
19128 ast_cli(a->fd, " Theoretical Address: %s\n", ast_sockaddr_stringify(&cur->sa));
19129 ast_cli(a->fd, " Received Address: %s\n", ast_sockaddr_stringify(&cur->recv));
19130 ast_cli(a->fd, " SIP Transfer mode: %s\n", transfermode2str(cur->allowtransfer));
19131 ast_cli(a->fd, " Force rport: %s\n", AST_CLI_YESNO(ast_test_flag(&cur->flags[0], SIP_NAT_FORCE_RPORT)));
19132 if (ast_sockaddr_isnull(&cur->redirip)) {
19133 ast_cli(a->fd,
19134 " Audio IP: %s (local)\n",
19135 ast_sockaddr_stringify_addr(&cur->ourip));
19136 } else {
19137 ast_cli(a->fd,
19138 " Audio IP: %s (Outside bridge)\n",
19139 ast_sockaddr_stringify_addr(&cur->redirip));
19140 }
19141 ast_cli(a->fd, " Our Tag: %s\n", cur->tag);
19142 ast_cli(a->fd, " Their Tag: %s\n", cur->theirtag);
19143 ast_cli(a->fd, " SIP User agent: %s\n", cur->useragent);
19144 if (!ast_strlen_zero(cur->username))
19145 ast_cli(a->fd, " Username: %s\n", cur->username);
19146 if (!ast_strlen_zero(cur->peername))
19147 ast_cli(a->fd, " Peername: %s\n", cur->peername);
19148 if (!ast_strlen_zero(cur->uri))
19149 ast_cli(a->fd, " Original uri: %s\n", cur->uri);
19150 if (!ast_strlen_zero(cur->cid_num))
19151 ast_cli(a->fd, " Caller-ID: %s\n", cur->cid_num);
19152 ast_cli(a->fd, " Need Destroy: %s\n", AST_CLI_YESNO(cur->needdestroy));
19153 ast_cli(a->fd, " Last Message: %s\n", cur->lastmsg);
19154 ast_cli(a->fd, " Promiscuous Redir: %s\n", AST_CLI_YESNO(ast_test_flag(&cur->flags[0], SIP_PROMISCREDIR)));
19155 ast_cli(a->fd, " Route: %s\n", cur->route ? cur->route->hop : "N/A");
19156 ast_cli(a->fd, " DTMF Mode: %s\n", dtmfmode2str(ast_test_flag(&cur->flags[0], SIP_DTMF)));
19157 ast_cli(a->fd, " SIP Options: ");
19158 if (cur->sipoptions) {
19159 int x;
19160 for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
19161 if (cur->sipoptions & sip_options[x].id)
19162 ast_cli(a->fd, "%s ", sip_options[x].text);
19163 }
19164 ast_cli(a->fd, "\n");
19165 } else
19166 ast_cli(a->fd, "(none)\n");
19167
19168 if (!cur->stimer)
19169 ast_cli(a->fd, " Session-Timer: Uninitiallized\n");
19170 else {
19171 ast_cli(a->fd, " Session-Timer: %s\n", cur->stimer->st_active ? "Active" : "Inactive");
19172 if (cur->stimer->st_active == TRUE) {
19173 ast_cli(a->fd, " S-Timer Interval: %d\n", cur->stimer->st_interval);
19174 ast_cli(a->fd, " S-Timer Refresher: %s\n", strefresher2str(cur->stimer->st_ref));
19175 ast_cli(a->fd, " S-Timer Expirys: %d\n", cur->stimer->st_expirys);
19176 ast_cli(a->fd, " S-Timer Sched Id: %d\n", cur->stimer->st_schedid);
19177 ast_cli(a->fd, " S-Timer Peer Sts: %s\n", cur->stimer->st_active_peer_ua ? "Active" : "Inactive");
19178 ast_cli(a->fd, " S-Timer Cached Min-SE: %d\n", cur->stimer->st_cached_min_se);
19179 ast_cli(a->fd, " S-Timer Cached SE: %d\n", cur->stimer->st_cached_max_se);
19180 ast_cli(a->fd, " S-Timer Cached Ref: %s\n", strefresherparam2str(cur->stimer->st_cached_ref));
19181 ast_cli(a->fd, " S-Timer Cached Mode: %s\n", stmode2str(cur->stimer->st_cached_mode));
19182 }
19183 }
19184
19185 ast_cli(a->fd, "\n\n");
19186
19187 found++;
19188 }
19189
19190 sip_pvt_unlock(cur);
19191
19192 ao2_t_ref(cur, -1, "toss dialog ptr set by iterator_next");
19193 }
19194 ao2_iterator_destroy(&i);
19195
19196 if (!found)
19197 ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
19198
19199 return CLI_SUCCESS;
19200 }
19201
19202
19203 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
19204 {
19205 struct sip_pvt *cur;
19206 size_t len;
19207 int found = 0;
19208 struct ao2_iterator i;
19209
19210 switch (cmd) {
19211 case CLI_INIT:
19212 e->command = "sip show history";
19213 e->usage =
19214 "Usage: sip show history <call-id>\n"
19215 " Provides detailed dialog history on a given SIP call (specified by call-id).\n";
19216 return NULL;
19217 case CLI_GENERATE:
19218 return complete_sip_show_history(a->line, a->word, a->pos, a->n);
19219 }
19220
19221 if (a->argc != 4)
19222 return CLI_SHOWUSAGE;
19223
19224 if (!recordhistory)
19225 ast_cli(a->fd, "\n***Note: History recording is currently DISABLED. Use 'sip set history on' to ENABLE.\n");
19226
19227 len = strlen(a->argv[3]);
19228
19229 i = ao2_iterator_init(dialogs, 0);
19230 while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
19231 sip_pvt_lock(cur);
19232 if (!strncasecmp(cur->callid, a->argv[3], len)) {
19233 struct sip_history *hist;
19234 int x = 0;
19235
19236 ast_cli(a->fd, "\n");
19237 if (cur->subscribed != NONE)
19238 ast_cli(a->fd, " * Subscription\n");
19239 else
19240 ast_cli(a->fd, " * SIP Call\n");
19241 if (cur->history)
19242 AST_LIST_TRAVERSE(cur->history, hist, list)
19243 ast_cli(a->fd, "%d. %s\n", ++x, hist->event);
19244 if (x == 0)
19245 ast_cli(a->fd, "Call '%s' has no history\n", cur->callid);
19246 found++;
19247 }
19248 sip_pvt_unlock(cur);
19249 ao2_t_ref(cur, -1, "toss dialog ptr from iterator_next");
19250 }
19251 ao2_iterator_destroy(&i);
19252
19253 if (!found)
19254 ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
19255
19256 return CLI_SUCCESS;
19257 }
19258
19259
19260 static void sip_dump_history(struct sip_pvt *dialog)
19261 {
19262 int x = 0;
19263 struct sip_history *hist;
19264 static int errmsg = 0;
19265
19266 if (!dialog)
19267 return;
19268
19269 if (!option_debug && !sipdebug) {
19270 if (!errmsg) {
19271 ast_log(LOG_NOTICE, "You must have debugging enabled (SIP or Asterisk) in order to dump SIP history.\n");
19272 errmsg = 1;
19273 }
19274 return;
19275 }
19276
19277 ast_debug(1, "\n---------- SIP HISTORY for '%s' \n", dialog->callid);
19278 if (dialog->subscribed)
19279 ast_debug(1, " * Subscription\n");
19280 else
19281 ast_debug(1, " * SIP Call\n");
19282 if (dialog->history)
19283 AST_LIST_TRAVERSE(dialog->history, hist, list)
19284 ast_debug(1, " %-3.3d. %s\n", ++x, hist->event);
19285 if (!x)
19286 ast_debug(1, "Call '%s' has no history\n", dialog->callid);
19287 ast_debug(1, "\n---------- END SIP HISTORY for '%s' \n", dialog->callid);
19288 }
19289
19290
19291
19292 static void handle_request_info(struct sip_pvt *p, struct sip_request *req)
19293 {
19294 char buf[1024] = "";
19295 unsigned int event;
19296 const char *c = get_header(req, "Content-Type");
19297
19298
19299 if (!strcasecmp(c, "application/dtmf-relay") ||
19300 !strcasecmp(c, "application/vnd.nortelnetworks.digits") ||
19301 !strcasecmp(c, "application/dtmf")) {
19302 unsigned int duration = 0;
19303
19304 if (!p->owner) {
19305 transmit_response(p, "481 Call leg/transaction does not exist", req);
19306 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19307 return;
19308 }
19309
19310
19311
19312 if (strcasecmp(c, "application/dtmf")) {
19313 const char *msg_body;
19314
19315 if ( ast_strlen_zero(msg_body = get_body(req, "Signal", '='))
19316 && ast_strlen_zero(msg_body = get_body(req, "d", '='))) {
19317 ast_log(LOG_WARNING, "Unable to retrieve DTMF signal for INFO message on "
19318 "call %s\n", p->callid);
19319 transmit_response(p, "200 OK", req);
19320 return;
19321 }
19322 ast_copy_string(buf, msg_body, sizeof(buf));
19323
19324 if (!ast_strlen_zero((msg_body = get_body(req, "Duration", '=')))) {
19325 sscanf(msg_body, "%30u", &duration);
19326 }
19327 } else {
19328
19329 get_msg_text(buf, sizeof(buf), req);
19330 }
19331
19332
19333 if (ast_strlen_zero(buf)) {
19334 transmit_response(p, "200 OK", req);
19335 return;
19336 }
19337
19338 if (!duration) {
19339 duration = 100;
19340 }
19341
19342 if (buf[0] == '*') {
19343 event = 10;
19344 } else if (buf[0] == '#') {
19345 event = 11;
19346 } else if (buf[0] == '!') {
19347 event = 16;
19348 } else if ('A' <= buf[0] && buf[0] <= 'D') {
19349 event = 12 + buf[0] - 'A';
19350 } else if ('a' <= buf[0] && buf[0] <= 'd') {
19351 event = 12 + buf[0] - 'a';
19352 } else if ((sscanf(buf, "%30u", &event) != 1) || event > 16) {
19353 ast_log(AST_LOG_WARNING, "Unable to convert DTMF event signal code to a valid "
19354 "value for INFO message on call %s\n", p->callid);
19355 transmit_response(p, "200 OK", req);
19356 return;
19357 }
19358
19359 if (event == 16) {
19360
19361 struct ast_frame f = { AST_FRAME_CONTROL, { AST_CONTROL_FLASH, } };
19362 ast_queue_frame(p->owner, &f);
19363 if (sipdebug) {
19364 ast_verbose("* DTMF-relay event received: FLASH\n");
19365 }
19366 } else {
19367
19368 struct ast_frame f = { AST_FRAME_DTMF, };
19369 if (event < 10) {
19370 f.subclass.integer = '0' + event;
19371 } else if (event == 10) {
19372 f.subclass.integer = '*';
19373 } else if (event == 11) {
19374 f.subclass.integer = '#';
19375 } else {
19376 f.subclass.integer = 'A' + (event - 12);
19377 }
19378 f.len = duration;
19379 ast_queue_frame(p->owner, &f);
19380 if (sipdebug) {
19381 ast_verbose("* DTMF-relay event received: %c\n", (int) f.subclass.integer);
19382 }
19383 }
19384 transmit_response(p, "200 OK", req);
19385 return;
19386 } else if (!strcasecmp(c, "application/media_control+xml")) {
19387
19388 if (p->owner)
19389 ast_queue_control(p->owner, AST_CONTROL_VIDUPDATE);
19390 transmit_response(p, "200 OK", req);
19391 return;
19392 } else if (!ast_strlen_zero(c = get_header(req, "X-ClientCode"))) {
19393
19394 if (ast_test_flag(&p->flags[0], SIP_USECLIENTCODE)) {
19395 if (p->owner && p->owner->cdr)
19396 ast_cdr_setuserfield(p->owner, c);
19397 if (p->owner && ast_bridged_channel(p->owner) && ast_bridged_channel(p->owner)->cdr)
19398 ast_cdr_setuserfield(ast_bridged_channel(p->owner), c);
19399 transmit_response(p, "200 OK", req);
19400 } else {
19401 transmit_response(p, "403 Forbidden", req);
19402 }
19403 return;
19404 } else if (!ast_strlen_zero(c = get_header(req, "Record"))) {
19405
19406
19407
19408
19409
19410
19411
19412 struct ast_call_feature *feat;
19413 int j;
19414 struct ast_frame f = { AST_FRAME_DTMF, };
19415
19416 if (!p->owner) {
19417 transmit_response(p, "481 Call leg/transaction does not exist", req);
19418 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19419 return;
19420 }
19421
19422
19423 ast_rdlock_call_features();
19424 feat = ast_find_call_feature("automon");
19425 if (!feat || ast_strlen_zero(feat->exten)) {
19426 ast_log(LOG_WARNING, "Recording requested, but no One Touch Monitor registered. (See features.conf)\n");
19427
19428 transmit_response(p, "403 Forbidden", req);
19429 ast_unlock_call_features();
19430 return;
19431 }
19432
19433 f.len = 100;
19434 for (j=0; j < strlen(feat->exten); j++) {
19435 f.subclass.integer = feat->exten[j];
19436 ast_queue_frame(p->owner, &f);
19437 if (sipdebug)
19438 ast_verbose("* DTMF-relay event faked: %c\n", f.subclass.integer);
19439 }
19440 ast_unlock_call_features();
19441
19442 ast_debug(1, "Got a Request to Record the channel, state %s\n", c);
19443 transmit_response(p, "200 OK", req);
19444 return;
19445 } else if (ast_strlen_zero(c = get_header(req, "Content-Length")) || !strcasecmp(c, "0")) {
19446
19447 transmit_response(p, "200 OK", req);
19448 return;
19449 }
19450
19451
19452
19453
19454 ast_log(LOG_WARNING, "Unable to parse INFO message from %s. Content %s\n", p->callid, buf);
19455 transmit_response(p, "415 Unsupported media type", req);
19456 return;
19457 }
19458
19459
19460 static char *sip_do_debug_ip(int fd, const char *arg)
19461 {
19462 if (ast_sockaddr_resolve_first_af(&debugaddr, arg, 0, 0)) {
19463 return CLI_SHOWUSAGE;
19464 }
19465
19466 ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_sockaddr_stringify_addr(&debugaddr));
19467 sipdebug |= sip_debug_console;
19468
19469 return CLI_SUCCESS;
19470 }
19471
19472
19473 static char *sip_do_debug_peer(int fd, const char *arg)
19474 {
19475 struct sip_peer *peer = find_peer(arg, NULL, TRUE, FINDPEERS, FALSE, 0);
19476 if (!peer)
19477 ast_cli(fd, "No such peer '%s'\n", arg);
19478 else if (ast_sockaddr_isnull(&peer->addr))
19479 ast_cli(fd, "Unable to get IP address of peer '%s'\n", arg);
19480 else {
19481 ast_sockaddr_copy(&debugaddr, &peer->addr);
19482 ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_sockaddr_stringify_addr(&debugaddr));
19483 sipdebug |= sip_debug_console;
19484 }
19485 if (peer)
19486 unref_peer(peer, "sip_do_debug_peer: unref_peer, from find_peer call");
19487 return CLI_SUCCESS;
19488 }
19489
19490
19491 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
19492 {
19493 int oldsipdebug = sipdebug & sip_debug_console;
19494 const char *what;
19495
19496 if (cmd == CLI_INIT) {
19497 e->command = "sip set debug {on|off|ip|peer}";
19498 e->usage =
19499 "Usage: sip set debug {off|on|ip addr[:port]|peer peername}\n"
19500 " Globally disables dumping of SIP packets,\n"
19501 " or enables it either globally or for a (single)\n"
19502 " IP address or registered peer.\n";
19503 return NULL;
19504 } else if (cmd == CLI_GENERATE) {
19505 if (a->pos == 4 && !strcasecmp(a->argv[3], "peer"))
19506 return complete_sip_peer(a->word, a->n, 0);
19507 return NULL;
19508 }
19509
19510 what = a->argv[e->args-1];
19511 if (a->argc == e->args) {
19512 if (!strcasecmp(what, "on")) {
19513 sipdebug |= sip_debug_console;
19514 sipdebug_text = 1;
19515 memset(&debugaddr, 0, sizeof(debugaddr));
19516 ast_cli(a->fd, "SIP Debugging %senabled\n", oldsipdebug ? "re-" : "");
19517 return CLI_SUCCESS;
19518 } else if (!strcasecmp(what, "off")) {
19519 sipdebug &= ~sip_debug_console;
19520 sipdebug_text = 0;
19521 ast_cli(a->fd, "SIP Debugging Disabled\n");
19522 return CLI_SUCCESS;
19523 }
19524 } else if (a->argc == e->args +1) {
19525 if (!strcasecmp(what, "ip"))
19526 return sip_do_debug_ip(a->fd, a->argv[e->args]);
19527 else if (!strcasecmp(what, "peer"))
19528 return sip_do_debug_peer(a->fd, a->argv[e->args]);
19529 }
19530 return CLI_SHOWUSAGE;
19531 }
19532
19533
19534 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
19535 {
19536 struct ast_variable *varlist;
19537 int i;
19538
19539 switch (cmd) {
19540 case CLI_INIT:
19541 e->command = "sip notify";
19542 e->usage =
19543 "Usage: sip notify <type> <peer> [<peer>...]\n"
19544 " Send a NOTIFY message to a SIP peer or peers\n"
19545 " Message types are defined in sip_notify.conf\n";
19546 return NULL;
19547 case CLI_GENERATE:
19548 return complete_sipnotify(a->line, a->word, a->pos, a->n);
19549 }
19550
19551 if (a->argc < 4)
19552 return CLI_SHOWUSAGE;
19553
19554 if (!notify_types) {
19555 ast_cli(a->fd, "No %s file found, or no types listed there\n", notify_config);
19556 return CLI_FAILURE;
19557 }
19558
19559 varlist = ast_variable_browse(notify_types, a->argv[2]);
19560
19561 if (!varlist) {
19562 ast_cli(a->fd, "Unable to find notify type '%s'\n", a->argv[2]);
19563 return CLI_FAILURE;
19564 }
19565
19566 for (i = 3; i < a->argc; i++) {
19567 struct sip_pvt *p;
19568 char buf[512];
19569 struct ast_variable *header, *var;
19570
19571 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
19572 ast_log(LOG_WARNING, "Unable to build sip pvt data for notify (memory/socket error)\n");
19573 return CLI_FAILURE;
19574 }
19575
19576 if (create_addr(p, a->argv[i], NULL, 1)) {
19577
19578 dialog_unlink_all(p);
19579 dialog_unref(p, "unref dialog inside for loop" );
19580
19581 ast_cli(a->fd, "Could not create address for '%s'\n", a->argv[i]);
19582 continue;
19583 }
19584
19585
19586 ast_set_flag(&p->flags[0], SIP_OUTGOING);
19587 sip_notify_allocate(p);
19588 p->notify->headers = header = ast_variable_new("Subscription-State", "terminated", "");
19589
19590 for (var = varlist; var; var = var->next) {
19591 ast_copy_string(buf, var->value, sizeof(buf));
19592 ast_unescape_semicolon(buf);
19593
19594 if (!strcasecmp(var->name, "Content")) {
19595 if (ast_str_strlen(p->notify->content))
19596 ast_str_append(&p->notify->content, 0, "\r\n");
19597 ast_str_append(&p->notify->content, 0, "%s", buf);
19598 } else if (!strcasecmp(var->name, "Content-Length")) {
19599 ast_log(LOG_WARNING, "it is not necessary to specify Content-Length in sip_notify.conf, ignoring\n");
19600 } else {
19601 header->next = ast_variable_new(var->name, buf, "");
19602 header = header->next;
19603 }
19604 }
19605
19606
19607 ast_cli(a->fd, "Sending NOTIFY of type '%s' to '%s'\n", a->argv[2], a->argv[i]);
19608 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
19609 transmit_invite(p, SIP_NOTIFY, 0, 2, NULL);
19610 dialog_unref(p, "bump down the count of p since we're done with it.");
19611 }
19612
19613 return CLI_SUCCESS;
19614 }
19615
19616
19617 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
19618 {
19619 switch (cmd) {
19620 case CLI_INIT:
19621 e->command = "sip set history {on|off}";
19622 e->usage =
19623 "Usage: sip set history {on|off}\n"
19624 " Enables/Disables recording of SIP dialog history for debugging purposes.\n"
19625 " Use 'sip show history' to view the history of a call number.\n";
19626 return NULL;
19627 case CLI_GENERATE:
19628 return NULL;
19629 }
19630
19631 if (a->argc != e->args)
19632 return CLI_SHOWUSAGE;
19633
19634 if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
19635 recordhistory = TRUE;
19636 ast_cli(a->fd, "SIP History Recording Enabled (use 'sip show history')\n");
19637 } else if (!strncasecmp(a->argv[e->args - 1], "off", 3)) {
19638 recordhistory = FALSE;
19639 ast_cli(a->fd, "SIP History Recording Disabled\n");
19640 } else {
19641 return CLI_SHOWUSAGE;
19642 }
19643 return CLI_SUCCESS;
19644 }
19645
19646
19647 static int do_register_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code)
19648 {
19649 char *header, *respheader;
19650 char digest[1024];
19651
19652 p->authtries++;
19653 auth_headers(code, &header, &respheader);
19654 memset(digest, 0, sizeof(digest));
19655 if (reply_digest(p, req, header, SIP_REGISTER, digest, sizeof(digest))) {
19656
19657
19658 if (sip_debug_test_pvt(p) && p->registry)
19659 ast_verbose("No authentication challenge, sending blank registration to domain/host name %s\n", p->registry->hostname);
19660
19661 return -1;
19662 }
19663 if (p->do_history)
19664 append_history(p, "RegistryAuth", "Try: %d", p->authtries);
19665 if (sip_debug_test_pvt(p) && p->registry)
19666 ast_verbose("Responding to challenge, registration to domain/host name %s\n", p->registry->hostname);
19667 return transmit_register(p->registry, SIP_REGISTER, digest, respheader);
19668 }
19669
19670
19671 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code, int sipmethod, int init)
19672 {
19673 char *header, *respheader;
19674 char digest[1024];
19675
19676 if (!p->options && !(p->options = ast_calloc(1, sizeof(*p->options))))
19677 return -2;
19678
19679 p->authtries++;
19680 auth_headers(code, &header, &respheader);
19681 ast_debug(2, "Auth attempt %d on %s\n", p->authtries, sip_methods[sipmethod].text);
19682 memset(digest, 0, sizeof(digest));
19683 if (reply_digest(p, req, header, sipmethod, digest, sizeof(digest) )) {
19684
19685 return -1;
19686 }
19687
19688 p->options->auth = digest;
19689 p->options->authheader = respheader;
19690 return transmit_invite(p, sipmethod, sipmethod == SIP_INVITE, init, NULL);
19691 }
19692
19693
19694
19695
19696
19697 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len)
19698 {
19699 char tmp[512];
19700 char *c;
19701 char oldnonce[256];
19702
19703
19704 const struct x {
19705 const char *key;
19706 const ast_string_field *field;
19707 } *i, keys[] = {
19708 { "realm=", &p->realm },
19709 { "nonce=", &p->nonce },
19710 { "opaque=", &p->opaque },
19711 { "qop=", &p->qop },
19712 { "domain=", &p->domain },
19713 { NULL, 0 },
19714 };
19715
19716 ast_copy_string(tmp, get_header(req, header), sizeof(tmp));
19717 if (ast_strlen_zero(tmp))
19718 return -1;
19719 if (strncasecmp(tmp, "Digest ", strlen("Digest "))) {
19720 ast_log(LOG_WARNING, "missing Digest.\n");
19721 return -1;
19722 }
19723 c = tmp + strlen("Digest ");
19724 ast_copy_string(oldnonce, p->nonce, sizeof(oldnonce));
19725 while (c && *(c = ast_skip_blanks(c))) {
19726 for (i = keys; i->key != NULL; i++) {
19727 char *src, *separator;
19728 if (strncasecmp(c, i->key, strlen(i->key)) != 0)
19729 continue;
19730
19731 c += strlen(i->key);
19732 if (*c == '"') {
19733 src = ++c;
19734 separator = "\"";
19735 } else {
19736 src = c;
19737 separator = ",";
19738 }
19739 strsep(&c, separator);
19740 ast_string_field_ptr_set(p, i->field, src);
19741 break;
19742 }
19743 if (i->key == NULL)
19744 strsep(&c, ",");
19745 }
19746
19747 if (strcmp(p->nonce, oldnonce))
19748 p->noncecount = 0;
19749
19750
19751 if (p->registry) {
19752 struct sip_registry *r = p->registry;
19753
19754 if (strcmp(r->nonce, p->nonce)) {
19755 ast_string_field_set(r, realm, p->realm);
19756 ast_string_field_set(r, nonce, p->nonce);
19757 ast_string_field_set(r, authdomain, p->domain);
19758 ast_string_field_set(r, opaque, p->opaque);
19759 ast_string_field_set(r, qop, p->qop);
19760 r->noncecount = 0;
19761 }
19762 }
19763 return build_reply_digest(p, sipmethod, digest, digest_len);
19764 }
19765
19766
19767
19768
19769
19770
19771 static int build_reply_digest(struct sip_pvt *p, int method, char* digest, int digest_len)
19772 {
19773 char a1[256];
19774 char a2[256];
19775 char a1_hash[256];
19776 char a2_hash[256];
19777 char resp[256];
19778 char resp_hash[256];
19779 char uri[256];
19780 char opaque[256] = "";
19781 char cnonce[80];
19782 const char *username;
19783 const char *secret;
19784 const char *md5secret;
19785 struct sip_auth *auth;
19786 struct sip_auth_container *credentials;
19787
19788 if (!ast_strlen_zero(p->domain))
19789 snprintf(uri, sizeof(uri), "%s:%s", p->socket.type == SIP_TRANSPORT_TLS ? "sips" : "sip", p->domain);
19790 else if (!ast_strlen_zero(p->uri))
19791 ast_copy_string(uri, p->uri, sizeof(uri));
19792 else
19793 snprintf(uri, sizeof(uri), "%s:%s@%s", p->socket.type == SIP_TRANSPORT_TLS ? "sips" : "sip", p->username, ast_sockaddr_stringify_host_remote(&p->sa));
19794
19795 snprintf(cnonce, sizeof(cnonce), "%08lx", ast_random());
19796
19797
19798 ao2_lock(p);
19799 credentials = p->peerauth;
19800 if (credentials) {
19801 ao2_t_ref(credentials, +1, "Ref peer auth for digest");
19802 }
19803 ao2_unlock(p);
19804 auth = find_realm_authentication(credentials, p->realm);
19805 if (!auth) {
19806
19807 if (credentials) {
19808 ao2_t_ref(credentials, -1, "Unref peer auth for digest");
19809 }
19810 ast_mutex_lock(&authl_lock);
19811 credentials = authl;
19812 if (credentials) {
19813 ao2_t_ref(credentials, +1, "Ref global auth for digest");
19814 }
19815 ast_mutex_unlock(&authl_lock);
19816 auth = find_realm_authentication(credentials, p->realm);
19817 }
19818
19819 if (auth) {
19820 ast_debug(3, "use realm [%s] from peer [%s][%s]\n", auth->username, p->peername, p->username);
19821 username = auth->username;
19822 secret = auth->secret;
19823 md5secret = auth->md5secret;
19824 if (sipdebug)
19825 ast_debug(1, "Using realm %s authentication for call %s\n", p->realm, p->callid);
19826 } else {
19827
19828 username = p->authname;
19829 secret = p->relatedpeer
19830 && !ast_strlen_zero(p->relatedpeer->remotesecret)
19831 ? p->relatedpeer->remotesecret : p->peersecret;
19832 md5secret = p->peermd5secret;
19833 }
19834 if (ast_strlen_zero(username)) {
19835
19836 if (credentials) {
19837 ao2_t_ref(credentials, -1, "Unref auth for digest");
19838 }
19839 return -1;
19840 }
19841
19842
19843 snprintf(a1, sizeof(a1), "%s:%s:%s", username, p->realm, secret);
19844 snprintf(a2, sizeof(a2), "%s:%s", sip_methods[method].text, uri);
19845 if (!ast_strlen_zero(md5secret))
19846 ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
19847 else
19848 ast_md5_hash(a1_hash, a1);
19849 ast_md5_hash(a2_hash, a2);
19850
19851 p->noncecount++;
19852 if (!ast_strlen_zero(p->qop))
19853 snprintf(resp, sizeof(resp), "%s:%s:%08x:%s:%s:%s", a1_hash, p->nonce, p->noncecount, cnonce, "auth", a2_hash);
19854 else
19855 snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, p->nonce, a2_hash);
19856 ast_md5_hash(resp_hash, resp);
19857
19858
19859 if (!ast_strlen_zero(p->opaque)) {
19860 snprintf(opaque, sizeof(opaque), ", opaque=\"%s\"", p->opaque);
19861 }
19862
19863
19864 if (!ast_strlen_zero(p->qop))
19865 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);
19866 else
19867 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);
19868
19869 append_history(p, "AuthResp", "Auth response sent for %s in realm %s - nc %d", username, p->realm, p->noncecount);
19870
19871 if (credentials) {
19872 ao2_t_ref(credentials, -1, "Unref auth for digest");
19873 }
19874 return 0;
19875 }
19876
19877
19878 static int func_header_read(struct ast_channel *chan, const char *function, char *data, char *buf, size_t len)
19879 {
19880 struct sip_pvt *p;
19881 const char *content = NULL;
19882 AST_DECLARE_APP_ARGS(args,
19883 AST_APP_ARG(header);
19884 AST_APP_ARG(number);
19885 );
19886 int i, number, start = 0;
19887
19888 if (ast_strlen_zero(data)) {
19889 ast_log(LOG_WARNING, "This function requires a header name.\n");
19890 return -1;
19891 }
19892
19893 ast_channel_lock(chan);
19894 if (!IS_SIP_TECH(chan->tech)) {
19895 ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
19896 ast_channel_unlock(chan);
19897 return -1;
19898 }
19899
19900 AST_STANDARD_APP_ARGS(args, data);
19901 if (!args.number) {
19902 number = 1;
19903 } else {
19904 sscanf(args.number, "%30d", &number);
19905 if (number < 1)
19906 number = 1;
19907 }
19908
19909 p = chan->tech_pvt;
19910
19911
19912 if (!p) {
19913 ast_channel_unlock(chan);
19914 return -1;
19915 }
19916
19917 for (i = 0; i < number; i++)
19918 content = __get_header(&p->initreq, args.header, &start);
19919
19920 if (ast_strlen_zero(content)) {
19921 ast_channel_unlock(chan);
19922 return -1;
19923 }
19924
19925 ast_copy_string(buf, content, len);
19926 ast_channel_unlock(chan);
19927
19928 return 0;
19929 }
19930
19931 static struct ast_custom_function sip_header_function = {
19932 .name = "SIP_HEADER",
19933 .read = func_header_read,
19934 };
19935
19936
19937 static int func_check_sipdomain(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
19938 {
19939 if (ast_strlen_zero(data)) {
19940 ast_log(LOG_WARNING, "CHECKSIPDOMAIN requires an argument - A domain name\n");
19941 return -1;
19942 }
19943 if (check_sip_domain(data, NULL, 0))
19944 ast_copy_string(buf, data, len);
19945 else
19946 buf[0] = '\0';
19947 return 0;
19948 }
19949
19950 static struct ast_custom_function checksipdomain_function = {
19951 .name = "CHECKSIPDOMAIN",
19952 .read = func_check_sipdomain,
19953 };
19954
19955
19956 static int function_sippeer(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
19957 {
19958 struct sip_peer *peer;
19959 char *colname;
19960
19961 if ((colname = strchr(data, ':'))) {
19962 static int deprecation_warning = 0;
19963 *colname++ = '\0';
19964 if (deprecation_warning++ % 10 == 0)
19965 ast_log(LOG_WARNING, "SIPPEER(): usage of ':' to separate arguments is deprecated. Please use ',' instead.\n");
19966 } else if ((colname = strchr(data, ',')))
19967 *colname++ = '\0';
19968 else
19969 colname = "ip";
19970
19971 if (!(peer = find_peer(data, NULL, TRUE, FINDPEERS, FALSE, 0)))
19972 return -1;
19973
19974 if (!strcasecmp(colname, "ip")) {
19975 ast_copy_string(buf, ast_sockaddr_stringify_addr(&peer->addr), len);
19976 } else if (!strcasecmp(colname, "port")) {
19977 snprintf(buf, len, "%d", ast_sockaddr_port(&peer->addr));
19978 } else if (!strcasecmp(colname, "status")) {
19979 peer_status(peer, buf, len);
19980 } else if (!strcasecmp(colname, "language")) {
19981 ast_copy_string(buf, peer->language, len);
19982 } else if (!strcasecmp(colname, "regexten")) {
19983 ast_copy_string(buf, peer->regexten, len);
19984 } else if (!strcasecmp(colname, "limit")) {
19985 snprintf(buf, len, "%d", peer->call_limit);
19986 } else if (!strcasecmp(colname, "busylevel")) {
19987 snprintf(buf, len, "%d", peer->busy_level);
19988 } else if (!strcasecmp(colname, "curcalls")) {
19989 snprintf(buf, len, "%d", peer->inUse);
19990 } else if (!strcasecmp(colname, "maxforwards")) {
19991 snprintf(buf, len, "%d", peer->maxforwards);
19992 } else if (!strcasecmp(colname, "accountcode")) {
19993 ast_copy_string(buf, peer->accountcode, len);
19994 } else if (!strcasecmp(colname, "callgroup")) {
19995 ast_print_group(buf, len, peer->callgroup);
19996 } else if (!strcasecmp(colname, "pickupgroup")) {
19997 ast_print_group(buf, len, peer->pickupgroup);
19998 } else if (!strcasecmp(colname, "useragent")) {
19999 ast_copy_string(buf, peer->useragent, len);
20000 } else if (!strcasecmp(colname, "mailbox")) {
20001 struct ast_str *mailbox_str = ast_str_alloca(512);
20002 peer_mailboxes_to_str(&mailbox_str, peer);
20003 ast_copy_string(buf, ast_str_buffer(mailbox_str), len);
20004 } else if (!strcasecmp(colname, "context")) {
20005 ast_copy_string(buf, peer->context, len);
20006 } else if (!strcasecmp(colname, "expire")) {
20007 snprintf(buf, len, "%d", peer->expire);
20008 } else if (!strcasecmp(colname, "dynamic")) {
20009 ast_copy_string(buf, peer->host_dynamic ? "yes" : "no", len);
20010 } else if (!strcasecmp(colname, "callerid_name")) {
20011 ast_copy_string(buf, peer->cid_name, len);
20012 } else if (!strcasecmp(colname, "callerid_num")) {
20013 ast_copy_string(buf, peer->cid_num, len);
20014 } else if (!strcasecmp(colname, "codecs")) {
20015 ast_getformatname_multiple(buf, len -1, peer->capability);
20016 } else if (!strcasecmp(colname, "encryption")) {
20017 snprintf(buf, len, "%d", ast_test_flag(&peer->flags[1], SIP_PAGE2_USE_SRTP));
20018 } else if (!strncasecmp(colname, "chanvar[", 8)) {
20019 char *chanvar=colname + 8;
20020 struct ast_variable *v;
20021
20022 chanvar = strsep(&chanvar, "]");
20023 for (v = peer->chanvars ; v ; v = v->next) {
20024 if (!strcasecmp(v->name, chanvar)) {
20025 ast_copy_string(buf, v->value, len);
20026 }
20027 }
20028 } else if (!strncasecmp(colname, "codec[", 6)) {
20029 char *codecnum;
20030 format_t codec = 0;
20031
20032 codecnum = colname + 6;
20033 codecnum = strsep(&codecnum, "]");
20034 if((codec = ast_codec_pref_index(&peer->prefs, atoi(codecnum)))) {
20035 ast_copy_string(buf, ast_getformatname(codec), len);
20036 } else {
20037 buf[0] = '\0';
20038 }
20039 } else {
20040 buf[0] = '\0';
20041 }
20042
20043 unref_peer(peer, "unref_peer from function_sippeer, just before return");
20044
20045 return 0;
20046 }
20047
20048
20049 static struct ast_custom_function sippeer_function = {
20050 .name = "SIPPEER",
20051 .read = function_sippeer,
20052 };
20053
20054
20055 static int function_sipchaninfo_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
20056 {
20057 struct sip_pvt *p;
20058 static int deprecated = 0;
20059
20060 *buf = 0;
20061
20062 if (!data) {
20063 ast_log(LOG_WARNING, "This function requires a parameter name.\n");
20064 return -1;
20065 }
20066
20067 ast_channel_lock(chan);
20068 if (!IS_SIP_TECH(chan->tech)) {
20069 ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
20070 ast_channel_unlock(chan);
20071 return -1;
20072 }
20073
20074 if (deprecated++ % 20 == 0) {
20075
20076 ast_log(LOG_WARNING, "SIPCHANINFO() is deprecated. Please transition to using CHANNEL().\n");
20077 }
20078
20079 p = chan->tech_pvt;
20080
20081
20082 if (!p) {
20083 ast_channel_unlock(chan);
20084 return -1;
20085 }
20086
20087 if (!strcasecmp(data, "peerip")) {
20088 ast_copy_string(buf, ast_sockaddr_stringify_addr(&p->sa), len);
20089 } else if (!strcasecmp(data, "recvip")) {
20090 ast_copy_string(buf, ast_sockaddr_stringify_addr(&p->recv), len);
20091 } else if (!strcasecmp(data, "from")) {
20092 ast_copy_string(buf, p->from, len);
20093 } else if (!strcasecmp(data, "uri")) {
20094 ast_copy_string(buf, p->uri, len);
20095 } else if (!strcasecmp(data, "useragent")) {
20096 ast_copy_string(buf, p->useragent, len);
20097 } else if (!strcasecmp(data, "peername")) {
20098 ast_copy_string(buf, p->peername, len);
20099 } else if (!strcasecmp(data, "t38passthrough")) {
20100 if (p->t38.state == T38_DISABLED) {
20101 ast_copy_string(buf, "0", len);
20102 } else {
20103 ast_copy_string(buf, "1", len);
20104 }
20105 } else {
20106 ast_channel_unlock(chan);
20107 return -1;
20108 }
20109 ast_channel_unlock(chan);
20110
20111 return 0;
20112 }
20113
20114
20115 static struct ast_custom_function sipchaninfo_function = {
20116 .name = "SIPCHANINFO",
20117 .read = function_sipchaninfo_read,
20118 };
20119
20120
20121
20122
20123 static void change_redirecting_information(struct sip_pvt *p, struct sip_request *req,
20124 struct ast_party_redirecting *redirecting,
20125 struct ast_set_party_redirecting *update_redirecting, int set_call_forward)
20126 {
20127 char *redirecting_from_name = NULL;
20128 char *redirecting_from_number = NULL;
20129 char *redirecting_to_name = NULL;
20130 char *redirecting_to_number = NULL;
20131 int reason = AST_REDIRECTING_REASON_UNCONDITIONAL;
20132 int is_response = req->method == SIP_RESPONSE;
20133 int res = 0;
20134
20135 res = get_rdnis(p, req, &redirecting_from_name, &redirecting_from_number, &reason);
20136 if (res == -1) {
20137 if (is_response) {
20138 get_name_and_number(get_header(req, "TO"), &redirecting_from_name, &redirecting_from_number);
20139 } else {
20140 return;
20141 }
20142 }
20143
20144
20145
20146
20147
20148 if (is_response) {
20149 parse_moved_contact(p, req, &redirecting_to_name, &redirecting_to_number, set_call_forward);
20150 } else {
20151 get_name_and_number(get_header(req, "TO"), &redirecting_to_name, &redirecting_to_number);
20152 }
20153
20154 if (!ast_strlen_zero(redirecting_from_number)) {
20155 ast_debug(3, "Got redirecting from number %s\n", redirecting_from_number);
20156 update_redirecting->from.number = 1;
20157 redirecting->from.number.valid = 1;
20158 ast_free(redirecting->from.number.str);
20159 redirecting->from.number.str = redirecting_from_number;
20160 }
20161 if (!ast_strlen_zero(redirecting_from_name)) {
20162 ast_debug(3, "Got redirecting from name %s\n", redirecting_from_name);
20163 update_redirecting->from.name = 1;
20164 redirecting->from.name.valid = 1;
20165 ast_free(redirecting->from.name.str);
20166 redirecting->from.name.str = redirecting_from_name;
20167 }
20168 if (!ast_strlen_zero(p->cid_tag)) {
20169 ast_free(redirecting->from.tag);
20170 redirecting->from.tag = ast_strdup(p->cid_tag);
20171 ast_free(redirecting->to.tag);
20172 redirecting->to.tag = ast_strdup(p->cid_tag);
20173 }
20174 if (!ast_strlen_zero(redirecting_to_number)) {
20175 ast_debug(3, "Got redirecting to number %s\n", redirecting_to_number);
20176 update_redirecting->to.number = 1;
20177 redirecting->to.number.valid = 1;
20178 ast_free(redirecting->to.number.str);
20179 redirecting->to.number.str = redirecting_to_number;
20180 }
20181 if (!ast_strlen_zero(redirecting_to_name)) {
20182 ast_debug(3, "Got redirecting to name %s\n", redirecting_from_number);
20183 update_redirecting->to.name = 1;
20184 redirecting->to.name.valid = 1;
20185 ast_free(redirecting->to.name.str);
20186 redirecting->to.name.str = redirecting_to_name;
20187 }
20188 redirecting->reason = reason;
20189 }
20190
20191
20192
20193
20194
20195
20196
20197 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req, char **name, char **number, int set_call_forward)
20198 {
20199 char contact[SIPBUFSIZE];
20200 char *contact_name = NULL;
20201 char *contact_number = NULL;
20202 char *separator, *trans;
20203 char *domain;
20204 enum sip_transport transport = SIP_TRANSPORT_UDP;
20205
20206 ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
20207 if ((separator = strchr(contact, ',')))
20208 *separator = '\0';
20209
20210 contact_number = get_in_brackets(contact);
20211 if ((trans = strcasestr(contact_number, ";transport="))) {
20212 trans += 11;
20213
20214 if ((separator = strchr(trans, ';')))
20215 *separator = '\0';
20216
20217 if (!strncasecmp(trans, "tcp", 3))
20218 transport = SIP_TRANSPORT_TCP;
20219 else if (!strncasecmp(trans, "tls", 3))
20220 transport = SIP_TRANSPORT_TLS;
20221 else {
20222 if (strncasecmp(trans, "udp", 3))
20223 ast_debug(1, "received contact with an invalid transport, '%s'\n", contact_number);
20224
20225 transport = SIP_TRANSPORT_UDP;
20226 }
20227 }
20228 contact_number = remove_uri_parameters(contact_number);
20229
20230 if (p->socket.tcptls_session) {
20231 ao2_ref(p->socket.tcptls_session, -1);
20232 p->socket.tcptls_session = NULL;
20233 }
20234
20235 set_socket_transport(&p->socket, transport);
20236
20237 if (set_call_forward && ast_test_flag(&p->flags[0], SIP_PROMISCREDIR)) {
20238 char *host = NULL;
20239 if (!strncasecmp(contact_number, "sip:", 4))
20240 contact_number += 4;
20241 else if (!strncasecmp(contact_number, "sips:", 5))
20242 contact_number += 5;
20243 separator = strchr(contact_number, '/');
20244 if (separator)
20245 *separator = '\0';
20246 if ((host = strchr(contact_number, '@'))) {
20247 *host++ = '\0';
20248 ast_debug(2, "Found promiscuous redirection to 'SIP/%s::::%s@%s'\n", contact_number, get_transport(transport), host);
20249 if (p->owner)
20250 ast_string_field_build(p->owner, call_forward, "SIP/%s::::%s@%s", contact_number, get_transport(transport), host);
20251 } else {
20252 ast_debug(2, "Found promiscuous redirection to 'SIP/::::%s@%s'\n", get_transport(transport), contact_number);
20253 if (p->owner)
20254 ast_string_field_build(p->owner, call_forward, "SIP/::::%s@%s", get_transport(transport), contact_number);
20255 }
20256 } else {
20257 separator = strchr(contact, '@');
20258 if (separator) {
20259 *separator++ = '\0';
20260 domain = separator;
20261 } else {
20262
20263 domain = contact;
20264 }
20265 separator = strchr(contact, '/');
20266 if (separator)
20267 *separator = '\0';
20268
20269 if (!strncasecmp(contact_number, "sip:", 4))
20270 contact_number += 4;
20271 else if (!strncasecmp(contact_number, "sips:", 5))
20272 contact_number += 5;
20273 separator = strchr(contact_number, ';');
20274 if (separator)
20275 *separator = '\0';
20276 ast_uri_decode(contact_number);
20277 if (set_call_forward) {
20278 ast_debug(2, "Received 302 Redirect to extension '%s' (domain %s)\n", contact_number, domain);
20279 if (p->owner) {
20280 pbx_builtin_setvar_helper(p->owner, "SIPDOMAIN", domain);
20281 ast_string_field_set(p->owner, call_forward, contact_number);
20282 }
20283 }
20284 }
20285
20286
20287
20288 if (*contact == '\"') {
20289 contact_name = contact + 1;
20290 if (!(separator = (char *)find_closing_quote(contact_name, NULL))) {
20291 ast_log(LOG_NOTICE, "No closing quote on name in Contact header? %s\n", contact);
20292 }
20293 *separator = '\0';
20294 }
20295
20296 if (name && !ast_strlen_zero(contact_name)) {
20297 *name = ast_strdup(contact_name);
20298 }
20299 if (number) {
20300 *number = ast_strdup(contact_number);
20301 }
20302 }
20303
20304
20305
20306
20307
20308
20309 static void check_pendings(struct sip_pvt *p)
20310 {
20311 if (ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
20312 if (p->reinviteid > -1) {
20313
20314 return;
20315 } else if (p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA) {
20316
20317 p->invitestate = INV_CANCELLED;
20318 transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
20319
20320 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
20321 ast_clear_flag(&p->flags[0], SIP_PENDINGBYE);
20322 }
20323
20324
20325 } else {
20326
20327
20328
20329 if (p->pendinginvite && !p->ongoing_reinvite)
20330 return;
20331
20332 if (p->owner) {
20333 ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
20334 }
20335
20336 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, TRUE);
20337 ast_clear_flag(&p->flags[0], SIP_PENDINGBYE);
20338 }
20339 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20340 } else if (ast_test_flag(&p->flags[0], SIP_NEEDREINVITE)) {
20341
20342 if (p->pendinginvite || p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA || p->waitid > 0) {
20343 ast_debug(2, "NOT Sending pending reinvite (yet) on '%s'\n", p->callid);
20344 } else {
20345 ast_debug(2, "Sending pending reinvite on '%s'\n", p->callid);
20346
20347 transmit_reinvite_with_sdp(p, (p->t38.state == T38_LOCAL_REINVITE ? TRUE : FALSE), FALSE);
20348 ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);
20349 }
20350 }
20351 }
20352
20353
20354
20355
20356
20357 static int sip_reinvite_retry(const void *data)
20358 {
20359 struct sip_pvt *p = (struct sip_pvt *) data;
20360 struct ast_channel *owner;
20361
20362 sip_pvt_lock(p);
20363 while ((owner = p->owner) && ast_channel_trylock(owner)) {
20364 sip_pvt_unlock(p);
20365 usleep(1);
20366 sip_pvt_lock(p);
20367 }
20368 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
20369 p->waitid = -1;
20370 check_pendings(p);
20371 sip_pvt_unlock(p);
20372 if (owner) {
20373 ast_channel_unlock(owner);
20374 }
20375 dialog_unref(p, "unref the dialog ptr from sip_reinvite_retry, because it held a dialog ptr");
20376 return 0;
20377 }
20378
20379
20380
20381
20382
20383
20384 static void handle_response_update(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
20385 {
20386 if (p->options) {
20387 p->options->auth_type = (resp == 401 ? WWW_AUTH : PROXY_AUTH);
20388 }
20389 if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp, SIP_UPDATE, 1)) {
20390 ast_log(LOG_NOTICE, "Failed to authenticate on UPDATE to '%s'\n", get_header(&p->initreq, "From"));
20391 }
20392 }
20393
20394 static void cc_handle_publish_error(struct sip_pvt *pvt, const int resp, struct sip_request *req, struct sip_epa_entry *epa_entry)
20395 {
20396 struct cc_epa_entry *cc_entry = epa_entry->instance_data;
20397 struct sip_monitor_instance *monitor_instance = ao2_callback(sip_monitor_instances, 0,
20398 find_sip_monitor_instance_by_suspension_entry, epa_entry);
20399 const char *min_expires;
20400
20401 if (!monitor_instance) {
20402 ast_log(LOG_WARNING, "Can't find monitor_instance corresponding to epa_entry %p.\n", epa_entry);
20403 return;
20404 }
20405
20406 if (resp != 423) {
20407 ast_cc_monitor_failed(cc_entry->core_id, monitor_instance->device_name,
20408 "Received error response to our PUBLISH");
20409 ao2_ref(monitor_instance, -1);
20410 return;
20411 }
20412
20413
20414
20415
20416
20417
20418
20419
20420
20421 min_expires = get_header(req, "Min-Expires");
20422 if (ast_strlen_zero(min_expires)) {
20423 pvt->expiry *= 2;
20424 if (pvt->expiry < 0) {
20425
20426 ast_cc_monitor_failed(cc_entry->core_id, monitor_instance->device_name,
20427 "PUBLISH expiry overflowed");
20428 ao2_ref(monitor_instance, -1);
20429 return;
20430 }
20431 } else if (sscanf(min_expires, "%d", &pvt->expiry) != 1) {
20432 ast_cc_monitor_failed(cc_entry->core_id, monitor_instance->device_name,
20433 "Min-Expires has non-numeric value");
20434 ao2_ref(monitor_instance, -1);
20435 return;
20436 }
20437
20438
20439
20440 transmit_invite(pvt, SIP_PUBLISH, FALSE, 0, NULL);
20441 ao2_ref(monitor_instance, -1);
20442 }
20443
20444 static void handle_response_publish(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
20445 {
20446 struct sip_epa_entry *epa_entry = p->epa_entry;
20447 const char *etag = get_header(req, "Sip-ETag");
20448
20449 ast_assert(epa_entry != NULL);
20450
20451 if (resp == 401 || resp == 407) {
20452 ast_string_field_set(p, theirtag, NULL);
20453 if (p->options) {
20454 p->options->auth_type = (resp == 401 ? WWW_AUTH : PROXY_AUTH);
20455 }
20456 if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp, SIP_PUBLISH, 0)) {
20457 ast_log(LOG_NOTICE, "Failed to authenticate on PUBLISH to '%s'\n", get_header(&p->initreq, "From"));
20458 pvt_set_needdestroy(p, "Failed to authenticate on PUBLISH");
20459 sip_alreadygone(p);
20460 }
20461 return;
20462 }
20463
20464 if (resp == 501 || resp == 405) {
20465 mark_method_unallowed(&p->allowed_methods, SIP_PUBLISH);
20466 }
20467
20468 if (resp == 200) {
20469 p->authtries = 0;
20470
20471
20472
20473 if (!ast_strlen_zero(etag)) {
20474 ast_copy_string(epa_entry->entity_tag, etag, sizeof(epa_entry->entity_tag));
20475 }
20476
20477
20478
20479
20480 if (epa_entry->static_data->handle_ok) {
20481 epa_entry->static_data->handle_ok(p, req, epa_entry);
20482 }
20483 } else {
20484
20485
20486
20487
20488 if (epa_entry->static_data->handle_error) {
20489 epa_entry->static_data->handle_error(p, resp, req, epa_entry);
20490 }
20491 }
20492 }
20493
20494
20495
20496
20497
20498
20499
20500
20501
20502
20503
20504
20505 static void sip_queue_hangup_cause(struct sip_pvt *p, int cause)
20506 {
20507 struct ast_channel *owner = p->owner;
20508 const char *name = ast_strdupa(owner->name);
20509
20510
20511 ast_channel_ref(owner);
20512 ast_channel_unlock(owner);
20513 sip_pvt_unlock(p);
20514 ast_set_hangupsource(owner, name, 0);
20515 if (cause) {
20516 ast_queue_hangup_with_cause(owner, cause);
20517 } else {
20518 ast_queue_hangup(owner);
20519 }
20520 ast_channel_unref(owner);
20521
20522
20523 owner = sip_pvt_lock_full(p);
20524 if (owner) {
20525 ast_channel_unref(owner);
20526 }
20527 }
20528
20529
20530 static void handle_response_invite(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
20531 {
20532 int outgoing = ast_test_flag(&p->flags[0], SIP_OUTGOING);
20533 int res = 0;
20534 int xmitres = 0;
20535 int reinvite = ast_test_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
20536 char *p_hdrval;
20537 int rtn;
20538 struct ast_party_connected_line connected;
20539 struct ast_set_party_connected_line update_connected;
20540
20541 if (reinvite)
20542 ast_debug(4, "SIP response %d to RE-invite on %s call %s\n", resp, outgoing ? "outgoing" : "incoming", p->callid);
20543 else
20544 ast_debug(4, "SIP response %d to standard invite\n", resp);
20545
20546 if (p->alreadygone) {
20547 ast_debug(1, "Got response on call that is already terminated: %s (ignoring)\n", p->callid);
20548 return;
20549 }
20550
20551
20552
20553 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"));
20554
20555
20556
20557
20558 if (resp > 100 && resp < 200 && resp!=101 && resp != 180 && resp != 181 && resp != 182 && resp != 183)
20559 resp = 183;
20560
20561
20562 if (resp >= 100 && resp < 200 && p->invitestate == INV_CALLING)
20563 p->invitestate = INV_PROCEEDING;
20564
20565
20566 if (resp >= 300 && (p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA ))
20567 p->invitestate = INV_COMPLETED;
20568
20569 if ((resp >= 200 && reinvite)) {
20570 p->ongoing_reinvite = 0;
20571 if (p->reinviteid > -1) {
20572 AST_SCHED_DEL_UNREF(sched, p->reinviteid, dialog_unref(p, "unref dialog for reinvite timeout because of a final response"));
20573 }
20574 }
20575
20576
20577 if ((resp == 200 || resp >= 300) && p->pendinginvite && seqno == p->pendinginvite) {
20578 p->pendinginvite = 0;
20579 }
20580
20581
20582
20583
20584 if (!reinvite) {
20585 set_pvt_allowed_methods(p, req);
20586 }
20587
20588 switch (resp) {
20589 case 100:
20590 case 101:
20591 if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p))
20592 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
20593 check_pendings(p);
20594 break;
20595
20596 case 180:
20597 case 182:
20598 if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p))
20599 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
20600
20601
20602
20603 parse_ok_contact(p, req);
20604 if (!reinvite) {
20605 build_route(p, req, 1, resp);
20606 }
20607 if (!req->ignore && p->owner) {
20608 if (get_rpid(p, req)) {
20609
20610 ast_party_connected_line_init(&connected);
20611 memset(&update_connected, 0, sizeof(update_connected));
20612
20613 update_connected.id.number = 1;
20614 connected.id.number.valid = 1;
20615 connected.id.number.str = (char *) p->cid_num;
20616 connected.id.number.presentation = p->callingpres;
20617
20618 update_connected.id.name = 1;
20619 connected.id.name.valid = 1;
20620 connected.id.name.str = (char *) p->cid_name;
20621 connected.id.name.presentation = p->callingpres;
20622
20623 connected.id.tag = (char *) p->cid_tag;
20624 connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
20625 ast_channel_queue_connected_line_update(p->owner, &connected,
20626 &update_connected);
20627 }
20628 sip_handle_cc(p, req, AST_CC_CCNR);
20629 ast_queue_control(p->owner, AST_CONTROL_RINGING);
20630 if (p->owner->_state != AST_STATE_UP) {
20631 ast_setstate(p->owner, AST_STATE_RINGING);
20632 }
20633 }
20634 if (find_sdp(req)) {
20635 if (p->invitestate != INV_CANCELLED)
20636 p->invitestate = INV_EARLY_MEDIA;
20637 res = process_sdp(p, req, SDP_T38_NONE);
20638 if (!req->ignore && p->owner) {
20639
20640 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
20641 }
20642 ast_rtp_instance_activate(p->rtp);
20643 }
20644 check_pendings(p);
20645 break;
20646
20647 case 181:
20648 if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
20649 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
20650
20651
20652
20653 parse_ok_contact(p, req);
20654 if (!reinvite) {
20655 build_route(p, req, 1, resp);
20656 }
20657 if (!req->ignore && p->owner) {
20658 struct ast_party_redirecting redirecting;
20659 struct ast_set_party_redirecting update_redirecting;
20660
20661 ast_party_redirecting_init(&redirecting);
20662 memset(&update_redirecting, 0, sizeof(update_redirecting));
20663 change_redirecting_information(p, req, &redirecting, &update_redirecting,
20664 FALSE);
20665 ast_channel_queue_redirecting_update(p->owner, &redirecting,
20666 &update_redirecting);
20667 ast_party_redirecting_free(&redirecting);
20668 sip_handle_cc(p, req, AST_CC_CCNR);
20669 }
20670 check_pendings(p);
20671 break;
20672
20673 case 183:
20674 if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
20675 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
20676
20677
20678
20679 parse_ok_contact(p, req);
20680 if (!reinvite) {
20681 build_route(p, req, 1, resp);
20682 }
20683 if (!req->ignore && p->owner) {
20684 if (get_rpid(p, req)) {
20685
20686 ast_party_connected_line_init(&connected);
20687 memset(&update_connected, 0, sizeof(update_connected));
20688
20689 update_connected.id.number = 1;
20690 connected.id.number.valid = 1;
20691 connected.id.number.str = (char *) p->cid_num;
20692 connected.id.number.presentation = p->callingpres;
20693
20694 update_connected.id.name = 1;
20695 connected.id.name.valid = 1;
20696 connected.id.name.str = (char *) p->cid_name;
20697 connected.id.name.presentation = p->callingpres;
20698
20699 connected.id.tag = (char *) p->cid_tag;
20700 connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
20701 ast_channel_queue_connected_line_update(p->owner, &connected,
20702 &update_connected);
20703 }
20704 sip_handle_cc(p, req, AST_CC_CCNR);
20705 }
20706 if (find_sdp(req)) {
20707 if (p->invitestate != INV_CANCELLED)
20708 p->invitestate = INV_EARLY_MEDIA;
20709 res = process_sdp(p, req, SDP_T38_NONE);
20710 if (!req->ignore && p->owner) {
20711
20712 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
20713 }
20714 ast_rtp_instance_activate(p->rtp);
20715 } else {
20716
20717
20718
20719
20720 if (!req->ignore && p->owner) {
20721 ast_queue_control(p->owner, AST_CONTROL_RINGING);
20722 }
20723 }
20724 check_pendings(p);
20725 break;
20726
20727 case 200:
20728 if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
20729 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
20730 p->authtries = 0;
20731 if (find_sdp(req)) {
20732 if ((res = process_sdp(p, req, SDP_T38_ACCEPT)) && !req->ignore)
20733 if (!reinvite) {
20734
20735
20736 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
20737 }
20738 ast_rtp_instance_activate(p->rtp);
20739 }
20740
20741 if (!req->ignore && p->owner) {
20742 int rpid_changed;
20743
20744 rpid_changed = get_rpid(p, req);
20745 if (rpid_changed || !reinvite) {
20746
20747 ast_party_connected_line_init(&connected);
20748 memset(&update_connected, 0, sizeof(update_connected));
20749 if (rpid_changed
20750 || !ast_strlen_zero(p->cid_num)
20751 || (p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
20752 update_connected.id.number = 1;
20753 connected.id.number.valid = 1;
20754 connected.id.number.str = (char *) p->cid_num;
20755 connected.id.number.presentation = p->callingpres;
20756 }
20757 if (rpid_changed
20758 || !ast_strlen_zero(p->cid_name)
20759 || (p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
20760 update_connected.id.name = 1;
20761 connected.id.name.valid = 1;
20762 connected.id.name.str = (char *) p->cid_name;
20763 connected.id.name.presentation = p->callingpres;
20764 }
20765 if (update_connected.id.number || update_connected.id.name) {
20766 connected.id.tag = (char *) p->cid_tag;
20767 connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
20768 ast_channel_queue_connected_line_update(p->owner, &connected,
20769 &update_connected);
20770 }
20771 }
20772 }
20773
20774
20775
20776
20777 if (outgoing) {
20778 update_call_counter(p, DEC_CALL_RINGING);
20779 parse_ok_contact(p, req);
20780
20781 if (!reinvite) {
20782 build_route(p, req, 1, resp);
20783 }
20784 if(set_address_from_contact(p)) {
20785
20786
20787 if (!p->route && !req->ignore)
20788 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
20789 }
20790
20791 }
20792
20793 if (!req->ignore && p->owner) {
20794 if (!reinvite) {
20795 ast_queue_control(p->owner, AST_CONTROL_ANSWER);
20796 if (sip_cfg.callevents)
20797 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
20798 "Channel: %s\r\nChanneltype: %s\r\nUniqueid: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
20799 p->owner->name, "SIP", p->owner->uniqueid, p->callid, p->fullcontact, p->peername);
20800 } else {
20801 if (p->t38.state == T38_DISABLED) {
20802 ast_queue_control(p->owner, AST_CONTROL_UPDATE_RTP_PEER);
20803 } else {
20804 ast_queue_frame(p->owner, &ast_null_frame);
20805 }
20806 }
20807 } else {
20808
20809
20810
20811 if (!req->ignore)
20812 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
20813 }
20814
20815
20816 if (st_get_mode(p, 0) != SESSION_TIMER_MODE_REFUSE && p->outgoing_call == TRUE && !reinvite) {
20817 p_hdrval = (char*)get_header(req, "Session-Expires");
20818 if (!ast_strlen_zero(p_hdrval)) {
20819
20820 enum st_refresher_param st_ref_param;
20821 int tmp_st_interval = 0;
20822 rtn = parse_session_expires(p_hdrval, &tmp_st_interval, &st_ref_param);
20823 if (rtn != 0) {
20824 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
20825 }
20826 if (st_ref_param == SESSION_TIMER_REFRESHER_PARAM_UAC) {
20827 p->stimer->st_ref = SESSION_TIMER_REFRESHER_US;
20828 } else if (st_ref_param == SESSION_TIMER_REFRESHER_PARAM_UAS) {
20829 p->stimer->st_ref = SESSION_TIMER_REFRESHER_THEM;
20830 } else {
20831 ast_log(LOG_WARNING, "Unknown refresher on %s\n", p->callid);
20832 }
20833 if (tmp_st_interval) {
20834 p->stimer->st_interval = tmp_st_interval;
20835 }
20836 p->stimer->st_active = TRUE;
20837 p->stimer->st_active_peer_ua = TRUE;
20838 start_session_timer(p);
20839 } else {
20840
20841 if (st_get_mode(p, 0) == SESSION_TIMER_MODE_ORIGINATE) {
20842 p->stimer->st_ref = SESSION_TIMER_REFRESHER_US;
20843 p->stimer->st_active_peer_ua = FALSE;
20844 start_session_timer(p);
20845 }
20846 }
20847 }
20848
20849
20850
20851 p->invitestate = INV_TERMINATED;
20852 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
20853 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, TRUE);
20854 check_pendings(p);
20855 break;
20856
20857 case 407:
20858 case 401:
20859
20860 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
20861 if (p->options)
20862 p->options->auth_type = resp;
20863
20864
20865 ast_string_field_set(p, theirtag, NULL);
20866 if (!req->ignore) {
20867 if (p->authtries < MAX_AUTHTRIES)
20868 p->invitestate = INV_CALLING;
20869 if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, SIP_INVITE, 1)) {
20870 ast_log(LOG_NOTICE, "Failed to authenticate on INVITE to '%s'\n", get_header(&p->initreq, "From"));
20871 pvt_set_needdestroy(p, "failed to authenticate on INVITE");
20872 sip_alreadygone(p);
20873 if (p->owner)
20874 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
20875 }
20876 }
20877 break;
20878
20879 case 403:
20880
20881 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
20882 ast_log(LOG_WARNING, "Received response: \"Forbidden\" from '%s'\n", get_header(&p->initreq, "From"));
20883 if (!req->ignore && p->owner) {
20884 sip_queue_hangup_cause(p, hangup_sip2cause(resp));
20885 }
20886 break;
20887
20888 case 404:
20889 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
20890 if (p->owner && !req->ignore) {
20891 sip_queue_hangup_cause(p, hangup_sip2cause(resp));
20892 }
20893 break;
20894
20895 case 481:
20896
20897 ast_log(LOG_WARNING, "Re-invite to non-existing call leg on other UA. SIP dialog '%s'. Giving up.\n", p->callid);
20898 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
20899 if (p->owner) {
20900 ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
20901 }
20902 break;
20903
20904 case 422:
20905 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
20906 ast_string_field_set(p, theirtag, NULL);
20907 proc_422_rsp(p, req);
20908 break;
20909
20910 case 428:
20911 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
20912 append_history(p, "Identity", "SIP identity is required. Not supported by Asterisk.");
20913 ast_log(LOG_WARNING, "SIP identity required by proxy. SIP dialog '%s'. Giving up.\n", p->callid);
20914 if (p->owner && !req->ignore) {
20915 ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
20916 }
20917 break;
20918
20919 case 487:
20920
20921
20922
20923 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
20924 if (p->owner && !req->ignore) {
20925 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_NORMAL_CLEARING);
20926 append_history(p, "Hangup", "Got 487 on CANCEL request from us. Queued AST hangup request");
20927 } else if (!req->ignore) {
20928 update_call_counter(p, DEC_CALL_LIMIT);
20929 append_history(p, "Hangup", "Got 487 on CANCEL request from us on call without owner. Killing this dialog.");
20930 }
20931 check_pendings(p);
20932 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20933 break;
20934 case 415:
20935 case 488:
20936 case 606:
20937 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
20938 if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
20939 change_t38_state(p, T38_DISABLED);
20940
20941
20942
20943
20944 transmit_reinvite_with_sdp(p, FALSE, FALSE);
20945 } else {
20946
20947 if (p->owner && !req->ignore) {
20948 ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
20949 }
20950 }
20951 break;
20952 case 491:
20953 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
20954 if (p->owner && !req->ignore) {
20955 if (p->owner->_state != AST_STATE_UP) {
20956 ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
20957 } else {
20958
20959
20960
20961 int wait;
20962
20963
20964 if (p->outgoing_call) {
20965 wait = 2100 + ast_random() % 2000;
20966 } else {
20967 wait = ast_random() % 2000;
20968 }
20969 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."));
20970 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);
20971 ast_debug(2, "Reinvite race. Waiting %d secs before retry\n", wait);
20972 }
20973 }
20974 break;
20975
20976 case 408:
20977 case 405:
20978 case 501:
20979 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
20980 if (p->owner) {
20981 ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
20982 }
20983 break;
20984 }
20985 if (xmitres == XMIT_ERROR)
20986 ast_log(LOG_WARNING, "Could not transmit message in dialog %s\n", p->callid);
20987 }
20988
20989
20990
20991
20992 static void handle_response_notify(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
20993 {
20994 switch (resp) {
20995 case 200:
20996
20997 if (p->owner) {
20998 if (p->refer) {
20999 ast_log(LOG_NOTICE, "Got OK on REFER Notify message\n");
21000 } else {
21001 ast_log(LOG_WARNING, "Notify answer on an owned channel? - %s\n", p->owner->name);
21002 }
21003 } else {
21004 if (p->subscribed == NONE && !p->refer) {
21005 ast_debug(4, "Got 200 accepted on NOTIFY %s\n", p->callid);
21006 pvt_set_needdestroy(p, "received 200 response");
21007 }
21008 if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
21009
21010 ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
21011 cb_extensionstate((char *)p->context, (char *)p->exten, p->laststate, (void *) p);
21012 }
21013 }
21014 break;
21015 case 401:
21016 case 407:
21017 if (!p->notify) {
21018 break;
21019 }
21020 ast_string_field_set(p, theirtag, NULL);
21021 if (ast_strlen_zero(p->authname)) {
21022 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));
21023 pvt_set_needdestroy(p, "unable to authenticate NOTIFY");
21024 }
21025 if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_NOTIFY, 0)) {
21026 ast_log(LOG_NOTICE, "Failed to authenticate on NOTIFY to '%s'\n", get_header(&p->initreq, "From"));
21027 pvt_set_needdestroy(p, "failed to authenticate NOTIFY");
21028 }
21029 break;
21030 case 481:
21031 pvt_set_needdestroy(p, "Received 481 response for NOTIFY");
21032 break;
21033 }
21034 }
21035
21036
21037 static void handle_response_subscribe(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
21038 {
21039 if (p->subscribed == CALL_COMPLETION) {
21040 struct sip_monitor_instance *monitor_instance;
21041
21042 if (resp < 300) {
21043 return;
21044 }
21045
21046
21047 monitor_instance = ao2_callback(sip_monitor_instances, 0,
21048 find_sip_monitor_instance_by_subscription_pvt, p);
21049 if (monitor_instance) {
21050 ast_cc_monitor_failed(monitor_instance->core_id,
21051 monitor_instance->device_name,
21052 "Received error response to our SUBSCRIBE");
21053 }
21054 return;
21055 }
21056
21057 if (p->subscribed != MWI_NOTIFICATION) {
21058 return;
21059 }
21060 if (!p->mwi) {
21061 return;
21062 }
21063
21064 switch (resp) {
21065 case 200:
21066 ast_debug(3, "Got 200 OK on subscription for MWI\n");
21067 set_pvt_allowed_methods(p, req);
21068 if (p->options) {
21069 if (p->options->outboundproxy) {
21070 ao2_ref(p->options->outboundproxy, -1);
21071 }
21072 ast_free(p->options);
21073 p->options = NULL;
21074 }
21075 p->mwi->subscribed = 1;
21076 if ((p->mwi->resub = ast_sched_add(sched, mwi_expiry * 1000, sip_subscribe_mwi_do, ASTOBJ_REF(p->mwi))) < 0) {
21077 ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
21078 }
21079 break;
21080 case 401:
21081 case 407:
21082 ast_string_field_set(p, theirtag, NULL);
21083 if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_SUBSCRIBE, 0)) {
21084 ast_log(LOG_NOTICE, "Failed to authenticate on SUBSCRIBE to '%s'\n", get_header(&p->initreq, "From"));
21085 p->mwi->call = NULL;
21086 ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
21087 pvt_set_needdestroy(p, "failed to authenticate SUBSCRIBE");
21088 }
21089 break;
21090 case 403:
21091 transmit_response_with_date(p, "200 OK", req);
21092 ast_log(LOG_WARNING, "Authentication failed while trying to subscribe for MWI.\n");
21093 p->mwi->call = NULL;
21094 ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
21095 pvt_set_needdestroy(p, "received 403 response");
21096 sip_alreadygone(p);
21097 break;
21098 case 404:
21099 ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side said that a mailbox may not have been configured.\n");
21100 p->mwi->call = NULL;
21101 ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
21102 pvt_set_needdestroy(p, "received 404 response");
21103 break;
21104 case 481:
21105 ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side said that our dialog did not exist.\n");
21106 p->mwi->call = NULL;
21107 ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
21108 pvt_set_needdestroy(p, "received 481 response");
21109 break;
21110 case 500:
21111 case 501:
21112 ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side may have suffered a heart attack.\n");
21113 p->mwi->call = NULL;
21114 ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
21115 pvt_set_needdestroy(p, "received 500/501 response");
21116 break;
21117 }
21118 }
21119
21120
21121
21122
21123 static void handle_response_refer(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
21124 {
21125 enum ast_control_transfer message = AST_TRANSFER_FAILED;
21126
21127
21128 if (!p->refer)
21129 return;
21130
21131 switch (resp) {
21132 case 202:
21133
21134
21135 p->refer->status = REFER_ACCEPTED;
21136
21137 ast_debug(3, "Got 202 accepted on transfer\n");
21138
21139 break;
21140
21141 case 401:
21142 case 407:
21143 if (ast_strlen_zero(p->authname)) {
21144 ast_log(LOG_WARNING, "Asked to authenticate REFER to %s but we have no matching peer or realm auth!\n",
21145 ast_sockaddr_stringify(&p->recv));
21146 if (p->owner) {
21147 ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
21148 }
21149 pvt_set_needdestroy(p, "unable to authenticate REFER");
21150 }
21151 if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_REFER, 0)) {
21152 ast_log(LOG_NOTICE, "Failed to authenticate on REFER to '%s'\n", get_header(&p->initreq, "From"));
21153 p->refer->status = REFER_NOAUTH;
21154 if (p->owner) {
21155 ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
21156 }
21157 pvt_set_needdestroy(p, "failed to authenticate REFER");
21158 }
21159 break;
21160
21161 case 405:
21162
21163
21164 ast_log(LOG_NOTICE, "SIP transfer to %s failed, REFER not allowed. \n", p->refer->refer_to);
21165 pvt_set_needdestroy(p, "received 405 response");
21166 p->refer->status = REFER_FAILED;
21167 if (p->owner) {
21168 ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
21169 }
21170 break;
21171
21172 case 481:
21173
21174
21175
21176
21177 ast_log(LOG_WARNING, "Remote host can't match REFER request to call '%s'. Giving up.\n", p->callid);
21178 if (p->owner)
21179 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
21180 pvt_set_needdestroy(p, "received 481 response");
21181 break;
21182
21183 case 500:
21184 case 501:
21185
21186
21187 ast_log(LOG_NOTICE, "SIP transfer to %s failed, call miserably fails. \n", p->refer->refer_to);
21188 pvt_set_needdestroy(p, "received 500/501 response");
21189 p->refer->status = REFER_FAILED;
21190 if (p->owner) {
21191 ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
21192 }
21193 break;
21194 case 603:
21195 ast_log(LOG_NOTICE, "SIP transfer to %s declined, call miserably fails. \n", p->refer->refer_to);
21196 p->refer->status = REFER_FAILED;
21197 pvt_set_needdestroy(p, "received 603 response");
21198 if (p->owner) {
21199 ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
21200 }
21201 break;
21202 default:
21203
21204
21205
21206
21207 if (resp < 299) {
21208 ast_log(LOG_WARNING, "SIP transfer to %s had unxpected 2xx response (%d), confusion is possible. \n", p->refer->refer_to, resp);
21209 } else {
21210 ast_log(LOG_WARNING, "SIP transfer to %s with response (%d). \n", p->refer->refer_to, resp);
21211 }
21212
21213 p->refer->status = REFER_FAILED;
21214 pvt_set_needdestroy(p, "received failure response");
21215 if (p->owner) {
21216 ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
21217 }
21218 break;
21219 }
21220 }
21221
21222
21223 static int handle_response_register(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
21224 {
21225 int expires, expires_ms;
21226 struct sip_registry *r;
21227 r=p->registry;
21228
21229 switch (resp) {
21230 case 401:
21231 if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
21232 ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s@%s' (Tries %d)\n", p->registry->username, p->registry->hostname, p->authtries);
21233 pvt_set_needdestroy(p, "failed to authenticate REGISTER");
21234 }
21235 break;
21236 case 403:
21237 ast_log(LOG_WARNING, "Forbidden - wrong password on authentication for REGISTER for '%s' to '%s'\n", p->registry->username, p->registry->hostname);
21238 AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 403"));
21239 r->regstate = REG_STATE_NOAUTH;
21240 pvt_set_needdestroy(p, "received 403 response");
21241 break;
21242 case 404:
21243 ast_log(LOG_WARNING, "Got 404 Not found on SIP register to service %s@%s, giving up\n", p->registry->username, p->registry->hostname);
21244 pvt_set_needdestroy(p, "received 404 response");
21245 if (r->call)
21246 r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 404");
21247 r->regstate = REG_STATE_REJECTED;
21248 AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 404"));
21249 break;
21250 case 407:
21251 if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
21252 ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s' (tries '%d')\n", get_header(&p->initreq, "From"), p->authtries);
21253 pvt_set_needdestroy(p, "failed to authenticate REGISTER");
21254 }
21255 break;
21256 case 408:
21257
21258 if (r) {
21259 r->regattempts = 0;
21260 } else {
21261 ast_log(LOG_WARNING, "Got a 408 response to our REGISTER on call %s after we had destroyed the registry object\n", p->callid);
21262 }
21263 break;
21264 case 423:
21265 r->expiry = atoi(get_header(req, "Min-Expires"));
21266 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);
21267 AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 423"));
21268 if (r->call) {
21269 r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 423");
21270 pvt_set_needdestroy(p, "received 423 response");
21271 }
21272 if (r->expiry > max_expiry) {
21273 ast_log(LOG_WARNING, "Required expiration time from %s@%s is too high, giving up\n", p->registry->username, p->registry->hostname);
21274 r->expiry = r->configured_expiry;
21275 r->regstate = REG_STATE_REJECTED;
21276 } else {
21277 r->regstate = REG_STATE_UNREGISTERED;
21278 transmit_register(r, SIP_REGISTER, NULL, NULL);
21279 }
21280 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));
21281 break;
21282 case 479:
21283 ast_log(LOG_WARNING, "Got error 479 on register to %s@%s, giving up (check config)\n", p->registry->username, p->registry->hostname);
21284 pvt_set_needdestroy(p, "received 479 response");
21285 if (r->call)
21286 r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 479");
21287 r->regstate = REG_STATE_REJECTED;
21288 AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 479"));
21289 break;
21290 case 200:
21291 if (!r) {
21292 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));
21293 pvt_set_needdestroy(p, "received erroneous 200 response");
21294 return 0;
21295 }
21296
21297 r->regstate = REG_STATE_REGISTERED;
21298 r->regtime = ast_tvnow();
21299 manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelType: SIP\r\nDomain: %s\r\nStatus: %s\r\n", r->hostname, regstate2str(r->regstate));
21300 r->regattempts = 0;
21301 ast_debug(1, "Registration successful\n");
21302 if (r->timeout > -1) {
21303 ast_debug(1, "Cancelling timeout %d\n", r->timeout);
21304 }
21305 AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 200"));
21306 if (r->call)
21307 r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 200");
21308 p->registry = registry_unref(p->registry, "unref registry entry p->registry");
21309
21310 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21311
21312
21313
21314
21315
21316
21317 expires = 0;
21318
21319
21320 if (!ast_strlen_zero(get_header(req, "Contact"))) {
21321 const char *contact = NULL;
21322 const char *tmptmp = NULL;
21323 int start = 0;
21324 for(;;) {
21325 contact = __get_header(req, "Contact", &start);
21326
21327 if(!ast_strlen_zero(contact)) {
21328 if( (tmptmp=strstr(contact, p->our_contact))) {
21329 contact=tmptmp;
21330 break;
21331 }
21332 } else
21333 break;
21334 }
21335 tmptmp = strcasestr(contact, "expires=");
21336 if (tmptmp) {
21337 if (sscanf(tmptmp + 8, "%30d;", &expires) != 1)
21338 expires = 0;
21339 }
21340
21341 }
21342 if (!expires)
21343 expires=atoi(get_header(req, "expires"));
21344 if (!expires)
21345 expires=default_expiry;
21346
21347 expires_ms = expires * 1000;
21348 if (expires <= EXPIRY_GUARD_LIMIT)
21349 expires_ms -= MAX((expires_ms * EXPIRY_GUARD_PCT), EXPIRY_GUARD_MIN);
21350 else
21351 expires_ms -= EXPIRY_GUARD_SECS * 1000;
21352 if (sipdebug)
21353 ast_log(LOG_NOTICE, "Outbound Registration: Expiry for %s is %d sec (Scheduling reregistration in %d s)\n", r->hostname, expires, expires_ms/1000);
21354
21355 r->refresh= (int) expires_ms / 1000;
21356
21357
21358 AST_SCHED_REPLACE_UNREF(r->expire, sched, expires_ms, sip_reregister, r,
21359 registry_unref(_data,"unref in REPLACE del fail"),
21360 registry_unref(r,"unref in REPLACE add fail"),
21361 registry_addref(r,"The Addition side of REPLACE"));
21362 }
21363 return 1;
21364 }
21365
21366
21367 static void handle_response_peerpoke(struct sip_pvt *p, int resp, struct sip_request *req)
21368 {
21369 struct sip_peer *peer = p->relatedpeer ;
21370 int statechanged, is_reachable, was_reachable;
21371 int pingtime = ast_tvdiff_ms(ast_tvnow(), peer->ps);
21372
21373
21374
21375
21376
21377
21378 if (pingtime < 1) {
21379 pingtime = 1;
21380 }
21381
21382 if (!peer->maxms) {
21383 pvt_set_needdestroy(p, "got OPTIONS response but qualify is not enabled");
21384 return;
21385 }
21386
21387
21388
21389
21390
21391 was_reachable = peer->lastms > 0 && peer->lastms <= peer->maxms;
21392 is_reachable = pingtime <= peer->maxms;
21393 statechanged = peer->lastms == 0
21394 || was_reachable != is_reachable;
21395
21396 peer->lastms = pingtime;
21397 peer->call = dialog_unref(peer->call, "unref dialog peer->call");
21398 if (statechanged) {
21399 const char *s = is_reachable ? "Reachable" : "Lagged";
21400 char str_lastms[20];
21401 snprintf(str_lastms, sizeof(str_lastms), "%d", pingtime);
21402
21403 ast_log(LOG_NOTICE, "Peer '%s' is now %s. (%dms / %dms)\n",
21404 peer->name, s, pingtime, peer->maxms);
21405 ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "SIP/%s", peer->name);
21406 if (sip_cfg.peer_rtupdate) {
21407 ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", str_lastms, SENTINEL);
21408 }
21409 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
21410 "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: %s\r\nTime: %d\r\n",
21411 peer->name, s, pingtime);
21412 if (is_reachable && sip_cfg.regextenonqualify)
21413 register_peer_exten(peer, TRUE);
21414 }
21415
21416 pvt_set_needdestroy(p, "got OPTIONS response");
21417
21418
21419 AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
21420 is_reachable ? peer->qualifyfreq : DEFAULT_FREQ_NOTOK,
21421 sip_poke_peer_s, peer,
21422 unref_peer(_data, "removing poke peer ref"),
21423 unref_peer(peer, "removing poke peer ref"),
21424 ref_peer(peer, "adding poke peer ref"));
21425 }
21426
21427
21428
21429
21430
21431
21432
21433
21434 static void handle_response_info(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
21435 {
21436 int sipmethod = SIP_INFO;
21437
21438 switch (resp) {
21439 case 401:
21440 case 407:
21441 ast_log(LOG_WARNING, "Host '%s' requests authentication (%d) for '%s'\n",
21442 ast_sockaddr_stringify(&p->sa), resp, sip_methods[sipmethod].text);
21443 break;
21444 case 405:
21445 case 501:
21446 mark_method_unallowed(&p->allowed_methods, sipmethod);
21447 if (p->relatedpeer) {
21448 mark_method_allowed(&p->relatedpeer->disallowed_methods, sipmethod);
21449 }
21450 ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n",
21451 ast_sockaddr_stringify(&p->sa), sip_methods[sipmethod].text);
21452 break;
21453 default:
21454 if (300 <= resp && resp < 700) {
21455 ast_verb(3, "Got SIP %s response %d \"%s\" back from host '%s'\n",
21456 sip_methods[sipmethod].text, resp, rest, ast_sockaddr_stringify(&p->sa));
21457 }
21458 break;
21459 }
21460 }
21461
21462
21463
21464
21465
21466
21467
21468
21469
21470 static void handle_response_message(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
21471 {
21472 int sipmethod = SIP_MESSAGE;
21473
21474
21475
21476 switch (resp) {
21477 case 401:
21478 case 407:
21479 ast_log(LOG_WARNING, "Host '%s' requests authentication (%d) for '%s'\n",
21480 ast_sockaddr_stringify(&p->sa), resp, sip_methods[sipmethod].text);
21481 break;
21482 case 405:
21483 case 501:
21484 mark_method_unallowed(&p->allowed_methods, sipmethod);
21485 if (p->relatedpeer) {
21486 mark_method_allowed(&p->relatedpeer->disallowed_methods, sipmethod);
21487 }
21488 ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n",
21489 ast_sockaddr_stringify(&p->sa), sip_methods[sipmethod].text);
21490 break;
21491 default:
21492 if (100 <= resp && resp < 200) {
21493
21494 } else if (200 <= resp && resp < 300) {
21495 p->authtries = 0;
21496 } else if (300 <= resp && resp < 700) {
21497 ast_verb(3, "Got SIP %s response %d \"%s\" back from host '%s'\n",
21498 sip_methods[sipmethod].text, resp, rest, ast_sockaddr_stringify(&p->sa));
21499 }
21500 break;
21501 }
21502 }
21503
21504
21505 static void stop_media_flows(struct sip_pvt *p)
21506 {
21507
21508 if (p->rtp)
21509 ast_rtp_instance_stop(p->rtp);
21510 if (p->vrtp)
21511 ast_rtp_instance_stop(p->vrtp);
21512 if (p->trtp)
21513 ast_rtp_instance_stop(p->trtp);
21514 if (p->udptl)
21515 ast_udptl_stop(p->udptl);
21516 }
21517
21518
21519
21520 static void handle_response(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
21521 {
21522 struct ast_channel *owner;
21523 int sipmethod;
21524 const char *c = get_header(req, "Cseq");
21525
21526 char *c_copy = ast_strdupa(c);
21527
21528 const char *msg = ast_skip_blanks(ast_skip_nonblanks(c_copy));
21529
21530 if (!msg)
21531 msg = "";
21532
21533 sipmethod = find_sip_method(msg);
21534
21535 owner = p->owner;
21536 if (owner) {
21537 const char *rp = NULL, *rh = NULL;
21538
21539 owner->hangupcause = 0;
21540 if (ast_test_flag(&p->flags[1], SIP_PAGE2_Q850_REASON) && (rh = get_header(req, "Reason"))) {
21541 rh = ast_skip_blanks(rh);
21542 if (!strncasecmp(rh, "Q.850", 5)) {
21543 rp = strstr(rh, "cause=");
21544 if (rp && sscanf(rp + 6, "%30d", &owner->hangupcause) == 1) {
21545 owner->hangupcause &= 0x7f;
21546 if (req->debug)
21547 ast_verbose("Using Reason header for cause code: %d\n", owner->hangupcause);
21548 }
21549 }
21550 }
21551
21552 if (!owner->hangupcause)
21553 owner->hangupcause = hangup_sip2cause(resp);
21554 }
21555
21556 if (p->socket.type == SIP_TRANSPORT_UDP) {
21557 int ack_res = FALSE;
21558
21559
21560 if ((resp >= 100) && (resp <= 199)) {
21561
21562 if (sipmethod == SIP_INVITE) {
21563 ack_res = __sip_semi_ack(p, seqno, 0, sipmethod);
21564 }
21565 } else {
21566 ack_res = __sip_ack(p, seqno, 0, sipmethod);
21567 }
21568
21569 if (ack_res == FALSE) {
21570
21571 if (sipmethod == SIP_INVITE && resp >= 200) {
21572 transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, resp < 300 ? TRUE: FALSE);
21573 }
21574
21575 append_history(p, "Ignore", "Ignoring this retransmit\n");
21576 return;
21577 }
21578 }
21579
21580
21581 if (!p->owner && sipmethod == SIP_NOTIFY && p->pendinginvite) {
21582 p->pendinginvite = 0;
21583 }
21584
21585
21586 if (ast_strlen_zero(p->theirtag) || (resp >= 200)) {
21587 char tag[128];
21588
21589 gettag(req, "To", tag, sizeof(tag));
21590 ast_string_field_set(p, theirtag, tag);
21591 }
21592
21593
21594
21595
21596
21597
21598
21599
21600
21601
21602
21603
21604
21605
21606
21607 if ((resp == 404 || resp == 408 || resp == 481) && sipmethod == SIP_BYE) {
21608 pvt_set_needdestroy(p, "received 4XX response to a BYE");
21609 return;
21610 }
21611
21612 if (p->relatedpeer && sipmethod == SIP_OPTIONS) {
21613
21614
21615
21616 if (resp != 100)
21617 handle_response_peerpoke(p, resp, req);
21618 } else if (sipmethod == SIP_REFER && resp >= 200) {
21619 handle_response_refer(p, resp, rest, req, seqno);
21620 } else if (sipmethod == SIP_PUBLISH) {
21621
21622
21623
21624 handle_response_publish(p, resp, rest, req, seqno);
21625 } else if (sipmethod == SIP_INFO) {
21626
21627 handle_response_info(p, resp, rest, req, seqno);
21628 } else if (sipmethod == SIP_MESSAGE) {
21629
21630 handle_response_message(p, resp, rest, req, seqno);
21631 } else if (sipmethod == SIP_NOTIFY) {
21632
21633 handle_response_notify(p, resp, rest, req, seqno);
21634 } else if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
21635 switch(resp) {
21636 case 100:
21637 case 101:
21638 case 183:
21639 case 180:
21640 case 182:
21641 case 181:
21642 if (sipmethod == SIP_INVITE)
21643 handle_response_invite(p, resp, rest, req, seqno);
21644 break;
21645 case 200:
21646 p->authtries = 0;
21647 if (sipmethod == SIP_INVITE) {
21648 handle_response_invite(p, resp, rest, req, seqno);
21649 } else if (sipmethod == SIP_REGISTER) {
21650 handle_response_register(p, resp, rest, req, seqno);
21651 } else if (sipmethod == SIP_SUBSCRIBE) {
21652 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
21653 handle_response_subscribe(p, resp, rest, req, seqno);
21654 } else if (sipmethod == SIP_BYE) {
21655 pvt_set_needdestroy(p, "received 200 response");
21656 ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
21657 }
21658 break;
21659 case 401:
21660 case 407:
21661 if (sipmethod == SIP_INVITE)
21662 handle_response_invite(p, resp, rest, req, seqno);
21663 else if (sipmethod == SIP_SUBSCRIBE)
21664 handle_response_subscribe(p, resp, rest, req, seqno);
21665 else if (p->registry && sipmethod == SIP_REGISTER)
21666 handle_response_register(p, resp, rest, req, seqno);
21667 else if (sipmethod == SIP_UPDATE) {
21668 handle_response_update(p, resp, rest, req, seqno);
21669 } else if (sipmethod == SIP_BYE) {
21670 if (p->options)
21671 p->options->auth_type = resp;
21672 if (ast_strlen_zero(p->authname)) {
21673 ast_log(LOG_WARNING, "Asked to authenticate %s, to %s but we have no matching peer!\n",
21674 msg, ast_sockaddr_stringify(&p->recv));
21675 pvt_set_needdestroy(p, "unable to authenticate BYE");
21676 } else if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp, sipmethod, 0)) {
21677 ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
21678 pvt_set_needdestroy(p, "failed to authenticate BYE");
21679 }
21680 } else {
21681 ast_log(LOG_WARNING, "Got authentication request (%d) on %s to '%s'\n", resp, sip_methods[sipmethod].text, get_header(req, "To"));
21682 pvt_set_needdestroy(p, "received 407 response");
21683 }
21684 break;
21685 case 403:
21686 if (sipmethod == SIP_INVITE)
21687 handle_response_invite(p, resp, rest, req, seqno);
21688 else if (sipmethod == SIP_SUBSCRIBE)
21689 handle_response_subscribe(p, resp, rest, req, seqno);
21690 else if (p->registry && sipmethod == SIP_REGISTER)
21691 handle_response_register(p, resp, rest, req, seqno);
21692 else {
21693 ast_log(LOG_WARNING, "Forbidden - maybe wrong password on authentication for %s\n", msg);
21694 pvt_set_needdestroy(p, "received 403 response");
21695 }
21696 break;
21697 case 404:
21698 if (p->registry && sipmethod == SIP_REGISTER)
21699 handle_response_register(p, resp, rest, req, seqno);
21700 else if (sipmethod == SIP_INVITE)
21701 handle_response_invite(p, resp, rest, req, seqno);
21702 else if (sipmethod == SIP_SUBSCRIBE)
21703 handle_response_subscribe(p, resp, rest, req, seqno);
21704 else if (owner)
21705 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
21706 break;
21707 case 423:
21708 if (sipmethod == SIP_REGISTER)
21709 handle_response_register(p, resp, rest, req, seqno);
21710 break;
21711 case 408:
21712 if (sipmethod == SIP_INVITE)
21713 handle_response_invite(p, resp, rest, req, seqno);
21714 else if (sipmethod == SIP_REGISTER)
21715 handle_response_register(p, resp, rest, req, seqno);
21716 else if (sipmethod == SIP_BYE) {
21717 pvt_set_needdestroy(p, "received 408 response");
21718 ast_debug(4, "Got timeout on bye. Thanks for the answer. Now, kill this call\n");
21719 } else {
21720 if (owner)
21721 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
21722 pvt_set_needdestroy(p, "received 408 response");
21723 }
21724 break;
21725
21726 case 428:
21727 case 422:
21728 if (sipmethod == SIP_INVITE) {
21729 handle_response_invite(p, resp, rest, req, seqno);
21730 }
21731 break;
21732
21733 case 481:
21734 if (sipmethod == SIP_INVITE) {
21735 handle_response_invite(p, resp, rest, req, seqno);
21736 } else if (sipmethod == SIP_SUBSCRIBE) {
21737 handle_response_subscribe(p, resp, rest, req, seqno);
21738 } else if (sipmethod == SIP_BYE) {
21739
21740
21741 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
21742 } else if (sipmethod == SIP_CANCEL) {
21743
21744
21745 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
21746 } else {
21747 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
21748
21749 }
21750 break;
21751 case 487:
21752 if (sipmethod == SIP_INVITE)
21753 handle_response_invite(p, resp, rest, req, seqno);
21754 break;
21755 case 415:
21756 case 488:
21757 case 606:
21758 if (sipmethod == SIP_INVITE)
21759 handle_response_invite(p, resp, rest, req, seqno);
21760 break;
21761 case 491:
21762 if (sipmethod == SIP_INVITE)
21763 handle_response_invite(p, resp, rest, req, seqno);
21764 else {
21765 ast_debug(1, "Got 491 on %s, unsupported. Call ID %s\n", sip_methods[sipmethod].text, p->callid);
21766 pvt_set_needdestroy(p, "received 491 response");
21767 }
21768 break;
21769 case 405:
21770 case 501:
21771 mark_method_unallowed(&p->allowed_methods, sipmethod);
21772 if (p->relatedpeer) {
21773 mark_method_allowed(&p->relatedpeer->disallowed_methods, sipmethod);
21774 }
21775 if (sipmethod == SIP_INVITE)
21776 handle_response_invite(p, resp, rest, req, seqno);
21777 else
21778 ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n", ast_sockaddr_stringify(&p->sa), msg);
21779 break;
21780 default:
21781 if ((resp >= 300) && (resp < 700)) {
21782
21783 if ((resp != 487))
21784 ast_verb(3, "Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_sockaddr_stringify(&p->sa));
21785
21786 if (sipmethod == SIP_INVITE)
21787 stop_media_flows(p);
21788
21789
21790 switch(resp) {
21791 case 300:
21792 case 301:
21793 case 302:
21794 case 305:
21795 if (p->owner) {
21796 struct ast_party_redirecting redirecting;
21797 struct ast_set_party_redirecting update_redirecting;
21798
21799 ast_party_redirecting_init(&redirecting);
21800 memset(&update_redirecting, 0, sizeof(update_redirecting));
21801 change_redirecting_information(p, req, &redirecting,
21802 &update_redirecting, TRUE);
21803 ast_channel_set_redirecting(p->owner, &redirecting,
21804 &update_redirecting);
21805 ast_party_redirecting_free(&redirecting);
21806 }
21807
21808 case 486:
21809 case 600:
21810 case 603:
21811 if (p->owner) {
21812 sip_handle_cc(p, req, AST_CC_CCBS);
21813 ast_queue_control(p->owner, AST_CONTROL_BUSY);
21814 }
21815 break;
21816 case 482:
21817 case 480:
21818 case 404:
21819 case 410:
21820 case 400:
21821 case 500:
21822 if (sipmethod == SIP_SUBSCRIBE) {
21823 handle_response_subscribe(p, resp, rest, req, seqno);
21824 break;
21825 }
21826
21827 case 502:
21828 case 503:
21829 case 504:
21830 if (owner)
21831 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
21832 break;
21833 case 484:
21834 if (owner && sipmethod != SIP_BYE) {
21835 switch (ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP)) {
21836 case SIP_PAGE2_ALLOWOVERLAP_YES:
21837 ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
21838 break;
21839 default:
21840 ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(404));
21841 break;
21842 }
21843 }
21844 break;
21845 default:
21846
21847 if (owner && sipmethod != SIP_BYE)
21848 ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
21849 break;
21850 }
21851
21852 if (sipmethod == SIP_INVITE)
21853 transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
21854 sip_alreadygone(p);
21855 if (!p->owner) {
21856 pvt_set_needdestroy(p, "transaction completed");
21857 }
21858 } else if ((resp >= 100) && (resp < 200)) {
21859 if (sipmethod == SIP_INVITE) {
21860 if (!req->ignore && sip_cancel_destroy(p))
21861 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
21862 if (find_sdp(req))
21863 process_sdp(p, req, SDP_T38_NONE);
21864 if (p->owner) {
21865
21866 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
21867 }
21868 }
21869 } else
21870 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));
21871 }
21872 } else {
21873
21874
21875 if (req->debug)
21876 ast_verbose("SIP Response message for INCOMING dialog %s arrived\n", msg);
21877
21878 if (sipmethod == SIP_INVITE && resp == 200) {
21879
21880
21881 char tag[128];
21882
21883 gettag(req, "To", tag, sizeof(tag));
21884 ast_string_field_set(p, theirtag, tag);
21885 }
21886
21887 switch(resp) {
21888 case 200:
21889 if (sipmethod == SIP_INVITE) {
21890 handle_response_invite(p, resp, rest, req, seqno);
21891 } else if (sipmethod == SIP_CANCEL) {
21892 ast_debug(1, "Got 200 OK on CANCEL\n");
21893
21894
21895 } else if (sipmethod == SIP_BYE) {
21896 pvt_set_needdestroy(p, "transaction completed");
21897 }
21898 break;
21899 case 401:
21900 case 407:
21901 if (sipmethod == SIP_INVITE)
21902 handle_response_invite(p, resp, rest, req, seqno);
21903 else if (sipmethod == SIP_BYE) {
21904 if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, sipmethod, 0)) {
21905 ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
21906 pvt_set_needdestroy(p, "failed to authenticate BYE");
21907 }
21908 }
21909 break;
21910 case 481:
21911 if (sipmethod == SIP_INVITE) {
21912
21913 handle_response_invite(p, resp, rest, req, seqno);
21914 } else if (sipmethod == SIP_BYE) {
21915 pvt_set_needdestroy(p, "received 481 response");
21916 } else if (sipdebug) {
21917 ast_debug(1, "Remote host can't match request %s to call '%s'. Giving up\n", sip_methods[sipmethod].text, p->callid);
21918 }
21919 break;
21920 case 501:
21921 if (sipmethod == SIP_INVITE)
21922 handle_response_invite(p, resp, rest, req, seqno);
21923 break;
21924 default:
21925 if ((resp >= 100) && (resp < 200)) {
21926 if (sipmethod == SIP_INVITE) {
21927 if (!req->ignore && sip_cancel_destroy(p))
21928 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
21929 }
21930 }
21931 if ((resp >= 300) && (resp < 700)) {
21932 if ((resp != 487))
21933 ast_verb(3, "Incoming call: Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_sockaddr_stringify(&p->sa));
21934 switch(resp) {
21935 case 415:
21936 case 488:
21937 case 603:
21938 case 500:
21939 case 502:
21940 case 503:
21941 case 504:
21942
21943
21944 if (sipmethod == SIP_INVITE && sip_cancel_destroy(p))
21945 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
21946 break;
21947 }
21948 }
21949 break;
21950 }
21951 }
21952 }
21953
21954
21955
21956
21957
21958
21959
21960 static void *sip_park_thread(void *stuff)
21961 {
21962 struct ast_channel *transferee, *transferer;
21963 struct sip_dual *d;
21964 int ext;
21965 int res;
21966
21967 d = stuff;
21968 transferee = d->chan1;
21969 transferer = d->chan2;
21970
21971 ast_debug(4, "SIP Park: Transferer channel %s, Transferee %s\n", transferer->name, transferee->name);
21972
21973 res = ast_park_call_exten(transferee, transferer, d->park_exten, d->park_context, 0, &ext);
21974
21975 #ifdef WHEN_WE_KNOW_THAT_THE_CLIENT_SUPPORTS_MESSAGE
21976 if (res) {
21977 transmit_message_with_text(transferer->tech_pvt, "Unable to park call.\n");
21978 } else {
21979
21980 sprintf(buf, "Call parked on extension '%d'", ext);
21981 transmit_message_with_text(transferer->tech_pvt, buf);
21982 }
21983 #endif
21984
21985
21986
21987 if (!res) {
21988
21989 append_history(transferer->tech_pvt, "SIPpark", "Parked call on %d", ext);
21990 transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "200 OK", TRUE);
21991 transferer->hangupcause = AST_CAUSE_NORMAL_CLEARING;
21992 ast_hangup(transferer);
21993 ast_debug(1, "SIP Call parked on extension '%d'\n", ext);
21994 } else {
21995 transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "503 Service Unavailable", TRUE);
21996 append_history(transferer->tech_pvt, "SIPpark", "Parking failed\n");
21997 ast_debug(1, "SIP Call parked failed \n");
21998
21999 }
22000 deinit_req(&d->req);
22001 ast_free(d->park_exten);
22002 ast_free(d->park_context);
22003 ast_free(d);
22004 return NULL;
22005 }
22006
22007
22008 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)
22009 {
22010 struct sip_dual *d;
22011 struct ast_channel *transferee, *transferer;
22012 pthread_t th;
22013
22014 transferee = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan1->accountcode, chan1->exten, chan1->context, chan1->linkedid, chan1->amaflags, "Parking/%s", chan1->name);
22015 transferer = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan2->accountcode, chan2->exten, chan2->context, chan2->linkedid, chan2->amaflags, "SIPPeer/%s", chan2->name);
22016 d = ast_calloc(1, sizeof(*d));
22017 if (!transferee || !transferer || !d) {
22018 if (transferee) {
22019 ast_hangup(transferee);
22020 }
22021 if (transferer) {
22022 ast_hangup(transferer);
22023 }
22024 ast_free(d);
22025 return -1;
22026 }
22027 d->park_exten = ast_strdup(park_exten);
22028 d->park_context = ast_strdup(park_context);
22029 if (!d->park_exten || !d->park_context) {
22030 ast_hangup(transferee);
22031 ast_hangup(transferer);
22032 ast_free(d->park_exten);
22033 ast_free(d->park_context);
22034 ast_free(d);
22035 return -1;
22036 }
22037
22038
22039 transferee->readformat = chan1->readformat;
22040 transferee->writeformat = chan1->writeformat;
22041
22042
22043 if (ast_channel_masquerade(transferee, chan1)) {
22044 ast_hangup(transferee);
22045 ast_hangup(transferer);
22046 ast_free(d->park_exten);
22047 ast_free(d->park_context);
22048 ast_free(d);
22049 return -1;
22050 }
22051
22052
22053 ast_copy_string(transferee->context, chan1->context, sizeof(transferee->context));
22054 ast_copy_string(transferee->exten, chan1->exten, sizeof(transferee->exten));
22055 transferee->priority = chan1->priority;
22056
22057 ast_do_masquerade(transferee);
22058
22059
22060
22061
22062
22063 transferer->readformat = chan2->readformat;
22064 transferer->writeformat = chan2->writeformat;
22065 ast_string_field_set(transferer, parkinglot, chan2->parkinglot);
22066
22067
22068 if (ast_channel_masquerade(transferer, chan2)) {
22069 ast_hangup(transferer);
22070 ast_free(d->park_exten);
22071 ast_free(d->park_context);
22072 ast_free(d);
22073 return -1;
22074 }
22075
22076
22077 ast_copy_string(transferer->context, chan2->context, sizeof(transferer->context));
22078 ast_copy_string(transferer->exten, chan2->exten, sizeof(transferer->exten));
22079 transferer->priority = chan2->priority;
22080
22081 ast_do_masquerade(transferer);
22082
22083
22084 copy_request(&d->req, req);
22085 d->chan1 = transferee;
22086 d->chan2 = transferer;
22087 d->seqno = seqno;
22088 if (ast_pthread_create_detached_background(&th, NULL, sip_park_thread, d) < 0) {
22089
22090 deinit_req(&d->req);
22091 ast_free(d->park_exten);
22092 ast_free(d->park_context);
22093 ast_free(d);
22094
22095 return -1;
22096 }
22097 return 0;
22098 }
22099
22100
22101
22102
22103
22104 static void *sip_pickup_thread(void *stuff)
22105 {
22106 struct ast_channel *chan;
22107 chan = stuff;
22108
22109 if (ast_pickup_call(chan)) {
22110 chan->hangupcause = AST_CAUSE_CALL_REJECTED;
22111 } else {
22112 chan->hangupcause = AST_CAUSE_NORMAL_CLEARING;
22113 }
22114 ast_hangup(chan);
22115 ast_channel_unref(chan);
22116 chan = NULL;
22117 return NULL;
22118 }
22119
22120
22121
22122
22123 static int sip_pickup(struct ast_channel *chan)
22124 {
22125 pthread_t threadid;
22126
22127 ast_channel_ref(chan);
22128
22129 if (ast_pthread_create_detached_background(&threadid, NULL, sip_pickup_thread, chan)) {
22130 ast_debug(1, "Unable to start Group pickup thread on channel %s\n", chan->name);
22131 ast_channel_unref(chan);
22132 return -1;
22133 }
22134 ast_debug(1, "Started Group pickup thread on channel %s\n", chan->name);
22135 return 0;
22136 }
22137
22138
22139
22140
22141
22142 static void ast_quiet_chan(struct ast_channel *chan)
22143 {
22144 if (chan && chan->_state == AST_STATE_UP) {
22145 if (ast_test_flag(chan, AST_FLAG_MOH))
22146 ast_moh_stop(chan);
22147 else if (chan->generatordata)
22148 ast_deactivate_generator(chan);
22149 }
22150 }
22151
22152
22153
22154 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target)
22155 {
22156 int res = 0;
22157 struct ast_channel *peera = NULL,
22158 *peerb = NULL,
22159 *peerc = NULL,
22160 *peerd = NULL;
22161
22162
22163
22164
22165 ast_debug(4, "Sip transfer:--------------------\n");
22166 if (transferer->chan1)
22167 ast_debug(4, "-- Transferer to PBX channel: %s State %s\n", transferer->chan1->name, ast_state2str(transferer->chan1->_state));
22168 else
22169 ast_debug(4, "-- No transferer first channel - odd??? \n");
22170 if (target->chan1)
22171 ast_debug(4, "-- Transferer to PBX second channel (target): %s State %s\n", target->chan1->name, ast_state2str(target->chan1->_state));
22172 else
22173 ast_debug(4, "-- No target first channel ---\n");
22174 if (transferer->chan2)
22175 ast_debug(4, "-- Bridged call to transferee: %s State %s\n", transferer->chan2->name, ast_state2str(transferer->chan2->_state));
22176 else
22177 ast_debug(4, "-- No bridged call to transferee\n");
22178 if (target->chan2)
22179 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)");
22180 else
22181 ast_debug(4, "-- No target second channel ---\n");
22182 ast_debug(4, "-- END Sip transfer:--------------------\n");
22183 if (transferer->chan2) {
22184 peera = transferer->chan1;
22185 peerb = target->chan1;
22186 peerc = transferer->chan2;
22187 peerd = target->chan2;
22188 ast_debug(3, "SIP transfer: Four channels to handle\n");
22189 } else if (target->chan2) {
22190 peera = target->chan1;
22191 peerb = transferer->chan1;
22192 peerc = target->chan2;
22193 peerd = transferer->chan2;
22194 ast_debug(3, "SIP transfer: Three channels to handle\n");
22195 }
22196
22197 if (peera && peerb && peerc && (peerb != peerc)) {
22198 ast_quiet_chan(peera);
22199 ast_quiet_chan(peerb);
22200 ast_quiet_chan(peerc);
22201 if (peerd)
22202 ast_quiet_chan(peerd);
22203
22204 ast_debug(4, "SIP transfer: trying to masquerade %s into %s\n", peerc->name, peerb->name);
22205 if (ast_channel_masquerade(peerb, peerc)) {
22206 ast_log(LOG_WARNING, "Failed to masquerade %s into %s\n", peerb->name, peerc->name);
22207 res = -1;
22208 } else
22209 ast_debug(4, "SIP transfer: Succeeded to masquerade channels.\n");
22210 return res;
22211 } else {
22212 ast_log(LOG_NOTICE, "SIP Transfer attempted with no appropriate bridged calls to transfer\n");
22213 if (transferer->chan1)
22214 ast_softhangup_nolock(transferer->chan1, AST_SOFTHANGUP_DEV);
22215 if (target->chan1)
22216 ast_softhangup_nolock(target->chan1, AST_SOFTHANGUP_DEV);
22217 return -1;
22218 }
22219 return 0;
22220 }
22221
22222
22223
22224
22225
22226
22227 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize)
22228 {
22229 const char *thetag;
22230
22231 if (!tagbuf)
22232 return NULL;
22233 tagbuf[0] = '\0';
22234 thetag = get_header(req, header);
22235 thetag = strcasestr(thetag, ";tag=");
22236 if (thetag) {
22237 thetag += 5;
22238 ast_copy_string(tagbuf, thetag, tagbufsize);
22239 return strsep(&tagbuf, ";");
22240 }
22241 return NULL;
22242 }
22243
22244 static int handle_cc_notify(struct sip_pvt *pvt, struct sip_request *req)
22245 {
22246 struct sip_monitor_instance *monitor_instance = ao2_callback(sip_monitor_instances, 0,
22247 find_sip_monitor_instance_by_subscription_pvt, pvt);
22248 const char *status = get_body(req, "cc-state", ':');
22249 struct cc_epa_entry *cc_entry;
22250 char *uri;
22251
22252 if (!monitor_instance) {
22253 transmit_response(pvt, "400 Bad Request", req);
22254 return -1;
22255 }
22256
22257 if (ast_strlen_zero(status)) {
22258 ao2_ref(monitor_instance, -1);
22259 transmit_response(pvt, "400 Bad Request", req);
22260 return -1;
22261 }
22262
22263 if (!strcmp(status, "queued")) {
22264
22265
22266
22267
22268 ast_cc_monitor_request_acked(monitor_instance->core_id, "SIP endpoint %s accepted request", monitor_instance->device_name);
22269 transmit_response(pvt, "200 OK", req);
22270 ao2_ref(monitor_instance, -1);
22271 return 0;
22272 }
22273
22274
22275 uri = get_body(req, "cc-URI", ':');
22276 if (ast_strlen_zero(uri)) {
22277 uri = get_in_brackets((char *)get_header(req, "From"));
22278 }
22279
22280 ast_string_field_set(monitor_instance, notify_uri, uri);
22281 if (monitor_instance->suspension_entry) {
22282 cc_entry = monitor_instance->suspension_entry->instance_data;
22283 if (cc_entry->current_state == CC_CLOSED) {
22284
22285
22286
22287
22288
22289 construct_pidf_body(CC_CLOSED, monitor_instance->suspension_entry->body,
22290 sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
22291 transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_INITIAL, monitor_instance->notify_uri);
22292 } else {
22293 ast_cc_monitor_callee_available(monitor_instance->core_id, "SIP monitored callee has become available");
22294 }
22295 } else {
22296 ast_cc_monitor_callee_available(monitor_instance->core_id, "SIP monitored callee has become available");
22297 }
22298 ao2_ref(monitor_instance, -1);
22299 transmit_response(pvt, "200 OK", req);
22300
22301 return 0;
22302 }
22303
22304
22305 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e)
22306 {
22307
22308
22309 int res = 0;
22310 const char *event = get_header(req, "Event");
22311 char *sep;
22312
22313 if( (sep = strchr(event, ';')) ) {
22314 *sep++ = '\0';
22315 }
22316
22317 if (sipdebug)
22318 ast_debug(2, "Got NOTIFY Event: %s\n", event);
22319
22320 if (!strcmp(event, "refer")) {
22321
22322
22323
22324
22325
22326 char buf[1024];
22327 char *cmd, *code;
22328 int respcode;
22329 int success = TRUE;
22330
22331
22332
22333
22334
22335
22336
22337
22338 if (strncasecmp(get_header(req, "Content-Type"), "message/sipfrag", strlen("message/sipfrag"))) {
22339
22340 transmit_response(p, "400 Bad request", req);
22341 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22342 return -1;
22343 }
22344
22345
22346 if (get_msg_text(buf, sizeof(buf), req)) {
22347 ast_log(LOG_WARNING, "Unable to retrieve attachment from NOTIFY %s\n", p->callid);
22348 transmit_response(p, "400 Bad request", req);
22349 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22350 return -1;
22351 }
22352
22353
22354
22355
22356
22357
22358
22359
22360
22361
22362
22363
22364
22365
22366
22367
22368
22369
22370
22371
22372
22373 ast_debug(3, "* SIP Transfer NOTIFY Attachment: \n---%s\n---\n", buf);
22374 cmd = ast_skip_blanks(buf);
22375 code = cmd;
22376
22377 while(*code && (*code > 32)) {
22378 code++;
22379 }
22380 *code++ = '\0';
22381 code = ast_skip_blanks(code);
22382 sep = code;
22383 sep++;
22384 while(*sep && (*sep > 32)) {
22385 sep++;
22386 }
22387 *sep++ = '\0';
22388 respcode = atoi(code);
22389 switch (respcode) {
22390 case 200:
22391
22392 break;
22393 case 301:
22394 case 302:
22395
22396 success = FALSE;
22397 break;
22398 case 503:
22399 case 603:
22400
22401 success = FALSE;
22402 break;
22403 case 0:
22404
22405 ast_log(LOG_NOTICE, "Error parsing sipfrag in NOTIFY in response to REFER.\n");
22406 success = FALSE;
22407 break;
22408 default:
22409 if (respcode < 200) {
22410
22411 success = -1;
22412 } else {
22413 ast_log(LOG_NOTICE, "Got unknown code '%d' in NOTIFY in response to REFER.\n", respcode);
22414 success = FALSE;
22415 }
22416 break;
22417 }
22418 if (success == FALSE) {
22419 ast_log(LOG_NOTICE, "Transfer failed. Sorry. Nothing further to do with this call\n");
22420 }
22421
22422 if (p->owner && success != -1) {
22423 enum ast_control_transfer message = success ? AST_TRANSFER_SUCCESS : AST_TRANSFER_FAILED;
22424 ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
22425 }
22426
22427 transmit_response(p, "200 OK", req);
22428 } else if (!strcmp(event, "message-summary")) {
22429 const char *mailbox = NULL;
22430 char *c = ast_strdupa(get_body(req, "Voice-Message", ':'));
22431
22432 if (!p->mwi) {
22433 struct sip_peer *peer = find_peer(NULL, &p->recv, TRUE, FINDPEERS, FALSE, p->socket.type);
22434
22435 if (peer) {
22436 mailbox = ast_strdupa(peer->unsolicited_mailbox);
22437 unref_peer(peer, "removing unsolicited mwi ref");
22438 }
22439 } else {
22440 mailbox = p->mwi->mailbox;
22441 }
22442
22443 if (!ast_strlen_zero(mailbox) && !ast_strlen_zero(c)) {
22444 char *old = strsep(&c, " ");
22445 char *new = strsep(&old, "/");
22446 struct ast_event *event;
22447
22448 if ((event = ast_event_new(AST_EVENT_MWI,
22449 AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox,
22450 AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, "SIP_Remote",
22451 AST_EVENT_IE_NEWMSGS, AST_EVENT_IE_PLTYPE_UINT, atoi(new),
22452 AST_EVENT_IE_OLDMSGS, AST_EVENT_IE_PLTYPE_UINT, atoi(old),
22453 AST_EVENT_IE_END))) {
22454 ast_event_queue_and_cache(event);
22455 }
22456 transmit_response(p, "200 OK", req);
22457 } else {
22458 transmit_response(p, "489 Bad event", req);
22459 res = -1;
22460 }
22461 } else if (!strcmp(event, "keep-alive")) {
22462
22463
22464 transmit_response(p, "200 OK", req);
22465 } else if (!strcmp(event, "call-completion")) {
22466 res = handle_cc_notify(p, req);
22467 } else {
22468
22469 transmit_response(p, "489 Bad event", req);
22470 res = -1;
22471 }
22472
22473 if (!p->lastinvite)
22474 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22475
22476 return res;
22477 }
22478
22479
22480
22481
22482 static int handle_request_options(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e)
22483 {
22484 const char *msg;
22485 enum sip_get_dest_result gotdest;
22486 int res;
22487
22488 if (p->lastinvite) {
22489
22490 transmit_response_with_allow(p, "200 OK", req, 0);
22491 return 0;
22492 }
22493
22494 if (sip_cfg.auth_options_requests) {
22495
22496 copy_request(&p->initreq, req);
22497 set_pvt_allowed_methods(p, req);
22498 res = check_user(p, req, SIP_OPTIONS, e, XMIT_UNRELIABLE, addr);
22499 if (res == AUTH_CHALLENGE_SENT) {
22500 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22501 return 0;
22502 }
22503 if (res < 0) {
22504 if (res == AUTH_FAKE_AUTH) {
22505 ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", get_header(req, "From"));
22506 transmit_fake_auth_response(p, SIP_OPTIONS, req, XMIT_UNRELIABLE);
22507 } else {
22508 ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", get_header(req, "From"));
22509 transmit_response(p, "403 Forbidden", req);
22510 }
22511 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22512 return 0;
22513 }
22514 }
22515
22516
22517 gotdest = get_destination(p, req, NULL);
22518 build_contact(p);
22519
22520 if (ast_strlen_zero(p->context))
22521 ast_string_field_set(p, context, sip_cfg.default_context);
22522
22523 if (ast_shutting_down()) {
22524 msg = "503 Unavailable";
22525 } else {
22526 msg = "404 Not Found";
22527 switch (gotdest) {
22528 case SIP_GET_DEST_INVALID_URI:
22529 msg = "416 Unsupported URI scheme";
22530 break;
22531 case SIP_GET_DEST_EXTEN_MATCHMORE:
22532 case SIP_GET_DEST_REFUSED:
22533 case SIP_GET_DEST_EXTEN_NOT_FOUND:
22534
22535 break;
22536 case SIP_GET_DEST_EXTEN_FOUND:
22537 msg = "200 OK";
22538 break;
22539 }
22540 }
22541 transmit_response_with_allow(p, msg, req, 0);
22542
22543
22544
22545 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22546
22547 return 0;
22548 }
22549
22550
22551
22552
22553
22554
22555
22556
22557
22558
22559
22560
22561
22562 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, uint32_t seqno, struct ast_sockaddr *addr, int *nounlock)
22563 {
22564 int earlyreplace = 0;
22565 int oneleggedreplace = 0;
22566 struct ast_channel *c = p->owner;
22567 struct ast_channel *replacecall = p->refer->refer_call->owner;
22568 struct ast_channel *targetcall;
22569
22570
22571 if (replacecall->_state == AST_STATE_RING)
22572 earlyreplace = 1;
22573
22574
22575 if (!(targetcall = ast_bridged_channel(replacecall))) {
22576
22577 if (!earlyreplace) {
22578 ast_debug(2, " Attended transfer attempted to replace call with no bridge (maybe ringing). Channel %s!\n", replacecall->name);
22579 oneleggedreplace = 1;
22580 }
22581 }
22582 if (targetcall && targetcall->_state == AST_STATE_RINGING)
22583 ast_debug(4, "SIP transfer: Target channel is in ringing state\n");
22584
22585 if (targetcall)
22586 ast_debug(4, "SIP transfer: Invite Replace incoming channel should bridge to channel %s while hanging up channel %s\n", targetcall->name, replacecall->name);
22587 else
22588 ast_debug(4, "SIP transfer: Invite Replace incoming channel should replace and hang up channel %s (one call leg)\n", replacecall->name);
22589
22590 if (req->ignore) {
22591 ast_log(LOG_NOTICE, "Ignoring this INVITE with replaces in a stupid way.\n");
22592
22593
22594
22595 transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE, FALSE);
22596
22597 if (c) {
22598 *nounlock = 1;
22599 ast_channel_unlock(c);
22600 }
22601 ast_channel_unlock(replacecall);
22602 sip_pvt_unlock(p->refer->refer_call);
22603 return 1;
22604 }
22605 if (!c) {
22606
22607 ast_log(LOG_ERROR, "Unable to create new channel. Invite/replace failed.\n");
22608 transmit_response_reliable(p, "503 Service Unavailable", req);
22609 append_history(p, "Xfer", "INVITE/Replace Failed. No new channel.");
22610 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22611 ast_channel_unlock(replacecall);
22612 sip_pvt_unlock(p->refer->refer_call);
22613 return 1;
22614 }
22615 append_history(p, "Xfer", "INVITE/Replace received");
22616
22617
22618
22619
22620
22621
22622
22623
22624
22625
22626
22627 transmit_response(p, "100 Trying", req);
22628 ast_setstate(c, AST_STATE_RING);
22629
22630
22631
22632
22633
22634 transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE, FALSE);
22635
22636 ast_setstate(c, AST_STATE_UP);
22637
22638
22639 ast_quiet_chan(replacecall);
22640 ast_quiet_chan(targetcall);
22641 ast_debug(4, "Invite/Replaces: preparing to masquerade %s into %s\n", c->name, replacecall->name);
22642
22643
22644 if (! earlyreplace && ! oneleggedreplace )
22645 ast_set_flag(&p->refer->refer_call->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
22646
22647
22648 if(ast_channel_masquerade(replacecall, c))
22649 ast_log(LOG_ERROR, "Failed to masquerade C into Replacecall\n");
22650 else
22651 ast_debug(4, "Invite/Replaces: Going to masquerade %s into %s\n", c->name, replacecall->name);
22652
22653
22654
22655
22656
22657 ast_channel_ref(c);
22658 ast_channel_unlock(replacecall);
22659 ast_channel_unlock(c);
22660 sip_pvt_unlock(p->refer->refer_call);
22661 sip_pvt_unlock(p);
22662 if (ast_do_masquerade(replacecall)) {
22663 ast_log(LOG_WARNING, "Failed to perform masquerade with INVITE replaces\n");
22664 }
22665 ast_channel_lock(c);
22666 if (earlyreplace || oneleggedreplace ) {
22667 c->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
22668 }
22669 ast_setstate(c, AST_STATE_DOWN);
22670 ast_channel_unlock(c);
22671
22672
22673 c->tech_pvt = dialog_unref(c->tech_pvt, "unref dialog c->tech_pvt");
22674
22675
22676 ast_hangup(c);
22677
22678 *nounlock = 1;
22679
22680 sip_pvt_lock(p);
22681 ast_channel_unref(c);
22682 return 0;
22683 }
22684
22685
22686 static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context)
22687 {
22688 struct ast_str *str = ast_str_alloca(AST_MAX_EXTENSION + AST_MAX_CONTEXT + 2);
22689 struct ast_app *pickup = pbx_findapp("Pickup");
22690
22691 if (!pickup) {
22692 ast_log(LOG_ERROR, "Unable to perform pickup: Application 'Pickup' not loaded (app_directed_pickup.so).\n");
22693 return -1;
22694 }
22695
22696 ast_str_set(&str, 0, "%s@%s", extension, sip_cfg.notifycid == IGNORE_CONTEXT ? "PICKUPMARK" : context);
22697
22698 ast_debug(2, "About to call Pickup(%s)\n", ast_str_buffer(str));
22699
22700
22701
22702
22703 pbx_exec(channel, pickup, ast_str_buffer(str));
22704
22705 return 0;
22706 }
22707
22708
22709 static int sip_t38_abort(const void *data)
22710 {
22711 struct sip_pvt *p = (struct sip_pvt *) data;
22712
22713 sip_pvt_lock(p);
22714
22715
22716
22717
22718
22719 if (p->t38id != -1) {
22720 change_t38_state(p, T38_DISABLED);
22721 transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
22722 p->t38id = -1;
22723 dialog_unref(p, "unref the dialog ptr from sip_t38_abort, because it held a dialog ptr");
22724 }
22725 sip_pvt_unlock(p);
22726 return 0;
22727 }
22728
22729
22730
22731
22732
22733
22734
22735
22736
22737
22738
22739
22740 static int handle_request_update(struct sip_pvt *p, struct sip_request *req)
22741 {
22742 if (ast_strlen_zero(get_header(req, "X-Asterisk-rpid-update"))) {
22743 transmit_response(p, "501 Method Not Implemented", req);
22744 return 0;
22745 }
22746 if (!p->owner) {
22747 transmit_response(p, "481 Call/Transaction Does Not Exist", req);
22748 return 0;
22749 }
22750 if (get_rpid(p, req)) {
22751 struct ast_party_connected_line connected;
22752 struct ast_set_party_connected_line update_connected;
22753
22754 ast_party_connected_line_init(&connected);
22755 memset(&update_connected, 0, sizeof(update_connected));
22756
22757 update_connected.id.number = 1;
22758 connected.id.number.valid = 1;
22759 connected.id.number.str = (char *) p->cid_num;
22760 connected.id.number.presentation = p->callingpres;
22761
22762 update_connected.id.name = 1;
22763 connected.id.name.valid = 1;
22764 connected.id.name.str = (char *) p->cid_name;
22765 connected.id.name.presentation = p->callingpres;
22766
22767 connected.id.tag = (char *) p->cid_tag;
22768 connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
22769 ast_channel_queue_connected_line_update(p->owner, &connected, &update_connected);
22770 }
22771 transmit_response(p, "200 OK", req);
22772 return 0;
22773 }
22774
22775
22776
22777
22778
22779
22780
22781
22782 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)
22783 {
22784 int res = 1;
22785 int gotdest;
22786 const char *p_replaces;
22787 char *replace_id = NULL;
22788 int refer_locked = 0;
22789 const char *required;
22790 unsigned int required_profile = 0;
22791 struct ast_channel *c = NULL;
22792 struct sip_peer *authpeer = NULL;
22793 int reinvite = 0;
22794 int rtn;
22795 struct ast_party_redirecting redirecting;
22796 struct ast_set_party_redirecting update_redirecting;
22797
22798 const char *p_uac_se_hdr;
22799 const char *p_uac_min_se;
22800 int uac_max_se = -1;
22801 int uac_min_se = -1;
22802 int st_active = FALSE;
22803 int st_interval = 0;
22804 enum st_refresher tmp_st_ref = SESSION_TIMER_REFRESHER_AUTO;
22805 int dlg_min_se = -1;
22806 struct {
22807 char exten[AST_MAX_EXTENSION];
22808 char context[AST_MAX_CONTEXT];
22809 } pickup = {
22810 .exten = "",
22811 };
22812
22813
22814 if (!p->sipoptions) {
22815 const char *supported = get_header(req, "Supported");
22816 if (!ast_strlen_zero(supported)) {
22817 p->sipoptions = parse_sip_options(supported, NULL, 0);
22818 }
22819 }
22820
22821
22822 required = get_header(req, "Require");
22823 if (!ast_strlen_zero(required)) {
22824 char unsupported[256] = { 0, };
22825 required_profile = parse_sip_options(required, unsupported, ARRAY_LEN(unsupported));
22826
22827
22828
22829 if (!ast_strlen_zero(unsupported)) {
22830 transmit_response_with_unsupported(p, "420 Bad extension (unsupported)", req, unsupported);
22831 ast_log(LOG_WARNING, "Received SIP INVITE with unsupported required extension: required:%s unsupported:%s\n", required, unsupported);
22832 p->invitestate = INV_COMPLETED;
22833 if (!p->lastinvite)
22834 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22835 res = -1;
22836 goto request_invite_cleanup;
22837 }
22838 }
22839
22840
22841
22842 p->sipoptions |= required_profile;
22843 p->reqsipoptions = required_profile;
22844
22845
22846 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) {
22847
22848
22849
22850
22851
22852 int different;
22853 const char *initial_rlPart2 = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
22854 const char *this_rlPart2 = REQ_OFFSET_TO_STR(req, rlPart2);
22855 if (sip_cfg.pedanticsipchecking)
22856 different = sip_uri_cmp(initial_rlPart2, this_rlPart2);
22857 else
22858 different = strcmp(initial_rlPart2, this_rlPart2);
22859 if (!different) {
22860 transmit_response(p, "482 Loop Detected", req);
22861 p->invitestate = INV_COMPLETED;
22862 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22863 res = 0;
22864 goto request_invite_cleanup;
22865 } else {
22866
22867
22868
22869
22870
22871
22872
22873 char *uri = ast_strdupa(this_rlPart2);
22874 char *at = strchr(uri, '@');
22875 char *peerorhost;
22876 ast_debug(2, "Potential spiral detected. Original RURI was %s, new RURI is %s\n", initial_rlPart2, this_rlPart2);
22877 transmit_response(p, "100 Trying", req);
22878 if (at) {
22879 *at = '\0';
22880 }
22881
22882 if ((peerorhost = strchr(uri, ':'))) {
22883 *peerorhost++ = '\0';
22884 }
22885 ast_string_field_set(p, theirtag, NULL);
22886
22887
22888 ast_string_field_set(p->owner, call_forward, peerorhost);
22889 ast_queue_control(p->owner, AST_CONTROL_BUSY);
22890 res = 0;
22891 goto request_invite_cleanup;
22892 }
22893 }
22894
22895 if (!req->ignore && p->pendinginvite) {
22896 if (!ast_test_flag(&p->flags[0], SIP_OUTGOING) && (p->invitestate == INV_COMPLETED || p->invitestate == INV_TERMINATED)) {
22897
22898
22899
22900
22901
22902
22903
22904
22905
22906
22907 __sip_ack(p, p->pendinginvite, 1, 0);
22908 } else {
22909
22910 p->glareinvite = seqno;
22911 if (p->rtp && find_sdp(req)) {
22912 struct ast_sockaddr addr;
22913 if (get_ip_and_port_from_sdp(req, SDP_AUDIO, &addr)) {
22914 ast_log(LOG_WARNING, "Failed to set an alternate media source on glared reinvite. Audio may not work properly on this call.\n");
22915 } else {
22916 ast_rtp_instance_set_alt_remote_address(p->rtp, &addr);
22917 }
22918 if (p->vrtp) {
22919 if (get_ip_and_port_from_sdp(req, SDP_VIDEO, &addr)) {
22920 ast_log(LOG_WARNING, "Failed to set an alternate media source on glared reinvite. Video may not work properly on this call.\n");
22921 } else {
22922 ast_rtp_instance_set_alt_remote_address(p->vrtp, &addr);
22923 }
22924 }
22925 }
22926 transmit_response_reliable(p, "491 Request Pending", req);
22927 check_via(p, req);
22928 ast_debug(1, "Got INVITE on call where we already have pending INVITE, deferring that - %s\n", p->callid);
22929
22930 res = 0;
22931 goto request_invite_cleanup;
22932 }
22933 }
22934
22935 p_replaces = get_header(req, "Replaces");
22936 if (!ast_strlen_zero(p_replaces)) {
22937
22938 char *ptr;
22939 char *fromtag = NULL;
22940 char *totag = NULL;
22941 char *start, *to;
22942 int error = 0;
22943
22944 if (p->owner) {
22945 ast_debug(3, "INVITE w Replaces on existing call? Refusing action. [%s]\n", p->callid);
22946 transmit_response_reliable(p, "400 Bad request", req);
22947 check_via(p, req);
22948 copy_request(&p->initreq, req);
22949
22950 res = -1;
22951 goto request_invite_cleanup;
22952 }
22953
22954 if (sipdebug)
22955 ast_debug(3, "INVITE part of call transfer. Replaces [%s]\n", p_replaces);
22956
22957 replace_id = ast_strdupa(p_replaces);
22958 ast_uri_decode(replace_id);
22959
22960 if (!p->refer && !sip_refer_allocate(p)) {
22961 transmit_response_reliable(p, "500 Server Internal Error", req);
22962 append_history(p, "Xfer", "INVITE/Replace Failed. Out of memory.");
22963 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22964 p->invitestate = INV_COMPLETED;
22965 check_via(p, req);
22966 copy_request(&p->initreq, req);
22967 res = -1;
22968 goto request_invite_cleanup;
22969 }
22970
22971
22972
22973
22974
22975
22976
22977
22978
22979
22980 replace_id = ast_skip_blanks(replace_id);
22981
22982 start = replace_id;
22983 while ( (ptr = strsep(&start, ";")) ) {
22984 ptr = ast_skip_blanks(ptr);
22985 if ( (to = strcasestr(ptr, "to-tag=") ) )
22986 totag = to + 7;
22987 else if ( (to = strcasestr(ptr, "from-tag=") ) ) {
22988 fromtag = to + 9;
22989 fromtag = strsep(&fromtag, "&");
22990 }
22991 }
22992
22993 if (sipdebug)
22994 ast_debug(4, "Invite/replaces: Will use Replace-Call-ID : %s Fromtag: %s Totag: %s\n",
22995 replace_id,
22996 fromtag ? fromtag : "<no from tag>",
22997 totag ? totag : "<no to tag>");
22998
22999
23000
23001
23002
23003 if (strncmp(replace_id, "pickup-", 7) == 0) {
23004 struct sip_pvt *subscription = NULL;
23005 replace_id += 7;
23006
23007 if ((subscription = get_sip_pvt_byid_locked(replace_id, totag, fromtag)) == NULL) {
23008 ast_log(LOG_NOTICE, "Unable to find subscription with call-id: %s\n", replace_id);
23009 transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
23010 error = 1;
23011 } else {
23012 ast_log(LOG_NOTICE, "Trying to pick up %s@%s\n", subscription->exten, subscription->context);
23013 ast_copy_string(pickup.exten, subscription->exten, sizeof(pickup.exten));
23014 ast_copy_string(pickup.context, subscription->context, sizeof(pickup.context));
23015 sip_pvt_unlock(subscription);
23016 if (subscription->owner) {
23017 ast_channel_unlock(subscription->owner);
23018 }
23019 subscription = dialog_unref(subscription, "unref dialog subscription");
23020 }
23021 }
23022
23023
23024 if (!error && ast_strlen_zero(pickup.exten) && (p->refer->refer_call = get_sip_pvt_byid_locked(replace_id, totag, fromtag)) == NULL) {
23025 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existent call id (%s)!\n", replace_id);
23026 transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
23027 error = 1;
23028 } else {
23029 refer_locked = 1;
23030 }
23031
23032
23033
23034
23035
23036 if (p->refer->refer_call == p) {
23037 ast_log(LOG_NOTICE, "INVITE with replaces into it's own call id (%s == %s)!\n", replace_id, p->callid);
23038 transmit_response_reliable(p, "400 Bad request", req);
23039 error = 1;
23040 }
23041
23042 if (!error && ast_strlen_zero(pickup.exten) && !p->refer->refer_call->owner) {
23043
23044 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existing call id (%s)!\n", replace_id);
23045
23046 transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replace)", req);
23047 error = 1;
23048 }
23049
23050 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) {
23051 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-ringing or active call id (%s)!\n", replace_id);
23052 transmit_response_reliable(p, "603 Declined (Replaces)", req);
23053 error = 1;
23054 }
23055
23056 if (error) {
23057 append_history(p, "Xfer", "INVITE/Replace Failed.");
23058 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
23059 sip_pvt_unlock(p);
23060 if (p->refer->refer_call) {
23061 sip_pvt_unlock(p->refer->refer_call);
23062 if (p->refer->refer_call->owner) {
23063 ast_channel_unlock(p->refer->refer_call->owner);
23064 }
23065 p->refer->refer_call = dialog_unref(p->refer->refer_call, "unref dialog p->refer->refer_call");
23066 }
23067 refer_locked = 0;
23068 p->invitestate = INV_COMPLETED;
23069 check_via(p, req);
23070 copy_request(&p->initreq, req);
23071 res = -1;
23072 goto request_invite_cleanup;
23073 }
23074 }
23075
23076
23077
23078
23079 if (!req->ignore) {
23080 int newcall = (p->initreq.headers ? TRUE : FALSE);
23081
23082 if (sip_cancel_destroy(p))
23083 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
23084
23085 p->pendinginvite = seqno;
23086 check_via(p, req);
23087
23088 copy_request(&p->initreq, req);
23089 if (sipdebug)
23090 ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
23091 if (!p->owner) {
23092 if (debug)
23093 ast_verbose("Using INVITE request as basis request - %s\n", p->callid);
23094 if (newcall)
23095 append_history(p, "Invite", "New call: %s", p->callid);
23096 parse_ok_contact(p, req);
23097 } else {
23098 ast_clear_flag(&p->flags[0], SIP_OUTGOING);
23099 if (get_rpid(p, req)) {
23100 struct ast_party_connected_line connected;
23101 struct ast_set_party_connected_line update_connected;
23102
23103 ast_party_connected_line_init(&connected);
23104 memset(&update_connected, 0, sizeof(update_connected));
23105
23106 update_connected.id.number = 1;
23107 connected.id.number.valid = 1;
23108 connected.id.number.str = (char *) p->cid_num;
23109 connected.id.number.presentation = p->callingpres;
23110
23111 update_connected.id.name = 1;
23112 connected.id.name.valid = 1;
23113 connected.id.name.str = (char *) p->cid_name;
23114 connected.id.name.presentation = p->callingpres;
23115
23116 connected.id.tag = (char *) p->cid_tag;
23117 connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
23118 ast_channel_queue_connected_line_update(p->owner, &connected,
23119 &update_connected);
23120 }
23121
23122 if (find_sdp(req)) {
23123 if (process_sdp(p, req, SDP_T38_INITIATE)) {
23124 if (!ast_strlen_zero(get_header(req, "Content-Encoding"))) {
23125
23126
23127
23128 transmit_response_reliable(p, "415 Unsupported Media type", req);
23129 } else {
23130 transmit_response_reliable(p, "488 Not acceptable here", req);
23131 }
23132 if (!p->lastinvite)
23133 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
23134 res = -1;
23135 goto request_invite_cleanup;
23136 }
23137 ast_queue_control(p->owner, AST_CONTROL_SRCUPDATE);
23138 } else {
23139 p->jointcapability = p->capability;
23140 ast_debug(1, "Hm.... No sdp for the moment\n");
23141
23142
23143
23144 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
23145 ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
23146
23147 ast_queue_frame(p->owner, &ast_null_frame);
23148 change_hold_state(p, req, FALSE, 0);
23149 }
23150 }
23151 if (p->do_history)
23152 append_history(p, "ReInv", "Re-invite received");
23153 }
23154 } else if (debug)
23155 ast_verbose("Ignoring this INVITE request\n");
23156
23157 if (!p->lastinvite && !req->ignore && !p->owner) {
23158
23159
23160 int cc_recall_core_id = -1;
23161 set_pvt_allowed_methods(p, req);
23162 res = check_user_full(p, req, SIP_INVITE, e, XMIT_RELIABLE, addr, &authpeer);
23163 if (res == AUTH_CHALLENGE_SENT) {
23164 p->invitestate = INV_COMPLETED;
23165 res = 0;
23166 goto request_invite_cleanup;
23167 }
23168 if (res < 0) {
23169 if (res == AUTH_FAKE_AUTH) {
23170 ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", get_header(req, "From"));
23171 transmit_fake_auth_response(p, SIP_INVITE, req, XMIT_RELIABLE);
23172 } else {
23173 ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", get_header(req, "From"));
23174 transmit_response_reliable(p, "403 Forbidden", req);
23175 }
23176 p->invitestate = INV_COMPLETED;
23177 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
23178 res = 0;
23179 goto request_invite_cleanup;
23180 }
23181
23182
23183 if (p->relatedpeer) {
23184 p->relatedpeer = unref_peer(p->relatedpeer,"unsetting the relatedpeer field in the dialog, before it is set to something else.");
23185 }
23186 if (authpeer) {
23187 p->relatedpeer = ref_peer(authpeer, "setting dialog's relatedpeer pointer");
23188 }
23189
23190 req->authenticated = 1;
23191
23192
23193 if (find_sdp(req)) {
23194 if (process_sdp(p, req, SDP_T38_INITIATE)) {
23195
23196
23197
23198 if (!ast_strlen_zero(get_header(req, "Content-Encoding"))) {
23199 transmit_response_reliable(p, "415 Unsupported Media type", req);
23200 } else {
23201
23202 transmit_response_reliable(p, "488 Not acceptable here", req);
23203 }
23204 p->invitestate = INV_COMPLETED;
23205 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
23206 ast_debug(1, "No compatible codecs for this SIP call.\n");
23207 res = -1;
23208 goto request_invite_cleanup;
23209 }
23210 } else {
23211 p->jointcapability = p->capability;
23212 ast_debug(2, "No SDP in Invite, third party call control\n");
23213 }
23214
23215
23216
23217 if (p->owner)
23218 ast_queue_frame(p->owner, &ast_null_frame);
23219
23220
23221
23222 if (ast_strlen_zero(p->context))
23223 ast_string_field_set(p, context, sip_cfg.default_context);
23224
23225
23226
23227 ast_debug(1, "Checking SIP call limits for device %s\n", p->username);
23228 if ((res = update_call_counter(p, INC_CALL_LIMIT))) {
23229 if (res < 0) {
23230 ast_log(LOG_NOTICE, "Failed to place call for device %s, too many calls\n", p->username);
23231 transmit_response_reliable(p, "480 Temporarily Unavailable (Call limit) ", req);
23232 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
23233 p->invitestate = INV_COMPLETED;
23234 }
23235 res = 0;
23236 goto request_invite_cleanup;
23237 }
23238 gotdest = get_destination(p, NULL, &cc_recall_core_id);
23239 extract_uri(p, req);
23240 build_contact(p);
23241
23242 if (p->rtp) {
23243 ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
23244 ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
23245 }
23246
23247 if (!replace_id && (gotdest != SIP_GET_DEST_EXTEN_FOUND)) {
23248 switch(gotdest) {
23249 case SIP_GET_DEST_INVALID_URI:
23250 transmit_response_reliable(p, "416 Unsupported URI scheme", req);
23251 break;
23252 case SIP_GET_DEST_EXTEN_MATCHMORE:
23253 if (ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP)
23254 == SIP_PAGE2_ALLOWOVERLAP_YES) {
23255 transmit_response_reliable(p, "484 Address Incomplete", req);
23256 break;
23257 }
23258
23259
23260
23261
23262
23263
23264
23265
23266
23267 case SIP_GET_DEST_EXTEN_NOT_FOUND:
23268 {
23269 char *decoded_exten = ast_strdupa(p->exten);
23270 transmit_response_reliable(p, "404 Not Found", req);
23271 ast_uri_decode(decoded_exten);
23272 ast_log(LOG_NOTICE, "Call from '%s' (%s) to extension"
23273 " '%s' rejected because extension not found in context '%s'.\n",
23274 S_OR(p->username, p->peername), ast_sockaddr_stringify(&p->recv), decoded_exten, p->context);
23275 }
23276 break;
23277 case SIP_GET_DEST_REFUSED:
23278 default:
23279 transmit_response_reliable(p, "403 Forbidden", req);
23280 }
23281
23282 p->invitestate = INV_COMPLETED;
23283 update_call_counter(p, DEC_CALL_LIMIT);
23284 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
23285 res = 0;
23286 goto request_invite_cleanup;
23287 } else {
23288
23289
23290
23291 if (ast_strlen_zero(p->exten))
23292 ast_string_field_set(p, exten, "s");
23293
23294
23295 make_our_tag(p);
23296
23297
23298 c = sip_new(p, AST_STATE_DOWN, S_OR(p->peername, NULL), NULL);
23299 if (cc_recall_core_id != -1) {
23300 ast_setup_cc_recall_datastore(c, cc_recall_core_id);
23301 ast_cc_agent_set_interfaces_chanvar(c);
23302 }
23303 *recount = 1;
23304
23305
23306 build_route(p, req, 0, 0);
23307
23308 if (c) {
23309 ast_party_redirecting_init(&redirecting);
23310 memset(&update_redirecting, 0, sizeof(update_redirecting));
23311 change_redirecting_information(p, req, &redirecting, &update_redirecting,
23312 FALSE);
23313 ast_channel_set_redirecting(c, &redirecting, &update_redirecting);
23314 ast_party_redirecting_free(&redirecting);
23315 }
23316 }
23317 } else {
23318 ast_party_redirecting_init(&redirecting);
23319 memset(&update_redirecting, 0, sizeof(update_redirecting));
23320 if (sipdebug) {
23321 if (!req->ignore)
23322 ast_debug(2, "Got a SIP re-invite for call %s\n", p->callid);
23323 else
23324 ast_debug(2, "Got a SIP re-transmit of INVITE for call %s\n", p->callid);
23325 }
23326 if (!req->ignore)
23327 reinvite = 1;
23328 c = p->owner;
23329 change_redirecting_information(p, req, &redirecting, &update_redirecting, FALSE);
23330 if (c) {
23331 ast_channel_set_redirecting(c, &redirecting, &update_redirecting);
23332 }
23333 ast_party_redirecting_free(&redirecting);
23334 }
23335
23336
23337 if ((p->sipoptions & SIP_OPT_TIMER) && !ast_strlen_zero(get_header(req, "Session-Expires"))) {
23338 enum st_refresher_param st_ref_param;
23339
23340
23341
23342 ast_debug(2, "Incoming INVITE with 'timer' option supported and \"Session-Expires\" header.\n");
23343
23344
23345 if (!p->stimer)
23346 sip_st_alloc(p);
23347
23348
23349 p_uac_se_hdr = get_header(req, "Session-Expires");
23350 rtn = parse_session_expires(p_uac_se_hdr, &uac_max_se, &st_ref_param);
23351 tmp_st_ref = (st_ref_param == SESSION_TIMER_REFRESHER_PARAM_UAC) ? SESSION_TIMER_REFRESHER_THEM : SESSION_TIMER_REFRESHER_US;
23352 if (rtn != 0) {
23353 transmit_response_reliable(p, "400 Session-Expires Invalid Syntax", req);
23354 p->invitestate = INV_COMPLETED;
23355 if (!p->lastinvite) {
23356 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
23357 }
23358 res = -1;
23359 goto request_invite_cleanup;
23360 }
23361
23362
23363 p_uac_min_se = get_header(req, "Min-SE");
23364 if (!ast_strlen_zero(p_uac_min_se)) {
23365 rtn = parse_minse(p_uac_min_se, &uac_min_se);
23366 if (rtn != 0) {
23367 transmit_response_reliable(p, "400 Min-SE Invalid Syntax", req);
23368 p->invitestate = INV_COMPLETED;
23369 if (!p->lastinvite) {
23370 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
23371 }
23372 res = -1;
23373 goto request_invite_cleanup;
23374 }
23375 }
23376
23377 dlg_min_se = st_get_se(p, FALSE);
23378 switch (st_get_mode(p, 1)) {
23379 case SESSION_TIMER_MODE_ACCEPT:
23380 case SESSION_TIMER_MODE_ORIGINATE:
23381 if (uac_max_se > 0 && uac_max_se < dlg_min_se) {
23382 transmit_response_with_minse(p, "422 Session Interval Too Small", req, dlg_min_se);
23383 p->invitestate = INV_COMPLETED;
23384 if (!p->lastinvite) {
23385 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
23386 }
23387 res = -1;
23388 goto request_invite_cleanup;
23389 }
23390
23391 p->stimer->st_active_peer_ua = TRUE;
23392 st_active = TRUE;
23393 if (st_ref_param == SESSION_TIMER_REFRESHER_PARAM_UNKNOWN) {
23394 tmp_st_ref = st_get_refresher(p);
23395 }
23396
23397 if (uac_max_se > 0) {
23398 int dlg_max_se = st_get_se(p, TRUE);
23399 if (dlg_max_se >= uac_min_se) {
23400 st_interval = (uac_max_se < dlg_max_se) ? uac_max_se : dlg_max_se;
23401 } else {
23402 st_interval = uac_max_se;
23403 }
23404 } else {
23405
23406 st_interval = global_max_se;
23407 }
23408 break;
23409
23410 case SESSION_TIMER_MODE_REFUSE:
23411 if (p->reqsipoptions & SIP_OPT_TIMER) {
23412 transmit_response_with_unsupported(p, "420 Option Disabled", req, required);
23413 ast_log(LOG_WARNING, "Received SIP INVITE with supported but disabled option: %s\n", required);
23414 p->invitestate = INV_COMPLETED;
23415 if (!p->lastinvite) {
23416 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
23417 }
23418 res = -1;
23419 goto request_invite_cleanup;
23420 }
23421 break;
23422
23423 default:
23424 ast_log(LOG_ERROR, "Internal Error %d at %s:%d\n", st_get_mode(p, 1), __FILE__, __LINE__);
23425 break;
23426 }
23427 } else {
23428
23429
23430
23431 switch (st_get_mode(p, 1)) {
23432 case SESSION_TIMER_MODE_ORIGINATE:
23433 st_active = TRUE;
23434 st_interval = st_get_se(p, TRUE);
23435 tmp_st_ref = SESSION_TIMER_REFRESHER_US;
23436 p->stimer->st_active_peer_ua = (p->sipoptions & SIP_OPT_TIMER) ? TRUE : FALSE;
23437 break;
23438
23439 default:
23440 break;
23441 }
23442 }
23443
23444 if (reinvite == 0) {
23445
23446 if (st_active == TRUE) {
23447 p->stimer->st_active = TRUE;
23448 p->stimer->st_interval = st_interval;
23449 p->stimer->st_ref = tmp_st_ref;
23450 start_session_timer(p);
23451 }
23452 } else {
23453 if (p->stimer->st_active == TRUE) {
23454
23455
23456
23457 ast_debug (2, "Restarting session-timers on a refresh - %s\n", p->callid);
23458
23459
23460 if (st_interval > 0) {
23461 p->stimer->st_interval = st_interval;
23462 p->stimer->st_ref = tmp_st_ref;
23463 }
23464
23465 restart_session_timer(p);
23466 if (p->stimer->st_expirys > 0) {
23467 p->stimer->st_expirys--;
23468 }
23469 }
23470 }
23471
23472 if (!req->ignore && p)
23473 p->lastinvite = seqno;
23474
23475 if (c && replace_id) {
23476 if (!ast_strlen_zero(pickup.exten)) {
23477 append_history(p, "Xfer", "INVITE/Replace received");
23478
23479
23480 transmit_response(p, "100 Trying", req);
23481 p->invitestate = INV_PROCEEDING;
23482 ast_setstate(c, AST_STATE_RING);
23483
23484
23485 ast_channel_unlock(c);
23486 *nounlock = 1;
23487
23488
23489
23490
23491
23492
23493 sip_pvt_unlock(p);
23494 do_magic_pickup(c, pickup.exten, pickup.context);
23495
23496 ast_hangup(c);
23497 sip_pvt_lock(p);
23498
23499 res = 0;
23500 goto request_invite_cleanup;
23501 } else {
23502
23503 if (sipdebug)
23504 ast_debug(4, "Sending this call to the invite/replcaes handler %s\n", p->callid);
23505 res = handle_invite_replaces(p, req, debug, seqno, addr, nounlock);
23506 refer_locked = 0;
23507 goto request_invite_cleanup;
23508 }
23509 }
23510
23511
23512 if (c) {
23513 enum ast_channel_state c_state = c->_state;
23514
23515 if (c_state != AST_STATE_UP && reinvite &&
23516 (p->invitestate == INV_TERMINATED || p->invitestate == INV_CONFIRMED)) {
23517
23518
23519
23520
23521
23522
23523
23524
23525
23526 c_state = AST_STATE_UP;
23527 }
23528
23529 switch(c_state) {
23530 case AST_STATE_DOWN:
23531 ast_debug(2, "%s: New call is still down.... Trying... \n", c->name);
23532 transmit_provisional_response(p, "100 Trying", req, 0);
23533 p->invitestate = INV_PROCEEDING;
23534 ast_setstate(c, AST_STATE_RING);
23535 if (strcmp(p->exten, ast_pickup_ext())) {
23536 enum ast_pbx_result result;
23537
23538 result = ast_pbx_start(c);
23539
23540 switch(result) {
23541 case AST_PBX_FAILED:
23542 ast_log(LOG_WARNING, "Failed to start PBX :(\n");
23543 p->invitestate = INV_COMPLETED;
23544 transmit_response_reliable(p, "503 Unavailable", req);
23545 break;
23546 case AST_PBX_CALL_LIMIT:
23547 ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
23548 p->invitestate = INV_COMPLETED;
23549 transmit_response_reliable(p, "480 Temporarily Unavailable", req);
23550 break;
23551 case AST_PBX_SUCCESS:
23552
23553 break;
23554 }
23555
23556 if (result) {
23557
23558
23559 ast_channel_unlock(c);
23560 *nounlock = 1;
23561 sip_pvt_unlock(p);
23562 ast_hangup(c);
23563 sip_pvt_lock(p);
23564 c = NULL;
23565 }
23566 } else {
23567 if (sip_pickup(c)) {
23568 ast_log(LOG_WARNING, "Failed to start Group pickup by %s\n", c->name);
23569 transmit_response_reliable(p, "480 Temporarily Unavailable", req);
23570 sip_alreadygone(p);
23571 c->hangupcause = AST_CAUSE_FAILURE;
23572
23573
23574 ast_channel_unlock(c);
23575 *nounlock = 1;
23576
23577 p->invitestate = INV_COMPLETED;
23578 sip_pvt_unlock(p);
23579 ast_hangup(c);
23580 sip_pvt_lock(p);
23581 c = NULL;
23582 }
23583 }
23584 break;
23585 case AST_STATE_RING:
23586 transmit_provisional_response(p, "100 Trying", req, 0);
23587 p->invitestate = INV_PROCEEDING;
23588 break;
23589 case AST_STATE_RINGING:
23590 transmit_provisional_response(p, "180 Ringing", req, 0);
23591 p->invitestate = INV_PROCEEDING;
23592 break;
23593 case AST_STATE_UP:
23594 ast_debug(2, "%s: This call is UP.... \n", c->name);
23595
23596 transmit_response(p, "100 Trying", req);
23597
23598 if (p->t38.state == T38_PEER_REINVITE) {
23599 if (p->t38id > -1) {
23600
23601 AST_SCHED_DEL_UNREF(sched, p->t38id, dialog_unref(p, "remove ref for t38id"));
23602 }
23603 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."));
23604 } else if (p->t38.state == T38_ENABLED) {
23605 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
23606 transmit_response_with_t38_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL)));
23607 } else if (p->t38.state == T38_DISABLED) {
23608
23609 if (p->srtp && !ast_test_flag(p->srtp, SRTP_CRYPTO_OFFER_OK)) {
23610 ast_log(LOG_WARNING, "Target does not support required crypto\n");
23611 transmit_response_reliable(p, "488 Not Acceptable Here (crypto)", req);
23612 } else {
23613 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
23614 transmit_response_with_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL)), p->session_modify == TRUE ? FALSE : TRUE, FALSE);
23615 ast_queue_control(p->owner, AST_CONTROL_UPDATE_RTP_PEER);
23616 }
23617 }
23618
23619 p->invitestate = INV_TERMINATED;
23620 break;
23621 default:
23622 ast_log(LOG_WARNING, "Don't know how to handle INVITE in state %d\n", c->_state);
23623 transmit_response(p, "100 Trying", req);
23624 break;
23625 }
23626 } else {
23627 if (p && (p->autokillid == -1)) {
23628 const char *msg;
23629
23630 if (!p->jointcapability)
23631 msg = "488 Not Acceptable Here (codec error)";
23632 else {
23633 ast_log(LOG_NOTICE, "Unable to create/find SIP channel for this INVITE\n");
23634 msg = "503 Unavailable";
23635 }
23636 transmit_response_reliable(p, msg, req);
23637 p->invitestate = INV_COMPLETED;
23638 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
23639 }
23640 }
23641
23642 request_invite_cleanup:
23643
23644 if (refer_locked && p->refer && p->refer->refer_call) {
23645 sip_pvt_unlock(p->refer->refer_call);
23646 if (p->refer->refer_call->owner) {
23647 ast_channel_unlock(p->refer->refer_call->owner);
23648 }
23649 p->refer->refer_call = dialog_unref(p->refer->refer_call, "unref dialog p->refer->refer_call");
23650 }
23651 if (authpeer) {
23652 authpeer = unref_peer(authpeer, "unref_peer, from handle_request_invite authpeer");
23653 }
23654
23655 return res;
23656 }
23657
23658
23659
23660
23661
23662
23663
23664
23665
23666
23667
23668
23669
23670
23671 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, uint32_t seqno, int *nounlock)
23672 {
23673 struct sip_dual target;
23674
23675 int res = 0;
23676 struct sip_pvt *targetcall_pvt;
23677 struct ast_party_connected_line connected_to_transferee;
23678 struct ast_party_connected_line connected_to_target;
23679 char transferer_linkedid[32];
23680 struct ast_channel *chans[2];
23681
23682
23683 if (!(targetcall_pvt = get_sip_pvt_byid_locked(transferer->refer->replaces_callid, transferer->refer->replaces_callid_totag,
23684 transferer->refer->replaces_callid_fromtag))) {
23685 if (transferer->refer->localtransfer) {
23686
23687
23688
23689 transmit_notify_with_sipfrag(transferer, seqno, "481 Call leg/transaction does not exist", TRUE);
23690 append_history(transferer, "Xfer", "Refer failed");
23691 ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
23692 transferer->refer->status = REFER_FAILED;
23693 return -1;
23694 }
23695
23696 ast_debug(3, "SIP attended transfer: Not our call - generating INVITE with replaces\n");
23697 return 0;
23698 }
23699
23700
23701 append_history(transferer, "Xfer", "Refer accepted");
23702 if (!targetcall_pvt->owner) {
23703 ast_debug(4, "SIP attended transfer: Error: No owner of target call\n");
23704
23705 transmit_notify_with_sipfrag(transferer, seqno, "503 Service Unavailable", TRUE);
23706 append_history(transferer, "Xfer", "Refer failed");
23707 ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
23708 transferer->refer->status = REFER_FAILED;
23709 sip_pvt_unlock(targetcall_pvt);
23710 if (targetcall_pvt)
23711 ao2_t_ref(targetcall_pvt, -1, "Drop targetcall_pvt pointer");
23712 return -1;
23713 }
23714
23715
23716 target.chan1 = ast_channel_ref(targetcall_pvt->owner);
23717 target.chan2 = ast_bridged_channel(targetcall_pvt->owner);
23718 if (target.chan2) {
23719 ast_channel_ref(target.chan2);
23720 }
23721
23722 if (!target.chan2 || !(target.chan2->_state == AST_STATE_UP || target.chan2->_state == AST_STATE_RINGING) ) {
23723
23724 if (target.chan2)
23725 ast_debug(4, "SIP attended transfer: Error: Wrong state of target call: %s\n", ast_state2str(target.chan2->_state));
23726 else if (target.chan1->_state != AST_STATE_RING)
23727 ast_debug(4, "SIP attended transfer: Error: No target channel\n");
23728 else
23729 ast_debug(4, "SIP attended transfer: Attempting transfer in ringing state\n");
23730 }
23731
23732
23733 if (sipdebug) {
23734 if (current->chan2)
23735 ast_debug(4, "SIP attended transfer: trying to bridge %s and %s\n", target.chan1->name, current->chan2->name);
23736 else
23737 ast_debug(4, "SIP attended transfer: trying to make %s take over (masq) %s\n", target.chan1->name, current->chan1->name);
23738 }
23739
23740 ast_set_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
23741
23742 ast_copy_string(transferer_linkedid, transferer->owner->linkedid, sizeof(transferer_linkedid));
23743
23744
23745 chans[0] = transferer->owner;
23746 chans[1] = target.chan1;
23747 ast_manager_event_multichan(EVENT_FLAG_CALL, "Transfer", 2, chans,
23748 "TransferMethod: SIP\r\n"
23749 "TransferType: Attended\r\n"
23750 "Channel: %s\r\n"
23751 "Uniqueid: %s\r\n"
23752 "SIP-Callid: %s\r\n"
23753 "TargetChannel: %s\r\n"
23754 "TargetUniqueid: %s\r\n",
23755 transferer->owner->name,
23756 transferer->owner->uniqueid,
23757 transferer->callid,
23758 target.chan1->name,
23759 target.chan1->uniqueid);
23760 ast_party_connected_line_init(&connected_to_transferee);
23761 ast_party_connected_line_init(&connected_to_target);
23762
23763 ast_party_connected_line_copy(&connected_to_transferee, ¤t->chan1->connected);
23764
23765 ast_party_connected_line_copy(&connected_to_target, &target.chan1->connected);
23766 connected_to_target.source = connected_to_transferee.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
23767 res = attempt_transfer(current, &target);
23768 if (res) {
23769
23770 transmit_notify_with_sipfrag(transferer, seqno, "486 Busy Here", TRUE);
23771 append_history(transferer, "Xfer", "Refer failed");
23772 ast_clear_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
23773
23774 sip_pvt_unlock(targetcall_pvt);
23775 ast_channel_unlock(target.chan1);
23776 } else {
23777
23778 const char *xfersound = pbx_builtin_getvar_helper(target.chan1, "ATTENDED_TRANSFER_COMPLETE_SOUND");
23779
23780
23781 ast_cel_report_event(target.chan1, AST_CEL_ATTENDEDTRANSFER, NULL, transferer_linkedid, target.chan2);
23782
23783
23784 transmit_notify_with_sipfrag(transferer, seqno, "200 OK", TRUE);
23785 append_history(transferer, "Xfer", "Refer succeeded");
23786 transferer->refer->status = REFER_200OK;
23787 if (target.chan2 && !ast_strlen_zero(xfersound) && ast_streamfile(target.chan2, xfersound, target.chan2->language) >= 0) {
23788 ast_waitstream(target.chan2, "");
23789 }
23790
23791
23792
23793
23794
23795
23796
23797
23798
23799
23800
23801 ast_channel_ref(current->chan1);
23802 ast_channel_unlock(current->chan1);
23803 ast_channel_unlock(target.chan1);
23804 *nounlock = 1;
23805 sip_pvt_unlock(targetcall_pvt);
23806 sip_pvt_unlock(transferer);
23807
23808 ast_do_masquerade(target.chan1);
23809
23810 ast_indicate(target.chan1, AST_CONTROL_UNHOLD);
23811 if (target.chan2) {
23812 ast_indicate(target.chan2, AST_CONTROL_UNHOLD);
23813 }
23814
23815 if (current->chan2 && current->chan2->_state == AST_STATE_RING) {
23816 ast_indicate(target.chan1, AST_CONTROL_RINGING);
23817 }
23818
23819 if (target.chan2) {
23820 ast_channel_queue_connected_line_update(target.chan1, &connected_to_transferee, NULL);
23821 ast_channel_queue_connected_line_update(target.chan2, &connected_to_target, NULL);
23822 } else {
23823
23824
23825
23826
23827
23828
23829
23830 struct ast_control_read_action_payload *frame_payload;
23831 int payload_size;
23832 int frame_size;
23833 unsigned char connected_line_data[1024];
23834 payload_size = ast_connected_line_build_data(connected_line_data,
23835 sizeof(connected_line_data), &connected_to_target, NULL);
23836 frame_size = payload_size + sizeof(*frame_payload);
23837 if (payload_size != -1) {
23838 frame_payload = ast_alloca(frame_size);
23839 frame_payload->payload_size = payload_size;
23840 memcpy(frame_payload->payload, connected_line_data, payload_size);
23841 frame_payload->action = AST_FRAME_READ_ACTION_CONNECTED_LINE_MACRO;
23842 ast_queue_control_data(target.chan1, AST_CONTROL_READ_ACTION, frame_payload, frame_size);
23843 }
23844
23845
23846
23847
23848 ast_channel_queue_connected_line_update(target.chan1, &connected_to_transferee, NULL);
23849
23850 }
23851 sip_pvt_lock(transferer);
23852
23853 ast_channel_unref(current->chan1);
23854 }
23855
23856
23857 ast_party_connected_line_free(&connected_to_target);
23858 ast_party_connected_line_free(&connected_to_transferee);
23859 ast_channel_unref(target.chan1);
23860 if (target.chan2) {
23861 ast_channel_unref(target.chan2);
23862 }
23863 if (targetcall_pvt)
23864 ao2_t_ref(targetcall_pvt, -1, "drop targetcall_pvt");
23865 return 1;
23866 }
23867
23868
23869
23870
23871
23872
23873
23874
23875
23876
23877
23878
23879
23880
23881
23882
23883
23884
23885
23886
23887
23888
23889
23890
23891
23892
23893
23894
23895
23896
23897
23898
23899
23900
23901
23902
23903
23904
23905
23906
23907
23908
23909
23910
23911
23912
23913
23914
23915
23916
23917
23918
23919
23920
23921
23922
23923
23924
23925
23926
23927
23928
23929
23930
23931
23932 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, uint32_t seqno, int *nounlock)
23933 {
23934
23935
23936
23937
23938 struct sip_dual current = { 0, };
23939 struct ast_channel *chans[2] = { 0, };
23940 char *refer_to = NULL;
23941 char *refer_to_domain = NULL;
23942 char *refer_to_context = NULL;
23943 char *referred_by = NULL;
23944 char *callid = NULL;
23945 int localtransfer = 0;
23946 int attendedtransfer = 0;
23947 int res = 0;
23948
23949 if (req->debug) {
23950 ast_verbose("Call %s got a SIP call transfer from %s: (REFER)!\n",
23951 p->callid,
23952 ast_test_flag(&p->flags[0], SIP_OUTGOING) ? "callee" : "caller");
23953 }
23954
23955 if (!p->owner) {
23956
23957
23958 ast_debug(3, "Call %s: Declined REFER, outside of dialog...\n", p->callid);
23959 transmit_response(p, "603 Declined (No dialog)", req);
23960 if (!req->ignore) {
23961 append_history(p, "Xfer", "Refer failed. Outside of dialog.");
23962 sip_alreadygone(p);
23963 pvt_set_needdestroy(p, "outside of dialog");
23964 }
23965 res = 0;
23966 goto handle_refer_cleanup;
23967 }
23968
23969
23970 if (p->allowtransfer == TRANSFER_CLOSED ) {
23971
23972 transmit_response(p, "603 Declined (policy)", req);
23973 append_history(p, "Xfer", "Refer failed. Allowtransfer == closed.");
23974
23975 res = 0;
23976 goto handle_refer_cleanup;
23977 }
23978
23979 if (!req->ignore && ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
23980
23981 transmit_response(p, "491 Request pending", req);
23982 append_history(p, "Xfer", "Refer failed. Request pending.");
23983 res = 0;
23984 goto handle_refer_cleanup;
23985 }
23986
23987
23988 if (!p->refer && !sip_refer_allocate(p)) {
23989 transmit_response(p, "500 Internal Server Error", req);
23990 append_history(p, "Xfer", "Refer failed. Memory allocation error.");
23991 res = -3;
23992 goto handle_refer_cleanup;
23993 }
23994
23995 res = get_refer_info(p, req);
23996
23997 p->refer->status = REFER_SENT;
23998
23999 if (res != 0) {
24000 switch (res) {
24001 case -2:
24002 transmit_response(p, "400 Bad Request (Refer-to missing)", req);
24003 append_history(p, "Xfer", "Refer failed. Refer-to missing.");
24004 if (req->debug) {
24005 ast_debug(1, "SIP transfer to black hole can't be handled (no refer-to: )\n");
24006 }
24007 break;
24008 case -3:
24009 transmit_response(p, "603 Declined (Non sip: uri)", req);
24010 append_history(p, "Xfer", "Refer failed. Non SIP uri");
24011 if (req->debug) {
24012 ast_debug(1, "SIP transfer to non-SIP uri denied\n");
24013 }
24014 break;
24015 default:
24016
24017 transmit_response(p, "202 Accepted", req);
24018 append_history(p, "Xfer", "Refer failed. Bad extension.");
24019 transmit_notify_with_sipfrag(p, seqno, "404 Not found", TRUE);
24020 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
24021 if (req->debug) {
24022 ast_debug(1, "SIP transfer to bad extension: %s\n", p->refer->refer_to);
24023 }
24024 break;
24025 }
24026 res = 0;
24027 goto handle_refer_cleanup;
24028 }
24029 if (ast_strlen_zero(p->context)) {
24030 ast_string_field_set(p, context, sip_cfg.default_context);
24031 }
24032
24033
24034 if (sip_cfg.allow_external_domains && check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
24035 p->refer->localtransfer = 1;
24036 if (sipdebug) {
24037 ast_debug(3, "This SIP transfer is local : %s\n", p->refer->refer_to_domain);
24038 }
24039 } else if (AST_LIST_EMPTY(&domain_list) || check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
24040
24041 p->refer->localtransfer = 1;
24042 } else if (sipdebug) {
24043 ast_debug(3, "This SIP transfer is to a remote SIP extension (remote domain %s)\n", p->refer->refer_to_domain);
24044 }
24045
24046
24047
24048 if (req->ignore) {
24049 goto handle_refer_cleanup;
24050 }
24051
24052
24053
24054
24055
24056
24057
24058
24059
24060
24061
24062
24063
24064
24065
24066
24067
24068
24069
24070
24071
24072
24073
24074
24075
24076
24077 chans[0] = current.chan1 = p->owner;
24078
24079
24080 chans[1] = current.chan2 = ast_bridged_channel(current.chan1);
24081
24082 ast_channel_ref(current.chan1);
24083 if (current.chan2) {
24084 ast_channel_ref(current.chan2);
24085 }
24086
24087 if (sipdebug) {
24088 ast_debug(3, "SIP %s transfer: Transferer channel %s, transferee channel %s\n",
24089 p->refer->attendedtransfer ? "attended" : "blind",
24090 current.chan1->name,
24091 current.chan2 ? current.chan2->name : "<none>");
24092 }
24093
24094 if (!current.chan2 && !p->refer->attendedtransfer) {
24095
24096
24097
24098 if (sipdebug) {
24099 ast_debug(3, "Refused SIP transfer on non-bridged channel.\n");
24100 }
24101 p->refer->status = REFER_FAILED;
24102 append_history(p, "Xfer", "Refer failed. Non-bridged channel.");
24103 transmit_response(p, "603 Declined", req);
24104 res = -1;
24105 goto handle_refer_cleanup;
24106 }
24107
24108 if (current.chan2) {
24109 if (sipdebug) {
24110 ast_debug(4, "Got SIP transfer, applying to bridged peer '%s'\n", current.chan2->name);
24111 }
24112 ast_queue_control(current.chan1, AST_CONTROL_UNHOLD);
24113 }
24114
24115 ast_set_flag(&p->flags[0], SIP_GOTREFER);
24116
24117
24118 transmit_response(p, "202 Accepted", req);
24119
24120
24121 if (p->refer->attendedtransfer) {
24122
24123 if ((res = local_attended_transfer(p, ¤t, req, seqno, nounlock))) {
24124 goto handle_refer_cleanup;
24125 }
24126
24127 if (sipdebug) {
24128 ast_debug(4, "SIP attended transfer: Still not our call - generating INVITE with replaces\n");
24129 }
24130
24131 }
24132
24133
24134 refer_to = ast_strdupa(p->refer->refer_to);
24135 refer_to_domain = ast_strdupa(p->refer->refer_to_domain);
24136 refer_to_context = ast_strdupa(p->refer->refer_to_context);
24137 referred_by = ast_strdupa(p->refer->referred_by);
24138 callid = ast_strdupa(p->callid);
24139 localtransfer = p->refer->localtransfer;
24140 attendedtransfer = p->refer->attendedtransfer;
24141
24142 if (!*nounlock) {
24143 ast_channel_unlock(p->owner);
24144 *nounlock = 1;
24145 }
24146 sip_pvt_unlock(p);
24147
24148
24149 if (localtransfer && ast_parking_ext_valid(refer_to, current.chan1, refer_to_context)) {
24150 sip_pvt_lock(p);
24151 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
24152 p->refer->status = REFER_200OK;
24153 append_history(p, "Xfer", "REFER to call parking.");
24154 sip_pvt_unlock(p);
24155
24156 ast_manager_event_multichan(EVENT_FLAG_CALL, "Transfer", 2, chans,
24157 "TransferMethod: SIP\r\n"
24158 "TransferType: Blind\r\n"
24159 "Channel: %s\r\n"
24160 "Uniqueid: %s\r\n"
24161 "SIP-Callid: %s\r\n"
24162 "TargetChannel: %s\r\n"
24163 "TargetUniqueid: %s\r\n"
24164 "TransferExten: %s\r\n"
24165 "Transfer2Parking: Yes\r\n",
24166 current.chan1->name,
24167 current.chan1->uniqueid,
24168 callid,
24169 current.chan2->name,
24170 current.chan2->uniqueid,
24171 refer_to);
24172
24173 if (sipdebug) {
24174 ast_debug(4, "SIP transfer to parking: trying to park %s. Parked by %s\n", current.chan2->name, current.chan1->name);
24175 }
24176
24177
24178 if (sip_park(current.chan2, current.chan1, req, seqno, refer_to, refer_to_context)) {
24179 sip_pvt_lock(p);
24180 transmit_notify_with_sipfrag(p, seqno, "500 Internal Server Error", TRUE);
24181 } else {
24182 sip_pvt_lock(p);
24183 }
24184 goto handle_refer_cleanup;
24185 }
24186
24187
24188
24189
24190 if (current.chan1 && current.chan2) {
24191 ast_debug(3, "chan1->name: %s\n", current.chan1->name);
24192 pbx_builtin_setvar_helper(current.chan1, "BLINDTRANSFER", current.chan2->name);
24193 }
24194
24195 if (current.chan2) {
24196 pbx_builtin_setvar_helper(current.chan2, "BLINDTRANSFER", current.chan1->name);
24197 pbx_builtin_setvar_helper(current.chan2, "SIPDOMAIN", refer_to_domain);
24198 pbx_builtin_setvar_helper(current.chan2, "SIPTRANSFER", "yes");
24199
24200 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER", "yes");
24201
24202 if (!ast_strlen_zero(referred_by)) {
24203 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REFERER", referred_by);
24204 }
24205 }
24206
24207 sip_pvt_lock(p);
24208
24209 if (!ast_strlen_zero(p->refer->replaces_callid)) {
24210 char tempheader[SIPBUFSIZE];
24211 snprintf(tempheader, sizeof(tempheader), "%s%s%s%s%s", p->refer->replaces_callid,
24212 p->refer->replaces_callid_totag ? ";to-tag=" : "",
24213 p->refer->replaces_callid_totag,
24214 p->refer->replaces_callid_fromtag ? ";from-tag=" : "",
24215 p->refer->replaces_callid_fromtag);
24216
24217 if (current.chan2) {
24218 sip_pvt_unlock(p);
24219 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REPLACES", tempheader);
24220 sip_pvt_lock(p);
24221 }
24222 }
24223
24224
24225
24226
24227 if (!p->refer->attendedtransfer) {
24228 transmit_notify_with_sipfrag(p, seqno, "180 Ringing", FALSE);
24229 }
24230
24231
24232
24233
24234
24235 if (!current.chan2) {
24236
24237
24238
24239
24240
24241
24242
24243 p->refer->status = REFER_FAILED;
24244 transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable (can't handle one-legged xfers)", TRUE);
24245 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
24246 append_history(p, "Xfer", "Refer failed (only bridged calls).");
24247 res = -1;
24248 goto handle_refer_cleanup;
24249 }
24250 ast_set_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
24251
24252
24253
24254
24255
24256
24257
24258 sip_pvt_unlock(p);
24259 ast_indicate(current.chan2, AST_CONTROL_UNHOLD);
24260 res = ast_async_goto(current.chan2, refer_to_context, refer_to, 1);
24261
24262 if (!res) {
24263 ast_manager_event_multichan(EVENT_FLAG_CALL, "Transfer", 2, chans,
24264 "TransferMethod: SIP\r\n"
24265 "TransferType: Blind\r\n"
24266 "Channel: %s\r\n"
24267 "Uniqueid: %s\r\n"
24268 "SIP-Callid: %s\r\n"
24269 "TargetChannel: %s\r\n"
24270 "TargetUniqueid: %s\r\n"
24271 "TransferExten: %s\r\n"
24272 "TransferContext: %s\r\n",
24273 current.chan1->name,
24274 current.chan1->uniqueid,
24275 callid,
24276 current.chan2->name,
24277 current.chan2->uniqueid,
24278 refer_to,
24279 refer_to_context);
24280
24281 ast_debug(3, "%s transfer succeeded. Telling transferer.\n", attendedtransfer? "Attended" : "Blind");
24282
24283
24284 ast_channel_lock(current.chan1);
24285 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);
24286 ast_channel_unlock(current.chan1);
24287
24288 sip_pvt_lock(p);
24289 transmit_notify_with_sipfrag(p, seqno, "200 Ok", TRUE);
24290 if (p->refer->localtransfer) {
24291 p->refer->status = REFER_200OK;
24292 }
24293 if (p->owner) {
24294 p->owner->hangupcause = AST_CAUSE_NORMAL_CLEARING;
24295 }
24296 append_history(p, "Xfer", "Refer succeeded.");
24297 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
24298
24299
24300 res = 0;
24301 } else {
24302 sip_pvt_lock(p);
24303 ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
24304 ast_debug(3, "%s transfer failed. Resuming original call.\n", p->refer->attendedtransfer? "Attended" : "Blind");
24305 append_history(p, "Xfer", "Refer failed.");
24306
24307 p->refer->status = REFER_FAILED;
24308 transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable", TRUE);
24309 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
24310 res = -1;
24311 }
24312
24313 handle_refer_cleanup:
24314 if (current.chan1) {
24315 ast_channel_unref(current.chan1);
24316 }
24317 if (current.chan2) {
24318 ast_channel_unref(current.chan2);
24319 }
24320
24321
24322 return res;
24323 }
24324
24325
24326 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req)
24327 {
24328
24329 check_via(p, req);
24330 sip_alreadygone(p);
24331
24332 if (p->owner && p->owner->_state == AST_STATE_UP) {
24333
24334 transmit_response(p, "200 OK", req);
24335 ast_debug(1, "Got CANCEL on an answered call. Ignoring... \n");
24336 return 0;
24337 }
24338
24339
24340
24341
24342
24343
24344 if (p->invitestate == INV_TERMINATED || p->invitestate == INV_COMPLETED) {
24345 __sip_pretend_ack(p);
24346 }
24347 if (p->invitestate != INV_TERMINATED)
24348 p->invitestate = INV_CANCELLED;
24349
24350 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD))
24351 update_call_counter(p, DEC_CALL_LIMIT);
24352
24353 stop_media_flows(p);
24354 if (p->owner) {
24355 sip_queue_hangup_cause(p, 0);
24356 } else {
24357 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
24358 }
24359 if (ast_str_strlen(p->initreq.data) > 0) {
24360 struct sip_pkt *pkt, *prev_pkt;
24361
24362
24363
24364
24365
24366
24367
24368
24369
24370
24371
24372 for (pkt = p->packets, prev_pkt = NULL; pkt; prev_pkt = pkt, pkt = pkt->next) {
24373 if (pkt->seqno == p->lastinvite && pkt->response_code == 487) {
24374 AST_SCHED_DEL(sched, pkt->retransid);
24375 UNLINK(pkt, p->packets, prev_pkt);
24376 dialog_unref(pkt->owner, "unref packet->owner from dialog");
24377 if (pkt->data) {
24378 ast_free(pkt->data);
24379 }
24380 ast_free(pkt);
24381 break;
24382 }
24383 }
24384 transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
24385 transmit_response(p, "200 OK", req);
24386 return 1;
24387 } else {
24388 transmit_response(p, "481 Call Leg Does Not Exist", req);
24389 return 0;
24390 }
24391 }
24392
24393
24394 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req)
24395 {
24396 struct ast_channel *c=NULL;
24397 int res;
24398 struct ast_channel *bridged_to;
24399 const char *required;
24400
24401
24402 if (p->pendinginvite && !ast_test_flag(&p->flags[0], SIP_OUTGOING) && !req->ignore) {
24403 transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
24404 }
24405
24406 __sip_pretend_ack(p);
24407
24408 p->invitestate = INV_TERMINATED;
24409
24410 copy_request(&p->initreq, req);
24411 if (sipdebug)
24412 ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
24413 check_via(p, req);
24414 sip_alreadygone(p);
24415
24416
24417 if (p->do_history || p->owner) {
24418 char quality_buf[AST_MAX_USER_FIELD], *quality;
24419 struct ast_channel *bridge = p->owner ? ast_bridged_channel(p->owner) : NULL;
24420
24421
24422
24423
24424 while (bridge && ast_channel_trylock(bridge)) {
24425 ast_channel_unlock(p->owner);
24426 do {
24427
24428 sip_pvt_unlock(p);
24429 usleep(1);
24430 sip_pvt_lock(p);
24431 } while (p->owner && ast_channel_trylock(p->owner));
24432 bridge = p->owner ? ast_bridged_channel(p->owner) : NULL;
24433 }
24434
24435
24436 if (p->rtp && (quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
24437 if (p->do_history) {
24438 append_history(p, "RTCPaudio", "Quality:%s", quality);
24439
24440 if ((quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY_JITTER, quality_buf, sizeof(quality_buf)))) {
24441 append_history(p, "RTCPaudioJitter", "Quality:%s", quality);
24442 }
24443 if ((quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY_LOSS, quality_buf, sizeof(quality_buf)))) {
24444 append_history(p, "RTCPaudioLoss", "Quality:%s", quality);
24445 }
24446 if ((quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY_RTT, quality_buf, sizeof(quality_buf)))) {
24447 append_history(p, "RTCPaudioRTT", "Quality:%s", quality);
24448 }
24449 }
24450
24451 if (p->owner) {
24452 ast_rtp_instance_set_stats_vars(p->owner, p->rtp);
24453 }
24454
24455 }
24456
24457 if (bridge) {
24458 struct sip_pvt *q = bridge->tech_pvt;
24459
24460 if (IS_SIP_TECH(bridge->tech) && q && q->rtp) {
24461 ast_rtp_instance_set_stats_vars(bridge, q->rtp);
24462 }
24463 ast_channel_unlock(bridge);
24464 }
24465
24466 if (p->vrtp && (quality = ast_rtp_instance_get_quality(p->vrtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
24467 if (p->do_history) {
24468 append_history(p, "RTCPvideo", "Quality:%s", quality);
24469 }
24470 if (p->owner) {
24471 pbx_builtin_setvar_helper(p->owner, "RTPVIDEOQOS", quality);
24472 }
24473 }
24474 if (p->trtp && (quality = ast_rtp_instance_get_quality(p->trtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
24475 if (p->do_history) {
24476 append_history(p, "RTCPtext", "Quality:%s", quality);
24477 }
24478 if (p->owner) {
24479 pbx_builtin_setvar_helper(p->owner, "RTPTEXTQOS", quality);
24480 }
24481 }
24482 }
24483
24484 stop_media_flows(p);
24485 stop_session_timer(p);
24486
24487 if (!ast_strlen_zero(get_header(req, "Also"))) {
24488 ast_log(LOG_NOTICE, "Client '%s' using deprecated BYE/Also transfer method. Ask vendor to support REFER instead\n",
24489 ast_sockaddr_stringify(&p->recv));
24490 if (ast_strlen_zero(p->context))
24491 ast_string_field_set(p, context, sip_cfg.default_context);
24492 res = get_also_info(p, req);
24493 if (!res) {
24494 c = p->owner;
24495 if (c) {
24496 bridged_to = ast_bridged_channel(c);
24497 if (bridged_to) {
24498
24499 ast_queue_control(c, AST_CONTROL_UNHOLD);
24500 ast_channel_unlock(c);
24501 ast_async_goto(bridged_to, p->context, p->refer->refer_to, 1);
24502 ast_channel_lock(c);
24503 } else
24504 ast_queue_hangup(p->owner);
24505 }
24506 } else {
24507 ast_log(LOG_WARNING, "Invalid transfer information from '%s'\n", ast_sockaddr_stringify(&p->recv));
24508 if (p->owner)
24509 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
24510 }
24511 } else if (p->owner) {
24512 sip_queue_hangup_cause(p, 0);
24513 sip_scheddestroy_final(p, DEFAULT_TRANS_TIMEOUT);
24514 ast_debug(3, "Received bye, issuing owner hangup\n");
24515 } else {
24516 sip_scheddestroy_final(p, DEFAULT_TRANS_TIMEOUT);
24517 ast_debug(3, "Received bye, no owner, selfdestruct soon.\n");
24518 }
24519 ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
24520
24521
24522 required = get_header(req, "Require");
24523 if (!ast_strlen_zero(required)) {
24524 char unsupported[256] = { 0, };
24525 parse_sip_options(required, unsupported, ARRAY_LEN(unsupported));
24526
24527
24528 if (!ast_strlen_zero(unsupported)) {
24529 transmit_response_with_unsupported(p, "420 Bad extension (unsupported)", req, unsupported);
24530 ast_log(LOG_WARNING, "Received SIP BYE with unsupported required extension: required:%s unsupported:%s\n", required, unsupported);
24531 } else {
24532 transmit_response(p, "200 OK", req);
24533 }
24534 } else {
24535 transmit_response(p, "200 OK", req);
24536 }
24537
24538 return 1;
24539 }
24540
24541
24542 static int handle_request_message(struct sip_pvt *p, struct sip_request *req)
24543 {
24544 if (!req->ignore) {
24545 if (req->debug)
24546 ast_verbose("Receiving message!\n");
24547 receive_message(p, req);
24548 } else
24549 transmit_response(p, "202 Accepted", req);
24550 return 1;
24551 }
24552
24553 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)
24554 {
24555 int etag_present = !ast_strlen_zero(etag);
24556 int body_present = req->lines > 0;
24557
24558 ast_assert(expires_int != NULL);
24559
24560 if (ast_strlen_zero(expires)) {
24561
24562
24563
24564
24565 *expires_int = DEFAULT_PUBLISH_EXPIRES;
24566 } else if (sscanf(expires, "%30d", expires_int) != 1) {
24567 return SIP_PUBLISH_UNKNOWN;
24568 }
24569
24570 if (*expires_int == 0) {
24571 return SIP_PUBLISH_REMOVE;
24572 } else if (!etag_present && body_present) {
24573 return SIP_PUBLISH_INITIAL;
24574 } else if (etag_present && !body_present) {
24575 return SIP_PUBLISH_REFRESH;
24576 } else if (etag_present && body_present) {
24577 return SIP_PUBLISH_MODIFY;
24578 }
24579
24580 return SIP_PUBLISH_UNKNOWN;
24581 }
24582
24583 #ifdef HAVE_LIBXML2
24584 static void get_pidf_body(struct sip_request *req, char *pidf_body, size_t size)
24585 {
24586 int i;
24587 struct ast_str *str = ast_str_alloca(size);
24588 for (i = 0; i < req->lines; ++i) {
24589 ast_str_append(&str, 0, "%s", REQ_OFFSET_TO_STR(req, line[i]));
24590 }
24591 ast_copy_string(pidf_body, ast_str_buffer(str), size);
24592 }
24593
24594 static int pidf_validate_tuple(struct ast_xml_node *tuple_node)
24595 {
24596 const char *id;
24597 int status_found = FALSE;
24598 struct ast_xml_node *tuple_children;
24599 struct ast_xml_node *tuple_children_iterator;
24600
24601 if (!(id = ast_xml_get_attribute(tuple_node, "id"))) {
24602 ast_log(LOG_WARNING, "Tuple XML element has no attribute 'id'\n");
24603 return FALSE;
24604 }
24605
24606 ast_xml_free_attr(id);
24607
24608 if (!(tuple_children = ast_xml_node_get_children(tuple_node))) {
24609
24610 ast_log(LOG_WARNING, "Tuple XML element has no child elements\n");
24611 return FALSE;
24612 }
24613 for (tuple_children_iterator = tuple_children; tuple_children_iterator;
24614 tuple_children_iterator = ast_xml_node_get_next(tuple_children_iterator)) {
24615
24616
24617
24618
24619 if (strcmp(ast_xml_node_get_name(tuple_children_iterator), "status")) {
24620
24621 continue;
24622 }
24623 if (status_found == TRUE) {
24624
24625 ast_log(LOG_WARNING, "Multiple status elements found in tuple. Only one allowed\n");
24626 return FALSE;
24627 }
24628 status_found = TRUE;
24629 }
24630 return status_found;
24631 }
24632
24633
24634 static int pidf_validate_presence(struct ast_xml_doc *doc)
24635 {
24636 struct ast_xml_node *presence_node = ast_xml_get_root(doc);
24637 struct ast_xml_node *child_nodes;
24638 struct ast_xml_node *node_iterator;
24639 struct ast_xml_ns *ns;
24640 const char *entity;
24641 const char *namespace;
24642 const char presence_namespace[] = "urn:ietf:params:xml:ns:pidf";
24643
24644 if (!presence_node) {
24645 ast_log(LOG_WARNING, "Unable to retrieve root node of the XML document\n");
24646 return FALSE;
24647 }
24648
24649
24650
24651 if (strcmp(ast_xml_node_get_name(presence_node), "presence")) {
24652 ast_log(LOG_WARNING, "Root node of PIDF document is not 'presence'. Invalid\n");
24653 return FALSE;
24654 }
24655
24656
24657
24658
24659 if (!(entity = ast_xml_get_attribute(presence_node, "entity"))) {
24660 ast_log(LOG_WARNING, "Presence element of PIDF document has no 'entity' attribute\n");
24661 return FALSE;
24662 }
24663
24664 ast_xml_free_attr(entity);
24665
24666 if (!(ns = ast_xml_find_namespace(doc, presence_node, NULL))) {
24667 ast_log(LOG_WARNING, "Couldn't find default namespace...\n");
24668 return FALSE;
24669 }
24670
24671 namespace = ast_xml_get_ns_href(ns);
24672 if (ast_strlen_zero(namespace) || strcmp(namespace, presence_namespace)) {
24673 ast_log(LOG_WARNING, "PIDF document has invalid namespace value %s\n", namespace);
24674 return FALSE;
24675 }
24676
24677 if (!(child_nodes = ast_xml_node_get_children(presence_node))) {
24678 ast_log(LOG_WARNING, "PIDF document has no elements as children of 'presence'. Invalid\n");
24679 return FALSE;
24680 }
24681
24682
24683
24684
24685
24686
24687
24688
24689
24690 for (node_iterator = child_nodes; node_iterator;
24691 node_iterator = ast_xml_node_get_next(node_iterator)) {
24692 if (strcmp(ast_xml_node_get_name(node_iterator), "tuple")) {
24693
24694 continue;
24695 }
24696 if (pidf_validate_tuple(node_iterator) == FALSE) {
24697 ast_log(LOG_WARNING, "Unable to validate tuple\n");
24698 return FALSE;
24699 }
24700 }
24701
24702 return TRUE;
24703 }
24704
24705
24706
24707
24708
24709
24710
24711
24712
24713
24714
24715
24716
24717
24718
24719
24720 static int sip_pidf_validate(struct sip_request *req, struct ast_xml_doc **pidf_doc)
24721 {
24722 struct ast_xml_doc *doc;
24723 int content_length;
24724 const char *content_length_str = get_header(req, "Content-Length");
24725 const char *content_type = get_header(req, "Content-Type");
24726 char pidf_body[SIPBUFSIZE];
24727 int res;
24728
24729 if (ast_strlen_zero(content_type) || strcmp(content_type, "application/pidf+xml")) {
24730 ast_log(LOG_WARNING, "Content type is not PIDF\n");
24731 return FALSE;
24732 }
24733
24734 if (ast_strlen_zero(content_length_str)) {
24735 ast_log(LOG_WARNING, "No content length. Can't determine bounds of PIDF document\n");
24736 return FALSE;
24737 }
24738
24739 if (sscanf(content_length_str, "%30d", &content_length) != 1) {
24740 ast_log(LOG_WARNING, "Invalid content length provided\n");
24741 return FALSE;
24742 }
24743
24744 if (content_length > sizeof(pidf_body)) {
24745 ast_log(LOG_WARNING, "Content length of PIDF document truncated to %d bytes\n", (int) sizeof(pidf_body));
24746 content_length = sizeof(pidf_body);
24747 }
24748
24749 get_pidf_body(req, pidf_body, content_length);
24750
24751 if (!(doc = ast_xml_read_memory(pidf_body, content_length))) {
24752 ast_log(LOG_WARNING, "Unable to open XML PIDF document. Is it malformed?\n");
24753 return FALSE;
24754 }
24755
24756 res = pidf_validate_presence(doc);
24757 if (res == TRUE) {
24758 *pidf_doc = doc;
24759 } else {
24760 ast_xml_close(doc);
24761 }
24762 return res;
24763 }
24764
24765 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)
24766 {
24767 const char *uri = REQ_OFFSET_TO_STR(req, rlPart2);
24768 struct ast_cc_agent *agent;
24769 struct sip_cc_agent_pvt *agent_pvt;
24770 struct ast_xml_doc *pidf_doc = NULL;
24771 const char *basic_status = NULL;
24772 struct ast_xml_node *presence_node;
24773 struct ast_xml_node *presence_children;
24774 struct ast_xml_node *tuple_node;
24775 struct ast_xml_node *tuple_children;
24776 struct ast_xml_node *status_node;
24777 struct ast_xml_node *status_children;
24778 struct ast_xml_node *basic_node;
24779 int res = 0;
24780
24781 if (!((agent = find_sip_cc_agent_by_notify_uri(uri)) || (agent = find_sip_cc_agent_by_subscribe_uri(uri)))) {
24782 ast_log(LOG_WARNING, "Could not find agent using uri '%s'\n", uri);
24783 transmit_response(pvt, "412 Conditional Request Failed", req);
24784 return -1;
24785 }
24786
24787 agent_pvt = agent->private_data;
24788
24789 if (sip_pidf_validate(req, &pidf_doc) == FALSE) {
24790 res = -1;
24791 goto cc_publish_cleanup;
24792 }
24793
24794
24795
24796
24797
24798
24799
24800 presence_node = ast_xml_get_root(pidf_doc);
24801 if (!(presence_children = ast_xml_node_get_children(presence_node))) {
24802 ast_log(LOG_WARNING, "No tuples within presence element.\n");
24803 res = -1;
24804 goto cc_publish_cleanup;
24805 }
24806
24807 if (!(tuple_node = ast_xml_find_element(presence_children, "tuple", NULL, NULL))) {
24808 ast_log(LOG_NOTICE, "Couldn't find tuple node?\n");
24809 res = -1;
24810 goto cc_publish_cleanup;
24811 }
24812
24813
24814
24815
24816 tuple_children = ast_xml_node_get_children(tuple_node);
24817
24818 status_node = ast_xml_find_element(tuple_children, "status", NULL, NULL);
24819
24820 if (!(status_children = ast_xml_node_get_children(status_node))) {
24821 ast_log(LOG_WARNING, "No basic elements within status element.\n");
24822 res = -1;
24823 goto cc_publish_cleanup;
24824 }
24825
24826 if (!(basic_node = ast_xml_find_element(status_children, "basic", NULL, NULL))) {
24827 ast_log(LOG_WARNING, "Couldn't find basic node?\n");
24828 res = -1;
24829 goto cc_publish_cleanup;
24830 }
24831
24832 basic_status = ast_xml_get_text(basic_node);
24833
24834 if (ast_strlen_zero(basic_status)) {
24835 ast_log(LOG_NOTICE, "NOthing in basic node?\n");
24836 res = -1;
24837 goto cc_publish_cleanup;
24838 }
24839
24840 if (!strcmp(basic_status, "open")) {
24841 agent_pvt->is_available = TRUE;
24842 ast_cc_agent_caller_available(agent->core_id, "Received PUBLISH stating SIP caller %s is available",
24843 agent->device_name);
24844 } else if (!strcmp(basic_status, "closed")) {
24845 agent_pvt->is_available = FALSE;
24846 ast_cc_agent_caller_busy(agent->core_id, "Received PUBLISH stating SIP caller %s is busy",
24847 agent->device_name);
24848 } else {
24849 ast_log(LOG_NOTICE, "Invalid content in basic element: %s\n", basic_status);
24850 }
24851
24852 cc_publish_cleanup:
24853 if (basic_status) {
24854 ast_xml_free_text(basic_status);
24855 }
24856 if (pidf_doc) {
24857 ast_xml_close(pidf_doc);
24858 }
24859 ao2_ref(agent, -1);
24860 if (res) {
24861 transmit_response(pvt, "400 Bad Request", req);
24862 }
24863 return res;
24864 }
24865
24866 #endif
24867
24868 static int handle_sip_publish_initial(struct sip_pvt *p, struct sip_request *req, struct event_state_compositor *esc, const int expires)
24869 {
24870 struct sip_esc_entry *esc_entry = create_esc_entry(esc, req, expires);
24871 int res = 0;
24872
24873 if (!esc_entry) {
24874 transmit_response(p, "503 Internal Server Failure", req);
24875 return -1;
24876 }
24877
24878 if (esc->callbacks->initial_handler) {
24879 res = esc->callbacks->initial_handler(p, req, esc, esc_entry);
24880 }
24881
24882 if (!res) {
24883 transmit_response_with_sip_etag(p, "200 OK", req, esc_entry, 0);
24884 }
24885
24886 ao2_ref(esc_entry, -1);
24887 return res;
24888 }
24889
24890 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)
24891 {
24892 struct sip_esc_entry *esc_entry = get_esc_entry(etag, esc);
24893 int expires_ms = expires * 1000;
24894 int res = 0;
24895
24896 if (!esc_entry) {
24897 transmit_response(p, "412 Conditional Request Failed", req);
24898 return -1;
24899 }
24900
24901 AST_SCHED_REPLACE_UNREF(esc_entry->sched_id, sched, expires_ms, publish_expire, esc_entry,
24902 ao2_ref(_data, -1),
24903 ao2_ref(esc_entry, -1),
24904 ao2_ref(esc_entry, +1));
24905
24906 if (esc->callbacks->refresh_handler) {
24907 res = esc->callbacks->refresh_handler(p, req, esc, esc_entry);
24908 }
24909
24910 if (!res) {
24911 transmit_response_with_sip_etag(p, "200 OK", req, esc_entry, 1);
24912 }
24913
24914 ao2_ref(esc_entry, -1);
24915 return res;
24916 }
24917
24918 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)
24919 {
24920 struct sip_esc_entry *esc_entry = get_esc_entry(etag, esc);
24921 int expires_ms = expires * 1000;
24922 int res = 0;
24923
24924 if (!esc_entry) {
24925 transmit_response(p, "412 Conditional Request Failed", req);
24926 return -1;
24927 }
24928
24929 AST_SCHED_REPLACE_UNREF(esc_entry->sched_id, sched, expires_ms, publish_expire, esc_entry,
24930 ao2_ref(_data, -1),
24931 ao2_ref(esc_entry, -1),
24932 ao2_ref(esc_entry, +1));
24933
24934 if (esc->callbacks->modify_handler) {
24935 res = esc->callbacks->modify_handler(p, req, esc, esc_entry);
24936 }
24937
24938 if (!res) {
24939 transmit_response_with_sip_etag(p, "200 OK", req, esc_entry, 1);
24940 }
24941
24942 ao2_ref(esc_entry, -1);
24943 return res;
24944 }
24945
24946 static int handle_sip_publish_remove(struct sip_pvt *p, struct sip_request *req, struct event_state_compositor *esc, const char * const etag)
24947 {
24948 struct sip_esc_entry *esc_entry = get_esc_entry(etag, esc);
24949 int res = 0;
24950
24951 if (!esc_entry) {
24952 transmit_response(p, "412 Conditional Request Failed", req);
24953 return -1;
24954 }
24955
24956 AST_SCHED_DEL(sched, esc_entry->sched_id);
24957
24958 ao2_ref(esc_entry, -1);
24959
24960 if (esc->callbacks->remove_handler) {
24961 res = esc->callbacks->remove_handler(p, req, esc, esc_entry);
24962 }
24963
24964 if (!res) {
24965 transmit_response_with_sip_etag(p, "200 OK", req, esc_entry, 1);
24966 }
24967
24968
24969 ao2_unlink(esc->compositor, esc_entry);
24970 ao2_ref(esc_entry, -1);
24971 return res;
24972 }
24973
24974 static int handle_request_publish(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const uint32_t seqno, const char *uri)
24975 {
24976 const char *etag = get_header(req, "SIP-If-Match");
24977 const char *event = get_header(req, "Event");
24978 struct event_state_compositor *esc;
24979 enum sip_publish_type publish_type;
24980 const char *expires_str = get_header(req, "Expires");
24981 int expires_int;
24982 int auth_result;
24983 int handler_result = -1;
24984
24985 if (ast_strlen_zero(event)) {
24986 transmit_response(p, "489 Bad Event", req);
24987 pvt_set_needdestroy(p, "missing Event: header");
24988 return -1;
24989 }
24990
24991 if (!(esc = get_esc(event))) {
24992 transmit_response(p, "489 Bad Event", req);
24993 pvt_set_needdestroy(p, "unknown event package in publish");
24994 return -1;
24995 }
24996
24997 auth_result = check_user(p, req, SIP_PUBLISH, uri, XMIT_RELIABLE, addr);
24998 if (auth_result == AUTH_CHALLENGE_SENT) {
24999 p->lastinvite = seqno;
25000 return 0;
25001 } else if (auth_result < 0) {
25002 if (auth_result == AUTH_FAKE_AUTH) {
25003 ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", get_header(req, "From"));
25004 transmit_fake_auth_response(p, SIP_INVITE, req, XMIT_RELIABLE);
25005 } else {
25006 ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", get_header(req, "From"));
25007 transmit_response_reliable(p, "403 Forbidden", req);
25008 }
25009 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
25010 ast_string_field_set(p, theirtag, NULL);
25011 return 0;
25012 } else if (auth_result == AUTH_SUCCESSFUL && p->lastinvite) {
25013
25014 __sip_ack(p, p->lastinvite, 1, 0);
25015 }
25016
25017 publish_type = determine_sip_publish_type(req, event, etag, expires_str, &expires_int);
25018
25019 if (expires_int > max_expiry) {
25020 expires_int = max_expiry;
25021 } else if (expires_int < min_expiry && expires_int > 0) {
25022 transmit_response_with_minexpires(p, "423 Interval too small", req);
25023 pvt_set_needdestroy(p, "Expires is less that the min expires allowed.");
25024 return 0;
25025 }
25026 p->expiry = expires_int;
25027
25028
25029
25030
25031 switch (publish_type) {
25032 case SIP_PUBLISH_UNKNOWN:
25033 transmit_response(p, "400 Bad Request", req);
25034 break;
25035 case SIP_PUBLISH_INITIAL:
25036 handler_result = handle_sip_publish_initial(p, req, esc, expires_int);
25037 break;
25038 case SIP_PUBLISH_REFRESH:
25039 handler_result = handle_sip_publish_refresh(p, req, esc, etag, expires_int);
25040 break;
25041 case SIP_PUBLISH_MODIFY:
25042 handler_result = handle_sip_publish_modify(p, req, esc, etag, expires_int);
25043 break;
25044 case SIP_PUBLISH_REMOVE:
25045 handler_result = handle_sip_publish_remove(p, req, esc, etag);
25046 break;
25047 default:
25048 transmit_response(p, "400 Impossible Condition", req);
25049 break;
25050 }
25051 if (!handler_result && p->expiry > 0) {
25052 sip_scheddestroy(p, (p->expiry + 10) * 1000);
25053 } else {
25054 pvt_set_needdestroy(p, "forcing expiration");
25055 }
25056
25057 return handler_result;
25058 }
25059
25060
25061
25062
25063
25064
25065
25066 static void add_peer_mwi_subs(struct sip_peer *peer)
25067 {
25068 struct sip_mailbox *mailbox;
25069
25070 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
25071 if (mailbox->event_sub) {
25072 ast_event_unsubscribe(mailbox->event_sub);
25073 }
25074
25075 mailbox->event_sub = ast_event_subscribe(AST_EVENT_MWI, mwi_event_cb, "SIP mbox event", peer,
25076 AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox->mailbox,
25077 AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, S_OR(mailbox->context, "default"),
25078 AST_EVENT_IE_END);
25079 }
25080 }
25081
25082 static int handle_cc_subscribe(struct sip_pvt *p, struct sip_request *req)
25083 {
25084 const char *uri = REQ_OFFSET_TO_STR(req, rlPart2);
25085 char *param_separator;
25086 struct ast_cc_agent *agent;
25087 struct sip_cc_agent_pvt *agent_pvt;
25088 const char *expires_str = get_header(req, "Expires");
25089 int expires = -1;
25090
25091 if (!ast_strlen_zero(expires_str)) {
25092 sscanf(expires_str, "%d", &expires);
25093 }
25094
25095 if ((param_separator = strchr(uri, ';'))) {
25096 *param_separator = '\0';
25097 }
25098
25099 p->subscribed = CALL_COMPLETION;
25100
25101 if (!(agent = find_sip_cc_agent_by_subscribe_uri(uri))) {
25102 if (!expires) {
25103
25104
25105
25106
25107
25108
25109 transmit_response(p, "200 OK", req);
25110 return 0;
25111 }
25112 ast_log(LOG_WARNING, "Invalid URI '%s' in CC subscribe\n", uri);
25113 transmit_response(p, "404 Not Found", req);
25114 return -1;
25115 }
25116
25117 agent_pvt = agent->private_data;
25118
25119 if (!expires) {
25120
25121
25122
25123 ast_cc_failed(agent->core_id, "CC is being canceled by %s", agent->device_name);
25124 transmit_response(p, "200 OK", req);
25125 ao2_ref(agent, -1);
25126 return 0;
25127 }
25128
25129 agent_pvt->subscribe_pvt = dialog_ref(p, "SIP CC agent gains reference to subscription dialog");
25130 ast_cc_agent_accept_request(agent->core_id, "SIP caller %s has requested CC via SUBSCRIBE",
25131 agent->device_name);
25132
25133
25134
25135
25136 ao2_ref(agent, -1);
25137 return 0;
25138 }
25139
25140
25141 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e)
25142 {
25143 int gotdest = 0;
25144 int res = 0;
25145 int firststate;
25146 struct sip_peer *authpeer = NULL;
25147 const char *eventheader = get_header(req, "Event");
25148 int resubscribe = (p->subscribed != NONE) && !req->ignore;
25149 char *event_end;
25150 ptrdiff_t event_len = 0;
25151
25152 if (p->initreq.headers) {
25153
25154 if (p->initreq.method != SIP_SUBSCRIBE) {
25155
25156
25157 transmit_response(p, "403 Forbidden (within dialog)", req);
25158
25159 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);
25160 return 0;
25161 } else if (req->debug) {
25162 if (resubscribe)
25163 ast_debug(1, "Got a re-subscribe on existing subscription %s\n", p->callid);
25164 else
25165 ast_debug(1, "Got a new subscription %s (possibly with auth) or retransmission\n", p->callid);
25166 }
25167 }
25168
25169
25170
25171
25172 if (!sip_cfg.allowsubscribe) {
25173 transmit_response(p, "403 Forbidden (policy)", req);
25174 pvt_set_needdestroy(p, "forbidden");
25175 return 0;
25176 }
25177
25178 if (!req->ignore && !resubscribe) {
25179 const char *to = get_header(req, "To");
25180 char totag[128];
25181 set_pvt_allowed_methods(p, req);
25182
25183
25184 if (!ast_strlen_zero(to) && gettag(req, "To", totag, sizeof(totag))) {
25185 if (req->debug)
25186 ast_verbose("Received resubscription for a dialog we no longer know about. Telling remote side to subscribe again.\n");
25187 transmit_response(p, "481 Subscription does not exist", req);
25188 pvt_set_needdestroy(p, "subscription does not exist");
25189 return 0;
25190 }
25191
25192
25193 if (req->debug)
25194 ast_verbose("Creating new subscription\n");
25195
25196 copy_request(&p->initreq, req);
25197 if (sipdebug)
25198 ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
25199 check_via(p, req);
25200 build_route(p, req, 0, 0);
25201 } else if (req->debug && req->ignore)
25202 ast_verbose("Ignoring this SUBSCRIBE request\n");
25203
25204
25205 if (ast_strlen_zero(eventheader)) {
25206 transmit_response(p, "489 Bad Event", req);
25207 ast_debug(2, "Received SIP subscribe for unknown event package: <none>\n");
25208 pvt_set_needdestroy(p, "unknown event package in subscribe");
25209 return 0;
25210 }
25211
25212 event_end = strchr(eventheader, ';');
25213 if (event_end) {
25214 event_len = event_end - eventheader;
25215 }
25216
25217
25218
25219
25220 if (p->subscribed == NONE || resubscribe) {
25221 res = check_user_full(p, req, SIP_SUBSCRIBE, e, 0, addr, &authpeer);
25222
25223
25224 if (res == AUTH_CHALLENGE_SENT)
25225 return 0;
25226 if (res != AUTH_SUCCESSFUL) {
25227 if (res == AUTH_FAKE_AUTH) {
25228 ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", get_header(req, "From"));
25229 transmit_fake_auth_response(p, SIP_SUBSCRIBE, req, XMIT_UNRELIABLE);
25230 } else {
25231 ast_log(LOG_NOTICE, "Failed to authenticate device %s for SUBSCRIBE\n", get_header(req, "From"));
25232 transmit_response_reliable(p, "403 Forbidden", req);
25233 }
25234
25235 pvt_set_needdestroy(p, "authentication failed");
25236 return 0;
25237 }
25238 }
25239
25240
25241
25242
25243
25244
25245 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
25246 transmit_response(p, "403 Forbidden (policy)", req);
25247 pvt_set_needdestroy(p, "subscription not allowed");
25248 if (authpeer) {
25249 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 1)");
25250 }
25251 return 0;
25252 }
25253
25254 if (strncmp(eventheader, "message-summary", MAX(event_len, 15)) && strncmp(eventheader, "call-completion", MAX(event_len, 15))) {
25255
25256 gotdest = get_destination(p, NULL, NULL);
25257 }
25258
25259
25260 parse_ok_contact(p, req);
25261
25262 build_contact(p);
25263 if (gotdest != SIP_GET_DEST_EXTEN_FOUND) {
25264 if (gotdest == SIP_GET_DEST_INVALID_URI) {
25265 transmit_response(p, "416 Unsupported URI scheme", req);
25266 } else {
25267 transmit_response(p, "404 Not Found", req);
25268 }
25269 pvt_set_needdestroy(p, "subscription target not found");
25270 if (authpeer) {
25271 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
25272 }
25273 return 0;
25274 }
25275
25276
25277 if (ast_strlen_zero(p->tag))
25278 make_our_tag(p);
25279
25280 if (!strncmp(eventheader, "presence", MAX(event_len, 8)) || !strncmp(eventheader, "dialog", MAX(event_len, 6))) {
25281 unsigned int pidf_xml;
25282 const char *accept;
25283 int start = 0;
25284 enum subscriptiontype subscribed = NONE;
25285 const char *unknown_acceptheader = NULL;
25286
25287
25288 accept = __get_header(req, "Accept", &start);
25289 while ((subscribed == NONE) && !ast_strlen_zero(accept)) {
25290 pidf_xml = strstr(accept, "application/pidf+xml") ? 1 : 0;
25291
25292
25293
25294 if (pidf_xml && strstr(p->useragent, "Polycom")) {
25295 subscribed = XPIDF_XML;
25296 } else if (pidf_xml) {
25297 subscribed = PIDF_XML;
25298 } else if (strstr(accept, "application/dialog-info+xml")) {
25299 subscribed = DIALOG_INFO_XML;
25300
25301 } else if (strstr(accept, "application/cpim-pidf+xml")) {
25302 subscribed = CPIM_PIDF_XML;
25303 } else if (strstr(accept, "application/xpidf+xml")) {
25304 subscribed = XPIDF_XML;
25305 } else {
25306 unknown_acceptheader = accept;
25307 }
25308
25309 accept = __get_header(req, "Accept", &start);
25310 }
25311
25312 if (!start) {
25313 if (p->subscribed == NONE) {
25314 transmit_response(p, "489 Bad Event", req);
25315 ast_log(LOG_WARNING,"SUBSCRIBE failure: no Accept header: pvt: "
25316 "stateid: %d, laststate: %d, dialogver: %u, subscribecont: "
25317 "'%s', subscribeuri: '%s'\n",
25318 p->stateid,
25319 p->laststate,
25320 p->dialogver,
25321 p->subscribecontext,
25322 p->subscribeuri);
25323 pvt_set_needdestroy(p, "no Accept header");
25324 if (authpeer) {
25325 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
25326 }
25327 return 0;
25328 }
25329
25330
25331 } else if (subscribed == NONE) {
25332
25333 char mybuf[200];
25334 if (!ast_strlen_zero(unknown_acceptheader)) {
25335 snprintf(mybuf, sizeof(mybuf), "489 Bad Event (format %s)", unknown_acceptheader);
25336 } else {
25337 snprintf(mybuf, sizeof(mybuf), "489 Bad Event");
25338 }
25339 transmit_response(p, mybuf, req);
25340 ast_log(LOG_WARNING,"SUBSCRIBE failure: unrecognized format:"
25341 "'%s' pvt: subscribed: %d, stateid: %d, laststate: %d,"
25342 "dialogver: %u, subscribecont: '%s', subscribeuri: '%s'\n",
25343 unknown_acceptheader,
25344 (int)p->subscribed,
25345 p->stateid,
25346 p->laststate,
25347 p->dialogver,
25348 p->subscribecontext,
25349 p->subscribeuri);
25350 pvt_set_needdestroy(p, "unrecognized format");
25351 if (authpeer) {
25352 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
25353 }
25354 return 0;
25355 } else {
25356 p->subscribed = subscribed;
25357 }
25358 } else if (!strncmp(eventheader, "message-summary", MAX(event_len, 15))) {
25359 int start = 0;
25360 int found_supported = 0;
25361 const char *acceptheader;
25362
25363 acceptheader = __get_header(req, "Accept", &start);
25364 while (!found_supported && !ast_strlen_zero(acceptheader)) {
25365 found_supported = strcmp(acceptheader, "application/simple-message-summary") ? 0 : 1;
25366 if (!found_supported && (option_debug > 2)) {
25367 ast_log(LOG_DEBUG, "Received SIP mailbox subscription for unknown format: %s\n", acceptheader);
25368 }
25369 acceptheader = __get_header(req, "Accept", &start);
25370 }
25371 if (start && !found_supported) {
25372
25373 transmit_response(p, "406 Not Acceptable", req);
25374 ast_debug(2, "Received SIP mailbox subscription for unknown format: %s\n", acceptheader);
25375 pvt_set_needdestroy(p, "unknown format");
25376 if (authpeer) {
25377 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 3)");
25378 }
25379 return 0;
25380 }
25381
25382
25383
25384
25385
25386 if (!authpeer || AST_LIST_EMPTY(&authpeer->mailboxes)) {
25387 if (!authpeer) {
25388 transmit_response(p, "404 Not found", req);
25389 } else {
25390 transmit_response(p, "404 Not found (no mailbox)", req);
25391 ast_log(LOG_NOTICE, "Received SIP subscribe for peer without mailbox: %s\n", S_OR(authpeer->name, ""));
25392 }
25393 pvt_set_needdestroy(p, "received 404 response");
25394 if (authpeer) {
25395 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 3)");
25396 }
25397 return 0;
25398 }
25399
25400 p->subscribed = MWI_NOTIFICATION;
25401 if (ast_test_flag(&authpeer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY)) {
25402 ao2_unlock(p);
25403 add_peer_mwi_subs(authpeer);
25404 ao2_lock(p);
25405 }
25406 if (authpeer->mwipvt != p) {
25407
25408 if (authpeer->mwipvt) {
25409 dialog_unlink_all(authpeer->mwipvt);
25410 authpeer->mwipvt = dialog_unref(authpeer->mwipvt, "unref dialog authpeer->mwipvt");
25411 }
25412 authpeer->mwipvt = dialog_ref(p, "setting peers' mwipvt to p");
25413 }
25414 if (p->relatedpeer != authpeer) {
25415 if (p->relatedpeer) {
25416 unref_peer(p->relatedpeer, "Unref previously stored relatedpeer ptr");
25417 }
25418 p->relatedpeer = ref_peer(authpeer, "setting dialog's relatedpeer pointer");
25419 }
25420
25421 } else if (!strncmp(eventheader, "call-completion", MAX(event_len, 15))) {
25422 handle_cc_subscribe(p, req);
25423 } else {
25424 transmit_response(p, "489 Bad Event", req);
25425 ast_debug(2, "Received SIP subscribe for unknown event package: %s\n", eventheader);
25426 pvt_set_needdestroy(p, "unknown event package");
25427 if (authpeer) {
25428 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 5)");
25429 }
25430 return 0;
25431 }
25432
25433
25434 if (p->subscribed != MWI_NOTIFICATION && p->subscribed != CALL_COMPLETION && !resubscribe) {
25435 if (p->stateid != -1) {
25436 ast_extension_state_del(p->stateid, cb_extensionstate);
25437 }
25438 dialog_ref(p, "copying dialog ptr into extension state struct");
25439 p->stateid = ast_extension_state_add_destroy(p->context, p->exten,
25440 cb_extensionstate, cb_extensionstate_destroy, p);
25441 if (p->stateid == -1) {
25442 dialog_unref(p, "copying dialog ptr into extension state struct failed");
25443 }
25444 }
25445
25446 if (!req->ignore) {
25447 p->lastinvite = seqno;
25448 }
25449 if (!p->needdestroy) {
25450 p->expiry = atoi(get_header(req, "Expires"));
25451
25452
25453 if (p->expiry > max_expiry) {
25454 p->expiry = max_expiry;
25455 } else if (p->expiry < min_expiry && p->expiry > 0) {
25456 transmit_response_with_minexpires(p, "423 Interval too small", req);
25457 ast_log(LOG_WARNING, "Received subscription for extension \"%s\" context \"%s\" "
25458 "with Expire header less that 'minexpire' limit. Received \"Expire: %d\" min is %d\n",
25459 p->exten, p->context, p->expiry, min_expiry);
25460 pvt_set_needdestroy(p, "Expires is less that the min expires allowed.");
25461 if (authpeer) {
25462 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 6)");
25463 }
25464 return 0;
25465 }
25466
25467 if (sipdebug) {
25468 const char *action = p->expiry > 0 ? "Adding" : "Removing";
25469 if (p->subscribed == MWI_NOTIFICATION && p->relatedpeer) {
25470 ast_debug(2, "%s subscription for mailbox notification - peer %s\n",
25471 action, p->relatedpeer->name);
25472 } else if (p->subscribed == CALL_COMPLETION) {
25473 ast_debug(2, "%s CC subscription for peer %s\n", action, p->username);
25474 } else {
25475 ast_debug(2, "%s subscription for extension %s context %s for peer %s\n",
25476 action, p->exten, p->context, p->username);
25477 }
25478 }
25479 if (p->autokillid > -1 && sip_cancel_destroy(p))
25480 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
25481 if (p->expiry > 0)
25482 sip_scheddestroy(p, (p->expiry + 10) * 1000);
25483
25484 if (p->subscribed == MWI_NOTIFICATION) {
25485 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
25486 transmit_response(p, "200 OK", req);
25487 if (p->relatedpeer) {
25488 struct sip_peer *peer = p->relatedpeer;
25489 ref_peer(peer, "ensure a peer ref is held during MWI sending");
25490 ao2_unlock(p);
25491 sip_send_mwi_to_peer(peer, 0);
25492 ao2_lock(p);
25493 unref_peer(peer, "release a peer ref now that MWI is sent");
25494 }
25495 } else if (p->subscribed != CALL_COMPLETION) {
25496 sip_pvt_unlock(p);
25497 firststate = ast_extension_state(NULL, p->context, p->exten);
25498 sip_pvt_lock(p);
25499
25500 if (firststate < 0) {
25501 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));
25502 transmit_response(p, "404 Not found", req);
25503 pvt_set_needdestroy(p, "no extension for SUBSCRIBE");
25504 if (authpeer) {
25505 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 6)");
25506 }
25507 return 0;
25508 }
25509 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
25510 transmit_response(p, "200 OK", req);
25511 transmit_state_notify(p, firststate, 1, FALSE);
25512 append_history(p, "Subscribestatus", "%s", ast_extension_state2str(firststate));
25513
25514 ast_string_field_build(p, subscribeuri, "%s@%s", p->exten, p->context);
25515
25516
25517 }
25518 if (!p->expiry) {
25519 pvt_set_needdestroy(p, "forcing expiration");
25520 }
25521 }
25522
25523 if (authpeer) {
25524 unref_peer(authpeer, "unref pointer into (*authpeer)");
25525 }
25526 return 1;
25527 }
25528
25529
25530 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e)
25531 {
25532 enum check_auth_result res;
25533
25534
25535
25536 if (p->initreq.headers && p->initreq.method != SIP_REGISTER) {
25537 ast_log(LOG_WARNING, "Ignoring spurious REGISTER with Call-ID: %s\n", p->callid);
25538 return -1;
25539 }
25540
25541
25542 copy_request(&p->initreq, req);
25543 if (sipdebug)
25544 ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
25545 check_via(p, req);
25546 if ((res = register_verify(p, addr, req, e)) < 0) {
25547 const char *reason;
25548
25549 switch (res) {
25550 case AUTH_SECRET_FAILED:
25551 reason = "Wrong password";
25552 break;
25553 case AUTH_USERNAME_MISMATCH:
25554 reason = "Username/auth name mismatch";
25555 break;
25556 case AUTH_NOT_FOUND:
25557 reason = "No matching peer found";
25558 break;
25559 case AUTH_UNKNOWN_DOMAIN:
25560 reason = "Not a local domain";
25561 break;
25562 case AUTH_PEER_NOT_DYNAMIC:
25563 reason = "Peer is not supposed to register";
25564 break;
25565 case AUTH_ACL_FAILED:
25566 reason = "Device does not match ACL";
25567 break;
25568 case AUTH_BAD_TRANSPORT:
25569 reason = "Device not configured to use this transport type";
25570 break;
25571 default:
25572 reason = "Unknown failure";
25573 break;
25574 }
25575 ast_log(LOG_NOTICE, "Registration from '%s' failed for '%s' - %s\n",
25576 get_header(req, "To"), ast_sockaddr_stringify(addr),
25577 reason);
25578 append_history(p, "RegRequest", "Failed : Account %s : %s", get_header(req, "To"), reason);
25579 } else {
25580 req->authenticated = 1;
25581 append_history(p, "RegRequest", "Succeeded : Account %s", get_header(req, "To"));
25582 }
25583
25584 if (res < 1) {
25585
25586
25587 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
25588 }
25589 return res;
25590 }
25591
25592
25593
25594
25595
25596
25597
25598
25599 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int *recount, int *nounlock)
25600 {
25601
25602
25603 const char *cmd;
25604 const char *cseq;
25605 const char *useragent;
25606 const char *via;
25607 const char *callid;
25608 int via_pos = 0;
25609 uint32_t seqno;
25610 int len;
25611 int respid;
25612 int res = 0;
25613 int debug = sip_debug_test_pvt(p);
25614 const char *e;
25615 int error = 0;
25616 int oldmethod = p->method;
25617 int acked = 0;
25618
25619
25620
25621
25622 cseq = get_header(req, "Cseq");
25623 cmd = REQ_OFFSET_TO_STR(req, header[0]);
25624
25625 via = __get_header(req, "Via", &via_pos);
25626
25627 callid = get_header(req, "Call-ID");
25628
25629
25630 if (ast_strlen_zero(cmd) || ast_strlen_zero(cseq) || ast_strlen_zero(via)) {
25631 ast_log(LOG_ERROR, "Dropping this SIP message with Call-ID '%s', it's incomplete.\n", callid);
25632 error = 1;
25633 }
25634 if (!error && sscanf(cseq, "%30u%n", &seqno, &len) != 1) {
25635 ast_log(LOG_ERROR, "No seqno in '%s'. Dropping incomplete message.\n", cmd);
25636 error = 1;
25637 }
25638 if (error) {
25639 if (!p->initreq.headers) {
25640 pvt_set_needdestroy(p, "no headers");
25641 }
25642 return -1;
25643 }
25644
25645
25646 cmd = REQ_OFFSET_TO_STR(req, rlPart1);
25647 e = ast_skip_blanks(REQ_OFFSET_TO_STR(req, rlPart2));
25648
25649
25650 useragent = get_header(req, "User-Agent");
25651 if (!ast_strlen_zero(useragent))
25652 ast_string_field_set(p, useragent, useragent);
25653
25654
25655 if (req->method == SIP_RESPONSE) {
25656
25657
25658
25659
25660
25661
25662 if (ast_strlen_zero(e)) {
25663 return 0;
25664 }
25665 if (sscanf(e, "%30d %n", &respid, &len) != 1) {
25666 ast_log(LOG_WARNING, "Invalid response: '%s'\n", e);
25667 return 0;
25668 }
25669 if (respid <= 0) {
25670 ast_log(LOG_WARNING, "Invalid SIP response code: '%d'\n", respid);
25671 return 0;
25672 }
25673
25674
25675
25676 if (!ast_strlen_zero(__get_header(req, "via", &via_pos))) {
25677 ast_log(LOG_WARNING, "Misrouted SIP response '%s' with Call-ID '%s', too many vias\n", e, callid);
25678 return 0;
25679 }
25680 if (p->ocseq && (p->ocseq < seqno)) {
25681 ast_debug(1, "Ignoring out of order response %u (expecting %u)\n", seqno, p->ocseq);
25682 return -1;
25683 } else {
25684 char causevar[256], causeval[256];
25685
25686 if ((respid == 200) || ((respid >= 300) && (respid <= 399))) {
25687 extract_uri(p, req);
25688 }
25689
25690 handle_response(p, respid, e + len, req, seqno);
25691
25692 if (global_store_sip_cause && p->owner) {
25693 struct ast_channel *owner = p->owner;
25694
25695 snprintf(causevar, sizeof(causevar), "MASTER_CHANNEL(HASH(SIP_CAUSE,%s))", owner->name);
25696 snprintf(causeval, sizeof(causeval), "SIP %s", REQ_OFFSET_TO_STR(req, rlPart2));
25697
25698 ast_channel_ref(owner);
25699 sip_pvt_unlock(p);
25700 ast_channel_unlock(owner);
25701 *nounlock = 1;
25702 pbx_builtin_setvar_helper(owner, causevar, causeval);
25703 ast_channel_unref(owner);
25704 sip_pvt_lock(p);
25705 }
25706 }
25707 return 0;
25708 }
25709
25710
25711
25712
25713
25714 p->method = req->method;
25715 ast_debug(4, "**** Received %s (%d) - Command in SIP %s\n", sip_methods[p->method].text, sip_methods[p->method].id, cmd);
25716
25717 if (p->icseq && (p->icseq > seqno) ) {
25718 if (p->pendinginvite && seqno == p->pendinginvite && (req->method == SIP_ACK || req->method == SIP_CANCEL)) {
25719 ast_debug(2, "Got CANCEL or ACK on INVITE with transactions in between.\n");
25720 } else {
25721 ast_debug(1, "Ignoring too old SIP packet packet %u (expecting >= %u)\n", seqno, p->icseq);
25722 if (req->method == SIP_INVITE) {
25723 unsigned int ran = (ast_random() % 10) + 1;
25724 char seconds[4];
25725 snprintf(seconds, sizeof(seconds), "%u", ran);
25726 transmit_response_with_retry_after(p, "500 Server error", req, seconds);
25727 } else if (req->method != SIP_ACK) {
25728 transmit_response(p, "500 Server error", req);
25729 }
25730 return -1;
25731 }
25732 } else if (p->icseq &&
25733 p->icseq == seqno &&
25734 req->method != SIP_ACK &&
25735 (p->method != SIP_CANCEL || p->alreadygone)) {
25736
25737
25738
25739 req->ignore = 1;
25740 ast_debug(3, "Ignoring SIP message because of retransmit (%s Seqno %u, ours %u)\n", sip_methods[p->method].text, p->icseq, seqno);
25741 }
25742
25743
25744
25745 if (!p->pendinginvite && (req->method == SIP_CANCEL)) {
25746 transmit_response(p, "481 Call/Transaction Does Not Exist", req);
25747 return res;
25748 }
25749
25750 if (seqno >= p->icseq)
25751
25752
25753
25754 p->icseq = seqno;
25755
25756
25757 if (ast_strlen_zero(p->theirtag)) {
25758 char tag[128];
25759
25760 gettag(req, "From", tag, sizeof(tag));
25761 ast_string_field_set(p, theirtag, tag);
25762 }
25763 snprintf(p->lastmsg, sizeof(p->lastmsg), "Rx: %s", cmd);
25764
25765 if (sip_cfg.pedanticsipchecking) {
25766
25767
25768
25769
25770 if (!p->initreq.headers && req->has_to_tag) {
25771
25772 if (!req->ignore && req->method == SIP_INVITE) {
25773
25774
25775
25776
25777
25778
25779 char totag[128];
25780 gettag(req, "To", totag, sizeof(totag));
25781 ast_string_field_set(p, tag, totag);
25782 p->pendinginvite = p->icseq;
25783 transmit_response_reliable(p, "481 Call/Transaction Does Not Exist", req);
25784
25785 return res;
25786 } else if (req->method != SIP_ACK) {
25787 transmit_response(p, "481 Call/Transaction Does Not Exist", req);
25788 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
25789 return res;
25790 }
25791
25792 }
25793 }
25794
25795 if (!e && (p->method == SIP_INVITE || p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER || p->method == SIP_NOTIFY || p->method == SIP_PUBLISH)) {
25796 transmit_response(p, "400 Bad request", req);
25797 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
25798 return -1;
25799 }
25800
25801
25802 switch (p->method) {
25803 case SIP_OPTIONS:
25804 res = handle_request_options(p, req, addr, e);
25805 break;
25806 case SIP_INVITE:
25807 res = handle_request_invite(p, req, debug, seqno, addr, recount, e, nounlock);
25808 break;
25809 case SIP_REFER:
25810 res = handle_request_refer(p, req, debug, seqno, nounlock);
25811 break;
25812 case SIP_CANCEL:
25813 res = handle_request_cancel(p, req);
25814 break;
25815 case SIP_BYE:
25816 res = handle_request_bye(p, req);
25817 break;
25818 case SIP_MESSAGE:
25819 res = handle_request_message(p, req);
25820 break;
25821 case SIP_PUBLISH:
25822 res = handle_request_publish(p, req, addr, seqno, e);
25823 break;
25824 case SIP_SUBSCRIBE:
25825 res = handle_request_subscribe(p, req, addr, seqno, e);
25826 break;
25827 case SIP_REGISTER:
25828 res = handle_request_register(p, req, addr, e);
25829 break;
25830 case SIP_INFO:
25831 if (req->debug)
25832 ast_verbose("Receiving INFO!\n");
25833 if (!req->ignore)
25834 handle_request_info(p, req);
25835 else
25836 transmit_response(p, "200 OK", req);
25837 break;
25838 case SIP_NOTIFY:
25839 res = handle_request_notify(p, req, addr, seqno, e);
25840 break;
25841 case SIP_UPDATE:
25842 res = handle_request_update(p, req);
25843 break;
25844 case SIP_ACK:
25845
25846 if (seqno == p->pendinginvite) {
25847 p->invitestate = INV_TERMINATED;
25848 p->pendinginvite = 0;
25849 acked = __sip_ack(p, seqno, 1 , 0);
25850 if (find_sdp(req)) {
25851 if (process_sdp(p, req, SDP_T38_NONE)) {
25852 return -1;
25853 }
25854 if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
25855 ast_queue_control(p->owner, AST_CONTROL_SRCCHANGE);
25856 }
25857 }
25858 check_pendings(p);
25859 } else if (p->glareinvite == seqno) {
25860
25861 p->glareinvite = 0;
25862 acked = __sip_ack(p, seqno, 1, 0);
25863 }
25864 if (!acked) {
25865
25866
25867 p->method = oldmethod;
25868 }
25869 if (!p->lastinvite && ast_strlen_zero(p->randdata)) {
25870 pvt_set_needdestroy(p, "unmatched ACK");
25871 }
25872 break;
25873 default:
25874 transmit_response_with_allow(p, "501 Method Not Implemented", req, 0);
25875 ast_log(LOG_NOTICE, "Unknown SIP command '%s' from '%s'\n",
25876 cmd, ast_sockaddr_stringify(&p->sa));
25877
25878 if (!p->initreq.headers) {
25879 pvt_set_needdestroy(p, "unimplemented method");
25880 }
25881 break;
25882 }
25883 return res;
25884 }
25885
25886
25887
25888
25889
25890
25891 static int sipsock_read(int *id, int fd, short events, void *ignore)
25892 {
25893 struct sip_request req;
25894 struct ast_sockaddr addr;
25895 int res;
25896 static char readbuf[65535];
25897
25898 memset(&req, 0, sizeof(req));
25899 res = ast_recvfrom(fd, readbuf, sizeof(readbuf) - 1, 0, &addr);
25900 if (res < 0) {
25901 #if !defined(__FreeBSD__)
25902 if (errno == EAGAIN)
25903 ast_log(LOG_NOTICE, "SIP: Received packet with bad UDP checksum\n");
25904 else
25905 #endif
25906 if (errno != ECONNREFUSED)
25907 ast_log(LOG_WARNING, "Recv error: %s\n", strerror(errno));
25908 return 1;
25909 }
25910
25911 readbuf[res] = '\0';
25912
25913 if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
25914 return 1;
25915 }
25916
25917 if (ast_str_set(&req.data, 0, "%s", readbuf) == AST_DYNSTR_BUILD_FAILED) {
25918 return -1;
25919 }
25920
25921 req.socket.fd = sipsock;
25922 set_socket_transport(&req.socket, SIP_TRANSPORT_UDP);
25923 req.socket.tcptls_session = NULL;
25924 req.socket.port = htons(ast_sockaddr_port(&bindaddr));
25925
25926 handle_request_do(&req, &addr);
25927 deinit_req(&req);
25928
25929 return 1;
25930 }
25931
25932
25933
25934
25935
25936 static int handle_request_do(struct sip_request *req, struct ast_sockaddr *addr)
25937 {
25938 struct sip_pvt *p;
25939 struct ast_channel *owner_chan_ref = NULL;
25940 int recount = 0;
25941 int nounlock = 0;
25942
25943 if (sip_debug_test_addr(addr))
25944 req->debug = 1;
25945 if (sip_cfg.pedanticsipchecking)
25946 lws2sws(req->data);
25947 if (req->debug) {
25948 ast_verbose("\n<--- SIP read from %s:%s --->\n%s\n<------------->\n",
25949 get_transport(req->socket.type), ast_sockaddr_stringify(addr), ast_str_buffer(req->data));
25950 }
25951
25952 if (parse_request(req) == -1) {
25953 ast_str_reset(req->data);
25954 return 1;
25955 }
25956 req->method = find_sip_method(REQ_OFFSET_TO_STR(req, rlPart1));
25957
25958 if (req->debug)
25959 ast_verbose("--- (%d headers %d lines)%s ---\n", req->headers, req->lines, (req->headers + req->lines == 0) ? " Nat keepalive" : "");
25960
25961 if (req->headers < 2) {
25962 ast_str_reset(req->data);
25963 return 1;
25964 }
25965
25966
25967 ast_mutex_lock(&netlock);
25968
25969
25970 p = find_call(req, addr, req->method);
25971 if (p == NULL) {
25972 ast_debug(1, "Invalid SIP message - rejected , no callid, len %zu\n", ast_str_strlen(req->data));
25973 ast_mutex_unlock(&netlock);
25974 return 1;
25975 }
25976
25977
25978
25979 owner_chan_ref = sip_pvt_lock_full(p);
25980
25981 copy_socket_data(&p->socket, &req->socket);
25982 ast_sockaddr_copy(&p->recv, addr);
25983
25984
25985 if (p->owner) {
25986 req->authenticated = 1;
25987 }
25988
25989 if (p->do_history)
25990 append_history(p, "Rx", "%s / %s / %s", ast_str_buffer(req->data), get_header(req, "CSeq"), REQ_OFFSET_TO_STR(req, rlPart2));
25991
25992 if (handle_incoming(p, req, addr, &recount, &nounlock) == -1) {
25993
25994 ast_debug(1, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
25995 }
25996
25997 if (recount) {
25998 ast_update_use_count();
25999 }
26000
26001 if (p->owner && !nounlock) {
26002 ast_channel_unlock(p->owner);
26003 }
26004 if (owner_chan_ref) {
26005 ast_channel_unref(owner_chan_ref);
26006 }
26007 sip_pvt_unlock(p);
26008 ao2_t_ref(p, -1, "throw away dialog ptr from find_call at end of routine");
26009 ast_mutex_unlock(&netlock);
26010
26011 return 1;
26012 }
26013
26014
26015
26016
26017
26018
26019
26020 static int sip_standard_port(enum sip_transport type, int port)
26021 {
26022 if (type & SIP_TRANSPORT_TLS)
26023 return port == STANDARD_TLS_PORT;
26024 else
26025 return port == STANDARD_SIP_PORT;
26026 }
26027
26028 static int threadinfo_locate_cb(void *obj, void *arg, int flags)
26029 {
26030 struct sip_threadinfo *th = obj;
26031 struct ast_sockaddr *s = arg;
26032
26033 if (!ast_sockaddr_cmp(s, &th->tcptls_session->remote_address)) {
26034 return CMP_MATCH | CMP_STOP;
26035 }
26036
26037 return 0;
26038 }
26039
26040
26041
26042
26043
26044
26045 static struct ast_tcptls_session_instance *sip_tcp_locate(struct ast_sockaddr *s)
26046 {
26047 struct sip_threadinfo *th;
26048 struct ast_tcptls_session_instance *tcptls_instance = NULL;
26049
26050 if ((th = ao2_callback(threadt, 0, threadinfo_locate_cb, s))) {
26051 tcptls_instance = (ao2_ref(th->tcptls_session, +1), th->tcptls_session);
26052 ao2_t_ref(th, -1, "decrement ref from callback");
26053 }
26054
26055 return tcptls_instance;
26056 }
26057
26058
26059
26060
26061
26062
26063 int get_address_family_filter(unsigned int transport)
26064 {
26065 const struct ast_sockaddr *addr = NULL;
26066
26067 if ((transport == SIP_TRANSPORT_UDP) || !transport) {
26068 addr = &bindaddr;
26069 }
26070 else if (transport == SIP_TRANSPORT_TCP) {
26071 addr = &sip_tcp_desc.local_address;
26072 }
26073 else if (transport == SIP_TRANSPORT_TLS) {
26074 addr = &sip_tls_desc.local_address;
26075 }
26076
26077 if (ast_sockaddr_is_ipv6(addr) && ast_sockaddr_is_any(addr)) {
26078 return 0;
26079 }
26080
26081 return addr->ss.ss_family;
26082 }
26083
26084
26085 static int sip_prepare_socket(struct sip_pvt *p)
26086 {
26087 struct sip_socket *s = &p->socket;
26088 static const char name[] = "SIP socket";
26089 struct sip_threadinfo *th = NULL;
26090 struct ast_tcptls_session_instance *tcptls_session;
26091 struct ast_tcptls_session_args *ca;
26092 struct ast_sockaddr sa_tmp;
26093 pthread_t launched;
26094
26095
26096 if ((s->fd != -1) && (s->type == SIP_TRANSPORT_UDP)) {
26097 return s->fd;
26098 }
26099 if ((s->type & (SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS)) &&
26100 (s->tcptls_session) &&
26101 (s->tcptls_session->fd != -1)) {
26102 return s->tcptls_session->fd;
26103 }
26104
26105
26106
26107
26108 if (p->outboundproxy && p->outboundproxy->transport) {
26109 s->type = p->outboundproxy->transport;
26110 }
26111
26112 if (s->type == SIP_TRANSPORT_UDP) {
26113 s->fd = sipsock;
26114 return s->fd;
26115 }
26116
26117
26118
26119
26120
26121
26122
26123
26124
26125
26126
26127 ast_sockaddr_copy(&sa_tmp, sip_real_dst(p));
26128 if ((tcptls_session = sip_tcp_locate(&sa_tmp))) {
26129 s->fd = tcptls_session->fd;
26130 if (s->tcptls_session) {
26131 ao2_ref(s->tcptls_session, -1);
26132 s->tcptls_session = NULL;
26133 }
26134 s->tcptls_session = tcptls_session;
26135 return s->fd;
26136
26137 } else if (s->tcptls_session) {
26138 return s->fd;
26139 }
26140
26141
26142
26143 if (!(ca = ao2_alloc(sizeof(*ca), sip_tcptls_client_args_destructor)) ||
26144 !(ca->name = ast_strdup(name))) {
26145 goto create_tcptls_session_fail;
26146 }
26147 ca->accept_fd = -1;
26148 ast_sockaddr_copy(&ca->remote_address,sip_real_dst(p));
26149
26150 if (s->type == SIP_TRANSPORT_TLS) {
26151 if (!(ca->tls_cfg = ast_calloc(1, sizeof(*ca->tls_cfg)))) {
26152 goto create_tcptls_session_fail;
26153 }
26154 memcpy(ca->tls_cfg, &default_tls_cfg, sizeof(*ca->tls_cfg));
26155
26156 if (!(ca->tls_cfg->certfile = ast_strdup(default_tls_cfg.certfile)) ||
26157 !(ca->tls_cfg->pvtfile = ast_strdup(default_tls_cfg.pvtfile)) ||
26158 !(ca->tls_cfg->cipher = ast_strdup(default_tls_cfg.cipher)) ||
26159 !(ca->tls_cfg->cafile = ast_strdup(default_tls_cfg.cafile)) ||
26160 !(ca->tls_cfg->capath = ast_strdup(default_tls_cfg.capath))) {
26161
26162 goto create_tcptls_session_fail;
26163 }
26164
26165
26166 if (!ast_strlen_zero(p->tohost)) {
26167 ast_copy_string(ca->hostname, p->tohost, sizeof(ca->hostname));
26168 }
26169 }
26170
26171
26172 if (!(s->tcptls_session = ast_tcptls_client_create(ca))) {
26173 goto create_tcptls_session_fail;
26174 }
26175
26176 s->fd = s->tcptls_session->fd;
26177
26178
26179
26180
26181
26182 if (!(th = sip_threadinfo_create(s->tcptls_session, s->type))) {
26183 goto create_tcptls_session_fail;
26184 }
26185
26186
26187 ao2_ref(s->tcptls_session, +1);
26188
26189 if (ast_pthread_create_detached_background(&launched, NULL, sip_tcp_worker_fn, s->tcptls_session)) {
26190 ast_debug(1, "Unable to launch '%s'.", ca->name);
26191 ao2_ref(s->tcptls_session, -1);
26192 goto create_tcptls_session_fail;
26193 }
26194
26195 return s->fd;
26196
26197 create_tcptls_session_fail:
26198 if (ca) {
26199 ao2_t_ref(ca, -1, "failed to create client, getting rid of client tcptls_session arguments");
26200 }
26201 if (s->tcptls_session) {
26202 ast_tcptls_close_session_file(s->tcptls_session);
26203 s->fd = -1;
26204 ao2_ref(s->tcptls_session, -1);
26205 s->tcptls_session = NULL;
26206 }
26207 if (th) {
26208 ao2_t_unlink(threadt, th, "Removing tcptls thread info object, thread failed to open");
26209 }
26210
26211 return -1;
26212 }
26213
26214
26215
26216
26217
26218 static int get_cached_mwi(struct sip_peer *peer, int *new, int *old)
26219 {
26220 struct sip_mailbox *mailbox;
26221 int in_cache;
26222
26223 in_cache = 0;
26224 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
26225 struct ast_event *event;
26226 event = ast_event_get_cached(AST_EVENT_MWI,
26227 AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox->mailbox,
26228 AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, S_OR(mailbox->context, "default"),
26229 AST_EVENT_IE_END);
26230 if (!event)
26231 continue;
26232 *new += ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
26233 *old += ast_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS);
26234 ast_event_destroy(event);
26235 in_cache = 1;
26236 }
26237
26238 return in_cache;
26239 }
26240
26241
26242
26243
26244 static int sip_send_mwi_to_peer(struct sip_peer *peer, int cache_only)
26245 {
26246
26247 struct sip_pvt *p;
26248 int newmsgs = 0, oldmsgs = 0;
26249 const char *vmexten = NULL;
26250
26251 ao2_lock(peer);
26252
26253 if (peer->vmexten) {
26254 vmexten = ast_strdupa(peer->vmexten);
26255 }
26256
26257 if (ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY) && !peer->mwipvt) {
26258 update_peer_lastmsgssent(peer, -1, 1);
26259 ao2_unlock(peer);
26260 return 0;
26261 }
26262
26263
26264 if (ast_sockaddr_isnull(&peer->addr) && ast_sockaddr_isnull(&peer->defaddr)) {
26265 update_peer_lastmsgssent(peer, -1, 1);
26266 ao2_unlock(peer);
26267 return 0;
26268 }
26269
26270
26271 if (!get_cached_mwi(peer, &newmsgs, &oldmsgs) && !cache_only) {
26272
26273 struct ast_str *mailbox_str = ast_str_alloca(512);
26274 peer_mailboxes_to_str(&mailbox_str, peer);
26275 ao2_unlock(peer);
26276
26277 if (!ast_str_strlen(mailbox_str)) {
26278 update_peer_lastmsgssent(peer, -1, 0);
26279 return 0;
26280 }
26281 ast_app_inboxcount(ast_str_buffer(mailbox_str), &newmsgs, &oldmsgs);
26282 ao2_lock(peer);
26283 }
26284
26285 if (peer->mwipvt) {
26286
26287 p = dialog_ref(peer->mwipvt, "sip_send_mwi_to_peer: Setting dialog ptr p from peer->mwipvt");
26288 ao2_unlock(peer);
26289 } else {
26290 ao2_unlock(peer);
26291
26292 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
26293 update_peer_lastmsgssent(peer, -1, 0);
26294 return -1;
26295 }
26296
26297
26298
26299
26300
26301 set_socket_transport(&p->socket, 0);
26302 if (create_addr_from_peer(p, peer)) {
26303
26304 dialog_unlink_all(p);
26305 dialog_unref(p, "unref dialog p just created via sip_alloc");
26306 update_peer_lastmsgssent(peer, -1, 0);
26307 return 0;
26308 }
26309
26310 ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
26311 build_via(p);
26312
26313 ao2_lock(peer);
26314 if (!ast_strlen_zero(peer->mwi_from)) {
26315 ast_string_field_set(p, mwi_from, peer->mwi_from);
26316 } else if (!ast_strlen_zero(default_mwi_from)) {
26317 ast_string_field_set(p, mwi_from, default_mwi_from);
26318 }
26319 ao2_unlock(peer);
26320
26321
26322 change_callid_pvt(p, NULL);
26323
26324
26325 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
26326 }
26327
26328
26329
26330 sip_pvt_lock(p);
26331
26332
26333 ast_set_flag(&p->flags[0], SIP_OUTGOING);
26334
26335 transmit_notify_with_mwi(p, newmsgs, oldmsgs, vmexten);
26336 sip_pvt_unlock(p);
26337 dialog_unref(p, "unref dialog ptr p just before it goes out of scope at the end of sip_send_mwi_to_peer.");
26338
26339 update_peer_lastmsgssent(peer, ((newmsgs > 0x7fff ? 0x7fff0000 : (newmsgs << 16)) | (oldmsgs > 0xffff ? 0xffff : oldmsgs)), 0);
26340
26341 return 0;
26342 }
26343
26344
26345 static void check_rtp_timeout(struct sip_pvt *dialog, time_t t)
26346 {
26347
26348 if (!dialog->rtp || !dialog->owner)
26349 return;
26350
26351
26352 if (dialog->owner->_state != AST_STATE_UP || !ast_sockaddr_isnull(&dialog->redirip))
26353 return;
26354
26355
26356 if (dialog->t38.state == T38_ENABLED)
26357 return;
26358
26359
26360 if (!ast_rtp_instance_get_keepalive(dialog->rtp) && !ast_rtp_instance_get_timeout(dialog->rtp) && !ast_rtp_instance_get_hold_timeout(dialog->rtp)) {
26361 return;
26362 }
26363
26364
26365 if (dialog->lastrtptx && ast_rtp_instance_get_keepalive(dialog->rtp) &&
26366 (t > dialog->lastrtptx + ast_rtp_instance_get_keepalive(dialog->rtp))) {
26367
26368 dialog->lastrtptx = time(NULL);
26369 ast_rtp_instance_sendcng(dialog->rtp, 0);
26370 }
26371
26372
26373
26374
26375
26376
26377
26378
26379 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))) {
26380 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)))) {
26381
26382 if (ast_rtp_instance_get_timeout(dialog->rtp)) {
26383 if (!dialog->owner || ast_channel_trylock(dialog->owner)) {
26384
26385
26386
26387
26388 return;
26389 }
26390 ast_log(LOG_NOTICE, "Disconnecting call '%s' for lack of RTP activity in %ld seconds\n",
26391 dialog->owner->name, (long) (t - dialog->lastrtprx));
26392
26393 ast_softhangup_nolock(dialog->owner, AST_SOFTHANGUP_DEV);
26394 ast_channel_unlock(dialog->owner);
26395
26396
26397
26398
26399 ast_rtp_instance_set_timeout(dialog->rtp, 0);
26400 ast_rtp_instance_set_hold_timeout(dialog->rtp, 0);
26401 if (dialog->vrtp) {
26402 ast_rtp_instance_set_timeout(dialog->vrtp, 0);
26403 ast_rtp_instance_set_hold_timeout(dialog->vrtp, 0);
26404 }
26405 }
26406 }
26407 }
26408 }
26409
26410
26411
26412
26413
26414 static void *do_monitor(void *data)
26415 {
26416 int res;
26417 time_t t;
26418 int reloading;
26419
26420
26421 if (sipsock > -1)
26422 sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
26423
26424
26425 for(;;) {
26426
26427 ast_mutex_lock(&sip_reload_lock);
26428 reloading = sip_reloading;
26429 sip_reloading = FALSE;
26430 ast_mutex_unlock(&sip_reload_lock);
26431 if (reloading) {
26432 ast_verb(1, "Reloading SIP\n");
26433 sip_do_reload(sip_reloadreason);
26434
26435
26436 if (sipsock > -1) {
26437 if (sipsock_read_id)
26438 sipsock_read_id = ast_io_change(io, sipsock_read_id, sipsock, NULL, 0, NULL);
26439 else
26440 sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
26441 } else if (sipsock_read_id) {
26442 ast_io_remove(io, sipsock_read_id);
26443 sipsock_read_id = NULL;
26444 }
26445 }
26446
26447
26448 t = time(NULL);
26449
26450
26451
26452
26453
26454
26455
26456
26457
26458
26459 ao2_t_callback(dialogs, OBJ_NODATA | OBJ_MULTIPLE, dialog_needdestroy, &t,
26460 "callback to monitor dialog status");
26461 if (ao2_container_count(dialogs_to_destroy)) {
26462
26463 ao2_t_callback(dialogs_to_destroy, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE,
26464 dialog_unlink_callback, NULL, "callback to dialog_unlink_all");
26465 }
26466
26467
26468
26469
26470
26471
26472
26473 pthread_testcancel();
26474
26475 res = ast_sched_wait(sched);
26476 if ((res < 0) || (res > 1000))
26477 res = 1000;
26478 res = ast_io_wait(io, res);
26479 if (res > 20)
26480 ast_debug(1, "chan_sip: ast_io_wait ran %d all at once\n", res);
26481 ast_mutex_lock(&monlock);
26482 res = ast_sched_runq(sched);
26483 if (res >= 20)
26484 ast_debug(1, "chan_sip: ast_sched_runq ran %d all at once\n", res);
26485 if (global_store_sip_cause && res >= 100)
26486 ast_log(LOG_WARNING, "scheduler delays detected, setting 'storesipcause' to 'no' in %s will improve performance\n", config);
26487 ast_mutex_unlock(&monlock);
26488 }
26489
26490
26491 return NULL;
26492 }
26493
26494
26495 static int restart_monitor(void)
26496 {
26497
26498 if (monitor_thread == AST_PTHREADT_STOP)
26499 return 0;
26500 ast_mutex_lock(&monlock);
26501 if (monitor_thread == pthread_self()) {
26502 ast_mutex_unlock(&monlock);
26503 ast_log(LOG_WARNING, "Cannot kill myself\n");
26504 return -1;
26505 }
26506 if (monitor_thread != AST_PTHREADT_NULL) {
26507
26508 pthread_kill(monitor_thread, SIGURG);
26509 } else {
26510
26511 if (ast_pthread_create_background(&monitor_thread, NULL, do_monitor, NULL) < 0) {
26512 ast_mutex_unlock(&monlock);
26513 ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
26514 return -1;
26515 }
26516 }
26517 ast_mutex_unlock(&monlock);
26518 return 0;
26519 }
26520
26521
26522
26523 static void restart_session_timer(struct sip_pvt *p)
26524 {
26525 if (!p->stimer) {
26526 ast_log(LOG_WARNING, "Null stimer in restart_session_timer - %s\n", p->callid);
26527 return;
26528 }
26529
26530 if (p->stimer->st_active == TRUE) {
26531 ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
26532 AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
26533 dialog_unref(p, "Removing session timer ref"));
26534 start_session_timer(p);
26535 }
26536 }
26537
26538
26539
26540 static void stop_session_timer(struct sip_pvt *p)
26541 {
26542 if (!p->stimer) {
26543 ast_log(LOG_WARNING, "Null stimer in stop_session_timer - %s\n", p->callid);
26544 return;
26545 }
26546
26547 if (p->stimer->st_active == TRUE) {
26548 p->stimer->st_active = FALSE;
26549 ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
26550 AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
26551 dialog_unref(p, "removing session timer ref"));
26552 }
26553 }
26554
26555
26556
26557 static void start_session_timer(struct sip_pvt *p)
26558 {
26559 if (!p->stimer) {
26560 ast_log(LOG_WARNING, "Null stimer in start_session_timer - %s\n", p->callid);
26561 return;
26562 }
26563
26564 if (p->stimer->st_schedid > -1) {
26565
26566 ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
26567 AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
26568 dialog_unref(p, "unref stimer->st_schedid from dialog"));
26569 }
26570
26571 p->stimer->st_schedid = ast_sched_add(sched, p->stimer->st_interval * 1000 / 2, proc_session_timer,
26572 dialog_ref(p, "adding session timer ref"));
26573 if (p->stimer->st_schedid < 0) {
26574 dialog_unref(p, "removing session timer ref");
26575 ast_log(LOG_ERROR, "ast_sched_add failed - %s\n", p->callid);
26576 } else {
26577 p->stimer->st_active = TRUE;
26578 ast_debug(2, "Session timer started: %d - %s\n", p->stimer->st_schedid, p->callid);
26579 }
26580 }
26581
26582
26583
26584 static int proc_session_timer(const void *vp)
26585 {
26586 struct sip_pvt *p = (struct sip_pvt *) vp;
26587 int res = 0;
26588
26589 if (!p->stimer) {
26590 ast_log(LOG_WARNING, "Null stimer in proc_session_timer - %s\n", p->callid);
26591 goto return_unref;
26592 }
26593
26594 ast_debug(2, "Session timer expired: %d - %s\n", p->stimer->st_schedid, p->callid);
26595
26596 if (!p->owner) {
26597 goto return_unref;
26598 }
26599
26600 if ((p->stimer->st_active != TRUE) || (p->owner->_state != AST_STATE_UP)) {
26601 goto return_unref;
26602 }
26603
26604 if (p->stimer->st_ref == SESSION_TIMER_REFRESHER_US) {
26605 res = 1;
26606 transmit_reinvite_with_sdp(p, FALSE, TRUE);
26607 } else {
26608 p->stimer->st_expirys++;
26609 if (p->stimer->st_expirys >= 2) {
26610 if (p->stimer->quit_flag) {
26611 goto return_unref;
26612 }
26613 ast_log(LOG_WARNING, "Session-Timer expired - %s\n", p->callid);
26614 sip_pvt_lock(p);
26615 while (p->owner && ast_channel_trylock(p->owner)) {
26616 sip_pvt_unlock(p);
26617 usleep(1);
26618 if (p->stimer && p->stimer->quit_flag) {
26619 goto return_unref;
26620 }
26621 sip_pvt_lock(p);
26622 }
26623
26624 ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
26625 ast_channel_unlock(p->owner);
26626 sip_pvt_unlock(p);
26627 } else {
26628 res = 1;
26629 }
26630 }
26631
26632 return_unref:
26633 if (!res) {
26634
26635 if (p->stimer) {
26636 ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
26637 p->stimer->st_schedid = -1;
26638 stop_session_timer(p);
26639 }
26640
26641
26642
26643 dialog_unref(p, "removing session timer ref");
26644 }
26645
26646 return res;
26647 }
26648
26649
26650
26651 int parse_minse (const char *p_hdrval, int *const p_interval)
26652 {
26653 if (ast_strlen_zero(p_hdrval)) {
26654 ast_log(LOG_WARNING, "Null Min-SE header\n");
26655 return -1;
26656 }
26657
26658 *p_interval = 0;
26659 p_hdrval = ast_skip_blanks(p_hdrval);
26660 if (!sscanf(p_hdrval, "%30d", p_interval)) {
26661 ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
26662 return -1;
26663 }
26664
26665 ast_debug(2, "Received Min-SE: %d\n", *p_interval);
26666 return 0;
26667 }
26668
26669
26670
26671 int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher_param *const p_ref)
26672 {
26673 char *p_token;
26674 int ref_idx;
26675 char *p_se_hdr;
26676
26677 if (ast_strlen_zero(p_hdrval)) {
26678 ast_log(LOG_WARNING, "Null Session-Expires header\n");
26679 return -1;
26680 }
26681
26682 *p_ref = SESSION_TIMER_REFRESHER_PARAM_UNKNOWN;
26683 *p_interval = 0;
26684
26685 p_se_hdr = ast_strdupa(p_hdrval);
26686 p_se_hdr = ast_skip_blanks(p_se_hdr);
26687
26688 while ((p_token = strsep(&p_se_hdr, ";"))) {
26689 p_token = ast_skip_blanks(p_token);
26690 if (!sscanf(p_token, "%30d", p_interval)) {
26691 ast_log(LOG_WARNING, "Parsing of Session-Expires failed\n");
26692 return -1;
26693 }
26694
26695 ast_debug(2, "Session-Expires: %d\n", *p_interval);
26696
26697 if (!p_se_hdr)
26698 continue;
26699
26700 p_se_hdr = ast_skip_blanks(p_se_hdr);
26701 ref_idx = strlen("refresher=");
26702 if (!strncasecmp(p_se_hdr, "refresher=", ref_idx)) {
26703 p_se_hdr += ref_idx;
26704 p_se_hdr = ast_skip_blanks(p_se_hdr);
26705
26706 if (!strncasecmp(p_se_hdr, "uac", strlen("uac"))) {
26707 *p_ref = SESSION_TIMER_REFRESHER_PARAM_UAC;
26708 ast_debug(2, "Refresher: UAC\n");
26709 } else if (!strncasecmp(p_se_hdr, "uas", strlen("uas"))) {
26710 *p_ref = SESSION_TIMER_REFRESHER_PARAM_UAS;
26711 ast_debug(2, "Refresher: UAS\n");
26712 } else {
26713 ast_log(LOG_WARNING, "Invalid refresher value %s\n", p_se_hdr);
26714 return -1;
26715 }
26716 break;
26717 }
26718 }
26719 return 0;
26720 }
26721
26722
26723
26724
26725
26726
26727
26728
26729
26730 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp)
26731 {
26732 int rtn;
26733 const char *p_hdrval;
26734 int minse;
26735
26736 p_hdrval = get_header(rsp, "Min-SE");
26737 if (ast_strlen_zero(p_hdrval)) {
26738 ast_log(LOG_WARNING, "422 response without a Min-SE header %s\n", p_hdrval);
26739 return;
26740 }
26741 rtn = parse_minse(p_hdrval, &minse);
26742 if (rtn != 0) {
26743 ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
26744 return;
26745 }
26746 p->stimer->st_interval = minse;
26747 transmit_invite(p, SIP_INVITE, 1, 2, NULL);
26748 }
26749
26750
26751
26752
26753
26754
26755 int st_get_se(struct sip_pvt *p, int max)
26756 {
26757 if (max == TRUE) {
26758 if (p->stimer->st_cached_max_se) {
26759 return p->stimer->st_cached_max_se;
26760 }
26761 if (p->relatedpeer) {
26762 p->stimer->st_cached_max_se = p->relatedpeer->stimer.st_max_se;
26763 return (p->stimer->st_cached_max_se);
26764 }
26765 p->stimer->st_cached_max_se = global_max_se;
26766 return (p->stimer->st_cached_max_se);
26767 }
26768
26769 if (p->stimer->st_cached_min_se) {
26770 return p->stimer->st_cached_min_se;
26771 }
26772 if (p->relatedpeer) {
26773 p->stimer->st_cached_min_se = p->relatedpeer->stimer.st_min_se;
26774 return (p->stimer->st_cached_min_se);
26775 }
26776 p->stimer->st_cached_min_se = global_min_se;
26777 return (p->stimer->st_cached_min_se);
26778 }
26779
26780
26781
26782
26783
26784
26785
26786
26787 enum st_refresher st_get_refresher(struct sip_pvt *p)
26788 {
26789 if (p->stimer->st_cached_ref != SESSION_TIMER_REFRESHER_AUTO) {
26790 return p->stimer->st_cached_ref;
26791 }
26792
26793 if (p->relatedpeer) {
26794 p->stimer->st_cached_ref = (p->relatedpeer->stimer.st_ref == SESSION_TIMER_REFRESHER_PARAM_UAC) ? SESSION_TIMER_REFRESHER_THEM : SESSION_TIMER_REFRESHER_US;
26795 return p->stimer->st_cached_ref;
26796 }
26797
26798 p->stimer->st_cached_ref = (global_st_refresher == SESSION_TIMER_REFRESHER_PARAM_UAC) ? SESSION_TIMER_REFRESHER_THEM : SESSION_TIMER_REFRESHER_US;
26799 return p->stimer->st_cached_ref;
26800 }
26801
26802
26803
26804
26805
26806
26807
26808
26809 enum st_mode st_get_mode(struct sip_pvt *p, int no_cached)
26810 {
26811 if (!p->stimer) {
26812 sip_st_alloc(p);
26813 if (!p->stimer) {
26814 return SESSION_TIMER_MODE_INVALID;
26815 }
26816 }
26817
26818 if (!no_cached && p->stimer->st_cached_mode != SESSION_TIMER_MODE_INVALID)
26819 return p->stimer->st_cached_mode;
26820
26821 if (p->relatedpeer) {
26822 p->stimer->st_cached_mode = p->relatedpeer->stimer.st_mode_oper;
26823 return p->stimer->st_cached_mode;
26824 }
26825
26826 p->stimer->st_cached_mode = global_st_mode;
26827 return global_st_mode;
26828 }
26829
26830
26831
26832 static int sip_poke_noanswer(const void *data)
26833 {
26834 struct sip_peer *peer = (struct sip_peer *)data;
26835
26836 peer->pokeexpire = -1;
26837
26838 if (peer->lastms > -1) {
26839 ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE! Last qualify: %d\n", peer->name, peer->lastms);
26840 if (sip_cfg.peer_rtupdate) {
26841 ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", "-1", SENTINEL);
26842 }
26843 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer->name, -1);
26844 if (sip_cfg.regextenonqualify) {
26845 register_peer_exten(peer, FALSE);
26846 }
26847 }
26848
26849 if (peer->call) {
26850 dialog_unlink_all(peer->call);
26851 peer->call = dialog_unref(peer->call, "unref dialog peer->call");
26852
26853 }
26854
26855
26856 if (peer->lastms > -1) {
26857 peer->lastms = -1;
26858 ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "SIP/%s", peer->name);
26859 }
26860
26861
26862 AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
26863 DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer,
26864 unref_peer(_data, "removing poke peer ref"),
26865 unref_peer(peer, "removing poke peer ref"),
26866 ref_peer(peer, "adding poke peer ref"));
26867
26868
26869 unref_peer(peer, "release peer poke noanswer ref");
26870
26871 return 0;
26872 }
26873
26874
26875
26876
26877
26878
26879 static int sip_poke_peer(struct sip_peer *peer, int force)
26880 {
26881 struct sip_pvt *p;
26882 int xmitres = 0;
26883
26884 if ((!peer->maxms && !force) || ast_sockaddr_isnull(&peer->addr)) {
26885
26886
26887 AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
26888 unref_peer(peer, "removing poke peer ref"));
26889
26890 peer->lastms = 0;
26891 if (peer->call) {
26892 peer->call = dialog_unref(peer->call, "unref dialog peer->call");
26893 }
26894 return 0;
26895 }
26896 if (peer->call) {
26897 if (sipdebug) {
26898 ast_log(LOG_NOTICE, "Still have a QUALIFY dialog active, deleting\n");
26899 }
26900 dialog_unlink_all(peer->call);
26901 peer->call = dialog_unref(peer->call, "unref dialog peer->call");
26902
26903 }
26904 if (!(p = sip_alloc(NULL, NULL, 0, SIP_OPTIONS, NULL))) {
26905 return -1;
26906 }
26907 peer->call = dialog_ref(p, "copy sip alloc from p to peer->call");
26908
26909 p->sa = peer->addr;
26910 p->recv = peer->addr;
26911 copy_socket_data(&p->socket, &peer->socket);
26912 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
26913 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
26914 ast_copy_flags(&p->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
26915
26916
26917 if (!ast_strlen_zero(peer->fullcontact)) {
26918 ast_string_field_set(p, fullcontact, peer->fullcontact);
26919 }
26920
26921 if (!ast_strlen_zero(peer->fromuser)) {
26922 ast_string_field_set(p, fromuser, peer->fromuser);
26923 }
26924
26925 if (!ast_strlen_zero(peer->tohost)) {
26926 ast_string_field_set(p, tohost, peer->tohost);
26927 } else {
26928 ast_string_field_set(p, tohost, ast_sockaddr_stringify_host_remote(&peer->addr));
26929 }
26930
26931
26932 ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
26933 build_via(p);
26934
26935
26936 change_callid_pvt(p, NULL);
26937
26938 AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
26939 unref_peer(peer, "removing poke peer ref"));
26940
26941 if (p->relatedpeer)
26942 p->relatedpeer = unref_peer(p->relatedpeer,"unsetting the relatedpeer field in the dialog, before it is set to something else.");
26943 p->relatedpeer = ref_peer(peer, "setting the relatedpeer field in the dialog");
26944 ast_set_flag(&p->flags[0], SIP_OUTGOING);
26945 #ifdef VOCAL_DATA_HACK
26946 ast_copy_string(p->username, "__VOCAL_DATA_SHOULD_READ_THE_SIP_SPEC__", sizeof(p->username));
26947 xmitres = transmit_invite(p, SIP_INVITE, 0, 2, NULL);
26948 #else
26949 xmitres = transmit_invite(p, SIP_OPTIONS, 0, 2, NULL);
26950 #endif
26951 peer->ps = ast_tvnow();
26952 if (xmitres == XMIT_ERROR) {
26953
26954 sip_poke_noanswer(ref_peer(peer, "add ref for peerexpire (fake, for sip_poke_noanswer to remove)"));
26955 } else if (!force) {
26956 AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, peer->maxms * 2, sip_poke_noanswer, peer,
26957 unref_peer(_data, "removing poke peer ref"),
26958 unref_peer(peer, "removing poke peer ref"),
26959 ref_peer(peer, "adding poke peer ref"));
26960 }
26961 dialog_unref(p, "unref dialog at end of sip_poke_peer, obtained from sip_alloc, just before it goes out of scope");
26962 return 0;
26963 }
26964
26965
26966
26967
26968
26969
26970
26971
26972
26973
26974
26975
26976
26977
26978
26979
26980
26981
26982
26983
26984
26985
26986
26987
26988
26989
26990
26991
26992
26993
26994
26995
26996
26997
26998 static int sip_devicestate(void *data)
26999 {
27000 char *host;
27001 char *tmp;
27002 struct sip_peer *p;
27003
27004 int res = AST_DEVICE_INVALID;
27005
27006
27007 host = ast_strdupa(data ? data : "");
27008 if ((tmp = strchr(host, '@')))
27009 host = tmp + 1;
27010
27011 ast_debug(3, "Checking device state for peer %s\n", host);
27012
27013
27014
27015
27016
27017
27018
27019
27020 if ((p = find_peer(host, NULL, FALSE, FINDALLDEVICES, TRUE, 0))) {
27021 if (!(ast_sockaddr_isnull(&p->addr) && ast_sockaddr_isnull(&p->defaddr))) {
27022
27023
27024
27025
27026
27027
27028
27029
27030
27031
27032
27033 if (p->onHold)
27034
27035 res = AST_DEVICE_ONHOLD;
27036 else if (p->inRinging) {
27037 if (p->inRinging == p->inUse)
27038 res = AST_DEVICE_RINGING;
27039 else
27040 res = AST_DEVICE_RINGINUSE;
27041 } else if (p->call_limit && (p->inUse == p->call_limit))
27042
27043 res = AST_DEVICE_BUSY;
27044 else if (p->call_limit && p->busy_level && p->inUse >= p->busy_level)
27045
27046 res = AST_DEVICE_BUSY;
27047 else if (p->call_limit && p->inUse)
27048
27049 res = AST_DEVICE_INUSE;
27050 else if (p->maxms && ((p->lastms > p->maxms) || (p->lastms < 0)))
27051
27052 res = AST_DEVICE_UNAVAILABLE;
27053 else
27054 res = AST_DEVICE_NOT_INUSE;
27055 } else {
27056
27057 res = AST_DEVICE_UNAVAILABLE;
27058 }
27059 unref_peer(p, "unref_peer, from sip_devicestate, release ref from find_peer");
27060 }
27061
27062 return res;
27063 }
27064
27065
27066
27067
27068
27069
27070
27071
27072
27073
27074
27075
27076
27077
27078
27079
27080 static struct ast_channel *sip_request_call(const char *type, format_t format, const struct ast_channel *requestor, void *data, int *cause)
27081 {
27082 struct sip_pvt *p;
27083 struct ast_channel *tmpc = NULL;
27084 char *ext = NULL, *host;
27085 char tmp[256];
27086 char *dest = data;
27087 char *dnid;
27088 char *secret = NULL;
27089 char *md5secret = NULL;
27090 char *authname = NULL;
27091 char *trans = NULL;
27092 char dialstring[256];
27093 char *remote_address;
27094 enum sip_transport transport = 0;
27095 format_t oldformat = format;
27096 AST_DECLARE_APP_ARGS(args,
27097 AST_APP_ARG(peerorhost);
27098 AST_APP_ARG(exten);
27099 AST_APP_ARG(remote_address);
27100 );
27101
27102
27103
27104
27105
27106
27107
27108
27109 format &= AST_FORMAT_AUDIO_MASK;
27110 if (!format) {
27111 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));
27112 *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
27113 return NULL;
27114 }
27115 ast_debug(1, "Asked to create a SIP channel with formats: %s\n", ast_getformatname_multiple(tmp, sizeof(tmp), oldformat));
27116
27117 if (ast_strlen_zero(dest)) {
27118 ast_log(LOG_ERROR, "Unable to create channel with empty destination.\n");
27119 *cause = AST_CAUSE_CHANNEL_UNACCEPTABLE;
27120 return NULL;
27121 }
27122
27123 if (!(p = sip_alloc(NULL, NULL, 0, SIP_INVITE, NULL))) {
27124 ast_log(LOG_ERROR, "Unable to build sip pvt data for '%s' (Out of memory or socket error)\n", dest);
27125 *cause = AST_CAUSE_SWITCH_CONGESTION;
27126 return NULL;
27127 }
27128
27129 p->outgoing_call = TRUE;
27130
27131 snprintf(dialstring, sizeof(dialstring), "%s/%s", type, dest);
27132 ast_string_field_set(p, dialstring, dialstring);
27133
27134 if (!(p->options = ast_calloc(1, sizeof(*p->options)))) {
27135 dialog_unlink_all(p);
27136 dialog_unref(p, "unref dialog p from mem fail");
27137
27138 ast_log(LOG_ERROR, "Unable to build option SIP data structure - Out of memory\n");
27139 *cause = AST_CAUSE_SWITCH_CONGESTION;
27140 return NULL;
27141 }
27142
27143
27144 ast_copy_string(tmp, dest, sizeof(tmp));
27145
27146
27147 dnid = strchr(tmp, '!');
27148 if (dnid != NULL) {
27149 *dnid++ = '\0';
27150 ast_string_field_set(p, todnid, dnid);
27151 }
27152
27153
27154 AST_NONSTANDARD_APP_ARGS(args, tmp, '/');
27155
27156
27157 host = strchr(args.peerorhost, '@');
27158 if (host) {
27159 *host++ = '\0';
27160 ext = args.peerorhost;
27161 secret = strchr(ext, ':');
27162 }
27163 if (secret) {
27164 *secret++ = '\0';
27165 md5secret = strchr(secret, ':');
27166 }
27167 if (md5secret) {
27168 *md5secret++ = '\0';
27169 authname = strchr(md5secret, ':');
27170 }
27171 if (authname) {
27172 *authname++ = '\0';
27173 trans = strchr(authname, ':');
27174 }
27175 if (trans) {
27176 *trans++ = '\0';
27177 if (!strcasecmp(trans, "tcp"))
27178 transport = SIP_TRANSPORT_TCP;
27179 else if (!strcasecmp(trans, "tls"))
27180 transport = SIP_TRANSPORT_TLS;
27181 else {
27182 if (strcasecmp(trans, "udp"))
27183 ast_log(LOG_WARNING, "'%s' is not a valid transport option to Dial() for SIP calls, using udp by default.\n", trans);
27184 transport = SIP_TRANSPORT_UDP;
27185 }
27186 } else {
27187 transport = SIP_TRANSPORT_UDP;
27188 }
27189
27190 if (!host) {
27191 ext = args.exten;
27192 host = args.peerorhost;
27193 remote_address = args.remote_address;
27194 } else {
27195 remote_address = args.remote_address;
27196 if (!ast_strlen_zero(args.exten)) {
27197 ast_log(LOG_NOTICE, "Conflicting extension values given. Using '%s' and not '%s'\n", ext, args.exten);
27198 }
27199 }
27200
27201 if (!ast_strlen_zero(remote_address)) {
27202 p->options->outboundproxy = proxy_from_config(remote_address, 0, NULL);
27203 if (!p->options->outboundproxy) {
27204 ast_log(LOG_WARNING, "Unable to parse outboundproxy %s. We will not use this remote IP address\n", remote_address);
27205 }
27206 }
27207
27208 set_socket_transport(&p->socket, transport);
27209
27210
27211
27212
27213
27214
27215 if (create_addr(p, host, NULL, 1)) {
27216 *cause = AST_CAUSE_UNREGISTERED;
27217 ast_debug(3, "Cant create SIP call - target device not registered\n");
27218 dialog_unlink_all(p);
27219 dialog_unref(p, "unref dialog p UNREGISTERED");
27220
27221 return NULL;
27222 }
27223 if (ast_strlen_zero(p->peername) && ext)
27224 ast_string_field_set(p, peername, ext);
27225
27226 ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
27227 build_via(p);
27228
27229
27230 change_callid_pvt(p, NULL);
27231
27232
27233
27234
27235
27236
27237 if (ext) {
27238 ast_string_field_set(p, username, ext);
27239 ast_string_field_set(p, fullcontact, NULL);
27240 }
27241 if (secret && !ast_strlen_zero(secret))
27242 ast_string_field_set(p, peersecret, secret);
27243
27244 if (md5secret && !ast_strlen_zero(md5secret))
27245 ast_string_field_set(p, peermd5secret, md5secret);
27246
27247 if (authname && !ast_strlen_zero(authname))
27248 ast_string_field_set(p, authname, authname);
27249 #if 0
27250 printf("Setting up to call extension '%s' at '%s'\n", ext ? ext : "<none>", host);
27251 #endif
27252 p->prefcodec = oldformat;
27253 p->jointcapability = oldformat & p->capability;
27254 sip_pvt_lock(p);
27255 tmpc = sip_new(p, AST_STATE_DOWN, host, requestor ? requestor->linkedid : NULL);
27256 if (sip_cfg.callevents)
27257 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
27258 "Channel: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
27259 p->owner? p->owner->name : "", "SIP", p->callid, p->fullcontact, p->peername);
27260 sip_pvt_unlock(p);
27261 if (!tmpc) {
27262 dialog_unlink_all(p);
27263
27264 } else {
27265 ast_channel_unlock(tmpc);
27266 }
27267 dialog_unref(p, "toss pvt ptr at end of sip_request_call");
27268 ast_update_use_count();
27269 restart_monitor();
27270 return tmpc;
27271 }
27272
27273
27274 static void set_insecure_flags (struct ast_flags *flags, const char *value, int lineno)
27275 {
27276 if (ast_strlen_zero(value))
27277 return;
27278
27279 if (!ast_false(value)) {
27280 char buf[64];
27281 char *word, *next;
27282
27283 ast_copy_string(buf, value, sizeof(buf));
27284 next = buf;
27285 while ((word = strsep(&next, ","))) {
27286 if (!strcasecmp(word, "port"))
27287 ast_set_flag(&flags[0], SIP_INSECURE_PORT);
27288 else if (!strcasecmp(word, "invite"))
27289 ast_set_flag(&flags[0], SIP_INSECURE_INVITE);
27290 else
27291 ast_log(LOG_WARNING, "Unknown insecure mode '%s' on line %d\n", value, lineno);
27292 }
27293 }
27294 }
27295
27296
27297
27298
27299
27300 static int handle_t38_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v,
27301 int *maxdatagram)
27302 {
27303 int res = 1;
27304
27305 if (!strcasecmp(v->name, "t38pt_udptl")) {
27306 char *buf = ast_strdupa(v->value);
27307 char *word, *next = buf;
27308
27309 ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT);
27310
27311 while ((word = strsep(&next, ","))) {
27312 if (ast_true(word) || !strcasecmp(word, "fec")) {
27313 ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
27314 ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_FEC);
27315 } else if (!strcasecmp(word, "redundancy")) {
27316 ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
27317 ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY);
27318 } else if (!strcasecmp(word, "none")) {
27319 ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
27320 ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL);
27321 } else if (!strncasecmp(word, "maxdatagram=", 12)) {
27322 if (sscanf(&word[12], "%30u", maxdatagram) != 1) {
27323 ast_log(LOG_WARNING, "Invalid maxdatagram '%s' at line %d of %s\n", v->value, v->lineno, config);
27324 *maxdatagram = global_t38_maxdatagram;
27325 }
27326 }
27327 }
27328 } else if (!strcasecmp(v->name, "t38pt_usertpsource")) {
27329 ast_set_flag(&mask[1], SIP_PAGE2_UDPTL_DESTINATION);
27330 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_UDPTL_DESTINATION);
27331 } else {
27332 res = 0;
27333 }
27334
27335 return res;
27336 }
27337
27338
27339
27340
27341
27342
27343
27344
27345 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v)
27346 {
27347 int res = 1;
27348
27349 if (!strcasecmp(v->name, "trustrpid")) {
27350 ast_set_flag(&mask[0], SIP_TRUSTRPID);
27351 ast_set2_flag(&flags[0], ast_true(v->value), SIP_TRUSTRPID);
27352 } else if (!strcasecmp(v->name, "sendrpid")) {
27353 ast_set_flag(&mask[0], SIP_SENDRPID);
27354 if (!strcasecmp(v->value, "pai")) {
27355 ast_set_flag(&flags[0], SIP_SENDRPID_PAI);
27356 } else if (!strcasecmp(v->value, "rpid")) {
27357 ast_set_flag(&flags[0], SIP_SENDRPID_RPID);
27358 } else if (ast_true(v->value)) {
27359 ast_set_flag(&flags[0], SIP_SENDRPID_RPID);
27360 }
27361 } else if (!strcasecmp(v->name, "rpid_update")) {
27362 ast_set_flag(&mask[1], SIP_PAGE2_RPID_UPDATE);
27363 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RPID_UPDATE);
27364 } else if (!strcasecmp(v->name, "rpid_immediate")) {
27365 ast_set_flag(&mask[1], SIP_PAGE2_RPID_IMMEDIATE);
27366 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RPID_IMMEDIATE);
27367 } else if (!strcasecmp(v->name, "g726nonstandard")) {
27368 ast_set_flag(&mask[0], SIP_G726_NONSTANDARD);
27369 ast_set2_flag(&flags[0], ast_true(v->value), SIP_G726_NONSTANDARD);
27370 } else if (!strcasecmp(v->name, "useclientcode")) {
27371 ast_set_flag(&mask[0], SIP_USECLIENTCODE);
27372 ast_set2_flag(&flags[0], ast_true(v->value), SIP_USECLIENTCODE);
27373 } else if (!strcasecmp(v->name, "dtmfmode")) {
27374 ast_set_flag(&mask[0], SIP_DTMF);
27375 ast_clear_flag(&flags[0], SIP_DTMF);
27376 if (!strcasecmp(v->value, "inband"))
27377 ast_set_flag(&flags[0], SIP_DTMF_INBAND);
27378 else if (!strcasecmp(v->value, "rfc2833"))
27379 ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
27380 else if (!strcasecmp(v->value, "info"))
27381 ast_set_flag(&flags[0], SIP_DTMF_INFO);
27382 else if (!strcasecmp(v->value, "shortinfo"))
27383 ast_set_flag(&flags[0], SIP_DTMF_SHORTINFO);
27384 else if (!strcasecmp(v->value, "auto"))
27385 ast_set_flag(&flags[0], SIP_DTMF_AUTO);
27386 else {
27387 ast_log(LOG_WARNING, "Unknown dtmf mode '%s' on line %d, using rfc2833\n", v->value, v->lineno);
27388 ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
27389 }
27390 } else if (!strcasecmp(v->name, "nat")) {
27391 ast_set_flag(&mask[0], SIP_NAT_FORCE_RPORT);
27392 ast_set_flag(&flags[0], SIP_NAT_FORCE_RPORT);
27393 if (!strcasecmp(v->value, "no")) {
27394 ast_clear_flag(&flags[0], SIP_NAT_FORCE_RPORT);
27395 } else if (!strcasecmp(v->value, "yes")) {
27396
27397 ast_set_flag(&mask[1], SIP_PAGE2_SYMMETRICRTP);
27398 ast_set_flag(&flags[1], SIP_PAGE2_SYMMETRICRTP);
27399 } else if (!strcasecmp(v->value, "comedia")) {
27400 ast_clear_flag(&flags[0], SIP_NAT_FORCE_RPORT);
27401 ast_set_flag(&mask[1], SIP_PAGE2_SYMMETRICRTP);
27402 ast_set_flag(&flags[1], SIP_PAGE2_SYMMETRICRTP);
27403 }
27404 } else if (!strcasecmp(v->name, "directmedia") || !strcasecmp(v->name, "canreinvite")) {
27405 ast_set_flag(&mask[0], SIP_REINVITE);
27406 ast_clear_flag(&flags[0], SIP_REINVITE);
27407 if (ast_true(v->value)) {
27408 ast_set_flag(&flags[0], SIP_DIRECT_MEDIA | SIP_DIRECT_MEDIA_NAT);
27409 } else if (!ast_false(v->value)) {
27410 char buf[64];
27411 char *word, *next = buf;
27412
27413 ast_copy_string(buf, v->value, sizeof(buf));
27414 while ((word = strsep(&next, ","))) {
27415 if (!strcasecmp(word, "update")) {
27416 ast_set_flag(&flags[0], SIP_REINVITE_UPDATE | SIP_DIRECT_MEDIA);
27417 } else if (!strcasecmp(word, "nonat")) {
27418 ast_set_flag(&flags[0], SIP_DIRECT_MEDIA);
27419 ast_clear_flag(&flags[0], SIP_DIRECT_MEDIA_NAT);
27420 } else if (!strcasecmp(word, "outgoing")) {
27421 ast_set_flag(&flags[0], SIP_DIRECT_MEDIA);
27422 ast_set_flag(&mask[2], SIP_PAGE3_DIRECT_MEDIA_OUTGOING);
27423 ast_set_flag(&flags[2], SIP_PAGE3_DIRECT_MEDIA_OUTGOING);
27424 } else {
27425 ast_log(LOG_WARNING, "Unknown directmedia mode '%s' on line %d\n", v->value, v->lineno);
27426 }
27427 }
27428 }
27429 } else if (!strcasecmp(v->name, "insecure")) {
27430 ast_set_flag(&mask[0], SIP_INSECURE);
27431 ast_clear_flag(&flags[0], SIP_INSECURE);
27432 set_insecure_flags(&flags[0], v->value, v->lineno);
27433 } else if (!strcasecmp(v->name, "progressinband")) {
27434 ast_set_flag(&mask[0], SIP_PROG_INBAND);
27435 ast_clear_flag(&flags[0], SIP_PROG_INBAND);
27436 if (ast_true(v->value))
27437 ast_set_flag(&flags[0], SIP_PROG_INBAND_YES);
27438 else if (strcasecmp(v->value, "never"))
27439 ast_set_flag(&flags[0], SIP_PROG_INBAND_NO);
27440 } else if (!strcasecmp(v->name, "promiscredir")) {
27441 ast_set_flag(&mask[0], SIP_PROMISCREDIR);
27442 ast_set2_flag(&flags[0], ast_true(v->value), SIP_PROMISCREDIR);
27443 } else if (!strcasecmp(v->name, "videosupport")) {
27444 if (!strcasecmp(v->value, "always")) {
27445 ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
27446 ast_set_flag(&flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
27447 } else {
27448 ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT);
27449 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_VIDEOSUPPORT);
27450 }
27451 } else if (!strcasecmp(v->name, "textsupport")) {
27452 ast_set_flag(&mask[1], SIP_PAGE2_TEXTSUPPORT);
27453 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_TEXTSUPPORT);
27454 res = 1;
27455 } else if (!strcasecmp(v->name, "allowoverlap")) {
27456 ast_set_flag(&mask[1], SIP_PAGE2_ALLOWOVERLAP);
27457 ast_clear_flag(&flags[1], SIP_PAGE2_ALLOWOVERLAP);
27458 if (ast_true(v->value)) {
27459 ast_set_flag(&flags[1], SIP_PAGE2_ALLOWOVERLAP_YES);
27460 } else if (!strcasecmp(v->value, "dtmf")){
27461 ast_set_flag(&flags[1], SIP_PAGE2_ALLOWOVERLAP_DTMF);
27462 }
27463 } else if (!strcasecmp(v->name, "allowsubscribe")) {
27464 ast_set_flag(&mask[1], SIP_PAGE2_ALLOWSUBSCRIBE);
27465 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWSUBSCRIBE);
27466 } else if (!strcasecmp(v->name, "ignoresdpversion")) {
27467 ast_set_flag(&mask[1], SIP_PAGE2_IGNORESDPVERSION);
27468 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_IGNORESDPVERSION);
27469 } else if (!strcasecmp(v->name, "faxdetect")) {
27470 ast_set_flag(&mask[1], SIP_PAGE2_FAX_DETECT);
27471 if (ast_true(v->value)) {
27472 ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_BOTH);
27473 } else if (ast_false(v->value)) {
27474 ast_clear_flag(&flags[1], SIP_PAGE2_FAX_DETECT_BOTH);
27475 } else {
27476 char *buf = ast_strdupa(v->value);
27477 char *word, *next = buf;
27478
27479 while ((word = strsep(&next, ","))) {
27480 if (!strcasecmp(word, "cng")) {
27481 ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_CNG);
27482 } else if (!strcasecmp(word, "t38")) {
27483 ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_T38);
27484 } else {
27485 ast_log(LOG_WARNING, "Unknown faxdetect mode '%s' on line %d.\n", word, v->lineno);
27486 }
27487 }
27488 }
27489 } else if (!strcasecmp(v->name, "rfc2833compensate")) {
27490 ast_set_flag(&mask[1], SIP_PAGE2_RFC2833_COMPENSATE);
27491 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RFC2833_COMPENSATE);
27492 } else if (!strcasecmp(v->name, "buggymwi")) {
27493 ast_set_flag(&mask[1], SIP_PAGE2_BUGGY_MWI);
27494 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_BUGGY_MWI);
27495 } else
27496 res = 0;
27497
27498 return res;
27499 }
27500
27501
27502 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context)
27503 {
27504 struct domain *d;
27505
27506 if (ast_strlen_zero(domain)) {
27507 ast_log(LOG_WARNING, "Zero length domain.\n");
27508 return 1;
27509 }
27510
27511 if (!(d = ast_calloc(1, sizeof(*d))))
27512 return 0;
27513
27514 ast_copy_string(d->domain, domain, sizeof(d->domain));
27515
27516 if (!ast_strlen_zero(context))
27517 ast_copy_string(d->context, context, sizeof(d->context));
27518
27519 d->mode = mode;
27520
27521 AST_LIST_LOCK(&domain_list);
27522 AST_LIST_INSERT_TAIL(&domain_list, d, list);
27523 AST_LIST_UNLOCK(&domain_list);
27524
27525 if (sipdebug)
27526 ast_debug(1, "Added local SIP domain '%s'\n", domain);
27527
27528 return 1;
27529 }
27530
27531
27532 static int check_sip_domain(const char *domain, char *context, size_t len)
27533 {
27534 struct domain *d;
27535 int result = 0;
27536
27537 AST_LIST_LOCK(&domain_list);
27538 AST_LIST_TRAVERSE(&domain_list, d, list) {
27539 if (strcasecmp(d->domain, domain)) {
27540 continue;
27541 }
27542
27543 if (len && !ast_strlen_zero(d->context))
27544 ast_copy_string(context, d->context, len);
27545
27546 result = 1;
27547 break;
27548 }
27549 AST_LIST_UNLOCK(&domain_list);
27550
27551 return result;
27552 }
27553
27554
27555 static void clear_sip_domains(void)
27556 {
27557 struct domain *d;
27558
27559 AST_LIST_LOCK(&domain_list);
27560 while ((d = AST_LIST_REMOVE_HEAD(&domain_list, list)))
27561 ast_free(d);
27562 AST_LIST_UNLOCK(&domain_list);
27563 }
27564
27565
27566
27567
27568
27569
27570
27571
27572
27573 static void destroy_realm_authentication(void *obj)
27574 {
27575 struct sip_auth_container *credentials = obj;
27576 struct sip_auth *auth;
27577
27578 while ((auth = AST_LIST_REMOVE_HEAD(&credentials->list, node))) {
27579 ast_free(auth);
27580 }
27581 }
27582
27583
27584
27585
27586
27587
27588
27589
27590
27591
27592
27593 static void add_realm_authentication(struct sip_auth_container **credentials, const char *configuration, int lineno)
27594 {
27595 char *authcopy;
27596 char *username=NULL, *realm=NULL, *secret=NULL, *md5secret=NULL;
27597 struct sip_auth *auth;
27598
27599 if (ast_strlen_zero(configuration)) {
27600
27601 return;
27602 }
27603
27604 ast_debug(1, "Auth config :: %s\n", configuration);
27605
27606 authcopy = ast_strdupa(configuration);
27607 username = authcopy;
27608
27609
27610 realm = strrchr(username, '@');
27611 if (realm)
27612 *realm++ = '\0';
27613 if (ast_strlen_zero(username) || ast_strlen_zero(realm)) {
27614 ast_log(LOG_WARNING, "Format for authentication entry is user[:secret]@realm at line %d\n", lineno);
27615 return;
27616 }
27617
27618
27619 if ((secret = strchr(username, ':'))) {
27620 *secret++ = '\0';
27621 } else if ((md5secret = strchr(username, '#'))) {
27622 *md5secret++ = '\0';
27623 }
27624
27625
27626 if (!*credentials) {
27627 *credentials = ao2_t_alloc(sizeof(**credentials), destroy_realm_authentication,
27628 "Create realm auth container.");
27629 if (!*credentials) {
27630
27631 return;
27632 }
27633 }
27634
27635
27636 auth = ast_calloc(1, sizeof(*auth));
27637 if (!auth) {
27638 return;
27639 }
27640 ast_copy_string(auth->realm, realm, sizeof(auth->realm));
27641 ast_copy_string(auth->username, username, sizeof(auth->username));
27642 if (secret)
27643 ast_copy_string(auth->secret, secret, sizeof(auth->secret));
27644 if (md5secret)
27645 ast_copy_string(auth->md5secret, md5secret, sizeof(auth->md5secret));
27646
27647
27648 AST_LIST_INSERT_TAIL(&(*credentials)->list, auth, node);
27649
27650 ast_verb(3, "Added authentication for realm %s\n", realm);
27651 }
27652
27653
27654
27655
27656
27657
27658
27659
27660
27661
27662 static struct sip_auth *find_realm_authentication(struct sip_auth_container *credentials, const char *realm)
27663 {
27664 struct sip_auth *auth;
27665
27666 if (credentials) {
27667 AST_LIST_TRAVERSE(&credentials->list, auth, node) {
27668 if (!strcasecmp(auth->realm, realm)) {
27669 break;
27670 }
27671 }
27672 } else {
27673 auth = NULL;
27674 }
27675
27676 return auth;
27677 }
27678
27679
27680
27681
27682 static struct ast_variable *add_var(const char *buf, struct ast_variable *list)
27683 {
27684 struct ast_variable *tmpvar = NULL;
27685 char *varname = ast_strdupa(buf), *varval = NULL;
27686
27687 if ((varval = strchr(varname, '='))) {
27688 *varval++ = '\0';
27689 if ((tmpvar = ast_variable_new(varname, varval, ""))) {
27690 tmpvar->next = list;
27691 list = tmpvar;
27692 }
27693 }
27694 return list;
27695 }
27696
27697
27698 static void set_peer_defaults(struct sip_peer *peer)
27699 {
27700 if (peer->expire == 0) {
27701
27702
27703
27704 peer->expire = -1;
27705 peer->pokeexpire = -1;
27706 set_socket_transport(&peer->socket, SIP_TRANSPORT_UDP);
27707 }
27708 peer->type = SIP_TYPE_PEER;
27709 ast_copy_flags(&peer->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
27710 ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
27711 ast_copy_flags(&peer->flags[2], &global_flags[2], SIP_PAGE3_FLAGS_TO_COPY);
27712 ast_string_field_set(peer, context, sip_cfg.default_context);
27713 ast_string_field_set(peer, subscribecontext, sip_cfg.default_subscribecontext);
27714 ast_string_field_set(peer, language, default_language);
27715 ast_string_field_set(peer, mohinterpret, default_mohinterpret);
27716 ast_string_field_set(peer, mohsuggest, default_mohsuggest);
27717 ast_string_field_set(peer, engine, default_engine);
27718 ast_sockaddr_setnull(&peer->addr);
27719 ast_sockaddr_setnull(&peer->defaddr);
27720 peer->capability = sip_cfg.capability;
27721 peer->maxcallbitrate = default_maxcallbitrate;
27722 peer->rtptimeout = global_rtptimeout;
27723 peer->rtpholdtimeout = global_rtpholdtimeout;
27724 peer->rtpkeepalive = global_rtpkeepalive;
27725 peer->allowtransfer = sip_cfg.allowtransfer;
27726 peer->autoframing = global_autoframing;
27727 peer->t38_maxdatagram = global_t38_maxdatagram;
27728 peer->qualifyfreq = global_qualifyfreq;
27729 if (global_callcounter)
27730 peer->call_limit=INT_MAX;
27731 ast_string_field_set(peer, vmexten, default_vmexten);
27732 ast_string_field_set(peer, secret, "");
27733 ast_string_field_set(peer, remotesecret, "");
27734 ast_string_field_set(peer, md5secret, "");
27735 ast_string_field_set(peer, cid_num, "");
27736 ast_string_field_set(peer, cid_name, "");
27737 ast_string_field_set(peer, cid_tag, "");
27738 ast_string_field_set(peer, fromdomain, "");
27739 ast_string_field_set(peer, fromuser, "");
27740 ast_string_field_set(peer, regexten, "");
27741 peer->callgroup = 0;
27742 peer->pickupgroup = 0;
27743 peer->maxms = default_qualify;
27744 peer->prefs = default_prefs;
27745 peer->stimer.st_mode_oper = global_st_mode;
27746 peer->stimer.st_ref = global_st_refresher;
27747 peer->stimer.st_min_se = global_min_se;
27748 peer->stimer.st_max_se = global_max_se;
27749 peer->timer_t1 = global_t1;
27750 peer->timer_b = global_timer_b;
27751 clear_peer_mailboxes(peer);
27752 peer->disallowed_methods = sip_cfg.disallowed_methods;
27753 peer->transports = default_transports;
27754 peer->default_outbound_transport = default_primary_transport;
27755 }
27756
27757
27758 static struct sip_peer *temp_peer(const char *name)
27759 {
27760 struct sip_peer *peer;
27761
27762 if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct")))
27763 return NULL;
27764
27765 if (ast_string_field_init(peer, 512)) {
27766 ao2_t_ref(peer, -1, "failed to string_field_init, drop peer");
27767 return NULL;
27768 }
27769
27770 if (!(peer->cc_params = ast_cc_config_params_init())) {
27771 ao2_t_ref(peer, -1, "failed to allocate cc_params for peer");
27772 return NULL;
27773 }
27774
27775 ast_atomic_fetchadd_int(&apeerobjs, 1);
27776 set_peer_defaults(peer);
27777
27778 ast_copy_string(peer->name, name, sizeof(peer->name));
27779
27780 peer->selfdestruct = TRUE;
27781 peer->host_dynamic = TRUE;
27782 peer->prefs = default_prefs;
27783 reg_source_db(peer);
27784
27785 return peer;
27786 }
27787
27788
27789 static void add_peer_mailboxes(struct sip_peer *peer, const char *value)
27790 {
27791 char *next, *mbox, *context;
27792
27793 next = ast_strdupa(value);
27794
27795 while ((mbox = context = strsep(&next, ","))) {
27796 struct sip_mailbox *mailbox;
27797 int duplicate = 0;
27798
27799 mbox = ast_strip(mbox);
27800 strsep(&context, "@");
27801
27802 if (ast_strlen_zero(mbox)) {
27803 continue;
27804 }
27805
27806
27807 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
27808 if (!strcmp(mailbox->mailbox, mbox) && !strcmp(S_OR(mailbox->context, ""), S_OR(context, ""))) {
27809 duplicate = 1;
27810 break;
27811 }
27812 }
27813 if (duplicate) {
27814 continue;
27815 }
27816
27817 if (!(mailbox = ast_calloc(1, sizeof(*mailbox) + strlen(mbox) + strlen(S_OR(context, ""))))) {
27818 continue;
27819 }
27820
27821 if (!ast_strlen_zero(context)) {
27822 mailbox->context = mailbox->mailbox + strlen(mbox) + 1;
27823 strcpy(mailbox->context, context);
27824 }
27825 strcpy(mailbox->mailbox, mbox);
27826
27827 AST_LIST_INSERT_TAIL(&peer->mailboxes, mailbox, entry);
27828 }
27829 }
27830
27831
27832 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only)
27833 {
27834 struct sip_peer *peer = NULL;
27835 struct ast_ha *oldha = NULL;
27836 struct ast_ha *olddirectmediaha = NULL;
27837 int found = 0;
27838 int firstpass = 1;
27839 uint16_t port = 0;
27840 int format = 0;
27841 int timerb_set = 0, timert1_set = 0;
27842 time_t regseconds = 0;
27843 struct ast_flags peerflags[3] = {{(0)}};
27844 struct ast_flags mask[3] = {{(0)}};
27845 char callback[256] = "";
27846 struct sip_peer tmp_peer;
27847 const char *srvlookup = NULL;
27848 static int deprecation_warning = 1;
27849 int alt_fullcontact = alt ? 1 : 0, headercount = 0;
27850 struct ast_str *fullcontact = ast_str_alloca(512);
27851
27852 if (!realtime || ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
27853
27854
27855
27856
27857
27858 ast_copy_string(tmp_peer.name, name, sizeof(tmp_peer.name));
27859 peer = ao2_t_find(peers, &tmp_peer, OBJ_POINTER | OBJ_UNLINK, "find and unlink peer from peers table");
27860 }
27861
27862 if (peer) {
27863
27864 found++;
27865
27866
27867 if (!ast_sockaddr_isnull(&peer->addr)) {
27868 ao2_t_unlink(peers_by_ip, peer, "ao2_unlink peer from peers_by_ip table");
27869 }
27870 if (!(peer->the_mark))
27871 firstpass = 0;
27872 } else {
27873 if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct")))
27874 return NULL;
27875
27876 if (ast_string_field_init(peer, 512)) {
27877 ao2_t_ref(peer, -1, "failed to string_field_init, drop peer");
27878 return NULL;
27879 }
27880
27881 if (!(peer->cc_params = ast_cc_config_params_init())) {
27882 ao2_t_ref(peer, -1, "failed to allocate cc_params for peer");
27883 return NULL;
27884 }
27885
27886 if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
27887 ast_atomic_fetchadd_int(&rpeerobjs, 1);
27888 ast_debug(3, "-REALTIME- peer built. Name: %s. Peer objects: %d\n", name, rpeerobjs);
27889 } else
27890 ast_atomic_fetchadd_int(&speerobjs, 1);
27891 }
27892
27893
27894 if (firstpass) {
27895 peer->lastmsgssent = -1;
27896 oldha = peer->ha;
27897 peer->ha = NULL;
27898 olddirectmediaha = peer->directmediaha;
27899 peer->directmediaha = NULL;
27900 set_peer_defaults(peer);
27901 peer->type = 0;
27902 }
27903
27904
27905 ast_copy_string(peer->name, name, sizeof(peer->name));
27906
27907
27908 if (peer->chanvars) {
27909 ast_variables_destroy(peer->chanvars);
27910 peer->chanvars = NULL;
27911
27912 }
27913
27914 if (found)
27915 peer->portinuri = 0;
27916
27917
27918 ao2_lock(peer);
27919 if (peer->auth) {
27920 ao2_t_ref(peer->auth, -1, "Removing old peer authentication");
27921 peer->auth = NULL;
27922 }
27923 ao2_unlock(peer);
27924
27925
27926 peer->default_outbound_transport = 0;
27927 peer->transports = 0;
27928
27929 if (!devstate_only) {
27930 struct sip_mailbox *mailbox;
27931 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
27932 mailbox->delme = 1;
27933 }
27934 }
27935
27936 for (; v || ((v = alt) && !(alt=NULL)); v = v->next) {
27937 if (!devstate_only) {
27938 if (handle_common_options(&peerflags[0], &mask[0], v)) {
27939 continue;
27940 }
27941 if (handle_t38_options(&peerflags[0], &mask[0], v, &peer->t38_maxdatagram)) {
27942 continue;
27943 }
27944 if (!strcasecmp(v->name, "transport")) {
27945 char *val = ast_strdupa(v->value);
27946 char *trans;
27947
27948 peer->transports = peer->default_outbound_transport = 0;
27949 while ((trans = strsep(&val, ","))) {
27950 trans = ast_skip_blanks(trans);
27951
27952 if (!strncasecmp(trans, "udp", 3)) {
27953 peer->transports |= SIP_TRANSPORT_UDP;
27954 } else if (sip_cfg.tcp_enabled && !strncasecmp(trans, "tcp", 3)) {
27955 peer->transports |= SIP_TRANSPORT_TCP;
27956 } else if (default_tls_cfg.enabled && !strncasecmp(trans, "tls", 3)) {
27957 peer->transports |= SIP_TRANSPORT_TLS;
27958 } else if (!strncasecmp(trans, "tcp", 3) || !strncasecmp(trans, "tls", 3)) {
27959 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);
27960 } else {
27961 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);
27962 }
27963
27964 if (!peer->default_outbound_transport) {
27965 peer->default_outbound_transport = peer->transports;
27966 }
27967 }
27968 } else if (realtime && !strcasecmp(v->name, "regseconds")) {
27969 ast_get_time_t(v->value, ®seconds, 0, NULL);
27970 } else if (realtime && !strcasecmp(v->name, "name")) {
27971 ast_copy_string(peer->name, v->value, sizeof(peer->name));
27972 } else if (realtime && !strcasecmp(v->name, "useragent")) {
27973 ast_string_field_set(peer, useragent, v->value);
27974 } else if (!strcasecmp(v->name, "type")) {
27975 if (!strcasecmp(v->value, "peer")) {
27976 peer->type |= SIP_TYPE_PEER;
27977 } else if (!strcasecmp(v->value, "user")) {
27978 peer->type |= SIP_TYPE_USER;
27979 } else if (!strcasecmp(v->value, "friend")) {
27980 peer->type = SIP_TYPE_USER | SIP_TYPE_PEER;
27981 }
27982 } else if (!strcasecmp(v->name, "remotesecret")) {
27983 ast_string_field_set(peer, remotesecret, v->value);
27984 } else if (!strcasecmp(v->name, "secret")) {
27985 ast_string_field_set(peer, secret, v->value);
27986 } else if (!strcasecmp(v->name, "md5secret")) {
27987 ast_string_field_set(peer, md5secret, v->value);
27988 } else if (!strcasecmp(v->name, "auth")) {
27989 add_realm_authentication(&peer->auth, v->value, v->lineno);
27990 } else if (!strcasecmp(v->name, "callerid")) {
27991 char cid_name[80] = { '\0' }, cid_num[80] = { '\0' };
27992
27993 ast_callerid_split(v->value, cid_name, sizeof(cid_name), cid_num, sizeof(cid_num));
27994 ast_string_field_set(peer, cid_name, cid_name);
27995 ast_string_field_set(peer, cid_num, cid_num);
27996 } else if (!strcasecmp(v->name, "mwi_from")) {
27997 ast_string_field_set(peer, mwi_from, v->value);
27998 } else if (!strcasecmp(v->name, "fullname")) {
27999 ast_string_field_set(peer, cid_name, v->value);
28000 } else if (!strcasecmp(v->name, "trunkname")) {
28001
28002 ast_string_field_set(peer, cid_name, "");
28003 } else if (!strcasecmp(v->name, "cid_number")) {
28004 ast_string_field_set(peer, cid_num, v->value);
28005 } else if (!strcasecmp(v->name, "cid_tag")) {
28006 ast_string_field_set(peer, cid_tag, v->value);
28007 } else if (!strcasecmp(v->name, "context")) {
28008 ast_string_field_set(peer, context, v->value);
28009 ast_set_flag(&peer->flags[1], SIP_PAGE2_HAVEPEERCONTEXT);
28010 } else if (!strcasecmp(v->name, "subscribecontext")) {
28011 ast_string_field_set(peer, subscribecontext, v->value);
28012 } else if (!strcasecmp(v->name, "fromdomain")) {
28013 char *fromdomainport;
28014 ast_string_field_set(peer, fromdomain, v->value);
28015 if ((fromdomainport = strchr(peer->fromdomain, ':'))) {
28016 *fromdomainport++ = '\0';
28017 if (!(peer->fromdomainport = port_str2int(fromdomainport, 0))) {
28018 ast_log(LOG_NOTICE, "'%s' is not a valid port number for fromdomain.\n",fromdomainport);
28019 }
28020 } else {
28021 peer->fromdomainport = STANDARD_SIP_PORT;
28022 }
28023 } else if (!strcasecmp(v->name, "usereqphone")) {
28024 ast_set2_flag(&peer->flags[0], ast_true(v->value), SIP_USEREQPHONE);
28025 } else if (!strcasecmp(v->name, "fromuser")) {
28026 ast_string_field_set(peer, fromuser, v->value);
28027 } else if (!strcasecmp(v->name, "outboundproxy")) {
28028 struct sip_proxy *proxy;
28029 if (ast_strlen_zero(v->value)) {
28030 ast_log(LOG_WARNING, "no value given for outbound proxy on line %d of sip.conf\n", v->lineno);
28031 continue;
28032 }
28033 proxy = proxy_from_config(v->value, v->lineno, peer->outboundproxy);
28034 if (!proxy) {
28035 ast_log(LOG_WARNING, "failure parsing the outbound proxy on line %d of sip.conf.\n", v->lineno);
28036 continue;
28037 }
28038 peer->outboundproxy = proxy;
28039 } else if (!strcasecmp(v->name, "host")) {
28040 if (!strcasecmp(v->value, "dynamic")) {
28041
28042 if ((!found && !realtime) || !peer->host_dynamic) {
28043
28044
28045 ast_sockaddr_setnull(&peer->addr);
28046 }
28047 peer->host_dynamic = TRUE;
28048 } else {
28049
28050 AST_SCHED_DEL_UNREF(sched, peer->expire,
28051 unref_peer(peer, "removing register expire ref"));
28052 peer->host_dynamic = FALSE;
28053 srvlookup = v->value;
28054 }
28055 } else if (!strcasecmp(v->name, "defaultip")) {
28056 if (!ast_strlen_zero(v->value) && ast_get_ip(&peer->defaddr, v->value)) {
28057 unref_peer(peer, "unref_peer: from build_peer defaultip");
28058 return NULL;
28059 }
28060 } else if (!strcasecmp(v->name, "permit") || !strcasecmp(v->name, "deny")) {
28061 int ha_error = 0;
28062 if (!ast_strlen_zero(v->value)) {
28063 peer->ha = ast_append_ha(v->name, v->value, peer->ha, &ha_error);
28064 }
28065 if (ha_error) {
28066 ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
28067 }
28068 } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny")) {
28069 int ha_error = 0;
28070 if (!ast_strlen_zero(v->value)) {
28071 peer->contactha = ast_append_ha(v->name + 7, v->value, peer->contactha, &ha_error);
28072 }
28073 if (ha_error) {
28074 ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
28075 }
28076 } else if (!strcasecmp(v->name, "directmediapermit") || !strcasecmp(v->name, "directmediadeny")) {
28077 int ha_error = 0;
28078 peer->directmediaha = ast_append_ha(v->name + 11, v->value, peer->directmediaha, &ha_error);
28079 if (ha_error) {
28080 ast_log(LOG_ERROR, "Bad directmedia ACL entry in configuration line %d : %s\n", v->lineno, v->value);
28081 }
28082 } else if (!strcasecmp(v->name, "port")) {
28083 peer->portinuri = 1;
28084 if (!(port = port_str2int(v->value, 0))) {
28085 if (realtime) {
28086
28087 peer->portinuri = 0;
28088 } else {
28089 ast_log(LOG_WARNING, "Invalid peer port configuration at line %d : %s\n", v->lineno, v->value);
28090 }
28091 }
28092 } else if (!strcasecmp(v->name, "callingpres")) {
28093 peer->callingpres = ast_parse_caller_presentation(v->value);
28094 if (peer->callingpres == -1) {
28095 peer->callingpres = atoi(v->value);
28096 }
28097 } else if (!strcasecmp(v->name, "username") || !strcmp(v->name, "defaultuser")) {
28098 ast_string_field_set(peer, username, v->value);
28099 if (!strcasecmp(v->name, "username")) {
28100 if (deprecation_warning) {
28101 ast_log(LOG_NOTICE, "The 'username' field for sip peers has been deprecated in favor of the term 'defaultuser'\n");
28102 deprecation_warning = 0;
28103 }
28104 peer->deprecated_username = 1;
28105 }
28106 } else if (!strcasecmp(v->name, "language")) {
28107 ast_string_field_set(peer, language, v->value);
28108 } else if (!strcasecmp(v->name, "regexten")) {
28109 ast_string_field_set(peer, regexten, v->value);
28110 } else if (!strcasecmp(v->name, "callbackextension")) {
28111 ast_copy_string(callback, v->value, sizeof(callback));
28112 } else if (!strcasecmp(v->name, "amaflags")) {
28113 format = ast_cdr_amaflags2int(v->value);
28114 if (format < 0) {
28115 ast_log(LOG_WARNING, "Invalid AMA Flags for peer: %s at line %d\n", v->value, v->lineno);
28116 } else {
28117 peer->amaflags = format;
28118 }
28119 } else if (!strcasecmp(v->name, "maxforwards")) {
28120 if (sscanf(v->value, "%30d", &peer->maxforwards) != 1
28121 || peer->maxforwards < 1 || 255 < peer->maxforwards) {
28122 ast_log(LOG_WARNING, "'%s' is not a valid maxforwards value at line %d. Using default.\n", v->value, v->lineno);
28123 peer->maxforwards = sip_cfg.default_max_forwards;
28124 }
28125 } else if (!strcasecmp(v->name, "accountcode")) {
28126 ast_string_field_set(peer, accountcode, v->value);
28127 } else if (!strcasecmp(v->name, "mohinterpret")) {
28128 ast_string_field_set(peer, mohinterpret, v->value);
28129 } else if (!strcasecmp(v->name, "mohsuggest")) {
28130 ast_string_field_set(peer, mohsuggest, v->value);
28131 } else if (!strcasecmp(v->name, "parkinglot")) {
28132 ast_string_field_set(peer, parkinglot, v->value);
28133 } else if (!strcasecmp(v->name, "rtp_engine")) {
28134 ast_string_field_set(peer, engine, v->value);
28135 } else if (!strcasecmp(v->name, "mailbox")) {
28136 add_peer_mailboxes(peer, v->value);
28137 } else if (!strcasecmp(v->name, "hasvoicemail")) {
28138
28139
28140 if (ast_true(v->value) && AST_LIST_EMPTY(&peer->mailboxes)) {
28141 add_peer_mailboxes(peer, name);
28142 }
28143 } else if (!strcasecmp(v->name, "subscribemwi")) {
28144 ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_SUBSCRIBEMWIONLY);
28145 } else if (!strcasecmp(v->name, "vmexten")) {
28146 ast_string_field_set(peer, vmexten, v->value);
28147 } else if (!strcasecmp(v->name, "callgroup")) {
28148 peer->callgroup = ast_get_group(v->value);
28149 } else if (!strcasecmp(v->name, "allowtransfer")) {
28150 peer->allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
28151 } else if (!strcasecmp(v->name, "pickupgroup")) {
28152 peer->pickupgroup = ast_get_group(v->value);
28153 } else if (!strcasecmp(v->name, "allow")) {
28154 int error = ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, TRUE);
28155 if (error) {
28156 ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
28157 }
28158 } else if (!strcasecmp(v->name, "disallow")) {
28159 int error = ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, FALSE);
28160 if (error) {
28161 ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
28162 }
28163 } else if (!strcasecmp(v->name, "preferred_codec_only")) {
28164 ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_PREFERRED_CODEC);
28165 } else if (!strcasecmp(v->name, "autoframing")) {
28166 peer->autoframing = ast_true(v->value);
28167 } else if (!strcasecmp(v->name, "rtptimeout")) {
28168 if ((sscanf(v->value, "%30d", &peer->rtptimeout) != 1) || (peer->rtptimeout < 0)) {
28169 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
28170 peer->rtptimeout = global_rtptimeout;
28171 }
28172 } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
28173 if ((sscanf(v->value, "%30d", &peer->rtpholdtimeout) != 1) || (peer->rtpholdtimeout < 0)) {
28174 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
28175 peer->rtpholdtimeout = global_rtpholdtimeout;
28176 }
28177 } else if (!strcasecmp(v->name, "rtpkeepalive")) {
28178 if ((sscanf(v->value, "%30d", &peer->rtpkeepalive) != 1) || (peer->rtpkeepalive < 0)) {
28179 ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d. Using default.\n", v->value, v->lineno);
28180 peer->rtpkeepalive = global_rtpkeepalive;
28181 }
28182 } else if (!strcasecmp(v->name, "timert1")) {
28183 if ((sscanf(v->value, "%30d", &peer->timer_t1) != 1) || (peer->timer_t1 < 200) || (peer->timer_t1 < global_t1min)) {
28184 ast_log(LOG_WARNING, "'%s' is not a valid T1 time at line %d. Using default.\n", v->value, v->lineno);
28185 peer->timer_t1 = global_t1min;
28186 }
28187 timert1_set = 1;
28188 } else if (!strcasecmp(v->name, "timerb")) {
28189 if ((sscanf(v->value, "%30d", &peer->timer_b) != 1) || (peer->timer_b < 200)) {
28190 ast_log(LOG_WARNING, "'%s' is not a valid Timer B time at line %d. Using default.\n", v->value, v->lineno);
28191 peer->timer_b = global_timer_b;
28192 }
28193 timerb_set = 1;
28194 } else if (!strcasecmp(v->name, "setvar")) {
28195 peer->chanvars = add_var(v->value, peer->chanvars);
28196 } else if (!strcasecmp(v->name, "header")) {
28197 char tmp[4096];
28198 snprintf(tmp, sizeof(tmp), "__SIPADDHEADERpre%2d=%s", ++headercount, v->value);
28199 peer->chanvars = add_var(tmp, peer->chanvars);
28200 } else if (!strcasecmp(v->name, "qualifyfreq")) {
28201 int i;
28202 if (sscanf(v->value, "%30d", &i) == 1) {
28203 peer->qualifyfreq = i * 1000;
28204 } else {
28205 ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
28206 peer->qualifyfreq = global_qualifyfreq;
28207 }
28208 } else if (!strcasecmp(v->name, "maxcallbitrate")) {
28209 peer->maxcallbitrate = atoi(v->value);
28210 if (peer->maxcallbitrate < 0) {
28211 peer->maxcallbitrate = default_maxcallbitrate;
28212 }
28213 } else if (!strcasecmp(v->name, "session-timers")) {
28214 int i = (int) str2stmode(v->value);
28215 if (i < 0) {
28216 ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
28217 peer->stimer.st_mode_oper = global_st_mode;
28218 } else {
28219 peer->stimer.st_mode_oper = i;
28220 }
28221 } else if (!strcasecmp(v->name, "session-expires")) {
28222 if (sscanf(v->value, "%30d", &peer->stimer.st_max_se) != 1) {
28223 ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
28224 peer->stimer.st_max_se = global_max_se;
28225 }
28226 } else if (!strcasecmp(v->name, "session-minse")) {
28227 if (sscanf(v->value, "%30d", &peer->stimer.st_min_se) != 1) {
28228 ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
28229 peer->stimer.st_min_se = global_min_se;
28230 }
28231 if (peer->stimer.st_min_se < 90) {
28232 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);
28233 peer->stimer.st_min_se = global_min_se;
28234 }
28235 } else if (!strcasecmp(v->name, "session-refresher")) {
28236 int i = (int) str2strefresherparam(v->value);
28237 if (i < 0) {
28238 ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
28239 peer->stimer.st_ref = global_st_refresher;
28240 } else {
28241 peer->stimer.st_ref = i;
28242 }
28243 } else if (!strcasecmp(v->name, "disallowed_methods")) {
28244 char *disallow = ast_strdupa(v->value);
28245 mark_parsed_methods(&peer->disallowed_methods, disallow);
28246 } else if (!strcasecmp(v->name, "unsolicited_mailbox")) {
28247 ast_string_field_set(peer, unsolicited_mailbox, v->value);
28248 } else if (!strcasecmp(v->name, "use_q850_reason")) {
28249 ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_Q850_REASON);
28250 } else if (!strcasecmp(v->name, "encryption")) {
28251 ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_USE_SRTP);
28252 } else if (!strcasecmp(v->name, "snom_aoc_enabled")) {
28253 ast_set2_flag(&peer->flags[2], ast_true(v->value), SIP_PAGE3_SNOM_AOC);
28254 }
28255 }
28256
28257
28258 if (realtime && !strcasecmp(v->name, "lastms")) {
28259 sscanf(v->value, "%30d", &peer->lastms);
28260 } else if (realtime && !strcasecmp(v->name, "ipaddr") && !ast_strlen_zero(v->value) ) {
28261 ast_sockaddr_parse(&peer->addr, v->value, PARSE_PORT_FORBID);
28262 } else if (realtime && !strcasecmp(v->name, "fullcontact")) {
28263 if (alt_fullcontact && !alt) {
28264
28265
28266
28267
28268
28269 alt_fullcontact = 0;
28270 ast_str_reset(fullcontact);
28271 }
28272
28273 if (ast_str_strlen(fullcontact) > 0) {
28274 ast_str_append(&fullcontact, 0, ";%s", v->value);
28275 } else {
28276 ast_str_set(&fullcontact, 0, "%s", v->value);
28277 }
28278 } else if (!strcasecmp(v->name, "qualify")) {
28279 if (!strcasecmp(v->value, "no")) {
28280 peer->maxms = 0;
28281 } else if (!strcasecmp(v->value, "yes")) {
28282 peer->maxms = default_qualify ? default_qualify : DEFAULT_MAXMS;
28283 } else if (sscanf(v->value, "%30d", &peer->maxms) != 1) {
28284 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);
28285 peer->maxms = 0;
28286 }
28287 if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && peer->maxms > 0) {
28288
28289
28290
28291
28292 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);
28293 peer->maxms = 0;
28294 }
28295 } else if (!strcasecmp(v->name, "callcounter")) {
28296 peer->call_limit = ast_true(v->value) ? INT_MAX : 0;
28297 } else if (!strcasecmp(v->name, "call-limit")) {
28298 peer->call_limit = atoi(v->value);
28299 if (peer->call_limit < 0) {
28300 peer->call_limit = 0;
28301 }
28302 } else if (!strcasecmp(v->name, "busylevel")) {
28303 peer->busy_level = atoi(v->value);
28304 if (peer->busy_level < 0) {
28305 peer->busy_level = 0;
28306 }
28307 } else if (ast_cc_is_config_param(v->name)) {
28308 ast_cc_set_param(peer->cc_params, v->name, v->value);
28309 }
28310 }
28311
28312 if (!devstate_only) {
28313 struct sip_mailbox *mailbox;
28314 AST_LIST_TRAVERSE_SAFE_BEGIN(&peer->mailboxes, mailbox, entry) {
28315 if (mailbox->delme) {
28316 AST_LIST_REMOVE_CURRENT(entry);
28317 destroy_mailbox(mailbox);
28318 }
28319 }
28320 AST_LIST_TRAVERSE_SAFE_END;
28321 }
28322
28323 if (!can_parse_xml && (ast_get_cc_agent_policy(peer->cc_params) == AST_CC_AGENT_NATIVE)) {
28324 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);
28325 ast_set_cc_agent_policy(peer->cc_params, AST_CC_AGENT_NEVER);
28326 }
28327
28328
28329
28330 if (peer->timer_b < peer->timer_t1 * 64) {
28331 if (timerb_set && timert1_set) {
28332 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);
28333 } else if (timerb_set) {
28334 if ((peer->timer_t1 = peer->timer_b / 64) < global_t1min) {
28335 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);
28336 peer->timer_t1 = global_t1min;
28337 peer->timer_b = peer->timer_t1 * 64;
28338 }
28339 peer->timer_t1 = peer->timer_b / 64;
28340 } else {
28341 peer->timer_b = peer->timer_t1 * 64;
28342 }
28343 }
28344
28345 if (!peer->default_outbound_transport) {
28346
28347 peer->transports = default_transports;
28348
28349 peer->default_outbound_transport = default_primary_transport;
28350 }
28351
28352
28353
28354
28355
28356 if (((peer->socket.type != peer->default_outbound_transport) && (peer->expire == -1)) ||
28357 !(peer->socket.type & peer->transports) || !(peer->socket.type)) {
28358
28359 set_socket_transport(&peer->socket, peer->default_outbound_transport);
28360 }
28361
28362 if (ast_str_strlen(fullcontact)) {
28363 ast_string_field_set(peer, fullcontact, ast_str_buffer(fullcontact));
28364 peer->rt_fromcontact = TRUE;
28365
28366
28367
28368
28369
28370
28371
28372
28373 if (!ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) || ast_sockaddr_isnull(&peer->addr)) {
28374 __set_address_from_contact(ast_str_buffer(fullcontact), &peer->addr, 0);
28375 }
28376 }
28377
28378 if (srvlookup && peer->dnsmgr == NULL) {
28379 char transport[MAXHOSTNAMELEN];
28380 char _srvlookup[MAXHOSTNAMELEN];
28381 char *params;
28382
28383 ast_copy_string(_srvlookup, srvlookup, sizeof(_srvlookup));
28384 if ((params = strchr(_srvlookup, ';'))) {
28385 *params++ = '\0';
28386 }
28387
28388 snprintf(transport, sizeof(transport), "_%s._%s", get_srv_service(peer->socket.type), get_srv_protocol(peer->socket.type));
28389
28390 peer->addr.ss.ss_family = get_address_family_filter(peer->socket.type);
28391 if (ast_dnsmgr_lookup_cb(_srvlookup, &peer->addr, &peer->dnsmgr, sip_cfg.srvlookup && !peer->portinuri ? transport : NULL,
28392 on_dns_update_peer, ref_peer(peer, "Store peer on dnsmgr"))) {
28393 ast_log(LOG_ERROR, "srvlookup failed for host: %s, on peer %s, removing peer\n", _srvlookup, peer->name);
28394 unref_peer(peer, "dnsmgr lookup failed, getting rid of peer dnsmgr ref");
28395 unref_peer(peer, "getting rid of a peer pointer");
28396 return NULL;
28397 }
28398 if (!peer->dnsmgr) {
28399
28400 unref_peer(peer, "dnsmgr disabled, unref peer");
28401 }
28402
28403 ast_string_field_set(peer, tohost, srvlookup);
28404
28405 if (global_dynamic_exclude_static && !ast_sockaddr_isnull(&peer->addr)) {
28406 int ha_error = 0;
28407 sip_cfg.contact_ha = ast_append_ha("deny", ast_sockaddr_stringify_addr(&peer->addr),
28408 sip_cfg.contact_ha, &ha_error);
28409 if (ha_error) {
28410 ast_log(LOG_ERROR, "Bad or unresolved host/IP entry in configuration for peer %s, cannot add to contact ACL\n", peer->name);
28411 }
28412 }
28413 } else if (peer->dnsmgr && !peer->host_dynamic) {
28414
28415 ast_dnsmgr_refresh(peer->dnsmgr);
28416 }
28417
28418 if (port && !realtime && peer->host_dynamic) {
28419 ast_sockaddr_set_port(&peer->defaddr, port);
28420 } else if (port) {
28421 ast_sockaddr_set_port(&peer->addr, port);
28422 }
28423
28424 if (ast_sockaddr_port(&peer->addr) == 0) {
28425 ast_sockaddr_set_port(&peer->addr,
28426 (peer->socket.type & SIP_TRANSPORT_TLS) ?
28427 STANDARD_TLS_PORT : STANDARD_SIP_PORT);
28428 }
28429 if (ast_sockaddr_port(&peer->defaddr) == 0) {
28430 ast_sockaddr_set_port(&peer->defaddr,
28431 (peer->socket.type & SIP_TRANSPORT_TLS) ?
28432 STANDARD_TLS_PORT : STANDARD_SIP_PORT);
28433 }
28434 if (!peer->socket.port) {
28435 peer->socket.port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
28436 }
28437
28438 if (!sip_cfg.ignore_regexpire && peer->host_dynamic && realtime) {
28439 time_t nowtime = time(NULL);
28440
28441 if ((nowtime - regseconds) > 0) {
28442 destroy_association(peer);
28443 memset(&peer->addr, 0, sizeof(peer->addr));
28444 peer->lastms = -1;
28445 ast_debug(1, "Bah, we're expired (%d/%d/%d)!\n", (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
28446 }
28447 }
28448
28449
28450 if (!devstate_only && realtime && peer->lastms > 0) {
28451 ref_peer(peer, "schedule qualify");
28452 sip_poke_peer(peer, 0);
28453 }
28454
28455 ast_copy_flags(&peer->flags[0], &peerflags[0], mask[0].flags);
28456 ast_copy_flags(&peer->flags[1], &peerflags[1], mask[1].flags);
28457 ast_copy_flags(&peer->flags[2], &peerflags[2], mask[2].flags);
28458 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
28459 sip_cfg.allowsubscribe = TRUE;
28460 }
28461
28462 if (peer->host_dynamic && (!peer->is_realtime || !sip_cfg.peer_rtupdate)) {
28463 reg_source_db(peer);
28464 }
28465
28466
28467
28468 if (!devstate_only && !ast_test_flag(&peer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY) &&
28469 !AST_LIST_EMPTY(&peer->mailboxes)) {
28470 add_peer_mwi_subs(peer);
28471
28472
28473
28474 sip_send_mwi_to_peer(peer, 1);
28475 }
28476
28477 peer->the_mark = 0;
28478
28479 ast_free_ha(oldha);
28480 ast_free_ha(olddirectmediaha);
28481 if (!ast_strlen_zero(callback)) {
28482 char *reg_string;
28483 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) {
28484 sip_register(reg_string, 0);
28485 ast_free(reg_string);
28486 }
28487 }
28488 return peer;
28489 }
28490
28491 static int peer_markall_func(void *device, void *arg, int flags)
28492 {
28493 struct sip_peer *peer = device;
28494 peer->the_mark = 1;
28495 return 0;
28496 }
28497
28498 static void display_nat_warning(const char *cat, int reason, struct ast_flags *flags) {
28499 int global_nat, specific_nat;
28500
28501 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))) {
28502 ast_log(LOG_WARNING, "!!! PLEASE NOTE: Setting 'nat' for a peer/user that differs from the global setting can make\n");
28503 ast_log(LOG_WARNING, "!!! the name of that peer/user discoverable by an attacker. Replies for non-existent peers/users\n");
28504 ast_log(LOG_WARNING, "!!! will be sent to a different port than replies for an existing peer/user. If at all possible,\n");
28505 ast_log(LOG_WARNING, "!!! use the global 'nat' setting and do not set 'nat' per peer/user.\n");
28506 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));
28507 }
28508 }
28509
28510 static void cleanup_all_regs(void)
28511 {
28512
28513
28514 ASTOBJ_CONTAINER_TRAVERSE(®l, 1, do {
28515 ASTOBJ_WRLOCK(iterator);
28516 if (iterator->call) {
28517 ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", iterator->username, iterator->hostname);
28518
28519 dialog_unlink_all(iterator->call);
28520 iterator->call = dialog_unref(iterator->call, "remove iterator->call from registry traversal");
28521 }
28522 if (iterator->expire > -1) {
28523 AST_SCHED_DEL_UNREF(sched, iterator->expire, registry_unref(iterator, "reg ptr unref from reload config"));
28524 }
28525 if (iterator->timeout > -1) {
28526 AST_SCHED_DEL_UNREF(sched, iterator->timeout, registry_unref(iterator, "reg ptr unref from reload config"));
28527 }
28528 if (iterator->dnsmgr) {
28529 ast_dnsmgr_release(iterator->dnsmgr);
28530 iterator->dnsmgr = NULL;
28531 registry_unref(iterator, "reg ptr unref from dnsmgr");
28532 }
28533 ASTOBJ_UNLOCK(iterator);
28534 } while(0));
28535 }
28536
28537
28538
28539
28540
28541
28542
28543 static int reload_config(enum channelreloadreason reason)
28544 {
28545 struct ast_config *cfg, *ucfg;
28546 struct ast_variable *v;
28547 struct sip_peer *peer;
28548 char *cat, *stringp, *context, *oldregcontext;
28549 char newcontexts[AST_MAX_CONTEXT], oldcontexts[AST_MAX_CONTEXT];
28550 struct ast_flags dummy[2];
28551 struct ast_flags config_flags = { reason == CHANNEL_MODULE_LOAD ? 0 : ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) ? 0 : CONFIG_FLAG_FILEUNCHANGED };
28552 int auto_sip_domains = FALSE;
28553 struct ast_sockaddr old_bindaddr = bindaddr;
28554 int registry_count = 0, peer_count = 0, timerb_set = 0, timert1_set = 0;
28555 int subscribe_network_change = 1;
28556 time_t run_start, run_end;
28557 int bindport = 0;
28558
28559 run_start = time(0);
28560 ast_unload_realtime("sipregs");
28561 ast_unload_realtime("sippeers");
28562 cfg = ast_config_load(config, config_flags);
28563
28564
28565 if (!cfg) {
28566 ast_log(LOG_NOTICE, "Unable to load config %s\n", config);
28567 return -1;
28568 } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
28569 ucfg = ast_config_load("users.conf", config_flags);
28570 if (ucfg == CONFIG_STATUS_FILEUNCHANGED) {
28571 return 1;
28572 } else if (ucfg == CONFIG_STATUS_FILEINVALID) {
28573 ast_log(LOG_ERROR, "Contents of users.conf are invalid and cannot be parsed\n");
28574 return 1;
28575 }
28576
28577 ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
28578 if ((cfg = ast_config_load(config, config_flags)) == CONFIG_STATUS_FILEINVALID) {
28579 ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed\n", config);
28580 ast_config_destroy(ucfg);
28581 return 1;
28582 }
28583 if (!cfg) {
28584
28585 ast_log(LOG_NOTICE, "Unable to load config %s\n", config);
28586 return -1;
28587 }
28588 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
28589 ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed\n", config);
28590 return 1;
28591 } else {
28592 ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
28593 if ((ucfg = ast_config_load("users.conf", config_flags)) == CONFIG_STATUS_FILEINVALID) {
28594 ast_log(LOG_ERROR, "Contents of users.conf are invalid and cannot be parsed\n");
28595 ast_config_destroy(cfg);
28596 return 1;
28597 }
28598 }
28599
28600 ast_free_ha(sip_cfg.contact_ha);
28601 sip_cfg.contact_ha = NULL;
28602
28603 default_tls_cfg.enabled = FALSE;
28604
28605 if (reason != CHANNEL_MODULE_LOAD) {
28606 ast_debug(4, "--------------- SIP reload started\n");
28607
28608 clear_sip_domains();
28609 ast_mutex_lock(&authl_lock);
28610 if (authl) {
28611 ao2_t_ref(authl, -1, "Removing old global authentication");
28612 authl = NULL;
28613 }
28614 ast_mutex_unlock(&authl_lock);
28615
28616
28617 cleanup_all_regs();
28618
28619 ASTOBJ_CONTAINER_DESTROYALL(®l, sip_registry_destroy);
28620 ast_debug(4, "--------------- Done destroying registry list\n");
28621 ao2_t_callback(peers, OBJ_NODATA, peer_markall_func, NULL, "callback to mark all peers");
28622 }
28623
28624
28625 if (reason != CHANNEL_MODULE_LOAD) {
28626 ast_free(default_tls_cfg.certfile);
28627 ast_free(default_tls_cfg.pvtfile);
28628 ast_free(default_tls_cfg.cipher);
28629 ast_free(default_tls_cfg.cafile);
28630 ast_free(default_tls_cfg.capath);
28631 }
28632 default_tls_cfg.certfile = ast_strdup(AST_CERTFILE);
28633 default_tls_cfg.pvtfile = ast_strdup("");
28634 default_tls_cfg.cipher = ast_strdup("");
28635 default_tls_cfg.cafile = ast_strdup("");
28636 default_tls_cfg.capath = ast_strdup("");
28637
28638
28639 ast_copy_string(oldcontexts, sip_cfg.regcontext, sizeof(oldcontexts));
28640 oldregcontext = oldcontexts;
28641
28642
28643
28644 sipdebug &= sip_debug_console;
28645 ast_clear_flag(&global_flags[0], AST_FLAGS_ALL);
28646 ast_clear_flag(&global_flags[1], AST_FLAGS_ALL);
28647 ast_clear_flag(&global_flags[2], AST_FLAGS_ALL);
28648
28649
28650 ast_sockaddr_parse(&bindaddr, "0.0.0.0:0", 0);
28651 memset(&internip, 0, sizeof(internip));
28652
28653
28654 ast_free_ha(localaddr);
28655 memset(&localaddr, 0, sizeof(localaddr));
28656 memset(&externaddr, 0, sizeof(externaddr));
28657 memset(&media_address, 0, sizeof(media_address));
28658 memset(&default_prefs, 0 , sizeof(default_prefs));
28659 memset(&sip_cfg.outboundproxy, 0, sizeof(struct sip_proxy));
28660 sip_cfg.outboundproxy.force = FALSE;
28661 default_transports = SIP_TRANSPORT_UDP;
28662 default_primary_transport = SIP_TRANSPORT_UDP;
28663 ourport_tcp = STANDARD_SIP_PORT;
28664 ourport_tls = STANDARD_TLS_PORT;
28665 externtcpport = STANDARD_SIP_PORT;
28666 externtlsport = STANDARD_TLS_PORT;
28667 sip_cfg.srvlookup = DEFAULT_SRVLOOKUP;
28668 global_tos_sip = DEFAULT_TOS_SIP;
28669 global_tos_audio = DEFAULT_TOS_AUDIO;
28670 global_tos_video = DEFAULT_TOS_VIDEO;
28671 global_tos_text = DEFAULT_TOS_TEXT;
28672 global_cos_sip = DEFAULT_COS_SIP;
28673 global_cos_audio = DEFAULT_COS_AUDIO;
28674 global_cos_video = DEFAULT_COS_VIDEO;
28675 global_cos_text = DEFAULT_COS_TEXT;
28676
28677 externhost[0] = '\0';
28678 externexpire = 0;
28679 externrefresh = 10;
28680
28681
28682 sip_cfg.allow_external_domains = DEFAULT_ALLOW_EXT_DOM;
28683 sip_cfg.regcontext[0] = '\0';
28684 sip_cfg.capability = DEFAULT_CAPABILITY;
28685 sip_cfg.regextenonqualify = DEFAULT_REGEXTENONQUALIFY;
28686 sip_cfg.legacy_useroption_parsing = DEFAULT_LEGACY_USEROPTION_PARSING;
28687 sip_cfg.notifyringing = DEFAULT_NOTIFYRINGING;
28688 sip_cfg.notifycid = DEFAULT_NOTIFYCID;
28689 sip_cfg.notifyhold = FALSE;
28690 sip_cfg.directrtpsetup = FALSE;
28691 sip_cfg.alwaysauthreject = DEFAULT_ALWAYSAUTHREJECT;
28692 sip_cfg.auth_options_requests = DEFAULT_AUTH_OPTIONS;
28693 sip_cfg.allowsubscribe = FALSE;
28694 sip_cfg.disallowed_methods = SIP_UNKNOWN;
28695 sip_cfg.contact_ha = NULL;
28696 snprintf(global_useragent, sizeof(global_useragent), "%s %s", DEFAULT_USERAGENT, ast_get_version());
28697 snprintf(global_sdpsession, sizeof(global_sdpsession), "%s %s", DEFAULT_SDPSESSION, ast_get_version());
28698 snprintf(global_sdpowner, sizeof(global_sdpowner), "%s", DEFAULT_SDPOWNER);
28699 global_prematuremediafilter = TRUE;
28700 ast_copy_string(default_notifymime, DEFAULT_NOTIFYMIME, sizeof(default_notifymime));
28701 ast_copy_string(sip_cfg.realm, S_OR(ast_config_AST_SYSTEM_NAME, DEFAULT_REALM), sizeof(sip_cfg.realm));
28702 sip_cfg.domainsasrealm = DEFAULT_DOMAINSASREALM;
28703 ast_copy_string(default_callerid, DEFAULT_CALLERID, sizeof(default_callerid));
28704 ast_copy_string(default_mwi_from, DEFAULT_MWI_FROM, sizeof(default_mwi_from));
28705 sip_cfg.compactheaders = DEFAULT_COMPACTHEADERS;
28706 global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
28707 global_regattempts_max = 0;
28708 sip_cfg.pedanticsipchecking = DEFAULT_PEDANTIC;
28709 sip_cfg.autocreatepeer = DEFAULT_AUTOCREATEPEER;
28710 global_autoframing = 0;
28711 sip_cfg.allowguest = DEFAULT_ALLOWGUEST;
28712 global_callcounter = DEFAULT_CALLCOUNTER;
28713 global_match_auth_username = FALSE;
28714 global_rtptimeout = 0;
28715 global_rtpholdtimeout = 0;
28716 global_rtpkeepalive = DEFAULT_RTPKEEPALIVE;
28717 sip_cfg.allowtransfer = TRANSFER_OPENFORALL;
28718 sip_cfg.rtautoclear = 120;
28719 ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE);
28720 ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP_YES);
28721 sip_cfg.peer_rtupdate = TRUE;
28722 global_dynamic_exclude_static = 0;
28723 sip_cfg.tcp_enabled = FALSE;
28724
28725
28726 global_st_mode = SESSION_TIMER_MODE_ACCEPT;
28727 global_st_refresher = SESSION_TIMER_REFRESHER_PARAM_UAS;
28728 global_min_se = DEFAULT_MIN_SE;
28729 global_max_se = DEFAULT_MAX_SE;
28730
28731
28732 global_qualify_gap = DEFAULT_QUALIFY_GAP;
28733 global_qualify_peers = DEFAULT_QUALIFY_PEERS;
28734
28735
28736 ast_copy_string(sip_cfg.default_context, DEFAULT_CONTEXT, sizeof(sip_cfg.default_context));
28737 sip_cfg.default_subscribecontext[0] = '\0';
28738 sip_cfg.default_max_forwards = DEFAULT_MAX_FORWARDS;
28739 default_language[0] = '\0';
28740 default_fromdomain[0] = '\0';
28741 default_fromdomainport = 0;
28742 default_qualify = DEFAULT_QUALIFY;
28743 default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
28744 ast_copy_string(default_mohinterpret, DEFAULT_MOHINTERPRET, sizeof(default_mohinterpret));
28745 ast_copy_string(default_mohsuggest, DEFAULT_MOHSUGGEST, sizeof(default_mohsuggest));
28746 ast_copy_string(default_vmexten, DEFAULT_VMEXTEN, sizeof(default_vmexten));
28747 ast_set_flag(&global_flags[0], SIP_DTMF_RFC2833);
28748 ast_set_flag(&global_flags[0], SIP_DIRECT_MEDIA);
28749 ast_set_flag(&global_flags[0], SIP_NAT_FORCE_RPORT);
28750 ast_copy_string(default_engine, DEFAULT_ENGINE, sizeof(default_engine));
28751 ast_copy_string(default_parkinglot, DEFAULT_PARKINGLOT, sizeof(default_parkinglot));
28752
28753
28754 dumphistory = FALSE;
28755 recordhistory = FALSE;
28756 sipdebug &= ~sip_debug_config;
28757
28758
28759 global_relaxdtmf = FALSE;
28760 sip_cfg.callevents = DEFAULT_CALLEVENTS;
28761 global_authfailureevents = FALSE;
28762 global_t1 = DEFAULT_TIMER_T1;
28763 global_timer_b = 64 * DEFAULT_TIMER_T1;
28764 global_t1min = DEFAULT_T1MIN;
28765 global_qualifyfreq = DEFAULT_QUALIFYFREQ;
28766 global_t38_maxdatagram = -1;
28767 global_shrinkcallerid = 1;
28768 authlimit = DEFAULT_AUTHLIMIT;
28769 authtimeout = DEFAULT_AUTHTIMEOUT;
28770 global_store_sip_cause = DEFAULT_STORE_SIP_CAUSE;
28771
28772 sip_cfg.matchexternaddrlocally = DEFAULT_MATCHEXTERNADDRLOCALLY;
28773
28774
28775 memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
28776
28777 ast_clear_flag(&global_flags[1], SIP_PAGE2_FAX_DETECT);
28778 ast_clear_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT | SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
28779 ast_clear_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT);
28780 ast_clear_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION);
28781
28782
28783
28784 for (v = ast_variable_browse(cfg, "general"); v; v = v->next) {
28785 if (handle_common_options(&global_flags[0], &dummy[0], v)) {
28786 continue;
28787 }
28788 if (handle_t38_options(&global_flags[0], &dummy[0], v, &global_t38_maxdatagram)) {
28789 continue;
28790 }
28791
28792 if (!ast_jb_read_conf(&global_jbconf, v->name, v->value))
28793 continue;
28794
28795
28796 if (!ast_tls_read_conf(&default_tls_cfg, &sip_tls_desc, v->name, v->value)) {
28797 continue;
28798 }
28799
28800 if (!strcasecmp(v->name, "context")) {
28801 ast_copy_string(sip_cfg.default_context, v->value, sizeof(sip_cfg.default_context));
28802 } else if (!strcasecmp(v->name, "subscribecontext")) {
28803 ast_copy_string(sip_cfg.default_subscribecontext, v->value, sizeof(sip_cfg.default_subscribecontext));
28804 } else if (!strcasecmp(v->name, "callcounter")) {
28805 global_callcounter = ast_true(v->value) ? 1 : 0;
28806 } else if (!strcasecmp(v->name, "allowguest")) {
28807 sip_cfg.allowguest = ast_true(v->value) ? 1 : 0;
28808 } else if (!strcasecmp(v->name, "realm")) {
28809 ast_copy_string(sip_cfg.realm, v->value, sizeof(sip_cfg.realm));
28810 } else if (!strcasecmp(v->name, "domainsasrealm")) {
28811 sip_cfg.domainsasrealm = ast_true(v->value);
28812 } else if (!strcasecmp(v->name, "useragent")) {
28813 ast_copy_string(global_useragent, v->value, sizeof(global_useragent));
28814 ast_debug(1, "Setting SIP channel User-Agent Name to %s\n", global_useragent);
28815 } else if (!strcasecmp(v->name, "sdpsession")) {
28816 ast_copy_string(global_sdpsession, v->value, sizeof(global_sdpsession));
28817 } else if (!strcasecmp(v->name, "sdpowner")) {
28818
28819 if (!strstr(v->value, " ")) {
28820 ast_copy_string(global_sdpowner, v->value, sizeof(global_sdpowner));
28821 } else {
28822 ast_log(LOG_WARNING, "'%s' must not contain spaces at line %d. Using default.\n", v->value, v->lineno);
28823 }
28824 } else if (!strcasecmp(v->name, "allowtransfer")) {
28825 sip_cfg.allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
28826 } else if (!strcasecmp(v->name, "rtcachefriends")) {
28827 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTCACHEFRIENDS);
28828 } else if (!strcasecmp(v->name, "rtsavesysname")) {
28829 sip_cfg.rtsave_sysname = ast_true(v->value);
28830 } else if (!strcasecmp(v->name, "rtupdate")) {
28831 sip_cfg.peer_rtupdate = ast_true(v->value);
28832 } else if (!strcasecmp(v->name, "ignoreregexpire")) {
28833 sip_cfg.ignore_regexpire = ast_true(v->value);
28834 } else if (!strcasecmp(v->name, "timert1")) {
28835
28836
28837
28838 global_t1 = atoi(v->value);
28839 } else if (!strcasecmp(v->name, "timerb")) {
28840 int tmp = atoi(v->value);
28841 if (tmp < 500) {
28842 global_timer_b = global_t1 * 64;
28843 ast_log(LOG_WARNING, "Invalid value for timerb ('%s'). Setting to default ('%d').\n", v->value, global_timer_b);
28844 }
28845 timerb_set = 1;
28846 } else if (!strcasecmp(v->name, "t1min")) {
28847 global_t1min = atoi(v->value);
28848 } else if (!strcasecmp(v->name, "transport")) {
28849 char *val = ast_strdupa(v->value);
28850 char *trans;
28851
28852 default_transports = default_primary_transport = 0;
28853 while ((trans = strsep(&val, ","))) {
28854 trans = ast_skip_blanks(trans);
28855
28856 if (!strncasecmp(trans, "udp", 3)) {
28857 default_transports |= SIP_TRANSPORT_UDP;
28858 } else if (!strncasecmp(trans, "tcp", 3)) {
28859 default_transports |= SIP_TRANSPORT_TCP;
28860 } else if (!strncasecmp(trans, "tls", 3)) {
28861 default_transports |= SIP_TRANSPORT_TLS;
28862 } else {
28863 ast_log(LOG_NOTICE, "'%s' is not a valid transport type. if no other is specified, udp will be used.\n", trans);
28864 }
28865 if (default_primary_transport == 0) {
28866 default_primary_transport = default_transports;
28867 }
28868 }
28869 } else if (!strcasecmp(v->name, "tcpenable")) {
28870 if (!ast_false(v->value)) {
28871 ast_debug(2, "Enabling TCP socket for listening\n");
28872 sip_cfg.tcp_enabled = TRUE;
28873 }
28874 } else if (!strcasecmp(v->name, "tcpbindaddr")) {
28875 if (ast_parse_arg(v->value, PARSE_ADDR,
28876 &sip_tcp_desc.local_address)) {
28877 ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n",
28878 v->name, v->value, v->lineno, config);
28879 }
28880 ast_debug(2, "Setting TCP socket address to %s\n",
28881 ast_sockaddr_stringify(&sip_tcp_desc.local_address));
28882 } else if (!strcasecmp(v->name, "dynamic_exclude_static") || !strcasecmp(v->name, "dynamic_excludes_static")) {
28883 global_dynamic_exclude_static = ast_true(v->value);
28884 } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny")) {
28885 int ha_error = 0;
28886 sip_cfg.contact_ha = ast_append_ha(v->name + 7, v->value, sip_cfg.contact_ha, &ha_error);
28887 if (ha_error) {
28888 ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
28889 }
28890 } else if (!strcasecmp(v->name, "rtautoclear")) {
28891 int i = atoi(v->value);
28892 if (i > 0) {
28893 sip_cfg.rtautoclear = i;
28894 } else {
28895 i = 0;
28896 }
28897 ast_set2_flag(&global_flags[1], i || ast_true(v->value), SIP_PAGE2_RTAUTOCLEAR);
28898 } else if (!strcasecmp(v->name, "usereqphone")) {
28899 ast_set2_flag(&global_flags[0], ast_true(v->value), SIP_USEREQPHONE);
28900 } else if (!strcasecmp(v->name, "prematuremedia")) {
28901 global_prematuremediafilter = ast_true(v->value);
28902 } else if (!strcasecmp(v->name, "relaxdtmf")) {
28903 global_relaxdtmf = ast_true(v->value);
28904 } else if (!strcasecmp(v->name, "vmexten")) {
28905 ast_copy_string(default_vmexten, v->value, sizeof(default_vmexten));
28906 } else if (!strcasecmp(v->name, "rtptimeout")) {
28907 if ((sscanf(v->value, "%30d", &global_rtptimeout) != 1) || (global_rtptimeout < 0)) {
28908 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
28909 global_rtptimeout = 0;
28910 }
28911 } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
28912 if ((sscanf(v->value, "%30d", &global_rtpholdtimeout) != 1) || (global_rtpholdtimeout < 0)) {
28913 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
28914 global_rtpholdtimeout = 0;
28915 }
28916 } else if (!strcasecmp(v->name, "rtpkeepalive")) {
28917 if ((sscanf(v->value, "%30d", &global_rtpkeepalive) != 1) || (global_rtpkeepalive < 0)) {
28918 ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d. Using default.\n", v->value, v->lineno);
28919 global_rtpkeepalive = DEFAULT_RTPKEEPALIVE;
28920 }
28921 } else if (!strcasecmp(v->name, "compactheaders")) {
28922 sip_cfg.compactheaders = ast_true(v->value);
28923 } else if (!strcasecmp(v->name, "notifymimetype")) {
28924 ast_copy_string(default_notifymime, v->value, sizeof(default_notifymime));
28925 } else if (!strcasecmp(v->name, "directrtpsetup")) {
28926 sip_cfg.directrtpsetup = ast_true(v->value);
28927 } else if (!strcasecmp(v->name, "notifyringing")) {
28928 sip_cfg.notifyringing = ast_true(v->value);
28929 } else if (!strcasecmp(v->name, "notifyhold")) {
28930 sip_cfg.notifyhold = ast_true(v->value);
28931 } else if (!strcasecmp(v->name, "notifycid")) {
28932 if (!strcasecmp(v->value, "ignore-context")) {
28933 sip_cfg.notifycid = IGNORE_CONTEXT;
28934 } else {
28935 sip_cfg.notifycid = ast_true(v->value) ? ENABLED : DISABLED;
28936 }
28937 } else if (!strcasecmp(v->name, "alwaysauthreject")) {
28938 sip_cfg.alwaysauthreject = ast_true(v->value);
28939 } else if (!strcasecmp(v->name, "auth_options_requests")) {
28940 if (ast_true(v->value)) {
28941 sip_cfg.auth_options_requests = 1;
28942 }
28943 } else if (!strcasecmp(v->name, "mohinterpret")) {
28944 ast_copy_string(default_mohinterpret, v->value, sizeof(default_mohinterpret));
28945 } else if (!strcasecmp(v->name, "mohsuggest")) {
28946 ast_copy_string(default_mohsuggest, v->value, sizeof(default_mohsuggest));
28947 } else if (!strcasecmp(v->name, "language")) {
28948 ast_copy_string(default_language, v->value, sizeof(default_language));
28949 } else if (!strcasecmp(v->name, "regcontext")) {
28950 ast_copy_string(newcontexts, v->value, sizeof(newcontexts));
28951 stringp = newcontexts;
28952
28953 cleanup_stale_contexts(stringp, oldregcontext);
28954
28955 while ((context = strsep(&stringp, "&"))) {
28956 ast_copy_string(used_context, context, sizeof(used_context));
28957 ast_context_find_or_create(NULL, NULL, context, "SIP");
28958 }
28959 ast_copy_string(sip_cfg.regcontext, v->value, sizeof(sip_cfg.regcontext));
28960 } else if (!strcasecmp(v->name, "regextenonqualify")) {
28961 sip_cfg.regextenonqualify = ast_true(v->value);
28962 } else if (!strcasecmp(v->name, "legacy_useroption_parsing")) {
28963 sip_cfg.legacy_useroption_parsing = ast_true(v->value);
28964 } else if (!strcasecmp(v->name, "callerid")) {
28965 ast_copy_string(default_callerid, v->value, sizeof(default_callerid));
28966 } else if (!strcasecmp(v->name, "mwi_from")) {
28967 ast_copy_string(default_mwi_from, v->value, sizeof(default_mwi_from));
28968 } else if (!strcasecmp(v->name, "fromdomain")) {
28969 char *fromdomainport;
28970 ast_copy_string(default_fromdomain, v->value, sizeof(default_fromdomain));
28971 if ((fromdomainport = strchr(default_fromdomain, ':'))) {
28972 *fromdomainport++ = '\0';
28973 if (!(default_fromdomainport = port_str2int(fromdomainport, 0))) {
28974 ast_log(LOG_NOTICE, "'%s' is not a valid port number for fromdomain.\n",fromdomainport);
28975 }
28976 } else {
28977 default_fromdomainport = STANDARD_SIP_PORT;
28978 }
28979 } else if (!strcasecmp(v->name, "outboundproxy")) {
28980 struct sip_proxy *proxy;
28981 if (ast_strlen_zero(v->value)) {
28982 ast_log(LOG_WARNING, "no value given for outbound proxy on line %d of sip.conf\n", v->lineno);
28983 continue;
28984 }
28985 proxy = proxy_from_config(v->value, v->lineno, &sip_cfg.outboundproxy);
28986 if (!proxy) {
28987 ast_log(LOG_WARNING, "failure parsing the outbound proxy on line %d of sip.conf.\n", v->lineno);
28988 continue;
28989 }
28990 } else if (!strcasecmp(v->name, "autocreatepeer")) {
28991 sip_cfg.autocreatepeer = ast_true(v->value);
28992 } else if (!strcasecmp(v->name, "match_auth_username")) {
28993 global_match_auth_username = ast_true(v->value);
28994 } else if (!strcasecmp(v->name, "srvlookup")) {
28995 sip_cfg.srvlookup = ast_true(v->value);
28996 } else if (!strcasecmp(v->name, "pedantic")) {
28997 sip_cfg.pedanticsipchecking = ast_true(v->value);
28998 } else if (!strcasecmp(v->name, "maxexpirey") || !strcasecmp(v->name, "maxexpiry")) {
28999 max_expiry = atoi(v->value);
29000 if (max_expiry < 1) {
29001 max_expiry = DEFAULT_MAX_EXPIRY;
29002 }
29003 } else if (!strcasecmp(v->name, "minexpirey") || !strcasecmp(v->name, "minexpiry")) {
29004 min_expiry = atoi(v->value);
29005 if (min_expiry < 1) {
29006 min_expiry = DEFAULT_MIN_EXPIRY;
29007 }
29008 } else if (!strcasecmp(v->name, "defaultexpiry") || !strcasecmp(v->name, "defaultexpirey")) {
29009 default_expiry = atoi(v->value);
29010 if (default_expiry < 1) {
29011 default_expiry = DEFAULT_DEFAULT_EXPIRY;
29012 }
29013 } else if (!strcasecmp(v->name, "mwiexpiry") || !strcasecmp(v->name, "mwiexpirey")) {
29014 mwi_expiry = atoi(v->value);
29015 if (mwi_expiry < 1) {
29016 mwi_expiry = DEFAULT_MWI_EXPIRY;
29017 }
29018 } else if (!strcasecmp(v->name, "tcpauthtimeout")) {
29019 if (ast_parse_arg(v->value, PARSE_INT32|PARSE_DEFAULT|PARSE_IN_RANGE,
29020 &authtimeout, DEFAULT_AUTHTIMEOUT, 1, INT_MAX)) {
29021 ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n",
29022 v->name, v->value, v->lineno, config);
29023 }
29024 } else if (!strcasecmp(v->name, "tcpauthlimit")) {
29025 if (ast_parse_arg(v->value, PARSE_INT32|PARSE_DEFAULT|PARSE_IN_RANGE,
29026 &authlimit, DEFAULT_AUTHLIMIT, 1, INT_MAX)) {
29027 ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n",
29028 v->name, v->value, v->lineno, config);
29029 }
29030 } else if (!strcasecmp(v->name, "sipdebug")) {
29031 if (ast_true(v->value))
29032 sipdebug |= sip_debug_config;
29033 } else if (!strcasecmp(v->name, "dumphistory")) {
29034 dumphistory = ast_true(v->value);
29035 } else if (!strcasecmp(v->name, "recordhistory")) {
29036 recordhistory = ast_true(v->value);
29037 } else if (!strcasecmp(v->name, "registertimeout")) {
29038 global_reg_timeout = atoi(v->value);
29039 if (global_reg_timeout < 1) {
29040 global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
29041 }
29042 } else if (!strcasecmp(v->name, "registerattempts")) {
29043 global_regattempts_max = atoi(v->value);
29044 } else if (!strcasecmp(v->name, "bindaddr") || !strcasecmp(v->name, "udpbindaddr")) {
29045 if (ast_parse_arg(v->value, PARSE_ADDR, &bindaddr)) {
29046 ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
29047 }
29048 } else if (!strcasecmp(v->name, "localnet")) {
29049 struct ast_ha *na;
29050 int ha_error = 0;
29051
29052 if (!(na = ast_append_ha("d", v->value, localaddr, &ha_error))) {
29053 ast_log(LOG_WARNING, "Invalid localnet value: %s\n", v->value);
29054 } else {
29055 localaddr = na;
29056 }
29057 if (ha_error) {
29058 ast_log(LOG_ERROR, "Bad localnet configuration value line %d : %s\n", v->lineno, v->value);
29059 }
29060 } else if (!strcasecmp(v->name, "media_address")) {
29061 if (ast_parse_arg(v->value, PARSE_ADDR, &media_address))
29062 ast_log(LOG_WARNING, "Invalid address for media_address keyword: %s\n", v->value);
29063 } else if (!strcasecmp(v->name, "externaddr") || !strcasecmp(v->name, "externip")) {
29064 if (ast_parse_arg(v->value, PARSE_ADDR, &externaddr)) {
29065 ast_log(LOG_WARNING,
29066 "Invalid address for externaddr keyword: %s\n",
29067 v->value);
29068 }
29069 externexpire = 0;
29070 } else if (!strcasecmp(v->name, "externhost")) {
29071 ast_copy_string(externhost, v->value, sizeof(externhost));
29072 if (ast_sockaddr_resolve_first(&externaddr, externhost, 0)) {
29073 ast_log(LOG_WARNING, "Invalid address for externhost keyword: %s\n", externhost);
29074 }
29075 externexpire = time(NULL);
29076 } else if (!strcasecmp(v->name, "externrefresh")) {
29077 if (sscanf(v->value, "%30d", &externrefresh) != 1) {
29078 ast_log(LOG_WARNING, "Invalid externrefresh value '%s', must be an integer >0 at line %d\n", v->value, v->lineno);
29079 externrefresh = 10;
29080 }
29081 } else if (!strcasecmp(v->name, "externtcpport")) {
29082 if (!(externtcpport = port_str2int(v->value, 0))) {
29083 ast_log(LOG_WARNING, "Invalid externtcpport value, must be a positive integer between 1 and 65535 at line %d\n", v->lineno);
29084 externtcpport = 0;
29085 }
29086 } else if (!strcasecmp(v->name, "externtlsport")) {
29087 if (!(externtlsport = port_str2int(v->value, STANDARD_TLS_PORT))) {
29088 ast_log(LOG_WARNING, "Invalid externtlsport value, must be a positive integer between 1 and 65535 at line %d\n", v->lineno);
29089 }
29090 } else if (!strcasecmp(v->name, "allow")) {
29091 int error = ast_parse_allow_disallow(&default_prefs, &sip_cfg.capability, v->value, TRUE);
29092 if (error) {
29093 ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
29094 }
29095 } else if (!strcasecmp(v->name, "disallow")) {
29096 int error = ast_parse_allow_disallow(&default_prefs, &sip_cfg.capability, v->value, FALSE);
29097 if (error) {
29098 ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
29099 }
29100 } else if (!strcasecmp(v->name, "preferred_codec_only")) {
29101 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_PREFERRED_CODEC);
29102 } else if (!strcasecmp(v->name, "autoframing")) {
29103 global_autoframing = ast_true(v->value);
29104 } else if (!strcasecmp(v->name, "allowexternaldomains")) {
29105 sip_cfg.allow_external_domains = ast_true(v->value);
29106 } else if (!strcasecmp(v->name, "autodomain")) {
29107 auto_sip_domains = ast_true(v->value);
29108 } else if (!strcasecmp(v->name, "domain")) {
29109 char *domain = ast_strdupa(v->value);
29110 char *cntx = strchr(domain, ',');
29111
29112 if (cntx) {
29113 *cntx++ = '\0';
29114 }
29115
29116 if (ast_strlen_zero(cntx)) {
29117 ast_debug(1, "No context specified at line %d for domain '%s'\n", v->lineno, domain);
29118 }
29119 if (ast_strlen_zero(domain)) {
29120 ast_log(LOG_WARNING, "Empty domain specified at line %d\n", v->lineno);
29121 } else {
29122 add_sip_domain(ast_strip(domain), SIP_DOMAIN_CONFIG, cntx ? ast_strip(cntx) : "");
29123 }
29124 } else if (!strcasecmp(v->name, "register")) {
29125 if (sip_register(v->value, v->lineno) == 0) {
29126 registry_count++;
29127 }
29128 } else if (!strcasecmp(v->name, "mwi")) {
29129 sip_subscribe_mwi(v->value, v->lineno);
29130 } else if (!strcasecmp(v->name, "tos_sip")) {
29131 if (ast_str2tos(v->value, &global_tos_sip)) {
29132 ast_log(LOG_WARNING, "Invalid tos_sip value at line %d, refer to QoS documentation\n", v->lineno);
29133 }
29134 } else if (!strcasecmp(v->name, "tos_audio")) {
29135 if (ast_str2tos(v->value, &global_tos_audio)) {
29136 ast_log(LOG_WARNING, "Invalid tos_audio value at line %d, refer to QoS documentation\n", v->lineno);
29137 }
29138 } else if (!strcasecmp(v->name, "tos_video")) {
29139 if (ast_str2tos(v->value, &global_tos_video)) {
29140 ast_log(LOG_WARNING, "Invalid tos_video value at line %d, refer to QoS documentation\n", v->lineno);
29141 }
29142 } else if (!strcasecmp(v->name, "tos_text")) {
29143 if (ast_str2tos(v->value, &global_tos_text)) {
29144 ast_log(LOG_WARNING, "Invalid tos_text value at line %d, refer to QoS documentation\n", v->lineno);
29145 }
29146 } else if (!strcasecmp(v->name, "cos_sip")) {
29147 if (ast_str2cos(v->value, &global_cos_sip)) {
29148 ast_log(LOG_WARNING, "Invalid cos_sip value at line %d, refer to QoS documentation\n", v->lineno);
29149 }
29150 } else if (!strcasecmp(v->name, "cos_audio")) {
29151 if (ast_str2cos(v->value, &global_cos_audio)) {
29152 ast_log(LOG_WARNING, "Invalid cos_audio value at line %d, refer to QoS documentation\n", v->lineno);
29153 }
29154 } else if (!strcasecmp(v->name, "cos_video")) {
29155 if (ast_str2cos(v->value, &global_cos_video)) {
29156 ast_log(LOG_WARNING, "Invalid cos_video value at line %d, refer to QoS documentation\n", v->lineno);
29157 }
29158 } else if (!strcasecmp(v->name, "cos_text")) {
29159 if (ast_str2cos(v->value, &global_cos_text)) {
29160 ast_log(LOG_WARNING, "Invalid cos_text value at line %d, refer to QoS documentation\n", v->lineno);
29161 }
29162 } else if (!strcasecmp(v->name, "bindport")) {
29163 if (sscanf(v->value, "%5d", &bindport) != 1) {
29164 ast_log(LOG_WARNING, "Invalid port number '%s' at line %d of %s\n", v->value, v->lineno, config);
29165 }
29166 } else if (!strcasecmp(v->name, "qualify")) {
29167 if (!strcasecmp(v->value, "no")) {
29168 default_qualify = 0;
29169 } else if (!strcasecmp(v->value, "yes")) {
29170 default_qualify = DEFAULT_MAXMS;
29171 } else if (sscanf(v->value, "%30d", &default_qualify) != 1) {
29172 ast_log(LOG_WARNING, "Qualification default should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", v->lineno);
29173 default_qualify = 0;
29174 }
29175 } else if (!strcasecmp(v->name, "qualifyfreq")) {
29176 int i;
29177 if (sscanf(v->value, "%30d", &i) == 1) {
29178 global_qualifyfreq = i * 1000;
29179 } else {
29180 ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
29181 global_qualifyfreq = DEFAULT_QUALIFYFREQ;
29182 }
29183 } else if (!strcasecmp(v->name, "callevents")) {
29184 sip_cfg.callevents = ast_true(v->value);
29185 } else if (!strcasecmp(v->name, "authfailureevents")) {
29186 global_authfailureevents = ast_true(v->value);
29187 } else if (!strcasecmp(v->name, "maxcallbitrate")) {
29188 default_maxcallbitrate = atoi(v->value);
29189 if (default_maxcallbitrate < 0)
29190 default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
29191 } else if (!strcasecmp(v->name, "matchexternaddrlocally") || !strcasecmp(v->name, "matchexterniplocally")) {
29192 sip_cfg.matchexternaddrlocally = ast_true(v->value);
29193 } else if (!strcasecmp(v->name, "session-timers")) {
29194 int i = (int) str2stmode(v->value);
29195 if (i < 0) {
29196 ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
29197 global_st_mode = SESSION_TIMER_MODE_ACCEPT;
29198 } else {
29199 global_st_mode = i;
29200 }
29201 } else if (!strcasecmp(v->name, "session-expires")) {
29202 if (sscanf(v->value, "%30d", &global_max_se) != 1) {
29203 ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
29204 global_max_se = DEFAULT_MAX_SE;
29205 }
29206 } else if (!strcasecmp(v->name, "session-minse")) {
29207 if (sscanf(v->value, "%30d", &global_min_se) != 1) {
29208 ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
29209 global_min_se = DEFAULT_MIN_SE;
29210 }
29211 if (global_min_se < 90) {
29212 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);
29213 global_min_se = DEFAULT_MIN_SE;
29214 }
29215 } else if (!strcasecmp(v->name, "session-refresher")) {
29216 int i = (int) str2strefresherparam(v->value);
29217 if (i < 0) {
29218 ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
29219 global_st_refresher = SESSION_TIMER_REFRESHER_PARAM_UAS;
29220 } else {
29221 global_st_refresher = i;
29222 }
29223 } else if (!strcasecmp(v->name, "storesipcause")) {
29224 global_store_sip_cause = ast_true(v->value);
29225 } else if (!strcasecmp(v->name, "qualifygap")) {
29226 if (sscanf(v->value, "%30d", &global_qualify_gap) != 1) {
29227 ast_log(LOG_WARNING, "Invalid qualifygap '%s' at line %d of %s\n", v->value, v->lineno, config);
29228 global_qualify_gap = DEFAULT_QUALIFY_GAP;
29229 }
29230 } else if (!strcasecmp(v->name, "qualifypeers")) {
29231 if (sscanf(v->value, "%30d", &global_qualify_peers) != 1) {
29232 ast_log(LOG_WARNING, "Invalid pokepeers '%s' at line %d of %s\n", v->value, v->lineno, config);
29233 global_qualify_peers = DEFAULT_QUALIFY_PEERS;
29234 }
29235 } else if (!strcasecmp(v->name, "disallowed_methods")) {
29236 char *disallow = ast_strdupa(v->value);
29237 mark_parsed_methods(&sip_cfg.disallowed_methods, disallow);
29238 } else if (!strcasecmp(v->name, "shrinkcallerid")) {
29239 if (ast_true(v->value)) {
29240 global_shrinkcallerid = 1;
29241 } else if (ast_false(v->value)) {
29242 global_shrinkcallerid = 0;
29243 } else {
29244 ast_log(LOG_WARNING, "shrinkcallerid value %s is not valid at line %d.\n", v->value, v->lineno);
29245 }
29246 } else if (!strcasecmp(v->name, "use_q850_reason")) {
29247 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_Q850_REASON);
29248 } else if (!strcasecmp(v->name, "maxforwards")) {
29249 if (sscanf(v->value, "%30d", &sip_cfg.default_max_forwards) != 1
29250 || sip_cfg.default_max_forwards < 1 || 255 < sip_cfg.default_max_forwards) {
29251 ast_log(LOG_WARNING, "'%s' is not a valid maxforwards value at line %d. Using default.\n", v->value, v->lineno);
29252 sip_cfg.default_max_forwards = DEFAULT_MAX_FORWARDS;
29253 }
29254 } else if (!strcasecmp(v->name, "subscribe_network_change_event")) {
29255 if (ast_true(v->value)) {
29256 subscribe_network_change = 1;
29257 } else if (ast_false(v->value)) {
29258 subscribe_network_change = 0;
29259 } else {
29260 ast_log(LOG_WARNING, "subscribe_network_change_event value %s is not valid at line %d.\n", v->value, v->lineno);
29261 }
29262 } else if (!strcasecmp(v->name, "snom_aoc_enabled")) {
29263 ast_set2_flag(&global_flags[2], ast_true(v->value), SIP_PAGE3_SNOM_AOC);
29264 } else if (!strcasecmp(v->name, "parkinglot")) {
29265 ast_copy_string(default_parkinglot, v->value, sizeof(default_parkinglot));
29266 }
29267 }
29268
29269 if (subscribe_network_change) {
29270 network_change_event_subscribe();
29271 } else {
29272 network_change_event_unsubscribe();
29273 }
29274
29275 if (global_t1 < global_t1min) {
29276 ast_log(LOG_WARNING, "'t1min' (%d) cannot be greater than 't1timer' (%d). Resetting 't1timer' to the value of 't1min'\n", global_t1min, global_t1);
29277 global_t1 = global_t1min;
29278 }
29279
29280 if (global_timer_b < global_t1 * 64) {
29281 if (timerb_set && timert1_set) {
29282 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);
29283 } else if (timerb_set) {
29284 if ((global_t1 = global_timer_b / 64) < global_t1min) {
29285 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);
29286 global_t1 = global_t1min;
29287 global_timer_b = global_t1 * 64;
29288 }
29289 } else {
29290 global_timer_b = global_t1 * 64;
29291 }
29292 }
29293 if (!sip_cfg.allow_external_domains && AST_LIST_EMPTY(&domain_list)) {
29294 ast_log(LOG_WARNING, "To disallow external domains, you need to configure local SIP domains.\n");
29295 sip_cfg.allow_external_domains = 1;
29296 }
29297
29298 if (!sip_cfg.tcp_enabled && (default_transports & SIP_TRANSPORT_TCP)) {
29299 ast_log(LOG_WARNING, "Cannot use 'tcp' transport with tcpenable=no. Removing from available transports.\n");
29300 default_primary_transport &= ~SIP_TRANSPORT_TCP;
29301 default_transports &= ~SIP_TRANSPORT_TCP;
29302 }
29303 if (!default_tls_cfg.enabled && (default_transports & SIP_TRANSPORT_TLS)) {
29304 ast_log(LOG_WARNING, "Cannot use 'tls' transport with tlsenable=no. Removing from available transports.\n");
29305 default_primary_transport &= ~SIP_TRANSPORT_TLS;
29306 default_transports &= ~SIP_TRANSPORT_TLS;
29307 }
29308 if (!default_transports) {
29309 ast_log(LOG_WARNING, "No valid transports available, falling back to 'udp'.\n");
29310 default_transports = default_primary_transport = SIP_TRANSPORT_UDP;
29311 } else if (!default_primary_transport) {
29312 ast_log(LOG_WARNING, "No valid default transport. Selecting 'udp' as default.\n");
29313 default_primary_transport = SIP_TRANSPORT_UDP;
29314 }
29315
29316
29317 for (v = ast_variable_browse(cfg, "authentication"); v ; v = v->next) {
29318
29319 if (!strcasecmp(v->name, "auth")) {
29320 add_realm_authentication(&authl, v->value, v->lineno);
29321 }
29322 }
29323
29324 if (bindport) {
29325 if (ast_sockaddr_port(&bindaddr)) {
29326 ast_log(LOG_WARNING, "bindport is also specified in bindaddr. "
29327 "Using %d.\n", bindport);
29328 }
29329 ast_sockaddr_set_port(&bindaddr, bindport);
29330 }
29331
29332 if (!ast_sockaddr_port(&bindaddr)) {
29333 ast_sockaddr_set_port(&bindaddr, STANDARD_SIP_PORT);
29334 }
29335
29336
29337 ast_sockaddr_copy(&internip, &bindaddr);
29338 if (ast_find_ourip(&internip, &bindaddr, 0)) {
29339 ast_log(LOG_WARNING, "Unable to get own IP address, SIP disabled\n");
29340 ast_config_destroy(cfg);
29341 return 0;
29342 }
29343
29344 ast_mutex_lock(&netlock);
29345 if ((sipsock > -1) && (ast_sockaddr_cmp(&old_bindaddr, &bindaddr))) {
29346 close(sipsock);
29347 sipsock = -1;
29348 }
29349 if (sipsock < 0) {
29350 sipsock = socket(ast_sockaddr_is_ipv6(&bindaddr) ?
29351 AF_INET6 : AF_INET, SOCK_DGRAM, 0);
29352 if (sipsock < 0) {
29353 ast_log(LOG_WARNING, "Unable to create SIP socket: %s\n", strerror(errno));
29354 ast_config_destroy(cfg);
29355 ast_mutex_unlock(&netlock);
29356 return -1;
29357 } else {
29358
29359 const int reuseFlag = 1;
29360
29361 setsockopt(sipsock, SOL_SOCKET, SO_REUSEADDR,
29362 (const char*)&reuseFlag,
29363 sizeof reuseFlag);
29364
29365 ast_enable_packet_fragmentation(sipsock);
29366
29367 if (ast_bind(sipsock, &bindaddr) < 0) {
29368 ast_log(LOG_WARNING, "Failed to bind to %s: %s\n",
29369 ast_sockaddr_stringify(&bindaddr), strerror(errno));
29370 close(sipsock);
29371 sipsock = -1;
29372 } else {
29373 ast_verb(2, "SIP Listening on %s\n", ast_sockaddr_stringify(&bindaddr));
29374 ast_set_qos(sipsock, global_tos_sip, global_cos_sip, "SIP");
29375 }
29376 }
29377 } else {
29378 ast_set_qos(sipsock, global_tos_sip, global_cos_sip, "SIP");
29379 }
29380 ast_mutex_unlock(&netlock);
29381
29382
29383 if (sip_cfg.tcp_enabled) {
29384 if (ast_sockaddr_isnull(&sip_tcp_desc.local_address)) {
29385 ast_sockaddr_copy(&sip_tcp_desc.local_address, &bindaddr);
29386 }
29387 if (!ast_sockaddr_port(&sip_tcp_desc.local_address)) {
29388 ast_sockaddr_set_port(&sip_tcp_desc.local_address, STANDARD_SIP_PORT);
29389 }
29390 } else {
29391 ast_sockaddr_setnull(&sip_tcp_desc.local_address);
29392 }
29393 ast_tcptls_server_start(&sip_tcp_desc);
29394 if (sip_cfg.tcp_enabled && sip_tcp_desc.accept_fd == -1) {
29395
29396 ast_log(LOG_ERROR, "SIP TCP Server start failed. Not listening on TCP socket.\n");
29397 } else {
29398 ast_debug(2, "SIP TCP server started\n");
29399 }
29400
29401
29402 memcpy(sip_tls_desc.tls_cfg, &default_tls_cfg, sizeof(default_tls_cfg));
29403
29404 if (ast_ssl_setup(sip_tls_desc.tls_cfg)) {
29405 if (ast_sockaddr_isnull(&sip_tls_desc.local_address)) {
29406 ast_sockaddr_copy(&sip_tls_desc.local_address, &bindaddr);
29407 ast_sockaddr_set_port(&sip_tls_desc.local_address,
29408 STANDARD_TLS_PORT);
29409 }
29410 if (!ast_sockaddr_port(&sip_tls_desc.local_address)) {
29411 ast_sockaddr_set_port(&sip_tls_desc.local_address,
29412 STANDARD_TLS_PORT);
29413 }
29414 ast_tcptls_server_start(&sip_tls_desc);
29415 if (default_tls_cfg.enabled && sip_tls_desc.accept_fd == -1) {
29416 ast_log(LOG_ERROR, "TLS Server start failed. Not listening on TLS socket.\n");
29417 sip_tls_desc.tls_cfg = NULL;
29418 }
29419 } else if (sip_tls_desc.tls_cfg->enabled) {
29420 sip_tls_desc.tls_cfg = NULL;
29421 ast_log(LOG_WARNING, "SIP TLS server did not load because of errors.\n");
29422 }
29423
29424 if (ucfg) {
29425 struct ast_variable *gen;
29426 int genhassip, genregistersip;
29427 const char *hassip, *registersip;
29428
29429 genhassip = ast_true(ast_variable_retrieve(ucfg, "general", "hassip"));
29430 genregistersip = ast_true(ast_variable_retrieve(ucfg, "general", "registersip"));
29431 gen = ast_variable_browse(ucfg, "general");
29432 cat = ast_category_browse(ucfg, NULL);
29433 while (cat) {
29434 if (strcasecmp(cat, "general")) {
29435 hassip = ast_variable_retrieve(ucfg, cat, "hassip");
29436 registersip = ast_variable_retrieve(ucfg, cat, "registersip");
29437 if (ast_true(hassip) || (!hassip && genhassip)) {
29438 peer = build_peer(cat, gen, ast_variable_browse(ucfg, cat), 0, 0);
29439 if (peer) {
29440
29441 peer->type = SIP_TYPE_USER | SIP_TYPE_PEER;
29442 ao2_t_link(peers, peer, "link peer into peer table");
29443 if ((peer->type & SIP_TYPE_PEER) && !ast_sockaddr_isnull(&peer->addr)) {
29444 ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
29445 }
29446
29447 unref_peer(peer, "unref_peer: from reload_config");
29448 peer_count++;
29449 }
29450 }
29451 if (ast_true(registersip) || (!registersip && genregistersip)) {
29452 char tmp[256];
29453 const char *host = ast_variable_retrieve(ucfg, cat, "host");
29454 const char *username = ast_variable_retrieve(ucfg, cat, "username");
29455 const char *secret = ast_variable_retrieve(ucfg, cat, "secret");
29456 const char *contact = ast_variable_retrieve(ucfg, cat, "contact");
29457 const char *authuser = ast_variable_retrieve(ucfg, cat, "authuser");
29458 if (!host) {
29459 host = ast_variable_retrieve(ucfg, "general", "host");
29460 }
29461 if (!username) {
29462 username = ast_variable_retrieve(ucfg, "general", "username");
29463 }
29464 if (!secret) {
29465 secret = ast_variable_retrieve(ucfg, "general", "secret");
29466 }
29467 if (!contact) {
29468 contact = "s";
29469 }
29470 if (!ast_strlen_zero(username) && !ast_strlen_zero(host)) {
29471 if (!ast_strlen_zero(secret)) {
29472 if (!ast_strlen_zero(authuser)) {
29473 snprintf(tmp, sizeof(tmp), "%s?%s:%s:%s@%s/%s", cat, username, secret, authuser, host, contact);
29474 } else {
29475 snprintf(tmp, sizeof(tmp), "%s?%s:%s@%s/%s", cat, username, secret, host, contact);
29476 }
29477 } else if (!ast_strlen_zero(authuser)) {
29478 snprintf(tmp, sizeof(tmp), "%s?%s::%s@%s/%s", cat, username, authuser, host, contact);
29479 } else {
29480 snprintf(tmp, sizeof(tmp), "%s?%s@%s/%s", cat, username, host, contact);
29481 }
29482 if (sip_register(tmp, 0) == 0) {
29483 registry_count++;
29484 }
29485 }
29486 }
29487 }
29488 cat = ast_category_browse(ucfg, cat);
29489 }
29490 ast_config_destroy(ucfg);
29491 }
29492
29493
29494 cat = NULL;
29495 while ( (cat = ast_category_browse(cfg, cat)) ) {
29496 const char *utype;
29497 if (!strcasecmp(cat, "general") || !strcasecmp(cat, "authentication"))
29498 continue;
29499 utype = ast_variable_retrieve(cfg, cat, "type");
29500 if (!utype) {
29501 ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
29502 continue;
29503 } else {
29504 if (!strcasecmp(utype, "user")) {
29505 ;
29506 } else if (!strcasecmp(utype, "friend")) {
29507 ;
29508 } else if (!strcasecmp(utype, "peer")) {
29509 ;
29510 } else {
29511 ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, "sip.conf");
29512 continue;
29513 }
29514 peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0, 0);
29515 if (peer) {
29516 display_nat_warning(cat, reason, &peer->flags[0]);
29517 ao2_t_link(peers, peer, "link peer into peers table");
29518 if ((peer->type & SIP_TYPE_PEER) && !ast_sockaddr_isnull(&peer->addr)) {
29519 ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
29520 }
29521 unref_peer(peer, "unref the result of the build_peer call. Now, the links from the tables are the only ones left.");
29522 peer_count++;
29523 }
29524 }
29525 }
29526
29527
29528
29529
29530
29531
29532 if (auto_sip_domains) {
29533 char temp[MAXHOSTNAMELEN];
29534
29535
29536 if (!ast_sockaddr_isnull(&bindaddr) && !ast_sockaddr_is_any(&bindaddr)) {
29537 add_sip_domain(ast_sockaddr_stringify_addr(&bindaddr),
29538 SIP_DOMAIN_AUTO, NULL);
29539 } else if (!ast_sockaddr_isnull(&internip) && !ast_sockaddr_is_any(&internip)) {
29540
29541 add_sip_domain(ast_sockaddr_stringify_addr(&internip),
29542 SIP_DOMAIN_AUTO, NULL);
29543 } else {
29544 ast_log(LOG_NOTICE, "Can't add wildcard IP address to domain list, please add IP address to domain manually.\n");
29545 }
29546
29547
29548 if (!ast_sockaddr_isnull(&sip_tcp_desc.local_address) &&
29549 !ast_sockaddr_cmp(&bindaddr, &sip_tcp_desc.local_address)) {
29550 add_sip_domain(ast_sockaddr_stringify_addr(&sip_tcp_desc.local_address),
29551 SIP_DOMAIN_AUTO, NULL);
29552 }
29553
29554
29555 if (!ast_sockaddr_isnull(&sip_tls_desc.local_address) &&
29556 !ast_sockaddr_cmp(&bindaddr, &sip_tls_desc.local_address) &&
29557 !ast_sockaddr_cmp(&sip_tcp_desc.local_address,
29558 &sip_tls_desc.local_address)) {
29559 add_sip_domain(ast_sockaddr_stringify_addr(&sip_tcp_desc.local_address),
29560 SIP_DOMAIN_AUTO, NULL);
29561 }
29562
29563
29564 if (!ast_sockaddr_isnull(&externaddr)) {
29565 add_sip_domain(ast_sockaddr_stringify_addr(&externaddr),
29566 SIP_DOMAIN_AUTO, NULL);
29567 }
29568
29569
29570 if (!ast_strlen_zero(externhost)) {
29571 add_sip_domain(externhost, SIP_DOMAIN_AUTO, NULL);
29572 }
29573
29574
29575 if (!gethostname(temp, sizeof(temp))) {
29576 add_sip_domain(temp, SIP_DOMAIN_AUTO, NULL);
29577 }
29578 }
29579
29580
29581 ast_config_destroy(cfg);
29582
29583
29584 if (notify_types)
29585 ast_config_destroy(notify_types);
29586 if ((notify_types = ast_config_load(notify_config, config_flags)) == CONFIG_STATUS_FILEINVALID) {
29587 ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed.\n", notify_config);
29588 notify_types = NULL;
29589 }
29590
29591
29592 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);
29593 run_end = time(0);
29594 ast_debug(4, "SIP reload_config done...Runtime= %d sec\n", (int)(run_end-run_start));
29595
29596 return 0;
29597 }
29598
29599 static int apply_directmedia_ha(struct sip_pvt *p1, struct sip_pvt *p2, const char *op)
29600 {
29601 struct ast_sockaddr us = { { 0, }, }, them = { { 0, }, };
29602 int res = AST_SENSE_ALLOW;
29603
29604 ast_rtp_instance_get_remote_address(p1->rtp, &them);
29605 ast_rtp_instance_get_local_address(p1->rtp, &us);
29606
29607
29608
29609 if (!p2->relatedpeer) {
29610 return res;
29611 }
29612
29613 if ((res = ast_apply_ha(p2->relatedpeer->directmediaha, &them)) == AST_SENSE_DENY) {
29614 const char *us_addr = ast_strdupa(ast_sockaddr_stringify(&us));
29615 const char *them_addr = ast_strdupa(ast_sockaddr_stringify(&them));
29616
29617 ast_debug(3, "Reinvite %s to %s denied by directmedia ACL on %s\n",
29618 op, them_addr, us_addr);
29619 }
29620
29621 return res;
29622 }
29623
29624 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan)
29625 {
29626 struct sip_pvt *p;
29627 struct ast_channel *opp_chan;
29628 struct sip_pvt *opp;
29629 struct ast_udptl *udptl = NULL;
29630
29631 p = chan->tech_pvt;
29632 if (!p) {
29633 return NULL;
29634 }
29635
29636 if (!(opp_chan = ast_bridged_channel(chan))) {
29637 return NULL;
29638 } else if (((opp_chan->tech != &sip_tech) && (opp_chan->tech != &sip_tech_info)) ||
29639 (!(opp = opp_chan->tech_pvt))) {
29640 return NULL;
29641 }
29642
29643 sip_pvt_lock(p);
29644 while (sip_pvt_trylock(opp)) {
29645 sip_pvt_unlock(p);
29646 usleep(1);
29647 sip_pvt_lock(p);
29648 }
29649
29650 if (p->udptl && ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
29651 if (apply_directmedia_ha(p, opp, "UDPTL T.38 data")) {
29652 udptl = p->udptl;
29653 }
29654 }
29655
29656 sip_pvt_unlock(opp);
29657 sip_pvt_unlock(p);
29658 return udptl;
29659 }
29660
29661 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl)
29662 {
29663 struct sip_pvt *p;
29664
29665
29666 ast_channel_lock(chan);
29667 p = chan->tech_pvt;
29668 if (!p) {
29669 ast_channel_unlock(chan);
29670 return -1;
29671 }
29672 sip_pvt_lock(p);
29673 if (p->owner != chan) {
29674
29675 ast_debug(1, "The private is not owned by channel %s anymore.\n", chan->name);
29676 sip_pvt_unlock(p);
29677 ast_channel_unlock(chan);
29678 return 0;
29679 }
29680
29681 if (udptl) {
29682 ast_udptl_get_peer(udptl, &p->udptlredirip);
29683 } else {
29684 memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
29685 }
29686 if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
29687 if (!p->pendinginvite) {
29688 ast_debug(3, "Sending reinvite on SIP '%s' - It's UDPTL soon redirected to IP %s\n",
29689 p->callid, ast_sockaddr_stringify(udptl ? &p->udptlredirip : &p->ourip));
29690 transmit_reinvite_with_sdp(p, TRUE, FALSE);
29691 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
29692 ast_debug(3, "Deferring reinvite on SIP '%s' - It's UDPTL will be redirected to IP %s\n",
29693 p->callid, ast_sockaddr_stringify(udptl ? &p->udptlredirip : &p->ourip));
29694 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
29695 }
29696 }
29697
29698 p->lastrtprx = p->lastrtptx = time(NULL);
29699 sip_pvt_unlock(p);
29700 ast_channel_unlock(chan);
29701 return 0;
29702 }
29703
29704 static enum ast_rtp_glue_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
29705 {
29706 struct sip_pvt *p = NULL;
29707 struct ast_channel *opp_chan;
29708 struct sip_pvt *opp = NULL;
29709 enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_LOCAL;
29710
29711 if (!(p = chan->tech_pvt)) {
29712 return AST_RTP_GLUE_RESULT_FORBID;
29713 }
29714
29715 if ((opp_chan = ast_bridged_channel(chan)) && (((opp_chan->tech != &sip_tech) && (opp_chan->tech != &sip_tech_info)) ||
29716 (!(opp = opp_chan->tech_pvt)))) {
29717 return AST_RTP_GLUE_RESULT_FORBID;
29718 }
29719
29720 sip_pvt_lock(p);
29721 while (opp && sip_pvt_trylock(opp)) {
29722 sip_pvt_unlock(p);
29723 usleep(1);
29724 sip_pvt_lock(p);
29725 }
29726
29727 if (!(p->rtp)) {
29728 if (opp) {
29729 sip_pvt_unlock(opp);
29730 }
29731 sip_pvt_unlock(p);
29732 return AST_RTP_GLUE_RESULT_FORBID;
29733 }
29734
29735 ao2_ref(p->rtp, +1);
29736 *instance = p->rtp;
29737
29738 if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
29739 res = AST_RTP_GLUE_RESULT_REMOTE;
29740 if (opp && !apply_directmedia_ha(p, opp, "audio")) {
29741 res = AST_RTP_GLUE_RESULT_FORBID;
29742 }
29743 } else if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA_NAT)) {
29744 res = AST_RTP_GLUE_RESULT_REMOTE;
29745 } else if (ast_test_flag(&global_jbconf, AST_JB_FORCED)) {
29746 res = AST_RTP_GLUE_RESULT_FORBID;
29747 }
29748
29749 if (opp) {
29750 sip_pvt_unlock(opp);
29751 }
29752
29753 if (p->srtp) {
29754 res = AST_RTP_GLUE_RESULT_FORBID;
29755 }
29756
29757 sip_pvt_unlock(p);
29758
29759 return res;
29760 }
29761
29762 static enum ast_rtp_glue_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
29763 {
29764 struct sip_pvt *p = NULL;
29765 struct ast_channel *opp_chan;
29766 struct sip_pvt *opp = NULL;
29767 enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_FORBID;
29768
29769 if (!(p = chan->tech_pvt)) {
29770 return AST_RTP_GLUE_RESULT_FORBID;
29771 }
29772
29773 if ((opp_chan = ast_bridged_channel(chan)) && (((opp_chan->tech != &sip_tech) && (opp_chan->tech != &sip_tech_info)) ||
29774 (!(opp = opp_chan->tech_pvt)))) {
29775 return AST_RTP_GLUE_RESULT_FORBID;
29776 }
29777
29778 sip_pvt_lock(p);
29779 while (opp && sip_pvt_trylock(opp)) {
29780 sip_pvt_unlock(p);
29781 usleep(1);
29782 sip_pvt_lock(p);
29783 }
29784
29785 if (!(p->vrtp)) {
29786 if (opp) {
29787 sip_pvt_unlock(opp);
29788 }
29789 sip_pvt_unlock(p);
29790 return AST_RTP_GLUE_RESULT_FORBID;
29791 }
29792
29793 ao2_ref(p->vrtp, +1);
29794 *instance = p->vrtp;
29795
29796 if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
29797 res = AST_RTP_GLUE_RESULT_REMOTE;
29798 if (opp && !apply_directmedia_ha(p, opp, "video")) {
29799 res = AST_RTP_GLUE_RESULT_FORBID;
29800 }
29801 }
29802
29803 if (opp) {
29804 sip_pvt_unlock(opp);
29805 }
29806 sip_pvt_unlock(p);
29807
29808 return res;
29809 }
29810
29811 static enum ast_rtp_glue_result sip_get_trtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
29812 {
29813 struct sip_pvt *p = NULL;
29814 struct ast_channel *opp_chan;
29815 struct sip_pvt *opp = NULL;
29816 enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_FORBID;
29817
29818 if (!(p = chan->tech_pvt)) {
29819 return AST_RTP_GLUE_RESULT_FORBID;
29820 }
29821
29822 if ((opp_chan = ast_bridged_channel(chan)) && (((opp_chan->tech != &sip_tech) && (opp_chan->tech != &sip_tech_info)) ||
29823 (!(opp = opp_chan->tech_pvt)))) {
29824 return AST_RTP_GLUE_RESULT_FORBID;
29825 }
29826
29827 sip_pvt_lock(p);
29828 while (opp && sip_pvt_trylock(opp)) {
29829 sip_pvt_unlock(p);
29830 usleep(1);
29831 sip_pvt_lock(p);
29832 }
29833
29834 if (!(p->trtp)) {
29835 if (opp) {
29836 sip_pvt_unlock(opp);
29837 }
29838 sip_pvt_unlock(p);
29839 return AST_RTP_GLUE_RESULT_FORBID;
29840 }
29841
29842 ao2_ref(p->trtp, +1);
29843 *instance = p->trtp;
29844
29845 if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
29846 res = AST_RTP_GLUE_RESULT_REMOTE;
29847 if (opp && !apply_directmedia_ha(p, opp, "text")) {
29848 res = AST_RTP_GLUE_RESULT_FORBID;
29849 }
29850 }
29851
29852 if (opp) {
29853 sip_pvt_unlock(opp);
29854 }
29855 sip_pvt_unlock(p);
29856
29857 return res;
29858 }
29859
29860 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)
29861 {
29862 struct sip_pvt *p;
29863 int changed = 0;
29864
29865
29866 ast_channel_lock(chan);
29867 p = chan->tech_pvt;
29868 if (!p) {
29869 ast_channel_unlock(chan);
29870 return -1;
29871 }
29872 sip_pvt_lock(p);
29873 if (p->owner != chan) {
29874
29875 ast_debug(1, "The private is not owned by channel %s anymore.\n", chan->name);
29876 sip_pvt_unlock(p);
29877 ast_channel_unlock(chan);
29878 return 0;
29879 }
29880
29881
29882 if ((instance || vinstance || tinstance) &&
29883 !ast_bridged_channel(chan) &&
29884 !sip_cfg.directrtpsetup) {
29885 sip_pvt_unlock(p);
29886 ast_channel_unlock(chan);
29887 return 0;
29888 }
29889
29890 if (p->alreadygone) {
29891
29892 sip_pvt_unlock(p);
29893 ast_channel_unlock(chan);
29894 return 0;
29895 }
29896
29897
29898
29899
29900 if (nat_active && !ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA_NAT)) {
29901 sip_pvt_unlock(p);
29902 ast_channel_unlock(chan);
29903 return 0;
29904 }
29905
29906 if (instance) {
29907 changed |= ast_rtp_instance_get_and_cmp_remote_address(instance, &p->redirip);
29908
29909 if (p->rtp) {
29910
29911 ast_channel_set_fd(chan, 1, -1);
29912
29913 ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_RTCP, 0);
29914 }
29915 } else if (!ast_sockaddr_isnull(&p->redirip)) {
29916 memset(&p->redirip, 0, sizeof(p->redirip));
29917 changed = 1;
29918
29919 if (p->rtp) {
29920
29921
29922 ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_RTCP, 1);
29923
29924 ast_channel_set_fd(chan, 1, ast_rtp_instance_fd(p->rtp, 1));
29925 }
29926 }
29927
29928 if (vinstance) {
29929 changed |= ast_rtp_instance_get_and_cmp_remote_address(vinstance, &p->vredirip);
29930
29931 if (p->vrtp) {
29932
29933 ast_channel_set_fd(chan, 3, -1);
29934
29935 ast_rtp_instance_set_prop(p->vrtp, AST_RTP_PROPERTY_RTCP, 0);
29936 }
29937 } else if (!ast_sockaddr_isnull(&p->vredirip)) {
29938 memset(&p->vredirip, 0, sizeof(p->vredirip));
29939 changed = 1;
29940
29941 if (p->vrtp) {
29942
29943
29944 ast_rtp_instance_set_prop(p->vrtp, AST_RTP_PROPERTY_RTCP, 1);
29945
29946 ast_channel_set_fd(chan, 3, ast_rtp_instance_fd(p->vrtp, 1));
29947 }
29948 }
29949
29950 if (tinstance) {
29951 changed |= ast_rtp_instance_get_and_cmp_remote_address(tinstance, &p->tredirip);
29952 } else if (!ast_sockaddr_isnull(&p->tredirip)) {
29953 memset(&p->tredirip, 0, sizeof(p->tredirip));
29954 changed = 1;
29955 }
29956 if (codecs && (p->redircodecs != codecs)) {
29957 p->redircodecs = codecs;
29958 changed = 1;
29959 }
29960
29961 if (ast_test_flag(&p->flags[2], SIP_PAGE3_DIRECT_MEDIA_OUTGOING) && !p->outgoing_call) {
29962
29963
29964
29965
29966 ast_clear_flag(&p->flags[2], SIP_PAGE3_DIRECT_MEDIA_OUTGOING);
29967 sip_pvt_unlock(p);
29968 ast_channel_unlock(chan);
29969 return 0;
29970 }
29971
29972 if (changed && !ast_test_flag(&p->flags[0], SIP_GOTREFER) && !ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
29973 if (chan->_state != AST_STATE_UP) {
29974 if (p->do_history)
29975 append_history(p, "ExtInv", "Initial invite sent with remote bridge proposal.");
29976 ast_debug(1, "Early remote bridge setting SIP '%s' - Sending media to %s\n", p->callid, ast_sockaddr_stringify(instance ? &p->redirip : &p->ourip));
29977 } else if (!p->pendinginvite) {
29978 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));
29979 transmit_reinvite_with_sdp(p, FALSE, FALSE);
29980 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
29981 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));
29982
29983 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
29984 }
29985 }
29986
29987 p->lastrtprx = p->lastrtptx = time(NULL);
29988 sip_pvt_unlock(p);
29989 ast_channel_unlock(chan);
29990 return 0;
29991 }
29992
29993 static format_t sip_get_codec(struct ast_channel *chan)
29994 {
29995 struct sip_pvt *p = chan->tech_pvt;
29996 return p->peercapability ? p->peercapability : p->capability;
29997 }
29998
29999 static struct ast_rtp_glue sip_rtp_glue = {
30000 .type = "SIP",
30001 .get_rtp_info = sip_get_rtp_peer,
30002 .get_vrtp_info = sip_get_vrtp_peer,
30003 .get_trtp_info = sip_get_trtp_peer,
30004 .update_peer = sip_set_rtp_peer,
30005 .get_codec = sip_get_codec,
30006 };
30007
30008 static char *app_dtmfmode = "SIPDtmfMode";
30009 static char *app_sipaddheader = "SIPAddHeader";
30010 static char *app_sipremoveheader = "SIPRemoveHeader";
30011
30012
30013 static int sip_dtmfmode(struct ast_channel *chan, const char *data)
30014 {
30015 struct sip_pvt *p;
30016 const char *mode = data;
30017
30018 if (!data) {
30019 ast_log(LOG_WARNING, "This application requires the argument: info, inband, rfc2833\n");
30020 return 0;
30021 }
30022 ast_channel_lock(chan);
30023 if (!IS_SIP_TECH(chan->tech)) {
30024 ast_log(LOG_WARNING, "Call this application only on SIP incoming calls\n");
30025 ast_channel_unlock(chan);
30026 return 0;
30027 }
30028 p = chan->tech_pvt;
30029 if (!p) {
30030 ast_channel_unlock(chan);
30031 return 0;
30032 }
30033 sip_pvt_lock(p);
30034 if (!strcasecmp(mode, "info")) {
30035 ast_clear_flag(&p->flags[0], SIP_DTMF);
30036 ast_set_flag(&p->flags[0], SIP_DTMF_INFO);
30037 p->jointnoncodeccapability &= ~AST_RTP_DTMF;
30038 } else if (!strcasecmp(mode, "shortinfo")) {
30039 ast_clear_flag(&p->flags[0], SIP_DTMF);
30040 ast_set_flag(&p->flags[0], SIP_DTMF_SHORTINFO);
30041 p->jointnoncodeccapability &= ~AST_RTP_DTMF;
30042 } else if (!strcasecmp(mode, "rfc2833")) {
30043 ast_clear_flag(&p->flags[0], SIP_DTMF);
30044 ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
30045 p->jointnoncodeccapability |= AST_RTP_DTMF;
30046 } else if (!strcasecmp(mode, "inband")) {
30047 ast_clear_flag(&p->flags[0], SIP_DTMF);
30048 ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
30049 p->jointnoncodeccapability &= ~AST_RTP_DTMF;
30050 } else {
30051 ast_log(LOG_WARNING, "I don't know about this dtmf mode: %s\n", mode);
30052 }
30053 if (p->rtp)
30054 ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
30055 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
30056 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
30057 enable_dsp_detect(p);
30058 } else {
30059 disable_dsp_detect(p);
30060 }
30061 sip_pvt_unlock(p);
30062 ast_channel_unlock(chan);
30063 return 0;
30064 }
30065
30066
30067 static int sip_addheader(struct ast_channel *chan, const char *data)
30068 {
30069 int no = 0;
30070 int ok = FALSE;
30071 char varbuf[30];
30072 const char *inbuf = data;
30073 char *subbuf;
30074
30075 if (ast_strlen_zero(inbuf)) {
30076 ast_log(LOG_WARNING, "This application requires the argument: Header\n");
30077 return 0;
30078 }
30079 ast_channel_lock(chan);
30080
30081
30082 while (!ok && no <= 50) {
30083 no++;
30084 snprintf(varbuf, sizeof(varbuf), "__SIPADDHEADER%.2d", no);
30085
30086
30087 if ((pbx_builtin_getvar_helper(chan, (const char *) varbuf + 2) == (const char *) NULL)) {
30088 ok = TRUE;
30089 }
30090 }
30091 if (ok) {
30092 size_t len = strlen(inbuf);
30093 subbuf = ast_alloca(len + 1);
30094 ast_get_encoded_str(inbuf, subbuf, len + 1);
30095 pbx_builtin_setvar_helper(chan, varbuf, subbuf);
30096 if (sipdebug) {
30097 ast_debug(1, "SIP Header added \"%s\" as %s\n", inbuf, varbuf);
30098 }
30099 } else {
30100 ast_log(LOG_WARNING, "Too many SIP headers added, max 50\n");
30101 }
30102 ast_channel_unlock(chan);
30103 return 0;
30104 }
30105
30106
30107 static int sip_removeheader(struct ast_channel *chan, const char *data)
30108 {
30109 struct ast_var_t *newvariable;
30110 struct varshead *headp;
30111 int removeall = 0;
30112 char *inbuf = (char *) data;
30113
30114 if (ast_strlen_zero(inbuf)) {
30115 removeall = 1;
30116 }
30117 ast_channel_lock(chan);
30118
30119 headp=&chan->varshead;
30120 AST_LIST_TRAVERSE_SAFE_BEGIN (headp, newvariable, entries) {
30121 if (strncasecmp(ast_var_name(newvariable), "SIPADDHEADER", strlen("SIPADDHEADER")) == 0) {
30122 if (removeall || (!strncasecmp(ast_var_value(newvariable),inbuf,strlen(inbuf)))) {
30123 if (sipdebug)
30124 ast_debug(1,"removing SIP Header \"%s\" as %s\n",
30125 ast_var_value(newvariable),
30126 ast_var_name(newvariable));
30127 AST_LIST_REMOVE_CURRENT(entries);
30128 ast_var_delete(newvariable);
30129 }
30130 }
30131 }
30132 AST_LIST_TRAVERSE_SAFE_END;
30133
30134 ast_channel_unlock(chan);
30135 return 0;
30136 }
30137
30138
30139
30140
30141
30142
30143
30144 static int sip_sipredirect(struct sip_pvt *p, const char *dest)
30145 {
30146 char *cdest;
30147 char *extension, *domain;
30148
30149 cdest = ast_strdupa(dest);
30150
30151 extension = strsep(&cdest, "@");
30152 domain = cdest;
30153 if (ast_strlen_zero(extension)) {
30154 ast_log(LOG_ERROR, "Missing mandatory argument: extension\n");
30155 return 0;
30156 }
30157
30158
30159 if (!domain) {
30160 char *local_to_header;
30161 char to_header[256];
30162
30163 ast_copy_string(to_header, get_header(&p->initreq, "To"), sizeof(to_header));
30164 if (ast_strlen_zero(to_header)) {
30165 ast_log(LOG_ERROR, "Cannot retrieve the 'To' header from the original SIP request!\n");
30166 return 0;
30167 }
30168 if (((local_to_header = strcasestr(to_header, "sip:")) || (local_to_header = strcasestr(to_header, "sips:")))
30169 && (local_to_header = strchr(local_to_header, '@'))) {
30170 char ldomain[256];
30171
30172 memset(ldomain, 0, sizeof(ldomain));
30173 local_to_header++;
30174
30175 sscanf(local_to_header, "%256[^<>; ]", ldomain);
30176 if (ast_strlen_zero(ldomain)) {
30177 ast_log(LOG_ERROR, "Can't find the host address\n");
30178 return 0;
30179 }
30180 domain = ast_strdupa(ldomain);
30181 }
30182 }
30183
30184 ast_string_field_build(p, our_contact, "Transfer <sip:%s@%s>", extension, domain);
30185 transmit_response_reliable(p, "302 Moved Temporarily", &p->initreq);
30186
30187 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
30188 sip_alreadygone(p);
30189
30190 if (p->owner) {
30191 enum ast_control_transfer message = AST_TRANSFER_SUCCESS;
30192 ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
30193 }
30194
30195 return 0;
30196 }
30197
30198 static int sip_is_xml_parsable(void)
30199 {
30200 #ifdef HAVE_LIBXML2
30201 return TRUE;
30202 #else
30203 return FALSE;
30204 #endif
30205 }
30206
30207
30208 static void sip_poke_all_peers(void)
30209 {
30210 int ms = 0, num = 0;
30211 struct ao2_iterator i;
30212 struct sip_peer *peer;
30213
30214 if (!speerobjs) {
30215 return;
30216 }
30217
30218 i = ao2_iterator_init(peers, 0);
30219 while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
30220 ao2_lock(peer);
30221
30222 if (peer->maxms) {
30223 if (num == global_qualify_peers) {
30224 ms += global_qualify_gap;
30225 num = 0;
30226 } else {
30227 num++;
30228 }
30229 AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, ms, sip_poke_peer_s, peer,
30230 unref_peer(_data, "removing poke peer ref"),
30231 unref_peer(peer, "removing poke peer ref"),
30232 ref_peer(peer, "adding poke peer ref"));
30233 }
30234 ao2_unlock(peer);
30235 unref_peer(peer, "toss iterator peer ptr");
30236 }
30237 ao2_iterator_destroy(&i);
30238 }
30239
30240
30241 static void sip_send_all_registers(void)
30242 {
30243 int ms;
30244 int regspacing;
30245 if (!regobjs)
30246 return;
30247 regspacing = default_expiry * 1000/regobjs;
30248 if (regspacing > 100) {
30249 regspacing = 100;
30250 }
30251 ms = regspacing;
30252 ASTOBJ_CONTAINER_TRAVERSE(®l, 1, do {
30253 ASTOBJ_WRLOCK(iterator);
30254 ms += regspacing;
30255 AST_SCHED_REPLACE_UNREF(iterator->expire, sched, ms, sip_reregister, iterator,
30256 registry_unref(_data, "REPLACE sched del decs the refcount"),
30257 registry_unref(iterator, "REPLACE sched add failure decs the refcount"),
30258 registry_addref(iterator, "REPLACE sched add incs the refcount"));
30259 ASTOBJ_UNLOCK(iterator);
30260 } while (0)
30261 );
30262 }
30263
30264
30265 static void sip_send_all_mwi_subscriptions(void)
30266 {
30267 ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
30268 struct sip_subscription_mwi *saved;
30269 ASTOBJ_WRLOCK(iterator);
30270 AST_SCHED_DEL(sched, iterator->resub);
30271 saved = ASTOBJ_REF(iterator);
30272 if ((iterator->resub = ast_sched_add(sched, 1, sip_subscribe_mwi_do, saved)) < 0) {
30273 ASTOBJ_UNREF(saved, sip_subscribe_mwi_destroy);
30274 }
30275 ASTOBJ_UNLOCK(iterator);
30276 } while (0));
30277 }
30278
30279
30280 static int setup_srtp(struct sip_srtp **srtp)
30281 {
30282 if (!ast_rtp_engine_srtp_is_registered()) {
30283 ast_log(LOG_ERROR, "No SRTP module loaded, can't setup SRTP session.\n");
30284 return -1;
30285 }
30286
30287 if (!(*srtp = sip_srtp_alloc())) {
30288 return -1;
30289 }
30290
30291 return 0;
30292 }
30293
30294 static int process_crypto(struct sip_pvt *p, struct ast_rtp_instance *rtp, struct sip_srtp **srtp, const char *a)
30295 {
30296
30297 if (!rtp) {
30298 ast_debug(3, "Received offer with crypto line for media stream that is not enabled\n");
30299 return FALSE;
30300 }
30301
30302 if (strncasecmp(a, "crypto:", 7)) {
30303 return FALSE;
30304 }
30305 if (!*srtp) {
30306 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
30307 ast_log(LOG_WARNING, "Ignoring unexpected crypto attribute in SDP answer\n");
30308 return FALSE;
30309 }
30310
30311 if (setup_srtp(srtp) < 0) {
30312 return FALSE;
30313 }
30314 }
30315
30316 if (!(*srtp)->crypto && !((*srtp)->crypto = sdp_crypto_setup())) {
30317 return FALSE;
30318 }
30319
30320 if (sdp_crypto_process((*srtp)->crypto, a, rtp) < 0) {
30321 return FALSE;
30322 }
30323
30324 ast_set_flag(*srtp, SRTP_CRYPTO_OFFER_OK);
30325
30326 return TRUE;
30327 }
30328
30329
30330 static int sip_do_reload(enum channelreloadreason reason)
30331 {
30332 time_t start_poke, end_poke;
30333
30334 reload_config(reason);
30335 ast_sched_dump(sched);
30336
30337 start_poke = time(0);
30338
30339 unlink_marked_peers_from_tables();
30340
30341 ast_debug(4, "--------------- Done destroying pruned peers\n");
30342
30343
30344 sip_poke_all_peers();
30345
30346
30347 sip_send_all_registers();
30348
30349 sip_send_all_mwi_subscriptions();
30350
30351 end_poke = time(0);
30352
30353 ast_debug(4, "do_reload finished. peer poke/prune reg contact time = %d sec.\n", (int)(end_poke-start_poke));
30354
30355 ast_debug(4, "--------------- SIP reload done\n");
30356
30357 return 0;
30358 }
30359
30360
30361 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
30362 {
30363
30364 switch (cmd) {
30365 case CLI_INIT:
30366 e->command = "sip reload";
30367 e->usage =
30368 "Usage: sip reload\n"
30369 " Reloads SIP configuration from sip.conf\n";
30370 return NULL;
30371 case CLI_GENERATE:
30372 return NULL;
30373 }
30374
30375 ast_mutex_lock(&sip_reload_lock);
30376 if (sip_reloading) {
30377 ast_verbose("Previous SIP reload not yet done\n");
30378 } else {
30379 sip_reloading = TRUE;
30380 sip_reloadreason = (a && a->fd) ? CHANNEL_CLI_RELOAD : CHANNEL_MODULE_RELOAD;
30381 }
30382 ast_mutex_unlock(&sip_reload_lock);
30383 restart_monitor();
30384
30385 return CLI_SUCCESS;
30386 }
30387
30388
30389 static int reload(void)
30390 {
30391 if (sip_reload(0, 0, NULL))
30392 return 0;
30393 return 1;
30394 }
30395
30396
30397
30398
30399
30400 static int ast_sockaddr_resolve_first_af(struct ast_sockaddr *addr,
30401 const char* name, int flag, int family)
30402 {
30403 struct ast_sockaddr *addrs;
30404 int addrs_cnt;
30405
30406 addrs_cnt = ast_sockaddr_resolve(&addrs, name, flag, family);
30407 if (addrs_cnt <= 0) {
30408 return 1;
30409 }
30410 if (addrs_cnt > 1) {
30411 ast_debug(1, "Multiple addresses, using the first one only\n");
30412 }
30413
30414 ast_sockaddr_copy(addr, &addrs[0]);
30415
30416 ast_free(addrs);
30417 return 0;
30418 }
30419
30420
30421
30422
30423
30424 static int ast_sockaddr_resolve_first(struct ast_sockaddr *addr,
30425 const char* name, int flag)
30426 {
30427 return ast_sockaddr_resolve_first_af(addr, name, flag, get_address_family_filter(SIP_TRANSPORT_UDP));
30428 }
30429
30430
30431
30432
30433
30434 static int ast_sockaddr_resolve_first_transport(struct ast_sockaddr *addr,
30435 const char* name, int flag, unsigned int transport)
30436 {
30437 return ast_sockaddr_resolve_first_af(addr, name, flag, get_address_family_filter(transport));
30438 }
30439
30440
30441
30442
30443 static int peer_hash_cb(const void *obj, const int flags)
30444 {
30445 const struct sip_peer *peer = obj;
30446
30447 return ast_str_case_hash(peer->name);
30448 }
30449
30450
30451
30452
30453 static int peer_cmp_cb(void *obj, void *arg, int flags)
30454 {
30455 struct sip_peer *peer = obj, *peer2 = arg;
30456
30457 return !strcasecmp(peer->name, peer2->name) ? CMP_MATCH | CMP_STOP : 0;
30458 }
30459
30460
30461
30462
30463
30464
30465 static int peer_iphash_cb(const void *obj, const int flags)
30466 {
30467 const struct sip_peer *peer = obj;
30468 int ret = 0;
30469
30470 if (ast_sockaddr_isnull(&peer->addr)) {
30471 ast_log(LOG_ERROR, "Empty address\n");
30472 }
30473
30474 ret = ast_sockaddr_hash(&peer->addr);
30475
30476 if (ret < 0) {
30477 ret = -ret;
30478 }
30479
30480 return ret;
30481 }
30482
30483
30484
30485
30486
30487
30488
30489
30490
30491
30492
30493
30494
30495
30496
30497
30498
30499
30500
30501 static int peer_ipcmp_cb(void *obj, void *arg, int flags)
30502 {
30503 struct sip_peer *peer = obj, *peer2 = arg;
30504
30505 if (ast_sockaddr_cmp_addr(&peer->addr, &peer2->addr)) {
30506
30507 return 0;
30508 }
30509
30510
30511 if ((peer->transports & peer2->transports) & (SIP_TRANSPORT_TLS | SIP_TRANSPORT_TCP)) {
30512
30513 return CMP_MATCH | CMP_STOP;
30514 } else if (ast_test_flag(&peer2->flags[0], SIP_INSECURE_PORT)) {
30515
30516
30517 return ast_test_flag(&peer->flags[0], SIP_INSECURE_PORT) ?
30518 (CMP_MATCH | CMP_STOP) : 0;
30519 }
30520
30521
30522 return ast_sockaddr_port(&peer->addr) == ast_sockaddr_port(&peer2->addr) ?
30523 (CMP_MATCH | CMP_STOP) : 0;
30524 }
30525
30526
30527 static int threadt_hash_cb(const void *obj, const int flags)
30528 {
30529 const struct sip_threadinfo *th = obj;
30530
30531 return ast_sockaddr_hash(&th->tcptls_session->remote_address);
30532 }
30533
30534 static int threadt_cmp_cb(void *obj, void *arg, int flags)
30535 {
30536 struct sip_threadinfo *th = obj, *th2 = arg;
30537
30538 return (th->tcptls_session == th2->tcptls_session) ? CMP_MATCH | CMP_STOP : 0;
30539 }
30540
30541
30542
30543
30544 static int dialog_hash_cb(const void *obj, const int flags)
30545 {
30546 const struct sip_pvt *pvt = obj;
30547
30548 return ast_str_case_hash(pvt->callid);
30549 }
30550
30551
30552
30553
30554 static int dialog_find_multiple(void *obj, void *arg, int flags)
30555 {
30556 struct sip_pvt *pvt = obj, *pvt2 = arg;
30557
30558 return !strcasecmp(pvt->callid, pvt2->callid) ? CMP_MATCH : 0;
30559 }
30560
30561
30562
30563
30564 static int dialog_cmp_cb(void *obj, void *arg, int flags)
30565 {
30566 struct sip_pvt *pvt = obj, *pvt2 = arg;
30567
30568 return !strcasecmp(pvt->callid, pvt2->callid) ? CMP_MATCH | CMP_STOP : 0;
30569 }
30570
30571
30572 static struct ast_cli_entry cli_sip[] = {
30573 AST_CLI_DEFINE(sip_show_channels, "List active SIP channels or subscriptions"),
30574 AST_CLI_DEFINE(sip_show_channelstats, "List statistics for active SIP channels"),
30575 AST_CLI_DEFINE(sip_show_domains, "List our local SIP domains"),
30576 AST_CLI_DEFINE(sip_show_inuse, "List all inuse/limits"),
30577 AST_CLI_DEFINE(sip_show_objects, "List all SIP object allocations"),
30578 AST_CLI_DEFINE(sip_show_peers, "List defined SIP peers"),
30579 AST_CLI_DEFINE(sip_show_registry, "List SIP registration status"),
30580 AST_CLI_DEFINE(sip_unregister, "Unregister (force expiration) a SIP peer from the registry"),
30581 AST_CLI_DEFINE(sip_show_settings, "Show SIP global settings"),
30582 AST_CLI_DEFINE(sip_show_mwi, "Show MWI subscriptions"),
30583 AST_CLI_DEFINE(sip_cli_notify, "Send a notify packet to a SIP peer"),
30584 AST_CLI_DEFINE(sip_show_channel, "Show detailed SIP channel info"),
30585 AST_CLI_DEFINE(sip_show_history, "Show SIP dialog history"),
30586 AST_CLI_DEFINE(sip_show_peer, "Show details on specific SIP peer"),
30587 AST_CLI_DEFINE(sip_show_users, "List defined SIP users"),
30588 AST_CLI_DEFINE(sip_show_user, "Show details on specific SIP user"),
30589 AST_CLI_DEFINE(sip_qualify_peer, "Send an OPTIONS packet to a peer"),
30590 AST_CLI_DEFINE(sip_show_sched, "Present a report on the status of the scheduler queue"),
30591 AST_CLI_DEFINE(sip_prune_realtime, "Prune cached Realtime users/peers"),
30592 AST_CLI_DEFINE(sip_do_debug, "Enable/Disable SIP debugging"),
30593 AST_CLI_DEFINE(sip_set_history, "Enable/Disable SIP history"),
30594 AST_CLI_DEFINE(sip_reload, "Reload SIP configuration"),
30595 AST_CLI_DEFINE(sip_show_tcp, "List TCP Connections")
30596 };
30597
30598
30599 static void sip_register_tests(void)
30600 {
30601 sip_config_parser_register_tests();
30602 sip_request_parser_register_tests();
30603 sip_dialplan_function_register_tests();
30604 }
30605
30606
30607 static void sip_unregister_tests(void)
30608 {
30609 sip_config_parser_unregister_tests();
30610 sip_request_parser_unregister_tests();
30611 sip_dialplan_function_unregister_tests();
30612 }
30613
30614 #ifdef TEST_FRAMEWORK
30615 AST_TEST_DEFINE(test_sip_mwi_subscribe_parse)
30616 {
30617 int found = 0;
30618 enum ast_test_result_state res = AST_TEST_PASS;
30619 const char *mwi1 = "1234@mysipprovider.com/1234";
30620 const char *mwi2 = "1234:password@mysipprovider.com/1234";
30621 const char *mwi3 = "1234:password@mysipprovider.com:5061/1234";
30622 const char *mwi4 = "1234:password:authuser@mysipprovider.com/1234";
30623 const char *mwi5 = "1234:password:authuser@mysipprovider.com:5061/1234";
30624 const char *mwi6 = "1234:password";
30625
30626 switch (cmd) {
30627 case TEST_INIT:
30628 info->name = "sip_mwi_subscribe_parse_test";
30629 info->category = "/channels/chan_sip/";
30630 info->summary = "SIP MWI subscribe line parse unit test";
30631 info->description =
30632 "Tests the parsing of mwi subscription lines (e.g., mwi => from sip.conf)";
30633 return AST_TEST_NOT_RUN;
30634 case TEST_EXECUTE:
30635 break;
30636 }
30637
30638 if (sip_subscribe_mwi(mwi1, 1)) {
30639 res = AST_TEST_FAIL;
30640 } else {
30641 found = 0;
30642 res = AST_TEST_FAIL;
30643 ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
30644 ASTOBJ_WRLOCK(iterator);
30645 if (
30646 !strcmp(iterator->hostname, "mysipprovider.com") &&
30647 !strcmp(iterator->username, "1234") &&
30648 !strcmp(iterator->secret, "") &&
30649 !strcmp(iterator->authuser, "") &&
30650 !strcmp(iterator->mailbox, "1234") &&
30651 iterator->portno == 0) {
30652 found = 1;
30653 res = AST_TEST_PASS;
30654 }
30655 ASTOBJ_UNLOCK(iterator);
30656 } while(0));
30657 if (!found) {
30658 ast_test_status_update(test, "sip_subscribe_mwi test 1 failed\n");
30659 }
30660 }
30661
30662 if (sip_subscribe_mwi(mwi2, 1)) {
30663 res = AST_TEST_FAIL;
30664 } else {
30665 found = 0;
30666 res = AST_TEST_FAIL;
30667 ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
30668 ASTOBJ_WRLOCK(iterator);
30669 if (
30670 !strcmp(iterator->hostname, "mysipprovider.com") &&
30671 !strcmp(iterator->username, "1234") &&
30672 !strcmp(iterator->secret, "password") &&
30673 !strcmp(iterator->authuser, "") &&
30674 !strcmp(iterator->mailbox, "1234") &&
30675 iterator->portno == 0) {
30676 found = 1;
30677 res = AST_TEST_PASS;
30678 }
30679 ASTOBJ_UNLOCK(iterator);
30680 } while(0));
30681 if (!found) {
30682 ast_test_status_update(test, "sip_subscribe_mwi test 2 failed\n");
30683 }
30684 }
30685
30686 if (sip_subscribe_mwi(mwi3, 1)) {
30687 res = AST_TEST_FAIL;
30688 } else {
30689 found = 0;
30690 res = AST_TEST_FAIL;
30691 ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
30692 ASTOBJ_WRLOCK(iterator);
30693 if (
30694 !strcmp(iterator->hostname, "mysipprovider.com") &&
30695 !strcmp(iterator->username, "1234") &&
30696 !strcmp(iterator->secret, "password") &&
30697 !strcmp(iterator->authuser, "") &&
30698 !strcmp(iterator->mailbox, "1234") &&
30699 iterator->portno == 5061) {
30700 found = 1;
30701 res = AST_TEST_PASS;
30702 }
30703 ASTOBJ_UNLOCK(iterator);
30704 } while(0));
30705 if (!found) {
30706 ast_test_status_update(test, "sip_subscribe_mwi test 3 failed\n");
30707 }
30708 }
30709
30710 if (sip_subscribe_mwi(mwi4, 1)) {
30711 res = AST_TEST_FAIL;
30712 } else {
30713 found = 0;
30714 res = AST_TEST_FAIL;
30715 ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
30716 ASTOBJ_WRLOCK(iterator);
30717 if (
30718 !strcmp(iterator->hostname, "mysipprovider.com") &&
30719 !strcmp(iterator->username, "1234") &&
30720 !strcmp(iterator->secret, "password") &&
30721 !strcmp(iterator->authuser, "authuser") &&
30722 !strcmp(iterator->mailbox, "1234") &&
30723 iterator->portno == 0) {
30724 found = 1;
30725 res = AST_TEST_PASS;
30726 }
30727 ASTOBJ_UNLOCK(iterator);
30728 } while(0));
30729 if (!found) {
30730 ast_test_status_update(test, "sip_subscribe_mwi test 4 failed\n");
30731 }
30732 }
30733
30734 if (sip_subscribe_mwi(mwi5, 1)) {
30735 res = AST_TEST_FAIL;
30736 } else {
30737 found = 0;
30738 res = AST_TEST_FAIL;
30739 ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
30740 ASTOBJ_WRLOCK(iterator);
30741 if (
30742 !strcmp(iterator->hostname, "mysipprovider.com") &&
30743 !strcmp(iterator->username, "1234") &&
30744 !strcmp(iterator->secret, "password") &&
30745 !strcmp(iterator->authuser, "authuser") &&
30746 !strcmp(iterator->mailbox, "1234") &&
30747 iterator->portno == 5061) {
30748 found = 1;
30749 res = AST_TEST_PASS;
30750 }
30751 ASTOBJ_UNLOCK(iterator);
30752 } while(0));
30753 if (!found) {
30754 ast_test_status_update(test, "sip_subscribe_mwi test 5 failed\n");
30755 }
30756 }
30757
30758 if (sip_subscribe_mwi(mwi6, 1)) {
30759 res = AST_TEST_PASS;
30760 } else {
30761 res = AST_TEST_FAIL;
30762 }
30763 return res;
30764 }
30765
30766 AST_TEST_DEFINE(test_sip_peers_get)
30767 {
30768 struct sip_peer *peer;
30769 struct ast_data *node;
30770 struct ast_data_query query = {
30771 .path = "/asterisk/channel/sip/peers",
30772 .search = "peers/peer/name=test_peer_data_provider"
30773 };
30774
30775 switch (cmd) {
30776 case TEST_INIT:
30777 info->name = "sip_peers_get_data_test";
30778 info->category = "/main/data/sip/peers/";
30779 info->summary = "SIP peers data providers unit test";
30780 info->description =
30781 "Tests whether the SIP peers data provider implementation works as expected.";
30782 return AST_TEST_NOT_RUN;
30783 case TEST_EXECUTE:
30784 break;
30785 }
30786
30787
30788 peer = build_peer("test_peer_data_provider", NULL, NULL, 0, 0);
30789 if (!peer) {
30790 return AST_TEST_FAIL;
30791 }
30792 peer->type = SIP_TYPE_USER;
30793 peer->call_limit = 10;
30794 ao2_link(peers, peer);
30795
30796
30797 node = ast_data_get(&query);
30798 if (!node) {
30799 ao2_unlink(peers, peer);
30800 ao2_ref(peer, -1);
30801 return AST_TEST_FAIL;
30802 }
30803
30804
30805 if (strcmp(ast_data_retrieve_string(node, "peer/name"), "test_peer_data_provider")) {
30806 ao2_unlink(peers, peer);
30807 ao2_ref(peer, -1);
30808 ast_data_free(node);
30809 return AST_TEST_FAIL;
30810 }
30811
30812 if (strcmp(ast_data_retrieve_string(node, "peer/type"), "user")) {
30813 ao2_unlink(peers, peer);
30814 ao2_ref(peer, -1);
30815 ast_data_free(node);
30816 return AST_TEST_FAIL;
30817 }
30818
30819 if (ast_data_retrieve_int(node, "peer/call_limit") != 10) {
30820 ao2_unlink(peers, peer);
30821 ao2_ref(peer, -1);
30822 ast_data_free(node);
30823 return AST_TEST_FAIL;
30824 }
30825
30826
30827 ast_data_free(node);
30828
30829 ao2_unlink(peers, peer);
30830 ao2_ref(peer, -1);
30831
30832 return AST_TEST_PASS;
30833 }
30834
30835
30836
30837
30838
30839
30840
30841
30842
30843
30844
30845
30846
30847
30848
30849
30850
30851
30852
30853 static int mock_tcp_loop(char *fragments[], size_t num_fragments,
30854 struct ast_str **overflow, char **messages, int *num_messages, struct ast_test* test)
30855 {
30856 struct ast_str *req_data;
30857 int i = 0;
30858 int res = 0;
30859
30860 req_data = ast_str_create(128);
30861 ast_str_reset(*overflow);
30862
30863 while (i < num_fragments || ast_str_strlen(*overflow) > 0) {
30864 enum message_integrity message_integrity = MESSAGE_FRAGMENT;
30865 ast_str_reset(req_data);
30866 while (message_integrity == MESSAGE_FRAGMENT) {
30867 if (ast_str_strlen(*overflow) > 0) {
30868 ast_str_append(&req_data, 0, "%s", ast_str_buffer(*overflow));
30869 ast_str_reset(*overflow);
30870 } else {
30871 ast_str_append(&req_data, 0, "%s", fragments[i++]);
30872 }
30873 message_integrity = check_message_integrity(&req_data, overflow);
30874 }
30875 if (strcmp(ast_str_buffer(req_data), messages[*num_messages])) {
30876 ast_test_status_update(test, "Mismatch in SIP messages.\n");
30877 ast_test_status_update(test, "Expected message:\n%s", messages[*num_messages]);
30878 ast_test_status_update(test, "Parsed message:\n%s", ast_str_buffer(req_data));
30879 res = -1;
30880 goto end;
30881 } else {
30882 ast_test_status_update(test, "Successfully read message:\n%s", ast_str_buffer(req_data));
30883 }
30884 (*num_messages)++;
30885 }
30886
30887 end:
30888 ast_free(req_data);
30889 return res;
30890 };
30891
30892 AST_TEST_DEFINE(test_tcp_message_fragmentation)
30893 {
30894
30895 char *normal[] = {
30896 "INVITE sip:bob@example.org SIP/2.0\r\n"
30897 "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
30898 "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
30899 "To: <sip:bob@example.org:5060>\r\n"
30900 "Call-ID: 12345\r\n"
30901 "CSeq: 1 INVITE\r\n"
30902 "Contact: sip:127.0.0.1:5061\r\n"
30903 "Max-Forwards: 70\r\n"
30904 "Content-Type: application/sdp\r\n"
30905 "Content-Length: 130\r\n"
30906 "\r\n"
30907 "v=0\r\n"
30908 "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
30909 "s=-\r\n"
30910 "c=IN IP4 127.0.0.1\r\n"
30911 "t=0 0\r\n"
30912 "m=audio 10000 RTP/AVP 0\r\n"
30913 "a=rtpmap:0 PCMU/8000\r\n"
30914 };
30915
30916
30917
30918
30919 char *fragmented[] = {
30920 "INVITE sip:bob@example.org SIP/2.0\r\n"
30921 "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
30922 "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
30923 "To: <sip:bob@example.org:5060>\r\n"
30924 "Call-ID: 12345\r\n"
30925 "CSeq: 1 INVITE\r\n"
30926 "Contact: sip:127.0.0.1:5061\r\n"
30927 "Max-Forwards: ",
30928
30929 "70\r\n"
30930 "Content-Type: application/sdp\r\n"
30931 "Content-Length: 130\r\n"
30932 "\r\n"
30933 "v=0\r\n"
30934 "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
30935 "s=-\r\n"
30936 "c=IN IP4 127.0.0.1\r\n"
30937 "t=0 0\r\n"
30938 "m=audio 10000 RTP/AVP 0\r\n"
30939 "a=rtpmap:0 PCMU/8000\r\n"
30940 };
30941
30942
30943
30944 char *fragmented_body[] = {
30945 "INVITE sip:bob@example.org SIP/2.0\r\n"
30946 "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
30947 "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
30948 "To: <sip:bob@example.org:5060>\r\n"
30949 "Call-ID: 12345\r\n"
30950 "CSeq: 1 INVITE\r\n"
30951 "Contact: sip:127.0.0.1:5061\r\n"
30952 "Max-Forwards: 70\r\n"
30953 "Content-Type: application/sdp\r\n"
30954 "Content-Length: 130\r\n"
30955 "\r\n",
30956
30957 "v=0\r\n"
30958 "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
30959 "s=-\r\n"
30960 "c=IN IP4 127.0.0.1\r\n"
30961 "t=0 0\r\n"
30962 "m=audio 10000 RTP/AVP 0\r\n"
30963 "a=rtpmap:0 PCMU/8000\r\n"
30964 };
30965
30966
30967
30968
30969 char *multi_fragment[] = {
30970 "INVITE sip:bob@example.org SIP/2.0\r\n"
30971 "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
30972 "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
30973 "To: <sip:bob@example.org:5060>\r\n"
30974 "Call-ID: 12345\r\n"
30975 "CSeq: 1 INVITE\r\n",
30976
30977 "Contact: sip:127.0.0.1:5061\r\n"
30978 "Max-Forwards: 70\r\n"
30979 "Content-Type: application/sdp\r\n"
30980 "Content-Length: 130\r\n"
30981 "\r\n"
30982 "v=0\r\n"
30983 "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
30984 "s=-\r\n"
30985 "c=IN IP4",
30986
30987 " 127.0.0.1\r\n"
30988 "t=0 0\r\n"
30989 "m=audio 10000 RTP/AVP 0\r\n"
30990 "a=rtpmap:0 PCMU/8000\r\n"
30991 };
30992
30993
30994
30995
30996 char *multi_message[] = {
30997 "SIP/2.0 100 Trying\r\n"
30998 "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
30999 "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
31000 "To: <sip:bob@example.org:5060>\r\n"
31001 "Call-ID: 12345\r\n"
31002 "CSeq: 1 INVITE\r\n"
31003 "Contact: <sip:bob@example.org:5060>\r\n"
31004 "Content-Length: 0\r\n"
31005 "\r\n"
31006 "SIP/2.0 180 Ringing\r\n"
31007 "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
31008 "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
31009 "To: <sip:bob@example.org:5060>\r\n"
31010 "Call-ID: 12345\r\n"
31011 "CSeq: 1 INVITE\r\n"
31012 "Contact: <sip:bob@example.org:5060>\r\n"
31013 "Content-Length: 0\r\n"
31014 "\r\n"
31015 };
31016 char *multi_message_divided[] = {
31017 "SIP/2.0 100 Trying\r\n"
31018 "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
31019 "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
31020 "To: <sip:bob@example.org:5060>\r\n"
31021 "Call-ID: 12345\r\n"
31022 "CSeq: 1 INVITE\r\n"
31023 "Contact: <sip:bob@example.org:5060>\r\n"
31024 "Content-Length: 0\r\n"
31025 "\r\n",
31026
31027 "SIP/2.0 180 Ringing\r\n"
31028 "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
31029 "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
31030 "To: <sip:bob@example.org:5060>\r\n"
31031 "Call-ID: 12345\r\n"
31032 "CSeq: 1 INVITE\r\n"
31033 "Contact: <sip:bob@example.org:5060>\r\n"
31034 "Content-Length: 0\r\n"
31035 "\r\n"
31036 };
31037
31038
31039
31040 char *multi_message_body[] = {
31041 "INVITE sip:bob@example.org SIP/2.0\r\n"
31042 "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
31043 "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
31044 "To: <sip:bob@example.org:5060>\r\n"
31045 "Call-ID: 12345\r\n"
31046 "CSeq: 1 INVITE\r\n"
31047 "Contact: sip:127.0.0.1:5061\r\n"
31048 "Max-Forwards: 70\r\n"
31049 "Content-Type: application/sdp\r\n"
31050 "Content-Length: 130\r\n"
31051 "\r\n"
31052 "v=0\r\n"
31053 "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
31054 "s=-\r\n"
31055 "c=IN IP4 127.0.0.1\r\n"
31056 "t=0 0\r\n"
31057 "m=audio 10000 RTP/AVP 0\r\n"
31058 "a=rtpmap:0 PCMU/8000\r\n"
31059 "INVITE sip:bob@example.org SIP/2.0\r\n"
31060 "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
31061 "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
31062 "To: <sip:bob@example.org:5060>\r\n"
31063 "Call-ID: 12345\r\n"
31064 "CSeq: 2 INVITE\r\n"
31065 "Contact: sip:127.0.0.1:5061\r\n"
31066 "Max-Forwards: 70\r\n"
31067 "Content-Type: application/sdp\r\n"
31068 "Content-Length: 130\r\n"
31069 "\r\n"
31070 "v=0\r\n"
31071 "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
31072 "s=-\r\n"
31073 "c=IN IP4 127.0.0.1\r\n"
31074 "t=0 0\r\n"
31075 "m=audio 10000 RTP/AVP 0\r\n"
31076 "a=rtpmap:0 PCMU/8000\r\n"
31077 };
31078 char *multi_message_body_divided[] = {
31079 "INVITE sip:bob@example.org SIP/2.0\r\n"
31080 "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
31081 "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
31082 "To: <sip:bob@example.org:5060>\r\n"
31083 "Call-ID: 12345\r\n"
31084 "CSeq: 1 INVITE\r\n"
31085 "Contact: sip:127.0.0.1:5061\r\n"
31086 "Max-Forwards: 70\r\n"
31087 "Content-Type: application/sdp\r\n"
31088 "Content-Length: 130\r\n"
31089 "\r\n"
31090 "v=0\r\n"
31091 "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
31092 "s=-\r\n"
31093 "c=IN IP4 127.0.0.1\r\n"
31094 "t=0 0\r\n"
31095 "m=audio 10000 RTP/AVP 0\r\n"
31096 "a=rtpmap:0 PCMU/8000\r\n",
31097
31098 "INVITE sip:bob@example.org SIP/2.0\r\n"
31099 "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
31100 "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
31101 "To: <sip:bob@example.org:5060>\r\n"
31102 "Call-ID: 12345\r\n"
31103 "CSeq: 2 INVITE\r\n"
31104 "Contact: sip:127.0.0.1:5061\r\n"
31105 "Max-Forwards: 70\r\n"
31106 "Content-Type: application/sdp\r\n"
31107 "Content-Length: 130\r\n"
31108 "\r\n"
31109 "v=0\r\n"
31110 "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
31111 "s=-\r\n"
31112 "c=IN IP4 127.0.0.1\r\n"
31113 "t=0 0\r\n"
31114 "m=audio 10000 RTP/AVP 0\r\n"
31115 "a=rtpmap:0 PCMU/8000\r\n"
31116 };
31117
31118
31119
31120
31121
31122 char *multi_message_in_fragments[] = {
31123 "SIP/2.0 100 Trying\r\n"
31124 "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
31125 "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
31126 "To: <sip:bob@example.org:5060>\r\n"
31127 "Call-ID: 12345\r\n"
31128 "CSeq: 1 INVI",
31129
31130 "TE\r\n"
31131 "Contact: <sip:bob@example.org:5060>\r\n"
31132 "Content-Length: 0\r\n"
31133 "\r\n"
31134 "SIP/2.0 180 Ringing\r\n"
31135 "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
31136 "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
31137 "To: <sip:bob@example.org:5060>\r\n"
31138 "Call-ID: 12345\r\n"
31139 "CSeq: 1 INVITE\r\n"
31140 "Contact: <sip:bob@example.org:5060>\r\n"
31141 "Content-Length: 0\r\n"
31142 "\r\n"
31143 };
31144
31145
31146
31147
31148 char *compact[] = {
31149 "INVITE sip:bob@example.org SIP/2.0\r\n"
31150 "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
31151 "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
31152 "To: <sip:bob@example.org:5060>\r\n"
31153 "Call-ID: 12345\r\n"
31154 "CSeq: 1 INVITE\r\n"
31155 "Contact: sip:127.0.0.1:5061\r\n"
31156 "Max-Forwards: 70\r\n"
31157 "Content-Type: application/sdp\r\n"
31158 "l:130\r\n"
31159 "\r\n"
31160 "v=0\r\n"
31161 "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
31162 "s=-\r\n"
31163 "c=IN IP4 127.0.0.1\r\n"
31164 "t=0 0\r\n"
31165 "m=audio 10000 RTP/AVP 0\r\n"
31166 "a=rtpmap:0 PCMU/8000\r\n"
31167 };
31168
31169
31170
31171
31172 char *faux[] = {
31173 "INVITE sip:bob@example.org SIP/2.0\r\n"
31174 "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
31175 "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
31176 "To: <sip:bob@example.org:5060>\r\n"
31177 "Call-ID: 12345\r\n"
31178 "CSeq: 1 INVITE\r\n"
31179 "Contact: sip:127.0.0.1:5061\r\n"
31180 "Max-Forwards: 70\r\n"
31181 "Content-Type: application/sdp\r\n"
31182 "DisContent-Length: 0\r\n"
31183 "MalContent-Length: 60\r\n"
31184 "Content-Length:130\r\n"
31185 "\r\n"
31186 "v=0\r\n"
31187 "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
31188 "s=-\r\n"
31189 "c=IN IP4 127.0.0.1\r\n"
31190 "t=0 0\r\n"
31191 "m=audio 10000 RTP/AVP 0\r\n"
31192 "a=rtpmap:0 PCMU/8000\r\n"
31193 };
31194
31195
31196
31197
31198
31199
31200 char *folded[] = {
31201 "INVITE sip:bob@example.org SIP/2.0\r\n"
31202 "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
31203 "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
31204 "To: <sip:bob@example.org:5060>\r\n"
31205 "Call-ID: 12345\r\n"
31206 "CSeq: 1 INVITE\r\n"
31207 "Contact: sip:127.0.0.1:5061\r\n"
31208 "Max-Forwards: 70\r\n"
31209 "Content-Type: application/sdp\r\n"
31210 "Content-Length: \t\r\n"
31211 "\t \r\n"
31212 " 130\t \r\n"
31213 "\r\n"
31214 "v=0\r\n"
31215 "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
31216 "s=-\r\n"
31217 "c=IN IP4 127.0.0.1\r\n"
31218 "t=0 0\r\n"
31219 "m=audio 10000 RTP/AVP 0\r\n"
31220 "a=rtpmap:0 PCMU/8000\r\n"
31221 };
31222
31223
31224
31225
31226
31227 char *cl_in_body[] = {
31228 "INVITE sip:bob@example.org SIP/2.0\r\n"
31229 "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
31230 "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
31231 "To: <sip:bob@example.org:5060>\r\n"
31232 "Call-ID: 12345\r\n"
31233 "CSeq: 1 INVITE\r\n"
31234 "Contact: sip:127.0.0.1:5061\r\n"
31235 "Max-Forwards: 70\r\n"
31236 "Content-Type: application/sdp\r\n"
31237 "l: 149\r\n"
31238 "\r\n"
31239 "v=0\r\n"
31240 "Content-Length: 0\r\n"
31241 "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
31242 "s=-\r\n"
31243 "c=IN IP4 127.0.0.1\r\n"
31244 "t=0 0\r\n"
31245 "m=audio 10000 RTP/AVP 0\r\n"
31246 "a=rtpmap:0 PCMU/8000\r\n"
31247 };
31248
31249 struct ast_str *overflow;
31250 struct {
31251 char **fragments;
31252 char **expected;
31253 int num_expected;
31254 const char *description;
31255 } tests[] = {
31256 { normal, normal, 1, "normal" },
31257 { fragmented, normal, 1, "fragmented" },
31258 { fragmented_body, normal, 1, "fragmented_body" },
31259 { multi_fragment, normal, 1, "multi_fragment" },
31260 { multi_message, multi_message_divided, 2, "multi_message" },
31261 { multi_message_body, multi_message_body_divided, 2, "multi_message_body" },
31262 { multi_message_in_fragments, multi_message_divided, 2, "multi_message_in_fragments" },
31263 { compact, compact, 1, "compact" },
31264 { faux, faux, 1, "faux" },
31265 { folded, folded, 1, "folded" },
31266 { cl_in_body, cl_in_body, 1, "cl_in_body" },
31267 };
31268 int i;
31269 enum ast_test_result_state res = AST_TEST_PASS;
31270
31271 switch (cmd) {
31272 case TEST_INIT:
31273 info->name = "sip_tcp_message_fragmentation";
31274 info->category = "/main/sip/transport/";
31275 info->summary = "SIP TCP message fragmentation test";
31276 info->description =
31277 "Tests reception of different TCP messages that have been fragmented or"
31278 "run together. This test mimicks the code that TCP reception uses.";
31279 return AST_TEST_NOT_RUN;
31280 case TEST_EXECUTE:
31281 break;
31282 }
31283 if (!sip_cfg.pedanticsipchecking) {
31284 ast_log(LOG_WARNING, "Not running test. Pedantic SIP checking is not enabled, so it is guaranteed to fail\n");
31285 return AST_TEST_NOT_RUN;
31286 }
31287
31288 overflow = ast_str_create(128);
31289 if (!overflow) {
31290 return AST_TEST_FAIL;
31291 }
31292 for (i = 0; i < ARRAY_LEN(tests); ++i) {
31293 int num_messages = 0;
31294 if (mock_tcp_loop(tests[i].fragments, ARRAY_LEN(tests[i].fragments),
31295 &overflow, tests[i].expected, &num_messages, test)) {
31296 ast_test_status_update(test, "Failed to parse message '%s'\n", tests[i].description);
31297 res = AST_TEST_FAIL;
31298 break;
31299 }
31300 if (num_messages != tests[i].num_expected) {
31301 ast_test_status_update(test, "Did not receive the expected number of messages. "
31302 "Expected %d but received %d\n", tests[i].num_expected, num_messages);
31303 res = AST_TEST_FAIL;
31304 break;
31305 }
31306 }
31307 ast_free(overflow);
31308 return res;
31309 }
31310
31311 #endif
31312
31313 #define DATA_EXPORT_SIP_PEER(MEMBER) \
31314 MEMBER(sip_peer, name, AST_DATA_STRING) \
31315 MEMBER(sip_peer, secret, AST_DATA_PASSWORD) \
31316 MEMBER(sip_peer, md5secret, AST_DATA_PASSWORD) \
31317 MEMBER(sip_peer, remotesecret, AST_DATA_PASSWORD) \
31318 MEMBER(sip_peer, context, AST_DATA_STRING) \
31319 MEMBER(sip_peer, subscribecontext, AST_DATA_STRING) \
31320 MEMBER(sip_peer, username, AST_DATA_STRING) \
31321 MEMBER(sip_peer, accountcode, AST_DATA_STRING) \
31322 MEMBER(sip_peer, tohost, AST_DATA_STRING) \
31323 MEMBER(sip_peer, regexten, AST_DATA_STRING) \
31324 MEMBER(sip_peer, fromuser, AST_DATA_STRING) \
31325 MEMBER(sip_peer, fromdomain, AST_DATA_STRING) \
31326 MEMBER(sip_peer, fullcontact, AST_DATA_STRING) \
31327 MEMBER(sip_peer, cid_num, AST_DATA_STRING) \
31328 MEMBER(sip_peer, cid_name, AST_DATA_STRING) \
31329 MEMBER(sip_peer, vmexten, AST_DATA_STRING) \
31330 MEMBER(sip_peer, language, AST_DATA_STRING) \
31331 MEMBER(sip_peer, mohinterpret, AST_DATA_STRING) \
31332 MEMBER(sip_peer, mohsuggest, AST_DATA_STRING) \
31333 MEMBER(sip_peer, parkinglot, AST_DATA_STRING) \
31334 MEMBER(sip_peer, useragent, AST_DATA_STRING) \
31335 MEMBER(sip_peer, mwi_from, AST_DATA_STRING) \
31336 MEMBER(sip_peer, engine, AST_DATA_STRING) \
31337 MEMBER(sip_peer, unsolicited_mailbox, AST_DATA_STRING) \
31338 MEMBER(sip_peer, is_realtime, AST_DATA_BOOLEAN) \
31339 MEMBER(sip_peer, host_dynamic, AST_DATA_BOOLEAN) \
31340 MEMBER(sip_peer, autoframing, AST_DATA_BOOLEAN) \
31341 MEMBER(sip_peer, inUse, AST_DATA_INTEGER) \
31342 MEMBER(sip_peer, inRinging, AST_DATA_INTEGER) \
31343 MEMBER(sip_peer, onHold, AST_DATA_INTEGER) \
31344 MEMBER(sip_peer, call_limit, AST_DATA_INTEGER) \
31345 MEMBER(sip_peer, t38_maxdatagram, AST_DATA_INTEGER) \
31346 MEMBER(sip_peer, maxcallbitrate, AST_DATA_INTEGER) \
31347 MEMBER(sip_peer, rtptimeout, AST_DATA_SECONDS) \
31348 MEMBER(sip_peer, rtpholdtimeout, AST_DATA_SECONDS) \
31349 MEMBER(sip_peer, rtpkeepalive, AST_DATA_SECONDS) \
31350 MEMBER(sip_peer, lastms, AST_DATA_MILLISECONDS) \
31351 MEMBER(sip_peer, maxms, AST_DATA_MILLISECONDS) \
31352 MEMBER(sip_peer, qualifyfreq, AST_DATA_MILLISECONDS) \
31353 MEMBER(sip_peer, timer_t1, AST_DATA_MILLISECONDS) \
31354 MEMBER(sip_peer, timer_b, AST_DATA_MILLISECONDS)
31355
31356 AST_DATA_STRUCTURE(sip_peer, DATA_EXPORT_SIP_PEER);
31357
31358 static int peers_data_provider_get(const struct ast_data_search *search,
31359 struct ast_data *data_root)
31360 {
31361 struct sip_peer *peer;
31362 struct ao2_iterator i;
31363 struct ast_data *data_peer, *data_peer_mailboxes = NULL, *data_peer_mailbox, *enum_node;
31364 struct ast_data *data_sip_options;
31365 int total_mailboxes, x;
31366 struct sip_mailbox *mailbox;
31367
31368 i = ao2_iterator_init(peers, 0);
31369 while ((peer = ao2_iterator_next(&i))) {
31370 ao2_lock(peer);
31371
31372 data_peer = ast_data_add_node(data_root, "peer");
31373 if (!data_peer) {
31374 ao2_unlock(peer);
31375 ao2_ref(peer, -1);
31376 continue;
31377 }
31378
31379 ast_data_add_structure(sip_peer, data_peer, peer);
31380
31381
31382 enum_node = ast_data_add_node(data_peer, "allowtransfer");
31383 if (!enum_node) {
31384 ao2_unlock(peer);
31385 ao2_ref(peer, -1);
31386 continue;
31387 }
31388 ast_data_add_str(enum_node, "text", transfermode2str(peer->allowtransfer));
31389 ast_data_add_int(enum_node, "value", peer->allowtransfer);
31390
31391
31392 ast_data_add_str(data_peer, "transports", get_transport_list(peer->transports));
31393
31394
31395 if ((peer->type & SIP_TYPE_USER) && (peer->type & SIP_TYPE_PEER)) {
31396 ast_data_add_str(data_peer, "type", "friend");
31397 } else if (peer->type & SIP_TYPE_PEER) {
31398 ast_data_add_str(data_peer, "type", "peer");
31399 } else if (peer->type & SIP_TYPE_USER) {
31400 ast_data_add_str(data_peer, "type", "user");
31401 }
31402
31403
31404 total_mailboxes = 0;
31405 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
31406 if (!total_mailboxes) {
31407 data_peer_mailboxes = ast_data_add_node(data_peer, "mailboxes");
31408 if (!data_peer_mailboxes) {
31409 break;
31410 }
31411 total_mailboxes++;
31412 }
31413
31414 data_peer_mailbox = ast_data_add_node(data_peer_mailboxes, "mailbox");
31415 if (!data_peer_mailbox) {
31416 continue;
31417 }
31418 ast_data_add_str(data_peer_mailbox, "mailbox", mailbox->mailbox);
31419 ast_data_add_str(data_peer_mailbox, "context", mailbox->context);
31420 }
31421
31422
31423 enum_node = ast_data_add_node(data_peer, "amaflags");
31424 if (!enum_node) {
31425 ao2_unlock(peer);
31426 ao2_ref(peer, -1);
31427 continue;
31428 }
31429 ast_data_add_int(enum_node, "value", peer->amaflags);
31430 ast_data_add_str(enum_node, "text", ast_cdr_flags2str(peer->amaflags));
31431
31432
31433 data_sip_options = ast_data_add_node(data_peer, "sipoptions");
31434 if (!data_sip_options) {
31435 ao2_unlock(peer);
31436 ao2_ref(peer, -1);
31437 continue;
31438 }
31439 for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
31440 ast_data_add_bool(data_sip_options, sip_options[x].text, peer->sipoptions & sip_options[x].id);
31441 }
31442
31443
31444 enum_node = ast_data_add_node(data_peer, "callingpres");
31445 if (!enum_node) {
31446 ao2_unlock(peer);
31447 ao2_ref(peer, -1);
31448 continue;
31449 }
31450 ast_data_add_int(enum_node, "value", peer->callingpres);
31451 ast_data_add_str(enum_node, "text", ast_describe_caller_presentation(peer->callingpres));
31452
31453
31454 ast_data_add_codecs(data_peer, "codecs", peer->capability);
31455
31456 if (!ast_data_search_match(search, data_peer)) {
31457 ast_data_remove_node(data_root, data_peer);
31458 }
31459
31460 ao2_unlock(peer);
31461 ao2_ref(peer, -1);
31462 }
31463 ao2_iterator_destroy(&i);
31464
31465 return 0;
31466 }
31467
31468 static const struct ast_data_handler peers_data_provider = {
31469 .version = AST_DATA_HANDLER_VERSION,
31470 .get = peers_data_provider_get
31471 };
31472
31473 static const struct ast_data_entry sip_data_providers[] = {
31474 AST_DATA_ENTRY("asterisk/channel/sip/peers", &peers_data_provider),
31475 };
31476
31477
31478 static int load_module(void)
31479 {
31480 ast_verbose("SIP channel loading...\n");
31481
31482
31483
31484 peers = ao2_t_container_alloc(HASH_PEER_SIZE, peer_hash_cb, peer_cmp_cb, "allocate peers");
31485 peers_by_ip = ao2_t_container_alloc(HASH_PEER_SIZE, peer_iphash_cb, peer_ipcmp_cb, "allocate peers_by_ip");
31486 dialogs = ao2_t_container_alloc(HASH_DIALOG_SIZE, dialog_hash_cb, dialog_cmp_cb, "allocate dialogs");
31487 dialogs_to_destroy = ao2_t_container_alloc(1, NULL, NULL, "allocate dialogs_to_destroy");
31488 threadt = ao2_t_container_alloc(HASH_DIALOG_SIZE, threadt_hash_cb, threadt_cmp_cb, "allocate threadt table");
31489 if (!peers || !peers_by_ip || !dialogs || !dialogs_to_destroy || !threadt) {
31490 ast_log(LOG_ERROR, "Unable to create primary SIP container(s)\n");
31491 return AST_MODULE_LOAD_FAILURE;
31492 }
31493
31494 ASTOBJ_CONTAINER_INIT(®l);
31495 ASTOBJ_CONTAINER_INIT(&submwil);
31496
31497 if (!(sched = sched_context_create())) {
31498 ast_log(LOG_ERROR, "Unable to create scheduler context\n");
31499 return AST_MODULE_LOAD_FAILURE;
31500 }
31501
31502 if (!(io = io_context_create())) {
31503 ast_log(LOG_ERROR, "Unable to create I/O context\n");
31504 sched_context_destroy(sched);
31505 return AST_MODULE_LOAD_FAILURE;
31506 }
31507
31508 sip_reloadreason = CHANNEL_MODULE_LOAD;
31509
31510 can_parse_xml = sip_is_xml_parsable();
31511 if (reload_config(sip_reloadreason)) {
31512 return AST_MODULE_LOAD_DECLINE;
31513 }
31514
31515
31516
31517
31518
31519 memcpy(&sip_tech_info, &sip_tech, sizeof(sip_tech));
31520 memset((void *) &sip_tech_info.send_digit_begin, 0, sizeof(sip_tech_info.send_digit_begin));
31521
31522
31523 if (ast_channel_register(&sip_tech)) {
31524 ast_log(LOG_ERROR, "Unable to register channel type 'SIP'\n");
31525 io_context_destroy(io);
31526 sched_context_destroy(sched);
31527 return AST_MODULE_LOAD_FAILURE;
31528 }
31529
31530 #ifdef TEST_FRAMEWORK
31531 AST_TEST_REGISTER(test_sip_peers_get);
31532 AST_TEST_REGISTER(test_sip_mwi_subscribe_parse);
31533 AST_TEST_REGISTER(test_tcp_message_fragmentation);
31534 #endif
31535
31536
31537 ast_data_register_multiple(sip_data_providers, ARRAY_LEN(sip_data_providers));
31538
31539
31540 ast_cli_register_multiple(cli_sip, ARRAY_LEN(cli_sip));
31541
31542
31543 ast_udptl_proto_register(&sip_udptl);
31544
31545
31546 ast_rtp_glue_register(&sip_rtp_glue);
31547
31548
31549 ast_register_application_xml(app_dtmfmode, sip_dtmfmode);
31550 ast_register_application_xml(app_sipaddheader, sip_addheader);
31551 ast_register_application_xml(app_sipremoveheader, sip_removeheader);
31552
31553
31554 ast_custom_function_register(&sip_header_function);
31555 ast_custom_function_register(&sippeer_function);
31556 ast_custom_function_register(&sipchaninfo_function);
31557 ast_custom_function_register(&checksipdomain_function);
31558
31559
31560 ast_manager_register_xml("SIPpeers", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peers);
31561 ast_manager_register_xml("SIPshowpeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peer);
31562 ast_manager_register_xml("SIPqualifypeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_qualify_peer);
31563 ast_manager_register_xml("SIPshowregistry", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_show_registry);
31564 ast_manager_register_xml("SIPnotify", EVENT_FLAG_SYSTEM, manager_sipnotify);
31565 sip_poke_all_peers();
31566 sip_send_all_registers();
31567 sip_send_all_mwi_subscriptions();
31568 initialize_escs();
31569
31570 if (sip_epa_register(&cc_epa_static_data)) {
31571 return AST_MODULE_LOAD_DECLINE;
31572 }
31573
31574 if (sip_reqresp_parser_init() == -1) {
31575 ast_log(LOG_ERROR, "Unable to initialize the SIP request and response parser\n");
31576 return AST_MODULE_LOAD_DECLINE;
31577 }
31578
31579 if (can_parse_xml) {
31580
31581
31582
31583 if (ast_cc_agent_register(&sip_cc_agent_callbacks)) {
31584 return AST_MODULE_LOAD_DECLINE;
31585 }
31586 }
31587 if (ast_cc_monitor_register(&sip_cc_monitor_callbacks)) {
31588 return AST_MODULE_LOAD_DECLINE;
31589 }
31590 if (!(sip_monitor_instances = ao2_container_alloc(37, sip_monitor_instance_hash_fn, sip_monitor_instance_cmp_fn))) {
31591 return AST_MODULE_LOAD_DECLINE;
31592 }
31593
31594
31595 restart_monitor();
31596
31597 ast_realtime_require_field(ast_check_realtime("sipregs") ? "sipregs" : "sippeers",
31598 "name", RQ_CHAR, 10,
31599 "ipaddr", RQ_CHAR, INET6_ADDRSTRLEN - 1,
31600 "port", RQ_UINTEGER2, 5,
31601 "regseconds", RQ_INTEGER4, 11,
31602 "defaultuser", RQ_CHAR, 10,
31603 "fullcontact", RQ_CHAR, 35,
31604 "regserver", RQ_CHAR, 20,
31605 "useragent", RQ_CHAR, 20,
31606 "lastms", RQ_INTEGER4, 11,
31607 SENTINEL);
31608
31609
31610 sip_register_tests();
31611 network_change_event_subscribe();
31612
31613 return AST_MODULE_LOAD_SUCCESS;
31614 }
31615
31616
31617 static int unload_module(void)
31618 {
31619 struct sip_pvt *p;
31620 struct sip_threadinfo *th;
31621 struct ast_context *con;
31622 struct ao2_iterator i;
31623 int wait_count;
31624
31625 network_change_event_unsubscribe();
31626
31627 ast_sched_dump(sched);
31628
31629
31630 ast_channel_unregister(&sip_tech);
31631
31632
31633 ast_custom_function_unregister(&sipchaninfo_function);
31634 ast_custom_function_unregister(&sippeer_function);
31635 ast_custom_function_unregister(&sip_header_function);
31636 ast_custom_function_unregister(&checksipdomain_function);
31637
31638
31639 ast_unregister_application(app_dtmfmode);
31640 ast_unregister_application(app_sipaddheader);
31641 ast_unregister_application(app_sipremoveheader);
31642
31643 #ifdef TEST_FRAMEWORK
31644 AST_TEST_UNREGISTER(test_sip_peers_get);
31645 AST_TEST_UNREGISTER(test_sip_mwi_subscribe_parse);
31646 AST_TEST_UNREGISTER(test_tcp_message_fragmentation);
31647 #endif
31648
31649 ast_data_unregister(NULL);
31650
31651
31652 ast_cli_unregister_multiple(cli_sip, ARRAY_LEN(cli_sip));
31653
31654
31655 ast_udptl_proto_unregister(&sip_udptl);
31656
31657
31658 ast_rtp_glue_unregister(&sip_rtp_glue);
31659
31660
31661 ast_manager_unregister("SIPpeers");
31662 ast_manager_unregister("SIPshowpeer");
31663 ast_manager_unregister("SIPqualifypeer");
31664 ast_manager_unregister("SIPshowregistry");
31665 ast_manager_unregister("SIPnotify");
31666
31667
31668 if (sip_tcp_desc.master) {
31669 ast_tcptls_server_stop(&sip_tcp_desc);
31670 }
31671 if (sip_tls_desc.master) {
31672 ast_tcptls_server_stop(&sip_tls_desc);
31673 }
31674 ast_ssl_teardown(sip_tls_desc.tls_cfg);
31675
31676
31677 i = ao2_iterator_init(threadt, 0);
31678 while ((th = ao2_t_iterator_next(&i, "iterate through tcp threads for 'sip show tcp'"))) {
31679 pthread_t thread = th->threadid;
31680 th->stop = 1;
31681 pthread_kill(thread, SIGURG);
31682 ao2_t_ref(th, -1, "decrement ref from iterator");
31683 }
31684 ao2_iterator_destroy(&i);
31685
31686
31687 i = ao2_iterator_init(dialogs, 0);
31688 while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
31689 if (p->owner)
31690 ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
31691 ao2_t_ref(p, -1, "toss dialog ptr from iterator_next");
31692 }
31693 ao2_iterator_destroy(&i);
31694
31695 unlink_all_peers_from_tables();
31696
31697 ast_mutex_lock(&monlock);
31698 if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP) && (monitor_thread != AST_PTHREADT_NULL)) {
31699 pthread_cancel(monitor_thread);
31700 pthread_kill(monitor_thread, SIGURG);
31701 pthread_join(monitor_thread, NULL);
31702 }
31703 monitor_thread = AST_PTHREADT_STOP;
31704 ast_mutex_unlock(&monlock);
31705
31706
31707 i = ao2_iterator_init(dialogs, 0);
31708 while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
31709 dialog_unlink_all(p);
31710 ao2_t_ref(p, -1, "throw away iterator result");
31711 }
31712 ao2_iterator_destroy(&i);
31713
31714
31715 ast_free_ha(localaddr);
31716
31717 ast_mutex_lock(&authl_lock);
31718 if (authl) {
31719 ao2_t_ref(authl, -1, "Removing global authentication");
31720 authl = NULL;
31721 }
31722 ast_mutex_unlock(&authl_lock);
31723
31724 sip_epa_unregister_all();
31725 destroy_escs();
31726
31727 ast_free(default_tls_cfg.certfile);
31728 ast_free(default_tls_cfg.pvtfile);
31729 ast_free(default_tls_cfg.cipher);
31730 ast_free(default_tls_cfg.cafile);
31731 ast_free(default_tls_cfg.capath);
31732
31733 cleanup_all_regs();
31734 ASTOBJ_CONTAINER_DESTROYALL(®l, sip_registry_destroy);
31735 ASTOBJ_CONTAINER_DESTROY(®l);
31736
31737 ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
31738 ASTOBJ_WRLOCK(iterator);
31739 if (iterator->dnsmgr) {
31740 ast_dnsmgr_release(iterator->dnsmgr);
31741 iterator->dnsmgr = NULL;
31742 ASTOBJ_UNREF(iterator, sip_subscribe_mwi_destroy);
31743 }
31744 ASTOBJ_UNLOCK(iterator);
31745 } while(0));
31746 ASTOBJ_CONTAINER_DESTROYALL(&submwil, sip_subscribe_mwi_destroy);
31747 ASTOBJ_CONTAINER_DESTROY(&submwil);
31748
31749
31750
31751
31752
31753
31754
31755
31756 wait_count = 1000;
31757 while (ao2_container_count(threadt) && --wait_count) {
31758 sched_yield();
31759 }
31760 if (!wait_count) {
31761 ast_debug(2, "TCP/TLS thread container did not become empty :(\n");
31762 }
31763
31764 ao2_t_ref(peers, -1, "unref the peers table");
31765 ao2_t_ref(peers_by_ip, -1, "unref the peers_by_ip table");
31766 ao2_t_ref(dialogs, -1, "unref the dialogs table");
31767 ao2_t_ref(dialogs_to_destroy, -1, "unref dialogs_to_destroy");
31768 ao2_t_ref(threadt, -1, "unref the thread table");
31769 ao2_t_ref(sip_monitor_instances, -1, "unref the sip_monitor_instances table");
31770
31771 clear_sip_domains();
31772 ast_free_ha(sip_cfg.contact_ha);
31773 close(sipsock);
31774 sched_context_destroy(sched);
31775 con = ast_context_find(used_context);
31776 if (con) {
31777 ast_context_destroy(con, "SIP");
31778 }
31779 ast_unload_realtime("sipregs");
31780 ast_unload_realtime("sippeers");
31781 ast_cc_monitor_unregister(&sip_cc_monitor_callbacks);
31782 ast_cc_agent_unregister(&sip_cc_agent_callbacks);
31783
31784 sip_reqresp_parser_exit();
31785 sip_unregister_tests();
31786
31787 return 0;
31788 }
31789
31790 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Session Initiation Protocol (SIP)",
31791 .load = load_module,
31792 .unload = unload_module,
31793 .reload = reload,
31794 .load_pri = AST_MODPRI_CHANNEL_DRIVER,
31795 .nonoptreq = "res_crypto,chan_local",
31796 );