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: 367963 $")
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 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(const struct ast_sockaddr *addr);
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
01419
01420
01421
01422
01423 static void sip_dump_history(struct sip_pvt *dialog);
01424 static inline int sip_debug_test_addr(const struct ast_sockaddr *addr);
01425 static inline int sip_debug_test_pvt(struct sip_pvt *p);
01426 static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
01427 static void sip_dump_history(struct sip_pvt *dialog);
01428
01429
01430 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only);
01431 static int update_call_counter(struct sip_pvt *fup, int event);
01432 static void sip_destroy_peer(struct sip_peer *peer);
01433 static void sip_destroy_peer_fn(void *peer);
01434 static void set_peer_defaults(struct sip_peer *peer);
01435 static struct sip_peer *temp_peer(const char *name);
01436 static void register_peer_exten(struct sip_peer *peer, int onoff);
01437 static struct sip_peer *find_peer(const char *peer, struct ast_sockaddr *addr, int realtime, int forcenamematch, int devstate_only, int transport);
01438 static int sip_poke_peer_s(const void *data);
01439 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
01440 static void reg_source_db(struct sip_peer *peer);
01441 static void destroy_association(struct sip_peer *peer);
01442 static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
01443 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
01444 static void set_socket_transport(struct sip_socket *socket, int transport);
01445
01446
01447 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);
01448 static void update_peer(struct sip_peer *p, int expire);
01449 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config);
01450 static const char *get_name_from_variable(const struct ast_variable *var);
01451 static struct sip_peer *realtime_peer(const char *peername, struct ast_sockaddr *sin, int devstate_only, int which_objects);
01452 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01453
01454
01455 static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p);
01456 static void sip_registry_destroy(struct sip_registry *reg);
01457 static int sip_register(const char *value, int lineno);
01458 static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
01459 static int sip_reregister(const void *data);
01460 static int __sip_do_register(struct sip_registry *r);
01461 static int sip_reg_timeout(const void *data);
01462 static void sip_send_all_registers(void);
01463 static int sip_reinvite_retry(const void *data);
01464
01465
01466 static void append_date(struct sip_request *req);
01467 static int determine_firstline_parts(struct sip_request *req);
01468 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
01469 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
01470 static int find_sip_method(const char *msg);
01471 static unsigned int parse_allowed_methods(struct sip_request *req);
01472 static unsigned int set_pvt_allowed_methods(struct sip_pvt *pvt, struct sip_request *req);
01473 static int parse_request(struct sip_request *req);
01474 static const char *get_header(const struct sip_request *req, const char *name);
01475 static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
01476 static int method_match(enum sipmethod id, const char *name);
01477 static void parse_copy(struct sip_request *dst, const struct sip_request *src);
01478 static const char *find_alias(const char *name, const char *_default);
01479 static const char *__get_header(const struct sip_request *req, const char *name, int *start);
01480 static void lws2sws(struct ast_str *msgbuf);
01481 static void extract_uri(struct sip_pvt *p, struct sip_request *req);
01482 static char *remove_uri_parameters(char *uri);
01483 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
01484 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
01485 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
01486 static int set_address_from_contact(struct sip_pvt *pvt);
01487 static void check_via(struct sip_pvt *p, struct sip_request *req);
01488 static int get_rpid(struct sip_pvt *p, struct sip_request *oreq);
01489 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq, char **name, char **number, int *reason);
01490 static enum sip_get_dest_result get_destination(struct sip_pvt *p, struct sip_request *oreq, int *cc_recall_core_id);
01491 static int get_msg_text(char *buf, int len, struct sip_request *req);
01492 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout);
01493 static void update_connectedline(struct sip_pvt *p, const void *data, size_t datalen);
01494 static void update_redirecting(struct sip_pvt *p, const void *data, size_t datalen);
01495 static int get_domain(const char *str, char *domain, int len);
01496 static void get_realm(struct sip_pvt *p, const struct sip_request *req);
01497
01498
01499 static void *_sip_tcp_helper_thread(struct ast_tcptls_session_instance *tcptls_session);
01500 static void *sip_tcp_worker_fn(void *);
01501
01502
01503 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
01504 static int init_req(struct sip_request *req, int sipmethod, const char *recip);
01505 static void deinit_req(struct sip_request *req);
01506 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, uint32_t seqno, int newbranch);
01507 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, const char * const explicit_uri);
01508 static int init_resp(struct sip_request *resp, const char *msg);
01509 static inline int resp_needs_contact(const char *msg, enum sipmethod method);
01510 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
01511 static const struct ast_sockaddr *sip_real_dst(const struct sip_pvt *p);
01512 static void build_via(struct sip_pvt *p);
01513 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
01514 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct ast_sockaddr *addr, int newdialog, struct ast_sockaddr *remote_address);
01515 static char *generate_random_string(char *buf, size_t size);
01516 static void build_callid_pvt(struct sip_pvt *pvt);
01517 static void change_callid_pvt(struct sip_pvt *pvt, const char *callid);
01518 static void build_callid_registry(struct sip_registry *reg, const struct ast_sockaddr *ourip, const char *fromdomain);
01519 static void make_our_tag(char *tagbuf, size_t len);
01520 static int add_header(struct sip_request *req, const char *var, const char *value);
01521 static int add_header_max_forwards(struct sip_pvt *dialog, struct sip_request *req);
01522 static int add_content(struct sip_request *req, const char *line);
01523 static int finalize_content(struct sip_request *req);
01524 static int add_text(struct sip_request *req, const char *text);
01525 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode);
01526 static int add_rpid(struct sip_request *req, struct sip_pvt *p);
01527 static int add_vidupdate(struct sip_request *req);
01528 static void add_route(struct sip_request *req, struct sip_route *route);
01529 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
01530 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
01531 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
01532 static void set_destination(struct sip_pvt *p, char *uri);
01533 static void append_date(struct sip_request *req);
01534 static void build_contact(struct sip_pvt *p);
01535
01536
01537 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int *recount, int *nounlock);
01538 static int handle_request_update(struct sip_pvt *p, struct sip_request *req);
01539 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);
01540 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, uint32_t seqno, int *nounlock);
01541 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
01542 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *sin, const char *e);
01543 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
01544 static int handle_request_message(struct sip_pvt *p, struct sip_request *req);
01545 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e);
01546 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
01547 static int handle_request_options(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
01548 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, uint32_t seqno, struct ast_sockaddr *addr, int *nounlock);
01549 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e);
01550 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, uint32_t seqno, int *nounlock);
01551
01552
01553 static void handle_response_publish(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01554 static void handle_response_invite(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01555 static void handle_response_notify(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01556 static void handle_response_refer(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01557 static void handle_response_subscribe(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01558 static int handle_response_register(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01559 static void handle_response(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01560
01561
01562 static int setup_srtp(struct sip_srtp **srtp);
01563 static int process_crypto(struct sip_pvt *p, struct ast_rtp_instance *rtp, struct sip_srtp **srtp, const char *a);
01564
01565
01566 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
01567 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
01568 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
01569 static void change_t38_state(struct sip_pvt *p, int state);
01570
01571
01572 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp);
01573 static int proc_session_timer(const void *vp);
01574 static void stop_session_timer(struct sip_pvt *p);
01575 static void start_session_timer(struct sip_pvt *p);
01576 static void restart_session_timer(struct sip_pvt *p);
01577 static const char *strefresher2str(enum st_refresher r);
01578 static int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref);
01579 static int parse_minse(const char *p_hdrval, int *const p_interval);
01580 static int st_get_se(struct sip_pvt *, int max);
01581 static enum st_refresher st_get_refresher(struct sip_pvt *);
01582 static enum st_mode st_get_mode(struct sip_pvt *, int no_cached);
01583 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p);
01584
01585
01586 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);
01587
01588
01589 static int sip_subscribe_mwi(const char *value, int lineno);
01590 static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi);
01591 static void sip_send_all_mwi_subscriptions(void);
01592 static int sip_subscribe_mwi_do(const void *data);
01593 static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi);
01594
01595
01596 const struct ast_channel_tech sip_tech = {
01597 .type = "SIP",
01598 .description = "Session Initiation Protocol (SIP)",
01599 .capabilities = AST_FORMAT_AUDIO_MASK,
01600 .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
01601 .requester = sip_request_call,
01602 .devicestate = sip_devicestate,
01603 .call = sip_call,
01604 .send_html = sip_sendhtml,
01605 .hangup = sip_hangup,
01606 .answer = sip_answer,
01607 .read = sip_read,
01608 .write = sip_write,
01609 .write_video = sip_write,
01610 .write_text = sip_write,
01611 .indicate = sip_indicate,
01612 .transfer = sip_transfer,
01613 .fixup = sip_fixup,
01614 .send_digit_begin = sip_senddigit_begin,
01615 .send_digit_end = sip_senddigit_end,
01616 .bridge = ast_rtp_instance_bridge,
01617 .early_bridge = ast_rtp_instance_early_bridge,
01618 .send_text = sip_sendtext,
01619 .func_channel_read = sip_acf_channel_read,
01620 .setoption = sip_setoption,
01621 .queryoption = sip_queryoption,
01622 .get_pvt_uniqueid = sip_get_callid,
01623 };
01624
01625
01626
01627
01628
01629
01630
01631 struct ast_channel_tech sip_tech_info;
01632
01633 static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan);
01634 static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent);
01635 static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent);
01636 static void sip_cc_agent_respond(struct ast_cc_agent *agent, enum ast_cc_agent_response_reason reason);
01637 static int sip_cc_agent_status_request(struct ast_cc_agent *agent);
01638 static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent);
01639 static int sip_cc_agent_recall(struct ast_cc_agent *agent);
01640 static void sip_cc_agent_destructor(struct ast_cc_agent *agent);
01641
01642 static struct ast_cc_agent_callbacks sip_cc_agent_callbacks = {
01643 .type = "SIP",
01644 .init = sip_cc_agent_init,
01645 .start_offer_timer = sip_cc_agent_start_offer_timer,
01646 .stop_offer_timer = sip_cc_agent_stop_offer_timer,
01647 .respond = sip_cc_agent_respond,
01648 .status_request = sip_cc_agent_status_request,
01649 .start_monitoring = sip_cc_agent_start_monitoring,
01650 .callee_available = sip_cc_agent_recall,
01651 .destructor = sip_cc_agent_destructor,
01652 };
01653
01654 static int find_by_notify_uri_helper(void *obj, void *arg, int flags)
01655 {
01656 struct ast_cc_agent *agent = obj;
01657 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01658 const char *uri = arg;
01659
01660 return !sip_uri_cmp(agent_pvt->notify_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
01661 }
01662
01663 static struct ast_cc_agent *find_sip_cc_agent_by_notify_uri(const char * const uri)
01664 {
01665 struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_notify_uri_helper, (char *)uri, "SIP");
01666 return agent;
01667 }
01668
01669 static int find_by_subscribe_uri_helper(void *obj, void *arg, int flags)
01670 {
01671 struct ast_cc_agent *agent = obj;
01672 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01673 const char *uri = arg;
01674
01675 return !sip_uri_cmp(agent_pvt->subscribe_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
01676 }
01677
01678 static struct ast_cc_agent *find_sip_cc_agent_by_subscribe_uri(const char * const uri)
01679 {
01680 struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_subscribe_uri_helper, (char *)uri, "SIP");
01681 return agent;
01682 }
01683
01684 static int find_by_callid_helper(void *obj, void *arg, int flags)
01685 {
01686 struct ast_cc_agent *agent = obj;
01687 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01688 struct sip_pvt *call_pvt = arg;
01689
01690 return !strcmp(agent_pvt->original_callid, call_pvt->callid) ? CMP_MATCH | CMP_STOP : 0;
01691 }
01692
01693 static struct ast_cc_agent *find_sip_cc_agent_by_original_callid(struct sip_pvt *pvt)
01694 {
01695 struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_callid_helper, pvt, "SIP");
01696 return agent;
01697 }
01698
01699 static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan)
01700 {
01701 struct sip_cc_agent_pvt *agent_pvt = ast_calloc(1, sizeof(*agent_pvt));
01702 struct sip_pvt *call_pvt = chan->tech_pvt;
01703
01704 if (!agent_pvt) {
01705 return -1;
01706 }
01707
01708 ast_assert(!strcmp(chan->tech->type, "SIP"));
01709
01710 ast_copy_string(agent_pvt->original_callid, call_pvt->callid, sizeof(agent_pvt->original_callid));
01711 ast_copy_string(agent_pvt->original_exten, call_pvt->exten, sizeof(agent_pvt->original_exten));
01712 agent_pvt->offer_timer_id = -1;
01713 agent->private_data = agent_pvt;
01714 sip_pvt_lock(call_pvt);
01715 ast_set_flag(&call_pvt->flags[0], SIP_OFFER_CC);
01716 sip_pvt_unlock(call_pvt);
01717 return 0;
01718 }
01719
01720 static int sip_offer_timer_expire(const void *data)
01721 {
01722 struct ast_cc_agent *agent = (struct ast_cc_agent *) data;
01723 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01724
01725 agent_pvt->offer_timer_id = -1;
01726
01727 return ast_cc_failed(agent->core_id, "SIP agent %s's offer timer expired", agent->device_name);
01728 }
01729
01730 static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent)
01731 {
01732 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01733 int when;
01734
01735 when = ast_get_cc_offer_timer(agent->cc_params) * 1000;
01736 agent_pvt->offer_timer_id = ast_sched_add(sched, when, sip_offer_timer_expire, agent);
01737 return 0;
01738 }
01739
01740 static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent)
01741 {
01742 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01743
01744 AST_SCHED_DEL(sched, agent_pvt->offer_timer_id);
01745 return 0;
01746 }
01747
01748 static void sip_cc_agent_respond(struct ast_cc_agent *agent, enum ast_cc_agent_response_reason reason)
01749 {
01750 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01751
01752 sip_pvt_lock(agent_pvt->subscribe_pvt);
01753 ast_set_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
01754 if (reason == AST_CC_AGENT_RESPONSE_SUCCESS || !ast_strlen_zero(agent_pvt->notify_uri)) {
01755
01756
01757
01758
01759
01760
01761
01762
01763
01764
01765
01766
01767 transmit_response(agent_pvt->subscribe_pvt, "200 OK", &agent_pvt->subscribe_pvt->initreq);
01768 transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_QUEUED);
01769 } else {
01770 transmit_response(agent_pvt->subscribe_pvt, "500 Internal Error", &agent_pvt->subscribe_pvt->initreq);
01771 }
01772 sip_pvt_unlock(agent_pvt->subscribe_pvt);
01773 agent_pvt->is_available = TRUE;
01774 }
01775
01776 static int sip_cc_agent_status_request(struct ast_cc_agent *agent)
01777 {
01778 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01779 enum ast_device_state state = agent_pvt->is_available ? AST_DEVICE_NOT_INUSE : AST_DEVICE_INUSE;
01780 return ast_cc_agent_status_response(agent->core_id, state);
01781 }
01782
01783 static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent)
01784 {
01785
01786
01787
01788
01789 return 0;
01790 }
01791
01792 static int sip_cc_agent_recall(struct ast_cc_agent *agent)
01793 {
01794 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01795
01796
01797
01798
01799 if (!agent_pvt->is_available) {
01800 return ast_cc_agent_caller_busy(agent->core_id, "Caller %s is busy, reporting to the core",
01801 agent->device_name);
01802 }
01803
01804
01805
01806 sip_pvt_lock(agent_pvt->subscribe_pvt);
01807 transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_READY);
01808 sip_pvt_unlock(agent_pvt->subscribe_pvt);
01809 return 0;
01810 }
01811
01812 static void sip_cc_agent_destructor(struct ast_cc_agent *agent)
01813 {
01814 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01815
01816 if (!agent_pvt) {
01817
01818 return;
01819 }
01820
01821 sip_cc_agent_stop_offer_timer(agent);
01822 if (agent_pvt->subscribe_pvt) {
01823 sip_pvt_lock(agent_pvt->subscribe_pvt);
01824 if (!ast_test_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
01825
01826
01827
01828 transmit_response(agent_pvt->subscribe_pvt, "500 Internal Server Error", &agent_pvt->subscribe_pvt->initreq);
01829 }
01830 sip_pvt_unlock(agent_pvt->subscribe_pvt);
01831 agent_pvt->subscribe_pvt = dialog_unref(agent_pvt->subscribe_pvt, "SIP CC agent destructor: Remove ref to subscription");
01832 }
01833 ast_free(agent_pvt);
01834 }
01835
01836 struct ao2_container *sip_monitor_instances;
01837
01838 static int sip_monitor_instance_hash_fn(const void *obj, const int flags)
01839 {
01840 const struct sip_monitor_instance *monitor_instance = obj;
01841 return monitor_instance->core_id;
01842 }
01843
01844 static int sip_monitor_instance_cmp_fn(void *obj, void *arg, int flags)
01845 {
01846 struct sip_monitor_instance *monitor_instance1 = obj;
01847 struct sip_monitor_instance *monitor_instance2 = arg;
01848
01849 return monitor_instance1->core_id == monitor_instance2->core_id ? CMP_MATCH | CMP_STOP : 0;
01850 }
01851
01852 static void sip_monitor_instance_destructor(void *data)
01853 {
01854 struct sip_monitor_instance *monitor_instance = data;
01855 if (monitor_instance->subscription_pvt) {
01856 sip_pvt_lock(monitor_instance->subscription_pvt);
01857 monitor_instance->subscription_pvt->expiry = 0;
01858 transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 0, monitor_instance->subscribe_uri);
01859 sip_pvt_unlock(monitor_instance->subscription_pvt);
01860 dialog_unref(monitor_instance->subscription_pvt, "Unref monitor instance ref of subscription pvt");
01861 }
01862 if (monitor_instance->suspension_entry) {
01863 monitor_instance->suspension_entry->body[0] = '\0';
01864 transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_REMOVE ,monitor_instance->notify_uri);
01865 ao2_t_ref(monitor_instance->suspension_entry, -1, "Decrementing suspension entry refcount in sip_monitor_instance_destructor");
01866 }
01867 ast_string_field_free_memory(monitor_instance);
01868 }
01869
01870 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)
01871 {
01872 struct sip_monitor_instance *monitor_instance = ao2_alloc(sizeof(*monitor_instance), sip_monitor_instance_destructor);
01873
01874 if (!monitor_instance) {
01875 return NULL;
01876 }
01877
01878 if (ast_string_field_init(monitor_instance, 256)) {
01879 ao2_ref(monitor_instance, -1);
01880 return NULL;
01881 }
01882
01883 ast_string_field_set(monitor_instance, subscribe_uri, subscribe_uri);
01884 ast_string_field_set(monitor_instance, peername, peername);
01885 ast_string_field_set(monitor_instance, device_name, device_name);
01886 monitor_instance->core_id = core_id;
01887 ao2_link(sip_monitor_instances, monitor_instance);
01888 return monitor_instance;
01889 }
01890
01891 static int find_sip_monitor_instance_by_subscription_pvt(void *obj, void *arg, int flags)
01892 {
01893 struct sip_monitor_instance *monitor_instance = obj;
01894 return monitor_instance->subscription_pvt == arg ? CMP_MATCH | CMP_STOP : 0;
01895 }
01896
01897 static int find_sip_monitor_instance_by_suspension_entry(void *obj, void *arg, int flags)
01898 {
01899 struct sip_monitor_instance *monitor_instance = obj;
01900 return monitor_instance->suspension_entry == arg ? CMP_MATCH | CMP_STOP : 0;
01901 }
01902
01903 static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id);
01904 static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor);
01905 static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor);
01906 static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id);
01907 static void sip_cc_monitor_destructor(void *private_data);
01908
01909 static struct ast_cc_monitor_callbacks sip_cc_monitor_callbacks = {
01910 .type = "SIP",
01911 .request_cc = sip_cc_monitor_request_cc,
01912 .suspend = sip_cc_monitor_suspend,
01913 .unsuspend = sip_cc_monitor_unsuspend,
01914 .cancel_available_timer = sip_cc_monitor_cancel_available_timer,
01915 .destructor = sip_cc_monitor_destructor,
01916 };
01917
01918 static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id)
01919 {
01920 struct sip_monitor_instance *monitor_instance = monitor->private_data;
01921 enum ast_cc_service_type service = monitor->service_offered;
01922 int when;
01923
01924 if (!monitor_instance) {
01925 return -1;
01926 }
01927
01928 if (!(monitor_instance->subscription_pvt = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL))) {
01929 return -1;
01930 }
01931
01932 when = service == AST_CC_CCBS ? ast_get_ccbs_available_timer(monitor->interface->config_params) :
01933 ast_get_ccnr_available_timer(monitor->interface->config_params);
01934
01935 sip_pvt_lock(monitor_instance->subscription_pvt);
01936 ast_set_flag(&monitor_instance->subscription_pvt->flags[0], SIP_OUTGOING);
01937 create_addr(monitor_instance->subscription_pvt, monitor_instance->peername, 0, 1, NULL);
01938 ast_sip_ouraddrfor(&monitor_instance->subscription_pvt->sa, &monitor_instance->subscription_pvt->ourip, monitor_instance->subscription_pvt);
01939 monitor_instance->subscription_pvt->subscribed = CALL_COMPLETION;
01940 monitor_instance->subscription_pvt->expiry = when;
01941
01942 transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 2, monitor_instance->subscribe_uri);
01943 sip_pvt_unlock(monitor_instance->subscription_pvt);
01944
01945 ao2_t_ref(monitor, +1, "Adding a ref to the monitor for the scheduler");
01946 *available_timer_id = ast_sched_add(sched, when * 1000, ast_cc_available_timer_expire, monitor);
01947 return 0;
01948 }
01949
01950 static int construct_pidf_body(enum sip_cc_publish_state state, char *pidf_body, size_t size, const char *presentity)
01951 {
01952 struct ast_str *body = ast_str_alloca(size);
01953 char tuple_id[32];
01954
01955 generate_random_string(tuple_id, sizeof(tuple_id));
01956
01957
01958
01959
01960 ast_str_append(&body, 0, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
01961
01962
01963
01964
01965
01966
01967 ast_str_append(&body, 0, "<presence xmlns=\"urn:ietf:params:xml:ns:pidf\" entity=\"%s\">\n", presentity);
01968 ast_str_append(&body, 0, "<tuple id=\"%s\">\n", tuple_id);
01969 ast_str_append(&body, 0, "<status><basic>%s</basic></status>\n", state == CC_OPEN ? "open" : "closed");
01970 ast_str_append(&body, 0, "</tuple>\n");
01971 ast_str_append(&body, 0, "</presence>\n");
01972 ast_copy_string(pidf_body, ast_str_buffer(body), size);
01973 return 0;
01974 }
01975
01976 static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor)
01977 {
01978 struct sip_monitor_instance *monitor_instance = monitor->private_data;
01979 enum sip_publish_type publish_type;
01980 struct cc_epa_entry *cc_entry;
01981
01982 if (!monitor_instance) {
01983 return -1;
01984 }
01985
01986 if (!monitor_instance->suspension_entry) {
01987
01988 if (!(monitor_instance->suspension_entry = create_epa_entry("call-completion", monitor_instance->peername))) {
01989 ast_log(LOG_WARNING, "Unable to allocate sip EPA entry for call-completion\n");
01990 ao2_ref(monitor_instance, -1);
01991 return -1;
01992 }
01993 if (!(cc_entry = ast_calloc(1, sizeof(*cc_entry)))) {
01994 ast_log(LOG_WARNING, "Unable to allocate space for instance data of EPA entry for call-completion\n");
01995 ao2_ref(monitor_instance, -1);
01996 return -1;
01997 }
01998 cc_entry->core_id = monitor->core_id;
01999 monitor_instance->suspension_entry->instance_data = cc_entry;
02000 publish_type = SIP_PUBLISH_INITIAL;
02001 } else {
02002 publish_type = SIP_PUBLISH_MODIFY;
02003 cc_entry = monitor_instance->suspension_entry->instance_data;
02004 }
02005
02006 cc_entry->current_state = CC_CLOSED;
02007
02008 if (ast_strlen_zero(monitor_instance->notify_uri)) {
02009
02010
02011
02012
02013
02014
02015
02016
02017
02018
02019
02020
02021 return 0;
02022 }
02023 construct_pidf_body(CC_CLOSED, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
02024 return transmit_publish(monitor_instance->suspension_entry, publish_type, monitor_instance->notify_uri);
02025 }
02026
02027 static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor)
02028 {
02029 struct sip_monitor_instance *monitor_instance = monitor->private_data;
02030 struct cc_epa_entry *cc_entry;
02031
02032 if (!monitor_instance) {
02033 return -1;
02034 }
02035
02036 ast_assert(monitor_instance->suspension_entry != NULL);
02037
02038 cc_entry = monitor_instance->suspension_entry->instance_data;
02039 cc_entry->current_state = CC_OPEN;
02040 if (ast_strlen_zero(monitor_instance->notify_uri)) {
02041
02042
02043
02044
02045 return 0;
02046 }
02047 construct_pidf_body(CC_OPEN, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
02048 return transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_MODIFY, monitor_instance->notify_uri);
02049 }
02050
02051 static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id)
02052 {
02053 if (*sched_id != -1) {
02054 AST_SCHED_DEL(sched, *sched_id);
02055 ao2_t_ref(monitor, -1, "Removing scheduler's reference to the monitor");
02056 }
02057 return 0;
02058 }
02059
02060 static void sip_cc_monitor_destructor(void *private_data)
02061 {
02062 struct sip_monitor_instance *monitor_instance = private_data;
02063 ao2_unlink(sip_monitor_instances, monitor_instance);
02064 ast_module_unref(ast_module_info->self);
02065 }
02066
02067 static int sip_get_cc_information(struct sip_request *req, char *subscribe_uri, size_t size, enum ast_cc_service_type *service)
02068 {
02069 char *call_info = ast_strdupa(get_header(req, "Call-Info"));
02070 char *uri;
02071 char *purpose;
02072 char *service_str;
02073 static const char cc_purpose[] = "purpose=call-completion";
02074 static const int cc_purpose_len = sizeof(cc_purpose) - 1;
02075
02076 if (ast_strlen_zero(call_info)) {
02077
02078 return -1;
02079 }
02080
02081 uri = strsep(&call_info, ";");
02082
02083 while ((purpose = strsep(&call_info, ";"))) {
02084 if (!strncmp(purpose, cc_purpose, cc_purpose_len)) {
02085 break;
02086 }
02087 }
02088 if (!purpose) {
02089
02090 return -1;
02091 }
02092
02093
02094 while ((service_str = strsep(&call_info, ";"))) {
02095 if (!strncmp(service_str, "m=", 2)) {
02096 break;
02097 }
02098 }
02099 if (!service_str) {
02100
02101
02102
02103 service_str = "BS";
02104 } else {
02105
02106
02107
02108 strsep(&service_str, "=");
02109 }
02110
02111 if ((*service = service_string_to_service_type(service_str)) == AST_CC_NONE) {
02112
02113 return -1;
02114 }
02115
02116 ast_copy_string(subscribe_uri, get_in_brackets(uri), size);
02117
02118 return 0;
02119 }
02120
02121
02122
02123
02124
02125
02126
02127
02128
02129
02130
02131
02132
02133
02134
02135
02136
02137
02138 static void sip_handle_cc(struct sip_pvt *pvt, struct sip_request *req, enum ast_cc_service_type service)
02139 {
02140 enum ast_cc_monitor_policies monitor_policy = ast_get_cc_monitor_policy(pvt->cc_params);
02141 int core_id;
02142 char interface_name[AST_CHANNEL_NAME];
02143
02144 if (monitor_policy == AST_CC_MONITOR_NEVER) {
02145
02146 return;
02147 }
02148
02149 if ((core_id = ast_cc_get_current_core_id(pvt->owner)) == -1) {
02150
02151 return;
02152 }
02153
02154 ast_channel_get_device_name(pvt->owner, interface_name, sizeof(interface_name));
02155
02156 if (monitor_policy == AST_CC_MONITOR_ALWAYS || monitor_policy == AST_CC_MONITOR_NATIVE) {
02157 char subscribe_uri[SIPBUFSIZE];
02158 char device_name[AST_CHANNEL_NAME];
02159 enum ast_cc_service_type offered_service;
02160 struct sip_monitor_instance *monitor_instance;
02161 if (sip_get_cc_information(req, subscribe_uri, sizeof(subscribe_uri), &offered_service)) {
02162
02163
02164
02165
02166 goto generic;
02167 }
02168 ast_channel_get_device_name(pvt->owner, device_name, sizeof(device_name));
02169 if (!(monitor_instance = sip_monitor_instance_init(core_id, subscribe_uri, pvt->peername, device_name))) {
02170
02171 goto generic;
02172 }
02173
02174
02175
02176
02177 ast_module_ref(ast_module_info->self);
02178 ast_queue_cc_frame(pvt->owner, "SIP", pvt->dialstring, offered_service, monitor_instance);
02179 ao2_ref(monitor_instance, -1);
02180 return;
02181 }
02182
02183 generic:
02184 if (monitor_policy == AST_CC_MONITOR_GENERIC || monitor_policy == AST_CC_MONITOR_ALWAYS) {
02185 ast_queue_cc_frame(pvt->owner, AST_CC_GENERIC_MONITOR_TYPE, interface_name, service, NULL);
02186 }
02187 }
02188
02189
02190 static struct ast_tls_config sip_tls_cfg;
02191
02192
02193 static struct ast_tls_config default_tls_cfg;
02194
02195
02196 static struct ast_tcptls_session_args sip_tcp_desc = {
02197 .accept_fd = -1,
02198 .master = AST_PTHREADT_NULL,
02199 .tls_cfg = NULL,
02200 .poll_timeout = -1,
02201 .name = "SIP TCP server",
02202 .accept_fn = ast_tcptls_server_root,
02203 .worker_fn = sip_tcp_worker_fn,
02204 };
02205
02206
02207 static struct ast_tcptls_session_args sip_tls_desc = {
02208 .accept_fd = -1,
02209 .master = AST_PTHREADT_NULL,
02210 .tls_cfg = &sip_tls_cfg,
02211 .poll_timeout = -1,
02212 .name = "SIP TLS server",
02213 .accept_fn = ast_tcptls_server_root,
02214 .worker_fn = sip_tcp_worker_fn,
02215 };
02216
02217
02218
02219 #define append_history(p, event, fmt , args... ) append_history_full(p, "%-15s " fmt, event, ## args)
02220
02221 struct sip_pvt *dialog_ref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
02222 {
02223 if (p)
02224 #ifdef REF_DEBUG
02225 __ao2_ref_debug(p, 1, tag, file, line, func);
02226 #else
02227 ao2_ref(p, 1);
02228 #endif
02229 else
02230 ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
02231 return p;
02232 }
02233
02234 struct sip_pvt *dialog_unref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
02235 {
02236 if (p)
02237 #ifdef REF_DEBUG
02238 __ao2_ref_debug(p, -1, tag, file, line, func);
02239 #else
02240 ao2_ref(p, -1);
02241 #endif
02242 return NULL;
02243 }
02244
02245
02246
02247
02248 static const char *map_x_s(const struct _map_x_s *table, int x, const char *errorstring)
02249 {
02250 const struct _map_x_s *cur;
02251
02252 for (cur = table; cur->s; cur++)
02253 if (cur->x == x)
02254 return cur->s;
02255 return errorstring;
02256 }
02257
02258
02259
02260
02261 static int map_s_x(const struct _map_x_s *table, const char *s, int errorvalue)
02262 {
02263 const struct _map_x_s *cur;
02264
02265 for (cur = table; cur->s; cur++)
02266 if (!strcasecmp(cur->s, s))
02267 return cur->x;
02268 return errorvalue;
02269 }
02270
02271 static enum AST_REDIRECTING_REASON sip_reason_str_to_code(const char *text)
02272 {
02273 enum AST_REDIRECTING_REASON ast = AST_REDIRECTING_REASON_UNKNOWN;
02274 int i;
02275
02276 for (i = 0; i < ARRAY_LEN(sip_reason_table); ++i) {
02277 if (!strcasecmp(text, sip_reason_table[i].text)) {
02278 ast = sip_reason_table[i].code;
02279 break;
02280 }
02281 }
02282
02283 return ast;
02284 }
02285
02286 static const char *sip_reason_code_to_str(enum AST_REDIRECTING_REASON code)
02287 {
02288 if (code >= 0 && code < ARRAY_LEN(sip_reason_table)) {
02289 return sip_reason_table[code].text;
02290 }
02291
02292 return "unknown";
02293 }
02294
02295
02296
02297
02298
02299
02300
02301
02302 #define check_request_transport(peer, tmpl) ({ \
02303 int ret = 0; \
02304 if (peer->socket.type == tmpl->socket.type) \
02305 ; \
02306 else if (!(peer->transports & tmpl->socket.type)) {\
02307 ast_log(LOG_ERROR, \
02308 "'%s' is not a valid transport for '%s'. we only use '%s'! ending call.\n", \
02309 get_transport(tmpl->socket.type), peer->name, get_transport_list(peer->transports) \
02310 ); \
02311 ret = 1; \
02312 } else if (peer->socket.type & SIP_TRANSPORT_TLS) { \
02313 ast_log(LOG_WARNING, \
02314 "peer '%s' HAS NOT USED (OR SWITCHED TO) TLS in favor of '%s' (but this was allowed in sip.conf)!\n", \
02315 peer->name, get_transport(tmpl->socket.type) \
02316 ); \
02317 } else { \
02318 ast_debug(1, \
02319 "peer '%s' has contacted us over %s even though we prefer %s.\n", \
02320 peer->name, get_transport(tmpl->socket.type), get_transport(peer->socket.type) \
02321 ); \
02322 }\
02323 (ret); \
02324 })
02325
02326
02327
02328
02329 static struct ast_variable *copy_vars(struct ast_variable *src)
02330 {
02331 struct ast_variable *res = NULL, *tmp, *v = NULL;
02332
02333 for (v = src ; v ; v = v->next) {
02334 if ((tmp = ast_variable_new(v->name, v->value, v->file))) {
02335 tmp->next = res;
02336 res = tmp;
02337 }
02338 }
02339 return res;
02340 }
02341
02342 static void tcptls_packet_destructor(void *obj)
02343 {
02344 struct tcptls_packet *packet = obj;
02345
02346 ast_free(packet->data);
02347 }
02348
02349 static void sip_tcptls_client_args_destructor(void *obj)
02350 {
02351 struct ast_tcptls_session_args *args = obj;
02352 if (args->tls_cfg) {
02353 ast_free(args->tls_cfg->certfile);
02354 ast_free(args->tls_cfg->pvtfile);
02355 ast_free(args->tls_cfg->cipher);
02356 ast_free(args->tls_cfg->cafile);
02357 ast_free(args->tls_cfg->capath);
02358 }
02359 ast_free(args->tls_cfg);
02360 ast_free((char *) args->name);
02361 }
02362
02363 static void sip_threadinfo_destructor(void *obj)
02364 {
02365 struct sip_threadinfo *th = obj;
02366 struct tcptls_packet *packet;
02367 if (th->alert_pipe[1] > -1) {
02368 close(th->alert_pipe[0]);
02369 }
02370 if (th->alert_pipe[1] > -1) {
02371 close(th->alert_pipe[1]);
02372 }
02373 th->alert_pipe[0] = th->alert_pipe[1] = -1;
02374
02375 while ((packet = AST_LIST_REMOVE_HEAD(&th->packet_q, entry))) {
02376 ao2_t_ref(packet, -1, "thread destruction, removing packet from frame queue");
02377 }
02378
02379 if (th->tcptls_session) {
02380 ao2_t_ref(th->tcptls_session, -1, "remove tcptls_session for sip_threadinfo object");
02381 }
02382 }
02383
02384
02385 static struct sip_threadinfo *sip_threadinfo_create(struct ast_tcptls_session_instance *tcptls_session, int transport)
02386 {
02387 struct sip_threadinfo *th;
02388
02389 if (!tcptls_session || !(th = ao2_alloc(sizeof(*th), sip_threadinfo_destructor))) {
02390 return NULL;
02391 }
02392
02393 th->alert_pipe[0] = th->alert_pipe[1] = -1;
02394
02395 if (pipe(th->alert_pipe) == -1) {
02396 ao2_t_ref(th, -1, "Failed to open alert pipe on sip_threadinfo");
02397 ast_log(LOG_ERROR, "Could not create sip alert pipe in tcptls thread, error %s\n", strerror(errno));
02398 return NULL;
02399 }
02400 ao2_t_ref(tcptls_session, +1, "tcptls_session ref for sip_threadinfo object");
02401 th->tcptls_session = tcptls_session;
02402 th->type = transport ? transport : (tcptls_session->ssl ? SIP_TRANSPORT_TLS: SIP_TRANSPORT_TCP);
02403 ao2_t_link(threadt, th, "Adding new tcptls helper thread");
02404 ao2_t_ref(th, -1, "Decrementing threadinfo ref from alloc, only table ref remains");
02405 return th;
02406 }
02407
02408
02409 static int sip_tcptls_write(struct ast_tcptls_session_instance *tcptls_session, const void *buf, size_t len)
02410 {
02411 int res = len;
02412 struct sip_threadinfo *th = NULL;
02413 struct tcptls_packet *packet = NULL;
02414 struct sip_threadinfo tmp = {
02415 .tcptls_session = tcptls_session,
02416 };
02417 enum sip_tcptls_alert alert = TCPTLS_ALERT_DATA;
02418
02419 if (!tcptls_session) {
02420 return XMIT_ERROR;
02421 }
02422
02423 ast_mutex_lock(&tcptls_session->lock);
02424
02425 if ((tcptls_session->fd == -1) ||
02426 !(th = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread")) ||
02427 !(packet = ao2_alloc(sizeof(*packet), tcptls_packet_destructor)) ||
02428 !(packet->data = ast_str_create(len))) {
02429 goto tcptls_write_setup_error;
02430 }
02431
02432
02433 ast_str_set(&packet->data, 0, "%s", (char *) buf);
02434 packet->len = len;
02435
02436
02437
02438
02439 ao2_lock(th);
02440 if (write(th->alert_pipe[1], &alert, sizeof(alert)) == -1) {
02441 ast_log(LOG_ERROR, "write() to alert pipe failed: %s\n", strerror(errno));
02442 ao2_t_ref(packet, -1, "could not write to alert pipe, remove packet");
02443 packet = NULL;
02444 res = XMIT_ERROR;
02445 } else {
02446 AST_LIST_INSERT_TAIL(&th->packet_q, packet, entry);
02447 }
02448 ao2_unlock(th);
02449
02450 ast_mutex_unlock(&tcptls_session->lock);
02451 ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo object after finding it");
02452 return res;
02453
02454 tcptls_write_setup_error:
02455 if (th) {
02456 ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo obj, could not create packet");
02457 }
02458 if (packet) {
02459 ao2_t_ref(packet, -1, "could not allocate packet's data");
02460 }
02461 ast_mutex_unlock(&tcptls_session->lock);
02462
02463 return XMIT_ERROR;
02464 }
02465
02466
02467 static void *sip_tcp_worker_fn(void *data)
02468 {
02469 struct ast_tcptls_session_instance *tcptls_session = data;
02470
02471 return _sip_tcp_helper_thread(tcptls_session);
02472 }
02473
02474
02475
02476
02477
02478
02479
02480
02481 static int sip_check_authtimeout(time_t start)
02482 {
02483 int timeout;
02484 time_t now;
02485 if(time(&now) == -1) {
02486 ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
02487 return -1;
02488 }
02489
02490 timeout = (authtimeout - (now - start)) * 1000;
02491 if (timeout < 0) {
02492
02493 return 0;
02494 }
02495
02496 return timeout;
02497 }
02498
02499
02500
02501
02502 static void *_sip_tcp_helper_thread(struct ast_tcptls_session_instance *tcptls_session)
02503 {
02504 int res, cl, timeout = -1, authenticated = 0, flags, after_poll = 0, need_poll = 1;
02505 time_t start;
02506 struct sip_request req = { 0, } , reqcpy = { 0, };
02507 struct sip_threadinfo *me = NULL;
02508 char buf[1024] = "";
02509 struct pollfd fds[2] = { { 0 }, { 0 }, };
02510 struct ast_tcptls_session_args *ca = NULL;
02511
02512
02513
02514
02515
02516
02517
02518
02519
02520
02521
02522
02523 if (!tcptls_session->client) {
02524 if (ast_atomic_fetchadd_int(&unauth_sessions, +1) >= authlimit) {
02525
02526 goto cleanup;
02527 }
02528
02529 if ((flags = fcntl(tcptls_session->fd, F_GETFL)) == -1) {
02530 ast_log(LOG_ERROR, "error setting socket to non blocking mode, fcntl() failed: %s\n", strerror(errno));
02531 goto cleanup;
02532 }
02533
02534 flags |= O_NONBLOCK;
02535 if (fcntl(tcptls_session->fd, F_SETFL, flags) == -1) {
02536 ast_log(LOG_ERROR, "error setting socket to non blocking mode, fcntl() failed: %s\n", strerror(errno));
02537 goto cleanup;
02538 }
02539
02540 if (!(me = sip_threadinfo_create(tcptls_session, tcptls_session->ssl ? SIP_TRANSPORT_TLS : SIP_TRANSPORT_TCP))) {
02541 goto cleanup;
02542 }
02543 ao2_t_ref(me, +1, "Adding threadinfo ref for tcp_helper_thread");
02544 } else {
02545 struct sip_threadinfo tmp = {
02546 .tcptls_session = tcptls_session,
02547 };
02548
02549 if ((!(ca = tcptls_session->parent)) ||
02550 (!(me = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread"))) ||
02551 (!(tcptls_session = ast_tcptls_client_start(tcptls_session)))) {
02552 goto cleanup;
02553 }
02554 }
02555
02556 flags = 1;
02557 if (setsockopt(tcptls_session->fd, SOL_SOCKET, SO_KEEPALIVE, &flags, sizeof(flags))) {
02558 ast_log(LOG_ERROR, "error enabling TCP keep-alives on sip socket: %s\n", strerror(errno));
02559 goto cleanup;
02560 }
02561
02562 me->threadid = pthread_self();
02563 ast_debug(2, "Starting thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");
02564
02565
02566 fds[0].fd = tcptls_session->fd;
02567 fds[1].fd = me->alert_pipe[0];
02568 fds[0].events = fds[1].events = POLLIN | POLLPRI;
02569
02570 if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
02571 goto cleanup;
02572 }
02573 if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET))) {
02574 goto cleanup;
02575 }
02576
02577 if(time(&start) == -1) {
02578 ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
02579 goto cleanup;
02580 }
02581
02582 for (;;) {
02583 struct ast_str *str_save;
02584
02585 if (!tcptls_session->client && req.authenticated && !authenticated) {
02586 authenticated = 1;
02587 ast_atomic_fetchadd_int(&unauth_sessions, -1);
02588 }
02589
02590
02591 if (!tcptls_session->client && !authenticated ) {
02592 if ((timeout = sip_check_authtimeout(start)) < 0) {
02593 goto cleanup;
02594 }
02595
02596 if (timeout == 0) {
02597 ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
02598 goto cleanup;
02599 }
02600 } else {
02601 timeout = -1;
02602 }
02603
02604 res = ast_poll(fds, 2, timeout);
02605 if (res < 0) {
02606 ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", tcptls_session->ssl ? "SSL": "TCP", res);
02607 goto cleanup;
02608 } else if (res == 0) {
02609
02610 ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
02611 goto cleanup;
02612 }
02613
02614
02615
02616 if (fds[0].revents) {
02617 after_poll = 1;
02618
02619 fds[0].revents = 0;
02620
02621
02622 str_save = req.data;
02623 memset(&req, 0, sizeof(req));
02624 req.data = str_save;
02625 ast_str_reset(req.data);
02626
02627 str_save = reqcpy.data;
02628 memset(&reqcpy, 0, sizeof(reqcpy));
02629 reqcpy.data = str_save;
02630 ast_str_reset(reqcpy.data);
02631
02632 memset(buf, 0, sizeof(buf));
02633
02634 if (tcptls_session->ssl) {
02635 set_socket_transport(&req.socket, SIP_TRANSPORT_TLS);
02636 req.socket.port = htons(ourport_tls);
02637 } else {
02638 set_socket_transport(&req.socket, SIP_TRANSPORT_TCP);
02639 req.socket.port = htons(ourport_tcp);
02640 }
02641 req.socket.fd = tcptls_session->fd;
02642
02643
02644 while (ast_str_strlen(req.data) < 4 || strncmp(REQ_OFFSET_TO_STR(&req, data->used - 4), "\r\n\r\n", 4)) {
02645 if (!tcptls_session->client && !authenticated ) {
02646 if ((timeout = sip_check_authtimeout(start)) < 0) {
02647 goto cleanup;
02648 }
02649
02650 if (timeout == 0) {
02651 ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
02652 goto cleanup;
02653 }
02654 } else {
02655 timeout = -1;
02656 }
02657
02658
02659
02660
02661 if (!tcptls_session->ssl || need_poll) {
02662 need_poll = 0;
02663 after_poll = 1;
02664 res = ast_wait_for_input(tcptls_session->fd, timeout);
02665 if (res < 0) {
02666 ast_debug(2, "SIP TCP server :: ast_wait_for_input returned %d\n", res);
02667 goto cleanup;
02668 } else if (res == 0) {
02669
02670 ast_debug(2, "SIP TCP server timed out\n");
02671 goto cleanup;
02672 }
02673 }
02674
02675 ast_mutex_lock(&tcptls_session->lock);
02676 if (!fgets(buf, sizeof(buf), tcptls_session->f)) {
02677 ast_mutex_unlock(&tcptls_session->lock);
02678 if (after_poll) {
02679 goto cleanup;
02680 } else {
02681 need_poll = 1;
02682 continue;
02683 }
02684 }
02685 ast_mutex_unlock(&tcptls_session->lock);
02686 after_poll = 0;
02687 if (me->stop) {
02688 goto cleanup;
02689 }
02690 ast_str_append(&req.data, 0, "%s", buf);
02691 }
02692 copy_request(&reqcpy, &req);
02693 parse_request(&reqcpy);
02694
02695 if (sscanf(get_header(&reqcpy, "Content-Length"), "%30d", &cl)) {
02696 while (cl > 0) {
02697 size_t bytes_read;
02698 if (!tcptls_session->client && !authenticated ) {
02699 if ((timeout = sip_check_authtimeout(start)) < 0) {
02700 goto cleanup;
02701 }
02702
02703 if (timeout == 0) {
02704 ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
02705 goto cleanup;
02706 }
02707 } else {
02708 timeout = -1;
02709 }
02710
02711 if (!tcptls_session->ssl || need_poll) {
02712 need_poll = 0;
02713 after_poll = 1;
02714 res = ast_wait_for_input(tcptls_session->fd, timeout);
02715 if (res < 0) {
02716 ast_debug(2, "SIP TCP server :: ast_wait_for_input returned %d\n", res);
02717 goto cleanup;
02718 } else if (res == 0) {
02719
02720 ast_debug(2, "SIP TCP server timed out\n");
02721 goto cleanup;
02722 }
02723 }
02724
02725 ast_mutex_lock(&tcptls_session->lock);
02726 if (!(bytes_read = fread(buf, 1, MIN(sizeof(buf) - 1, cl), tcptls_session->f))) {
02727 ast_mutex_unlock(&tcptls_session->lock);
02728 if (after_poll) {
02729 goto cleanup;
02730 } else {
02731 need_poll = 1;
02732 continue;
02733 }
02734 }
02735 buf[bytes_read] = '\0';
02736 ast_mutex_unlock(&tcptls_session->lock);
02737 after_poll = 0;
02738 if (me->stop) {
02739 goto cleanup;
02740 }
02741 cl -= strlen(buf);
02742 ast_str_append(&req.data, 0, "%s", buf);
02743 }
02744 }
02745
02746
02747
02748 req.socket.tcptls_session = tcptls_session;
02749 handle_request_do(&req, &tcptls_session->remote_address);
02750 }
02751
02752 if (fds[1].revents) {
02753 enum sip_tcptls_alert alert;
02754 struct tcptls_packet *packet;
02755
02756 fds[1].revents = 0;
02757
02758 if (read(me->alert_pipe[0], &alert, sizeof(alert)) == -1) {
02759 ast_log(LOG_ERROR, "read() failed: %s\n", strerror(errno));
02760 continue;
02761 }
02762
02763 switch (alert) {
02764 case TCPTLS_ALERT_STOP:
02765 goto cleanup;
02766 case TCPTLS_ALERT_DATA:
02767 ao2_lock(me);
02768 if (!(packet = AST_LIST_REMOVE_HEAD(&me->packet_q, entry))) {
02769 ast_log(LOG_WARNING, "TCPTLS thread alert_pipe indicated packet should be sent, but frame_q is empty");
02770 }
02771 ao2_unlock(me);
02772
02773 if (packet) {
02774 if (ast_tcptls_server_write(tcptls_session, ast_str_buffer(packet->data), packet->len) == -1) {
02775 ast_log(LOG_WARNING, "Failure to write to tcp/tls socket\n");
02776 }
02777 ao2_t_ref(packet, -1, "tcptls packet sent, this is no longer needed");
02778 }
02779 break;
02780 default:
02781 ast_log(LOG_ERROR, "Unknown tcptls thread alert '%d'\n", alert);
02782 }
02783 }
02784 }
02785
02786 ast_debug(2, "Shutting down thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");
02787
02788 cleanup:
02789 if (tcptls_session && !tcptls_session->client && !authenticated) {
02790 ast_atomic_fetchadd_int(&unauth_sessions, -1);
02791 }
02792
02793 if (me) {
02794 ao2_t_unlink(threadt, me, "Removing tcptls helper thread, thread is closing");
02795 ao2_t_ref(me, -1, "Removing tcp_helper_threads threadinfo ref");
02796 }
02797 deinit_req(&reqcpy);
02798 deinit_req(&req);
02799
02800
02801 if (ca) {
02802 ao2_t_ref(ca, -1, "closing tcptls thread, getting rid of client tcptls_session arguments");
02803 }
02804
02805 if (tcptls_session) {
02806 ast_mutex_lock(&tcptls_session->lock);
02807 ast_tcptls_close_session_file(tcptls_session);
02808 tcptls_session->parent = NULL;
02809 ast_mutex_unlock(&tcptls_session->lock);
02810
02811 ao2_ref(tcptls_session, -1);
02812 tcptls_session = NULL;
02813 }
02814 return NULL;
02815 }
02816
02817 #ifdef REF_DEBUG
02818 #define ref_peer(arg1,arg2) _ref_peer((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
02819 #define unref_peer(arg1,arg2) _unref_peer((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
02820 static struct sip_peer *_ref_peer(struct sip_peer *peer, char *tag, char *file, int line, const char *func)
02821 {
02822 if (peer)
02823 __ao2_ref_debug(peer, 1, tag, file, line, func);
02824 else
02825 ast_log(LOG_ERROR, "Attempt to Ref a null peer pointer\n");
02826 return peer;
02827 }
02828
02829 static struct sip_peer *_unref_peer(struct sip_peer *peer, char *tag, char *file, int line, const char *func)
02830 {
02831 if (peer)
02832 __ao2_ref_debug(peer, -1, tag, file, line, func);
02833 return NULL;
02834 }
02835 #else
02836
02837
02838
02839
02840
02841 static void *unref_peer(struct sip_peer *peer, char *tag)
02842 {
02843 ao2_t_ref(peer, -1, tag);
02844 return NULL;
02845 }
02846
02847 static struct sip_peer *ref_peer(struct sip_peer *peer, char *tag)
02848 {
02849 ao2_t_ref(peer, 1, tag);
02850 return peer;
02851 }
02852 #endif
02853
02854 static void peer_sched_cleanup(struct sip_peer *peer)
02855 {
02856 if (peer->pokeexpire != -1) {
02857 AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
02858 unref_peer(peer, "removing poke peer ref"));
02859 }
02860 if (peer->expire != -1) {
02861 AST_SCHED_DEL_UNREF(sched, peer->expire,
02862 unref_peer(peer, "remove register expire ref"));
02863 }
02864 }
02865
02866 typedef enum {
02867 SIP_PEERS_MARKED,
02868 SIP_PEERS_ALL,
02869 } peer_unlink_flag_t;
02870
02871
02872
02873 static int match_and_cleanup_peer_sched(void *peerobj, void *arg, int flags)
02874 {
02875 struct sip_peer *peer = peerobj;
02876 peer_unlink_flag_t which = *(peer_unlink_flag_t *)arg;
02877
02878 if (which == SIP_PEERS_ALL || peer->the_mark) {
02879 peer_sched_cleanup(peer);
02880 if (peer->dnsmgr) {
02881 ast_dnsmgr_release(peer->dnsmgr);
02882 peer->dnsmgr = NULL;
02883 unref_peer(peer, "Release peer from dnsmgr");
02884 }
02885 return CMP_MATCH;
02886 }
02887 return 0;
02888 }
02889
02890 static void unlink_peers_from_tables(peer_unlink_flag_t flag)
02891 {
02892 ao2_t_callback(peers, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE,
02893 match_and_cleanup_peer_sched, &flag, "initiating callback to remove marked peers");
02894 ao2_t_callback(peers_by_ip, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE,
02895 match_and_cleanup_peer_sched, &flag, "initiating callback to remove marked peers");
02896 }
02897
02898
02899 static void unlink_marked_peers_from_tables(void)
02900 {
02901 unlink_peers_from_tables(SIP_PEERS_MARKED);
02902 }
02903
02904 static void unlink_all_peers_from_tables(void)
02905 {
02906 unlink_peers_from_tables(SIP_PEERS_ALL);
02907 }
02908
02909
02910 static void unlink_peer_from_tables(struct sip_peer *peer)
02911 {
02912 ao2_t_unlink(peers, peer, "ao2_unlink of peer from peers table");
02913 if (!ast_sockaddr_isnull(&peer->addr)) {
02914 ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
02915 }
02916 }
02917
02918
02919
02920
02921
02922
02923
02924
02925
02926
02927
02928
02929 static void ref_proxy(struct sip_pvt *pvt, struct sip_proxy *proxy)
02930 {
02931 struct sip_proxy *old_obproxy = pvt->outboundproxy;
02932
02933
02934
02935 if (proxy && proxy != &sip_cfg.outboundproxy) {
02936 ao2_ref(proxy, +1);
02937 }
02938 pvt->outboundproxy = proxy;
02939 if (old_obproxy && old_obproxy != &sip_cfg.outboundproxy) {
02940 ao2_ref(old_obproxy, -1);
02941 }
02942 }
02943
02944
02945
02946
02947
02948
02949
02950
02951 void dialog_unlink_all(struct sip_pvt *dialog)
02952 {
02953 struct sip_pkt *cp;
02954 struct ast_channel *owner;
02955
02956 dialog_ref(dialog, "Let's bump the count in the unlink so it doesn't accidentally become dead before we are done");
02957
02958 ao2_t_unlink(dialogs, dialog, "unlinking dialog via ao2_unlink");
02959
02960
02961 owner = sip_pvt_lock_full(dialog);
02962 if (owner) {
02963 ast_debug(1, "Detaching from channel %s\n", owner->name);
02964 owner->tech_pvt = dialog_unref(owner->tech_pvt, "resetting channel dialog ptr in unlink_all");
02965 ast_channel_unlock(owner);
02966 ast_channel_unref(owner);
02967 dialog->owner = NULL;
02968 }
02969 sip_pvt_unlock(dialog);
02970
02971 if (dialog->registry) {
02972 if (dialog->registry->call == dialog) {
02973 dialog->registry->call = dialog_unref(dialog->registry->call, "nulling out the registry's call dialog field in unlink_all");
02974 }
02975 dialog->registry = registry_unref(dialog->registry, "delete dialog->registry");
02976 }
02977 if (dialog->stateid != -1) {
02978 ast_extension_state_del(dialog->stateid, cb_extensionstate);
02979 dialog->stateid = -1;
02980 }
02981
02982 if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog) {
02983 dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
02984 }
02985 if (dialog->relatedpeer && dialog->relatedpeer->call == dialog) {
02986 dialog->relatedpeer->call = dialog_unref(dialog->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
02987 }
02988
02989
02990 while((cp = dialog->packets)) {
02991 dialog->packets = dialog->packets->next;
02992 AST_SCHED_DEL(sched, cp->retransid);
02993 dialog_unref(cp->owner, "remove all current packets in this dialog, and the pointer to the dialog too as part of __sip_destroy");
02994 if (cp->data) {
02995 ast_free(cp->data);
02996 }
02997 ast_free(cp);
02998 }
02999
03000 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"));
03001
03002 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"));
03003
03004 if (dialog->autokillid > -1) {
03005 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"));
03006 }
03007
03008 if (dialog->request_queue_sched_id > -1) {
03009 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"));
03010 }
03011
03012 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"));
03013
03014 if (dialog->t38id > -1) {
03015 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"));
03016 }
03017
03018 if (dialog->stimer) {
03019 stop_session_timer(dialog);
03020 }
03021
03022 dialog_unref(dialog, "Let's unbump the count in the unlink so the poor pvt can disappear if it is time");
03023 }
03024
03025 void *registry_unref(struct sip_registry *reg, char *tag)
03026 {
03027 ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount - 1);
03028 ASTOBJ_UNREF(reg, sip_registry_destroy);
03029 return NULL;
03030 }
03031
03032
03033 static struct sip_registry *registry_addref(struct sip_registry *reg, char *tag)
03034 {
03035 ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount + 1);
03036 return ASTOBJ_REF(reg);
03037 }
03038
03039
03040 static struct ast_udptl_protocol sip_udptl = {
03041 .type = "SIP",
03042 .get_udptl_info = sip_get_udptl_peer,
03043 .set_udptl_peer = sip_set_udptl_peer,
03044 };
03045
03046 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
03047 __attribute__((format(printf, 2, 3)));
03048
03049
03050
03051 static const char *referstatus2str(enum referstatus rstatus)
03052 {
03053 return map_x_s(referstatusstrings, rstatus, "");
03054 }
03055
03056 static inline void pvt_set_needdestroy(struct sip_pvt *pvt, const char *reason)
03057 {
03058 if (pvt->final_destruction_scheduled) {
03059 return;
03060 }
03061 append_history(pvt, "NeedDestroy", "Setting needdestroy because %s", reason);
03062 pvt->needdestroy = 1;
03063 }
03064
03065
03066
03067
03068 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
03069 {
03070 if (p->initreq.headers) {
03071 ast_debug(1, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
03072 } else {
03073 ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
03074 }
03075
03076 copy_request(&p->initreq, req);
03077 parse_request(&p->initreq);
03078 if (req->debug) {
03079 ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
03080 }
03081 }
03082
03083
03084 static void sip_alreadygone(struct sip_pvt *dialog)
03085 {
03086 ast_debug(3, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
03087 dialog->alreadygone = 1;
03088 }
03089
03090
03091 static int proxy_update(struct sip_proxy *proxy)
03092 {
03093
03094
03095 if (!ast_sockaddr_parse(&proxy->ip, proxy->name, 0)) {
03096
03097
03098 proxy->ip.ss.ss_family = get_address_family_filter(&bindaddr);
03099 if (ast_get_ip_or_srv(&proxy->ip, proxy->name, sip_cfg.srvlookup ? "_sip._udp" : NULL) < 0) {
03100 ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
03101 return FALSE;
03102 }
03103
03104 }
03105
03106 ast_sockaddr_set_port(&proxy->ip, proxy->port);
03107
03108 proxy->last_dnsupdate = time(NULL);
03109 return TRUE;
03110 }
03111
03112
03113
03114
03115
03116 unsigned int port_str2int(const char *pt, unsigned int standard)
03117 {
03118 int port = standard;
03119 if (ast_strlen_zero(pt) || (sscanf(pt, "%30d", &port) != 1) || (port < 1) || (port > 65535)) {
03120 port = standard;
03121 }
03122
03123 return port;
03124 }
03125
03126
03127 static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
03128 {
03129 if (peer && peer->outboundproxy) {
03130 if (sipdebug) {
03131 ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
03132 }
03133 append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
03134 return peer->outboundproxy;
03135 }
03136 if (sip_cfg.outboundproxy.name[0]) {
03137 if (sipdebug) {
03138 ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
03139 }
03140 append_history(dialog, "OBproxy", "Using global obproxy %s", sip_cfg.outboundproxy.name);
03141 return &sip_cfg.outboundproxy;
03142 }
03143 if (sipdebug) {
03144 ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
03145 }
03146 return NULL;
03147 }
03148
03149
03150
03151
03152
03153
03154
03155 static int method_match(enum sipmethod id, const char *name)
03156 {
03157 int len = strlen(sip_methods[id].text);
03158 int l_name = name ? strlen(name) : 0;
03159
03160 return (l_name >= len && name[len] < 33 &&
03161 !strncasecmp(sip_methods[id].text, name, len));
03162 }
03163
03164
03165 static int find_sip_method(const char *msg)
03166 {
03167 int i, res = 0;
03168
03169 if (ast_strlen_zero(msg)) {
03170 return 0;
03171 }
03172 for (i = 1; i < ARRAY_LEN(sip_methods) && !res; i++) {
03173 if (method_match(i, msg)) {
03174 res = sip_methods[i].id;
03175 }
03176 }
03177 return res;
03178 }
03179
03180
03181 static inline int sip_debug_test_addr(const struct ast_sockaddr *addr)
03182 {
03183
03184 if (!sipdebug) {
03185 return 0;
03186 }
03187
03188
03189 if (ast_sockaddr_isnull(&debugaddr)) {
03190 return 1;
03191 }
03192
03193
03194
03195
03196 if (ast_sockaddr_port(&debugaddr)) {
03197 return !ast_sockaddr_cmp(&debugaddr, addr);
03198 } else {
03199 return !ast_sockaddr_cmp_addr(&debugaddr, addr);
03200 }
03201 }
03202
03203
03204 static const struct ast_sockaddr *sip_real_dst(const struct sip_pvt *p)
03205 {
03206 if (p->outboundproxy) {
03207 return &p->outboundproxy->ip;
03208 }
03209
03210 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;
03211 }
03212
03213
03214 static const char *sip_nat_mode(const struct sip_pvt *p)
03215 {
03216 return ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) ? "NAT" : "no NAT";
03217 }
03218
03219
03220 static inline int sip_debug_test_pvt(struct sip_pvt *p)
03221 {
03222 if (!sipdebug) {
03223 return 0;
03224 }
03225 return sip_debug_test_addr(sip_real_dst(p));
03226 }
03227
03228
03229 static int get_transport_str2enum(const char *transport)
03230 {
03231 int res = 0;
03232
03233 if (ast_strlen_zero(transport)) {
03234 return res;
03235 }
03236
03237 if (!strcasecmp(transport, "udp")) {
03238 res |= SIP_TRANSPORT_UDP;
03239 }
03240 if (!strcasecmp(transport, "tcp")) {
03241 res |= SIP_TRANSPORT_TCP;
03242 }
03243 if (!strcasecmp(transport, "tls")) {
03244 res |= SIP_TRANSPORT_TLS;
03245 }
03246
03247 return res;
03248 }
03249
03250
03251 static inline const char *get_transport_list(unsigned int transports) {
03252 switch (transports) {
03253 case SIP_TRANSPORT_UDP:
03254 return "UDP";
03255 case SIP_TRANSPORT_TCP:
03256 return "TCP";
03257 case SIP_TRANSPORT_TLS:
03258 return "TLS";
03259 case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TCP:
03260 return "TCP,UDP";
03261 case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TLS:
03262 return "TLS,UDP";
03263 case SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS:
03264 return "TLS,TCP";
03265 default:
03266 return transports ?
03267 "TLS,TCP,UDP" : "UNKNOWN";
03268 }
03269 }
03270
03271
03272 static inline const char *get_transport(enum sip_transport t)
03273 {
03274 switch (t) {
03275 case SIP_TRANSPORT_UDP:
03276 return "UDP";
03277 case SIP_TRANSPORT_TCP:
03278 return "TCP";
03279 case SIP_TRANSPORT_TLS:
03280 return "TLS";
03281 }
03282
03283 return "UNKNOWN";
03284 }
03285
03286
03287 static inline const char *get_srv_protocol(enum sip_transport t)
03288 {
03289 switch (t) {
03290 case SIP_TRANSPORT_UDP:
03291 return "udp";
03292 case SIP_TRANSPORT_TLS:
03293 case SIP_TRANSPORT_TCP:
03294 return "tcp";
03295 }
03296
03297 return "udp";
03298 }
03299
03300
03301 static inline const char *get_srv_service(enum sip_transport t)
03302 {
03303 switch (t) {
03304 case SIP_TRANSPORT_TCP:
03305 case SIP_TRANSPORT_UDP:
03306 return "sip";
03307 case SIP_TRANSPORT_TLS:
03308 return "sips";
03309 }
03310 return "sip";
03311 }
03312
03313
03314
03315
03316
03317
03318
03319 static inline const char *get_transport_pvt(struct sip_pvt *p)
03320 {
03321 if (p->outboundproxy && p->outboundproxy->transport) {
03322 set_socket_transport(&p->socket, p->outboundproxy->transport);
03323 }
03324
03325 return get_transport(p->socket.type);
03326 }
03327
03328
03329
03330
03331
03332
03333
03334
03335
03336
03337
03338
03339 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data)
03340 {
03341 int res = 0;
03342 const struct ast_sockaddr *dst = sip_real_dst(p);
03343
03344 ast_debug(2, "Trying to put '%.11s' onto %s socket destined for %s\n", data->str, get_transport_pvt(p), ast_sockaddr_stringify(dst));
03345
03346 if (sip_prepare_socket(p) < 0) {
03347 return XMIT_ERROR;
03348 }
03349
03350 if (p->socket.type == SIP_TRANSPORT_UDP) {
03351 res = ast_sendto(p->socket.fd, data->str, ast_str_strlen(data), 0, dst);
03352 } else if (p->socket.tcptls_session) {
03353 res = sip_tcptls_write(p->socket.tcptls_session, data->str, ast_str_strlen(data));
03354 } else {
03355 ast_debug(2, "Socket type is TCP but no tcptls_session is present to write to\n");
03356 return XMIT_ERROR;
03357 }
03358
03359 if (res == -1) {
03360 switch (errno) {
03361 case EBADF:
03362 case EHOSTUNREACH:
03363 case ENETDOWN:
03364 case ENETUNREACH:
03365 case ECONNREFUSED:
03366 res = XMIT_ERROR;
03367 }
03368 }
03369 if (res != ast_str_strlen(data)) {
03370 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));
03371 }
03372
03373 return res;
03374 }
03375
03376
03377 static void build_via(struct sip_pvt *p)
03378 {
03379
03380 const char *rport = (ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) || ast_test_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT)) ? ";rport" : "";
03381
03382
03383 snprintf(p->via, sizeof(p->via), "SIP/2.0/%s %s;branch=z9hG4bK%08x%s",
03384 get_transport_pvt(p),
03385 ast_sockaddr_stringify_remote(&p->ourip),
03386 (int) p->branch, rport);
03387 }
03388
03389
03390
03391
03392
03393
03394
03395
03396 static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p)
03397 {
03398 struct ast_sockaddr theirs;
03399
03400
03401
03402
03403
03404
03405
03406
03407
03408
03409
03410
03411
03412 int want_remap = 0;
03413
03414 ast_sockaddr_copy(us, &internip);
03415
03416 ast_ouraddrfor(them, us);
03417 ast_sockaddr_copy(&theirs, them);
03418
03419 if (ast_sockaddr_is_ipv6(&theirs)) {
03420 if (localaddr && !ast_sockaddr_isnull(&externaddr)) {
03421 ast_log(LOG_WARNING, "Address remapping activated in sip.conf "
03422 "but we're using IPv6, which doesn't need it. Please "
03423 "remove \"localnet\" and/or \"externaddr\" settings.\n");
03424 }
03425 } else {
03426 want_remap = localaddr &&
03427 !ast_sockaddr_isnull(&externaddr) &&
03428 ast_apply_ha(localaddr, &theirs) == AST_SENSE_ALLOW ;
03429 }
03430
03431 if (want_remap &&
03432 (!sip_cfg.matchexternaddrlocally || !ast_apply_ha(localaddr, us)) ) {
03433
03434 if (externexpire && time(NULL) >= externexpire) {
03435 if (ast_sockaddr_resolve_first(&externaddr, externhost, 0)) {
03436 ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
03437 }
03438 externexpire = time(NULL) + externrefresh;
03439 }
03440 if (!ast_sockaddr_isnull(&externaddr)) {
03441 ast_sockaddr_copy(us, &externaddr);
03442 switch (p->socket.type) {
03443 case SIP_TRANSPORT_TCP:
03444 if (!externtcpport && ast_sockaddr_port(&externaddr)) {
03445
03446 externtcpport = ast_sockaddr_port(&externaddr);
03447 }
03448 ast_sockaddr_set_port(us, externtcpport);
03449 break;
03450 case SIP_TRANSPORT_TLS:
03451 ast_sockaddr_set_port(us, externtlsport);
03452 break;
03453 case SIP_TRANSPORT_UDP:
03454 if (!ast_sockaddr_port(&externaddr)) {
03455 ast_sockaddr_set_port(us, ast_sockaddr_port(&bindaddr));
03456 }
03457 break;
03458 default:
03459 break;
03460 }
03461 }
03462 ast_debug(1, "Target address %s is not local, substituting externaddr\n",
03463 ast_sockaddr_stringify(them));
03464 } else if (p) {
03465
03466 switch (p->socket.type) {
03467 case SIP_TRANSPORT_TCP:
03468 if (!ast_sockaddr_is_any(&sip_tcp_desc.local_address)) {
03469 ast_sockaddr_copy(us,
03470 &sip_tcp_desc.local_address);
03471 } else {
03472 ast_sockaddr_set_port(us,
03473 ast_sockaddr_port(&sip_tcp_desc.local_address));
03474 }
03475 break;
03476 case SIP_TRANSPORT_TLS:
03477 if (!ast_sockaddr_is_any(&sip_tls_desc.local_address)) {
03478 ast_sockaddr_copy(us,
03479 &sip_tls_desc.local_address);
03480 } else {
03481 ast_sockaddr_set_port(us,
03482 ast_sockaddr_port(&sip_tls_desc.local_address));
03483 }
03484 break;
03485 case SIP_TRANSPORT_UDP:
03486
03487 default:
03488 if (!ast_sockaddr_is_any(&bindaddr)) {
03489 ast_sockaddr_copy(us, &bindaddr);
03490 }
03491 if (!ast_sockaddr_port(us)) {
03492 ast_sockaddr_set_port(us, ast_sockaddr_port(&bindaddr));
03493 }
03494 }
03495 } else if (!ast_sockaddr_is_any(&bindaddr)) {
03496 ast_sockaddr_copy(us, &bindaddr);
03497 }
03498 ast_debug(3, "Setting SIP_TRANSPORT_%s with address %s\n", get_transport(p->socket.type), ast_sockaddr_stringify(us));
03499 }
03500
03501
03502 static __attribute__((format(printf, 2, 0))) void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
03503 {
03504 char buf[80], *c = buf;
03505 struct sip_history *hist;
03506 int l;
03507
03508 vsnprintf(buf, sizeof(buf), fmt, ap);
03509 strsep(&c, "\r\n");
03510 l = strlen(buf) + 1;
03511 if (!(hist = ast_calloc(1, sizeof(*hist) + l))) {
03512 return;
03513 }
03514 if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
03515 ast_free(hist);
03516 return;
03517 }
03518 memcpy(hist->event, buf, l);
03519 if (p->history_entries == MAX_HISTORY_ENTRIES) {
03520 struct sip_history *oldest;
03521 oldest = AST_LIST_REMOVE_HEAD(p->history, list);
03522 p->history_entries--;
03523 ast_free(oldest);
03524 }
03525 AST_LIST_INSERT_TAIL(p->history, hist, list);
03526 p->history_entries++;
03527 }
03528
03529
03530 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
03531 {
03532 va_list ap;
03533
03534 if (!p) {
03535 return;
03536 }
03537
03538 if (!p->do_history && !recordhistory && !dumphistory) {
03539 return;
03540 }
03541
03542 va_start(ap, fmt);
03543 append_history_va(p, fmt, ap);
03544 va_end(ap);
03545
03546 return;
03547 }
03548
03549
03550 static int retrans_pkt(const void *data)
03551 {
03552 struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
03553 int reschedule = DEFAULT_RETRANS;
03554 int xmitres = 0;
03555
03556 int64_t diff = pkt->retrans_stop_time - ast_tvdiff_ms(ast_tvnow(), pkt->time_sent);
03557
03558
03559
03560
03561 if ((diff <= 0) || (diff > pkt->retrans_stop_time)) {
03562 pkt->retrans_stop = 1;
03563 }
03564
03565
03566 sip_pvt_lock(pkt->owner);
03567
03568 if (!pkt->retrans_stop) {
03569 pkt->retrans++;
03570 if (!pkt->timer_t1) {
03571 if (sipdebug) {
03572 ast_debug(4, "SIP TIMER: Not rescheduling id #%d:%s (Method %d) (No timer T1)\n",
03573 pkt->retransid,
03574 sip_methods[pkt->method].text,
03575 pkt->method);
03576 }
03577 } else {
03578 int siptimer_a;
03579
03580 if (sipdebug) {
03581 ast_debug(4, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n",
03582 pkt->retransid,
03583 pkt->retrans,
03584 sip_methods[pkt->method].text,
03585 pkt->method);
03586 }
03587 if (!pkt->timer_a) {
03588 pkt->timer_a = 2 ;
03589 } else {
03590 pkt->timer_a = 2 * pkt->timer_a;
03591 }
03592
03593
03594 siptimer_a = pkt->timer_t1 * pkt->timer_a;
03595 if (pkt->method != SIP_INVITE && siptimer_a > 4000) {
03596 siptimer_a = 4000;
03597 }
03598
03599
03600 reschedule = siptimer_a;
03601 ast_debug(4, "** SIP timers: Rescheduling retransmission %d to %d ms (t1 %d ms (Retrans id #%d)) \n",
03602 pkt->retrans + 1,
03603 siptimer_a,
03604 pkt->timer_t1,
03605 pkt->retransid);
03606 }
03607
03608 if (sip_debug_test_pvt(pkt->owner)) {
03609 const struct ast_sockaddr *dst = sip_real_dst(pkt->owner);
03610 ast_verbose("Retransmitting #%d (%s) to %s:\n%s\n---\n",
03611 pkt->retrans, sip_nat_mode(pkt->owner),
03612 ast_sockaddr_stringify(dst),
03613 pkt->data->str);
03614 }
03615
03616 append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data->str);
03617 xmitres = __sip_xmit(pkt->owner, pkt->data);
03618
03619
03620
03621
03622
03623
03624 if (xmitres != XMIT_ERROR) {
03625 if (reschedule >= diff) {
03626 pkt->retrans_stop = 1;
03627 reschedule = diff;
03628 }
03629 sip_pvt_unlock(pkt->owner);
03630 return reschedule;
03631 }
03632 }
03633
03634
03635
03636
03637 pkt->retransid = -1;
03638
03639 if (pkt->owner && pkt->method != SIP_OPTIONS && xmitres == 0) {
03640 if (pkt->is_fatal || sipdebug) {
03641 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"
03642 "Packet timed out after %dms with no response\n",
03643 pkt->owner->callid,
03644 pkt->seqno,
03645 pkt->is_fatal ? "Critical" : "Non-critical",
03646 pkt->is_resp ? "Response" : "Request",
03647 (int) ast_tvdiff_ms(ast_tvnow(), pkt->time_sent));
03648 }
03649 } else if (pkt->method == SIP_OPTIONS && sipdebug) {
03650 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);
03651 }
03652
03653 if (xmitres == XMIT_ERROR) {
03654 ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission on Call ID %s\n", pkt->owner->callid);
03655 append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03656 } else {
03657 append_history(pkt->owner, "MaxRetries", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03658 }
03659
03660 if (pkt->is_fatal) {
03661 while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
03662 sip_pvt_unlock(pkt->owner);
03663 usleep(1);
03664 sip_pvt_lock(pkt->owner);
03665 }
03666 if (pkt->owner->owner && !pkt->owner->owner->hangupcause) {
03667 pkt->owner->owner->hangupcause = AST_CAUSE_NO_USER_RESPONSE;
03668 }
03669 if (pkt->owner->owner) {
03670 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);
03671
03672 if (pkt->is_resp &&
03673 (pkt->response_code >= 200) &&
03674 (pkt->response_code < 300) &&
03675 pkt->owner->pendinginvite &&
03676 ast_test_flag(&pkt->owner->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
03677
03678
03679
03680
03681
03682
03683
03684 pkt->owner->invitestate = INV_TERMINATED;
03685 pkt->owner->pendinginvite = 0;
03686 } else {
03687
03688 sip_alreadygone(pkt->owner);
03689 }
03690 ast_queue_hangup_with_cause(pkt->owner->owner, AST_CAUSE_PROTOCOL_ERROR);
03691 ast_channel_unlock(pkt->owner->owner);
03692 } else {
03693
03694
03695
03696 if (pkt->method != SIP_OPTIONS && pkt->method != SIP_REGISTER) {
03697 pvt_set_needdestroy(pkt->owner, "no response to critical packet");
03698 sip_alreadygone(pkt->owner);
03699 append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
03700 }
03701 }
03702 }
03703
03704 if (pkt->method == SIP_BYE) {
03705
03706 sip_alreadygone(pkt->owner);
03707 if (pkt->owner->owner) {
03708 ast_channel_unlock(pkt->owner->owner);
03709 }
03710 append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
03711 pvt_set_needdestroy(pkt->owner, "no response to BYE");
03712 }
03713
03714
03715 for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
03716 if (cur == pkt) {
03717 UNLINK(cur, pkt->owner->packets, prev);
03718 sip_pvt_unlock(pkt->owner);
03719 if (pkt->owner) {
03720 pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
03721 }
03722 if (pkt->data) {
03723 ast_free(pkt->data);
03724 }
03725 pkt->data = NULL;
03726 ast_free(pkt);
03727 return 0;
03728 }
03729 }
03730
03731 ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
03732 sip_pvt_unlock(pkt->owner);
03733 return 0;
03734 }
03735
03736
03737
03738
03739
03740
03741 static enum sip_result __sip_reliable_xmit(struct sip_pvt *p, uint32_t seqno, int resp, struct ast_str *data, int fatal, int sipmethod)
03742 {
03743 struct sip_pkt *pkt = NULL;
03744 int siptimer_a = DEFAULT_RETRANS;
03745 int xmitres = 0;
03746 int respid;
03747
03748 if (sipmethod == SIP_INVITE) {
03749
03750 p->pendinginvite = seqno;
03751 }
03752
03753
03754
03755
03756 if (!(p->socket.type & SIP_TRANSPORT_UDP)) {
03757 xmitres = __sip_xmit(p, data);
03758 if (xmitres == XMIT_ERROR) {
03759 append_history(p, "XmitErr", "%s", fatal ? "(Critical)" : "(Non-critical)");
03760 return AST_FAILURE;
03761 } else {
03762 return AST_SUCCESS;
03763 }
03764 }
03765
03766 if (!(pkt = ast_calloc(1, sizeof(*pkt)))) {
03767 return AST_FAILURE;
03768 }
03769
03770 if (!(pkt->data = ast_str_create(ast_str_strlen(data)))) {
03771 ast_free(pkt);
03772 return AST_FAILURE;
03773 }
03774 ast_str_set(&pkt->data, 0, "%s%s", data->str, "\0");
03775
03776 pkt->method = sipmethod;
03777 pkt->seqno = seqno;
03778 pkt->is_resp = resp;
03779 pkt->is_fatal = fatal;
03780 pkt->owner = dialog_ref(p, "__sip_reliable_xmit: setting pkt->owner");
03781 pkt->next = p->packets;
03782 p->packets = pkt;
03783 if (resp) {
03784
03785 if (sscanf(ast_str_buffer(pkt->data), "SIP/2.0 %30u", &respid) == 1) {
03786 pkt->response_code = respid;
03787 }
03788 }
03789 pkt->timer_t1 = p->timer_t1;
03790 pkt->retransid = -1;
03791 if (pkt->timer_t1) {
03792 siptimer_a = pkt->timer_t1;
03793 }
03794
03795 pkt->time_sent = ast_tvnow();
03796 pkt->retrans_stop_time = 64 * (pkt->timer_t1 ? pkt->timer_t1 : DEFAULT_TIMER_T1);
03797
03798
03799 AST_SCHED_REPLACE_VARIABLE(pkt->retransid, sched, siptimer_a, retrans_pkt, pkt, 1);
03800 if (sipdebug) {
03801 ast_debug(4, "*** SIP TIMER: Initializing retransmit timer on packet: Id #%d\n", pkt->retransid);
03802 }
03803
03804 xmitres = __sip_xmit(pkt->owner, pkt->data);
03805
03806 if (xmitres == XMIT_ERROR) {
03807 append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03808 ast_log(LOG_ERROR, "Serious Network Trouble; __sip_xmit returns error for pkt data\n");
03809 AST_SCHED_DEL(sched, pkt->retransid);
03810 p->packets = pkt->next;
03811 pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
03812 ast_free(pkt->data);
03813 ast_free(pkt);
03814 return AST_FAILURE;
03815 } else {
03816
03817
03818
03819
03820 if (monitor_thread != AST_PTHREADT_NULL) {
03821 pthread_kill(monitor_thread, SIGURG);
03822 }
03823 return AST_SUCCESS;
03824 }
03825 }
03826
03827
03828
03829
03830
03831
03832 static int __sip_autodestruct(const void *data)
03833 {
03834 struct sip_pvt *p = (struct sip_pvt *)data;
03835 struct ast_channel *owner;
03836
03837
03838 if (p->subscribed && p->subscribed != MWI_NOTIFICATION && p->subscribed != CALL_COMPLETION) {
03839 transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE);
03840 p->subscribed = NONE;
03841 append_history(p, "Subscribestatus", "timeout");
03842 ast_debug(3, "Re-scheduled destruction of SIP subscription %s\n", p->callid ? p->callid : "<unknown>");
03843 return 10000;
03844 }
03845
03846
03847 if (p->packets) {
03848 if (!p->needdestroy) {
03849 char method_str[31];
03850 ast_debug(3, "Re-scheduled destruction of SIP call %s\n", p->callid ? p->callid : "<unknown>");
03851 append_history(p, "ReliableXmit", "timeout");
03852 if (sscanf(p->lastmsg, "Tx: %30s", method_str) == 1 || sscanf(p->lastmsg, "Rx: %30s", method_str) == 1) {
03853 if (method_match(SIP_CANCEL, method_str) || method_match(SIP_BYE, method_str)) {
03854 pvt_set_needdestroy(p, "autodestruct");
03855 }
03856 }
03857 return 10000;
03858 } else {
03859
03860 __sip_pretend_ack(p);
03861 }
03862 }
03863
03864
03865 p->autokillid = -1;
03866
03867
03868
03869
03870
03871 owner = sip_pvt_lock_full(p);
03872 if (owner) {
03873 ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
03874 ast_queue_hangup_with_cause(owner, AST_CAUSE_PROTOCOL_ERROR);
03875 ast_channel_unlock(owner);
03876 ast_channel_unref(owner);
03877 } else if (p->refer && !p->alreadygone) {
03878 ast_debug(3, "Finally hanging up channel after transfer: %s\n", p->callid);
03879 stop_media_flows(p);
03880 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
03881 append_history(p, "ReferBYE", "Sending BYE on transferer call leg %s", p->callid);
03882 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
03883 } else {
03884 append_history(p, "AutoDestroy", "%s", p->callid);
03885 ast_debug(3, "Auto destroying SIP dialog '%s'\n", p->callid);
03886 sip_pvt_unlock(p);
03887 dialog_unlink_all(p);
03888 sip_pvt_lock(p);
03889
03890
03891
03892 }
03893
03894 sip_pvt_unlock(p);
03895
03896 dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
03897
03898 return 0;
03899 }
03900
03901
03902
03903
03904 void sip_scheddestroy_final(struct sip_pvt *p, int ms)
03905 {
03906 if (p->final_destruction_scheduled) {
03907 return;
03908 }
03909
03910 sip_scheddestroy(p, ms);
03911 if (p->autokillid != -1) {
03912 p->final_destruction_scheduled = 1;
03913 }
03914 }
03915
03916
03917 void sip_scheddestroy(struct sip_pvt *p, int ms)
03918 {
03919 if (p->final_destruction_scheduled) {
03920 return;
03921 }
03922
03923 if (ms < 0) {
03924 if (p->timer_t1 == 0) {
03925 p->timer_t1 = global_t1;
03926 }
03927 if (p->timer_b == 0) {
03928 p->timer_b = global_timer_b;
03929 }
03930 ms = p->timer_t1 * 64;
03931 }
03932 if (sip_debug_test_pvt(p)) {
03933 ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
03934 }
03935 if (sip_cancel_destroy(p)) {
03936 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
03937 }
03938
03939 if (p->do_history) {
03940 append_history(p, "SchedDestroy", "%d ms", ms);
03941 }
03942 p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, dialog_ref(p, "setting ref as passing into ast_sched_add for __sip_autodestruct"));
03943
03944 if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_schedid > 0) {
03945 stop_session_timer(p);
03946 }
03947 }
03948
03949
03950
03951
03952
03953 int sip_cancel_destroy(struct sip_pvt *p)
03954 {
03955 if (p->final_destruction_scheduled) {
03956 return 0;
03957 }
03958
03959 if (p->autokillid > -1) {
03960 append_history(p, "CancelDestroy", "");
03961 AST_SCHED_DEL_UNREF(sched, p->autokillid, dialog_unref(p, "remove ref for autokillid"));
03962 }
03963 return 0;
03964 }
03965
03966
03967
03968 int __sip_ack(struct sip_pvt *p, uint32_t seqno, int resp, int sipmethod)
03969 {
03970 struct sip_pkt *cur, *prev = NULL;
03971 const char *msg = "Not Found";
03972 int res = FALSE;
03973
03974
03975
03976
03977
03978
03979 if (p->outboundproxy && !p->outboundproxy->force){
03980 ref_proxy(p, NULL);
03981 }
03982
03983 for (cur = p->packets; cur; prev = cur, cur = cur->next) {
03984 if (cur->seqno != seqno || cur->is_resp != resp) {
03985 continue;
03986 }
03987 if (cur->is_resp || cur->method == sipmethod) {
03988 res = TRUE;
03989 msg = "Found";
03990 if (!resp && (seqno == p->pendinginvite)) {
03991 ast_debug(1, "Acked pending invite %u\n", p->pendinginvite);
03992 p->pendinginvite = 0;
03993 }
03994 if (cur->retransid > -1) {
03995 if (sipdebug)
03996 ast_debug(4, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
03997 }
03998
03999
04000
04001
04002
04003
04004
04005
04006
04007
04008
04009
04010
04011
04012
04013
04014 while (cur->retransid > -1 && ast_sched_del(sched, cur->retransid)) {
04015 sip_pvt_unlock(p);
04016 usleep(1);
04017 sip_pvt_lock(p);
04018 }
04019 UNLINK(cur, p->packets, prev);
04020 dialog_unref(cur->owner, "unref pkt cur->owner dialog from sip ack before freeing pkt");
04021 if (cur->data) {
04022 ast_free(cur->data);
04023 }
04024 ast_free(cur);
04025 break;
04026 }
04027 }
04028 ast_debug(1, "Stopping retransmission on '%s' of %s %u: Match %s\n",
04029 p->callid, resp ? "Response" : "Request", seqno, msg);
04030 return res;
04031 }
04032
04033
04034
04035 void __sip_pretend_ack(struct sip_pvt *p)
04036 {
04037 struct sip_pkt *cur = NULL;
04038
04039 while (p->packets) {
04040 int method;
04041 if (cur == p->packets) {
04042 ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
04043 return;
04044 }
04045 cur = p->packets;
04046 method = (cur->method) ? cur->method : find_sip_method(cur->data->str);
04047 __sip_ack(p, cur->seqno, cur->is_resp, method);
04048 }
04049 }
04050
04051
04052 int __sip_semi_ack(struct sip_pvt *p, uint32_t seqno, int resp, int sipmethod)
04053 {
04054 struct sip_pkt *cur;
04055 int res = FALSE;
04056
04057 for (cur = p->packets; cur; cur = cur->next) {
04058 if (cur->seqno == seqno && cur->is_resp == resp &&
04059 (cur->is_resp || method_match(sipmethod, cur->data->str))) {
04060
04061 if (cur->retransid > -1) {
04062 if (sipdebug)
04063 ast_debug(4, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
04064 }
04065 AST_SCHED_DEL(sched, cur->retransid);
04066 res = TRUE;
04067 break;
04068 }
04069 }
04070 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");
04071 return res;
04072 }
04073
04074
04075
04076 static void parse_copy(struct sip_request *dst, const struct sip_request *src)
04077 {
04078 copy_request(dst, src);
04079 parse_request(dst);
04080 }
04081
04082
04083 static void add_blank(struct sip_request *req)
04084 {
04085 if (!req->lines) {
04086
04087 ast_str_append(&req->data, 0, "\r\n");
04088 }
04089 }
04090
04091 static int send_provisional_keepalive_full(struct sip_pvt *pvt, int with_sdp)
04092 {
04093 const char *msg = NULL;
04094 struct ast_channel *chan;
04095 int res = 0;
04096
04097 chan = sip_pvt_lock_full(pvt);
04098
04099 if (!pvt->last_provisional || !strncasecmp(pvt->last_provisional, "100", 3)) {
04100 msg = "183 Session Progress";
04101 }
04102
04103 if (pvt->invitestate < INV_COMPLETED) {
04104 if (with_sdp) {
04105 transmit_response_with_sdp(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq, XMIT_UNRELIABLE, FALSE, FALSE);
04106 } else {
04107 transmit_response(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq);
04108 }
04109 res = PROVIS_KEEPALIVE_TIMEOUT;
04110 }
04111
04112 if (chan) {
04113 ast_channel_unlock(chan);
04114 chan = ast_channel_unref(chan);
04115 }
04116
04117 if (!res) {
04118 pvt->provisional_keepalive_sched_id = -1;
04119 }
04120
04121 sip_pvt_unlock(pvt);
04122
04123 #if 0
04124
04125
04126
04127
04128
04129
04130
04131
04132 if (!res) {
04133 dialog_unref(pvt, "dialog ref for provisional keepalive");
04134 }
04135 #endif
04136
04137 return res;
04138 }
04139
04140 static int send_provisional_keepalive(const void *data) {
04141 struct sip_pvt *pvt = (struct sip_pvt *) data;
04142
04143 return send_provisional_keepalive_full(pvt, 0);
04144 }
04145
04146 static int send_provisional_keepalive_with_sdp(const void *data) {
04147 struct sip_pvt *pvt = (void *)data;
04148
04149 return send_provisional_keepalive_full(pvt, 1);
04150 }
04151
04152 static void update_provisional_keepalive(struct sip_pvt *pvt, int with_sdp)
04153 {
04154 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"));
04155
04156 pvt->provisional_keepalive_sched_id = ast_sched_add(sched, PROVIS_KEEPALIVE_TIMEOUT,
04157 with_sdp ? send_provisional_keepalive_with_sdp : send_provisional_keepalive, dialog_ref(pvt, "Increment refcount to pass dialog pointer to sched callback"));
04158 }
04159
04160
04161 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno)
04162 {
04163 int res;
04164
04165 finalize_content(req);
04166 add_blank(req);
04167 if (sip_debug_test_pvt(p)) {
04168 const struct ast_sockaddr *dst = sip_real_dst(p);
04169
04170 ast_verbose("\n<--- %sTransmitting (%s) to %s --->\n%s\n<------------>\n",
04171 reliable ? "Reliably " : "", sip_nat_mode(p),
04172 ast_sockaddr_stringify(dst),
04173 req->data->str);
04174 }
04175 if (p->do_history) {
04176 struct sip_request tmp = { .rlPart1 = 0, };
04177 parse_copy(&tmp, req);
04178 append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", tmp.data->str, get_header(&tmp, "CSeq"),
04179 (tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? REQ_OFFSET_TO_STR(&tmp, rlPart2) : sip_methods[tmp.method].text);
04180 deinit_req(&tmp);
04181 }
04182
04183
04184 if (p->initreq.method == SIP_INVITE && reliable == XMIT_CRITICAL) {
04185 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"));
04186 }
04187
04188 res = (reliable) ?
04189 __sip_reliable_xmit(p, seqno, 1, req->data, (reliable == XMIT_CRITICAL), req->method) :
04190 __sip_xmit(p, req->data);
04191 deinit_req(req);
04192 if (res > 0) {
04193 return 0;
04194 }
04195 return res;
04196 }
04197
04198
04199
04200
04201
04202
04203 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno)
04204 {
04205 int res;
04206
04207
04208
04209
04210 if (p->outboundproxy) {
04211 p->sa = p->outboundproxy->ip;
04212 }
04213
04214 finalize_content(req);
04215 add_blank(req);
04216 if (sip_debug_test_pvt(p)) {
04217 if (ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT)) {
04218 ast_verbose("%sTransmitting (NAT) to %s:\n%s\n---\n", reliable ? "Reliably " : "", ast_sockaddr_stringify(&p->recv), req->data->str);
04219 } else {
04220 ast_verbose("%sTransmitting (no NAT) to %s:\n%s\n---\n", reliable ? "Reliably " : "", ast_sockaddr_stringify(&p->sa), req->data->str);
04221 }
04222 }
04223 if (p->do_history) {
04224 struct sip_request tmp = { .rlPart1 = 0, };
04225 parse_copy(&tmp, req);
04226 append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", tmp.data->str, get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
04227 deinit_req(&tmp);
04228 }
04229 res = (reliable) ?
04230 __sip_reliable_xmit(p, seqno, 0, req->data, (reliable == XMIT_CRITICAL), req->method) :
04231 __sip_xmit(p, req->data);
04232 deinit_req(req);
04233 return res;
04234 }
04235
04236 static void enable_dsp_detect(struct sip_pvt *p)
04237 {
04238 int features = 0;
04239
04240 if (p->dsp) {
04241 return;
04242 }
04243
04244 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
04245 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
04246 if (p->rtp) {
04247 ast_rtp_instance_dtmf_mode_set(p->rtp, AST_RTP_DTMF_MODE_INBAND);
04248 }
04249 features |= DSP_FEATURE_DIGIT_DETECT;
04250 }
04251
04252 if (ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_CNG)) {
04253 features |= DSP_FEATURE_FAX_DETECT;
04254 }
04255
04256 if (!features) {
04257 return;
04258 }
04259
04260 if (!(p->dsp = ast_dsp_new())) {
04261 return;
04262 }
04263
04264 ast_dsp_set_features(p->dsp, features);
04265 if (global_relaxdtmf) {
04266 ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
04267 }
04268 }
04269
04270 static void disable_dsp_detect(struct sip_pvt *p)
04271 {
04272 if (p->dsp) {
04273 ast_dsp_free(p->dsp);
04274 p->dsp = NULL;
04275 }
04276 }
04277
04278
04279 static int sip_setoption(struct ast_channel *chan, int option, void *data, int datalen)
04280 {
04281 int res = -1;
04282 struct sip_pvt *p = chan->tech_pvt;
04283
04284 if (!p) {
04285 ast_log(LOG_ERROR, "Attempt to Ref a null pointer. sip private structure is gone!\n");
04286 return -1;
04287 }
04288
04289 sip_pvt_lock(p);
04290
04291 switch (option) {
04292 case AST_OPTION_FORMAT_READ:
04293 if (p->rtp) {
04294 res = ast_rtp_instance_set_read_format(p->rtp, *(int *) data);
04295 }
04296 break;
04297 case AST_OPTION_FORMAT_WRITE:
04298 if (p->rtp) {
04299 res = ast_rtp_instance_set_write_format(p->rtp, *(int *) data);
04300 }
04301 break;
04302 case AST_OPTION_MAKE_COMPATIBLE:
04303 if (p->rtp) {
04304 res = ast_rtp_instance_make_compatible(chan, p->rtp, (struct ast_channel *) data);
04305 }
04306 break;
04307 case AST_OPTION_DIGIT_DETECT:
04308 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
04309 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
04310 char *cp = (char *) data;
04311
04312 ast_debug(1, "%sabling digit detection on %s\n", *cp ? "En" : "Dis", chan->name);
04313 if (*cp) {
04314 enable_dsp_detect(p);
04315 } else {
04316 disable_dsp_detect(p);
04317 }
04318 res = 0;
04319 }
04320 break;
04321 case AST_OPTION_SECURE_SIGNALING:
04322 p->req_secure_signaling = *(unsigned int *) data;
04323 res = 0;
04324 break;
04325 case AST_OPTION_SECURE_MEDIA:
04326 ast_set2_flag(&p->flags[1], *(unsigned int *) data, SIP_PAGE2_USE_SRTP);
04327 res = 0;
04328 break;
04329 default:
04330 break;
04331 }
04332
04333 sip_pvt_unlock(p);
04334
04335 return res;
04336 }
04337
04338
04339 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen)
04340 {
04341 int res = -1;
04342 enum ast_t38_state state = T38_STATE_UNAVAILABLE;
04343 struct sip_pvt *p = (struct sip_pvt *) chan->tech_pvt;
04344 char *cp;
04345
04346 sip_pvt_lock(p);
04347
04348 switch (option) {
04349 case AST_OPTION_T38_STATE:
04350
04351 if (*datalen != sizeof(enum ast_t38_state)) {
04352 ast_log(LOG_ERROR, "Invalid datalen for AST_OPTION_T38_STATE option. Expected %d, got %d\n", (int)sizeof(enum ast_t38_state), *datalen);
04353 break;
04354 }
04355
04356
04357 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
04358 switch (p->t38.state) {
04359 case T38_LOCAL_REINVITE:
04360 case T38_PEER_REINVITE:
04361 state = T38_STATE_NEGOTIATING;
04362 break;
04363 case T38_ENABLED:
04364 state = T38_STATE_NEGOTIATED;
04365 break;
04366 default:
04367 state = T38_STATE_UNKNOWN;
04368 }
04369 }
04370
04371 *((enum ast_t38_state *) data) = state;
04372 res = 0;
04373
04374 break;
04375 case AST_OPTION_DIGIT_DETECT:
04376 cp = (char *) data;
04377 *cp = p->dsp ? 1 : 0;
04378 ast_debug(1, "Reporting digit detection %sabled on %s\n", *cp ? "en" : "dis", chan->name);
04379 break;
04380 case AST_OPTION_SECURE_SIGNALING:
04381 *((unsigned int *) data) = p->req_secure_signaling;
04382 res = 0;
04383 break;
04384 case AST_OPTION_SECURE_MEDIA:
04385 *((unsigned int *) data) = ast_test_flag(&p->flags[1], SIP_PAGE2_USE_SRTP) ? 1 : 0;
04386 res = 0;
04387 break;
04388 case AST_OPTION_DEVICE_NAME:
04389 if (p && p->outgoing_call) {
04390 cp = (char *) data;
04391 ast_copy_string(cp, p->dialstring, *datalen);
04392 res = 0;
04393 }
04394
04395
04396
04397 break;
04398 default:
04399 break;
04400 }
04401
04402 sip_pvt_unlock(p);
04403
04404 return res;
04405 }
04406
04407
04408
04409
04410
04411 const char *find_closing_quote(const char *start, const char *lim)
04412 {
04413 char last_char = '\0';
04414 const char *s;
04415 for (s = start; *s && s != lim; last_char = *s++) {
04416 if (*s == '"' && last_char != '\\')
04417 break;
04418 }
04419 return s;
04420 }
04421
04422
04423 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
04424 {
04425 struct sip_pvt *p = chan->tech_pvt;
04426
04427 if (subclass != AST_HTML_URL)
04428 return -1;
04429
04430 ast_string_field_build(p, url, "<%s>;mode=active", data);
04431
04432 if (sip_debug_test_pvt(p))
04433 ast_debug(1, "Send URL %s, state = %d!\n", data, chan->_state);
04434
04435 switch (chan->_state) {
04436 case AST_STATE_RING:
04437 transmit_response(p, "100 Trying", &p->initreq);
04438 break;
04439 case AST_STATE_RINGING:
04440 transmit_response(p, "180 Ringing", &p->initreq);
04441 break;
04442 case AST_STATE_UP:
04443 if (!p->pendinginvite) {
04444 transmit_reinvite_with_sdp(p, FALSE, FALSE);
04445 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
04446 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
04447 }
04448 break;
04449 default:
04450 ast_log(LOG_WARNING, "Don't know how to send URI when state is %d!\n", chan->_state);
04451 }
04452
04453 return 0;
04454 }
04455
04456
04457 static const char *sip_get_callid(struct ast_channel *chan)
04458 {
04459 return chan->tech_pvt ? ((struct sip_pvt *) chan->tech_pvt)->callid : "";
04460 }
04461
04462
04463
04464
04465
04466
04467 static int sip_sendtext(struct ast_channel *ast, const char *text)
04468 {
04469 struct sip_pvt *dialog = ast->tech_pvt;
04470 int debug;
04471
04472 if (!dialog) {
04473 return -1;
04474 }
04475
04476
04477 if (!text) {
04478 return 0;
04479 }
04480 if(!is_method_allowed(&dialog->allowed_methods, SIP_MESSAGE)) {
04481 ast_debug(2, "Trying to send MESSAGE to device that does not support it.\n");
04482 return(0);
04483 }
04484
04485 debug = sip_debug_test_pvt(dialog);
04486 if (debug) {
04487 ast_verbose("Sending text %s on %s\n", text, ast->name);
04488 }
04489
04490 transmit_message_with_text(dialog, text);
04491 return 0;
04492 }
04493
04494
04495
04496
04497
04498
04499 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)
04500 {
04501 char port[10];
04502 char ipaddr[INET6_ADDRSTRLEN];
04503 char regseconds[20];
04504 char *tablename = NULL;
04505 char str_lastms[20];
04506
04507 const char *sysname = ast_config_AST_SYSTEM_NAME;
04508 char *syslabel = NULL;
04509
04510 time_t nowtime = time(NULL) + expirey;
04511 const char *fc = fullcontact ? "fullcontact" : NULL;
04512
04513 int realtimeregs = ast_check_realtime("sipregs");
04514
04515 tablename = realtimeregs ? "sipregs" : "sippeers";
04516
04517
04518 snprintf(str_lastms, sizeof(str_lastms), "%d", lastms);
04519 snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime);
04520 ast_copy_string(ipaddr, ast_sockaddr_isnull(addr) ? "" : ast_sockaddr_stringify_addr(addr), sizeof(ipaddr));
04521 ast_copy_string(port, ast_sockaddr_port(addr) ? ast_sockaddr_stringify_port(addr) : "", sizeof(port));
04522
04523 if (ast_strlen_zero(sysname))
04524 sysname = NULL;
04525 else if (sip_cfg.rtsave_sysname)
04526 syslabel = "regserver";
04527
04528
04529
04530
04531
04532
04533
04534 if (fc) {
04535 ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
04536 "port", port, "regseconds", regseconds,
04537 deprecated_username ? "username" : "defaultuser", defaultuser,
04538 "useragent", useragent, "lastms", str_lastms,
04539 fc, fullcontact, syslabel, sysname, SENTINEL);
04540 } else {
04541 ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
04542 "port", port, "regseconds", regseconds,
04543 "useragent", useragent, "lastms", str_lastms,
04544 deprecated_username ? "username" : "defaultuser", defaultuser,
04545 syslabel, sysname, SENTINEL);
04546 }
04547 }
04548
04549
04550 static void register_peer_exten(struct sip_peer *peer, int onoff)
04551 {
04552 char multi[256];
04553 char *stringp, *ext, *context;
04554 struct pbx_find_info q = { .stacklen = 0 };
04555
04556
04557
04558
04559
04560 if (ast_strlen_zero(sip_cfg.regcontext))
04561 return;
04562
04563 ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
04564 stringp = multi;
04565 while ((ext = strsep(&stringp, "&"))) {
04566 if ((context = strchr(ext, '@'))) {
04567 *context++ = '\0';
04568 if (!ast_context_find(context)) {
04569 ast_log(LOG_WARNING, "Context %s must exist in regcontext= in sip.conf!\n", context);
04570 continue;
04571 }
04572 } else {
04573 context = sip_cfg.regcontext;
04574 }
04575 if (onoff) {
04576 if (!ast_exists_extension(NULL, context, ext, 1, NULL)) {
04577 ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
04578 ast_strdup(peer->name), ast_free_ptr, "SIP");
04579 }
04580 } else if (pbx_find_extension(NULL, NULL, &q, context, ext, 1, NULL, "", E_MATCH)) {
04581 ast_context_remove_extension(context, ext, 1, NULL);
04582 }
04583 }
04584 }
04585
04586
04587 static void destroy_mailbox(struct sip_mailbox *mailbox)
04588 {
04589 if (mailbox->event_sub)
04590 ast_event_unsubscribe(mailbox->event_sub);
04591 ast_free(mailbox);
04592 }
04593
04594
04595 static void clear_peer_mailboxes(struct sip_peer *peer)
04596 {
04597 struct sip_mailbox *mailbox;
04598
04599 while ((mailbox = AST_LIST_REMOVE_HEAD(&peer->mailboxes, entry)))
04600 destroy_mailbox(mailbox);
04601 }
04602
04603 static void sip_destroy_peer_fn(void *peer)
04604 {
04605 sip_destroy_peer(peer);
04606 }
04607
04608
04609 static void sip_destroy_peer(struct sip_peer *peer)
04610 {
04611 ast_debug(3, "Destroying SIP peer %s\n", peer->name);
04612
04613
04614
04615
04616
04617
04618 clear_peer_mailboxes(peer);
04619
04620 if (peer->outboundproxy) {
04621 ao2_ref(peer->outboundproxy, -1);
04622 peer->outboundproxy = NULL;
04623 }
04624
04625
04626 if (peer->call) {
04627 dialog_unlink_all(peer->call);
04628 peer->call = dialog_unref(peer->call, "peer->call is being unset");
04629 }
04630
04631 if (peer->mwipvt) {
04632 dialog_unlink_all(peer->mwipvt);
04633 peer->mwipvt = dialog_unref(peer->mwipvt, "unreffing peer->mwipvt");
04634 }
04635
04636 if (peer->chanvars) {
04637 ast_variables_destroy(peer->chanvars);
04638 peer->chanvars = NULL;
04639 }
04640
04641 register_peer_exten(peer, FALSE);
04642 ast_free_ha(peer->ha);
04643 ast_free_ha(peer->directmediaha);
04644 if (peer->selfdestruct)
04645 ast_atomic_fetchadd_int(&apeerobjs, -1);
04646 else if (!ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && peer->is_realtime) {
04647 ast_atomic_fetchadd_int(&rpeerobjs, -1);
04648 ast_debug(3, "-REALTIME- peer Destroyed. Name: %s. Realtime Peer objects: %d\n", peer->name, rpeerobjs);
04649 } else
04650 ast_atomic_fetchadd_int(&speerobjs, -1);
04651 if (peer->auth) {
04652 ao2_t_ref(peer->auth, -1, "Removing peer authentication");
04653 peer->auth = NULL;
04654 }
04655
04656 if (peer->socket.tcptls_session) {
04657 ao2_ref(peer->socket.tcptls_session, -1);
04658 peer->socket.tcptls_session = NULL;
04659 }
04660
04661 ast_cc_config_params_destroy(peer->cc_params);
04662
04663 ast_string_field_free_memory(peer);
04664 }
04665
04666
04667 static void update_peer(struct sip_peer *p, int expire)
04668 {
04669 int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
04670 if (sip_cfg.peer_rtupdate &&
04671 (p->is_realtime || rtcachefriends)) {
04672 realtime_update_peer(p->name, &p->addr, p->username, p->fullcontact, p->useragent, expire, p->deprecated_username, p->lastms);
04673 }
04674 }
04675
04676 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *cfg)
04677 {
04678 struct ast_variable *var = NULL;
04679 struct ast_flags flags = {0};
04680 char *cat = NULL;
04681 const char *insecure;
04682 while ((cat = ast_category_browse(cfg, cat))) {
04683 insecure = ast_variable_retrieve(cfg, cat, "insecure");
04684 set_insecure_flags(&flags, insecure, -1);
04685 if (ast_test_flag(&flags, SIP_INSECURE_PORT)) {
04686 var = ast_category_root(cfg, cat);
04687 break;
04688 }
04689 }
04690 return var;
04691 }
04692
04693 static struct ast_variable *get_insecure_variable_from_sippeers(const char *column, const char *value)
04694 {
04695 struct ast_config *peerlist;
04696 struct ast_variable *var = NULL;
04697 if ((peerlist = ast_load_realtime_multientry("sippeers", column, value, "insecure LIKE", "%port%", SENTINEL))) {
04698 if ((var = get_insecure_variable_from_config(peerlist))) {
04699
04700
04701 var = ast_variables_dup(var);
04702 }
04703 ast_config_destroy(peerlist);
04704 }
04705 return var;
04706 }
04707
04708
04709
04710
04711
04712
04713 static struct ast_variable *get_insecure_variable_from_sipregs(const char *column, const char *value, struct ast_variable **var)
04714 {
04715 struct ast_variable *varregs = NULL;
04716 struct ast_config *regs, *peers;
04717 char *regscat;
04718 const char *regname;
04719
04720 if (!(regs = ast_load_realtime_multientry("sipregs", column, value, SENTINEL))) {
04721 return NULL;
04722 }
04723
04724
04725 if (!(peers = ast_load_realtime_multientry("sippeers", "insecure LIKE", "%port%", SENTINEL))) {
04726 ast_config_destroy(regs);
04727 return NULL;
04728 }
04729
04730
04731
04732 regscat = NULL;
04733 while ((regscat = ast_category_browse(regs, regscat)) && (regname = ast_variable_retrieve(regs, regscat, "name"))) {
04734 char *peerscat;
04735 const char *peername;
04736
04737 peerscat = NULL;
04738 while ((peerscat = ast_category_browse(peers, peerscat)) && (peername = ast_variable_retrieve(peers, peerscat, "name"))) {
04739 if (!strcasecmp(regname, peername)) {
04740
04741
04742 const char *insecure = ast_variable_retrieve(peers, peerscat, "insecure");
04743 struct ast_flags flags = {0};
04744 set_insecure_flags(&flags, insecure, -1);
04745 if (ast_test_flag(&flags, SIP_INSECURE_PORT)) {
04746
04747 if ((varregs = ast_variables_dup(ast_category_root(regs, regscat)))) {
04748 if (!(*var = ast_variables_dup(ast_category_root(peers, peerscat)))) {
04749 ast_variables_destroy(varregs);
04750 varregs = NULL;
04751 }
04752 }
04753 goto done;
04754 }
04755 }
04756 }
04757 }
04758
04759 done:
04760 ast_config_destroy(regs);
04761 ast_config_destroy(peers);
04762 return varregs;
04763 }
04764
04765 static const char *get_name_from_variable(const struct ast_variable *var)
04766 {
04767
04768
04769
04770
04771
04772
04773
04774
04775 const struct ast_variable *tmp;
04776 for (tmp = var; tmp; tmp = tmp->next) {
04777 if (!strcasecmp(tmp->name, "name")) {
04778 if (!ast_strlen_zero(tmp->value)) {
04779 return tmp->value;
04780 }
04781 break;
04782 }
04783 }
04784 return NULL;
04785 }
04786
04787
04788
04789 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)
04790 {
04791
04792 if ((*var = ast_load_realtime("sippeers", "name", *name, "host", "dynamic", SENTINEL))) {
04793 ;
04794
04795 } else if (addr && !(*var = ast_load_realtime("sippeers", "name", *name, "host", ipaddr, SENTINEL))) {
04796 ;
04797
04798 } else if ((*var = ast_load_realtime("sippeers", "name", *name, SENTINEL))) {
04799
04800
04801
04802
04803
04804
04805 if (addr) {
04806 struct ast_variable *tmp;
04807 for (tmp = *var; tmp; tmp = tmp->next) {
04808 if (!strcasecmp(tmp->name, "host")) {
04809 struct ast_sockaddr *addrs = NULL;
04810
04811 if (ast_sockaddr_resolve(&addrs,
04812 tmp->value,
04813 PARSE_PORT_FORBID,
04814 get_address_family_filter(&bindaddr)) <= 0 ||
04815 ast_sockaddr_cmp(&addrs[0], addr)) {
04816
04817 ast_variables_destroy(*var);
04818 *var = NULL;
04819 }
04820 ast_free(addrs);
04821 break;
04822 }
04823 }
04824 }
04825 }
04826
04827
04828 if (*var) {
04829 if (varregs) {
04830 *varregs = ast_load_realtime("sipregs", "name", *name, SENTINEL);
04831 }
04832 return 1;
04833 }
04834 return 0;
04835 }
04836
04837
04838
04839
04840
04841
04842
04843 static struct ast_variable *realtime_peer_get_sippeer_helper(const char **name, struct ast_variable **varregs) {
04844 struct ast_variable *var = NULL;
04845 const char *old_name = *name;
04846 *name = get_name_from_variable(*varregs);
04847 if (!*name || !(var = ast_load_realtime("sippeers", "name", *name, SENTINEL))) {
04848 if (!*name) {
04849 ast_log(LOG_WARNING, "Found sipreg but it has no name\n");
04850 }
04851 ast_variables_destroy(*varregs);
04852 *varregs = NULL;
04853 *name = old_name;
04854 }
04855 return var;
04856 }
04857
04858
04859
04860
04861 static int realtime_peer_by_addr(const char **name, struct ast_sockaddr *addr, const char *ipaddr, struct ast_variable **var, struct ast_variable **varregs)
04862 {
04863 char portstring[6];
04864 ast_copy_string(portstring, ast_sockaddr_stringify_port(addr), sizeof(portstring));
04865
04866
04867 *name = NULL;
04868
04869
04870 if ((*var = ast_load_realtime("sippeers", "host", ipaddr, "port", portstring, SENTINEL))) {
04871 ;
04872
04873 } else if (varregs && (*varregs = ast_load_realtime("sipregs", "ipaddr", ipaddr, "port", portstring, SENTINEL)) &&
04874 (*var = realtime_peer_get_sippeer_helper(name, varregs))) {
04875 ;
04876
04877 } else if (!varregs && (*var = ast_load_realtime("sippeers", "ipaddr", ipaddr, "port", portstring, SENTINEL))) {
04878 ;
04879
04880 } else if ((*var = get_insecure_variable_from_sippeers("host", ipaddr))) {
04881 ;
04882
04883
04884
04885
04886 } else if (varregs && (*varregs = get_insecure_variable_from_sipregs("ipaddr", ipaddr, var))) {
04887 ;
04888
04889 } else if (!varregs && (*var = get_insecure_variable_from_sippeers("ipaddr", ipaddr))) {
04890 ;
04891 }
04892
04893
04894 if (!*var) {
04895 return 0;
04896 }
04897
04898
04899
04900
04901 if (!*name && !(*name = get_name_from_variable(*var))) {
04902 ast_log(LOG_WARNING, "Found peer for IP %s but it has no name\n", ipaddr);
04903 ast_variables_destroy(*var);
04904 *var = NULL;
04905 if (varregs && *varregs) {
04906 ast_variables_destroy(*varregs);
04907 *varregs = NULL;
04908 }
04909 return 0;
04910 }
04911
04912
04913
04914
04915 if (varregs && !*varregs) {
04916 *varregs = ast_load_realtime("sipregs", "name", *name, SENTINEL);
04917 }
04918 return 1;
04919 }
04920
04921
04922
04923
04924
04925
04926
04927
04928
04929
04930 static struct sip_peer *realtime_peer(const char *newpeername, struct ast_sockaddr *addr, int devstate_only, int which_objects)
04931 {
04932 struct sip_peer *peer = NULL;
04933 struct ast_variable *var = NULL;
04934 struct ast_variable *varregs = NULL;
04935 char ipaddr[INET6_ADDRSTRLEN];
04936 int realtimeregs = ast_check_realtime("sipregs");
04937
04938 if (addr) {
04939 ast_copy_string(ipaddr, ast_sockaddr_stringify_addr(addr), sizeof(ipaddr));
04940 } else {
04941 ipaddr[0] = '\0';
04942 }
04943
04944 if (newpeername && realtime_peer_by_name(&newpeername, addr, ipaddr, &var, realtimeregs ? &varregs : NULL)) {
04945 ;
04946 } else if (addr && realtime_peer_by_addr(&newpeername, addr, ipaddr, &var, realtimeregs ? &varregs : NULL)) {
04947 ;
04948 } else {
04949 return NULL;
04950 }
04951
04952
04953
04954 if (which_objects == FINDUSERS) {
04955 struct ast_variable *tmp;
04956 for (tmp = var; tmp; tmp = tmp->next) {
04957 if (!strcasecmp(tmp->name, "type") && (!strcasecmp(tmp->value, "peer"))) {
04958 goto cleanup;
04959 }
04960 }
04961 }
04962
04963
04964 peer = build_peer(newpeername, var, varregs, TRUE, devstate_only);
04965 if (!peer) {
04966 goto cleanup;
04967 }
04968
04969 ast_debug(3, "-REALTIME- loading peer from database to memory. Name: %s. Peer objects: %d\n", peer->name, rpeerobjs);
04970
04971 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && !devstate_only) {
04972
04973 ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
04974 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
04975 AST_SCHED_REPLACE_UNREF(peer->expire, sched, sip_cfg.rtautoclear * 1000, expire_register, peer,
04976 unref_peer(_data, "remove registration ref"),
04977 unref_peer(peer, "remove registration ref"),
04978 ref_peer(peer, "add registration ref"));
04979 }
04980 ao2_t_link(peers, peer, "link peer into peers table");
04981 if (!ast_sockaddr_isnull(&peer->addr)) {
04982 ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
04983 }
04984 }
04985 peer->is_realtime = 1;
04986
04987 cleanup:
04988 ast_variables_destroy(var);
04989 ast_variables_destroy(varregs);
04990 return peer;
04991 }
04992
04993
04994 static int find_by_name(void *obj, void *arg, void *data, int flags)
04995 {
04996 struct sip_peer *search = obj, *match = arg;
04997 int *which_objects = data;
04998
04999
05000 if (strcmp(search->name, match->name)) {
05001 return 0;
05002 }
05003
05004 switch (*which_objects) {
05005 case FINDUSERS:
05006 if (!(search->type & SIP_TYPE_USER)) {
05007 return 0;
05008 }
05009 break;
05010 case FINDPEERS:
05011 if (!(search->type & SIP_TYPE_PEER)) {
05012 return 0;
05013 }
05014 break;
05015 case FINDALLDEVICES:
05016 break;
05017 }
05018
05019 return CMP_MATCH | CMP_STOP;
05020 }
05021
05022
05023
05024
05025
05026
05027
05028
05029
05030
05031
05032
05033
05034
05035 static struct sip_peer *find_peer(const char *peer, struct ast_sockaddr *addr, int realtime, int which_objects, int devstate_only, int transport)
05036 {
05037 struct sip_peer *p = NULL;
05038 struct sip_peer tmp_peer;
05039
05040 if (peer) {
05041 ast_copy_string(tmp_peer.name, peer, sizeof(tmp_peer.name));
05042 p = ao2_t_callback_data(peers, OBJ_POINTER, find_by_name, &tmp_peer, &which_objects, "ao2_find in peers table");
05043 } else if (addr) {
05044 ast_sockaddr_copy(&tmp_peer.addr, addr);
05045 tmp_peer.flags[0].flags = 0;
05046 tmp_peer.transports = transport;
05047 p = ao2_t_find(peers_by_ip, &tmp_peer, OBJ_POINTER, "ao2_find in peers_by_ip table");
05048 if (!p) {
05049 ast_set_flag(&tmp_peer.flags[0], SIP_INSECURE_PORT);
05050 p = ao2_t_find(peers_by_ip, &tmp_peer, OBJ_POINTER, "ao2_find in peers_by_ip table 2");
05051 if (p) {
05052 return p;
05053 }
05054 }
05055 }
05056
05057 if (!p && (realtime || devstate_only)) {
05058 p = realtime_peer(peer, addr, devstate_only, which_objects);
05059 if (p) {
05060 switch (which_objects) {
05061 case FINDUSERS:
05062 if (!(p->type & SIP_TYPE_USER)) {
05063 unref_peer(p, "Wrong type of realtime SIP endpoint");
05064 return NULL;
05065 }
05066 break;
05067 case FINDPEERS:
05068 if (!(p->type & SIP_TYPE_PEER)) {
05069 unref_peer(p, "Wrong type of realtime SIP endpoint");
05070 return NULL;
05071 }
05072 break;
05073 case FINDALLDEVICES:
05074 break;
05075 }
05076 }
05077 }
05078
05079 return p;
05080 }
05081
05082
05083 static void do_setnat(struct sip_pvt *p)
05084 {
05085 const char *mode;
05086 int natflags;
05087
05088 natflags = ast_test_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP);
05089 mode = natflags ? "On" : "Off";
05090
05091 if (p->rtp) {
05092 ast_debug(1, "Setting NAT on RTP to %s\n", mode);
05093 ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_NAT, natflags);
05094 }
05095 if (p->vrtp) {
05096 ast_debug(1, "Setting NAT on VRTP to %s\n", mode);
05097 ast_rtp_instance_set_prop(p->vrtp, AST_RTP_PROPERTY_NAT, natflags);
05098 }
05099 if (p->udptl) {
05100 ast_debug(1, "Setting NAT on UDPTL to %s\n", mode);
05101 ast_udptl_setnat(p->udptl, natflags);
05102 }
05103 if (p->trtp) {
05104 ast_debug(1, "Setting NAT on TRTP to %s\n", mode);
05105 ast_rtp_instance_set_prop(p->trtp, AST_RTP_PROPERTY_NAT, natflags);
05106 }
05107 }
05108
05109
05110 static void change_t38_state(struct sip_pvt *p, int state)
05111 {
05112 int old = p->t38.state;
05113 struct ast_channel *chan = p->owner;
05114 struct ast_control_t38_parameters parameters = { .request_response = 0 };
05115
05116
05117 if (old == state)
05118 return;
05119
05120 p->t38.state = state;
05121 ast_debug(2, "T38 state changed to %d on channel %s\n", p->t38.state, chan ? chan->name : "<none>");
05122
05123
05124 if (!chan)
05125 return;
05126
05127
05128 switch (state) {
05129 case T38_PEER_REINVITE:
05130 parameters = p->t38.their_parms;
05131 parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
05132 parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
05133 ast_udptl_set_tag(p->udptl, "%s", chan->name);
05134 break;
05135 case T38_ENABLED:
05136 parameters = p->t38.their_parms;
05137 parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
05138 parameters.request_response = AST_T38_NEGOTIATED;
05139 ast_udptl_set_tag(p->udptl, "%s", chan->name);
05140 break;
05141 case T38_DISABLED:
05142 if (old == T38_ENABLED) {
05143 parameters.request_response = AST_T38_TERMINATED;
05144 } else if (old == T38_LOCAL_REINVITE) {
05145 parameters.request_response = AST_T38_REFUSED;
05146 }
05147 break;
05148 case T38_LOCAL_REINVITE:
05149
05150 break;
05151 }
05152
05153
05154 if (parameters.request_response)
05155 ast_queue_control_data(chan, AST_CONTROL_T38_PARAMETERS, ¶meters, sizeof(parameters));
05156 }
05157
05158
05159 static void set_t38_capabilities(struct sip_pvt *p)
05160 {
05161 if (p->udptl) {
05162 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY) {
05163 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
05164 } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_FEC) {
05165 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
05166 } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL) {
05167 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
05168 }
05169 }
05170 }
05171
05172 static void copy_socket_data(struct sip_socket *to_sock, const struct sip_socket *from_sock)
05173 {
05174 if (to_sock->tcptls_session) {
05175 ao2_ref(to_sock->tcptls_session, -1);
05176 to_sock->tcptls_session = NULL;
05177 }
05178
05179 if (from_sock->tcptls_session) {
05180 ao2_ref(from_sock->tcptls_session, +1);
05181 }
05182
05183 *to_sock = *from_sock;
05184 }
05185
05186
05187
05188
05189 static int dialog_initialize_rtp(struct sip_pvt *dialog)
05190 {
05191 struct ast_sockaddr bindaddr_tmp;
05192
05193 if (!sip_methods[dialog->method].need_rtp) {
05194 return 0;
05195 }
05196
05197 ast_sockaddr_copy(&bindaddr_tmp, &bindaddr);
05198 if (!(dialog->rtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr_tmp, NULL))) {
05199 return -1;
05200 }
05201
05202 if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS) ||
05203 (ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT) && (dialog->capability & AST_FORMAT_VIDEO_MASK))) {
05204 if (!(dialog->vrtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr_tmp, NULL))) {
05205 return -1;
05206 }
05207 ast_rtp_instance_set_timeout(dialog->vrtp, dialog->rtptimeout);
05208 ast_rtp_instance_set_hold_timeout(dialog->vrtp, dialog->rtpholdtimeout);
05209 ast_rtp_instance_set_keepalive(dialog->vrtp, dialog->rtpkeepalive);
05210
05211 ast_rtp_instance_set_prop(dialog->vrtp, AST_RTP_PROPERTY_RTCP, 1);
05212 }
05213
05214 if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_TEXTSUPPORT)) {
05215 if (!(dialog->trtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr_tmp, NULL))) {
05216 return -1;
05217 }
05218
05219 ast_rtp_instance_set_keepalive(dialog->trtp, dialog->rtpkeepalive);
05220
05221 ast_rtp_instance_set_prop(dialog->trtp, AST_RTP_PROPERTY_RTCP, 1);
05222 }
05223
05224 ast_rtp_instance_set_timeout(dialog->rtp, dialog->rtptimeout);
05225 ast_rtp_instance_set_hold_timeout(dialog->rtp, dialog->rtpholdtimeout);
05226 ast_rtp_instance_set_keepalive(dialog->rtp, dialog->rtpkeepalive);
05227
05228 ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_RTCP, 1);
05229 ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
05230 ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
05231
05232 ast_rtp_instance_set_qos(dialog->rtp, global_tos_audio, global_cos_audio, "SIP RTP");
05233
05234 do_setnat(dialog);
05235
05236 return 0;
05237 }
05238
05239
05240
05241
05242
05243
05244
05245
05246 static int create_addr_from_peer(struct sip_pvt *dialog, struct sip_peer *peer)
05247 {
05248 struct sip_auth_container *credentials;
05249
05250
05251
05252
05253 if (dialog->socket.type && check_request_transport(peer, dialog))
05254 return -1;
05255 copy_socket_data(&dialog->socket, &peer->socket);
05256
05257 if (!(ast_sockaddr_isnull(&peer->addr) && ast_sockaddr_isnull(&peer->defaddr)) &&
05258 (!peer->maxms || ((peer->lastms >= 0) && (peer->lastms <= peer->maxms)))) {
05259 dialog->sa = ast_sockaddr_isnull(&peer->addr) ? peer->defaddr : peer->addr;
05260 dialog->recv = dialog->sa;
05261 } else
05262 return -1;
05263
05264
05265 ast_copy_flags(&dialog->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
05266 ast_copy_flags(&dialog->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
05267 ast_copy_flags(&dialog->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
05268 dialog->capability = peer->capability;
05269 dialog->prefs = peer->prefs;
05270 dialog->amaflags = peer->amaflags;
05271
05272 ast_string_field_set(dialog, engine, peer->engine);
05273
05274 dialog->rtptimeout = peer->rtptimeout;
05275 dialog->rtpholdtimeout = peer->rtpholdtimeout;
05276 dialog->rtpkeepalive = peer->rtpkeepalive;
05277 if (dialog_initialize_rtp(dialog)) {
05278 return -1;
05279 }
05280
05281 if (dialog->rtp) {
05282 ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
05283 ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
05284
05285 ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(dialog->rtp), dialog->rtp, &dialog->prefs);
05286 dialog->autoframing = peer->autoframing;
05287 }
05288
05289
05290 ast_string_field_set(dialog, peername, peer->name);
05291 ast_string_field_set(dialog, authname, peer->username);
05292 ast_string_field_set(dialog, username, peer->username);
05293 ast_string_field_set(dialog, peersecret, peer->secret);
05294 ast_string_field_set(dialog, peermd5secret, peer->md5secret);
05295 ast_string_field_set(dialog, mohsuggest, peer->mohsuggest);
05296 ast_string_field_set(dialog, mohinterpret, peer->mohinterpret);
05297 ast_string_field_set(dialog, tohost, peer->tohost);
05298 ast_string_field_set(dialog, fullcontact, peer->fullcontact);
05299 ast_string_field_set(dialog, accountcode, peer->accountcode);
05300 ast_string_field_set(dialog, context, peer->context);
05301 ast_string_field_set(dialog, cid_num, peer->cid_num);
05302 ast_string_field_set(dialog, cid_name, peer->cid_name);
05303 ast_string_field_set(dialog, cid_tag, peer->cid_tag);
05304 ast_string_field_set(dialog, mwi_from, peer->mwi_from);
05305 if (!ast_strlen_zero(peer->parkinglot)) {
05306 ast_string_field_set(dialog, parkinglot, peer->parkinglot);
05307 }
05308 ast_string_field_set(dialog, engine, peer->engine);
05309 ref_proxy(dialog, obproxy_get(dialog, peer));
05310 dialog->callgroup = peer->callgroup;
05311 dialog->pickupgroup = peer->pickupgroup;
05312 dialog->allowtransfer = peer->allowtransfer;
05313 dialog->jointnoncodeccapability = dialog->noncodeccapability;
05314
05315
05316 ao2_lock(peer);
05317 credentials = peer->auth;
05318 if (credentials) {
05319 ao2_t_ref(credentials, +1, "Ref peer auth for dialog");
05320 }
05321 ao2_unlock(peer);
05322 ao2_lock(dialog);
05323 if (dialog->peerauth) {
05324 ao2_t_ref(dialog->peerauth, -1, "Unref old dialog peer auth");
05325 }
05326 dialog->peerauth = credentials;
05327 ao2_unlock(dialog);
05328
05329 dialog->maxcallbitrate = peer->maxcallbitrate;
05330 dialog->disallowed_methods = peer->disallowed_methods;
05331 ast_cc_copy_config_params(dialog->cc_params, peer->cc_params);
05332 if (ast_strlen_zero(dialog->tohost))
05333 ast_string_field_set(dialog, tohost, ast_sockaddr_stringify_host_remote(&dialog->sa));
05334 if (!ast_strlen_zero(peer->fromdomain)) {
05335 ast_string_field_set(dialog, fromdomain, peer->fromdomain);
05336 if (!dialog->initreq.headers) {
05337 char *new_callid;
05338 char *tmpcall = ast_strdupa(dialog->callid);
05339
05340 new_callid = strchr(tmpcall, '@');
05341 if (new_callid) {
05342 int callid_size;
05343
05344 *new_callid = '\0';
05345
05346
05347 callid_size = strlen(tmpcall) + strlen(peer->fromdomain) + 2;
05348 new_callid = alloca(callid_size);
05349 snprintf(new_callid, callid_size, "%s@%s", tmpcall, peer->fromdomain);
05350 change_callid_pvt(dialog, new_callid);
05351 }
05352 }
05353 }
05354 if (!ast_strlen_zero(peer->fromuser))
05355 ast_string_field_set(dialog, fromuser, peer->fromuser);
05356 if (!ast_strlen_zero(peer->language))
05357 ast_string_field_set(dialog, language, peer->language);
05358
05359
05360
05361
05362 if (peer->maxms && peer->lastms)
05363 dialog->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
05364 else
05365 dialog->timer_t1 = peer->timer_t1;
05366
05367
05368
05369 if (peer->timer_b)
05370 dialog->timer_b = peer->timer_b;
05371 else
05372 dialog->timer_b = 64 * dialog->timer_t1;
05373
05374 if ((ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
05375 (ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
05376 dialog->noncodeccapability |= AST_RTP_DTMF;
05377 else
05378 dialog->noncodeccapability &= ~AST_RTP_DTMF;
05379 dialog->directmediaha = ast_duplicate_ha_list(peer->directmediaha);
05380 if (peer->call_limit)
05381 ast_set_flag(&dialog->flags[0], SIP_CALL_LIMIT);
05382 if (!dialog->portinuri)
05383 dialog->portinuri = peer->portinuri;
05384 dialog->chanvars = copy_vars(peer->chanvars);
05385 if (peer->fromdomainport)
05386 dialog->fromdomainport = peer->fromdomainport;
05387
05388 return 0;
05389 }
05390
05391
05392 static inline int default_sip_port(enum sip_transport type)
05393 {
05394 return type == SIP_TRANSPORT_TLS ? STANDARD_TLS_PORT : STANDARD_SIP_PORT;
05395 }
05396
05397
05398
05399
05400 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct ast_sockaddr *addr, int newdialog, struct ast_sockaddr *remote_address)
05401 {
05402 struct sip_peer *peer;
05403 char *peername, *peername2, *hostn;
05404 char host[MAXHOSTNAMELEN];
05405 char service[MAXHOSTNAMELEN];
05406 int srv_ret = 0;
05407 int tportno;
05408
05409 AST_DECLARE_APP_ARGS(hostport,
05410 AST_APP_ARG(host);
05411 AST_APP_ARG(port);
05412 );
05413
05414 peername = ast_strdupa(opeer);
05415 peername2 = ast_strdupa(opeer);
05416 AST_NONSTANDARD_RAW_ARGS(hostport, peername2, ':');
05417
05418 if (hostport.port)
05419 dialog->portinuri = 1;
05420
05421 dialog->timer_t1 = global_t1;
05422 dialog->timer_b = global_timer_b;
05423 peer = find_peer(peername, NULL, TRUE, FINDPEERS, FALSE, 0);
05424
05425 if (peer) {
05426 int res;
05427 if (newdialog) {
05428 set_socket_transport(&dialog->socket, 0);
05429 }
05430 res = create_addr_from_peer(dialog, peer);
05431 if (!ast_sockaddr_isnull(remote_address)) {
05432 ast_sockaddr_copy(&dialog->sa, remote_address);
05433 }
05434 dialog->relatedpeer = ref_peer(peer, "create_addr: setting dialog's relatedpeer pointer");
05435 unref_peer(peer, "create_addr: unref peer from find_peer hashtab lookup");
05436 return res;
05437 } else if (ast_check_digits(peername)) {
05438
05439
05440
05441 ast_log(LOG_WARNING, "Purely numeric hostname (%s), and not a peer--rejecting!\n", peername);
05442 return -1;
05443 } else {
05444 dialog->rtptimeout = global_rtptimeout;
05445 dialog->rtpholdtimeout = global_rtpholdtimeout;
05446 dialog->rtpkeepalive = global_rtpkeepalive;
05447 if (dialog_initialize_rtp(dialog)) {
05448 return -1;
05449 }
05450 }
05451
05452 ast_string_field_set(dialog, tohost, hostport.host);
05453 dialog->allowed_methods &= ~sip_cfg.disallowed_methods;
05454
05455
05456 ref_proxy(dialog, obproxy_get(dialog, NULL));
05457
05458 if (addr) {
05459
05460 ast_sockaddr_copy(&dialog->sa, addr);
05461 } else {
05462
05463
05464
05465
05466
05467
05468 hostn = peername;
05469
05470
05471
05472 if (!hostport.port && sip_cfg.srvlookup) {
05473 snprintf(service, sizeof(service), "_%s._%s.%s",
05474 get_srv_service(dialog->socket.type),
05475 get_srv_protocol(dialog->socket.type), peername);
05476 if ((srv_ret = ast_get_srv(NULL, host, sizeof(host), &tportno,
05477 service)) > 0) {
05478 hostn = host;
05479 }
05480 }
05481
05482 if (ast_sockaddr_resolve_first(&dialog->sa, hostn, 0)) {
05483 ast_log(LOG_WARNING, "No such host: %s\n", peername);
05484 return -1;
05485 }
05486
05487 if (srv_ret > 0) {
05488 ast_sockaddr_set_port(&dialog->sa, tportno);
05489 }
05490 }
05491
05492 if (!dialog->socket.type)
05493 set_socket_transport(&dialog->socket, SIP_TRANSPORT_UDP);
05494 if (!dialog->socket.port) {
05495 dialog->socket.port = htons(ast_sockaddr_port(&bindaddr));
05496 }
05497
05498 if (!ast_sockaddr_port(&dialog->sa)) {
05499 ast_sockaddr_set_port(&dialog->sa, default_sip_port(dialog->socket.type));
05500 }
05501 ast_sockaddr_copy(&dialog->recv, &dialog->sa);
05502 return 0;
05503 }
05504
05505
05506
05507
05508 static int auto_congest(const void *arg)
05509 {
05510 struct sip_pvt *p = (struct sip_pvt *)arg;
05511
05512 sip_pvt_lock(p);
05513 p->initid = -1;
05514 if (p->owner) {
05515
05516 if (!ast_channel_trylock(p->owner)) {
05517 append_history(p, "Cong", "Auto-congesting (timer)");
05518 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
05519 ast_channel_unlock(p->owner);
05520 }
05521
05522
05523 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
05524 }
05525 sip_pvt_unlock(p);
05526 dialog_unref(p, "unreffing arg passed into auto_congest callback (p->initid)");
05527 return 0;
05528 }
05529
05530
05531
05532
05533 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
05534 {
05535 int res;
05536 struct sip_pvt *p = ast->tech_pvt;
05537 struct varshead *headp;
05538 struct ast_var_t *current;
05539 const char *referer = NULL;
05540 int cc_core_id;
05541 char uri[SIPBUFSIZE] = "";
05542
05543 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
05544 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
05545 return -1;
05546 }
05547
05548 if (ast_cc_is_recall(ast, &cc_core_id, "SIP")) {
05549 char device_name[AST_CHANNEL_NAME];
05550 struct ast_cc_monitor *recall_monitor;
05551 struct sip_monitor_instance *monitor_instance;
05552 ast_channel_get_device_name(ast, device_name, sizeof(device_name));
05553 if ((recall_monitor = ast_cc_get_monitor_by_recall_core_id(cc_core_id, device_name))) {
05554 monitor_instance = recall_monitor->private_data;
05555 ast_copy_string(uri, monitor_instance->notify_uri, sizeof(uri));
05556 ao2_t_ref(recall_monitor, -1, "Got the URI we need so unreffing monitor");
05557 }
05558 }
05559
05560
05561 headp=&ast->varshead;
05562 AST_LIST_TRAVERSE(headp, current, entries) {
05563
05564 if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
05565 p->options->vxml_url = ast_var_value(current);
05566 } else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
05567 p->options->uri_options = ast_var_value(current);
05568 } else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
05569
05570 p->options->addsipheaders = 1;
05571 } else if (!strcasecmp(ast_var_name(current), "SIPFROMDOMAIN")) {
05572 ast_string_field_set(p, fromdomain, ast_var_value(current));
05573 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER")) {
05574
05575 p->options->transfer = 1;
05576 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REFERER")) {
05577
05578 referer = ast_var_value(current);
05579 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REPLACES")) {
05580
05581 p->options->replaces = ast_var_value(current);
05582 } else if (!strcasecmp(ast_var_name(current), "SIP_MAX_FORWARDS")) {
05583 if (sscanf(ast_var_value(current), "%d", &(p->maxforwards)) != 1) {
05584 ast_log(LOG_WARNING, "The SIP_MAX_FORWARDS channel variable is not a valid integer.");
05585 }
05586 }
05587 }
05588
05589
05590 if (p->req_secure_signaling && p->socket.type != SIP_TRANSPORT_TLS) {
05591 ast_log(LOG_WARNING, "Encrypted signaling is required\n");
05592 ast->hangupcause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
05593 return -1;
05594 }
05595
05596 if (ast_test_flag(&p->flags[1], SIP_PAGE2_USE_SRTP)) {
05597 if (ast_test_flag(&p->flags[0], SIP_REINVITE)) {
05598 ast_debug(1, "Direct media not possible when using SRTP, ignoring canreinvite setting\n");
05599 ast_clear_flag(&p->flags[0], SIP_REINVITE);
05600 }
05601
05602 if (p->rtp && !p->srtp && setup_srtp(&p->srtp) < 0) {
05603 ast_log(LOG_WARNING, "SRTP audio setup failed\n");
05604 return -1;
05605 }
05606
05607 if (p->vrtp && !p->vsrtp && setup_srtp(&p->vsrtp) < 0) {
05608 ast_log(LOG_WARNING, "SRTP video setup failed\n");
05609 return -1;
05610 }
05611
05612 if (p->trtp && !p->tsrtp && setup_srtp(&p->tsrtp) < 0) {
05613 ast_log(LOG_WARNING, "SRTP text setup failed\n");
05614 return -1;
05615 }
05616 }
05617
05618 res = 0;
05619 ast_set_flag(&p->flags[0], SIP_OUTGOING);
05620
05621
05622
05623
05624 ast_clear_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_T38);
05625
05626 if (p->options->transfer) {
05627 char buf[SIPBUFSIZE/2];
05628
05629 if (referer) {
05630 if (sipdebug)
05631 ast_debug(3, "Call for %s transfered by %s\n", p->username, referer);
05632 snprintf(buf, sizeof(buf)-1, "-> %s (via %s)", p->cid_name, referer);
05633 } else
05634 snprintf(buf, sizeof(buf)-1, "-> %s", p->cid_name);
05635 ast_string_field_set(p, cid_name, buf);
05636 }
05637 ast_debug(1, "Outgoing Call for %s\n", p->username);
05638
05639 res = update_call_counter(p, INC_CALL_RINGING);
05640
05641 if (res == -1) {
05642 ast->hangupcause = AST_CAUSE_USER_BUSY;
05643 return res;
05644 }
05645 p->callingpres = ast_party_id_presentation(&ast->caller.id);
05646 p->jointcapability = ast_rtp_instance_available_formats(p->rtp, p->capability, p->prefcodec);
05647 p->jointnoncodeccapability = p->noncodeccapability;
05648
05649
05650 if (!(p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
05651 ast_log(LOG_WARNING, "No audio format found to offer. Cancelling call to %s\n", p->username);
05652 res = -1;
05653 } else {
05654 int xmitres;
05655 struct ast_party_connected_line connected;
05656 struct ast_set_party_connected_line update_connected;
05657
05658 sip_pvt_lock(p);
05659
05660
05661 memset(&update_connected, 0, sizeof(update_connected));
05662 ast_party_connected_line_init(&connected);
05663 if (!ast_strlen_zero(p->cid_num)
05664 || (p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
05665 update_connected.id.number = 1;
05666 connected.id.number.valid = 1;
05667 connected.id.number.str = (char *) p->cid_num;
05668 connected.id.number.presentation = p->callingpres;
05669 }
05670 if (!ast_strlen_zero(p->cid_name)
05671 || (p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
05672 update_connected.id.name = 1;
05673 connected.id.name.valid = 1;
05674 connected.id.name.str = (char *) p->cid_name;
05675 connected.id.name.presentation = p->callingpres;
05676 }
05677 if (update_connected.id.number || update_connected.id.name) {
05678 connected.id.tag = (char *) p->cid_tag;
05679 connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
05680 ast_channel_queue_connected_line_update(ast, &connected, &update_connected);
05681 }
05682
05683 xmitres = transmit_invite(p, SIP_INVITE, 1, 2, uri);
05684 sip_pvt_unlock(p);
05685 if (xmitres == XMIT_ERROR)
05686 return -1;
05687 p->invitestate = INV_CALLING;
05688
05689
05690 AST_SCHED_REPLACE_UNREF(p->initid, sched, p->timer_b, auto_congest, p,
05691 dialog_unref(_data, "dialog ptr dec when SCHED_REPLACE del op succeeded"),
05692 dialog_unref(p, "dialog ptr dec when SCHED_REPLACE add failed"),
05693 dialog_ref(p, "dialog ptr inc when SCHED_REPLACE add succeeded") );
05694 }
05695 return res;
05696 }
05697
05698
05699
05700 static void sip_registry_destroy(struct sip_registry *reg)
05701 {
05702
05703 ast_debug(3, "Destroying registry entry for %s@%s\n", reg->username, reg->hostname);
05704
05705 if (reg->call) {
05706
05707
05708 reg->call->registry = registry_unref(reg->call->registry, "destroy reg->call->registry");
05709 ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", reg->username, reg->hostname);
05710 dialog_unlink_all(reg->call);
05711 reg->call = dialog_unref(reg->call, "unref reg->call");
05712
05713 }
05714 AST_SCHED_DEL(sched, reg->expire);
05715 AST_SCHED_DEL(sched, reg->timeout);
05716
05717 ast_string_field_free_memory(reg);
05718 ast_atomic_fetchadd_int(®objs, -1);
05719 ast_free(reg);
05720 }
05721
05722
05723 static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi)
05724 {
05725 if (mwi->call) {
05726 mwi->call->mwi = NULL;
05727 sip_destroy(mwi->call);
05728 }
05729
05730 AST_SCHED_DEL(sched, mwi->resub);
05731 ast_string_field_free_memory(mwi);
05732 ast_free(mwi);
05733 }
05734
05735
05736 void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist)
05737 {
05738 struct sip_request *req;
05739
05740
05741 if (p->stimer) {
05742 p->stimer->quit_flag = 1;
05743 stop_session_timer(p);
05744 ast_free(p->stimer);
05745 p->stimer = NULL;
05746 }
05747
05748 if (sip_debug_test_pvt(p))
05749 ast_verbose("Really destroying SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
05750
05751 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
05752 update_call_counter(p, DEC_CALL_LIMIT);
05753 ast_debug(2, "This call did not properly clean up call limits. Call ID %s\n", p->callid);
05754 }
05755
05756
05757 if (p->owner) {
05758 if (lockowner)
05759 ast_channel_lock(p->owner);
05760 ast_debug(1, "Detaching from %s\n", p->owner->name);
05761 p->owner->tech_pvt = NULL;
05762
05763 p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
05764 if (lockowner)
05765 ast_channel_unlock(p->owner);
05766
05767 usleep(1);
05768 }
05769
05770
05771 if (p->relatedpeer && p->relatedpeer->mwipvt)
05772 p->relatedpeer->mwipvt = dialog_unref(p->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
05773 if (p->relatedpeer && p->relatedpeer->call == p)
05774 p->relatedpeer->call = dialog_unref(p->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
05775
05776 if (p->relatedpeer)
05777 p->relatedpeer = unref_peer(p->relatedpeer,"unsetting a dialog relatedpeer field in sip_destroy");
05778
05779 if (p->registry) {
05780 if (p->registry->call == p)
05781 p->registry->call = dialog_unref(p->registry->call, "nulling out the registry's call dialog field in unlink_all");
05782 p->registry = registry_unref(p->registry, "delete p->registry");
05783 }
05784
05785 if (p->mwi) {
05786 p->mwi->call = NULL;
05787 }
05788
05789 if (dumphistory)
05790 sip_dump_history(p);
05791
05792 if (p->options)
05793 ast_free(p->options);
05794
05795 if (p->notify) {
05796 ast_variables_destroy(p->notify->headers);
05797 ast_free(p->notify->content);
05798 ast_free(p->notify);
05799 }
05800 if (p->rtp) {
05801 ast_rtp_instance_destroy(p->rtp);
05802 }
05803 if (p->vrtp) {
05804 ast_rtp_instance_destroy(p->vrtp);
05805 }
05806 if (p->trtp) {
05807 ast_rtp_instance_destroy(p->trtp);
05808 }
05809 if (p->udptl)
05810 ast_udptl_destroy(p->udptl);
05811 if (p->refer)
05812 ast_free(p->refer);
05813 if (p->route) {
05814 free_old_route(p->route);
05815 p->route = NULL;
05816 }
05817 deinit_req(&p->initreq);
05818
05819
05820 if (p->history) {
05821 struct sip_history *hist;
05822 while ( (hist = AST_LIST_REMOVE_HEAD(p->history, list)) ) {
05823 ast_free(hist);
05824 p->history_entries--;
05825 }
05826 ast_free(p->history);
05827 p->history = NULL;
05828 }
05829
05830 while ((req = AST_LIST_REMOVE_HEAD(&p->request_queue, next))) {
05831 ast_free(req);
05832 }
05833
05834 if (p->chanvars) {
05835 ast_variables_destroy(p->chanvars);
05836 p->chanvars = NULL;
05837 }
05838
05839 if (p->srtp) {
05840 sip_srtp_destroy(p->srtp);
05841 p->srtp = NULL;
05842 }
05843
05844 if (p->vsrtp) {
05845 sip_srtp_destroy(p->vsrtp);
05846 p->vsrtp = NULL;
05847 }
05848
05849 if (p->tsrtp) {
05850 sip_srtp_destroy(p->tsrtp);
05851 p->tsrtp = NULL;
05852 }
05853
05854 if (p->directmediaha) {
05855 ast_free_ha(p->directmediaha);
05856 p->directmediaha = NULL;
05857 }
05858
05859 ast_string_field_free_memory(p);
05860
05861 ast_cc_config_params_destroy(p->cc_params);
05862
05863 if (p->epa_entry) {
05864 ao2_ref(p->epa_entry, -1);
05865 p->epa_entry = NULL;
05866 }
05867
05868 if (p->socket.tcptls_session) {
05869 ao2_ref(p->socket.tcptls_session, -1);
05870 p->socket.tcptls_session = NULL;
05871 }
05872
05873 if (p->peerauth) {
05874 ao2_t_ref(p->peerauth, -1, "Removing active peer authentication");
05875 p->peerauth = NULL;
05876 }
05877 }
05878
05879
05880
05881
05882
05883
05884
05885
05886
05887
05888
05889
05890
05891
05892
05893 static int update_call_counter(struct sip_pvt *fup, int event)
05894 {
05895 char name[256];
05896 int *inuse = NULL, *call_limit = NULL, *inringing = NULL;
05897 int outgoing = fup->outgoing_call;
05898 struct sip_peer *p = NULL;
05899
05900 ast_debug(3, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
05901
05902
05903
05904
05905 if (!ast_test_flag(&fup->flags[0], SIP_CALL_LIMIT) && !ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD))
05906 return 0;
05907
05908 ast_copy_string(name, fup->username, sizeof(name));
05909
05910
05911 if (fup->relatedpeer) {
05912 p = ref_peer(fup->relatedpeer, "ref related peer for update_call_counter");
05913 inuse = &p->inUse;
05914 call_limit = &p->call_limit;
05915 inringing = &p->inRinging;
05916 ast_copy_string(name, fup->peername, sizeof(name));
05917 }
05918 if (!p) {
05919 ast_debug(2, "%s is not a local device, no call limit\n", name);
05920 return 0;
05921 }
05922
05923 switch(event) {
05924
05925 case DEC_CALL_LIMIT:
05926
05927 if (inuse) {
05928 sip_pvt_lock(fup);
05929 ao2_lock(p);
05930 if (*inuse > 0) {
05931 if (ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
05932 (*inuse)--;
05933 ast_clear_flag(&fup->flags[0], SIP_INC_COUNT);
05934 }
05935 } else {
05936 *inuse = 0;
05937 }
05938 ao2_unlock(p);
05939 sip_pvt_unlock(fup);
05940 }
05941
05942
05943 if (inringing) {
05944 sip_pvt_lock(fup);
05945 ao2_lock(p);
05946 if (*inringing > 0) {
05947 if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
05948 (*inringing)--;
05949 ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
05950 }
05951 } else {
05952 *inringing = 0;
05953 }
05954 ao2_unlock(p);
05955 sip_pvt_unlock(fup);
05956 }
05957
05958
05959 sip_pvt_lock(fup);
05960 ao2_lock(p);
05961 if (ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD) && sip_cfg.notifyhold) {
05962 ast_clear_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD);
05963 ao2_unlock(p);
05964 sip_pvt_unlock(fup);
05965 sip_peer_hold(fup, FALSE);
05966 } else {
05967 ao2_unlock(p);
05968 sip_pvt_unlock(fup);
05969 }
05970 if (sipdebug)
05971 ast_debug(2, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
05972 break;
05973
05974 case INC_CALL_RINGING:
05975 case INC_CALL_LIMIT:
05976
05977 if (*call_limit > 0 ) {
05978 if (*inuse >= *call_limit) {
05979 ast_log(LOG_NOTICE, "Call %s %s '%s' rejected due to usage limit of %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
05980 unref_peer(p, "update_call_counter: unref peer p, call limit exceeded");
05981 return -1;
05982 }
05983 }
05984 if (inringing && (event == INC_CALL_RINGING)) {
05985 sip_pvt_lock(fup);
05986 ao2_lock(p);
05987 if (!ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
05988 (*inringing)++;
05989 ast_set_flag(&fup->flags[0], SIP_INC_RINGING);
05990 }
05991 ao2_unlock(p);
05992 sip_pvt_unlock(fup);
05993 }
05994 if (inuse) {
05995 sip_pvt_lock(fup);
05996 ao2_lock(p);
05997 if (!ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
05998 (*inuse)++;
05999 ast_set_flag(&fup->flags[0], SIP_INC_COUNT);
06000 }
06001 ao2_unlock(p);
06002 sip_pvt_unlock(fup);
06003 }
06004 if (sipdebug) {
06005 ast_debug(2, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", "peer", name, *inuse, *call_limit);
06006 }
06007 break;
06008
06009 case DEC_CALL_RINGING:
06010 if (inringing) {
06011 sip_pvt_lock(fup);
06012 ao2_lock(p);
06013 if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
06014 if (*inringing > 0) {
06015 (*inringing)--;
06016 }
06017 ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
06018 }
06019 ao2_unlock(p);
06020 sip_pvt_unlock(fup);
06021 }
06022 break;
06023
06024 default:
06025 ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
06026 }
06027
06028 if (p) {
06029 ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", p->name);
06030 unref_peer(p, "update_call_counter: unref_peer from call counter");
06031 }
06032 return 0;
06033 }
06034
06035
06036 static void sip_destroy_fn(void *p)
06037 {
06038 sip_destroy(p);
06039 }
06040
06041
06042
06043
06044
06045
06046 struct sip_pvt *sip_destroy(struct sip_pvt *p)
06047 {
06048 ast_debug(3, "Destroying SIP dialog %s\n", p->callid);
06049 __sip_destroy(p, TRUE, TRUE);
06050 return NULL;
06051 }
06052
06053
06054 int hangup_sip2cause(int cause)
06055 {
06056
06057
06058 switch(cause) {
06059 case 401:
06060 return AST_CAUSE_CALL_REJECTED;
06061 case 403:
06062 return AST_CAUSE_CALL_REJECTED;
06063 case 404:
06064 return AST_CAUSE_UNALLOCATED;
06065 case 405:
06066 return AST_CAUSE_INTERWORKING;
06067 case 407:
06068 return AST_CAUSE_CALL_REJECTED;
06069 case 408:
06070 return AST_CAUSE_NO_USER_RESPONSE;
06071 case 409:
06072 return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
06073 case 410:
06074 return AST_CAUSE_NUMBER_CHANGED;
06075 case 411:
06076 return AST_CAUSE_INTERWORKING;
06077 case 413:
06078 return AST_CAUSE_INTERWORKING;
06079 case 414:
06080 return AST_CAUSE_INTERWORKING;
06081 case 415:
06082 return AST_CAUSE_INTERWORKING;
06083 case 420:
06084 return AST_CAUSE_NO_ROUTE_DESTINATION;
06085 case 480:
06086 return AST_CAUSE_NO_ANSWER;
06087 case 481:
06088 return AST_CAUSE_INTERWORKING;
06089 case 482:
06090 return AST_CAUSE_INTERWORKING;
06091 case 483:
06092 return AST_CAUSE_NO_ANSWER;
06093 case 484:
06094 return AST_CAUSE_INVALID_NUMBER_FORMAT;
06095 case 485:
06096 return AST_CAUSE_UNALLOCATED;
06097 case 486:
06098 return AST_CAUSE_BUSY;
06099 case 487:
06100 return AST_CAUSE_INTERWORKING;
06101 case 488:
06102 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
06103 case 491:
06104 return AST_CAUSE_INTERWORKING;
06105 case 493:
06106 return AST_CAUSE_INTERWORKING;
06107 case 500:
06108 return AST_CAUSE_FAILURE;
06109 case 501:
06110 return AST_CAUSE_FACILITY_REJECTED;
06111 case 502:
06112 return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
06113 case 503:
06114 return AST_CAUSE_CONGESTION;
06115 case 504:
06116 return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
06117 case 505:
06118 return AST_CAUSE_INTERWORKING;
06119 case 600:
06120 return AST_CAUSE_USER_BUSY;
06121 case 603:
06122 return AST_CAUSE_CALL_REJECTED;
06123 case 604:
06124 return AST_CAUSE_UNALLOCATED;
06125 case 606:
06126 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
06127 default:
06128 if (cause < 500 && cause >= 400) {
06129
06130 return AST_CAUSE_INTERWORKING;
06131 } else if (cause < 600 && cause >= 500) {
06132
06133 return AST_CAUSE_CONGESTION;
06134 } else if (cause < 700 && cause >= 600) {
06135
06136 return AST_CAUSE_INTERWORKING;
06137 }
06138 return AST_CAUSE_NORMAL;
06139 }
06140
06141 return 0;
06142 }
06143
06144
06145
06146
06147
06148
06149
06150
06151
06152
06153
06154
06155
06156
06157
06158
06159
06160
06161
06162
06163
06164
06165
06166
06167
06168
06169
06170
06171
06172
06173
06174
06175
06176 const char *hangup_cause2sip(int cause)
06177 {
06178 switch (cause) {
06179 case AST_CAUSE_UNALLOCATED:
06180 case AST_CAUSE_NO_ROUTE_DESTINATION:
06181 case AST_CAUSE_NO_ROUTE_TRANSIT_NET:
06182 return "404 Not Found";
06183 case AST_CAUSE_CONGESTION:
06184 case AST_CAUSE_SWITCH_CONGESTION:
06185 return "503 Service Unavailable";
06186 case AST_CAUSE_NO_USER_RESPONSE:
06187 return "408 Request Timeout";
06188 case AST_CAUSE_NO_ANSWER:
06189 case AST_CAUSE_UNREGISTERED:
06190 return "480 Temporarily unavailable";
06191 case AST_CAUSE_CALL_REJECTED:
06192 return "403 Forbidden";
06193 case AST_CAUSE_NUMBER_CHANGED:
06194 return "410 Gone";
06195 case AST_CAUSE_NORMAL_UNSPECIFIED:
06196 return "480 Temporarily unavailable";
06197 case AST_CAUSE_INVALID_NUMBER_FORMAT:
06198 return "484 Address incomplete";
06199 case AST_CAUSE_USER_BUSY:
06200 return "486 Busy here";
06201 case AST_CAUSE_FAILURE:
06202 return "500 Server internal failure";
06203 case AST_CAUSE_FACILITY_REJECTED:
06204 return "501 Not Implemented";
06205 case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
06206 return "503 Service Unavailable";
06207
06208 case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
06209 return "502 Bad Gateway";
06210 case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL:
06211 return "488 Not Acceptable Here";
06212
06213 case AST_CAUSE_NOTDEFINED:
06214 default:
06215 ast_debug(1, "AST hangup cause %d (no match found in SIP)\n", cause);
06216 return NULL;
06217 }
06218
06219
06220 return 0;
06221 }
06222
06223
06224
06225 static int sip_hangup(struct ast_channel *ast)
06226 {
06227 struct sip_pvt *p = ast->tech_pvt;
06228 int needcancel = FALSE;
06229 int needdestroy = 0;
06230 struct ast_channel *oldowner = ast;
06231
06232 if (!p) {
06233 ast_debug(1, "Asked to hangup channel that was not connected\n");
06234 return 0;
06235 }
06236 if (ast_test_flag(ast, AST_FLAG_ANSWERED_ELSEWHERE) || ast->hangupcause == AST_CAUSE_ANSWERED_ELSEWHERE) {
06237 ast_debug(1, "This call was answered elsewhere");
06238 if (ast->hangupcause == AST_CAUSE_ANSWERED_ELSEWHERE) {
06239 ast_debug(1, "####### It's the cause code, buddy. The cause code!!!\n");
06240 }
06241 append_history(p, "Cancel", "Call answered elsewhere");
06242 p->answered_elsewhere = TRUE;
06243 }
06244
06245
06246 if (p->owner)
06247 p->hangupcause = p->owner->hangupcause;
06248
06249 if (ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
06250 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
06251 if (sipdebug)
06252 ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
06253 update_call_counter(p, DEC_CALL_LIMIT);
06254 }
06255 ast_debug(4, "SIP Transfer: Not hanging up right now... Rescheduling hangup for %s.\n", p->callid);
06256 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06257 ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
06258 p->needdestroy = 0;
06259 p->owner->tech_pvt = dialog_unref(p->owner->tech_pvt, "unref p->owner->tech_pvt");
06260 sip_pvt_lock(p);
06261 p->owner = NULL;
06262 sip_pvt_unlock(p);
06263 ast_module_unref(ast_module_info->self);
06264 return 0;
06265 }
06266
06267 if (ast_test_flag(ast, AST_FLAG_ZOMBIE)) {
06268 if (p->refer)
06269 ast_debug(1, "SIP Transfer: Hanging up Zombie channel %s after transfer ... Call-ID: %s\n", ast->name, p->callid);
06270 else
06271 ast_debug(1, "Hanging up zombie call. Be scared.\n");
06272 } else
06273 ast_debug(1, "Hangup call %s, SIP callid %s\n", ast->name, p->callid);
06274
06275 sip_pvt_lock(p);
06276 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
06277 if (sipdebug)
06278 ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
06279 update_call_counter(p, DEC_CALL_LIMIT);
06280 }
06281
06282
06283 if (p->owner != ast) {
06284 ast_log(LOG_WARNING, "Huh? We aren't the owner? Can't hangup call.\n");
06285 sip_pvt_unlock(p);
06286 return 0;
06287 }
06288
06289
06290 if (p->invitestate < INV_COMPLETED && p->owner->_state != AST_STATE_UP) {
06291 needcancel = TRUE;
06292 ast_debug(4, "Hanging up channel in state %s (not UP)\n", ast_state2str(ast->_state));
06293 }
06294
06295 stop_media_flows(p);
06296
06297 append_history(p, needcancel ? "Cancel" : "Hangup", "Cause %s", p->owner ? ast_cause2str(p->hangupcause) : "Unknown");
06298
06299
06300 disable_dsp_detect(p);
06301
06302 p->owner = NULL;
06303 ast->tech_pvt = dialog_unref(ast->tech_pvt, "unref ast->tech_pvt");
06304
06305 ast_module_unref(ast_module_info->self);
06306
06307
06308
06309
06310
06311
06312 if (p->alreadygone)
06313 needdestroy = 1;
06314 else if (p->invitestate != INV_CALLING)
06315 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06316
06317
06318 if (!p->alreadygone && p->initreq.data && !ast_strlen_zero(p->initreq.data->str)) {
06319 if (needcancel) {
06320 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06321
06322 if (p->invitestate == INV_CALLING) {
06323
06324 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
06325
06326 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06327 append_history(p, "DELAY", "Not sending cancel, waiting for timeout");
06328 } else {
06329 struct sip_pkt *cur;
06330
06331 for (cur = p->packets; cur; cur = cur->next) {
06332 __sip_semi_ack(p, cur->seqno, cur->is_resp, cur->method ? cur->method : find_sip_method(cur->data->str));
06333 }
06334 p->invitestate = INV_CANCELLED;
06335
06336 transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
06337
06338
06339 needdestroy = 0;
06340 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06341 }
06342 } else {
06343 const char *res;
06344 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"));
06345 if (p->hangupcause && (res = hangup_cause2sip(p->hangupcause)))
06346 transmit_response_reliable(p, res, &p->initreq);
06347 else
06348 transmit_response_reliable(p, "603 Declined", &p->initreq);
06349 p->invitestate = INV_TERMINATED;
06350 }
06351 } else {
06352 if (p->stimer->st_active == TRUE) {
06353 stop_session_timer(p);
06354 }
06355
06356 if (!p->pendinginvite) {
06357 struct ast_channel *bridge = ast_bridged_channel(oldowner);
06358 char quality_buf[AST_MAX_USER_FIELD], *quality;
06359
06360
06361
06362
06363 while (bridge && ast_channel_trylock(bridge)) {
06364 sip_pvt_unlock(p);
06365 do {
06366 CHANNEL_DEADLOCK_AVOIDANCE(oldowner);
06367 } while (sip_pvt_trylock(p));
06368 bridge = ast_bridged_channel(oldowner);
06369 }
06370
06371 if (p->rtp) {
06372 ast_rtp_instance_set_stats_vars(oldowner, p->rtp);
06373 }
06374
06375 if (bridge) {
06376 struct sip_pvt *q = bridge->tech_pvt;
06377
06378 if (IS_SIP_TECH(bridge->tech) && q && q->rtp) {
06379 ast_rtp_instance_set_stats_vars(bridge, q->rtp);
06380 }
06381 ast_channel_unlock(bridge);
06382 }
06383
06384 if (p->do_history || oldowner) {
06385 if (p->rtp && (quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
06386 if (p->do_history) {
06387 append_history(p, "RTCPaudio", "Quality:%s", quality);
06388 }
06389 if (oldowner) {
06390 pbx_builtin_setvar_helper(oldowner, "RTPAUDIOQOS", quality);
06391 }
06392 }
06393 if (p->vrtp && (quality = ast_rtp_instance_get_quality(p->vrtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
06394 if (p->do_history) {
06395 append_history(p, "RTCPvideo", "Quality:%s", quality);
06396 }
06397 if (oldowner) {
06398 pbx_builtin_setvar_helper(oldowner, "RTPVIDEOQOS", quality);
06399 }
06400 }
06401 if (p->trtp && (quality = ast_rtp_instance_get_quality(p->trtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
06402 if (p->do_history) {
06403 append_history(p, "RTCPtext", "Quality:%s", quality);
06404 }
06405 if (oldowner) {
06406 pbx_builtin_setvar_helper(oldowner, "RTPTEXTQOS", quality);
06407 }
06408 }
06409 }
06410
06411
06412 if (oldowner->_state == AST_STATE_UP) {
06413 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
06414 }
06415
06416 } else {
06417
06418
06419 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
06420 ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);
06421 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"));
06422 if (sip_cancel_destroy(p))
06423 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
06424 }
06425 }
06426 }
06427 if (needdestroy) {
06428 pvt_set_needdestroy(p, "hangup");
06429 }
06430 sip_pvt_unlock(p);
06431 return 0;
06432 }
06433
06434
06435 static void try_suggested_sip_codec(struct sip_pvt *p)
06436 {
06437 format_t fmt;
06438 const char *codec;
06439
06440 if (p->outgoing_call) {
06441 codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC_OUTBOUND");
06442 } else if (!(codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC_INBOUND"))) {
06443 codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC");
06444 }
06445
06446 if (!codec)
06447 return;
06448
06449 fmt = ast_getformatbyname(codec);
06450 if (fmt) {
06451 ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC} variable\n", codec);
06452 if (p->jointcapability & fmt) {
06453 p->jointcapability &= fmt;
06454 p->capability &= fmt;
06455 } else
06456 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
06457 } else
06458 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n", codec);
06459 return;
06460 }
06461
06462
06463
06464 static int sip_answer(struct ast_channel *ast)
06465 {
06466 int res = 0;
06467 struct sip_pvt *p = ast->tech_pvt;
06468
06469 sip_pvt_lock(p);
06470 if (ast->_state != AST_STATE_UP) {
06471 try_suggested_sip_codec(p);
06472
06473 ast_setstate(ast, AST_STATE_UP);
06474 ast_debug(1, "SIP answering channel: %s\n", ast->name);
06475 ast_rtp_instance_update_source(p->rtp);
06476 res = transmit_response_with_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL, FALSE, TRUE);
06477 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
06478 }
06479 sip_pvt_unlock(p);
06480 return res;
06481 }
06482
06483
06484 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
06485 {
06486 struct sip_pvt *p = ast->tech_pvt;
06487 int res = 0;
06488
06489 switch (frame->frametype) {
06490 case AST_FRAME_VOICE:
06491 if (!(frame->subclass.codec & ast->nativeformats)) {
06492 char s1[512], s2[512], s3[512];
06493 ast_log(LOG_WARNING, "Asked to transmit frame type %s, while native formats is %s read/write = %s/%s\n",
06494 ast_getformatname(frame->subclass.codec),
06495 ast_getformatname_multiple(s1, sizeof(s1), ast->nativeformats & AST_FORMAT_AUDIO_MASK),
06496 ast_getformatname_multiple(s2, sizeof(s2), ast->readformat),
06497 ast_getformatname_multiple(s3, sizeof(s3), ast->writeformat));
06498 return 0;
06499 }
06500 if (p) {
06501 sip_pvt_lock(p);
06502 if (p->t38.state == T38_ENABLED) {
06503
06504 sip_pvt_unlock(p);
06505 break;
06506 } else if (p->rtp) {
06507
06508 if ((ast->_state != AST_STATE_UP) &&
06509 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06510 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06511 ast_rtp_instance_update_source(p->rtp);
06512 if (!global_prematuremediafilter) {
06513 p->invitestate = INV_EARLY_MEDIA;
06514 transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06515 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06516 }
06517 }
06518 p->lastrtptx = time(NULL);
06519 res = ast_rtp_instance_write(p->rtp, frame);
06520 }
06521 sip_pvt_unlock(p);
06522 }
06523 break;
06524 case AST_FRAME_VIDEO:
06525 if (p) {
06526 sip_pvt_lock(p);
06527 if (p->vrtp) {
06528
06529 if ((ast->_state != AST_STATE_UP) &&
06530 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06531 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06532 p->invitestate = INV_EARLY_MEDIA;
06533 transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06534 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06535 }
06536 p->lastrtptx = time(NULL);
06537 res = ast_rtp_instance_write(p->vrtp, frame);
06538 }
06539 sip_pvt_unlock(p);
06540 }
06541 break;
06542 case AST_FRAME_TEXT:
06543 if (p) {
06544 sip_pvt_lock(p);
06545 if (p->red) {
06546 ast_rtp_red_buffer(p->trtp, frame);
06547 } else {
06548 if (p->trtp) {
06549
06550 if ((ast->_state != AST_STATE_UP) &&
06551 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06552 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06553 p->invitestate = INV_EARLY_MEDIA;
06554 transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06555 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06556 }
06557 p->lastrtptx = time(NULL);
06558 res = ast_rtp_instance_write(p->trtp, frame);
06559 }
06560 }
06561 sip_pvt_unlock(p);
06562 }
06563 break;
06564 case AST_FRAME_IMAGE:
06565 return 0;
06566 break;
06567 case AST_FRAME_MODEM:
06568 if (p) {
06569 sip_pvt_lock(p);
06570
06571
06572
06573
06574 if ((ast->_state == AST_STATE_UP) &&
06575 p->udptl &&
06576 (p->t38.state == T38_ENABLED)) {
06577 res = ast_udptl_write(p->udptl, frame);
06578 }
06579 sip_pvt_unlock(p);
06580 }
06581 break;
06582 default:
06583 ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
06584 return 0;
06585 }
06586
06587 return res;
06588 }
06589
06590
06591
06592 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
06593 {
06594 int ret = -1;
06595 struct sip_pvt *p;
06596
06597 if (newchan && ast_test_flag(newchan, AST_FLAG_ZOMBIE))
06598 ast_debug(1, "New channel is zombie\n");
06599 if (oldchan && ast_test_flag(oldchan, AST_FLAG_ZOMBIE))
06600 ast_debug(1, "Old channel is zombie\n");
06601
06602 if (!newchan || !newchan->tech_pvt) {
06603 if (!newchan)
06604 ast_log(LOG_WARNING, "No new channel! Fixup of %s failed.\n", oldchan->name);
06605 else
06606 ast_log(LOG_WARNING, "No SIP tech_pvt! Fixup of %s failed.\n", oldchan->name);
06607 return -1;
06608 }
06609 p = newchan->tech_pvt;
06610
06611 sip_pvt_lock(p);
06612 append_history(p, "Masq", "Old channel: %s\n", oldchan->name);
06613 append_history(p, "Masq (cont)", "...new owner: %s\n", newchan->name);
06614 if (p->owner != oldchan)
06615 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
06616 else {
06617 p->owner = newchan;
06618
06619
06620
06621
06622
06623
06624 sip_set_rtp_peer(newchan, NULL, NULL, 0, 0, 0);
06625 ret = 0;
06626 }
06627 ast_debug(3, "SIP Fixup: New owner for dialogue %s: %s (Old parent: %s)\n", p->callid, p->owner->name, oldchan->name);
06628
06629 sip_pvt_unlock(p);
06630 return ret;
06631 }
06632
06633 static int sip_senddigit_begin(struct ast_channel *ast, char digit)
06634 {
06635 struct sip_pvt *p = ast->tech_pvt;
06636 int res = 0;
06637
06638 sip_pvt_lock(p);
06639 switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
06640 case SIP_DTMF_INBAND:
06641 res = -1;
06642 break;
06643 case SIP_DTMF_RFC2833:
06644 if (p->rtp)
06645 ast_rtp_instance_dtmf_begin(p->rtp, digit);
06646 break;
06647 default:
06648 break;
06649 }
06650 sip_pvt_unlock(p);
06651
06652 return res;
06653 }
06654
06655
06656
06657 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration)
06658 {
06659 struct sip_pvt *p = ast->tech_pvt;
06660 int res = 0;
06661
06662 sip_pvt_lock(p);
06663 switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
06664 case SIP_DTMF_INFO:
06665 case SIP_DTMF_SHORTINFO:
06666 transmit_info_with_digit(p, digit, duration);
06667 break;
06668 case SIP_DTMF_RFC2833:
06669 if (p->rtp)
06670 ast_rtp_instance_dtmf_end_with_duration(p->rtp, digit, duration);
06671 break;
06672 case SIP_DTMF_INBAND:
06673 res = -1;
06674 break;
06675 }
06676 sip_pvt_unlock(p);
06677
06678 return res;
06679 }
06680
06681
06682 static int sip_transfer(struct ast_channel *ast, const char *dest)
06683 {
06684 struct sip_pvt *p = ast->tech_pvt;
06685 int res;
06686
06687 if (dest == NULL)
06688 dest = "";
06689 sip_pvt_lock(p);
06690 if (ast->_state == AST_STATE_RING)
06691 res = sip_sipredirect(p, dest);
06692 else
06693 res = transmit_refer(p, dest);
06694 sip_pvt_unlock(p);
06695 return res;
06696 }
06697
06698
06699 static int interpret_t38_parameters(struct sip_pvt *p, const struct ast_control_t38_parameters *parameters)
06700 {
06701 int res = 0;
06702
06703 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) || !p->udptl) {
06704 return -1;
06705 }
06706 switch (parameters->request_response) {
06707 case AST_T38_NEGOTIATED:
06708 case AST_T38_REQUEST_NEGOTIATE:
06709
06710 if (!parameters->max_ifp) {
06711 change_t38_state(p, T38_DISABLED);
06712 if (p->t38.state == T38_PEER_REINVITE) {
06713 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"));
06714 transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
06715 }
06716 break;
06717 } else if (p->t38.state == T38_PEER_REINVITE) {
06718 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"));
06719 p->t38.our_parms = *parameters;
06720
06721
06722
06723 if (!p->t38.their_parms.fill_bit_removal) {
06724 p->t38.our_parms.fill_bit_removal = FALSE;
06725 }
06726 if (!p->t38.their_parms.transcoding_mmr) {
06727 p->t38.our_parms.transcoding_mmr = FALSE;
06728 }
06729 if (!p->t38.their_parms.transcoding_jbig) {
06730 p->t38.our_parms.transcoding_jbig = FALSE;
06731 }
06732 p->t38.our_parms.version = MIN(p->t38.our_parms.version, p->t38.their_parms.version);
06733 p->t38.our_parms.rate_management = p->t38.their_parms.rate_management;
06734 ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
06735 change_t38_state(p, T38_ENABLED);
06736 transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
06737 } else if (p->t38.state != T38_ENABLED) {
06738 p->t38.our_parms = *parameters;
06739 ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
06740 change_t38_state(p, T38_LOCAL_REINVITE);
06741 if (!p->pendinginvite) {
06742 transmit_reinvite_with_sdp(p, TRUE, FALSE);
06743 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
06744 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
06745 }
06746 }
06747 break;
06748 case AST_T38_TERMINATED:
06749 case AST_T38_REFUSED:
06750 case AST_T38_REQUEST_TERMINATE:
06751 if (p->t38.state == T38_PEER_REINVITE) {
06752 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"));
06753 change_t38_state(p, T38_DISABLED);
06754 transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
06755 } else if (p->t38.state == T38_ENABLED)
06756 transmit_reinvite_with_sdp(p, FALSE, FALSE);
06757 break;
06758 case AST_T38_REQUEST_PARMS: {
06759 struct ast_control_t38_parameters parameters = p->t38.their_parms;
06760
06761 if (p->t38.state == T38_PEER_REINVITE) {
06762 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"));
06763 parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
06764 parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
06765 ast_queue_control_data(p->owner, AST_CONTROL_T38_PARAMETERS, ¶meters, sizeof(parameters));
06766
06767
06768
06769
06770 res = AST_T38_REQUEST_PARMS;
06771 }
06772 break;
06773 }
06774 default:
06775 res = -1;
06776 break;
06777 }
06778
06779 return res;
06780 }
06781
06782
06783
06784
06785
06786
06787
06788
06789
06790
06791 static int initialize_udptl(struct sip_pvt *p)
06792 {
06793 int natflags = ast_test_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP);
06794
06795 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
06796 return 1;
06797 }
06798
06799
06800 if (p->udptl) {
06801 return 0;
06802 }
06803
06804
06805 if ((p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, &bindaddr))) {
06806 if (p->owner) {
06807 ast_channel_set_fd(p->owner, 5, ast_udptl_fd(p->udptl));
06808 }
06809
06810 ast_udptl_setqos(p->udptl, global_tos_audio, global_cos_audio);
06811 p->t38_maxdatagram = p->relatedpeer ? p->relatedpeer->t38_maxdatagram : global_t38_maxdatagram;
06812 set_t38_capabilities(p);
06813
06814 ast_debug(1, "Setting NAT on UDPTL to %s\n", natflags ? "On" : "Off");
06815 ast_udptl_setnat(p->udptl, natflags);
06816 } else {
06817 ast_log(AST_LOG_WARNING, "UDPTL creation failed - disabling T38 for this dialog\n");
06818 ast_clear_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT);
06819 return 1;
06820 }
06821
06822 return 0;
06823 }
06824
06825
06826
06827
06828
06829
06830 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
06831 {
06832 struct sip_pvt *p = ast->tech_pvt;
06833 int res = 0;
06834
06835 sip_pvt_lock(p);
06836 switch(condition) {
06837 case AST_CONTROL_RINGING:
06838 if (ast->_state == AST_STATE_RING) {
06839 p->invitestate = INV_EARLY_MEDIA;
06840 if (!ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) ||
06841 (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) {
06842
06843 transmit_provisional_response(p, "180 Ringing", &p->initreq, 0);
06844 ast_set_flag(&p->flags[0], SIP_RINGING);
06845 if (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) != SIP_PROG_INBAND_YES)
06846 break;
06847 } else {
06848
06849 }
06850 }
06851 res = -1;
06852 break;
06853 case AST_CONTROL_BUSY:
06854 if (ast->_state != AST_STATE_UP) {
06855 transmit_response_reliable(p, "486 Busy Here", &p->initreq);
06856 p->invitestate = INV_COMPLETED;
06857 sip_alreadygone(p);
06858 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
06859 break;
06860 }
06861 res = -1;
06862 break;
06863 case AST_CONTROL_CONGESTION:
06864 if (ast->_state != AST_STATE_UP) {
06865 transmit_response_reliable(p, "503 Service Unavailable", &p->initreq);
06866 p->invitestate = INV_COMPLETED;
06867 sip_alreadygone(p);
06868 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
06869 break;
06870 }
06871 res = -1;
06872 break;
06873 case AST_CONTROL_INCOMPLETE:
06874 if (ast->_state != AST_STATE_UP) {
06875 switch (ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP)) {
06876 case SIP_PAGE2_ALLOWOVERLAP_YES:
06877 transmit_response_reliable(p, "484 Address Incomplete", &p->initreq);
06878 p->invitestate = INV_COMPLETED;
06879 sip_alreadygone(p);
06880 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
06881 break;
06882 case SIP_PAGE2_ALLOWOVERLAP_DTMF:
06883
06884 break;
06885 default:
06886
06887 transmit_response_reliable(p, "404 Not Found", &p->initreq);
06888 p->invitestate = INV_COMPLETED;
06889 sip_alreadygone(p);
06890 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
06891 break;
06892 }
06893 }
06894 break;
06895 case AST_CONTROL_PROCEEDING:
06896 if ((ast->_state != AST_STATE_UP) &&
06897 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06898 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06899 transmit_response(p, "100 Trying", &p->initreq);
06900 p->invitestate = INV_PROCEEDING;
06901 break;
06902 }
06903 res = -1;
06904 break;
06905 case AST_CONTROL_PROGRESS:
06906 if ((ast->_state != AST_STATE_UP) &&
06907 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06908 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06909 p->invitestate = INV_EARLY_MEDIA;
06910 transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06911 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06912 break;
06913 }
06914 res = -1;
06915 break;
06916 case AST_CONTROL_HOLD:
06917 ast_rtp_instance_update_source(p->rtp);
06918 ast_moh_start(ast, data, p->mohinterpret);
06919 break;
06920 case AST_CONTROL_UNHOLD:
06921 ast_rtp_instance_update_source(p->rtp);
06922 ast_moh_stop(ast);
06923 break;
06924 case AST_CONTROL_VIDUPDATE:
06925 if (p->vrtp && !p->novideo) {
06926 transmit_info_with_vidupdate(p);
06927
06928 } else
06929 res = -1;
06930 break;
06931 case AST_CONTROL_T38_PARAMETERS:
06932 res = -1;
06933 if (datalen != sizeof(struct ast_control_t38_parameters)) {
06934 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);
06935 } else {
06936 const struct ast_control_t38_parameters *parameters = data;
06937 if (!initialize_udptl(p)) {
06938 res = interpret_t38_parameters(p, parameters);
06939 }
06940 }
06941 break;
06942 case AST_CONTROL_SRCUPDATE:
06943 ast_rtp_instance_update_source(p->rtp);
06944 break;
06945 case AST_CONTROL_SRCCHANGE:
06946 ast_rtp_instance_change_source(p->rtp);
06947 break;
06948 case AST_CONTROL_CONNECTED_LINE:
06949 update_connectedline(p, data, datalen);
06950 break;
06951 case AST_CONTROL_REDIRECTING:
06952 update_redirecting(p, data, datalen);
06953 break;
06954 case AST_CONTROL_AOC:
06955 {
06956 struct ast_aoc_decoded *decoded = ast_aoc_decode((struct ast_aoc_encoded *) data, datalen, ast);
06957 if (!decoded) {
06958 ast_log(LOG_ERROR, "Error decoding indicated AOC data\n");
06959 res = -1;
06960 break;
06961 }
06962 switch (ast_aoc_get_msg_type(decoded)) {
06963 case AST_AOC_REQUEST:
06964 if (ast_aoc_get_termination_request(decoded)) {
06965
06966
06967
06968
06969
06970
06971
06972 ast_debug(1, "AOC-E termination request received on %s. This is not yet supported on sip. Continue with hangup \n", p->owner->name);
06973 ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
06974 }
06975 break;
06976 case AST_AOC_D:
06977 case AST_AOC_E:
06978 if (ast_test_flag(&p->flags[2], SIP_PAGE3_SNOM_AOC)) {
06979 transmit_info_with_aoc(p, decoded);
06980 }
06981 break;
06982 case AST_AOC_S:
06983 default:
06984 break;
06985 }
06986 ast_aoc_destroy_decoded(decoded);
06987 }
06988 break;
06989 case AST_CONTROL_UPDATE_RTP_PEER:
06990 break;
06991 case -1:
06992 res = -1;
06993 break;
06994 default:
06995 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
06996 res = -1;
06997 break;
06998 }
06999 sip_pvt_unlock(p);
07000 return res;
07001 }
07002
07003
07004
07005
07006
07007
07008
07009
07010
07011
07012
07013
07014 static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title, const char *linkedid)
07015 {
07016 struct ast_channel *tmp;
07017 struct ast_variable *v = NULL;
07018 format_t fmt;
07019 format_t what;
07020 format_t video;
07021 format_t text;
07022 format_t needvideo = 0;
07023 int needtext = 0;
07024 char buf[SIPBUFSIZE];
07025 char *exten;
07026
07027 {
07028 const char *my_name;
07029
07030 if (title) {
07031 my_name = title;
07032 } else {
07033 my_name = ast_strdupa(i->fromdomain);
07034 }
07035
07036 sip_pvt_unlock(i);
07037
07038 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));
07039 }
07040 if (!tmp) {
07041 ast_log(LOG_WARNING, "Unable to allocate AST channel structure for SIP channel\n");
07042 sip_pvt_lock(i);
07043 return NULL;
07044 }
07045 ast_channel_lock(tmp);
07046 sip_pvt_lock(i);
07047 ast_channel_cc_params_init(tmp, i->cc_params);
07048 tmp->caller.id.tag = ast_strdup(i->cid_tag);
07049
07050 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;
07051
07052
07053
07054 if (i->jointcapability) {
07055 what = i->jointcapability;
07056 video = i->jointcapability & AST_FORMAT_VIDEO_MASK;
07057 text = i->jointcapability & AST_FORMAT_TEXT_MASK;
07058 } else if (i->capability) {
07059 what = i->capability;
07060 video = i->capability & AST_FORMAT_VIDEO_MASK;
07061 text = i->capability & AST_FORMAT_TEXT_MASK;
07062 } else {
07063 what = sip_cfg.capability;
07064 video = sip_cfg.capability & AST_FORMAT_VIDEO_MASK;
07065 text = sip_cfg.capability & AST_FORMAT_TEXT_MASK;
07066 }
07067
07068
07069 tmp->nativeformats = ast_codec_choose(&i->prefs, what, 1) | video | text;
07070 ast_debug(3, "*** Our native formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, tmp->nativeformats));
07071 ast_debug(3, "*** Joint capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->jointcapability));
07072 ast_debug(3, "*** Our capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->capability));
07073 ast_debug(3, "*** AST_CODEC_CHOOSE formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, ast_codec_choose(&i->prefs, what, 1)));
07074 if (i->prefcodec)
07075 ast_debug(3, "*** Our preferred formats from the incoming channel are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->prefcodec));
07076
07077
07078 fmt = ast_best_codec(tmp->nativeformats);
07079
07080
07081
07082
07083
07084 if (i->vrtp) {
07085 if (ast_test_flag(&i->flags[1], SIP_PAGE2_VIDEOSUPPORT))
07086 needvideo = AST_FORMAT_VIDEO_MASK;
07087 else if (i->prefcodec)
07088 needvideo = i->prefcodec & AST_FORMAT_VIDEO_MASK;
07089 else
07090 needvideo = i->jointcapability & AST_FORMAT_VIDEO_MASK;
07091 }
07092
07093 if (i->trtp) {
07094 if (i->prefcodec)
07095 needtext = i->prefcodec & AST_FORMAT_TEXT_MASK;
07096 else
07097 needtext = i->jointcapability & AST_FORMAT_TEXT_MASK;
07098 }
07099
07100 if (needvideo)
07101 ast_debug(3, "This channel can handle video! HOLLYWOOD next!\n");
07102 else
07103 ast_debug(3, "This channel will not be able to handle video.\n");
07104
07105 enable_dsp_detect(i);
07106
07107 if ((ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
07108 (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
07109 if (i->rtp) {
07110 ast_rtp_instance_dtmf_mode_set(i->rtp, AST_RTP_DTMF_MODE_INBAND);
07111 }
07112 } else if (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) {
07113 if (i->rtp) {
07114 ast_rtp_instance_dtmf_mode_set(i->rtp, AST_RTP_DTMF_MODE_RFC2833);
07115 }
07116 }
07117
07118
07119
07120
07121 if (i->rtp) {
07122 ast_channel_set_fd(tmp, 0, ast_rtp_instance_fd(i->rtp, 0));
07123 ast_channel_set_fd(tmp, 1, ast_rtp_instance_fd(i->rtp, 1));
07124 }
07125 if (needvideo && i->vrtp) {
07126 ast_channel_set_fd(tmp, 2, ast_rtp_instance_fd(i->vrtp, 0));
07127 ast_channel_set_fd(tmp, 3, ast_rtp_instance_fd(i->vrtp, 1));
07128 }
07129 if (needtext && i->trtp) {
07130 ast_channel_set_fd(tmp, 4, ast_rtp_instance_fd(i->trtp, 0));
07131 }
07132 if (i->udptl) {
07133 ast_channel_set_fd(tmp, 5, ast_udptl_fd(i->udptl));
07134 }
07135
07136 if (state == AST_STATE_RING)
07137 tmp->rings = 1;
07138 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
07139
07140 tmp->writeformat = fmt;
07141 tmp->rawwriteformat = fmt;
07142 ast_rtp_instance_set_write_format(i->rtp, fmt);
07143
07144 tmp->readformat = fmt;
07145 tmp->rawreadformat = fmt;
07146 ast_rtp_instance_set_read_format(i->rtp, fmt);
07147
07148 tmp->tech_pvt = dialog_ref(i, "sip_new: set chan->tech_pvt to i");
07149
07150 tmp->callgroup = i->callgroup;
07151 tmp->pickupgroup = i->pickupgroup;
07152 tmp->caller.id.name.presentation = i->callingpres;
07153 tmp->caller.id.number.presentation = i->callingpres;
07154 if (!ast_strlen_zero(i->parkinglot))
07155 ast_string_field_set(tmp, parkinglot, i->parkinglot);
07156 if (!ast_strlen_zero(i->accountcode))
07157 ast_string_field_set(tmp, accountcode, i->accountcode);
07158 if (i->amaflags)
07159 tmp->amaflags = i->amaflags;
07160 if (!ast_strlen_zero(i->language))
07161 ast_string_field_set(tmp, language, i->language);
07162 i->owner = tmp;
07163 ast_module_ref(ast_module_info->self);
07164 ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
07165
07166
07167
07168
07169 exten = ast_strdupa(i->exten);
07170 sip_pvt_unlock(i);
07171 ast_channel_unlock(tmp);
07172 if (!ast_exists_extension(NULL, i->context, i->exten, 1, i->cid_num)) {
07173 ast_uri_decode(exten);
07174 }
07175 ast_channel_lock(tmp);
07176 sip_pvt_lock(i);
07177 ast_copy_string(tmp->exten, exten, sizeof(tmp->exten));
07178
07179
07180
07181 if (!ast_strlen_zero(i->cid_num)) {
07182 tmp->caller.ani.number.valid = 1;
07183 tmp->caller.ani.number.str = ast_strdup(i->cid_num);
07184 }
07185 if (!ast_strlen_zero(i->rdnis)) {
07186 tmp->redirecting.from.number.valid = 1;
07187 tmp->redirecting.from.number.str = ast_strdup(i->rdnis);
07188 }
07189
07190 if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s")) {
07191 tmp->dialed.number.str = ast_strdup(i->exten);
07192 }
07193
07194 tmp->priority = 1;
07195 if (!ast_strlen_zero(i->uri))
07196 pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
07197 if (!ast_strlen_zero(i->domain))
07198 pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
07199 if (!ast_strlen_zero(i->callid))
07200 pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
07201 if (i->rtp)
07202 ast_jb_configure(tmp, &global_jbconf);
07203
07204
07205 for (v = i->chanvars ; v ; v = v->next) {
07206 char valuebuf[1024];
07207 pbx_builtin_setvar_helper(tmp, v->name, ast_get_encoded_str(v->value, valuebuf, sizeof(valuebuf)));
07208 }
07209
07210 if (i->do_history)
07211 append_history(i, "NewChan", "Channel %s - from %s", tmp->name, i->callid);
07212
07213
07214 if (sip_cfg.callevents)
07215 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
07216 "Channel: %s\r\nUniqueid: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\n",
07217 tmp->name, tmp->uniqueid, "SIP", i->callid, i->fullcontact);
07218
07219 return tmp;
07220 }
07221
07222
07223 static char *get_body_by_line(const char *line, const char *name, int nameLen, char delimiter)
07224 {
07225 if (!strncasecmp(line, name, nameLen) && line[nameLen] == delimiter)
07226 return ast_skip_blanks(line + nameLen + 1);
07227
07228 return "";
07229 }
07230
07231
07232
07233
07234
07235 static const char *get_sdp_iterate(int *start, struct sip_request *req, const char *name)
07236 {
07237 int len = strlen(name);
07238
07239 while (*start < (req->sdp_start + req->sdp_count)) {
07240 const char *r = get_body_by_line(REQ_OFFSET_TO_STR(req, line[(*start)++]), name, len, '=');
07241 if (r[0] != '\0')
07242 return r;
07243 }
07244
07245
07246 (*start)++;
07247
07248 return "";
07249 }
07250
07251
07252
07253
07254
07255
07256 static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value)
07257 {
07258 char type = '\0';
07259 const char *line = NULL;
07260
07261 if (stop > (req->sdp_start + req->sdp_count)) {
07262 stop = req->sdp_start + req->sdp_count;
07263 }
07264
07265 while (*start < stop) {
07266 line = REQ_OFFSET_TO_STR(req, line[(*start)++]);
07267 if (line[1] == '=') {
07268 type = line[0];
07269 *value = ast_skip_blanks(line + 2);
07270 break;
07271 }
07272 }
07273
07274 return type;
07275 }
07276
07277
07278 static char *get_body(struct sip_request *req, char *name, char delimiter)
07279 {
07280 int x;
07281 int len = strlen(name);
07282 char *r;
07283
07284 for (x = 0; x < req->lines; x++) {
07285 r = get_body_by_line(REQ_OFFSET_TO_STR(req, line[x]), name, len, delimiter);
07286 if (r[0] != '\0')
07287 return r;
07288 }
07289
07290 return "";
07291 }
07292
07293
07294 static const char *find_alias(const char *name, const char *_default)
07295 {
07296
07297 static const struct cfalias {
07298 char * const fullname;
07299 char * const shortname;
07300 } aliases[] = {
07301 { "Content-Type", "c" },
07302 { "Content-Encoding", "e" },
07303 { "From", "f" },
07304 { "Call-ID", "i" },
07305 { "Contact", "m" },
07306 { "Content-Length", "l" },
07307 { "Subject", "s" },
07308 { "To", "t" },
07309 { "Supported", "k" },
07310 { "Refer-To", "r" },
07311 { "Referred-By", "b" },
07312 { "Allow-Events", "u" },
07313 { "Event", "o" },
07314 { "Via", "v" },
07315 { "Accept-Contact", "a" },
07316 { "Reject-Contact", "j" },
07317 { "Request-Disposition", "d" },
07318 { "Session-Expires", "x" },
07319 { "Identity", "y" },
07320 { "Identity-Info", "n" },
07321 };
07322 int x;
07323
07324 for (x = 0; x < ARRAY_LEN(aliases); x++) {
07325 if (!strcasecmp(aliases[x].fullname, name))
07326 return aliases[x].shortname;
07327 }
07328
07329 return _default;
07330 }
07331
07332 static const char *__get_header(const struct sip_request *req, const char *name, int *start)
07333 {
07334
07335
07336
07337
07338
07339
07340
07341
07342
07343 const char *sname = find_alias(name, NULL);
07344 int x, len = strlen(name), slen = (sname ? 1 : 0);
07345 for (x = *start; x < req->headers; x++) {
07346 const char *header = REQ_OFFSET_TO_STR(req, header[x]);
07347 int smatch = 0, match = !strncasecmp(header, name, len);
07348 if (slen) {
07349 smatch = !strncasecmp(header, sname, slen);
07350 }
07351 if (match || smatch) {
07352
07353 const char *r = header + (match ? len : slen );
07354 if (sip_cfg.pedanticsipchecking) {
07355 r = ast_skip_blanks(r);
07356 }
07357
07358 if (*r == ':') {
07359 *start = x+1;
07360 return ast_skip_blanks(r+1);
07361 }
07362 }
07363 }
07364
07365
07366 return "";
07367 }
07368
07369
07370
07371
07372 static const char *get_header(const struct sip_request *req, const char *name)
07373 {
07374 int start = 0;
07375 return __get_header(req, name, &start);
07376 }
07377
07378
07379 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect)
07380 {
07381
07382 struct ast_frame *f;
07383
07384 if (!p->rtp) {
07385
07386 return &ast_null_frame;
07387 }
07388
07389 switch(ast->fdno) {
07390 case 0:
07391 f = ast_rtp_instance_read(p->rtp, 0);
07392 break;
07393 case 1:
07394 f = ast_rtp_instance_read(p->rtp, 1);
07395 break;
07396 case 2:
07397 f = ast_rtp_instance_read(p->vrtp, 0);
07398 break;
07399 case 3:
07400 f = ast_rtp_instance_read(p->vrtp, 1);
07401 break;
07402 case 4:
07403 f = ast_rtp_instance_read(p->trtp, 0);
07404 if (sipdebug_text) {
07405 int i;
07406 unsigned char* arr = f->data.ptr;
07407 for (i=0; i < f->datalen; i++)
07408 ast_verbose("%c", (arr[i] > ' ' && arr[i] < '}') ? arr[i] : '.');
07409 ast_verbose(" -> ");
07410 for (i=0; i < f->datalen; i++)
07411 ast_verbose("%02X ", arr[i]);
07412 ast_verbose("\n");
07413 }
07414 break;
07415 case 5:
07416 f = ast_udptl_read(p->udptl);
07417 break;
07418 default:
07419 f = &ast_null_frame;
07420 }
07421
07422 if (f && (f->frametype == AST_FRAME_DTMF_BEGIN || f->frametype == AST_FRAME_DTMF_END) &&
07423 (ast_test_flag(&p->flags[0], SIP_DTMF) != SIP_DTMF_RFC2833)) {
07424 ast_debug(1, "Ignoring DTMF (%c) RTP frame because dtmfmode is not RFC2833\n", f->subclass.integer);
07425 return &ast_null_frame;
07426 }
07427
07428
07429 if (!p->owner || (f && f->frametype != AST_FRAME_VOICE))
07430 return f;
07431
07432 if (f && f->subclass.codec != (p->owner->nativeformats & AST_FORMAT_AUDIO_MASK)) {
07433 if (!(f->subclass.codec & p->jointcapability)) {
07434 ast_debug(1, "Bogus frame of format '%s' received from '%s'!\n",
07435 ast_getformatname(f->subclass.codec), p->owner->name);
07436 return &ast_null_frame;
07437 }
07438 ast_debug(1, "Oooh, format changed to %s\n",
07439 ast_getformatname(f->subclass.codec));
07440 p->owner->nativeformats = (p->owner->nativeformats & (AST_FORMAT_VIDEO_MASK | AST_FORMAT_TEXT_MASK)) | f->subclass.codec;
07441 ast_set_read_format(p->owner, p->owner->readformat);
07442 ast_set_write_format(p->owner, p->owner->writeformat);
07443 }
07444
07445 if (f && p->dsp) {
07446 f = ast_dsp_process(p->owner, p->dsp, f);
07447 if (f && f->frametype == AST_FRAME_DTMF) {
07448 if (f->subclass.integer == 'f') {
07449 ast_debug(1, "Fax CNG detected on %s\n", ast->name);
07450 *faxdetect = 1;
07451
07452 if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
07453 ast_dsp_set_features(p->dsp, DSP_FEATURE_DIGIT_DETECT);
07454 } else {
07455 ast_dsp_free(p->dsp);
07456 p->dsp = NULL;
07457 }
07458 } else {
07459 ast_debug(1, "* Detected inband DTMF '%c'\n", f->subclass.integer);
07460 }
07461 }
07462 }
07463
07464 return f;
07465 }
07466
07467
07468 static struct ast_frame *sip_read(struct ast_channel *ast)
07469 {
07470 struct ast_frame *fr;
07471 struct sip_pvt *p = ast->tech_pvt;
07472 int faxdetected = FALSE;
07473
07474 sip_pvt_lock(p);
07475 fr = sip_rtp_read(ast, p, &faxdetected);
07476 p->lastrtprx = time(NULL);
07477
07478
07479 if (faxdetected && ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_CNG)) {
07480 if (strcmp(ast->exten, "fax")) {
07481 const char *target_context = S_OR(ast->macrocontext, ast->context);
07482
07483
07484
07485
07486
07487 sip_pvt_unlock(p);
07488 ast_channel_unlock(ast);
07489 if (ast_exists_extension(ast, target_context, "fax", 1,
07490 S_COR(ast->caller.id.number.valid, ast->caller.id.number.str, NULL))) {
07491 ast_channel_lock(ast);
07492 sip_pvt_lock(p);
07493 ast_verbose(VERBOSE_PREFIX_2 "Redirecting '%s' to fax extension due to CNG detection\n", ast->name);
07494 pbx_builtin_setvar_helper(ast, "FAXEXTEN", ast->exten);
07495 if (ast_async_goto(ast, target_context, "fax", 1)) {
07496 ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", ast->name, target_context);
07497 }
07498 fr = &ast_null_frame;
07499 } else {
07500 ast_channel_lock(ast);
07501 sip_pvt_lock(p);
07502 ast_log(LOG_NOTICE, "FAX CNG detected but no fax extension\n");
07503 }
07504 }
07505 }
07506
07507
07508 if (fr && fr->frametype == AST_FRAME_VOICE && p->invitestate != INV_EARLY_MEDIA && ast->_state != AST_STATE_UP) {
07509 fr = &ast_null_frame;
07510 }
07511
07512 sip_pvt_unlock(p);
07513
07514 return fr;
07515 }
07516
07517
07518
07519 static char *generate_random_string(char *buf, size_t size)
07520 {
07521 long val[4];
07522 int x;
07523
07524 for (x=0; x<4; x++)
07525 val[x] = ast_random();
07526 snprintf(buf, size, "%08lx%08lx%08lx%08lx", val[0], val[1], val[2], val[3]);
07527
07528 return buf;
07529 }
07530
07531 static char *generate_uri(struct sip_pvt *pvt, char *buf, size_t size)
07532 {
07533 struct ast_str *uri = ast_str_alloca(size);
07534 ast_str_set(&uri, 0, "%s", pvt->socket.type == SIP_TRANSPORT_TLS ? "sips:" : "sip:");
07535
07536
07537
07538 ast_str_append(&uri, 0, "%s", generate_random_string(buf, size));
07539 ast_str_append(&uri, 0, "@%s", ast_sockaddr_stringify_remote(&pvt->ourip));
07540 ast_copy_string(buf, ast_str_buffer(uri), size);
07541 return buf;
07542 }
07543
07544
07545
07546
07547
07548
07549
07550
07551 static void build_callid_pvt(struct sip_pvt *pvt)
07552 {
07553 char buf[33];
07554 const char *host = S_OR(pvt->fromdomain, ast_sockaddr_stringify_remote(&pvt->ourip));
07555
07556 ast_string_field_build(pvt, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
07557 }
07558
07559
07560 #define CONTAINER_UNLINK(container, obj, tag) \
07561 ({ \
07562 int found = 0; \
07563 typeof((obj)) __removed_obj; \
07564 __removed_obj = ao2_t_callback((container), \
07565 OBJ_UNLINK | OBJ_POINTER, ao2_match_by_addr, (obj), (tag)); \
07566 if (__removed_obj) { \
07567 ao2_ref(__removed_obj, -1); \
07568 found = 1; \
07569 } \
07570 found; \
07571 })
07572
07573
07574
07575
07576
07577
07578
07579
07580
07581
07582 static void change_callid_pvt(struct sip_pvt *pvt, const char *callid)
07583 {
07584 int in_dialog_container;
07585
07586 ao2_lock(dialogs);
07587 in_dialog_container = CONTAINER_UNLINK(dialogs, pvt,
07588 "About to change the callid -- remove the old name");
07589 if (callid) {
07590 ast_string_field_set(pvt, callid, callid);
07591 } else {
07592 build_callid_pvt(pvt);
07593 }
07594 if (in_dialog_container) {
07595 ao2_t_link(dialogs, pvt, "New dialog callid -- inserted back into table");
07596 }
07597 ao2_unlock(dialogs);
07598 }
07599
07600
07601 static void build_callid_registry(struct sip_registry *reg, const struct ast_sockaddr *ourip, const char *fromdomain)
07602 {
07603 char buf[33];
07604
07605 const char *host = S_OR(fromdomain, ast_sockaddr_stringify_host_remote(ourip));
07606
07607 ast_string_field_build(reg, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
07608 }
07609
07610
07611 static void make_our_tag(char *tagbuf, size_t len)
07612 {
07613 snprintf(tagbuf, len, "as%08lx", ast_random());
07614 }
07615
07616
07617 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p)
07618 {
07619 struct sip_st_dlg *stp;
07620
07621 if (p->stimer) {
07622 ast_log(LOG_ERROR, "Session-Timer struct already allocated\n");
07623 return p->stimer;
07624 }
07625
07626 if (!(stp = ast_calloc(1, sizeof(struct sip_st_dlg))))
07627 return NULL;
07628
07629 p->stimer = stp;
07630
07631 stp->st_schedid = -1;
07632
07633 return p->stimer;
07634 }
07635
07636
07637
07638
07639
07640 struct sip_pvt *sip_alloc(ast_string_field callid, struct ast_sockaddr *addr,
07641 int useglobal_nat, const int intended_method, struct sip_request *req)
07642 {
07643 struct sip_pvt *p;
07644
07645 if (!(p = ao2_t_alloc(sizeof(*p), sip_destroy_fn, "allocate a dialog(pvt) struct")))
07646 return NULL;
07647
07648 if (ast_string_field_init(p, 512)) {
07649 ao2_t_ref(p, -1, "failed to string_field_init, drop p");
07650 return NULL;
07651 }
07652
07653 if (!(p->cc_params = ast_cc_config_params_init())) {
07654 ao2_t_ref(p, -1, "Yuck, couldn't allocate cc_params struct. Get rid o' p");
07655 return NULL;
07656 }
07657
07658
07659
07660 if (req) {
07661 struct sip_via *via;
07662 const char *cseq = get_header(req, "Cseq");
07663 uint32_t seqno;
07664
07665
07666 via = parse_via(get_header(req, "Via"));
07667 if (via) {
07668
07669
07670 if (!ast_strlen_zero(via->branch) && !strncasecmp(via->branch, "z9hG4bK", 7)) {
07671 ast_string_field_set(p, initviabranch, via->branch);
07672 ast_string_field_set(p, initviasentby, via->sent_by);
07673 }
07674 free_via(via);
07675 }
07676
07677
07678
07679 if (!ast_strlen_zero(cseq) && (sscanf(cseq, "%30u", &seqno) == 1)) {
07680 p->init_icseq = seqno;
07681 }
07682
07683 set_socket_transport(&p->socket, req->socket.type);
07684 } else {
07685 set_socket_transport(&p->socket, SIP_TRANSPORT_UDP);
07686 }
07687
07688 p->socket.fd = -1;
07689 p->method = intended_method;
07690 p->initid = -1;
07691 p->waitid = -1;
07692 p->autokillid = -1;
07693 p->request_queue_sched_id = -1;
07694 p->provisional_keepalive_sched_id = -1;
07695 p->t38id = -1;
07696 p->subscribed = NONE;
07697 p->stateid = -1;
07698 p->sessionversion_remote = -1;
07699 p->session_modify = TRUE;
07700 p->stimer = NULL;
07701 p->prefs = default_prefs;
07702 p->maxforwards = sip_cfg.default_max_forwards;
07703
07704 if (intended_method != SIP_OPTIONS) {
07705 p->timer_t1 = global_t1;
07706 p->timer_b = global_timer_b;
07707 }
07708
07709 if (!addr) {
07710 p->ourip = internip;
07711 } else {
07712 ast_sockaddr_copy(&p->sa, addr);
07713 ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
07714 }
07715
07716
07717 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
07718 ast_copy_flags(&p->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
07719 ast_copy_flags(&p->flags[2], &global_flags[2], SIP_PAGE3_FLAGS_TO_COPY);
07720
07721 p->do_history = recordhistory;
07722
07723 p->branch = ast_random();
07724 make_our_tag(p->tag, sizeof(p->tag));
07725 p->ocseq = INITIAL_CSEQ;
07726 p->allowed_methods = UINT_MAX;
07727
07728 if (sip_methods[intended_method].need_rtp) {
07729 p->maxcallbitrate = default_maxcallbitrate;
07730 p->autoframing = global_autoframing;
07731 }
07732
07733 if (useglobal_nat && addr) {
07734
07735 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT_FORCE_RPORT);
07736 ast_sockaddr_copy(&p->recv, addr);
07737
07738 do_setnat(p);
07739 }
07740
07741 if (p->method != SIP_REGISTER) {
07742 ast_string_field_set(p, fromdomain, default_fromdomain);
07743 p->fromdomainport = default_fromdomainport;
07744 }
07745 build_via(p);
07746 if (!callid)
07747 build_callid_pvt(p);
07748 else
07749 ast_string_field_set(p, callid, callid);
07750
07751 ast_string_field_set(p, mohinterpret, default_mohinterpret);
07752 ast_string_field_set(p, mohsuggest, default_mohsuggest);
07753 p->capability = sip_cfg.capability;
07754 p->allowtransfer = sip_cfg.allowtransfer;
07755 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
07756 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
07757 p->noncodeccapability |= AST_RTP_DTMF;
07758 }
07759 ast_string_field_set(p, context, sip_cfg.default_context);
07760 ast_string_field_set(p, parkinglot, default_parkinglot);
07761 ast_string_field_set(p, engine, default_engine);
07762
07763 AST_LIST_HEAD_INIT_NOLOCK(&p->request_queue);
07764
07765
07766
07767 ao2_t_link(dialogs, p, "link pvt into dialogs table");
07768
07769 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");
07770 return p;
07771 }
07772
07773
07774
07775
07776
07777
07778
07779
07780 static int addr_is_multicast(const struct ast_sockaddr *addr)
07781 {
07782 return ((ast_sockaddr_ipv4(addr) & 0xf0000000) == 0xe0000000);
07783 }
07784
07785
07786
07787
07788
07789
07790
07791
07792
07793
07794
07795
07796
07797
07798
07799
07800 static int process_via(struct sip_pvt *p, const struct sip_request *req)
07801 {
07802 struct sip_via *via = parse_via(get_header(req, "Via"));
07803
07804 if (!via) {
07805 ast_log(LOG_ERROR, "error processing via header\n");
07806 return -1;
07807 }
07808
07809 if (via->maddr) {
07810 if (ast_sockaddr_resolve_first(&p->sa, via->maddr, PARSE_PORT_FORBID)) {
07811 ast_log(LOG_WARNING, "Can't find address for maddr '%s'\n", via->maddr);
07812 ast_log(LOG_ERROR, "error processing via header\n");
07813 free_via(via);
07814 return -1;
07815 }
07816
07817 if (addr_is_multicast(&p->sa)) {
07818 setsockopt(sipsock, IPPROTO_IP, IP_MULTICAST_TTL, &via->ttl, sizeof(via->ttl));
07819 }
07820 }
07821
07822 ast_sockaddr_set_port(&p->sa, via->port ? via->port : STANDARD_SIP_PORT);
07823
07824 free_via(via);
07825 return 0;
07826 }
07827
07828
07829 struct match_req_args {
07830 int method;
07831 const char *callid;
07832 const char *totag;
07833 const char *fromtag;
07834 uint32_t seqno;
07835
07836
07837 const char *ruri;
07838 const char *viabranch;
07839 const char *viasentby;
07840
07841
07842 int authentication_present;
07843 };
07844
07845 enum match_req_res {
07846 SIP_REQ_MATCH,
07847 SIP_REQ_NOT_MATCH,
07848 SIP_REQ_LOOP_DETECTED,
07849 };
07850
07851
07852
07853
07854
07855
07856 static enum match_req_res match_req_to_dialog(struct sip_pvt *sip_pvt_ptr, struct match_req_args *arg)
07857 {
07858 const char *init_ruri = NULL;
07859 if (sip_pvt_ptr->initreq.headers) {
07860 init_ruri = REQ_OFFSET_TO_STR(&sip_pvt_ptr->initreq, rlPart2);
07861 }
07862
07863
07864
07865
07866 if (!ast_strlen_zero(arg->callid) && strcmp(sip_pvt_ptr->callid, arg->callid)) {
07867
07868 return SIP_REQ_NOT_MATCH;
07869 }
07870 if (arg->method == SIP_RESPONSE) {
07871
07872
07873 if (!ast_strlen_zero(sip_pvt_ptr->theirtag) && ast_test_flag(&sip_pvt_ptr->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
07874 if (ast_strlen_zero(arg->totag)) {
07875
07876 return SIP_REQ_NOT_MATCH;
07877 }
07878 if (strcmp(arg->totag, sip_pvt_ptr->theirtag)) {
07879
07880 return SIP_REQ_NOT_MATCH;
07881 }
07882 }
07883
07884 if (strcmp(arg->fromtag, sip_pvt_ptr->tag)) {
07885
07886 return SIP_REQ_NOT_MATCH;
07887 }
07888 } else {
07889
07890
07891
07892 if (!arg->authentication_present && strcmp(arg->fromtag, sip_pvt_ptr->theirtag)) {
07893
07894 return SIP_REQ_NOT_MATCH;
07895 }
07896
07897 if (!ast_strlen_zero(arg->totag) && (strcmp(arg->totag, sip_pvt_ptr->tag))) {
07898
07899 return SIP_REQ_NOT_MATCH;
07900 }
07901 }
07902
07903
07904
07905
07906
07907
07908
07909
07910
07911
07912
07913
07914
07915
07916
07917
07918
07919 if ((arg->method != SIP_RESPONSE) &&
07920 ast_strlen_zero(arg->totag) &&
07921 (sip_pvt_ptr->init_icseq == arg->seqno) &&
07922 !ast_strlen_zero(sip_pvt_ptr->initviabranch) &&
07923 init_ruri) {
07924
07925
07926 if (ast_strlen_zero(arg->viabranch) ||
07927 strcmp(arg->viabranch, sip_pvt_ptr->initviabranch) ||
07928 ast_strlen_zero(arg->viasentby) ||
07929 strcmp(arg->viasentby, sip_pvt_ptr->initviasentby)) {
07930
07931
07932
07933 if ((sip_pvt_ptr->method != arg->method)) {
07934 return SIP_REQ_NOT_MATCH;
07935 }
07936
07937
07938
07939 if (sip_uri_cmp(init_ruri, arg->ruri)) {
07940
07941 return SIP_REQ_NOT_MATCH;
07942 }
07943
07944
07945
07946
07947
07948
07949
07950
07951
07952
07953
07954
07955
07956
07957
07958
07959
07960
07961
07962 return SIP_REQ_LOOP_DETECTED;
07963 }
07964 }
07965
07966
07967
07968
07969
07970
07971 if ((arg->method != SIP_RESPONSE) &&
07972 ast_strlen_zero(arg->totag) &&
07973 arg->authentication_present &&
07974 sip_uri_cmp(init_ruri, arg->ruri)) {
07975
07976
07977 return SIP_REQ_NOT_MATCH;
07978 }
07979
07980 return SIP_REQ_MATCH;
07981 }
07982
07983
07984
07985
07986
07987
07988
07989
07990
07991
07992
07993
07994
07995
07996
07997
07998
07999
08000 static struct ast_channel *sip_pvt_lock_full(struct sip_pvt *pvt)
08001 {
08002 struct ast_channel *chan;
08003
08004
08005
08006
08007 for (;;) {
08008
08009 sip_pvt_lock(pvt);
08010 chan = pvt->owner;
08011 if (chan) {
08012
08013
08014
08015 ast_channel_ref(chan);
08016 } else {
08017
08018 return NULL;
08019 }
08020
08021
08022
08023
08024 sip_pvt_unlock(pvt);
08025
08026
08027 ast_channel_lock(chan);
08028 sip_pvt_lock(pvt);
08029
08030 if (pvt->owner == chan) {
08031
08032 break;
08033 }
08034
08035
08036
08037
08038
08039
08040 ast_channel_unlock(chan);
08041 ast_channel_unref(chan);
08042 sip_pvt_unlock(pvt);
08043 }
08044
08045
08046 return pvt->owner;
08047 }
08048
08049
08050
08051
08052
08053
08054 static struct sip_pvt *find_call(struct sip_request *req, struct ast_sockaddr *addr, const int intended_method)
08055 {
08056 char totag[128];
08057 char fromtag[128];
08058 const char *callid = get_header(req, "Call-ID");
08059 const char *from = get_header(req, "From");
08060 const char *to = get_header(req, "To");
08061 const char *cseq = get_header(req, "Cseq");
08062 struct sip_pvt *sip_pvt_ptr;
08063 uint32_t seqno;
08064
08065
08066 if (ast_strlen_zero(callid) || ast_strlen_zero(to) ||
08067 ast_strlen_zero(from) || ast_strlen_zero(cseq) ||
08068 (sscanf(cseq, "%30u", &seqno) != 1)) {
08069
08070
08071 if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
08072 transmit_response_using_temp(callid, addr, 1, intended_method,
08073 req, "400 Bad Request");
08074 }
08075 return NULL;
08076 }
08077
08078 if (sip_cfg.pedanticsipchecking) {
08079
08080
08081
08082
08083
08084
08085 if (gettag(req, "To", totag, sizeof(totag)))
08086 req->has_to_tag = 1;
08087 gettag(req, "From", fromtag, sizeof(fromtag));
08088
08089 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);
08090
08091
08092 if (ast_strlen_zero(fromtag)) {
08093 ast_debug(5, "%s request has no from tag, dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
08094 return NULL;
08095 }
08096
08097 if (ast_strlen_zero(totag) && (req->method == SIP_ACK || req->method == SIP_BYE || req->method == SIP_INFO )) {
08098 ast_debug(5, "%s must have a to tag. dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
08099 return NULL;
08100 }
08101 }
08102
08103 if (!sip_cfg.pedanticsipchecking) {
08104 struct sip_pvt tmp_dialog = {
08105 .callid = callid,
08106 };
08107 sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find in dialogs");
08108 if (sip_pvt_ptr) {
08109
08110 return sip_pvt_ptr;
08111 }
08112 } else {
08113 struct sip_pvt tmp_dialog = {
08114 .callid = callid,
08115 };
08116 struct match_req_args args = { 0, };
08117 int found;
08118 struct ao2_iterator *iterator = ao2_t_callback(dialogs,
08119 OBJ_POINTER | OBJ_MULTIPLE,
08120 dialog_find_multiple,
08121 &tmp_dialog,
08122 "pedantic ao2_find in dialogs");
08123 struct sip_via *via = NULL;
08124
08125 args.method = req->method;
08126 args.callid = NULL;
08127 args.totag = totag;
08128 args.fromtag = fromtag;
08129 args.seqno = seqno;
08130
08131
08132 if (req->method != SIP_RESPONSE) {
08133 args.ruri = REQ_OFFSET_TO_STR(req, rlPart2);
08134 via = parse_via(get_header(req, "Via"));
08135 if (via) {
08136 args.viasentby = via->sent_by;
08137 args.viabranch = via->branch;
08138 }
08139 if (!ast_strlen_zero(get_header(req, "Authorization")) ||
08140 !ast_strlen_zero(get_header(req, "Proxy-Authorization"))) {
08141 args.authentication_present = 1;
08142 }
08143 }
08144
08145
08146 while (iterator && (sip_pvt_ptr = ao2_iterator_next(iterator))) {
08147 found = match_req_to_dialog(sip_pvt_ptr, &args);
08148
08149 switch (found) {
08150 case SIP_REQ_MATCH:
08151 ao2_iterator_destroy(iterator);
08152 free_via(via);
08153 return sip_pvt_ptr;
08154 case SIP_REQ_LOOP_DETECTED:
08155
08156
08157 transmit_response_using_temp(callid, addr, 1, intended_method, req, "482 (Loop Detected)");
08158 dialog_unref(sip_pvt_ptr, "pvt did not match incoming SIP msg, unref from search.");
08159 ao2_iterator_destroy(iterator);
08160 free_via(via);
08161 return NULL;
08162 case SIP_REQ_NOT_MATCH:
08163 default:
08164 dialog_unref(sip_pvt_ptr, "pvt did not match incoming SIP msg, unref from search");
08165 }
08166 }
08167 if (iterator) {
08168 ao2_iterator_destroy(iterator);
08169 }
08170
08171 free_via(via);
08172 }
08173
08174
08175 if (sip_methods[intended_method].can_create == CAN_CREATE_DIALOG) {
08176 struct sip_pvt *p = NULL;
08177
08178 if (intended_method == SIP_REFER) {
08179
08180 transmit_response_using_temp(callid, addr, 1, intended_method, req, "603 Declined (no dialog)");
08181
08182
08183 } else if (!(p = sip_alloc(callid, addr, 1, intended_method, req))) {
08184
08185
08186
08187
08188
08189
08190
08191
08192 transmit_response_using_temp(callid, addr, 1, intended_method, req, "500 Server internal error");
08193 ast_debug(4, "Failed allocating SIP dialog, sending 500 Server internal error and giving up\n");
08194 }
08195 return p;
08196 } else if( sip_methods[intended_method].can_create == CAN_CREATE_DIALOG_UNSUPPORTED_METHOD) {
08197
08198 transmit_response_using_temp(callid, addr, 1, intended_method, req, "501 Method Not Implemented");
08199 ast_debug(2, "Got a request with unsupported SIP method.\n");
08200 } else if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
08201
08202 transmit_response_using_temp(callid, addr, 1, intended_method, req, "481 Call leg/transaction does not exist");
08203 ast_debug(2, "That's odd... Got a request in unknown dialog. Callid %s\n", callid ? callid : "<unknown>");
08204 }
08205
08206
08207 if (intended_method == SIP_RESPONSE)
08208 ast_debug(2, "That's odd... Got a response on a call we don't know about. Callid %s\n", callid ? callid : "<unknown>");
08209
08210 return NULL;
08211 }
08212
08213
08214 static int sip_register(const char *value, int lineno)
08215 {
08216 struct sip_registry *reg;
08217
08218 if (!(reg = ast_calloc_with_stringfields(1, struct sip_registry, 256))) {
08219 ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry entry\n");
08220 return -1;
08221 }
08222
08223 ast_atomic_fetchadd_int(®objs, 1);
08224 ASTOBJ_INIT(reg);
08225
08226 if (sip_parse_register_line(reg, default_expiry, value, lineno)) {
08227 registry_unref(reg, "failure to parse, unref the reg pointer");
08228 return -1;
08229 }
08230
08231
08232 if (reg->refresh && !reg->expiry && !reg->configured_expiry) {
08233 reg->refresh = reg->expiry = reg->configured_expiry = default_expiry;
08234 }
08235
08236
08237 ASTOBJ_CONTAINER_LINK(®l, reg);
08238
08239
08240 registry_unref(reg, "unref the reg pointer");
08241
08242 return 0;
08243 }
08244
08245
08246 static int sip_subscribe_mwi(const char *value, int lineno)
08247 {
08248 struct sip_subscription_mwi *mwi;
08249 int portnum = 0;
08250 enum sip_transport transport = SIP_TRANSPORT_UDP;
08251 char buf[256] = "";
08252 char *username = NULL, *hostname = NULL, *secret = NULL, *authuser = NULL, *porta = NULL, *mailbox = NULL, *at = NULL;
08253
08254 if (!value) {
08255 return -1;
08256 }
08257
08258 ast_copy_string(buf, value, sizeof(buf));
08259
08260 if (!(at = strstr(buf, "@"))) {
08261 return -1;
08262 }
08263
08264 if ((hostname = strrchr(buf, '@'))) {
08265 *hostname++ = '\0';
08266 username = buf;
08267 }
08268
08269 if ((secret = strchr(username, ':'))) {
08270 *secret++ = '\0';
08271 if ((authuser = strchr(secret, ':'))) {
08272 *authuser++ = '\0';
08273 }
08274 }
08275
08276 if ((mailbox = strchr(hostname, '/'))) {
08277 *mailbox++ = '\0';
08278 }
08279
08280 if (ast_strlen_zero(username) || ast_strlen_zero(hostname) || ast_strlen_zero(mailbox)) {
08281 ast_log(LOG_WARNING, "Format for MWI subscription is user[:secret[:authuser]]@host[:port]/mailbox at line %d\n", lineno);
08282 return -1;
08283 }
08284
08285 if ((porta = strchr(hostname, ':'))) {
08286 *porta++ = '\0';
08287 if (!(portnum = atoi(porta))) {
08288 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
08289 return -1;
08290 }
08291 }
08292
08293 if (!(mwi = ast_calloc_with_stringfields(1, struct sip_subscription_mwi, 256))) {
08294 return -1;
08295 }
08296
08297 ASTOBJ_INIT(mwi);
08298 ast_string_field_set(mwi, username, username);
08299 if (secret) {
08300 ast_string_field_set(mwi, secret, secret);
08301 }
08302 if (authuser) {
08303 ast_string_field_set(mwi, authuser, authuser);
08304 }
08305 ast_string_field_set(mwi, hostname, hostname);
08306 ast_string_field_set(mwi, mailbox, mailbox);
08307 mwi->resub = -1;
08308 mwi->portno = portnum;
08309 mwi->transport = transport;
08310
08311 ASTOBJ_CONTAINER_LINK(&submwil, mwi);
08312 ASTOBJ_UNREF(mwi, sip_subscribe_mwi_destroy);
08313
08314 return 0;
08315 }
08316
08317 static void mark_method_allowed(unsigned int *allowed_methods, enum sipmethod method)
08318 {
08319 (*allowed_methods) |= (1 << method);
08320 }
08321
08322 static void mark_method_unallowed(unsigned int *allowed_methods, enum sipmethod method)
08323 {
08324 (*allowed_methods) &= ~(1 << method);
08325 }
08326
08327
08328 static int is_method_allowed(unsigned int *allowed_methods, enum sipmethod method)
08329 {
08330 return ((*allowed_methods) >> method) & 1;
08331 }
08332
08333 static void mark_parsed_methods(unsigned int *methods, char *methods_str)
08334 {
08335 char *method;
08336 for (method = strsep(&methods_str, ","); !ast_strlen_zero(method); method = strsep(&methods_str, ",")) {
08337 int id = find_sip_method(ast_skip_blanks(method));
08338 if (id == SIP_UNKNOWN) {
08339 continue;
08340 }
08341 mark_method_allowed(methods, id);
08342 }
08343 }
08344
08345
08346
08347
08348
08349
08350
08351
08352
08353
08354
08355
08356
08357
08358
08359
08360 static unsigned int parse_allowed_methods(struct sip_request *req)
08361 {
08362 char *allow = ast_strdupa(get_header(req, "Allow"));
08363 unsigned int allowed_methods = SIP_UNKNOWN;
08364
08365 if (ast_strlen_zero(allow)) {
08366
08367
08368
08369
08370 char *contact = ast_strdupa(get_header(req, "Contact"));
08371 char *methods = strstr(contact, ";methods=");
08372
08373 if (ast_strlen_zero(methods)) {
08374
08375
08376
08377
08378
08379
08380
08381
08382
08383
08384
08385 return UINT_MAX;
08386 }
08387 allow = ast_strip_quoted(methods + 9, "\"", "\"");
08388 }
08389 mark_parsed_methods(&allowed_methods, allow);
08390 return allowed_methods;
08391 }
08392
08393
08394
08395
08396
08397
08398
08399
08400
08401
08402 static unsigned int set_pvt_allowed_methods(struct sip_pvt *pvt, struct sip_request *req)
08403 {
08404 pvt->allowed_methods = parse_allowed_methods(req);
08405
08406 if (ast_test_flag(&pvt->flags[1], SIP_PAGE2_RPID_UPDATE)) {
08407 mark_method_allowed(&pvt->allowed_methods, SIP_UPDATE);
08408 }
08409 pvt->allowed_methods &= ~(pvt->disallowed_methods);
08410
08411 return pvt->allowed_methods;
08412 }
08413
08414
08415
08416 static void lws2sws(struct ast_str *data)
08417 {
08418 char *msgbuf = data->str;
08419 int len = ast_str_strlen(data);
08420 int h = 0, t = 0;
08421 int lws = 0;
08422
08423 for (; h < len;) {
08424
08425 if (msgbuf[h] == '\r') {
08426 h++;
08427 continue;
08428 }
08429
08430 if (msgbuf[h] == '\n') {
08431
08432 if (h + 1 == len)
08433 break;
08434
08435 if (msgbuf[h + 1] == ' ' || msgbuf[h + 1] == '\t') {
08436
08437 h++;
08438 continue;
08439 }
08440
08441 msgbuf[t++] = msgbuf[h++];
08442 lws = 0;
08443 continue;
08444 }
08445 if (msgbuf[h] == ' ' || msgbuf[h] == '\t') {
08446 if (lws) {
08447 h++;
08448 continue;
08449 }
08450 msgbuf[t++] = msgbuf[h++];
08451 lws = 1;
08452 continue;
08453 }
08454 msgbuf[t++] = msgbuf[h++];
08455 if (lws)
08456 lws = 0;
08457 }
08458 msgbuf[t] = '\0';
08459 data->used = t;
08460 }
08461
08462
08463
08464
08465 static int parse_request(struct sip_request *req)
08466 {
08467 char *c = req->data->str;
08468 ptrdiff_t *dst = req->header;
08469 int i = 0, lim = SIP_MAX_HEADERS - 1;
08470 unsigned int skipping_headers = 0;
08471 ptrdiff_t current_header_offset = 0;
08472 char *previous_header = "";
08473
08474 req->header[0] = 0;
08475 req->headers = -1;
08476 for (; *c; c++) {
08477 if (*c == '\r') {
08478 *c = '\0';
08479 } else if (*c == '\n') {
08480 *c = '\0';
08481 current_header_offset = (c + 1) - req->data->str;
08482 previous_header = req->data->str + dst[i];
08483 if (skipping_headers) {
08484
08485
08486
08487 if (ast_strlen_zero(previous_header)) {
08488 skipping_headers = 0;
08489 }
08490 dst[i] = current_header_offset;
08491 continue;
08492 }
08493 if (sipdebug) {
08494 ast_debug(4, "%7s %2d [%3d]: %s\n",
08495 req->headers < 0 ? "Header" : "Body",
08496 i, (int) strlen(previous_header), previous_header);
08497 }
08498 if (ast_strlen_zero(previous_header) && req->headers < 0) {
08499 req->headers = i;
08500 dst = req->line;
08501 i = 0;
08502 lim = SIP_MAX_LINES - 1;
08503 } else {
08504 if (i++ == lim) {
08505
08506
08507
08508 if (req->headers != -1) {
08509 break;
08510 } else {
08511 req->headers = i;
08512 dst = req->line;
08513 i = 0;
08514 lim = SIP_MAX_LINES - 1;
08515 skipping_headers = 1;
08516 }
08517 }
08518 }
08519 dst[i] = current_header_offset;
08520 }
08521 }
08522
08523
08524
08525
08526
08527
08528 previous_header = req->data->str + dst[i];
08529 if ((i < lim) && !ast_strlen_zero(previous_header)) {
08530 if (sipdebug) {
08531 ast_debug(4, "%7s %2d [%3d]: %s\n",
08532 req->headers < 0 ? "Header" : "Body",
08533 i, (int) strlen(previous_header), previous_header );
08534 }
08535 i++;
08536 }
08537
08538
08539 if (req->headers >= 0) {
08540 req->lines = i;
08541 } else {
08542 req->headers = i;
08543 req->lines = 0;
08544
08545 req->line[0] = ast_str_strlen(req->data);
08546 }
08547
08548 if (*c) {
08549 ast_log(LOG_WARNING, "Too many lines, skipping <%s>\n", c);
08550 }
08551
08552
08553 return determine_firstline_parts(req);
08554 }
08555
08556
08557
08558
08559
08560
08561
08562
08563
08564 static int find_sdp(struct sip_request *req)
08565 {
08566 const char *content_type;
08567 const char *content_length;
08568 const char *search;
08569 char *boundary;
08570 unsigned int x;
08571 int boundaryisquoted = FALSE;
08572 int found_application_sdp = FALSE;
08573 int found_end_of_headers = FALSE;
08574
08575 content_length = get_header(req, "Content-Length");
08576
08577 if (!ast_strlen_zero(content_length)) {
08578 if (sscanf(content_length, "%30u", &x) != 1) {
08579 ast_log(LOG_WARNING, "Invalid Content-Length: %s\n", content_length);
08580 return 0;
08581 }
08582
08583
08584
08585 if (x == 0)
08586 return 0;
08587 }
08588
08589 content_type = get_header(req, "Content-Type");
08590
08591
08592 if (!strncasecmp(content_type, "application/sdp", 15)) {
08593 req->sdp_start = 0;
08594 req->sdp_count = req->lines;
08595 return req->lines ? 1 : 0;
08596 }
08597
08598
08599 if (strncasecmp(content_type, "multipart/mixed", 15))
08600 return 0;
08601
08602
08603 if ((search = strcasestr(content_type, ";boundary=")))
08604 search += 10;
08605 else if ((search = strcasestr(content_type, "; boundary=")))
08606 search += 11;
08607 else
08608 return 0;
08609
08610 if (ast_strlen_zero(search))
08611 return 0;
08612
08613
08614 if (*search == '\"') {
08615 search++;
08616 boundaryisquoted = TRUE;
08617 }
08618
08619
08620
08621 boundary = ast_strdupa(search - 2);
08622 boundary[0] = boundary[1] = '-';
08623
08624 if (boundaryisquoted)
08625 boundary[strlen(boundary) - 1] = '\0';
08626
08627
08628
08629
08630 for (x = 0; x < (req->lines); x++) {
08631 const char *line = REQ_OFFSET_TO_STR(req, line[x]);
08632 if (!strncasecmp(line, boundary, strlen(boundary))){
08633 if (found_application_sdp && found_end_of_headers) {
08634 req->sdp_count = (x - 1) - req->sdp_start;
08635 return 1;
08636 }
08637 found_application_sdp = FALSE;
08638 }
08639 if (!strcasecmp(line, "Content-Type: application/sdp"))
08640 found_application_sdp = TRUE;
08641
08642 if (ast_strlen_zero(line)) {
08643 if (found_application_sdp && !found_end_of_headers){
08644 req->sdp_start = x;
08645 found_end_of_headers = TRUE;
08646 }
08647 }
08648 }
08649 if (found_application_sdp && found_end_of_headers) {
08650 req->sdp_count = x - req->sdp_start;
08651 return TRUE;
08652 }
08653 return FALSE;
08654 }
08655
08656
08657 static void change_hold_state(struct sip_pvt *dialog, struct sip_request *req, int holdstate, int sendonly)
08658 {
08659 if (sip_cfg.notifyhold && (!holdstate || !ast_test_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD)))
08660 sip_peer_hold(dialog, holdstate);
08661 if (sip_cfg.callevents)
08662 manager_event(EVENT_FLAG_CALL, "Hold",
08663 "Status: %s\r\n"
08664 "Channel: %s\r\n"
08665 "Uniqueid: %s\r\n",
08666 holdstate ? "On" : "Off",
08667 dialog->owner->name,
08668 dialog->owner->uniqueid);
08669 append_history(dialog, holdstate ? "Hold" : "Unhold", "%s", req->data->str);
08670 if (!holdstate) {
08671 ast_clear_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD);
08672 return;
08673 }
08674
08675
08676 if (sendonly == 1)
08677 ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_ONEDIR);
08678 else if (sendonly == 2)
08679 ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_INACTIVE);
08680 else
08681 ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_ACTIVE);
08682 return;
08683 }
08684
08685
08686 static int get_ip_and_port_from_sdp(struct sip_request *req, const enum media_type media, struct ast_sockaddr *addr)
08687 {
08688 const char *m;
08689 const char *c;
08690 int miterator = req->sdp_start;
08691 int citerator = req->sdp_start;
08692 int x = 0;
08693 int numberofports;
08694 int len;
08695 int af;
08696 char proto[4], host[258] = "";
08697
08698 c = get_sdp_iterate(&citerator, req, "c");
08699 if (sscanf(c, "IN %3s %256s", proto, host) != 2) {
08700 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
08701
08702 }
08703
08704 for (m = get_sdp_iterate(&miterator, req, "m"); !ast_strlen_zero(m); m = get_sdp_iterate(&miterator, req, "m")) {
08705 if ((media == SDP_AUDIO && ((sscanf(m, "audio %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08706 (sscanf(m, "audio %30u RTP/AVP %n", &x, &len) == 1 && len > 0))) ||
08707 (media == SDP_VIDEO && ((sscanf(m, "video %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08708 (sscanf(m, "video %30u RTP/AVP %n", &x, &len) == 1 && len > 0)))) {
08709
08710
08711
08712
08713 c = get_sdp_iterate(&citerator, req, "c");
08714 if (!ast_strlen_zero(c)) {
08715 sscanf(c, "IN %3s %256s", proto, host);
08716 }
08717 break;
08718 }
08719 }
08720
08721 if (!strcmp("IP4", proto)) {
08722 af = AF_INET;
08723 } else if (!strcmp("IP6", proto)) {
08724 af = AF_INET6;
08725 } else {
08726 ast_log(LOG_WARNING, "Unknown protocol '%s'.\n", proto);
08727 return -1;
08728 }
08729
08730 if (ast_strlen_zero(host) || x == 0) {
08731 ast_log(LOG_WARNING, "Failed to read an alternate host or port in SDP. Expect %s problems\n", media == SDP_AUDIO ? "audio" : "video");
08732 return -1;
08733 }
08734
08735 if (ast_sockaddr_resolve_first_af(addr, host, 0, af)) {
08736 ast_log(LOG_WARNING, "Could not look up IP address of alternate hostname. Expect %s problems\n", media == SDP_AUDIO? "audio" : "video");
08737 return -1;
08738 }
08739
08740 return 0;
08741 }
08742
08743
08744
08745
08746
08747
08748
08749 static int sockaddr_is_null_or_any(const struct ast_sockaddr *addr)
08750 {
08751 return ast_sockaddr_isnull(addr) || ast_sockaddr_is_any(addr);
08752 }
08753
08754
08755
08756
08757
08758
08759 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action)
08760 {
08761
08762 int start = req->sdp_start;
08763 int next = start;
08764 int iterator = start;
08765
08766
08767 char type = '\0';
08768 const char *value = NULL;
08769 const char *m = NULL;
08770 const char *nextm = NULL;
08771 int len = -1;
08772
08773
08774 struct ast_sockaddr sessionsa;
08775 struct ast_sockaddr audiosa;
08776 struct ast_sockaddr videosa;
08777 struct ast_sockaddr textsa;
08778 struct ast_sockaddr imagesa;
08779 struct ast_sockaddr *sa = NULL;
08780 struct ast_sockaddr *vsa = NULL;
08781 struct ast_sockaddr *tsa = NULL;
08782 struct ast_sockaddr *isa = NULL;
08783 int portno = -1;
08784 int vportno = -1;
08785 int tportno = -1;
08786 int udptlportno = -1;
08787
08788
08789 format_t peercapability = 0, vpeercapability = 0, tpeercapability = 0;
08790 int peernoncodeccapability = 0, vpeernoncodeccapability = 0, tpeernoncodeccapability = 0;
08791
08792 struct ast_rtp_codecs newaudiortp, newvideortp, newtextrtp;
08793 format_t newjointcapability;
08794 format_t newpeercapability;
08795 int newnoncodeccapability;
08796
08797 const char *codecs;
08798 int codec;
08799
08800
08801 int secure_audio = FALSE;
08802 int secure_video = FALSE;
08803
08804
08805 int sendonly = -1;
08806 int vsendonly = -1;
08807 int numberofports;
08808 int numberofmediastreams = 0;
08809 int last_rtpmap_codec = 0;
08810 int red_data_pt[10];
08811 int red_num_gen = 0;
08812 char red_fmtp[100] = "empty";
08813 int debug = sip_debug_test_pvt(p);
08814
08815
08816 char buf[SIPBUFSIZE];
08817
08818
08819
08820 if (!p->rtp) {
08821 ast_log(LOG_ERROR, "Got SDP but have no RTP session allocated.\n");
08822 return -1;
08823 }
08824
08825
08826 ast_rtp_codecs_payloads_clear(&newaudiortp, NULL);
08827 ast_rtp_codecs_payloads_clear(&newvideortp, NULL);
08828 ast_rtp_codecs_payloads_clear(&newtextrtp, NULL);
08829
08830
08831 p->lastrtprx = p->lastrtptx = time(NULL);
08832
08833 memset(p->offered_media, 0, sizeof(p->offered_media));
08834
08835
08836
08837 p->novideo = TRUE;
08838 p->notext = TRUE;
08839
08840 if (p->vrtp) {
08841 ast_rtp_codecs_payloads_clear(&newvideortp, NULL);
08842 }
08843
08844 if (p->trtp) {
08845 ast_rtp_codecs_payloads_clear(&newtextrtp, NULL);
08846 }
08847
08848
08849 nextm = get_sdp_iterate(&next, req, "m");
08850 if (ast_strlen_zero(nextm)) {
08851 ast_log(LOG_WARNING, "Insufficient information for SDP (m= not found)\n");
08852 return -1;
08853 }
08854
08855
08856 while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
08857 int processed = FALSE;
08858 switch (type) {
08859 case 'o':
08860
08861
08862
08863 if (!process_sdp_o(value, p))
08864 return (p->session_modify == FALSE) ? 0 : -1;
08865 break;
08866 case 'c':
08867 if (process_sdp_c(value, &sessionsa)) {
08868 processed = TRUE;
08869 sa = &sessionsa;
08870 vsa = sa;
08871 tsa = sa;
08872 isa = sa;
08873 }
08874 break;
08875 case 'a':
08876 if (process_sdp_a_sendonly(value, &sendonly)) {
08877 processed = TRUE;
08878 vsendonly = sendonly;
08879 }
08880 else if (process_sdp_a_audio(value, p, &newaudiortp, &last_rtpmap_codec))
08881 processed = TRUE;
08882 else if (process_sdp_a_video(value, p, &newvideortp, &last_rtpmap_codec))
08883 processed = TRUE;
08884 else if (process_sdp_a_text(value, p, &newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec))
08885 processed = TRUE;
08886 else if (process_sdp_a_image(value, p))
08887 processed = TRUE;
08888 break;
08889 }
08890
08891 ast_debug(3, "Processing session-level SDP %c=%s... %s\n", type, value, (processed == TRUE)? "OK." : "UNSUPPORTED.");
08892 }
08893
08894
08895
08896
08897 while (!ast_strlen_zero(nextm)) {
08898 int audio = FALSE;
08899 int video = FALSE;
08900 int image = FALSE;
08901 int text = FALSE;
08902 char protocol[5] = {0,};
08903 int x;
08904
08905 numberofports = 1;
08906 len = -1;
08907 start = next;
08908 m = nextm;
08909 iterator = next;
08910 nextm = get_sdp_iterate(&next, req, "m");
08911
08912
08913 if ((sscanf(m, "audio %30u/%30u RTP/%4s %n", &x, &numberofports, protocol, &len) == 3 && len > 0) ||
08914 (sscanf(m, "audio %30u RTP/%4s %n", &x, protocol, &len) == 2 && len > 0)) {
08915 if (x == 0) {
08916 ast_log(LOG_WARNING, "ignoring 'audio' media offer because port number is zero");
08917 continue;
08918 }
08919 if (!strcmp(protocol, "SAVP")) {
08920 secure_audio = 1;
08921 } else if (strcmp(protocol, "AVP")) {
08922 ast_log(LOG_WARNING, "unknown SDP media protocol in offer: %s\n", protocol);
08923 continue;
08924 }
08925 if (p->offered_media[SDP_AUDIO].order_offered) {
08926 ast_log(LOG_WARNING, "Multiple audio streams are not supported\n");
08927 return -3;
08928 }
08929 audio = TRUE;
08930 p->offered_media[SDP_AUDIO].order_offered = ++numberofmediastreams;
08931 portno = x;
08932
08933
08934 codecs = m + len;
08935 ast_copy_string(p->offered_media[SDP_AUDIO].codecs, codecs, sizeof(p->offered_media[SDP_AUDIO].codecs));
08936 for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
08937 if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
08938 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
08939 return -1;
08940 }
08941 if (debug)
08942 ast_verbose("Found RTP audio format %d\n", codec);
08943
08944 ast_rtp_codecs_payloads_set_m_type(&newaudiortp, NULL, codec);
08945 }
08946
08947 } else if ((sscanf(m, "video %30u/%30u RTP/%4s %n", &x, &numberofports, protocol, &len) == 3 && len > 0) ||
08948 (sscanf(m, "video %30u RTP/%4s %n", &x, protocol, &len) == 2 && len > 0)) {
08949 if (x == 0) {
08950 ast_log(LOG_WARNING, "ignoring 'video' media offer because port number is zero");
08951 continue;
08952 }
08953 if (!strcmp(protocol, "SAVP")) {
08954 secure_video = 1;
08955 } else if (strcmp(protocol, "AVP")) {
08956 ast_log(LOG_WARNING, "unknown SDP media protocol in offer: %s\n", protocol);
08957 continue;
08958 }
08959 if (p->offered_media[SDP_VIDEO].order_offered) {
08960 ast_log(LOG_WARNING, "Multiple video streams are not supported\n");
08961 return -3;
08962 }
08963 video = TRUE;
08964 p->novideo = FALSE;
08965 p->offered_media[SDP_VIDEO].order_offered = ++numberofmediastreams;
08966 vportno = x;
08967
08968
08969 codecs = m + len;
08970 ast_copy_string(p->offered_media[SDP_VIDEO].codecs, codecs, sizeof(p->offered_media[SDP_VIDEO].codecs));
08971 for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
08972 if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
08973 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
08974 return -1;
08975 }
08976 if (debug)
08977 ast_verbose("Found RTP video format %d\n", codec);
08978 ast_rtp_codecs_payloads_set_m_type(&newvideortp, NULL, codec);
08979 }
08980
08981 } else if ((sscanf(m, "text %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08982 (sscanf(m, "text %30u RTP/AVP %n", &x, &len) == 1 && len > 0)) {
08983 if (x == 0) {
08984 ast_log(LOG_WARNING, "ignoring 'text' media offer because port number is zero");
08985 continue;
08986 }
08987 if (p->offered_media[SDP_TEXT].order_offered) {
08988 ast_log(LOG_WARNING, "Multiple text streams are not supported\n");
08989 return -3;
08990 }
08991 text = TRUE;
08992 p->notext = FALSE;
08993 p->offered_media[SDP_TEXT].order_offered = ++numberofmediastreams;
08994 tportno = x;
08995
08996
08997 codecs = m + len;
08998 ast_copy_string(p->offered_media[SDP_TEXT].codecs, codecs, sizeof(p->offered_media[SDP_TEXT].codecs));
08999 for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
09000 if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
09001 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
09002 return -1;
09003 }
09004 if (debug)
09005 ast_verbose("Found RTP text format %d\n", codec);
09006 ast_rtp_codecs_payloads_set_m_type(&newtextrtp, NULL, codec);
09007 }
09008
09009 } else if (((sscanf(m, "image %30u udptl t38%n", &x, &len) == 1 && len > 0) ||
09010 (sscanf(m, "image %30u UDPTL t38%n", &x, &len) == 1 && len > 0))) {
09011 if (x == 0) {
09012 ast_log(LOG_WARNING, "ignoring 'image' media offer because port number is zero");
09013 continue;
09014 }
09015 if (initialize_udptl(p)) {
09016 continue;
09017 }
09018
09019 if (p->offered_media[SDP_IMAGE].order_offered) {
09020 ast_log(LOG_WARNING, "Multiple T.38 streams are not supported\n");
09021 return -3;
09022 }
09023 image = TRUE;
09024 if (debug)
09025 ast_verbose("Got T.38 offer in SDP in dialog %s\n", p->callid);
09026 p->offered_media[SDP_IMAGE].order_offered = ++numberofmediastreams;
09027 udptlportno = x;
09028
09029 if (p->t38.state != T38_ENABLED) {
09030 memset(&p->t38.their_parms, 0, sizeof(p->t38.their_parms));
09031
09032
09033
09034 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
09035 }
09036 } else {
09037 ast_log(LOG_WARNING, "Unsupported SDP media type in offer: %s\n", m);
09038 continue;
09039 }
09040
09041
09042 if (numberofports > 1)
09043 ast_log(LOG_WARNING, "SDP offered %d ports for media, not supported by Asterisk. Will try anyway...\n", numberofports);
09044
09045
09046 while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
09047 int processed = FALSE;
09048
09049 switch (type) {
09050 case 'c':
09051 if (audio) {
09052 if (process_sdp_c(value, &audiosa)) {
09053 processed = TRUE;
09054 sa = &audiosa;
09055 }
09056 } else if (video) {
09057 if (process_sdp_c(value, &videosa)) {
09058 processed = TRUE;
09059 vsa = &videosa;
09060 }
09061 } else if (text) {
09062 if (process_sdp_c(value, &textsa)) {
09063 processed = TRUE;
09064 tsa = &textsa;
09065 }
09066 } else if (image) {
09067 if (process_sdp_c(value, &imagesa)) {
09068 processed = TRUE;
09069 isa = &imagesa;
09070 }
09071 }
09072 break;
09073 case 'a':
09074
09075 if (audio) {
09076 if (process_sdp_a_sendonly(value, &sendonly))
09077 processed = TRUE;
09078 else if (process_crypto(p, p->rtp, &p->srtp, value))
09079 processed = TRUE;
09080 else if (process_sdp_a_audio(value, p, &newaudiortp, &last_rtpmap_codec))
09081 processed = TRUE;
09082 }
09083
09084 else if (video) {
09085 if (process_sdp_a_sendonly(value, &vsendonly))
09086 processed = TRUE;
09087 else if (process_crypto(p, p->vrtp, &p->vsrtp, value))
09088 processed = TRUE;
09089 else if (process_sdp_a_video(value, p, &newvideortp, &last_rtpmap_codec))
09090 processed = TRUE;
09091 }
09092
09093 else if (text) {
09094 if (process_sdp_a_text(value, p, &newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec))
09095 processed = TRUE;
09096 else if (process_crypto(p, p->trtp, &p->tsrtp, value))
09097 processed = TRUE;
09098 }
09099
09100 else if (image) {
09101 if (process_sdp_a_image(value, p))
09102 processed = TRUE;
09103 }
09104 break;
09105 }
09106
09107 ast_debug(3, "Processing media-level (%s) SDP %c=%s... %s\n",
09108 (audio == TRUE)? "audio" : (video == TRUE)? "video" : "image",
09109 type, value,
09110 (processed == TRUE)? "OK." : "UNSUPPORTED.");
09111 }
09112 }
09113
09114
09115
09116 if (!sa && !vsa && !tsa && !isa) {
09117 ast_log(LOG_WARNING, "Insufficient information in SDP (c=)...\n");
09118 return -1;
09119 }
09120
09121 if (portno == -1 && vportno == -1 && udptlportno == -1 && tportno == -1) {
09122
09123
09124 ast_log(LOG_WARNING, "Failing due to no acceptable offer found\n");
09125 return -2;
09126 }
09127
09128 if (secure_audio && !(p->srtp && (ast_test_flag(p->srtp, SRTP_CRYPTO_OFFER_OK)))) {
09129 ast_log(LOG_WARNING, "Can't provide secure audio requested in SDP offer\n");
09130 return -4;
09131 }
09132
09133 if (!secure_audio && p->srtp) {
09134 ast_log(LOG_WARNING, "We are requesting SRTP, but they responded without it!\n");
09135 return -4;
09136 }
09137
09138 if (secure_video && !(p->vsrtp && (ast_test_flag(p->vsrtp, SRTP_CRYPTO_OFFER_OK)))) {
09139 ast_log(LOG_WARNING, "Can't provide secure video requested in SDP offer\n");
09140 return -4;
09141 }
09142
09143 if (!p->novideo && !secure_video && p->vsrtp) {
09144 ast_log(LOG_WARNING, "We are requesting SRTP, but they responded without it!\n");
09145 return -4;
09146 }
09147
09148 if (!(secure_audio || secure_video) && ast_test_flag(&p->flags[1], SIP_PAGE2_USE_SRTP)) {
09149 ast_log(LOG_WARNING, "Matched device setup to use SRTP, but request was not!\n");
09150 return -4;
09151 }
09152
09153 if (udptlportno == -1) {
09154 change_t38_state(p, T38_DISABLED);
09155 }
09156
09157
09158 ast_rtp_codecs_payload_formats(&newaudiortp, &peercapability, &peernoncodeccapability);
09159 ast_rtp_codecs_payload_formats(&newvideortp, &vpeercapability, &vpeernoncodeccapability);
09160 ast_rtp_codecs_payload_formats(&newtextrtp, &tpeercapability, &tpeernoncodeccapability);
09161
09162 newjointcapability = p->capability & (peercapability | vpeercapability | tpeercapability);
09163 newpeercapability = (peercapability | vpeercapability | tpeercapability);
09164 newnoncodeccapability = p->noncodeccapability & peernoncodeccapability;
09165
09166 if (debug) {
09167
09168 char s1[SIPBUFSIZE], s2[SIPBUFSIZE], s3[SIPBUFSIZE], s4[SIPBUFSIZE], s5[SIPBUFSIZE];
09169
09170 ast_verbose("Capabilities: us - %s, peer - audio=%s/video=%s/text=%s, combined - %s\n",
09171 ast_getformatname_multiple(s1, SIPBUFSIZE, p->capability),
09172 ast_getformatname_multiple(s2, SIPBUFSIZE, peercapability),
09173 ast_getformatname_multiple(s3, SIPBUFSIZE, vpeercapability),
09174 ast_getformatname_multiple(s4, SIPBUFSIZE, tpeercapability),
09175 ast_getformatname_multiple(s5, SIPBUFSIZE, newjointcapability));
09176 }
09177 if (debug) {
09178 struct ast_str *s1 = ast_str_alloca(SIPBUFSIZE);
09179 struct ast_str *s2 = ast_str_alloca(SIPBUFSIZE);
09180 struct ast_str *s3 = ast_str_alloca(SIPBUFSIZE);
09181
09182 ast_verbose("Non-codec capabilities (dtmf): us - %s, peer - %s, combined - %s\n",
09183 ast_rtp_lookup_mime_multiple2(s1, p->noncodeccapability, 0, 0),
09184 ast_rtp_lookup_mime_multiple2(s2, peernoncodeccapability, 0, 0),
09185 ast_rtp_lookup_mime_multiple2(s3, newnoncodeccapability, 0, 0));
09186 }
09187 if (!newjointcapability && udptlportno == -1) {
09188 ast_log(LOG_NOTICE, "No compatible codecs, not accepting this offer!\n");
09189
09190 return -1;
09191 }
09192
09193 if (portno != -1 || vportno != -1 || tportno != -1) {
09194
09195
09196 p->jointcapability = newjointcapability;
09197 p->peercapability = newpeercapability;
09198 p->jointnoncodeccapability = newnoncodeccapability;
09199
09200
09201 if (ast_test_flag(&p->flags[1], SIP_PAGE2_PREFERRED_CODEC)) {
09202 p->jointcapability = ast_codec_choose(&p->prefs, p->jointcapability, 1);
09203 }
09204 }
09205
09206
09207 if (p->rtp) {
09208 if (portno > 0) {
09209 ast_sockaddr_set_port(sa, portno);
09210 ast_rtp_instance_set_remote_address(p->rtp, sa);
09211 if (debug) {
09212 ast_verbose("Peer audio RTP is at port %s\n",
09213 ast_sockaddr_stringify(sa));
09214 }
09215
09216 ast_rtp_codecs_payloads_copy(&newaudiortp, ast_rtp_instance_get_codecs(p->rtp), p->rtp);
09217
09218
09219 ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_RTCP, 1);
09220
09221 if (p->owner) {
09222 ast_channel_set_fd(p->owner, 1, ast_rtp_instance_fd(p->rtp, 1));
09223 }
09224
09225 if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) {
09226 ast_clear_flag(&p->flags[0], SIP_DTMF);
09227 if (newnoncodeccapability & AST_RTP_DTMF) {
09228
09229 ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
09230
09231 ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF, 1);
09232 ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
09233 } else {
09234 ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
09235 }
09236 }
09237 } else if (udptlportno > 0) {
09238 if (debug)
09239 ast_verbose("Got T.38 Re-invite without audio. Keeping RTP active during T.38 session.\n");
09240
09241 if (p->owner) {
09242 ast_channel_set_fd(p->owner, 1, -1);
09243 }
09244
09245 ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_RTCP, 0);
09246 } else {
09247 ast_rtp_instance_stop(p->rtp);
09248 if (debug)
09249 ast_verbose("Peer doesn't provide audio\n");
09250 }
09251 }
09252
09253
09254 if (p->vrtp) {
09255 if (vportno > 0) {
09256 ast_sockaddr_set_port(vsa, vportno);
09257 ast_rtp_instance_set_remote_address(p->vrtp, vsa);
09258 if (debug) {
09259 ast_verbose("Peer video RTP is at port %s\n",
09260 ast_sockaddr_stringify(vsa));
09261 }
09262 ast_rtp_codecs_payloads_copy(&newvideortp, ast_rtp_instance_get_codecs(p->vrtp), p->vrtp);
09263 } else {
09264 ast_rtp_instance_stop(p->vrtp);
09265 if (debug)
09266 ast_verbose("Peer doesn't provide video\n");
09267 }
09268 }
09269
09270
09271 if (p->trtp) {
09272 if (tportno > 0) {
09273 ast_sockaddr_set_port(tsa, tportno);
09274 ast_rtp_instance_set_remote_address(p->trtp, tsa);
09275 if (debug) {
09276 ast_verbose("Peer T.140 RTP is at port %s\n",
09277 ast_sockaddr_stringify(tsa));
09278 }
09279 if ((p->jointcapability & AST_FORMAT_T140RED)) {
09280 p->red = 1;
09281 ast_rtp_red_init(p->trtp, 300, red_data_pt, 2);
09282 } else {
09283 p->red = 0;
09284 }
09285 ast_rtp_codecs_payloads_copy(&newtextrtp, ast_rtp_instance_get_codecs(p->trtp), p->trtp);
09286 } else {
09287 ast_rtp_instance_stop(p->trtp);
09288 if (debug)
09289 ast_verbose("Peer doesn't provide T.140\n");
09290 }
09291 }
09292
09293 if (p->udptl) {
09294 if (udptlportno > 0) {
09295 if (ast_test_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP) && ast_test_flag(&p->flags[1], SIP_PAGE2_UDPTL_DESTINATION)) {
09296 ast_rtp_instance_get_remote_address(p->rtp, isa);
09297 if (!ast_sockaddr_isnull(isa) && debug) {
09298 ast_debug(1, "Peer T.38 UDPTL is set behind NAT and with destination, destination address now %s\n", ast_sockaddr_stringify(isa));
09299 }
09300 }
09301 ast_sockaddr_set_port(isa, udptlportno);
09302 ast_udptl_set_peer(p->udptl, isa);
09303 if (debug)
09304 ast_debug(1,"Peer T.38 UDPTL is at port %s\n", ast_sockaddr_stringify(isa));
09305
09306
09307 if (!ast_udptl_get_far_max_datagram(p->udptl)) {
09308
09309 ast_udptl_set_far_max_datagram(p->udptl, 0);
09310 }
09311
09312
09313 if ((t38action == SDP_T38_ACCEPT) &&
09314 (p->t38.state == T38_LOCAL_REINVITE)) {
09315 change_t38_state(p, T38_ENABLED);
09316 } else if ((t38action == SDP_T38_INITIATE) &&
09317 p->owner && p->lastinvite) {
09318 change_t38_state(p, T38_PEER_REINVITE);
09319
09320 if (ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_T38)) {
09321 ast_channel_lock(p->owner);
09322 if (strcmp(p->owner->exten, "fax")) {
09323 const char *target_context = S_OR(p->owner->macrocontext, p->owner->context);
09324 ast_channel_unlock(p->owner);
09325 if (ast_exists_extension(p->owner, target_context, "fax", 1,
09326 S_COR(p->owner->caller.id.number.valid, p->owner->caller.id.number.str, NULL))) {
09327 ast_verbose(VERBOSE_PREFIX_2 "Redirecting '%s' to fax extension due to peer T.38 re-INVITE\n", p->owner->name);
09328 pbx_builtin_setvar_helper(p->owner, "FAXEXTEN", p->owner->exten);
09329 if (ast_async_goto(p->owner, target_context, "fax", 1)) {
09330 ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", p->owner->name, target_context);
09331 }
09332 } else {
09333 ast_log(LOG_NOTICE, "T.38 re-INVITE detected but no fax extension\n");
09334 }
09335 } else {
09336 ast_channel_unlock(p->owner);
09337 }
09338 }
09339 }
09340 } else {
09341 change_t38_state(p, T38_DISABLED);
09342 ast_udptl_stop(p->udptl);
09343 if (debug)
09344 ast_debug(1, "Peer doesn't provide T.38 UDPTL\n");
09345 }
09346 }
09347
09348 if ((portno == -1) && (p->t38.state != T38_DISABLED)) {
09349 ast_debug(3, "Have T.38 but no audio, accepting offer anyway\n");
09350 return 0;
09351 }
09352
09353
09354 ast_debug(2, "We're settling with these formats: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, p->jointcapability));
09355
09356 if (!p->owner)
09357 return 0;
09358
09359 ast_debug(4, "We have an owner, now see if we need to change this call\n");
09360
09361 if (!(p->owner->nativeformats & p->jointcapability) && (p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
09362 if (debug) {
09363 char s1[SIPBUFSIZE], s2[SIPBUFSIZE];
09364 ast_debug(1, "Oooh, we need to change our audio formats since our peer supports only %s and not %s\n",
09365 ast_getformatname_multiple(s1, SIPBUFSIZE, p->jointcapability),
09366 ast_getformatname_multiple(s2, SIPBUFSIZE, p->owner->nativeformats));
09367 }
09368 p->owner->nativeformats = ast_codec_choose(&p->prefs, p->jointcapability, 1) | (p->capability & vpeercapability) | (p->capability & tpeercapability);
09369 ast_set_read_format(p->owner, p->owner->readformat);
09370 ast_set_write_format(p->owner, p->owner->writeformat);
09371 }
09372
09373 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)) {
09374 ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
09375
09376 ast_queue_frame(p->owner, &ast_null_frame);
09377 change_hold_state(p, req, FALSE, sendonly);
09378 } 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)) {
09379 ast_queue_control_data(p->owner, AST_CONTROL_HOLD,
09380 S_OR(p->mohsuggest, NULL),
09381 !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
09382 if (sendonly)
09383 ast_rtp_instance_stop(p->rtp);
09384
09385
09386 ast_queue_frame(p->owner, &ast_null_frame);
09387 change_hold_state(p, req, TRUE, sendonly);
09388 }
09389
09390 return 0;
09391 }
09392
09393 static int process_sdp_o(const char *o, struct sip_pvt *p)
09394 {
09395 char *o_copy;
09396 char *token;
09397 int64_t rua_version;
09398
09399
09400
09401
09402
09403
09404
09405
09406
09407
09408 p->session_modify = TRUE;
09409
09410 if (ast_strlen_zero(o)) {
09411 ast_log(LOG_WARNING, "SDP syntax error. SDP without an o= line\n");
09412 return FALSE;
09413 }
09414
09415 o_copy = ast_strdupa(o);
09416 token = strsep(&o_copy, " ");
09417 if (!o_copy) {
09418 ast_log(LOG_WARNING, "SDP syntax error in o= line username\n");
09419 return FALSE;
09420 }
09421 token = strsep(&o_copy, " ");
09422 if (!o_copy) {
09423 ast_log(LOG_WARNING, "SDP syntax error in o= line session-id\n");
09424 return FALSE;
09425 }
09426 token = strsep(&o_copy, " ");
09427 if (!o_copy) {
09428 ast_log(LOG_WARNING, "SDP syntax error in o= line\n");
09429 return FALSE;
09430 }
09431 if (!sscanf(token, "%30" SCNd64, &rua_version)) {
09432 ast_log(LOG_WARNING, "SDP syntax error in o= line version\n");
09433 return FALSE;
09434 }
09435
09436
09437
09438
09439
09440
09441
09442
09443
09444
09445
09446
09447
09448
09449
09450
09451
09452
09453
09454 if (ast_test_flag(&p->flags[1], SIP_PAGE2_IGNORESDPVERSION) ||
09455 (p->sessionversion_remote < 0) ||
09456 (p->sessionversion_remote < rua_version)) {
09457 p->sessionversion_remote = rua_version;
09458 } else {
09459 if (p->t38.state == T38_LOCAL_REINVITE) {
09460 p->sessionversion_remote = rua_version;
09461 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);
09462 } else {
09463 p->session_modify = FALSE;
09464 ast_debug(2, "Call %s responded to our reinvite without changing SDP version; ignoring SDP.\n", p->callid);
09465 return FALSE;
09466 }
09467 }
09468
09469 return TRUE;
09470 }
09471
09472 static int process_sdp_c(const char *c, struct ast_sockaddr *addr)
09473 {
09474 char proto[4], host[258];
09475 int af;
09476
09477
09478 if (sscanf(c, "IN %3s %255s", proto, host) == 2) {
09479 if (!strcmp("IP4", proto)) {
09480 af = AF_INET;
09481 } else if (!strcmp("IP6", proto)) {
09482 af = AF_INET6;
09483 } else {
09484 ast_log(LOG_WARNING, "Unknown protocol '%s'.\n", proto);
09485 return FALSE;
09486 }
09487 if (ast_sockaddr_resolve_first_af(addr, host, 0, af)) {
09488 ast_log(LOG_WARNING, "Unable to lookup RTP Audio host in c= line, '%s'\n", c);
09489 return FALSE;
09490 }
09491 return TRUE;
09492 } else {
09493 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
09494 return FALSE;
09495 }
09496 return FALSE;
09497 }
09498
09499 static int process_sdp_a_sendonly(const char *a, int *sendonly)
09500 {
09501 int found = FALSE;
09502
09503 if (!strcasecmp(a, "sendonly")) {
09504 if (*sendonly == -1)
09505 *sendonly = 1;
09506 found = TRUE;
09507 } else if (!strcasecmp(a, "inactive")) {
09508 if (*sendonly == -1)
09509 *sendonly = 2;
09510 found = TRUE;
09511 } else if (!strcasecmp(a, "sendrecv")) {
09512 if (*sendonly == -1)
09513 *sendonly = 0;
09514 found = TRUE;
09515 }
09516 return found;
09517 }
09518
09519 static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newaudiortp, int *last_rtpmap_codec)
09520 {
09521 int found = FALSE;
09522 int codec;
09523 char mimeSubtype[128];
09524 char fmtp_string[64];
09525 unsigned int sample_rate;
09526 int debug = sip_debug_test_pvt(p);
09527
09528 if (!strncasecmp(a, "ptime", 5)) {
09529 char *tmp = strrchr(a, ':');
09530 long int framing = 0;
09531 if (tmp) {
09532 tmp++;
09533 framing = strtol(tmp, NULL, 10);
09534 if (framing == LONG_MIN || framing == LONG_MAX) {
09535 framing = 0;
09536 ast_debug(1, "Can't read framing from SDP: %s\n", a);
09537 }
09538 }
09539 if (framing && p->autoframing) {
09540 struct ast_codec_pref *pref = &ast_rtp_instance_get_codecs(p->rtp)->pref;
09541 int codec_n;
09542 for (codec_n = 0; codec_n < AST_RTP_MAX_PT; codec_n++) {
09543 struct ast_rtp_payload_type format = ast_rtp_codecs_payload_lookup(ast_rtp_instance_get_codecs(p->rtp), codec_n);
09544 if (!format.asterisk_format || !format.code)
09545 continue;
09546 ast_debug(1, "Setting framing for %s to %ld\n", ast_getformatname(format.code), framing);
09547 ast_codec_pref_setsize(pref, format.code, framing);
09548 }
09549 ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(p->rtp), p->rtp, pref);
09550 }
09551 found = TRUE;
09552 } else if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
09553
09554 if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
09555 if (!(ast_rtp_codecs_payloads_set_rtpmap_type_rate(newaudiortp, NULL, codec, "audio", mimeSubtype,
09556 ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0, sample_rate))) {
09557 if (debug)
09558 ast_verbose("Found audio description format %s for ID %d\n", mimeSubtype, codec);
09559
09560 (*last_rtpmap_codec)++;
09561 found = TRUE;
09562 } else {
09563 ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
09564 if (debug)
09565 ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
09566 }
09567 } else {
09568 if (debug)
09569 ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
09570 }
09571 } else if (sscanf(a, "fmtp: %30u %63s", &codec, fmtp_string) == 2) {
09572 struct ast_rtp_payload_type payload;
09573
09574 payload = ast_rtp_codecs_payload_lookup(newaudiortp, codec);
09575 if (payload.code && payload.asterisk_format) {
09576 unsigned int bit_rate;
09577
09578 switch (payload.code) {
09579 case AST_FORMAT_SIREN7:
09580 if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
09581 if (bit_rate != 32000) {
09582 ast_log(LOG_WARNING, "Got Siren7 offer at %d bps, but only 32000 bps supported; ignoring.\n", bit_rate);
09583 ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
09584 } else {
09585 found = TRUE;
09586 }
09587 }
09588 break;
09589 case AST_FORMAT_SIREN14:
09590 if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
09591 if (bit_rate != 48000) {
09592 ast_log(LOG_WARNING, "Got Siren14 offer at %d bps, but only 48000 bps supported; ignoring.\n", bit_rate);
09593 ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
09594 } else {
09595 found = TRUE;
09596 }
09597 }
09598 break;
09599 case AST_FORMAT_G719:
09600 if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
09601 if (bit_rate != 64000) {
09602 ast_log(LOG_WARNING, "Got G.719 offer at %d bps, but only 64000 bps supported; ignoring.\n", bit_rate);
09603 ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
09604 } else {
09605 found = TRUE;
09606 }
09607 }
09608 }
09609 }
09610 }
09611
09612 return found;
09613 }
09614
09615 static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newvideortp, int *last_rtpmap_codec)
09616 {
09617 int found = FALSE;
09618 int codec;
09619 char mimeSubtype[128];
09620 unsigned int sample_rate;
09621 int debug = sip_debug_test_pvt(p);
09622
09623 if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
09624
09625 if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
09626
09627 if (!strncasecmp(mimeSubtype, "H26", 3) || !strncasecmp(mimeSubtype, "MP4", 3)) {
09628 if (!(ast_rtp_codecs_payloads_set_rtpmap_type_rate(newvideortp, NULL, codec, "video", mimeSubtype, 0, sample_rate))) {
09629 if (debug)
09630 ast_verbose("Found video description format %s for ID %d\n", mimeSubtype, codec);
09631
09632 (*last_rtpmap_codec)++;
09633 found = TRUE;
09634 } else {
09635 ast_rtp_codecs_payloads_unset(newvideortp, NULL, codec);
09636 if (debug)
09637 ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
09638 }
09639 }
09640 } else {
09641 if (debug)
09642 ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
09643 }
09644 }
09645
09646 return found;
09647 }
09648
09649 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)
09650 {
09651 int found = FALSE;
09652 int codec;
09653 char mimeSubtype[128];
09654 unsigned int sample_rate;
09655 char *red_cp;
09656 int debug = sip_debug_test_pvt(p);
09657
09658 if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
09659
09660 if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
09661 if (!strncasecmp(mimeSubtype, "T140", 4)) {
09662 if (p->trtp) {
09663
09664 ast_rtp_codecs_payloads_set_rtpmap_type_rate(newtextrtp, NULL, codec, "text", mimeSubtype, 0, sample_rate);
09665 found = TRUE;
09666 }
09667 } else if (!strncasecmp(mimeSubtype, "RED", 3)) {
09668 if (p->trtp) {
09669 ast_rtp_codecs_payloads_set_rtpmap_type_rate(newtextrtp, NULL, codec, "text", mimeSubtype, 0, sample_rate);
09670 sprintf(red_fmtp, "fmtp:%d ", codec);
09671 if (debug)
09672 ast_verbose("RED submimetype has payload type: %d\n", codec);
09673 found = TRUE;
09674 }
09675 }
09676 } else {
09677 if (debug)
09678 ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
09679 }
09680 } else if (!strncmp(a, red_fmtp, strlen(red_fmtp))) {
09681
09682 red_cp = &red_fmtp[strlen(red_fmtp)];
09683 strncpy(red_fmtp, a, 100);
09684
09685 sscanf(red_cp, "%30u", &red_data_pt[*red_num_gen]);
09686 red_cp = strtok(red_cp, "/");
09687 while (red_cp && (*red_num_gen)++ < AST_RED_MAX_GENERATION) {
09688 sscanf(red_cp, "%30u", &red_data_pt[*red_num_gen]);
09689 red_cp = strtok(NULL, "/");
09690 }
09691 red_cp = red_fmtp;
09692 found = TRUE;
09693 }
09694
09695 return found;
09696 }
09697
09698 static int process_sdp_a_image(const char *a, struct sip_pvt *p)
09699 {
09700 int found = FALSE;
09701 char s[256];
09702 unsigned int x;
09703
09704 if (initialize_udptl(p)) {
09705 return found;
09706 }
09707
09708 if ((sscanf(a, "T38FaxMaxBuffer:%30u", &x) == 1)) {
09709 ast_debug(3, "MaxBufferSize:%d\n", x);
09710 found = TRUE;
09711 } else if ((sscanf(a, "T38MaxBitRate:%30u", &x) == 1) || (sscanf(a, "T38FaxMaxRate:%30u", &x) == 1)) {
09712 ast_debug(3, "T38MaxBitRate: %d\n", x);
09713 switch (x) {
09714 case 14400:
09715 p->t38.their_parms.rate = AST_T38_RATE_14400;
09716 break;
09717 case 12000:
09718 p->t38.their_parms.rate = AST_T38_RATE_12000;
09719 break;
09720 case 9600:
09721 p->t38.their_parms.rate = AST_T38_RATE_9600;
09722 break;
09723 case 7200:
09724 p->t38.their_parms.rate = AST_T38_RATE_7200;
09725 break;
09726 case 4800:
09727 p->t38.their_parms.rate = AST_T38_RATE_4800;
09728 break;
09729 case 2400:
09730 p->t38.their_parms.rate = AST_T38_RATE_2400;
09731 break;
09732 }
09733 found = TRUE;
09734 } else if ((sscanf(a, "T38FaxVersion:%30u", &x) == 1)) {
09735 ast_debug(3, "FaxVersion: %u\n", x);
09736 p->t38.their_parms.version = x;
09737 found = TRUE;
09738 } else if ((sscanf(a, "T38FaxMaxDatagram:%30u", &x) == 1) || (sscanf(a, "T38MaxDatagram:%30u", &x) == 1)) {
09739
09740 if (((signed int) p->t38_maxdatagram >= 0) && ((unsigned int) p->t38_maxdatagram > x)) {
09741 ast_debug(1, "Overriding T38FaxMaxDatagram '%d' with '%d'\n", x, p->t38_maxdatagram);
09742 x = p->t38_maxdatagram;
09743 }
09744 ast_debug(3, "FaxMaxDatagram: %u\n", x);
09745 ast_udptl_set_far_max_datagram(p->udptl, x);
09746 found = TRUE;
09747 } else if ((strncmp(a, "T38FaxFillBitRemoval", 20) == 0)) {
09748 if (sscanf(a, "T38FaxFillBitRemoval:%30u", &x) == 1) {
09749 ast_debug(3, "FillBitRemoval: %d\n", x);
09750 if (x == 1) {
09751 p->t38.their_parms.fill_bit_removal = TRUE;
09752 }
09753 } else {
09754 ast_debug(3, "FillBitRemoval\n");
09755 p->t38.their_parms.fill_bit_removal = TRUE;
09756 }
09757 found = TRUE;
09758 } else if ((strncmp(a, "T38FaxTranscodingMMR", 20) == 0)) {
09759 if (sscanf(a, "T38FaxTranscodingMMR:%30u", &x) == 1) {
09760 ast_debug(3, "Transcoding MMR: %d\n", x);
09761 if (x == 1) {
09762 p->t38.their_parms.transcoding_mmr = TRUE;
09763 }
09764 } else {
09765 ast_debug(3, "Transcoding MMR\n");
09766 p->t38.their_parms.transcoding_mmr = TRUE;
09767 }
09768 found = TRUE;
09769 } else if ((strncmp(a, "T38FaxTranscodingJBIG", 21) == 0)) {
09770 if (sscanf(a, "T38FaxTranscodingJBIG:%30u", &x) == 1) {
09771 ast_debug(3, "Transcoding JBIG: %d\n", x);
09772 if (x == 1) {
09773 p->t38.their_parms.transcoding_jbig = TRUE;
09774 }
09775 } else {
09776 ast_debug(3, "Transcoding JBIG\n");
09777 p->t38.their_parms.transcoding_jbig = TRUE;
09778 }
09779 found = TRUE;
09780 } else if ((sscanf(a, "T38FaxRateManagement:%255s", s) == 1)) {
09781 ast_debug(3, "RateManagement: %s\n", s);
09782 if (!strcasecmp(s, "localTCF"))
09783 p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_LOCAL_TCF;
09784 else if (!strcasecmp(s, "transferredTCF"))
09785 p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF;
09786 found = TRUE;
09787 } else if ((sscanf(a, "T38FaxUdpEC:%255s", s) == 1)) {
09788 ast_debug(3, "UDP EC: %s\n", s);
09789 if (!strcasecmp(s, "t38UDPRedundancy")) {
09790 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
09791 } else if (!strcasecmp(s, "t38UDPFEC")) {
09792 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
09793 } else {
09794 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
09795 }
09796 found = TRUE;
09797 }
09798
09799 return found;
09800 }
09801
09802
09803
09804
09805 static int add_supported_header(struct sip_pvt *pvt, struct sip_request *req)
09806 {
09807 int res;
09808 if (st_get_mode(pvt, 0) != SESSION_TIMER_MODE_REFUSE) {
09809 res = add_header(req, "Supported", "replaces, timer");
09810 } else {
09811 res = add_header(req, "Supported", "replaces");
09812 }
09813 return res;
09814 }
09815
09816
09817 static int add_header(struct sip_request *req, const char *var, const char *value)
09818 {
09819 if (req->headers == SIP_MAX_HEADERS) {
09820 ast_log(LOG_WARNING, "Out of SIP header space\n");
09821 return -1;
09822 }
09823
09824 if (req->lines) {
09825 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
09826 return -1;
09827 }
09828
09829 if (sip_cfg.compactheaders) {
09830 var = find_alias(var, var);
09831 }
09832
09833 ast_str_append(&req->data, 0, "%s: %s\r\n", var, value);
09834 req->header[req->headers] = ast_str_strlen(req->data);
09835
09836 req->headers++;
09837
09838 return 0;
09839 }
09840
09841
09842
09843
09844
09845 static int add_header_max_forwards(struct sip_pvt *dialog, struct sip_request *req)
09846 {
09847 char clen[10];
09848
09849 snprintf(clen, sizeof(clen), "%d", dialog->maxforwards);
09850
09851 return add_header(req, "Max-Forwards", clen);
09852 }
09853
09854
09855 static int finalize_content(struct sip_request *req)
09856 {
09857 char clen[10];
09858
09859 if (req->lines) {
09860 ast_log(LOG_WARNING, "finalize_content() called on a message that has already been finalized\n");
09861 return -1;
09862 }
09863
09864 snprintf(clen, sizeof(clen), "%zd", ast_str_strlen(req->content));
09865 add_header(req, "Content-Length", clen);
09866
09867 if (ast_str_strlen(req->content)) {
09868 ast_str_append(&req->data, 0, "\r\n%s", ast_str_buffer(req->content));
09869 }
09870 req->lines = ast_str_strlen(req->content) ? 1 : 0;
09871 return 0;
09872 }
09873
09874
09875 static int add_content(struct sip_request *req, const char *line)
09876 {
09877 if (req->lines) {
09878 ast_log(LOG_WARNING, "Can't add more content when the content has been finalized\n");
09879 return -1;
09880 }
09881
09882 ast_str_append(&req->content, 0, "%s", line);
09883 return 0;
09884 }
09885
09886
09887 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field)
09888 {
09889 const char *tmp = get_header(orig, field);
09890
09891 if (!ast_strlen_zero(tmp))
09892 return add_header(req, field, tmp);
09893 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
09894 return -1;
09895 }
09896
09897
09898 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field)
09899 {
09900 int start = 0;
09901 int copied = 0;
09902 for (;;) {
09903 const char *tmp = __get_header(orig, field, &start);
09904
09905 if (ast_strlen_zero(tmp))
09906 break;
09907
09908 add_header(req, field, tmp);
09909 copied++;
09910 }
09911 return copied ? 0 : -1;
09912 }
09913
09914
09915
09916
09917
09918
09919
09920
09921
09922 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field)
09923 {
09924 int copied = 0;
09925 int start = 0;
09926
09927 for (;;) {
09928 char new[512];
09929 const char *oh = __get_header(orig, field, &start);
09930
09931 if (ast_strlen_zero(oh))
09932 break;
09933
09934 if (!copied) {
09935 char leftmost[512], *others, *rport;
09936
09937
09938 ast_copy_string(leftmost, oh, sizeof(leftmost));
09939 others = strchr(leftmost, ',');
09940 if (others)
09941 *others++ = '\0';
09942
09943
09944 rport = strstr(leftmost, ";rport");
09945 if (rport && *(rport+6) == '=')
09946 rport = NULL;
09947
09948 if (((ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT)) || (rport && ast_test_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT)))) {
09949
09950 char *end;
09951
09952 rport = strstr(leftmost, ";rport");
09953
09954 if (rport) {
09955 end = strchr(rport + 1, ';');
09956 if (end)
09957 memmove(rport, end, strlen(end) + 1);
09958 else
09959 *rport = '\0';
09960 }
09961
09962
09963 snprintf(new, sizeof(new), "%s;received=%s;rport=%d%s%s",
09964 leftmost, ast_sockaddr_stringify_addr_remote(&p->recv),
09965 ast_sockaddr_port(&p->recv),
09966 others ? "," : "", others ? others : "");
09967 } else {
09968
09969 snprintf(new, sizeof(new), "%s;received=%s%s%s",
09970 leftmost, ast_sockaddr_stringify_addr_remote(&p->recv),
09971 others ? "," : "", others ? others : "");
09972 }
09973 oh = new;
09974 }
09975 add_header(req, field, oh);
09976 copied++;
09977 }
09978 if (!copied) {
09979 ast_log(LOG_NOTICE, "No header field '%s' present to copy\n", field);
09980 return -1;
09981 }
09982 return 0;
09983 }
09984
09985
09986 static void add_route(struct sip_request *req, struct sip_route *route)
09987 {
09988 char r[SIPBUFSIZE*2], *p;
09989 int n, rem = sizeof(r);
09990
09991 if (!route)
09992 return;
09993
09994 p = r;
09995 for (;route ; route = route->next) {
09996 n = strlen(route->hop);
09997 if (rem < n+3)
09998 break;
09999 if (p != r) {
10000 *p++ = ',';
10001 --rem;
10002 }
10003 *p++ = '<';
10004 ast_copy_string(p, route->hop, rem);
10005 p += n;
10006 *p++ = '>';
10007 rem -= (n+2);
10008 }
10009 *p = '\0';
10010 add_header(req, "Route", r);
10011 }
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022 static void set_destination(struct sip_pvt *p, char *uri)
10023 {
10024 char *h, *maddr, hostname[256];
10025 int hn;
10026 int debug=sip_debug_test_pvt(p);
10027 int tls_on = FALSE;
10028
10029 if (debug)
10030 ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
10031
10032
10033 h = strchr(uri, '@');
10034 if (h)
10035 ++h;
10036 else {
10037 h = uri;
10038 if (!strncasecmp(h, "sip:", 4)) {
10039 h += 4;
10040 } else if (!strncasecmp(h, "sips:", 5)) {
10041 h += 5;
10042 tls_on = TRUE;
10043 }
10044 }
10045 hn = strcspn(h, ";>") + 1;
10046 if (hn > sizeof(hostname))
10047 hn = sizeof(hostname);
10048 ast_copy_string(hostname, h, hn);
10049
10050 h += hn - 1;
10051
10052
10053
10054 if (ast_sockaddr_resolve_first(&p->sa, hostname, 0)) {
10055 ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
10056 return;
10057 }
10058
10059
10060 maddr = strstr(h, "maddr=");
10061 if (maddr) {
10062 int port;
10063
10064 maddr += 6;
10065 hn = strspn(maddr, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
10066 "0123456789-.:[]") + 1;
10067 if (hn > sizeof(hostname))
10068 hn = sizeof(hostname);
10069 ast_copy_string(hostname, maddr, hn);
10070
10071 port = ast_sockaddr_port(&p->sa);
10072
10073
10074
10075 if (ast_sockaddr_resolve_first(&p->sa, hostname, PARSE_PORT_FORBID)) {
10076 ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
10077 return;
10078 }
10079
10080 ast_sockaddr_set_port(&p->sa, port);
10081 }
10082
10083 if (!ast_sockaddr_port(&p->sa)) {
10084 ast_sockaddr_set_port(&p->sa, tls_on ?
10085 STANDARD_TLS_PORT : STANDARD_SIP_PORT);
10086 }
10087
10088 if (debug) {
10089 ast_verbose("set_destination: set destination to %s\n",
10090 ast_sockaddr_stringify(&p->sa));
10091 }
10092 }
10093
10094
10095 static int init_resp(struct sip_request *resp, const char *msg)
10096 {
10097
10098 memset(resp, 0, sizeof(*resp));
10099 resp->method = SIP_RESPONSE;
10100 if (!(resp->data = ast_str_create(SIP_MIN_PACKET)))
10101 goto e_return;
10102 if (!(resp->content = ast_str_create(SIP_MIN_PACKET)))
10103 goto e_free_data;
10104 resp->header[0] = 0;
10105 ast_str_set(&resp->data, 0, "SIP/2.0 %s\r\n", msg);
10106 resp->headers++;
10107 return 0;
10108
10109 e_free_data:
10110 ast_free(resp->data);
10111 resp->data = NULL;
10112 e_return:
10113 return -1;
10114 }
10115
10116
10117 static int init_req(struct sip_request *req, int sipmethod, const char *recip)
10118 {
10119
10120 memset(req, 0, sizeof(*req));
10121 if (!(req->data = ast_str_create(SIP_MIN_PACKET)))
10122 goto e_return;
10123 if (!(req->content = ast_str_create(SIP_MIN_PACKET)))
10124 goto e_free_data;
10125 req->method = sipmethod;
10126 req->header[0] = 0;
10127 ast_str_set(&req->data, 0, "%s %s SIP/2.0\r\n", sip_methods[sipmethod].text, recip);
10128 req->headers++;
10129 return 0;
10130
10131 e_free_data:
10132 ast_free(req->data);
10133 req->data = NULL;
10134 e_return:
10135 return -1;
10136 }
10137
10138
10139 static void deinit_req(struct sip_request *req)
10140 {
10141 if (req->data) {
10142 ast_free(req->data);
10143 req->data = NULL;
10144 }
10145 if (req->content) {
10146 ast_free(req->content);
10147 req->content = NULL;
10148 }
10149 }
10150
10151
10152
10153 static inline int resp_needs_contact(const char *msg, enum sipmethod method) {
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169 switch (method) {
10170
10171 case SIP_INVITE:
10172 case SIP_UPDATE:
10173 case SIP_SUBSCRIBE:
10174 case SIP_NOTIFY:
10175 if ((msg[0] >= '1' && msg[0] <= '3') || !strncmp(msg, "485", 3))
10176 return 1;
10177 break;
10178
10179
10180 case SIP_REGISTER:
10181 case SIP_OPTIONS:
10182 if (msg[0] == '2' || msg[0] == '3' || !strncmp(msg, "485", 3))
10183 return 1;
10184 break;
10185
10186
10187 case SIP_BYE:
10188 case SIP_PRACK:
10189 case SIP_MESSAGE:
10190 case SIP_PUBLISH:
10191 if (msg[0] == '3' || !strncmp(msg, "485", 3))
10192 return 1;
10193 break;
10194
10195
10196 case SIP_REFER:
10197 if (msg[0] >= '2' && msg[0] <= '6')
10198 return 1;
10199 break;
10200
10201
10202 case SIP_ACK:
10203 case SIP_CANCEL:
10204 case SIP_INFO:
10205 case SIP_PING:
10206 default:
10207 return 0;
10208 }
10209 return 0;
10210 }
10211
10212
10213 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req)
10214 {
10215 char newto[256];
10216 const char *ot;
10217
10218 init_resp(resp, msg);
10219 copy_via_headers(p, resp, req, "Via");
10220 if (msg[0] == '1' || msg[0] == '2')
10221 copy_all_header(resp, req, "Record-Route");
10222 copy_header(resp, req, "From");
10223 ot = get_header(req, "To");
10224 if (!strcasestr(ot, "tag=") && strncmp(msg, "100", 3)) {
10225
10226
10227 if (!ast_strlen_zero(p->theirtag) && ast_test_flag(&p->flags[0], SIP_OUTGOING))
10228 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
10229 else if (p->tag && !ast_test_flag(&p->flags[0], SIP_OUTGOING))
10230 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
10231 else
10232 ast_copy_string(newto, ot, sizeof(newto));
10233 ot = newto;
10234 }
10235 add_header(resp, "To", ot);
10236 copy_header(resp, req, "Call-ID");
10237 copy_header(resp, req, "CSeq");
10238 if (!ast_strlen_zero(global_useragent))
10239 add_header(resp, "Server", global_useragent);
10240 add_header(resp, "Allow", ALLOWED_METHODS);
10241 add_supported_header(p, resp);
10242
10243
10244 if (p->method == SIP_INVITE && p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE) {
10245 char se_hdr[256];
10246 snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval,
10247 strefresher2str(p->stimer->st_ref));
10248 add_header(resp, "Session-Expires", se_hdr);
10249 }
10250
10251 if (msg[0] == '2' && (p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER)) {
10252
10253
10254 char tmp[256];
10255
10256 snprintf(tmp, sizeof(tmp), "%d", p->expiry);
10257 add_header(resp, "Expires", tmp);
10258 if (p->expiry) {
10259 char contact[SIPBUFSIZE];
10260 const char *contact_uri = p->method == SIP_SUBSCRIBE ? p->our_contact : p->fullcontact;
10261 char *brackets = strchr(contact_uri, '<');
10262 snprintf(contact, sizeof(contact), "%s%s%s;expires=%d", brackets ? "" : "<", contact_uri, brackets ? "" : ">", p->expiry);
10263 add_header(resp, "Contact", contact);
10264 }
10265 } else if (!ast_strlen_zero(p->our_contact) && resp_needs_contact(msg, p->method)) {
10266 add_header(resp, "Contact", p->our_contact);
10267 }
10268
10269 if (!ast_strlen_zero(p->url)) {
10270 add_header(resp, "Access-URL", p->url);
10271 ast_string_field_set(p, url, NULL);
10272 }
10273
10274
10275
10276
10277
10278
10279
10280 p->sa = p->recv;
10281
10282 if (process_via(p, req)) {
10283 ast_log(LOG_WARNING, "error processing via header, will send response to originating address\n");
10284 }
10285
10286 return 0;
10287 }
10288
10289
10290 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, uint32_t seqno, int newbranch)
10291 {
10292 struct sip_request *orig = &p->initreq;
10293 char stripped[80];
10294 char tmp[80];
10295 char newto[256];
10296 const char *c;
10297 const char *ot, *of;
10298 int is_strict = FALSE;
10299 int is_outbound = ast_test_flag(&p->flags[0], SIP_OUTGOING);
10300
10301 memset(req, 0, sizeof(struct sip_request));
10302
10303 snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", sip_methods[sipmethod].text);
10304
10305 if (!seqno) {
10306 p->ocseq++;
10307 seqno = p->ocseq;
10308 }
10309
10310
10311 if (sipmethod == SIP_CANCEL) {
10312 p->branch = p->invite_branch;
10313 build_via(p);
10314 } else if (newbranch && (sipmethod == SIP_INVITE)) {
10315 p->branch ^= ast_random();
10316 p->invite_branch = p->branch;
10317 build_via(p);
10318 } else if (newbranch) {
10319 p->branch ^= ast_random();
10320 build_via(p);
10321 }
10322
10323
10324 if (p->route && !ast_strlen_zero(p->route->hop) && strstr(p->route->hop, ";lr") == NULL) {
10325 is_strict = TRUE;
10326 if (sipdebug)
10327 ast_debug(1, "Strict routing enforced for session %s\n", p->callid);
10328 }
10329
10330 if (sipmethod == SIP_CANCEL)
10331 c = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
10332 else if (sipmethod == SIP_ACK) {
10333
10334
10335 if (!ast_strlen_zero(p->okcontacturi))
10336 c = is_strict ? p->route->hop : p->okcontacturi;
10337 else
10338 c = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
10339 } else if (!ast_strlen_zero(p->okcontacturi))
10340 c = is_strict ? p->route->hop : p->okcontacturi;
10341 else if (!ast_strlen_zero(p->uri))
10342 c = p->uri;
10343 else {
10344 char *n;
10345
10346 ast_copy_string(stripped, get_header(orig, is_outbound ? "To" : "From"),
10347 sizeof(stripped));
10348 n = get_in_brackets(stripped);
10349 c = remove_uri_parameters(n);
10350 }
10351 init_req(req, sipmethod, c);
10352
10353 snprintf(tmp, sizeof(tmp), "%u %s", seqno, sip_methods[sipmethod].text);
10354
10355 add_header(req, "Via", p->via);
10356
10357
10358
10359
10360
10361 if (sipmethod == SIP_CANCEL ||
10362 (sipmethod == SIP_ACK && (p->invitestate == INV_COMPLETED || p->invitestate == INV_CANCELLED))) {
10363 set_destination(p, ast_strdupa(p->uri));
10364 } else if (p->route) {
10365 set_destination(p, p->route->hop);
10366 add_route(req, is_strict ? p->route->next : p->route);
10367 }
10368 add_header_max_forwards(p, req);
10369
10370 ot = get_header(orig, "To");
10371 of = get_header(orig, "From");
10372
10373
10374
10375 if (!strcasestr(ot, "tag=") && sipmethod != SIP_CANCEL) {
10376
10377
10378 if (is_outbound && !ast_strlen_zero(p->theirtag))
10379 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
10380 else if (!is_outbound)
10381 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
10382 else
10383 snprintf(newto, sizeof(newto), "%s", ot);
10384 ot = newto;
10385 }
10386
10387 if (is_outbound) {
10388 add_header(req, "From", of);
10389 add_header(req, "To", ot);
10390 } else {
10391 add_header(req, "From", ot);
10392 add_header(req, "To", of);
10393 }
10394
10395 if (sipmethod != SIP_BYE && sipmethod != SIP_CANCEL && sipmethod != SIP_MESSAGE)
10396 add_header(req, "Contact", p->our_contact);
10397
10398 copy_header(req, orig, "Call-ID");
10399 add_header(req, "CSeq", tmp);
10400
10401 if (!ast_strlen_zero(global_useragent))
10402 add_header(req, "User-Agent", global_useragent);
10403
10404 if (!ast_strlen_zero(p->url)) {
10405 add_header(req, "Access-URL", p->url);
10406 ast_string_field_set(p, url, NULL);
10407 }
10408
10409
10410
10411
10412
10413
10414
10415
10416 if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE
10417 && sipmethod == SIP_INVITE) {
10418 char se_hdr[256];
10419 snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval,
10420 strefresher2str(p->stimer->st_ref));
10421 add_header(req, "Session-Expires", se_hdr);
10422 snprintf(se_hdr, sizeof(se_hdr), "%d", st_get_se(p, FALSE));
10423 add_header(req, "Min-SE", se_hdr);
10424 }
10425
10426 return 0;
10427 }
10428
10429
10430 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
10431 {
10432 struct sip_request resp;
10433 uint32_t seqno = 0;
10434
10435 if (reliable && (sscanf(get_header(req, "CSeq"), "%30u ", &seqno) != 1)) {
10436 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
10437 return -1;
10438 }
10439 respprep(&resp, p, msg, req);
10440
10441 if (ast_test_flag(&p->flags[0], SIP_SENDRPID)
10442 && ast_test_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND)
10443 && (!strncmp(msg, "180", 3) || !strncmp(msg, "183", 3))) {
10444 ast_clear_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND);
10445 add_rpid(&resp, p);
10446 }
10447 if (ast_test_flag(&p->flags[0], SIP_OFFER_CC)) {
10448 add_cc_call_info_to_response(p, &resp);
10449 }
10450
10451
10452 if (!strncmp(msg, "302", 3)) {
10453 add_diversion_header(&resp, p);
10454 }
10455
10456
10457
10458 if (p->method == SIP_INVITE && msg[0] != '1') {
10459 char buf[20];
10460
10461 if (ast_test_flag(&p->flags[1], SIP_PAGE2_Q850_REASON)) {
10462 int hangupcause = 0;
10463
10464 if (p->owner && p->owner->hangupcause) {
10465 hangupcause = p->owner->hangupcause;
10466 } else if (p->hangupcause) {
10467 hangupcause = p->hangupcause;
10468 } else {
10469 int respcode;
10470 if (sscanf(msg, "%30d ", &respcode))
10471 hangupcause = hangup_sip2cause(respcode);
10472 }
10473
10474 if (hangupcause) {
10475 sprintf(buf, "Q.850;cause=%i", hangupcause & 0x7f);
10476 add_header(&resp, "Reason", buf);
10477 }
10478 }
10479
10480 if (p->owner && p->owner->hangupcause) {
10481 add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->owner->hangupcause));
10482 snprintf(buf, sizeof(buf), "%d", p->owner->hangupcause);
10483 add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
10484 }
10485 }
10486 return send_response(p, &resp, reliable, seqno);
10487 }
10488
10489 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)
10490 {
10491 struct sip_request resp;
10492
10493 if (need_new_etag) {
10494 create_new_sip_etag(esc_entry, 1);
10495 }
10496 respprep(&resp, p, msg, req);
10497 add_header(&resp, "SIP-ETag", esc_entry->entity_tag);
10498
10499 return send_response(p, &resp, 0, 0);
10500 }
10501
10502 static int temp_pvt_init(void *data)
10503 {
10504 struct sip_pvt *p = data;
10505
10506 p->do_history = 0;
10507 return ast_string_field_init(p, 512);
10508 }
10509
10510 static void temp_pvt_cleanup(void *data)
10511 {
10512 struct sip_pvt *p = data;
10513
10514 ast_string_field_free_memory(p);
10515
10516 ast_free(data);
10517 }
10518
10519
10520 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)
10521 {
10522 struct sip_pvt *p = NULL;
10523
10524 if (!(p = ast_threadstorage_get(&ts_temp_pvt, sizeof(*p)))) {
10525 ast_log(LOG_ERROR, "Failed to get temporary pvt\n");
10526 return -1;
10527 }
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537 p->method = intended_method;
10538
10539 if (!addr) {
10540 ast_sockaddr_copy(&p->ourip, &internip);
10541 } else {
10542 ast_sockaddr_copy(&p->sa, addr);
10543 ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
10544 }
10545
10546 p->branch = ast_random();
10547 make_our_tag(p->tag, sizeof(p->tag));
10548 p->ocseq = INITIAL_CSEQ;
10549
10550 if (useglobal_nat && addr) {
10551 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT_FORCE_RPORT);
10552 ast_sockaddr_copy(&p->recv, addr);
10553 do_setnat(p);
10554 }
10555
10556 ast_string_field_set(p, fromdomain, default_fromdomain);
10557 p->fromdomainport = default_fromdomainport;
10558 build_via(p);
10559 ast_string_field_set(p, callid, callid);
10560
10561 copy_socket_data(&p->socket, &req->socket);
10562
10563
10564 __transmit_response(p, msg, req, XMIT_UNRELIABLE);
10565
10566
10567 ast_string_field_init(p, 0);
10568
10569 return 0;
10570 }
10571
10572
10573 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req)
10574 {
10575 return __transmit_response(p, msg, req, XMIT_UNRELIABLE);
10576 }
10577
10578
10579 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported)
10580 {
10581 struct sip_request resp;
10582 respprep(&resp, p, msg, req);
10583 append_date(&resp);
10584 add_header(&resp, "Unsupported", unsupported);
10585 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
10586 }
10587
10588
10589 static int transmit_response_with_minse(struct sip_pvt *p, const char *msg, const struct sip_request *req, int minse_int)
10590 {
10591 struct sip_request resp;
10592 char minse_str[20];
10593
10594 respprep(&resp, p, msg, req);
10595 append_date(&resp);
10596
10597 snprintf(minse_str, sizeof(minse_str), "%d", minse_int);
10598 add_header(&resp, "Min-SE", minse_str);
10599 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
10600 }
10601
10602
10603
10604
10605
10606 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req)
10607 {
10608 return __transmit_response(p, msg, req, req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL);
10609 }
10610
10611
10612 static void append_date(struct sip_request *req)
10613 {
10614 char tmpdat[256];
10615 struct tm tm;
10616 time_t t = time(NULL);
10617
10618 gmtime_r(&t, &tm);
10619 strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
10620 add_header(req, "Date", tmpdat);
10621 }
10622
10623
10624 static int transmit_response_with_retry_after(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *seconds)
10625 {
10626 struct sip_request resp;
10627 respprep(&resp, p, msg, req);
10628 add_header(&resp, "Retry-After", seconds);
10629 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
10630 }
10631
10632
10633 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req)
10634 {
10635 struct sip_request resp;
10636 respprep(&resp, p, msg, req);
10637 append_date(&resp);
10638 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
10639 }
10640
10641
10642 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
10643 {
10644 struct sip_request resp;
10645 respprep(&resp, p, msg, req);
10646 add_header(&resp, "Accept", "application/sdp");
10647 return send_response(p, &resp, reliable, 0);
10648 }
10649
10650
10651 static int transmit_response_with_minexpires(struct sip_pvt *p, const char *msg, const struct sip_request *req)
10652 {
10653 struct sip_request resp;
10654 char tmp[32];
10655
10656 snprintf(tmp, sizeof(tmp), "%d", min_expiry);
10657 respprep(&resp, p, msg, req);
10658 add_header(&resp, "Min-Expires", tmp);
10659 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
10660 }
10661
10662
10663 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)
10664 {
10665 struct sip_request resp;
10666 char tmp[512];
10667 uint32_t seqno = 0;
10668
10669 if (reliable && (sscanf(get_header(req, "CSeq"), "%30u ", &seqno) != 1)) {
10670 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
10671 return -1;
10672 }
10673
10674 get_realm(p, req);
10675
10676
10677
10678 snprintf(tmp, sizeof(tmp), "Digest algorithm=MD5, realm=\"%s\", nonce=\"%s\"%s", p->realm, randdata, stale ? ", stale=true" : "");
10679 respprep(&resp, p, msg, req);
10680 add_header(&resp, header, tmp);
10681 append_history(p, "AuthChal", "Auth challenge sent for %s - nc %d", p->username, p->noncecount);
10682 return send_response(p, &resp, reliable, seqno);
10683 }
10684
10685
10686
10687
10688
10689
10690
10691 static int get_domain(const char *str, char *domain, int len)
10692 {
10693 char tmpf[256];
10694 char *a, *from;
10695
10696 *domain = '\0';
10697 ast_copy_string(tmpf, str, sizeof(tmpf));
10698 from = get_in_brackets(tmpf);
10699 if (!ast_strlen_zero(from)) {
10700 if (strncasecmp(from, "sip:", 4)) {
10701 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", from);
10702 return -1;
10703 }
10704 from += 4;
10705 } else
10706 from = NULL;
10707
10708 if (from) {
10709 int bracket = 0;
10710
10711
10712 if ((a = strchr(from, ';')))
10713 *a = '\0';
10714
10715 for (a = from; *a != '\0'; ++a) {
10716 if (*a == ':' && bracket == 0) {
10717 *a = '\0';
10718 break;
10719 } else if (*a == '[') {
10720 ++bracket;
10721 } else if (*a == ']') {
10722 --bracket;
10723 }
10724 }
10725 if ((a = strchr(from, '@'))) {
10726 *a = '\0';
10727 ast_copy_string(domain, a + 1, len);
10728 } else
10729 ast_copy_string(domain, from, len);
10730 }
10731
10732 return ast_strlen_zero(domain);
10733 }
10734
10735
10736
10737
10738
10739 static void get_realm(struct sip_pvt *p, const struct sip_request *req)
10740 {
10741 char domain[MAXHOSTNAMELEN];
10742
10743 if (!ast_strlen_zero(p->realm))
10744 return;
10745
10746 if (sip_cfg.domainsasrealm &&
10747 !AST_LIST_EMPTY(&domain_list))
10748 {
10749
10750 if (!get_domain(get_header(req, "From"), domain, sizeof(domain))) {
10751 if (check_sip_domain(domain, NULL, 0)) {
10752 ast_string_field_set(p, realm, domain);
10753 return;
10754 }
10755 }
10756
10757 if (!get_domain(get_header(req, "To"), domain, sizeof(domain))) {
10758 if (check_sip_domain(domain, NULL, 0)) {
10759 ast_string_field_set(p, realm, domain);
10760 return;
10761 }
10762 }
10763 }
10764
10765
10766 ast_string_field_set(p, realm, sip_cfg.realm);
10767 }
10768
10769
10770
10771
10772
10773
10774
10775
10776 static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp)
10777 {
10778 int res;
10779
10780 if (!(res = with_sdp ? transmit_response_with_sdp(p, msg, req, XMIT_UNRELIABLE, FALSE, FALSE) : transmit_response(p, msg, req))) {
10781 p->last_provisional = msg;
10782 update_provisional_keepalive(p, with_sdp);
10783 }
10784
10785 return res;
10786 }
10787
10788
10789 static int add_text(struct sip_request *req, const char *text)
10790 {
10791
10792 add_header(req, "Content-Type", "text/plain;charset=UTF-8");
10793 add_content(req, text);
10794 return 0;
10795 }
10796
10797
10798
10799
10800
10801 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode)
10802 {
10803 char tmp[256];
10804 int event;
10805 if (mode) {
10806
10807 if ('0' <= digit && digit <= '9') {
10808 event = digit - '0';
10809 } else if (digit == '*') {
10810 event = 10;
10811 } else if (digit == '#') {
10812 event = 11;
10813 } else if ('A' <= digit && digit <= 'D') {
10814 event = 12 + digit - 'A';
10815 } else if ('a' <= digit && digit <= 'd') {
10816 event = 12 + digit - 'a';
10817 } else {
10818
10819 event = 0;
10820 }
10821 snprintf(tmp, sizeof(tmp), "%d\r\n", event);
10822 add_header(req, "Content-Type", "application/dtmf");
10823 add_content(req, tmp);
10824 } else {
10825
10826 snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=%u\r\n", digit, duration);
10827 add_header(req, "Content-Type", "application/dtmf-relay");
10828 add_content(req, tmp);
10829 }
10830 return 0;
10831 }
10832
10833
10834
10835
10836
10837 static int add_rpid(struct sip_request *req, struct sip_pvt *p)
10838 {
10839 struct ast_str *tmp = ast_str_alloca(256);
10840 char tmp2[256];
10841 char *lid_num = NULL;
10842 char *lid_name = NULL;
10843 int lid_pres;
10844 const char *fromdomain;
10845 const char *privacy = NULL;
10846 const char *screen = NULL;
10847 const char *anonymous_string = "\"Anonymous\" <sip:anonymous@anonymous.invalid>";
10848
10849 if (!ast_test_flag(&p->flags[0], SIP_SENDRPID)) {
10850 return 0;
10851 }
10852
10853 if (p->owner && p->owner->connected.id.number.valid
10854 && p->owner->connected.id.number.str) {
10855 lid_num = p->owner->connected.id.number.str;
10856 }
10857 if (p->owner && p->owner->connected.id.name.valid
10858 && p->owner->connected.id.name.str) {
10859 lid_name = p->owner->connected.id.name.str;
10860 }
10861 lid_pres = (p->owner) ? ast_party_id_presentation(&p->owner->connected.id) : AST_PRES_NUMBER_NOT_AVAILABLE;
10862
10863 if (ast_strlen_zero(lid_num))
10864 return 0;
10865 if (ast_strlen_zero(lid_name))
10866 lid_name = lid_num;
10867 fromdomain = S_OR(p->fromdomain, ast_sockaddr_stringify_host_remote(&p->ourip));
10868
10869 lid_num = ast_uri_encode(lid_num, tmp2, sizeof(tmp2), 0);
10870
10871 if (ast_test_flag(&p->flags[0], SIP_SENDRPID_PAI)) {
10872 if ((lid_pres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
10873 ast_str_set(&tmp, -1, "%s", anonymous_string);
10874 } else {
10875 ast_str_set(&tmp, -1, "\"%s\" <sip:%s@%s>", lid_name, lid_num, fromdomain);
10876 }
10877 add_header(req, "P-Asserted-Identity", ast_str_buffer(tmp));
10878 } else {
10879 ast_str_set(&tmp, -1, "\"%s\" <sip:%s@%s>;party=%s", lid_name, lid_num, fromdomain, ast_test_flag(&p->flags[0], SIP_OUTGOING) ? "calling" : "called");
10880
10881 switch (lid_pres) {
10882 case AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED:
10883 case AST_PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN:
10884 privacy = "off";
10885 screen = "no";
10886 break;
10887 case AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN:
10888 case AST_PRES_ALLOWED_NETWORK_NUMBER:
10889 privacy = "off";
10890 screen = "yes";
10891 break;
10892 case AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED:
10893 case AST_PRES_PROHIB_USER_NUMBER_FAILED_SCREEN:
10894 privacy = "full";
10895 screen = "no";
10896 break;
10897 case AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN:
10898 case AST_PRES_PROHIB_NETWORK_NUMBER:
10899 privacy = "full";
10900 screen = "yes";
10901 break;
10902 case AST_PRES_NUMBER_NOT_AVAILABLE:
10903 break;
10904 default:
10905 if ((lid_pres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
10906 privacy = "full";
10907 }
10908 else
10909 privacy = "off";
10910 screen = "no";
10911 break;
10912 }
10913
10914 if (!ast_strlen_zero(privacy) && !ast_strlen_zero(screen)) {
10915 ast_str_append(&tmp, -1, ";privacy=%s;screen=%s", privacy, screen);
10916 }
10917
10918 add_header(req, "Remote-Party-ID", ast_str_buffer(tmp));
10919 }
10920 return 0;
10921 }
10922
10923
10924
10925 static int add_vidupdate(struct sip_request *req)
10926 {
10927 const char *xml_is_a_huge_waste_of_space =
10928 "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
10929 " <media_control>\r\n"
10930 " <vc_primitive>\r\n"
10931 " <to_encoder>\r\n"
10932 " <picture_fast_update>\r\n"
10933 " </picture_fast_update>\r\n"
10934 " </to_encoder>\r\n"
10935 " </vc_primitive>\r\n"
10936 " </media_control>\r\n";
10937 add_header(req, "Content-Type", "application/media_control+xml");
10938 add_content(req, xml_is_a_huge_waste_of_space);
10939 return 0;
10940 }
10941
10942
10943 static void add_codec_to_sdp(const struct sip_pvt *p, format_t codec,
10944 struct ast_str **m_buf, struct ast_str **a_buf,
10945 int debug, int *min_packet_size)
10946 {
10947 int rtp_code;
10948 struct ast_format_list fmt;
10949
10950
10951 if (debug)
10952 ast_verbose("Adding codec 0x%" PRIx64 " (%s) to SDP\n", codec, ast_getformatname(codec));
10953 if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->rtp), 1, codec)) == -1)
10954 return;
10955
10956 if (p->rtp) {
10957 struct ast_codec_pref *pref = &ast_rtp_instance_get_codecs(p->rtp)->pref;
10958 fmt = ast_codec_pref_getsize(pref, codec);
10959 } else
10960 return;
10961 ast_str_append(m_buf, 0, " %d", rtp_code);
10962 ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
10963 ast_rtp_lookup_mime_subtype2(1, codec,
10964 ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0),
10965 ast_rtp_lookup_sample_rate2(1, codec));
10966
10967 switch (codec) {
10968 case AST_FORMAT_G729A:
10969
10970 ast_str_append(a_buf, 0, "a=fmtp:%d annexb=no\r\n", rtp_code);
10971 break;
10972 case AST_FORMAT_G723_1:
10973
10974 ast_str_append(a_buf, 0, "a=fmtp:%d annexa=no\r\n", rtp_code);
10975 break;
10976 case AST_FORMAT_ILBC:
10977
10978 ast_str_append(a_buf, 0, "a=fmtp:%d mode=%d\r\n", rtp_code, fmt.cur_ms);
10979 break;
10980 case AST_FORMAT_SIREN7:
10981
10982 ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=32000\r\n", rtp_code);
10983 break;
10984 case AST_FORMAT_SIREN14:
10985
10986 ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=48000\r\n", rtp_code);
10987 break;
10988 case AST_FORMAT_G719:
10989
10990 ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=64000\r\n", rtp_code);
10991 break;
10992 }
10993
10994 if (fmt.cur_ms && (fmt.cur_ms < *min_packet_size))
10995 *min_packet_size = fmt.cur_ms;
10996
10997
10998 if ((*min_packet_size)==0 && fmt.cur_ms)
10999 *min_packet_size = fmt.cur_ms;
11000 }
11001
11002
11003
11004 static void add_vcodec_to_sdp(const struct sip_pvt *p, format_t codec,
11005 struct ast_str **m_buf, struct ast_str **a_buf,
11006 int debug, int *min_packet_size)
11007 {
11008 int rtp_code;
11009
11010 if (!p->vrtp)
11011 return;
11012
11013 if (debug)
11014 ast_verbose("Adding video codec 0x%" PRIx64 " (%s) to SDP\n", codec, ast_getformatname(codec));
11015
11016 if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->vrtp), 1, codec)) == -1)
11017 return;
11018
11019 ast_str_append(m_buf, 0, " %d", rtp_code);
11020 ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
11021 ast_rtp_lookup_mime_subtype2(1, codec, 0),
11022 ast_rtp_lookup_sample_rate2(1, codec));
11023
11024 }
11025
11026
11027 static void add_tcodec_to_sdp(const struct sip_pvt *p, int codec,
11028 struct ast_str **m_buf, struct ast_str **a_buf,
11029 int debug, int *min_packet_size)
11030 {
11031 int rtp_code;
11032
11033 if (!p->trtp)
11034 return;
11035
11036 if (debug)
11037 ast_verbose("Adding text codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
11038
11039 if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->trtp), 1, codec)) == -1)
11040 return;
11041
11042 ast_str_append(m_buf, 0, " %d", rtp_code);
11043 ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
11044 ast_rtp_lookup_mime_subtype2(1, codec, 0),
11045 ast_rtp_lookup_sample_rate2(1, codec));
11046
11047
11048 if (codec == AST_FORMAT_T140RED) {
11049 int t140code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->trtp), 1, AST_FORMAT_T140);
11050 ast_str_append(a_buf, 0, "a=fmtp:%d %d/%d/%d\r\n", rtp_code,
11051 t140code,
11052 t140code,
11053 t140code);
11054
11055 }
11056 }
11057
11058
11059
11060 static unsigned int t38_get_rate(enum ast_control_t38_rate rate)
11061 {
11062 switch (rate) {
11063 case AST_T38_RATE_2400:
11064 return 2400;
11065 case AST_T38_RATE_4800:
11066 return 4800;
11067 case AST_T38_RATE_7200:
11068 return 7200;
11069 case AST_T38_RATE_9600:
11070 return 9600;
11071 case AST_T38_RATE_12000:
11072 return 12000;
11073 case AST_T38_RATE_14400:
11074 return 14400;
11075 default:
11076 return 0;
11077 }
11078 }
11079
11080
11081 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
11082 struct ast_str **m_buf, struct ast_str **a_buf,
11083 int debug)
11084 {
11085 int rtp_code;
11086
11087 if (debug)
11088 ast_verbose("Adding non-codec 0x%x (%s) to SDP\n", format, ast_rtp_lookup_mime_subtype2(0, format, 0));
11089 if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->rtp), 0, format)) == -1)
11090 return;
11091
11092 ast_str_append(m_buf, 0, " %d", rtp_code);
11093 ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
11094 ast_rtp_lookup_mime_subtype2(0, format, 0),
11095 ast_rtp_lookup_sample_rate2(0, format));
11096 if (format == AST_RTP_DTMF)
11097 ast_str_append(a_buf, 0, "a=fmtp:%d 0-16\r\n", rtp_code);
11098 }
11099
11100
11101
11102
11103 static void get_our_media_address(struct sip_pvt *p, int needvideo, int needtext,
11104 struct ast_sockaddr *addr, struct ast_sockaddr *vaddr,
11105 struct ast_sockaddr *taddr, struct ast_sockaddr *dest,
11106 struct ast_sockaddr *vdest, struct ast_sockaddr *tdest)
11107 {
11108 int use_externip = 0;
11109
11110
11111 ast_rtp_instance_get_local_address(p->rtp, addr);
11112 if (p->vrtp) {
11113 ast_rtp_instance_get_local_address(p->vrtp, vaddr);
11114 }
11115 if (p->trtp) {
11116 ast_rtp_instance_get_local_address(p->trtp, taddr);
11117 }
11118
11119
11120
11121
11122 use_externip = ast_sockaddr_cmp_addr(&p->ourip, addr);
11123
11124
11125
11126 if (!ast_sockaddr_isnull(&p->redirip)) {
11127 ast_sockaddr_copy(dest, &p->redirip);
11128 } else {
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140 ast_sockaddr_copy(dest,
11141 !ast_sockaddr_isnull(&media_address) ? &media_address :
11142 !ast_sockaddr_is_any(addr) && !use_externip ? addr :
11143 &p->ourip);
11144 ast_sockaddr_set_port(dest, ast_sockaddr_port(addr));
11145 }
11146
11147 if (needvideo) {
11148
11149 if (!ast_sockaddr_isnull(&p->vredirip)) {
11150 ast_sockaddr_copy(vdest, &p->vredirip);
11151 } else {
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163 ast_sockaddr_copy(vdest,
11164 !ast_sockaddr_isnull(&media_address) ? &media_address :
11165 !ast_sockaddr_is_any(vaddr) && !use_externip ? vaddr :
11166 &p->ourip);
11167 ast_sockaddr_set_port(vdest, ast_sockaddr_port(vaddr));
11168 }
11169 }
11170
11171 if (needtext) {
11172
11173 if (!ast_sockaddr_isnull(&p->tredirip)) {
11174 ast_sockaddr_copy(tdest, &p->tredirip);
11175 } else {
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187 ast_sockaddr_copy(tdest,
11188 !ast_sockaddr_isnull(&media_address) ? &media_address :
11189 !ast_sockaddr_is_any(taddr) && !use_externip ? taddr :
11190 &p->ourip);
11191 ast_sockaddr_set_port(tdest, ast_sockaddr_port(taddr));
11192 }
11193 }
11194 }
11195
11196 static void get_crypto_attrib(struct sip_srtp *srtp, const char **a_crypto)
11197 {
11198
11199 if (srtp) {
11200 if (!srtp->crypto) {
11201 srtp->crypto = sdp_crypto_setup();
11202 }
11203 if (srtp->crypto && (sdp_crypto_offer(srtp->crypto) >= 0)) {
11204 *a_crypto = sdp_crypto_attrib(srtp->crypto);
11205 }
11206
11207 if (!*a_crypto) {
11208 ast_log(LOG_WARNING, "No SRTP key management enabled\n");
11209 }
11210 }
11211 }
11212
11213
11214
11215
11216
11217
11218
11219 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38)
11220 {
11221 format_t alreadysent = 0;
11222 int doing_directmedia = FALSE;
11223
11224 struct ast_sockaddr addr = { {0,} };
11225 struct ast_sockaddr vaddr = { {0,} };
11226 struct ast_sockaddr taddr = { {0,} };
11227 struct ast_sockaddr udptladdr = { {0,} };
11228 struct ast_sockaddr dest = { {0,} };
11229 struct ast_sockaddr vdest = { {0,} };
11230 struct ast_sockaddr tdest = { {0,} };
11231 struct ast_sockaddr udptldest = { {0,} };
11232
11233
11234 char *version = "v=0\r\n";
11235 char subject[256];
11236 char owner[256];
11237 char connection[256];
11238 char *session_time = "t=0 0\r\n";
11239 char bandwidth[256] = "";
11240 char *hold = "";
11241 struct ast_str *m_audio = ast_str_alloca(256);
11242 struct ast_str *m_video = ast_str_alloca(256);
11243 struct ast_str *m_text = ast_str_alloca(256);
11244 struct ast_str *m_modem = ast_str_alloca(256);
11245 struct ast_str *a_audio = ast_str_alloca(1024);
11246 struct ast_str *a_video = ast_str_alloca(1024);
11247 struct ast_str *a_text = ast_str_alloca(1024);
11248 struct ast_str *a_modem = ast_str_alloca(1024);
11249 const char *a_crypto = NULL;
11250 const char *v_a_crypto = NULL;
11251 const char *t_a_crypto = NULL;
11252
11253 format_t x;
11254 format_t capability = 0;
11255 int needaudio = FALSE;
11256 int needvideo = FALSE;
11257 int needtext = FALSE;
11258 int debug = sip_debug_test_pvt(p);
11259 int min_audio_packet_size = 0;
11260 int min_video_packet_size = 0;
11261 int min_text_packet_size = 0;
11262
11263 char codecbuf[SIPBUFSIZE];
11264 char buf[SIPBUFSIZE];
11265 char dummy_answer[256];
11266
11267
11268 snprintf(subject, sizeof(subject), "s=%s\r\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
11269
11270 if (!p->rtp) {
11271 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
11272 return AST_FAILURE;
11273 }
11274
11275
11276
11277
11278 if (!p->sessionid) {
11279 p->sessionid = (int)ast_random();
11280 p->sessionversion = p->sessionid;
11281 } else {
11282 if (oldsdp == FALSE)
11283 p->sessionversion++;
11284 }
11285
11286 if (add_audio) {
11287 doing_directmedia = (!ast_sockaddr_isnull(&p->redirip) && p->redircodecs) ? TRUE : FALSE;
11288
11289 if ((p->jointcapability & AST_FORMAT_VIDEO_MASK) && !p->novideo) {
11290 if (doing_directmedia && !(p->jointcapability & AST_FORMAT_VIDEO_MASK & p->redircodecs)) {
11291 ast_debug(2, "This call needs video offers, but caller probably did not offer it!\n");
11292 } else if (p->vrtp) {
11293 needvideo = TRUE;
11294 ast_debug(2, "This call needs video offers!\n");
11295 } else {
11296 ast_debug(2, "This call needs video offers, but there's no video support enabled!\n");
11297 }
11298 }
11299
11300 if ((p->jointcapability & AST_FORMAT_TEXT_MASK) && !p->notext) {
11301 if (sipdebug_text)
11302 ast_verbose("We think we can do text\n");
11303 if (p->trtp) {
11304 if (sipdebug_text) {
11305 ast_verbose("And we have a text rtp object\n");
11306 }
11307 needtext = TRUE;
11308 ast_debug(2, "This call needs text offers! \n");
11309 } else {
11310 ast_debug(2, "This call needs text offers, but there's no text support enabled ! \n");
11311 }
11312 }
11313 }
11314
11315 get_our_media_address(p, needvideo, needtext, &addr, &vaddr, &taddr, &dest, &vdest, &tdest);
11316
11317 snprintf(owner, sizeof(owner), "o=%s %d %d IN %s %s\r\n",
11318 ast_strlen_zero(global_sdpowner) ? "-" : global_sdpowner,
11319 p->sessionid, p->sessionversion,
11320 (ast_sockaddr_is_ipv6(&dest) && !ast_sockaddr_is_ipv4_mapped(&dest)) ?
11321 "IP6" : "IP4",
11322 ast_sockaddr_stringify_addr_remote(&dest));
11323
11324 snprintf(connection, sizeof(connection), "c=IN %s %s\r\n",
11325 (ast_sockaddr_is_ipv6(&dest) && !ast_sockaddr_is_ipv4_mapped(&dest)) ?
11326 "IP6" : "IP4",
11327 ast_sockaddr_stringify_addr_remote(&dest));
11328
11329 if (add_audio) {
11330 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_ONEDIR) {
11331 hold = "a=recvonly\r\n";
11332 doing_directmedia = FALSE;
11333 } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_INACTIVE) {
11334 hold = "a=inactive\r\n";
11335 doing_directmedia = FALSE;
11336 } else {
11337 hold = "a=sendrecv\r\n";
11338 }
11339
11340 capability = p->jointcapability;
11341
11342
11343 ast_debug(1, "** Our capability: %s Video flag: %s Text flag: %s\n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), capability),
11344 p->novideo ? "True" : "False", p->notext ? "True" : "False");
11345 ast_debug(1, "** Our prefcodec: %s \n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), p->prefcodec));
11346
11347 if (doing_directmedia) {
11348 capability &= p->redircodecs;
11349 ast_debug(1, "** Our native-bridge filtered capablity: %s\n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), capability));
11350 }
11351
11352
11353 if (capability & AST_FORMAT_AUDIO_MASK)
11354 needaudio = TRUE;
11355
11356 if (debug) {
11357 ast_verbose("Audio is at %s\n", ast_sockaddr_stringify_port(&addr));
11358 }
11359
11360
11361
11362 if (needvideo) {
11363 get_crypto_attrib(p->vsrtp, &v_a_crypto);
11364 ast_str_append(&m_video, 0, "m=video %d RTP/%s", ast_sockaddr_port(&vdest),
11365 v_a_crypto ? "SAVP" : "AVP");
11366
11367
11368 if (p->maxcallbitrate)
11369 snprintf(bandwidth, sizeof(bandwidth), "b=CT:%d\r\n", p->maxcallbitrate);
11370 if (debug) {
11371 ast_verbose("Video is at %s\n", ast_sockaddr_stringify(&vdest));
11372 }
11373 }
11374
11375
11376
11377 if (needtext) {
11378 if (sipdebug_text)
11379 ast_verbose("Lets set up the text sdp\n");
11380 get_crypto_attrib(p->tsrtp, &t_a_crypto);
11381 ast_str_append(&m_text, 0, "m=text %d RTP/%s", ast_sockaddr_port(&tdest),
11382 t_a_crypto ? "SAVP" : "AVP");
11383 if (debug) {
11384 ast_verbose("Text is at %s\n", ast_sockaddr_stringify(&taddr));
11385 }
11386 }
11387
11388
11389
11390
11391
11392
11393 get_crypto_attrib(p->srtp, &a_crypto);
11394 ast_str_append(&m_audio, 0, "m=audio %d RTP/%s", ast_sockaddr_port(&dest),
11395 a_crypto ? "SAVP" : "AVP");
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406 if (capability & p->prefcodec) {
11407 format_t codec = p->prefcodec & AST_FORMAT_AUDIO_MASK;
11408
11409 add_codec_to_sdp(p, codec, &m_audio, &a_audio, debug, &min_audio_packet_size);
11410 alreadysent |= codec;
11411 }
11412
11413
11414 for (x = 0; x < 64; x++) {
11415 format_t codec;
11416
11417 if (!(codec = ast_codec_pref_index(&p->prefs, x)))
11418 break;
11419
11420 if (!(capability & codec))
11421 continue;
11422
11423 if (alreadysent & codec)
11424 continue;
11425
11426 add_codec_to_sdp(p, codec, &m_audio, &a_audio, debug, &min_audio_packet_size);
11427 alreadysent |= codec;
11428 }
11429
11430
11431 for (x = 1ULL; x <= (needtext ? AST_FORMAT_TEXT_MASK : (needvideo ? AST_FORMAT_VIDEO_MASK : AST_FORMAT_AUDIO_MASK)); x <<= 1) {
11432 if (!(capability & x))
11433 continue;
11434
11435 if (alreadysent & x)
11436 continue;
11437
11438 if (x & AST_FORMAT_AUDIO_MASK)
11439 add_codec_to_sdp(p, x, &m_audio, &a_audio, debug, &min_audio_packet_size);
11440 else if (x & AST_FORMAT_VIDEO_MASK)
11441 add_vcodec_to_sdp(p, x, &m_video, &a_video, debug, &min_video_packet_size);
11442 else if (x & AST_FORMAT_TEXT_MASK)
11443 add_tcodec_to_sdp(p, x, &m_text, &a_text, debug, &min_text_packet_size);
11444 }
11445
11446
11447 for (x = 1LL; x <= AST_RTP_MAX; x <<= 1) {
11448 if (!(p->jointnoncodeccapability & x))
11449 continue;
11450
11451 add_noncodec_to_sdp(p, x, &m_audio, &a_audio, debug);
11452 }
11453
11454 ast_debug(3, "-- Done with adding codecs to SDP\n");
11455
11456 if (!p->owner || !ast_internal_timing_enabled(p->owner))
11457 ast_str_append(&a_audio, 0, "a=silenceSupp:off - - - -\r\n");
11458
11459 if (min_audio_packet_size)
11460 ast_str_append(&a_audio, 0, "a=ptime:%d\r\n", min_audio_packet_size);
11461
11462
11463 if (min_video_packet_size)
11464 ast_str_append(&a_video, 0, "a=ptime:%d\r\n", min_video_packet_size);
11465
11466
11467 if (min_text_packet_size)
11468 ast_str_append(&a_text, 0, "a=ptime:%d\r\n", min_text_packet_size);
11469
11470 if (m_audio->len - m_audio->used < 2 || m_video->len - m_video->used < 2 ||
11471 m_text->len - m_text->used < 2 || a_text->len - a_text->used < 2 ||
11472 a_audio->len - a_audio->used < 2 || a_video->len - a_video->used < 2)
11473 ast_log(LOG_WARNING, "SIP SDP may be truncated due to undersized buffer!!\n");
11474 }
11475
11476 if (add_t38) {
11477
11478 ast_udptl_get_us(p->udptl, &udptladdr);
11479
11480
11481 if (!ast_sockaddr_isnull(&p->udptlredirip)) {
11482 ast_sockaddr_copy(&udptldest, &p->udptlredirip);
11483 } else {
11484 ast_sockaddr_copy(&udptldest, &p->ourip);
11485 ast_sockaddr_set_port(&udptldest, ast_sockaddr_port(&udptladdr));
11486 }
11487
11488 if (debug) {
11489 ast_debug(1, "T.38 UDPTL is at %s port %d\n", ast_sockaddr_stringify_addr(&p->ourip), ast_sockaddr_port(&udptladdr));
11490 }
11491
11492
11493
11494
11495 ast_str_append(&m_modem, 0, "m=image %d udptl t38\r\n", ast_sockaddr_port(&udptldest));
11496
11497 if (!ast_sockaddr_cmp(&udptldest, &dest)) {
11498 ast_str_append(&m_modem, 0, "c=IN %s %s\r\n",
11499 (ast_sockaddr_is_ipv6(&dest) && !ast_sockaddr_is_ipv4_mapped(&dest)) ?
11500 "IP6" : "IP4", ast_sockaddr_stringify_addr_remote(&udptldest));
11501 }
11502
11503 ast_str_append(&a_modem, 0, "a=T38FaxVersion:%d\r\n", p->t38.our_parms.version);
11504 ast_str_append(&a_modem, 0, "a=T38MaxBitRate:%d\r\n", t38_get_rate(p->t38.our_parms.rate));
11505 if (p->t38.our_parms.fill_bit_removal) {
11506 ast_str_append(&a_modem, 0, "a=T38FaxFillBitRemoval\r\n");
11507 }
11508 if (p->t38.our_parms.transcoding_mmr) {
11509 ast_str_append(&a_modem, 0, "a=T38FaxTranscodingMMR\r\n");
11510 }
11511 if (p->t38.our_parms.transcoding_jbig) {
11512 ast_str_append(&a_modem, 0, "a=T38FaxTranscodingJBIG\r\n");
11513 }
11514 switch (p->t38.our_parms.rate_management) {
11515 case AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF:
11516 ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:transferredTCF\r\n");
11517 break;
11518 case AST_T38_RATE_MANAGEMENT_LOCAL_TCF:
11519 ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:localTCF\r\n");
11520 break;
11521 }
11522 ast_str_append(&a_modem, 0, "a=T38FaxMaxDatagram:%u\r\n", ast_udptl_get_local_max_datagram(p->udptl));
11523 switch (ast_udptl_get_error_correction_scheme(p->udptl)) {
11524 case UDPTL_ERROR_CORRECTION_NONE:
11525 break;
11526 case UDPTL_ERROR_CORRECTION_FEC:
11527 ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPFEC\r\n");
11528 break;
11529 case UDPTL_ERROR_CORRECTION_REDUNDANCY:
11530 ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPRedundancy\r\n");
11531 break;
11532 }
11533 }
11534
11535 if (needaudio)
11536 ast_str_append(&m_audio, 0, "\r\n");
11537 if (needvideo)
11538 ast_str_append(&m_video, 0, "\r\n");
11539 if (needtext)
11540 ast_str_append(&m_text, 0, "\r\n");
11541
11542 add_header(resp, "Content-Type", "application/sdp");
11543 add_content(resp, version);
11544 add_content(resp, owner);
11545 add_content(resp, subject);
11546 add_content(resp, connection);
11547
11548 if (needvideo) {
11549 add_content(resp, bandwidth);
11550 }
11551 add_content(resp, session_time);
11552
11553 if (p->offered_media[SDP_AUDIO].order_offered ||
11554 p->offered_media[SDP_VIDEO].order_offered ||
11555 p->offered_media[SDP_TEXT].order_offered ||
11556 p->offered_media[SDP_IMAGE].order_offered) {
11557 int i;
11558
11559 for (i = 1; i <= 3; i++) {
11560 if (p->offered_media[SDP_AUDIO].order_offered == i) {
11561 if (needaudio) {
11562 add_content(resp, m_audio->str);
11563 add_content(resp, a_audio->str);
11564 add_content(resp, hold);
11565 if (a_crypto) {
11566 add_content(resp, a_crypto);
11567 }
11568 } else {
11569 snprintf(dummy_answer, sizeof(dummy_answer), "m=audio 0 RTP/AVP %s\r\n", p->offered_media[SDP_AUDIO].codecs);
11570 add_content(resp, dummy_answer);
11571 }
11572 } else if (p->offered_media[SDP_VIDEO].order_offered == i) {
11573 if (needvideo) {
11574 add_content(resp, m_video->str);
11575 add_content(resp, a_video->str);
11576 add_content(resp, hold);
11577 if (v_a_crypto) {
11578 add_content(resp, v_a_crypto);
11579 }
11580 } else {
11581 snprintf(dummy_answer, sizeof(dummy_answer), "m=video 0 RTP/AVP %s\r\n", p->offered_media[SDP_VIDEO].codecs);
11582 add_content(resp, dummy_answer);
11583 }
11584 } else if (p->offered_media[SDP_TEXT].order_offered == i) {
11585 if (needtext) {
11586 add_content(resp, m_text->str);
11587 add_content(resp, a_text->str);
11588 add_content(resp, hold);
11589 if (t_a_crypto) {
11590 add_content(resp, t_a_crypto);
11591 }
11592 } else {
11593 snprintf(dummy_answer, sizeof(dummy_answer), "m=text 0 RTP/AVP %s\r\n", p->offered_media[SDP_TEXT].codecs);
11594 add_content(resp, dummy_answer);
11595 }
11596 } else if (p->offered_media[SDP_IMAGE].order_offered == i) {
11597 if (add_t38) {
11598 add_content(resp, m_modem->str);
11599 add_content(resp, a_modem->str);
11600 } else {
11601 add_content(resp, "m=image 0 udptl t38\r\n");
11602 }
11603 }
11604 }
11605 } else {
11606
11607 if (needaudio) {
11608 add_content(resp, m_audio->str);
11609 add_content(resp, a_audio->str);
11610 add_content(resp, hold);
11611 if (a_crypto) {
11612 add_content(resp, a_crypto);
11613 }
11614 }
11615 if (needvideo) {
11616 add_content(resp, m_video->str);
11617 add_content(resp, a_video->str);
11618 add_content(resp, hold);
11619 if (v_a_crypto) {
11620 add_content(resp, v_a_crypto);
11621 }
11622 }
11623 if (needtext) {
11624 add_content(resp, m_text->str);
11625 add_content(resp, a_text->str);
11626 add_content(resp, hold);
11627 if (t_a_crypto) {
11628 add_content(resp, t_a_crypto);
11629 }
11630 }
11631 if (add_t38) {
11632 add_content(resp, m_modem->str);
11633 add_content(resp, a_modem->str);
11634 }
11635 }
11636
11637
11638 p->lastrtprx = p->lastrtptx = time(NULL);
11639
11640 ast_debug(3, "Done building SDP. Settling with this capability: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, capability));
11641
11642 return AST_SUCCESS;
11643 }
11644
11645
11646 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
11647 {
11648 struct sip_request resp;
11649 uint32_t seqno;
11650
11651 if (sscanf(get_header(req, "CSeq"), "%30u ", &seqno) != 1) {
11652 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
11653 return -1;
11654 }
11655 respprep(&resp, p, msg, req);
11656 if (p->udptl) {
11657 add_sdp(&resp, p, 0, 0, 1);
11658 } else
11659 ast_log(LOG_ERROR, "Can't add SDP to response, since we have no UDPTL session allocated. Call-ID %s\n", p->callid);
11660 if (retrans && !p->pendinginvite)
11661 p->pendinginvite = seqno;
11662 return send_response(p, &resp, retrans, seqno);
11663 }
11664
11665
11666 static void copy_request(struct sip_request *dst, const struct sip_request *src)
11667 {
11668
11669
11670
11671 struct ast_str *duplicate = dst->data;
11672 struct ast_str *duplicate_content = dst->content;
11673
11674
11675
11676 memcpy(dst, src, sizeof(*dst));
11677 dst->data = duplicate;
11678 dst->content = duplicate_content;
11679
11680
11681 if (!dst->data && !(dst->data = ast_str_create(ast_str_strlen(src->data) + 1)))
11682 return;
11683 ast_str_copy_string(&dst->data, src->data);
11684
11685
11686 if (src->content) {
11687 if (!dst->content && !(dst->content = ast_str_create(ast_str_strlen(src->content) + 1)))
11688 return;
11689 ast_str_copy_string(&dst->content, src->content);
11690 }
11691 }
11692
11693 static void add_cc_call_info_to_response(struct sip_pvt *p, struct sip_request *resp)
11694 {
11695 char uri[SIPBUFSIZE];
11696 struct ast_str *header = ast_str_alloca(SIPBUFSIZE);
11697 struct ast_cc_agent *agent = find_sip_cc_agent_by_original_callid(p);
11698 struct sip_cc_agent_pvt *agent_pvt;
11699
11700 if (!agent) {
11701
11702
11703
11704 ast_log(LOG_WARNING, "Can't find SIP CC agent for call '%s' even though OFFER_CC flag was set?\n", p->callid);
11705 return;
11706 }
11707
11708 agent_pvt = agent->private_data;
11709
11710 if (!ast_strlen_zero(agent_pvt->subscribe_uri)) {
11711 ast_copy_string(uri, agent_pvt->subscribe_uri, sizeof(uri));
11712 } else {
11713 generate_uri(p, uri, sizeof(uri));
11714 ast_copy_string(agent_pvt->subscribe_uri, uri, sizeof(agent_pvt->subscribe_uri));
11715 }
11716
11717
11718
11719
11720 ast_str_set(&header, 0, "<%s>;purpose=call-completion;m=%s", uri, "NR");
11721 add_header(resp, "Call-Info", ast_str_buffer(header));
11722 ao2_ref(agent, -1);
11723 }
11724
11725
11726
11727
11728 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)
11729 {
11730 struct sip_request resp;
11731 uint32_t seqno;
11732 if (sscanf(get_header(req, "CSeq"), "%30u ", &seqno) != 1) {
11733 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
11734 return -1;
11735 }
11736 respprep(&resp, p, msg, req);
11737 if (rpid == TRUE) {
11738 add_rpid(&resp, p);
11739 }
11740 if (ast_test_flag(&p->flags[0], SIP_OFFER_CC)) {
11741 add_cc_call_info_to_response(p, &resp);
11742 }
11743 if (p->rtp) {
11744 if (!p->autoframing && !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
11745 ast_debug(1, "Setting framing from config on incoming call\n");
11746 ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(p->rtp), p->rtp, &p->prefs);
11747 }
11748 ast_rtp_instance_activate(p->rtp);
11749 try_suggested_sip_codec(p);
11750 if (p->t38.state == T38_ENABLED) {
11751 add_sdp(&resp, p, oldsdp, TRUE, TRUE);
11752 } else {
11753 add_sdp(&resp, p, oldsdp, TRUE, FALSE);
11754 }
11755 } else
11756 ast_log(LOG_ERROR, "Can't add SDP to response, since we have no RTP session allocated. Call-ID %s\n", p->callid);
11757 if (reliable && !p->pendinginvite)
11758 p->pendinginvite = seqno;
11759 return send_response(p, &resp, reliable, seqno);
11760 }
11761
11762
11763 static int determine_firstline_parts(struct sip_request *req)
11764 {
11765 char *e = ast_skip_blanks(req->data->str);
11766 char *local_rlPart1;
11767
11768 if (!*e)
11769 return -1;
11770 req->rlPart1 = e - req->data->str;
11771 local_rlPart1 = e;
11772 e = ast_skip_nonblanks(e);
11773 if (*e)
11774 *e++ = '\0';
11775
11776 e = ast_skip_blanks(e);
11777 if ( !*e )
11778 return -1;
11779 ast_trim_blanks(e);
11780
11781 if (!strcasecmp(local_rlPart1, "SIP/2.0") ) {
11782 if (strlen(e) < 3)
11783 return -1;
11784 req->rlPart2 = e - req->data->str;
11785 } else {
11786 if ( *e == '<' ) {
11787 ast_debug(3, "Oops. Bogus uri in <> %s\n", e);
11788 e++;
11789 if (!*e)
11790 return -1;
11791 }
11792 req->rlPart2 = e - req->data->str;
11793 e = ast_skip_nonblanks(e);
11794 if (*e)
11795 *e++ = '\0';
11796 e = ast_skip_blanks(e);
11797 if (strcasecmp(e, "SIP/2.0") ) {
11798 ast_debug(3, "Skipping packet - Bad request protocol %s\n", e);
11799 return -1;
11800 }
11801 }
11802 return 1;
11803 }
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp)
11819 {
11820 struct sip_request req;
11821
11822 reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ? SIP_UPDATE : SIP_INVITE, 0, 1);
11823
11824 add_header(&req, "Allow", ALLOWED_METHODS);
11825 add_supported_header(p, &req);
11826 if (sipdebug) {
11827 if (oldsdp == TRUE)
11828 add_header(&req, "X-asterisk-Info", "SIP re-invite (Session-Timers)");
11829 else
11830 add_header(&req, "X-asterisk-Info", "SIP re-invite (External RTP bridge)");
11831 }
11832
11833 if (ast_test_flag(&p->flags[0], SIP_SENDRPID))
11834 add_rpid(&req, p);
11835
11836 if (p->do_history) {
11837 append_history(p, "ReInv", "Re-invite sent");
11838 }
11839 memset(p->offered_media, 0, sizeof(p->offered_media));
11840
11841 try_suggested_sip_codec(p);
11842 if (t38version) {
11843 add_sdp(&req, p, oldsdp, FALSE, TRUE);
11844 } else {
11845 add_sdp(&req, p, oldsdp, TRUE, FALSE);
11846 }
11847
11848
11849 initialize_initreq(p, &req);
11850 p->lastinvite = p->ocseq;
11851 ast_set_flag(&p->flags[0], SIP_OUTGOING);
11852
11853 return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
11854 }
11855
11856
11857 static char *remove_uri_parameters(char *uri)
11858 {
11859 char *atsign;
11860 atsign = strchr(uri, '@');
11861 if (!atsign) {
11862 atsign = uri;
11863 }
11864 atsign = strchr(atsign, ';');
11865 if (atsign)
11866 *atsign = '\0';
11867 return uri;
11868 }
11869
11870
11871 static void extract_uri(struct sip_pvt *p, struct sip_request *req)
11872 {
11873 char stripped[SIPBUFSIZE];
11874 char *c;
11875
11876 ast_copy_string(stripped, get_header(req, "Contact"), sizeof(stripped));
11877 c = get_in_brackets(stripped);
11878
11879 c = remove_uri_parameters(c);
11880 if (!ast_strlen_zero(c)) {
11881 ast_string_field_set(p, uri, c);
11882 }
11883
11884 }
11885
11886
11887 static void build_contact(struct sip_pvt *p)
11888 {
11889 char tmp[SIPBUFSIZE];
11890 char *user = ast_uri_encode(p->exten, tmp, sizeof(tmp), 0);
11891
11892 if (p->socket.type == SIP_TRANSPORT_UDP) {
11893 ast_string_field_build(p, our_contact, "<sip:%s%s%s>", user,
11894 ast_strlen_zero(user) ? "" : "@", ast_sockaddr_stringify_remote(&p->ourip));
11895 } else {
11896 ast_string_field_build(p, our_contact, "<sip:%s%s%s;transport=%s>", user,
11897 ast_strlen_zero(user) ? "" : "@", ast_sockaddr_stringify_remote(&p->ourip),
11898 get_transport(p->socket.type));
11899 }
11900 }
11901
11902
11903 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, const char * const explicit_uri)
11904 {
11905 struct ast_str *invite = ast_str_alloca(256);
11906 char from[256];
11907 char to[256];
11908 char tmp_n[SIPBUFSIZE/2];
11909 char tmp_l[SIPBUFSIZE/2];
11910 const char *l = NULL;
11911 const char *n = NULL;
11912 const char *d = NULL;
11913 const char *urioptions = "";
11914 int ourport;
11915
11916 if (ast_test_flag(&p->flags[0], SIP_USEREQPHONE)) {
11917 const char *s = p->username;
11918
11919
11920
11921
11922
11923
11924 if (*s == '+')
11925 s++;
11926 for (; *s; s++) {
11927 if (!strchr(AST_DIGIT_ANYNUM, *s) )
11928 break;
11929 }
11930
11931 if (!*s)
11932 urioptions = ";user=phone";
11933 }
11934
11935
11936 snprintf(p->lastmsg, sizeof(p->lastmsg), "Init: %s", sip_methods[sipmethod].text);
11937
11938 d = S_OR(p->fromdomain, ast_sockaddr_stringify_host_remote(&p->ourip));
11939 if (p->owner) {
11940 if ((ast_party_id_presentation(&p->owner->connected.id) & AST_PRES_RESTRICTION) == AST_PRES_ALLOWED) {
11941 l = p->owner->connected.id.number.valid ? p->owner->connected.id.number.str : NULL;
11942 n = p->owner->connected.id.name.valid ? p->owner->connected.id.name.str : NULL;
11943 } else {
11944
11945
11946 l = CALLERID_UNKNOWN;
11947 n = l;
11948 d = FROMDOMAIN_INVALID;
11949 }
11950 }
11951
11952
11953
11954
11955
11956
11957
11958 if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->mwi_from)) {
11959 l = p->mwi_from;
11960 }
11961
11962 if (ast_strlen_zero(l))
11963 l = default_callerid;
11964 if (ast_strlen_zero(n))
11965 n = l;
11966
11967 if (!ast_strlen_zero(p->fromuser))
11968 l = p->fromuser;
11969 else
11970 ast_string_field_set(p, fromuser, l);
11971
11972
11973 if (!ast_strlen_zero(p->fromname))
11974 n = p->fromname;
11975 else
11976 ast_string_field_set(p, fromname, n);
11977
11978 if (sip_cfg.pedanticsipchecking) {
11979 ast_escape_quoted(n, tmp_n, sizeof(tmp_n));
11980 n = tmp_n;
11981 ast_uri_encode(l, tmp_l, sizeof(tmp_l), 0);
11982 l = tmp_l;
11983 }
11984
11985 ourport = (p->fromdomainport) ? p->fromdomainport : ast_sockaddr_port(&p->ourip);
11986 if (!sip_standard_port(p->socket.type, ourport)) {
11987 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s:%d>;tag=%s", n, l, d, ourport, p->tag);
11988 } else {
11989 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=%s", n, l, d, p->tag);
11990 }
11991
11992 if (!ast_strlen_zero(explicit_uri)) {
11993 ast_str_set(&invite, 0, "%s", explicit_uri);
11994 } else {
11995
11996 if (!ast_strlen_zero(p->fullcontact)) {
11997
11998 ast_str_append(&invite, 0, "%s", p->fullcontact);
11999 } else {
12000
12001 ast_str_append(&invite, 0, "sip:");
12002 if (!ast_strlen_zero(p->username)) {
12003 n = p->username;
12004 if (sip_cfg.pedanticsipchecking) {
12005 ast_uri_encode(n, tmp_n, sizeof(tmp_n), 0);
12006 n = tmp_n;
12007 }
12008 ast_str_append(&invite, 0, "%s@", n);
12009 }
12010 ast_str_append(&invite, 0, "%s", p->tohost);
12011 if (p->portinuri) {
12012 ast_str_append(&invite, 0, ":%d", ast_sockaddr_port(&p->sa));
12013 }
12014 ast_str_append(&invite, 0, "%s", urioptions);
12015 }
12016 }
12017
12018
12019 if (p->options && !ast_strlen_zero(p->options->uri_options))
12020 ast_str_append(&invite, 0, ";%s", p->options->uri_options);
12021
12022
12023
12024
12025 ast_string_field_set(p, uri, invite->str);
12026
12027 if (!ast_strlen_zero(p->todnid)) {
12028
12029 if (!strchr(p->todnid, '@')) {
12030
12031 snprintf(to, sizeof(to), "<sip:%s@%s>%s%s", p->todnid, p->tohost, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
12032 } else {
12033 snprintf(to, sizeof(to), "<sip:%s>%s%s", p->todnid, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
12034 }
12035 } else {
12036 if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->theirtag)) {
12037
12038 snprintf(to, sizeof(to), "<%s%s>;tag=%s", (strncasecmp(p->uri, "sip:", 4) ? "sip:" : ""), p->uri, p->theirtag);
12039 } else if (p->options && p->options->vxml_url) {
12040
12041 snprintf(to, sizeof(to), "<%s>;%s", p->uri, p->options->vxml_url);
12042 } else {
12043 snprintf(to, sizeof(to), "<%s>", p->uri);
12044 }
12045 }
12046
12047 init_req(req, sipmethod, p->uri);
12048
12049 snprintf(tmp_n, sizeof(tmp_n), "%u %s", ++p->ocseq, sip_methods[sipmethod].text);
12050
12051 add_header(req, "Via", p->via);
12052 add_header_max_forwards(p, req);
12053
12054
12055
12056
12057 add_route(req, p->route);
12058
12059 add_header(req, "From", from);
12060 add_header(req, "To", to);
12061 ast_string_field_set(p, exten, l);
12062 build_contact(p);
12063 add_header(req, "Contact", p->our_contact);
12064 add_header(req, "Call-ID", p->callid);
12065 add_header(req, "CSeq", tmp_n);
12066 if (!ast_strlen_zero(global_useragent)) {
12067 add_header(req, "User-Agent", global_useragent);
12068 }
12069 }
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079 static void add_diversion_header(struct sip_request *req, struct sip_pvt *pvt)
12080 {
12081 const char *diverting_number;
12082 const char *diverting_name;
12083 const char *reason;
12084 char header_text[256];
12085
12086 if (!pvt->owner) {
12087 return;
12088 }
12089
12090 diverting_number = pvt->owner->redirecting.from.number.str;
12091 if (!pvt->owner->redirecting.from.number.valid
12092 || ast_strlen_zero(diverting_number)) {
12093 return;
12094 }
12095
12096 reason = sip_reason_code_to_str(pvt->owner->redirecting.reason);
12097
12098
12099 diverting_name = pvt->owner->redirecting.from.name.str;
12100 if (!pvt->owner->redirecting.from.name.valid
12101 || ast_strlen_zero(diverting_name)) {
12102 snprintf(header_text, sizeof(header_text), "<sip:%s@%s>;reason=%s", diverting_number,
12103 ast_sockaddr_stringify_host_remote(&pvt->ourip), reason);
12104 } else {
12105 snprintf(header_text, sizeof(header_text), "\"%s\" <sip:%s@%s>;reason=%s",
12106 diverting_name, diverting_number,
12107 ast_sockaddr_stringify_host_remote(&pvt->ourip), reason);
12108 }
12109
12110 add_header(req, "Diversion", header_text);
12111 }
12112
12113 static int transmit_publish(struct sip_epa_entry *epa_entry, enum sip_publish_type publish_type, const char * const explicit_uri)
12114 {
12115 struct sip_pvt *pvt;
12116 int expires;
12117
12118 epa_entry->publish_type = publish_type;
12119
12120 if (!(pvt = sip_alloc(NULL, NULL, 0, SIP_PUBLISH, NULL))) {
12121 return -1;
12122 }
12123
12124 sip_pvt_lock(pvt);
12125
12126 if (create_addr(pvt, epa_entry->destination, NULL, TRUE, NULL)) {
12127 sip_pvt_unlock(pvt);
12128 dialog_unlink_all(pvt);
12129 dialog_unref(pvt, "create_addr failed in transmit_publish. Unref dialog");
12130 return -1;
12131 }
12132 ast_sip_ouraddrfor(&pvt->sa, &pvt->ourip, pvt);
12133 ast_set_flag(&pvt->flags[0], SIP_OUTGOING);
12134 expires = (publish_type == SIP_PUBLISH_REMOVE) ? 0 : DEFAULT_PUBLISH_EXPIRES;
12135 pvt->expiry = expires;
12136
12137
12138 ao2_ref(epa_entry, +1);
12139 pvt->epa_entry = epa_entry;
12140
12141 transmit_invite(pvt, SIP_PUBLISH, FALSE, 2, explicit_uri);
12142 sip_pvt_unlock(pvt);
12143 sip_scheddestroy(pvt, DEFAULT_TRANS_TIMEOUT);
12144 dialog_unref(pvt, "Done with the sip_pvt allocated for transmitting PUBLISH");
12145 return 0;
12146 }
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init, const char * const explicit_uri)
12158 {
12159 struct sip_request req;
12160 struct ast_variable *var;
12161
12162 req.method = sipmethod;
12163 if (init) {
12164 p->branch ^= ast_random();
12165 p->invite_branch = p->branch;
12166 build_via(p);
12167 }
12168 if (init > 1) {
12169 initreqprep(&req, p, sipmethod, explicit_uri);
12170 } else {
12171
12172 reqprep(&req, p, sipmethod, 0, init ? 0 : 1);
12173 }
12174
12175 if (p->options && p->options->auth) {
12176 add_header(&req, p->options->authheader, p->options->auth);
12177 }
12178 append_date(&req);
12179 if (sipmethod == SIP_REFER) {
12180 if (p->refer) {
12181 char buf[SIPBUFSIZE];
12182 if (!ast_strlen_zero(p->refer->refer_to)) {
12183 add_header(&req, "Refer-To", p->refer->refer_to);
12184 }
12185 if (!ast_strlen_zero(p->refer->referred_by)) {
12186 snprintf(buf, sizeof(buf), "%s <%s>", p->refer->referred_by_name, p->refer->referred_by);
12187 add_header(&req, "Referred-By", buf);
12188 }
12189 }
12190 } else if (sipmethod == SIP_SUBSCRIBE) {
12191 char buf[SIPBUFSIZE];
12192 if (p->subscribed == MWI_NOTIFICATION) {
12193 add_header(&req, "Event", "message-summary");
12194 add_header(&req, "Accept", "application/simple-message-summary");
12195 } else if (p->subscribed == CALL_COMPLETION) {
12196 add_header(&req, "Event", "call-completion");
12197 add_header(&req, "Accept", "application/call-completion");
12198 }
12199 snprintf(buf, sizeof(buf), "%d", p->expiry);
12200 add_header(&req, "Expires", buf);
12201 }
12202
12203
12204
12205 if (p->options && !ast_strlen_zero(p->options->replaces)) {
12206 add_header(&req, "Replaces", p->options->replaces);
12207 add_header(&req, "Require", "replaces");
12208 }
12209
12210
12211 if (st_get_mode(p, 0) == SESSION_TIMER_MODE_ORIGINATE) {
12212 char i2astr[10];
12213
12214 if (!p->stimer->st_interval) {
12215 p->stimer->st_interval = st_get_se(p, TRUE);
12216 }
12217
12218 p->stimer->st_active = TRUE;
12219
12220 snprintf(i2astr, sizeof(i2astr), "%d", p->stimer->st_interval);
12221 add_header(&req, "Session-Expires", i2astr);
12222 snprintf(i2astr, sizeof(i2astr), "%d", st_get_se(p, FALSE));
12223 add_header(&req, "Min-SE", i2astr);
12224 }
12225
12226 add_header(&req, "Allow", ALLOWED_METHODS);
12227 add_supported_header(p, &req);
12228
12229 if (p->options && p->options->addsipheaders && p->owner) {
12230 struct ast_channel *chan = p->owner;
12231 struct varshead *headp;
12232
12233 ast_channel_lock(chan);
12234
12235 headp = &chan->varshead;
12236
12237 if (!headp) {
12238 ast_log(LOG_WARNING, "No Headp for the channel...ooops!\n");
12239 } else {
12240 const struct ast_var_t *current;
12241 AST_LIST_TRAVERSE(headp, current, entries) {
12242
12243 if (!strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
12244 char *content, *end;
12245 const char *header = ast_var_value(current);
12246 char *headdup = ast_strdupa(header);
12247
12248
12249 if (*headdup == '"') {
12250 headdup++;
12251 }
12252 if ((content = strchr(headdup, ':'))) {
12253 *content++ = '\0';
12254 content = ast_skip_blanks(content);
12255
12256 end = content + strlen(content) -1;
12257 if (*end == '"') {
12258 *end = '\0';
12259 }
12260
12261 add_header(&req, headdup, content);
12262 if (sipdebug) {
12263 ast_debug(1, "Adding SIP Header \"%s\" with content :%s: \n", headdup, content);
12264 }
12265 }
12266 }
12267 }
12268 }
12269
12270 ast_channel_unlock(chan);
12271 }
12272 if ((sipmethod == SIP_INVITE || sipmethod == SIP_UPDATE) && ast_test_flag(&p->flags[0], SIP_SENDRPID))
12273 add_rpid(&req, p);
12274 if (sipmethod == SIP_INVITE) {
12275 add_diversion_header(&req, p);
12276 }
12277 if (sdp) {
12278 memset(p->offered_media, 0, sizeof(p->offered_media));
12279 if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
12280 ast_debug(1, "T38 is in state %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
12281 add_sdp(&req, p, FALSE, FALSE, TRUE);
12282 } else if (p->rtp) {
12283 try_suggested_sip_codec(p);
12284 add_sdp(&req, p, FALSE, TRUE, FALSE);
12285 }
12286 } else if (p->notify) {
12287 for (var = p->notify->headers; var; var = var->next) {
12288 add_header(&req, var->name, var->value);
12289 }
12290 if (ast_str_strlen(p->notify->content)) {
12291 add_content(&req, ast_str_buffer(p->notify->content));
12292 }
12293 } else if (sipmethod == SIP_PUBLISH) {
12294 char expires[SIPBUFSIZE];
12295
12296 switch (p->epa_entry->static_data->event) {
12297 case CALL_COMPLETION:
12298 snprintf(expires, sizeof(expires), "%d", p->expiry);
12299 add_header(&req, "Event", "call-completion");
12300 add_header(&req, "Expires", expires);
12301 if (p->epa_entry->publish_type != SIP_PUBLISH_INITIAL) {
12302 add_header(&req, "SIP-If-Match", p->epa_entry->entity_tag);
12303 }
12304
12305 if (!ast_strlen_zero(p->epa_entry->body)) {
12306 add_header(&req, "Content-Type", "application/pidf+xml");
12307 add_content(&req, p->epa_entry->body);
12308 }
12309 default:
12310 break;
12311 }
12312 }
12313
12314 if (!p->initreq.headers || init > 2) {
12315 initialize_initreq(p, &req);
12316 }
12317 if (sipmethod == SIP_INVITE || sipmethod == SIP_SUBSCRIBE) {
12318 p->lastinvite = p->ocseq;
12319 }
12320 return send_request(p, &req, init ? XMIT_CRITICAL : XMIT_RELIABLE, p->ocseq);
12321 }
12322
12323
12324 static int sip_subscribe_mwi_do(const void *data)
12325 {
12326 struct sip_subscription_mwi *mwi = (struct sip_subscription_mwi*)data;
12327
12328 if (!mwi) {
12329 return -1;
12330 }
12331
12332 mwi->resub = -1;
12333 __sip_subscribe_mwi_do(mwi);
12334 ASTOBJ_UNREF(mwi, sip_subscribe_mwi_destroy);
12335
12336 return 0;
12337 }
12338
12339 static void on_dns_update_registry(struct ast_sockaddr *old, struct ast_sockaddr *new, void *data)
12340 {
12341 struct sip_registry *reg = data;
12342 const char *old_str;
12343
12344
12345 if (ast_sockaddr_isnull(new)) {
12346 ast_debug(1, "Empty sockaddr change...ignoring!\n");
12347 return;
12348 }
12349
12350 if (!ast_sockaddr_port(new)) {
12351 ast_sockaddr_set_port(new, reg->portno);
12352 }
12353
12354 old_str = ast_strdupa(ast_sockaddr_stringify(old));
12355
12356 ast_debug(1, "Changing registry %s from %s to %s\n", S_OR(reg->peername, reg->hostname), old_str, ast_sockaddr_stringify(new));
12357 ast_sockaddr_copy(®->us, new);
12358 }
12359
12360 static void on_dns_update_peer(struct ast_sockaddr *old, struct ast_sockaddr *new, void *data)
12361 {
12362 struct sip_peer *peer = data;
12363 const char *old_str;
12364
12365
12366 if (ast_sockaddr_isnull(new)) {
12367 ast_debug(1, "Empty sockaddr change...ignoring!\n");
12368 return;
12369 }
12370
12371 if (!ast_sockaddr_isnull(&peer->addr)) {
12372 ao2_unlink(peers_by_ip, peer);
12373 }
12374
12375 if (!ast_sockaddr_port(new)) {
12376 ast_sockaddr_set_port(new, default_sip_port(peer->socket.type));
12377 }
12378
12379 old_str = ast_strdupa(ast_sockaddr_stringify(old));
12380 ast_debug(1, "Changing peer %s address from %s to %s\n", peer->name, old_str, ast_sockaddr_stringify(new));
12381
12382 ao2_lock(peer);
12383 ast_sockaddr_copy(&peer->addr, new);
12384 ao2_unlock(peer);
12385
12386 ao2_link(peers_by_ip, peer);
12387 }
12388
12389 static void on_dns_update_mwi(struct ast_sockaddr *old, struct ast_sockaddr *new, void *data)
12390 {
12391 struct sip_subscription_mwi *mwi = data;
12392 const char *old_str;
12393
12394
12395 if (ast_sockaddr_isnull(new)) {
12396 ast_debug(1, "Empty sockaddr change...ignoring!\n");
12397 return;
12398 }
12399
12400 old_str = ast_strdupa(ast_sockaddr_stringify(old));
12401 ast_debug(1, "Changing mwi %s from %s to %s\n", mwi->hostname, old_str, ast_sockaddr_stringify(new));
12402 ast_sockaddr_copy(&mwi->us, new);
12403 }
12404
12405
12406 static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi)
12407 {
12408
12409 if (!mwi->dnsmgr) {
12410 char transport[MAXHOSTNAMELEN];
12411 struct sip_subscription_mwi *saved;
12412 snprintf(transport, sizeof(transport), "_%s._%s", get_srv_service(mwi->transport), get_srv_protocol(mwi->transport));
12413
12414 mwi->us.ss.ss_family = get_address_family_filter(&bindaddr);
12415 saved = ASTOBJ_REF(mwi);
12416 ast_dnsmgr_lookup_cb(mwi->hostname, &mwi->us, &mwi->dnsmgr, sip_cfg.srvlookup ? transport : NULL, on_dns_update_mwi, saved);
12417 if (!mwi->dnsmgr) {
12418 ASTOBJ_UNREF(saved, sip_subscribe_mwi_destroy);
12419 }
12420 }
12421
12422
12423 if (mwi->call) {
12424 transmit_invite(mwi->call, SIP_SUBSCRIBE, 0, 0, NULL);
12425 return 0;
12426 }
12427
12428
12429 if (!(mwi->call = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL))) {
12430 return -1;
12431 }
12432
12433 ref_proxy(mwi->call, obproxy_get(mwi->call, NULL));
12434
12435 if (!ast_sockaddr_port(&mwi->us) && mwi->portno) {
12436 ast_sockaddr_set_port(&mwi->us, mwi->portno);
12437 }
12438
12439
12440 if (create_addr(mwi->call, mwi->hostname, &mwi->us, 0, NULL)) {
12441 dialog_unlink_all(mwi->call);
12442 mwi->call = dialog_unref(mwi->call, "unref dialog after unlink_all");
12443 return 0;
12444 }
12445
12446 mwi->call->expiry = mwi_expiry;
12447
12448 if (!mwi->dnsmgr && mwi->portno) {
12449 ast_sockaddr_set_port(&mwi->call->sa, mwi->portno);
12450 ast_sockaddr_set_port(&mwi->call->recv, mwi->portno);
12451 } else {
12452 mwi->portno = ast_sockaddr_port(&mwi->call->sa);
12453 }
12454
12455
12456 if (!ast_strlen_zero(mwi->authuser)) {
12457 ast_string_field_set(mwi->call, peername, mwi->authuser);
12458 ast_string_field_set(mwi->call, authname, mwi->authuser);
12459 ast_string_field_set(mwi->call, fromuser, mwi->authuser);
12460 } else {
12461 ast_string_field_set(mwi->call, peername, mwi->username);
12462 ast_string_field_set(mwi->call, authname, mwi->username);
12463 ast_string_field_set(mwi->call, fromuser, mwi->username);
12464 }
12465 ast_string_field_set(mwi->call, username, mwi->username);
12466 if (!ast_strlen_zero(mwi->secret)) {
12467 ast_string_field_set(mwi->call, peersecret, mwi->secret);
12468 }
12469 set_socket_transport(&mwi->call->socket, mwi->transport);
12470 mwi->call->socket.port = htons(mwi->portno);
12471 ast_sip_ouraddrfor(&mwi->call->sa, &mwi->call->ourip, mwi->call);
12472 build_contact(mwi->call);
12473 build_via(mwi->call);
12474
12475
12476 change_callid_pvt(mwi->call, NULL);
12477
12478 ast_set_flag(&mwi->call->flags[0], SIP_OUTGOING);
12479
12480
12481 mwi->call->mwi = ASTOBJ_REF(mwi);
12482
12483 mwi->call->subscribed = MWI_NOTIFICATION;
12484
12485
12486 transmit_invite(mwi->call, SIP_SUBSCRIBE, 0, 2, NULL);
12487
12488 return 0;
12489 }
12490
12491
12492 static int find_calling_channel(void *obj, void *arg, void *data, int flags)
12493 {
12494 struct ast_channel *c = obj;
12495 struct sip_pvt *p = data;
12496 int res;
12497
12498 ast_channel_lock(c);
12499
12500 res = (c->pbx &&
12501 (!strcasecmp(c->macroexten, p->exten) || !strcasecmp(c->exten, p->exten)) &&
12502 (sip_cfg.notifycid == IGNORE_CONTEXT || !strcasecmp(c->context, p->context)));
12503
12504 ast_channel_unlock(c);
12505
12506 return res ? CMP_MATCH | CMP_STOP : 0;
12507 }
12508
12509
12510 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)
12511 {
12512 enum state { NOTIFY_OPEN, NOTIFY_INUSE, NOTIFY_CLOSED } local_state = NOTIFY_OPEN;
12513 const char *statestring = "terminated";
12514 const char *pidfstate = "--";
12515 const char *pidfnote= "Ready";
12516 char hint[AST_MAX_EXTENSION];
12517
12518 switch (state) {
12519 case (AST_EXTENSION_RINGING | AST_EXTENSION_INUSE):
12520 statestring = (sip_cfg.notifyringing) ? "early" : "confirmed";
12521 local_state = NOTIFY_INUSE;
12522 pidfstate = "busy";
12523 pidfnote = "Ringing";
12524 break;
12525 case AST_EXTENSION_RINGING:
12526 statestring = "early";
12527 local_state = NOTIFY_INUSE;
12528 pidfstate = "busy";
12529 pidfnote = "Ringing";
12530 break;
12531 case AST_EXTENSION_INUSE:
12532 statestring = "confirmed";
12533 local_state = NOTIFY_INUSE;
12534 pidfstate = "busy";
12535 pidfnote = "On the phone";
12536 break;
12537 case AST_EXTENSION_BUSY:
12538 statestring = "confirmed";
12539 local_state = NOTIFY_CLOSED;
12540 pidfstate = "busy";
12541 pidfnote = "On the phone";
12542 break;
12543 case AST_EXTENSION_UNAVAILABLE:
12544 statestring = "terminated";
12545 local_state = NOTIFY_CLOSED;
12546 pidfstate = "away";
12547 pidfnote = "Unavailable";
12548 break;
12549 case AST_EXTENSION_ONHOLD:
12550 statestring = "confirmed";
12551 local_state = NOTIFY_CLOSED;
12552 pidfstate = "busy";
12553 pidfnote = "On hold";
12554 break;
12555 case AST_EXTENSION_NOT_INUSE:
12556 default:
12557
12558 break;
12559 }
12560
12561
12562 if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, context, exten)) {
12563 char *hint2 = hint, *individual_hint = NULL;
12564 int hint_count = 0, unavailable_count = 0;
12565
12566 while ((individual_hint = strsep(&hint2, "&"))) {
12567 hint_count++;
12568
12569 if (ast_device_state(individual_hint) == AST_DEVICE_UNAVAILABLE)
12570 unavailable_count++;
12571 }
12572
12573
12574
12575
12576 if (hint_count > 0 && hint_count == unavailable_count) {
12577 local_state = NOTIFY_CLOSED;
12578 pidfstate = "away";
12579 pidfnote = "Not online";
12580 }
12581 }
12582
12583 switch (subscribed) {
12584 case XPIDF_XML:
12585 case CPIM_PIDF_XML:
12586 ast_str_append(tmp, 0,
12587 "<?xml version=\"1.0\"?>\n"
12588 "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n"
12589 "<presence>\n");
12590 ast_str_append(tmp, 0, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
12591 ast_str_append(tmp, 0, "<atom id=\"%s\">\n", exten);
12592 ast_str_append(tmp, 0, "<address uri=\"%s;user=ip\" priority=\"0.800000\">\n", mto);
12593 ast_str_append(tmp, 0, "<status status=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "open" : (local_state == NOTIFY_INUSE) ? "inuse" : "closed");
12594 ast_str_append(tmp, 0, "<msnsubstatus substatus=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "online" : (local_state == NOTIFY_INUSE) ? "onthephone" : "offline");
12595 ast_str_append(tmp, 0, "</address>\n</atom>\n</presence>\n");
12596 break;
12597 case PIDF_XML:
12598 ast_str_append(tmp, 0,
12599 "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"
12600 "<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);
12601 ast_str_append(tmp, 0, "<pp:person><status>\n");
12602 if (pidfstate[0] != '-') {
12603 ast_str_append(tmp, 0, "<ep:activities><ep:%s/></ep:activities>\n", pidfstate);
12604 }
12605 ast_str_append(tmp, 0, "</status></pp:person>\n");
12606 ast_str_append(tmp, 0, "<note>%s</note>\n", pidfnote);
12607 ast_str_append(tmp, 0, "<tuple id=\"%s\">\n", exten);
12608 ast_str_append(tmp, 0, "<contact priority=\"1\">%s</contact>\n", mto);
12609 if (pidfstate[0] == 'b')
12610 ast_str_append(tmp, 0, "<status><basic>open</basic></status>\n");
12611 else
12612 ast_str_append(tmp, 0, "<status><basic>%s</basic></status>\n", (local_state != NOTIFY_CLOSED) ? "open" : "closed");
12613 ast_str_append(tmp, 0, "</tuple>\n</presence>\n");
12614 break;
12615 case DIALOG_INFO_XML:
12616 ast_str_append(tmp, 0, "<?xml version=\"1.0\"?>\n");
12617 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);
12618 if ((state & AST_EXTENSION_RINGING) && sip_cfg.notifyringing) {
12619 const char *local_display = exten;
12620 char *local_target = ast_strdupa(mto);
12621
12622
12623
12624
12625 if (sip_cfg.notifycid) {
12626 struct ast_channel *caller;
12627
12628 if ((caller = ast_channel_callback(find_calling_channel, NULL, p, 0))) {
12629 char *cid_num;
12630 int need;
12631
12632 ast_channel_lock(caller);
12633 cid_num = S_COR(caller->caller.id.number.valid,
12634 caller->caller.id.number.str, "");
12635 need = strlen(cid_num) + strlen(p->fromdomain) + sizeof("sip:@");
12636 local_target = alloca(need);
12637 snprintf(local_target, need, "sip:%s@%s", cid_num, p->fromdomain);
12638 local_display = ast_strdupa(S_COR(caller->caller.id.name.valid,
12639 caller->caller.id.name.str, ""));
12640 ast_channel_unlock(caller);
12641 caller = ast_channel_unref(caller);
12642 }
12643
12644
12645
12646 if (sip_cfg.pedanticsipchecking) {
12647 ast_str_append(tmp, 0, "<dialog id=\"%s\" call-id=\"pickup-%s\" local-tag=\"%s\" remote-tag=\"%s\" direction=\"recipient\">\n",
12648 exten, p->callid, p->theirtag, p->tag);
12649 } else {
12650 ast_str_append(tmp, 0, "<dialog id=\"%s\" call-id=\"pickup-%s\" direction=\"recipient\">\n",
12651 exten, p->callid);
12652 }
12653 ast_str_append(tmp, 0,
12654 "<remote>\n"
12655
12656
12657 "<identity display=\"%s\">%s</identity>\n"
12658 "<target uri=\"%s\"/>\n"
12659 "</remote>\n"
12660 "<local>\n"
12661 "<identity>%s</identity>\n"
12662 "<target uri=\"%s\"/>\n"
12663 "</local>\n",
12664 local_display, local_target, local_target, mto, mto);
12665 } else {
12666 ast_str_append(tmp, 0, "<dialog id=\"%s\" direction=\"recipient\">\n", exten);
12667 }
12668
12669 } else {
12670 ast_str_append(tmp, 0, "<dialog id=\"%s\">\n", exten);
12671 }
12672 ast_str_append(tmp, 0, "<state>%s</state>\n", statestring);
12673 if (state == AST_EXTENSION_ONHOLD) {
12674 ast_str_append(tmp, 0, "<local>\n<target uri=\"%s\">\n"
12675 "<param pname=\"+sip.rendering\" pvalue=\"no\"/>\n"
12676 "</target>\n</local>\n", mto);
12677 }
12678 ast_str_append(tmp, 0, "</dialog>\n</dialog-info>\n");
12679 break;
12680 case NONE:
12681 default:
12682 break;
12683 }
12684 }
12685
12686 static int transmit_cc_notify(struct ast_cc_agent *agent, struct sip_pvt *subscription, enum sip_cc_notify_state state)
12687 {
12688 struct sip_request req;
12689 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
12690 char uri[SIPBUFSIZE];
12691 char state_str[64];
12692 char subscription_state_hdr[64];
12693
12694 if (state < CC_QUEUED || state > CC_READY) {
12695 ast_log(LOG_WARNING, "Invalid state provided for transmit_cc_notify (%d)\n", state);
12696 return -1;
12697 }
12698
12699 reqprep(&req, subscription, SIP_NOTIFY, 0, TRUE);
12700 snprintf(state_str, sizeof(state_str), "%s\r\n", sip_cc_notify_state_map[state].state_string);
12701 add_header(&req, "Event", "call-completion");
12702 add_header(&req, "Content-Type", "application/call-completion");
12703 snprintf(subscription_state_hdr, sizeof(subscription_state_hdr), "active;expires=%d", subscription->expiry);
12704 add_header(&req, "Subscription-State", subscription_state_hdr);
12705 if (state == CC_READY) {
12706 generate_uri(subscription, agent_pvt->notify_uri, sizeof(agent_pvt->notify_uri));
12707 snprintf(uri, sizeof(uri) - 1, "cc-URI: %s\r\n", agent_pvt->notify_uri);
12708 }
12709 add_content(&req, state_str);
12710 if (state == CC_READY) {
12711 add_content(&req, uri);
12712 }
12713 return send_request(subscription, &req, XMIT_RELIABLE, subscription->ocseq);
12714 }
12715
12716
12717 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout)
12718 {
12719 struct ast_str *tmp = ast_str_alloca(4000);
12720 char from[256], to[256];
12721 char *c, *mfrom, *mto;
12722 struct sip_request req;
12723 const struct cfsubscription_types *subscriptiontype;
12724
12725 memset(from, 0, sizeof(from));
12726 memset(to, 0, sizeof(to));
12727
12728 subscriptiontype = find_subscription_type(p->subscribed);
12729
12730 ast_copy_string(from, get_header(&p->initreq, "From"), sizeof(from));
12731 c = get_in_brackets(from);
12732 if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
12733 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
12734 return -1;
12735 }
12736
12737 mfrom = remove_uri_parameters(c);
12738
12739 ast_copy_string(to, get_header(&p->initreq, "To"), sizeof(to));
12740 c = get_in_brackets(to);
12741 if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
12742 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
12743 return -1;
12744 }
12745 mto = remove_uri_parameters(c);
12746
12747 reqprep(&req, p, SIP_NOTIFY, 0, 1);
12748
12749 switch(state) {
12750 case AST_EXTENSION_DEACTIVATED:
12751 if (timeout)
12752 add_header(&req, "Subscription-State", "terminated;reason=timeout");
12753 else {
12754 add_header(&req, "Subscription-State", "terminated;reason=probation");
12755 add_header(&req, "Retry-After", "60");
12756 }
12757 break;
12758 case AST_EXTENSION_REMOVED:
12759 add_header(&req, "Subscription-State", "terminated;reason=noresource");
12760 break;
12761 default:
12762 if (p->expiry)
12763 add_header(&req, "Subscription-State", "active");
12764 else
12765 add_header(&req, "Subscription-State", "terminated;reason=timeout");
12766 }
12767
12768 switch (p->subscribed) {
12769 case XPIDF_XML:
12770 case CPIM_PIDF_XML:
12771 add_header(&req, "Event", subscriptiontype->event);
12772 state_notify_build_xml(state, full, p->exten, p->context, &tmp, p, p->subscribed, mfrom, mto);
12773 add_header(&req, "Content-Type", subscriptiontype->mediatype);
12774 p->dialogver++;
12775 break;
12776 case PIDF_XML:
12777 add_header(&req, "Event", subscriptiontype->event);
12778 state_notify_build_xml(state, full, p->exten, p->context, &tmp, p, p->subscribed, mfrom, mto);
12779 add_header(&req, "Content-Type", subscriptiontype->mediatype);
12780 p->dialogver++;
12781 break;
12782 case DIALOG_INFO_XML:
12783 add_header(&req, "Event", subscriptiontype->event);
12784 state_notify_build_xml(state, full, p->exten, p->context, &tmp, p, p->subscribed, mfrom, mto);
12785 add_header(&req, "Content-Type", subscriptiontype->mediatype);
12786 p->dialogver++;
12787 break;
12788 case NONE:
12789 default:
12790 break;
12791 }
12792
12793 add_content(&req, tmp->str);
12794
12795 p->pendinginvite = p->ocseq;
12796
12797 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
12798 }
12799
12800
12801
12802
12803
12804
12805
12806 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten)
12807 {
12808 struct sip_request req;
12809 struct ast_str *out = ast_str_alloca(500);
12810 int ourport = (p->fromdomainport) ? p->fromdomainport : ast_sockaddr_port(&p->ourip);
12811 const char *domain;
12812 const char *exten = S_OR(vmexten, default_vmexten);
12813
12814 initreqprep(&req, p, SIP_NOTIFY, NULL);
12815 add_header(&req, "Event", "message-summary");
12816 add_header(&req, "Content-Type", default_notifymime);
12817 ast_str_append(&out, 0, "Messages-Waiting: %s\r\n", newmsgs ? "yes" : "no");
12818
12819
12820 domain = S_OR(p->fromdomain, ast_sockaddr_stringify_host_remote(&p->ourip));
12821
12822 if (!sip_standard_port(p->socket.type, ourport)) {
12823 if (p->socket.type == SIP_TRANSPORT_UDP) {
12824 ast_str_append(&out, 0, "Message-Account: sip:%s@%s:%d\r\n", exten, domain, ourport);
12825 } else {
12826 ast_str_append(&out, 0, "Message-Account: sip:%s@%s:%d;transport=%s\r\n", exten, domain, ourport, get_transport(p->socket.type));
12827 }
12828 } else {
12829 if (p->socket.type == SIP_TRANSPORT_UDP) {
12830 ast_str_append(&out, 0, "Message-Account: sip:%s@%s\r\n", exten, domain);
12831 } else {
12832 ast_str_append(&out, 0, "Message-Account: sip:%s@%s;transport=%s\r\n", exten, domain, get_transport(p->socket.type));
12833 }
12834 }
12835
12836
12837
12838 ast_str_append(&out, 0, "Voice-Message: %d/%d%s\r\n",
12839 newmsgs, oldmsgs, (ast_test_flag(&p->flags[1], SIP_PAGE2_BUGGY_MWI) ? "" : " (0/0)"));
12840
12841 if (p->subscribed) {
12842 if (p->expiry) {
12843 add_header(&req, "Subscription-State", "active");
12844 } else {
12845 add_header(&req, "Subscription-State", "terminated;reason=timeout");
12846 }
12847 }
12848
12849 add_content(&req, out->str);
12850
12851 if (!p->initreq.headers) {
12852 initialize_initreq(p, &req);
12853 }
12854 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
12855 }
12856
12857
12858 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate)
12859 {
12860 struct sip_request req;
12861 char tmp[SIPBUFSIZE/2];
12862
12863 reqprep(&req, p, SIP_NOTIFY, 0, 1);
12864 snprintf(tmp, sizeof(tmp), "refer;id=%d", cseq);
12865 add_header(&req, "Event", tmp);
12866 add_header(&req, "Subscription-state", terminate ? "terminated;reason=noresource" : "active");
12867 add_header(&req, "Content-Type", "message/sipfrag;version=2.0");
12868 add_header(&req, "Allow", ALLOWED_METHODS);
12869 add_supported_header(p, &req);
12870
12871 snprintf(tmp, sizeof(tmp), "SIP/2.0 %s\r\n", message);
12872 add_content(&req, tmp);
12873
12874 if (!p->initreq.headers) {
12875 initialize_initreq(p, &req);
12876 }
12877
12878 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
12879 }
12880
12881 static int manager_sipnotify(struct mansession *s, const struct message *m)
12882 {
12883 const char *channame = astman_get_header(m, "Channel");
12884 struct ast_variable *vars = astman_get_variables(m);
12885 struct sip_pvt *p;
12886 struct ast_variable *header, *var;
12887
12888 if (ast_strlen_zero(channame)) {
12889 astman_send_error(s, m, "SIPNotify requires a channel name");
12890 return 0;
12891 }
12892
12893 if (!strncasecmp(channame, "sip/", 4)) {
12894 channame += 4;
12895 }
12896
12897 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
12898 astman_send_error(s, m, "Unable to build sip pvt data for notify (memory/socket error)");
12899 return 0;
12900 }
12901
12902 if (create_addr(p, channame, NULL, 0, NULL)) {
12903
12904 dialog_unlink_all(p);
12905 dialog_unref(p, "unref dialog inside for loop" );
12906
12907 astman_send_error(s, m, "Could not create address");
12908 return 0;
12909 }
12910
12911
12912 ast_set_flag(&p->flags[0], SIP_OUTGOING);
12913 sip_notify_allocate(p);
12914
12915 p->notify->headers = header = ast_variable_new("Subscription-State", "terminated", "");
12916
12917 for (var = vars; var; var = var->next) {
12918 if (!strcasecmp(var->name, "Content")) {
12919 if (ast_str_strlen(p->notify->content))
12920 ast_str_append(&p->notify->content, 0, "\r\n");
12921 ast_str_append(&p->notify->content, 0, "%s", var->value);
12922 } else if (!strcasecmp(var->name, "Content-Length")) {
12923 ast_log(LOG_WARNING, "it is not necessary to specify Content-Length, ignoring");
12924 } else {
12925 header->next = ast_variable_new(var->name, var->value, "");
12926 header = header->next;
12927 }
12928 }
12929
12930 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
12931 transmit_invite(p, SIP_NOTIFY, 0, 2, NULL);
12932 dialog_unref(p, "bump down the count of p since we're done with it.");
12933
12934 astman_send_ack(s, m, "Notify Sent");
12935 ast_variables_destroy(vars);
12936 return 0;
12937 }
12938
12939
12940
12941 static void update_redirecting(struct sip_pvt *p, const void *data, size_t datalen)
12942 {
12943 struct sip_request resp;
12944
12945 if (p->owner->_state == AST_STATE_UP || ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
12946 return;
12947 }
12948
12949 respprep(&resp, p, "181 Call is being forwarded", &p->initreq);
12950 add_diversion_header(&resp, p);
12951 send_response(p, &resp, XMIT_UNRELIABLE, 0);
12952 }
12953
12954
12955 static void update_connectedline(struct sip_pvt *p, const void *data, size_t datalen)
12956 {
12957
12958 if (!ast_test_flag(&p->flags[0], SIP_SENDRPID)) {
12959 return;
12960 }
12961 if (!p->owner->connected.id.number.valid
12962 || ast_strlen_zero(p->owner->connected.id.number.str)) {
12963 return;
12964 }
12965
12966 append_history(p, "ConnectedLine", "%s party is now %s <%s>",
12967 ast_test_flag(&p->flags[0], SIP_OUTGOING) ? "Calling" : "Called",
12968 S_COR(p->owner->connected.id.name.valid, p->owner->connected.id.name.str, ""),
12969 S_COR(p->owner->connected.id.number.valid, p->owner->connected.id.number.str, ""));
12970
12971 if (p->owner->_state == AST_STATE_UP || ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
12972 struct sip_request req;
12973
12974 if (!p->pendinginvite && (p->invitestate == INV_CONFIRMED || p->invitestate == INV_TERMINATED)) {
12975 reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ? SIP_UPDATE : SIP_INVITE, 0, 1);
12976
12977 add_header(&req, "Allow", ALLOWED_METHODS);
12978 add_supported_header(p, &req);
12979 add_rpid(&req, p);
12980 add_sdp(&req, p, FALSE, TRUE, FALSE);
12981
12982 initialize_initreq(p, &req);
12983 p->lastinvite = p->ocseq;
12984 ast_set_flag(&p->flags[0], SIP_OUTGOING);
12985 p->invitestate = INV_CALLING;
12986 send_request(p, &req, XMIT_CRITICAL, p->ocseq);
12987 } else if ((is_method_allowed(&p->allowed_methods, SIP_UPDATE)) && (!ast_strlen_zero(p->okcontacturi))) {
12988 reqprep(&req, p, SIP_UPDATE, 0, 1);
12989 add_rpid(&req, p);
12990 add_header(&req, "X-Asterisk-rpid-update", "Yes");
12991 send_request(p, &req, XMIT_CRITICAL, p->ocseq);
12992 } else {
12993
12994 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
12995 }
12996 } else {
12997 ast_set_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND);
12998 if (ast_test_flag(&p->flags[1], SIP_PAGE2_RPID_IMMEDIATE)) {
12999 struct sip_request resp;
13000
13001 if ((p->owner->_state == AST_STATE_RING) && !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT)) {
13002 ast_clear_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND);
13003 respprep(&resp, p, "180 Ringing", &p->initreq);
13004 add_rpid(&resp, p);
13005 send_response(p, &resp, XMIT_UNRELIABLE, 0);
13006 ast_set_flag(&p->flags[0], SIP_RINGING);
13007 } else if (p->owner->_state == AST_STATE_RINGING) {
13008 ast_clear_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND);
13009 respprep(&resp, p, "183 Session Progress", &p->initreq);
13010 add_rpid(&resp, p);
13011 send_response(p, &resp, XMIT_UNRELIABLE, 0);
13012 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
13013 } else {
13014 ast_debug(1, "Unable able to send update to '%s' in state '%s'\n", p->owner->name, ast_state2str(p->owner->_state));
13015 }
13016 }
13017 }
13018 }
13019
13020 static const struct _map_x_s regstatestrings[] = {
13021 { REG_STATE_FAILED, "Failed" },
13022 { REG_STATE_UNREGISTERED, "Unregistered"},
13023 { REG_STATE_REGSENT, "Request Sent"},
13024 { REG_STATE_AUTHSENT, "Auth. Sent"},
13025 { REG_STATE_REGISTERED, "Registered"},
13026 { REG_STATE_REJECTED, "Rejected"},
13027 { REG_STATE_TIMEOUT, "Timeout"},
13028 { REG_STATE_NOAUTH, "No Authentication"},
13029 { -1, NULL }
13030 };
13031
13032
13033 static const char *regstate2str(enum sipregistrystate regstate)
13034 {
13035 return map_x_s(regstatestrings, regstate, "Unknown");
13036 }
13037
13038
13039
13040
13041
13042
13043
13044 static int sip_reregister(const void *data)
13045 {
13046
13047 struct sip_registry *r = (struct sip_registry *) data;
13048
13049
13050 if (!r) {
13051 return 0;
13052 }
13053
13054 if (r->call && r->call->do_history) {
13055 append_history(r->call, "RegistryRenew", "Account: %s@%s", r->username, r->hostname);
13056 }
13057
13058
13059 if (sipdebug) {
13060 ast_log(LOG_NOTICE, " -- Re-registration for %s@%s\n", r->username, r->hostname);
13061 }
13062
13063 r->expire = -1;
13064 r->expiry = r->configured_expiry;
13065 __sip_do_register(r);
13066 registry_unref(r, "unref the re-register scheduled event");
13067 return 0;
13068 }
13069
13070
13071
13072
13073 static int __sip_do_register(struct sip_registry *r)
13074 {
13075 int res;
13076
13077 res = transmit_register(r, SIP_REGISTER, NULL, NULL);
13078 return res;
13079 }
13080
13081
13082
13083
13084
13085
13086
13087 static int sip_reg_timeout(const void *data)
13088 {
13089
13090
13091 struct sip_registry *r = (struct sip_registry *)data;
13092 struct sip_pvt *p;
13093
13094
13095 if (!r) {
13096 return 0;
13097 }
13098
13099 if (r->dnsmgr) {
13100
13101 ast_dnsmgr_refresh(r->dnsmgr);
13102 }
13103
13104
13105
13106
13107
13108 if (r->call) {
13109
13110
13111 p = r->call;
13112 sip_pvt_lock(p);
13113 pvt_set_needdestroy(p, "registration timeout");
13114
13115 __sip_pretend_ack(p);
13116 sip_pvt_unlock(p);
13117
13118
13119
13120 if (p->registry) {
13121 p->registry = registry_unref(p->registry, "p->registry unreffed");
13122 }
13123 r->call = dialog_unref(r->call, "unrefing r->call");
13124 }
13125
13126 r->timeout = -1;
13127 if (global_regattempts_max && r->regattempts >= global_regattempts_max) {
13128
13129
13130
13131 ast_log(LOG_NOTICE, " -- Last Registration Attempt #%d failed, Giving up forever trying to register '%s@%s'\n", r->regattempts, r->username, r->hostname);
13132 r->regstate = REG_STATE_FAILED;
13133 } else {
13134 r->regstate = REG_STATE_UNREGISTERED;
13135 transmit_register(r, SIP_REGISTER, NULL, NULL);
13136 ast_log(LOG_NOTICE, " -- Registration for '%s@%s' timed out, trying again (Attempt #%d)\n", r->username, r->hostname, r->regattempts);
13137 }
13138 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));
13139 registry_unref(r, "unreffing registry_unref r");
13140 return 0;
13141 }
13142
13143 static const char *sip_sanitized_host(const char *host)
13144 {
13145 struct ast_sockaddr addr = { { 0, 0, }, };
13146
13147
13148
13149
13150 if (!ast_sockaddr_parse(&addr, host, PARSE_PORT_FORBID)) {
13151 return host;
13152 }
13153 return ast_sockaddr_stringify_host_remote(&addr);
13154 }
13155
13156
13157
13158
13159 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader)
13160 {
13161 struct sip_request req;
13162 char from[256];
13163 char to[256];
13164 char tmp[80];
13165 char addr[80];
13166 struct sip_pvt *p;
13167 struct sip_peer *peer = NULL;
13168 int res;
13169 int portno = 0;
13170
13171
13172 if (r == NULL || ((auth == NULL) && (r->regstate == REG_STATE_REGSENT || r->regstate == REG_STATE_AUTHSENT))) {
13173 if (r) {
13174 ast_log(LOG_NOTICE, "Strange, trying to register %s@%s when registration already pending\n", r->username, r->hostname);
13175 }
13176 return 0;
13177 }
13178
13179 if (r->dnsmgr == NULL) {
13180 char transport[MAXHOSTNAMELEN];
13181 peer = find_peer(r->hostname, NULL, TRUE, FINDPEERS, FALSE, 0);
13182 snprintf(transport, sizeof(transport), "_%s._%s",get_srv_service(r->transport), get_srv_protocol(r->transport));
13183 r->us.ss.ss_family = get_address_family_filter(&bindaddr);
13184
13185
13186
13187
13188
13189 if (!obproxy_get(r->call, peer)) {
13190 registry_addref(r, "add reg ref for dnsmgr");
13191 ast_dnsmgr_lookup_cb(peer ? peer->tohost : r->hostname, &r->us, &r->dnsmgr, sip_cfg.srvlookup ? transport : NULL, on_dns_update_registry, r);
13192 if (!r->dnsmgr) {
13193
13194 registry_unref(r, "remove reg ref, dnsmgr disabled");
13195 }
13196 }
13197 if (peer) {
13198 peer = unref_peer(peer, "removing peer ref for dnsmgr_lookup");
13199 }
13200 }
13201
13202 if (r->call) {
13203 if (!auth) {
13204 ast_log(LOG_WARNING, "Already have a REGISTER going on to %s@%s?? \n", r->username, r->hostname);
13205 return 0;
13206 } else {
13207 p = dialog_ref(r->call, "getting a copy of the r->call dialog in transmit_register");
13208 make_our_tag(p->tag, sizeof(p->tag));
13209 ast_string_field_set(p, theirtag, NULL);
13210 }
13211 } else {
13212
13213 if (!r->callid_valid) {
13214 build_callid_registry(r, &internip, default_fromdomain);
13215 r->callid_valid = TRUE;
13216 }
13217
13218 if (!(p = sip_alloc( r->callid, NULL, 0, SIP_REGISTER, NULL))) {
13219 ast_log(LOG_WARNING, "Unable to allocate registration transaction (memory or socket error)\n");
13220 return 0;
13221 }
13222
13223 if (p->do_history) {
13224 append_history(p, "RegistryInit", "Account: %s@%s", r->username, r->hostname);
13225 }
13226
13227
13228 if (!ast_sockaddr_isnull(&r->us)) {
13229 if (!ast_sockaddr_port(&r->us) && r->portno) {
13230 ast_sockaddr_set_port(&r->us, r->portno);
13231 }
13232
13233
13234
13235
13236
13237 if ((peer = find_peer(S_OR(r->peername, r->hostname), NULL, TRUE, FINDPEERS, FALSE, 0))) {
13238 if (ast_sockaddr_cmp(&peer->addr, &r->us)) {
13239 on_dns_update_peer(&peer->addr, &r->us, peer);
13240 }
13241 peer = unref_peer(peer, "unref after find_peer");
13242 }
13243 }
13244
13245
13246 if (create_addr(p, S_OR(r->peername, r->hostname), &r->us, 0, NULL)) {
13247
13248
13249 dialog_unlink_all(p);
13250 p = dialog_unref(p, "unref dialog after unlink_all");
13251 if (r->timeout > -1) {
13252 AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
13253 registry_unref(_data, "del for REPLACE of registry ptr"),
13254 registry_unref(r, "object ptr dec when SCHED_REPLACE add failed"),
13255 registry_addref(r,"add for REPLACE registry ptr"));
13256 ast_log(LOG_WARNING, "Still have a registration timeout for %s@%s (create_addr() error), %d\n", r->username, r->hostname, r->timeout);
13257 } else {
13258 r->timeout = ast_sched_add(sched, global_reg_timeout * 1000, sip_reg_timeout, registry_addref(r, "add for REPLACE registry ptr"));
13259 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);
13260 }
13261 r->regattempts++;
13262 return 0;
13263 }
13264
13265
13266 ast_string_field_set(r, callid, p->callid);
13267
13268 if (!r->dnsmgr && r->portno) {
13269 ast_sockaddr_set_port(&p->sa, r->portno);
13270 ast_sockaddr_set_port(&p->recv, r->portno);
13271 }
13272 if (!ast_strlen_zero(p->fromdomain)) {
13273 portno = (p->fromdomainport) ? p->fromdomainport : STANDARD_SIP_PORT;
13274 } else if (!ast_strlen_zero(r->regdomain)) {
13275 portno = (r->regdomainport) ? r->regdomainport : STANDARD_SIP_PORT;
13276 } else {
13277 portno = ast_sockaddr_port(&p->sa);
13278 }
13279
13280 ast_set_flag(&p->flags[0], SIP_OUTGOING);
13281 r->call = dialog_ref(p, "copying dialog into registry r->call");
13282 p->registry = registry_addref(r, "transmit_register: addref to p->registry in transmit_register");
13283 if (!ast_strlen_zero(r->secret)) {
13284 ast_string_field_set(p, peersecret, r->secret);
13285 }
13286 if (!ast_strlen_zero(r->md5secret))
13287 ast_string_field_set(p, peermd5secret, r->md5secret);
13288
13289
13290 if (!ast_strlen_zero(r->authuser)) {
13291 ast_string_field_set(p, peername, r->authuser);
13292 ast_string_field_set(p, authname, r->authuser);
13293 } else if (!ast_strlen_zero(r->username)) {
13294 ast_string_field_set(p, peername, r->username);
13295 ast_string_field_set(p, authname, r->username);
13296 ast_string_field_set(p, fromuser, r->username);
13297 }
13298 if (!ast_strlen_zero(r->username)) {
13299 ast_string_field_set(p, username, r->username);
13300 }
13301
13302 if (!ast_strlen_zero(r->callback)) {
13303 ast_string_field_set(p, exten, r->callback);
13304 }
13305
13306
13307 set_socket_transport(&p->socket, r->transport);
13308 if (r->transport == SIP_TRANSPORT_TLS || r->transport == SIP_TRANSPORT_TCP) {
13309 p->socket.port =
13310 htons(ast_sockaddr_port(&sip_tcp_desc.local_address));
13311 }
13312
13313
13314
13315
13316
13317
13318 ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
13319 build_contact(p);
13320 }
13321
13322
13323 if (auth == NULL) {
13324 if (r->timeout > -1) {
13325 ast_log(LOG_WARNING, "Still have a registration timeout, #%d - deleting it\n", r->timeout);
13326 }
13327 AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
13328 registry_unref(_data,"reg ptr unrefed from del in SCHED_REPLACE"),
13329 registry_unref(r,"reg ptr unrefed from add failure in SCHED_REPLACE"),
13330 registry_addref(r,"reg ptr reffed from add in SCHED_REPLACE"));
13331 ast_debug(1, "Scheduled a registration timeout for %s id #%d \n", r->hostname, r->timeout);
13332 }
13333
13334 snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%s", r->username, S_OR(r->regdomain, sip_sanitized_host(p->tohost)), p->tag);
13335 if (!ast_strlen_zero(p->theirtag)) {
13336 snprintf(to, sizeof(to), "<sip:%s@%s>;tag=%s", r->username, S_OR(r->regdomain, sip_sanitized_host(p->tohost)), p->theirtag);
13337 } else {
13338 snprintf(to, sizeof(to), "<sip:%s@%s>", r->username, S_OR(r->regdomain, sip_sanitized_host(p->tohost)));
13339 }
13340
13341
13342
13343 if (portno && portno != STANDARD_SIP_PORT) {
13344 snprintf(addr, sizeof(addr), "sip:%s:%d", S_OR(p->fromdomain,S_OR(r->regdomain, sip_sanitized_host(r->hostname))), portno);
13345 } else {
13346 snprintf(addr, sizeof(addr), "sip:%s", S_OR(p->fromdomain,S_OR(r->regdomain, sip_sanitized_host(r->hostname))));
13347 }
13348
13349 ast_string_field_set(p, uri, addr);
13350
13351 p->branch ^= ast_random();
13352
13353 init_req(&req, sipmethod, addr);
13354
13355
13356 snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, sip_methods[sipmethod].text);
13357 p->ocseq = r->ocseq;
13358
13359 build_via(p);
13360 add_header(&req, "Via", p->via);
13361 add_header_max_forwards(p, &req);
13362 add_header(&req, "From", from);
13363 add_header(&req, "To", to);
13364 add_header(&req, "Call-ID", p->callid);
13365 add_header(&req, "CSeq", tmp);
13366 if (!ast_strlen_zero(global_useragent))
13367 add_header(&req, "User-Agent", global_useragent);
13368
13369 if (auth) {
13370 add_header(&req, authheader, auth);
13371 } else if (!ast_strlen_zero(r->nonce)) {
13372 char digest[1024];
13373
13374
13375
13376
13377
13378
13379 if (sipdebug) {
13380 ast_debug(1, " >>> Re-using Auth data for %s@%s\n", r->username, r->hostname);
13381 }
13382 ast_string_field_set(p, realm, r->realm);
13383 ast_string_field_set(p, nonce, r->nonce);
13384 ast_string_field_set(p, domain, r->authdomain);
13385 ast_string_field_set(p, opaque, r->opaque);
13386 ast_string_field_set(p, qop, r->qop);
13387 p->noncecount = ++r->noncecount;
13388
13389 memset(digest, 0, sizeof(digest));
13390 if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
13391 add_header(&req, "Authorization", digest);
13392 } else {
13393 ast_log(LOG_NOTICE, "No authorization available for authentication of registration to %s@%s\n", r->username, r->hostname);
13394 }
13395 }
13396
13397 snprintf(tmp, sizeof(tmp), "%d", r->expiry);
13398 add_header(&req, "Expires", tmp);
13399 add_header(&req, "Contact", p->our_contact);
13400
13401 initialize_initreq(p, &req);
13402 if (sip_debug_test_pvt(p)) {
13403 ast_verbose("REGISTER %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
13404 }
13405 r->regstate = auth ? REG_STATE_AUTHSENT : REG_STATE_REGSENT;
13406 r->regattempts++;
13407 ast_debug(4, "REGISTER attempt %d to %s@%s\n", r->regattempts, r->username, r->hostname);
13408 res = send_request(p, &req, XMIT_CRITICAL, p->ocseq);
13409 dialog_unref(p, "p is finished here at the end of transmit_register");
13410 return res;
13411 }
13412
13413
13414 static int transmit_message_with_text(struct sip_pvt *p, const char *text)
13415 {
13416 struct sip_request req;
13417
13418 reqprep(&req, p, SIP_MESSAGE, 0, 1);
13419 add_text(&req, text);
13420 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
13421 }
13422
13423
13424 static int sip_refer_allocate(struct sip_pvt *p)
13425 {
13426 p->refer = ast_calloc(1, sizeof(struct sip_refer));
13427 return p->refer ? 1 : 0;
13428 }
13429
13430
13431 static int sip_notify_allocate(struct sip_pvt *p)
13432 {
13433 p->notify = ast_calloc(1, sizeof(struct sip_notify));
13434 if (p->notify) {
13435 p->notify->content = ast_str_create(128);
13436 }
13437 return p->notify ? 1 : 0;
13438 }
13439
13440
13441
13442
13443
13444
13445 static int transmit_refer(struct sip_pvt *p, const char *dest)
13446 {
13447 struct sip_request req = {
13448 .headers = 0,
13449 };
13450 char from[256];
13451 const char *of;
13452 char *c;
13453 char referto[256];
13454 int use_tls=FALSE;
13455
13456 if (sipdebug) {
13457 ast_debug(1, "SIP transfer of %s to %s\n", p->callid, dest);
13458 }
13459
13460
13461 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
13462 of = get_header(&p->initreq, "To");
13463 } else {
13464 of = get_header(&p->initreq, "From");
13465 }
13466
13467 ast_copy_string(from, of, sizeof(from));
13468 of = get_in_brackets(from);
13469 ast_string_field_set(p, from, of);
13470 if (!strncasecmp(of, "sip:", 4)) {
13471 of += 4;
13472 } else if (!strncasecmp(of, "sips:", 5)) {
13473 of += 5;
13474 use_tls = TRUE;
13475 } else {
13476 ast_log(LOG_NOTICE, "From address missing 'sip(s):', assuming sip:\n");
13477 }
13478
13479 if ((c = strchr(dest, '@'))) {
13480 c = NULL;
13481 } else if ((c = strchr(of, '@'))) {
13482 *c++ = '\0';
13483 }
13484 if (c) {
13485 snprintf(referto, sizeof(referto), "<sip%s:%s@%s>", use_tls ? "s" : "", dest, c);
13486 } else {
13487 snprintf(referto, sizeof(referto), "<sip%s:%s>", use_tls ? "s" : "", dest);
13488 }
13489
13490
13491 sip_refer_allocate(p);
13492 ast_copy_string(p->refer->refer_to, referto, sizeof(p->refer->refer_to));
13493 ast_copy_string(p->refer->referred_by, p->our_contact, sizeof(p->refer->referred_by));
13494 p->refer->status = REFER_SENT;
13495
13496 reqprep(&req, p, SIP_REFER, 0, 1);
13497
13498 add_header(&req, "Refer-To", referto);
13499 add_header(&req, "Allow", ALLOWED_METHODS);
13500 add_supported_header(p, &req);
13501 if (!ast_strlen_zero(p->our_contact)) {
13502 add_header(&req, "Referred-By", p->our_contact);
13503 }
13504
13505 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515 }
13516
13517
13518 static int transmit_info_with_aoc(struct sip_pvt *p, struct ast_aoc_decoded *decoded)
13519 {
13520 struct sip_request req;
13521 struct ast_str *str = ast_str_alloca(512);
13522 const struct ast_aoc_unit_entry *unit_entry = ast_aoc_get_unit_info(decoded, 0);
13523 enum ast_aoc_charge_type charging = ast_aoc_get_charge_type(decoded);
13524
13525 reqprep(&req, p, SIP_INFO, 0, 1);
13526
13527 if (ast_aoc_get_msg_type(decoded) == AST_AOC_D) {
13528 ast_str_append(&str, 0, "type=active;");
13529 } else if (ast_aoc_get_msg_type(decoded) == AST_AOC_E) {
13530 ast_str_append(&str, 0, "type=terminated;");
13531 } else {
13532
13533 return -1;
13534 }
13535
13536 switch (charging) {
13537 case AST_AOC_CHARGE_FREE:
13538 ast_str_append(&str, 0, "free-of-charge;");
13539 break;
13540 case AST_AOC_CHARGE_CURRENCY:
13541 ast_str_append(&str, 0, "charging;");
13542 ast_str_append(&str, 0, "charging-info=currency;");
13543 ast_str_append(&str, 0, "amount=%u;", ast_aoc_get_currency_amount(decoded));
13544 ast_str_append(&str, 0, "multiplier=%s;", ast_aoc_get_currency_multiplier_decimal(decoded));
13545 if (!ast_strlen_zero(ast_aoc_get_currency_name(decoded))) {
13546 ast_str_append(&str, 0, "currency=%s;", ast_aoc_get_currency_name(decoded));
13547 }
13548 break;
13549 case AST_AOC_CHARGE_UNIT:
13550 ast_str_append(&str, 0, "charging;");
13551 ast_str_append(&str, 0, "charging-info=pulse;");
13552 if (unit_entry) {
13553 ast_str_append(&str, 0, "recorded-units=%u;", unit_entry->amount);
13554 }
13555 break;
13556 default:
13557 ast_str_append(&str, 0, "not-available;");
13558 };
13559
13560 add_header(&req, "AOC", ast_str_buffer(str));
13561
13562 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
13563 }
13564
13565
13566 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration)
13567 {
13568 struct sip_request req;
13569
13570 reqprep(&req, p, SIP_INFO, 0, 1);
13571 add_digit(&req, digit, duration, (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_SHORTINFO));
13572 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
13573 }
13574
13575
13576 static int transmit_info_with_vidupdate(struct sip_pvt *p)
13577 {
13578 struct sip_request req;
13579
13580 reqprep(&req, p, SIP_INFO, 0, 1);
13581 add_vidupdate(&req);
13582 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
13583 }
13584
13585
13586
13587
13588 static int transmit_request(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch)
13589 {
13590 struct sip_request resp;
13591
13592 reqprep(&resp, p, sipmethod, seqno, newbranch);
13593 if (sipmethod == SIP_CANCEL && p->answered_elsewhere) {
13594 add_header(&resp, "Reason", "SIP;cause=200;text=\"Call completed elsewhere\"");
13595 }
13596
13597 if (sipmethod == SIP_ACK) {
13598 p->invitestate = INV_CONFIRMED;
13599 }
13600
13601 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
13602 }
13603
13604
13605 static void auth_headers(enum sip_auth_type code, char **header, char **respheader)
13606 {
13607 if (code == WWW_AUTH) {
13608 *header = "WWW-Authenticate";
13609 *respheader = "Authorization";
13610 } else if (code == PROXY_AUTH) {
13611 *header = "Proxy-Authenticate";
13612 *respheader = "Proxy-Authorization";
13613 } else {
13614 ast_verbose("-- wrong response code %d\n", code);
13615 *header = *respheader = "Invalid";
13616 }
13617 }
13618
13619
13620 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch)
13621 {
13622 struct sip_request resp;
13623
13624 reqprep(&resp, p, sipmethod, seqno, newbranch);
13625 if (!ast_strlen_zero(p->realm)) {
13626 char digest[1024];
13627
13628 memset(digest, 0, sizeof(digest));
13629 if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
13630 char *dummy, *response;
13631 enum sip_auth_type code = p->options ? p->options->auth_type : PROXY_AUTH;
13632 auth_headers(code, &dummy, &response);
13633 add_header(&resp, response, digest);
13634 } else {
13635 ast_log(LOG_WARNING, "No authentication available for call %s\n", p->callid);
13636 }
13637 }
13638
13639
13640 if (sipmethod == SIP_BYE) {
13641 char buf[20];
13642
13643 if (ast_test_flag(&p->flags[1], SIP_PAGE2_Q850_REASON) && p->hangupcause) {
13644 sprintf(buf, "Q.850;cause=%i", p->hangupcause & 0x7f);
13645 add_header(&resp, "Reason", buf);
13646 }
13647
13648 add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->hangupcause));
13649 snprintf(buf, sizeof(buf), "%d", p->hangupcause);
13650 add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
13651 }
13652
13653 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
13654 }
13655
13656
13657 static void destroy_association(struct sip_peer *peer)
13658 {
13659 int realtimeregs = ast_check_realtime("sipregs");
13660 char *tablename = (realtimeregs) ? "sipregs" : "sippeers";
13661
13662 if (!sip_cfg.ignore_regexpire) {
13663 if (peer->rt_fromcontact && sip_cfg.peer_rtupdate) {
13664 ast_update_realtime(tablename, "name", peer->name, "fullcontact", "", "ipaddr", "", "port", "", "regseconds", "0", "regserver", "", "useragent", "", "lastms", "0", SENTINEL);
13665 } else {
13666 ast_db_del("SIP/Registry", peer->name);
13667 ast_db_del("SIP/PeerMethods", peer->name);
13668 }
13669 }
13670 }
13671
13672 static void set_socket_transport(struct sip_socket *socket, int transport)
13673 {
13674
13675 if (socket->type != transport) {
13676 socket->fd = -1;
13677 socket->type = transport;
13678 if (socket->tcptls_session) {
13679 ao2_ref(socket->tcptls_session, -1);
13680 socket->tcptls_session = NULL;
13681 }
13682 }
13683 }
13684
13685
13686 static int expire_register(const void *data)
13687 {
13688 struct sip_peer *peer = (struct sip_peer *)data;
13689
13690 if (!peer) {
13691 return 0;
13692 }
13693
13694 peer->expire = -1;
13695 peer->portinuri = 0;
13696
13697 destroy_association(peer);
13698 set_socket_transport(&peer->socket, peer->default_outbound_transport);
13699
13700 if (peer->socket.tcptls_session) {
13701 ao2_ref(peer->socket.tcptls_session, -1);
13702 peer->socket.tcptls_session = NULL;
13703 }
13704
13705 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
13706 register_peer_exten(peer, FALSE);
13707 ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
13708
13709
13710
13711
13712 if (peer->is_realtime) {
13713 ast_debug(3, "-REALTIME- peer expired registration. Name: %s. Realtime peer objects now %d\n", peer->name, rpeerobjs);
13714 }
13715
13716 if (peer->selfdestruct ||
13717 ast_test_flag(&peer->flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
13718 unlink_peer_from_tables(peer);
13719 } else if (!ast_sockaddr_isnull(&peer->addr)) {
13720
13721
13722
13723 ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
13724 }
13725
13726
13727
13728 memset(&peer->addr, 0, sizeof(peer->addr));
13729
13730 unref_peer(peer, "removing peer ref for expire_register");
13731
13732 return 0;
13733 }
13734
13735
13736 static int sip_poke_peer_s(const void *data)
13737 {
13738 struct sip_peer *peer = (struct sip_peer *)data;
13739 struct sip_peer *foundpeer;
13740
13741 peer->pokeexpire = -1;
13742
13743 foundpeer = ao2_find(peers, peer, OBJ_POINTER);
13744 if (!foundpeer) {
13745 unref_peer(peer, "removing poke peer ref");
13746 return 0;
13747 } else if (foundpeer->name != peer->name) {
13748 unref_peer(foundpeer, "removing above peer ref");
13749 unref_peer(peer, "removing poke peer ref");
13750 return 0;
13751 }
13752
13753 unref_peer(foundpeer, "removing above peer ref");
13754 sip_poke_peer(peer, 0);
13755 unref_peer(peer, "removing poke peer ref");
13756
13757 return 0;
13758 }
13759
13760
13761 static void reg_source_db(struct sip_peer *peer)
13762 {
13763 char data[256];
13764 struct ast_sockaddr sa;
13765 int expire;
13766 char full_addr[128];
13767 AST_DECLARE_APP_ARGS(args,
13768 AST_APP_ARG(addr);
13769 AST_APP_ARG(port);
13770 AST_APP_ARG(expiry_str);
13771 AST_APP_ARG(username);
13772 AST_APP_ARG(contact);
13773 );
13774
13775
13776 if (peer->rt_fromcontact && sip_cfg.peer_rtupdate) {
13777 return;
13778 }
13779 if (ast_db_get("SIP/Registry", peer->name, data, sizeof(data))) {
13780 return;
13781 }
13782
13783 AST_NONSTANDARD_RAW_ARGS(args, data, ':');
13784
13785 snprintf(full_addr, sizeof(full_addr), "%s:%s", args.addr, args.port);
13786
13787 if (!ast_sockaddr_parse(&sa, full_addr, 0)) {
13788 return;
13789 }
13790
13791 if (args.expiry_str) {
13792 expire = atoi(args.expiry_str);
13793 } else {
13794 return;
13795 }
13796
13797 if (args.username) {
13798 ast_string_field_set(peer, username, args.username);
13799 }
13800 if (args.contact) {
13801 ast_string_field_set(peer, fullcontact, args.contact);
13802 }
13803
13804 ast_debug(2, "SIP Seeding peer from astdb: '%s' at %s@%s for %d\n",
13805 peer->name, peer->username, ast_sockaddr_stringify_host(&sa), expire);
13806
13807 ast_sockaddr_copy(&peer->addr, &sa);
13808 if (sipsock < 0) {
13809
13810 AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, ast_random() % 5000 + 1, sip_poke_peer_s, peer,
13811 unref_peer(_data, "removing poke peer ref"),
13812 unref_peer(peer, "removing poke peer ref"),
13813 ref_peer(peer, "adding poke peer ref"));
13814 } else {
13815 sip_poke_peer(peer, 0);
13816 }
13817 AST_SCHED_REPLACE_UNREF(peer->expire, sched, (expire + 10) * 1000, expire_register, peer,
13818 unref_peer(_data, "remove registration ref"),
13819 unref_peer(peer, "remove registration ref"),
13820 ref_peer(peer, "add registration ref"));
13821 register_peer_exten(peer, TRUE);
13822 }
13823
13824
13825 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req)
13826 {
13827 char contact[SIPBUFSIZE];
13828 char *c;
13829
13830
13831 ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
13832 c = get_in_brackets(contact);
13833
13834
13835 ast_string_field_set(pvt, fullcontact, c);
13836
13837
13838 ast_string_field_set(pvt, okcontacturi, c);
13839
13840
13841
13842 return TRUE;
13843 }
13844
13845
13846
13847
13848
13849
13850
13851 static int parse_uri_legacy_check(char *uri, const char *scheme, char **user, char **pass, char **hostport, char **transport)
13852 {
13853 int ret = parse_uri(uri, scheme, user, pass, hostport, transport);
13854 if (sip_cfg.legacy_useroption_parsing) {
13855 char *p;
13856 if ((p = strchr(uri, (int)';'))) {
13857 *p = '\0';
13858 }
13859 }
13860 return ret;
13861 }
13862
13863 static int __set_address_from_contact(const char *fullcontact, struct ast_sockaddr *addr, int tcp)
13864 {
13865 char *hostport, *transport;
13866 char contact_buf[256];
13867 char *contact;
13868
13869
13870 ast_copy_string(contact_buf, fullcontact, sizeof(contact_buf));
13871 contact = contact_buf;
13872
13873
13874
13875
13876
13877
13878
13879
13880 if (parse_uri_legacy_check(contact, "sip:,sips:", &contact, NULL, &hostport,
13881 &transport)) {
13882 ast_log(LOG_WARNING, "Invalid contact uri %s (missing sip: or sips:), attempting to use anyway\n", fullcontact);
13883 }
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894 if (ast_strlen_zero(hostport)) {
13895 ast_log(LOG_WARNING, "Invalid URI: parse_uri failed to acquire hostport\n");
13896 return -1;
13897 }
13898
13899 if (ast_sockaddr_resolve_first(addr, hostport, 0)) {
13900 ast_log(LOG_WARNING, "Invalid host name in Contact: (can't "
13901 "resolve in DNS) : '%s'\n", hostport);
13902 return -1;
13903 }
13904
13905
13906 if (!ast_sockaddr_port(addr)) {
13907 ast_sockaddr_set_port(addr,
13908 (get_transport_str2enum(transport) ==
13909 SIP_TRANSPORT_TLS ||
13910 !strncasecmp(fullcontact, "sips", 4)) ?
13911 STANDARD_TLS_PORT : STANDARD_SIP_PORT);
13912 }
13913
13914 return 0;
13915 }
13916
13917
13918 static int set_address_from_contact(struct sip_pvt *pvt)
13919 {
13920 if (ast_test_flag(&pvt->flags[0], SIP_NAT_FORCE_RPORT)) {
13921
13922
13923
13924 pvt->sa = pvt->recv;
13925 return 0;
13926 }
13927
13928 return __set_address_from_contact(pvt->fullcontact, &pvt->sa, pvt->socket.type == SIP_TRANSPORT_TLS ? 1 : 0);
13929 }
13930
13931
13932 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *peer, struct sip_request *req)
13933 {
13934 char contact[SIPBUFSIZE];
13935 char data[SIPBUFSIZE];
13936 const char *expires = get_header(req, "Expires");
13937 int expire = atoi(expires);
13938 char *curi = NULL, *hostport = NULL, *transport = NULL;
13939 int transport_type;
13940 const char *useragent;
13941 struct ast_sockaddr oldsin, testsa;
13942 char *firstcuri = NULL;
13943 int start = 0;
13944 int wildcard_found = 0;
13945 int single_binding_found = 0;
13946
13947 ast_copy_string(contact, __get_header(req, "Contact", &start), sizeof(contact));
13948
13949 if (ast_strlen_zero(expires)) {
13950 char *s = strcasestr(contact, ";expires=");
13951 if (s) {
13952 expires = strsep(&s, ";");
13953 if (sscanf(expires + 9, "%30d", &expire) != 1) {
13954 expire = default_expiry;
13955 }
13956 } else {
13957
13958 expire = default_expiry;
13959 }
13960 }
13961
13962 copy_socket_data(&pvt->socket, &req->socket);
13963
13964 do {
13965
13966 curi = contact;
13967 if (strchr(contact, '<') == NULL)
13968 strsep(&curi, ";");
13969 curi = get_in_brackets(contact);
13970 if (!firstcuri) {
13971 firstcuri = ast_strdupa(curi);
13972 }
13973
13974 if (!strcasecmp(curi, "*")) {
13975 wildcard_found = 1;
13976 } else {
13977 single_binding_found = 1;
13978 }
13979
13980 if (wildcard_found && (ast_strlen_zero(expires) || expire != 0 || single_binding_found)) {
13981
13982
13983 return PARSE_REGISTER_FAILED;
13984 }
13985
13986 ast_copy_string(contact, __get_header(req, "Contact", &start), sizeof(contact));
13987 } while (!ast_strlen_zero(contact));
13988 curi = firstcuri;
13989
13990
13991
13992
13993
13994 if (ast_strlen_zero(curi) && ast_strlen_zero(expires)) {
13995
13996 if (peer->expire > -1 && !ast_strlen_zero(peer->fullcontact)) {
13997 pvt->expiry = ast_sched_when(sched, peer->expire);
13998 }
13999 return PARSE_REGISTER_QUERY;
14000 } else if (!strcasecmp(curi, "*") || !expire) {
14001
14002 AST_SCHED_DEL_UNREF(sched, peer->expire,
14003 unref_peer(peer, "remove register expire ref"));
14004 ast_verb(3, "Unregistered SIP '%s'\n", peer->name);
14005 expire_register(ref_peer(peer,"add ref for explicit expire_register"));
14006 return PARSE_REGISTER_UPDATE;
14007 }
14008
14009
14010 ast_string_field_set(peer, fullcontact, curi);
14011
14012
14013 ast_string_field_build(pvt, our_contact, "<%s>", curi);
14014
14015
14016 if (ast_strlen_zero(curi) || parse_uri_legacy_check(curi, "sip:,sips:", &curi, NULL, &hostport, &transport)) {
14017 ast_log(LOG_NOTICE, "Not a valid SIP contact (missing sip:/sips:) trying to use anyway\n");
14018 }
14019
14020
14021 if (!(transport_type = get_transport_str2enum(transport))) {
14022 transport_type = pvt->socket.type;
14023 }
14024
14025
14026
14027
14028 if ((peer->socket.type != transport_type) && (peer->transports & transport_type)) {
14029 set_socket_transport(&peer->socket, transport_type);
14030 }
14031
14032 oldsin = peer->addr;
14033
14034
14035 if (!ast_sockaddr_isnull(&peer->addr) && (!peer->is_realtime || ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS))) {
14036 ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
14037 }
14038
14039 if (!ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) && !ast_test_flag(&peer->flags[0], SIP_NAT_RPORT_PRESENT)) {
14040
14041 ast_debug(1, "Store REGISTER's Contact header for call routing.\n");
14042
14043
14044 if (ast_sockaddr_resolve_first(&testsa, hostport, 0)) {
14045 ast_log(LOG_WARNING, "Invalid hostport '%s'\n", hostport);
14046 ast_string_field_set(peer, fullcontact, "");
14047 ast_string_field_set(pvt, our_contact, "");
14048 return PARSE_REGISTER_FAILED;
14049 }
14050
14051
14052
14053 peer->portinuri = ast_sockaddr_port(&testsa) ? TRUE : FALSE;
14054
14055 if (!ast_sockaddr_port(&testsa)) {
14056 ast_sockaddr_set_port(&testsa, default_sip_port(transport_type));
14057 }
14058
14059 ast_sockaddr_copy(&peer->addr, &testsa);
14060 } else {
14061
14062
14063 ast_debug(1, "Store REGISTER's src-IP:port for call routing.\n");
14064 peer->addr = pvt->recv;
14065 }
14066
14067
14068 if (ast_apply_ha(sip_cfg.contact_ha, &peer->addr) != AST_SENSE_ALLOW ||
14069 ast_apply_ha(peer->contactha, &peer->addr) != AST_SENSE_ALLOW) {
14070 ast_log(LOG_WARNING, "Domain '%s' disallowed by contact ACL (violating IP %s)\n", hostport,
14071 ast_sockaddr_stringify_addr(&testsa));
14072 ast_string_field_set(peer, fullcontact, "");
14073 ast_string_field_set(pvt, our_contact, "");
14074 return PARSE_REGISTER_DENIED;
14075 }
14076
14077
14078
14079
14080 if ((peer->socket.type == pvt->socket.type) &&
14081 !ast_sockaddr_cmp(&peer->addr, &pvt->recv)) {
14082 copy_socket_data(&peer->socket, &pvt->socket);
14083 }
14084
14085
14086 if (!peer->is_realtime || ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
14087 ao2_t_link(peers_by_ip, peer, "ao2_link into peers_by_ip table");
14088 }
14089
14090
14091 peer->sipoptions = pvt->sipoptions;
14092
14093 if (!ast_strlen_zero(curi) && ast_strlen_zero(peer->username)) {
14094 ast_string_field_set(peer, username, curi);
14095 }
14096
14097 AST_SCHED_DEL_UNREF(sched, peer->expire,
14098 unref_peer(peer, "remove register expire ref"));
14099
14100 if (expire > max_expiry) {
14101 expire = max_expiry;
14102 }
14103 if (expire < min_expiry) {
14104 expire = min_expiry;
14105 }
14106 if (peer->is_realtime && !ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
14107 peer->expire = -1;
14108 } else {
14109 peer->expire = ast_sched_add(sched, (expire + 10) * 1000, expire_register,
14110 ref_peer(peer, "add registration ref"));
14111 if (peer->expire == -1) {
14112 unref_peer(peer, "remote registration ref");
14113 }
14114 }
14115 pvt->expiry = expire;
14116 snprintf(data, sizeof(data), "%s:%d:%s:%s", ast_sockaddr_stringify(&peer->addr),
14117 expire, peer->username, peer->fullcontact);
14118
14119 if (!peer->rt_fromcontact || !sip_cfg.peer_rtupdate)
14120 ast_db_put("SIP/Registry", peer->name, data);
14121 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));
14122
14123
14124 if (VERBOSITY_ATLEAST(2) && ast_sockaddr_cmp(&peer->addr, &oldsin)) {
14125 ast_verbose(VERBOSE_PREFIX_3 "Registered SIP '%s' at %s\n", peer->name,
14126 ast_sockaddr_stringify(&peer->addr));
14127 }
14128 sip_poke_peer(peer, 0);
14129 register_peer_exten(peer, 1);
14130
14131
14132 useragent = get_header(req, "User-Agent");
14133 if (strcasecmp(useragent, peer->useragent)) {
14134 ast_string_field_set(peer, useragent, useragent);
14135 ast_verb(4, "Saved useragent \"%s\" for peer %s\n", peer->useragent, peer->name);
14136 }
14137 return PARSE_REGISTER_UPDATE;
14138 }
14139
14140
14141 static void free_old_route(struct sip_route *route)
14142 {
14143 struct sip_route *next;
14144
14145 while (route) {
14146 next = route->next;
14147 ast_free(route);
14148 route = next;
14149 }
14150 }
14151
14152
14153 static void list_route(struct sip_route *route)
14154 {
14155 if (!route) {
14156 ast_verbose("list_route: no route\n");
14157 } else {
14158 for (;route; route = route->next)
14159 ast_verbose("list_route: hop: <%s>\n", route->hop);
14160 }
14161 }
14162
14163
14164
14165 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards, int resp)
14166 {
14167 struct sip_route *thishop, *head, *tail;
14168 int start = 0;
14169 int len;
14170 const char *rr, *c;
14171
14172
14173 if (p->route && p->route_persistent) {
14174 ast_debug(1, "build_route: Retaining previous route: <%s>\n", p->route->hop);
14175 return;
14176 }
14177
14178 if (p->route) {
14179 free_old_route(p->route);
14180 p->route = NULL;
14181 }
14182
14183
14184
14185 if ((resp < 100) || (resp > 199)) {
14186 p->route_persistent = 1;
14187 }
14188
14189
14190
14191
14192
14193
14194 head = NULL;
14195 tail = head;
14196
14197 for (;;) {
14198
14199 char rr_copy[256];
14200 char *rr_copy_ptr;
14201 char *rr_iter;
14202 rr = __get_header(req, "Record-Route", &start);
14203 if (*rr == '\0') {
14204 break;
14205 }
14206 ast_copy_string(rr_copy, rr, sizeof(rr_copy));
14207 rr_copy_ptr = rr_copy;
14208 while ((rr_iter = strsep(&rr_copy_ptr, ","))) {
14209 char *uri = get_in_brackets(rr_iter);
14210 len = strlen(uri) + 1;
14211
14212 if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
14213
14214 ast_copy_string(thishop->hop, uri, len);
14215 ast_debug(2, "build_route: Record-Route hop: <%s>\n", thishop->hop);
14216
14217 if (backwards) {
14218
14219 thishop->next = head;
14220 head = thishop;
14221
14222 if (!tail) {
14223 tail = thishop;
14224 }
14225 } else {
14226 thishop->next = NULL;
14227
14228 if (tail) {
14229 tail->next = thishop;
14230 } else {
14231 head = thishop;
14232 }
14233 tail = thishop;
14234 }
14235 }
14236 }
14237 }
14238
14239
14240 if (!head || (!ast_strlen_zero(head->hop) && strstr(head->hop, ";lr") == NULL) ) {
14241
14242
14243 char *contact = ast_strdupa(get_header(req, "Contact"));
14244 if (!ast_strlen_zero(contact)) {
14245 ast_debug(2, "build_route: Contact hop: %s\n", contact);
14246
14247 c = get_in_brackets(contact);
14248 len = strlen(c) + 1;
14249 if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
14250
14251 ast_copy_string(thishop->hop, c, len);
14252 thishop->next = NULL;
14253
14254 if (tail) {
14255 tail->next = thishop;
14256 } else {
14257 head = thishop;
14258 }
14259 }
14260 }
14261 }
14262
14263
14264 p->route = head;
14265
14266
14267 if (sip_debug_test_pvt(p)) {
14268 list_route(p->route);
14269 }
14270 }
14271
14272
14273
14274
14275
14276
14277
14278 static void set_nonce_randdata(struct sip_pvt *p, int forceupdate)
14279 {
14280 if (p->stalenonce || forceupdate || ast_strlen_zero(p->randdata)) {
14281 ast_string_field_build(p, randdata, "%08lx", ast_random());
14282 p->stalenonce = 0;
14283 }
14284 }
14285
14286 AST_THREADSTORAGE(check_auth_buf);
14287 #define CHECK_AUTH_BUF_INITLEN 256
14288
14289
14290
14291
14292
14293
14294 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
14295 const char *secret, const char *md5secret, int sipmethod,
14296 const char *uri, enum xmittype reliable, int ignore)
14297 {
14298 const char *response;
14299 char *reqheader, *respheader;
14300 const char *authtoken;
14301 char a1_hash[256];
14302 char resp_hash[256]="";
14303 char *c;
14304 int wrongnonce = FALSE;
14305 int good_response;
14306 const char *usednonce = p->randdata;
14307 struct ast_str *buf;
14308 int res;
14309
14310
14311 enum keys { K_RESP, K_URI, K_USER, K_NONCE, K_LAST };
14312 struct x {
14313 const char *key;
14314 const char *s;
14315 } *i, keys[] = {
14316 [K_RESP] = { "response=", "" },
14317 [K_URI] = { "uri=", "" },
14318 [K_USER] = { "username=", "" },
14319 [K_NONCE] = { "nonce=", "" },
14320 [K_LAST] = { NULL, NULL}
14321 };
14322
14323
14324 if (ast_strlen_zero(secret) && ast_strlen_zero(md5secret))
14325 return AUTH_SUCCESSFUL;
14326
14327
14328
14329 response = "401 Unauthorized";
14330
14331
14332
14333
14334
14335 auth_headers(WWW_AUTH, &respheader, &reqheader);
14336
14337 authtoken = get_header(req, reqheader);
14338 if (ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
14339
14340
14341 if (!reliable) {
14342
14343
14344 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
14345
14346 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14347 }
14348 return AUTH_CHALLENGE_SENT;
14349 } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
14350
14351 set_nonce_randdata(p, 1);
14352 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
14353
14354 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14355 return AUTH_CHALLENGE_SENT;
14356 }
14357
14358
14359
14360
14361
14362
14363 if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN))) {
14364 return AUTH_SECRET_FAILED;
14365 }
14366
14367
14368 res = ast_str_set(&buf, 0, "%s", authtoken);
14369
14370 if (res == AST_DYNSTR_BUILD_FAILED) {
14371 return AUTH_SECRET_FAILED;
14372 }
14373
14374 c = buf->str;
14375
14376 while(c && *(c = ast_skip_blanks(c)) ) {
14377 for (i = keys; i->key != NULL; i++) {
14378 const char *separator = ",";
14379
14380 if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
14381 continue;
14382 }
14383
14384 c += strlen(i->key);
14385 if (*c == '"') {
14386 c++;
14387 separator = "\"";
14388 }
14389 i->s = c;
14390 strsep(&c, separator);
14391 break;
14392 }
14393 if (i->key == NULL) {
14394 strsep(&c, " ,");
14395 }
14396 }
14397
14398
14399 if (strcmp(username, keys[K_USER].s)) {
14400 ast_log(LOG_WARNING, "username mismatch, have <%s>, digest has <%s>\n",
14401 username, keys[K_USER].s);
14402
14403 return AUTH_USERNAME_MISMATCH;
14404 }
14405
14406
14407
14408 if (strcasecmp(p->randdata, keys[K_NONCE].s) || p->stalenonce) {
14409 wrongnonce = TRUE;
14410 usednonce = keys[K_NONCE].s;
14411 } else {
14412 p->stalenonce = 1;
14413 }
14414
14415 if (!ast_strlen_zero(md5secret)) {
14416 ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
14417 } else {
14418 char a1[256];
14419
14420 snprintf(a1, sizeof(a1), "%s:%s:%s", username, p->realm, secret);
14421 ast_md5_hash(a1_hash, a1);
14422 }
14423
14424
14425 {
14426 char a2[256];
14427 char a2_hash[256];
14428 char resp[256];
14429
14430 snprintf(a2, sizeof(a2), "%s:%s", sip_methods[sipmethod].text,
14431 S_OR(keys[K_URI].s, uri));
14432 ast_md5_hash(a2_hash, a2);
14433 snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, usednonce, a2_hash);
14434 ast_md5_hash(resp_hash, resp);
14435 }
14436
14437 good_response = keys[K_RESP].s &&
14438 !strncasecmp(keys[K_RESP].s, resp_hash, strlen(resp_hash));
14439 if (wrongnonce) {
14440 if (good_response) {
14441 if (sipdebug)
14442 ast_log(LOG_NOTICE, "Correct auth, but based on stale nonce received from '%s'\n", get_header(req, "From"));
14443
14444 set_nonce_randdata(p, 0);
14445 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, TRUE);
14446 } else {
14447
14448 if (!req->ignore) {
14449 if (sipdebug) {
14450 ast_log(LOG_NOTICE, "Bad authentication received from '%s'\n", get_header(req, "To"));
14451 }
14452 set_nonce_randdata(p, 1);
14453 } else {
14454 if (sipdebug) {
14455 ast_log(LOG_NOTICE, "Duplicate authentication received from '%s'\n", get_header(req, "To"));
14456 }
14457 }
14458 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
14459 }
14460
14461
14462 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14463 return AUTH_CHALLENGE_SENT;
14464 }
14465 if (good_response) {
14466 append_history(p, "AuthOK", "Auth challenge successful for %s", username);
14467 return AUTH_SUCCESSFUL;
14468 }
14469
14470
14471
14472
14473
14474
14475 return AUTH_SECRET_FAILED;
14476 }
14477
14478
14479 static void sip_peer_hold(struct sip_pvt *p, int hold)
14480 {
14481 if (!p->relatedpeer) {
14482 return;
14483 }
14484
14485
14486 ast_atomic_fetchadd_int(&p->relatedpeer->onHold, (hold ? +1 : -1));
14487
14488
14489 ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", p->relatedpeer->name);
14490
14491 return;
14492 }
14493
14494
14495 static void mwi_event_cb(const struct ast_event *event, void *userdata)
14496 {
14497 struct sip_peer *peer = userdata;
14498
14499 sip_send_mwi_to_peer(peer, 0);
14500 }
14501
14502 static void network_change_event_subscribe(void)
14503 {
14504 if (!network_change_event_subscription) {
14505 network_change_event_subscription = ast_event_subscribe(AST_EVENT_NETWORK_CHANGE,
14506 network_change_event_cb, "SIP Network Change", NULL, AST_EVENT_IE_END);
14507 }
14508 }
14509
14510 static void network_change_event_unsubscribe(void)
14511 {
14512 if (network_change_event_subscription) {
14513 network_change_event_subscription = ast_event_unsubscribe(network_change_event_subscription);
14514 }
14515 }
14516
14517 static int network_change_event_sched_cb(const void *data)
14518 {
14519 network_change_event_sched_id = -1;
14520 sip_send_all_registers();
14521 sip_send_all_mwi_subscriptions();
14522 return 0;
14523 }
14524
14525 static void network_change_event_cb(const struct ast_event *event, void *userdata)
14526 {
14527 ast_debug(1, "SIP, got a network change event, renewing all SIP registrations.\n");
14528 if (network_change_event_sched_id == -1) {
14529 network_change_event_sched_id = ast_sched_add(sched, 1000, network_change_event_sched_cb, NULL);
14530 }
14531 }
14532
14533 static void cb_extensionstate_destroy(int id, void *data)
14534 {
14535 struct sip_pvt *p = data;
14536
14537 dialog_unref(p, "the extensionstate containing this dialog ptr was destroyed");
14538 }
14539
14540
14541
14542
14543 static int cb_extensionstate(char *context, char* exten, int state, void *data)
14544 {
14545 struct sip_pvt *p = data;
14546
14547 sip_pvt_lock(p);
14548
14549 switch(state) {
14550 case AST_EXTENSION_DEACTIVATED:
14551 case AST_EXTENSION_REMOVED:
14552 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14553 ast_verb(2, "Extension state: Watcher for hint %s %s. Notify User %s\n", exten, state == AST_EXTENSION_DEACTIVATED ? "deactivated" : "removed", p->username);
14554 p->subscribed = NONE;
14555 append_history(p, "Subscribestatus", "%s", state == AST_EXTENSION_REMOVED ? "HintRemoved" : "Deactivated");
14556 break;
14557 default:
14558 p->laststate = state;
14559 break;
14560 }
14561 if (p->subscribed != NONE) {
14562 if (!p->pendinginvite) {
14563 transmit_state_notify(p, state, 1, FALSE);
14564 } else {
14565
14566
14567 ast_set_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
14568 }
14569 }
14570 ast_verb(2, "Extension Changed %s[%s] new state %s for Notify User %s %s\n", exten, context, ast_extension_state2str(state), p->username,
14571 ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE) ? "(queued)" : "");
14572
14573 sip_pvt_unlock(p);
14574
14575 return 0;
14576 }
14577
14578
14579
14580
14581 static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable)
14582 {
14583
14584
14585 const char *response = "401 Unauthorized";
14586 const char *reqheader = "Authorization";
14587 const char *respheader = "WWW-Authenticate";
14588 const char *authtoken;
14589 struct ast_str *buf;
14590 char *c;
14591
14592
14593 enum keys { K_NONCE, K_LAST };
14594 struct x {
14595 const char *key;
14596 const char *s;
14597 } *i, keys[] = {
14598 [K_NONCE] = { "nonce=", "" },
14599 [K_LAST] = { NULL, NULL}
14600 };
14601
14602 authtoken = get_header(req, reqheader);
14603 if (req->ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
14604
14605
14606 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
14607
14608 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14609 return;
14610 } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
14611
14612 set_nonce_randdata(p, 1);
14613 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
14614
14615 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14616 return;
14617 }
14618
14619 if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN))) {
14620 transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
14621 return;
14622 }
14623
14624
14625 if (ast_str_set(&buf, 0, "%s", authtoken) == AST_DYNSTR_BUILD_FAILED) {
14626 transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
14627 return;
14628 }
14629
14630 c = buf->str;
14631
14632 while (c && *(c = ast_skip_blanks(c))) {
14633 for (i = keys; i->key != NULL; i++) {
14634 const char *separator = ",";
14635
14636 if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
14637 continue;
14638 }
14639
14640 c += strlen(i->key);
14641 if (*c == '"') {
14642 c++;
14643 separator = "\"";
14644 }
14645 i->s = c;
14646 strsep(&c, separator);
14647 break;
14648 }
14649 if (i->key == NULL) {
14650 strsep(&c, " ,");
14651 }
14652 }
14653
14654
14655 if (strcasecmp(p->randdata, keys[K_NONCE].s)) {
14656 if (!req->ignore) {
14657 set_nonce_randdata(p, 1);
14658 }
14659 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
14660
14661
14662 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14663 } else {
14664 transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
14665 }
14666 }
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682 static char *terminate_uri(char *uri)
14683 {
14684 char *t = uri;
14685 while (*t && *t > ' ' && *t != ';') {
14686 t++;
14687 }
14688 *t = '\0';
14689 return uri;
14690 }
14691
14692
14693
14694
14695
14696
14697
14698 static void extract_host_from_hostport(char **hostport)
14699 {
14700 char *dont_care;
14701 ast_sockaddr_split_hostport(*hostport, hostport, &dont_care, PARSE_PORT_IGNORE);
14702 }
14703
14704
14705
14706
14707
14708
14709 static enum check_auth_result register_verify(struct sip_pvt *p, struct ast_sockaddr *addr,
14710 struct sip_request *req, const char *uri)
14711 {
14712 enum check_auth_result res = AUTH_NOT_FOUND;
14713 struct sip_peer *peer;
14714 char tmp[256];
14715 char *c, *name, *unused_password, *domain;
14716 char *uri2 = ast_strdupa(uri);
14717
14718 terminate_uri(uri2);
14719
14720 ast_copy_string(tmp, get_header(req, "To"), sizeof(tmp));
14721
14722 c = get_in_brackets(tmp);
14723 c = remove_uri_parameters(c);
14724
14725 if (parse_uri_legacy_check(c, "sip:,sips:", &name, &unused_password, &domain, NULL)) {
14726 ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, ast_sockaddr_stringify_addr(addr));
14727 return -1;
14728 }
14729
14730 SIP_PEDANTIC_DECODE(name);
14731 SIP_PEDANTIC_DECODE(domain);
14732
14733 extract_host_from_hostport(&domain);
14734
14735 if (ast_strlen_zero(domain)) {
14736
14737 transmit_response(p, "404 Not found", &p->initreq);
14738 return AUTH_UNKNOWN_DOMAIN;
14739 }
14740
14741 if (ast_strlen_zero(name)) {
14742
14743
14744
14745
14746
14747
14748
14749 name = domain;
14750 }
14751
14752
14753
14754
14755
14756 if (!AST_LIST_EMPTY(&domain_list)) {
14757 if (!check_sip_domain(domain, NULL, 0)) {
14758 if (sip_cfg.alwaysauthreject) {
14759 transmit_fake_auth_response(p, SIP_REGISTER, &p->initreq, XMIT_UNRELIABLE);
14760 } else {
14761 transmit_response(p, "404 Not found (unknown domain)", &p->initreq);
14762 }
14763 return AUTH_UNKNOWN_DOMAIN;
14764 }
14765 }
14766
14767 ast_string_field_set(p, exten, name);
14768 build_contact(p);
14769 if (req->ignore) {
14770
14771 const char *expires = get_header(req, "Expires");
14772 int expire = atoi(expires);
14773
14774 if (ast_strlen_zero(expires)) {
14775 if ((expires = strcasestr(get_header(req, "Contact"), ";expires="))) {
14776 expire = atoi(expires + 9);
14777 }
14778 }
14779 if (!ast_strlen_zero(expires) && expire == 0) {
14780 transmit_response_with_date(p, "200 OK", req);
14781 return 0;
14782 }
14783 }
14784 peer = find_peer(name, NULL, TRUE, FINDPEERS, FALSE, 0);
14785
14786 if (!(peer && ast_apply_ha(peer->ha, addr))) {
14787
14788 if (peer) {
14789 unref_peer(peer, "register_verify: unref_peer: from find_peer operation");
14790 peer = NULL;
14791 res = AUTH_ACL_FAILED;
14792 } else {
14793 res = AUTH_NOT_FOUND;
14794 }
14795 }
14796
14797 if (peer) {
14798 ao2_lock(peer);
14799 if (!peer->host_dynamic) {
14800 ast_log(LOG_ERROR, "Peer '%s' is trying to register, but not configured as host=dynamic\n", peer->name);
14801 res = AUTH_PEER_NOT_DYNAMIC;
14802 } else {
14803 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_NAT_FORCE_RPORT);
14804 if (!(res = check_auth(p, req, peer->name, peer->secret, peer->md5secret, SIP_REGISTER, uri2, XMIT_UNRELIABLE, req->ignore))) {
14805 if (sip_cancel_destroy(p))
14806 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
14807
14808 if (check_request_transport(peer, req)) {
14809 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
14810 transmit_response_with_date(p, "403 Forbidden", req);
14811 res = AUTH_BAD_TRANSPORT;
14812 } else {
14813
14814
14815
14816 switch (parse_register_contact(p, peer, req)) {
14817 case PARSE_REGISTER_DENIED:
14818 ast_log(LOG_WARNING, "Registration denied because of contact ACL\n");
14819 transmit_response_with_date(p, "603 Denied", req);
14820 peer->lastmsgssent = -1;
14821 res = 0;
14822 break;
14823 case PARSE_REGISTER_FAILED:
14824 ast_log(LOG_WARNING, "Failed to parse contact info\n");
14825 transmit_response_with_date(p, "400 Bad Request", req);
14826 peer->lastmsgssent = -1;
14827 res = 0;
14828 break;
14829 case PARSE_REGISTER_QUERY:
14830 ast_string_field_set(p, fullcontact, peer->fullcontact);
14831 transmit_response_with_date(p, "200 OK", req);
14832 peer->lastmsgssent = -1;
14833 res = 0;
14834 break;
14835 case PARSE_REGISTER_UPDATE:
14836 ast_string_field_set(p, fullcontact, peer->fullcontact);
14837 update_peer(peer, p->expiry);
14838
14839 transmit_response_with_date(p, "200 OK", req);
14840 if (!ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY))
14841 peer->lastmsgssent = -1;
14842 res = 0;
14843 break;
14844 }
14845 }
14846
14847 }
14848 }
14849 ao2_unlock(peer);
14850 }
14851 if (!peer && sip_cfg.autocreatepeer) {
14852
14853 peer = temp_peer(name);
14854 if (peer) {
14855 ao2_t_link(peers, peer, "link peer into peer table");
14856 if (!ast_sockaddr_isnull(&peer->addr)) {
14857 ao2_t_link(peers_by_ip, peer, "link peer into peers-by-ip table");
14858 }
14859 ao2_lock(peer);
14860 if (sip_cancel_destroy(p))
14861 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
14862 switch (parse_register_contact(p, peer, req)) {
14863 case PARSE_REGISTER_DENIED:
14864 ast_log(LOG_WARNING, "Registration denied because of contact ACL\n");
14865 transmit_response_with_date(p, "403 Forbidden (ACL)", req);
14866 peer->lastmsgssent = -1;
14867 res = 0;
14868 break;
14869 case PARSE_REGISTER_FAILED:
14870 ast_log(LOG_WARNING, "Failed to parse contact info\n");
14871 transmit_response_with_date(p, "400 Bad Request", req);
14872 peer->lastmsgssent = -1;
14873 res = 0;
14874 break;
14875 case PARSE_REGISTER_QUERY:
14876 ast_string_field_set(p, fullcontact, peer->fullcontact);
14877 transmit_response_with_date(p, "200 OK", req);
14878 peer->lastmsgssent = -1;
14879 res = 0;
14880 break;
14881 case PARSE_REGISTER_UPDATE:
14882 ast_string_field_set(p, fullcontact, peer->fullcontact);
14883
14884 transmit_response_with_date(p, "200 OK", req);
14885 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));
14886 peer->lastmsgssent = -1;
14887 res = 0;
14888 break;
14889 }
14890 ao2_unlock(peer);
14891 }
14892 }
14893 if (!res) {
14894 ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
14895 }
14896 if (res < 0) {
14897 switch (res) {
14898 case AUTH_SECRET_FAILED:
14899
14900 transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
14901 if (global_authfailureevents) {
14902 const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
14903 const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
14904 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
14905 "ChannelType: SIP\r\n"
14906 "Peer: SIP/%s\r\n"
14907 "PeerStatus: Rejected\r\n"
14908 "Cause: AUTH_SECRET_FAILED\r\n"
14909 "Address: %s\r\n"
14910 "Port: %s\r\n",
14911 name, peer_addr, peer_port);
14912 }
14913 break;
14914 case AUTH_USERNAME_MISMATCH:
14915
14916
14917
14918
14919 case AUTH_NOT_FOUND:
14920 case AUTH_PEER_NOT_DYNAMIC:
14921 case AUTH_ACL_FAILED:
14922 if (sip_cfg.alwaysauthreject) {
14923 transmit_fake_auth_response(p, SIP_REGISTER, &p->initreq, XMIT_UNRELIABLE);
14924 if (global_authfailureevents) {
14925 const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
14926 const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
14927 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
14928 "ChannelType: SIP\r\n"
14929 "Peer: SIP/%s\r\n"
14930 "PeerStatus: Rejected\r\n"
14931 "Cause: %s\r\n"
14932 "Address: %s\r\n"
14933 "Port: %s\r\n",
14934 name,
14935 res == AUTH_PEER_NOT_DYNAMIC ? "AUTH_PEER_NOT_DYNAMIC" : "URI_NOT_FOUND",
14936 peer_addr, peer_port);
14937 }
14938 } else {
14939
14940 if (res == AUTH_PEER_NOT_DYNAMIC) {
14941 transmit_response(p, "403 Forbidden", &p->initreq);
14942 if (global_authfailureevents) {
14943 const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
14944 const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
14945 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
14946 "ChannelType: SIP\r\n"
14947 "Peer: SIP/%s\r\n"
14948 "PeerStatus: Rejected\r\n"
14949 "Cause: AUTH_PEER_NOT_DYNAMIC\r\n"
14950 "Address: %s\r\n"
14951 "Port: %s\r\n",
14952 name, peer_addr, peer_port);
14953 }
14954 } else {
14955 transmit_response(p, "404 Not found", &p->initreq);
14956 if (global_authfailureevents) {
14957 const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
14958 const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
14959 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
14960 "ChannelType: SIP\r\n"
14961 "Peer: SIP/%s\r\n"
14962 "PeerStatus: Rejected\r\n"
14963 "Cause: %s\r\n"
14964 "Address: %s\r\n"
14965 "Port: %s\r\n",
14966 name,
14967 (res == AUTH_USERNAME_MISMATCH) ? "AUTH_USERNAME_MISMATCH" : "URI_NOT_FOUND",
14968 peer_addr, peer_port);
14969 }
14970 }
14971 }
14972 break;
14973 case AUTH_BAD_TRANSPORT:
14974 default:
14975 break;
14976 }
14977 }
14978 if (peer) {
14979 unref_peer(peer, "register_verify: unref_peer: tossing stack peer pointer at end of func");
14980 }
14981
14982 return res;
14983 }
14984
14985
14986 static void sip_set_redirstr(struct sip_pvt *p, char *reason) {
14987
14988 if (!strcmp(reason, "unknown")) {
14989 ast_string_field_set(p, redircause, "UNKNOWN");
14990 } else if (!strcmp(reason, "user-busy")) {
14991 ast_string_field_set(p, redircause, "BUSY");
14992 } else if (!strcmp(reason, "no-answer")) {
14993 ast_string_field_set(p, redircause, "NOANSWER");
14994 } else if (!strcmp(reason, "unavailable")) {
14995 ast_string_field_set(p, redircause, "UNREACHABLE");
14996 } else if (!strcmp(reason, "unconditional")) {
14997 ast_string_field_set(p, redircause, "UNCONDITIONAL");
14998 } else if (!strcmp(reason, "time-of-day")) {
14999 ast_string_field_set(p, redircause, "UNKNOWN");
15000 } else if (!strcmp(reason, "do-not-disturb")) {
15001 ast_string_field_set(p, redircause, "UNKNOWN");
15002 } else if (!strcmp(reason, "deflection")) {
15003 ast_string_field_set(p, redircause, "UNKNOWN");
15004 } else if (!strcmp(reason, "follow-me")) {
15005 ast_string_field_set(p, redircause, "UNKNOWN");
15006 } else if (!strcmp(reason, "out-of-service")) {
15007 ast_string_field_set(p, redircause, "UNREACHABLE");
15008 } else if (!strcmp(reason, "away")) {
15009 ast_string_field_set(p, redircause, "UNREACHABLE");
15010 } else {
15011 ast_string_field_set(p, redircause, "UNKNOWN");
15012 }
15013 }
15014
15015
15016
15017
15018
15019 static int get_pai(struct sip_pvt *p, struct sip_request *req)
15020 {
15021 char pai[256];
15022 char privacy[64];
15023 char *cid_num = NULL;
15024 char *cid_name = NULL;
15025 char emptyname[1] = "";
15026 int callingpres = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
15027 char *uri = NULL;
15028 int is_anonymous = 0, do_update = 1, no_name = 0;
15029
15030 ast_copy_string(pai, get_header(req, "P-Asserted-Identity"), sizeof(pai));
15031
15032 if (ast_strlen_zero(pai)) {
15033 return 0;
15034 }
15035
15036
15037 if (get_name_and_number(pai, &cid_name, &cid_num)) {
15038 return 0;
15039 }
15040
15041 if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(cid_num)) {
15042 ast_shrink_phone_number(cid_num);
15043 }
15044
15045 uri = get_in_brackets(pai);
15046 if (!strncasecmp(uri, "sip:anonymous@anonymous.invalid", 31)) {
15047 callingpres = AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
15048
15049
15050
15051 ast_free(cid_num);
15052 is_anonymous = 1;
15053 cid_num = (char *)p->cid_num;
15054 }
15055
15056 ast_copy_string(privacy, get_header(req, "Privacy"), sizeof(privacy));
15057 if (!ast_strlen_zero(privacy) && !strncmp(privacy, "id", 2)) {
15058 callingpres = AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
15059 }
15060 if (!cid_name) {
15061 no_name = 1;
15062 cid_name = (char *)emptyname;
15063 }
15064
15065 if (!strcasecmp(p->cid_num, cid_num) && !strcasecmp(p->cid_name, cid_name) && p->callingpres == callingpres) {
15066 do_update = 0;
15067 } else {
15068
15069 ast_string_field_set(p, cid_num, cid_num);
15070 ast_string_field_set(p, cid_name, cid_name);
15071 p->callingpres = callingpres;
15072
15073 if (p->owner) {
15074 ast_set_callerid(p->owner, cid_num, cid_name, NULL);
15075 p->owner->caller.id.name.presentation = callingpres;
15076 p->owner->caller.id.number.presentation = callingpres;
15077 }
15078 }
15079
15080
15081 if (!is_anonymous) {
15082 ast_free(cid_num);
15083 }
15084 if (!no_name) {
15085 ast_free(cid_name);
15086 }
15087
15088 return do_update;
15089 }
15090
15091
15092
15093
15094
15095 static int get_rpid(struct sip_pvt *p, struct sip_request *oreq)
15096 {
15097 char tmp[256];
15098 struct sip_request *req;
15099 char *cid_num = "";
15100 char *cid_name = "";
15101 int callingpres = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
15102 char *privacy = "";
15103 char *screen = "";
15104 char *start, *end;
15105
15106 if (!ast_test_flag(&p->flags[0], SIP_TRUSTRPID))
15107 return 0;
15108 req = oreq;
15109 if (!req)
15110 req = &p->initreq;
15111 ast_copy_string(tmp, get_header(req, "Remote-Party-ID"), sizeof(tmp));
15112 if (ast_strlen_zero(tmp)) {
15113 return get_pai(p, req);
15114 }
15115
15116 start = tmp;
15117 if (*start == '"') {
15118 *start++ = '\0';
15119 end = strchr(start, '"');
15120 if (!end)
15121 return 0;
15122 *end++ = '\0';
15123 cid_name = start;
15124 start = ast_skip_blanks(end);
15125 }
15126
15127 if (*start != '<')
15128 return 0;
15129 *start++ = '\0';
15130 end = strchr(start, '@');
15131 if (!end)
15132 return 0;
15133 *end++ = '\0';
15134 if (strncasecmp(start, "sip:", 4))
15135 return 0;
15136 cid_num = start + 4;
15137 if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(cid_num))
15138 ast_shrink_phone_number(cid_num);
15139 start = end;
15140
15141 end = strchr(start, '>');
15142 if (!end)
15143 return 0;
15144 *end++ = '\0';
15145 if (*end) {
15146 start = end;
15147 if (*start != ';')
15148 return 0;
15149 *start++ = '\0';
15150 while (!ast_strlen_zero(start)) {
15151 end = strchr(start, ';');
15152 if (end)
15153 *end++ = '\0';
15154 if (!strncasecmp(start, "privacy=", 8))
15155 privacy = start + 8;
15156 else if (!strncasecmp(start, "screen=", 7))
15157 screen = start + 7;
15158 start = end;
15159 }
15160
15161 if (!strcasecmp(privacy, "full")) {
15162 if (!strcasecmp(screen, "yes"))
15163 callingpres = AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN;
15164 else if (!strcasecmp(screen, "no"))
15165 callingpres = AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
15166 } else {
15167 if (!strcasecmp(screen, "yes"))
15168 callingpres = AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN;
15169 else if (!strcasecmp(screen, "no"))
15170 callingpres = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
15171 }
15172 }
15173
15174
15175 if (!strcasecmp(p->cid_num, cid_num) && !strcasecmp(p->cid_name, cid_name) && p->callingpres == callingpres)
15176 return 0;
15177
15178 ast_string_field_set(p, cid_num, cid_num);
15179 ast_string_field_set(p, cid_name, cid_name);
15180 p->callingpres = callingpres;
15181
15182 if (p->owner) {
15183 ast_set_callerid(p->owner, cid_num, cid_name, NULL);
15184 p->owner->caller.id.name.presentation = callingpres;
15185 p->owner->caller.id.number.presentation = callingpres;
15186 }
15187
15188 return 1;
15189 }
15190
15191
15192 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq, char **name, char **number, int *reason)
15193 {
15194 char tmp[256], *exten, *rexten, *rdomain, *rname = NULL;
15195 char *params, *reason_param = NULL;
15196 struct sip_request *req;
15197
15198 req = oreq ? oreq : &p->initreq;
15199
15200 ast_copy_string(tmp, get_header(req, "Diversion"), sizeof(tmp));
15201 if (ast_strlen_zero(tmp))
15202 return -1;
15203
15204 if ((params = strchr(tmp, '>'))) {
15205 params = strchr(params, ';');
15206 }
15207
15208 exten = get_in_brackets(tmp);
15209 if (!strncasecmp(exten, "sip:", 4)) {
15210 exten += 4;
15211 } else if (!strncasecmp(exten, "sips:", 5)) {
15212 exten += 5;
15213 } else {
15214 ast_log(LOG_WARNING, "Huh? Not an RDNIS SIP header (%s)?\n", exten);
15215 return -1;
15216 }
15217
15218
15219 if (params) {
15220 *params = '\0';
15221 params++;
15222 while (*params == ';' || *params == ' ')
15223 params++;
15224
15225 if ((reason_param = strcasestr(params, "reason="))) {
15226 char *end;
15227 reason_param+=7;
15228 if ((end = strchr(reason_param, ';'))) {
15229 *end = '\0';
15230 }
15231
15232 if (*reason_param == '"')
15233 ast_strip_quoted(reason_param, "\"", "\"");
15234 if (!ast_strlen_zero(reason_param)) {
15235 sip_set_redirstr(p, reason_param);
15236 if (p->owner) {
15237 pbx_builtin_setvar_helper(p->owner, "__PRIREDIRECTREASON", p->redircause);
15238 pbx_builtin_setvar_helper(p->owner, "__SIPREDIRECTREASON", reason_param);
15239 }
15240 }
15241 }
15242 }
15243
15244 rdomain = exten;
15245 rexten = strsep(&rdomain, "@");
15246 if (p->owner)
15247 pbx_builtin_setvar_helper(p->owner, "__SIPRDNISDOMAIN", rdomain);
15248
15249 if (sip_debug_test_pvt(p))
15250 ast_verbose("RDNIS for this call is %s (reason %s)\n", exten, reason ? reason_param : "");
15251
15252
15253
15254 if (*tmp == '\"') {
15255 char *end_quote;
15256 rname = tmp + 1;
15257 end_quote = strchr(rname, '\"');
15258 *end_quote = '\0';
15259 }
15260
15261 if (number) {
15262 *number = ast_strdup(rexten);
15263 }
15264
15265 if (name && rname) {
15266 *name = ast_strdup(rname);
15267 }
15268
15269 if (reason && !ast_strlen_zero(reason_param)) {
15270 *reason = sip_reason_str_to_code(reason_param);
15271 }
15272
15273 return 0;
15274 }
15275
15276
15277
15278
15279
15280
15281
15282
15283
15284
15285
15286
15287
15288
15289
15290 static enum sip_get_dest_result get_destination(struct sip_pvt *p, struct sip_request *oreq, int *cc_recall_core_id)
15291 {
15292 char tmp[256] = "", *uri, *unused_password, *domain;
15293 char tmpf[256] = "", *from = NULL;
15294 struct sip_request *req;
15295 char *decoded_uri;
15296
15297 req = oreq;
15298 if (!req) {
15299 req = &p->initreq;
15300 }
15301
15302
15303 if (req->rlPart2)
15304 ast_copy_string(tmp, REQ_OFFSET_TO_STR(req, rlPart2), sizeof(tmp));
15305
15306 uri = ast_strdupa(get_in_brackets(tmp));
15307
15308 if (parse_uri_legacy_check(uri, "sip:,sips:", &uri, &unused_password, &domain, NULL)) {
15309 ast_log(LOG_WARNING, "Not a SIP header (%s)?\n", uri);
15310 return SIP_GET_DEST_INVALID_URI;
15311 }
15312
15313 SIP_PEDANTIC_DECODE(domain);
15314 SIP_PEDANTIC_DECODE(uri);
15315
15316 extract_host_from_hostport(&domain);
15317
15318 if (ast_strlen_zero(uri)) {
15319
15320
15321
15322
15323
15324 uri = "s";
15325 }
15326
15327 ast_string_field_set(p, domain, domain);
15328
15329
15330
15331
15332
15333 ast_copy_string(tmpf, get_header(req, "From"), sizeof(tmpf));
15334 if (!ast_strlen_zero(tmpf)) {
15335 from = get_in_brackets(tmpf);
15336 if (parse_uri_legacy_check(from, "sip:,sips:", &from, NULL, &domain, NULL)) {
15337 ast_log(LOG_WARNING, "Not a SIP header (%s)?\n", from);
15338 return SIP_GET_DEST_INVALID_URI;
15339 }
15340
15341 SIP_PEDANTIC_DECODE(from);
15342 SIP_PEDANTIC_DECODE(domain);
15343
15344 extract_host_from_hostport(&domain);
15345
15346 ast_string_field_set(p, fromdomain, domain);
15347 }
15348
15349 if (!AST_LIST_EMPTY(&domain_list)) {
15350 char domain_context[AST_MAX_EXTENSION];
15351
15352 domain_context[0] = '\0';
15353 if (!check_sip_domain(p->domain, domain_context, sizeof(domain_context))) {
15354 if (!sip_cfg.allow_external_domains && (req->method == SIP_INVITE || req->method == SIP_REFER)) {
15355 ast_debug(1, "Got SIP %s to non-local domain '%s'; refusing request.\n", sip_methods[req->method].text, p->domain);
15356 return SIP_GET_DEST_REFUSED;
15357 }
15358 }
15359
15360
15361 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_HAVEPEERCONTEXT) && !ast_strlen_zero(domain_context)) {
15362 ast_string_field_set(p, context, domain_context);
15363 }
15364 }
15365
15366
15367 if (req->method == SIP_SUBSCRIBE && !ast_strlen_zero(p->subscribecontext)) {
15368 ast_string_field_set(p, context, p->subscribecontext);
15369 }
15370
15371 if (sip_debug_test_pvt(p)) {
15372 ast_verbose("Looking for %s in %s (domain %s)\n", uri, p->context, p->domain);
15373 }
15374
15375
15376
15377 decoded_uri = ast_strdupa(uri);
15378 ast_uri_decode(decoded_uri);
15379
15380
15381 if (req->method == SIP_SUBSCRIBE) {
15382 char hint[AST_MAX_EXTENSION];
15383 int which = 0;
15384 if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, uri) ||
15385 (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, decoded_uri) && (which = 1))) {
15386 if (!oreq) {
15387 ast_string_field_set(p, exten, which ? decoded_uri : uri);
15388 }
15389 return SIP_GET_DEST_EXTEN_FOUND;
15390 } else {
15391 return SIP_GET_DEST_EXTEN_NOT_FOUND;
15392 }
15393 } else {
15394 struct ast_cc_agent *agent;
15395
15396
15397
15398 if (ast_exists_extension(NULL, p->context, uri, 1, S_OR(p->cid_num, from))) {
15399 if (!oreq) {
15400 ast_string_field_set(p, exten, uri);
15401 }
15402 return SIP_GET_DEST_EXTEN_FOUND;
15403 }
15404 if (ast_exists_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from))
15405 || !strcmp(decoded_uri, ast_pickup_ext())) {
15406 if (!oreq) {
15407 ast_string_field_set(p, exten, decoded_uri);
15408 }
15409 return SIP_GET_DEST_EXTEN_FOUND;
15410 }
15411 if ((agent = find_sip_cc_agent_by_notify_uri(tmp))) {
15412 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
15413
15414
15415
15416 ast_string_field_set(p, exten, agent_pvt->original_exten);
15417
15418
15419
15420 ast_cc_agent_recalling(agent->core_id, "SIP caller %s is attempting recall",
15421 agent->device_name);
15422 if (cc_recall_core_id) {
15423 *cc_recall_core_id = agent->core_id;
15424 }
15425 ao2_ref(agent, -1);
15426 return SIP_GET_DEST_EXTEN_FOUND;
15427 }
15428 }
15429
15430 if (ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP)
15431 && (ast_canmatch_extension(NULL, p->context, uri, 1, S_OR(p->cid_num, from))
15432 || ast_canmatch_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from))
15433 || !strncmp(decoded_uri, ast_pickup_ext(), strlen(decoded_uri)))) {
15434
15435 return SIP_GET_DEST_EXTEN_MATCHMORE;
15436 }
15437
15438 return SIP_GET_DEST_EXTEN_NOT_FOUND;
15439 }
15440
15441
15442
15443
15444 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag)
15445 {
15446 struct sip_pvt *sip_pvt_ptr;
15447 struct sip_pvt tmp_dialog = {
15448 .callid = callid,
15449 };
15450
15451 if (totag) {
15452 ast_debug(4, "Looking for callid %s (fromtag %s totag %s)\n", callid, fromtag ? fromtag : "<no fromtag>", totag ? totag : "<no totag>");
15453 }
15454
15455
15456
15457 sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find of dialog in dialogs table");
15458 if (sip_pvt_ptr) {
15459
15460 sip_pvt_lock(sip_pvt_ptr);
15461 if (sip_cfg.pedanticsipchecking) {
15462 unsigned char frommismatch = 0, tomismatch = 0;
15463
15464 if (ast_strlen_zero(fromtag)) {
15465 sip_pvt_unlock(sip_pvt_ptr);
15466 ast_debug(4, "Matched %s call for callid=%s - no from tag specified, pedantic check fails\n",
15467 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
15468 return NULL;
15469 }
15470
15471 if (ast_strlen_zero(totag)) {
15472 sip_pvt_unlock(sip_pvt_ptr);
15473 ast_debug(4, "Matched %s call for callid=%s - no to tag specified, pedantic check fails\n",
15474 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
15475 return NULL;
15476 }
15477
15478
15479
15480
15481
15482
15483
15484
15485
15486
15487
15488
15489
15490
15491 frommismatch = !!strcmp(fromtag, sip_pvt_ptr->theirtag);
15492 tomismatch = !!strcmp(totag, sip_pvt_ptr->tag);
15493
15494 if (frommismatch || tomismatch) {
15495 sip_pvt_unlock(sip_pvt_ptr);
15496 if (frommismatch) {
15497 ast_debug(4, "Matched %s call for callid=%s - pedantic from tag check fails; their tag is %s our tag is %s\n",
15498 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid,
15499 fromtag, sip_pvt_ptr->theirtag);
15500 }
15501 if (tomismatch) {
15502 ast_debug(4, "Matched %s call for callid=%s - pedantic to tag check fails; their tag is %s our tag is %s\n",
15503 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid,
15504 totag, sip_pvt_ptr->tag);
15505 }
15506 return NULL;
15507 }
15508 }
15509
15510 if (totag)
15511 ast_debug(4, "Matched %s call - their tag is %s Our tag is %s\n",
15512 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING",
15513 sip_pvt_ptr->theirtag, sip_pvt_ptr->tag);
15514
15515
15516 while (sip_pvt_ptr->owner && ast_channel_trylock(sip_pvt_ptr->owner)) {
15517 sip_pvt_unlock(sip_pvt_ptr);
15518 usleep(1);
15519 sip_pvt_lock(sip_pvt_ptr);
15520 }
15521 }
15522
15523 return sip_pvt_ptr;
15524 }
15525
15526
15527
15528
15529
15530
15531
15532
15533 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req)
15534 {
15535
15536 const char *p_referred_by = NULL;
15537 char *h_refer_to = NULL;
15538 char *h_referred_by = NULL;
15539 char *refer_to;
15540 const char *p_refer_to;
15541 char *referred_by_uri = NULL;
15542 char *ptr;
15543 struct sip_request *req = NULL;
15544 const char *transfer_context = NULL;
15545 struct sip_refer *referdata;
15546
15547
15548 req = outgoing_req;
15549 referdata = transferer->refer;
15550
15551 if (!req) {
15552 req = &transferer->initreq;
15553 }
15554
15555 p_refer_to = get_header(req, "Refer-To");
15556 if (ast_strlen_zero(p_refer_to)) {
15557 ast_log(LOG_WARNING, "Refer-To Header missing. Skipping transfer.\n");
15558 return -2;
15559 }
15560 h_refer_to = ast_strdupa(p_refer_to);
15561 refer_to = get_in_brackets(h_refer_to);
15562 if (!strncasecmp(refer_to, "sip:", 4)) {
15563 refer_to += 4;
15564 } else if (!strncasecmp(refer_to, "sips:", 5)) {
15565 refer_to += 5;
15566 } else {
15567 ast_log(LOG_WARNING, "Can't transfer to non-sip: URI. (Refer-to: %s)?\n", refer_to);
15568 return -3;
15569 }
15570
15571
15572 p_referred_by = get_header(req, "Referred-By");
15573
15574
15575 if (transferer->owner) {
15576 struct ast_channel *peer = ast_bridged_channel(transferer->owner);
15577 if (peer) {
15578 pbx_builtin_setvar_helper(peer, "SIPREFERRINGCONTEXT", transferer->context);
15579 pbx_builtin_setvar_helper(peer, "SIPREFERREDBYHDR", p_referred_by);
15580 }
15581 }
15582
15583 if (!ast_strlen_zero(p_referred_by)) {
15584 char *lessthan;
15585 h_referred_by = ast_strdupa(p_referred_by);
15586
15587
15588 ast_copy_string(referdata->referred_by_name, h_referred_by, sizeof(referdata->referred_by_name));
15589 if ((lessthan = strchr(referdata->referred_by_name, '<'))) {
15590 *(lessthan - 1) = '\0';
15591 }
15592
15593 referred_by_uri = get_in_brackets(h_referred_by);
15594
15595 if (!strncasecmp(referred_by_uri, "sip:", 4)) {
15596 referred_by_uri += 4;
15597 } else if (!strncasecmp(referred_by_uri, "sips:", 5)) {
15598 referred_by_uri += 5;
15599 } else {
15600 ast_log(LOG_WARNING, "Huh? Not a sip: header (Referred-by: %s). Skipping.\n", referred_by_uri);
15601 referred_by_uri = NULL;
15602 }
15603 }
15604
15605
15606 if ((ptr = strcasestr(refer_to, "replaces="))) {
15607 char *to = NULL, *from = NULL;
15608
15609
15610 referdata->attendedtransfer = 1;
15611 ast_copy_string(referdata->replaces_callid, ptr+9, sizeof(referdata->replaces_callid));
15612 ast_uri_decode(referdata->replaces_callid);
15613 if ((ptr = strchr(referdata->replaces_callid, ';'))) {
15614 *ptr++ = '\0';
15615 }
15616
15617 if (ptr) {
15618
15619 to = strcasestr(ptr, "to-tag=");
15620 from = strcasestr(ptr, "from-tag=");
15621 }
15622
15623
15624 if (to) {
15625 ptr = to + 7;
15626 if ((to = strchr(ptr, '&'))) {
15627 *to = '\0';
15628 }
15629 if ((to = strchr(ptr, ';'))) {
15630 *to = '\0';
15631 }
15632 ast_copy_string(referdata->replaces_callid_totag, ptr, sizeof(referdata->replaces_callid_totag));
15633 }
15634
15635 if (from) {
15636 ptr = from + 9;
15637 if ((to = strchr(ptr, '&'))) {
15638 *to = '\0';
15639 }
15640 if ((to = strchr(ptr, ';'))) {
15641 *to = '\0';
15642 }
15643 ast_copy_string(referdata->replaces_callid_fromtag, ptr, sizeof(referdata->replaces_callid_fromtag));
15644 }
15645
15646 if (!strcmp(referdata->replaces_callid, transferer->callid) &&
15647 (!sip_cfg.pedanticsipchecking ||
15648 (!strcmp(referdata->replaces_callid_fromtag, transferer->theirtag) &&
15649 !strcmp(referdata->replaces_callid_totag, transferer->tag)))) {
15650 ast_log(LOG_WARNING, "Got an attempt to replace own Call-ID on %s\n", transferer->callid);
15651 return -4;
15652 }
15653
15654 if (!sip_cfg.pedanticsipchecking) {
15655 ast_debug(2, "Attended transfer: Will use Replace-Call-ID : %s (No check of from/to tags)\n", referdata->replaces_callid );
15656 } else {
15657 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>" );
15658 }
15659 }
15660
15661 if ((ptr = strchr(refer_to, '@'))) {
15662 char *urioption = NULL, *domain;
15663 int bracket = 0;
15664 *ptr++ = '\0';
15665
15666 if ((urioption = strchr(ptr, ';'))) {
15667 *urioption++ = '\0';
15668 }
15669
15670 domain = ptr;
15671
15672
15673 for (; *ptr != '\0'; ++ptr) {
15674 if (*ptr == ':' && bracket == 0) {
15675 *ptr = '\0';
15676 break;
15677 } else if (*ptr == '[') {
15678 ++bracket;
15679 } else if (*ptr == ']') {
15680 --bracket;
15681 }
15682 }
15683
15684 SIP_PEDANTIC_DECODE(domain);
15685 SIP_PEDANTIC_DECODE(urioption);
15686
15687
15688 ast_copy_string(referdata->refer_to_domain, domain, sizeof(referdata->refer_to_domain));
15689 if (urioption) {
15690 ast_copy_string(referdata->refer_to_urioption, urioption, sizeof(referdata->refer_to_urioption));
15691 }
15692 }
15693
15694 if ((ptr = strchr(refer_to, ';')))
15695 *ptr = '\0';
15696
15697 SIP_PEDANTIC_DECODE(refer_to);
15698 ast_copy_string(referdata->refer_to, refer_to, sizeof(referdata->refer_to));
15699
15700 if (referred_by_uri) {
15701 if ((ptr = strchr(referred_by_uri, ';')))
15702 *ptr = '\0';
15703 SIP_PEDANTIC_DECODE(referred_by_uri);
15704 ast_copy_string(referdata->referred_by, referred_by_uri, sizeof(referdata->referred_by));
15705 } else {
15706 referdata->referred_by[0] = '\0';
15707 }
15708
15709
15710 if (transferer->owner)
15711 transfer_context = pbx_builtin_getvar_helper(transferer->owner, "TRANSFER_CONTEXT");
15712
15713
15714 if (ast_strlen_zero(transfer_context)) {
15715 transfer_context = S_OR(transferer->owner->macrocontext,
15716 S_OR(transferer->context, sip_cfg.default_context));
15717 }
15718
15719 ast_copy_string(referdata->refer_to_context, transfer_context, sizeof(referdata->refer_to_context));
15720
15721
15722 if (referdata->attendedtransfer || ast_exists_extension(NULL, transfer_context, refer_to, 1, NULL) ) {
15723 if (sip_debug_test_pvt(transferer)) {
15724 ast_verbose("SIP transfer to extension %s@%s by %s\n", refer_to, transfer_context, referred_by_uri);
15725 }
15726
15727 return 0;
15728 }
15729 if (sip_debug_test_pvt(transferer))
15730 ast_verbose("Failed SIP Transfer to non-existing extension %s in context %s\n n", refer_to, transfer_context);
15731
15732
15733 return -1;
15734 }
15735
15736
15737
15738
15739
15740 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq)
15741 {
15742 char tmp[256] = "", *c, *a;
15743 struct sip_request *req = oreq ? oreq : &p->initreq;
15744 struct sip_refer *referdata = NULL;
15745 const char *transfer_context = NULL;
15746
15747 if (!p->refer && !sip_refer_allocate(p))
15748 return -1;
15749
15750 referdata = p->refer;
15751
15752 ast_copy_string(tmp, get_header(req, "Also"), sizeof(tmp));
15753 c = get_in_brackets(tmp);
15754
15755 if (parse_uri_legacy_check(c, "sip:,sips:", &c, NULL, &a, NULL)) {
15756 ast_log(LOG_WARNING, "Huh? Not a SIP header in Also: transfer (%s)?\n", c);
15757 return -1;
15758 }
15759
15760 SIP_PEDANTIC_DECODE(c);
15761 SIP_PEDANTIC_DECODE(a);
15762
15763 if (!ast_strlen_zero(a)) {
15764 ast_copy_string(referdata->refer_to_domain, a, sizeof(referdata->refer_to_domain));
15765 }
15766
15767 if (sip_debug_test_pvt(p))
15768 ast_verbose("Looking for %s in %s\n", c, p->context);
15769
15770 if (p->owner)
15771 transfer_context = pbx_builtin_getvar_helper(p->owner, "TRANSFER_CONTEXT");
15772
15773
15774 if (ast_strlen_zero(transfer_context)) {
15775 transfer_context = S_OR(p->owner->macrocontext,
15776 S_OR(p->context, sip_cfg.default_context));
15777 }
15778 if (ast_exists_extension(NULL, transfer_context, c, 1, NULL)) {
15779
15780 ast_debug(1, "SIP Bye-also transfer to Extension %s@%s \n", c, transfer_context);
15781 ast_copy_string(referdata->refer_to, c, sizeof(referdata->refer_to));
15782 ast_copy_string(referdata->referred_by, "", sizeof(referdata->referred_by));
15783 ast_copy_string(referdata->refer_contact, "", sizeof(referdata->refer_contact));
15784 referdata->refer_call = dialog_unref(referdata->refer_call, "unreffing referdata->refer_call");
15785
15786 ast_string_field_set(p, context, transfer_context);
15787 return 0;
15788 } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
15789 return 1;
15790 }
15791
15792 return -1;
15793 }
15794
15795
15796
15797
15798
15799
15800
15801
15802
15803
15804
15805 static attribute_unused void check_via_response(struct sip_pvt *p, struct sip_request *req)
15806 {
15807 char via[256];
15808 char *cur, *opts;
15809
15810 ast_copy_string(via, get_header(req, "Via"), sizeof(via));
15811
15812
15813 opts = strchr(via, ',');
15814 if (opts)
15815 *opts = '\0';
15816
15817
15818 opts = strchr(via, ';');
15819 if (!opts)
15820 return;
15821 *opts++ = '\0';
15822 while ( (cur = strsep(&opts, ";")) ) {
15823 if (!strncmp(cur, "rport=", 6)) {
15824 int port = strtol(cur+6, NULL, 10);
15825
15826 ast_sockaddr_set_port(&p->ourip, port);
15827 } else if (!strncmp(cur, "received=", 9)) {
15828 if (ast_parse_arg(cur + 9, PARSE_ADDR, &p->ourip))
15829 ;
15830 }
15831 }
15832 }
15833
15834
15835 static void check_via(struct sip_pvt *p, struct sip_request *req)
15836 {
15837 char via[512];
15838 char *c, *maddr;
15839 struct ast_sockaddr tmp = { { 0, } };
15840 uint16_t port;
15841
15842 ast_copy_string(via, get_header(req, "Via"), sizeof(via));
15843
15844
15845 c = strchr(via, ',');
15846 if (c)
15847 *c = '\0';
15848
15849
15850 c = strstr(via, ";rport");
15851 if (c && (c[6] != '=')) {
15852 ast_set_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT);
15853 ast_set_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT);
15854 }
15855
15856
15857 maddr = strstr(via, "maddr=");
15858 if (maddr) {
15859 maddr += 6;
15860 c = maddr + strspn(maddr, "abcdefghijklmnopqrstuvwxyz"
15861 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-.:[]");
15862 *c = '\0';
15863 }
15864
15865 c = strchr(via, ';');
15866 if (c)
15867 *c = '\0';
15868
15869 c = strchr(via, ' ');
15870 if (c) {
15871 *c = '\0';
15872 c = ast_skip_blanks(c+1);
15873 if (strcasecmp(via, "SIP/2.0/UDP") && strcasecmp(via, "SIP/2.0/TCP") && strcasecmp(via, "SIP/2.0/TLS")) {
15874 ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
15875 return;
15876 }
15877
15878 if (maddr && ast_sockaddr_resolve_first(&p->sa, maddr, 0)) {
15879 p->sa = p->recv;
15880 }
15881
15882 ast_sockaddr_resolve_first(&tmp, c, 0);
15883 port = ast_sockaddr_port(&tmp);
15884 ast_sockaddr_set_port(&p->sa,
15885 port != 0 ? port : STANDARD_SIP_PORT);
15886
15887 if (sip_debug_test_pvt(p)) {
15888 ast_verbose("Sending to %s (%s)\n",
15889 ast_sockaddr_stringify(sip_real_dst(p)),
15890 sip_nat_mode(p));
15891 }
15892 }
15893 }
15894
15895
15896 static enum check_auth_result check_peer_ok(struct sip_pvt *p, char *of,
15897 struct sip_request *req, int sipmethod, struct ast_sockaddr *addr,
15898 struct sip_peer **authpeer,
15899 enum xmittype reliable, char *calleridname, char *uri2)
15900 {
15901 enum check_auth_result res;
15902 int debug = sip_debug_test_addr(addr);
15903 struct sip_peer *peer;
15904
15905 if (sipmethod == SIP_SUBSCRIBE) {
15906
15907
15908
15909 peer = find_peer(of, NULL, TRUE, FINDALLDEVICES, FALSE, 0);
15910 } else {
15911
15912 peer = find_peer(of, NULL, TRUE, FINDUSERS, FALSE, 0);
15913
15914
15915 if (!peer) {
15916 peer = find_peer(NULL, &p->recv, TRUE, FINDPEERS, FALSE, p->socket.type);
15917 }
15918 }
15919
15920 if (!peer) {
15921 if (debug) {
15922 ast_verbose("No matching peer for '%s' from '%s'\n",
15923 of, ast_sockaddr_stringify(&p->recv));
15924 }
15925 return AUTH_DONT_KNOW;
15926 }
15927
15928 if (!ast_apply_ha(peer->ha, addr)) {
15929 ast_debug(2, "Found peer '%s' for '%s', but fails host access\n", peer->name, of);
15930 unref_peer(peer, "unref_peer: check_peer_ok: from find_peer call, early return of AUTH_ACL_FAILED");
15931 return AUTH_ACL_FAILED;
15932 }
15933 if (debug)
15934 ast_verbose("Found peer '%s' for '%s' from %s\n",
15935 peer->name, of, ast_sockaddr_stringify(&p->recv));
15936
15937
15938
15939 if (p->rtp) {
15940 ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(p->rtp), p->rtp, &peer->prefs);
15941 p->autoframing = peer->autoframing;
15942 }
15943
15944
15945 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
15946 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
15947 ast_copy_flags(&p->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
15948
15949 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) && p->udptl) {
15950 p->t38_maxdatagram = peer->t38_maxdatagram;
15951 set_t38_capabilities(p);
15952 }
15953
15954
15955
15956 if (p->sipoptions)
15957 peer->sipoptions = p->sipoptions;
15958
15959 do_setnat(p);
15960
15961 ast_string_field_set(p, peersecret, peer->secret);
15962 ast_string_field_set(p, peermd5secret, peer->md5secret);
15963 ast_string_field_set(p, subscribecontext, peer->subscribecontext);
15964 ast_string_field_set(p, mohinterpret, peer->mohinterpret);
15965 ast_string_field_set(p, mohsuggest, peer->mohsuggest);
15966 if (!ast_strlen_zero(peer->parkinglot)) {
15967 ast_string_field_set(p, parkinglot, peer->parkinglot);
15968 }
15969 ast_string_field_set(p, engine, peer->engine);
15970 p->disallowed_methods = peer->disallowed_methods;
15971 set_pvt_allowed_methods(p, req);
15972 ast_cc_copy_config_params(p->cc_params, peer->cc_params);
15973 if (peer->callingpres)
15974 p->callingpres = peer->callingpres;
15975 if (peer->maxms && peer->lastms)
15976 p->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
15977 else
15978 p->timer_t1 = peer->timer_t1;
15979
15980
15981 if (peer->timer_b)
15982 p->timer_b = peer->timer_b;
15983 else
15984 p->timer_b = 64 * p->timer_t1;
15985
15986 if (ast_test_flag(&peer->flags[0], SIP_INSECURE_INVITE)) {
15987
15988 ast_string_field_set(p, peersecret, NULL);
15989 ast_string_field_set(p, peermd5secret, NULL);
15990 }
15991 if (!(res = check_auth(p, req, peer->name, p->peersecret, p->peermd5secret, sipmethod, uri2, reliable, req->ignore))) {
15992 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
15993 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
15994 ast_copy_flags(&p->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
15995
15996 if (peer->call_limit)
15997 ast_set_flag(&p->flags[0], SIP_CALL_LIMIT);
15998 ast_string_field_set(p, peername, peer->name);
15999 ast_string_field_set(p, authname, peer->name);
16000
16001 if (sipmethod == SIP_INVITE) {
16002
16003 ast_variables_destroy(p->chanvars);
16004 p->chanvars = copy_vars(peer->chanvars);
16005 }
16006
16007 if (authpeer) {
16008 ao2_t_ref(peer, 1, "copy pointer into (*authpeer)");
16009 (*authpeer) = peer;
16010 }
16011
16012 if (!ast_strlen_zero(peer->username)) {
16013 ast_string_field_set(p, username, peer->username);
16014
16015
16016 ast_string_field_set(p, authname, peer->username);
16017 }
16018 if (!get_rpid(p, req)) {
16019 if (!ast_strlen_zero(peer->cid_num)) {
16020 char *tmp = ast_strdupa(peer->cid_num);
16021 if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
16022 ast_shrink_phone_number(tmp);
16023 ast_string_field_set(p, cid_num, tmp);
16024 }
16025 if (!ast_strlen_zero(peer->cid_name))
16026 ast_string_field_set(p, cid_name, peer->cid_name);
16027 if (!ast_strlen_zero(peer->cid_tag))
16028 ast_string_field_set(p, cid_tag, peer->cid_tag);
16029 if (peer->callingpres)
16030 p->callingpres = peer->callingpres;
16031 }
16032 ast_string_field_set(p, fullcontact, peer->fullcontact);
16033
16034 if (!ast_strlen_zero(peer->context)) {
16035 ast_string_field_set(p, context, peer->context);
16036 }
16037 if (!ast_strlen_zero(peer->mwi_from)) {
16038 ast_string_field_set(p, mwi_from, peer->mwi_from);
16039 }
16040
16041 ast_string_field_set(p, peersecret, peer->secret);
16042 ast_string_field_set(p, peermd5secret, peer->md5secret);
16043 ast_string_field_set(p, language, peer->language);
16044 ast_string_field_set(p, accountcode, peer->accountcode);
16045 p->amaflags = peer->amaflags;
16046 p->callgroup = peer->callgroup;
16047 p->pickupgroup = peer->pickupgroup;
16048 p->capability = peer->capability;
16049 p->prefs = peer->prefs;
16050 p->jointcapability = peer->capability;
16051 if (peer->maxforwards > 0) {
16052 p->maxforwards = peer->maxforwards;
16053 }
16054 if (p->peercapability)
16055 p->jointcapability &= p->peercapability;
16056 p->maxcallbitrate = peer->maxcallbitrate;
16057 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
16058 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
16059 p->noncodeccapability |= AST_RTP_DTMF;
16060 else
16061 p->noncodeccapability &= ~AST_RTP_DTMF;
16062 p->jointnoncodeccapability = p->noncodeccapability;
16063 p->rtptimeout = peer->rtptimeout;
16064 p->rtpholdtimeout = peer->rtpholdtimeout;
16065 p->rtpkeepalive = peer->rtpkeepalive;
16066 if (!dialog_initialize_rtp(p)) {
16067 if (p->rtp) {
16068 ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(p->rtp), p->rtp, &peer->prefs);
16069 p->autoframing = peer->autoframing;
16070 }
16071 } else {
16072 res = AUTH_RTP_FAILED;
16073 }
16074 }
16075 unref_peer(peer, "check_peer_ok: unref_peer: tossing temp ptr to peer from find_peer");
16076 return res;
16077 }
16078
16079
16080
16081
16082
16083
16084
16085 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
16086 int sipmethod, const char *uri, enum xmittype reliable,
16087 struct ast_sockaddr *addr, struct sip_peer **authpeer)
16088 {
16089 char from[256] = "", *of, *name, *unused_password, *domain;
16090 enum check_auth_result res = AUTH_DONT_KNOW;
16091 char calleridname[50];
16092 char *uri2 = ast_strdupa(uri);
16093
16094 terminate_uri(uri2);
16095
16096 ast_copy_string(from, get_header(req, "From"), sizeof(from));
16097
16098
16099
16100 if (!(of = (char *) get_calleridname(from, calleridname, sizeof(calleridname)))) {
16101 ast_log(LOG_ERROR, "FROM header can not be parsed \n");
16102 return res;
16103 }
16104
16105 if (calleridname[0]) {
16106 ast_string_field_set(p, cid_name, calleridname);
16107 }
16108
16109 if (ast_strlen_zero(p->exten)) {
16110 char *t = uri2;
16111 if (!strncasecmp(t, "sip:", 4))
16112 t+= 4;
16113 else if (!strncasecmp(t, "sips:", 5))
16114 t += 5;
16115 ast_string_field_set(p, exten, t);
16116 t = strchr(p->exten, '@');
16117 if (t)
16118 *t = '\0';
16119
16120 if (ast_strlen_zero(p->our_contact))
16121 build_contact(p);
16122 }
16123
16124 of = get_in_brackets(of);
16125
16126
16127 ast_string_field_set(p, from, of);
16128
16129 if (parse_uri_legacy_check(of, "sip:,sips:", &name, &unused_password, &domain, NULL)) {
16130 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
16131 }
16132
16133 SIP_PEDANTIC_DECODE(name);
16134 SIP_PEDANTIC_DECODE(domain);
16135
16136 extract_host_from_hostport(&domain);
16137
16138 if (ast_strlen_zero(domain)) {
16139
16140 ast_log(LOG_ERROR, "Empty domain name in FROM header\n");
16141 return res;
16142 }
16143
16144 if (ast_strlen_zero(name)) {
16145
16146
16147
16148 name = domain;
16149 } else {
16150
16151 char *tmp = ast_strdupa(name);
16152
16153
16154
16155 tmp = strsep(&tmp, ";");
16156 if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp)) {
16157 ast_shrink_phone_number(tmp);
16158 }
16159 ast_string_field_set(p, cid_num, tmp);
16160 }
16161
16162 if (global_match_auth_username) {
16163
16164
16165
16166
16167
16168
16169
16170
16171 const char *hdr = get_header(req, "Authorization");
16172 if (ast_strlen_zero(hdr)) {
16173 hdr = get_header(req, "Proxy-Authorization");
16174 }
16175
16176 if (!ast_strlen_zero(hdr) && (hdr = strstr(hdr, "username=\""))) {
16177 ast_copy_string(from, hdr + strlen("username=\""), sizeof(from));
16178 name = from;
16179 name = strsep(&name, "\"");
16180 }
16181 }
16182
16183 res = check_peer_ok(p, name, req, sipmethod, addr,
16184 authpeer, reliable, calleridname, uri2);
16185 if (res != AUTH_DONT_KNOW) {
16186 return res;
16187 }
16188
16189
16190 if (sip_cfg.allowguest) {
16191 get_rpid(p, req);
16192 p->rtptimeout = global_rtptimeout;
16193 p->rtpholdtimeout = global_rtpholdtimeout;
16194 p->rtpkeepalive = global_rtpkeepalive;
16195 if (!dialog_initialize_rtp(p)) {
16196 res = AUTH_SUCCESSFUL;
16197 } else {
16198 res = AUTH_RTP_FAILED;
16199 }
16200 } else if (sip_cfg.alwaysauthreject) {
16201 res = AUTH_FAKE_AUTH;
16202 } else {
16203 res = AUTH_SECRET_FAILED;
16204 }
16205
16206 if (ast_test_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT)) {
16207 ast_set_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT);
16208 }
16209
16210 return res;
16211 }
16212
16213
16214
16215
16216 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, const char *uri, enum xmittype reliable, struct ast_sockaddr *addr)
16217 {
16218 return check_user_full(p, req, sipmethod, uri, reliable, addr, NULL);
16219 }
16220
16221
16222
16223
16224
16225
16226
16227
16228
16229 static int get_msg_text(char *buf, int len, struct sip_request *req)
16230 {
16231 int x;
16232 int linelen;
16233
16234 buf[0] = '\0';
16235 --len;
16236 for (x = 0; len && x < req->lines; ++x) {
16237 const char *line = REQ_OFFSET_TO_STR(req, line[x]);
16238 strncat(buf, line, len);
16239 linelen = strlen(buf);
16240 buf += linelen;
16241 len -= linelen;
16242 if (len) {
16243 strcat(buf, "\n");
16244 ++buf;
16245 --len;
16246 }
16247 }
16248 return 0;
16249 }
16250
16251
16252
16253
16254
16255 static void receive_message(struct sip_pvt *p, struct sip_request *req)
16256 {
16257 char buf[1400];
16258 char *bufp;
16259 struct ast_frame f;
16260 const char *content_type = get_header(req, "Content-Type");
16261
16262 if (strncmp(content_type, "text/plain", strlen("text/plain"))) {
16263 transmit_response(p, "415 Unsupported Media Type", req);
16264 if (!p->owner)
16265 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16266 return;
16267 }
16268
16269 if (get_msg_text(buf, sizeof(buf), req)) {
16270 ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
16271 transmit_response(p, "500 Internal Server Error", req);
16272 if (!p->owner) {
16273 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16274 }
16275 return;
16276 }
16277
16278
16279
16280 bufp = buf + strlen(buf);
16281 while (--bufp >= buf && *bufp == '\n') {
16282 *bufp = '\0';
16283 }
16284
16285 if (p->owner) {
16286 if (sip_debug_test_pvt(p))
16287 ast_verbose("SIP Text message received: '%s'\n", buf);
16288 memset(&f, 0, sizeof(f));
16289 f.frametype = AST_FRAME_TEXT;
16290 f.subclass.integer = 0;
16291 f.offset = 0;
16292 f.data.ptr = buf;
16293 f.datalen = strlen(buf) + 1;
16294 ast_queue_frame(p->owner, &f);
16295 transmit_response(p, "202 Accepted", req);
16296 return;
16297 }
16298
16299
16300 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);
16301 transmit_response(p, "405 Method Not Allowed", req);
16302 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16303 return;
16304 }
16305
16306
16307 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16308 {
16309 #define FORMAT "%-25.25s %-15.15s %-15.15s \n"
16310 #define FORMAT2 "%-25.25s %-15.15s %-15.15s \n"
16311 char ilimits[40];
16312 char iused[40];
16313 int showall = FALSE;
16314 struct ao2_iterator i;
16315 struct sip_peer *peer;
16316
16317 switch (cmd) {
16318 case CLI_INIT:
16319 e->command = "sip show inuse";
16320 e->usage =
16321 "Usage: sip show inuse [all]\n"
16322 " List all SIP devices usage counters and limits.\n"
16323 " Add option \"all\" to show all devices, not only those with a limit.\n";
16324 return NULL;
16325 case CLI_GENERATE:
16326 return NULL;
16327 }
16328
16329 if (a->argc < 3)
16330 return CLI_SHOWUSAGE;
16331
16332 if (a->argc == 4 && !strcmp(a->argv[3], "all"))
16333 showall = TRUE;
16334
16335 ast_cli(a->fd, FORMAT, "* Peer name", "In use", "Limit");
16336
16337 i = ao2_iterator_init(peers, 0);
16338 while ((peer = ao2_t_iterator_next(&i, "iterate thru peer table"))) {
16339 ao2_lock(peer);
16340 if (peer->call_limit)
16341 snprintf(ilimits, sizeof(ilimits), "%d", peer->call_limit);
16342 else
16343 ast_copy_string(ilimits, "N/A", sizeof(ilimits));
16344 snprintf(iused, sizeof(iused), "%d/%d/%d", peer->inUse, peer->inRinging, peer->onHold);
16345 if (showall || peer->call_limit)
16346 ast_cli(a->fd, FORMAT2, peer->name, iused, ilimits);
16347 ao2_unlock(peer);
16348 unref_peer(peer, "toss iterator pointer");
16349 }
16350 ao2_iterator_destroy(&i);
16351
16352 return CLI_SUCCESS;
16353 #undef FORMAT
16354 #undef FORMAT2
16355 }
16356
16357
16358
16359 static char *transfermode2str(enum transfermodes mode)
16360 {
16361 if (mode == TRANSFER_OPENFORALL)
16362 return "open";
16363 else if (mode == TRANSFER_CLOSED)
16364 return "closed";
16365 return "strict";
16366 }
16367
16368
16369
16370
16371
16372
16373
16374 static const struct _map_x_s stmodes[] = {
16375 { SESSION_TIMER_MODE_ACCEPT, "Accept"},
16376 { SESSION_TIMER_MODE_ORIGINATE, "Originate"},
16377 { SESSION_TIMER_MODE_REFUSE, "Refuse"},
16378 { -1, NULL},
16379 };
16380
16381 static const char *stmode2str(enum st_mode m)
16382 {
16383 return map_x_s(stmodes, m, "Unknown");
16384 }
16385
16386 static enum st_mode str2stmode(const char *s)
16387 {
16388 return map_s_x(stmodes, s, -1);
16389 }
16390
16391
16392 static const struct _map_x_s strefreshers[] = {
16393 { SESSION_TIMER_REFRESHER_AUTO, "auto"},
16394 { SESSION_TIMER_REFRESHER_UAC, "uac"},
16395 { SESSION_TIMER_REFRESHER_UAS, "uas"},
16396 { -1, NULL},
16397 };
16398
16399 static const char *strefresher2str(enum st_refresher r)
16400 {
16401 return map_x_s(strefreshers, r, "Unknown");
16402 }
16403
16404 static enum st_refresher str2strefresher(const char *s)
16405 {
16406 return map_s_x(strefreshers, s, -1);
16407 }
16408
16409
16410 static int peer_status(struct sip_peer *peer, char *status, int statuslen)
16411 {
16412 int res = 0;
16413 if (peer->maxms) {
16414 if (peer->lastms < 0) {
16415 ast_copy_string(status, "UNREACHABLE", statuslen);
16416 } else if (peer->lastms > peer->maxms) {
16417 snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
16418 res = 1;
16419 } else if (peer->lastms) {
16420 snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
16421 res = 1;
16422 } else {
16423 ast_copy_string(status, "UNKNOWN", statuslen);
16424 }
16425 } else {
16426 ast_copy_string(status, "Unmonitored", statuslen);
16427
16428 res = -1;
16429 }
16430 return res;
16431 }
16432
16433
16434 static char *sip_show_tcp(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16435 {
16436 struct sip_threadinfo *th;
16437 struct ao2_iterator i;
16438
16439 #define FORMAT2 "%-47.47s %9.9s %6.6s\n"
16440 #define FORMAT "%-47.47s %-9.9s %-6.6s\n"
16441
16442 switch (cmd) {
16443 case CLI_INIT:
16444 e->command = "sip show tcp";
16445 e->usage =
16446 "Usage: sip show tcp\n"
16447 " Lists all active TCP/TLS sessions.\n";
16448 return NULL;
16449 case CLI_GENERATE:
16450 return NULL;
16451 }
16452
16453 if (a->argc != 3)
16454 return CLI_SHOWUSAGE;
16455
16456 ast_cli(a->fd, FORMAT2, "Address", "Transport", "Type");
16457
16458 i = ao2_iterator_init(threadt, 0);
16459 while ((th = ao2_t_iterator_next(&i, "iterate through tcp threads for 'sip show tcp'"))) {
16460 ast_cli(a->fd, FORMAT,
16461 ast_sockaddr_stringify(&th->tcptls_session->remote_address),
16462 get_transport(th->type),
16463 (th->tcptls_session->client ? "Client" : "Server"));
16464 ao2_t_ref(th, -1, "decrement ref from iterator");
16465 }
16466 ao2_iterator_destroy(&i);
16467
16468 return CLI_SUCCESS;
16469 #undef FORMAT
16470 #undef FORMAT2
16471 }
16472
16473
16474 static char *sip_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16475 {
16476 regex_t regexbuf;
16477 int havepattern = FALSE;
16478 struct ao2_iterator user_iter;
16479 struct sip_peer *user;
16480
16481 #define FORMAT "%-25.25s %-15.15s %-15.15s %-15.15s %-5.5s%-10.10s\n"
16482
16483 switch (cmd) {
16484 case CLI_INIT:
16485 e->command = "sip show users";
16486 e->usage =
16487 "Usage: sip show users [like <pattern>]\n"
16488 " Lists all known SIP users.\n"
16489 " Optional regular expression pattern is used to filter the user list.\n";
16490 return NULL;
16491 case CLI_GENERATE:
16492 return NULL;
16493 }
16494
16495 switch (a->argc) {
16496 case 5:
16497 if (!strcasecmp(a->argv[3], "like")) {
16498 if (regcomp(®exbuf, a->argv[4], REG_EXTENDED | REG_NOSUB))
16499 return CLI_SHOWUSAGE;
16500 havepattern = TRUE;
16501 } else
16502 return CLI_SHOWUSAGE;
16503 case 3:
16504 break;
16505 default:
16506 return CLI_SHOWUSAGE;
16507 }
16508
16509 ast_cli(a->fd, FORMAT, "Username", "Secret", "Accountcode", "Def.Context", "ACL", "ForcerPort");
16510
16511 user_iter = ao2_iterator_init(peers, 0);
16512 while ((user = ao2_t_iterator_next(&user_iter, "iterate thru peers table"))) {
16513 ao2_lock(user);
16514 if (!(user->type & SIP_TYPE_USER)) {
16515 ao2_unlock(user);
16516 unref_peer(user, "sip show users");
16517 continue;
16518 }
16519
16520 if (havepattern && regexec(®exbuf, user->name, 0, NULL, 0)) {
16521 ao2_unlock(user);
16522 unref_peer(user, "sip show users");
16523 continue;
16524 }
16525
16526 ast_cli(a->fd, FORMAT, user->name,
16527 user->secret,
16528 user->accountcode,
16529 user->context,
16530 AST_CLI_YESNO(user->ha != NULL),
16531 AST_CLI_YESNO(ast_test_flag(&user->flags[0], SIP_NAT_FORCE_RPORT)));
16532 ao2_unlock(user);
16533 unref_peer(user, "sip show users");
16534 }
16535 ao2_iterator_destroy(&user_iter);
16536
16537 if (havepattern)
16538 regfree(®exbuf);
16539
16540 return CLI_SUCCESS;
16541 #undef FORMAT
16542 }
16543
16544
16545 static int manager_show_registry(struct mansession *s, const struct message *m)
16546 {
16547 const char *id = astman_get_header(m, "ActionID");
16548 char idtext[256] = "";
16549 int total = 0;
16550
16551 if (!ast_strlen_zero(id))
16552 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
16553
16554 astman_send_listack(s, m, "Registrations will follow", "start");
16555
16556 ASTOBJ_CONTAINER_TRAVERSE(®l, 1, do {
16557 ASTOBJ_RDLOCK(iterator);
16558 astman_append(s,
16559 "Event: RegistryEntry\r\n"
16560 "%s"
16561 "Host: %s\r\n"
16562 "Port: %d\r\n"
16563 "Username: %s\r\n"
16564 "Domain: %s\r\n"
16565 "DomainPort: %d\r\n"
16566 "Refresh: %d\r\n"
16567 "State: %s\r\n"
16568 "RegistrationTime: %ld\r\n"
16569 "\r\n",
16570 idtext,
16571 iterator->hostname,
16572 iterator->portno ? iterator->portno : STANDARD_SIP_PORT,
16573 iterator->username,
16574 S_OR(iterator->regdomain,iterator->hostname),
16575 iterator->regdomainport ? iterator->regdomainport : STANDARD_SIP_PORT,
16576 iterator->refresh,
16577 regstate2str(iterator->regstate),
16578 (long) iterator->regtime.tv_sec);
16579 ASTOBJ_UNLOCK(iterator);
16580 total++;
16581 } while(0));
16582
16583 astman_append(s,
16584 "Event: RegistrationsComplete\r\n"
16585 "EventList: Complete\r\n"
16586 "ListItems: %d\r\n"
16587 "%s"
16588 "\r\n", total, idtext);
16589
16590 return 0;
16591 }
16592
16593
16594
16595 static int manager_sip_show_peers(struct mansession *s, const struct message *m)
16596 {
16597 const char *id = astman_get_header(m, "ActionID");
16598 const char *a[] = {"sip", "show", "peers"};
16599 char idtext[256] = "";
16600 int total = 0;
16601
16602 if (!ast_strlen_zero(id))
16603 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
16604
16605 astman_send_listack(s, m, "Peer status list will follow", "start");
16606
16607 _sip_show_peers(-1, &total, s, m, 3, a);
16608
16609 astman_append(s,
16610 "Event: PeerlistComplete\r\n"
16611 "EventList: Complete\r\n"
16612 "ListItems: %d\r\n"
16613 "%s"
16614 "\r\n", total, idtext);
16615 return 0;
16616 }
16617
16618
16619 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16620 {
16621 switch (cmd) {
16622 case CLI_INIT:
16623 e->command = "sip show peers";
16624 e->usage =
16625 "Usage: sip show peers [like <pattern>]\n"
16626 " Lists all known SIP peers.\n"
16627 " Optional regular expression pattern is used to filter the peer list.\n";
16628 return NULL;
16629 case CLI_GENERATE:
16630 return NULL;
16631 }
16632
16633 return _sip_show_peers(a->fd, NULL, NULL, NULL, a->argc, (const char **) a->argv);
16634 }
16635
16636 int peercomparefunc(const void *a, const void *b);
16637
16638 int peercomparefunc(const void *a, const void *b)
16639 {
16640 struct sip_peer **ap = (struct sip_peer **)a;
16641 struct sip_peer **bp = (struct sip_peer **)b;
16642 return strcmp((*ap)->name, (*bp)->name);
16643 }
16644
16645
16646
16647 static char *_sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[])
16648 {
16649 regex_t regexbuf;
16650 int havepattern = FALSE;
16651 struct sip_peer *peer;
16652 struct ao2_iterator* it_peers;
16653
16654
16655 #define FORMAT2 "%-25.25s %-39.39s %-3.3s %-10.10s %-3.3s %-8s %-10s %s\n"
16656
16657 char name[256];
16658 int total_peers = 0;
16659 int peers_mon_online = 0;
16660 int peers_mon_offline = 0;
16661 int peers_unmon_offline = 0;
16662 int peers_unmon_online = 0;
16663 const char *id;
16664 char idtext[256] = "";
16665 int realtimepeers;
16666 struct sip_peer **peerarray;
16667 int k;
16668
16669 realtimepeers = ast_check_realtime("sippeers");
16670
16671 if (s) {
16672 id = astman_get_header(m, "ActionID");
16673 if (!ast_strlen_zero(id))
16674 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
16675 }
16676
16677 switch (argc) {
16678 case 5:
16679 if (!strcasecmp(argv[3], "like")) {
16680 if (regcomp(®exbuf, argv[4], REG_EXTENDED | REG_NOSUB))
16681 return CLI_SHOWUSAGE;
16682 havepattern = TRUE;
16683 } else
16684 return CLI_SHOWUSAGE;
16685 case 3:
16686 break;
16687 default:
16688 return CLI_SHOWUSAGE;
16689 }
16690
16691 if (!s) {
16692
16693 ast_cli(fd, FORMAT2, "Name/username", "Host", "Dyn", "Forcerport", "ACL", "Port", "Status", (realtimepeers ? "Realtime" : ""));
16694 }
16695
16696 ao2_lock(peers);
16697 if (!(it_peers = ao2_callback(peers, OBJ_MULTIPLE, NULL, NULL))) {
16698 ast_log(AST_LOG_ERROR, "Unable to create iterator for peers container for sip show peers\n");
16699 ao2_unlock(peers);
16700 return CLI_FAILURE;
16701 }
16702 if (!(peerarray = ast_calloc(sizeof(struct sip_peer *), ao2_container_count(peers)))) {
16703 ast_log(AST_LOG_ERROR, "Unable to allocate peer array for sip show peers\n");
16704 ao2_iterator_destroy(it_peers);
16705 ao2_unlock(peers);
16706 return CLI_FAILURE;
16707 }
16708 ao2_unlock(peers);
16709
16710 while ((peer = ao2_t_iterator_next(it_peers, "iterate thru peers table"))) {
16711 ao2_lock(peer);
16712
16713 if (!(peer->type & SIP_TYPE_PEER)) {
16714 ao2_unlock(peer);
16715 unref_peer(peer, "unref peer because it's actually a user");
16716 continue;
16717 }
16718
16719 if (havepattern && regexec(®exbuf, peer->name, 0, NULL, 0)) {
16720 ao2_unlock(peer);
16721 unref_peer(peer, "toss iterator peer ptr before continue");
16722 continue;
16723 }
16724
16725 peerarray[total_peers++] = peer;
16726 ao2_unlock(peer);
16727 }
16728 ao2_iterator_destroy(it_peers);
16729
16730 qsort(peerarray, total_peers, sizeof(struct sip_peer *), peercomparefunc);
16731
16732 for(k=0; k < total_peers; k++) {
16733 char status[20] = "";
16734 char srch[2000];
16735 char pstatus;
16736
16737
16738
16739
16740
16741
16742 char *tmp_port;
16743 char *tmp_host;
16744
16745 peer = peerarray[k];
16746
16747 tmp_port = ast_sockaddr_isnull(&peer->addr) ?
16748 "0" : ast_strdupa(ast_sockaddr_stringify_port(&peer->addr));
16749
16750 tmp_host = ast_sockaddr_isnull(&peer->addr) ?
16751 "(Unspecified)" : ast_strdupa(ast_sockaddr_stringify_addr(&peer->addr));
16752
16753 ao2_lock(peer);
16754 if (havepattern && regexec(®exbuf, peer->name, 0, NULL, 0)) {
16755 ao2_unlock(peer);
16756 peer = peerarray[k] = unref_peer(peer, "toss iterator peer ptr before continue");
16757 continue;
16758 }
16759
16760 if (!ast_strlen_zero(peer->username) && !s)
16761 snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
16762 else
16763 ast_copy_string(name, peer->name, sizeof(name));
16764
16765 pstatus = peer_status(peer, status, sizeof(status));
16766 if (pstatus == 1)
16767 peers_mon_online++;
16768 else if (pstatus == 0)
16769 peers_mon_offline++;
16770 else {
16771 if (ast_sockaddr_isnull(&peer->addr) ||
16772 !ast_sockaddr_port(&peer->addr)) {
16773 peers_unmon_offline++;
16774 } else {
16775 peers_unmon_online++;
16776 }
16777 }
16778
16779 snprintf(srch, sizeof(srch), FORMAT2, name,
16780 tmp_host,
16781 peer->host_dynamic ? " D " : " ",
16782 ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) ? " N " : " ",
16783 peer->ha ? " A " : " ",
16784 tmp_port, status,
16785 realtimepeers ? (peer->is_realtime ? "Cached RT":"") : "");
16786
16787 if (!s) {
16788 ast_cli(fd, FORMAT2, name,
16789 tmp_host,
16790 peer->host_dynamic ? " D " : " ",
16791 ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) ? " N " : " ",
16792 peer->ha ? " A " : " ",
16793 tmp_port, status,
16794 realtimepeers ? (peer->is_realtime ? "Cached RT":"") : "");
16795 } else {
16796
16797 astman_append(s,
16798 "Event: PeerEntry\r\n%s"
16799 "Channeltype: SIP\r\n"
16800 "ObjectName: %s\r\n"
16801 "ChanObjectType: peer\r\n"
16802 "IPaddress: %s\r\n"
16803 "IPport: %s\r\n"
16804 "Dynamic: %s\r\n"
16805 "Forcerport: %s\r\n"
16806 "VideoSupport: %s\r\n"
16807 "TextSupport: %s\r\n"
16808 "ACL: %s\r\n"
16809 "Status: %s\r\n"
16810 "RealtimeDevice: %s\r\n\r\n",
16811 idtext,
16812 peer->name,
16813 ast_sockaddr_isnull(&peer->addr) ? "-none-" : tmp_host,
16814 ast_sockaddr_isnull(&peer->addr) ? "0" : tmp_port,
16815 peer->host_dynamic ? "yes" : "no",
16816 ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) ? "yes" : "no",
16817 ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "yes" : "no",
16818 ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT) ? "yes" : "no",
16819 peer->ha ? "yes" : "no",
16820 status,
16821 realtimepeers ? (peer->is_realtime ? "yes":"no") : "no");
16822 }
16823 ao2_unlock(peer);
16824 peer = peerarray[k] = unref_peer(peer, "toss iterator peer ptr");
16825 }
16826
16827 if (!s)
16828 ast_cli(fd, "%d sip peers [Monitored: %d online, %d offline Unmonitored: %d online, %d offline]\n",
16829 total_peers, peers_mon_online, peers_mon_offline, peers_unmon_online, peers_unmon_offline);
16830
16831 if (havepattern)
16832 regfree(®exbuf);
16833
16834 if (total)
16835 *total = total_peers;
16836
16837 ast_free(peerarray);
16838
16839 return CLI_SUCCESS;
16840 #undef FORMAT2
16841 }
16842
16843 static int peer_dump_func(void *userobj, void *arg, int flags)
16844 {
16845 struct sip_peer *peer = userobj;
16846 int refc = ao2_t_ref(userobj, 0, "");
16847 struct ast_cli_args *a = (struct ast_cli_args *) arg;
16848
16849 ast_cli(a->fd, "name: %s\ntype: peer\nobjflags: %d\nrefcount: %d\n\n",
16850 peer->name, 0, refc);
16851 return 0;
16852 }
16853
16854 static int dialog_dump_func(void *userobj, void *arg, int flags)
16855 {
16856 struct sip_pvt *pvt = userobj;
16857 int refc = ao2_t_ref(userobj, 0, "");
16858 struct ast_cli_args *a = (struct ast_cli_args *) arg;
16859
16860 ast_cli(a->fd, "name: %s\ntype: dialog\nobjflags: %d\nrefcount: %d\n\n",
16861 pvt->callid, 0, refc);
16862 return 0;
16863 }
16864
16865
16866
16867 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16868 {
16869 char tmp[256];
16870
16871 switch (cmd) {
16872 case CLI_INIT:
16873 e->command = "sip show objects";
16874 e->usage =
16875 "Usage: sip show objects\n"
16876 " Lists status of known SIP objects\n";
16877 return NULL;
16878 case CLI_GENERATE:
16879 return NULL;
16880 }
16881
16882 if (a->argc != 3)
16883 return CLI_SHOWUSAGE;
16884 ast_cli(a->fd, "-= Peer objects: %d static, %d realtime, %d autocreate =-\n\n", speerobjs, rpeerobjs, apeerobjs);
16885 ao2_t_callback(peers, OBJ_NODATA, peer_dump_func, a, "initiate ao2_callback to dump peers");
16886 ast_cli(a->fd, "-= Peer objects by IP =-\n\n");
16887 ao2_t_callback(peers_by_ip, OBJ_NODATA, peer_dump_func, a, "initiate ao2_callback to dump peers_by_ip");
16888 ast_cli(a->fd, "-= Registry objects: %d =-\n\n", regobjs);
16889 ASTOBJ_CONTAINER_DUMP(a->fd, tmp, sizeof(tmp), ®l);
16890 ast_cli(a->fd, "-= Dialog objects:\n\n");
16891 ao2_t_callback(dialogs, OBJ_NODATA, dialog_dump_func, a, "initiate ao2_callback to dump dialogs");
16892 return CLI_SUCCESS;
16893 }
16894
16895 static void print_group(int fd, ast_group_t group, int crlf)
16896 {
16897 char buf[256];
16898 ast_cli(fd, crlf ? "%s\r\n" : "%s\n", ast_print_group(buf, sizeof(buf), group) );
16899 }
16900
16901
16902 static const struct _map_x_s dtmfstr[] = {
16903 { SIP_DTMF_RFC2833, "rfc2833" },
16904 { SIP_DTMF_INFO, "info" },
16905 { SIP_DTMF_SHORTINFO, "shortinfo" },
16906 { SIP_DTMF_INBAND, "inband" },
16907 { SIP_DTMF_AUTO, "auto" },
16908 { -1, NULL },
16909 };
16910
16911
16912 static const char *dtmfmode2str(int mode)
16913 {
16914 return map_x_s(dtmfstr, mode, "<error>");
16915 }
16916
16917
16918 static int str2dtmfmode(const char *str)
16919 {
16920 return map_s_x(dtmfstr, str, -1);
16921 }
16922
16923 static const struct _map_x_s insecurestr[] = {
16924 { SIP_INSECURE_PORT, "port" },
16925 { SIP_INSECURE_INVITE, "invite" },
16926 { SIP_INSECURE_PORT | SIP_INSECURE_INVITE, "port,invite" },
16927 { 0, "no" },
16928 { -1, NULL },
16929 };
16930
16931
16932 static const char *insecure2str(int mode)
16933 {
16934 return map_x_s(insecurestr, mode, "<error>");
16935 }
16936
16937 static const struct _map_x_s allowoverlapstr[] = {
16938 { SIP_PAGE2_ALLOWOVERLAP_YES, "Yes" },
16939 { SIP_PAGE2_ALLOWOVERLAP_DTMF, "DTMF" },
16940 { SIP_PAGE2_ALLOWOVERLAP_NO, "No" },
16941 { -1, NULL },
16942 };
16943
16944
16945 static const char *allowoverlap2str(int mode)
16946 {
16947 return map_x_s(allowoverlapstr, mode, "<error>");
16948 }
16949
16950
16951
16952
16953 static void cleanup_stale_contexts(char *new, char *old)
16954 {
16955 char *oldcontext, *newcontext, *stalecontext, *stringp, newlist[AST_MAX_CONTEXT];
16956
16957 while ((oldcontext = strsep(&old, "&"))) {
16958 stalecontext = '\0';
16959 ast_copy_string(newlist, new, sizeof(newlist));
16960 stringp = newlist;
16961 while ((newcontext = strsep(&stringp, "&"))) {
16962 if (!strcmp(newcontext, oldcontext)) {
16963
16964 stalecontext = '\0';
16965 break;
16966 } else if (strcmp(newcontext, oldcontext)) {
16967 stalecontext = oldcontext;
16968 }
16969
16970 }
16971 if (stalecontext)
16972 ast_context_destroy(ast_context_find(stalecontext), "SIP");
16973 }
16974 }
16975
16976
16977
16978
16979
16980
16981
16982
16983
16984
16985
16986 static int dialog_needdestroy(void *dialogobj, void *arg, int flags)
16987 {
16988 struct sip_pvt *dialog = dialogobj;
16989 time_t *t = arg;
16990
16991 if (sip_pvt_trylock(dialog)) {
16992
16993
16994 return 0;
16995 }
16996
16997
16998 check_rtp_timeout(dialog, *t);
16999
17000
17001 if (dialog->rtp && ast_rtp_instance_get_bridged(dialog->rtp)) {
17002 ast_debug(2, "Bridge still active. Delaying destroy of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
17003 sip_pvt_unlock(dialog);
17004 return 0;
17005 }
17006
17007 if (dialog->vrtp && ast_rtp_instance_get_bridged(dialog->vrtp)) {
17008 ast_debug(2, "Bridge still active. Delaying destroy of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
17009 sip_pvt_unlock(dialog);
17010 return 0;
17011 }
17012
17013
17014
17015
17016 if (dialog->needdestroy && !dialog->packets && !dialog->owner) {
17017
17018 if (dialog->rtp && ast_rtp_instance_get_bridged(dialog->rtp)) {
17019 ast_debug(2, "Bridge still active. Delaying destruction of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
17020 sip_pvt_unlock(dialog);
17021 return 0;
17022 }
17023
17024 if (dialog->vrtp && ast_rtp_instance_get_bridged(dialog->vrtp)) {
17025 ast_debug(2, "Bridge still active. Delaying destroy of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
17026 sip_pvt_unlock(dialog);
17027 return 0;
17028 }
17029
17030 sip_pvt_unlock(dialog);
17031
17032
17033 ao2_t_link(dialogs_to_destroy, dialog, "Link dialog for destruction");
17034 return 0;
17035 }
17036
17037 sip_pvt_unlock(dialog);
17038
17039 return 0;
17040 }
17041
17042
17043
17044
17045
17046
17047
17048
17049
17050
17051
17052 static int dialog_unlink_callback(void *obj, void *arg, int flags)
17053 {
17054 struct sip_pvt *dialog = obj;
17055
17056 dialog_unlink_all(dialog);
17057
17058 return CMP_MATCH;
17059 }
17060
17061
17062
17063 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17064 {
17065 struct sip_peer *peer, *pi;
17066 int prunepeer = FALSE;
17067 int multi = FALSE;
17068 const char *name = NULL;
17069 regex_t regexbuf;
17070 int havepattern = 0;
17071 struct ao2_iterator i;
17072 static const char * const choices[] = { "all", "like", NULL };
17073 char *cmplt;
17074
17075 if (cmd == CLI_INIT) {
17076 e->command = "sip prune realtime [peer|all]";
17077 e->usage =
17078 "Usage: sip prune realtime [peer [<name>|all|like <pattern>]|all]\n"
17079 " Prunes object(s) from the cache.\n"
17080 " Optional regular expression pattern is used to filter the objects.\n";
17081 return NULL;
17082 } else if (cmd == CLI_GENERATE) {
17083 if (a->pos == 4 && !strcasecmp(a->argv[3], "peer")) {
17084 cmplt = ast_cli_complete(a->word, choices, a->n);
17085 if (!cmplt)
17086 cmplt = complete_sip_peer(a->word, a->n - sizeof(choices), SIP_PAGE2_RTCACHEFRIENDS);
17087 return cmplt;
17088 }
17089 if (a->pos == 5 && !strcasecmp(a->argv[4], "like"))
17090 return complete_sip_peer(a->word, a->n, SIP_PAGE2_RTCACHEFRIENDS);
17091 return NULL;
17092 }
17093 switch (a->argc) {
17094 case 4:
17095 name = a->argv[3];
17096
17097 if (!strcasecmp(name, "peer") || !strcasecmp(name, "like"))
17098 return CLI_SHOWUSAGE;
17099 prunepeer = TRUE;
17100 if (!strcasecmp(name, "all")) {
17101 multi = TRUE;
17102 name = NULL;
17103 }
17104
17105 break;
17106 case 5:
17107
17108 name = a->argv[4];
17109 if (!strcasecmp(a->argv[3], "peer"))
17110 prunepeer = TRUE;
17111 else if (!strcasecmp(a->argv[3], "like")) {
17112 prunepeer = TRUE;
17113 multi = TRUE;
17114 } else
17115 return CLI_SHOWUSAGE;
17116 if (!strcasecmp(name, "like"))
17117 return CLI_SHOWUSAGE;
17118 if (!multi && !strcasecmp(name, "all")) {
17119 multi = TRUE;
17120 name = NULL;
17121 }
17122 break;
17123 case 6:
17124 name = a->argv[5];
17125 multi = TRUE;
17126
17127 if (strcasecmp(a->argv[4], "like"))
17128 return CLI_SHOWUSAGE;
17129 if (!strcasecmp(a->argv[3], "peer")) {
17130 prunepeer = TRUE;
17131 } else
17132 return CLI_SHOWUSAGE;
17133 break;
17134 default:
17135 return CLI_SHOWUSAGE;
17136 }
17137
17138 if (multi && name) {
17139 if (regcomp(®exbuf, name, REG_EXTENDED | REG_NOSUB)) {
17140 return CLI_SHOWUSAGE;
17141 }
17142 havepattern = 1;
17143 }
17144
17145 if (multi) {
17146 if (prunepeer) {
17147 int pruned = 0;
17148
17149 i = ao2_iterator_init(peers, 0);
17150 while ((pi = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
17151 ao2_lock(pi);
17152 if (name && regexec(®exbuf, pi->name, 0, NULL, 0)) {
17153 ao2_unlock(pi);
17154 unref_peer(pi, "toss iterator peer ptr before continue");
17155 continue;
17156 };
17157 if (ast_test_flag(&pi->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
17158 pi->the_mark = 1;
17159 pruned++;
17160 }
17161 ao2_unlock(pi);
17162 unref_peer(pi, "toss iterator peer ptr");
17163 }
17164 ao2_iterator_destroy(&i);
17165 if (pruned) {
17166 unlink_marked_peers_from_tables();
17167 ast_cli(a->fd, "%d peers pruned.\n", pruned);
17168 } else
17169 ast_cli(a->fd, "No peers found to prune.\n");
17170 }
17171 } else {
17172 if (prunepeer) {
17173 struct sip_peer tmp;
17174 ast_copy_string(tmp.name, name, sizeof(tmp.name));
17175 if ((peer = ao2_t_find(peers, &tmp, OBJ_POINTER | OBJ_UNLINK, "finding to unlink from peers"))) {
17176 if (!ast_sockaddr_isnull(&peer->addr)) {
17177 ao2_t_unlink(peers_by_ip, peer, "unlinking peer from peers_by_ip also");
17178 }
17179 if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
17180 ast_cli(a->fd, "Peer '%s' is not a Realtime peer, cannot be pruned.\n", name);
17181
17182 ao2_t_link(peers, peer, "link peer into peer table");
17183 if (!ast_sockaddr_isnull(&peer->addr)) {
17184 ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
17185 }
17186 } else
17187 ast_cli(a->fd, "Peer '%s' pruned.\n", name);
17188 unref_peer(peer, "sip_prune_realtime: unref_peer: tossing temp peer ptr");
17189 } else
17190 ast_cli(a->fd, "Peer '%s' not found.\n", name);
17191 }
17192 }
17193
17194 if (havepattern) {
17195 regfree(®exbuf);
17196 }
17197
17198 return CLI_SUCCESS;
17199 }
17200
17201
17202 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref)
17203 {
17204 int x;
17205 format_t codec;
17206
17207 for(x = 0; x < 64 ; x++) {
17208 codec = ast_codec_pref_index(pref, x);
17209 if (!codec)
17210 break;
17211 ast_cli(fd, "%s", ast_getformatname(codec));
17212 ast_cli(fd, ":%d", pref->framing[x]);
17213 if (x < 31 && ast_codec_pref_index(pref, x + 1))
17214 ast_cli(fd, ",");
17215 }
17216 if (!x)
17217 ast_cli(fd, "none");
17218 }
17219
17220
17221 static const char *domain_mode_to_text(const enum domain_mode mode)
17222 {
17223 switch (mode) {
17224 case SIP_DOMAIN_AUTO:
17225 return "[Automatic]";
17226 case SIP_DOMAIN_CONFIG:
17227 return "[Configured]";
17228 }
17229
17230 return "";
17231 }
17232
17233
17234 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17235 {
17236 struct domain *d;
17237 #define FORMAT "%-40.40s %-20.20s %-16.16s\n"
17238
17239 switch (cmd) {
17240 case CLI_INIT:
17241 e->command = "sip show domains";
17242 e->usage =
17243 "Usage: sip show domains\n"
17244 " Lists all configured SIP local domains.\n"
17245 " Asterisk only responds to SIP messages to local domains.\n";
17246 return NULL;
17247 case CLI_GENERATE:
17248 return NULL;
17249 }
17250
17251 if (AST_LIST_EMPTY(&domain_list)) {
17252 ast_cli(a->fd, "SIP Domain support not enabled.\n\n");
17253 return CLI_SUCCESS;
17254 } else {
17255 ast_cli(a->fd, FORMAT, "Our local SIP domains:", "Context", "Set by");
17256 AST_LIST_LOCK(&domain_list);
17257 AST_LIST_TRAVERSE(&domain_list, d, list)
17258 ast_cli(a->fd, FORMAT, d->domain, S_OR(d->context, "(default)"),
17259 domain_mode_to_text(d->mode));
17260 AST_LIST_UNLOCK(&domain_list);
17261 ast_cli(a->fd, "\n");
17262 return CLI_SUCCESS;
17263 }
17264 }
17265 #undef FORMAT
17266
17267
17268 static int manager_sip_show_peer(struct mansession *s, const struct message *m)
17269 {
17270 const char *a[4];
17271 const char *peer;
17272
17273 peer = astman_get_header(m, "Peer");
17274 if (ast_strlen_zero(peer)) {
17275 astman_send_error(s, m, "Peer: <name> missing.");
17276 return 0;
17277 }
17278 a[0] = "sip";
17279 a[1] = "show";
17280 a[2] = "peer";
17281 a[3] = peer;
17282
17283 _sip_show_peer(1, -1, s, m, 4, a);
17284 astman_append(s, "\r\n" );
17285 return 0;
17286 }
17287
17288
17289 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17290 {
17291 switch (cmd) {
17292 case CLI_INIT:
17293 e->command = "sip show peer";
17294 e->usage =
17295 "Usage: sip show peer <name> [load]\n"
17296 " Shows all details on one SIP peer and the current status.\n"
17297 " Option \"load\" forces lookup of peer in realtime storage.\n";
17298 return NULL;
17299 case CLI_GENERATE:
17300 return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
17301 }
17302 return _sip_show_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
17303 }
17304
17305
17306 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
17307 {
17308 struct sip_peer *peer;
17309 int load_realtime;
17310
17311 if (argc < 4)
17312 return CLI_SHOWUSAGE;
17313
17314 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
17315 if ((peer = find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0))) {
17316 sip_poke_peer(peer, 1);
17317 unref_peer(peer, "qualify: done with peer");
17318 } else if (type == 0) {
17319 ast_cli(fd, "Peer '%s' not found\n", argv[3]);
17320 } else {
17321 astman_send_error(s, m, "Peer not found");
17322 }
17323 return CLI_SUCCESS;
17324 }
17325
17326
17327 static int manager_sip_qualify_peer(struct mansession *s, const struct message *m)
17328 {
17329 const char *a[4];
17330 const char *peer;
17331
17332 peer = astman_get_header(m, "Peer");
17333 if (ast_strlen_zero(peer)) {
17334 astman_send_error(s, m, "Peer: <name> missing.");
17335 return 0;
17336 }
17337 a[0] = "sip";
17338 a[1] = "qualify";
17339 a[2] = "peer";
17340 a[3] = peer;
17341
17342 _sip_qualify_peer(1, -1, s, m, 4, a);
17343 astman_append(s, "\r\n\r\n" );
17344 return 0;
17345 }
17346
17347
17348 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17349 {
17350 switch (cmd) {
17351 case CLI_INIT:
17352 e->command = "sip qualify peer";
17353 e->usage =
17354 "Usage: sip qualify peer <name> [load]\n"
17355 " Requests a response from one SIP peer and the current status.\n"
17356 " Option \"load\" forces lookup of peer in realtime storage.\n";
17357 return NULL;
17358 case CLI_GENERATE:
17359 return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
17360 }
17361 return _sip_qualify_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
17362 }
17363
17364
17365 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer)
17366 {
17367 struct sip_mailbox *mailbox;
17368
17369 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
17370 ast_str_append(mailbox_str, 0, "%s%s%s%s",
17371 mailbox->mailbox,
17372 ast_strlen_zero(mailbox->context) ? "" : "@",
17373 S_OR(mailbox->context, ""),
17374 AST_LIST_NEXT(mailbox, entry) ? "," : "");
17375 }
17376 }
17377
17378 static struct _map_x_s faxecmodes[] = {
17379 { SIP_PAGE2_T38SUPPORT_UDPTL, "None"},
17380 { SIP_PAGE2_T38SUPPORT_UDPTL_FEC, "FEC"},
17381 { SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY, "Redundancy"},
17382 { -1, NULL},
17383 };
17384
17385 static const char *faxec2str(int faxec)
17386 {
17387 return map_x_s(faxecmodes, faxec, "Unknown");
17388 }
17389
17390
17391 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
17392 {
17393 char status[30] = "";
17394 char cbuf[256];
17395 struct sip_peer *peer;
17396 char codec_buf[512];
17397 struct ast_codec_pref *pref;
17398 struct ast_variable *v;
17399 int x = 0, load_realtime;
17400 format_t codec = 0;
17401 int realtimepeers;
17402
17403 realtimepeers = ast_check_realtime("sippeers");
17404
17405 if (argc < 4)
17406 return CLI_SHOWUSAGE;
17407
17408 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
17409 peer = find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0);
17410
17411 if (s) {
17412 if (peer) {
17413 const char *id = astman_get_header(m, "ActionID");
17414
17415 astman_append(s, "Response: Success\r\n");
17416 if (!ast_strlen_zero(id))
17417 astman_append(s, "ActionID: %s\r\n", id);
17418 } else {
17419 snprintf (cbuf, sizeof(cbuf), "Peer %s not found.", argv[3]);
17420 astman_send_error(s, m, cbuf);
17421 return CLI_SUCCESS;
17422 }
17423 }
17424 if (peer && type==0 ) {
17425 struct ast_str *mailbox_str = ast_str_alloca(512);
17426 struct sip_auth_container *credentials;
17427
17428 ao2_lock(peer);
17429 credentials = peer->auth;
17430 if (credentials) {
17431 ao2_t_ref(credentials, +1, "Ref peer auth for show");
17432 }
17433 ao2_unlock(peer);
17434
17435 ast_cli(fd, "\n\n");
17436 ast_cli(fd, " * Name : %s\n", peer->name);
17437 if (realtimepeers) {
17438 ast_cli(fd, " Realtime peer: %s\n", peer->is_realtime ? "Yes, cached" : "No");
17439 }
17440 ast_cli(fd, " Secret : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
17441 ast_cli(fd, " MD5Secret : %s\n", ast_strlen_zero(peer->md5secret)?"<Not set>":"<Set>");
17442 ast_cli(fd, " Remote Secret: %s\n", ast_strlen_zero(peer->remotesecret)?"<Not set>":"<Set>");
17443 if (credentials) {
17444 struct sip_auth *auth;
17445
17446 AST_LIST_TRAVERSE(&credentials->list, auth, node) {
17447 ast_cli(fd, " Realm-auth : Realm %-15.15s User %-10.20s %s\n",
17448 auth->realm,
17449 auth->username,
17450 !ast_strlen_zero(auth->secret)
17451 ? "<Secret set>"
17452 : (!ast_strlen_zero(auth->md5secret)
17453 ? "<MD5secret set>" : "<Not set>"));
17454 }
17455 ao2_t_ref(credentials, -1, "Unref peer auth for show");
17456 }
17457 ast_cli(fd, " Context : %s\n", peer->context);
17458 ast_cli(fd, " Subscr.Cont. : %s\n", S_OR(peer->subscribecontext, "<Not set>") );
17459 ast_cli(fd, " Language : %s\n", peer->language);
17460 if (!ast_strlen_zero(peer->accountcode))
17461 ast_cli(fd, " Accountcode : %s\n", peer->accountcode);
17462 ast_cli(fd, " AMA flags : %s\n", ast_cdr_flags2str(peer->amaflags));
17463 ast_cli(fd, " Transfer mode: %s\n", transfermode2str(peer->allowtransfer));
17464 ast_cli(fd, " CallingPres : %s\n", ast_describe_caller_presentation(peer->callingpres));
17465 if (!ast_strlen_zero(peer->fromuser))
17466 ast_cli(fd, " FromUser : %s\n", peer->fromuser);
17467 if (!ast_strlen_zero(peer->fromdomain))
17468 ast_cli(fd, " FromDomain : %s Port %d\n", peer->fromdomain, (peer->fromdomainport) ? peer->fromdomainport : STANDARD_SIP_PORT);
17469 ast_cli(fd, " Callgroup : ");
17470 print_group(fd, peer->callgroup, 0);
17471 ast_cli(fd, " Pickupgroup : ");
17472 print_group(fd, peer->pickupgroup, 0);
17473 peer_mailboxes_to_str(&mailbox_str, peer);
17474 ast_cli(fd, " MOH Suggest : %s\n", peer->mohsuggest);
17475 ast_cli(fd, " Mailbox : %s\n", mailbox_str->str);
17476 ast_cli(fd, " VM Extension : %s\n", peer->vmexten);
17477 ast_cli(fd, " LastMsgsSent : %d/%d\n", (peer->lastmsgssent & 0x7fff0000) >> 16, peer->lastmsgssent & 0xffff);
17478 ast_cli(fd, " Call limit : %d\n", peer->call_limit);
17479 ast_cli(fd, " Max forwards : %d\n", peer->maxforwards);
17480 if (peer->busy_level)
17481 ast_cli(fd, " Busy level : %d\n", peer->busy_level);
17482 ast_cli(fd, " Dynamic : %s\n", AST_CLI_YESNO(peer->host_dynamic));
17483 ast_cli(fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
17484 ast_cli(fd, " MaxCallBR : %d kbps\n", peer->maxcallbitrate);
17485 ast_cli(fd, " Expire : %ld\n", ast_sched_when(sched, peer->expire));
17486 ast_cli(fd, " Insecure : %s\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
17487 ast_cli(fd, " Force rport : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT)));
17488 ast_cli(fd, " ACL : %s\n", AST_CLI_YESNO(peer->ha != NULL));
17489 ast_cli(fd, " DirectMedACL : %s\n", AST_CLI_YESNO(peer->directmediaha != NULL));
17490 ast_cli(fd, " T.38 support : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
17491 ast_cli(fd, " T.38 EC mode : %s\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
17492 ast_cli(fd, " T.38 MaxDtgrm: %d\n", peer->t38_maxdatagram);
17493 ast_cli(fd, " DirectMedia : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)));
17494 ast_cli(fd, " PromiscRedir : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)));
17495 ast_cli(fd, " User=Phone : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)));
17496 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)));
17497 ast_cli(fd, " Text Support : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)));
17498 ast_cli(fd, " Ign SDP ver : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_IGNORESDPVERSION)));
17499 ast_cli(fd, " Trust RPID : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_TRUSTRPID)));
17500 ast_cli(fd, " Send RPID : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_SENDRPID)));
17501 ast_cli(fd, " Subscriptions: %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
17502 ast_cli(fd, " Overlap dial : %s\n", allowoverlap2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWOVERLAP)));
17503 if (peer->outboundproxy)
17504 ast_cli(fd, " Outb. proxy : %s %s\n", ast_strlen_zero(peer->outboundproxy->name) ? "<not set>" : peer->outboundproxy->name,
17505 peer->outboundproxy->force ? "(forced)" : "");
17506
17507
17508 ast_cli(fd, " DTMFmode : %s\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
17509 ast_cli(fd, " Timer T1 : %d\n", peer->timer_t1);
17510 ast_cli(fd, " Timer B : %d\n", peer->timer_b);
17511 ast_cli(fd, " ToHost : %s\n", peer->tohost);
17512 ast_cli(fd, " Addr->IP : %s\n", ast_sockaddr_stringify(&peer->addr));
17513 ast_cli(fd, " Defaddr->IP : %s\n", ast_sockaddr_stringify(&peer->defaddr));
17514 ast_cli(fd, " Prim.Transp. : %s\n", get_transport(peer->socket.type));
17515 ast_cli(fd, " Allowed.Trsp : %s\n", get_transport_list(peer->transports));
17516 if (!ast_strlen_zero(sip_cfg.regcontext))
17517 ast_cli(fd, " Reg. exten : %s\n", peer->regexten);
17518 ast_cli(fd, " Def. Username: %s\n", peer->username);
17519 ast_cli(fd, " SIP Options : ");
17520 if (peer->sipoptions) {
17521 int lastoption = -1;
17522 for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
17523 if (sip_options[x].id != lastoption) {
17524 if (peer->sipoptions & sip_options[x].id)
17525 ast_cli(fd, "%s ", sip_options[x].text);
17526 lastoption = x;
17527 }
17528 }
17529 } else
17530 ast_cli(fd, "(none)");
17531
17532 ast_cli(fd, "\n");
17533 ast_cli(fd, " Codecs : ");
17534 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
17535 ast_cli(fd, "%s\n", codec_buf);
17536 ast_cli(fd, " Codec Order : (");
17537 print_codec_to_cli(fd, &peer->prefs);
17538 ast_cli(fd, ")\n");
17539
17540 ast_cli(fd, " Auto-Framing : %s \n", AST_CLI_YESNO(peer->autoframing));
17541 ast_cli(fd, " Status : ");
17542 peer_status(peer, status, sizeof(status));
17543 ast_cli(fd, "%s\n", status);
17544 ast_cli(fd, " Useragent : %s\n", peer->useragent);
17545 ast_cli(fd, " Reg. Contact : %s\n", peer->fullcontact);
17546 ast_cli(fd, " Qualify Freq : %d ms\n", peer->qualifyfreq);
17547 if (peer->chanvars) {
17548 ast_cli(fd, " Variables :\n");
17549 for (v = peer->chanvars ; v ; v = v->next)
17550 ast_cli(fd, " %s = %s\n", v->name, v->value);
17551 }
17552
17553 ast_cli(fd, " Sess-Timers : %s\n", stmode2str(peer->stimer.st_mode_oper));
17554 ast_cli(fd, " Sess-Refresh : %s\n", strefresher2str(peer->stimer.st_ref));
17555 ast_cli(fd, " Sess-Expires : %d secs\n", peer->stimer.st_max_se);
17556 ast_cli(fd, " Min-Sess : %d secs\n", peer->stimer.st_min_se);
17557 ast_cli(fd, " RTP Engine : %s\n", peer->engine);
17558 ast_cli(fd, " Parkinglot : %s\n", peer->parkinglot);
17559 ast_cli(fd, " Use Reason : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_Q850_REASON)));
17560 ast_cli(fd, " Encryption : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_USE_SRTP)));
17561 ast_cli(fd, "\n");
17562 peer = unref_peer(peer, "sip_show_peer: unref_peer: done with peer ptr");
17563 } else if (peer && type == 1) {
17564 char buffer[256];
17565 struct ast_str *mailbox_str = ast_str_alloca(512);
17566 astman_append(s, "Channeltype: SIP\r\n");
17567 astman_append(s, "ObjectName: %s\r\n", peer->name);
17568 astman_append(s, "ChanObjectType: peer\r\n");
17569 astman_append(s, "SecretExist: %s\r\n", ast_strlen_zero(peer->secret)?"N":"Y");
17570 astman_append(s, "RemoteSecretExist: %s\r\n", ast_strlen_zero(peer->remotesecret)?"N":"Y");
17571 astman_append(s, "MD5SecretExist: %s\r\n", ast_strlen_zero(peer->md5secret)?"N":"Y");
17572 astman_append(s, "Context: %s\r\n", peer->context);
17573 astman_append(s, "Language: %s\r\n", peer->language);
17574 if (!ast_strlen_zero(peer->accountcode))
17575 astman_append(s, "Accountcode: %s\r\n", peer->accountcode);
17576 astman_append(s, "AMAflags: %s\r\n", ast_cdr_flags2str(peer->amaflags));
17577 astman_append(s, "CID-CallingPres: %s\r\n", ast_describe_caller_presentation(peer->callingpres));
17578 if (!ast_strlen_zero(peer->fromuser))
17579 astman_append(s, "SIP-FromUser: %s\r\n", peer->fromuser);
17580 if (!ast_strlen_zero(peer->fromdomain))
17581 astman_append(s, "SIP-FromDomain: %s\r\nSip-FromDomain-Port: %d\r\n", peer->fromdomain, (peer->fromdomainport) ? peer->fromdomainport : STANDARD_SIP_PORT);
17582 astman_append(s, "Callgroup: ");
17583 astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->callgroup));
17584 astman_append(s, "Pickupgroup: ");
17585 astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->pickupgroup));
17586 astman_append(s, "MOHSuggest: %s\r\n", peer->mohsuggest);
17587 peer_mailboxes_to_str(&mailbox_str, peer);
17588 astman_append(s, "VoiceMailbox: %s\r\n", mailbox_str->str);
17589 astman_append(s, "TransferMode: %s\r\n", transfermode2str(peer->allowtransfer));
17590 astman_append(s, "LastMsgsSent: %d\r\n", peer->lastmsgssent);
17591 astman_append(s, "Maxforwards: %d\r\n", peer->maxforwards);
17592 astman_append(s, "Call-limit: %d\r\n", peer->call_limit);
17593 astman_append(s, "Busy-level: %d\r\n", peer->busy_level);
17594 astman_append(s, "MaxCallBR: %d kbps\r\n", peer->maxcallbitrate);
17595 astman_append(s, "Dynamic: %s\r\n", peer->host_dynamic?"Y":"N");
17596 astman_append(s, "Callerid: %s\r\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, ""));
17597 astman_append(s, "RegExpire: %ld seconds\r\n", ast_sched_when(sched, peer->expire));
17598 astman_append(s, "SIP-AuthInsecure: %s\r\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
17599 astman_append(s, "SIP-Forcerport: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT)?"Y":"N"));
17600 astman_append(s, "ACL: %s\r\n", (peer->ha?"Y":"N"));
17601 astman_append(s, "SIP-CanReinvite: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)?"Y":"N"));
17602 astman_append(s, "SIP-DirectMedia: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)?"Y":"N"));
17603 astman_append(s, "SIP-PromiscRedir: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)?"Y":"N"));
17604 astman_append(s, "SIP-UserPhone: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)?"Y":"N"));
17605 astman_append(s, "SIP-VideoSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)?"Y":"N"));
17606 astman_append(s, "SIP-TextSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)?"Y":"N"));
17607 astman_append(s, "SIP-T.38Support: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)?"Y":"N"));
17608 astman_append(s, "SIP-T.38EC: %s\r\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
17609 astman_append(s, "SIP-T.38MaxDtgrm: %d\r\n", peer->t38_maxdatagram);
17610 astman_append(s, "SIP-Sess-Timers: %s\r\n", stmode2str(peer->stimer.st_mode_oper));
17611 astman_append(s, "SIP-Sess-Refresh: %s\r\n", strefresher2str(peer->stimer.st_ref));
17612 astman_append(s, "SIP-Sess-Expires: %d\r\n", peer->stimer.st_max_se);
17613 astman_append(s, "SIP-Sess-Min: %d\r\n", peer->stimer.st_min_se);
17614 astman_append(s, "SIP-RTP-Engine: %s\r\n", peer->engine);
17615 astman_append(s, "SIP-Encryption: %s\r\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_USE_SRTP) ? "Y" : "N");
17616
17617
17618 astman_append(s, "SIP-DTMFmode: %s\r\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
17619 astman_append(s, "ToHost: %s\r\n", peer->tohost);
17620 astman_append(s, "Address-IP: %s\r\nAddress-Port: %d\r\n", ast_sockaddr_stringify_addr(&peer->addr), ast_sockaddr_port(&peer->addr));
17621 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));
17622 astman_append(s, "Default-Username: %s\r\n", peer->username);
17623 if (!ast_strlen_zero(sip_cfg.regcontext))
17624 astman_append(s, "RegExtension: %s\r\n", peer->regexten);
17625 astman_append(s, "Codecs: ");
17626 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
17627 astman_append(s, "%s\r\n", codec_buf);
17628 astman_append(s, "CodecOrder: ");
17629 pref = &peer->prefs;
17630 for(x = 0; x < 64 ; x++) {
17631 codec = ast_codec_pref_index(pref, x);
17632 if (!codec)
17633 break;
17634 astman_append(s, "%s", ast_getformatname(codec));
17635 if (x < 63 && ast_codec_pref_index(pref, x+1))
17636 astman_append(s, ",");
17637 }
17638
17639 astman_append(s, "\r\n");
17640 astman_append(s, "Status: ");
17641 peer_status(peer, status, sizeof(status));
17642 astman_append(s, "%s\r\n", status);
17643 astman_append(s, "SIP-Useragent: %s\r\n", peer->useragent);
17644 astman_append(s, "Reg-Contact: %s\r\n", peer->fullcontact);
17645 astman_append(s, "QualifyFreq: %d ms\r\n", peer->qualifyfreq);
17646 astman_append(s, "Parkinglot: %s\r\n", peer->parkinglot);
17647 if (peer->chanvars) {
17648 for (v = peer->chanvars ; v ; v = v->next) {
17649 astman_append(s, "ChanVariable: %s=%s\r\n", v->name, v->value);
17650 }
17651 }
17652 astman_append(s, "SIP-Use-Reason-Header: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_Q850_REASON)) ? "Y" : "N");
17653
17654 peer = unref_peer(peer, "sip_show_peer: unref_peer: done with peer");
17655
17656 } else {
17657 ast_cli(fd, "Peer %s not found.\n", argv[3]);
17658 ast_cli(fd, "\n");
17659 }
17660
17661 return CLI_SUCCESS;
17662 }
17663
17664
17665 static char *complete_sip_user(const char *word, int state)
17666 {
17667 char *result = NULL;
17668 int wordlen = strlen(word);
17669 int which = 0;
17670 struct ao2_iterator user_iter;
17671 struct sip_peer *user;
17672
17673 user_iter = ao2_iterator_init(peers, 0);
17674 while ((user = ao2_t_iterator_next(&user_iter, "iterate thru peers table"))) {
17675 ao2_lock(user);
17676 if (!(user->type & SIP_TYPE_USER)) {
17677 ao2_unlock(user);
17678 unref_peer(user, "complete sip user");
17679 continue;
17680 }
17681
17682 if (!strncasecmp(word, user->name, wordlen) && ++which > state) {
17683 result = ast_strdup(user->name);
17684 }
17685 ao2_unlock(user);
17686 unref_peer(user, "complete sip user");
17687 if (result) {
17688 break;
17689 }
17690 }
17691 ao2_iterator_destroy(&user_iter);
17692 return result;
17693 }
17694
17695 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state)
17696 {
17697 if (pos == 3)
17698 return complete_sip_user(word, state);
17699
17700 return NULL;
17701 }
17702
17703
17704 static char *sip_show_user(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17705 {
17706 char cbuf[256];
17707 struct sip_peer *user;
17708 struct ast_variable *v;
17709 int load_realtime;
17710
17711 switch (cmd) {
17712 case CLI_INIT:
17713 e->command = "sip show user";
17714 e->usage =
17715 "Usage: sip show user <name> [load]\n"
17716 " Shows all details on one SIP user and the current status.\n"
17717 " Option \"load\" forces lookup of peer in realtime storage.\n";
17718 return NULL;
17719 case CLI_GENERATE:
17720 return complete_sip_show_user(a->line, a->word, a->pos, a->n);
17721 }
17722
17723 if (a->argc < 4)
17724 return CLI_SHOWUSAGE;
17725
17726
17727 load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? TRUE : FALSE;
17728
17729 if ((user = find_peer(a->argv[3], NULL, load_realtime, FINDUSERS, FALSE, 0))) {
17730 ao2_lock(user);
17731 ast_cli(a->fd, "\n\n");
17732 ast_cli(a->fd, " * Name : %s\n", user->name);
17733 ast_cli(a->fd, " Secret : %s\n", ast_strlen_zero(user->secret)?"<Not set>":"<Set>");
17734 ast_cli(a->fd, " MD5Secret : %s\n", ast_strlen_zero(user->md5secret)?"<Not set>":"<Set>");
17735 ast_cli(a->fd, " Context : %s\n", user->context);
17736 ast_cli(a->fd, " Language : %s\n", user->language);
17737 if (!ast_strlen_zero(user->accountcode))
17738 ast_cli(a->fd, " Accountcode : %s\n", user->accountcode);
17739 ast_cli(a->fd, " AMA flags : %s\n", ast_cdr_flags2str(user->amaflags));
17740 ast_cli(a->fd, " Transfer mode: %s\n", transfermode2str(user->allowtransfer));
17741 ast_cli(a->fd, " MaxCallBR : %d kbps\n", user->maxcallbitrate);
17742 ast_cli(a->fd, " CallingPres : %s\n", ast_describe_caller_presentation(user->callingpres));
17743 ast_cli(a->fd, " Call limit : %d\n", user->call_limit);
17744 ast_cli(a->fd, " Callgroup : ");
17745 print_group(a->fd, user->callgroup, 0);
17746 ast_cli(a->fd, " Pickupgroup : ");
17747 print_group(a->fd, user->pickupgroup, 0);
17748 ast_cli(a->fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), user->cid_name, user->cid_num, "<unspecified>"));
17749 ast_cli(a->fd, " ACL : %s\n", AST_CLI_YESNO(user->ha != NULL));
17750 ast_cli(a->fd, " Sess-Timers : %s\n", stmode2str(user->stimer.st_mode_oper));
17751 ast_cli(a->fd, " Sess-Refresh : %s\n", strefresher2str(user->stimer.st_ref));
17752 ast_cli(a->fd, " Sess-Expires : %d secs\n", user->stimer.st_max_se);
17753 ast_cli(a->fd, " Sess-Min-SE : %d secs\n", user->stimer.st_min_se);
17754 ast_cli(a->fd, " RTP Engine : %s\n", user->engine);
17755
17756 ast_cli(a->fd, " Codec Order : (");
17757 print_codec_to_cli(a->fd, &user->prefs);
17758 ast_cli(a->fd, ")\n");
17759
17760 ast_cli(a->fd, " Auto-Framing: %s \n", AST_CLI_YESNO(user->autoframing));
17761 if (user->chanvars) {
17762 ast_cli(a->fd, " Variables :\n");
17763 for (v = user->chanvars ; v ; v = v->next)
17764 ast_cli(a->fd, " %s = %s\n", v->name, v->value);
17765 }
17766
17767 ast_cli(a->fd, "\n");
17768
17769 ao2_unlock(user);
17770 unref_peer(user, "sip show user");
17771 } else {
17772 ast_cli(a->fd, "User %s not found.\n", a->argv[3]);
17773 ast_cli(a->fd, "\n");
17774 }
17775
17776 return CLI_SUCCESS;
17777 }
17778
17779
17780 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17781 {
17782 struct ast_str *cbuf;
17783 struct ast_cb_names cbnames = {9, { "retrans_pkt",
17784 "__sip_autodestruct",
17785 "expire_register",
17786 "auto_congest",
17787 "sip_reg_timeout",
17788 "sip_poke_peer_s",
17789 "sip_poke_noanswer",
17790 "sip_reregister",
17791 "sip_reinvite_retry"},
17792 { retrans_pkt,
17793 __sip_autodestruct,
17794 expire_register,
17795 auto_congest,
17796 sip_reg_timeout,
17797 sip_poke_peer_s,
17798 sip_poke_noanswer,
17799 sip_reregister,
17800 sip_reinvite_retry}};
17801
17802 switch (cmd) {
17803 case CLI_INIT:
17804 e->command = "sip show sched";
17805 e->usage =
17806 "Usage: sip show sched\n"
17807 " Shows stats on what's in the sched queue at the moment\n";
17808 return NULL;
17809 case CLI_GENERATE:
17810 return NULL;
17811 }
17812
17813 cbuf = ast_str_alloca(2048);
17814
17815 ast_cli(a->fd, "\n");
17816 ast_sched_report(sched, &cbuf, &cbnames);
17817 ast_cli(a->fd, "%s", cbuf->str);
17818
17819 return CLI_SUCCESS;
17820 }
17821
17822
17823 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17824 {
17825 #define FORMAT2 "%-39.39s %-6.6s %-12.12s %8.8s %-20.20s %-25.25s\n"
17826 #define FORMAT "%-39.39s %-6.6s %-12.12s %8d %-20.20s %-25.25s\n"
17827 char host[80];
17828 char user[80];
17829 char tmpdat[256];
17830 struct ast_tm tm;
17831 int counter = 0;
17832
17833 switch (cmd) {
17834 case CLI_INIT:
17835 e->command = "sip show registry";
17836 e->usage =
17837 "Usage: sip show registry\n"
17838 " Lists all registration requests and status.\n";
17839 return NULL;
17840 case CLI_GENERATE:
17841 return NULL;
17842 }
17843
17844 if (a->argc != 3)
17845 return CLI_SHOWUSAGE;
17846 ast_cli(a->fd, FORMAT2, "Host", "dnsmgr", "Username", "Refresh", "State", "Reg.Time");
17847
17848 ASTOBJ_CONTAINER_TRAVERSE(®l, 1, do {
17849 ASTOBJ_RDLOCK(iterator);
17850 snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
17851 snprintf(user, sizeof(user), "%s", iterator->username);
17852 if (!ast_strlen_zero(iterator->regdomain)) {
17853 snprintf(tmpdat, sizeof(tmpdat), "%s", user);
17854 snprintf(user, sizeof(user), "%s@%s", tmpdat, iterator->regdomain);}
17855 if (iterator->regdomainport) {
17856 snprintf(tmpdat, sizeof(tmpdat), "%s", user);
17857 snprintf(user, sizeof(user), "%s:%d", tmpdat, iterator->regdomainport);}
17858 if (iterator->regtime.tv_sec) {
17859 ast_localtime(&iterator->regtime, &tm, NULL);
17860 ast_strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T", &tm);
17861 } else
17862 tmpdat[0] = '\0';
17863 ast_cli(a->fd, FORMAT, host, (iterator->dnsmgr) ? "Y" : "N", user, iterator->refresh, regstate2str(iterator->regstate), tmpdat);
17864 ASTOBJ_UNLOCK(iterator);
17865 counter++;
17866 } while(0));
17867 ast_cli(a->fd, "%d SIP registrations.\n", counter);
17868 return CLI_SUCCESS;
17869 #undef FORMAT
17870 #undef FORMAT2
17871 }
17872
17873
17874
17875
17876
17877 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17878 {
17879 struct sip_peer *peer;
17880 int load_realtime = 0;
17881
17882 switch (cmd) {
17883 case CLI_INIT:
17884 e->command = "sip unregister";
17885 e->usage =
17886 "Usage: sip unregister <peer>\n"
17887 " Unregister (force expiration) a SIP peer from the registry\n";
17888 return NULL;
17889 case CLI_GENERATE:
17890 return complete_sip_unregister(a->line, a->word, a->pos, a->n);
17891 }
17892
17893 if (a->argc != 3)
17894 return CLI_SHOWUSAGE;
17895
17896 if ((peer = find_peer(a->argv[2], NULL, load_realtime, FINDPEERS, TRUE, 0))) {
17897 if (peer->expire > 0) {
17898 AST_SCHED_DEL_UNREF(sched, peer->expire,
17899 unref_peer(peer, "remove register expire ref"));
17900 expire_register(ref_peer(peer, "ref for expire_register"));
17901 ast_cli(a->fd, "Unregistered peer \'%s\'\n\n", a->argv[2]);
17902 } else {
17903 ast_cli(a->fd, "Peer %s not registered\n", a->argv[2]);
17904 }
17905 unref_peer(peer, "sip_unregister: unref_peer via sip_unregister: done with peer from find_peer call");
17906 } else {
17907 ast_cli(a->fd, "Peer unknown: \'%s\'. Not unregistered.\n", a->argv[2]);
17908 }
17909
17910 return CLI_SUCCESS;
17911 }
17912
17913
17914 static int show_chanstats_cb(void *__cur, void *__arg, int flags)
17915 {
17916 #define FORMAT2 "%-15.15s %-11.11s %-8.8s %-10.10s %-10.10s ( %%) %-6.6s %-10.10s %-10.10s ( %%) %-6.6s\n"
17917 #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"
17918 struct sip_pvt *cur = __cur;
17919 struct ast_rtp_instance_stats stats;
17920 char durbuf[10];
17921 int duration;
17922 int durh, durm, durs;
17923 struct ast_channel *c = cur->owner;
17924 struct __show_chan_arg *arg = __arg;
17925 int fd = arg->fd;
17926
17927
17928 if (cur->subscribed != NONE)
17929 return 0;
17930
17931 if (!cur->rtp) {
17932 if (sipdebug) {
17933 ast_cli(fd, "%-15.15s %-11.11s (inv state: %s) -- %s\n",
17934 ast_sockaddr_stringify_addr(&cur->sa), cur->callid,
17935 invitestate2string[cur->invitestate].desc,
17936 "-- No RTP active");
17937 }
17938 return 0;
17939 }
17940
17941 ast_rtp_instance_get_stats(cur->rtp, &stats, AST_RTP_INSTANCE_STAT_ALL);
17942
17943 if (c && c->cdr && !ast_tvzero(c->cdr->start)) {
17944 duration = (int)(ast_tvdiff_ms(ast_tvnow(), c->cdr->start) / 1000);
17945 durh = duration / 3600;
17946 durm = (duration % 3600) / 60;
17947 durs = duration % 60;
17948 snprintf(durbuf, sizeof(durbuf), "%02d:%02d:%02d", durh, durm, durs);
17949 } else {
17950 durbuf[0] = '\0';
17951 }
17952
17953 ast_cli(fd, FORMAT,
17954 ast_sockaddr_stringify_addr(&cur->sa),
17955 cur->callid,
17956 durbuf,
17957 stats.rxcount > (unsigned int) 100000 ? (unsigned int) (stats.rxcount)/(unsigned int) 1000 : stats.rxcount,
17958 stats.rxcount > (unsigned int) 100000 ? "K":" ",
17959 stats.rxploss,
17960 (stats.rxcount + stats.rxploss) > 0 ? (double) stats.rxploss / (stats.rxcount + stats.rxploss) * 100 : 0,
17961 stats.rxjitter,
17962 stats.txcount > (unsigned int) 100000 ? (unsigned int) (stats.txcount)/(unsigned int) 1000 : stats.txcount,
17963 stats.txcount > (unsigned int) 100000 ? "K":" ",
17964 stats.txploss,
17965 stats.txcount > 0 ? (double) stats.txploss / stats.txcount * 100 : 0,
17966 stats.txjitter
17967 );
17968 arg->numchans++;
17969
17970 return 0;
17971 }
17972
17973
17974 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17975 {
17976 struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
17977
17978 switch (cmd) {
17979 case CLI_INIT:
17980 e->command = "sip show channelstats";
17981 e->usage =
17982 "Usage: sip show channelstats\n"
17983 " Lists all currently active SIP channel's RTCP statistics.\n"
17984 " Note that calls in the much optimized RTP P2P bridge mode will not show any packets here.";
17985 return NULL;
17986 case CLI_GENERATE:
17987 return NULL;
17988 }
17989
17990 if (a->argc != 3)
17991 return CLI_SHOWUSAGE;
17992
17993 ast_cli(a->fd, FORMAT2, "Peer", "Call ID", "Duration", "Recv: Pack", "Lost", "Jitter", "Send: Pack", "Lost", "Jitter");
17994
17995 ao2_t_callback(dialogs, OBJ_NODATA, show_chanstats_cb, &arg, "callback to sip show chanstats");
17996 ast_cli(a->fd, "%d active SIP channel%s\n", arg.numchans, (arg.numchans != 1) ? "s" : "");
17997 return CLI_SUCCESS;
17998 }
17999 #undef FORMAT
18000 #undef FORMAT2
18001
18002
18003 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18004 {
18005 int realtimepeers;
18006 int realtimeregs;
18007 char codec_buf[SIPBUFSIZE];
18008 const char *msg;
18009 struct sip_auth_container *credentials;
18010
18011 switch (cmd) {
18012 case CLI_INIT:
18013 e->command = "sip show settings";
18014 e->usage =
18015 "Usage: sip show settings\n"
18016 " Provides detailed list of the configuration of the SIP channel.\n";
18017 return NULL;
18018 case CLI_GENERATE:
18019 return NULL;
18020 }
18021
18022 if (a->argc != 3)
18023 return CLI_SHOWUSAGE;
18024
18025 realtimepeers = ast_check_realtime("sippeers");
18026 realtimeregs = ast_check_realtime("sipregs");
18027
18028 ast_mutex_lock(&authl_lock);
18029 credentials = authl;
18030 if (credentials) {
18031 ao2_t_ref(credentials, +1, "Ref global auth for show");
18032 }
18033 ast_mutex_unlock(&authl_lock);
18034
18035 ast_cli(a->fd, "\n\nGlobal Settings:\n");
18036 ast_cli(a->fd, "----------------\n");
18037 ast_cli(a->fd, " UDP Bindaddress: %s\n", ast_sockaddr_stringify(&bindaddr));
18038 if (ast_sockaddr_is_ipv6(&bindaddr) && ast_sockaddr_is_any(&bindaddr)) {
18039 ast_cli(a->fd, " ** Additional Info:\n");
18040 ast_cli(a->fd, " [::] may include IPv4 in addition to IPv6, if such a feature is enabled in the OS.\n");
18041 }
18042 ast_cli(a->fd, " TCP SIP Bindaddress: %s\n",
18043 sip_cfg.tcp_enabled != FALSE ?
18044 ast_sockaddr_stringify(&sip_tcp_desc.local_address) :
18045 "Disabled");
18046 ast_cli(a->fd, " TLS SIP Bindaddress: %s\n",
18047 default_tls_cfg.enabled != FALSE ?
18048 ast_sockaddr_stringify(&sip_tls_desc.local_address) :
18049 "Disabled");
18050 ast_cli(a->fd, " Videosupport: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT)));
18051 ast_cli(a->fd, " Textsupport: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT)));
18052 ast_cli(a->fd, " Ignore SDP sess. ver.: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION)));
18053 ast_cli(a->fd, " AutoCreate Peer: %s\n", AST_CLI_YESNO(sip_cfg.autocreatepeer));
18054 ast_cli(a->fd, " Match Auth Username: %s\n", AST_CLI_YESNO(global_match_auth_username));
18055 ast_cli(a->fd, " Allow unknown access: %s\n", AST_CLI_YESNO(sip_cfg.allowguest));
18056 ast_cli(a->fd, " Allow subscriptions: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
18057 ast_cli(a->fd, " Allow overlap dialing: %s\n", allowoverlap2str(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP)));
18058 ast_cli(a->fd, " Allow promisc. redir: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_PROMISCREDIR)));
18059 ast_cli(a->fd, " Enable call counters: %s\n", AST_CLI_YESNO(global_callcounter));
18060 ast_cli(a->fd, " SIP domain support: %s\n", AST_CLI_YESNO(!AST_LIST_EMPTY(&domain_list)));
18061 ast_cli(a->fd, " Realm. auth: %s\n", AST_CLI_YESNO(credentials != NULL));
18062 if (credentials) {
18063 struct sip_auth *auth;
18064
18065 AST_LIST_TRAVERSE(&credentials->list, auth, node) {
18066 ast_cli(a->fd, " Realm. auth entry: Realm %-15.15s User %-10.20s %s\n",
18067 auth->realm,
18068 auth->username,
18069 !ast_strlen_zero(auth->secret)
18070 ? "<Secret set>"
18071 : (!ast_strlen_zero(auth->md5secret)
18072 ? "<MD5secret set>" : "<Not set>"));
18073 }
18074 ao2_t_ref(credentials, -1, "Unref global auth for show");
18075 }
18076 ast_cli(a->fd, " Our auth realm %s\n", sip_cfg.realm);
18077 ast_cli(a->fd, " Use domains as realms: %s\n", AST_CLI_YESNO(sip_cfg.domainsasrealm));
18078 ast_cli(a->fd, " Call to non-local dom.: %s\n", AST_CLI_YESNO(sip_cfg.allow_external_domains));
18079 ast_cli(a->fd, " URI user is phone no: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_USEREQPHONE)));
18080 ast_cli(a->fd, " Always auth rejects: %s\n", AST_CLI_YESNO(sip_cfg.alwaysauthreject));
18081 ast_cli(a->fd, " Direct RTP setup: %s\n", AST_CLI_YESNO(sip_cfg.directrtpsetup));
18082 ast_cli(a->fd, " User Agent: %s\n", global_useragent);
18083 ast_cli(a->fd, " SDP Session Name: %s\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
18084 ast_cli(a->fd, " SDP Owner Name: %s\n", ast_strlen_zero(global_sdpowner) ? "-" : global_sdpowner);
18085 ast_cli(a->fd, " Reg. context: %s\n", S_OR(sip_cfg.regcontext, "(not set)"));
18086 ast_cli(a->fd, " Regexten on Qualify: %s\n", AST_CLI_YESNO(sip_cfg.regextenonqualify));
18087 ast_cli(a->fd, " Legacy userfield parse: %s\n", AST_CLI_YESNO(sip_cfg.legacy_useroption_parsing));
18088 ast_cli(a->fd, " Caller ID: %s\n", default_callerid);
18089 if ((default_fromdomainport) && (default_fromdomainport != STANDARD_SIP_PORT)) {
18090 ast_cli(a->fd, " From: Domain: %s:%d\n", default_fromdomain, default_fromdomainport);
18091 } else {
18092 ast_cli(a->fd, " From: Domain: %s\n", default_fromdomain);
18093 }
18094 ast_cli(a->fd, " Record SIP history: %s\n", AST_CLI_ONOFF(recordhistory));
18095 ast_cli(a->fd, " Call Events: %s\n", AST_CLI_ONOFF(sip_cfg.callevents));
18096 ast_cli(a->fd, " Auth. Failure Events: %s\n", AST_CLI_ONOFF(global_authfailureevents));
18097
18098 ast_cli(a->fd, " T.38 support: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
18099 ast_cli(a->fd, " T.38 EC mode: %s\n", faxec2str(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
18100 ast_cli(a->fd, " T.38 MaxDtgrm: %d\n", global_t38_maxdatagram);
18101 if (!realtimepeers && !realtimeregs)
18102 ast_cli(a->fd, " SIP realtime: Disabled\n" );
18103 else
18104 ast_cli(a->fd, " SIP realtime: Enabled\n" );
18105 ast_cli(a->fd, " Qualify Freq : %d ms\n", global_qualifyfreq);
18106 ast_cli(a->fd, " Q.850 Reason header: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_Q850_REASON)));
18107 ast_cli(a->fd, " Store SIP_CAUSE: %s\n", AST_CLI_YESNO(global_store_sip_cause));
18108 ast_cli(a->fd, "\nNetwork QoS Settings:\n");
18109 ast_cli(a->fd, "---------------------------\n");
18110 ast_cli(a->fd, " IP ToS SIP: %s\n", ast_tos2str(global_tos_sip));
18111 ast_cli(a->fd, " IP ToS RTP audio: %s\n", ast_tos2str(global_tos_audio));
18112 ast_cli(a->fd, " IP ToS RTP video: %s\n", ast_tos2str(global_tos_video));
18113 ast_cli(a->fd, " IP ToS RTP text: %s\n", ast_tos2str(global_tos_text));
18114 ast_cli(a->fd, " 802.1p CoS SIP: %d\n", global_cos_sip);
18115 ast_cli(a->fd, " 802.1p CoS RTP audio: %d\n", global_cos_audio);
18116 ast_cli(a->fd, " 802.1p CoS RTP video: %d\n", global_cos_video);
18117 ast_cli(a->fd, " 802.1p CoS RTP text: %d\n", global_cos_text);
18118 ast_cli(a->fd, " Jitterbuffer enabled: %s\n", AST_CLI_YESNO(ast_test_flag(&global_jbconf, AST_JB_ENABLED)));
18119 if (ast_test_flag(&global_jbconf, AST_JB_ENABLED)) {
18120 ast_cli(a->fd, " Jitterbuffer forced: %s\n", AST_CLI_YESNO(ast_test_flag(&global_jbconf, AST_JB_FORCED)));
18121 ast_cli(a->fd, " Jitterbuffer max size: %ld\n", global_jbconf.max_size);
18122 ast_cli(a->fd, " Jitterbuffer resync: %ld\n", global_jbconf.resync_threshold);
18123 ast_cli(a->fd, " Jitterbuffer impl: %s\n", global_jbconf.impl);
18124 if (!strcasecmp(global_jbconf.impl, "adaptive")) {
18125 ast_cli(a->fd, " Jitterbuffer tgt extra: %ld\n", global_jbconf.target_extra);
18126 }
18127 ast_cli(a->fd, " Jitterbuffer log: %s\n", AST_CLI_YESNO(ast_test_flag(&global_jbconf, AST_JB_LOG)));
18128 }
18129
18130 ast_cli(a->fd, "\nNetwork Settings:\n");
18131 ast_cli(a->fd, "---------------------------\n");
18132
18133 if (localaddr == NULL)
18134 msg = "Disabled, no localnet list";
18135 else if (ast_sockaddr_isnull(&externaddr))
18136 msg = "Disabled";
18137 else if (!ast_strlen_zero(externhost))
18138 msg = "Enabled using externhost";
18139 else
18140 msg = "Enabled using externaddr";
18141 ast_cli(a->fd, " SIP address remapping: %s\n", msg);
18142 ast_cli(a->fd, " Externhost: %s\n", S_OR(externhost, "<none>"));
18143 ast_cli(a->fd, " Externaddr: %s\n", ast_sockaddr_stringify(&externaddr));
18144 ast_cli(a->fd, " Externrefresh: %d\n", externrefresh);
18145 {
18146 struct ast_ha *d;
18147 const char *prefix = "Localnet:";
18148
18149 for (d = localaddr; d ; prefix = "", d = d->next) {
18150 const char *addr = ast_strdupa(ast_sockaddr_stringify_addr(&d->addr));
18151 const char *mask = ast_strdupa(ast_sockaddr_stringify_addr(&d->netmask));
18152 ast_cli(a->fd, " %-24s%s/%s\n", prefix, addr, mask);
18153 }
18154 }
18155 ast_cli(a->fd, "\nGlobal Signalling Settings:\n");
18156 ast_cli(a->fd, "---------------------------\n");
18157 ast_cli(a->fd, " Codecs: ");
18158 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, sip_cfg.capability);
18159 ast_cli(a->fd, "%s\n", codec_buf);
18160 ast_cli(a->fd, " Codec Order: ");
18161 print_codec_to_cli(a->fd, &default_prefs);
18162 ast_cli(a->fd, "\n");
18163 ast_cli(a->fd, " Relax DTMF: %s\n", AST_CLI_YESNO(global_relaxdtmf));
18164 ast_cli(a->fd, " RFC2833 Compensation: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_RFC2833_COMPENSATE)));
18165 ast_cli(a->fd, " Symmetric RTP: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_SYMMETRICRTP)));
18166 ast_cli(a->fd, " Compact SIP headers: %s\n", AST_CLI_YESNO(sip_cfg.compactheaders));
18167 ast_cli(a->fd, " RTP Keepalive: %d %s\n", global_rtpkeepalive, global_rtpkeepalive ? "" : "(Disabled)" );
18168 ast_cli(a->fd, " RTP Timeout: %d %s\n", global_rtptimeout, global_rtptimeout ? "" : "(Disabled)" );
18169 ast_cli(a->fd, " RTP Hold Timeout: %d %s\n", global_rtpholdtimeout, global_rtpholdtimeout ? "" : "(Disabled)");
18170 ast_cli(a->fd, " MWI NOTIFY mime type: %s\n", default_notifymime);
18171 ast_cli(a->fd, " DNS SRV lookup: %s\n", AST_CLI_YESNO(sip_cfg.srvlookup));
18172 ast_cli(a->fd, " Pedantic SIP support: %s\n", AST_CLI_YESNO(sip_cfg.pedanticsipchecking));
18173 ast_cli(a->fd, " Reg. min duration %d secs\n", min_expiry);
18174 ast_cli(a->fd, " Reg. max duration: %d secs\n", max_expiry);
18175 ast_cli(a->fd, " Reg. default duration: %d secs\n", default_expiry);
18176 ast_cli(a->fd, " Outbound reg. timeout: %d secs\n", global_reg_timeout);
18177 ast_cli(a->fd, " Outbound reg. attempts: %d\n", global_regattempts_max);
18178 ast_cli(a->fd, " Notify ringing state: %s\n", AST_CLI_YESNO(sip_cfg.notifyringing));
18179 if (sip_cfg.notifyringing) {
18180 ast_cli(a->fd, " Include CID: %s%s\n",
18181 AST_CLI_YESNO(sip_cfg.notifycid),
18182 sip_cfg.notifycid == IGNORE_CONTEXT ? " (Ignoring context)" : "");
18183 }
18184 ast_cli(a->fd, " Notify hold state: %s\n", AST_CLI_YESNO(sip_cfg.notifyhold));
18185 ast_cli(a->fd, " SIP Transfer mode: %s\n", transfermode2str(sip_cfg.allowtransfer));
18186 ast_cli(a->fd, " Max Call Bitrate: %d kbps\n", default_maxcallbitrate);
18187 ast_cli(a->fd, " Auto-Framing: %s\n", AST_CLI_YESNO(global_autoframing));
18188 ast_cli(a->fd, " Outb. proxy: %s %s\n", ast_strlen_zero(sip_cfg.outboundproxy.name) ? "<not set>" : sip_cfg.outboundproxy.name,
18189 sip_cfg.outboundproxy.force ? "(forced)" : "");
18190 ast_cli(a->fd, " Session Timers: %s\n", stmode2str(global_st_mode));
18191 ast_cli(a->fd, " Session Refresher: %s\n", strefresher2str (global_st_refresher));
18192 ast_cli(a->fd, " Session Expires: %d secs\n", global_max_se);
18193 ast_cli(a->fd, " Session Min-SE: %d secs\n", global_min_se);
18194 ast_cli(a->fd, " Timer T1: %d\n", global_t1);
18195 ast_cli(a->fd, " Timer T1 minimum: %d\n", global_t1min);
18196 ast_cli(a->fd, " Timer B: %d\n", global_timer_b);
18197 ast_cli(a->fd, " No premature media: %s\n", AST_CLI_YESNO(global_prematuremediafilter));
18198 ast_cli(a->fd, " Max forwards: %d\n", sip_cfg.default_max_forwards);
18199
18200 ast_cli(a->fd, "\nDefault Settings:\n");
18201 ast_cli(a->fd, "-----------------\n");
18202 ast_cli(a->fd, " Allowed transports: %s\n", get_transport_list(default_transports));
18203 ast_cli(a->fd, " Outbound transport: %s\n", get_transport(default_primary_transport));
18204 ast_cli(a->fd, " Context: %s\n", sip_cfg.default_context);
18205 ast_cli(a->fd, " Force rport: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_NAT_FORCE_RPORT)));
18206 ast_cli(a->fd, " DTMF: %s\n", dtmfmode2str(ast_test_flag(&global_flags[0], SIP_DTMF)));
18207 ast_cli(a->fd, " Qualify: %d\n", default_qualify);
18208 ast_cli(a->fd, " Use ClientCode: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_USECLIENTCODE)));
18209 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)));
18210 ast_cli(a->fd, " Language: %s\n", default_language);
18211 ast_cli(a->fd, " MOH Interpret: %s\n", default_mohinterpret);
18212 ast_cli(a->fd, " MOH Suggest: %s\n", default_mohsuggest);
18213 ast_cli(a->fd, " Voice Mail Extension: %s\n", default_vmexten);
18214
18215
18216 if (realtimepeers || realtimeregs) {
18217 ast_cli(a->fd, "\nRealtime SIP Settings:\n");
18218 ast_cli(a->fd, "----------------------\n");
18219 ast_cli(a->fd, " Realtime Peers: %s\n", AST_CLI_YESNO(realtimepeers));
18220 ast_cli(a->fd, " Realtime Regs: %s\n", AST_CLI_YESNO(realtimeregs));
18221 ast_cli(a->fd, " Cache Friends: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)));
18222 ast_cli(a->fd, " Update: %s\n", AST_CLI_YESNO(sip_cfg.peer_rtupdate));
18223 ast_cli(a->fd, " Ignore Reg. Expire: %s\n", AST_CLI_YESNO(sip_cfg.ignore_regexpire));
18224 ast_cli(a->fd, " Save sys. name: %s\n", AST_CLI_YESNO(sip_cfg.rtsave_sysname));
18225 ast_cli(a->fd, " Auto Clear: %d (%s)\n", sip_cfg.rtautoclear, ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR) ? "Enabled" : "Disabled");
18226 }
18227 ast_cli(a->fd, "\n----\n");
18228 return CLI_SUCCESS;
18229 }
18230
18231 static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18232 {
18233 #define FORMAT "%-30.30s %-12.12s %-10.10s %-10.10s\n"
18234 char host[80];
18235
18236 switch (cmd) {
18237 case CLI_INIT:
18238 e->command = "sip show mwi";
18239 e->usage =
18240 "Usage: sip show mwi\n"
18241 " Provides a list of MWI subscriptions and status.\n";
18242 return NULL;
18243 case CLI_GENERATE:
18244 return NULL;
18245 }
18246
18247 ast_cli(a->fd, FORMAT, "Host", "Username", "Mailbox", "Subscribed");
18248
18249 ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
18250 ASTOBJ_RDLOCK(iterator);
18251 snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
18252 ast_cli(a->fd, FORMAT, host, iterator->username, iterator->mailbox, AST_CLI_YESNO(iterator->subscribed));
18253 ASTOBJ_UNLOCK(iterator);
18254 } while(0));
18255
18256 return CLI_SUCCESS;
18257 #undef FORMAT
18258 }
18259
18260
18261
18262 static const char *subscription_type2str(enum subscriptiontype subtype)
18263 {
18264 int i;
18265
18266 for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
18267 if (subscription_types[i].type == subtype) {
18268 return subscription_types[i].text;
18269 }
18270 }
18271 return subscription_types[0].text;
18272 }
18273
18274
18275 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype)
18276 {
18277 int i;
18278
18279 for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
18280 if (subscription_types[i].type == subtype) {
18281 return &subscription_types[i];
18282 }
18283 }
18284 return &subscription_types[0];
18285 }
18286
18287
18288
18289
18290
18291
18292
18293
18294 #define FORMAT4 "%-15.15s %-15.15s %-15.15s %-15.15s %-13.13s %-15.15s %-10.10s %-6.6d\n"
18295 #define FORMAT3 "%-15.15s %-15.15s %-15.15s %-15.15s %-13.13s %-15.15s %-10.10s %-6.6s\n"
18296 #define FORMAT2 "%-15.15s %-15.15s %-15.15s %-15.15s %-7.7s %-15.15s %-10.10s %-10.10s\n"
18297 #define FORMAT "%-15.15s %-15.15s %-15.15s %-15.15s %-3.3s %-3.3s %-15.15s %-10.10s %-10.10s\n"
18298
18299
18300 static int show_channels_cb(void *__cur, void *__arg, int flags)
18301 {
18302 struct sip_pvt *cur = __cur;
18303 struct __show_chan_arg *arg = __arg;
18304 const struct ast_sockaddr *dst = sip_real_dst(cur);
18305
18306
18307 if (cur->subscribed == NONE && !arg->subscriptions) {
18308
18309 const char *referstatus = cur->refer ? referstatus2str(cur->refer->status) : "";
18310 char formatbuf[SIPBUFSIZE/2];
18311
18312 ast_cli(arg->fd, FORMAT, ast_sockaddr_stringify_addr(dst),
18313 S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
18314 cur->callid,
18315 ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0),
18316 AST_CLI_YESNO(ast_test_flag(&cur->flags[1], SIP_PAGE2_CALL_ONHOLD)),
18317 cur->needdestroy ? "(d)" : "",
18318 cur->lastmsg ,
18319 referstatus,
18320 cur->relatedpeer ? cur->relatedpeer->name : "<guest>"
18321 );
18322 arg->numchans++;
18323 }
18324 if (cur->subscribed != NONE && arg->subscriptions) {
18325 struct ast_str *mailbox_str = ast_str_alloca(512);
18326 if (cur->subscribed == MWI_NOTIFICATION && cur->relatedpeer)
18327 peer_mailboxes_to_str(&mailbox_str, cur->relatedpeer);
18328 ast_cli(arg->fd, FORMAT4, ast_sockaddr_stringify_addr(dst),
18329 S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
18330 cur->callid,
18331
18332 cur->subscribed == MWI_NOTIFICATION ? "--" : cur->subscribeuri,
18333 cur->subscribed == MWI_NOTIFICATION ? "<none>" : ast_extension_state2str(cur->laststate),
18334 subscription_type2str(cur->subscribed),
18335 cur->subscribed == MWI_NOTIFICATION ? S_OR(mailbox_str->str, "<none>") : "<none>",
18336 cur->expiry
18337 );
18338 arg->numchans++;
18339 }
18340 return 0;
18341 }
18342
18343
18344
18345
18346
18347
18348 static char *sip_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18349 {
18350 struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
18351
18352
18353 if (cmd == CLI_INIT) {
18354 e->command = "sip show {channels|subscriptions}";
18355 e->usage =
18356 "Usage: sip show channels\n"
18357 " Lists all currently active SIP calls (dialogs).\n"
18358 "Usage: sip show subscriptions\n"
18359 " Lists active SIP subscriptions.\n";
18360 return NULL;
18361 } else if (cmd == CLI_GENERATE)
18362 return NULL;
18363
18364 if (a->argc != e->args)
18365 return CLI_SHOWUSAGE;
18366 arg.subscriptions = !strcasecmp(a->argv[e->args - 1], "subscriptions");
18367 if (!arg.subscriptions)
18368 ast_cli(arg.fd, FORMAT2, "Peer", "User/ANR", "Call ID", "Format", "Hold", "Last Message", "Expiry", "Peer");
18369 else
18370 ast_cli(arg.fd, FORMAT3, "Peer", "User", "Call ID", "Extension", "Last state", "Type", "Mailbox", "Expiry");
18371
18372
18373 ao2_t_callback(dialogs, OBJ_NODATA, show_channels_cb, &arg, "callback to show channels");
18374
18375
18376 ast_cli(arg.fd, "%d active SIP %s%s\n", arg.numchans,
18377 (arg.subscriptions ? "subscription" : "dialog"),
18378 ESS(arg.numchans));
18379 return CLI_SUCCESS;
18380 #undef FORMAT
18381 #undef FORMAT2
18382 #undef FORMAT3
18383 }
18384
18385
18386
18387
18388
18389
18390 static char *complete_sipch(const char *line, const char *word, int pos, int state)
18391 {
18392 int which=0;
18393 struct sip_pvt *cur;
18394 char *c = NULL;
18395 int wordlen = strlen(word);
18396 struct ao2_iterator i;
18397
18398 if (pos != 3) {
18399 return NULL;
18400 }
18401
18402 i = ao2_iterator_init(dialogs, 0);
18403 while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
18404 sip_pvt_lock(cur);
18405 if (!strncasecmp(word, cur->callid, wordlen) && ++which > state) {
18406 c = ast_strdup(cur->callid);
18407 sip_pvt_unlock(cur);
18408 dialog_unref(cur, "drop ref in iterator loop break");
18409 break;
18410 }
18411 sip_pvt_unlock(cur);
18412 dialog_unref(cur, "drop ref in iterator loop");
18413 }
18414 ao2_iterator_destroy(&i);
18415 return c;
18416 }
18417
18418
18419
18420 static char *complete_sip_peer(const char *word, int state, int flags2)
18421 {
18422 char *result = NULL;
18423 int wordlen = strlen(word);
18424 int which = 0;
18425 struct ao2_iterator i = ao2_iterator_init(peers, 0);
18426 struct sip_peer *peer;
18427
18428 while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
18429
18430 if (!strncasecmp(word, peer->name, wordlen) &&
18431 (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
18432 ++which > state)
18433 result = ast_strdup(peer->name);
18434 unref_peer(peer, "toss iterator peer ptr before break");
18435 if (result) {
18436 break;
18437 }
18438 }
18439 ao2_iterator_destroy(&i);
18440 return result;
18441 }
18442
18443
18444 static char *complete_sip_registered_peer(const char *word, int state, int flags2)
18445 {
18446 char *result = NULL;
18447 int wordlen = strlen(word);
18448 int which = 0;
18449 struct ao2_iterator i;
18450 struct sip_peer *peer;
18451
18452 i = ao2_iterator_init(peers, 0);
18453 while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
18454 if (!strncasecmp(word, peer->name, wordlen) &&
18455 (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
18456 ++which > state && peer->expire > 0)
18457 result = ast_strdup(peer->name);
18458 if (result) {
18459 unref_peer(peer, "toss iterator peer ptr before break");
18460 break;
18461 }
18462 unref_peer(peer, "toss iterator peer ptr");
18463 }
18464 ao2_iterator_destroy(&i);
18465 return result;
18466 }
18467
18468
18469 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state)
18470 {
18471 if (pos == 3)
18472 return complete_sipch(line, word, pos, state);
18473
18474 return NULL;
18475 }
18476
18477
18478 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state)
18479 {
18480 if (pos == 3) {
18481 return complete_sip_peer(word, state, 0);
18482 }
18483
18484 return NULL;
18485 }
18486
18487
18488 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state)
18489 {
18490 if (pos == 2)
18491 return complete_sip_registered_peer(word, state, 0);
18492
18493 return NULL;
18494 }
18495
18496
18497 static char *complete_sipnotify(const char *line, const char *word, int pos, int state)
18498 {
18499 char *c = NULL;
18500
18501 if (pos == 2) {
18502 int which = 0;
18503 char *cat = NULL;
18504 int wordlen = strlen(word);
18505
18506
18507
18508 if (!notify_types)
18509 return NULL;
18510
18511 while ( (cat = ast_category_browse(notify_types, cat)) ) {
18512 if (!strncasecmp(word, cat, wordlen) && ++which > state) {
18513 c = ast_strdup(cat);
18514 break;
18515 }
18516 }
18517 return c;
18518 }
18519
18520 if (pos > 2)
18521 return complete_sip_peer(word, state, 0);
18522
18523 return NULL;
18524 }
18525
18526
18527 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18528 {
18529 struct sip_pvt *cur;
18530 size_t len;
18531 int found = 0;
18532 struct ao2_iterator i;
18533
18534 switch (cmd) {
18535 case CLI_INIT:
18536 e->command = "sip show channel";
18537 e->usage =
18538 "Usage: sip show channel <call-id>\n"
18539 " Provides detailed status on a given SIP dialog (identified by SIP call-id).\n";
18540 return NULL;
18541 case CLI_GENERATE:
18542 return complete_sipch(a->line, a->word, a->pos, a->n);
18543 }
18544
18545 if (a->argc != 4)
18546 return CLI_SHOWUSAGE;
18547 len = strlen(a->argv[3]);
18548
18549 i = ao2_iterator_init(dialogs, 0);
18550 while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
18551 sip_pvt_lock(cur);
18552
18553 if (!strncasecmp(cur->callid, a->argv[3], len)) {
18554 char formatbuf[SIPBUFSIZE/2];
18555 ast_cli(a->fd, "\n");
18556 if (cur->subscribed != NONE)
18557 ast_cli(a->fd, " * Subscription (type: %s)\n", subscription_type2str(cur->subscribed));
18558 else
18559 ast_cli(a->fd, " * SIP Call\n");
18560 ast_cli(a->fd, " Curr. trans. direction: %s\n", ast_test_flag(&cur->flags[0], SIP_OUTGOING) ? "Outgoing" : "Incoming");
18561 ast_cli(a->fd, " Call-ID: %s\n", cur->callid);
18562 ast_cli(a->fd, " Owner channel ID: %s\n", cur->owner ? cur->owner->name : "<none>");
18563 ast_cli(a->fd, " Our Codec Capability: %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->capability));
18564 ast_cli(a->fd, " Non-Codec Capability (DTMF): %d\n", cur->noncodeccapability);
18565 ast_cli(a->fd, " Their Codec Capability: %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->peercapability));
18566 ast_cli(a->fd, " Joint Codec Capability: %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->jointcapability));
18567 ast_cli(a->fd, " Format: %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0) );
18568 ast_cli(a->fd, " T.38 support %s\n", AST_CLI_YESNO(cur->udptl != NULL));
18569 ast_cli(a->fd, " Video support %s\n", AST_CLI_YESNO(cur->vrtp != NULL));
18570 ast_cli(a->fd, " MaxCallBR: %d kbps\n", cur->maxcallbitrate);
18571 ast_cli(a->fd, " Theoretical Address: %s\n", ast_sockaddr_stringify(&cur->sa));
18572 ast_cli(a->fd, " Received Address: %s\n", ast_sockaddr_stringify(&cur->recv));
18573 ast_cli(a->fd, " SIP Transfer mode: %s\n", transfermode2str(cur->allowtransfer));
18574 ast_cli(a->fd, " Force rport: %s\n", AST_CLI_YESNO(ast_test_flag(&cur->flags[0], SIP_NAT_FORCE_RPORT)));
18575 if (ast_sockaddr_isnull(&cur->redirip)) {
18576 ast_cli(a->fd,
18577 " Audio IP: %s (local)\n",
18578 ast_sockaddr_stringify_addr(&cur->ourip));
18579 } else {
18580 ast_cli(a->fd,
18581 " Audio IP: %s (Outside bridge)\n",
18582 ast_sockaddr_stringify_addr(&cur->redirip));
18583 }
18584 ast_cli(a->fd, " Our Tag: %s\n", cur->tag);
18585 ast_cli(a->fd, " Their Tag: %s\n", cur->theirtag);
18586 ast_cli(a->fd, " SIP User agent: %s\n", cur->useragent);
18587 if (!ast_strlen_zero(cur->username))
18588 ast_cli(a->fd, " Username: %s\n", cur->username);
18589 if (!ast_strlen_zero(cur->peername))
18590 ast_cli(a->fd, " Peername: %s\n", cur->peername);
18591 if (!ast_strlen_zero(cur->uri))
18592 ast_cli(a->fd, " Original uri: %s\n", cur->uri);
18593 if (!ast_strlen_zero(cur->cid_num))
18594 ast_cli(a->fd, " Caller-ID: %s\n", cur->cid_num);
18595 ast_cli(a->fd, " Need Destroy: %s\n", AST_CLI_YESNO(cur->needdestroy));
18596 ast_cli(a->fd, " Last Message: %s\n", cur->lastmsg);
18597 ast_cli(a->fd, " Promiscuous Redir: %s\n", AST_CLI_YESNO(ast_test_flag(&cur->flags[0], SIP_PROMISCREDIR)));
18598 ast_cli(a->fd, " Route: %s\n", cur->route ? cur->route->hop : "N/A");
18599 ast_cli(a->fd, " DTMF Mode: %s\n", dtmfmode2str(ast_test_flag(&cur->flags[0], SIP_DTMF)));
18600 ast_cli(a->fd, " SIP Options: ");
18601 if (cur->sipoptions) {
18602 int x;
18603 for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
18604 if (cur->sipoptions & sip_options[x].id)
18605 ast_cli(a->fd, "%s ", sip_options[x].text);
18606 }
18607 ast_cli(a->fd, "\n");
18608 } else
18609 ast_cli(a->fd, "(none)\n");
18610
18611 if (!cur->stimer)
18612 ast_cli(a->fd, " Session-Timer: Uninitiallized\n");
18613 else {
18614 ast_cli(a->fd, " Session-Timer: %s\n", cur->stimer->st_active ? "Active" : "Inactive");
18615 if (cur->stimer->st_active == TRUE) {
18616 ast_cli(a->fd, " S-Timer Interval: %d\n", cur->stimer->st_interval);
18617 ast_cli(a->fd, " S-Timer Refresher: %s\n", strefresher2str(cur->stimer->st_ref));
18618 ast_cli(a->fd, " S-Timer Expirys: %d\n", cur->stimer->st_expirys);
18619 ast_cli(a->fd, " S-Timer Sched Id: %d\n", cur->stimer->st_schedid);
18620 ast_cli(a->fd, " S-Timer Peer Sts: %s\n", cur->stimer->st_active_peer_ua ? "Active" : "Inactive");
18621 ast_cli(a->fd, " S-Timer Cached Min-SE: %d\n", cur->stimer->st_cached_min_se);
18622 ast_cli(a->fd, " S-Timer Cached SE: %d\n", cur->stimer->st_cached_max_se);
18623 ast_cli(a->fd, " S-Timer Cached Ref: %s\n", strefresher2str(cur->stimer->st_cached_ref));
18624 ast_cli(a->fd, " S-Timer Cached Mode: %s\n", stmode2str(cur->stimer->st_cached_mode));
18625 }
18626 }
18627
18628 ast_cli(a->fd, "\n\n");
18629
18630 found++;
18631 }
18632
18633 sip_pvt_unlock(cur);
18634
18635 ao2_t_ref(cur, -1, "toss dialog ptr set by iterator_next");
18636 }
18637 ao2_iterator_destroy(&i);
18638
18639 if (!found)
18640 ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
18641
18642 return CLI_SUCCESS;
18643 }
18644
18645
18646 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18647 {
18648 struct sip_pvt *cur;
18649 size_t len;
18650 int found = 0;
18651 struct ao2_iterator i;
18652
18653 switch (cmd) {
18654 case CLI_INIT:
18655 e->command = "sip show history";
18656 e->usage =
18657 "Usage: sip show history <call-id>\n"
18658 " Provides detailed dialog history on a given SIP call (specified by call-id).\n";
18659 return NULL;
18660 case CLI_GENERATE:
18661 return complete_sip_show_history(a->line, a->word, a->pos, a->n);
18662 }
18663
18664 if (a->argc != 4)
18665 return CLI_SHOWUSAGE;
18666
18667 if (!recordhistory)
18668 ast_cli(a->fd, "\n***Note: History recording is currently DISABLED. Use 'sip set history on' to ENABLE.\n");
18669
18670 len = strlen(a->argv[3]);
18671
18672 i = ao2_iterator_init(dialogs, 0);
18673 while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
18674 sip_pvt_lock(cur);
18675 if (!strncasecmp(cur->callid, a->argv[3], len)) {
18676 struct sip_history *hist;
18677 int x = 0;
18678
18679 ast_cli(a->fd, "\n");
18680 if (cur->subscribed != NONE)
18681 ast_cli(a->fd, " * Subscription\n");
18682 else
18683 ast_cli(a->fd, " * SIP Call\n");
18684 if (cur->history)
18685 AST_LIST_TRAVERSE(cur->history, hist, list)
18686 ast_cli(a->fd, "%d. %s\n", ++x, hist->event);
18687 if (x == 0)
18688 ast_cli(a->fd, "Call '%s' has no history\n", cur->callid);
18689 found++;
18690 }
18691 sip_pvt_unlock(cur);
18692 ao2_t_ref(cur, -1, "toss dialog ptr from iterator_next");
18693 }
18694 ao2_iterator_destroy(&i);
18695
18696 if (!found)
18697 ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
18698
18699 return CLI_SUCCESS;
18700 }
18701
18702
18703 static void sip_dump_history(struct sip_pvt *dialog)
18704 {
18705 int x = 0;
18706 struct sip_history *hist;
18707 static int errmsg = 0;
18708
18709 if (!dialog)
18710 return;
18711
18712 if (!option_debug && !sipdebug) {
18713 if (!errmsg) {
18714 ast_log(LOG_NOTICE, "You must have debugging enabled (SIP or Asterisk) in order to dump SIP history.\n");
18715 errmsg = 1;
18716 }
18717 return;
18718 }
18719
18720 ast_debug(1, "\n---------- SIP HISTORY for '%s' \n", dialog->callid);
18721 if (dialog->subscribed)
18722 ast_debug(1, " * Subscription\n");
18723 else
18724 ast_debug(1, " * SIP Call\n");
18725 if (dialog->history)
18726 AST_LIST_TRAVERSE(dialog->history, hist, list)
18727 ast_debug(1, " %-3.3d. %s\n", ++x, hist->event);
18728 if (!x)
18729 ast_debug(1, "Call '%s' has no history\n", dialog->callid);
18730 ast_debug(1, "\n---------- END SIP HISTORY for '%s' \n", dialog->callid);
18731 }
18732
18733
18734
18735 static void handle_request_info(struct sip_pvt *p, struct sip_request *req)
18736 {
18737 char buf[1024] = "";
18738 unsigned int event;
18739 const char *c = get_header(req, "Content-Type");
18740
18741
18742 if (!strcasecmp(c, "application/dtmf-relay") ||
18743 !strcasecmp(c, "application/vnd.nortelnetworks.digits") ||
18744 !strcasecmp(c, "application/dtmf")) {
18745 unsigned int duration = 0;
18746
18747 if (!p->owner) {
18748 transmit_response(p, "481 Call leg/transaction does not exist", req);
18749 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18750 return;
18751 }
18752
18753
18754
18755 if (strcasecmp(c, "application/dtmf")) {
18756 const char *msg_body;
18757
18758 if ( ast_strlen_zero(msg_body = get_body(req, "Signal", '='))
18759 && ast_strlen_zero(msg_body = get_body(req, "d", '='))) {
18760 ast_log(LOG_WARNING, "Unable to retrieve DTMF signal for INFO message on "
18761 "call %s\n", p->callid);
18762 transmit_response(p, "200 OK", req);
18763 return;
18764 }
18765 ast_copy_string(buf, msg_body, sizeof(buf));
18766
18767 if (!ast_strlen_zero((msg_body = get_body(req, "Duration", '=')))) {
18768 sscanf(msg_body, "%30u", &duration);
18769 }
18770 } else {
18771
18772 get_msg_text(buf, sizeof(buf), req);
18773 }
18774
18775
18776 if (ast_strlen_zero(buf)) {
18777 transmit_response(p, "200 OK", req);
18778 return;
18779 }
18780
18781 if (!duration) {
18782 duration = 100;
18783 }
18784
18785 if (buf[0] == '*') {
18786 event = 10;
18787 } else if (buf[0] == '#') {
18788 event = 11;
18789 } else if (buf[0] == '!') {
18790 event = 16;
18791 } else if ('A' <= buf[0] && buf[0] <= 'D') {
18792 event = 12 + buf[0] - 'A';
18793 } else if ('a' <= buf[0] && buf[0] <= 'd') {
18794 event = 12 + buf[0] - 'a';
18795 } else if ((sscanf(buf, "%30u", &event) != 1) || event > 16) {
18796 ast_log(AST_LOG_WARNING, "Unable to convert DTMF event signal code to a valid "
18797 "value for INFO message on call %s\n", p->callid);
18798 transmit_response(p, "200 OK", req);
18799 return;
18800 }
18801
18802 if (event == 16) {
18803
18804 struct ast_frame f = { AST_FRAME_CONTROL, { AST_CONTROL_FLASH, } };
18805 ast_queue_frame(p->owner, &f);
18806 if (sipdebug) {
18807 ast_verbose("* DTMF-relay event received: FLASH\n");
18808 }
18809 } else {
18810
18811 struct ast_frame f = { AST_FRAME_DTMF, };
18812 if (event < 10) {
18813 f.subclass.integer = '0' + event;
18814 } else if (event == 10) {
18815 f.subclass.integer = '*';
18816 } else if (event == 11) {
18817 f.subclass.integer = '#';
18818 } else {
18819 f.subclass.integer = 'A' + (event - 12);
18820 }
18821 f.len = duration;
18822 ast_queue_frame(p->owner, &f);
18823 if (sipdebug) {
18824 ast_verbose("* DTMF-relay event received: %c\n", (int) f.subclass.integer);
18825 }
18826 }
18827 transmit_response(p, "200 OK", req);
18828 return;
18829 } else if (!strcasecmp(c, "application/media_control+xml")) {
18830
18831 if (p->owner)
18832 ast_queue_control(p->owner, AST_CONTROL_VIDUPDATE);
18833 transmit_response(p, "200 OK", req);
18834 return;
18835 } else if (!ast_strlen_zero(c = get_header(req, "X-ClientCode"))) {
18836
18837 if (ast_test_flag(&p->flags[0], SIP_USECLIENTCODE)) {
18838 if (p->owner && p->owner->cdr)
18839 ast_cdr_setuserfield(p->owner, c);
18840 if (p->owner && ast_bridged_channel(p->owner) && ast_bridged_channel(p->owner)->cdr)
18841 ast_cdr_setuserfield(ast_bridged_channel(p->owner), c);
18842 transmit_response(p, "200 OK", req);
18843 } else {
18844 transmit_response(p, "403 Forbidden", req);
18845 }
18846 return;
18847 } else if (!ast_strlen_zero(c = get_header(req, "Record"))) {
18848
18849
18850
18851
18852
18853
18854
18855 struct ast_call_feature *feat;
18856 int j;
18857 struct ast_frame f = { AST_FRAME_DTMF, };
18858
18859 if (!p->owner) {
18860 transmit_response(p, "481 Call leg/transaction does not exist", req);
18861 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18862 return;
18863 }
18864
18865
18866 ast_rdlock_call_features();
18867 feat = ast_find_call_feature("automon");
18868 if (!feat || ast_strlen_zero(feat->exten)) {
18869 ast_log(LOG_WARNING, "Recording requested, but no One Touch Monitor registered. (See features.conf)\n");
18870
18871 transmit_response(p, "403 Forbidden", req);
18872 ast_unlock_call_features();
18873 return;
18874 }
18875
18876 f.len = 100;
18877 for (j=0; j < strlen(feat->exten); j++) {
18878 f.subclass.integer = feat->exten[j];
18879 ast_queue_frame(p->owner, &f);
18880 if (sipdebug)
18881 ast_verbose("* DTMF-relay event faked: %c\n", f.subclass.integer);
18882 }
18883 ast_unlock_call_features();
18884
18885 ast_debug(1, "Got a Request to Record the channel, state %s\n", c);
18886 transmit_response(p, "200 OK", req);
18887 return;
18888 } else if (ast_strlen_zero(c = get_header(req, "Content-Length")) || !strcasecmp(c, "0")) {
18889
18890 transmit_response(p, "200 OK", req);
18891 return;
18892 }
18893
18894
18895
18896
18897 ast_log(LOG_WARNING, "Unable to parse INFO message from %s. Content %s\n", p->callid, buf);
18898 transmit_response(p, "415 Unsupported media type", req);
18899 return;
18900 }
18901
18902
18903 static char *sip_do_debug_ip(int fd, const char *arg)
18904 {
18905 if (ast_sockaddr_resolve_first(&debugaddr, arg, 0)) {
18906 return CLI_SHOWUSAGE;
18907 }
18908
18909 ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_sockaddr_stringify_addr(&debugaddr));
18910 sipdebug |= sip_debug_console;
18911
18912 return CLI_SUCCESS;
18913 }
18914
18915
18916 static char *sip_do_debug_peer(int fd, const char *arg)
18917 {
18918 struct sip_peer *peer = find_peer(arg, NULL, TRUE, FINDPEERS, FALSE, 0);
18919 if (!peer)
18920 ast_cli(fd, "No such peer '%s'\n", arg);
18921 else if (ast_sockaddr_isnull(&peer->addr))
18922 ast_cli(fd, "Unable to get IP address of peer '%s'\n", arg);
18923 else {
18924 ast_sockaddr_copy(&debugaddr, &peer->addr);
18925 ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_sockaddr_stringify_addr(&debugaddr));
18926 sipdebug |= sip_debug_console;
18927 }
18928 if (peer)
18929 unref_peer(peer, "sip_do_debug_peer: unref_peer, from find_peer call");
18930 return CLI_SUCCESS;
18931 }
18932
18933
18934 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18935 {
18936 int oldsipdebug = sipdebug & sip_debug_console;
18937 const char *what;
18938
18939 if (cmd == CLI_INIT) {
18940 e->command = "sip set debug {on|off|ip|peer}";
18941 e->usage =
18942 "Usage: sip set debug {off|on|ip addr[:port]|peer peername}\n"
18943 " Globally disables dumping of SIP packets,\n"
18944 " or enables it either globally or for a (single)\n"
18945 " IP address or registered peer.\n";
18946 return NULL;
18947 } else if (cmd == CLI_GENERATE) {
18948 if (a->pos == 4 && !strcasecmp(a->argv[3], "peer"))
18949 return complete_sip_peer(a->word, a->n, 0);
18950 return NULL;
18951 }
18952
18953 what = a->argv[e->args-1];
18954 if (a->argc == e->args) {
18955 if (!strcasecmp(what, "on")) {
18956 sipdebug |= sip_debug_console;
18957 sipdebug_text = 1;
18958 memset(&debugaddr, 0, sizeof(debugaddr));
18959 ast_cli(a->fd, "SIP Debugging %senabled\n", oldsipdebug ? "re-" : "");
18960 return CLI_SUCCESS;
18961 } else if (!strcasecmp(what, "off")) {
18962 sipdebug &= ~sip_debug_console;
18963 sipdebug_text = 0;
18964 ast_cli(a->fd, "SIP Debugging Disabled\n");
18965 return CLI_SUCCESS;
18966 }
18967 } else if (a->argc == e->args +1) {
18968 if (!strcasecmp(what, "ip"))
18969 return sip_do_debug_ip(a->fd, a->argv[e->args]);
18970 else if (!strcasecmp(what, "peer"))
18971 return sip_do_debug_peer(a->fd, a->argv[e->args]);
18972 }
18973 return CLI_SHOWUSAGE;
18974 }
18975
18976
18977 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18978 {
18979 struct ast_variable *varlist;
18980 int i;
18981
18982 switch (cmd) {
18983 case CLI_INIT:
18984 e->command = "sip notify";
18985 e->usage =
18986 "Usage: sip notify <type> <peer> [<peer>...]\n"
18987 " Send a NOTIFY message to a SIP peer or peers\n"
18988 " Message types are defined in sip_notify.conf\n";
18989 return NULL;
18990 case CLI_GENERATE:
18991 return complete_sipnotify(a->line, a->word, a->pos, a->n);
18992 }
18993
18994 if (a->argc < 4)
18995 return CLI_SHOWUSAGE;
18996
18997 if (!notify_types) {
18998 ast_cli(a->fd, "No %s file found, or no types listed there\n", notify_config);
18999 return CLI_FAILURE;
19000 }
19001
19002 varlist = ast_variable_browse(notify_types, a->argv[2]);
19003
19004 if (!varlist) {
19005 ast_cli(a->fd, "Unable to find notify type '%s'\n", a->argv[2]);
19006 return CLI_FAILURE;
19007 }
19008
19009 for (i = 3; i < a->argc; i++) {
19010 struct sip_pvt *p;
19011 char buf[512];
19012 struct ast_variable *header, *var;
19013
19014 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
19015 ast_log(LOG_WARNING, "Unable to build sip pvt data for notify (memory/socket error)\n");
19016 return CLI_FAILURE;
19017 }
19018
19019 if (create_addr(p, a->argv[i], NULL, 1, NULL)) {
19020
19021 dialog_unlink_all(p);
19022 dialog_unref(p, "unref dialog inside for loop" );
19023
19024 ast_cli(a->fd, "Could not create address for '%s'\n", a->argv[i]);
19025 continue;
19026 }
19027
19028
19029 ast_set_flag(&p->flags[0], SIP_OUTGOING);
19030 sip_notify_allocate(p);
19031 p->notify->headers = header = ast_variable_new("Subscription-State", "terminated", "");
19032
19033 for (var = varlist; var; var = var->next) {
19034 ast_copy_string(buf, var->value, sizeof(buf));
19035 ast_unescape_semicolon(buf);
19036
19037 if (!strcasecmp(var->name, "Content")) {
19038 if (ast_str_strlen(p->notify->content))
19039 ast_str_append(&p->notify->content, 0, "\r\n");
19040 ast_str_append(&p->notify->content, 0, "%s", buf);
19041 } else if (!strcasecmp(var->name, "Content-Length")) {
19042 ast_log(LOG_WARNING, "it is not necessary to specify Content-Length in sip_notify.conf, ignoring");
19043 } else {
19044 header->next = ast_variable_new(var->name, buf, "");
19045 header = header->next;
19046 }
19047 }
19048
19049
19050 ast_cli(a->fd, "Sending NOTIFY of type '%s' to '%s'\n", a->argv[2], a->argv[i]);
19051 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
19052 transmit_invite(p, SIP_NOTIFY, 0, 2, NULL);
19053 dialog_unref(p, "bump down the count of p since we're done with it.");
19054 }
19055
19056 return CLI_SUCCESS;
19057 }
19058
19059
19060 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
19061 {
19062 switch (cmd) {
19063 case CLI_INIT:
19064 e->command = "sip set history {on|off}";
19065 e->usage =
19066 "Usage: sip set history {on|off}\n"
19067 " Enables/Disables recording of SIP dialog history for debugging purposes.\n"
19068 " Use 'sip show history' to view the history of a call number.\n";
19069 return NULL;
19070 case CLI_GENERATE:
19071 return NULL;
19072 }
19073
19074 if (a->argc != e->args)
19075 return CLI_SHOWUSAGE;
19076
19077 if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
19078 recordhistory = TRUE;
19079 ast_cli(a->fd, "SIP History Recording Enabled (use 'sip show history')\n");
19080 } else if (!strncasecmp(a->argv[e->args - 1], "off", 3)) {
19081 recordhistory = FALSE;
19082 ast_cli(a->fd, "SIP History Recording Disabled\n");
19083 } else {
19084 return CLI_SHOWUSAGE;
19085 }
19086 return CLI_SUCCESS;
19087 }
19088
19089
19090 static int do_register_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code)
19091 {
19092 char *header, *respheader;
19093 char digest[1024];
19094
19095 p->authtries++;
19096 auth_headers(code, &header, &respheader);
19097 memset(digest, 0, sizeof(digest));
19098 if (reply_digest(p, req, header, SIP_REGISTER, digest, sizeof(digest))) {
19099
19100
19101 if (sip_debug_test_pvt(p) && p->registry)
19102 ast_verbose("No authentication challenge, sending blank registration to domain/host name %s\n", p->registry->hostname);
19103
19104 return -1;
19105 }
19106 if (p->do_history)
19107 append_history(p, "RegistryAuth", "Try: %d", p->authtries);
19108 if (sip_debug_test_pvt(p) && p->registry)
19109 ast_verbose("Responding to challenge, registration to domain/host name %s\n", p->registry->hostname);
19110 return transmit_register(p->registry, SIP_REGISTER, digest, respheader);
19111 }
19112
19113
19114 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code, int sipmethod, int init)
19115 {
19116 char *header, *respheader;
19117 char digest[1024];
19118
19119 if (!p->options && !(p->options = ast_calloc(1, sizeof(*p->options))))
19120 return -2;
19121
19122 p->authtries++;
19123 auth_headers(code, &header, &respheader);
19124 ast_debug(2, "Auth attempt %d on %s\n", p->authtries, sip_methods[sipmethod].text);
19125 memset(digest, 0, sizeof(digest));
19126 if (reply_digest(p, req, header, sipmethod, digest, sizeof(digest) )) {
19127
19128 return -1;
19129 }
19130
19131 p->options->auth = digest;
19132 p->options->authheader = respheader;
19133 return transmit_invite(p, sipmethod, sipmethod == SIP_INVITE, init, NULL);
19134 }
19135
19136
19137
19138
19139
19140 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len)
19141 {
19142 char tmp[512];
19143 char *c;
19144 char oldnonce[256];
19145
19146
19147 const struct x {
19148 const char *key;
19149 const ast_string_field *field;
19150 } *i, keys[] = {
19151 { "realm=", &p->realm },
19152 { "nonce=", &p->nonce },
19153 { "opaque=", &p->opaque },
19154 { "qop=", &p->qop },
19155 { "domain=", &p->domain },
19156 { NULL, 0 },
19157 };
19158
19159 ast_copy_string(tmp, get_header(req, header), sizeof(tmp));
19160 if (ast_strlen_zero(tmp))
19161 return -1;
19162 if (strncasecmp(tmp, "Digest ", strlen("Digest "))) {
19163 ast_log(LOG_WARNING, "missing Digest.\n");
19164 return -1;
19165 }
19166 c = tmp + strlen("Digest ");
19167 ast_copy_string(oldnonce, p->nonce, sizeof(oldnonce));
19168 while (c && *(c = ast_skip_blanks(c))) {
19169 for (i = keys; i->key != NULL; i++) {
19170 char *src, *separator;
19171 if (strncasecmp(c, i->key, strlen(i->key)) != 0)
19172 continue;
19173
19174 c += strlen(i->key);
19175 if (*c == '"') {
19176 src = ++c;
19177 separator = "\"";
19178 } else {
19179 src = c;
19180 separator = ",";
19181 }
19182 strsep(&c, separator);
19183 ast_string_field_ptr_set(p, i->field, src);
19184 break;
19185 }
19186 if (i->key == NULL)
19187 strsep(&c, ",");
19188 }
19189
19190 if (strcmp(p->nonce, oldnonce))
19191 p->noncecount = 0;
19192
19193
19194 if (p->registry) {
19195 struct sip_registry *r = p->registry;
19196
19197 if (strcmp(r->nonce, p->nonce)) {
19198 ast_string_field_set(r, realm, p->realm);
19199 ast_string_field_set(r, nonce, p->nonce);
19200 ast_string_field_set(r, authdomain, p->domain);
19201 ast_string_field_set(r, opaque, p->opaque);
19202 ast_string_field_set(r, qop, p->qop);
19203 r->noncecount = 0;
19204 }
19205 }
19206 return build_reply_digest(p, sipmethod, digest, digest_len);
19207 }
19208
19209
19210
19211
19212
19213
19214 static int build_reply_digest(struct sip_pvt *p, int method, char* digest, int digest_len)
19215 {
19216 char a1[256];
19217 char a2[256];
19218 char a1_hash[256];
19219 char a2_hash[256];
19220 char resp[256];
19221 char resp_hash[256];
19222 char uri[256];
19223 char opaque[256] = "";
19224 char cnonce[80];
19225 const char *username;
19226 const char *secret;
19227 const char *md5secret;
19228 struct sip_auth *auth;
19229 struct sip_auth_container *credentials;
19230
19231 if (!ast_strlen_zero(p->domain))
19232 snprintf(uri, sizeof(uri), "%s:%s", p->socket.type == SIP_TRANSPORT_TLS ? "sips" : "sip", p->domain);
19233 else if (!ast_strlen_zero(p->uri))
19234 ast_copy_string(uri, p->uri, sizeof(uri));
19235 else
19236 snprintf(uri, sizeof(uri), "%s:%s@%s", p->socket.type == SIP_TRANSPORT_TLS ? "sips" : "sip", p->username, ast_sockaddr_stringify_host_remote(&p->sa));
19237
19238 snprintf(cnonce, sizeof(cnonce), "%08lx", ast_random());
19239
19240
19241 ao2_lock(p);
19242 credentials = p->peerauth;
19243 if (credentials) {
19244 ao2_t_ref(credentials, +1, "Ref peer auth for digest");
19245 }
19246 ao2_unlock(p);
19247 auth = find_realm_authentication(credentials, p->realm);
19248 if (!auth) {
19249
19250 if (credentials) {
19251 ao2_t_ref(credentials, -1, "Unref peer auth for digest");
19252 }
19253 ast_mutex_lock(&authl_lock);
19254 credentials = authl;
19255 if (credentials) {
19256 ao2_t_ref(credentials, +1, "Ref global auth for digest");
19257 }
19258 ast_mutex_unlock(&authl_lock);
19259 auth = find_realm_authentication(credentials, p->realm);
19260 }
19261
19262 if (auth) {
19263 ast_debug(3, "use realm [%s] from peer [%s][%s]\n", auth->username, p->peername, p->username);
19264 username = auth->username;
19265 secret = auth->secret;
19266 md5secret = auth->md5secret;
19267 if (sipdebug)
19268 ast_debug(1, "Using realm %s authentication for call %s\n", p->realm, p->callid);
19269 } else {
19270
19271 username = p->authname;
19272 secret = p->relatedpeer
19273 && !ast_strlen_zero(p->relatedpeer->remotesecret)
19274 ? p->relatedpeer->remotesecret : p->peersecret;
19275 md5secret = p->peermd5secret;
19276 }
19277 if (ast_strlen_zero(username)) {
19278
19279 if (credentials) {
19280 ao2_t_ref(credentials, -1, "Unref auth for digest");
19281 }
19282 return -1;
19283 }
19284
19285
19286 snprintf(a1, sizeof(a1), "%s:%s:%s", username, p->realm, secret);
19287 snprintf(a2, sizeof(a2), "%s:%s", sip_methods[method].text, uri);
19288 if (!ast_strlen_zero(md5secret))
19289 ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
19290 else
19291 ast_md5_hash(a1_hash, a1);
19292 ast_md5_hash(a2_hash, a2);
19293
19294 p->noncecount++;
19295 if (!ast_strlen_zero(p->qop))
19296 snprintf(resp, sizeof(resp), "%s:%s:%08x:%s:%s:%s", a1_hash, p->nonce, p->noncecount, cnonce, "auth", a2_hash);
19297 else
19298 snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, p->nonce, a2_hash);
19299 ast_md5_hash(resp_hash, resp);
19300
19301
19302 if (!ast_strlen_zero(p->opaque)) {
19303 snprintf(opaque, sizeof(opaque), ", opaque=\"%s\"", p->opaque);
19304 }
19305
19306
19307 if (!ast_strlen_zero(p->qop))
19308 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);
19309 else
19310 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);
19311
19312 append_history(p, "AuthResp", "Auth response sent for %s in realm %s - nc %d", username, p->realm, p->noncecount);
19313
19314 if (credentials) {
19315 ao2_t_ref(credentials, -1, "Unref auth for digest");
19316 }
19317 return 0;
19318 }
19319
19320
19321 static int func_header_read(struct ast_channel *chan, const char *function, char *data, char *buf, size_t len)
19322 {
19323 struct sip_pvt *p;
19324 const char *content = NULL;
19325 AST_DECLARE_APP_ARGS(args,
19326 AST_APP_ARG(header);
19327 AST_APP_ARG(number);
19328 );
19329 int i, number, start = 0;
19330
19331 if (ast_strlen_zero(data)) {
19332 ast_log(LOG_WARNING, "This function requires a header name.\n");
19333 return -1;
19334 }
19335
19336 ast_channel_lock(chan);
19337 if (!IS_SIP_TECH(chan->tech)) {
19338 ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
19339 ast_channel_unlock(chan);
19340 return -1;
19341 }
19342
19343 AST_STANDARD_APP_ARGS(args, data);
19344 if (!args.number) {
19345 number = 1;
19346 } else {
19347 sscanf(args.number, "%30d", &number);
19348 if (number < 1)
19349 number = 1;
19350 }
19351
19352 p = chan->tech_pvt;
19353
19354
19355 if (!p) {
19356 ast_channel_unlock(chan);
19357 return -1;
19358 }
19359
19360 for (i = 0; i < number; i++)
19361 content = __get_header(&p->initreq, args.header, &start);
19362
19363 if (ast_strlen_zero(content)) {
19364 ast_channel_unlock(chan);
19365 return -1;
19366 }
19367
19368 ast_copy_string(buf, content, len);
19369 ast_channel_unlock(chan);
19370
19371 return 0;
19372 }
19373
19374 static struct ast_custom_function sip_header_function = {
19375 .name = "SIP_HEADER",
19376 .read = func_header_read,
19377 };
19378
19379
19380 static int func_check_sipdomain(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
19381 {
19382 if (ast_strlen_zero(data)) {
19383 ast_log(LOG_WARNING, "CHECKSIPDOMAIN requires an argument - A domain name\n");
19384 return -1;
19385 }
19386 if (check_sip_domain(data, NULL, 0))
19387 ast_copy_string(buf, data, len);
19388 else
19389 buf[0] = '\0';
19390 return 0;
19391 }
19392
19393 static struct ast_custom_function checksipdomain_function = {
19394 .name = "CHECKSIPDOMAIN",
19395 .read = func_check_sipdomain,
19396 };
19397
19398
19399 static int function_sippeer(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
19400 {
19401 struct sip_peer *peer;
19402 char *colname;
19403
19404 if ((colname = strchr(data, ':'))) {
19405 static int deprecation_warning = 0;
19406 *colname++ = '\0';
19407 if (deprecation_warning++ % 10 == 0)
19408 ast_log(LOG_WARNING, "SIPPEER(): usage of ':' to separate arguments is deprecated. Please use ',' instead.\n");
19409 } else if ((colname = strchr(data, ',')))
19410 *colname++ = '\0';
19411 else
19412 colname = "ip";
19413
19414 if (!(peer = find_peer(data, NULL, TRUE, FINDPEERS, FALSE, 0)))
19415 return -1;
19416
19417 if (!strcasecmp(colname, "ip")) {
19418 ast_copy_string(buf, ast_sockaddr_stringify_addr(&peer->addr), len);
19419 } else if (!strcasecmp(colname, "port")) {
19420 snprintf(buf, len, "%d", ast_sockaddr_port(&peer->addr));
19421 } else if (!strcasecmp(colname, "status")) {
19422 peer_status(peer, buf, len);
19423 } else if (!strcasecmp(colname, "language")) {
19424 ast_copy_string(buf, peer->language, len);
19425 } else if (!strcasecmp(colname, "regexten")) {
19426 ast_copy_string(buf, peer->regexten, len);
19427 } else if (!strcasecmp(colname, "limit")) {
19428 snprintf(buf, len, "%d", peer->call_limit);
19429 } else if (!strcasecmp(colname, "busylevel")) {
19430 snprintf(buf, len, "%d", peer->busy_level);
19431 } else if (!strcasecmp(colname, "curcalls")) {
19432 snprintf(buf, len, "%d", peer->inUse);
19433 } else if (!strcasecmp(colname, "maxforwards")) {
19434 snprintf(buf, len, "%d", peer->maxforwards);
19435 } else if (!strcasecmp(colname, "accountcode")) {
19436 ast_copy_string(buf, peer->accountcode, len);
19437 } else if (!strcasecmp(colname, "callgroup")) {
19438 ast_print_group(buf, len, peer->callgroup);
19439 } else if (!strcasecmp(colname, "pickupgroup")) {
19440 ast_print_group(buf, len, peer->pickupgroup);
19441 } else if (!strcasecmp(colname, "useragent")) {
19442 ast_copy_string(buf, peer->useragent, len);
19443 } else if (!strcasecmp(colname, "mailbox")) {
19444 struct ast_str *mailbox_str = ast_str_alloca(512);
19445 peer_mailboxes_to_str(&mailbox_str, peer);
19446 ast_copy_string(buf, mailbox_str->str, len);
19447 } else if (!strcasecmp(colname, "context")) {
19448 ast_copy_string(buf, peer->context, len);
19449 } else if (!strcasecmp(colname, "expire")) {
19450 snprintf(buf, len, "%d", peer->expire);
19451 } else if (!strcasecmp(colname, "dynamic")) {
19452 ast_copy_string(buf, peer->host_dynamic ? "yes" : "no", len);
19453 } else if (!strcasecmp(colname, "callerid_name")) {
19454 ast_copy_string(buf, peer->cid_name, len);
19455 } else if (!strcasecmp(colname, "callerid_num")) {
19456 ast_copy_string(buf, peer->cid_num, len);
19457 } else if (!strcasecmp(colname, "codecs")) {
19458 ast_getformatname_multiple(buf, len -1, peer->capability);
19459 } else if (!strcasecmp(colname, "encryption")) {
19460 snprintf(buf, len, "%d", ast_test_flag(&peer->flags[1], SIP_PAGE2_USE_SRTP));
19461 } else if (!strncasecmp(colname, "chanvar[", 8)) {
19462 char *chanvar=colname + 8;
19463 struct ast_variable *v;
19464
19465 chanvar = strsep(&chanvar, "]");
19466 for (v = peer->chanvars ; v ; v = v->next) {
19467 if (!strcasecmp(v->name, chanvar)) {
19468 ast_copy_string(buf, v->value, len);
19469 }
19470 }
19471 } else if (!strncasecmp(colname, "codec[", 6)) {
19472 char *codecnum;
19473 format_t codec = 0;
19474
19475 codecnum = colname + 6;
19476 codecnum = strsep(&codecnum, "]");
19477 if((codec = ast_codec_pref_index(&peer->prefs, atoi(codecnum)))) {
19478 ast_copy_string(buf, ast_getformatname(codec), len);
19479 } else {
19480 buf[0] = '\0';
19481 }
19482 } else {
19483 buf[0] = '\0';
19484 }
19485
19486 unref_peer(peer, "unref_peer from function_sippeer, just before return");
19487
19488 return 0;
19489 }
19490
19491
19492 static struct ast_custom_function sippeer_function = {
19493 .name = "SIPPEER",
19494 .read = function_sippeer,
19495 };
19496
19497
19498 static int function_sipchaninfo_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
19499 {
19500 struct sip_pvt *p;
19501 static int deprecated = 0;
19502
19503 *buf = 0;
19504
19505 if (!data) {
19506 ast_log(LOG_WARNING, "This function requires a parameter name.\n");
19507 return -1;
19508 }
19509
19510 ast_channel_lock(chan);
19511 if (!IS_SIP_TECH(chan->tech)) {
19512 ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
19513 ast_channel_unlock(chan);
19514 return -1;
19515 }
19516
19517 if (deprecated++ % 20 == 0) {
19518
19519 ast_log(LOG_WARNING, "SIPCHANINFO() is deprecated. Please transition to using CHANNEL().\n");
19520 }
19521
19522 p = chan->tech_pvt;
19523
19524
19525 if (!p) {
19526 ast_channel_unlock(chan);
19527 return -1;
19528 }
19529
19530 if (!strcasecmp(data, "peerip")) {
19531 ast_copy_string(buf, ast_sockaddr_stringify_addr(&p->sa), len);
19532 } else if (!strcasecmp(data, "recvip")) {
19533 ast_copy_string(buf, ast_sockaddr_stringify_addr(&p->recv), len);
19534 } else if (!strcasecmp(data, "from")) {
19535 ast_copy_string(buf, p->from, len);
19536 } else if (!strcasecmp(data, "uri")) {
19537 ast_copy_string(buf, p->uri, len);
19538 } else if (!strcasecmp(data, "useragent")) {
19539 ast_copy_string(buf, p->useragent, len);
19540 } else if (!strcasecmp(data, "peername")) {
19541 ast_copy_string(buf, p->peername, len);
19542 } else if (!strcasecmp(data, "t38passthrough")) {
19543 if (p->t38.state == T38_DISABLED) {
19544 ast_copy_string(buf, "0", len);
19545 } else {
19546 ast_copy_string(buf, "1", len);
19547 }
19548 } else {
19549 ast_channel_unlock(chan);
19550 return -1;
19551 }
19552 ast_channel_unlock(chan);
19553
19554 return 0;
19555 }
19556
19557
19558 static struct ast_custom_function sipchaninfo_function = {
19559 .name = "SIPCHANINFO",
19560 .read = function_sipchaninfo_read,
19561 };
19562
19563
19564
19565
19566 static void change_redirecting_information(struct sip_pvt *p, struct sip_request *req,
19567 struct ast_party_redirecting *redirecting,
19568 struct ast_set_party_redirecting *update_redirecting, int set_call_forward)
19569 {
19570 char *redirecting_from_name = NULL;
19571 char *redirecting_from_number = NULL;
19572 char *redirecting_to_name = NULL;
19573 char *redirecting_to_number = NULL;
19574 int reason = AST_REDIRECTING_REASON_UNCONDITIONAL;
19575 int is_response = req->method == SIP_RESPONSE;
19576 int res = 0;
19577
19578 res = get_rdnis(p, req, &redirecting_from_name, &redirecting_from_number, &reason);
19579 if (res == -1) {
19580 if (is_response) {
19581 get_name_and_number(get_header(req, "TO"), &redirecting_from_name, &redirecting_from_number);
19582 } else {
19583 return;
19584 }
19585 }
19586
19587
19588
19589
19590
19591 if (is_response) {
19592 parse_moved_contact(p, req, &redirecting_to_name, &redirecting_to_number, set_call_forward);
19593 } else {
19594 get_name_and_number(get_header(req, "TO"), &redirecting_to_name, &redirecting_to_number);
19595 }
19596
19597 if (!ast_strlen_zero(redirecting_from_number)) {
19598 ast_debug(3, "Got redirecting from number %s\n", redirecting_from_number);
19599 update_redirecting->from.number = 1;
19600 redirecting->from.number.valid = 1;
19601 ast_free(redirecting->from.number.str);
19602 redirecting->from.number.str = redirecting_from_number;
19603 }
19604 if (!ast_strlen_zero(redirecting_from_name)) {
19605 ast_debug(3, "Got redirecting from name %s\n", redirecting_from_name);
19606 update_redirecting->from.name = 1;
19607 redirecting->from.name.valid = 1;
19608 ast_free(redirecting->from.name.str);
19609 redirecting->from.name.str = redirecting_from_name;
19610 }
19611 if (!ast_strlen_zero(p->cid_tag)) {
19612 ast_free(redirecting->from.tag);
19613 redirecting->from.tag = ast_strdup(p->cid_tag);
19614 ast_free(redirecting->to.tag);
19615 redirecting->to.tag = ast_strdup(p->cid_tag);
19616 }
19617 if (!ast_strlen_zero(redirecting_to_number)) {
19618 ast_debug(3, "Got redirecting to number %s\n", redirecting_to_number);
19619 update_redirecting->to.number = 1;
19620 redirecting->to.number.valid = 1;
19621 ast_free(redirecting->to.number.str);
19622 redirecting->to.number.str = redirecting_to_number;
19623 }
19624 if (!ast_strlen_zero(redirecting_to_name)) {
19625 ast_debug(3, "Got redirecting to name %s\n", redirecting_from_number);
19626 update_redirecting->to.name = 1;
19627 redirecting->to.name.valid = 1;
19628 ast_free(redirecting->to.name.str);
19629 redirecting->to.name.str = redirecting_to_name;
19630 }
19631 redirecting->reason = reason;
19632 }
19633
19634
19635
19636
19637
19638
19639
19640 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req, char **name, char **number, int set_call_forward)
19641 {
19642 char contact[SIPBUFSIZE];
19643 char *contact_name = NULL;
19644 char *contact_number = NULL;
19645 char *separator, *trans;
19646 char *domain;
19647 enum sip_transport transport = SIP_TRANSPORT_UDP;
19648
19649 ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
19650 if ((separator = strchr(contact, ',')))
19651 *separator = '\0';
19652
19653 contact_number = get_in_brackets(contact);
19654 if ((trans = strcasestr(contact_number, ";transport="))) {
19655 trans += 11;
19656
19657 if ((separator = strchr(trans, ';')))
19658 *separator = '\0';
19659
19660 if (!strncasecmp(trans, "tcp", 3))
19661 transport = SIP_TRANSPORT_TCP;
19662 else if (!strncasecmp(trans, "tls", 3))
19663 transport = SIP_TRANSPORT_TLS;
19664 else {
19665 if (strncasecmp(trans, "udp", 3))
19666 ast_debug(1, "received contact with an invalid transport, '%s'\n", contact_number);
19667
19668 transport = SIP_TRANSPORT_UDP;
19669 }
19670 }
19671 contact_number = remove_uri_parameters(contact_number);
19672
19673 if (p->socket.tcptls_session) {
19674 ao2_ref(p->socket.tcptls_session, -1);
19675 p->socket.tcptls_session = NULL;
19676 }
19677
19678 set_socket_transport(&p->socket, transport);
19679
19680 if (set_call_forward && ast_test_flag(&p->flags[0], SIP_PROMISCREDIR)) {
19681 char *host = NULL;
19682 if (!strncasecmp(contact_number, "sip:", 4))
19683 contact_number += 4;
19684 else if (!strncasecmp(contact_number, "sips:", 5))
19685 contact_number += 5;
19686 separator = strchr(contact_number, '/');
19687 if (separator)
19688 *separator = '\0';
19689 if ((host = strchr(contact_number, '@'))) {
19690 *host++ = '\0';
19691 ast_debug(2, "Found promiscuous redirection to 'SIP/%s::::%s@%s'\n", contact_number, get_transport(transport), host);
19692 if (p->owner)
19693 ast_string_field_build(p->owner, call_forward, "SIP/%s::::%s@%s", contact_number, get_transport(transport), host);
19694 } else {
19695 ast_debug(2, "Found promiscuous redirection to 'SIP/::::%s@%s'\n", get_transport(transport), contact_number);
19696 if (p->owner)
19697 ast_string_field_build(p->owner, call_forward, "SIP/::::%s@%s", get_transport(transport), contact_number);
19698 }
19699 } else {
19700 separator = strchr(contact, '@');
19701 if (separator) {
19702 *separator++ = '\0';
19703 domain = separator;
19704 } else {
19705
19706 domain = contact;
19707 }
19708 separator = strchr(contact, '/');
19709 if (separator)
19710 *separator = '\0';
19711
19712 if (!strncasecmp(contact_number, "sip:", 4))
19713 contact_number += 4;
19714 else if (!strncasecmp(contact_number, "sips:", 5))
19715 contact_number += 5;
19716 separator = strchr(contact_number, ';');
19717 if (separator)
19718 *separator = '\0';
19719 ast_uri_decode(contact_number);
19720 if (set_call_forward) {
19721 ast_debug(2, "Received 302 Redirect to extension '%s' (domain %s)\n", contact_number, domain);
19722 if (p->owner) {
19723 pbx_builtin_setvar_helper(p->owner, "SIPDOMAIN", domain);
19724 ast_string_field_set(p->owner, call_forward, contact_number);
19725 }
19726 }
19727 }
19728
19729
19730
19731 if (*contact == '\"') {
19732 contact_name = contact + 1;
19733 if (!(separator = (char *)find_closing_quote(contact_name, NULL))) {
19734 ast_log(LOG_NOTICE, "No closing quote on name in Contact header? %s\n", contact);
19735 }
19736 *separator = '\0';
19737 }
19738
19739 if (name && !ast_strlen_zero(contact_name)) {
19740 *name = ast_strdup(contact_name);
19741 }
19742 if (number) {
19743 *number = ast_strdup(contact_number);
19744 }
19745 }
19746
19747
19748
19749
19750
19751
19752 static void check_pendings(struct sip_pvt *p)
19753 {
19754 if (ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
19755
19756 if (p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA) {
19757 p->invitestate = INV_CANCELLED;
19758 transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
19759
19760 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
19761 ast_clear_flag(&p->flags[0], SIP_PENDINGBYE);
19762 }
19763
19764
19765 } else {
19766
19767
19768 if (p->pendinginvite)
19769 return;
19770
19771 if (p->owner) {
19772 ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
19773 }
19774
19775 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, TRUE);
19776 ast_clear_flag(&p->flags[0], SIP_PENDINGBYE);
19777 }
19778 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19779 } else if (ast_test_flag(&p->flags[0], SIP_NEEDREINVITE)) {
19780
19781 if (p->pendinginvite || p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA || p->waitid > 0) {
19782 ast_debug(2, "NOT Sending pending reinvite (yet) on '%s'\n", p->callid);
19783 } else {
19784 ast_debug(2, "Sending pending reinvite on '%s'\n", p->callid);
19785
19786 transmit_reinvite_with_sdp(p, (p->t38.state == T38_LOCAL_REINVITE ? TRUE : FALSE), FALSE);
19787 ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);
19788 }
19789 }
19790 }
19791
19792
19793
19794
19795
19796 static int sip_reinvite_retry(const void *data)
19797 {
19798 struct sip_pvt *p = (struct sip_pvt *) data;
19799 struct ast_channel *owner;
19800
19801 sip_pvt_lock(p);
19802 while ((owner = p->owner) && ast_channel_trylock(owner)) {
19803 sip_pvt_unlock(p);
19804 usleep(1);
19805 sip_pvt_lock(p);
19806 }
19807 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
19808 p->waitid = -1;
19809 check_pendings(p);
19810 sip_pvt_unlock(p);
19811 if (owner) {
19812 ast_channel_unlock(owner);
19813 }
19814 dialog_unref(p, "unref the dialog ptr from sip_reinvite_retry, because it held a dialog ptr");
19815 return 0;
19816 }
19817
19818
19819
19820
19821
19822
19823 static void handle_response_update(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
19824 {
19825 if (p->options) {
19826 p->options->auth_type = (resp == 401 ? WWW_AUTH : PROXY_AUTH);
19827 }
19828 if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp, SIP_UPDATE, 1)) {
19829 ast_log(LOG_NOTICE, "Failed to authenticate on UPDATE to '%s'\n", get_header(&p->initreq, "From"));
19830 }
19831 }
19832
19833 static void cc_handle_publish_error(struct sip_pvt *pvt, const int resp, struct sip_request *req, struct sip_epa_entry *epa_entry)
19834 {
19835 struct cc_epa_entry *cc_entry = epa_entry->instance_data;
19836 struct sip_monitor_instance *monitor_instance = ao2_callback(sip_monitor_instances, 0,
19837 find_sip_monitor_instance_by_suspension_entry, epa_entry);
19838 const char *min_expires;
19839
19840 if (!monitor_instance) {
19841 ast_log(LOG_WARNING, "Can't find monitor_instance corresponding to epa_entry %p.\n", epa_entry);
19842 return;
19843 }
19844
19845 if (resp != 423) {
19846 ast_cc_monitor_failed(cc_entry->core_id, monitor_instance->device_name,
19847 "Received error response to our PUBLISH");
19848 ao2_ref(monitor_instance, -1);
19849 return;
19850 }
19851
19852
19853
19854
19855
19856
19857
19858
19859
19860 min_expires = get_header(req, "Min-Expires");
19861 if (ast_strlen_zero(min_expires)) {
19862 pvt->expiry *= 2;
19863 if (pvt->expiry < 0) {
19864
19865 ast_cc_monitor_failed(cc_entry->core_id, monitor_instance->device_name,
19866 "PUBLISH expiry overflowed");
19867 ao2_ref(monitor_instance, -1);
19868 return;
19869 }
19870 } else if (sscanf(min_expires, "%d", &pvt->expiry) != 1) {
19871 ast_cc_monitor_failed(cc_entry->core_id, monitor_instance->device_name,
19872 "Min-Expires has non-numeric value");
19873 ao2_ref(monitor_instance, -1);
19874 return;
19875 }
19876
19877
19878
19879 transmit_invite(pvt, SIP_PUBLISH, FALSE, 0, NULL);
19880 ao2_ref(monitor_instance, -1);
19881 }
19882
19883 static void handle_response_publish(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
19884 {
19885 struct sip_epa_entry *epa_entry = p->epa_entry;
19886 const char *etag = get_header(req, "Sip-ETag");
19887
19888 ast_assert(epa_entry != NULL);
19889
19890 if (resp == 401 || resp == 407) {
19891 ast_string_field_set(p, theirtag, NULL);
19892 if (p->options) {
19893 p->options->auth_type = (resp == 401 ? WWW_AUTH : PROXY_AUTH);
19894 }
19895 if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp, SIP_PUBLISH, 0)) {
19896 ast_log(LOG_NOTICE, "Failed to authenticate on PUBLISH to '%s'\n", get_header(&p->initreq, "From"));
19897 pvt_set_needdestroy(p, "Failed to authenticate on PUBLISH");
19898 sip_alreadygone(p);
19899 }
19900 return;
19901 }
19902
19903 if (resp == 501 || resp == 405) {
19904 mark_method_unallowed(&p->allowed_methods, SIP_PUBLISH);
19905 }
19906
19907 if (resp == 200) {
19908 p->authtries = 0;
19909
19910
19911
19912 if (!ast_strlen_zero(etag)) {
19913 ast_copy_string(epa_entry->entity_tag, etag, sizeof(epa_entry->entity_tag));
19914 }
19915
19916
19917
19918
19919 if (epa_entry->static_data->handle_ok) {
19920 epa_entry->static_data->handle_ok(p, req, epa_entry);
19921 }
19922 } else {
19923
19924
19925
19926
19927 if (epa_entry->static_data->handle_error) {
19928 epa_entry->static_data->handle_error(p, resp, req, epa_entry);
19929 }
19930 }
19931 }
19932
19933
19934 static void handle_response_invite(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
19935 {
19936 int outgoing = ast_test_flag(&p->flags[0], SIP_OUTGOING);
19937 int res = 0;
19938 int xmitres = 0;
19939 int reinvite = ast_test_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
19940 char *p_hdrval;
19941 int rtn;
19942 struct ast_party_connected_line connected;
19943 struct ast_set_party_connected_line update_connected;
19944
19945 if (reinvite)
19946 ast_debug(4, "SIP response %d to RE-invite on %s call %s\n", resp, outgoing ? "outgoing" : "incoming", p->callid);
19947 else
19948 ast_debug(4, "SIP response %d to standard invite\n", resp);
19949
19950 if (p->alreadygone) {
19951 ast_debug(1, "Got response on call that is already terminated: %s (ignoring)\n", p->callid);
19952 return;
19953 }
19954
19955
19956
19957 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"));
19958
19959
19960
19961
19962 if (resp > 100 && resp < 200 && resp!=101 && resp != 180 && resp != 181 && resp != 182 && resp != 183)
19963 resp = 183;
19964
19965
19966 if (resp >= 100 && resp < 200 && p->invitestate == INV_CALLING)
19967 p->invitestate = INV_PROCEEDING;
19968
19969
19970 if (resp >= 300 && (p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA ))
19971 p->invitestate = INV_COMPLETED;
19972
19973
19974 if ((resp == 200 || resp >= 300) && p->pendinginvite && seqno == p->pendinginvite)
19975 p->pendinginvite = 0;
19976
19977
19978
19979
19980 if (!reinvite) {
19981 set_pvt_allowed_methods(p, req);
19982 }
19983
19984 switch (resp) {
19985 case 100:
19986 case 101:
19987 if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p))
19988 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
19989 check_pendings(p);
19990 break;
19991
19992 case 180:
19993 case 182:
19994 if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p))
19995 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
19996
19997
19998
19999 parse_ok_contact(p, req);
20000 if (!reinvite) {
20001 build_route(p, req, 1, resp);
20002 }
20003 if (!req->ignore && p->owner) {
20004 if (get_rpid(p, req)) {
20005
20006 ast_party_connected_line_init(&connected);
20007 memset(&update_connected, 0, sizeof(update_connected));
20008
20009 update_connected.id.number = 1;
20010 connected.id.number.valid = 1;
20011 connected.id.number.str = (char *) p->cid_num;
20012 connected.id.number.presentation = p->callingpres;
20013
20014 update_connected.id.name = 1;
20015 connected.id.name.valid = 1;
20016 connected.id.name.str = (char *) p->cid_name;
20017 connected.id.name.presentation = p->callingpres;
20018
20019 connected.id.tag = (char *) p->cid_tag;
20020 connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
20021 ast_channel_queue_connected_line_update(p->owner, &connected,
20022 &update_connected);
20023 }
20024 sip_handle_cc(p, req, AST_CC_CCNR);
20025 ast_queue_control(p->owner, AST_CONTROL_RINGING);
20026 if (p->owner->_state != AST_STATE_UP) {
20027 ast_setstate(p->owner, AST_STATE_RINGING);
20028 }
20029 }
20030 if (find_sdp(req)) {
20031 if (p->invitestate != INV_CANCELLED)
20032 p->invitestate = INV_EARLY_MEDIA;
20033 res = process_sdp(p, req, SDP_T38_NONE);
20034 if (!req->ignore && p->owner) {
20035
20036 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
20037 }
20038 ast_rtp_instance_activate(p->rtp);
20039 }
20040 check_pendings(p);
20041 break;
20042
20043 case 181:
20044 if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
20045 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
20046
20047
20048
20049 parse_ok_contact(p, req);
20050 if (!reinvite) {
20051 build_route(p, req, 1, resp);
20052 }
20053 if (!req->ignore && p->owner) {
20054 struct ast_party_redirecting redirecting;
20055 struct ast_set_party_redirecting update_redirecting;
20056
20057 ast_party_redirecting_init(&redirecting);
20058 memset(&update_redirecting, 0, sizeof(update_redirecting));
20059 change_redirecting_information(p, req, &redirecting, &update_redirecting,
20060 FALSE);
20061 ast_channel_queue_redirecting_update(p->owner, &redirecting,
20062 &update_redirecting);
20063 ast_party_redirecting_free(&redirecting);
20064 sip_handle_cc(p, req, AST_CC_CCNR);
20065 }
20066 check_pendings(p);
20067 break;
20068
20069 case 183:
20070 if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
20071 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
20072
20073
20074
20075 parse_ok_contact(p, req);
20076 if (!reinvite) {
20077 build_route(p, req, 1, resp);
20078 }
20079 if (!req->ignore && p->owner) {
20080 if (get_rpid(p, req)) {
20081
20082 ast_party_connected_line_init(&connected);
20083 memset(&update_connected, 0, sizeof(update_connected));
20084
20085 update_connected.id.number = 1;
20086 connected.id.number.valid = 1;
20087 connected.id.number.str = (char *) p->cid_num;
20088 connected.id.number.presentation = p->callingpres;
20089
20090 update_connected.id.name = 1;
20091 connected.id.name.valid = 1;
20092 connected.id.name.str = (char *) p->cid_name;
20093 connected.id.name.presentation = p->callingpres;
20094
20095 connected.id.tag = (char *) p->cid_tag;
20096 connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
20097 ast_channel_queue_connected_line_update(p->owner, &connected,
20098 &update_connected);
20099 }
20100 sip_handle_cc(p, req, AST_CC_CCNR);
20101 }
20102 if (find_sdp(req)) {
20103 if (p->invitestate != INV_CANCELLED)
20104 p->invitestate = INV_EARLY_MEDIA;
20105 res = process_sdp(p, req, SDP_T38_NONE);
20106 if (!req->ignore && p->owner) {
20107
20108 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
20109 }
20110 ast_rtp_instance_activate(p->rtp);
20111 } else {
20112
20113
20114
20115
20116 if (!req->ignore && p->owner) {
20117 ast_queue_control(p->owner, AST_CONTROL_RINGING);
20118 }
20119 }
20120 check_pendings(p);
20121 break;
20122
20123 case 200:
20124 if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
20125 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
20126 p->authtries = 0;
20127 if (find_sdp(req)) {
20128 if ((res = process_sdp(p, req, SDP_T38_ACCEPT)) && !req->ignore)
20129 if (!reinvite) {
20130
20131
20132 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
20133 }
20134 ast_rtp_instance_activate(p->rtp);
20135 }
20136
20137 if (!req->ignore && p->owner) {
20138 int rpid_changed;
20139
20140 rpid_changed = get_rpid(p, req);
20141 if (rpid_changed || !reinvite) {
20142
20143 ast_party_connected_line_init(&connected);
20144 memset(&update_connected, 0, sizeof(update_connected));
20145 if (rpid_changed
20146 || !ast_strlen_zero(p->cid_num)
20147 || (p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
20148 update_connected.id.number = 1;
20149 connected.id.number.valid = 1;
20150 connected.id.number.str = (char *) p->cid_num;
20151 connected.id.number.presentation = p->callingpres;
20152 }
20153 if (rpid_changed
20154 || !ast_strlen_zero(p->cid_name)
20155 || (p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
20156 update_connected.id.name = 1;
20157 connected.id.name.valid = 1;
20158 connected.id.name.str = (char *) p->cid_name;
20159 connected.id.name.presentation = p->callingpres;
20160 }
20161 if (update_connected.id.number || update_connected.id.name) {
20162 connected.id.tag = (char *) p->cid_tag;
20163 connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
20164 ast_channel_queue_connected_line_update(p->owner, &connected,
20165 &update_connected);
20166 }
20167 }
20168 }
20169
20170
20171
20172
20173 if (outgoing) {
20174 update_call_counter(p, DEC_CALL_RINGING);
20175 parse_ok_contact(p, req);
20176
20177 if (!reinvite) {
20178 build_route(p, req, 1, resp);
20179 }
20180 if(set_address_from_contact(p)) {
20181
20182
20183 if (!p->route && !req->ignore)
20184 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
20185 }
20186
20187 }
20188
20189 if (!req->ignore && p->owner) {
20190 if (!reinvite) {
20191 ast_queue_control(p->owner, AST_CONTROL_ANSWER);
20192 if (sip_cfg.callevents)
20193 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
20194 "Channel: %s\r\nChanneltype: %s\r\nUniqueid: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
20195 p->owner->name, "SIP", p->owner->uniqueid, p->callid, p->fullcontact, p->peername);
20196 } else {
20197 if (p->t38.state == T38_DISABLED) {
20198 ast_queue_control(p->owner, AST_CONTROL_UPDATE_RTP_PEER);
20199 } else {
20200 ast_queue_frame(p->owner, &ast_null_frame);
20201 }
20202 }
20203 } else {
20204
20205
20206
20207 if (!req->ignore)
20208 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
20209 }
20210
20211
20212 if (st_get_mode(p, 0) != SESSION_TIMER_MODE_REFUSE && p->outgoing_call == TRUE && !reinvite) {
20213 p_hdrval = (char*)get_header(req, "Session-Expires");
20214 if (!ast_strlen_zero(p_hdrval)) {
20215
20216 enum st_refresher tmp_st_ref = SESSION_TIMER_REFRESHER_AUTO;
20217 int tmp_st_interval = 0;
20218 rtn = parse_session_expires(p_hdrval, &tmp_st_interval, &tmp_st_ref);
20219 if (rtn != 0) {
20220 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
20221 }
20222 if (tmp_st_ref == SESSION_TIMER_REFRESHER_UAC ||
20223 tmp_st_ref == SESSION_TIMER_REFRESHER_UAS) {
20224 p->stimer->st_ref = tmp_st_ref;
20225 }
20226 if (tmp_st_interval) {
20227 p->stimer->st_interval = tmp_st_interval;
20228 }
20229 p->stimer->st_active = TRUE;
20230 p->stimer->st_active_peer_ua = TRUE;
20231 start_session_timer(p);
20232 } else {
20233
20234 if (st_get_mode(p, 0) == SESSION_TIMER_MODE_ORIGINATE) {
20235 p->stimer->st_ref = SESSION_TIMER_REFRESHER_UAC;
20236 p->stimer->st_active_peer_ua = FALSE;
20237 start_session_timer(p);
20238 }
20239 }
20240 }
20241
20242
20243
20244 p->invitestate = INV_TERMINATED;
20245 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
20246 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, TRUE);
20247 check_pendings(p);
20248 break;
20249
20250 case 407:
20251 case 401:
20252
20253 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
20254 if (p->options)
20255 p->options->auth_type = resp;
20256
20257
20258 ast_string_field_set(p, theirtag, NULL);
20259 if (!req->ignore) {
20260 if (p->authtries < MAX_AUTHTRIES)
20261 p->invitestate = INV_CALLING;
20262 if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, SIP_INVITE, 1)) {
20263 ast_log(LOG_NOTICE, "Failed to authenticate on INVITE to '%s'\n", get_header(&p->initreq, "From"));
20264 pvt_set_needdestroy(p, "failed to authenticate on INVITE");
20265 sip_alreadygone(p);
20266 if (p->owner)
20267 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
20268 }
20269 }
20270 break;
20271
20272 case 403:
20273
20274 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
20275 ast_log(LOG_WARNING, "Received response: \"Forbidden\" from '%s'\n", get_header(&p->initreq, "From"));
20276 if (!req->ignore && p->owner) {
20277 ast_set_hangupsource(p->owner, p->owner->name, 0);
20278 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_CONGESTION);
20279 }
20280 break;
20281
20282 case 404:
20283 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
20284 if (p->owner && !req->ignore) {
20285 ast_set_hangupsource(p->owner, p->owner->name, 0);
20286 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_CONGESTION);
20287 }
20288 break;
20289
20290 case 408:
20291 case 481:
20292
20293 ast_log(LOG_WARNING, "Re-invite to non-existing call leg on other UA. SIP dialog '%s'. Giving up.\n", p->callid);
20294 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
20295 if (p->owner) {
20296 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_CONGESTION);
20297 }
20298 break;
20299
20300 case 422:
20301 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
20302 ast_string_field_set(p, theirtag, NULL);
20303 proc_422_rsp(p, req);
20304 break;
20305
20306 case 428:
20307 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
20308 append_history(p, "Identity", "SIP identity is required. Not supported by Asterisk.");
20309 ast_log(LOG_WARNING, "SIP identity required by proxy. SIP dialog '%s'. Giving up.\n", p->callid);
20310 if (p->owner && !req->ignore) {
20311 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_CONGESTION);
20312 }
20313 break;
20314
20315 case 487:
20316
20317
20318
20319 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
20320 if (p->owner && !req->ignore) {
20321 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_NORMAL_CLEARING);
20322 append_history(p, "Hangup", "Got 487 on CANCEL request from us. Queued AST hangup request");
20323 } else if (!req->ignore) {
20324 update_call_counter(p, DEC_CALL_LIMIT);
20325 append_history(p, "Hangup", "Got 487 on CANCEL request from us on call without owner. Killing this dialog.");
20326 }
20327 check_pendings(p);
20328 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20329 break;
20330 case 415:
20331 case 488:
20332 case 606:
20333 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
20334 if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
20335 change_t38_state(p, T38_DISABLED);
20336
20337
20338
20339
20340 transmit_reinvite_with_sdp(p, FALSE, FALSE);
20341 } else {
20342
20343 if (p->owner && !req->ignore) {
20344 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_CONGESTION);
20345 }
20346 }
20347 break;
20348 case 491:
20349 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
20350 if (p->owner && !req->ignore) {
20351 if (p->owner->_state != AST_STATE_UP) {
20352 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_CONGESTION);
20353 } else {
20354
20355
20356
20357 int wait;
20358
20359
20360 if (p->outgoing_call) {
20361 wait = 2100 + ast_random() % 2000;
20362 } else {
20363 wait = ast_random() % 2000;
20364 }
20365 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."));
20366 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);
20367 ast_debug(2, "Reinvite race. Waiting %d secs before retry\n", wait);
20368 }
20369 }
20370 break;
20371
20372 case 405:
20373 case 501:
20374 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
20375 if (p->owner) {
20376 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_CONGESTION);
20377 }
20378 break;
20379 }
20380 if (xmitres == XMIT_ERROR)
20381 ast_log(LOG_WARNING, "Could not transmit message in dialog %s\n", p->callid);
20382 }
20383
20384
20385
20386
20387 static void handle_response_notify(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
20388 {
20389 switch (resp) {
20390 case 200:
20391
20392 if (p->owner) {
20393 if (p->refer) {
20394 ast_log(LOG_NOTICE, "Got OK on REFER Notify message\n");
20395 } else {
20396 ast_log(LOG_WARNING, "Notify answer on an owned channel? - %s\n", p->owner->name);
20397 }
20398 } else {
20399 if (p->subscribed == NONE && !p->refer) {
20400 ast_debug(4, "Got 200 accepted on NOTIFY %s\n", p->callid);
20401 pvt_set_needdestroy(p, "received 200 response");
20402 }
20403 if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
20404
20405 ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
20406 cb_extensionstate((char *)p->context, (char *)p->exten, p->laststate, (void *) p);
20407 }
20408 }
20409 break;
20410 case 401:
20411 case 407:
20412 if (!p->notify) {
20413 break;
20414 }
20415 ast_string_field_set(p, theirtag, NULL);
20416 if (ast_strlen_zero(p->authname)) {
20417 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));
20418 pvt_set_needdestroy(p, "unable to authenticate NOTIFY");
20419 }
20420 if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_NOTIFY, 0)) {
20421 ast_log(LOG_NOTICE, "Failed to authenticate on NOTIFY to '%s'\n", get_header(&p->initreq, "From"));
20422 pvt_set_needdestroy(p, "failed to authenticate NOTIFY");
20423 }
20424 break;
20425 case 481:
20426 pvt_set_needdestroy(p, "Received 481 response for NOTIFY");
20427 break;
20428 }
20429 }
20430
20431
20432 static void handle_response_subscribe(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
20433 {
20434 if (p->subscribed == CALL_COMPLETION) {
20435 struct sip_monitor_instance *monitor_instance;
20436
20437 if (resp < 300) {
20438 return;
20439 }
20440
20441
20442 monitor_instance = ao2_callback(sip_monitor_instances, 0,
20443 find_sip_monitor_instance_by_subscription_pvt, p);
20444 if (monitor_instance) {
20445 ast_cc_monitor_failed(monitor_instance->core_id,
20446 monitor_instance->device_name,
20447 "Received error response to our SUBSCRIBE");
20448 }
20449 return;
20450 }
20451
20452 if (p->subscribed != MWI_NOTIFICATION) {
20453 return;
20454 }
20455 if (!p->mwi) {
20456 return;
20457 }
20458
20459 switch (resp) {
20460 case 200:
20461 ast_debug(3, "Got 200 OK on subscription for MWI\n");
20462 set_pvt_allowed_methods(p, req);
20463 if (p->options) {
20464 ast_free(p->options);
20465 p->options = NULL;
20466 }
20467 p->mwi->subscribed = 1;
20468 if ((p->mwi->resub = ast_sched_add(sched, mwi_expiry * 1000, sip_subscribe_mwi_do, ASTOBJ_REF(p->mwi))) < 0) {
20469 ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
20470 }
20471 break;
20472 case 401:
20473 case 407:
20474 ast_string_field_set(p, theirtag, NULL);
20475 if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_SUBSCRIBE, 0)) {
20476 ast_log(LOG_NOTICE, "Failed to authenticate on SUBSCRIBE to '%s'\n", get_header(&p->initreq, "From"));
20477 p->mwi->call = NULL;
20478 ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
20479 pvt_set_needdestroy(p, "failed to authenticate SUBSCRIBE");
20480 }
20481 break;
20482 case 403:
20483 transmit_response_with_date(p, "200 OK", req);
20484 ast_log(LOG_WARNING, "Authentication failed while trying to subscribe for MWI.\n");
20485 p->mwi->call = NULL;
20486 ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
20487 pvt_set_needdestroy(p, "received 403 response");
20488 sip_alreadygone(p);
20489 break;
20490 case 404:
20491 ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side said that a mailbox may not have been configured.\n");
20492 p->mwi->call = NULL;
20493 ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
20494 pvt_set_needdestroy(p, "received 404 response");
20495 break;
20496 case 481:
20497 ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side said that our dialog did not exist.\n");
20498 p->mwi->call = NULL;
20499 ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
20500 pvt_set_needdestroy(p, "received 481 response");
20501 break;
20502 case 500:
20503 case 501:
20504 ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side may have suffered a heart attack.\n");
20505 p->mwi->call = NULL;
20506 ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
20507 pvt_set_needdestroy(p, "received 500/501 response");
20508 break;
20509 }
20510 }
20511
20512
20513
20514
20515 static void handle_response_refer(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
20516 {
20517 enum ast_control_transfer message = AST_TRANSFER_FAILED;
20518
20519
20520 if (!p->refer)
20521 return;
20522
20523 switch (resp) {
20524 case 202:
20525
20526
20527 p->refer->status = REFER_ACCEPTED;
20528
20529 ast_debug(3, "Got 202 accepted on transfer\n");
20530
20531 break;
20532
20533 case 401:
20534 case 407:
20535 if (ast_strlen_zero(p->authname)) {
20536 ast_log(LOG_WARNING, "Asked to authenticate REFER to %s but we have no matching peer or realm auth!\n",
20537 ast_sockaddr_stringify(&p->recv));
20538 if (p->owner) {
20539 ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
20540 }
20541 pvt_set_needdestroy(p, "unable to authenticate REFER");
20542 }
20543 if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_REFER, 0)) {
20544 ast_log(LOG_NOTICE, "Failed to authenticate on REFER to '%s'\n", get_header(&p->initreq, "From"));
20545 p->refer->status = REFER_NOAUTH;
20546 if (p->owner) {
20547 ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
20548 }
20549 pvt_set_needdestroy(p, "failed to authenticate REFER");
20550 }
20551 break;
20552
20553 case 405:
20554
20555
20556 ast_log(LOG_NOTICE, "SIP transfer to %s failed, REFER not allowed. \n", p->refer->refer_to);
20557 pvt_set_needdestroy(p, "received 405 response");
20558 p->refer->status = REFER_FAILED;
20559 if (p->owner) {
20560 ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
20561 }
20562 break;
20563
20564 case 481:
20565
20566
20567
20568
20569 ast_log(LOG_WARNING, "Remote host can't match REFER request to call '%s'. Giving up.\n", p->callid);
20570 if (p->owner)
20571 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
20572 pvt_set_needdestroy(p, "received 481 response");
20573 break;
20574
20575 case 500:
20576 case 501:
20577
20578
20579 ast_log(LOG_NOTICE, "SIP transfer to %s failed, call miserably fails. \n", p->refer->refer_to);
20580 pvt_set_needdestroy(p, "received 500/501 response");
20581 p->refer->status = REFER_FAILED;
20582 if (p->owner) {
20583 ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
20584 }
20585 break;
20586 case 603:
20587 ast_log(LOG_NOTICE, "SIP transfer to %s declined, call miserably fails. \n", p->refer->refer_to);
20588 p->refer->status = REFER_FAILED;
20589 pvt_set_needdestroy(p, "received 603 response");
20590 if (p->owner) {
20591 ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
20592 }
20593 break;
20594 default:
20595
20596
20597
20598
20599 if (resp < 299) {
20600 ast_log(LOG_WARNING, "SIP transfer to %s had unxpected 2xx response (%d), confusion is possible. \n", p->refer->refer_to, resp);
20601 } else {
20602 ast_log(LOG_WARNING, "SIP transfer to %s with response (%d). \n", p->refer->refer_to, resp);
20603 }
20604
20605 p->refer->status = REFER_FAILED;
20606 pvt_set_needdestroy(p, "received failure response");
20607 if (p->owner) {
20608 ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
20609 }
20610 break;
20611 }
20612 }
20613
20614
20615 static int handle_response_register(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
20616 {
20617 int expires, expires_ms;
20618 struct sip_registry *r;
20619 r=p->registry;
20620
20621 switch (resp) {
20622 case 401:
20623 if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
20624 ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s@%s' (Tries %d)\n", p->registry->username, p->registry->hostname, p->authtries);
20625 pvt_set_needdestroy(p, "failed to authenticate REGISTER");
20626 }
20627 break;
20628 case 403:
20629 ast_log(LOG_WARNING, "Forbidden - wrong password on authentication for REGISTER for '%s' to '%s'\n", p->registry->username, p->registry->hostname);
20630 AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 403"));
20631 r->regstate = REG_STATE_NOAUTH;
20632 pvt_set_needdestroy(p, "received 403 response");
20633 break;
20634 case 404:
20635 ast_log(LOG_WARNING, "Got 404 Not found on SIP register to service %s@%s, giving up\n", p->registry->username, p->registry->hostname);
20636 pvt_set_needdestroy(p, "received 404 response");
20637 if (r->call)
20638 r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 404");
20639 r->regstate = REG_STATE_REJECTED;
20640 AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 404"));
20641 break;
20642 case 407:
20643 if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
20644 ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s' (tries '%d')\n", get_header(&p->initreq, "From"), p->authtries);
20645 pvt_set_needdestroy(p, "failed to authenticate REGISTER");
20646 }
20647 break;
20648 case 408:
20649
20650 if (r) {
20651 r->regattempts = 0;
20652 } else {
20653 ast_log(LOG_WARNING, "Got a 408 response to our REGISTER on call %s after we had destroyed the registry object\n", p->callid);
20654 }
20655 break;
20656 case 423:
20657 r->expiry = atoi(get_header(req, "Min-Expires"));
20658 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);
20659 AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 423"));
20660 if (r->call) {
20661 r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 423");
20662 pvt_set_needdestroy(p, "received 423 response");
20663 }
20664 if (r->expiry > max_expiry) {
20665 ast_log(LOG_WARNING, "Required expiration time from %s@%s is too high, giving up\n", p->registry->username, p->registry->hostname);
20666 r->expiry = r->configured_expiry;
20667 r->regstate = REG_STATE_REJECTED;
20668 } else {
20669 r->regstate = REG_STATE_UNREGISTERED;
20670 transmit_register(r, SIP_REGISTER, NULL, NULL);
20671 }
20672 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));
20673 break;
20674 case 479:
20675 ast_log(LOG_WARNING, "Got error 479 on register to %s@%s, giving up (check config)\n", p->registry->username, p->registry->hostname);
20676 pvt_set_needdestroy(p, "received 479 response");
20677 if (r->call)
20678 r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 479");
20679 r->regstate = REG_STATE_REJECTED;
20680 AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 479"));
20681 break;
20682 case 200:
20683 if (!r) {
20684 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));
20685 pvt_set_needdestroy(p, "received erroneous 200 response");
20686 return 0;
20687 }
20688
20689 r->regstate = REG_STATE_REGISTERED;
20690 r->regtime = ast_tvnow();
20691 manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelType: SIP\r\nDomain: %s\r\nStatus: %s\r\n", r->hostname, regstate2str(r->regstate));
20692 r->regattempts = 0;
20693 ast_debug(1, "Registration successful\n");
20694 if (r->timeout > -1) {
20695 ast_debug(1, "Cancelling timeout %d\n", r->timeout);
20696 }
20697 AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 200"));
20698 if (r->call)
20699 r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 200");
20700 p->registry = registry_unref(p->registry, "unref registry entry p->registry");
20701
20702 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20703
20704
20705
20706
20707
20708
20709 expires = 0;
20710
20711
20712 if (!ast_strlen_zero(get_header(req, "Contact"))) {
20713 const char *contact = NULL;
20714 const char *tmptmp = NULL;
20715 int start = 0;
20716 for(;;) {
20717 contact = __get_header(req, "Contact", &start);
20718
20719 if(!ast_strlen_zero(contact)) {
20720 if( (tmptmp=strstr(contact, p->our_contact))) {
20721 contact=tmptmp;
20722 break;
20723 }
20724 } else
20725 break;
20726 }
20727 tmptmp = strcasestr(contact, "expires=");
20728 if (tmptmp) {
20729 if (sscanf(tmptmp + 8, "%30d;", &expires) != 1)
20730 expires = 0;
20731 }
20732
20733 }
20734 if (!expires)
20735 expires=atoi(get_header(req, "expires"));
20736 if (!expires)
20737 expires=default_expiry;
20738
20739 expires_ms = expires * 1000;
20740 if (expires <= EXPIRY_GUARD_LIMIT)
20741 expires_ms -= MAX((expires_ms * EXPIRY_GUARD_PCT), EXPIRY_GUARD_MIN);
20742 else
20743 expires_ms -= EXPIRY_GUARD_SECS * 1000;
20744 if (sipdebug)
20745 ast_log(LOG_NOTICE, "Outbound Registration: Expiry for %s is %d sec (Scheduling reregistration in %d s)\n", r->hostname, expires, expires_ms/1000);
20746
20747 r->refresh= (int) expires_ms / 1000;
20748
20749
20750 AST_SCHED_REPLACE_UNREF(r->expire, sched, expires_ms, sip_reregister, r,
20751 registry_unref(_data,"unref in REPLACE del fail"),
20752 registry_unref(r,"unref in REPLACE add fail"),
20753 registry_addref(r,"The Addition side of REPLACE"));
20754 }
20755 return 1;
20756 }
20757
20758
20759 static void handle_response_peerpoke(struct sip_pvt *p, int resp, struct sip_request *req)
20760 {
20761 struct sip_peer *peer = p->relatedpeer ;
20762 int statechanged, is_reachable, was_reachable;
20763 int pingtime = ast_tvdiff_ms(ast_tvnow(), peer->ps);
20764
20765
20766
20767
20768
20769
20770 if (pingtime < 1) {
20771 pingtime = 1;
20772 }
20773
20774 if (!peer->maxms) {
20775 pvt_set_needdestroy(p, "got OPTIONS response but qualify is not enabled");
20776 return;
20777 }
20778
20779
20780
20781
20782
20783 was_reachable = peer->lastms > 0 && peer->lastms <= peer->maxms;
20784 is_reachable = pingtime <= peer->maxms;
20785 statechanged = peer->lastms == 0
20786 || was_reachable != is_reachable;
20787
20788 peer->lastms = pingtime;
20789 peer->call = dialog_unref(peer->call, "unref dialog peer->call");
20790 if (statechanged) {
20791 const char *s = is_reachable ? "Reachable" : "Lagged";
20792 char str_lastms[20];
20793 snprintf(str_lastms, sizeof(str_lastms), "%d", pingtime);
20794
20795 ast_log(LOG_NOTICE, "Peer '%s' is now %s. (%dms / %dms)\n",
20796 peer->name, s, pingtime, peer->maxms);
20797 ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
20798 if (sip_cfg.peer_rtupdate) {
20799 ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", str_lastms, SENTINEL);
20800 }
20801 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
20802 "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: %s\r\nTime: %d\r\n",
20803 peer->name, s, pingtime);
20804 if (is_reachable && sip_cfg.regextenonqualify)
20805 register_peer_exten(peer, TRUE);
20806 }
20807
20808 pvt_set_needdestroy(p, "got OPTIONS response");
20809
20810
20811 AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
20812 is_reachable ? peer->qualifyfreq : DEFAULT_FREQ_NOTOK,
20813 sip_poke_peer_s, peer,
20814 unref_peer(_data, "removing poke peer ref"),
20815 unref_peer(peer, "removing poke peer ref"),
20816 ref_peer(peer, "adding poke peer ref"));
20817 }
20818
20819
20820
20821
20822
20823
20824
20825
20826 static void handle_response_info(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
20827 {
20828 int sipmethod = SIP_INFO;
20829
20830 switch (resp) {
20831 case 401:
20832 case 407:
20833 ast_log(LOG_WARNING, "Host '%s' requests authentication (%d) for '%s'\n",
20834 ast_sockaddr_stringify(&p->sa), resp, sip_methods[sipmethod].text);
20835 break;
20836 case 405:
20837 case 501:
20838 mark_method_unallowed(&p->allowed_methods, sipmethod);
20839 if (p->relatedpeer) {
20840 mark_method_allowed(&p->relatedpeer->disallowed_methods, sipmethod);
20841 }
20842 ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n",
20843 ast_sockaddr_stringify(&p->sa), sip_methods[sipmethod].text);
20844 break;
20845 default:
20846 if (300 <= resp && resp < 700) {
20847 ast_verb(3, "Got SIP %s response %d \"%s\" back from host '%s'\n",
20848 sip_methods[sipmethod].text, resp, rest, ast_sockaddr_stringify(&p->sa));
20849 }
20850 break;
20851 }
20852 }
20853
20854
20855
20856
20857
20858
20859
20860
20861
20862 static void handle_response_message(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
20863 {
20864 int sipmethod = SIP_MESSAGE;
20865
20866
20867
20868 switch (resp) {
20869 case 401:
20870 case 407:
20871 ast_log(LOG_WARNING, "Host '%s' requests authentication (%d) for '%s'\n",
20872 ast_sockaddr_stringify(&p->sa), resp, sip_methods[sipmethod].text);
20873 break;
20874 case 405:
20875 case 501:
20876 mark_method_unallowed(&p->allowed_methods, sipmethod);
20877 if (p->relatedpeer) {
20878 mark_method_allowed(&p->relatedpeer->disallowed_methods, sipmethod);
20879 }
20880 ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n",
20881 ast_sockaddr_stringify(&p->sa), sip_methods[sipmethod].text);
20882 break;
20883 default:
20884 if (100 <= resp && resp < 200) {
20885
20886 } else if (200 <= resp && resp < 300) {
20887 p->authtries = 0;
20888 } else if (300 <= resp && resp < 700) {
20889 ast_verb(3, "Got SIP %s response %d \"%s\" back from host '%s'\n",
20890 sip_methods[sipmethod].text, resp, rest, ast_sockaddr_stringify(&p->sa));
20891 }
20892 break;
20893 }
20894 }
20895
20896
20897 static void stop_media_flows(struct sip_pvt *p)
20898 {
20899
20900 if (p->rtp)
20901 ast_rtp_instance_stop(p->rtp);
20902 if (p->vrtp)
20903 ast_rtp_instance_stop(p->vrtp);
20904 if (p->trtp)
20905 ast_rtp_instance_stop(p->trtp);
20906 if (p->udptl)
20907 ast_udptl_stop(p->udptl);
20908 }
20909
20910
20911
20912 static void handle_response(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
20913 {
20914 struct ast_channel *owner;
20915 int sipmethod;
20916 const char *c = get_header(req, "Cseq");
20917
20918 char *c_copy = ast_strdupa(c);
20919
20920 const char *msg = ast_skip_blanks(ast_skip_nonblanks(c_copy));
20921
20922 if (!msg)
20923 msg = "";
20924
20925 sipmethod = find_sip_method(msg);
20926
20927 owner = p->owner;
20928 if (owner) {
20929 const char *rp = NULL, *rh = NULL;
20930
20931 owner->hangupcause = 0;
20932 if (ast_test_flag(&p->flags[1], SIP_PAGE2_Q850_REASON) && (rh = get_header(req, "Reason"))) {
20933 rh = ast_skip_blanks(rh);
20934 if (!strncasecmp(rh, "Q.850", 5)) {
20935 rp = strstr(rh, "cause=");
20936 if (rp && sscanf(rp + 6, "%30d", &owner->hangupcause) == 1) {
20937 owner->hangupcause &= 0x7f;
20938 if (req->debug)
20939 ast_verbose("Using Reason header for cause code: %d\n", owner->hangupcause);
20940 }
20941 }
20942 }
20943
20944 if (!owner->hangupcause)
20945 owner->hangupcause = hangup_sip2cause(resp);
20946 }
20947
20948 if (p->socket.type == SIP_TRANSPORT_UDP) {
20949 int ack_res = FALSE;
20950
20951
20952 if ((resp >= 100) && (resp <= 199)) {
20953
20954 if (sipmethod == SIP_INVITE) {
20955 ack_res = __sip_semi_ack(p, seqno, 0, sipmethod);
20956 }
20957 } else {
20958 ack_res = __sip_ack(p, seqno, 0, sipmethod);
20959 }
20960
20961 if (ack_res == FALSE) {
20962
20963 if (sipmethod == SIP_INVITE && resp >= 200) {
20964 transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, resp < 300 ? TRUE: FALSE);
20965 }
20966
20967 append_history(p, "Ignore", "Ignoring this retransmit\n");
20968 return;
20969 }
20970 }
20971
20972
20973 if (!p->owner && sipmethod == SIP_NOTIFY && p->pendinginvite) {
20974 p->pendinginvite = 0;
20975 }
20976
20977
20978 if (ast_strlen_zero(p->theirtag) || (resp >= 200)) {
20979 char tag[128];
20980
20981 gettag(req, "To", tag, sizeof(tag));
20982 ast_string_field_set(p, theirtag, tag);
20983 }
20984
20985
20986
20987
20988
20989
20990
20991
20992
20993
20994
20995
20996
20997
20998
20999 if ((resp == 404 || resp == 408 || resp == 481) && sipmethod == SIP_BYE) {
21000 pvt_set_needdestroy(p, "received 4XX response to a BYE");
21001 return;
21002 }
21003
21004 if (p->relatedpeer && sipmethod == SIP_OPTIONS) {
21005
21006
21007
21008 if (resp != 100)
21009 handle_response_peerpoke(p, resp, req);
21010 } else if (sipmethod == SIP_REFER && resp >= 200) {
21011 handle_response_refer(p, resp, rest, req, seqno);
21012 } else if (sipmethod == SIP_PUBLISH) {
21013
21014
21015
21016 handle_response_publish(p, resp, rest, req, seqno);
21017 } else if (sipmethod == SIP_INFO) {
21018
21019 handle_response_info(p, resp, rest, req, seqno);
21020 } else if (sipmethod == SIP_MESSAGE) {
21021
21022 handle_response_message(p, resp, rest, req, seqno);
21023 } else if (sipmethod == SIP_NOTIFY) {
21024
21025 handle_response_notify(p, resp, rest, req, seqno);
21026 } else if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
21027 switch(resp) {
21028 case 100:
21029 case 101:
21030 case 183:
21031 case 180:
21032 case 182:
21033 case 181:
21034 if (sipmethod == SIP_INVITE)
21035 handle_response_invite(p, resp, rest, req, seqno);
21036 break;
21037 case 200:
21038 p->authtries = 0;
21039 if (sipmethod == SIP_INVITE) {
21040 handle_response_invite(p, resp, rest, req, seqno);
21041 } else if (sipmethod == SIP_REGISTER) {
21042 handle_response_register(p, resp, rest, req, seqno);
21043 } else if (sipmethod == SIP_SUBSCRIBE) {
21044 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
21045 handle_response_subscribe(p, resp, rest, req, seqno);
21046 } else if (sipmethod == SIP_BYE) {
21047 pvt_set_needdestroy(p, "received 200 response");
21048 ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
21049 }
21050 break;
21051 case 401:
21052 case 407:
21053 if (sipmethod == SIP_INVITE)
21054 handle_response_invite(p, resp, rest, req, seqno);
21055 else if (sipmethod == SIP_SUBSCRIBE)
21056 handle_response_subscribe(p, resp, rest, req, seqno);
21057 else if (p->registry && sipmethod == SIP_REGISTER)
21058 handle_response_register(p, resp, rest, req, seqno);
21059 else if (sipmethod == SIP_UPDATE) {
21060 handle_response_update(p, resp, rest, req, seqno);
21061 } else if (sipmethod == SIP_BYE) {
21062 if (p->options)
21063 p->options->auth_type = resp;
21064 if (ast_strlen_zero(p->authname)) {
21065 ast_log(LOG_WARNING, "Asked to authenticate %s, to %s but we have no matching peer!\n",
21066 msg, ast_sockaddr_stringify(&p->recv));
21067 pvt_set_needdestroy(p, "unable to authenticate BYE");
21068 } else if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp, sipmethod, 0)) {
21069 ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
21070 pvt_set_needdestroy(p, "failed to authenticate BYE");
21071 }
21072 } else {
21073 ast_log(LOG_WARNING, "Got authentication request (%d) on %s to '%s'\n", resp, sip_methods[sipmethod].text, get_header(req, "To"));
21074 pvt_set_needdestroy(p, "received 407 response");
21075 }
21076 break;
21077 case 403:
21078 if (sipmethod == SIP_INVITE)
21079 handle_response_invite(p, resp, rest, req, seqno);
21080 else if (sipmethod == SIP_SUBSCRIBE)
21081 handle_response_subscribe(p, resp, rest, req, seqno);
21082 else if (p->registry && sipmethod == SIP_REGISTER)
21083 handle_response_register(p, resp, rest, req, seqno);
21084 else {
21085 ast_log(LOG_WARNING, "Forbidden - maybe wrong password on authentication for %s\n", msg);
21086 pvt_set_needdestroy(p, "received 403 response");
21087 }
21088 break;
21089 case 404:
21090 if (p->registry && sipmethod == SIP_REGISTER)
21091 handle_response_register(p, resp, rest, req, seqno);
21092 else if (sipmethod == SIP_INVITE)
21093 handle_response_invite(p, resp, rest, req, seqno);
21094 else if (sipmethod == SIP_SUBSCRIBE)
21095 handle_response_subscribe(p, resp, rest, req, seqno);
21096 else if (owner)
21097 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
21098 break;
21099 case 423:
21100 if (sipmethod == SIP_REGISTER)
21101 handle_response_register(p, resp, rest, req, seqno);
21102 break;
21103 case 408:
21104 if (sipmethod == SIP_INVITE)
21105 handle_response_invite(p, resp, rest, req, seqno);
21106 else if (sipmethod == SIP_REGISTER)
21107 handle_response_register(p, resp, rest, req, seqno);
21108 else if (sipmethod == SIP_BYE) {
21109 pvt_set_needdestroy(p, "received 408 response");
21110 ast_debug(4, "Got timeout on bye. Thanks for the answer. Now, kill this call\n");
21111 } else {
21112 if (owner)
21113 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
21114 pvt_set_needdestroy(p, "received 408 response");
21115 }
21116 break;
21117
21118 case 428:
21119 case 422:
21120 if (sipmethod == SIP_INVITE) {
21121 handle_response_invite(p, resp, rest, req, seqno);
21122 }
21123 break;
21124
21125 case 481:
21126 if (sipmethod == SIP_INVITE) {
21127 handle_response_invite(p, resp, rest, req, seqno);
21128 } else if (sipmethod == SIP_SUBSCRIBE) {
21129 handle_response_subscribe(p, resp, rest, req, seqno);
21130 } else if (sipmethod == SIP_BYE) {
21131
21132
21133 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
21134 } else if (sipmethod == SIP_CANCEL) {
21135
21136
21137 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
21138 } else {
21139 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
21140
21141 }
21142 break;
21143 case 487:
21144 if (sipmethod == SIP_INVITE)
21145 handle_response_invite(p, resp, rest, req, seqno);
21146 break;
21147 case 415:
21148 case 488:
21149 case 606:
21150 if (sipmethod == SIP_INVITE)
21151 handle_response_invite(p, resp, rest, req, seqno);
21152 break;
21153 case 491:
21154 if (sipmethod == SIP_INVITE)
21155 handle_response_invite(p, resp, rest, req, seqno);
21156 else {
21157 ast_debug(1, "Got 491 on %s, unsupported. Call ID %s\n", sip_methods[sipmethod].text, p->callid);
21158 pvt_set_needdestroy(p, "received 491 response");
21159 }
21160 break;
21161 case 405:
21162 case 501:
21163 mark_method_unallowed(&p->allowed_methods, sipmethod);
21164 if (p->relatedpeer) {
21165 mark_method_allowed(&p->relatedpeer->disallowed_methods, sipmethod);
21166 }
21167 if (sipmethod == SIP_INVITE)
21168 handle_response_invite(p, resp, rest, req, seqno);
21169 else
21170 ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n", ast_sockaddr_stringify(&p->sa), msg);
21171 break;
21172 default:
21173 if ((resp >= 300) && (resp < 700)) {
21174
21175 if ((resp != 487))
21176 ast_verb(3, "Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_sockaddr_stringify(&p->sa));
21177
21178 if (sipmethod == SIP_INVITE)
21179 stop_media_flows(p);
21180
21181
21182 switch(resp) {
21183 case 300:
21184 case 301:
21185 case 302:
21186 case 305:
21187 if (p->owner) {
21188 struct ast_party_redirecting redirecting;
21189 struct ast_set_party_redirecting update_redirecting;
21190
21191 ast_party_redirecting_init(&redirecting);
21192 memset(&update_redirecting, 0, sizeof(update_redirecting));
21193 change_redirecting_information(p, req, &redirecting,
21194 &update_redirecting, TRUE);
21195 ast_channel_set_redirecting(p->owner, &redirecting,
21196 &update_redirecting);
21197 ast_party_redirecting_free(&redirecting);
21198 }
21199
21200 case 486:
21201 case 600:
21202 case 603:
21203 if (p->owner) {
21204 sip_handle_cc(p, req, AST_CC_CCBS);
21205 ast_queue_control(p->owner, AST_CONTROL_BUSY);
21206 }
21207 break;
21208 case 482:
21209 case 480:
21210 case 404:
21211 case 410:
21212 case 400:
21213 case 500:
21214 if (sipmethod == SIP_SUBSCRIBE) {
21215 handle_response_subscribe(p, resp, rest, req, seqno);
21216 break;
21217 }
21218
21219 case 502:
21220 case 503:
21221 case 504:
21222 if (owner)
21223 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
21224 break;
21225 case 484:
21226 if (owner && sipmethod != SIP_BYE) {
21227 switch (ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP)) {
21228 case SIP_PAGE2_ALLOWOVERLAP_YES:
21229 ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
21230 break;
21231 default:
21232 ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(404));
21233 break;
21234 }
21235 }
21236 break;
21237 default:
21238
21239 if (owner && sipmethod != SIP_BYE)
21240 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
21241 break;
21242 }
21243
21244 if (sipmethod == SIP_INVITE)
21245 transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
21246 sip_alreadygone(p);
21247 if (!p->owner) {
21248 pvt_set_needdestroy(p, "transaction completed");
21249 }
21250 } else if ((resp >= 100) && (resp < 200)) {
21251 if (sipmethod == SIP_INVITE) {
21252 if (!req->ignore && sip_cancel_destroy(p))
21253 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
21254 if (find_sdp(req))
21255 process_sdp(p, req, SDP_T38_NONE);
21256 if (p->owner) {
21257
21258 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
21259 }
21260 }
21261 } else
21262 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));
21263 }
21264 } else {
21265
21266
21267 if (req->debug)
21268 ast_verbose("SIP Response message for INCOMING dialog %s arrived\n", msg);
21269
21270 if (sipmethod == SIP_INVITE && resp == 200) {
21271
21272
21273 char tag[128];
21274
21275 gettag(req, "To", tag, sizeof(tag));
21276 ast_string_field_set(p, theirtag, tag);
21277 }
21278
21279 switch(resp) {
21280 case 200:
21281 if (sipmethod == SIP_INVITE) {
21282 handle_response_invite(p, resp, rest, req, seqno);
21283 } else if (sipmethod == SIP_CANCEL) {
21284 ast_debug(1, "Got 200 OK on CANCEL\n");
21285
21286
21287 } else if (sipmethod == SIP_BYE) {
21288 pvt_set_needdestroy(p, "transaction completed");
21289 }
21290 break;
21291 case 401:
21292 case 407:
21293 if (sipmethod == SIP_INVITE)
21294 handle_response_invite(p, resp, rest, req, seqno);
21295 else if (sipmethod == SIP_BYE) {
21296 if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, sipmethod, 0)) {
21297 ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
21298 pvt_set_needdestroy(p, "failed to authenticate BYE");
21299 }
21300 }
21301 break;
21302 case 481:
21303 if (sipmethod == SIP_INVITE) {
21304
21305 handle_response_invite(p, resp, rest, req, seqno);
21306 } else if (sipmethod == SIP_BYE) {
21307 pvt_set_needdestroy(p, "received 481 response");
21308 } else if (sipdebug) {
21309 ast_debug(1, "Remote host can't match request %s to call '%s'. Giving up\n", sip_methods[sipmethod].text, p->callid);
21310 }
21311 break;
21312 case 501:
21313 if (sipmethod == SIP_INVITE)
21314 handle_response_invite(p, resp, rest, req, seqno);
21315 break;
21316 default:
21317 if ((resp >= 100) && (resp < 200)) {
21318 if (sipmethod == SIP_INVITE) {
21319 if (!req->ignore && sip_cancel_destroy(p))
21320 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
21321 }
21322 }
21323 if ((resp >= 300) && (resp < 700)) {
21324 if ((resp != 487))
21325 ast_verb(3, "Incoming call: Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_sockaddr_stringify(&p->sa));
21326 switch(resp) {
21327 case 415:
21328 case 488:
21329 case 603:
21330 case 500:
21331 case 502:
21332 case 503:
21333 case 504:
21334
21335
21336 if (sipmethod == SIP_INVITE && sip_cancel_destroy(p))
21337 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
21338 break;
21339 }
21340 }
21341 break;
21342 }
21343 }
21344 }
21345
21346
21347
21348
21349
21350
21351
21352 static void *sip_park_thread(void *stuff)
21353 {
21354 struct ast_channel *transferee, *transferer;
21355 struct sip_dual *d;
21356 int ext;
21357 int res;
21358
21359 d = stuff;
21360 transferee = d->chan1;
21361 transferer = d->chan2;
21362
21363 ast_debug(4, "SIP Park: Transferer channel %s, Transferee %s\n", transferer->name, transferee->name);
21364
21365 res = ast_park_call_exten(transferee, transferer, d->park_exten, d->park_context, 0, &ext);
21366
21367 #ifdef WHEN_WE_KNOW_THAT_THE_CLIENT_SUPPORTS_MESSAGE
21368 if (res) {
21369 transmit_message_with_text(transferer->tech_pvt, "Unable to park call.\n");
21370 } else {
21371
21372 sprintf(buf, "Call parked on extension '%d'", ext);
21373 transmit_message_with_text(transferer->tech_pvt, buf);
21374 }
21375 #endif
21376
21377
21378
21379 if (!res) {
21380
21381 append_history(transferer->tech_pvt, "SIPpark", "Parked call on %d", ext);
21382 transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "200 OK", TRUE);
21383 transferer->hangupcause = AST_CAUSE_NORMAL_CLEARING;
21384 ast_hangup(transferer);
21385 ast_debug(1, "SIP Call parked on extension '%d'\n", ext);
21386 } else {
21387 transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "503 Service Unavailable", TRUE);
21388 append_history(transferer->tech_pvt, "SIPpark", "Parking failed\n");
21389 ast_debug(1, "SIP Call parked failed \n");
21390
21391 }
21392 deinit_req(&d->req);
21393 ast_free(d->park_exten);
21394 ast_free(d->park_context);
21395 ast_free(d);
21396 return NULL;
21397 }
21398
21399
21400 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)
21401 {
21402 struct sip_dual *d;
21403 struct ast_channel *transferee, *transferer;
21404 pthread_t th;
21405
21406 transferee = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan1->accountcode, chan1->exten, chan1->context, chan1->linkedid, chan1->amaflags, "Parking/%s", chan1->name);
21407 transferer = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan2->accountcode, chan2->exten, chan2->context, chan2->linkedid, chan2->amaflags, "SIPPeer/%s", chan2->name);
21408 d = ast_calloc(1, sizeof(*d));
21409 if (!transferee || !transferer || !d) {
21410 if (transferee) {
21411 ast_hangup(transferee);
21412 }
21413 if (transferer) {
21414 ast_hangup(transferer);
21415 }
21416 ast_free(d);
21417 return -1;
21418 }
21419 d->park_exten = ast_strdup(park_exten);
21420 d->park_context = ast_strdup(park_context);
21421 if (!d->park_exten || !d->park_context) {
21422 ast_hangup(transferee);
21423 ast_hangup(transferer);
21424 ast_free(d->park_exten);
21425 ast_free(d->park_context);
21426 ast_free(d);
21427 return -1;
21428 }
21429
21430
21431 transferee->readformat = chan1->readformat;
21432 transferee->writeformat = chan1->writeformat;
21433
21434
21435 if (ast_channel_masquerade(transferee, chan1)) {
21436 ast_hangup(transferee);
21437 ast_hangup(transferer);
21438 ast_free(d->park_exten);
21439 ast_free(d->park_context);
21440 ast_free(d);
21441 return -1;
21442 }
21443
21444
21445 ast_copy_string(transferee->context, chan1->context, sizeof(transferee->context));
21446 ast_copy_string(transferee->exten, chan1->exten, sizeof(transferee->exten));
21447 transferee->priority = chan1->priority;
21448
21449 ast_do_masquerade(transferee);
21450
21451
21452
21453
21454
21455 transferer->readformat = chan2->readformat;
21456 transferer->writeformat = chan2->writeformat;
21457 ast_string_field_set(transferer, parkinglot, chan2->parkinglot);
21458
21459
21460 if (ast_channel_masquerade(transferer, chan2)) {
21461 ast_hangup(transferer);
21462 ast_free(d->park_exten);
21463 ast_free(d->park_context);
21464 ast_free(d);
21465 return -1;
21466 }
21467
21468
21469 ast_copy_string(transferer->context, chan2->context, sizeof(transferer->context));
21470 ast_copy_string(transferer->exten, chan2->exten, sizeof(transferer->exten));
21471 transferer->priority = chan2->priority;
21472
21473 ast_do_masquerade(transferer);
21474
21475
21476 copy_request(&d->req, req);
21477 d->chan1 = transferee;
21478 d->chan2 = transferer;
21479 d->seqno = seqno;
21480 if (ast_pthread_create_detached_background(&th, NULL, sip_park_thread, d) < 0) {
21481
21482 deinit_req(&d->req);
21483 ast_free(d->park_exten);
21484 ast_free(d->park_context);
21485 ast_free(d);
21486
21487 return -1;
21488 }
21489 return 0;
21490 }
21491
21492
21493
21494
21495
21496 static void *sip_pickup_thread(void *stuff)
21497 {
21498 struct ast_channel *chan;
21499 chan = stuff;
21500
21501 if (ast_pickup_call(chan)) {
21502 chan->hangupcause = AST_CAUSE_CALL_REJECTED;
21503 } else {
21504 chan->hangupcause = AST_CAUSE_NORMAL_CLEARING;
21505 }
21506 ast_hangup(chan);
21507 ast_channel_unref(chan);
21508 chan = NULL;
21509 return NULL;
21510 }
21511
21512
21513
21514
21515 static int sip_pickup(struct ast_channel *chan)
21516 {
21517 pthread_t threadid;
21518
21519 ast_channel_ref(chan);
21520
21521 if (ast_pthread_create_detached_background(&threadid, NULL, sip_pickup_thread, chan)) {
21522 ast_debug(1, "Unable to start Group pickup thread on channel %s\n", chan->name);
21523 ast_channel_unref(chan);
21524 return -1;
21525 }
21526 ast_debug(1, "Started Group pickup thread on channel %s\n", chan->name);
21527 return 0;
21528 }
21529
21530
21531
21532
21533
21534 static void ast_quiet_chan(struct ast_channel *chan)
21535 {
21536 if (chan && chan->_state == AST_STATE_UP) {
21537 if (ast_test_flag(chan, AST_FLAG_MOH))
21538 ast_moh_stop(chan);
21539 else if (chan->generatordata)
21540 ast_deactivate_generator(chan);
21541 }
21542 }
21543
21544
21545
21546 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target)
21547 {
21548 int res = 0;
21549 struct ast_channel *peera = NULL,
21550 *peerb = NULL,
21551 *peerc = NULL,
21552 *peerd = NULL;
21553
21554
21555
21556
21557 ast_debug(4, "Sip transfer:--------------------\n");
21558 if (transferer->chan1)
21559 ast_debug(4, "-- Transferer to PBX channel: %s State %s\n", transferer->chan1->name, ast_state2str(transferer->chan1->_state));
21560 else
21561 ast_debug(4, "-- No transferer first channel - odd??? \n");
21562 if (target->chan1)
21563 ast_debug(4, "-- Transferer to PBX second channel (target): %s State %s\n", target->chan1->name, ast_state2str(target->chan1->_state));
21564 else
21565 ast_debug(4, "-- No target first channel ---\n");
21566 if (transferer->chan2)
21567 ast_debug(4, "-- Bridged call to transferee: %s State %s\n", transferer->chan2->name, ast_state2str(transferer->chan2->_state));
21568 else
21569 ast_debug(4, "-- No bridged call to transferee\n");
21570 if (target->chan2)
21571 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)");
21572 else
21573 ast_debug(4, "-- No target second channel ---\n");
21574 ast_debug(4, "-- END Sip transfer:--------------------\n");
21575 if (transferer->chan2) {
21576 peera = transferer->chan1;
21577 peerb = target->chan1;
21578 peerc = transferer->chan2;
21579 peerd = target->chan2;
21580 ast_debug(3, "SIP transfer: Four channels to handle\n");
21581 } else if (target->chan2) {
21582 peera = target->chan1;
21583 peerb = transferer->chan1;
21584 peerc = target->chan2;
21585 peerd = transferer->chan2;
21586 ast_debug(3, "SIP transfer: Three channels to handle\n");
21587 }
21588
21589 if (peera && peerb && peerc && (peerb != peerc)) {
21590 ast_quiet_chan(peera);
21591 ast_quiet_chan(peerb);
21592 ast_quiet_chan(peerc);
21593 if (peerd)
21594 ast_quiet_chan(peerd);
21595
21596 ast_debug(4, "SIP transfer: trying to masquerade %s into %s\n", peerc->name, peerb->name);
21597 if (ast_channel_masquerade(peerb, peerc)) {
21598 ast_log(LOG_WARNING, "Failed to masquerade %s into %s\n", peerb->name, peerc->name);
21599 res = -1;
21600 } else
21601 ast_debug(4, "SIP transfer: Succeeded to masquerade channels.\n");
21602 return res;
21603 } else {
21604 ast_log(LOG_NOTICE, "SIP Transfer attempted with no appropriate bridged calls to transfer\n");
21605 if (transferer->chan1)
21606 ast_softhangup_nolock(transferer->chan1, AST_SOFTHANGUP_DEV);
21607 if (target->chan1)
21608 ast_softhangup_nolock(target->chan1, AST_SOFTHANGUP_DEV);
21609 return -1;
21610 }
21611 return 0;
21612 }
21613
21614
21615
21616
21617
21618
21619 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize)
21620 {
21621 const char *thetag;
21622
21623 if (!tagbuf)
21624 return NULL;
21625 tagbuf[0] = '\0';
21626 thetag = get_header(req, header);
21627 thetag = strcasestr(thetag, ";tag=");
21628 if (thetag) {
21629 thetag += 5;
21630 ast_copy_string(tagbuf, thetag, tagbufsize);
21631 return strsep(&tagbuf, ";");
21632 }
21633 return NULL;
21634 }
21635
21636 static int handle_cc_notify(struct sip_pvt *pvt, struct sip_request *req)
21637 {
21638 struct sip_monitor_instance *monitor_instance = ao2_callback(sip_monitor_instances, 0,
21639 find_sip_monitor_instance_by_subscription_pvt, pvt);
21640 const char *status = get_body(req, "cc-state", ':');
21641 struct cc_epa_entry *cc_entry;
21642 char *uri;
21643
21644 if (!monitor_instance) {
21645 transmit_response(pvt, "400 Bad Request", req);
21646 return -1;
21647 }
21648
21649 if (ast_strlen_zero(status)) {
21650 ao2_ref(monitor_instance, -1);
21651 transmit_response(pvt, "400 Bad Request", req);
21652 return -1;
21653 }
21654
21655 if (!strcmp(status, "queued")) {
21656
21657
21658
21659
21660 ast_cc_monitor_request_acked(monitor_instance->core_id, "SIP endpoint %s accepted request", monitor_instance->device_name);
21661 transmit_response(pvt, "200 OK", req);
21662 ao2_ref(monitor_instance, -1);
21663 return 0;
21664 }
21665
21666
21667 uri = get_body(req, "cc-URI", ':');
21668 if (ast_strlen_zero(uri)) {
21669 uri = get_in_brackets((char *)get_header(req, "From"));
21670 }
21671
21672 ast_string_field_set(monitor_instance, notify_uri, uri);
21673 if (monitor_instance->suspension_entry) {
21674 cc_entry = monitor_instance->suspension_entry->instance_data;
21675 if (cc_entry->current_state == CC_CLOSED) {
21676
21677
21678
21679
21680
21681 construct_pidf_body(CC_CLOSED, monitor_instance->suspension_entry->body,
21682 sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
21683 transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_INITIAL, monitor_instance->notify_uri);
21684 } else {
21685 ast_cc_monitor_callee_available(monitor_instance->core_id, "SIP monitored callee has become available");
21686 }
21687 } else {
21688 ast_cc_monitor_callee_available(monitor_instance->core_id, "SIP monitored callee has become available");
21689 }
21690 ao2_ref(monitor_instance, -1);
21691 transmit_response(pvt, "200 OK", req);
21692
21693 return 0;
21694 }
21695
21696
21697 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e)
21698 {
21699
21700
21701 int res = 0;
21702 const char *event = get_header(req, "Event");
21703 char *sep;
21704
21705 if( (sep = strchr(event, ';')) ) {
21706 *sep++ = '\0';
21707 }
21708
21709 if (sipdebug)
21710 ast_debug(2, "Got NOTIFY Event: %s\n", event);
21711
21712 if (!strcmp(event, "refer")) {
21713
21714
21715
21716
21717
21718 char buf[1024];
21719 char *cmd, *code;
21720 int respcode;
21721 int success = TRUE;
21722
21723
21724
21725
21726
21727
21728
21729
21730 if (strncasecmp(get_header(req, "Content-Type"), "message/sipfrag", strlen("message/sipfrag"))) {
21731
21732 transmit_response(p, "400 Bad request", req);
21733 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21734 return -1;
21735 }
21736
21737
21738 if (get_msg_text(buf, sizeof(buf), req)) {
21739 ast_log(LOG_WARNING, "Unable to retrieve attachment from NOTIFY %s\n", p->callid);
21740 transmit_response(p, "400 Bad request", req);
21741 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21742 return -1;
21743 }
21744
21745
21746
21747
21748
21749
21750
21751
21752
21753
21754
21755
21756
21757
21758
21759
21760
21761
21762
21763
21764
21765 ast_debug(3, "* SIP Transfer NOTIFY Attachment: \n---%s\n---\n", buf);
21766 cmd = ast_skip_blanks(buf);
21767 code = cmd;
21768
21769 while(*code && (*code > 32)) {
21770 code++;
21771 }
21772 *code++ = '\0';
21773 code = ast_skip_blanks(code);
21774 sep = code;
21775 sep++;
21776 while(*sep && (*sep > 32)) {
21777 sep++;
21778 }
21779 *sep++ = '\0';
21780 respcode = atoi(code);
21781 switch (respcode) {
21782 case 200:
21783
21784 break;
21785 case 301:
21786 case 302:
21787
21788 success = FALSE;
21789 break;
21790 case 503:
21791 case 603:
21792
21793 success = FALSE;
21794 break;
21795 case 0:
21796
21797 ast_log(LOG_NOTICE, "Error parsing sipfrag in NOTIFY in response to REFER.\n");
21798 success = FALSE;
21799 break;
21800 default:
21801 if (respcode < 200) {
21802
21803 success = -1;
21804 } else {
21805 ast_log(LOG_NOTICE, "Got unknown code '%d' in NOTIFY in response to REFER.\n", respcode);
21806 success = FALSE;
21807 }
21808 break;
21809 }
21810 if (success == FALSE) {
21811 ast_log(LOG_NOTICE, "Transfer failed. Sorry. Nothing further to do with this call\n");
21812 }
21813
21814 if (p->owner && success != -1) {
21815 enum ast_control_transfer message = success ? AST_TRANSFER_SUCCESS : AST_TRANSFER_FAILED;
21816 ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
21817 }
21818
21819 transmit_response(p, "200 OK", req);
21820 } else if (!strcmp(event, "message-summary")) {
21821 const char *mailbox = NULL;
21822 char *c = ast_strdupa(get_body(req, "Voice-Message", ':'));
21823
21824 if (!p->mwi) {
21825 struct sip_peer *peer = find_peer(NULL, &p->recv, TRUE, FINDPEERS, FALSE, p->socket.type);
21826
21827 if (peer) {
21828 mailbox = ast_strdupa(peer->unsolicited_mailbox);
21829 unref_peer(peer, "removing unsolicited mwi ref");
21830 }
21831 } else {
21832 mailbox = p->mwi->mailbox;
21833 }
21834
21835 if (!ast_strlen_zero(mailbox) && !ast_strlen_zero(c)) {
21836 char *old = strsep(&c, " ");
21837 char *new = strsep(&old, "/");
21838 struct ast_event *event;
21839
21840 if ((event = ast_event_new(AST_EVENT_MWI,
21841 AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox,
21842 AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, "SIP_Remote",
21843 AST_EVENT_IE_NEWMSGS, AST_EVENT_IE_PLTYPE_UINT, atoi(new),
21844 AST_EVENT_IE_OLDMSGS, AST_EVENT_IE_PLTYPE_UINT, atoi(old),
21845 AST_EVENT_IE_END))) {
21846 ast_event_queue_and_cache(event);
21847 }
21848 transmit_response(p, "200 OK", req);
21849 } else {
21850 transmit_response(p, "489 Bad event", req);
21851 res = -1;
21852 }
21853 } else if (!strcmp(event, "keep-alive")) {
21854
21855
21856 transmit_response(p, "200 OK", req);
21857 } else if (!strcmp(event, "call-completion")) {
21858 res = handle_cc_notify(p, req);
21859 } else {
21860
21861 transmit_response(p, "489 Bad event", req);
21862 res = -1;
21863 }
21864
21865 if (!p->lastinvite)
21866 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21867
21868 return res;
21869 }
21870
21871
21872
21873
21874 static int handle_request_options(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e)
21875 {
21876 const char *msg;
21877 enum sip_get_dest_result gotdest;
21878 int res;
21879
21880 if (p->lastinvite) {
21881
21882 transmit_response_with_allow(p, "200 OK", req, 0);
21883 return 0;
21884 }
21885
21886 if (sip_cfg.auth_options_requests) {
21887
21888 copy_request(&p->initreq, req);
21889 set_pvt_allowed_methods(p, req);
21890 res = check_user(p, req, SIP_OPTIONS, e, XMIT_UNRELIABLE, addr);
21891 if (res == AUTH_CHALLENGE_SENT) {
21892 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21893 return 0;
21894 }
21895 if (res < 0) {
21896 if (res == AUTH_FAKE_AUTH) {
21897 ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", get_header(req, "From"));
21898 transmit_fake_auth_response(p, SIP_OPTIONS, req, XMIT_UNRELIABLE);
21899 } else {
21900 ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", get_header(req, "From"));
21901 transmit_response(p, "403 Forbidden", req);
21902 }
21903 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21904 return 0;
21905 }
21906 }
21907
21908
21909 gotdest = get_destination(p, req, NULL);
21910 build_contact(p);
21911
21912 if (ast_strlen_zero(p->context))
21913 ast_string_field_set(p, context, sip_cfg.default_context);
21914
21915 if (ast_shutting_down()) {
21916 msg = "503 Unavailable";
21917 } else {
21918 msg = "404 Not Found";
21919 switch (gotdest) {
21920 case SIP_GET_DEST_INVALID_URI:
21921 msg = "416 Unsupported URI scheme";
21922 break;
21923 case SIP_GET_DEST_EXTEN_MATCHMORE:
21924 case SIP_GET_DEST_REFUSED:
21925 case SIP_GET_DEST_EXTEN_NOT_FOUND:
21926
21927 break;
21928 case SIP_GET_DEST_EXTEN_FOUND:
21929 msg = "200 OK";
21930 break;
21931 }
21932 }
21933 transmit_response_with_allow(p, msg, req, 0);
21934
21935
21936
21937 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21938
21939 return 0;
21940 }
21941
21942
21943
21944
21945
21946
21947
21948
21949
21950
21951
21952
21953
21954 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, uint32_t seqno, struct ast_sockaddr *addr, int *nounlock)
21955 {
21956 int earlyreplace = 0;
21957 int oneleggedreplace = 0;
21958 struct ast_channel *c = p->owner;
21959 struct ast_channel *replacecall = p->refer->refer_call->owner;
21960 struct ast_channel *targetcall;
21961
21962
21963 if (replacecall->_state == AST_STATE_RING)
21964 earlyreplace = 1;
21965
21966
21967 if (!(targetcall = ast_bridged_channel(replacecall))) {
21968
21969 if (!earlyreplace) {
21970 ast_debug(2, " Attended transfer attempted to replace call with no bridge (maybe ringing). Channel %s!\n", replacecall->name);
21971 oneleggedreplace = 1;
21972 }
21973 }
21974 if (targetcall && targetcall->_state == AST_STATE_RINGING)
21975 ast_debug(4, "SIP transfer: Target channel is in ringing state\n");
21976
21977 if (targetcall)
21978 ast_debug(4, "SIP transfer: Invite Replace incoming channel should bridge to channel %s while hanging up channel %s\n", targetcall->name, replacecall->name);
21979 else
21980 ast_debug(4, "SIP transfer: Invite Replace incoming channel should replace and hang up channel %s (one call leg)\n", replacecall->name);
21981
21982 if (req->ignore) {
21983 ast_log(LOG_NOTICE, "Ignoring this INVITE with replaces in a stupid way.\n");
21984
21985
21986
21987 transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE, FALSE);
21988
21989 if (c) {
21990 *nounlock = 1;
21991 ast_channel_unlock(c);
21992 }
21993 ast_channel_unlock(replacecall);
21994 sip_pvt_unlock(p->refer->refer_call);
21995 return 1;
21996 }
21997 if (!c) {
21998
21999 ast_log(LOG_ERROR, "Unable to create new channel. Invite/replace failed.\n");
22000 transmit_response_reliable(p, "503 Service Unavailable", req);
22001 append_history(p, "Xfer", "INVITE/Replace Failed. No new channel.");
22002 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22003 ast_channel_unlock(replacecall);
22004 sip_pvt_unlock(p->refer->refer_call);
22005 return 1;
22006 }
22007 append_history(p, "Xfer", "INVITE/Replace received");
22008
22009
22010
22011
22012
22013
22014
22015
22016
22017
22018
22019 transmit_response(p, "100 Trying", req);
22020 ast_setstate(c, AST_STATE_RING);
22021
22022
22023
22024
22025
22026 transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE, FALSE);
22027
22028 ast_setstate(c, AST_STATE_UP);
22029
22030
22031 ast_quiet_chan(replacecall);
22032 ast_quiet_chan(targetcall);
22033 ast_debug(4, "Invite/Replaces: preparing to masquerade %s into %s\n", c->name, replacecall->name);
22034
22035
22036 if (! earlyreplace && ! oneleggedreplace )
22037 ast_set_flag(&p->refer->refer_call->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
22038
22039
22040 if(ast_channel_masquerade(replacecall, c))
22041 ast_log(LOG_ERROR, "Failed to masquerade C into Replacecall\n");
22042 else
22043 ast_debug(4, "Invite/Replaces: Going to masquerade %s into %s\n", c->name, replacecall->name);
22044
22045
22046
22047
22048
22049 ast_channel_ref(c);
22050 ast_channel_unlock(replacecall);
22051 ast_channel_unlock(c);
22052 sip_pvt_unlock(p->refer->refer_call);
22053 sip_pvt_unlock(p);
22054 if (ast_do_masquerade(replacecall)) {
22055 ast_log(LOG_WARNING, "Failed to perform masquerade with INVITE replaces\n");
22056 }
22057 ast_channel_lock(c);
22058 if (earlyreplace || oneleggedreplace ) {
22059 c->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
22060 }
22061 ast_setstate(c, AST_STATE_DOWN);
22062 ast_channel_unlock(c);
22063
22064
22065 c->tech_pvt = dialog_unref(c->tech_pvt, "unref dialog c->tech_pvt");
22066
22067
22068 ast_hangup(c);
22069
22070 *nounlock = 1;
22071
22072 sip_pvt_lock(p);
22073 ast_channel_unref(c);
22074 return 0;
22075 }
22076
22077
22078 static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context)
22079 {
22080 struct ast_str *str = ast_str_alloca(AST_MAX_EXTENSION + AST_MAX_CONTEXT + 2);
22081 struct ast_app *pickup = pbx_findapp("Pickup");
22082
22083 if (!pickup) {
22084 ast_log(LOG_ERROR, "Unable to perform pickup: Application 'Pickup' not loaded (app_directed_pickup.so).\n");
22085 return -1;
22086 }
22087
22088 ast_str_set(&str, 0, "%s@%s", extension, sip_cfg.notifycid == IGNORE_CONTEXT ? "PICKUPMARK" : context);
22089
22090 ast_debug(2, "About to call Pickup(%s)\n", str->str);
22091
22092
22093
22094
22095 pbx_exec(channel, pickup, str->str);
22096
22097 return 0;
22098 }
22099
22100
22101 static int sip_t38_abort(const void *data)
22102 {
22103 struct sip_pvt *p = (struct sip_pvt *) data;
22104
22105 sip_pvt_lock(p);
22106
22107
22108
22109
22110
22111 if (p->t38id != -1) {
22112 change_t38_state(p, T38_DISABLED);
22113 transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
22114 p->t38id = -1;
22115 dialog_unref(p, "unref the dialog ptr from sip_t38_abort, because it held a dialog ptr");
22116 }
22117 sip_pvt_unlock(p);
22118 return 0;
22119 }
22120
22121
22122
22123
22124
22125
22126
22127
22128
22129
22130
22131
22132 static int handle_request_update(struct sip_pvt *p, struct sip_request *req)
22133 {
22134 if (ast_strlen_zero(get_header(req, "X-Asterisk-rpid-update"))) {
22135 transmit_response(p, "501 Method Not Implemented", req);
22136 return 0;
22137 }
22138 if (!p->owner) {
22139 transmit_response(p, "481 Call/Transaction Does Not Exist", req);
22140 return 0;
22141 }
22142 if (get_rpid(p, req)) {
22143 struct ast_party_connected_line connected;
22144 struct ast_set_party_connected_line update_connected;
22145
22146 ast_party_connected_line_init(&connected);
22147 memset(&update_connected, 0, sizeof(update_connected));
22148
22149 update_connected.id.number = 1;
22150 connected.id.number.valid = 1;
22151 connected.id.number.str = (char *) p->cid_num;
22152 connected.id.number.presentation = p->callingpres;
22153
22154 update_connected.id.name = 1;
22155 connected.id.name.valid = 1;
22156 connected.id.name.str = (char *) p->cid_name;
22157 connected.id.name.presentation = p->callingpres;
22158
22159 connected.id.tag = (char *) p->cid_tag;
22160 connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
22161 ast_channel_queue_connected_line_update(p->owner, &connected, &update_connected);
22162 }
22163 transmit_response(p, "200 OK", req);
22164 return 0;
22165 }
22166
22167
22168
22169
22170
22171
22172
22173
22174 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)
22175 {
22176 int res = 1;
22177 int gotdest;
22178 const char *p_replaces;
22179 char *replace_id = NULL;
22180 int refer_locked = 0;
22181 const char *required;
22182 unsigned int required_profile = 0;
22183 struct ast_channel *c = NULL;
22184 struct sip_peer *authpeer = NULL;
22185 int reinvite = 0;
22186 int rtn;
22187 struct ast_party_redirecting redirecting;
22188 struct ast_set_party_redirecting update_redirecting;
22189
22190 const char *p_uac_se_hdr;
22191 const char *p_uac_min_se;
22192 int uac_max_se = -1;
22193 int uac_min_se = -1;
22194 int st_active = FALSE;
22195 int st_interval = 0;
22196 enum st_refresher st_ref;
22197 int dlg_min_se = -1;
22198 struct {
22199 char exten[AST_MAX_EXTENSION];
22200 char context[AST_MAX_CONTEXT];
22201 } pickup = {
22202 .exten = "",
22203 };
22204 st_ref = SESSION_TIMER_REFRESHER_AUTO;
22205
22206
22207 if (!p->sipoptions) {
22208 const char *supported = get_header(req, "Supported");
22209 if (!ast_strlen_zero(supported)) {
22210 p->sipoptions = parse_sip_options(supported, NULL, 0);
22211 }
22212 }
22213
22214
22215 required = get_header(req, "Require");
22216 if (!ast_strlen_zero(required)) {
22217 char unsupported[256] = { 0, };
22218 required_profile = parse_sip_options(required, unsupported, ARRAY_LEN(unsupported));
22219
22220
22221
22222 if (!ast_strlen_zero(unsupported)) {
22223 transmit_response_with_unsupported(p, "420 Bad extension (unsupported)", req, unsupported);
22224 ast_log(LOG_WARNING, "Received SIP INVITE with unsupported required extension: required:%s unsupported:%s\n", required, unsupported);
22225 p->invitestate = INV_COMPLETED;
22226 if (!p->lastinvite)
22227 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22228 res = -1;
22229 goto request_invite_cleanup;
22230 }
22231 }
22232
22233
22234
22235 p->sipoptions |= required_profile;
22236 p->reqsipoptions = required_profile;
22237
22238
22239 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) {
22240
22241
22242
22243
22244
22245 int different;
22246 const char *initial_rlPart2 = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
22247 const char *this_rlPart2 = REQ_OFFSET_TO_STR(req, rlPart2);
22248 if (sip_cfg.pedanticsipchecking)
22249 different = sip_uri_cmp(initial_rlPart2, this_rlPart2);
22250 else
22251 different = strcmp(initial_rlPart2, this_rlPart2);
22252 if (!different) {
22253 transmit_response(p, "482 Loop Detected", req);
22254 p->invitestate = INV_COMPLETED;
22255 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22256 res = 0;
22257 goto request_invite_cleanup;
22258 } else {
22259
22260
22261
22262
22263
22264
22265
22266 char *uri = ast_strdupa(this_rlPart2);
22267 char *at = strchr(uri, '@');
22268 char *peerorhost;
22269 ast_debug(2, "Potential spiral detected. Original RURI was %s, new RURI is %s\n", initial_rlPart2, this_rlPart2);
22270 transmit_response(p, "100 Trying", req);
22271 if (at) {
22272 *at = '\0';
22273 }
22274
22275 if ((peerorhost = strchr(uri, ':'))) {
22276 *peerorhost++ = '\0';
22277 }
22278 ast_string_field_set(p, theirtag, NULL);
22279
22280
22281 ast_string_field_set(p->owner, call_forward, peerorhost);
22282 ast_queue_control(p->owner, AST_CONTROL_BUSY);
22283 res = 0;
22284 goto request_invite_cleanup;
22285 }
22286 }
22287
22288 if (!req->ignore && p->pendinginvite) {
22289 if (!ast_test_flag(&p->flags[0], SIP_OUTGOING) && (p->invitestate == INV_COMPLETED || p->invitestate == INV_TERMINATED)) {
22290
22291
22292
22293
22294
22295
22296
22297
22298
22299
22300 __sip_ack(p, p->pendinginvite, 1, 0);
22301 } else {
22302
22303 p->glareinvite = seqno;
22304 if (p->rtp && find_sdp(req)) {
22305 struct ast_sockaddr addr;
22306 if (get_ip_and_port_from_sdp(req, SDP_AUDIO, &addr)) {
22307 ast_log(LOG_WARNING, "Failed to set an alternate media source on glared reinvite. Audio may not work properly on this call.\n");
22308 } else {
22309 ast_rtp_instance_set_alt_remote_address(p->rtp, &addr);
22310 }
22311 if (p->vrtp) {
22312 if (get_ip_and_port_from_sdp(req, SDP_VIDEO, &addr)) {
22313 ast_log(LOG_WARNING, "Failed to set an alternate media source on glared reinvite. Video may not work properly on this call.\n");
22314 } else {
22315 ast_rtp_instance_set_alt_remote_address(p->vrtp, &addr);
22316 }
22317 }
22318 }
22319 transmit_response_reliable(p, "491 Request Pending", req);
22320 p->pendinginvite = seqno;
22321 check_via(p, req);
22322 copy_request(&p->initreq, req);
22323 ast_debug(1, "Got INVITE on call where we already have pending INVITE, deferring that - %s\n", p->callid);
22324
22325 res = 0;
22326 goto request_invite_cleanup;
22327 }
22328 }
22329
22330 p_replaces = get_header(req, "Replaces");
22331 if (!ast_strlen_zero(p_replaces)) {
22332
22333 char *ptr;
22334 char *fromtag = NULL;
22335 char *totag = NULL;
22336 char *start, *to;
22337 int error = 0;
22338
22339 if (p->owner) {
22340 ast_debug(3, "INVITE w Replaces on existing call? Refusing action. [%s]\n", p->callid);
22341 transmit_response_reliable(p, "400 Bad request", req);
22342 p->pendinginvite = seqno;
22343 check_via(p, req);
22344 copy_request(&p->initreq, req);
22345
22346 res = -1;
22347 goto request_invite_cleanup;
22348 }
22349
22350 if (sipdebug)
22351 ast_debug(3, "INVITE part of call transfer. Replaces [%s]\n", p_replaces);
22352
22353 replace_id = ast_strdupa(p_replaces);
22354 ast_uri_decode(replace_id);
22355
22356 if (!p->refer && !sip_refer_allocate(p)) {
22357 transmit_response_reliable(p, "500 Server Internal Error", req);
22358 append_history(p, "Xfer", "INVITE/Replace Failed. Out of memory.");
22359 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22360 p->invitestate = INV_COMPLETED;
22361 p->pendinginvite = seqno;
22362 check_via(p, req);
22363 copy_request(&p->initreq, req);
22364 res = -1;
22365 goto request_invite_cleanup;
22366 }
22367
22368
22369
22370
22371
22372
22373
22374
22375
22376
22377 replace_id = ast_skip_blanks(replace_id);
22378
22379 start = replace_id;
22380 while ( (ptr = strsep(&start, ";")) ) {
22381 ptr = ast_skip_blanks(ptr);
22382 if ( (to = strcasestr(ptr, "to-tag=") ) )
22383 totag = to + 7;
22384 else if ( (to = strcasestr(ptr, "from-tag=") ) ) {
22385 fromtag = to + 9;
22386 fromtag = strsep(&fromtag, "&");
22387 }
22388 }
22389
22390 if (sipdebug)
22391 ast_debug(4, "Invite/replaces: Will use Replace-Call-ID : %s Fromtag: %s Totag: %s\n",
22392 replace_id,
22393 fromtag ? fromtag : "<no from tag>",
22394 totag ? totag : "<no to tag>");
22395
22396
22397
22398
22399
22400 if (strncmp(replace_id, "pickup-", 7) == 0) {
22401 struct sip_pvt *subscription = NULL;
22402 replace_id += 7;
22403
22404 if ((subscription = get_sip_pvt_byid_locked(replace_id, totag, fromtag)) == NULL) {
22405 ast_log(LOG_NOTICE, "Unable to find subscription with call-id: %s\n", replace_id);
22406 transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
22407 error = 1;
22408 } else {
22409 ast_log(LOG_NOTICE, "Trying to pick up %s@%s\n", subscription->exten, subscription->context);
22410 ast_copy_string(pickup.exten, subscription->exten, sizeof(pickup.exten));
22411 ast_copy_string(pickup.context, subscription->context, sizeof(pickup.context));
22412 sip_pvt_unlock(subscription);
22413 if (subscription->owner) {
22414 ast_channel_unlock(subscription->owner);
22415 }
22416 }
22417 }
22418
22419
22420 if (!error && ast_strlen_zero(pickup.exten) && (p->refer->refer_call = get_sip_pvt_byid_locked(replace_id, totag, fromtag)) == NULL) {
22421 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existent call id (%s)!\n", replace_id);
22422 transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
22423 error = 1;
22424 } else {
22425 refer_locked = 1;
22426 }
22427
22428
22429
22430
22431
22432 if (p->refer->refer_call == p) {
22433 ast_log(LOG_NOTICE, "INVITE with replaces into it's own call id (%s == %s)!\n", replace_id, p->callid);
22434 p->refer->refer_call = dialog_unref(p->refer->refer_call, "unref dialog p->refer->refer_call");
22435 transmit_response_reliable(p, "400 Bad request", req);
22436 error = 1;
22437 }
22438
22439 if (!error && ast_strlen_zero(pickup.exten) && !p->refer->refer_call->owner) {
22440
22441 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existing call id (%s)!\n", replace_id);
22442
22443 transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replace)", req);
22444 error = 1;
22445 }
22446
22447 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) {
22448 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-ringing or active call id (%s)!\n", replace_id);
22449 transmit_response_reliable(p, "603 Declined (Replaces)", req);
22450 error = 1;
22451 }
22452
22453 if (error) {
22454 append_history(p, "Xfer", "INVITE/Replace Failed.");
22455 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22456 sip_pvt_unlock(p);
22457 if (p->refer->refer_call) {
22458 sip_pvt_unlock(p->refer->refer_call);
22459 if (p->refer->refer_call->owner) {
22460 ast_channel_unlock(p->refer->refer_call->owner);
22461 }
22462 }
22463 refer_locked = 0;
22464 p->invitestate = INV_COMPLETED;
22465 p->pendinginvite = seqno;
22466 check_via(p, req);
22467 copy_request(&p->initreq, req);
22468 res = -1;
22469 goto request_invite_cleanup;
22470 }
22471 }
22472
22473
22474
22475
22476 if (!req->ignore) {
22477 int newcall = (p->initreq.headers ? TRUE : FALSE);
22478
22479 if (sip_cancel_destroy(p))
22480 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
22481
22482 p->pendinginvite = seqno;
22483 check_via(p, req);
22484
22485 copy_request(&p->initreq, req);
22486 if (sipdebug)
22487 ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
22488 if (!p->owner) {
22489 if (debug)
22490 ast_verbose("Using INVITE request as basis request - %s\n", p->callid);
22491 if (newcall)
22492 append_history(p, "Invite", "New call: %s", p->callid);
22493 parse_ok_contact(p, req);
22494 } else {
22495 ast_clear_flag(&p->flags[0], SIP_OUTGOING);
22496 if (get_rpid(p, req)) {
22497 struct ast_party_connected_line connected;
22498 struct ast_set_party_connected_line update_connected;
22499
22500 ast_party_connected_line_init(&connected);
22501 memset(&update_connected, 0, sizeof(update_connected));
22502
22503 update_connected.id.number = 1;
22504 connected.id.number.valid = 1;
22505 connected.id.number.str = (char *) p->cid_num;
22506 connected.id.number.presentation = p->callingpres;
22507
22508 update_connected.id.name = 1;
22509 connected.id.name.valid = 1;
22510 connected.id.name.str = (char *) p->cid_name;
22511 connected.id.name.presentation = p->callingpres;
22512
22513 connected.id.tag = (char *) p->cid_tag;
22514 connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
22515 ast_channel_queue_connected_line_update(p->owner, &connected,
22516 &update_connected);
22517 }
22518
22519 if (find_sdp(req)) {
22520 if (process_sdp(p, req, SDP_T38_INITIATE)) {
22521 if (!ast_strlen_zero(get_header(req, "Content-Encoding"))) {
22522
22523
22524
22525 transmit_response_reliable(p, "415 Unsupported Media type", req);
22526 } else {
22527 transmit_response_reliable(p, "488 Not acceptable here", req);
22528 }
22529 if (!p->lastinvite)
22530 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22531 res = -1;
22532 goto request_invite_cleanup;
22533 }
22534 ast_queue_control(p->owner, AST_CONTROL_SRCUPDATE);
22535 } else {
22536 p->jointcapability = p->capability;
22537 ast_debug(1, "Hm.... No sdp for the moment\n");
22538
22539
22540
22541 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
22542 ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
22543
22544 ast_queue_frame(p->owner, &ast_null_frame);
22545 change_hold_state(p, req, FALSE, 0);
22546 }
22547 }
22548 if (p->do_history)
22549 append_history(p, "ReInv", "Re-invite received");
22550 }
22551 } else if (debug)
22552 ast_verbose("Ignoring this INVITE request\n");
22553
22554 if (!p->lastinvite && !req->ignore && !p->owner) {
22555
22556
22557 int cc_recall_core_id = -1;
22558 set_pvt_allowed_methods(p, req);
22559 res = check_user_full(p, req, SIP_INVITE, e, XMIT_RELIABLE, addr, &authpeer);
22560 if (res == AUTH_CHALLENGE_SENT) {
22561 p->invitestate = INV_COMPLETED;
22562 res = 0;
22563 goto request_invite_cleanup;
22564 }
22565 if (res < 0) {
22566 if (res == AUTH_FAKE_AUTH) {
22567 ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", get_header(req, "From"));
22568 transmit_fake_auth_response(p, SIP_INVITE, req, XMIT_RELIABLE);
22569 } else {
22570 ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", get_header(req, "From"));
22571 transmit_response_reliable(p, "403 Forbidden", req);
22572 }
22573 p->invitestate = INV_COMPLETED;
22574 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22575 res = 0;
22576 goto request_invite_cleanup;
22577 }
22578
22579
22580 if (p->relatedpeer) {
22581 p->relatedpeer = unref_peer(p->relatedpeer,"unsetting the relatedpeer field in the dialog, before it is set to something else.");
22582 }
22583 if (authpeer) {
22584 p->relatedpeer = ref_peer(authpeer, "setting dialog's relatedpeer pointer");
22585 }
22586
22587 req->authenticated = 1;
22588
22589
22590 if (find_sdp(req)) {
22591 if (process_sdp(p, req, SDP_T38_INITIATE)) {
22592
22593
22594
22595 if (!ast_strlen_zero(get_header(req, "Content-Encoding"))) {
22596 transmit_response_reliable(p, "415 Unsupported Media type", req);
22597 } else {
22598
22599 transmit_response_reliable(p, "488 Not acceptable here", req);
22600 }
22601 p->invitestate = INV_COMPLETED;
22602 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22603 ast_debug(1, "No compatible codecs for this SIP call.\n");
22604 res = -1;
22605 goto request_invite_cleanup;
22606 }
22607 } else {
22608 p->jointcapability = p->capability;
22609 ast_debug(2, "No SDP in Invite, third party call control\n");
22610 }
22611
22612
22613
22614 if (p->owner)
22615 ast_queue_frame(p->owner, &ast_null_frame);
22616
22617
22618
22619 if (ast_strlen_zero(p->context))
22620 ast_string_field_set(p, context, sip_cfg.default_context);
22621
22622
22623
22624 ast_debug(1, "Checking SIP call limits for device %s\n", p->username);
22625 if ((res = update_call_counter(p, INC_CALL_LIMIT))) {
22626 if (res < 0) {
22627 ast_log(LOG_NOTICE, "Failed to place call for device %s, too many calls\n", p->username);
22628 transmit_response_reliable(p, "480 Temporarily Unavailable (Call limit) ", req);
22629 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22630 p->invitestate = INV_COMPLETED;
22631 }
22632 res = 0;
22633 goto request_invite_cleanup;
22634 }
22635 gotdest = get_destination(p, NULL, &cc_recall_core_id);
22636 extract_uri(p, req);
22637 build_contact(p);
22638
22639 if (p->rtp) {
22640 ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
22641 ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
22642 }
22643
22644 if (!replace_id && (gotdest != SIP_GET_DEST_EXTEN_FOUND)) {
22645 switch(gotdest) {
22646 case SIP_GET_DEST_INVALID_URI:
22647 transmit_response_reliable(p, "416 Unsupported URI scheme", req);
22648 break;
22649 case SIP_GET_DEST_EXTEN_MATCHMORE:
22650 if (ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP)
22651 == SIP_PAGE2_ALLOWOVERLAP_YES) {
22652 transmit_response_reliable(p, "484 Address Incomplete", req);
22653 break;
22654 }
22655
22656
22657
22658
22659
22660
22661
22662
22663
22664 case SIP_GET_DEST_EXTEN_NOT_FOUND:
22665 case SIP_GET_DEST_REFUSED:
22666 default:
22667 {
22668 char *decoded_exten = ast_strdupa(p->exten);
22669 transmit_response_reliable(p, "404 Not Found", req);
22670 ast_uri_decode(decoded_exten);
22671 ast_log(LOG_NOTICE, "Call from '%s' (%s) to extension"
22672 " '%s' rejected because extension not found in context '%s'.\n",
22673 S_OR(p->username, p->peername), ast_sockaddr_stringify(&p->recv), decoded_exten, p->context);
22674 }
22675 }
22676
22677 p->invitestate = INV_COMPLETED;
22678 update_call_counter(p, DEC_CALL_LIMIT);
22679 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22680 res = 0;
22681 goto request_invite_cleanup;
22682 } else {
22683
22684
22685
22686 if (ast_strlen_zero(p->exten))
22687 ast_string_field_set(p, exten, "s");
22688
22689
22690 make_our_tag(p->tag, sizeof(p->tag));
22691
22692
22693 c = sip_new(p, AST_STATE_DOWN, S_OR(p->peername, NULL), NULL);
22694 if (cc_recall_core_id != -1) {
22695 ast_setup_cc_recall_datastore(c, cc_recall_core_id);
22696 ast_cc_agent_set_interfaces_chanvar(c);
22697 }
22698 *recount = 1;
22699
22700
22701 build_route(p, req, 0, 0);
22702
22703 if (c) {
22704 ast_party_redirecting_init(&redirecting);
22705 memset(&update_redirecting, 0, sizeof(update_redirecting));
22706 change_redirecting_information(p, req, &redirecting, &update_redirecting,
22707 FALSE);
22708 ast_channel_set_redirecting(c, &redirecting, &update_redirecting);
22709 ast_party_redirecting_free(&redirecting);
22710 }
22711 }
22712 } else {
22713 ast_party_redirecting_init(&redirecting);
22714 memset(&update_redirecting, 0, sizeof(update_redirecting));
22715 if (sipdebug) {
22716 if (!req->ignore)
22717 ast_debug(2, "Got a SIP re-invite for call %s\n", p->callid);
22718 else
22719 ast_debug(2, "Got a SIP re-transmit of INVITE for call %s\n", p->callid);
22720 }
22721 if (!req->ignore)
22722 reinvite = 1;
22723 c = p->owner;
22724 change_redirecting_information(p, req, &redirecting, &update_redirecting, FALSE);
22725 if (c) {
22726 ast_channel_set_redirecting(c, &redirecting, &update_redirecting);
22727 }
22728 ast_party_redirecting_free(&redirecting);
22729 }
22730
22731
22732 if ((p->sipoptions & SIP_OPT_TIMER) && !ast_strlen_zero(get_header(req, "Session-Expires"))) {
22733
22734
22735 ast_debug(2, "Incoming INVITE with 'timer' option supported and \"Session-Expires\" header.\n");
22736
22737
22738 if (!p->stimer)
22739 sip_st_alloc(p);
22740
22741
22742 p_uac_se_hdr = get_header(req, "Session-Expires");
22743 rtn = parse_session_expires(p_uac_se_hdr, &uac_max_se, &st_ref);
22744 if (rtn != 0) {
22745 transmit_response_reliable(p, "400 Session-Expires Invalid Syntax", req);
22746 p->invitestate = INV_COMPLETED;
22747 if (!p->lastinvite) {
22748 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22749 }
22750 res = -1;
22751 goto request_invite_cleanup;
22752 }
22753
22754
22755 p_uac_min_se = get_header(req, "Min-SE");
22756 if (!ast_strlen_zero(p_uac_min_se)) {
22757 rtn = parse_minse(p_uac_min_se, &uac_min_se);
22758 if (rtn != 0) {
22759 transmit_response_reliable(p, "400 Min-SE Invalid Syntax", req);
22760 p->invitestate = INV_COMPLETED;
22761 if (!p->lastinvite) {
22762 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22763 }
22764 res = -1;
22765 goto request_invite_cleanup;
22766 }
22767 }
22768
22769 dlg_min_se = st_get_se(p, FALSE);
22770 switch (st_get_mode(p, 1)) {
22771 case SESSION_TIMER_MODE_ACCEPT:
22772 case SESSION_TIMER_MODE_ORIGINATE:
22773 if (uac_max_se > 0 && uac_max_se < dlg_min_se) {
22774 transmit_response_with_minse(p, "422 Session Interval Too Small", req, dlg_min_se);
22775 p->invitestate = INV_COMPLETED;
22776 if (!p->lastinvite) {
22777 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22778 }
22779 res = -1;
22780 goto request_invite_cleanup;
22781 }
22782
22783 p->stimer->st_active_peer_ua = TRUE;
22784 st_active = TRUE;
22785 if (st_ref == SESSION_TIMER_REFRESHER_AUTO) {
22786 st_ref = st_get_refresher(p);
22787 }
22788
22789 if (uac_max_se > 0) {
22790 int dlg_max_se = st_get_se(p, TRUE);
22791 if (dlg_max_se >= uac_min_se) {
22792 st_interval = (uac_max_se < dlg_max_se) ? uac_max_se : dlg_max_se;
22793 } else {
22794 st_interval = uac_max_se;
22795 }
22796 } else {
22797
22798 st_interval = global_max_se;
22799 }
22800 break;
22801
22802 case SESSION_TIMER_MODE_REFUSE:
22803 if (p->reqsipoptions & SIP_OPT_TIMER) {
22804 transmit_response_with_unsupported(p, "420 Option Disabled", req, required);
22805 ast_log(LOG_WARNING, "Received SIP INVITE with supported but disabled option: %s\n", required);
22806 p->invitestate = INV_COMPLETED;
22807 if (!p->lastinvite) {
22808 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22809 }
22810 res = -1;
22811 goto request_invite_cleanup;
22812 }
22813 break;
22814
22815 default:
22816 ast_log(LOG_ERROR, "Internal Error %d at %s:%d\n", st_get_mode(p, 1), __FILE__, __LINE__);
22817 break;
22818 }
22819 } else {
22820
22821
22822
22823 switch (st_get_mode(p, 1)) {
22824 case SESSION_TIMER_MODE_ORIGINATE:
22825 st_active = TRUE;
22826 st_interval = st_get_se(p, TRUE);
22827 st_ref = SESSION_TIMER_REFRESHER_UAS;
22828 p->stimer->st_active_peer_ua = FALSE;
22829 break;
22830
22831 default:
22832 break;
22833 }
22834 }
22835
22836 if (reinvite == 0) {
22837
22838 if (st_active == TRUE) {
22839 p->stimer->st_active = TRUE;
22840 p->stimer->st_interval = st_interval;
22841 p->stimer->st_ref = st_ref;
22842 start_session_timer(p);
22843 }
22844 } else {
22845 if (p->stimer->st_active == TRUE) {
22846
22847
22848
22849 ast_debug (2, "Restarting session-timers on a refresh - %s\n", p->callid);
22850
22851
22852 if (st_interval > 0) {
22853 p->stimer->st_interval = st_interval;
22854 p->stimer->st_ref = st_ref;
22855 }
22856
22857 restart_session_timer(p);
22858 if (p->stimer->st_expirys > 0) {
22859 p->stimer->st_expirys--;
22860 }
22861 }
22862 }
22863
22864 if (!req->ignore && p)
22865 p->lastinvite = seqno;
22866
22867 if (c && replace_id) {
22868 if (!ast_strlen_zero(pickup.exten)) {
22869 append_history(p, "Xfer", "INVITE/Replace received");
22870
22871
22872 transmit_response(p, "100 Trying", req);
22873 p->invitestate = INV_PROCEEDING;
22874 ast_setstate(c, AST_STATE_RING);
22875
22876
22877 ast_channel_unlock(c);
22878 *nounlock = 1;
22879
22880
22881
22882
22883
22884
22885 sip_pvt_unlock(p);
22886 do_magic_pickup(c, pickup.exten, pickup.context);
22887
22888 ast_hangup(c);
22889 sip_pvt_lock(p);
22890
22891 res = 0;
22892 goto request_invite_cleanup;
22893 } else {
22894
22895 if (sipdebug)
22896 ast_debug(4, "Sending this call to the invite/replcaes handler %s\n", p->callid);
22897 res = handle_invite_replaces(p, req, debug, seqno, addr, nounlock);
22898 refer_locked = 0;
22899 goto request_invite_cleanup;
22900 }
22901 }
22902
22903
22904 if (c) {
22905 enum ast_channel_state c_state = c->_state;
22906
22907 if (c_state != AST_STATE_UP && reinvite &&
22908 (p->invitestate == INV_TERMINATED || p->invitestate == INV_CONFIRMED)) {
22909
22910
22911
22912
22913
22914
22915
22916
22917
22918 c_state = AST_STATE_UP;
22919 }
22920
22921 switch(c_state) {
22922 case AST_STATE_DOWN:
22923 ast_debug(2, "%s: New call is still down.... Trying... \n", c->name);
22924 transmit_provisional_response(p, "100 Trying", req, 0);
22925 p->invitestate = INV_PROCEEDING;
22926 ast_setstate(c, AST_STATE_RING);
22927 if (strcmp(p->exten, ast_pickup_ext())) {
22928 enum ast_pbx_result result;
22929
22930 result = ast_pbx_start(c);
22931
22932 switch(result) {
22933 case AST_PBX_FAILED:
22934 ast_log(LOG_WARNING, "Failed to start PBX :(\n");
22935 p->invitestate = INV_COMPLETED;
22936 transmit_response_reliable(p, "503 Unavailable", req);
22937 break;
22938 case AST_PBX_CALL_LIMIT:
22939 ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
22940 p->invitestate = INV_COMPLETED;
22941 transmit_response_reliable(p, "480 Temporarily Unavailable", req);
22942 break;
22943 case AST_PBX_SUCCESS:
22944
22945 break;
22946 }
22947
22948 if (result) {
22949
22950
22951 ast_channel_unlock(c);
22952 *nounlock = 1;
22953 sip_pvt_unlock(p);
22954 ast_hangup(c);
22955 sip_pvt_lock(p);
22956 c = NULL;
22957 }
22958 } else {
22959 if (sip_pickup(c)) {
22960 ast_log(LOG_WARNING, "Failed to start Group pickup by %s\n", c->name);
22961 transmit_response_reliable(p, "480 Temporarily Unavailable", req);
22962 sip_alreadygone(p);
22963 c->hangupcause = AST_CAUSE_FAILURE;
22964
22965
22966 ast_channel_unlock(c);
22967 *nounlock = 1;
22968
22969 p->invitestate = INV_COMPLETED;
22970 sip_pvt_unlock(p);
22971 ast_hangup(c);
22972 sip_pvt_lock(p);
22973 c = NULL;
22974 }
22975 }
22976 break;
22977 case AST_STATE_RING:
22978 transmit_provisional_response(p, "100 Trying", req, 0);
22979 p->invitestate = INV_PROCEEDING;
22980 break;
22981 case AST_STATE_RINGING:
22982 transmit_provisional_response(p, "180 Ringing", req, 0);
22983 p->invitestate = INV_PROCEEDING;
22984 break;
22985 case AST_STATE_UP:
22986 ast_debug(2, "%s: This call is UP.... \n", c->name);
22987
22988 transmit_response(p, "100 Trying", req);
22989
22990 if (p->t38.state == T38_PEER_REINVITE) {
22991 if (p->t38id > -1) {
22992
22993 AST_SCHED_DEL_UNREF(sched, p->t38id, dialog_unref(p, "remove ref for t38id"));
22994 }
22995 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."));
22996 } else if (p->t38.state == T38_ENABLED) {
22997 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
22998 transmit_response_with_t38_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL)));
22999 } else if (p->t38.state == T38_DISABLED) {
23000
23001 if (p->srtp && !ast_test_flag(p->srtp, SRTP_CRYPTO_OFFER_OK)) {
23002 ast_log(LOG_WARNING, "Target does not support required crypto\n");
23003 transmit_response_reliable(p, "488 Not Acceptable Here (crypto)", req);
23004 } else {
23005 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
23006 transmit_response_with_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL)), p->session_modify == TRUE ? FALSE : TRUE, FALSE);
23007 ast_queue_control(p->owner, AST_CONTROL_UPDATE_RTP_PEER);
23008 }
23009 }
23010
23011 p->invitestate = INV_TERMINATED;
23012 break;
23013 default:
23014 ast_log(LOG_WARNING, "Don't know how to handle INVITE in state %d\n", c->_state);
23015 transmit_response(p, "100 Trying", req);
23016 break;
23017 }
23018 } else {
23019 if (p && (p->autokillid == -1)) {
23020 const char *msg;
23021
23022 if (!p->jointcapability)
23023 msg = "488 Not Acceptable Here (codec error)";
23024 else {
23025 ast_log(LOG_NOTICE, "Unable to create/find SIP channel for this INVITE\n");
23026 msg = "503 Unavailable";
23027 }
23028 transmit_response_reliable(p, msg, req);
23029 p->invitestate = INV_COMPLETED;
23030 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
23031 }
23032 }
23033
23034 request_invite_cleanup:
23035
23036 if (refer_locked && p->refer && p->refer->refer_call) {
23037 sip_pvt_unlock(p->refer->refer_call);
23038 if (p->refer->refer_call->owner) {
23039 ast_channel_unlock(p->refer->refer_call->owner);
23040 }
23041 }
23042 if (authpeer) {
23043 authpeer = unref_peer(authpeer, "unref_peer, from handle_request_invite authpeer");
23044 }
23045
23046 return res;
23047 }
23048
23049
23050
23051
23052
23053
23054
23055
23056
23057
23058
23059
23060
23061
23062 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, uint32_t seqno, int *nounlock)
23063 {
23064 struct sip_dual target;
23065
23066 int res = 0;
23067 struct sip_pvt *targetcall_pvt;
23068 struct ast_party_connected_line connected_to_transferee;
23069 struct ast_party_connected_line connected_to_target;
23070 char transferer_linkedid[32];
23071 struct ast_channel *chans[2];
23072
23073
23074 if (!(targetcall_pvt = get_sip_pvt_byid_locked(transferer->refer->replaces_callid, transferer->refer->replaces_callid_totag,
23075 transferer->refer->replaces_callid_fromtag))) {
23076 if (transferer->refer->localtransfer) {
23077
23078
23079
23080 transmit_notify_with_sipfrag(transferer, seqno, "481 Call leg/transaction does not exist", TRUE);
23081 append_history(transferer, "Xfer", "Refer failed");
23082 ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
23083 transferer->refer->status = REFER_FAILED;
23084 return -1;
23085 }
23086
23087 ast_debug(3, "SIP attended transfer: Not our call - generating INVITE with replaces\n");
23088 return 0;
23089 }
23090
23091
23092 append_history(transferer, "Xfer", "Refer accepted");
23093 if (!targetcall_pvt->owner) {
23094 ast_debug(4, "SIP attended transfer: Error: No owner of target call\n");
23095
23096 transmit_notify_with_sipfrag(transferer, seqno, "503 Service Unavailable", TRUE);
23097 append_history(transferer, "Xfer", "Refer failed");
23098 ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
23099 transferer->refer->status = REFER_FAILED;
23100 sip_pvt_unlock(targetcall_pvt);
23101 if (targetcall_pvt)
23102 ao2_t_ref(targetcall_pvt, -1, "Drop targetcall_pvt pointer");
23103 return -1;
23104 }
23105
23106
23107 target.chan1 = targetcall_pvt->owner;
23108 target.chan2 = ast_bridged_channel(targetcall_pvt->owner);
23109
23110 if (!target.chan2 || !(target.chan2->_state == AST_STATE_UP || target.chan2->_state == AST_STATE_RINGING) ) {
23111
23112 if (target.chan2)
23113 ast_debug(4, "SIP attended transfer: Error: Wrong state of target call: %s\n", ast_state2str(target.chan2->_state));
23114 else if (target.chan1->_state != AST_STATE_RING)
23115 ast_debug(4, "SIP attended transfer: Error: No target channel\n");
23116 else
23117 ast_debug(4, "SIP attended transfer: Attempting transfer in ringing state\n");
23118 }
23119
23120
23121 if (sipdebug) {
23122 if (current->chan2)
23123 ast_debug(4, "SIP attended transfer: trying to bridge %s and %s\n", target.chan1->name, current->chan2->name);
23124 else
23125 ast_debug(4, "SIP attended transfer: trying to make %s take over (masq) %s\n", target.chan1->name, current->chan1->name);
23126 }
23127
23128 ast_set_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
23129
23130 ast_copy_string(transferer_linkedid, transferer->owner->linkedid, sizeof(transferer_linkedid));
23131
23132
23133 chans[0] = transferer->owner;
23134 chans[1] = target.chan1;
23135 ast_manager_event_multichan(EVENT_FLAG_CALL, "Transfer", 2, chans,
23136 "TransferMethod: SIP\r\n"
23137 "TransferType: Attended\r\n"
23138 "Channel: %s\r\n"
23139 "Uniqueid: %s\r\n"
23140 "SIP-Callid: %s\r\n"
23141 "TargetChannel: %s\r\n"
23142 "TargetUniqueid: %s\r\n",
23143 transferer->owner->name,
23144 transferer->owner->uniqueid,
23145 transferer->callid,
23146 target.chan1->name,
23147 target.chan1->uniqueid);
23148 ast_party_connected_line_init(&connected_to_transferee);
23149 ast_party_connected_line_init(&connected_to_target);
23150
23151 ast_party_connected_line_copy(&connected_to_transferee, ¤t->chan1->connected);
23152
23153 ast_party_connected_line_copy(&connected_to_target, &target.chan1->connected);
23154 connected_to_target.source = connected_to_transferee.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
23155 res = attempt_transfer(current, &target);
23156 if (res) {
23157
23158 transmit_notify_with_sipfrag(transferer, seqno, "486 Busy Here", TRUE);
23159 append_history(transferer, "Xfer", "Refer failed");
23160 ast_clear_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
23161
23162 sip_pvt_unlock(targetcall_pvt);
23163 ast_channel_unlock(target.chan1);
23164 } else {
23165
23166 const char *xfersound = pbx_builtin_getvar_helper(target.chan1, "ATTENDED_TRANSFER_COMPLETE_SOUND");
23167
23168
23169 ast_cel_report_event(target.chan1, AST_CEL_ATTENDEDTRANSFER, NULL, transferer_linkedid, target.chan2);
23170
23171
23172 transmit_notify_with_sipfrag(transferer, seqno, "200 OK", TRUE);
23173 append_history(transferer, "Xfer", "Refer succeeded");
23174 transferer->refer->status = REFER_200OK;
23175 if (target.chan2 && !ast_strlen_zero(xfersound) && ast_streamfile(target.chan2, xfersound, target.chan2->language) >= 0) {
23176 ast_waitstream(target.chan2, "");
23177 }
23178
23179
23180
23181
23182
23183
23184
23185
23186
23187
23188
23189 ast_channel_ref(current->chan1);
23190 ast_channel_unlock(current->chan1);
23191 ast_channel_unlock(target.chan1);
23192 *nounlock = 1;
23193 sip_pvt_unlock(targetcall_pvt);
23194 sip_pvt_unlock(transferer);
23195
23196 ast_do_masquerade(target.chan1);
23197
23198 ast_indicate(target.chan1, AST_CONTROL_UNHOLD);
23199 if (target.chan2) {
23200 ast_indicate(target.chan2, AST_CONTROL_UNHOLD);
23201 }
23202
23203 if (current->chan2 && current->chan2->_state == AST_STATE_RING) {
23204 ast_indicate(target.chan1, AST_CONTROL_RINGING);
23205 }
23206
23207 if (target.chan2) {
23208 ast_channel_queue_connected_line_update(target.chan1, &connected_to_transferee, NULL);
23209 ast_channel_queue_connected_line_update(target.chan2, &connected_to_target, NULL);
23210 } else {
23211
23212
23213
23214
23215
23216
23217
23218 struct ast_control_read_action_payload *frame_payload;
23219 int payload_size;
23220 int frame_size;
23221 unsigned char connected_line_data[1024];
23222 payload_size = ast_connected_line_build_data(connected_line_data,
23223 sizeof(connected_line_data), &connected_to_target, NULL);
23224 frame_size = payload_size + sizeof(*frame_payload);
23225 if (payload_size != -1 && (frame_payload = alloca(frame_size))) {
23226 frame_payload->payload_size = payload_size;
23227 memcpy(frame_payload->payload, connected_line_data, payload_size);
23228 frame_payload->action = AST_FRAME_READ_ACTION_CONNECTED_LINE_MACRO;
23229 ast_queue_control_data(target.chan1, AST_CONTROL_READ_ACTION, frame_payload, frame_size);
23230 }
23231
23232
23233
23234
23235 ast_channel_queue_connected_line_update(target.chan1, &connected_to_transferee, NULL);
23236
23237 }
23238 sip_pvt_lock(transferer);
23239
23240 ast_channel_unref(current->chan1);
23241 }
23242
23243
23244 ast_party_connected_line_free(&connected_to_target);
23245 ast_party_connected_line_free(&connected_to_transferee);
23246 if (targetcall_pvt)
23247 ao2_t_ref(targetcall_pvt, -1, "drop targetcall_pvt");
23248 return 1;
23249 }
23250
23251
23252
23253
23254
23255
23256
23257
23258
23259
23260
23261
23262
23263
23264
23265
23266
23267
23268
23269
23270
23271
23272
23273
23274
23275
23276
23277
23278
23279
23280
23281
23282
23283
23284
23285
23286
23287
23288
23289
23290
23291
23292
23293
23294
23295
23296
23297
23298
23299
23300
23301
23302
23303
23304
23305
23306
23307
23308
23309
23310
23311
23312
23313
23314
23315 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, uint32_t seqno, int *nounlock)
23316 {
23317
23318
23319
23320
23321 struct sip_dual current = { 0, };
23322 struct ast_channel *chans[2] = { 0, };
23323 char *refer_to = NULL;
23324 char *refer_to_domain = NULL;
23325 char *refer_to_context = NULL;
23326 char *referred_by = NULL;
23327 char *callid = NULL;
23328 int localtransfer = 0;
23329 int attendedtransfer = 0;
23330 int res = 0;
23331
23332 if (req->debug) {
23333 ast_verbose("Call %s got a SIP call transfer from %s: (REFER)!\n",
23334 p->callid,
23335 ast_test_flag(&p->flags[0], SIP_OUTGOING) ? "callee" : "caller");
23336 }
23337
23338 if (!p->owner) {
23339
23340
23341 ast_debug(3, "Call %s: Declined REFER, outside of dialog...\n", p->callid);
23342 transmit_response(p, "603 Declined (No dialog)", req);
23343 if (!req->ignore) {
23344 append_history(p, "Xfer", "Refer failed. Outside of dialog.");
23345 sip_alreadygone(p);
23346 pvt_set_needdestroy(p, "outside of dialog");
23347 }
23348 res = 0;
23349 goto handle_refer_cleanup;
23350 }
23351
23352
23353 if (p->allowtransfer == TRANSFER_CLOSED ) {
23354
23355 transmit_response(p, "603 Declined (policy)", req);
23356 append_history(p, "Xfer", "Refer failed. Allowtransfer == closed.");
23357
23358 res = 0;
23359 goto handle_refer_cleanup;
23360 }
23361
23362 if (!req->ignore && ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
23363
23364 transmit_response(p, "491 Request pending", req);
23365 append_history(p, "Xfer", "Refer failed. Request pending.");
23366 res = 0;
23367 goto handle_refer_cleanup;
23368 }
23369
23370
23371 if (!p->refer && !sip_refer_allocate(p)) {
23372 transmit_response(p, "500 Internal Server Error", req);
23373 append_history(p, "Xfer", "Refer failed. Memory allocation error.");
23374 res = -3;
23375 goto handle_refer_cleanup;
23376 }
23377
23378 res = get_refer_info(p, req);
23379
23380 p->refer->status = REFER_SENT;
23381
23382 if (res != 0) {
23383 switch (res) {
23384 case -2:
23385 transmit_response(p, "400 Bad Request (Refer-to missing)", req);
23386 append_history(p, "Xfer", "Refer failed. Refer-to missing.");
23387 if (req->debug) {
23388 ast_debug(1, "SIP transfer to black hole can't be handled (no refer-to: )\n");
23389 }
23390 break;
23391 case -3:
23392 transmit_response(p, "603 Declined (Non sip: uri)", req);
23393 append_history(p, "Xfer", "Refer failed. Non SIP uri");
23394 if (req->debug) {
23395 ast_debug(1, "SIP transfer to non-SIP uri denied\n");
23396 }
23397 break;
23398 default:
23399
23400 transmit_response(p, "202 Accepted", req);
23401 append_history(p, "Xfer", "Refer failed. Bad extension.");
23402 transmit_notify_with_sipfrag(p, seqno, "404 Not found", TRUE);
23403 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
23404 if (req->debug) {
23405 ast_debug(1, "SIP transfer to bad extension: %s\n", p->refer->refer_to);
23406 }
23407 break;
23408 }
23409 res = 0;
23410 goto handle_refer_cleanup;
23411 }
23412 if (ast_strlen_zero(p->context)) {
23413 ast_string_field_set(p, context, sip_cfg.default_context);
23414 }
23415
23416
23417 if (sip_cfg.allow_external_domains && check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
23418 p->refer->localtransfer = 1;
23419 if (sipdebug) {
23420 ast_debug(3, "This SIP transfer is local : %s\n", p->refer->refer_to_domain);
23421 }
23422 } else if (AST_LIST_EMPTY(&domain_list) || check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
23423
23424 p->refer->localtransfer = 1;
23425 } else if (sipdebug) {
23426 ast_debug(3, "This SIP transfer is to a remote SIP extension (remote domain %s)\n", p->refer->refer_to_domain);
23427 }
23428
23429
23430
23431 if (req->ignore) {
23432 goto handle_refer_cleanup;
23433 }
23434
23435
23436
23437
23438
23439
23440
23441
23442
23443
23444
23445
23446
23447
23448
23449
23450
23451
23452
23453
23454
23455
23456
23457
23458
23459
23460 chans[0] = current.chan1 = p->owner;
23461
23462
23463 chans[1] = current.chan2 = ast_bridged_channel(current.chan1);
23464
23465 ast_channel_ref(current.chan1);
23466 if (current.chan2) {
23467 ast_channel_ref(current.chan2);
23468 }
23469
23470 if (sipdebug) {
23471 ast_debug(3, "SIP %s transfer: Transferer channel %s, transferee channel %s\n",
23472 p->refer->attendedtransfer ? "attended" : "blind",
23473 current.chan1->name,
23474 current.chan2 ? current.chan2->name : "<none>");
23475 }
23476
23477 if (!current.chan2 && !p->refer->attendedtransfer) {
23478
23479
23480
23481 if (sipdebug) {
23482 ast_debug(3, "Refused SIP transfer on non-bridged channel.\n");
23483 }
23484 p->refer->status = REFER_FAILED;
23485 append_history(p, "Xfer", "Refer failed. Non-bridged channel.");
23486 transmit_response(p, "603 Declined", req);
23487 res = -1;
23488 goto handle_refer_cleanup;
23489 }
23490
23491 if (current.chan2) {
23492 if (sipdebug) {
23493 ast_debug(4, "Got SIP transfer, applying to bridged peer '%s'\n", current.chan2->name);
23494 }
23495 ast_queue_control(current.chan1, AST_CONTROL_UNHOLD);
23496 }
23497
23498 ast_set_flag(&p->flags[0], SIP_GOTREFER);
23499
23500
23501 transmit_response(p, "202 Accepted", req);
23502
23503
23504 if (p->refer->attendedtransfer) {
23505
23506 if ((res = local_attended_transfer(p, ¤t, req, seqno, nounlock))) {
23507 goto handle_refer_cleanup;
23508 }
23509
23510 if (sipdebug) {
23511 ast_debug(4, "SIP attended transfer: Still not our call - generating INVITE with replaces\n");
23512 }
23513
23514 }
23515
23516
23517 refer_to = ast_strdupa(p->refer->refer_to);
23518 refer_to_domain = ast_strdupa(p->refer->refer_to_domain);
23519 refer_to_context = ast_strdupa(p->refer->refer_to_context);
23520 referred_by = ast_strdupa(p->refer->referred_by);
23521 callid = ast_strdupa(p->callid);
23522 localtransfer = p->refer->localtransfer;
23523 attendedtransfer = p->refer->attendedtransfer;
23524
23525 if (!*nounlock) {
23526 ast_channel_unlock(p->owner);
23527 *nounlock = 1;
23528 }
23529 sip_pvt_unlock(p);
23530
23531
23532 if (localtransfer && ast_parking_ext_valid(refer_to, current.chan1, refer_to_context)) {
23533 sip_pvt_lock(p);
23534 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
23535 p->refer->status = REFER_200OK;
23536 append_history(p, "Xfer", "REFER to call parking.");
23537 sip_pvt_unlock(p);
23538
23539 ast_manager_event_multichan(EVENT_FLAG_CALL, "Transfer", 2, chans,
23540 "TransferMethod: SIP\r\n"
23541 "TransferType: Blind\r\n"
23542 "Channel: %s\r\n"
23543 "Uniqueid: %s\r\n"
23544 "SIP-Callid: %s\r\n"
23545 "TargetChannel: %s\r\n"
23546 "TargetUniqueid: %s\r\n"
23547 "TransferExten: %s\r\n"
23548 "Transfer2Parking: Yes\r\n",
23549 current.chan1->name,
23550 current.chan1->uniqueid,
23551 callid,
23552 current.chan2->name,
23553 current.chan2->uniqueid,
23554 refer_to);
23555
23556 if (sipdebug) {
23557 ast_debug(4, "SIP transfer to parking: trying to park %s. Parked by %s\n", current.chan2->name, current.chan1->name);
23558 }
23559
23560
23561 if (sip_park(current.chan2, current.chan1, req, seqno, refer_to, refer_to_context)) {
23562 sip_pvt_lock(p);
23563 transmit_notify_with_sipfrag(p, seqno, "500 Internal Server Error", TRUE);
23564 } else {
23565 sip_pvt_lock(p);
23566 }
23567 goto handle_refer_cleanup;
23568 }
23569
23570
23571
23572
23573 if (current.chan1 && current.chan2) {
23574 ast_debug(3, "chan1->name: %s\n", current.chan1->name);
23575 pbx_builtin_setvar_helper(current.chan1, "BLINDTRANSFER", current.chan2->name);
23576 }
23577
23578 if (current.chan2) {
23579 pbx_builtin_setvar_helper(current.chan2, "BLINDTRANSFER", current.chan1->name);
23580 pbx_builtin_setvar_helper(current.chan2, "SIPDOMAIN", refer_to_domain);
23581 pbx_builtin_setvar_helper(current.chan2, "SIPTRANSFER", "yes");
23582
23583 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER", "yes");
23584
23585 if (!ast_strlen_zero(referred_by)) {
23586 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REFERER", referred_by);
23587 }
23588 }
23589
23590 sip_pvt_lock(p);
23591
23592 if (!ast_strlen_zero(p->refer->replaces_callid)) {
23593 char tempheader[SIPBUFSIZE];
23594 snprintf(tempheader, sizeof(tempheader), "%s%s%s%s%s", p->refer->replaces_callid,
23595 p->refer->replaces_callid_totag ? ";to-tag=" : "",
23596 p->refer->replaces_callid_totag,
23597 p->refer->replaces_callid_fromtag ? ";from-tag=" : "",
23598 p->refer->replaces_callid_fromtag);
23599
23600 if (current.chan2) {
23601 sip_pvt_unlock(p);
23602 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REPLACES", tempheader);
23603 sip_pvt_lock(p);
23604 }
23605 }
23606
23607
23608
23609
23610 if (!p->refer->attendedtransfer) {
23611 transmit_notify_with_sipfrag(p, seqno, "180 Ringing", FALSE);
23612 }
23613
23614
23615
23616
23617
23618 if (!current.chan2) {
23619
23620
23621
23622
23623
23624
23625
23626 p->refer->status = REFER_FAILED;
23627 transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable (can't handle one-legged xfers)", TRUE);
23628 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
23629 append_history(p, "Xfer", "Refer failed (only bridged calls).");
23630 res = -1;
23631 goto handle_refer_cleanup;
23632 }
23633 ast_set_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
23634
23635
23636
23637
23638
23639
23640
23641 sip_pvt_unlock(p);
23642 ast_indicate(current.chan2, AST_CONTROL_UNHOLD);
23643 res = ast_async_goto(current.chan2, refer_to_context, refer_to, 1);
23644
23645 if (!res) {
23646 ast_manager_event_multichan(EVENT_FLAG_CALL, "Transfer", 2, chans,
23647 "TransferMethod: SIP\r\n"
23648 "TransferType: Blind\r\n"
23649 "Channel: %s\r\n"
23650 "Uniqueid: %s\r\n"
23651 "SIP-Callid: %s\r\n"
23652 "TargetChannel: %s\r\n"
23653 "TargetUniqueid: %s\r\n"
23654 "TransferExten: %s\r\n"
23655 "TransferContext: %s\r\n",
23656 current.chan1->name,
23657 current.chan1->uniqueid,
23658 callid,
23659 current.chan2->name,
23660 current.chan2->uniqueid,
23661 refer_to,
23662 refer_to_context);
23663
23664 ast_debug(3, "%s transfer succeeded. Telling transferer.\n", attendedtransfer? "Attended" : "Blind");
23665
23666
23667 ast_channel_lock(current.chan1);
23668 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);
23669 ast_channel_unlock(current.chan1);
23670
23671 sip_pvt_lock(p);
23672 transmit_notify_with_sipfrag(p, seqno, "200 Ok", TRUE);
23673 if (p->refer->localtransfer) {
23674 p->refer->status = REFER_200OK;
23675 }
23676 if (p->owner) {
23677 p->owner->hangupcause = AST_CAUSE_NORMAL_CLEARING;
23678 }
23679 append_history(p, "Xfer", "Refer succeeded.");
23680 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
23681
23682
23683 res = 0;
23684 } else {
23685 sip_pvt_lock(p);
23686 ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
23687 ast_debug(3, "%s transfer failed. Resuming original call.\n", p->refer->attendedtransfer? "Attended" : "Blind");
23688 append_history(p, "Xfer", "Refer failed.");
23689
23690 p->refer->status = REFER_FAILED;
23691 transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable", TRUE);
23692 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
23693 res = -1;
23694 }
23695
23696 handle_refer_cleanup:
23697 if (current.chan1) {
23698 ast_channel_unref(current.chan1);
23699 }
23700 if (current.chan2) {
23701 ast_channel_unref(current.chan2);
23702 }
23703
23704
23705 return res;
23706 }
23707
23708
23709 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req)
23710 {
23711
23712 check_via(p, req);
23713 sip_alreadygone(p);
23714
23715 if (p->owner && p->owner->_state == AST_STATE_UP) {
23716
23717 transmit_response(p, "200 OK", req);
23718 ast_debug(1, "Got CANCEL on an answered call. Ignoring... \n");
23719 return 0;
23720 }
23721
23722
23723
23724
23725
23726
23727 if (p->invitestate == INV_TERMINATED || p->invitestate == INV_COMPLETED) {
23728 __sip_pretend_ack(p);
23729 }
23730 if (p->invitestate != INV_TERMINATED)
23731 p->invitestate = INV_CANCELLED;
23732
23733 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD))
23734 update_call_counter(p, DEC_CALL_LIMIT);
23735
23736 stop_media_flows(p);
23737 if (p->owner) {
23738 ast_set_hangupsource(p->owner, p->owner->name, 0);
23739 ast_queue_hangup(p->owner);
23740 }
23741 else
23742 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
23743 if (ast_str_strlen(p->initreq.data) > 0) {
23744 struct sip_pkt *pkt, *prev_pkt;
23745
23746
23747
23748
23749
23750
23751
23752
23753
23754
23755
23756 for (pkt = p->packets, prev_pkt = NULL; pkt; prev_pkt = pkt, pkt = pkt->next) {
23757 if (pkt->seqno == p->lastinvite && pkt->response_code == 487) {
23758 AST_SCHED_DEL(sched, pkt->retransid);
23759 UNLINK(pkt, p->packets, prev_pkt);
23760 dialog_unref(pkt->owner, "unref packet->owner from dialog");
23761 if (pkt->data) {
23762 ast_free(pkt->data);
23763 }
23764 ast_free(pkt);
23765 break;
23766 }
23767 }
23768 transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
23769 transmit_response(p, "200 OK", req);
23770 return 1;
23771 } else {
23772 transmit_response(p, "481 Call Leg Does Not Exist", req);
23773 return 0;
23774 }
23775 }
23776
23777
23778 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req)
23779 {
23780 struct ast_channel *c=NULL;
23781 int res;
23782 struct ast_channel *bridged_to;
23783 const char *required;
23784
23785
23786 if (p->pendinginvite && !ast_test_flag(&p->flags[0], SIP_OUTGOING) && !req->ignore) {
23787 transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
23788 }
23789
23790 __sip_pretend_ack(p);
23791
23792 p->invitestate = INV_TERMINATED;
23793
23794 copy_request(&p->initreq, req);
23795 if (sipdebug)
23796 ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
23797 check_via(p, req);
23798 sip_alreadygone(p);
23799
23800
23801 if (p->do_history || p->owner) {
23802 char quality_buf[AST_MAX_USER_FIELD], *quality;
23803 struct ast_channel *bridge = p->owner ? ast_bridged_channel(p->owner) : NULL;
23804
23805
23806
23807
23808 while (bridge && ast_channel_trylock(bridge)) {
23809 ast_channel_unlock(p->owner);
23810 do {
23811
23812 sip_pvt_unlock(p);
23813 usleep(1);
23814 sip_pvt_lock(p);
23815 } while (p->owner && ast_channel_trylock(p->owner));
23816 bridge = p->owner ? ast_bridged_channel(p->owner) : NULL;
23817 }
23818
23819
23820 if (p->rtp && (quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
23821 if (p->do_history) {
23822 append_history(p, "RTCPaudio", "Quality:%s", quality);
23823
23824 if ((quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY_JITTER, quality_buf, sizeof(quality_buf)))) {
23825 append_history(p, "RTCPaudioJitter", "Quality:%s", quality);
23826 }
23827 if ((quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY_LOSS, quality_buf, sizeof(quality_buf)))) {
23828 append_history(p, "RTCPaudioLoss", "Quality:%s", quality);
23829 }
23830 if ((quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY_RTT, quality_buf, sizeof(quality_buf)))) {
23831 append_history(p, "RTCPaudioRTT", "Quality:%s", quality);
23832 }
23833 }
23834
23835 if (p->owner) {
23836 ast_rtp_instance_set_stats_vars(p->owner, p->rtp);
23837 }
23838
23839 }
23840
23841 if (bridge) {
23842 struct sip_pvt *q = bridge->tech_pvt;
23843
23844 if (IS_SIP_TECH(bridge->tech) && q && q->rtp) {
23845 ast_rtp_instance_set_stats_vars(bridge, q->rtp);
23846 }
23847 ast_channel_unlock(bridge);
23848 }
23849
23850 if (p->vrtp && (quality = ast_rtp_instance_get_quality(p->vrtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
23851 if (p->do_history) {
23852 append_history(p, "RTCPvideo", "Quality:%s", quality);
23853 }
23854 if (p->owner) {
23855 pbx_builtin_setvar_helper(p->owner, "RTPVIDEOQOS", quality);
23856 }
23857 }
23858 if (p->trtp && (quality = ast_rtp_instance_get_quality(p->trtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
23859 if (p->do_history) {
23860 append_history(p, "RTCPtext", "Quality:%s", quality);
23861 }
23862 if (p->owner) {
23863 pbx_builtin_setvar_helper(p->owner, "RTPTEXTQOS", quality);
23864 }
23865 }
23866 }
23867
23868 stop_media_flows(p);
23869 stop_session_timer(p);
23870
23871 if (!ast_strlen_zero(get_header(req, "Also"))) {
23872 ast_log(LOG_NOTICE, "Client '%s' using deprecated BYE/Also transfer method. Ask vendor to support REFER instead\n",
23873 ast_sockaddr_stringify(&p->recv));
23874 if (ast_strlen_zero(p->context))
23875 ast_string_field_set(p, context, sip_cfg.default_context);
23876 res = get_also_info(p, req);
23877 if (!res) {
23878 c = p->owner;
23879 if (c) {
23880 bridged_to = ast_bridged_channel(c);
23881 if (bridged_to) {
23882
23883 ast_queue_control(c, AST_CONTROL_UNHOLD);
23884 ast_channel_unlock(c);
23885 ast_async_goto(bridged_to, p->context, p->refer->refer_to, 1);
23886 ast_channel_lock(c);
23887 } else
23888 ast_queue_hangup(p->owner);
23889 }
23890 } else {
23891 ast_log(LOG_WARNING, "Invalid transfer information from '%s'\n", ast_sockaddr_stringify(&p->recv));
23892 if (p->owner)
23893 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
23894 }
23895 } else if (p->owner) {
23896 ast_set_hangupsource(p->owner, p->owner->name, 0);
23897 ast_queue_hangup(p->owner);
23898 sip_scheddestroy_final(p, DEFAULT_TRANS_TIMEOUT);
23899 ast_debug(3, "Received bye, issuing owner hangup\n");
23900 } else {
23901 sip_scheddestroy_final(p, DEFAULT_TRANS_TIMEOUT);
23902 ast_debug(3, "Received bye, no owner, selfdestruct soon.\n");
23903 }
23904 ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
23905
23906
23907 required = get_header(req, "Require");
23908 if (!ast_strlen_zero(required)) {
23909 char unsupported[256] = { 0, };
23910 parse_sip_options(required, unsupported, ARRAY_LEN(unsupported));
23911
23912
23913 if (!ast_strlen_zero(unsupported)) {
23914 transmit_response_with_unsupported(p, "420 Bad extension (unsupported)", req, unsupported);
23915 ast_log(LOG_WARNING, "Received SIP BYE with unsupported required extension: required:%s unsupported:%s\n", required, unsupported);
23916 } else {
23917 transmit_response(p, "200 OK", req);
23918 }
23919 } else {
23920 transmit_response(p, "200 OK", req);
23921 }
23922
23923 return 1;
23924 }
23925
23926
23927 static int handle_request_message(struct sip_pvt *p, struct sip_request *req)
23928 {
23929 if (!req->ignore) {
23930 if (req->debug)
23931 ast_verbose("Receiving message!\n");
23932 receive_message(p, req);
23933 } else
23934 transmit_response(p, "202 Accepted", req);
23935 return 1;
23936 }
23937
23938 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)
23939 {
23940 int etag_present = !ast_strlen_zero(etag);
23941 int body_present = req->lines > 0;
23942
23943 ast_assert(expires_int != NULL);
23944
23945 if (ast_strlen_zero(expires)) {
23946
23947
23948
23949
23950 *expires_int = DEFAULT_PUBLISH_EXPIRES;
23951 } else if (sscanf(expires, "%30d", expires_int) != 1) {
23952 return SIP_PUBLISH_UNKNOWN;
23953 }
23954
23955 if (*expires_int == 0) {
23956 return SIP_PUBLISH_REMOVE;
23957 } else if (!etag_present && body_present) {
23958 return SIP_PUBLISH_INITIAL;
23959 } else if (etag_present && !body_present) {
23960 return SIP_PUBLISH_REFRESH;
23961 } else if (etag_present && body_present) {
23962 return SIP_PUBLISH_MODIFY;
23963 }
23964
23965 return SIP_PUBLISH_UNKNOWN;
23966 }
23967
23968 #ifdef HAVE_LIBXML2
23969 static void get_pidf_body(struct sip_request *req, char *pidf_body, size_t size)
23970 {
23971 int i;
23972 struct ast_str *str = ast_str_alloca(size);
23973 for (i = 0; i < req->lines; ++i) {
23974 ast_str_append(&str, 0, "%s", REQ_OFFSET_TO_STR(req, line[i]));
23975 }
23976 ast_copy_string(pidf_body, ast_str_buffer(str), size);
23977 }
23978
23979 static int pidf_validate_tuple(struct ast_xml_node *tuple_node)
23980 {
23981 const char *id;
23982 int status_found = FALSE;
23983 struct ast_xml_node *tuple_children;
23984 struct ast_xml_node *tuple_children_iterator;
23985
23986 if (!(id = ast_xml_get_attribute(tuple_node, "id"))) {
23987 ast_log(LOG_WARNING, "Tuple XML element has no attribute 'id'\n");
23988 return FALSE;
23989 }
23990
23991 ast_xml_free_attr(id);
23992
23993 if (!(tuple_children = ast_xml_node_get_children(tuple_node))) {
23994
23995 ast_log(LOG_WARNING, "Tuple XML element has no child elements\n");
23996 return FALSE;
23997 }
23998 for (tuple_children_iterator = tuple_children; tuple_children_iterator;
23999 tuple_children_iterator = ast_xml_node_get_next(tuple_children_iterator)) {
24000
24001
24002
24003
24004 if (strcmp(ast_xml_node_get_name(tuple_children_iterator), "status")) {
24005
24006 continue;
24007 }
24008 if (status_found == TRUE) {
24009
24010 ast_log(LOG_WARNING, "Multiple status elements found in tuple. Only one allowed\n");
24011 return FALSE;
24012 }
24013 status_found = TRUE;
24014 }
24015 return status_found;
24016 }
24017
24018
24019 static int pidf_validate_presence(struct ast_xml_doc *doc)
24020 {
24021 struct ast_xml_node *presence_node = ast_xml_get_root(doc);
24022 struct ast_xml_node *child_nodes;
24023 struct ast_xml_node *node_iterator;
24024 struct ast_xml_ns *ns;
24025 const char *entity;
24026 const char *namespace;
24027 const char presence_namespace[] = "urn:ietf:params:xml:ns:pidf";
24028
24029 if (!presence_node) {
24030 ast_log(LOG_WARNING, "Unable to retrieve root node of the XML document\n");
24031 return FALSE;
24032 }
24033
24034
24035
24036 if (strcmp(ast_xml_node_get_name(presence_node), "presence")) {
24037 ast_log(LOG_WARNING, "Root node of PIDF document is not 'presence'. Invalid\n");
24038 return FALSE;
24039 }
24040
24041
24042
24043
24044 if (!(entity = ast_xml_get_attribute(presence_node, "entity"))) {
24045 ast_log(LOG_WARNING, "Presence element of PIDF document has no 'entity' attribute\n");
24046 return FALSE;
24047 }
24048
24049 ast_xml_free_attr(entity);
24050
24051 if (!(ns = ast_xml_find_namespace(doc, presence_node, NULL))) {
24052 ast_log(LOG_WARNING, "Couldn't find default namespace...\n");
24053 return FALSE;
24054 }
24055
24056 namespace = ast_xml_get_ns_href(ns);
24057 if (ast_strlen_zero(namespace) || strcmp(namespace, presence_namespace)) {
24058 ast_log(LOG_WARNING, "PIDF document has invalid namespace value %s\n", namespace);
24059 return FALSE;
24060 }
24061
24062 if (!(child_nodes = ast_xml_node_get_children(presence_node))) {
24063 ast_log(LOG_WARNING, "PIDF document has no elements as children of 'presence'. Invalid\n");
24064 return FALSE;
24065 }
24066
24067
24068
24069
24070
24071
24072
24073
24074
24075 for (node_iterator = child_nodes; node_iterator;
24076 node_iterator = ast_xml_node_get_next(node_iterator)) {
24077 if (strcmp(ast_xml_node_get_name(node_iterator), "tuple")) {
24078
24079 continue;
24080 }
24081 if (pidf_validate_tuple(node_iterator) == FALSE) {
24082 ast_log(LOG_WARNING, "Unable to validate tuple\n");
24083 return FALSE;
24084 }
24085 }
24086
24087 return TRUE;
24088 }
24089
24090
24091
24092
24093
24094
24095
24096
24097
24098
24099
24100
24101
24102
24103
24104
24105 static int sip_pidf_validate(struct sip_request *req, struct ast_xml_doc **pidf_doc)
24106 {
24107 struct ast_xml_doc *doc;
24108 int content_length;
24109 const char *content_length_str = get_header(req, "Content-Length");
24110 const char *content_type = get_header(req, "Content-Type");
24111 char pidf_body[SIPBUFSIZE];
24112 int res;
24113
24114 if (ast_strlen_zero(content_type) || strcmp(content_type, "application/pidf+xml")) {
24115 ast_log(LOG_WARNING, "Content type is not PIDF\n");
24116 return FALSE;
24117 }
24118
24119 if (ast_strlen_zero(content_length_str)) {
24120 ast_log(LOG_WARNING, "No content length. Can't determine bounds of PIDF document\n");
24121 return FALSE;
24122 }
24123
24124 if (sscanf(content_length_str, "%30d", &content_length) != 1) {
24125 ast_log(LOG_WARNING, "Invalid content length provided\n");
24126 return FALSE;
24127 }
24128
24129 if (content_length > sizeof(pidf_body)) {
24130 ast_log(LOG_WARNING, "Content length of PIDF document truncated to %d bytes\n", (int) sizeof(pidf_body));
24131 content_length = sizeof(pidf_body);
24132 }
24133
24134 get_pidf_body(req, pidf_body, content_length);
24135
24136 if (!(doc = ast_xml_read_memory(pidf_body, content_length))) {
24137 ast_log(LOG_WARNING, "Unable to open XML PIDF document. Is it malformed?\n");
24138 return FALSE;
24139 }
24140
24141 res = pidf_validate_presence(doc);
24142 if (res == TRUE) {
24143 *pidf_doc = doc;
24144 } else {
24145 ast_xml_close(doc);
24146 }
24147 return res;
24148 }
24149
24150 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)
24151 {
24152 const char *uri = REQ_OFFSET_TO_STR(req, rlPart2);
24153 struct ast_cc_agent *agent;
24154 struct sip_cc_agent_pvt *agent_pvt;
24155 struct ast_xml_doc *pidf_doc = NULL;
24156 const char *basic_status = NULL;
24157 struct ast_xml_node *presence_node;
24158 struct ast_xml_node *presence_children;
24159 struct ast_xml_node *tuple_node;
24160 struct ast_xml_node *tuple_children;
24161 struct ast_xml_node *status_node;
24162 struct ast_xml_node *status_children;
24163 struct ast_xml_node *basic_node;
24164 int res = 0;
24165
24166 if (!((agent = find_sip_cc_agent_by_notify_uri(uri)) || (agent = find_sip_cc_agent_by_subscribe_uri(uri)))) {
24167 ast_log(LOG_WARNING, "Could not find agent using uri '%s'\n", uri);
24168 transmit_response(pvt, "412 Conditional Request Failed", req);
24169 return -1;
24170 }
24171
24172 agent_pvt = agent->private_data;
24173
24174 if (sip_pidf_validate(req, &pidf_doc) == FALSE) {
24175 res = -1;
24176 goto cc_publish_cleanup;
24177 }
24178
24179
24180
24181
24182
24183
24184
24185 presence_node = ast_xml_get_root(pidf_doc);
24186 if (!(presence_children = ast_xml_node_get_children(presence_node))) {
24187 ast_log(LOG_WARNING, "No tuples within presence element.\n");
24188 res = -1;
24189 goto cc_publish_cleanup;
24190 }
24191
24192 if (!(tuple_node = ast_xml_find_element(presence_children, "tuple", NULL, NULL))) {
24193 ast_log(LOG_NOTICE, "Couldn't find tuple node?\n");
24194 res = -1;
24195 goto cc_publish_cleanup;
24196 }
24197
24198
24199
24200
24201 tuple_children = ast_xml_node_get_children(tuple_node);
24202 status_node = ast_xml_find_element(tuple_children, "status", NULL, NULL);
24203
24204 if (!(status_children = ast_xml_node_get_children(status_node))) {
24205 ast_log(LOG_WARNING, "No basic elements within status element.\n");
24206 res = -1;
24207 goto cc_publish_cleanup;
24208 }
24209
24210 if (!(basic_node = ast_xml_find_element(status_children, "basic", NULL, NULL))) {
24211 ast_log(LOG_WARNING, "Couldn't find basic node?\n");
24212 res = -1;
24213 goto cc_publish_cleanup;
24214 }
24215
24216 basic_status = ast_xml_get_text(basic_node);
24217
24218 if (ast_strlen_zero(basic_status)) {
24219 ast_log(LOG_NOTICE, "NOthing in basic node?\n");
24220 res = -1;
24221 goto cc_publish_cleanup;
24222 }
24223
24224 if (!strcmp(basic_status, "open")) {
24225 agent_pvt->is_available = TRUE;
24226 ast_cc_agent_caller_available(agent->core_id, "Received PUBLISH stating SIP caller %s is available",
24227 agent->device_name);
24228 } else if (!strcmp(basic_status, "closed")) {
24229 agent_pvt->is_available = FALSE;
24230 ast_cc_agent_caller_busy(agent->core_id, "Received PUBLISH stating SIP caller %s is busy",
24231 agent->device_name);
24232 } else {
24233 ast_log(LOG_NOTICE, "Invalid content in basic element: %s\n", basic_status);
24234 }
24235
24236 cc_publish_cleanup:
24237 if (basic_status) {
24238 ast_xml_free_text(basic_status);
24239 }
24240 if (pidf_doc) {
24241 ast_xml_close(pidf_doc);
24242 }
24243 ao2_ref(agent, -1);
24244 if (res) {
24245 transmit_response(pvt, "400 Bad Request", req);
24246 }
24247 return res;
24248 }
24249
24250 #endif
24251
24252 static int handle_sip_publish_initial(struct sip_pvt *p, struct sip_request *req, struct event_state_compositor *esc, const int expires)
24253 {
24254 struct sip_esc_entry *esc_entry = create_esc_entry(esc, req, expires);
24255 int res = 0;
24256
24257 if (!esc_entry) {
24258 transmit_response(p, "503 Internal Server Failure", req);
24259 return -1;
24260 }
24261
24262 if (esc->callbacks->initial_handler) {
24263 res = esc->callbacks->initial_handler(p, req, esc, esc_entry);
24264 }
24265
24266 if (!res) {
24267 transmit_response_with_sip_etag(p, "200 OK", req, esc_entry, 0);
24268 }
24269
24270 ao2_ref(esc_entry, -1);
24271 return res;
24272 }
24273
24274 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)
24275 {
24276 struct sip_esc_entry *esc_entry = get_esc_entry(etag, esc);
24277 int expires_ms = expires * 1000;
24278 int res = 0;
24279
24280 if (!esc_entry) {
24281 transmit_response(p, "412 Conditional Request Failed", req);
24282 return -1;
24283 }
24284
24285 AST_SCHED_REPLACE_UNREF(esc_entry->sched_id, sched, expires_ms, publish_expire, esc_entry,
24286 ao2_ref(_data, -1),
24287 ao2_ref(esc_entry, -1),
24288 ao2_ref(esc_entry, +1));
24289
24290 if (esc->callbacks->refresh_handler) {
24291 res = esc->callbacks->refresh_handler(p, req, esc, esc_entry);
24292 }
24293
24294 if (!res) {
24295 transmit_response_with_sip_etag(p, "200 OK", req, esc_entry, 1);
24296 }
24297
24298 ao2_ref(esc_entry, -1);
24299 return res;
24300 }
24301
24302 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)
24303 {
24304 struct sip_esc_entry *esc_entry = get_esc_entry(etag, esc);
24305 int expires_ms = expires * 1000;
24306 int res = 0;
24307
24308 if (!esc_entry) {
24309 transmit_response(p, "412 Conditional Request Failed", req);
24310 return -1;
24311 }
24312
24313 AST_SCHED_REPLACE_UNREF(esc_entry->sched_id, sched, expires_ms, publish_expire, esc_entry,
24314 ao2_ref(_data, -1),
24315 ao2_ref(esc_entry, -1),
24316 ao2_ref(esc_entry, +1));
24317
24318 if (esc->callbacks->modify_handler) {
24319 res = esc->callbacks->modify_handler(p, req, esc, esc_entry);
24320 }
24321
24322 if (!res) {
24323 transmit_response_with_sip_etag(p, "200 OK", req, esc_entry, 1);
24324 }
24325
24326 ao2_ref(esc_entry, -1);
24327 return res;
24328 }
24329
24330 static int handle_sip_publish_remove(struct sip_pvt *p, struct sip_request *req, struct event_state_compositor *esc, const char * const etag)
24331 {
24332 struct sip_esc_entry *esc_entry = get_esc_entry(etag, esc);
24333 int res = 0;
24334
24335 if (!esc_entry) {
24336 transmit_response(p, "412 Conditional Request Failed", req);
24337 return -1;
24338 }
24339
24340 AST_SCHED_DEL(sched, esc_entry->sched_id);
24341
24342 ao2_ref(esc_entry, -1);
24343
24344 if (esc->callbacks->remove_handler) {
24345 res = esc->callbacks->remove_handler(p, req, esc, esc_entry);
24346 }
24347
24348 if (!res) {
24349 transmit_response_with_sip_etag(p, "200 OK", req, esc_entry, 1);
24350 }
24351
24352
24353 ao2_unlink(esc->compositor, esc_entry);
24354 ao2_ref(esc_entry, -1);
24355 return res;
24356 }
24357
24358 static int handle_request_publish(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const uint32_t seqno, const char *uri)
24359 {
24360 const char *etag = get_header(req, "SIP-If-Match");
24361 const char *event = get_header(req, "Event");
24362 struct event_state_compositor *esc;
24363 enum sip_publish_type publish_type;
24364 const char *expires_str = get_header(req, "Expires");
24365 int expires_int;
24366 int auth_result;
24367 int handler_result = -1;
24368
24369 if (ast_strlen_zero(event)) {
24370 transmit_response(p, "489 Bad Event", req);
24371 pvt_set_needdestroy(p, "missing Event: header");
24372 return -1;
24373 }
24374
24375 if (!(esc = get_esc(event))) {
24376 transmit_response(p, "489 Bad Event", req);
24377 pvt_set_needdestroy(p, "unknown event package in publish");
24378 return -1;
24379 }
24380
24381 auth_result = check_user(p, req, SIP_PUBLISH, uri, XMIT_RELIABLE, addr);
24382 if (auth_result == AUTH_CHALLENGE_SENT) {
24383 p->lastinvite = seqno;
24384 return 0;
24385 } else if (auth_result < 0) {
24386 if (auth_result == AUTH_FAKE_AUTH) {
24387 ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", get_header(req, "From"));
24388 transmit_fake_auth_response(p, SIP_INVITE, req, XMIT_RELIABLE);
24389 } else {
24390 ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", get_header(req, "From"));
24391 transmit_response_reliable(p, "403 Forbidden", req);
24392 }
24393 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
24394 ast_string_field_set(p, theirtag, NULL);
24395 return 0;
24396 } else if (auth_result == AUTH_SUCCESSFUL && p->lastinvite) {
24397
24398 __sip_ack(p, p->lastinvite, 1, 0);
24399 }
24400
24401 publish_type = determine_sip_publish_type(req, event, etag, expires_str, &expires_int);
24402
24403 if (expires_int > max_expiry) {
24404 expires_int = max_expiry;
24405 } else if (expires_int < min_expiry && expires_int > 0) {
24406 transmit_response_with_minexpires(p, "423 Interval too small", req);
24407 pvt_set_needdestroy(p, "Expires is less that the min expires allowed.");
24408 return 0;
24409 }
24410 p->expiry = expires_int;
24411
24412
24413
24414
24415 switch (publish_type) {
24416 case SIP_PUBLISH_UNKNOWN:
24417 transmit_response(p, "400 Bad Request", req);
24418 break;
24419 case SIP_PUBLISH_INITIAL:
24420 handler_result = handle_sip_publish_initial(p, req, esc, expires_int);
24421 break;
24422 case SIP_PUBLISH_REFRESH:
24423 handler_result = handle_sip_publish_refresh(p, req, esc, etag, expires_int);
24424 break;
24425 case SIP_PUBLISH_MODIFY:
24426 handler_result = handle_sip_publish_modify(p, req, esc, etag, expires_int);
24427 break;
24428 case SIP_PUBLISH_REMOVE:
24429 handler_result = handle_sip_publish_remove(p, req, esc, etag);
24430 break;
24431 default:
24432 transmit_response(p, "400 Impossible Condition", req);
24433 break;
24434 }
24435 if (!handler_result && p->expiry > 0) {
24436 sip_scheddestroy(p, (p->expiry + 10) * 1000);
24437 } else {
24438 pvt_set_needdestroy(p, "forcing expiration");
24439 }
24440
24441 return handler_result;
24442 }
24443
24444
24445
24446
24447
24448
24449
24450 static void add_peer_mwi_subs(struct sip_peer *peer)
24451 {
24452 struct sip_mailbox *mailbox;
24453
24454 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
24455 if (mailbox->event_sub) {
24456 ast_event_unsubscribe(mailbox->event_sub);
24457 }
24458
24459 mailbox->event_sub = ast_event_subscribe(AST_EVENT_MWI, mwi_event_cb, "SIP mbox event", peer,
24460 AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox->mailbox,
24461 AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, S_OR(mailbox->context, "default"),
24462 AST_EVENT_IE_END);
24463 }
24464 }
24465
24466 static int handle_cc_subscribe(struct sip_pvt *p, struct sip_request *req)
24467 {
24468 const char *uri = REQ_OFFSET_TO_STR(req, rlPart2);
24469 char *param_separator;
24470 struct ast_cc_agent *agent;
24471 struct sip_cc_agent_pvt *agent_pvt;
24472 const char *expires_str = get_header(req, "Expires");
24473 int expires = -1;
24474
24475 if (!ast_strlen_zero(expires_str)) {
24476 sscanf(expires_str, "%d", &expires);
24477 }
24478
24479 if ((param_separator = strchr(uri, ';'))) {
24480 *param_separator = '\0';
24481 }
24482
24483 p->subscribed = CALL_COMPLETION;
24484
24485 if (!(agent = find_sip_cc_agent_by_subscribe_uri(uri))) {
24486 if (!expires) {
24487
24488
24489
24490
24491
24492
24493 transmit_response(p, "200 OK", req);
24494 return 0;
24495 }
24496 ast_log(LOG_WARNING, "Invalid URI '%s' in CC subscribe\n", uri);
24497 transmit_response(p, "404 Not Found", req);
24498 return -1;
24499 }
24500
24501 agent_pvt = agent->private_data;
24502
24503 if (!expires) {
24504
24505
24506
24507 ast_cc_failed(agent->core_id, "CC is being canceled by %s", agent->device_name);
24508 transmit_response(p, "200 OK", req);
24509 ao2_ref(agent, -1);
24510 return 0;
24511 }
24512
24513 agent_pvt->subscribe_pvt = dialog_ref(p, "SIP CC agent gains reference to subscription dialog");
24514 ast_cc_agent_accept_request(agent->core_id, "SIP caller %s has requested CC via SUBSCRIBE",
24515 agent->device_name);
24516
24517
24518
24519
24520 ao2_ref(agent, -1);
24521 return 0;
24522 }
24523
24524
24525 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e)
24526 {
24527 int gotdest = 0;
24528 int res = 0;
24529 int firststate;
24530 struct sip_peer *authpeer = NULL;
24531 const char *eventheader = get_header(req, "Event");
24532 int resubscribe = (p->subscribed != NONE) && !req->ignore;
24533 char *temp, *event;
24534
24535 if (p->initreq.headers) {
24536
24537 if (p->initreq.method != SIP_SUBSCRIBE) {
24538
24539
24540 transmit_response(p, "403 Forbidden (within dialog)", req);
24541
24542 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);
24543 return 0;
24544 } else if (req->debug) {
24545 if (resubscribe)
24546 ast_debug(1, "Got a re-subscribe on existing subscription %s\n", p->callid);
24547 else
24548 ast_debug(1, "Got a new subscription %s (possibly with auth) or retransmission\n", p->callid);
24549 }
24550 }
24551
24552
24553
24554
24555 if (!sip_cfg.allowsubscribe) {
24556 transmit_response(p, "403 Forbidden (policy)", req);
24557 pvt_set_needdestroy(p, "forbidden");
24558 return 0;
24559 }
24560
24561 if (!req->ignore && !resubscribe) {
24562 const char *to = get_header(req, "To");
24563 char totag[128];
24564 set_pvt_allowed_methods(p, req);
24565
24566
24567 if (!ast_strlen_zero(to) && gettag(req, "To", totag, sizeof(totag))) {
24568 if (req->debug)
24569 ast_verbose("Received resubscription for a dialog we no longer know about. Telling remote side to subscribe again.\n");
24570 transmit_response(p, "481 Subscription does not exist", req);
24571 pvt_set_needdestroy(p, "subscription does not exist");
24572 return 0;
24573 }
24574
24575
24576 if (req->debug)
24577 ast_verbose("Creating new subscription\n");
24578
24579 copy_request(&p->initreq, req);
24580 if (sipdebug)
24581 ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
24582 check_via(p, req);
24583 build_route(p, req, 0, 0);
24584 } else if (req->debug && req->ignore)
24585 ast_verbose("Ignoring this SUBSCRIBE request\n");
24586
24587
24588 if (ast_strlen_zero(eventheader)) {
24589 transmit_response(p, "489 Bad Event", req);
24590 ast_debug(2, "Received SIP subscribe for unknown event package: <none>\n");
24591 pvt_set_needdestroy(p, "unknown event package in subscribe");
24592 return 0;
24593 }
24594
24595 if ( (strchr(eventheader, ';'))) {
24596 event = ast_strdupa(eventheader);
24597 temp = strchr(event, ';');
24598 *temp = '\0';
24599
24600 } else
24601 event = (char *) eventheader;
24602
24603
24604
24605
24606 if (p->subscribed == NONE || resubscribe) {
24607 res = check_user_full(p, req, SIP_SUBSCRIBE, e, 0, addr, &authpeer);
24608
24609
24610 if (res == AUTH_CHALLENGE_SENT)
24611 return 0;
24612 if (res != AUTH_SUCCESSFUL) {
24613 if (res == AUTH_FAKE_AUTH) {
24614 ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", get_header(req, "From"));
24615 transmit_fake_auth_response(p, SIP_SUBSCRIBE, req, XMIT_UNRELIABLE);
24616 } else {
24617 ast_log(LOG_NOTICE, "Failed to authenticate device %s for SUBSCRIBE\n", get_header(req, "From"));
24618 transmit_response_reliable(p, "403 Forbidden", req);
24619 }
24620
24621 pvt_set_needdestroy(p, "authentication failed");
24622 return 0;
24623 }
24624 }
24625
24626
24627
24628
24629
24630
24631 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
24632 transmit_response(p, "403 Forbidden (policy)", req);
24633 pvt_set_needdestroy(p, "subscription not allowed");
24634 if (authpeer) {
24635 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 1)");
24636 }
24637 return 0;
24638 }
24639
24640 if (strcmp(event, "message-summary") && strcmp(event, "call-completion")) {
24641
24642 gotdest = get_destination(p, NULL, NULL);
24643 }
24644
24645
24646 parse_ok_contact(p, req);
24647
24648 build_contact(p);
24649 if (gotdest != SIP_GET_DEST_EXTEN_FOUND) {
24650 if (gotdest == SIP_GET_DEST_INVALID_URI) {
24651 transmit_response(p, "416 Unsupported URI scheme", req);
24652 } else {
24653 transmit_response(p, "404 Not Found", req);
24654 }
24655 pvt_set_needdestroy(p, "subscription target not found");
24656 if (authpeer) {
24657 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
24658 }
24659 return 0;
24660 }
24661
24662
24663 if (ast_strlen_zero(p->tag))
24664 make_our_tag(p->tag, sizeof(p->tag));
24665
24666 if (!strcmp(event, "presence") || !strcmp(event, "dialog")) {
24667 unsigned int pidf_xml;
24668 const char *accept;
24669 int start = 0;
24670 enum subscriptiontype subscribed = NONE;
24671 const char *unknown_acceptheader = NULL;
24672
24673
24674 accept = __get_header(req, "Accept", &start);
24675 while ((subscribed == NONE) && !ast_strlen_zero(accept)) {
24676 pidf_xml = strstr(accept, "application/pidf+xml") ? 1 : 0;
24677
24678
24679
24680 if (pidf_xml && strstr(p->useragent, "Polycom")) {
24681 subscribed = XPIDF_XML;
24682 } else if (pidf_xml) {
24683 subscribed = PIDF_XML;
24684 } else if (strstr(accept, "application/dialog-info+xml")) {
24685 subscribed = DIALOG_INFO_XML;
24686
24687 } else if (strstr(accept, "application/cpim-pidf+xml")) {
24688 subscribed = CPIM_PIDF_XML;
24689 } else if (strstr(accept, "application/xpidf+xml")) {
24690 subscribed = XPIDF_XML;
24691 } else {
24692 unknown_acceptheader = accept;
24693 }
24694
24695 accept = __get_header(req, "Accept", &start);
24696 }
24697
24698 if (!start) {
24699 if (p->subscribed == NONE) {
24700 transmit_response(p, "489 Bad Event", req);
24701 ast_log(LOG_WARNING,"SUBSCRIBE failure: no Accept header: pvt: "
24702 "stateid: %d, laststate: %d, dialogver: %u, subscribecont: "
24703 "'%s', subscribeuri: '%s'\n",
24704 p->stateid,
24705 p->laststate,
24706 p->dialogver,
24707 p->subscribecontext,
24708 p->subscribeuri);
24709 pvt_set_needdestroy(p, "no Accept header");
24710 if (authpeer) {
24711 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
24712 }
24713 return 0;
24714 }
24715
24716
24717 } else if (subscribed == NONE) {
24718
24719 char mybuf[200];
24720 if (!ast_strlen_zero(unknown_acceptheader)) {
24721 snprintf(mybuf, sizeof(mybuf), "489 Bad Event (format %s)", unknown_acceptheader);
24722 } else {
24723 snprintf(mybuf, sizeof(mybuf), "489 Bad Event");
24724 }
24725 transmit_response(p, mybuf, req);
24726 ast_log(LOG_WARNING,"SUBSCRIBE failure: unrecognized format:"
24727 "'%s' pvt: subscribed: %d, stateid: %d, laststate: %d,"
24728 "dialogver: %u, subscribecont: '%s', subscribeuri: '%s'\n",
24729 unknown_acceptheader,
24730 (int)p->subscribed,
24731 p->stateid,
24732 p->laststate,
24733 p->dialogver,
24734 p->subscribecontext,
24735 p->subscribeuri);
24736 pvt_set_needdestroy(p, "unrecognized format");
24737 if (authpeer) {
24738 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
24739 }
24740 return 0;
24741 } else {
24742 p->subscribed = subscribed;
24743 }
24744 } else if (!strcmp(event, "message-summary")) {
24745 int start = 0;
24746 int found_supported = 0;
24747 const char *acceptheader;
24748
24749 acceptheader = __get_header(req, "Accept", &start);
24750 while (!found_supported && !ast_strlen_zero(acceptheader)) {
24751 found_supported = strcmp(acceptheader, "application/simple-message-summary") ? 0 : 1;
24752 if (!found_supported && (option_debug > 2)) {
24753 ast_log(LOG_DEBUG, "Received SIP mailbox subscription for unknown format: %s\n", acceptheader);
24754 }
24755 acceptheader = __get_header(req, "Accept", &start);
24756 }
24757 if (start && !found_supported) {
24758
24759 transmit_response(p, "406 Not Acceptable", req);
24760 ast_debug(2, "Received SIP mailbox subscription for unknown format: %s\n", acceptheader);
24761 pvt_set_needdestroy(p, "unknown format");
24762 if (authpeer) {
24763 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 3)");
24764 }
24765 return 0;
24766 }
24767
24768
24769
24770
24771
24772 if (!authpeer || AST_LIST_EMPTY(&authpeer->mailboxes)) {
24773 if (!authpeer) {
24774 transmit_response(p, "404 Not found", req);
24775 } else {
24776 transmit_response(p, "404 Not found (no mailbox)", req);
24777 ast_log(LOG_NOTICE, "Received SIP subscribe for peer without mailbox: %s\n", S_OR(authpeer->name, ""));
24778 }
24779 pvt_set_needdestroy(p, "received 404 response");
24780 if (authpeer) {
24781 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 3)");
24782 }
24783 return 0;
24784 }
24785
24786 p->subscribed = MWI_NOTIFICATION;
24787 if (ast_test_flag(&authpeer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY)) {
24788 ao2_unlock(p);
24789 add_peer_mwi_subs(authpeer);
24790 ao2_lock(p);
24791 }
24792 if (authpeer->mwipvt != p) {
24793
24794 if (authpeer->mwipvt) {
24795 dialog_unlink_all(authpeer->mwipvt);
24796 authpeer->mwipvt = dialog_unref(authpeer->mwipvt, "unref dialog authpeer->mwipvt");
24797 }
24798 authpeer->mwipvt = dialog_ref(p, "setting peers' mwipvt to p");
24799 }
24800 if (p->relatedpeer != authpeer) {
24801 if (p->relatedpeer) {
24802 unref_peer(p->relatedpeer, "Unref previously stored relatedpeer ptr");
24803 }
24804 p->relatedpeer = ref_peer(authpeer, "setting dialog's relatedpeer pointer");
24805 }
24806
24807 } else if (!strcmp(event, "call-completion")) {
24808 handle_cc_subscribe(p, req);
24809 } else {
24810 transmit_response(p, "489 Bad Event", req);
24811 ast_debug(2, "Received SIP subscribe for unknown event package: %s\n", event);
24812 pvt_set_needdestroy(p, "unknown event package");
24813 if (authpeer) {
24814 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 5)");
24815 }
24816 return 0;
24817 }
24818
24819
24820 if (p->subscribed != MWI_NOTIFICATION && p->subscribed != CALL_COMPLETION && !resubscribe) {
24821 if (p->stateid != -1) {
24822 ast_extension_state_del(p->stateid, cb_extensionstate);
24823 }
24824 dialog_ref(p, "copying dialog ptr into extension state struct");
24825 p->stateid = ast_extension_state_add_destroy(p->context, p->exten,
24826 cb_extensionstate, cb_extensionstate_destroy, p);
24827 if (p->stateid == -1) {
24828 dialog_unref(p, "copying dialog ptr into extension state struct failed");
24829 }
24830 }
24831
24832 if (!req->ignore && p)
24833 p->lastinvite = seqno;
24834 if (p && !p->needdestroy) {
24835 p->expiry = atoi(get_header(req, "Expires"));
24836
24837
24838 if (p->expiry > max_expiry) {
24839 p->expiry = max_expiry;
24840 } else if (p->expiry < min_expiry && p->expiry > 0) {
24841 transmit_response_with_minexpires(p, "423 Interval too small", req);
24842 ast_log(LOG_WARNING, "Received subscription for extension \"%s\" context \"%s\" "
24843 "with Expire header less that 'minexpire' limit. Received \"Expire: %d\" min is %d\n",
24844 p->exten, p->context, p->expiry, min_expiry);
24845 pvt_set_needdestroy(p, "Expires is less that the min expires allowed.");
24846 if (authpeer) {
24847 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 6)");
24848 }
24849 return 0;
24850 }
24851
24852 if (sipdebug) {
24853 const char *action = p->expiry > 0 ? "Adding" : "Removing";
24854 if (p->subscribed == MWI_NOTIFICATION && p->relatedpeer) {
24855 ast_debug(2, "%s subscription for mailbox notification - peer %s\n",
24856 action, p->relatedpeer->name);
24857 } else if (p->subscribed == CALL_COMPLETION) {
24858 ast_debug(2, "%s CC subscription for peer %s\n", action, p->username);
24859 } else {
24860 ast_debug(2, "%s subscription for extension %s context %s for peer %s\n",
24861 action, p->exten, p->context, p->username);
24862 }
24863 }
24864 if (p->autokillid > -1 && sip_cancel_destroy(p))
24865 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
24866 if (p->expiry > 0)
24867 sip_scheddestroy(p, (p->expiry + 10) * 1000);
24868
24869 if (p->subscribed == MWI_NOTIFICATION) {
24870 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
24871 transmit_response(p, "200 OK", req);
24872 if (p->relatedpeer) {
24873 struct sip_peer *peer = p->relatedpeer;
24874 ref_peer(peer, "ensure a peer ref is held during MWI sending");
24875 ao2_unlock(p);
24876 sip_send_mwi_to_peer(peer, 0);
24877 ao2_lock(p);
24878 unref_peer(peer, "release a peer ref now that MWI is sent");
24879 }
24880 } else if (p->subscribed != CALL_COMPLETION) {
24881 if ((firststate = ast_extension_state(NULL, p->context, p->exten)) < 0) {
24882
24883 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));
24884 transmit_response(p, "404 Not found", req);
24885 pvt_set_needdestroy(p, "no extension for SUBSCRIBE");
24886 if (authpeer) {
24887 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 6)");
24888 }
24889 return 0;
24890 }
24891 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
24892 transmit_response(p, "200 OK", req);
24893 transmit_state_notify(p, firststate, 1, FALSE);
24894 append_history(p, "Subscribestatus", "%s", ast_extension_state2str(firststate));
24895
24896 ast_string_field_build(p, subscribeuri, "%s@%s", p->exten, p->context);
24897
24898
24899 }
24900 if (!p->expiry) {
24901 pvt_set_needdestroy(p, "forcing expiration");
24902 }
24903 }
24904
24905 if (authpeer) {
24906 unref_peer(authpeer, "unref pointer into (*authpeer)");
24907 }
24908 return 1;
24909 }
24910
24911
24912 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e)
24913 {
24914 enum check_auth_result res;
24915
24916
24917
24918 if (p->initreq.headers && p->initreq.method != SIP_REGISTER) {
24919 ast_log(LOG_WARNING, "Ignoring spurious REGISTER with Call-ID: %s\n", p->callid);
24920 return -1;
24921 }
24922
24923
24924 copy_request(&p->initreq, req);
24925 if (sipdebug)
24926 ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
24927 check_via(p, req);
24928 if ((res = register_verify(p, addr, req, e)) < 0) {
24929 const char *reason;
24930
24931 switch (res) {
24932 case AUTH_SECRET_FAILED:
24933 reason = "Wrong password";
24934 break;
24935 case AUTH_USERNAME_MISMATCH:
24936 reason = "Username/auth name mismatch";
24937 break;
24938 case AUTH_NOT_FOUND:
24939 reason = "No matching peer found";
24940 break;
24941 case AUTH_UNKNOWN_DOMAIN:
24942 reason = "Not a local domain";
24943 break;
24944 case AUTH_PEER_NOT_DYNAMIC:
24945 reason = "Peer is not supposed to register";
24946 break;
24947 case AUTH_ACL_FAILED:
24948 reason = "Device does not match ACL";
24949 break;
24950 case AUTH_BAD_TRANSPORT:
24951 reason = "Device not configured to use this transport type";
24952 break;
24953 default:
24954 reason = "Unknown failure";
24955 break;
24956 }
24957 ast_log(LOG_NOTICE, "Registration from '%s' failed for '%s' - %s\n",
24958 get_header(req, "To"), ast_sockaddr_stringify(addr),
24959 reason);
24960 append_history(p, "RegRequest", "Failed : Account %s : %s", get_header(req, "To"), reason);
24961 } else {
24962 req->authenticated = 1;
24963 append_history(p, "RegRequest", "Succeeded : Account %s", get_header(req, "To"));
24964 }
24965
24966 if (res < 1) {
24967
24968
24969 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
24970 }
24971 return res;
24972 }
24973
24974
24975
24976
24977
24978
24979
24980
24981 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int *recount, int *nounlock)
24982 {
24983
24984
24985 const char *cmd;
24986 const char *cseq;
24987 const char *useragent;
24988 const char *via;
24989 const char *callid;
24990 int via_pos = 0;
24991 uint32_t seqno;
24992 int len;
24993 int respid;
24994 int res = 0;
24995 int debug = sip_debug_test_pvt(p);
24996 const char *e;
24997 int error = 0;
24998 int oldmethod = p->method;
24999 int acked = 0;
25000
25001
25002
25003
25004 cseq = get_header(req, "Cseq");
25005 cmd = REQ_OFFSET_TO_STR(req, header[0]);
25006
25007 via = __get_header(req, "Via", &via_pos);
25008
25009 callid = get_header(req, "Call-ID");
25010
25011
25012 if (ast_strlen_zero(cmd) || ast_strlen_zero(cseq) || ast_strlen_zero(via)) {
25013 ast_log(LOG_ERROR, "Dropping this SIP message with Call-ID '%s', it's incomplete.\n", callid);
25014 error = 1;
25015 }
25016 if (!error && sscanf(cseq, "%30u%n", &seqno, &len) != 1) {
25017 ast_log(LOG_ERROR, "No seqno in '%s'. Dropping incomplete message.\n", cmd);
25018 error = 1;
25019 }
25020 if (error) {
25021 if (!p->initreq.headers) {
25022 pvt_set_needdestroy(p, "no headers");
25023 }
25024 return -1;
25025 }
25026
25027
25028 cmd = REQ_OFFSET_TO_STR(req, rlPart1);
25029 e = ast_skip_blanks(REQ_OFFSET_TO_STR(req, rlPart2));
25030
25031
25032 useragent = get_header(req, "User-Agent");
25033 if (!ast_strlen_zero(useragent))
25034 ast_string_field_set(p, useragent, useragent);
25035
25036
25037 if (req->method == SIP_RESPONSE) {
25038
25039
25040
25041
25042
25043
25044 if (ast_strlen_zero(e)) {
25045 return 0;
25046 }
25047 if (sscanf(e, "%30d %n", &respid, &len) != 1) {
25048 ast_log(LOG_WARNING, "Invalid response: '%s'\n", e);
25049 return 0;
25050 }
25051 if (respid <= 0) {
25052 ast_log(LOG_WARNING, "Invalid SIP response code: '%d'\n", respid);
25053 return 0;
25054 }
25055
25056
25057
25058 if (!ast_strlen_zero(__get_header(req, "via", &via_pos))) {
25059 ast_log(LOG_WARNING, "Misrouted SIP response '%s' with Call-ID '%s', too many vias\n", e, callid);
25060 return 0;
25061 }
25062 if (p->ocseq && (p->ocseq < seqno)) {
25063 ast_debug(1, "Ignoring out of order response %u (expecting %u)\n", seqno, p->ocseq);
25064 return -1;
25065 } else {
25066 char causevar[256], causeval[256];
25067
25068 if ((respid == 200) || ((respid >= 300) && (respid <= 399))) {
25069 extract_uri(p, req);
25070 }
25071
25072 handle_response(p, respid, e + len, req, seqno);
25073
25074 if (global_store_sip_cause && p->owner) {
25075 struct ast_channel *owner = p->owner;
25076
25077 snprintf(causevar, sizeof(causevar), "MASTER_CHANNEL(HASH(SIP_CAUSE,%s))", owner->name);
25078 snprintf(causeval, sizeof(causeval), "SIP %s", REQ_OFFSET_TO_STR(req, rlPart2));
25079
25080 ast_channel_ref(owner);
25081 sip_pvt_unlock(p);
25082 ast_channel_unlock(owner);
25083 *nounlock = 1;
25084 pbx_builtin_setvar_helper(owner, causevar, causeval);
25085 ast_channel_unref(owner);
25086 sip_pvt_lock(p);
25087 }
25088 }
25089 return 0;
25090 }
25091
25092
25093
25094
25095
25096 p->method = req->method;
25097 ast_debug(4, "**** Received %s (%d) - Command in SIP %s\n", sip_methods[p->method].text, sip_methods[p->method].id, cmd);
25098
25099 if (p->icseq && (p->icseq > seqno) ) {
25100 if (p->pendinginvite && seqno == p->pendinginvite && (req->method == SIP_ACK || req->method == SIP_CANCEL)) {
25101 ast_debug(2, "Got CANCEL or ACK on INVITE with transactions in between.\n");
25102 } else {
25103 ast_debug(1, "Ignoring too old SIP packet packet %u (expecting >= %u)\n", seqno, p->icseq);
25104 if (req->method == SIP_INVITE) {
25105 unsigned int ran = (ast_random() % 10) + 1;
25106 char seconds[4];
25107 snprintf(seconds, sizeof(seconds), "%u", ran);
25108 transmit_response_with_retry_after(p, "500 Server error", req, seconds);
25109 } else if (req->method != SIP_ACK) {
25110 transmit_response(p, "500 Server error", req);
25111 }
25112 return -1;
25113 }
25114 } else if (p->icseq &&
25115 p->icseq == seqno &&
25116 req->method != SIP_ACK &&
25117 (p->method != SIP_CANCEL || p->alreadygone)) {
25118
25119
25120
25121 req->ignore = 1;
25122 ast_debug(3, "Ignoring SIP message because of retransmit (%s Seqno %u, ours %u)\n", sip_methods[p->method].text, p->icseq, seqno);
25123 }
25124
25125
25126
25127 if (!p->pendinginvite && (req->method == SIP_CANCEL)) {
25128 transmit_response(p, "481 Call/Transaction Does Not Exist", req);
25129 return res;
25130 }
25131
25132 if (seqno >= p->icseq)
25133
25134
25135
25136 p->icseq = seqno;
25137
25138
25139 if (ast_strlen_zero(p->theirtag)) {
25140 char tag[128];
25141
25142 gettag(req, "From", tag, sizeof(tag));
25143 ast_string_field_set(p, theirtag, tag);
25144 }
25145 snprintf(p->lastmsg, sizeof(p->lastmsg), "Rx: %s", cmd);
25146
25147 if (sip_cfg.pedanticsipchecking) {
25148
25149
25150
25151
25152 if (!p->initreq.headers && req->has_to_tag) {
25153
25154 if (!req->ignore && req->method == SIP_INVITE) {
25155 transmit_response_reliable(p, "481 Call/Transaction Does Not Exist", req);
25156
25157 } else if (req->method != SIP_ACK) {
25158 transmit_response(p, "481 Call/Transaction Does Not Exist", req);
25159 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
25160 } else {
25161 ast_debug(1, "Got ACK for unknown dialog... strange.\n");
25162 }
25163 return res;
25164 }
25165 }
25166
25167 if (!e && (p->method == SIP_INVITE || p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER || p->method == SIP_NOTIFY || p->method == SIP_PUBLISH)) {
25168 transmit_response(p, "400 Bad request", req);
25169 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
25170 return -1;
25171 }
25172
25173
25174 switch (p->method) {
25175 case SIP_OPTIONS:
25176 res = handle_request_options(p, req, addr, e);
25177 break;
25178 case SIP_INVITE:
25179 res = handle_request_invite(p, req, debug, seqno, addr, recount, e, nounlock);
25180 break;
25181 case SIP_REFER:
25182 res = handle_request_refer(p, req, debug, seqno, nounlock);
25183 break;
25184 case SIP_CANCEL:
25185 res = handle_request_cancel(p, req);
25186 break;
25187 case SIP_BYE:
25188 res = handle_request_bye(p, req);
25189 break;
25190 case SIP_MESSAGE:
25191 res = handle_request_message(p, req);
25192 break;
25193 case SIP_PUBLISH:
25194 res = handle_request_publish(p, req, addr, seqno, e);
25195 break;
25196 case SIP_SUBSCRIBE:
25197 res = handle_request_subscribe(p, req, addr, seqno, e);
25198 break;
25199 case SIP_REGISTER:
25200 res = handle_request_register(p, req, addr, e);
25201 break;
25202 case SIP_INFO:
25203 if (req->debug)
25204 ast_verbose("Receiving INFO!\n");
25205 if (!req->ignore)
25206 handle_request_info(p, req);
25207 else
25208 transmit_response(p, "200 OK", req);
25209 break;
25210 case SIP_NOTIFY:
25211 res = handle_request_notify(p, req, addr, seqno, e);
25212 break;
25213 case SIP_UPDATE:
25214 res = handle_request_update(p, req);
25215 break;
25216 case SIP_ACK:
25217
25218 if (seqno == p->pendinginvite) {
25219 p->invitestate = INV_TERMINATED;
25220 p->pendinginvite = 0;
25221 acked = __sip_ack(p, seqno, 1 , 0);
25222 if (find_sdp(req)) {
25223 if (process_sdp(p, req, SDP_T38_NONE))
25224 return -1;
25225 }
25226 check_pendings(p);
25227 } else if (p->glareinvite == seqno) {
25228
25229 p->glareinvite = 0;
25230 acked = __sip_ack(p, seqno, 1, 0);
25231 }
25232 if (!acked) {
25233
25234
25235 p->method = oldmethod;
25236 }
25237 if (!p->lastinvite && ast_strlen_zero(p->randdata)) {
25238 pvt_set_needdestroy(p, "unmatched ACK");
25239 }
25240 break;
25241 default:
25242 transmit_response_with_allow(p, "501 Method Not Implemented", req, 0);
25243 ast_log(LOG_NOTICE, "Unknown SIP command '%s' from '%s'\n",
25244 cmd, ast_sockaddr_stringify(&p->sa));
25245
25246 if (!p->initreq.headers) {
25247 pvt_set_needdestroy(p, "unimplemented method");
25248 }
25249 break;
25250 }
25251 return res;
25252 }
25253
25254
25255
25256
25257
25258
25259 static int sipsock_read(int *id, int fd, short events, void *ignore)
25260 {
25261 struct sip_request req;
25262 struct ast_sockaddr addr;
25263 int res;
25264 static char readbuf[65535];
25265
25266 memset(&req, 0, sizeof(req));
25267 res = ast_recvfrom(fd, readbuf, sizeof(readbuf) - 1, 0, &addr);
25268 if (res < 0) {
25269 #if !defined(__FreeBSD__)
25270 if (errno == EAGAIN)
25271 ast_log(LOG_NOTICE, "SIP: Received packet with bad UDP checksum\n");
25272 else
25273 #endif
25274 if (errno != ECONNREFUSED)
25275 ast_log(LOG_WARNING, "Recv error: %s\n", strerror(errno));
25276 return 1;
25277 }
25278
25279 readbuf[res] = '\0';
25280
25281 if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
25282 return 1;
25283 }
25284
25285 if (ast_str_set(&req.data, 0, "%s", readbuf) == AST_DYNSTR_BUILD_FAILED) {
25286 return -1;
25287 }
25288
25289 req.socket.fd = sipsock;
25290 set_socket_transport(&req.socket, SIP_TRANSPORT_UDP);
25291 req.socket.tcptls_session = NULL;
25292 req.socket.port = htons(ast_sockaddr_port(&bindaddr));
25293
25294 handle_request_do(&req, &addr);
25295 deinit_req(&req);
25296
25297 return 1;
25298 }
25299
25300
25301
25302
25303
25304 static int handle_request_do(struct sip_request *req, struct ast_sockaddr *addr)
25305 {
25306 struct sip_pvt *p;
25307 struct ast_channel *owner_chan_ref = NULL;
25308 int recount = 0;
25309 int nounlock = 0;
25310
25311 if (sip_debug_test_addr(addr))
25312 req->debug = 1;
25313 if (sip_cfg.pedanticsipchecking)
25314 lws2sws(req->data);
25315 if (req->debug) {
25316 ast_verbose("\n<--- SIP read from %s:%s --->\n%s\n<------------->\n",
25317 get_transport(req->socket.type), ast_sockaddr_stringify(addr), req->data->str);
25318 }
25319
25320 if (parse_request(req) == -1) {
25321 ast_str_reset(req->data);
25322 return 1;
25323 }
25324 req->method = find_sip_method(REQ_OFFSET_TO_STR(req, rlPart1));
25325
25326 if (req->debug)
25327 ast_verbose("--- (%d headers %d lines)%s ---\n", req->headers, req->lines, (req->headers + req->lines == 0) ? " Nat keepalive" : "");
25328
25329 if (req->headers < 2) {
25330 ast_str_reset(req->data);
25331 return 1;
25332 }
25333
25334
25335 ast_mutex_lock(&netlock);
25336
25337
25338 p = find_call(req, addr, req->method);
25339 if (p == NULL) {
25340 ast_debug(1, "Invalid SIP message - rejected , no callid, len %zu\n", ast_str_strlen(req->data));
25341 ast_mutex_unlock(&netlock);
25342 return 1;
25343 }
25344
25345
25346
25347 owner_chan_ref = sip_pvt_lock_full(p);
25348
25349 copy_socket_data(&p->socket, &req->socket);
25350 ast_sockaddr_copy(&p->recv, addr);
25351
25352
25353 if (p->owner) {
25354 req->authenticated = 1;
25355 }
25356
25357 if (p->do_history)
25358 append_history(p, "Rx", "%s / %s / %s", req->data->str, get_header(req, "CSeq"), REQ_OFFSET_TO_STR(req, rlPart2));
25359
25360 if (handle_incoming(p, req, addr, &recount, &nounlock) == -1) {
25361
25362 ast_debug(1, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
25363 }
25364
25365 if (recount) {
25366 ast_update_use_count();
25367 }
25368
25369 if (p->owner && !nounlock) {
25370 ast_channel_unlock(p->owner);
25371 }
25372 if (owner_chan_ref) {
25373 ast_channel_unref(owner_chan_ref);
25374 }
25375 sip_pvt_unlock(p);
25376 ao2_t_ref(p, -1, "throw away dialog ptr from find_call at end of routine");
25377 ast_mutex_unlock(&netlock);
25378
25379 return 1;
25380 }
25381
25382
25383
25384
25385
25386
25387
25388 static int sip_standard_port(enum sip_transport type, int port)
25389 {
25390 if (type & SIP_TRANSPORT_TLS)
25391 return port == STANDARD_TLS_PORT;
25392 else
25393 return port == STANDARD_SIP_PORT;
25394 }
25395
25396 static int threadinfo_locate_cb(void *obj, void *arg, int flags)
25397 {
25398 struct sip_threadinfo *th = obj;
25399 struct ast_sockaddr *s = arg;
25400
25401 if (!ast_sockaddr_cmp(s, &th->tcptls_session->remote_address)) {
25402 return CMP_MATCH | CMP_STOP;
25403 }
25404
25405 return 0;
25406 }
25407
25408
25409
25410
25411
25412
25413 static struct ast_tcptls_session_instance *sip_tcp_locate(struct ast_sockaddr *s)
25414 {
25415 struct sip_threadinfo *th;
25416 struct ast_tcptls_session_instance *tcptls_instance = NULL;
25417
25418 if ((th = ao2_callback(threadt, 0, threadinfo_locate_cb, s))) {
25419 tcptls_instance = (ao2_ref(th->tcptls_session, +1), th->tcptls_session);
25420 ao2_t_ref(th, -1, "decrement ref from callback");
25421 }
25422
25423 return tcptls_instance;
25424 }
25425
25426
25427
25428
25429
25430
25431 int get_address_family_filter(const struct ast_sockaddr *addr)
25432 {
25433 if (ast_sockaddr_is_ipv6(addr) && ast_sockaddr_is_any(addr)) {
25434 return 0;
25435 }
25436
25437 return addr->ss.ss_family;
25438 }
25439
25440
25441 static int sip_prepare_socket(struct sip_pvt *p)
25442 {
25443 struct sip_socket *s = &p->socket;
25444 static const char name[] = "SIP socket";
25445 struct sip_threadinfo *th = NULL;
25446 struct ast_tcptls_session_instance *tcptls_session;
25447 struct ast_tcptls_session_args *ca;
25448 struct ast_sockaddr sa_tmp;
25449 pthread_t launched;
25450
25451
25452 if ((s->fd != -1) && (s->type == SIP_TRANSPORT_UDP)) {
25453 return s->fd;
25454 }
25455 if ((s->type & (SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS)) &&
25456 (s->tcptls_session) &&
25457 (s->tcptls_session->fd != -1)) {
25458 return s->tcptls_session->fd;
25459 }
25460
25461
25462
25463
25464 if (p->outboundproxy && p->outboundproxy->transport) {
25465 s->type = p->outboundproxy->transport;
25466 }
25467
25468 if (s->type == SIP_TRANSPORT_UDP) {
25469 s->fd = sipsock;
25470 return s->fd;
25471 }
25472
25473
25474
25475
25476
25477
25478
25479
25480
25481
25482
25483 ast_sockaddr_copy(&sa_tmp, sip_real_dst(p));
25484 if ((tcptls_session = sip_tcp_locate(&sa_tmp))) {
25485 s->fd = tcptls_session->fd;
25486 if (s->tcptls_session) {
25487 ao2_ref(s->tcptls_session, -1);
25488 s->tcptls_session = NULL;
25489 }
25490 s->tcptls_session = tcptls_session;
25491 return s->fd;
25492
25493 } else if (s->tcptls_session) {
25494 return s->fd;
25495 }
25496
25497
25498
25499 if (!(ca = ao2_alloc(sizeof(*ca), sip_tcptls_client_args_destructor)) ||
25500 !(ca->name = ast_strdup(name))) {
25501 goto create_tcptls_session_fail;
25502 }
25503 ca->accept_fd = -1;
25504 ast_sockaddr_copy(&ca->remote_address,sip_real_dst(p));
25505
25506 if (s->type == SIP_TRANSPORT_TLS) {
25507 if (!(ca->tls_cfg = ast_calloc(1, sizeof(*ca->tls_cfg)))) {
25508 goto create_tcptls_session_fail;
25509 }
25510 memcpy(ca->tls_cfg, &default_tls_cfg, sizeof(*ca->tls_cfg));
25511
25512 if (!(ca->tls_cfg->certfile = ast_strdup(default_tls_cfg.certfile)) ||
25513 !(ca->tls_cfg->pvtfile = ast_strdup(default_tls_cfg.pvtfile)) ||
25514 !(ca->tls_cfg->cipher = ast_strdup(default_tls_cfg.cipher)) ||
25515 !(ca->tls_cfg->cafile = ast_strdup(default_tls_cfg.cafile)) ||
25516 !(ca->tls_cfg->capath = ast_strdup(default_tls_cfg.capath))) {
25517
25518 goto create_tcptls_session_fail;
25519 }
25520
25521
25522 if (!ast_strlen_zero(p->tohost)) {
25523 ast_copy_string(ca->hostname, p->tohost, sizeof(ca->hostname));
25524 }
25525 }
25526
25527
25528 if (!(s->tcptls_session = ast_tcptls_client_create(ca))) {
25529 goto create_tcptls_session_fail;
25530 }
25531
25532 s->fd = s->tcptls_session->fd;
25533
25534
25535
25536
25537
25538 if (!(th = sip_threadinfo_create(s->tcptls_session, s->type))) {
25539 goto create_tcptls_session_fail;
25540 }
25541
25542
25543 ao2_ref(s->tcptls_session, +1);
25544
25545 if (ast_pthread_create_detached_background(&launched, NULL, sip_tcp_worker_fn, s->tcptls_session)) {
25546 ast_debug(1, "Unable to launch '%s'.", ca->name);
25547 ao2_ref(s->tcptls_session, -1);
25548 goto create_tcptls_session_fail;
25549 }
25550
25551 return s->fd;
25552
25553 create_tcptls_session_fail:
25554 if (ca) {
25555 ao2_t_ref(ca, -1, "failed to create client, getting rid of client tcptls_session arguments");
25556 }
25557 if (s->tcptls_session) {
25558 ast_tcptls_close_session_file(tcptls_session);
25559 s->fd = -1;
25560 ao2_ref(s->tcptls_session, -1);
25561 s->tcptls_session = NULL;
25562 }
25563 if (th) {
25564 ao2_t_unlink(threadt, th, "Removing tcptls thread info object, thread failed to open");
25565 }
25566
25567 return -1;
25568 }
25569
25570
25571
25572
25573
25574 static int get_cached_mwi(struct sip_peer *peer, int *new, int *old)
25575 {
25576 struct sip_mailbox *mailbox;
25577 int in_cache;
25578
25579 in_cache = 0;
25580 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
25581 struct ast_event *event;
25582 event = ast_event_get_cached(AST_EVENT_MWI,
25583 AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox->mailbox,
25584 AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, S_OR(mailbox->context, "default"),
25585 AST_EVENT_IE_END);
25586 if (!event)
25587 continue;
25588 *new += ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
25589 *old += ast_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS);
25590 ast_event_destroy(event);
25591 in_cache = 1;
25592 }
25593
25594 return in_cache;
25595 }
25596
25597
25598
25599
25600 static int sip_send_mwi_to_peer(struct sip_peer *peer, int cache_only)
25601 {
25602
25603 struct sip_pvt *p;
25604 int newmsgs = 0, oldmsgs = 0;
25605 const char *vmexten = NULL;
25606
25607 ao2_lock(peer);
25608
25609 if (peer->vmexten) {
25610 vmexten = ast_strdupa(peer->vmexten);
25611 }
25612
25613 if (ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY) && !peer->mwipvt) {
25614 ao2_unlock(peer);
25615 return 0;
25616 }
25617
25618
25619 if (ast_sockaddr_isnull(&peer->addr) && ast_sockaddr_isnull(&peer->defaddr)) {
25620 ao2_unlock(peer);
25621 return 0;
25622 }
25623
25624
25625 if (!get_cached_mwi(peer, &newmsgs, &oldmsgs) && !cache_only) {
25626
25627 struct ast_str *mailbox_str = ast_str_alloca(512);
25628 peer_mailboxes_to_str(&mailbox_str, peer);
25629 ao2_unlock(peer);
25630 ast_app_inboxcount(mailbox_str->str, &newmsgs, &oldmsgs);
25631 ao2_lock(peer);
25632 }
25633
25634 if (peer->mwipvt) {
25635
25636 p = dialog_ref(peer->mwipvt, "sip_send_mwi_to_peer: Setting dialog ptr p from peer->mwipvt");
25637 ao2_unlock(peer);
25638 } else {
25639 ao2_unlock(peer);
25640
25641 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
25642 return -1;
25643 }
25644
25645
25646
25647
25648
25649 set_socket_transport(&p->socket, 0);
25650 if (create_addr_from_peer(p, peer)) {
25651
25652 dialog_unlink_all(p);
25653 dialog_unref(p, "unref dialog p just created via sip_alloc");
25654
25655 return 0;
25656 }
25657
25658 ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
25659 build_via(p);
25660
25661 ao2_lock(peer);
25662 if (!ast_strlen_zero(peer->mwi_from)) {
25663 ast_string_field_set(p, mwi_from, peer->mwi_from);
25664 } else if (!ast_strlen_zero(default_mwi_from)) {
25665 ast_string_field_set(p, mwi_from, default_mwi_from);
25666 }
25667 ao2_unlock(peer);
25668
25669
25670 change_callid_pvt(p, NULL);
25671
25672
25673 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
25674 }
25675
25676
25677
25678 sip_pvt_lock(p);
25679
25680
25681 ast_set_flag(&p->flags[0], SIP_OUTGOING);
25682
25683 transmit_notify_with_mwi(p, newmsgs, oldmsgs, vmexten);
25684 sip_pvt_unlock(p);
25685 dialog_unref(p, "unref dialog ptr p just before it goes out of scope at the end of sip_send_mwi_to_peer.");
25686
25687 return 0;
25688 }
25689
25690
25691 static void check_rtp_timeout(struct sip_pvt *dialog, time_t t)
25692 {
25693
25694 if (!dialog->rtp || !dialog->owner)
25695 return;
25696
25697
25698 if (dialog->owner->_state != AST_STATE_UP || !ast_sockaddr_isnull(&dialog->redirip))
25699 return;
25700
25701
25702 if (dialog->t38.state == T38_ENABLED)
25703 return;
25704
25705
25706 if (!ast_rtp_instance_get_keepalive(dialog->rtp) && !ast_rtp_instance_get_timeout(dialog->rtp) && !ast_rtp_instance_get_hold_timeout(dialog->rtp)) {
25707 return;
25708 }
25709
25710
25711 if (dialog->lastrtptx && ast_rtp_instance_get_keepalive(dialog->rtp) &&
25712 (t > dialog->lastrtptx + ast_rtp_instance_get_keepalive(dialog->rtp))) {
25713
25714 dialog->lastrtptx = time(NULL);
25715 ast_rtp_instance_sendcng(dialog->rtp, 0);
25716 }
25717
25718
25719
25720
25721
25722
25723
25724
25725 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))) {
25726 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)))) {
25727
25728 if (ast_rtp_instance_get_timeout(dialog->rtp)) {
25729 if (!dialog->owner || ast_channel_trylock(dialog->owner)) {
25730
25731
25732
25733
25734 return;
25735 }
25736 ast_log(LOG_NOTICE, "Disconnecting call '%s' for lack of RTP activity in %ld seconds\n",
25737 dialog->owner->name, (long) (t - dialog->lastrtprx));
25738
25739 ast_softhangup_nolock(dialog->owner, AST_SOFTHANGUP_DEV);
25740 ast_channel_unlock(dialog->owner);
25741
25742
25743
25744
25745 ast_rtp_instance_set_timeout(dialog->rtp, 0);
25746 ast_rtp_instance_set_hold_timeout(dialog->rtp, 0);
25747 if (dialog->vrtp) {
25748 ast_rtp_instance_set_timeout(dialog->vrtp, 0);
25749 ast_rtp_instance_set_hold_timeout(dialog->vrtp, 0);
25750 }
25751 }
25752 }
25753 }
25754 }
25755
25756
25757
25758
25759
25760 static void *do_monitor(void *data)
25761 {
25762 int res;
25763 time_t t;
25764 int reloading;
25765
25766
25767 if (sipsock > -1)
25768 sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
25769
25770
25771 for(;;) {
25772
25773 ast_mutex_lock(&sip_reload_lock);
25774 reloading = sip_reloading;
25775 sip_reloading = FALSE;
25776 ast_mutex_unlock(&sip_reload_lock);
25777 if (reloading) {
25778 ast_verb(1, "Reloading SIP\n");
25779 sip_do_reload(sip_reloadreason);
25780
25781
25782 if (sipsock > -1) {
25783 if (sipsock_read_id)
25784 sipsock_read_id = ast_io_change(io, sipsock_read_id, sipsock, NULL, 0, NULL);
25785 else
25786 sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
25787 } else if (sipsock_read_id) {
25788 ast_io_remove(io, sipsock_read_id);
25789 sipsock_read_id = NULL;
25790 }
25791 }
25792
25793
25794 t = time(NULL);
25795
25796
25797
25798
25799
25800
25801
25802
25803
25804
25805 ao2_t_callback(dialogs, OBJ_NODATA | OBJ_MULTIPLE, dialog_needdestroy, &t,
25806 "callback to monitor dialog status");
25807 if (ao2_container_count(dialogs_to_destroy)) {
25808
25809 ao2_t_callback(dialogs_to_destroy, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE,
25810 dialog_unlink_callback, NULL, "callback to dialog_unlink_all");
25811 }
25812
25813
25814
25815
25816
25817
25818
25819 pthread_testcancel();
25820
25821 res = ast_sched_wait(sched);
25822 if ((res < 0) || (res > 1000))
25823 res = 1000;
25824 res = ast_io_wait(io, res);
25825 if (res > 20)
25826 ast_debug(1, "chan_sip: ast_io_wait ran %d all at once\n", res);
25827 ast_mutex_lock(&monlock);
25828 res = ast_sched_runq(sched);
25829 if (res >= 20)
25830 ast_debug(1, "chan_sip: ast_sched_runq ran %d all at once\n", res);
25831 if (global_store_sip_cause && res >= 100)
25832 ast_log(LOG_WARNING, "scheduler delays detected, setting 'storesipcause' to 'no' in %s will improve performance\n", config);
25833 ast_mutex_unlock(&monlock);
25834 }
25835
25836
25837 return NULL;
25838 }
25839
25840
25841 static int restart_monitor(void)
25842 {
25843
25844 if (monitor_thread == AST_PTHREADT_STOP)
25845 return 0;
25846 ast_mutex_lock(&monlock);
25847 if (monitor_thread == pthread_self()) {
25848 ast_mutex_unlock(&monlock);
25849 ast_log(LOG_WARNING, "Cannot kill myself\n");
25850 return -1;
25851 }
25852 if (monitor_thread != AST_PTHREADT_NULL) {
25853
25854 pthread_kill(monitor_thread, SIGURG);
25855 } else {
25856
25857 if (ast_pthread_create_background(&monitor_thread, NULL, do_monitor, NULL) < 0) {
25858 ast_mutex_unlock(&monlock);
25859 ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
25860 return -1;
25861 }
25862 }
25863 ast_mutex_unlock(&monlock);
25864 return 0;
25865 }
25866
25867
25868
25869 static void restart_session_timer(struct sip_pvt *p)
25870 {
25871 if (!p->stimer) {
25872 ast_log(LOG_WARNING, "Null stimer in restart_session_timer - %s\n", p->callid);
25873 return;
25874 }
25875
25876 if (p->stimer->st_active == TRUE) {
25877 ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
25878 AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
25879 dialog_unref(p, "Removing session timer ref"));
25880 start_session_timer(p);
25881 }
25882 }
25883
25884
25885
25886 static void stop_session_timer(struct sip_pvt *p)
25887 {
25888 if (!p->stimer) {
25889 ast_log(LOG_WARNING, "Null stimer in stop_session_timer - %s\n", p->callid);
25890 return;
25891 }
25892
25893 if (p->stimer->st_active == TRUE) {
25894 p->stimer->st_active = FALSE;
25895 ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
25896 AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
25897 dialog_unref(p, "removing session timer ref"));
25898 }
25899 }
25900
25901
25902
25903 static void start_session_timer(struct sip_pvt *p)
25904 {
25905 if (!p->stimer) {
25906 ast_log(LOG_WARNING, "Null stimer in start_session_timer - %s\n", p->callid);
25907 return;
25908 }
25909
25910 if (p->stimer->st_schedid > -1) {
25911
25912 ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
25913 AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
25914 dialog_unref(p, "unref stimer->st_schedid from dialog"));
25915 }
25916
25917 p->stimer->st_schedid = ast_sched_add(sched, p->stimer->st_interval * 1000 / 2, proc_session_timer,
25918 dialog_ref(p, "adding session timer ref"));
25919 if (p->stimer->st_schedid < 0) {
25920 dialog_unref(p, "removing session timer ref");
25921 ast_log(LOG_ERROR, "ast_sched_add failed - %s\n", p->callid);
25922 } else {
25923 p->stimer->st_active = TRUE;
25924 ast_debug(2, "Session timer started: %d - %s\n", p->stimer->st_schedid, p->callid);
25925 }
25926 }
25927
25928
25929
25930 static int proc_session_timer(const void *vp)
25931 {
25932 struct sip_pvt *p = (struct sip_pvt *) vp;
25933 int sendreinv = FALSE;
25934 int res = 0;
25935
25936 if (!p->stimer) {
25937 ast_log(LOG_WARNING, "Null stimer in proc_session_timer - %s\n", p->callid);
25938 goto return_unref;
25939 }
25940
25941 ast_debug(2, "Session timer expired: %d - %s\n", p->stimer->st_schedid, p->callid);
25942
25943 if (!p->owner) {
25944 goto return_unref;
25945 }
25946
25947 if ((p->stimer->st_active != TRUE) || (p->owner->_state != AST_STATE_UP)) {
25948 goto return_unref;
25949 }
25950
25951 switch (p->stimer->st_ref) {
25952 case SESSION_TIMER_REFRESHER_UAC:
25953 if (p->outgoing_call == TRUE) {
25954 sendreinv = TRUE;
25955 }
25956 break;
25957 case SESSION_TIMER_REFRESHER_UAS:
25958 if (p->outgoing_call != TRUE) {
25959 sendreinv = TRUE;
25960 }
25961 break;
25962 default:
25963 ast_log(LOG_ERROR, "Unknown session refresher %d\n", p->stimer->st_ref);
25964 goto return_unref;
25965 }
25966
25967 if (sendreinv == TRUE) {
25968 res = 1;
25969 transmit_reinvite_with_sdp(p, FALSE, TRUE);
25970 } else {
25971 p->stimer->st_expirys++;
25972 if (p->stimer->st_expirys >= 2) {
25973 if (p->stimer->quit_flag) {
25974 goto return_unref;
25975 }
25976 ast_log(LOG_WARNING, "Session-Timer expired - %s\n", p->callid);
25977 sip_pvt_lock(p);
25978 while (p->owner && ast_channel_trylock(p->owner)) {
25979 sip_pvt_unlock(p);
25980 usleep(1);
25981 if (p->stimer && p->stimer->quit_flag) {
25982 goto return_unref;
25983 }
25984 sip_pvt_lock(p);
25985 }
25986
25987 ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
25988 ast_channel_unlock(p->owner);
25989 sip_pvt_unlock(p);
25990 } else {
25991 res = 1;
25992 }
25993 }
25994
25995 return_unref:
25996 if (!res) {
25997
25998 if (p->stimer) {
25999 ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
26000 p->stimer->st_schedid = -1;
26001 stop_session_timer(p);
26002 }
26003
26004
26005
26006 dialog_unref(p, "removing session timer ref");
26007 }
26008
26009 return res;
26010 }
26011
26012
26013
26014 int parse_minse (const char *p_hdrval, int *const p_interval)
26015 {
26016 if (ast_strlen_zero(p_hdrval)) {
26017 ast_log(LOG_WARNING, "Null Min-SE header\n");
26018 return -1;
26019 }
26020
26021 *p_interval = 0;
26022 p_hdrval = ast_skip_blanks(p_hdrval);
26023 if (!sscanf(p_hdrval, "%30d", p_interval)) {
26024 ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
26025 return -1;
26026 }
26027
26028 ast_debug(2, "Received Min-SE: %d\n", *p_interval);
26029 return 0;
26030 }
26031
26032
26033
26034 int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref)
26035 {
26036 char *p_token;
26037 int ref_idx;
26038 char *p_se_hdr;
26039
26040 if (ast_strlen_zero(p_hdrval)) {
26041 ast_log(LOG_WARNING, "Null Session-Expires header\n");
26042 return -1;
26043 }
26044
26045 *p_ref = SESSION_TIMER_REFRESHER_AUTO;
26046 *p_interval = 0;
26047
26048 p_se_hdr = ast_strdupa(p_hdrval);
26049 p_se_hdr = ast_skip_blanks(p_se_hdr);
26050
26051 while ((p_token = strsep(&p_se_hdr, ";"))) {
26052 p_token = ast_skip_blanks(p_token);
26053 if (!sscanf(p_token, "%30d", p_interval)) {
26054 ast_log(LOG_WARNING, "Parsing of Session-Expires failed\n");
26055 return -1;
26056 }
26057
26058 ast_debug(2, "Session-Expires: %d\n", *p_interval);
26059
26060 if (!p_se_hdr)
26061 continue;
26062
26063 p_se_hdr = ast_skip_blanks(p_se_hdr);
26064 ref_idx = strlen("refresher=");
26065 if (!strncasecmp(p_se_hdr, "refresher=", ref_idx)) {
26066 p_se_hdr += ref_idx;
26067 p_se_hdr = ast_skip_blanks(p_se_hdr);
26068
26069 if (!strncasecmp(p_se_hdr, "uac", strlen("uac"))) {
26070 *p_ref = SESSION_TIMER_REFRESHER_UAC;
26071 ast_debug(2, "Refresher: UAC\n");
26072 } else if (!strncasecmp(p_se_hdr, "uas", strlen("uas"))) {
26073 *p_ref = SESSION_TIMER_REFRESHER_UAS;
26074 ast_debug(2, "Refresher: UAS\n");
26075 } else {
26076 ast_log(LOG_WARNING, "Invalid refresher value %s\n", p_se_hdr);
26077 return -1;
26078 }
26079 break;
26080 }
26081 }
26082 return 0;
26083 }
26084
26085
26086
26087
26088
26089
26090
26091
26092
26093 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp)
26094 {
26095 int rtn;
26096 const char *p_hdrval;
26097 int minse;
26098
26099 p_hdrval = get_header(rsp, "Min-SE");
26100 if (ast_strlen_zero(p_hdrval)) {
26101 ast_log(LOG_WARNING, "422 response without a Min-SE header %s\n", p_hdrval);
26102 return;
26103 }
26104 rtn = parse_minse(p_hdrval, &minse);
26105 if (rtn != 0) {
26106 ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
26107 return;
26108 }
26109 p->stimer->st_interval = minse;
26110 transmit_invite(p, SIP_INVITE, 1, 2, NULL);
26111 }
26112
26113
26114
26115
26116
26117
26118 int st_get_se(struct sip_pvt *p, int max)
26119 {
26120 if (max == TRUE) {
26121 if (p->stimer->st_cached_max_se) {
26122 return p->stimer->st_cached_max_se;
26123 }
26124 if (p->relatedpeer) {
26125 p->stimer->st_cached_max_se = p->relatedpeer->stimer.st_max_se;
26126 return (p->stimer->st_cached_max_se);
26127 }
26128 p->stimer->st_cached_max_se = global_max_se;
26129 return (p->stimer->st_cached_max_se);
26130 }
26131
26132 if (p->stimer->st_cached_min_se) {
26133 return p->stimer->st_cached_min_se;
26134 }
26135 if (p->relatedpeer) {
26136 p->stimer->st_cached_min_se = p->relatedpeer->stimer.st_min_se;
26137 return (p->stimer->st_cached_min_se);
26138 }
26139 p->stimer->st_cached_min_se = global_min_se;
26140 return (p->stimer->st_cached_min_se);
26141 }
26142
26143
26144
26145
26146
26147 enum st_refresher st_get_refresher(struct sip_pvt *p)
26148 {
26149 if (p->stimer->st_cached_ref != SESSION_TIMER_REFRESHER_AUTO)
26150 return p->stimer->st_cached_ref;
26151
26152 if (p->relatedpeer) {
26153 p->stimer->st_cached_ref = p->relatedpeer->stimer.st_ref;
26154 return p->stimer->st_cached_ref;
26155 }
26156
26157 p->stimer->st_cached_ref = global_st_refresher;
26158 return global_st_refresher;
26159 }
26160
26161
26162
26163
26164
26165
26166
26167
26168 enum st_mode st_get_mode(struct sip_pvt *p, int no_cached)
26169 {
26170 if (!p->stimer)
26171 sip_st_alloc(p);
26172
26173 if (!no_cached && p->stimer->st_cached_mode != SESSION_TIMER_MODE_INVALID)
26174 return p->stimer->st_cached_mode;
26175
26176 if (p->relatedpeer) {
26177 p->stimer->st_cached_mode = p->relatedpeer->stimer.st_mode_oper;
26178 return p->stimer->st_cached_mode;
26179 }
26180
26181 p->stimer->st_cached_mode = global_st_mode;
26182 return global_st_mode;
26183 }
26184
26185
26186
26187 static int sip_poke_noanswer(const void *data)
26188 {
26189 struct sip_peer *peer = (struct sip_peer *)data;
26190
26191 peer->pokeexpire = -1;
26192
26193 if (peer->lastms > -1) {
26194 ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE! Last qualify: %d\n", peer->name, peer->lastms);
26195 if (sip_cfg.peer_rtupdate) {
26196 ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", "-1", SENTINEL);
26197 }
26198 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer->name, -1);
26199 if (sip_cfg.regextenonqualify) {
26200 register_peer_exten(peer, FALSE);
26201 }
26202 }
26203
26204 if (peer->call) {
26205 dialog_unlink_all(peer->call);
26206 peer->call = dialog_unref(peer->call, "unref dialog peer->call");
26207
26208 }
26209
26210
26211 if (peer->lastms > -1) {
26212 peer->lastms = -1;
26213 ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
26214 }
26215
26216
26217 AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
26218 DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer,
26219 unref_peer(_data, "removing poke peer ref"),
26220 unref_peer(peer, "removing poke peer ref"),
26221 ref_peer(peer, "adding poke peer ref"));
26222
26223
26224 unref_peer(peer, "release peer poke noanswer ref");
26225
26226 return 0;
26227 }
26228
26229
26230
26231
26232
26233
26234 static int sip_poke_peer(struct sip_peer *peer, int force)
26235 {
26236 struct sip_pvt *p;
26237 int xmitres = 0;
26238
26239 if ((!peer->maxms && !force) || ast_sockaddr_isnull(&peer->addr)) {
26240
26241
26242 AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
26243 unref_peer(peer, "removing poke peer ref"));
26244
26245 peer->lastms = 0;
26246 if (peer->call) {
26247 peer->call = dialog_unref(peer->call, "unref dialog peer->call");
26248 }
26249 return 0;
26250 }
26251 if (peer->call) {
26252 if (sipdebug) {
26253 ast_log(LOG_NOTICE, "Still have a QUALIFY dialog active, deleting\n");
26254 }
26255 dialog_unlink_all(peer->call);
26256 peer->call = dialog_unref(peer->call, "unref dialog peer->call");
26257
26258 }
26259 if (!(p = sip_alloc(NULL, NULL, 0, SIP_OPTIONS, NULL))) {
26260 return -1;
26261 }
26262 peer->call = dialog_ref(p, "copy sip alloc from p to peer->call");
26263
26264 p->sa = peer->addr;
26265 p->recv = peer->addr;
26266 copy_socket_data(&p->socket, &peer->socket);
26267 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
26268 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
26269 ast_copy_flags(&p->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
26270
26271
26272 if (!ast_strlen_zero(peer->fullcontact)) {
26273 ast_string_field_set(p, fullcontact, peer->fullcontact);
26274 }
26275
26276 if (!ast_strlen_zero(peer->fromuser)) {
26277 ast_string_field_set(p, fromuser, peer->fromuser);
26278 }
26279
26280 if (!ast_strlen_zero(peer->tohost)) {
26281 ast_string_field_set(p, tohost, peer->tohost);
26282 } else {
26283 ast_string_field_set(p, tohost, ast_sockaddr_stringify_host_remote(&peer->addr));
26284 }
26285
26286
26287 ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
26288 build_via(p);
26289
26290
26291 change_callid_pvt(p, NULL);
26292
26293 AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
26294 unref_peer(peer, "removing poke peer ref"));
26295
26296 if (p->relatedpeer)
26297 p->relatedpeer = unref_peer(p->relatedpeer,"unsetting the relatedpeer field in the dialog, before it is set to something else.");
26298 p->relatedpeer = ref_peer(peer, "setting the relatedpeer field in the dialog");
26299 ast_set_flag(&p->flags[0], SIP_OUTGOING);
26300 #ifdef VOCAL_DATA_HACK
26301 ast_copy_string(p->username, "__VOCAL_DATA_SHOULD_READ_THE_SIP_SPEC__", sizeof(p->username));
26302 xmitres = transmit_invite(p, SIP_INVITE, 0, 2, NULL);
26303 #else
26304 xmitres = transmit_invite(p, SIP_OPTIONS, 0, 2, NULL);
26305 #endif
26306 peer->ps = ast_tvnow();
26307 if (xmitres == XMIT_ERROR) {
26308
26309 sip_poke_noanswer(ref_peer(peer, "add ref for peerexpire (fake, for sip_poke_noanswer to remove)"));
26310 } else if (!force) {
26311 AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, peer->maxms * 2, sip_poke_noanswer, peer,
26312 unref_peer(_data, "removing poke peer ref"),
26313 unref_peer(peer, "removing poke peer ref"),
26314 ref_peer(peer, "adding poke peer ref"));
26315 }
26316 dialog_unref(p, "unref dialog at end of sip_poke_peer, obtained from sip_alloc, just before it goes out of scope");
26317 return 0;
26318 }
26319
26320
26321
26322
26323
26324
26325
26326
26327
26328
26329
26330
26331
26332
26333
26334
26335
26336
26337
26338
26339
26340
26341
26342
26343
26344
26345
26346
26347
26348
26349
26350
26351
26352
26353 static int sip_devicestate(void *data)
26354 {
26355 char *host;
26356 char *tmp;
26357 struct sip_peer *p;
26358
26359 int res = AST_DEVICE_INVALID;
26360
26361
26362 host = ast_strdupa(data ? data : "");
26363 if ((tmp = strchr(host, '@')))
26364 host = tmp + 1;
26365
26366 ast_debug(3, "Checking device state for peer %s\n", host);
26367
26368
26369
26370
26371
26372
26373
26374
26375 if ((p = find_peer(host, NULL, FALSE, FINDALLDEVICES, TRUE, 0))) {
26376 if (!(ast_sockaddr_isnull(&p->addr) && ast_sockaddr_isnull(&p->defaddr))) {
26377
26378
26379
26380
26381
26382
26383
26384
26385
26386
26387
26388 if (p->onHold)
26389
26390 res = AST_DEVICE_ONHOLD;
26391 else if (p->inRinging) {
26392 if (p->inRinging == p->inUse)
26393 res = AST_DEVICE_RINGING;
26394 else
26395 res = AST_DEVICE_RINGINUSE;
26396 } else if (p->call_limit && (p->inUse == p->call_limit))
26397
26398 res = AST_DEVICE_BUSY;
26399 else if (p->call_limit && p->busy_level && p->inUse >= p->busy_level)
26400
26401 res = AST_DEVICE_BUSY;
26402 else if (p->call_limit && p->inUse)
26403
26404 res = AST_DEVICE_INUSE;
26405 else if (p->maxms && ((p->lastms > p->maxms) || (p->lastms < 0)))
26406
26407 res = AST_DEVICE_UNAVAILABLE;
26408 else
26409 res = AST_DEVICE_NOT_INUSE;
26410 } else {
26411
26412 res = AST_DEVICE_UNAVAILABLE;
26413 }
26414 unref_peer(p, "unref_peer, from sip_devicestate, release ref from find_peer");
26415 }
26416
26417 return res;
26418 }
26419
26420
26421
26422
26423
26424
26425
26426
26427
26428
26429
26430 static struct ast_channel *sip_request_call(const char *type, format_t format, const struct ast_channel *requestor, void *data, int *cause)
26431 {
26432 struct sip_pvt *p;
26433 struct ast_channel *tmpc = NULL;
26434 char *ext = NULL, *host;
26435 char tmp[256];
26436 char *dest = data;
26437 char *dnid;
26438 char *secret = NULL;
26439 char *md5secret = NULL;
26440 char *authname = NULL;
26441 char *trans = NULL;
26442 char dialstring[256];
26443 char *remote_address;
26444 enum sip_transport transport = 0;
26445 struct ast_sockaddr remote_address_sa = { {0,} };
26446 format_t oldformat = format;
26447 AST_DECLARE_APP_ARGS(args,
26448 AST_APP_ARG(peerorhost);
26449 AST_APP_ARG(exten);
26450 AST_APP_ARG(remote_address);
26451 );
26452
26453
26454
26455
26456
26457
26458
26459
26460 format &= AST_FORMAT_AUDIO_MASK;
26461 if (!format) {
26462 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));
26463 *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
26464 return NULL;
26465 }
26466 ast_debug(1, "Asked to create a SIP channel with formats: %s\n", ast_getformatname_multiple(tmp, sizeof(tmp), oldformat));
26467
26468 if (ast_strlen_zero(dest)) {
26469 ast_log(LOG_ERROR, "Unable to create channel with empty destination.\n");
26470 *cause = AST_CAUSE_CHANNEL_UNACCEPTABLE;
26471 return NULL;
26472 }
26473
26474 if (!(p = sip_alloc(NULL, NULL, 0, SIP_INVITE, NULL))) {
26475 ast_log(LOG_ERROR, "Unable to build sip pvt data for '%s' (Out of memory or socket error)\n", dest);
26476 *cause = AST_CAUSE_SWITCH_CONGESTION;
26477 return NULL;
26478 }
26479
26480 p->outgoing_call = TRUE;
26481
26482 snprintf(dialstring, sizeof(dialstring), "%s/%s", type, dest);
26483 ast_string_field_set(p, dialstring, dialstring);
26484
26485 if (!(p->options = ast_calloc(1, sizeof(*p->options)))) {
26486 dialog_unlink_all(p);
26487 dialog_unref(p, "unref dialog p from mem fail");
26488
26489 ast_log(LOG_ERROR, "Unable to build option SIP data structure - Out of memory\n");
26490 *cause = AST_CAUSE_SWITCH_CONGESTION;
26491 return NULL;
26492 }
26493
26494
26495 ast_copy_string(tmp, dest, sizeof(tmp));
26496
26497
26498 dnid = strchr(tmp, '!');
26499 if (dnid != NULL) {
26500 *dnid++ = '\0';
26501 ast_string_field_set(p, todnid, dnid);
26502 }
26503
26504
26505 AST_NONSTANDARD_APP_ARGS(args, tmp, '/');
26506
26507
26508 host = strchr(args.peerorhost, '@');
26509 if (host) {
26510 *host++ = '\0';
26511 ext = args.peerorhost;
26512 secret = strchr(ext, ':');
26513 }
26514 if (secret) {
26515 *secret++ = '\0';
26516 md5secret = strchr(secret, ':');
26517 }
26518 if (md5secret) {
26519 *md5secret++ = '\0';
26520 authname = strchr(md5secret, ':');
26521 }
26522 if (authname) {
26523 *authname++ = '\0';
26524 trans = strchr(authname, ':');
26525 }
26526 if (trans) {
26527 *trans++ = '\0';
26528 if (!strcasecmp(trans, "tcp"))
26529 transport = SIP_TRANSPORT_TCP;
26530 else if (!strcasecmp(trans, "tls"))
26531 transport = SIP_TRANSPORT_TLS;
26532 else {
26533 if (strcasecmp(trans, "udp"))
26534 ast_log(LOG_WARNING, "'%s' is not a valid transport option to Dial() for SIP calls, using udp by default.\n", trans);
26535 transport = SIP_TRANSPORT_UDP;
26536 }
26537 } else {
26538 transport = SIP_TRANSPORT_UDP;
26539 }
26540
26541 if (!host) {
26542 ext = args.exten;
26543 host = args.peerorhost;
26544 remote_address = args.remote_address;
26545 } else {
26546 remote_address = args.remote_address;
26547 if (!ast_strlen_zero(args.exten)) {
26548 ast_log(LOG_NOTICE, "Conflicting extension values given. Using '%s' and not '%s'\n", ext, args.exten);
26549 }
26550 }
26551
26552 if (!ast_strlen_zero(remote_address)) {
26553 if (ast_sockaddr_resolve_first(&remote_address_sa, remote_address, 0)) {
26554 ast_log(LOG_WARNING, "Unable to find IP address for host %s. We will not use this remote IP address\n", remote_address);
26555 } else {
26556 if (!ast_sockaddr_port(&remote_address_sa)) {
26557 ast_sockaddr_set_port(&remote_address_sa,
26558 transport & SIP_TRANSPORT_TLS ?
26559 STANDARD_TLS_PORT :
26560 STANDARD_SIP_PORT);
26561 }
26562 }
26563 }
26564
26565 set_socket_transport(&p->socket, transport);
26566
26567
26568
26569
26570
26571
26572 if (create_addr(p, host, NULL, 1, &remote_address_sa)) {
26573 *cause = AST_CAUSE_UNREGISTERED;
26574 ast_debug(3, "Cant create SIP call - target device not registered\n");
26575 dialog_unlink_all(p);
26576 dialog_unref(p, "unref dialog p UNREGISTERED");
26577
26578 return NULL;
26579 }
26580 if (ast_strlen_zero(p->peername) && ext)
26581 ast_string_field_set(p, peername, ext);
26582
26583 ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
26584 build_via(p);
26585
26586
26587 change_callid_pvt(p, NULL);
26588
26589
26590
26591
26592
26593
26594 if (ext) {
26595 ast_string_field_set(p, username, ext);
26596 ast_string_field_set(p, fullcontact, NULL);
26597 }
26598 if (secret && !ast_strlen_zero(secret))
26599 ast_string_field_set(p, peersecret, secret);
26600
26601 if (md5secret && !ast_strlen_zero(md5secret))
26602 ast_string_field_set(p, peermd5secret, md5secret);
26603
26604 if (authname && !ast_strlen_zero(authname))
26605 ast_string_field_set(p, authname, authname);
26606 #if 0
26607 printf("Setting up to call extension '%s' at '%s'\n", ext ? ext : "<none>", host);
26608 #endif
26609 p->prefcodec = oldformat;
26610 p->jointcapability = oldformat & p->capability;
26611 sip_pvt_lock(p);
26612 tmpc = sip_new(p, AST_STATE_DOWN, host, requestor ? requestor->linkedid : NULL);
26613 if (sip_cfg.callevents)
26614 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
26615 "Channel: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
26616 p->owner? p->owner->name : "", "SIP", p->callid, p->fullcontact, p->peername);
26617 sip_pvt_unlock(p);
26618 if (!tmpc) {
26619 dialog_unlink_all(p);
26620
26621 } else {
26622 ast_channel_unlock(tmpc);
26623 }
26624 dialog_unref(p, "toss pvt ptr at end of sip_request_call");
26625 ast_update_use_count();
26626 restart_monitor();
26627 return tmpc;
26628 }
26629
26630
26631 static void set_insecure_flags (struct ast_flags *flags, const char *value, int lineno)
26632 {
26633 if (ast_strlen_zero(value))
26634 return;
26635
26636 if (!ast_false(value)) {
26637 char buf[64];
26638 char *word, *next;
26639
26640 ast_copy_string(buf, value, sizeof(buf));
26641 next = buf;
26642 while ((word = strsep(&next, ","))) {
26643 if (!strcasecmp(word, "port"))
26644 ast_set_flag(&flags[0], SIP_INSECURE_PORT);
26645 else if (!strcasecmp(word, "invite"))
26646 ast_set_flag(&flags[0], SIP_INSECURE_INVITE);
26647 else
26648 ast_log(LOG_WARNING, "Unknown insecure mode '%s' on line %d\n", value, lineno);
26649 }
26650 }
26651 }
26652
26653
26654
26655
26656
26657 static int handle_t38_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v,
26658 int *maxdatagram)
26659 {
26660 int res = 1;
26661
26662 if (!strcasecmp(v->name, "t38pt_udptl")) {
26663 char *buf = ast_strdupa(v->value);
26664 char *word, *next = buf;
26665
26666 ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT);
26667
26668 while ((word = strsep(&next, ","))) {
26669 if (ast_true(word) || !strcasecmp(word, "fec")) {
26670 ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
26671 ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_FEC);
26672 } else if (!strcasecmp(word, "redundancy")) {
26673 ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
26674 ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY);
26675 } else if (!strcasecmp(word, "none")) {
26676 ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
26677 ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL);
26678 } else if (!strncasecmp(word, "maxdatagram=", 12)) {
26679 if (sscanf(&word[12], "%30u", maxdatagram) != 1) {
26680 ast_log(LOG_WARNING, "Invalid maxdatagram '%s' at line %d of %s\n", v->value, v->lineno, config);
26681 *maxdatagram = global_t38_maxdatagram;
26682 }
26683 }
26684 }
26685 } else if (!strcasecmp(v->name, "t38pt_usertpsource")) {
26686 ast_set_flag(&mask[1], SIP_PAGE2_UDPTL_DESTINATION);
26687 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_UDPTL_DESTINATION);
26688 } else {
26689 res = 0;
26690 }
26691
26692 return res;
26693 }
26694
26695
26696
26697
26698
26699
26700
26701
26702 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v)
26703 {
26704 int res = 1;
26705
26706 if (!strcasecmp(v->name, "trustrpid")) {
26707 ast_set_flag(&mask[0], SIP_TRUSTRPID);
26708 ast_set2_flag(&flags[0], ast_true(v->value), SIP_TRUSTRPID);
26709 } else if (!strcasecmp(v->name, "sendrpid")) {
26710 ast_set_flag(&mask[0], SIP_SENDRPID);
26711 if (!strcasecmp(v->value, "pai")) {
26712 ast_set_flag(&flags[0], SIP_SENDRPID_PAI);
26713 } else if (!strcasecmp(v->value, "rpid")) {
26714 ast_set_flag(&flags[0], SIP_SENDRPID_RPID);
26715 } else if (ast_true(v->value)) {
26716 ast_set_flag(&flags[0], SIP_SENDRPID_RPID);
26717 }
26718 } else if (!strcasecmp(v->name, "rpid_update")) {
26719 ast_set_flag(&mask[1], SIP_PAGE2_RPID_UPDATE);
26720 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RPID_UPDATE);
26721 } else if (!strcasecmp(v->name, "rpid_immediate")) {
26722 ast_set_flag(&mask[1], SIP_PAGE2_RPID_IMMEDIATE);
26723 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RPID_IMMEDIATE);
26724 } else if (!strcasecmp(v->name, "g726nonstandard")) {
26725 ast_set_flag(&mask[0], SIP_G726_NONSTANDARD);
26726 ast_set2_flag(&flags[0], ast_true(v->value), SIP_G726_NONSTANDARD);
26727 } else if (!strcasecmp(v->name, "useclientcode")) {
26728 ast_set_flag(&mask[0], SIP_USECLIENTCODE);
26729 ast_set2_flag(&flags[0], ast_true(v->value), SIP_USECLIENTCODE);
26730 } else if (!strcasecmp(v->name, "dtmfmode")) {
26731 ast_set_flag(&mask[0], SIP_DTMF);
26732 ast_clear_flag(&flags[0], SIP_DTMF);
26733 if (!strcasecmp(v->value, "inband"))
26734 ast_set_flag(&flags[0], SIP_DTMF_INBAND);
26735 else if (!strcasecmp(v->value, "rfc2833"))
26736 ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
26737 else if (!strcasecmp(v->value, "info"))
26738 ast_set_flag(&flags[0], SIP_DTMF_INFO);
26739 else if (!strcasecmp(v->value, "shortinfo"))
26740 ast_set_flag(&flags[0], SIP_DTMF_SHORTINFO);
26741 else if (!strcasecmp(v->value, "auto"))
26742 ast_set_flag(&flags[0], SIP_DTMF_AUTO);
26743 else {
26744 ast_log(LOG_WARNING, "Unknown dtmf mode '%s' on line %d, using rfc2833\n", v->value, v->lineno);
26745 ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
26746 }
26747 } else if (!strcasecmp(v->name, "nat")) {
26748 ast_set_flag(&mask[0], SIP_NAT_FORCE_RPORT);
26749 ast_set_flag(&flags[0], SIP_NAT_FORCE_RPORT);
26750 if (!strcasecmp(v->value, "no")) {
26751 ast_clear_flag(&flags[0], SIP_NAT_FORCE_RPORT);
26752 } else if (!strcasecmp(v->value, "yes")) {
26753
26754 ast_set_flag(&mask[1], SIP_PAGE2_SYMMETRICRTP);
26755 ast_set_flag(&flags[1], SIP_PAGE2_SYMMETRICRTP);
26756 } else if (!strcasecmp(v->value, "comedia")) {
26757 ast_clear_flag(&flags[0], SIP_NAT_FORCE_RPORT);
26758 ast_set_flag(&mask[1], SIP_PAGE2_SYMMETRICRTP);
26759 ast_set_flag(&flags[1], SIP_PAGE2_SYMMETRICRTP);
26760 }
26761 } else if (!strcasecmp(v->name, "directmedia") || !strcasecmp(v->name, "canreinvite")) {
26762 ast_set_flag(&mask[0], SIP_REINVITE);
26763 ast_clear_flag(&flags[0], SIP_REINVITE);
26764 if (ast_true(v->value)) {
26765 ast_set_flag(&flags[0], SIP_DIRECT_MEDIA | SIP_DIRECT_MEDIA_NAT);
26766 } else if (!ast_false(v->value)) {
26767 char buf[64];
26768 char *word, *next = buf;
26769
26770 ast_copy_string(buf, v->value, sizeof(buf));
26771 while ((word = strsep(&next, ","))) {
26772 if (!strcasecmp(word, "update")) {
26773 ast_set_flag(&flags[0], SIP_REINVITE_UPDATE | SIP_DIRECT_MEDIA);
26774 } else if (!strcasecmp(word, "nonat")) {
26775 ast_set_flag(&flags[0], SIP_DIRECT_MEDIA);
26776 ast_clear_flag(&flags[0], SIP_DIRECT_MEDIA_NAT);
26777 } else {
26778 ast_log(LOG_WARNING, "Unknown directmedia mode '%s' on line %d\n", v->value, v->lineno);
26779 }
26780 }
26781 }
26782 } else if (!strcasecmp(v->name, "insecure")) {
26783 ast_set_flag(&mask[0], SIP_INSECURE);
26784 ast_clear_flag(&flags[0], SIP_INSECURE);
26785 set_insecure_flags(&flags[0], v->value, v->lineno);
26786 } else if (!strcasecmp(v->name, "progressinband")) {
26787 ast_set_flag(&mask[0], SIP_PROG_INBAND);
26788 ast_clear_flag(&flags[0], SIP_PROG_INBAND);
26789 if (ast_true(v->value))
26790 ast_set_flag(&flags[0], SIP_PROG_INBAND_YES);
26791 else if (strcasecmp(v->value, "never"))
26792 ast_set_flag(&flags[0], SIP_PROG_INBAND_NO);
26793 } else if (!strcasecmp(v->name, "promiscredir")) {
26794 ast_set_flag(&mask[0], SIP_PROMISCREDIR);
26795 ast_set2_flag(&flags[0], ast_true(v->value), SIP_PROMISCREDIR);
26796 } else if (!strcasecmp(v->name, "videosupport")) {
26797 if (!strcasecmp(v->value, "always")) {
26798 ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
26799 ast_set_flag(&flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
26800 } else {
26801 ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT);
26802 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_VIDEOSUPPORT);
26803 }
26804 } else if (!strcasecmp(v->name, "textsupport")) {
26805 ast_set_flag(&mask[1], SIP_PAGE2_TEXTSUPPORT);
26806 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_TEXTSUPPORT);
26807 res = 1;
26808 } else if (!strcasecmp(v->name, "allowoverlap")) {
26809 ast_set_flag(&mask[1], SIP_PAGE2_ALLOWOVERLAP);
26810 ast_clear_flag(&flags[1], SIP_PAGE2_ALLOWOVERLAP);
26811 if (ast_true(v->value)) {
26812 ast_set_flag(&flags[1], SIP_PAGE2_ALLOWOVERLAP_YES);
26813 } else if (!strcasecmp(v->value, "dtmf")){
26814 ast_set_flag(&flags[1], SIP_PAGE2_ALLOWOVERLAP_DTMF);
26815 }
26816 } else if (!strcasecmp(v->name, "allowsubscribe")) {
26817 ast_set_flag(&mask[1], SIP_PAGE2_ALLOWSUBSCRIBE);
26818 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWSUBSCRIBE);
26819 } else if (!strcasecmp(v->name, "ignoresdpversion")) {
26820 ast_set_flag(&mask[1], SIP_PAGE2_IGNORESDPVERSION);
26821 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_IGNORESDPVERSION);
26822 } else if (!strcasecmp(v->name, "faxdetect")) {
26823 ast_set_flag(&mask[1], SIP_PAGE2_FAX_DETECT);
26824 if (ast_true(v->value)) {
26825 ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_BOTH);
26826 } else if (ast_false(v->value)) {
26827 ast_clear_flag(&flags[1], SIP_PAGE2_FAX_DETECT_BOTH);
26828 } else {
26829 char *buf = ast_strdupa(v->value);
26830 char *word, *next = buf;
26831
26832 while ((word = strsep(&next, ","))) {
26833 if (!strcasecmp(word, "cng")) {
26834 ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_CNG);
26835 } else if (!strcasecmp(word, "t38")) {
26836 ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_T38);
26837 } else {
26838 ast_log(LOG_WARNING, "Unknown faxdetect mode '%s' on line %d.\n", word, v->lineno);
26839 }
26840 }
26841 }
26842 } else if (!strcasecmp(v->name, "rfc2833compensate")) {
26843 ast_set_flag(&mask[1], SIP_PAGE2_RFC2833_COMPENSATE);
26844 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RFC2833_COMPENSATE);
26845 } else if (!strcasecmp(v->name, "buggymwi")) {
26846 ast_set_flag(&mask[1], SIP_PAGE2_BUGGY_MWI);
26847 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_BUGGY_MWI);
26848 } else
26849 res = 0;
26850
26851 return res;
26852 }
26853
26854
26855 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context)
26856 {
26857 struct domain *d;
26858
26859 if (ast_strlen_zero(domain)) {
26860 ast_log(LOG_WARNING, "Zero length domain.\n");
26861 return 1;
26862 }
26863
26864 if (!(d = ast_calloc(1, sizeof(*d))))
26865 return 0;
26866
26867 ast_copy_string(d->domain, domain, sizeof(d->domain));
26868
26869 if (!ast_strlen_zero(context))
26870 ast_copy_string(d->context, context, sizeof(d->context));
26871
26872 d->mode = mode;
26873
26874 AST_LIST_LOCK(&domain_list);
26875 AST_LIST_INSERT_TAIL(&domain_list, d, list);
26876 AST_LIST_UNLOCK(&domain_list);
26877
26878 if (sipdebug)
26879 ast_debug(1, "Added local SIP domain '%s'\n", domain);
26880
26881 return 1;
26882 }
26883
26884
26885 static int check_sip_domain(const char *domain, char *context, size_t len)
26886 {
26887 struct domain *d;
26888 int result = 0;
26889
26890 AST_LIST_LOCK(&domain_list);
26891 AST_LIST_TRAVERSE(&domain_list, d, list) {
26892 if (strcasecmp(d->domain, domain)) {
26893 continue;
26894 }
26895
26896 if (len && !ast_strlen_zero(d->context))
26897 ast_copy_string(context, d->context, len);
26898
26899 result = 1;
26900 break;
26901 }
26902 AST_LIST_UNLOCK(&domain_list);
26903
26904 return result;
26905 }
26906
26907
26908 static void clear_sip_domains(void)
26909 {
26910 struct domain *d;
26911
26912 AST_LIST_LOCK(&domain_list);
26913 while ((d = AST_LIST_REMOVE_HEAD(&domain_list, list)))
26914 ast_free(d);
26915 AST_LIST_UNLOCK(&domain_list);
26916 }
26917
26918
26919
26920
26921
26922
26923
26924
26925
26926 static void destroy_realm_authentication(void *obj)
26927 {
26928 struct sip_auth_container *credentials = obj;
26929 struct sip_auth *auth;
26930
26931 while ((auth = AST_LIST_REMOVE_HEAD(&credentials->list, node))) {
26932 ast_free(auth);
26933 }
26934 }
26935
26936
26937
26938
26939
26940
26941
26942
26943
26944
26945
26946 static void add_realm_authentication(struct sip_auth_container **credentials, const char *configuration, int lineno)
26947 {
26948 char *authcopy;
26949 char *username=NULL, *realm=NULL, *secret=NULL, *md5secret=NULL;
26950 struct sip_auth *auth;
26951
26952 if (ast_strlen_zero(configuration)) {
26953
26954 return;
26955 }
26956
26957 ast_debug(1, "Auth config :: %s\n", configuration);
26958
26959 authcopy = ast_strdupa(configuration);
26960 username = authcopy;
26961
26962
26963 realm = strrchr(username, '@');
26964 if (realm)
26965 *realm++ = '\0';
26966 if (ast_strlen_zero(username) || ast_strlen_zero(realm)) {
26967 ast_log(LOG_WARNING, "Format for authentication entry is user[:secret]@realm at line %d\n", lineno);
26968 return;
26969 }
26970
26971
26972 if ((secret = strchr(username, ':'))) {
26973 *secret++ = '\0';
26974 } else if ((md5secret = strchr(username, '#'))) {
26975 *md5secret++ = '\0';
26976 }
26977
26978
26979 if (!*credentials) {
26980 *credentials = ao2_t_alloc(sizeof(**credentials), destroy_realm_authentication,
26981 "Create realm auth container.");
26982 if (!*credentials) {
26983
26984 return;
26985 }
26986 }
26987
26988
26989 auth = ast_calloc(1, sizeof(*auth));
26990 if (!auth) {
26991 return;
26992 }
26993 ast_copy_string(auth->realm, realm, sizeof(auth->realm));
26994 ast_copy_string(auth->username, username, sizeof(auth->username));
26995 if (secret)
26996 ast_copy_string(auth->secret, secret, sizeof(auth->secret));
26997 if (md5secret)
26998 ast_copy_string(auth->md5secret, md5secret, sizeof(auth->md5secret));
26999
27000
27001 AST_LIST_INSERT_TAIL(&(*credentials)->list, auth, node);
27002
27003 ast_verb(3, "Added authentication for realm %s\n", realm);
27004 }
27005
27006
27007
27008
27009
27010
27011
27012
27013
27014
27015 static struct sip_auth *find_realm_authentication(struct sip_auth_container *credentials, const char *realm)
27016 {
27017 struct sip_auth *auth;
27018
27019 if (credentials) {
27020 AST_LIST_TRAVERSE(&credentials->list, auth, node) {
27021 if (!strcasecmp(auth->realm, realm)) {
27022 break;
27023 }
27024 }
27025 } else {
27026 auth = NULL;
27027 }
27028
27029 return auth;
27030 }
27031
27032
27033
27034
27035 static struct ast_variable *add_var(const char *buf, struct ast_variable *list)
27036 {
27037 struct ast_variable *tmpvar = NULL;
27038 char *varname = ast_strdupa(buf), *varval = NULL;
27039
27040 if ((varval = strchr(varname, '='))) {
27041 *varval++ = '\0';
27042 if ((tmpvar = ast_variable_new(varname, varval, ""))) {
27043 tmpvar->next = list;
27044 list = tmpvar;
27045 }
27046 }
27047 return list;
27048 }
27049
27050
27051 static void set_peer_defaults(struct sip_peer *peer)
27052 {
27053 if (peer->expire == 0) {
27054
27055
27056
27057 peer->expire = -1;
27058 peer->pokeexpire = -1;
27059 set_socket_transport(&peer->socket, SIP_TRANSPORT_UDP);
27060 }
27061 peer->type = SIP_TYPE_PEER;
27062 ast_copy_flags(&peer->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
27063 ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
27064 ast_copy_flags(&peer->flags[2], &global_flags[2], SIP_PAGE3_FLAGS_TO_COPY);
27065 ast_string_field_set(peer, context, sip_cfg.default_context);
27066 ast_string_field_set(peer, subscribecontext, sip_cfg.default_subscribecontext);
27067 ast_string_field_set(peer, language, default_language);
27068 ast_string_field_set(peer, mohinterpret, default_mohinterpret);
27069 ast_string_field_set(peer, mohsuggest, default_mohsuggest);
27070 ast_string_field_set(peer, engine, default_engine);
27071 ast_sockaddr_setnull(&peer->addr);
27072 ast_sockaddr_setnull(&peer->defaddr);
27073 peer->capability = sip_cfg.capability;
27074 peer->maxcallbitrate = default_maxcallbitrate;
27075 peer->rtptimeout = global_rtptimeout;
27076 peer->rtpholdtimeout = global_rtpholdtimeout;
27077 peer->rtpkeepalive = global_rtpkeepalive;
27078 peer->allowtransfer = sip_cfg.allowtransfer;
27079 peer->autoframing = global_autoframing;
27080 peer->t38_maxdatagram = global_t38_maxdatagram;
27081 peer->qualifyfreq = global_qualifyfreq;
27082 if (global_callcounter)
27083 peer->call_limit=INT_MAX;
27084 ast_string_field_set(peer, vmexten, default_vmexten);
27085 ast_string_field_set(peer, secret, "");
27086 ast_string_field_set(peer, remotesecret, "");
27087 ast_string_field_set(peer, md5secret, "");
27088 ast_string_field_set(peer, cid_num, "");
27089 ast_string_field_set(peer, cid_name, "");
27090 ast_string_field_set(peer, cid_tag, "");
27091 ast_string_field_set(peer, fromdomain, "");
27092 ast_string_field_set(peer, fromuser, "");
27093 ast_string_field_set(peer, regexten, "");
27094 peer->callgroup = 0;
27095 peer->pickupgroup = 0;
27096 peer->maxms = default_qualify;
27097 peer->prefs = default_prefs;
27098 peer->stimer.st_mode_oper = global_st_mode;
27099 peer->stimer.st_ref = global_st_refresher;
27100 peer->stimer.st_min_se = global_min_se;
27101 peer->stimer.st_max_se = global_max_se;
27102 peer->timer_t1 = global_t1;
27103 peer->timer_b = global_timer_b;
27104 clear_peer_mailboxes(peer);
27105 peer->disallowed_methods = sip_cfg.disallowed_methods;
27106 peer->transports = default_transports;
27107 peer->default_outbound_transport = default_primary_transport;
27108 }
27109
27110
27111 static struct sip_peer *temp_peer(const char *name)
27112 {
27113 struct sip_peer *peer;
27114
27115 if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct")))
27116 return NULL;
27117
27118 if (ast_string_field_init(peer, 512)) {
27119 ao2_t_ref(peer, -1, "failed to string_field_init, drop peer");
27120 return NULL;
27121 }
27122
27123 if (!(peer->cc_params = ast_cc_config_params_init())) {
27124 ao2_t_ref(peer, -1, "failed to allocate cc_params for peer");
27125 return NULL;
27126 }
27127
27128 ast_atomic_fetchadd_int(&apeerobjs, 1);
27129 set_peer_defaults(peer);
27130
27131 ast_copy_string(peer->name, name, sizeof(peer->name));
27132
27133 peer->selfdestruct = TRUE;
27134 peer->host_dynamic = TRUE;
27135 peer->prefs = default_prefs;
27136 reg_source_db(peer);
27137
27138 return peer;
27139 }
27140
27141
27142 static void add_peer_mailboxes(struct sip_peer *peer, const char *value)
27143 {
27144 char *next, *mbox, *context;
27145
27146 next = ast_strdupa(value);
27147
27148 while ((mbox = context = strsep(&next, ","))) {
27149 struct sip_mailbox *mailbox;
27150 int duplicate = 0;
27151
27152 mbox = ast_strip(mbox);
27153 strsep(&context, "@");
27154
27155 if (ast_strlen_zero(mbox)) {
27156 continue;
27157 }
27158
27159
27160 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
27161 if (!strcmp(mailbox->mailbox, mbox) && !strcmp(S_OR(mailbox->context, ""), S_OR(context, ""))) {
27162 duplicate = 1;
27163 break;
27164 }
27165 }
27166 if (duplicate) {
27167 continue;
27168 }
27169
27170 if (!(mailbox = ast_calloc(1, sizeof(*mailbox) + strlen(mbox) + strlen(S_OR(context, ""))))) {
27171 continue;
27172 }
27173
27174 if (!ast_strlen_zero(context)) {
27175 mailbox->context = mailbox->mailbox + strlen(mbox) + 1;
27176 strcpy(mailbox->context, context);
27177 }
27178 strcpy(mailbox->mailbox, mbox);
27179
27180 AST_LIST_INSERT_TAIL(&peer->mailboxes, mailbox, entry);
27181 }
27182 }
27183
27184
27185 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only)
27186 {
27187 struct sip_peer *peer = NULL;
27188 struct ast_ha *oldha = NULL;
27189 struct ast_ha *olddirectmediaha = NULL;
27190 int found = 0;
27191 int firstpass = 1;
27192 uint16_t port = 0;
27193 int format = 0;
27194 int timerb_set = 0, timert1_set = 0;
27195 time_t regseconds = 0;
27196 struct ast_flags peerflags[3] = {{(0)}};
27197 struct ast_flags mask[3] = {{(0)}};
27198 char callback[256] = "";
27199 struct sip_peer tmp_peer;
27200 const char *srvlookup = NULL;
27201 static int deprecation_warning = 1;
27202 int alt_fullcontact = alt ? 1 : 0, headercount = 0;
27203 struct ast_str *fullcontact = ast_str_alloca(512);
27204
27205 if (!realtime || ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
27206
27207
27208
27209
27210
27211 ast_copy_string(tmp_peer.name, name, sizeof(tmp_peer.name));
27212 peer = ao2_t_find(peers, &tmp_peer, OBJ_POINTER | OBJ_UNLINK, "find and unlink peer from peers table");
27213 }
27214
27215 if (peer) {
27216
27217 found++;
27218
27219
27220 if (!ast_sockaddr_isnull(&peer->addr)) {
27221 ao2_t_unlink(peers_by_ip, peer, "ao2_unlink peer from peers_by_ip table");
27222 }
27223 if (!(peer->the_mark))
27224 firstpass = 0;
27225 } else {
27226 if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct")))
27227 return NULL;
27228
27229 if (ast_string_field_init(peer, 512)) {
27230 ao2_t_ref(peer, -1, "failed to string_field_init, drop peer");
27231 return NULL;
27232 }
27233
27234 if (!(peer->cc_params = ast_cc_config_params_init())) {
27235 ao2_t_ref(peer, -1, "failed to allocate cc_params for peer");
27236 return NULL;
27237 }
27238
27239 if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
27240 ast_atomic_fetchadd_int(&rpeerobjs, 1);
27241 ast_debug(3, "-REALTIME- peer built. Name: %s. Peer objects: %d\n", name, rpeerobjs);
27242 } else
27243 ast_atomic_fetchadd_int(&speerobjs, 1);
27244 }
27245
27246
27247 if (firstpass) {
27248 peer->lastmsgssent = -1;
27249 oldha = peer->ha;
27250 peer->ha = NULL;
27251 olddirectmediaha = peer->directmediaha;
27252 peer->directmediaha = NULL;
27253 set_peer_defaults(peer);
27254 peer->type = 0;
27255 }
27256
27257
27258 ast_copy_string(peer->name, name, sizeof(peer->name));
27259
27260
27261 if (peer->chanvars) {
27262 ast_variables_destroy(peer->chanvars);
27263 peer->chanvars = NULL;
27264
27265 }
27266
27267 if (found)
27268 peer->portinuri = 0;
27269
27270
27271 ao2_lock(peer);
27272 if (peer->auth) {
27273 ao2_t_ref(peer->auth, -1, "Removing old peer authentication");
27274 peer->auth = NULL;
27275 }
27276 ao2_unlock(peer);
27277
27278
27279 peer->default_outbound_transport = 0;
27280 peer->transports = 0;
27281
27282 if (!devstate_only) {
27283 struct sip_mailbox *mailbox;
27284 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
27285 mailbox->delme = 1;
27286 }
27287 }
27288
27289 for (; v || ((v = alt) && !(alt=NULL)); v = v->next) {
27290 if (!devstate_only) {
27291 if (handle_common_options(&peerflags[0], &mask[0], v)) {
27292 continue;
27293 }
27294 if (handle_t38_options(&peerflags[0], &mask[0], v, &peer->t38_maxdatagram)) {
27295 continue;
27296 }
27297 if (!strcasecmp(v->name, "transport")) {
27298 char *val = ast_strdupa(v->value);
27299 char *trans;
27300
27301 peer->transports = peer->default_outbound_transport = 0;
27302 while ((trans = strsep(&val, ","))) {
27303 trans = ast_skip_blanks(trans);
27304
27305 if (!strncasecmp(trans, "udp", 3)) {
27306 peer->transports |= SIP_TRANSPORT_UDP;
27307 } else if (sip_cfg.tcp_enabled && !strncasecmp(trans, "tcp", 3)) {
27308 peer->transports |= SIP_TRANSPORT_TCP;
27309 } else if (default_tls_cfg.enabled && !strncasecmp(trans, "tls", 3)) {
27310 peer->transports |= SIP_TRANSPORT_TLS;
27311 } else if (!strncasecmp(trans, "tcp", 3) || !strncasecmp(trans, "tls", 3)) {
27312 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);
27313 } else {
27314 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);
27315 }
27316
27317 if (!peer->default_outbound_transport) {
27318 peer->default_outbound_transport = peer->transports;
27319 }
27320 }
27321 } else if (realtime && !strcasecmp(v->name, "regseconds")) {
27322 ast_get_time_t(v->value, ®seconds, 0, NULL);
27323 } else if (realtime && !strcasecmp(v->name, "name")) {
27324 ast_copy_string(peer->name, v->value, sizeof(peer->name));
27325 } else if (realtime && !strcasecmp(v->name, "useragent")) {
27326 ast_string_field_set(peer, useragent, v->value);
27327 } else if (!strcasecmp(v->name, "type")) {
27328 if (!strcasecmp(v->value, "peer")) {
27329 peer->type |= SIP_TYPE_PEER;
27330 } else if (!strcasecmp(v->value, "user")) {
27331 peer->type |= SIP_TYPE_USER;
27332 } else if (!strcasecmp(v->value, "friend")) {
27333 peer->type = SIP_TYPE_USER | SIP_TYPE_PEER;
27334 }
27335 } else if (!strcasecmp(v->name, "remotesecret")) {
27336 ast_string_field_set(peer, remotesecret, v->value);
27337 } else if (!strcasecmp(v->name, "secret")) {
27338 ast_string_field_set(peer, secret, v->value);
27339 } else if (!strcasecmp(v->name, "md5secret")) {
27340 ast_string_field_set(peer, md5secret, v->value);
27341 } else if (!strcasecmp(v->name, "auth")) {
27342 add_realm_authentication(&peer->auth, v->value, v->lineno);
27343 } else if (!strcasecmp(v->name, "callerid")) {
27344 char cid_name[80] = { '\0' }, cid_num[80] = { '\0' };
27345
27346 ast_callerid_split(v->value, cid_name, sizeof(cid_name), cid_num, sizeof(cid_num));
27347 ast_string_field_set(peer, cid_name, cid_name);
27348 ast_string_field_set(peer, cid_num, cid_num);
27349 } else if (!strcasecmp(v->name, "mwi_from")) {
27350 ast_string_field_set(peer, mwi_from, v->value);
27351 } else if (!strcasecmp(v->name, "fullname")) {
27352 ast_string_field_set(peer, cid_name, v->value);
27353 } else if (!strcasecmp(v->name, "trunkname")) {
27354
27355 ast_string_field_set(peer, cid_name, "");
27356 } else if (!strcasecmp(v->name, "cid_number")) {
27357 ast_string_field_set(peer, cid_num, v->value);
27358 } else if (!strcasecmp(v->name, "cid_tag")) {
27359 ast_string_field_set(peer, cid_tag, v->value);
27360 } else if (!strcasecmp(v->name, "context")) {
27361 ast_string_field_set(peer, context, v->value);
27362 ast_set_flag(&peer->flags[1], SIP_PAGE2_HAVEPEERCONTEXT);
27363 } else if (!strcasecmp(v->name, "subscribecontext")) {
27364 ast_string_field_set(peer, subscribecontext, v->value);
27365 } else if (!strcasecmp(v->name, "fromdomain")) {
27366 char *fromdomainport;
27367 ast_string_field_set(peer, fromdomain, v->value);
27368 if ((fromdomainport = strchr(peer->fromdomain, ':'))) {
27369 *fromdomainport++ = '\0';
27370 if (!(peer->fromdomainport = port_str2int(fromdomainport, 0))) {
27371 ast_log(LOG_NOTICE, "'%s' is not a valid port number for fromdomain.\n",fromdomainport);
27372 }
27373 } else {
27374 peer->fromdomainport = STANDARD_SIP_PORT;
27375 }
27376 } else if (!strcasecmp(v->name, "usereqphone")) {
27377 ast_set2_flag(&peer->flags[0], ast_true(v->value), SIP_USEREQPHONE);
27378 } else if (!strcasecmp(v->name, "fromuser")) {
27379 ast_string_field_set(peer, fromuser, v->value);
27380 } else if (!strcasecmp(v->name, "outboundproxy")) {
27381 char *tok, *proxyname;
27382
27383 if (ast_strlen_zero(v->value)) {
27384 ast_log(LOG_WARNING, "no value given for outbound proxy on line %d of sip.conf.", v->lineno);
27385 continue;
27386 }
27387
27388 peer->outboundproxy =
27389 ao2_alloc(sizeof(*peer->outboundproxy), NULL);
27390
27391 tok = ast_skip_blanks(strtok(ast_strdupa(v->value), ","));
27392
27393 sip_parse_host(tok, v->lineno, &proxyname,
27394 &peer->outboundproxy->port,
27395 &peer->outboundproxy->transport);
27396
27397 tok = ast_skip_blanks(strtok(ast_strdupa(v->value), ","));
27398
27399 if ((tok = strtok(NULL, ","))) {
27400 peer->outboundproxy->force = !strncasecmp(ast_skip_blanks(tok), "force", 5);
27401 } else {
27402 peer->outboundproxy->force = FALSE;
27403 }
27404
27405 if (ast_strlen_zero(proxyname)) {
27406 ast_log(LOG_WARNING, "you must specify a name for the outboundproxy on line %d of sip.conf.", v->lineno);
27407 sip_cfg.outboundproxy.name[0] = '\0';
27408 continue;
27409 }
27410
27411 ast_copy_string(peer->outboundproxy->name, proxyname, sizeof(peer->outboundproxy->name));
27412
27413 proxy_update(peer->outboundproxy);
27414 } else if (!strcasecmp(v->name, "host")) {
27415 if (!strcasecmp(v->value, "dynamic")) {
27416
27417 if (!found || !peer->host_dynamic) {
27418
27419
27420 ast_sockaddr_setnull(&peer->addr);
27421 }
27422 peer->host_dynamic = TRUE;
27423 } else {
27424
27425 AST_SCHED_DEL_UNREF(sched, peer->expire,
27426 unref_peer(peer, "removing register expire ref"));
27427 peer->host_dynamic = FALSE;
27428 srvlookup = v->value;
27429 }
27430 } else if (!strcasecmp(v->name, "defaultip")) {
27431 if (!ast_strlen_zero(v->value) && ast_get_ip(&peer->defaddr, v->value)) {
27432 unref_peer(peer, "unref_peer: from build_peer defaultip");
27433 return NULL;
27434 }
27435 } else if (!strcasecmp(v->name, "permit") || !strcasecmp(v->name, "deny")) {
27436 int ha_error = 0;
27437 if (!ast_strlen_zero(v->value)) {
27438 peer->ha = ast_append_ha(v->name, v->value, peer->ha, &ha_error);
27439 }
27440 if (ha_error) {
27441 ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
27442 }
27443 } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny")) {
27444 int ha_error = 0;
27445 if (!ast_strlen_zero(v->value)) {
27446 peer->contactha = ast_append_ha(v->name + 7, v->value, peer->contactha, &ha_error);
27447 }
27448 if (ha_error) {
27449 ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
27450 }
27451 } else if (!strcasecmp(v->name, "directmediapermit") || !strcasecmp(v->name, "directmediadeny")) {
27452 int ha_error = 0;
27453 peer->directmediaha = ast_append_ha(v->name + 11, v->value, peer->directmediaha, &ha_error);
27454 if (ha_error) {
27455 ast_log(LOG_ERROR, "Bad directmedia ACL entry in configuration line %d : %s\n", v->lineno, v->value);
27456 }
27457 } else if (!strcasecmp(v->name, "port")) {
27458 peer->portinuri = 1;
27459 if (!(port = port_str2int(v->value, 0))) {
27460 if (realtime) {
27461
27462 peer->portinuri = 0;
27463 } else {
27464 ast_log(LOG_WARNING, "Invalid peer port configuration at line %d : %s\n", v->lineno, v->value);
27465 }
27466 }
27467 } else if (!strcasecmp(v->name, "callingpres")) {
27468 peer->callingpres = ast_parse_caller_presentation(v->value);
27469 if (peer->callingpres == -1) {
27470 peer->callingpres = atoi(v->value);
27471 }
27472 } else if (!strcasecmp(v->name, "username") || !strcmp(v->name, "defaultuser")) {
27473 ast_string_field_set(peer, username, v->value);
27474 if (!strcasecmp(v->name, "username")) {
27475 if (deprecation_warning) {
27476 ast_log(LOG_NOTICE, "The 'username' field for sip peers has been deprecated in favor of the term 'defaultuser'\n");
27477 deprecation_warning = 0;
27478 }
27479 peer->deprecated_username = 1;
27480 }
27481 } else if (!strcasecmp(v->name, "language")) {
27482 ast_string_field_set(peer, language, v->value);
27483 } else if (!strcasecmp(v->name, "regexten")) {
27484 ast_string_field_set(peer, regexten, v->value);
27485 } else if (!strcasecmp(v->name, "callbackextension")) {
27486 ast_copy_string(callback, v->value, sizeof(callback));
27487 } else if (!strcasecmp(v->name, "amaflags")) {
27488 format = ast_cdr_amaflags2int(v->value);
27489 if (format < 0) {
27490 ast_log(LOG_WARNING, "Invalid AMA Flags for peer: %s at line %d\n", v->value, v->lineno);
27491 } else {
27492 peer->amaflags = format;
27493 }
27494 } else if (!strcasecmp(v->name, "maxforwards")) {
27495 if (sscanf(v->value, "%30d", &peer->maxforwards) != 1
27496 || peer->maxforwards < 1 || 255 < peer->maxforwards) {
27497 ast_log(LOG_WARNING, "'%s' is not a valid maxforwards value at line %d. Using default.\n", v->value, v->lineno);
27498 peer->maxforwards = sip_cfg.default_max_forwards;
27499 }
27500 } else if (!strcasecmp(v->name, "accountcode")) {
27501 ast_string_field_set(peer, accountcode, v->value);
27502 } else if (!strcasecmp(v->name, "mohinterpret")) {
27503 ast_string_field_set(peer, mohinterpret, v->value);
27504 } else if (!strcasecmp(v->name, "mohsuggest")) {
27505 ast_string_field_set(peer, mohsuggest, v->value);
27506 } else if (!strcasecmp(v->name, "parkinglot")) {
27507 ast_string_field_set(peer, parkinglot, v->value);
27508 } else if (!strcasecmp(v->name, "rtp_engine")) {
27509 ast_string_field_set(peer, engine, v->value);
27510 } else if (!strcasecmp(v->name, "mailbox")) {
27511 add_peer_mailboxes(peer, v->value);
27512 } else if (!strcasecmp(v->name, "hasvoicemail")) {
27513
27514
27515 if (ast_true(v->value) && AST_LIST_EMPTY(&peer->mailboxes)) {
27516 add_peer_mailboxes(peer, name);
27517 }
27518 } else if (!strcasecmp(v->name, "subscribemwi")) {
27519 ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_SUBSCRIBEMWIONLY);
27520 } else if (!strcasecmp(v->name, "vmexten")) {
27521 ast_string_field_set(peer, vmexten, v->value);
27522 } else if (!strcasecmp(v->name, "callgroup")) {
27523 peer->callgroup = ast_get_group(v->value);
27524 } else if (!strcasecmp(v->name, "allowtransfer")) {
27525 peer->allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
27526 } else if (!strcasecmp(v->name, "pickupgroup")) {
27527 peer->pickupgroup = ast_get_group(v->value);
27528 } else if (!strcasecmp(v->name, "allow")) {
27529 int error = ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, TRUE);
27530 if (error) {
27531 ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
27532 }
27533 } else if (!strcasecmp(v->name, "disallow")) {
27534 int error = ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, FALSE);
27535 if (error) {
27536 ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
27537 }
27538 } else if (!strcasecmp(v->name, "preferred_codec_only")) {
27539 ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_PREFERRED_CODEC);
27540 } else if (!strcasecmp(v->name, "autoframing")) {
27541 peer->autoframing = ast_true(v->value);
27542 } else if (!strcasecmp(v->name, "rtptimeout")) {
27543 if ((sscanf(v->value, "%30d", &peer->rtptimeout) != 1) || (peer->rtptimeout < 0)) {
27544 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
27545 peer->rtptimeout = global_rtptimeout;
27546 }
27547 } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
27548 if ((sscanf(v->value, "%30d", &peer->rtpholdtimeout) != 1) || (peer->rtpholdtimeout < 0)) {
27549 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
27550 peer->rtpholdtimeout = global_rtpholdtimeout;
27551 }
27552 } else if (!strcasecmp(v->name, "rtpkeepalive")) {
27553 if ((sscanf(v->value, "%30d", &peer->rtpkeepalive) != 1) || (peer->rtpkeepalive < 0)) {
27554 ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d. Using default.\n", v->value, v->lineno);
27555 peer->rtpkeepalive = global_rtpkeepalive;
27556 }
27557 } else if (!strcasecmp(v->name, "timert1")) {
27558 if ((sscanf(v->value, "%30d", &peer->timer_t1) != 1) || (peer->timer_t1 < 200) || (peer->timer_t1 < global_t1min)) {
27559 ast_log(LOG_WARNING, "'%s' is not a valid T1 time at line %d. Using default.\n", v->value, v->lineno);
27560 peer->timer_t1 = global_t1min;
27561 }
27562 timert1_set = 1;
27563 } else if (!strcasecmp(v->name, "timerb")) {
27564 if ((sscanf(v->value, "%30d", &peer->timer_b) != 1) || (peer->timer_b < 200)) {
27565 ast_log(LOG_WARNING, "'%s' is not a valid Timer B time at line %d. Using default.\n", v->value, v->lineno);
27566 peer->timer_b = global_timer_b;
27567 }
27568 timerb_set = 1;
27569 } else if (!strcasecmp(v->name, "setvar")) {
27570 peer->chanvars = add_var(v->value, peer->chanvars);
27571 } else if (!strcasecmp(v->name, "header")) {
27572 char tmp[4096];
27573 snprintf(tmp, sizeof(tmp), "__SIPADDHEADERpre%2d=%s", ++headercount, v->value);
27574 peer->chanvars = add_var(tmp, peer->chanvars);
27575 } else if (!strcasecmp(v->name, "qualifyfreq")) {
27576 int i;
27577 if (sscanf(v->value, "%30d", &i) == 1) {
27578 peer->qualifyfreq = i * 1000;
27579 } else {
27580 ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
27581 peer->qualifyfreq = global_qualifyfreq;
27582 }
27583 } else if (!strcasecmp(v->name, "maxcallbitrate")) {
27584 peer->maxcallbitrate = atoi(v->value);
27585 if (peer->maxcallbitrate < 0) {
27586 peer->maxcallbitrate = default_maxcallbitrate;
27587 }
27588 } else if (!strcasecmp(v->name, "session-timers")) {
27589 int i = (int) str2stmode(v->value);
27590 if (i < 0) {
27591 ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
27592 peer->stimer.st_mode_oper = global_st_mode;
27593 } else {
27594 peer->stimer.st_mode_oper = i;
27595 }
27596 } else if (!strcasecmp(v->name, "session-expires")) {
27597 if (sscanf(v->value, "%30d", &peer->stimer.st_max_se) != 1) {
27598 ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
27599 peer->stimer.st_max_se = global_max_se;
27600 }
27601 } else if (!strcasecmp(v->name, "session-minse")) {
27602 if (sscanf(v->value, "%30d", &peer->stimer.st_min_se) != 1) {
27603 ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
27604 peer->stimer.st_min_se = global_min_se;
27605 }
27606 if (peer->stimer.st_min_se < 90) {
27607 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);
27608 peer->stimer.st_min_se = global_min_se;
27609 }
27610 } else if (!strcasecmp(v->name, "session-refresher")) {
27611 int i = (int) str2strefresher(v->value);
27612 if (i < 0) {
27613 ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
27614 peer->stimer.st_ref = global_st_refresher;
27615 } else {
27616 peer->stimer.st_ref = i;
27617 }
27618 } else if (!strcasecmp(v->name, "disallowed_methods")) {
27619 char *disallow = ast_strdupa(v->value);
27620 mark_parsed_methods(&peer->disallowed_methods, disallow);
27621 } else if (!strcasecmp(v->name, "unsolicited_mailbox")) {
27622 ast_string_field_set(peer, unsolicited_mailbox, v->value);
27623 } else if (!strcasecmp(v->name, "use_q850_reason")) {
27624 ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_Q850_REASON);
27625 } else if (!strcasecmp(v->name, "encryption")) {
27626 ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_USE_SRTP);
27627 } else if (!strcasecmp(v->name, "snom_aoc_enabled")) {
27628 ast_set2_flag(&peer->flags[2], ast_true(v->value), SIP_PAGE3_SNOM_AOC);
27629 }
27630 }
27631
27632
27633 if (realtime && !strcasecmp(v->name, "lastms")) {
27634 sscanf(v->value, "%30d", &peer->lastms);
27635 } else if (realtime && !strcasecmp(v->name, "ipaddr") && !ast_strlen_zero(v->value) ) {
27636 ast_sockaddr_parse(&peer->addr, v->value, PARSE_PORT_FORBID);
27637 } else if (realtime && !strcasecmp(v->name, "fullcontact")) {
27638 if (alt_fullcontact && !alt) {
27639
27640
27641
27642
27643
27644 alt_fullcontact = 0;
27645 ast_str_reset(fullcontact);
27646 }
27647
27648 if (fullcontact->used > 0) {
27649 ast_str_append(&fullcontact, 0, ";%s", v->value);
27650 } else {
27651 ast_str_set(&fullcontact, 0, "%s", v->value);
27652 }
27653 } else if (!strcasecmp(v->name, "qualify")) {
27654 if (!strcasecmp(v->value, "no")) {
27655 peer->maxms = 0;
27656 } else if (!strcasecmp(v->value, "yes")) {
27657 peer->maxms = default_qualify ? default_qualify : DEFAULT_MAXMS;
27658 } else if (sscanf(v->value, "%30d", &peer->maxms) != 1) {
27659 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);
27660 peer->maxms = 0;
27661 }
27662 if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && peer->maxms > 0) {
27663
27664
27665
27666
27667 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);
27668 peer->maxms = 0;
27669 }
27670 } else if (!strcasecmp(v->name, "callcounter")) {
27671 peer->call_limit = ast_true(v->value) ? INT_MAX : 0;
27672 } else if (!strcasecmp(v->name, "call-limit")) {
27673 peer->call_limit = atoi(v->value);
27674 if (peer->call_limit < 0) {
27675 peer->call_limit = 0;
27676 }
27677 } else if (!strcasecmp(v->name, "busylevel")) {
27678 peer->busy_level = atoi(v->value);
27679 if (peer->busy_level < 0) {
27680 peer->busy_level = 0;
27681 }
27682 } else if (ast_cc_is_config_param(v->name)) {
27683 ast_cc_set_param(peer->cc_params, v->name, v->value);
27684 }
27685 }
27686
27687 if (!devstate_only) {
27688 struct sip_mailbox *mailbox;
27689 AST_LIST_TRAVERSE_SAFE_BEGIN(&peer->mailboxes, mailbox, entry) {
27690 if (mailbox->delme) {
27691 AST_LIST_REMOVE_CURRENT(entry);
27692 destroy_mailbox(mailbox);
27693 }
27694 }
27695 AST_LIST_TRAVERSE_SAFE_END;
27696 }
27697
27698 if (!can_parse_xml && (ast_get_cc_agent_policy(peer->cc_params) == AST_CC_AGENT_NATIVE)) {
27699 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);
27700 ast_set_cc_agent_policy(peer->cc_params, AST_CC_AGENT_NEVER);
27701 }
27702
27703
27704
27705 if (peer->timer_b < peer->timer_t1 * 64) {
27706 if (timerb_set && timert1_set) {
27707 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);
27708 } else if (timerb_set) {
27709 if ((peer->timer_t1 = peer->timer_b / 64) < global_t1min) {
27710 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);
27711 peer->timer_t1 = global_t1min;
27712 peer->timer_b = peer->timer_t1 * 64;
27713 }
27714 peer->timer_t1 = peer->timer_b / 64;
27715 } else {
27716 peer->timer_b = peer->timer_t1 * 64;
27717 }
27718 }
27719
27720 if (!peer->default_outbound_transport) {
27721
27722 peer->transports = default_transports;
27723
27724 peer->default_outbound_transport = default_primary_transport;
27725 }
27726
27727
27728
27729
27730
27731 if (((peer->socket.type != peer->default_outbound_transport) && (peer->expire == -1)) ||
27732 !(peer->socket.type & peer->transports) || !(peer->socket.type)) {
27733
27734 set_socket_transport(&peer->socket, peer->default_outbound_transport);
27735 }
27736
27737 if (ast_str_strlen(fullcontact)) {
27738 ast_string_field_set(peer, fullcontact, ast_str_buffer(fullcontact));
27739 peer->rt_fromcontact = TRUE;
27740
27741
27742
27743
27744
27745
27746
27747
27748 if (!ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) || ast_sockaddr_isnull(&peer->addr)) {
27749 __set_address_from_contact(fullcontact->str, &peer->addr, 0);
27750 }
27751 }
27752
27753 if (srvlookup && peer->dnsmgr == NULL) {
27754 char transport[MAXHOSTNAMELEN];
27755 char _srvlookup[MAXHOSTNAMELEN];
27756 char *params;
27757
27758 ast_copy_string(_srvlookup, srvlookup, sizeof(_srvlookup));
27759 if ((params = strchr(_srvlookup, ';'))) {
27760 *params++ = '\0';
27761 }
27762
27763 snprintf(transport, sizeof(transport), "_%s._%s", get_srv_service(peer->socket.type), get_srv_protocol(peer->socket.type));
27764
27765 peer->addr.ss.ss_family = get_address_family_filter(&bindaddr);
27766 if (ast_dnsmgr_lookup_cb(_srvlookup, &peer->addr, &peer->dnsmgr, sip_cfg.srvlookup && !peer->portinuri ? transport : NULL,
27767 on_dns_update_peer, ref_peer(peer, "Store peer on dnsmgr"))) {
27768 ast_log(LOG_ERROR, "srvlookup failed for host: %s, on peer %s, removing peer\n", _srvlookup, peer->name);
27769 unref_peer(peer, "dnsmgr lookup failed, getting rid of peer dnsmgr ref");
27770 unref_peer(peer, "getting rid of a peer pointer");
27771 return NULL;
27772 }
27773 if (!peer->dnsmgr) {
27774
27775 unref_peer(peer, "dnsmgr disabled, unref peer");
27776 }
27777
27778 ast_string_field_set(peer, tohost, srvlookup);
27779
27780 if (global_dynamic_exclude_static) {
27781 int ha_error = 0;
27782 sip_cfg.contact_ha = ast_append_ha("deny", ast_sockaddr_stringify_addr(&peer->addr),
27783 sip_cfg.contact_ha, &ha_error);
27784 if (ha_error) {
27785 ast_log(LOG_ERROR, "Bad or unresolved host/IP entry in configuration for peer %s, cannot add to contact ACL\n", peer->name);
27786 }
27787 }
27788 } else if (peer->dnsmgr && !peer->host_dynamic) {
27789
27790 ast_dnsmgr_refresh(peer->dnsmgr);
27791 }
27792
27793 if (port && !realtime && peer->host_dynamic) {
27794 ast_sockaddr_set_port(&peer->defaddr, port);
27795 } else if (port) {
27796 ast_sockaddr_set_port(&peer->addr, port);
27797 }
27798
27799 if (ast_sockaddr_port(&peer->addr) == 0) {
27800 ast_sockaddr_set_port(&peer->addr,
27801 (peer->socket.type & SIP_TRANSPORT_TLS) ?
27802 STANDARD_TLS_PORT : STANDARD_SIP_PORT);
27803 }
27804 if (ast_sockaddr_port(&peer->defaddr) == 0) {
27805 ast_sockaddr_set_port(&peer->defaddr,
27806 (peer->socket.type & SIP_TRANSPORT_TLS) ?
27807 STANDARD_TLS_PORT : STANDARD_SIP_PORT);
27808 }
27809 if (!peer->socket.port) {
27810 peer->socket.port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
27811 }
27812
27813 if (!sip_cfg.ignore_regexpire && peer->host_dynamic && realtime) {
27814 time_t nowtime = time(NULL);
27815
27816 if ((nowtime - regseconds) > 0) {
27817 destroy_association(peer);
27818 memset(&peer->addr, 0, sizeof(peer->addr));
27819 peer->lastms = -1;
27820 ast_debug(1, "Bah, we're expired (%d/%d/%d)!\n", (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
27821 }
27822 }
27823
27824
27825 if (!devstate_only && realtime && peer->lastms > 0) {
27826 ref_peer(peer, "schedule qualify");
27827 sip_poke_peer(peer, 0);
27828 }
27829
27830 ast_copy_flags(&peer->flags[0], &peerflags[0], mask[0].flags);
27831 ast_copy_flags(&peer->flags[1], &peerflags[1], mask[1].flags);
27832 ast_copy_flags(&peer->flags[2], &peerflags[2], mask[2].flags);
27833 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
27834 sip_cfg.allowsubscribe = TRUE;
27835 }
27836
27837 if (peer->host_dynamic && (!peer->is_realtime || !sip_cfg.peer_rtupdate)) {
27838 reg_source_db(peer);
27839 }
27840
27841
27842
27843 if (!devstate_only && !ast_test_flag(&peer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY) &&
27844 !AST_LIST_EMPTY(&peer->mailboxes)) {
27845 add_peer_mwi_subs(peer);
27846
27847
27848
27849 sip_send_mwi_to_peer(peer, 1);
27850 }
27851
27852 peer->the_mark = 0;
27853
27854 ast_free_ha(oldha);
27855 ast_free_ha(olddirectmediaha);
27856 if (!ast_strlen_zero(callback)) {
27857 char *reg_string;
27858 if (asprintf(®_string, "%s?%s:%s@%s/%s", peer->name, peer->username, !ast_strlen_zero(peer->remotesecret) ? peer->remotesecret : peer->secret, peer->tohost, callback) < 0) {
27859 ast_log(LOG_WARNING, "asprintf() failed: %s\n", strerror(errno));
27860 } else if (reg_string) {
27861 sip_register(reg_string, 0);
27862 ast_free(reg_string);
27863 }
27864 }
27865 return peer;
27866 }
27867
27868 static int peer_markall_func(void *device, void *arg, int flags)
27869 {
27870 struct sip_peer *peer = device;
27871 peer->the_mark = 1;
27872 return 0;
27873 }
27874
27875 static void display_nat_warning(const char *cat, int reason, struct ast_flags *flags) {
27876 int global_nat, specific_nat;
27877
27878 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))) {
27879 ast_log(LOG_WARNING, "!!! PLEASE NOTE: Setting 'nat' for a peer/user that differs from the global setting can make\n");
27880 ast_log(LOG_WARNING, "!!! the name of that peer/user discoverable by an attacker. Replies for non-existent peers/users\n");
27881 ast_log(LOG_WARNING, "!!! will be sent to a different port than replies for an existing peer/user. If at all possible,\n");
27882 ast_log(LOG_WARNING, "!!! use the global 'nat' setting and do not set 'nat' per peer/user.\n");
27883 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));
27884 }
27885 }
27886
27887 static void cleanup_all_regs(void)
27888 {
27889
27890
27891 ASTOBJ_CONTAINER_TRAVERSE(®l, 1, do {
27892 ASTOBJ_WRLOCK(iterator);
27893 if (iterator->call) {
27894 ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", iterator->username, iterator->hostname);
27895
27896 dialog_unlink_all(iterator->call);
27897 iterator->call = dialog_unref(iterator->call, "remove iterator->call from registry traversal");
27898 }
27899 if (iterator->expire > -1) {
27900 AST_SCHED_DEL_UNREF(sched, iterator->expire, registry_unref(iterator, "reg ptr unref from reload config"));
27901 }
27902 if (iterator->timeout > -1) {
27903 AST_SCHED_DEL_UNREF(sched, iterator->timeout, registry_unref(iterator, "reg ptr unref from reload config"));
27904 }
27905 if (iterator->dnsmgr) {
27906 ast_dnsmgr_release(iterator->dnsmgr);
27907 iterator->dnsmgr = NULL;
27908 registry_unref(iterator, "reg ptr unref from dnsmgr");
27909 }
27910 ASTOBJ_UNLOCK(iterator);
27911 } while(0));
27912 }
27913
27914
27915
27916
27917
27918
27919
27920 static int reload_config(enum channelreloadreason reason)
27921 {
27922 struct ast_config *cfg, *ucfg;
27923 struct ast_variable *v;
27924 struct sip_peer *peer;
27925 char *cat, *stringp, *context, *oldregcontext;
27926 char newcontexts[AST_MAX_CONTEXT], oldcontexts[AST_MAX_CONTEXT];
27927 struct ast_flags dummy[2];
27928 struct ast_flags config_flags = { reason == CHANNEL_MODULE_LOAD ? 0 : ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) ? 0 : CONFIG_FLAG_FILEUNCHANGED };
27929 int auto_sip_domains = FALSE;
27930 struct ast_sockaddr old_bindaddr = bindaddr;
27931 int registry_count = 0, peer_count = 0, timerb_set = 0, timert1_set = 0;
27932 int subscribe_network_change = 1;
27933 time_t run_start, run_end;
27934 int bindport = 0;
27935
27936 run_start = time(0);
27937 ast_unload_realtime("sipregs");
27938 ast_unload_realtime("sippeers");
27939 cfg = ast_config_load(config, config_flags);
27940
27941
27942 if (!cfg) {
27943 ast_log(LOG_NOTICE, "Unable to load config %s\n", config);
27944 return -1;
27945 } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
27946 ucfg = ast_config_load("users.conf", config_flags);
27947 if (ucfg == CONFIG_STATUS_FILEUNCHANGED) {
27948 return 1;
27949 } else if (ucfg == CONFIG_STATUS_FILEINVALID) {
27950 ast_log(LOG_ERROR, "Contents of users.conf are invalid and cannot be parsed\n");
27951 return 1;
27952 }
27953
27954 ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
27955 if ((cfg = ast_config_load(config, config_flags)) == CONFIG_STATUS_FILEINVALID) {
27956 ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed\n", config);
27957 ast_config_destroy(ucfg);
27958 return 1;
27959 }
27960 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
27961 ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed\n", config);
27962 return 1;
27963 } else {
27964 ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
27965 if ((ucfg = ast_config_load("users.conf", config_flags)) == CONFIG_STATUS_FILEINVALID) {
27966 ast_log(LOG_ERROR, "Contents of users.conf are invalid and cannot be parsed\n");
27967 ast_config_destroy(cfg);
27968 return 1;
27969 }
27970 }
27971
27972 ast_free_ha(sip_cfg.contact_ha);
27973 sip_cfg.contact_ha = NULL;
27974
27975 default_tls_cfg.enabled = FALSE;
27976
27977 if (reason != CHANNEL_MODULE_LOAD) {
27978 ast_debug(4, "--------------- SIP reload started\n");
27979
27980 clear_sip_domains();
27981 ast_mutex_lock(&authl_lock);
27982 if (authl) {
27983 ao2_t_ref(authl, -1, "Removing old global authentication");
27984 authl = NULL;
27985 }
27986 ast_mutex_unlock(&authl_lock);
27987
27988
27989 cleanup_all_regs();
27990
27991 ASTOBJ_CONTAINER_DESTROYALL(®l, sip_registry_destroy);
27992 ast_debug(4, "--------------- Done destroying registry list\n");
27993 ao2_t_callback(peers, OBJ_NODATA, peer_markall_func, NULL, "callback to mark all peers");
27994 }
27995
27996
27997 if (reason != CHANNEL_MODULE_LOAD) {
27998 ast_free(default_tls_cfg.certfile);
27999 ast_free(default_tls_cfg.pvtfile);
28000 ast_free(default_tls_cfg.cipher);
28001 ast_free(default_tls_cfg.cafile);
28002 ast_free(default_tls_cfg.capath);
28003 }
28004 default_tls_cfg.certfile = ast_strdup(AST_CERTFILE);
28005 default_tls_cfg.pvtfile = ast_strdup("");
28006 default_tls_cfg.cipher = ast_strdup("");
28007 default_tls_cfg.cafile = ast_strdup("");
28008 default_tls_cfg.capath = ast_strdup("");
28009
28010
28011 ast_copy_string(oldcontexts, sip_cfg.regcontext, sizeof(oldcontexts));
28012 oldregcontext = oldcontexts;
28013
28014
28015
28016 sipdebug &= sip_debug_console;
28017 ast_clear_flag(&global_flags[0], AST_FLAGS_ALL);
28018 ast_clear_flag(&global_flags[1], AST_FLAGS_ALL);
28019 ast_clear_flag(&global_flags[2], AST_FLAGS_ALL);
28020
28021
28022 ast_sockaddr_parse(&bindaddr, "0.0.0.0:0", 0);
28023 memset(&internip, 0, sizeof(internip));
28024
28025
28026 ast_free_ha(localaddr);
28027 memset(&localaddr, 0, sizeof(localaddr));
28028 memset(&externaddr, 0, sizeof(externaddr));
28029 memset(&media_address, 0, sizeof(media_address));
28030 memset(&default_prefs, 0 , sizeof(default_prefs));
28031 memset(&sip_cfg.outboundproxy, 0, sizeof(struct sip_proxy));
28032 sip_cfg.outboundproxy.force = FALSE;
28033 default_transports = SIP_TRANSPORT_UDP;
28034 default_primary_transport = SIP_TRANSPORT_UDP;
28035 ourport_tcp = STANDARD_SIP_PORT;
28036 ourport_tls = STANDARD_TLS_PORT;
28037 externtcpport = STANDARD_SIP_PORT;
28038 externtlsport = STANDARD_TLS_PORT;
28039 sip_cfg.srvlookup = DEFAULT_SRVLOOKUP;
28040 global_tos_sip = DEFAULT_TOS_SIP;
28041 global_tos_audio = DEFAULT_TOS_AUDIO;
28042 global_tos_video = DEFAULT_TOS_VIDEO;
28043 global_tos_text = DEFAULT_TOS_TEXT;
28044 global_cos_sip = DEFAULT_COS_SIP;
28045 global_cos_audio = DEFAULT_COS_AUDIO;
28046 global_cos_video = DEFAULT_COS_VIDEO;
28047 global_cos_text = DEFAULT_COS_TEXT;
28048
28049 externhost[0] = '\0';
28050 externexpire = 0;
28051 externrefresh = 10;
28052
28053
28054 sip_cfg.allow_external_domains = DEFAULT_ALLOW_EXT_DOM;
28055 sip_cfg.regcontext[0] = '\0';
28056 sip_cfg.capability = DEFAULT_CAPABILITY;
28057 sip_cfg.regextenonqualify = DEFAULT_REGEXTENONQUALIFY;
28058 sip_cfg.legacy_useroption_parsing = DEFAULT_LEGACY_USEROPTION_PARSING;
28059 sip_cfg.notifyringing = DEFAULT_NOTIFYRINGING;
28060 sip_cfg.notifycid = DEFAULT_NOTIFYCID;
28061 sip_cfg.notifyhold = FALSE;
28062 sip_cfg.directrtpsetup = FALSE;
28063 sip_cfg.alwaysauthreject = DEFAULT_ALWAYSAUTHREJECT;
28064 sip_cfg.auth_options_requests = DEFAULT_AUTH_OPTIONS;
28065 sip_cfg.allowsubscribe = FALSE;
28066 sip_cfg.disallowed_methods = SIP_UNKNOWN;
28067 sip_cfg.contact_ha = NULL;
28068 snprintf(global_useragent, sizeof(global_useragent), "%s %s", DEFAULT_USERAGENT, ast_get_version());
28069 snprintf(global_sdpsession, sizeof(global_sdpsession), "%s %s", DEFAULT_SDPSESSION, ast_get_version());
28070 snprintf(global_sdpowner, sizeof(global_sdpowner), "%s", DEFAULT_SDPOWNER);
28071 global_prematuremediafilter = TRUE;
28072 ast_copy_string(default_notifymime, DEFAULT_NOTIFYMIME, sizeof(default_notifymime));
28073 ast_copy_string(sip_cfg.realm, S_OR(ast_config_AST_SYSTEM_NAME, DEFAULT_REALM), sizeof(sip_cfg.realm));
28074 sip_cfg.domainsasrealm = DEFAULT_DOMAINSASREALM;
28075 ast_copy_string(default_callerid, DEFAULT_CALLERID, sizeof(default_callerid));
28076 ast_copy_string(default_mwi_from, DEFAULT_MWI_FROM, sizeof(default_mwi_from));
28077 sip_cfg.compactheaders = DEFAULT_COMPACTHEADERS;
28078 global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
28079 global_regattempts_max = 0;
28080 sip_cfg.pedanticsipchecking = DEFAULT_PEDANTIC;
28081 sip_cfg.autocreatepeer = DEFAULT_AUTOCREATEPEER;
28082 global_autoframing = 0;
28083 sip_cfg.allowguest = DEFAULT_ALLOWGUEST;
28084 global_callcounter = DEFAULT_CALLCOUNTER;
28085 global_match_auth_username = FALSE;
28086 global_rtptimeout = 0;
28087 global_rtpholdtimeout = 0;
28088 global_rtpkeepalive = DEFAULT_RTPKEEPALIVE;
28089 sip_cfg.allowtransfer = TRANSFER_OPENFORALL;
28090 sip_cfg.rtautoclear = 120;
28091 ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE);
28092 ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP_YES);
28093 sip_cfg.peer_rtupdate = TRUE;
28094 global_dynamic_exclude_static = 0;
28095 sip_cfg.tcp_enabled = FALSE;
28096
28097
28098 global_st_mode = SESSION_TIMER_MODE_ACCEPT;
28099 global_st_refresher = SESSION_TIMER_REFRESHER_UAS;
28100 global_min_se = DEFAULT_MIN_SE;
28101 global_max_se = DEFAULT_MAX_SE;
28102
28103
28104 global_qualify_gap = DEFAULT_QUALIFY_GAP;
28105 global_qualify_peers = DEFAULT_QUALIFY_PEERS;
28106
28107
28108 ast_copy_string(sip_cfg.default_context, DEFAULT_CONTEXT, sizeof(sip_cfg.default_context));
28109 sip_cfg.default_subscribecontext[0] = '\0';
28110 sip_cfg.default_max_forwards = DEFAULT_MAX_FORWARDS;
28111 default_language[0] = '\0';
28112 default_fromdomain[0] = '\0';
28113 default_fromdomainport = 0;
28114 default_qualify = DEFAULT_QUALIFY;
28115 default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
28116 ast_copy_string(default_mohinterpret, DEFAULT_MOHINTERPRET, sizeof(default_mohinterpret));
28117 ast_copy_string(default_mohsuggest, DEFAULT_MOHSUGGEST, sizeof(default_mohsuggest));
28118 ast_copy_string(default_vmexten, DEFAULT_VMEXTEN, sizeof(default_vmexten));
28119 ast_set_flag(&global_flags[0], SIP_DTMF_RFC2833);
28120 ast_set_flag(&global_flags[0], SIP_DIRECT_MEDIA);
28121 ast_set_flag(&global_flags[0], SIP_NAT_FORCE_RPORT);
28122 ast_copy_string(default_engine, DEFAULT_ENGINE, sizeof(default_engine));
28123 ast_copy_string(default_parkinglot, DEFAULT_PARKINGLOT, sizeof(default_parkinglot));
28124
28125
28126 dumphistory = FALSE;
28127 recordhistory = FALSE;
28128 sipdebug &= ~sip_debug_config;
28129
28130
28131 global_relaxdtmf = FALSE;
28132 sip_cfg.callevents = DEFAULT_CALLEVENTS;
28133 global_authfailureevents = FALSE;
28134 global_t1 = DEFAULT_TIMER_T1;
28135 global_timer_b = 64 * DEFAULT_TIMER_T1;
28136 global_t1min = DEFAULT_T1MIN;
28137 global_qualifyfreq = DEFAULT_QUALIFYFREQ;
28138 global_t38_maxdatagram = -1;
28139 global_shrinkcallerid = 1;
28140 authlimit = DEFAULT_AUTHLIMIT;
28141 authtimeout = DEFAULT_AUTHTIMEOUT;
28142 global_store_sip_cause = DEFAULT_STORE_SIP_CAUSE;
28143
28144 sip_cfg.matchexternaddrlocally = DEFAULT_MATCHEXTERNADDRLOCALLY;
28145
28146
28147 memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
28148
28149 ast_clear_flag(&global_flags[1], SIP_PAGE2_FAX_DETECT);
28150 ast_clear_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT | SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
28151 ast_clear_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT);
28152 ast_clear_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION);
28153
28154
28155
28156 for (v = ast_variable_browse(cfg, "general"); v; v = v->next) {
28157 if (handle_common_options(&global_flags[0], &dummy[0], v)) {
28158 continue;
28159 }
28160 if (handle_t38_options(&global_flags[0], &dummy[0], v, &global_t38_maxdatagram)) {
28161 continue;
28162 }
28163
28164 if (!ast_jb_read_conf(&global_jbconf, v->name, v->value))
28165 continue;
28166
28167
28168 if (!ast_tls_read_conf(&default_tls_cfg, &sip_tls_desc, v->name, v->value)) {
28169 continue;
28170 }
28171
28172 if (!strcasecmp(v->name, "context")) {
28173 ast_copy_string(sip_cfg.default_context, v->value, sizeof(sip_cfg.default_context));
28174 } else if (!strcasecmp(v->name, "subscribecontext")) {
28175 ast_copy_string(sip_cfg.default_subscribecontext, v->value, sizeof(sip_cfg.default_subscribecontext));
28176 } else if (!strcasecmp(v->name, "callcounter")) {
28177 global_callcounter = ast_true(v->value) ? 1 : 0;
28178 } else if (!strcasecmp(v->name, "allowguest")) {
28179 sip_cfg.allowguest = ast_true(v->value) ? 1 : 0;
28180 } else if (!strcasecmp(v->name, "realm")) {
28181 ast_copy_string(sip_cfg.realm, v->value, sizeof(sip_cfg.realm));
28182 } else if (!strcasecmp(v->name, "domainsasrealm")) {
28183 sip_cfg.domainsasrealm = ast_true(v->value);
28184 } else if (!strcasecmp(v->name, "useragent")) {
28185 ast_copy_string(global_useragent, v->value, sizeof(global_useragent));
28186 ast_debug(1, "Setting SIP channel User-Agent Name to %s\n", global_useragent);
28187 } else if (!strcasecmp(v->name, "sdpsession")) {
28188 ast_copy_string(global_sdpsession, v->value, sizeof(global_sdpsession));
28189 } else if (!strcasecmp(v->name, "sdpowner")) {
28190
28191 if (!strstr(v->value, " ")) {
28192 ast_copy_string(global_sdpowner, v->value, sizeof(global_sdpowner));
28193 } else {
28194 ast_log(LOG_WARNING, "'%s' must not contain spaces at line %d. Using default.\n", v->value, v->lineno);
28195 }
28196 } else if (!strcasecmp(v->name, "allowtransfer")) {
28197 sip_cfg.allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
28198 } else if (!strcasecmp(v->name, "rtcachefriends")) {
28199 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTCACHEFRIENDS);
28200 } else if (!strcasecmp(v->name, "rtsavesysname")) {
28201 sip_cfg.rtsave_sysname = ast_true(v->value);
28202 } else if (!strcasecmp(v->name, "rtupdate")) {
28203 sip_cfg.peer_rtupdate = ast_true(v->value);
28204 } else if (!strcasecmp(v->name, "ignoreregexpire")) {
28205 sip_cfg.ignore_regexpire = ast_true(v->value);
28206 } else if (!strcasecmp(v->name, "timert1")) {
28207
28208
28209
28210 global_t1 = atoi(v->value);
28211 } else if (!strcasecmp(v->name, "timerb")) {
28212 int tmp = atoi(v->value);
28213 if (tmp < 500) {
28214 global_timer_b = global_t1 * 64;
28215 ast_log(LOG_WARNING, "Invalid value for timerb ('%s'). Setting to default ('%d').\n", v->value, global_timer_b);
28216 }
28217 timerb_set = 1;
28218 } else if (!strcasecmp(v->name, "t1min")) {
28219 global_t1min = atoi(v->value);
28220 } else if (!strcasecmp(v->name, "transport")) {
28221 char *val = ast_strdupa(v->value);
28222 char *trans;
28223
28224 default_transports = default_primary_transport = 0;
28225 while ((trans = strsep(&val, ","))) {
28226 trans = ast_skip_blanks(trans);
28227
28228 if (!strncasecmp(trans, "udp", 3)) {
28229 default_transports |= SIP_TRANSPORT_UDP;
28230 } else if (!strncasecmp(trans, "tcp", 3)) {
28231 default_transports |= SIP_TRANSPORT_TCP;
28232 } else if (!strncasecmp(trans, "tls", 3)) {
28233 default_transports |= SIP_TRANSPORT_TLS;
28234 } else {
28235 ast_log(LOG_NOTICE, "'%s' is not a valid transport type. if no other is specified, udp will be used.\n", trans);
28236 }
28237 if (default_primary_transport == 0) {
28238 default_primary_transport = default_transports;
28239 }
28240 }
28241 } else if (!strcasecmp(v->name, "tcpenable")) {
28242 if (!ast_false(v->value)) {
28243 ast_debug(2, "Enabling TCP socket for listening\n");
28244 sip_cfg.tcp_enabled = TRUE;
28245 }
28246 } else if (!strcasecmp(v->name, "tcpbindaddr")) {
28247 if (ast_parse_arg(v->value, PARSE_ADDR,
28248 &sip_tcp_desc.local_address)) {
28249 ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n",
28250 v->name, v->value, v->lineno, config);
28251 }
28252 ast_debug(2, "Setting TCP socket address to %s\n",
28253 ast_sockaddr_stringify(&sip_tcp_desc.local_address));
28254 } else if (!strcasecmp(v->name, "dynamic_exclude_static") || !strcasecmp(v->name, "dynamic_excludes_static")) {
28255 global_dynamic_exclude_static = ast_true(v->value);
28256 } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny")) {
28257 int ha_error = 0;
28258 sip_cfg.contact_ha = ast_append_ha(v->name + 7, v->value, sip_cfg.contact_ha, &ha_error);
28259 if (ha_error) {
28260 ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
28261 }
28262 } else if (!strcasecmp(v->name, "rtautoclear")) {
28263 int i = atoi(v->value);
28264 if (i > 0) {
28265 sip_cfg.rtautoclear = i;
28266 } else {
28267 i = 0;
28268 }
28269 ast_set2_flag(&global_flags[1], i || ast_true(v->value), SIP_PAGE2_RTAUTOCLEAR);
28270 } else if (!strcasecmp(v->name, "usereqphone")) {
28271 ast_set2_flag(&global_flags[0], ast_true(v->value), SIP_USEREQPHONE);
28272 } else if (!strcasecmp(v->name, "prematuremedia")) {
28273 global_prematuremediafilter = ast_true(v->value);
28274 } else if (!strcasecmp(v->name, "relaxdtmf")) {
28275 global_relaxdtmf = ast_true(v->value);
28276 } else if (!strcasecmp(v->name, "vmexten")) {
28277 ast_copy_string(default_vmexten, v->value, sizeof(default_vmexten));
28278 } else if (!strcasecmp(v->name, "rtptimeout")) {
28279 if ((sscanf(v->value, "%30d", &global_rtptimeout) != 1) || (global_rtptimeout < 0)) {
28280 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
28281 global_rtptimeout = 0;
28282 }
28283 } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
28284 if ((sscanf(v->value, "%30d", &global_rtpholdtimeout) != 1) || (global_rtpholdtimeout < 0)) {
28285 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
28286 global_rtpholdtimeout = 0;
28287 }
28288 } else if (!strcasecmp(v->name, "rtpkeepalive")) {
28289 if ((sscanf(v->value, "%30d", &global_rtpkeepalive) != 1) || (global_rtpkeepalive < 0)) {
28290 ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d. Using default.\n", v->value, v->lineno);
28291 global_rtpkeepalive = DEFAULT_RTPKEEPALIVE;
28292 }
28293 } else if (!strcasecmp(v->name, "compactheaders")) {
28294 sip_cfg.compactheaders = ast_true(v->value);
28295 } else if (!strcasecmp(v->name, "notifymimetype")) {
28296 ast_copy_string(default_notifymime, v->value, sizeof(default_notifymime));
28297 } else if (!strcasecmp(v->name, "directrtpsetup")) {
28298 sip_cfg.directrtpsetup = ast_true(v->value);
28299 } else if (!strcasecmp(v->name, "notifyringing")) {
28300 sip_cfg.notifyringing = ast_true(v->value);
28301 } else if (!strcasecmp(v->name, "notifyhold")) {
28302 sip_cfg.notifyhold = ast_true(v->value);
28303 } else if (!strcasecmp(v->name, "notifycid")) {
28304 if (!strcasecmp(v->value, "ignore-context")) {
28305 sip_cfg.notifycid = IGNORE_CONTEXT;
28306 } else {
28307 sip_cfg.notifycid = ast_true(v->value) ? ENABLED : DISABLED;
28308 }
28309 } else if (!strcasecmp(v->name, "alwaysauthreject")) {
28310 sip_cfg.alwaysauthreject = ast_true(v->value);
28311 } else if (!strcasecmp(v->name, "auth_options_requests")) {
28312 if (ast_true(v->value)) {
28313 sip_cfg.auth_options_requests = 1;
28314 }
28315 } else if (!strcasecmp(v->name, "mohinterpret")) {
28316 ast_copy_string(default_mohinterpret, v->value, sizeof(default_mohinterpret));
28317 } else if (!strcasecmp(v->name, "mohsuggest")) {
28318 ast_copy_string(default_mohsuggest, v->value, sizeof(default_mohsuggest));
28319 } else if (!strcasecmp(v->name, "language")) {
28320 ast_copy_string(default_language, v->value, sizeof(default_language));
28321 } else if (!strcasecmp(v->name, "regcontext")) {
28322 ast_copy_string(newcontexts, v->value, sizeof(newcontexts));
28323 stringp = newcontexts;
28324
28325 cleanup_stale_contexts(stringp, oldregcontext);
28326
28327 while ((context = strsep(&stringp, "&"))) {
28328 ast_copy_string(used_context, context, sizeof(used_context));
28329 ast_context_find_or_create(NULL, NULL, context, "SIP");
28330 }
28331 ast_copy_string(sip_cfg.regcontext, v->value, sizeof(sip_cfg.regcontext));
28332 } else if (!strcasecmp(v->name, "regextenonqualify")) {
28333 sip_cfg.regextenonqualify = ast_true(v->value);
28334 } else if (!strcasecmp(v->name, "legacy_useroption_parsing")) {
28335 sip_cfg.legacy_useroption_parsing = ast_true(v->value);
28336 } else if (!strcasecmp(v->name, "callerid")) {
28337 ast_copy_string(default_callerid, v->value, sizeof(default_callerid));
28338 } else if (!strcasecmp(v->name, "mwi_from")) {
28339 ast_copy_string(default_mwi_from, v->value, sizeof(default_mwi_from));
28340 } else if (!strcasecmp(v->name, "fromdomain")) {
28341 char *fromdomainport;
28342 ast_copy_string(default_fromdomain, v->value, sizeof(default_fromdomain));
28343 if ((fromdomainport = strchr(default_fromdomain, ':'))) {
28344 *fromdomainport++ = '\0';
28345 if (!(default_fromdomainport = port_str2int(fromdomainport, 0))) {
28346 ast_log(LOG_NOTICE, "'%s' is not a valid port number for fromdomain.\n",fromdomainport);
28347 }
28348 } else {
28349 default_fromdomainport = STANDARD_SIP_PORT;
28350 }
28351 } else if (!strcasecmp(v->name, "outboundproxy")) {
28352 char *tok, *proxyname;
28353
28354 if (ast_strlen_zero(v->value)) {
28355 ast_log(LOG_WARNING, "no value given for outbound proxy on line %d of sip.conf.", v->lineno);
28356 continue;
28357 }
28358
28359 tok = ast_skip_blanks(strtok(ast_strdupa(v->value), ","));
28360
28361 sip_parse_host(tok, v->lineno, &proxyname,
28362 &sip_cfg.outboundproxy.port,
28363 &sip_cfg.outboundproxy.transport);
28364
28365 if ((tok = strtok(NULL, ","))) {
28366 sip_cfg.outboundproxy.force = !strncasecmp(ast_skip_blanks(tok), "force", 5);
28367 } else {
28368 sip_cfg.outboundproxy.force = FALSE;
28369 }
28370
28371 if (ast_strlen_zero(proxyname)) {
28372 ast_log(LOG_WARNING, "you must specify a name for the outboundproxy on line %d of sip.conf.", v->lineno);
28373 sip_cfg.outboundproxy.name[0] = '\0';
28374 continue;
28375 }
28376
28377 ast_copy_string(sip_cfg.outboundproxy.name, proxyname, sizeof(sip_cfg.outboundproxy.name));
28378
28379 proxy_update(&sip_cfg.outboundproxy);
28380 } else if (!strcasecmp(v->name, "autocreatepeer")) {
28381 sip_cfg.autocreatepeer = ast_true(v->value);
28382 } else if (!strcasecmp(v->name, "match_auth_username")) {
28383 global_match_auth_username = ast_true(v->value);
28384 } else if (!strcasecmp(v->name, "srvlookup")) {
28385 sip_cfg.srvlookup = ast_true(v->value);
28386 } else if (!strcasecmp(v->name, "pedantic")) {
28387 sip_cfg.pedanticsipchecking = ast_true(v->value);
28388 } else if (!strcasecmp(v->name, "maxexpirey") || !strcasecmp(v->name, "maxexpiry")) {
28389 max_expiry = atoi(v->value);
28390 if (max_expiry < 1) {
28391 max_expiry = DEFAULT_MAX_EXPIRY;
28392 }
28393 } else if (!strcasecmp(v->name, "minexpirey") || !strcasecmp(v->name, "minexpiry")) {
28394 min_expiry = atoi(v->value);
28395 if (min_expiry < 1) {
28396 min_expiry = DEFAULT_MIN_EXPIRY;
28397 }
28398 } else if (!strcasecmp(v->name, "defaultexpiry") || !strcasecmp(v->name, "defaultexpirey")) {
28399 default_expiry = atoi(v->value);
28400 if (default_expiry < 1) {
28401 default_expiry = DEFAULT_DEFAULT_EXPIRY;
28402 }
28403 } else if (!strcasecmp(v->name, "mwiexpiry") || !strcasecmp(v->name, "mwiexpirey")) {
28404 mwi_expiry = atoi(v->value);
28405 if (mwi_expiry < 1) {
28406 mwi_expiry = DEFAULT_MWI_EXPIRY;
28407 }
28408 } else if (!strcasecmp(v->name, "tcpauthtimeout")) {
28409 if (ast_parse_arg(v->value, PARSE_INT32|PARSE_DEFAULT|PARSE_IN_RANGE,
28410 &authtimeout, DEFAULT_AUTHTIMEOUT, 1, INT_MAX)) {
28411 ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n",
28412 v->name, v->value, v->lineno, config);
28413 }
28414 } else if (!strcasecmp(v->name, "tcpauthlimit")) {
28415 if (ast_parse_arg(v->value, PARSE_INT32|PARSE_DEFAULT|PARSE_IN_RANGE,
28416 &authlimit, DEFAULT_AUTHLIMIT, 1, INT_MAX)) {
28417 ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n",
28418 v->name, v->value, v->lineno, config);
28419 }
28420 } else if (!strcasecmp(v->name, "sipdebug")) {
28421 if (ast_true(v->value))
28422 sipdebug |= sip_debug_config;
28423 } else if (!strcasecmp(v->name, "dumphistory")) {
28424 dumphistory = ast_true(v->value);
28425 } else if (!strcasecmp(v->name, "recordhistory")) {
28426 recordhistory = ast_true(v->value);
28427 } else if (!strcasecmp(v->name, "registertimeout")) {
28428 global_reg_timeout = atoi(v->value);
28429 if (global_reg_timeout < 1) {
28430 global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
28431 }
28432 } else if (!strcasecmp(v->name, "registerattempts")) {
28433 global_regattempts_max = atoi(v->value);
28434 } else if (!strcasecmp(v->name, "bindaddr") || !strcasecmp(v->name, "udpbindaddr")) {
28435 if (ast_parse_arg(v->value, PARSE_ADDR, &bindaddr)) {
28436 ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
28437 }
28438 } else if (!strcasecmp(v->name, "localnet")) {
28439 struct ast_ha *na;
28440 int ha_error = 0;
28441
28442 if (!(na = ast_append_ha("d", v->value, localaddr, &ha_error))) {
28443 ast_log(LOG_WARNING, "Invalid localnet value: %s\n", v->value);
28444 } else {
28445 localaddr = na;
28446 }
28447 if (ha_error) {
28448 ast_log(LOG_ERROR, "Bad localnet configuration value line %d : %s\n", v->lineno, v->value);
28449 }
28450 } else if (!strcasecmp(v->name, "media_address")) {
28451 if (ast_parse_arg(v->value, PARSE_ADDR, &media_address))
28452 ast_log(LOG_WARNING, "Invalid address for media_address keyword: %s\n", v->value);
28453 } else if (!strcasecmp(v->name, "externaddr") || !strcasecmp(v->name, "externip")) {
28454 if (ast_parse_arg(v->value, PARSE_ADDR, &externaddr)) {
28455 ast_log(LOG_WARNING,
28456 "Invalid address for externaddr keyword: %s\n",
28457 v->value);
28458 }
28459 externexpire = 0;
28460 } else if (!strcasecmp(v->name, "externhost")) {
28461 ast_copy_string(externhost, v->value, sizeof(externhost));
28462 if (ast_sockaddr_resolve_first(&externaddr, externhost, 0)) {
28463 ast_log(LOG_WARNING, "Invalid address for externhost keyword: %s\n", externhost);
28464 }
28465 externexpire = time(NULL);
28466 } else if (!strcasecmp(v->name, "externrefresh")) {
28467 if (sscanf(v->value, "%30d", &externrefresh) != 1) {
28468 ast_log(LOG_WARNING, "Invalid externrefresh value '%s', must be an integer >0 at line %d\n", v->value, v->lineno);
28469 externrefresh = 10;
28470 }
28471 } else if (!strcasecmp(v->name, "externtcpport")) {
28472 if (!(externtcpport = port_str2int(v->value, 0))) {
28473 ast_log(LOG_WARNING, "Invalid externtcpport value, must be a positive integer between 1 and 65535 at line %d\n", v->lineno);
28474 externtcpport = 0;
28475 }
28476 } else if (!strcasecmp(v->name, "externtlsport")) {
28477 if (!(externtlsport = port_str2int(v->value, STANDARD_TLS_PORT))) {
28478 ast_log(LOG_WARNING, "Invalid externtlsport value, must be a positive integer between 1 and 65535 at line %d\n", v->lineno);
28479 }
28480 } else if (!strcasecmp(v->name, "allow")) {
28481 int error = ast_parse_allow_disallow(&default_prefs, &sip_cfg.capability, v->value, TRUE);
28482 if (error) {
28483 ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
28484 }
28485 } else if (!strcasecmp(v->name, "disallow")) {
28486 int error = ast_parse_allow_disallow(&default_prefs, &sip_cfg.capability, v->value, FALSE);
28487 if (error) {
28488 ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
28489 }
28490 } else if (!strcasecmp(v->name, "preferred_codec_only")) {
28491 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_PREFERRED_CODEC);
28492 } else if (!strcasecmp(v->name, "autoframing")) {
28493 global_autoframing = ast_true(v->value);
28494 } else if (!strcasecmp(v->name, "allowexternaldomains")) {
28495 sip_cfg.allow_external_domains = ast_true(v->value);
28496 } else if (!strcasecmp(v->name, "autodomain")) {
28497 auto_sip_domains = ast_true(v->value);
28498 } else if (!strcasecmp(v->name, "domain")) {
28499 char *domain = ast_strdupa(v->value);
28500 char *cntx = strchr(domain, ',');
28501
28502 if (cntx) {
28503 *cntx++ = '\0';
28504 }
28505
28506 if (ast_strlen_zero(cntx)) {
28507 ast_debug(1, "No context specified at line %d for domain '%s'\n", v->lineno, domain);
28508 }
28509 if (ast_strlen_zero(domain)) {
28510 ast_log(LOG_WARNING, "Empty domain specified at line %d\n", v->lineno);
28511 } else {
28512 add_sip_domain(ast_strip(domain), SIP_DOMAIN_CONFIG, cntx ? ast_strip(cntx) : "");
28513 }
28514 } else if (!strcasecmp(v->name, "register")) {
28515 if (sip_register(v->value, v->lineno) == 0) {
28516 registry_count++;
28517 }
28518 } else if (!strcasecmp(v->name, "mwi")) {
28519 sip_subscribe_mwi(v->value, v->lineno);
28520 } else if (!strcasecmp(v->name, "tos_sip")) {
28521 if (ast_str2tos(v->value, &global_tos_sip)) {
28522 ast_log(LOG_WARNING, "Invalid tos_sip value at line %d, refer to QoS documentation\n", v->lineno);
28523 }
28524 } else if (!strcasecmp(v->name, "tos_audio")) {
28525 if (ast_str2tos(v->value, &global_tos_audio)) {
28526 ast_log(LOG_WARNING, "Invalid tos_audio value at line %d, refer to QoS documentation\n", v->lineno);
28527 }
28528 } else if (!strcasecmp(v->name, "tos_video")) {
28529 if (ast_str2tos(v->value, &global_tos_video)) {
28530 ast_log(LOG_WARNING, "Invalid tos_video value at line %d, refer to QoS documentation\n", v->lineno);
28531 }
28532 } else if (!strcasecmp(v->name, "tos_text")) {
28533 if (ast_str2tos(v->value, &global_tos_text)) {
28534 ast_log(LOG_WARNING, "Invalid tos_text value at line %d, refer to QoS documentation\n", v->lineno);
28535 }
28536 } else if (!strcasecmp(v->name, "cos_sip")) {
28537 if (ast_str2cos(v->value, &global_cos_sip)) {
28538 ast_log(LOG_WARNING, "Invalid cos_sip value at line %d, refer to QoS documentation\n", v->lineno);
28539 }
28540 } else if (!strcasecmp(v->name, "cos_audio")) {
28541 if (ast_str2cos(v->value, &global_cos_audio)) {
28542 ast_log(LOG_WARNING, "Invalid cos_audio value at line %d, refer to QoS documentation\n", v->lineno);
28543 }
28544 } else if (!strcasecmp(v->name, "cos_video")) {
28545 if (ast_str2cos(v->value, &global_cos_video)) {
28546 ast_log(LOG_WARNING, "Invalid cos_video value at line %d, refer to QoS documentation\n", v->lineno);
28547 }
28548 } else if (!strcasecmp(v->name, "cos_text")) {
28549 if (ast_str2cos(v->value, &global_cos_text)) {
28550 ast_log(LOG_WARNING, "Invalid cos_text value at line %d, refer to QoS documentation\n", v->lineno);
28551 }
28552 } else if (!strcasecmp(v->name, "bindport")) {
28553 if (sscanf(v->value, "%5d", &bindport) != 1) {
28554 ast_log(LOG_WARNING, "Invalid port number '%s' at line %d of %s\n", v->value, v->lineno, config);
28555 }
28556 } else if (!strcasecmp(v->name, "qualify")) {
28557 if (!strcasecmp(v->value, "no")) {
28558 default_qualify = 0;
28559 } else if (!strcasecmp(v->value, "yes")) {
28560 default_qualify = DEFAULT_MAXMS;
28561 } else if (sscanf(v->value, "%30d", &default_qualify) != 1) {
28562 ast_log(LOG_WARNING, "Qualification default should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", v->lineno);
28563 default_qualify = 0;
28564 }
28565 } else if (!strcasecmp(v->name, "qualifyfreq")) {
28566 int i;
28567 if (sscanf(v->value, "%30d", &i) == 1) {
28568 global_qualifyfreq = i * 1000;
28569 } else {
28570 ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
28571 global_qualifyfreq = DEFAULT_QUALIFYFREQ;
28572 }
28573 } else if (!strcasecmp(v->name, "callevents")) {
28574 sip_cfg.callevents = ast_true(v->value);
28575 } else if (!strcasecmp(v->name, "authfailureevents")) {
28576 global_authfailureevents = ast_true(v->value);
28577 } else if (!strcasecmp(v->name, "maxcallbitrate")) {
28578 default_maxcallbitrate = atoi(v->value);
28579 if (default_maxcallbitrate < 0)
28580 default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
28581 } else if (!strcasecmp(v->name, "matchexternaddrlocally") || !strcasecmp(v->name, "matchexterniplocally")) {
28582 sip_cfg.matchexternaddrlocally = ast_true(v->value);
28583 } else if (!strcasecmp(v->name, "session-timers")) {
28584 int i = (int) str2stmode(v->value);
28585 if (i < 0) {
28586 ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
28587 global_st_mode = SESSION_TIMER_MODE_ACCEPT;
28588 } else {
28589 global_st_mode = i;
28590 }
28591 } else if (!strcasecmp(v->name, "session-expires")) {
28592 if (sscanf(v->value, "%30d", &global_max_se) != 1) {
28593 ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
28594 global_max_se = DEFAULT_MAX_SE;
28595 }
28596 } else if (!strcasecmp(v->name, "session-minse")) {
28597 if (sscanf(v->value, "%30d", &global_min_se) != 1) {
28598 ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
28599 global_min_se = DEFAULT_MIN_SE;
28600 }
28601 if (global_min_se < 90) {
28602 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);
28603 global_min_se = DEFAULT_MIN_SE;
28604 }
28605 } else if (!strcasecmp(v->name, "session-refresher")) {
28606 int i = (int) str2strefresher(v->value);
28607 if (i < 0) {
28608 ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
28609 global_st_refresher = SESSION_TIMER_REFRESHER_UAS;
28610 } else {
28611 global_st_refresher = i;
28612 }
28613 } else if (!strcasecmp(v->name, "storesipcause")) {
28614 global_store_sip_cause = ast_true(v->value);
28615 } else if (!strcasecmp(v->name, "qualifygap")) {
28616 if (sscanf(v->value, "%30d", &global_qualify_gap) != 1) {
28617 ast_log(LOG_WARNING, "Invalid qualifygap '%s' at line %d of %s\n", v->value, v->lineno, config);
28618 global_qualify_gap = DEFAULT_QUALIFY_GAP;
28619 }
28620 } else if (!strcasecmp(v->name, "qualifypeers")) {
28621 if (sscanf(v->value, "%30d", &global_qualify_peers) != 1) {
28622 ast_log(LOG_WARNING, "Invalid pokepeers '%s' at line %d of %s\n", v->value, v->lineno, config);
28623 global_qualify_peers = DEFAULT_QUALIFY_PEERS;
28624 }
28625 } else if (!strcasecmp(v->name, "disallowed_methods")) {
28626 char *disallow = ast_strdupa(v->value);
28627 mark_parsed_methods(&sip_cfg.disallowed_methods, disallow);
28628 } else if (!strcasecmp(v->name, "shrinkcallerid")) {
28629 if (ast_true(v->value)) {
28630 global_shrinkcallerid = 1;
28631 } else if (ast_false(v->value)) {
28632 global_shrinkcallerid = 0;
28633 } else {
28634 ast_log(LOG_WARNING, "shrinkcallerid value %s is not valid at line %d.\n", v->value, v->lineno);
28635 }
28636 } else if (!strcasecmp(v->name, "use_q850_reason")) {
28637 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_Q850_REASON);
28638 } else if (!strcasecmp(v->name, "maxforwards")) {
28639 if ((sscanf(v->value, "%30d", &sip_cfg.default_max_forwards) != 1) || (sip_cfg.default_max_forwards < 1)) {
28640 ast_log(LOG_WARNING, "'%s' is not a valid maxforwards value at line %d. Using default.\n", v->value, v->lineno);
28641 sip_cfg.default_max_forwards = DEFAULT_MAX_FORWARDS;
28642 }
28643 } else if (!strcasecmp(v->name, "subscribe_network_change_event")) {
28644 if (ast_true(v->value)) {
28645 subscribe_network_change = 1;
28646 } else if (ast_false(v->value)) {
28647 subscribe_network_change = 0;
28648 } else {
28649 ast_log(LOG_WARNING, "subscribe_network_change_event value %s is not valid at line %d.\n", v->value, v->lineno);
28650 }
28651 } else if (!strcasecmp(v->name, "snom_aoc_enabled")) {
28652 ast_set2_flag(&global_flags[2], ast_true(v->value), SIP_PAGE3_SNOM_AOC);
28653 } else if (!strcasecmp(v->name, "parkinglot")) {
28654 ast_copy_string(default_parkinglot, v->value, sizeof(default_parkinglot));
28655 }
28656 }
28657
28658 if (subscribe_network_change) {
28659 network_change_event_subscribe();
28660 } else {
28661 network_change_event_unsubscribe();
28662 }
28663
28664 if (global_t1 < global_t1min) {
28665 ast_log(LOG_WARNING, "'t1min' (%d) cannot be greater than 't1timer' (%d). Resetting 't1timer' to the value of 't1min'\n", global_t1min, global_t1);
28666 global_t1 = global_t1min;
28667 }
28668
28669 if (global_timer_b < global_t1 * 64) {
28670 if (timerb_set && timert1_set) {
28671 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);
28672 } else if (timerb_set) {
28673 if ((global_t1 = global_timer_b / 64) < global_t1min) {
28674 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);
28675 global_t1 = global_t1min;
28676 global_timer_b = global_t1 * 64;
28677 }
28678 } else {
28679 global_timer_b = global_t1 * 64;
28680 }
28681 }
28682 if (!sip_cfg.allow_external_domains && AST_LIST_EMPTY(&domain_list)) {
28683 ast_log(LOG_WARNING, "To disallow external domains, you need to configure local SIP domains.\n");
28684 sip_cfg.allow_external_domains = 1;
28685 }
28686
28687 if (!sip_cfg.tcp_enabled && (default_transports & SIP_TRANSPORT_TCP)) {
28688 ast_log(LOG_WARNING, "Cannot use 'tcp' transport with tcpenable=no. Removing from available transports.\n");
28689 default_primary_transport &= ~SIP_TRANSPORT_TCP;
28690 default_transports &= ~SIP_TRANSPORT_TCP;
28691 }
28692 if (!default_tls_cfg.enabled && (default_transports & SIP_TRANSPORT_TLS)) {
28693 ast_log(LOG_WARNING, "Cannot use 'tls' transport with tlsenable=no. Removing from available transports.\n");
28694 default_primary_transport &= ~SIP_TRANSPORT_TLS;
28695 default_transports &= ~SIP_TRANSPORT_TLS;
28696 }
28697 if (!default_transports) {
28698 ast_log(LOG_WARNING, "No valid transports available, falling back to 'udp'.\n");
28699 default_transports = default_primary_transport = SIP_TRANSPORT_UDP;
28700 } else if (!default_primary_transport) {
28701 ast_log(LOG_WARNING, "No valid default transport. Selecting 'udp' as default.\n");
28702 default_primary_transport = SIP_TRANSPORT_UDP;
28703 }
28704
28705
28706 for (v = ast_variable_browse(cfg, "authentication"); v ; v = v->next) {
28707
28708 if (!strcasecmp(v->name, "auth")) {
28709 add_realm_authentication(&authl, v->value, v->lineno);
28710 }
28711 }
28712
28713 if (bindport) {
28714 if (ast_sockaddr_port(&bindaddr)) {
28715 ast_log(LOG_WARNING, "bindport is also specified in bindaddr. "
28716 "Using %d.\n", bindport);
28717 }
28718 ast_sockaddr_set_port(&bindaddr, bindport);
28719 }
28720
28721 if (!ast_sockaddr_port(&bindaddr)) {
28722 ast_sockaddr_set_port(&bindaddr, STANDARD_SIP_PORT);
28723 }
28724
28725
28726 ast_sockaddr_copy(&internip, &bindaddr);
28727 if (ast_find_ourip(&internip, &bindaddr, 0)) {
28728 ast_log(LOG_WARNING, "Unable to get own IP address, SIP disabled\n");
28729 ast_config_destroy(cfg);
28730 return 0;
28731 }
28732
28733 ast_mutex_lock(&netlock);
28734 if ((sipsock > -1) && (ast_sockaddr_cmp(&old_bindaddr, &bindaddr))) {
28735 close(sipsock);
28736 sipsock = -1;
28737 }
28738 if (sipsock < 0) {
28739 sipsock = socket(ast_sockaddr_is_ipv6(&bindaddr) ?
28740 AF_INET6 : AF_INET, SOCK_DGRAM, 0);
28741 if (sipsock < 0) {
28742 ast_log(LOG_WARNING, "Unable to create SIP socket: %s\n", strerror(errno));
28743 ast_config_destroy(cfg);
28744 ast_mutex_unlock(&netlock);
28745 return -1;
28746 } else {
28747
28748 const int reuseFlag = 1;
28749
28750 setsockopt(sipsock, SOL_SOCKET, SO_REUSEADDR,
28751 (const char*)&reuseFlag,
28752 sizeof reuseFlag);
28753
28754 ast_enable_packet_fragmentation(sipsock);
28755
28756 if (ast_bind(sipsock, &bindaddr) < 0) {
28757 ast_log(LOG_WARNING, "Failed to bind to %s: %s\n",
28758 ast_sockaddr_stringify(&bindaddr), strerror(errno));
28759 close(sipsock);
28760 sipsock = -1;
28761 } else {
28762 ast_verb(2, "SIP Listening on %s\n", ast_sockaddr_stringify(&bindaddr));
28763 ast_set_qos(sipsock, global_tos_sip, global_cos_sip, "SIP");
28764 }
28765 }
28766 } else {
28767 ast_set_qos(sipsock, global_tos_sip, global_cos_sip, "SIP");
28768 }
28769 ast_mutex_unlock(&netlock);
28770
28771
28772 if (sip_cfg.tcp_enabled) {
28773 if (ast_sockaddr_isnull(&sip_tcp_desc.local_address)) {
28774 ast_sockaddr_copy(&sip_tcp_desc.local_address, &bindaddr);
28775 }
28776 if (!ast_sockaddr_port(&sip_tcp_desc.local_address)) {
28777 ast_sockaddr_set_port(&sip_tcp_desc.local_address, STANDARD_SIP_PORT);
28778 }
28779 } else {
28780 ast_sockaddr_setnull(&sip_tcp_desc.local_address);
28781 }
28782 ast_tcptls_server_start(&sip_tcp_desc);
28783 if (sip_cfg.tcp_enabled && sip_tcp_desc.accept_fd == -1) {
28784
28785 ast_log(LOG_ERROR, "SIP TCP Server start failed. Not listening on TCP socket.\n");
28786 } else {
28787 ast_debug(2, "SIP TCP server started\n");
28788 }
28789
28790
28791 memcpy(sip_tls_desc.tls_cfg, &default_tls_cfg, sizeof(default_tls_cfg));
28792
28793 if (ast_ssl_setup(sip_tls_desc.tls_cfg)) {
28794 if (ast_sockaddr_isnull(&sip_tls_desc.local_address)) {
28795 ast_sockaddr_copy(&sip_tls_desc.local_address, &bindaddr);
28796 ast_sockaddr_set_port(&sip_tls_desc.local_address,
28797 STANDARD_TLS_PORT);
28798 }
28799 if (!ast_sockaddr_port(&sip_tls_desc.local_address)) {
28800 ast_sockaddr_set_port(&sip_tls_desc.local_address,
28801 STANDARD_TLS_PORT);
28802 }
28803 ast_tcptls_server_start(&sip_tls_desc);
28804 if (default_tls_cfg.enabled && sip_tls_desc.accept_fd == -1) {
28805 ast_log(LOG_ERROR, "TLS Server start failed. Not listening on TLS socket.\n");
28806 sip_tls_desc.tls_cfg = NULL;
28807 }
28808 } else if (sip_tls_desc.tls_cfg->enabled) {
28809 sip_tls_desc.tls_cfg = NULL;
28810 ast_log(LOG_WARNING, "SIP TLS server did not load because of errors.\n");
28811 }
28812
28813 if (ucfg) {
28814 struct ast_variable *gen;
28815 int genhassip, genregistersip;
28816 const char *hassip, *registersip;
28817
28818 genhassip = ast_true(ast_variable_retrieve(ucfg, "general", "hassip"));
28819 genregistersip = ast_true(ast_variable_retrieve(ucfg, "general", "registersip"));
28820 gen = ast_variable_browse(ucfg, "general");
28821 cat = ast_category_browse(ucfg, NULL);
28822 while (cat) {
28823 if (strcasecmp(cat, "general")) {
28824 hassip = ast_variable_retrieve(ucfg, cat, "hassip");
28825 registersip = ast_variable_retrieve(ucfg, cat, "registersip");
28826 if (ast_true(hassip) || (!hassip && genhassip)) {
28827 peer = build_peer(cat, gen, ast_variable_browse(ucfg, cat), 0, 0);
28828 if (peer) {
28829
28830 peer->type = SIP_TYPE_USER | SIP_TYPE_PEER;
28831 ao2_t_link(peers, peer, "link peer into peer table");
28832 if ((peer->type & SIP_TYPE_PEER) && !ast_sockaddr_isnull(&peer->addr)) {
28833 ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
28834 }
28835
28836 unref_peer(peer, "unref_peer: from reload_config");
28837 peer_count++;
28838 }
28839 }
28840 if (ast_true(registersip) || (!registersip && genregistersip)) {
28841 char tmp[256];
28842 const char *host = ast_variable_retrieve(ucfg, cat, "host");
28843 const char *username = ast_variable_retrieve(ucfg, cat, "username");
28844 const char *secret = ast_variable_retrieve(ucfg, cat, "secret");
28845 const char *contact = ast_variable_retrieve(ucfg, cat, "contact");
28846 const char *authuser = ast_variable_retrieve(ucfg, cat, "authuser");
28847 if (!host) {
28848 host = ast_variable_retrieve(ucfg, "general", "host");
28849 }
28850 if (!username) {
28851 username = ast_variable_retrieve(ucfg, "general", "username");
28852 }
28853 if (!secret) {
28854 secret = ast_variable_retrieve(ucfg, "general", "secret");
28855 }
28856 if (!contact) {
28857 contact = "s";
28858 }
28859 if (!ast_strlen_zero(username) && !ast_strlen_zero(host)) {
28860 if (!ast_strlen_zero(secret)) {
28861 if (!ast_strlen_zero(authuser)) {
28862 snprintf(tmp, sizeof(tmp), "%s?%s:%s:%s@%s/%s", cat, username, secret, authuser, host, contact);
28863 } else {
28864 snprintf(tmp, sizeof(tmp), "%s?%s:%s@%s/%s", cat, username, secret, host, contact);
28865 }
28866 } else if (!ast_strlen_zero(authuser)) {
28867 snprintf(tmp, sizeof(tmp), "%s?%s::%s@%s/%s", cat, username, authuser, host, contact);
28868 } else {
28869 snprintf(tmp, sizeof(tmp), "%s?%s@%s/%s", cat, username, host, contact);
28870 }
28871 if (sip_register(tmp, 0) == 0) {
28872 registry_count++;
28873 }
28874 }
28875 }
28876 }
28877 cat = ast_category_browse(ucfg, cat);
28878 }
28879 ast_config_destroy(ucfg);
28880 }
28881
28882
28883 cat = NULL;
28884 while ( (cat = ast_category_browse(cfg, cat)) ) {
28885 const char *utype;
28886 if (!strcasecmp(cat, "general") || !strcasecmp(cat, "authentication"))
28887 continue;
28888 utype = ast_variable_retrieve(cfg, cat, "type");
28889 if (!utype) {
28890 ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
28891 continue;
28892 } else {
28893 if (!strcasecmp(utype, "user")) {
28894 ;
28895 } else if (!strcasecmp(utype, "friend")) {
28896 ;
28897 } else if (!strcasecmp(utype, "peer")) {
28898 ;
28899 } else {
28900 ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, "sip.conf");
28901 continue;
28902 }
28903 peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0, 0);
28904 if (peer) {
28905 display_nat_warning(cat, reason, &peer->flags[0]);
28906 ao2_t_link(peers, peer, "link peer into peers table");
28907 if ((peer->type & SIP_TYPE_PEER) && !ast_sockaddr_isnull(&peer->addr)) {
28908 ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
28909 }
28910 unref_peer(peer, "unref the result of the build_peer call. Now, the links from the tables are the only ones left.");
28911 peer_count++;
28912 }
28913 }
28914 }
28915
28916
28917
28918
28919
28920
28921 if (auto_sip_domains) {
28922 char temp[MAXHOSTNAMELEN];
28923
28924
28925 if (!ast_sockaddr_isnull(&bindaddr) && !ast_sockaddr_is_any(&bindaddr)) {
28926 add_sip_domain(ast_sockaddr_stringify_addr(&bindaddr),
28927 SIP_DOMAIN_AUTO, NULL);
28928 } else if (!ast_sockaddr_isnull(&internip) && !ast_sockaddr_is_any(&internip)) {
28929
28930 add_sip_domain(ast_sockaddr_stringify_addr(&internip),
28931 SIP_DOMAIN_AUTO, NULL);
28932 } else {
28933 ast_log(LOG_NOTICE, "Can't add wildcard IP address to domain list, please add IP address to domain manually.\n");
28934 }
28935
28936
28937 if (!ast_sockaddr_isnull(&sip_tcp_desc.local_address) &&
28938 !ast_sockaddr_cmp(&bindaddr, &sip_tcp_desc.local_address)) {
28939 add_sip_domain(ast_sockaddr_stringify_addr(&sip_tcp_desc.local_address),
28940 SIP_DOMAIN_AUTO, NULL);
28941 }
28942
28943
28944 if (!ast_sockaddr_isnull(&sip_tls_desc.local_address) &&
28945 !ast_sockaddr_cmp(&bindaddr, &sip_tls_desc.local_address) &&
28946 !ast_sockaddr_cmp(&sip_tcp_desc.local_address,
28947 &sip_tls_desc.local_address)) {
28948 add_sip_domain(ast_sockaddr_stringify_addr(&sip_tcp_desc.local_address),
28949 SIP_DOMAIN_AUTO, NULL);
28950 }
28951
28952
28953 if (!ast_sockaddr_isnull(&externaddr)) {
28954 add_sip_domain(ast_sockaddr_stringify_addr(&externaddr),
28955 SIP_DOMAIN_AUTO, NULL);
28956 }
28957
28958
28959 if (!ast_strlen_zero(externhost)) {
28960 add_sip_domain(externhost, SIP_DOMAIN_AUTO, NULL);
28961 }
28962
28963
28964 if (!gethostname(temp, sizeof(temp))) {
28965 add_sip_domain(temp, SIP_DOMAIN_AUTO, NULL);
28966 }
28967 }
28968
28969
28970 ast_config_destroy(cfg);
28971
28972
28973 if (notify_types)
28974 ast_config_destroy(notify_types);
28975 if ((notify_types = ast_config_load(notify_config, config_flags)) == CONFIG_STATUS_FILEINVALID) {
28976 ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed.\n", notify_config);
28977 notify_types = NULL;
28978 }
28979
28980
28981 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);
28982 run_end = time(0);
28983 ast_debug(4, "SIP reload_config done...Runtime= %d sec\n", (int)(run_end-run_start));
28984
28985 return 0;
28986 }
28987
28988 static int apply_directmedia_ha(struct sip_pvt *p, const char *op)
28989 {
28990 struct ast_sockaddr us = { { 0, }, }, them = { { 0, }, };
28991 int res = AST_SENSE_ALLOW;
28992
28993 ast_rtp_instance_get_remote_address(p->rtp, &them);
28994 ast_rtp_instance_get_local_address(p->rtp, &us);
28995
28996 if ((res = ast_apply_ha(p->directmediaha, &them)) == AST_SENSE_DENY) {
28997 const char *us_addr = ast_strdupa(ast_sockaddr_stringify(&us));
28998 const char *them_addr = ast_strdupa(ast_sockaddr_stringify(&them));
28999
29000 ast_debug(3, "Reinvite %s to %s denied by directmedia ACL on %s\n",
29001 op, them_addr, us_addr);
29002 }
29003
29004 return res;
29005 }
29006
29007 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan)
29008 {
29009 struct sip_pvt *p;
29010 struct ast_udptl *udptl = NULL;
29011
29012 p = chan->tech_pvt;
29013 if (!p) {
29014 return NULL;
29015 }
29016
29017 sip_pvt_lock(p);
29018 if (p->udptl && ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
29019 if (apply_directmedia_ha(p, "UDPTL T.38 data")) {
29020 udptl = p->udptl;
29021 }
29022 }
29023 sip_pvt_unlock(p);
29024 return udptl;
29025 }
29026
29027 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl)
29028 {
29029 struct sip_pvt *p;
29030
29031
29032 ast_channel_lock(chan);
29033 p = chan->tech_pvt;
29034 if (!p) {
29035 ast_channel_unlock(chan);
29036 return -1;
29037 }
29038 sip_pvt_lock(p);
29039 if (p->owner != chan) {
29040
29041 ast_debug(1, "The private is not owned by channel %s anymore.\n", chan->name);
29042 sip_pvt_unlock(p);
29043 ast_channel_unlock(chan);
29044 return 0;
29045 }
29046
29047 if (udptl) {
29048 ast_udptl_get_peer(udptl, &p->udptlredirip);
29049 } else {
29050 memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
29051 }
29052 if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
29053 if (!p->pendinginvite) {
29054 ast_debug(3, "Sending reinvite on SIP '%s' - It's UDPTL soon redirected to IP %s\n",
29055 p->callid, ast_sockaddr_stringify(udptl ? &p->udptlredirip : &p->ourip));
29056 transmit_reinvite_with_sdp(p, TRUE, FALSE);
29057 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
29058 ast_debug(3, "Deferring reinvite on SIP '%s' - It's UDPTL will be redirected to IP %s\n",
29059 p->callid, ast_sockaddr_stringify(udptl ? &p->udptlredirip : &p->ourip));
29060 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
29061 }
29062 }
29063
29064 p->lastrtprx = p->lastrtptx = time(NULL);
29065 sip_pvt_unlock(p);
29066 ast_channel_unlock(chan);
29067 return 0;
29068 }
29069
29070 static enum ast_rtp_glue_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
29071 {
29072 struct sip_pvt *p = NULL;
29073 enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_LOCAL;
29074
29075 if (!(p = chan->tech_pvt)) {
29076 return AST_RTP_GLUE_RESULT_FORBID;
29077 }
29078
29079 sip_pvt_lock(p);
29080 if (!(p->rtp)) {
29081 sip_pvt_unlock(p);
29082 return AST_RTP_GLUE_RESULT_FORBID;
29083 }
29084
29085 ao2_ref(p->rtp, +1);
29086 *instance = p->rtp;
29087
29088 if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
29089 res = AST_RTP_GLUE_RESULT_REMOTE;
29090 if (!apply_directmedia_ha(p, "audio")) {
29091 res = AST_RTP_GLUE_RESULT_FORBID;
29092 }
29093 } else if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA_NAT)) {
29094 res = AST_RTP_GLUE_RESULT_REMOTE;
29095 } else if (ast_test_flag(&global_jbconf, AST_JB_FORCED)) {
29096 res = AST_RTP_GLUE_RESULT_FORBID;
29097 }
29098
29099 if (p->srtp) {
29100 res = AST_RTP_GLUE_RESULT_FORBID;
29101 }
29102
29103 sip_pvt_unlock(p);
29104
29105 return res;
29106 }
29107
29108 static enum ast_rtp_glue_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
29109 {
29110 struct sip_pvt *p = NULL;
29111 enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_FORBID;
29112
29113 if (!(p = chan->tech_pvt)) {
29114 return AST_RTP_GLUE_RESULT_FORBID;
29115 }
29116
29117 sip_pvt_lock(p);
29118 if (!(p->vrtp)) {
29119 sip_pvt_unlock(p);
29120 return AST_RTP_GLUE_RESULT_FORBID;
29121 }
29122
29123 ao2_ref(p->vrtp, +1);
29124 *instance = p->vrtp;
29125
29126 if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
29127 res = AST_RTP_GLUE_RESULT_REMOTE;
29128 if (!apply_directmedia_ha(p, "video")) {
29129 res = AST_RTP_GLUE_RESULT_FORBID;
29130 }
29131 }
29132
29133 sip_pvt_unlock(p);
29134
29135 return res;
29136 }
29137
29138 static enum ast_rtp_glue_result sip_get_trtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
29139 {
29140 struct sip_pvt *p = NULL;
29141 enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_FORBID;
29142
29143 if (!(p = chan->tech_pvt)) {
29144 return AST_RTP_GLUE_RESULT_FORBID;
29145 }
29146
29147 sip_pvt_lock(p);
29148 if (!(p->trtp)) {
29149 sip_pvt_unlock(p);
29150 return AST_RTP_GLUE_RESULT_FORBID;
29151 }
29152
29153 ao2_ref(p->trtp, +1);
29154 *instance = p->trtp;
29155
29156 if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
29157 res = AST_RTP_GLUE_RESULT_REMOTE;
29158 if (!apply_directmedia_ha(p, "text")) {
29159 res = AST_RTP_GLUE_RESULT_FORBID;
29160 }
29161 }
29162
29163 sip_pvt_unlock(p);
29164
29165 return res;
29166 }
29167
29168 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)
29169 {
29170 struct sip_pvt *p;
29171 int changed = 0;
29172
29173
29174 ast_channel_lock(chan);
29175 p = chan->tech_pvt;
29176 if (!p) {
29177 ast_channel_unlock(chan);
29178 return -1;
29179 }
29180 sip_pvt_lock(p);
29181 if (p->owner != chan) {
29182
29183 ast_debug(1, "The private is not owned by channel %s anymore.\n", chan->name);
29184 sip_pvt_unlock(p);
29185 ast_channel_unlock(chan);
29186 return 0;
29187 }
29188
29189
29190 if ((instance || vinstance || tinstance) &&
29191 !ast_bridged_channel(chan) &&
29192 !sip_cfg.directrtpsetup) {
29193 sip_pvt_unlock(p);
29194 ast_channel_unlock(chan);
29195 return 0;
29196 }
29197
29198 if (p->alreadygone) {
29199
29200 sip_pvt_unlock(p);
29201 ast_channel_unlock(chan);
29202 return 0;
29203 }
29204
29205
29206
29207
29208 if (nat_active && !ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA_NAT)) {
29209 sip_pvt_unlock(p);
29210 ast_channel_unlock(chan);
29211 return 0;
29212 }
29213
29214 if (instance) {
29215 changed |= ast_rtp_instance_get_and_cmp_remote_address(instance, &p->redirip);
29216
29217 if (p->rtp) {
29218
29219 ast_channel_set_fd(chan, 1, -1);
29220
29221 ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_RTCP, 0);
29222 }
29223 } else if (!ast_sockaddr_isnull(&p->redirip)) {
29224 memset(&p->redirip, 0, sizeof(p->redirip));
29225 changed = 1;
29226
29227 if (p->rtp) {
29228
29229
29230 ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_RTCP, 1);
29231
29232 ast_channel_set_fd(chan, 1, ast_rtp_instance_fd(p->rtp, 1));
29233 }
29234 }
29235
29236 if (vinstance) {
29237 changed |= ast_rtp_instance_get_and_cmp_remote_address(vinstance, &p->vredirip);
29238
29239 if (p->vrtp) {
29240
29241 ast_channel_set_fd(chan, 3, -1);
29242
29243 ast_rtp_instance_set_prop(p->vrtp, AST_RTP_PROPERTY_RTCP, 0);
29244 }
29245 } else if (!ast_sockaddr_isnull(&p->vredirip)) {
29246 memset(&p->vredirip, 0, sizeof(p->vredirip));
29247 changed = 1;
29248
29249 if (p->vrtp) {
29250
29251
29252 ast_rtp_instance_set_prop(p->vrtp, AST_RTP_PROPERTY_RTCP, 1);
29253
29254 ast_channel_set_fd(chan, 3, ast_rtp_instance_fd(p->vrtp, 1));
29255 }
29256 }
29257
29258 if (tinstance) {
29259 changed |= ast_rtp_instance_get_and_cmp_remote_address(tinstance, &p->tredirip);
29260 } else if (!ast_sockaddr_isnull(&p->tredirip)) {
29261 memset(&p->tredirip, 0, sizeof(p->tredirip));
29262 changed = 1;
29263 }
29264 if (codecs && (p->redircodecs != codecs)) {
29265 p->redircodecs = codecs;
29266 changed = 1;
29267 }
29268 if (changed && !ast_test_flag(&p->flags[0], SIP_GOTREFER) && !ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
29269 if (chan->_state != AST_STATE_UP) {
29270 if (p->do_history)
29271 append_history(p, "ExtInv", "Initial invite sent with remote bridge proposal.");
29272 ast_debug(1, "Early remote bridge setting SIP '%s' - Sending media to %s\n", p->callid, ast_sockaddr_stringify(instance ? &p->redirip : &p->ourip));
29273 } else if (!p->pendinginvite) {
29274 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));
29275 transmit_reinvite_with_sdp(p, FALSE, FALSE);
29276 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
29277 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));
29278
29279 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
29280 }
29281 }
29282
29283 p->lastrtprx = p->lastrtptx = time(NULL);
29284 sip_pvt_unlock(p);
29285 ast_channel_unlock(chan);
29286 return 0;
29287 }
29288
29289 static format_t sip_get_codec(struct ast_channel *chan)
29290 {
29291 struct sip_pvt *p = chan->tech_pvt;
29292 return p->peercapability ? p->peercapability : p->capability;
29293 }
29294
29295 static struct ast_rtp_glue sip_rtp_glue = {
29296 .type = "SIP",
29297 .get_rtp_info = sip_get_rtp_peer,
29298 .get_vrtp_info = sip_get_vrtp_peer,
29299 .get_trtp_info = sip_get_trtp_peer,
29300 .update_peer = sip_set_rtp_peer,
29301 .get_codec = sip_get_codec,
29302 };
29303
29304 static char *app_dtmfmode = "SIPDtmfMode";
29305 static char *app_sipaddheader = "SIPAddHeader";
29306 static char *app_sipremoveheader = "SIPRemoveHeader";
29307
29308
29309 static int sip_dtmfmode(struct ast_channel *chan, const char *data)
29310 {
29311 struct sip_pvt *p;
29312 const char *mode = data;
29313
29314 if (!data) {
29315 ast_log(LOG_WARNING, "This application requires the argument: info, inband, rfc2833\n");
29316 return 0;
29317 }
29318 ast_channel_lock(chan);
29319 if (!IS_SIP_TECH(chan->tech)) {
29320 ast_log(LOG_WARNING, "Call this application only on SIP incoming calls\n");
29321 ast_channel_unlock(chan);
29322 return 0;
29323 }
29324 p = chan->tech_pvt;
29325 if (!p) {
29326 ast_channel_unlock(chan);
29327 return 0;
29328 }
29329 sip_pvt_lock(p);
29330 if (!strcasecmp(mode, "info")) {
29331 ast_clear_flag(&p->flags[0], SIP_DTMF);
29332 ast_set_flag(&p->flags[0], SIP_DTMF_INFO);
29333 p->jointnoncodeccapability &= ~AST_RTP_DTMF;
29334 } else if (!strcasecmp(mode, "shortinfo")) {
29335 ast_clear_flag(&p->flags[0], SIP_DTMF);
29336 ast_set_flag(&p->flags[0], SIP_DTMF_SHORTINFO);
29337 p->jointnoncodeccapability &= ~AST_RTP_DTMF;
29338 } else if (!strcasecmp(mode, "rfc2833")) {
29339 ast_clear_flag(&p->flags[0], SIP_DTMF);
29340 ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
29341 p->jointnoncodeccapability |= AST_RTP_DTMF;
29342 } else if (!strcasecmp(mode, "inband")) {
29343 ast_clear_flag(&p->flags[0], SIP_DTMF);
29344 ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
29345 p->jointnoncodeccapability &= ~AST_RTP_DTMF;
29346 } else {
29347 ast_log(LOG_WARNING, "I don't know about this dtmf mode: %s\n", mode);
29348 }
29349 if (p->rtp)
29350 ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
29351 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
29352 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
29353 enable_dsp_detect(p);
29354 } else {
29355 disable_dsp_detect(p);
29356 }
29357 sip_pvt_unlock(p);
29358 ast_channel_unlock(chan);
29359 return 0;
29360 }
29361
29362
29363 static int sip_addheader(struct ast_channel *chan, const char *data)
29364 {
29365 int no = 0;
29366 int ok = FALSE;
29367 char varbuf[30];
29368 const char *inbuf = data;
29369 char *subbuf;
29370
29371 if (ast_strlen_zero(inbuf)) {
29372 ast_log(LOG_WARNING, "This application requires the argument: Header\n");
29373 return 0;
29374 }
29375 ast_channel_lock(chan);
29376
29377
29378 while (!ok && no <= 50) {
29379 no++;
29380 snprintf(varbuf, sizeof(varbuf), "__SIPADDHEADER%.2d", no);
29381
29382
29383 if ((pbx_builtin_getvar_helper(chan, (const char *) varbuf + 2) == (const char *) NULL)) {
29384 ok = TRUE;
29385 }
29386 }
29387 if (ok) {
29388 size_t len = strlen(inbuf);
29389 subbuf = alloca(len + 1);
29390 ast_get_encoded_str(inbuf, subbuf, len + 1);
29391 pbx_builtin_setvar_helper(chan, varbuf, subbuf);
29392 if (sipdebug) {
29393 ast_debug(1, "SIP Header added \"%s\" as %s\n", inbuf, varbuf);
29394 }
29395 } else {
29396 ast_log(LOG_WARNING, "Too many SIP headers added, max 50\n");
29397 }
29398 ast_channel_unlock(chan);
29399 return 0;
29400 }
29401
29402
29403 static int sip_removeheader(struct ast_channel *chan, const char *data)
29404 {
29405 struct ast_var_t *newvariable;
29406 struct varshead *headp;
29407 int removeall = 0;
29408 char *inbuf = (char *) data;
29409
29410 if (ast_strlen_zero(inbuf)) {
29411 removeall = 1;
29412 }
29413 ast_channel_lock(chan);
29414
29415 headp=&chan->varshead;
29416 AST_LIST_TRAVERSE_SAFE_BEGIN (headp, newvariable, entries) {
29417 if (strncasecmp(ast_var_name(newvariable), "SIPADDHEADER", strlen("SIPADDHEADER")) == 0) {
29418 if (removeall || (!strncasecmp(ast_var_value(newvariable),inbuf,strlen(inbuf)))) {
29419 if (sipdebug)
29420 ast_debug(1,"removing SIP Header \"%s\" as %s\n",
29421 ast_var_value(newvariable),
29422 ast_var_name(newvariable));
29423 AST_LIST_REMOVE_CURRENT(entries);
29424 ast_var_delete(newvariable);
29425 }
29426 }
29427 }
29428 AST_LIST_TRAVERSE_SAFE_END;
29429
29430 ast_channel_unlock(chan);
29431 return 0;
29432 }
29433
29434
29435
29436
29437
29438
29439
29440 static int sip_sipredirect(struct sip_pvt *p, const char *dest)
29441 {
29442 char *cdest;
29443 char *extension, *domain;
29444
29445 cdest = ast_strdupa(dest);
29446
29447 extension = strsep(&cdest, "@");
29448 domain = cdest;
29449 if (ast_strlen_zero(extension)) {
29450 ast_log(LOG_ERROR, "Missing mandatory argument: extension\n");
29451 return 0;
29452 }
29453
29454
29455 if (!domain) {
29456 char *local_to_header;
29457 char to_header[256];
29458
29459 ast_copy_string(to_header, get_header(&p->initreq, "To"), sizeof(to_header));
29460 if (ast_strlen_zero(to_header)) {
29461 ast_log(LOG_ERROR, "Cannot retrieve the 'To' header from the original SIP request!\n");
29462 return 0;
29463 }
29464 if (((local_to_header = strcasestr(to_header, "sip:")) || (local_to_header = strcasestr(to_header, "sips:")))
29465 && (local_to_header = strchr(local_to_header, '@'))) {
29466 char ldomain[256];
29467
29468 memset(ldomain, 0, sizeof(ldomain));
29469 local_to_header++;
29470
29471 sscanf(local_to_header, "%256[^<>; ]", ldomain);
29472 if (ast_strlen_zero(ldomain)) {
29473 ast_log(LOG_ERROR, "Can't find the host address\n");
29474 return 0;
29475 }
29476 domain = ast_strdupa(ldomain);
29477 }
29478 }
29479
29480 ast_string_field_build(p, our_contact, "Transfer <sip:%s@%s>", extension, domain);
29481 transmit_response_reliable(p, "302 Moved Temporarily", &p->initreq);
29482
29483 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
29484 sip_alreadygone(p);
29485
29486 if (p->owner) {
29487 enum ast_control_transfer message = AST_TRANSFER_SUCCESS;
29488 ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
29489 }
29490
29491 return 0;
29492 }
29493
29494 static int sip_is_xml_parsable(void)
29495 {
29496 #ifdef HAVE_LIBXML2
29497 return TRUE;
29498 #else
29499 return FALSE;
29500 #endif
29501 }
29502
29503
29504 static void sip_poke_all_peers(void)
29505 {
29506 int ms = 0, num = 0;
29507 struct ao2_iterator i;
29508 struct sip_peer *peer;
29509
29510 if (!speerobjs) {
29511 return;
29512 }
29513
29514 i = ao2_iterator_init(peers, 0);
29515 while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
29516 ao2_lock(peer);
29517 if (num == global_qualify_peers) {
29518 ms += global_qualify_gap;
29519 num = 0;
29520 } else {
29521 num++;
29522 }
29523 AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, ms, sip_poke_peer_s, peer,
29524 unref_peer(_data, "removing poke peer ref"),
29525 unref_peer(peer, "removing poke peer ref"),
29526 ref_peer(peer, "adding poke peer ref"));
29527 ao2_unlock(peer);
29528 unref_peer(peer, "toss iterator peer ptr");
29529 }
29530 ao2_iterator_destroy(&i);
29531 }
29532
29533
29534 static void sip_send_all_registers(void)
29535 {
29536 int ms;
29537 int regspacing;
29538 if (!regobjs)
29539 return;
29540 regspacing = default_expiry * 1000/regobjs;
29541 if (regspacing > 100) {
29542 regspacing = 100;
29543 }
29544 ms = regspacing;
29545 ASTOBJ_CONTAINER_TRAVERSE(®l, 1, do {
29546 ASTOBJ_WRLOCK(iterator);
29547 ms += regspacing;
29548 AST_SCHED_REPLACE_UNREF(iterator->expire, sched, ms, sip_reregister, iterator,
29549 registry_unref(_data, "REPLACE sched del decs the refcount"),
29550 registry_unref(iterator, "REPLACE sched add failure decs the refcount"),
29551 registry_addref(iterator, "REPLACE sched add incs the refcount"));
29552 ASTOBJ_UNLOCK(iterator);
29553 } while (0)
29554 );
29555 }
29556
29557
29558 static void sip_send_all_mwi_subscriptions(void)
29559 {
29560 ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
29561 struct sip_subscription_mwi *saved;
29562 ASTOBJ_WRLOCK(iterator);
29563 AST_SCHED_DEL(sched, iterator->resub);
29564 saved = ASTOBJ_REF(iterator);
29565 if ((iterator->resub = ast_sched_add(sched, 1, sip_subscribe_mwi_do, saved)) < 0) {
29566 ASTOBJ_UNREF(saved, sip_subscribe_mwi_destroy);
29567 }
29568 ASTOBJ_UNLOCK(iterator);
29569 } while (0));
29570 }
29571
29572
29573 static int setup_srtp(struct sip_srtp **srtp)
29574 {
29575 if (!ast_rtp_engine_srtp_is_registered()) {
29576 ast_log(LOG_ERROR, "No SRTP module loaded, can't setup SRTP session.\n");
29577 return -1;
29578 }
29579
29580 if (!(*srtp = sip_srtp_alloc())) {
29581 return -1;
29582 }
29583
29584 return 0;
29585 }
29586
29587 static int process_crypto(struct sip_pvt *p, struct ast_rtp_instance *rtp, struct sip_srtp **srtp, const char *a)
29588 {
29589
29590 if (!rtp) {
29591 ast_debug(3, "Received offer with crypto line for media stream that is not enabled\n");
29592 return FALSE;
29593 }
29594
29595 if (strncasecmp(a, "crypto:", 7)) {
29596 return FALSE;
29597 }
29598 if (!*srtp) {
29599 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
29600 ast_log(LOG_WARNING, "Ignoring unexpected crypto attribute in SDP answer\n");
29601 return FALSE;
29602 }
29603
29604 if (setup_srtp(srtp) < 0) {
29605 return FALSE;
29606 }
29607 }
29608
29609
29610 if ((*srtp)->crypto && !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
29611 ast_debug(3, "We've already processed a crypto attribute, skipping '%s'\n", a);
29612 return FALSE;
29613 }
29614
29615 if (!(*srtp)->crypto && !((*srtp)->crypto = sdp_crypto_setup())) {
29616 return FALSE;
29617 }
29618
29619 if (sdp_crypto_process((*srtp)->crypto, a, rtp) < 0) {
29620 return FALSE;
29621 }
29622
29623 ast_set_flag(*srtp, SRTP_CRYPTO_OFFER_OK);
29624
29625 return TRUE;
29626 }
29627
29628
29629 static int sip_do_reload(enum channelreloadreason reason)
29630 {
29631 time_t start_poke, end_poke;
29632
29633 reload_config(reason);
29634 ast_sched_dump(sched);
29635
29636 start_poke = time(0);
29637
29638 unlink_marked_peers_from_tables();
29639
29640 ast_debug(4, "--------------- Done destroying pruned peers\n");
29641
29642
29643 sip_poke_all_peers();
29644
29645
29646 sip_send_all_registers();
29647
29648 sip_send_all_mwi_subscriptions();
29649
29650 end_poke = time(0);
29651
29652 ast_debug(4, "do_reload finished. peer poke/prune reg contact time = %d sec.\n", (int)(end_poke-start_poke));
29653
29654 ast_debug(4, "--------------- SIP reload done\n");
29655
29656 return 0;
29657 }
29658
29659
29660 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
29661 {
29662
29663 switch (cmd) {
29664 case CLI_INIT:
29665 e->command = "sip reload";
29666 e->usage =
29667 "Usage: sip reload\n"
29668 " Reloads SIP configuration from sip.conf\n";
29669 return NULL;
29670 case CLI_GENERATE:
29671 return NULL;
29672 }
29673
29674 ast_mutex_lock(&sip_reload_lock);
29675 if (sip_reloading) {
29676 ast_verbose("Previous SIP reload not yet done\n");
29677 } else {
29678 sip_reloading = TRUE;
29679 sip_reloadreason = (a && a->fd) ? CHANNEL_CLI_RELOAD : CHANNEL_MODULE_RELOAD;
29680 }
29681 ast_mutex_unlock(&sip_reload_lock);
29682 restart_monitor();
29683
29684 return CLI_SUCCESS;
29685 }
29686
29687
29688 static int reload(void)
29689 {
29690 if (sip_reload(0, 0, NULL))
29691 return 0;
29692 return 1;
29693 }
29694
29695
29696
29697
29698
29699 static int ast_sockaddr_resolve_first_af(struct ast_sockaddr *addr,
29700 const char* name, int flag, int family)
29701 {
29702 struct ast_sockaddr *addrs;
29703 int addrs_cnt;
29704
29705 addrs_cnt = ast_sockaddr_resolve(&addrs, name, flag, family);
29706 if (addrs_cnt <= 0) {
29707 return 1;
29708 }
29709 if (addrs_cnt > 1) {
29710 ast_debug(1, "Multiple addresses, using the first one only\n");
29711 }
29712
29713 ast_sockaddr_copy(addr, &addrs[0]);
29714
29715 ast_free(addrs);
29716 return 0;
29717 }
29718
29719
29720
29721
29722
29723 static int ast_sockaddr_resolve_first(struct ast_sockaddr *addr,
29724 const char* name, int flag)
29725 {
29726 return ast_sockaddr_resolve_first_af(addr, name, flag, get_address_family_filter(&bindaddr));
29727 }
29728
29729
29730
29731
29732 static int peer_hash_cb(const void *obj, const int flags)
29733 {
29734 const struct sip_peer *peer = obj;
29735
29736 return ast_str_case_hash(peer->name);
29737 }
29738
29739
29740
29741
29742 static int peer_cmp_cb(void *obj, void *arg, int flags)
29743 {
29744 struct sip_peer *peer = obj, *peer2 = arg;
29745
29746 return !strcasecmp(peer->name, peer2->name) ? CMP_MATCH | CMP_STOP : 0;
29747 }
29748
29749
29750
29751
29752
29753
29754 static int peer_iphash_cb(const void *obj, const int flags)
29755 {
29756 const struct sip_peer *peer = obj;
29757 int ret = 0;
29758
29759 if (ast_sockaddr_isnull(&peer->addr)) {
29760 ast_log(LOG_ERROR, "Empty address\n");
29761 }
29762
29763 ret = ast_sockaddr_hash(&peer->addr);
29764
29765 if (ret < 0) {
29766 ret = -ret;
29767 }
29768
29769 return ret;
29770 }
29771
29772
29773
29774
29775
29776
29777
29778
29779
29780
29781
29782
29783
29784
29785
29786
29787
29788
29789
29790 static int peer_ipcmp_cb(void *obj, void *arg, int flags)
29791 {
29792 struct sip_peer *peer = obj, *peer2 = arg;
29793
29794 if (ast_sockaddr_cmp_addr(&peer->addr, &peer2->addr)) {
29795
29796 return 0;
29797 }
29798
29799
29800 if ((peer->transports & peer2->transports) & (SIP_TRANSPORT_TLS | SIP_TRANSPORT_TCP)) {
29801
29802 return CMP_MATCH | CMP_STOP;
29803 } else if (ast_test_flag(&peer2->flags[0], SIP_INSECURE_PORT)) {
29804
29805
29806 return ast_test_flag(&peer->flags[0], SIP_INSECURE_PORT) ?
29807 (CMP_MATCH | CMP_STOP) : 0;
29808 }
29809
29810
29811 return ast_sockaddr_port(&peer->addr) == ast_sockaddr_port(&peer2->addr) ?
29812 (CMP_MATCH | CMP_STOP) : 0;
29813 }
29814
29815
29816 static int threadt_hash_cb(const void *obj, const int flags)
29817 {
29818 const struct sip_threadinfo *th = obj;
29819
29820 return ast_sockaddr_hash(&th->tcptls_session->remote_address);
29821 }
29822
29823 static int threadt_cmp_cb(void *obj, void *arg, int flags)
29824 {
29825 struct sip_threadinfo *th = obj, *th2 = arg;
29826
29827 return (th->tcptls_session == th2->tcptls_session) ? CMP_MATCH | CMP_STOP : 0;
29828 }
29829
29830
29831
29832
29833 static int dialog_hash_cb(const void *obj, const int flags)
29834 {
29835 const struct sip_pvt *pvt = obj;
29836
29837 return ast_str_case_hash(pvt->callid);
29838 }
29839
29840
29841
29842
29843 static int dialog_find_multiple(void *obj, void *arg, int flags)
29844 {
29845 struct sip_pvt *pvt = obj, *pvt2 = arg;
29846
29847 return !strcasecmp(pvt->callid, pvt2->callid) ? CMP_MATCH : 0;
29848 }
29849
29850
29851
29852
29853 static int dialog_cmp_cb(void *obj, void *arg, int flags)
29854 {
29855 struct sip_pvt *pvt = obj, *pvt2 = arg;
29856
29857 return !strcasecmp(pvt->callid, pvt2->callid) ? CMP_MATCH | CMP_STOP : 0;
29858 }
29859
29860
29861 static struct ast_cli_entry cli_sip[] = {
29862 AST_CLI_DEFINE(sip_show_channels, "List active SIP channels or subscriptions"),
29863 AST_CLI_DEFINE(sip_show_channelstats, "List statistics for active SIP channels"),
29864 AST_CLI_DEFINE(sip_show_domains, "List our local SIP domains"),
29865 AST_CLI_DEFINE(sip_show_inuse, "List all inuse/limits"),
29866 AST_CLI_DEFINE(sip_show_objects, "List all SIP object allocations"),
29867 AST_CLI_DEFINE(sip_show_peers, "List defined SIP peers"),
29868 AST_CLI_DEFINE(sip_show_registry, "List SIP registration status"),
29869 AST_CLI_DEFINE(sip_unregister, "Unregister (force expiration) a SIP peer from the registry"),
29870 AST_CLI_DEFINE(sip_show_settings, "Show SIP global settings"),
29871 AST_CLI_DEFINE(sip_show_mwi, "Show MWI subscriptions"),
29872 AST_CLI_DEFINE(sip_cli_notify, "Send a notify packet to a SIP peer"),
29873 AST_CLI_DEFINE(sip_show_channel, "Show detailed SIP channel info"),
29874 AST_CLI_DEFINE(sip_show_history, "Show SIP dialog history"),
29875 AST_CLI_DEFINE(sip_show_peer, "Show details on specific SIP peer"),
29876 AST_CLI_DEFINE(sip_show_users, "List defined SIP users"),
29877 AST_CLI_DEFINE(sip_show_user, "Show details on specific SIP user"),
29878 AST_CLI_DEFINE(sip_qualify_peer, "Send an OPTIONS packet to a peer"),
29879 AST_CLI_DEFINE(sip_show_sched, "Present a report on the status of the scheduler queue"),
29880 AST_CLI_DEFINE(sip_prune_realtime, "Prune cached Realtime users/peers"),
29881 AST_CLI_DEFINE(sip_do_debug, "Enable/Disable SIP debugging"),
29882 AST_CLI_DEFINE(sip_set_history, "Enable/Disable SIP history"),
29883 AST_CLI_DEFINE(sip_reload, "Reload SIP configuration"),
29884 AST_CLI_DEFINE(sip_show_tcp, "List TCP Connections")
29885 };
29886
29887
29888 static void sip_register_tests(void)
29889 {
29890 sip_config_parser_register_tests();
29891 sip_request_parser_register_tests();
29892 sip_dialplan_function_register_tests();
29893 }
29894
29895
29896 static void sip_unregister_tests(void)
29897 {
29898 sip_config_parser_unregister_tests();
29899 sip_request_parser_unregister_tests();
29900 sip_dialplan_function_unregister_tests();
29901 }
29902
29903 #ifdef TEST_FRAMEWORK
29904 AST_TEST_DEFINE(test_sip_mwi_subscribe_parse)
29905 {
29906 int found = 0;
29907 enum ast_test_result_state res = AST_TEST_PASS;
29908 const char *mwi1 = "1234@mysipprovider.com/1234";
29909 const char *mwi2 = "1234:password@mysipprovider.com/1234";
29910 const char *mwi3 = "1234:password@mysipprovider.com:5061/1234";
29911 const char *mwi4 = "1234:password:authuser@mysipprovider.com/1234";
29912 const char *mwi5 = "1234:password:authuser@mysipprovider.com:5061/1234";
29913 const char *mwi6 = "1234:password";
29914
29915 switch (cmd) {
29916 case TEST_INIT:
29917 info->name = "sip_mwi_subscribe_parse_test";
29918 info->category = "/channels/chan_sip/";
29919 info->summary = "SIP MWI subscribe line parse unit test";
29920 info->description =
29921 "Tests the parsing of mwi subscription lines (e.g., mwi => from sip.conf)";
29922 return AST_TEST_NOT_RUN;
29923 case TEST_EXECUTE:
29924 break;
29925 }
29926
29927 if (sip_subscribe_mwi(mwi1, 1)) {
29928 res = AST_TEST_FAIL;
29929 } else {
29930 found = 0;
29931 res = AST_TEST_FAIL;
29932 ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
29933 ASTOBJ_WRLOCK(iterator);
29934 if (
29935 !strcmp(iterator->hostname, "mysipprovider.com") &&
29936 !strcmp(iterator->username, "1234") &&
29937 !strcmp(iterator->secret, "") &&
29938 !strcmp(iterator->authuser, "") &&
29939 !strcmp(iterator->mailbox, "1234") &&
29940 iterator->portno == 0) {
29941 found = 1;
29942 res = AST_TEST_PASS;
29943 }
29944 ASTOBJ_UNLOCK(iterator);
29945 } while(0));
29946 if (!found) {
29947 ast_test_status_update(test, "sip_subscribe_mwi test 1 failed\n");
29948 }
29949 }
29950
29951 if (sip_subscribe_mwi(mwi2, 1)) {
29952 res = AST_TEST_FAIL;
29953 } else {
29954 found = 0;
29955 res = AST_TEST_FAIL;
29956 ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
29957 ASTOBJ_WRLOCK(iterator);
29958 if (
29959 !strcmp(iterator->hostname, "mysipprovider.com") &&
29960 !strcmp(iterator->username, "1234") &&
29961 !strcmp(iterator->secret, "password") &&
29962 !strcmp(iterator->authuser, "") &&
29963 !strcmp(iterator->mailbox, "1234") &&
29964 iterator->portno == 0) {
29965 found = 1;
29966 res = AST_TEST_PASS;
29967 }
29968 ASTOBJ_UNLOCK(iterator);
29969 } while(0));
29970 if (!found) {
29971 ast_test_status_update(test, "sip_subscribe_mwi test 2 failed\n");
29972 }
29973 }
29974
29975 if (sip_subscribe_mwi(mwi3, 1)) {
29976 res = AST_TEST_FAIL;
29977 } else {
29978 found = 0;
29979 res = AST_TEST_FAIL;
29980 ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
29981 ASTOBJ_WRLOCK(iterator);
29982 if (
29983 !strcmp(iterator->hostname, "mysipprovider.com") &&
29984 !strcmp(iterator->username, "1234") &&
29985 !strcmp(iterator->secret, "password") &&
29986 !strcmp(iterator->authuser, "") &&
29987 !strcmp(iterator->mailbox, "1234") &&
29988 iterator->portno == 5061) {
29989 found = 1;
29990 res = AST_TEST_PASS;
29991 }
29992 ASTOBJ_UNLOCK(iterator);
29993 } while(0));
29994 if (!found) {
29995 ast_test_status_update(test, "sip_subscribe_mwi test 3 failed\n");
29996 }
29997 }
29998
29999 if (sip_subscribe_mwi(mwi4, 1)) {
30000 res = AST_TEST_FAIL;
30001 } else {
30002 found = 0;
30003 res = AST_TEST_FAIL;
30004 ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
30005 ASTOBJ_WRLOCK(iterator);
30006 if (
30007 !strcmp(iterator->hostname, "mysipprovider.com") &&
30008 !strcmp(iterator->username, "1234") &&
30009 !strcmp(iterator->secret, "password") &&
30010 !strcmp(iterator->authuser, "authuser") &&
30011 !strcmp(iterator->mailbox, "1234") &&
30012 iterator->portno == 0) {
30013 found = 1;
30014 res = AST_TEST_PASS;
30015 }
30016 ASTOBJ_UNLOCK(iterator);
30017 } while(0));
30018 if (!found) {
30019 ast_test_status_update(test, "sip_subscribe_mwi test 4 failed\n");
30020 }
30021 }
30022
30023 if (sip_subscribe_mwi(mwi5, 1)) {
30024 res = AST_TEST_FAIL;
30025 } else {
30026 found = 0;
30027 res = AST_TEST_FAIL;
30028 ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
30029 ASTOBJ_WRLOCK(iterator);
30030 if (
30031 !strcmp(iterator->hostname, "mysipprovider.com") &&
30032 !strcmp(iterator->username, "1234") &&
30033 !strcmp(iterator->secret, "password") &&
30034 !strcmp(iterator->authuser, "authuser") &&
30035 !strcmp(iterator->mailbox, "1234") &&
30036 iterator->portno == 5061) {
30037 found = 1;
30038 res = AST_TEST_PASS;
30039 }
30040 ASTOBJ_UNLOCK(iterator);
30041 } while(0));
30042 if (!found) {
30043 ast_test_status_update(test, "sip_subscribe_mwi test 5 failed\n");
30044 }
30045 }
30046
30047 if (sip_subscribe_mwi(mwi6, 1)) {
30048 res = AST_TEST_PASS;
30049 } else {
30050 res = AST_TEST_FAIL;
30051 }
30052 return res;
30053 }
30054
30055 AST_TEST_DEFINE(test_sip_peers_get)
30056 {
30057 struct sip_peer *peer;
30058 struct ast_data *node;
30059 struct ast_data_query query = {
30060 .path = "/asterisk/channel/sip/peers",
30061 .search = "peers/peer/name=test_peer_data_provider"
30062 };
30063
30064 switch (cmd) {
30065 case TEST_INIT:
30066 info->name = "sip_peers_get_data_test";
30067 info->category = "/main/data/sip/peers/";
30068 info->summary = "SIP peers data providers unit test";
30069 info->description =
30070 "Tests whether the SIP peers data provider implementation works as expected.";
30071 return AST_TEST_NOT_RUN;
30072 case TEST_EXECUTE:
30073 break;
30074 }
30075
30076
30077 peer = build_peer("test_peer_data_provider", NULL, NULL, 0, 0);
30078 if (!peer) {
30079 return AST_TEST_FAIL;
30080 }
30081 peer->type = SIP_TYPE_USER;
30082 peer->call_limit = 10;
30083 ao2_link(peers, peer);
30084
30085
30086 node = ast_data_get(&query);
30087 if (!node) {
30088 ao2_unlink(peers, peer);
30089 ao2_ref(peer, -1);
30090 return AST_TEST_FAIL;
30091 }
30092
30093
30094 if (strcmp(ast_data_retrieve_string(node, "peer/name"), "test_peer_data_provider")) {
30095 ao2_unlink(peers, peer);
30096 ao2_ref(peer, -1);
30097 ast_data_free(node);
30098 return AST_TEST_FAIL;
30099 }
30100
30101 if (strcmp(ast_data_retrieve_string(node, "peer/type"), "user")) {
30102 ao2_unlink(peers, peer);
30103 ao2_ref(peer, -1);
30104 ast_data_free(node);
30105 return AST_TEST_FAIL;
30106 }
30107
30108 if (ast_data_retrieve_int(node, "peer/call_limit") != 10) {
30109 ao2_unlink(peers, peer);
30110 ao2_ref(peer, -1);
30111 ast_data_free(node);
30112 return AST_TEST_FAIL;
30113 }
30114
30115
30116 ast_data_free(node);
30117
30118 ao2_unlink(peers, peer);
30119 ao2_ref(peer, -1);
30120
30121 return AST_TEST_PASS;
30122 }
30123
30124 #endif
30125
30126 #define DATA_EXPORT_SIP_PEER(MEMBER) \
30127 MEMBER(sip_peer, name, AST_DATA_STRING) \
30128 MEMBER(sip_peer, secret, AST_DATA_PASSWORD) \
30129 MEMBER(sip_peer, md5secret, AST_DATA_PASSWORD) \
30130 MEMBER(sip_peer, remotesecret, AST_DATA_PASSWORD) \
30131 MEMBER(sip_peer, context, AST_DATA_STRING) \
30132 MEMBER(sip_peer, subscribecontext, AST_DATA_STRING) \
30133 MEMBER(sip_peer, username, AST_DATA_STRING) \
30134 MEMBER(sip_peer, accountcode, AST_DATA_STRING) \
30135 MEMBER(sip_peer, tohost, AST_DATA_STRING) \
30136 MEMBER(sip_peer, regexten, AST_DATA_STRING) \
30137 MEMBER(sip_peer, fromuser, AST_DATA_STRING) \
30138 MEMBER(sip_peer, fromdomain, AST_DATA_STRING) \
30139 MEMBER(sip_peer, fullcontact, AST_DATA_STRING) \
30140 MEMBER(sip_peer, cid_num, AST_DATA_STRING) \
30141 MEMBER(sip_peer, cid_name, AST_DATA_STRING) \
30142 MEMBER(sip_peer, vmexten, AST_DATA_STRING) \
30143 MEMBER(sip_peer, language, AST_DATA_STRING) \
30144 MEMBER(sip_peer, mohinterpret, AST_DATA_STRING) \
30145 MEMBER(sip_peer, mohsuggest, AST_DATA_STRING) \
30146 MEMBER(sip_peer, parkinglot, AST_DATA_STRING) \
30147 MEMBER(sip_peer, useragent, AST_DATA_STRING) \
30148 MEMBER(sip_peer, mwi_from, AST_DATA_STRING) \
30149 MEMBER(sip_peer, engine, AST_DATA_STRING) \
30150 MEMBER(sip_peer, unsolicited_mailbox, AST_DATA_STRING) \
30151 MEMBER(sip_peer, is_realtime, AST_DATA_BOOLEAN) \
30152 MEMBER(sip_peer, host_dynamic, AST_DATA_BOOLEAN) \
30153 MEMBER(sip_peer, autoframing, AST_DATA_BOOLEAN) \
30154 MEMBER(sip_peer, inUse, AST_DATA_INTEGER) \
30155 MEMBER(sip_peer, inRinging, AST_DATA_INTEGER) \
30156 MEMBER(sip_peer, onHold, AST_DATA_INTEGER) \
30157 MEMBER(sip_peer, call_limit, AST_DATA_INTEGER) \
30158 MEMBER(sip_peer, t38_maxdatagram, AST_DATA_INTEGER) \
30159 MEMBER(sip_peer, maxcallbitrate, AST_DATA_INTEGER) \
30160 MEMBER(sip_peer, rtptimeout, AST_DATA_SECONDS) \
30161 MEMBER(sip_peer, rtpholdtimeout, AST_DATA_SECONDS) \
30162 MEMBER(sip_peer, rtpkeepalive, AST_DATA_SECONDS) \
30163 MEMBER(sip_peer, lastms, AST_DATA_MILLISECONDS) \
30164 MEMBER(sip_peer, maxms, AST_DATA_MILLISECONDS) \
30165 MEMBER(sip_peer, qualifyfreq, AST_DATA_MILLISECONDS) \
30166 MEMBER(sip_peer, timer_t1, AST_DATA_MILLISECONDS) \
30167 MEMBER(sip_peer, timer_b, AST_DATA_MILLISECONDS)
30168
30169 AST_DATA_STRUCTURE(sip_peer, DATA_EXPORT_SIP_PEER);
30170
30171 static int peers_data_provider_get(const struct ast_data_search *search,
30172 struct ast_data *data_root)
30173 {
30174 struct sip_peer *peer;
30175 struct ao2_iterator i;
30176 struct ast_data *data_peer, *data_peer_mailboxes = NULL, *data_peer_mailbox, *enum_node;
30177 struct ast_data *data_sip_options;
30178 int total_mailboxes, x;
30179 struct sip_mailbox *mailbox;
30180
30181 i = ao2_iterator_init(peers, 0);
30182 while ((peer = ao2_iterator_next(&i))) {
30183 ao2_lock(peer);
30184
30185 data_peer = ast_data_add_node(data_root, "peer");
30186 if (!data_peer) {
30187 ao2_unlock(peer);
30188 ao2_ref(peer, -1);
30189 continue;
30190 }
30191
30192 ast_data_add_structure(sip_peer, data_peer, peer);
30193
30194
30195 enum_node = ast_data_add_node(data_peer, "allowtransfer");
30196 if (!enum_node) {
30197 ao2_unlock(peer);
30198 ao2_ref(peer, -1);
30199 continue;
30200 }
30201 ast_data_add_str(enum_node, "text", transfermode2str(peer->allowtransfer));
30202 ast_data_add_int(enum_node, "value", peer->allowtransfer);
30203
30204
30205 ast_data_add_str(data_peer, "transports", get_transport_list(peer->transports));
30206
30207
30208 if ((peer->type & SIP_TYPE_USER) && (peer->type & SIP_TYPE_PEER)) {
30209 ast_data_add_str(data_peer, "type", "friend");
30210 } else if (peer->type & SIP_TYPE_PEER) {
30211 ast_data_add_str(data_peer, "type", "peer");
30212 } else if (peer->type & SIP_TYPE_USER) {
30213 ast_data_add_str(data_peer, "type", "user");
30214 }
30215
30216
30217 total_mailboxes = 0;
30218 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
30219 if (!total_mailboxes) {
30220 data_peer_mailboxes = ast_data_add_node(data_peer, "mailboxes");
30221 if (!data_peer_mailboxes) {
30222 break;
30223 }
30224 total_mailboxes++;
30225 }
30226
30227 data_peer_mailbox = ast_data_add_node(data_peer_mailboxes, "mailbox");
30228 if (!data_peer_mailbox) {
30229 continue;
30230 }
30231 ast_data_add_str(data_peer_mailbox, "mailbox", mailbox->mailbox);
30232 ast_data_add_str(data_peer_mailbox, "context", mailbox->context);
30233 }
30234
30235
30236 enum_node = ast_data_add_node(data_peer, "amaflags");
30237 if (!enum_node) {
30238 ao2_unlock(peer);
30239 ao2_ref(peer, -1);
30240 continue;
30241 }
30242 ast_data_add_int(enum_node, "value", peer->amaflags);
30243 ast_data_add_str(enum_node, "text", ast_cdr_flags2str(peer->amaflags));
30244
30245
30246 data_sip_options = ast_data_add_node(data_peer, "sipoptions");
30247 if (!data_sip_options) {
30248 ao2_unlock(peer);
30249 ao2_ref(peer, -1);
30250 continue;
30251 }
30252 for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
30253 ast_data_add_bool(data_sip_options, sip_options[x].text, peer->sipoptions & sip_options[x].id);
30254 }
30255
30256
30257 enum_node = ast_data_add_node(data_peer, "callingpres");
30258 if (!enum_node) {
30259 ao2_unlock(peer);
30260 ao2_ref(peer, -1);
30261 continue;
30262 }
30263 ast_data_add_int(enum_node, "value", peer->callingpres);
30264 ast_data_add_str(enum_node, "text", ast_describe_caller_presentation(peer->callingpres));
30265
30266
30267 ast_data_add_codecs(data_peer, "codecs", peer->capability);
30268
30269 if (!ast_data_search_match(search, data_peer)) {
30270 ast_data_remove_node(data_root, data_peer);
30271 }
30272
30273 ao2_unlock(peer);
30274 ao2_ref(peer, -1);
30275 }
30276 ao2_iterator_destroy(&i);
30277
30278 return 0;
30279 }
30280
30281 static const struct ast_data_handler peers_data_provider = {
30282 .version = AST_DATA_HANDLER_VERSION,
30283 .get = peers_data_provider_get
30284 };
30285
30286 static const struct ast_data_entry sip_data_providers[] = {
30287 AST_DATA_ENTRY("asterisk/channel/sip/peers", &peers_data_provider),
30288 };
30289
30290
30291 static int load_module(void)
30292 {
30293 ast_verbose("SIP channel loading...\n");
30294
30295
30296
30297 peers = ao2_t_container_alloc(HASH_PEER_SIZE, peer_hash_cb, peer_cmp_cb, "allocate peers");
30298 peers_by_ip = ao2_t_container_alloc(HASH_PEER_SIZE, peer_iphash_cb, peer_ipcmp_cb, "allocate peers_by_ip");
30299 dialogs = ao2_t_container_alloc(HASH_DIALOG_SIZE, dialog_hash_cb, dialog_cmp_cb, "allocate dialogs");
30300 dialogs_to_destroy = ao2_t_container_alloc(1, NULL, NULL, "allocate dialogs_to_destroy");
30301 threadt = ao2_t_container_alloc(HASH_DIALOG_SIZE, threadt_hash_cb, threadt_cmp_cb, "allocate threadt table");
30302 if (!peers || !peers_by_ip || !dialogs || !dialogs_to_destroy || !threadt) {
30303 ast_log(LOG_ERROR, "Unable to create primary SIP container(s)\n");
30304 return AST_MODULE_LOAD_FAILURE;
30305 }
30306
30307 ASTOBJ_CONTAINER_INIT(®l);
30308 ASTOBJ_CONTAINER_INIT(&submwil);
30309
30310 if (!(sched = sched_context_create())) {
30311 ast_log(LOG_ERROR, "Unable to create scheduler context\n");
30312 return AST_MODULE_LOAD_FAILURE;
30313 }
30314
30315 if (!(io = io_context_create())) {
30316 ast_log(LOG_ERROR, "Unable to create I/O context\n");
30317 sched_context_destroy(sched);
30318 return AST_MODULE_LOAD_FAILURE;
30319 }
30320
30321 sip_reloadreason = CHANNEL_MODULE_LOAD;
30322
30323 can_parse_xml = sip_is_xml_parsable();
30324 if (reload_config(sip_reloadreason)) {
30325 return AST_MODULE_LOAD_DECLINE;
30326 }
30327
30328
30329
30330
30331
30332 memcpy(&sip_tech_info, &sip_tech, sizeof(sip_tech));
30333 memset((void *) &sip_tech_info.send_digit_begin, 0, sizeof(sip_tech_info.send_digit_begin));
30334
30335
30336 if (ast_channel_register(&sip_tech)) {
30337 ast_log(LOG_ERROR, "Unable to register channel type 'SIP'\n");
30338 io_context_destroy(io);
30339 sched_context_destroy(sched);
30340 return AST_MODULE_LOAD_FAILURE;
30341 }
30342
30343 #ifdef TEST_FRAMEWORK
30344 AST_TEST_REGISTER(test_sip_peers_get);
30345 AST_TEST_REGISTER(test_sip_mwi_subscribe_parse);
30346 #endif
30347
30348
30349 ast_data_register_multiple(sip_data_providers, ARRAY_LEN(sip_data_providers));
30350
30351
30352 ast_cli_register_multiple(cli_sip, ARRAY_LEN(cli_sip));
30353
30354
30355 ast_udptl_proto_register(&sip_udptl);
30356
30357
30358 ast_rtp_glue_register(&sip_rtp_glue);
30359
30360
30361 ast_register_application_xml(app_dtmfmode, sip_dtmfmode);
30362 ast_register_application_xml(app_sipaddheader, sip_addheader);
30363 ast_register_application_xml(app_sipremoveheader, sip_removeheader);
30364
30365
30366 ast_custom_function_register(&sip_header_function);
30367 ast_custom_function_register(&sippeer_function);
30368 ast_custom_function_register(&sipchaninfo_function);
30369 ast_custom_function_register(&checksipdomain_function);
30370
30371
30372 ast_manager_register_xml("SIPpeers", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peers);
30373 ast_manager_register_xml("SIPshowpeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peer);
30374 ast_manager_register_xml("SIPqualifypeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_qualify_peer);
30375 ast_manager_register_xml("SIPshowregistry", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_show_registry);
30376 ast_manager_register_xml("SIPnotify", EVENT_FLAG_SYSTEM, manager_sipnotify);
30377 sip_poke_all_peers();
30378 sip_send_all_registers();
30379 sip_send_all_mwi_subscriptions();
30380 initialize_escs();
30381
30382 if (sip_epa_register(&cc_epa_static_data)) {
30383 return AST_MODULE_LOAD_DECLINE;
30384 }
30385
30386 if (sip_reqresp_parser_init() == -1) {
30387 ast_log(LOG_ERROR, "Unable to initialize the SIP request and response parser\n");
30388 return AST_MODULE_LOAD_DECLINE;
30389 }
30390
30391 if (can_parse_xml) {
30392
30393
30394
30395 if (ast_cc_agent_register(&sip_cc_agent_callbacks)) {
30396 return AST_MODULE_LOAD_DECLINE;
30397 }
30398 }
30399 if (ast_cc_monitor_register(&sip_cc_monitor_callbacks)) {
30400 return AST_MODULE_LOAD_DECLINE;
30401 }
30402 if (!(sip_monitor_instances = ao2_container_alloc(37, sip_monitor_instance_hash_fn, sip_monitor_instance_cmp_fn))) {
30403 return AST_MODULE_LOAD_DECLINE;
30404 }
30405
30406
30407 restart_monitor();
30408
30409 ast_realtime_require_field(ast_check_realtime("sipregs") ? "sipregs" : "sippeers",
30410 "name", RQ_CHAR, 10,
30411 "ipaddr", RQ_CHAR, INET6_ADDRSTRLEN - 1,
30412 "port", RQ_UINTEGER2, 5,
30413 "regseconds", RQ_INTEGER4, 11,
30414 "defaultuser", RQ_CHAR, 10,
30415 "fullcontact", RQ_CHAR, 35,
30416 "regserver", RQ_CHAR, 20,
30417 "useragent", RQ_CHAR, 20,
30418 "lastms", RQ_INTEGER4, 11,
30419 SENTINEL);
30420
30421
30422 sip_register_tests();
30423 network_change_event_subscribe();
30424
30425 return AST_MODULE_LOAD_SUCCESS;
30426 }
30427
30428
30429 static int unload_module(void)
30430 {
30431 struct sip_pvt *p;
30432 struct sip_threadinfo *th;
30433 struct ast_context *con;
30434 struct ao2_iterator i;
30435 int wait_count;
30436
30437 network_change_event_unsubscribe();
30438
30439 ast_sched_dump(sched);
30440
30441
30442 ast_channel_unregister(&sip_tech);
30443
30444
30445 ast_custom_function_unregister(&sipchaninfo_function);
30446 ast_custom_function_unregister(&sippeer_function);
30447 ast_custom_function_unregister(&sip_header_function);
30448 ast_custom_function_unregister(&checksipdomain_function);
30449
30450
30451 ast_unregister_application(app_dtmfmode);
30452 ast_unregister_application(app_sipaddheader);
30453 ast_unregister_application(app_sipremoveheader);
30454
30455 #ifdef TEST_FRAMEWORK
30456 AST_TEST_UNREGISTER(test_sip_peers_get);
30457 AST_TEST_UNREGISTER(test_sip_mwi_subscribe_parse);
30458 #endif
30459
30460 ast_data_unregister(NULL);
30461
30462
30463 ast_cli_unregister_multiple(cli_sip, ARRAY_LEN(cli_sip));
30464
30465
30466 ast_udptl_proto_unregister(&sip_udptl);
30467
30468
30469 ast_rtp_glue_unregister(&sip_rtp_glue);
30470
30471
30472 ast_manager_unregister("SIPpeers");
30473 ast_manager_unregister("SIPshowpeer");
30474 ast_manager_unregister("SIPqualifypeer");
30475 ast_manager_unregister("SIPshowregistry");
30476 ast_manager_unregister("SIPnotify");
30477
30478
30479 if (sip_tcp_desc.master) {
30480 ast_tcptls_server_stop(&sip_tcp_desc);
30481 }
30482 if (sip_tls_desc.master) {
30483 ast_tcptls_server_stop(&sip_tls_desc);
30484 }
30485
30486
30487 i = ao2_iterator_init(threadt, 0);
30488 while ((th = ao2_t_iterator_next(&i, "iterate through tcp threads for 'sip show tcp'"))) {
30489 pthread_t thread = th->threadid;
30490 th->stop = 1;
30491 pthread_kill(thread, SIGURG);
30492 ao2_t_ref(th, -1, "decrement ref from iterator");
30493 }
30494 ao2_iterator_destroy(&i);
30495
30496
30497 i = ao2_iterator_init(dialogs, 0);
30498 while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
30499 if (p->owner)
30500 ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
30501 ao2_t_ref(p, -1, "toss dialog ptr from iterator_next");
30502 }
30503 ao2_iterator_destroy(&i);
30504
30505 unlink_all_peers_from_tables();
30506
30507 ast_mutex_lock(&monlock);
30508 if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP) && (monitor_thread != AST_PTHREADT_NULL)) {
30509 pthread_cancel(monitor_thread);
30510 pthread_kill(monitor_thread, SIGURG);
30511 pthread_join(monitor_thread, NULL);
30512 }
30513 monitor_thread = AST_PTHREADT_STOP;
30514 ast_mutex_unlock(&monlock);
30515
30516
30517 i = ao2_iterator_init(dialogs, 0);
30518 while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
30519 dialog_unlink_all(p);
30520 ao2_t_ref(p, -1, "throw away iterator result");
30521 }
30522 ao2_iterator_destroy(&i);
30523
30524
30525 ast_free_ha(localaddr);
30526
30527 ast_mutex_lock(&authl_lock);
30528 if (authl) {
30529 ao2_t_ref(authl, -1, "Removing global authentication");
30530 authl = NULL;
30531 }
30532 ast_mutex_unlock(&authl_lock);
30533
30534 sip_epa_unregister_all();
30535 destroy_escs();
30536
30537 ast_free(default_tls_cfg.certfile);
30538 ast_free(default_tls_cfg.pvtfile);
30539 ast_free(default_tls_cfg.cipher);
30540 ast_free(default_tls_cfg.cafile);
30541 ast_free(default_tls_cfg.capath);
30542
30543 cleanup_all_regs();
30544 ASTOBJ_CONTAINER_DESTROYALL(®l, sip_registry_destroy);
30545 ASTOBJ_CONTAINER_DESTROY(®l);
30546
30547 ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
30548 ASTOBJ_WRLOCK(iterator);
30549 if (iterator->dnsmgr) {
30550 ast_dnsmgr_release(iterator->dnsmgr);
30551 iterator->dnsmgr = NULL;
30552 ASTOBJ_UNREF(iterator, sip_subscribe_mwi_destroy);
30553 }
30554 ASTOBJ_UNLOCK(iterator);
30555 } while(0));
30556 ASTOBJ_CONTAINER_DESTROYALL(&submwil, sip_subscribe_mwi_destroy);
30557 ASTOBJ_CONTAINER_DESTROY(&submwil);
30558
30559
30560
30561
30562
30563
30564
30565
30566 wait_count = 1000;
30567 while (ao2_container_count(threadt) && --wait_count) {
30568 sched_yield();
30569 }
30570 if (!wait_count) {
30571 ast_debug(2, "TCP/TLS thread container did not become empty :(\n");
30572 }
30573
30574 ao2_t_ref(peers, -1, "unref the peers table");
30575 ao2_t_ref(peers_by_ip, -1, "unref the peers_by_ip table");
30576 ao2_t_ref(dialogs, -1, "unref the dialogs table");
30577 ao2_t_ref(dialogs_to_destroy, -1, "unref dialogs_to_destroy");
30578 ao2_t_ref(threadt, -1, "unref the thread table");
30579 ao2_t_ref(sip_monitor_instances, -1, "unref the sip_monitor_instances table");
30580
30581 clear_sip_domains();
30582 ast_free_ha(sip_cfg.contact_ha);
30583 close(sipsock);
30584 sched_context_destroy(sched);
30585 con = ast_context_find(used_context);
30586 if (con) {
30587 ast_context_destroy(con, "SIP");
30588 }
30589 ast_unload_realtime("sipregs");
30590 ast_unload_realtime("sippeers");
30591 ast_cc_monitor_unregister(&sip_cc_monitor_callbacks);
30592 ast_cc_agent_unregister(&sip_cc_agent_callbacks);
30593
30594 sip_reqresp_parser_exit();
30595 sip_unregister_tests();
30596
30597 return 0;
30598 }
30599
30600 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Session Initiation Protocol (SIP)",
30601 .load = load_module,
30602 .unload = unload_module,
30603 .reload = reload,
30604 .load_pri = AST_MODPRI_CHANNEL_DRIVER,
30605 .nonoptreq = "res_crypto,chan_local",
30606 );