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: 412872 $")
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_reg_retry_403;
00718 static int global_shrinkcallerid;
00719 static int global_callcounter;
00720
00721
00722 static unsigned int global_tos_sip;
00723 static unsigned int global_tos_audio;
00724 static unsigned int global_tos_video;
00725 static unsigned int global_tos_text;
00726 static unsigned int global_cos_sip;
00727 static unsigned int global_cos_audio;
00728 static unsigned int global_cos_video;
00729 static unsigned int global_cos_text;
00730 static unsigned int recordhistory;
00731 static unsigned int dumphistory;
00732 static char global_useragent[AST_MAX_EXTENSION];
00733 static char global_sdpsession[AST_MAX_EXTENSION];
00734 static char global_sdpowner[AST_MAX_EXTENSION];
00735 static int global_authfailureevents;
00736 static int global_t1;
00737 static int global_t1min;
00738 static int global_timer_b;
00739 static unsigned int global_autoframing;
00740 static int global_qualifyfreq;
00741 static int global_qualify_gap;
00742 static int global_qualify_peers;
00743
00744 static enum st_mode global_st_mode;
00745 static enum st_refresher_param global_st_refresher;
00746 static int global_min_se;
00747 static int global_max_se;
00748
00749 static int global_store_sip_cause;
00750
00751 static int global_dynamic_exclude_static = 0;
00752
00753
00754
00755
00756
00757
00758
00759
00760 static int can_parse_xml;
00761
00762
00763
00764
00765 static int speerobjs = 0;
00766 static int rpeerobjs = 0;
00767 static int apeerobjs = 0;
00768 static int regobjs = 0;
00769
00770
00771 static struct ast_flags global_flags[3] = {{0}};
00772 static int global_t38_maxdatagram;
00773
00774 static struct ast_event_sub *network_change_event_subscription;
00775 static int network_change_event_sched_id = -1;
00776
00777 static char used_context[AST_MAX_CONTEXT];
00778
00779 AST_MUTEX_DEFINE_STATIC(netlock);
00780
00781
00782
00783 AST_MUTEX_DEFINE_STATIC(monlock);
00784
00785 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
00786
00787
00788
00789 static pthread_t monitor_thread = AST_PTHREADT_NULL;
00790
00791 static int sip_reloading = FALSE;
00792 static enum channelreloadreason sip_reloadreason;
00793
00794 struct sched_context *sched;
00795 static struct io_context *io;
00796 static int *sipsock_read_id;
00797 struct sip_pkt;
00798 static AST_LIST_HEAD_STATIC(domain_list, domain);
00799
00800 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history);
00801
00802 static enum sip_debug_e sipdebug;
00803
00804
00805
00806
00807
00808 static int sipdebug_text;
00809
00810 static const struct _map_x_s referstatusstrings[] = {
00811 { REFER_IDLE, "<none>" },
00812 { REFER_SENT, "Request sent" },
00813 { REFER_RECEIVED, "Request received" },
00814 { REFER_CONFIRMED, "Confirmed" },
00815 { REFER_ACCEPTED, "Accepted" },
00816 { REFER_RINGING, "Target ringing" },
00817 { REFER_200OK, "Done" },
00818 { REFER_FAILED, "Failed" },
00819 { REFER_NOAUTH, "Failed - auth failure" },
00820 { -1, NULL}
00821 };
00822
00823
00824 #ifdef LOW_MEMORY
00825 static const int HASH_PEER_SIZE = 17;
00826 static const int HASH_DIALOG_SIZE = 17;
00827 #else
00828 static const int HASH_PEER_SIZE = 563;
00829 static const int HASH_DIALOG_SIZE = 563;
00830 #endif
00831
00832 static const struct {
00833 enum ast_cc_service_type service;
00834 const char *service_string;
00835 } sip_cc_service_map [] = {
00836 [AST_CC_NONE] = { AST_CC_NONE, "" },
00837 [AST_CC_CCBS] = { AST_CC_CCBS, "BS" },
00838 [AST_CC_CCNR] = { AST_CC_CCNR, "NR" },
00839 [AST_CC_CCNL] = { AST_CC_CCNL, "NL" },
00840 };
00841
00842 static enum ast_cc_service_type service_string_to_service_type(const char * const service_string)
00843 {
00844 enum ast_cc_service_type service;
00845 for (service = AST_CC_CCBS; service <= AST_CC_CCNL; ++service) {
00846 if (!strcasecmp(service_string, sip_cc_service_map[service].service_string)) {
00847 return service;
00848 }
00849 }
00850 return AST_CC_NONE;
00851 }
00852
00853 static const struct {
00854 enum sip_cc_notify_state state;
00855 const char *state_string;
00856 } sip_cc_notify_state_map [] = {
00857 [CC_QUEUED] = {CC_QUEUED, "cc-state: queued"},
00858 [CC_READY] = {CC_READY, "cc-state: ready"},
00859 };
00860
00861 AST_LIST_HEAD_STATIC(epa_static_data_list, epa_backend);
00862
00863 static int sip_epa_register(const struct epa_static_data *static_data)
00864 {
00865 struct epa_backend *backend = ast_calloc(1, sizeof(*backend));
00866
00867 if (!backend) {
00868 return -1;
00869 }
00870
00871 backend->static_data = static_data;
00872
00873 AST_LIST_LOCK(&epa_static_data_list);
00874 AST_LIST_INSERT_TAIL(&epa_static_data_list, backend, next);
00875 AST_LIST_UNLOCK(&epa_static_data_list);
00876 return 0;
00877 }
00878
00879 static void sip_epa_unregister_all(void)
00880 {
00881 struct epa_backend *backend;
00882
00883 AST_LIST_LOCK(&epa_static_data_list);
00884 while ((backend = AST_LIST_REMOVE_HEAD(&epa_static_data_list, next))) {
00885 ast_free(backend);
00886 }
00887 AST_LIST_UNLOCK(&epa_static_data_list);
00888 }
00889
00890 static void cc_handle_publish_error(struct sip_pvt *pvt, const int resp, struct sip_request *req, struct sip_epa_entry *epa_entry);
00891
00892 static void cc_epa_destructor(void *data)
00893 {
00894 struct sip_epa_entry *epa_entry = data;
00895 struct cc_epa_entry *cc_entry = epa_entry->instance_data;
00896 ast_free(cc_entry);
00897 }
00898
00899 static const struct epa_static_data cc_epa_static_data = {
00900 .event = CALL_COMPLETION,
00901 .name = "call-completion",
00902 .handle_error = cc_handle_publish_error,
00903 .destructor = cc_epa_destructor,
00904 };
00905
00906 static const struct epa_static_data *find_static_data(const char * const event_package)
00907 {
00908 const struct epa_backend *backend = NULL;
00909
00910 AST_LIST_LOCK(&epa_static_data_list);
00911 AST_LIST_TRAVERSE(&epa_static_data_list, backend, next) {
00912 if (!strcmp(backend->static_data->name, event_package)) {
00913 break;
00914 }
00915 }
00916 AST_LIST_UNLOCK(&epa_static_data_list);
00917 return backend ? backend->static_data : NULL;
00918 }
00919
00920 static struct sip_epa_entry *create_epa_entry (const char * const event_package, const char * const destination)
00921 {
00922 struct sip_epa_entry *epa_entry;
00923 const struct epa_static_data *static_data;
00924
00925 if (!(static_data = find_static_data(event_package))) {
00926 return NULL;
00927 }
00928
00929 if (!(epa_entry = ao2_t_alloc(sizeof(*epa_entry), static_data->destructor, "Allocate new EPA entry"))) {
00930 return NULL;
00931 }
00932
00933 epa_entry->static_data = static_data;
00934 ast_copy_string(epa_entry->destination, destination, sizeof(epa_entry->destination));
00935 return epa_entry;
00936 }
00937
00938
00939
00940
00941 static int esc_etag_counter;
00942 static const int DEFAULT_PUBLISH_EXPIRES = 3600;
00943
00944 #ifdef HAVE_LIBXML2
00945 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);
00946
00947 static const struct sip_esc_publish_callbacks cc_esc_publish_callbacks = {
00948 .initial_handler = cc_esc_publish_handler,
00949 .modify_handler = cc_esc_publish_handler,
00950 };
00951 #endif
00952
00953
00954
00955
00956
00957
00958
00959
00960
00961
00962
00963
00964
00965 static struct event_state_compositor {
00966 enum subscriptiontype event;
00967 const char * name;
00968 const struct sip_esc_publish_callbacks *callbacks;
00969 struct ao2_container *compositor;
00970 } event_state_compositors [] = {
00971 #ifdef HAVE_LIBXML2
00972 {CALL_COMPLETION, "call-completion", &cc_esc_publish_callbacks},
00973 #endif
00974 };
00975
00976 static const int ESC_MAX_BUCKETS = 37;
00977
00978 static void esc_entry_destructor(void *obj)
00979 {
00980 struct sip_esc_entry *esc_entry = obj;
00981 if (esc_entry->sched_id > -1) {
00982 AST_SCHED_DEL(sched, esc_entry->sched_id);
00983 }
00984 }
00985
00986 static int esc_hash_fn(const void *obj, const int flags)
00987 {
00988 const struct sip_esc_entry *entry = obj;
00989 return ast_str_hash(entry->entity_tag);
00990 }
00991
00992 static int esc_cmp_fn(void *obj, void *arg, int flags)
00993 {
00994 struct sip_esc_entry *entry1 = obj;
00995 struct sip_esc_entry *entry2 = arg;
00996
00997 return (!strcmp(entry1->entity_tag, entry2->entity_tag)) ? (CMP_MATCH | CMP_STOP) : 0;
00998 }
00999
01000 static struct event_state_compositor *get_esc(const char * const event_package) {
01001 int i;
01002 for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
01003 if (!strcasecmp(event_package, event_state_compositors[i].name)) {
01004 return &event_state_compositors[i];
01005 }
01006 }
01007 return NULL;
01008 }
01009
01010 static struct sip_esc_entry *get_esc_entry(const char * entity_tag, struct event_state_compositor *esc) {
01011 struct sip_esc_entry *entry;
01012 struct sip_esc_entry finder;
01013
01014 ast_copy_string(finder.entity_tag, entity_tag, sizeof(finder.entity_tag));
01015
01016 entry = ao2_find(esc->compositor, &finder, OBJ_POINTER);
01017
01018 return entry;
01019 }
01020
01021 static int publish_expire(const void *data)
01022 {
01023 struct sip_esc_entry *esc_entry = (struct sip_esc_entry *) data;
01024 struct event_state_compositor *esc = get_esc(esc_entry->event);
01025
01026 ast_assert(esc != NULL);
01027
01028 ao2_unlink(esc->compositor, esc_entry);
01029 ao2_ref(esc_entry, -1);
01030 return 0;
01031 }
01032
01033 static void create_new_sip_etag(struct sip_esc_entry *esc_entry, int is_linked)
01034 {
01035 int new_etag = ast_atomic_fetchadd_int(&esc_etag_counter, +1);
01036 struct event_state_compositor *esc = get_esc(esc_entry->event);
01037
01038 ast_assert(esc != NULL);
01039 if (is_linked) {
01040 ao2_unlink(esc->compositor, esc_entry);
01041 }
01042 snprintf(esc_entry->entity_tag, sizeof(esc_entry->entity_tag), "%d", new_etag);
01043 ao2_link(esc->compositor, esc_entry);
01044 }
01045
01046 static struct sip_esc_entry *create_esc_entry(struct event_state_compositor *esc, struct sip_request *req, const int expires)
01047 {
01048 struct sip_esc_entry *esc_entry;
01049 int expires_ms;
01050
01051 if (!(esc_entry = ao2_alloc(sizeof(*esc_entry), esc_entry_destructor))) {
01052 return NULL;
01053 }
01054
01055 esc_entry->event = esc->name;
01056
01057 expires_ms = expires * 1000;
01058
01059 ao2_ref(esc_entry, +1);
01060 esc_entry->sched_id = ast_sched_add(sched, expires_ms, publish_expire, esc_entry);
01061
01062
01063 create_new_sip_etag(esc_entry, 0);
01064
01065 return esc_entry;
01066 }
01067
01068 static int initialize_escs(void)
01069 {
01070 int i, res = 0;
01071 for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
01072 if (!((event_state_compositors[i].compositor) =
01073 ao2_container_alloc(ESC_MAX_BUCKETS, esc_hash_fn, esc_cmp_fn))) {
01074 res = -1;
01075 }
01076 }
01077 return res;
01078 }
01079
01080 static void destroy_escs(void)
01081 {
01082 int i;
01083 for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
01084 ao2_ref(event_state_compositors[i].compositor, -1);
01085 }
01086 }
01087
01088
01089
01090
01091
01092 struct ao2_container *dialogs_to_destroy;
01093
01094
01095
01096
01097
01098
01099
01100
01101
01102 static struct ao2_container *dialogs;
01103 #define sip_pvt_lock(x) ao2_lock(x)
01104 #define sip_pvt_trylock(x) ao2_trylock(x)
01105 #define sip_pvt_unlock(x) ao2_unlock(x)
01106
01107
01108 static struct ao2_container *threadt;
01109
01110
01111 static struct ao2_container *peers;
01112 static struct ao2_container *peers_by_ip;
01113
01114
01115 static struct sip_peer *bogus_peer;
01116
01117 #define BOGUS_PEER_MD5SECRET "intentionally_invalid_md5_string"
01118
01119
01120 static struct ast_register_list {
01121 ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
01122 int recheck;
01123 } regl;
01124
01125
01126 static struct ast_subscription_mwi_list {
01127 ASTOBJ_CONTAINER_COMPONENTS(struct sip_subscription_mwi);
01128 } submwil;
01129 static int temp_pvt_init(void *);
01130 static void temp_pvt_cleanup(void *);
01131
01132
01133 AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
01134
01135
01136 static struct sip_auth_container *authl = NULL;
01137
01138 AST_MUTEX_DEFINE_STATIC(authl_lock);
01139
01140
01141
01142
01143
01144
01145
01146
01147
01148
01149
01150
01151
01152
01153
01154
01155
01156 static int sipsock = -1;
01157
01158 struct ast_sockaddr bindaddr;
01159
01160
01161
01162
01163
01164
01165
01166 static struct ast_sockaddr internip;
01167
01168
01169
01170
01171
01172
01173
01174
01175
01176
01177
01178
01179
01180
01181
01182
01183 static struct ast_sockaddr externaddr;
01184 static struct ast_sockaddr media_address;
01185
01186 static char externhost[MAXHOSTNAMELEN];
01187 static time_t externexpire;
01188 static int externrefresh = 10;
01189 static uint16_t externtcpport;
01190 static uint16_t externtlsport;
01191
01192
01193
01194
01195
01196
01197
01198 static struct ast_ha *localaddr;
01199
01200 static int ourport_tcp;
01201 static int ourport_tls;
01202 static struct ast_sockaddr debugaddr;
01203
01204 static struct ast_config *notify_types = NULL;
01205
01206
01207
01208 #define UNLINK(element, head, prev) do { \
01209 if (prev) \
01210 (prev)->next = (element)->next; \
01211 else \
01212 (head) = (element)->next; \
01213 } while (0)
01214
01215 struct show_peers_context;
01216
01217
01218
01219
01220
01221
01222 static struct ast_channel *sip_request_call(const char *type, format_t format, const struct ast_channel *requestor, void *data, int *cause);
01223 static int sip_devicestate(void *data);
01224 static int sip_sendtext(struct ast_channel *ast, const char *text);
01225 static int sip_call(struct ast_channel *ast, char *dest, int timeout);
01226 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen);
01227 static int sip_hangup(struct ast_channel *ast);
01228 static int sip_answer(struct ast_channel *ast);
01229 static struct ast_frame *sip_read(struct ast_channel *ast);
01230 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
01231 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
01232 static int sip_transfer(struct ast_channel *ast, const char *dest);
01233 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
01234 static int sip_senddigit_begin(struct ast_channel *ast, char digit);
01235 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
01236 static int sip_setoption(struct ast_channel *chan, int option, void *data, int datalen);
01237 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen);
01238 static const char *sip_get_callid(struct ast_channel *chan);
01239
01240 static int handle_request_do(struct sip_request *req, struct ast_sockaddr *addr);
01241 static int sip_standard_port(enum sip_transport type, int port);
01242 static int sip_prepare_socket(struct sip_pvt *p);
01243 static int get_address_family_filter(unsigned int transport);
01244
01245
01246 static int sipsock_read(int *id, int fd, short events, void *ignore);
01247 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data);
01248 static int __sip_reliable_xmit(struct sip_pvt *p, uint32_t seqno, int resp, struct ast_str *data, int fatal, int sipmethod);
01249 static void add_cc_call_info_to_response(struct sip_pvt *p, struct sip_request *resp);
01250 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
01251 static int retrans_pkt(const void *data);
01252 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);
01253 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
01254 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
01255 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
01256 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);
01257 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
01258 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);
01259 static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp);
01260 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
01261 static void transmit_fake_auth_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable);
01262 static int transmit_request(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch);
01263 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch);
01264 static int transmit_publish(struct sip_epa_entry *epa_entry, enum sip_publish_type publish_type, const char * const explicit_uri);
01265 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init, const char * const explicit_uri);
01266 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp);
01267 static int transmit_info_with_aoc(struct sip_pvt *p, struct ast_aoc_decoded *decoded);
01268 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
01269 static int transmit_info_with_vidupdate(struct sip_pvt *p);
01270 static int transmit_message_with_text(struct sip_pvt *p, const char *text);
01271 static int transmit_refer(struct sip_pvt *p, const char *dest);
01272 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten);
01273 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
01274 static int transmit_cc_notify(struct ast_cc_agent *agent, struct sip_pvt *subscription, enum sip_cc_notify_state state);
01275 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
01276 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno);
01277 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno);
01278 static void copy_request(struct sip_request *dst, const struct sip_request *src);
01279 static void receive_message(struct sip_pvt *p, struct sip_request *req);
01280 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req, char **name, char **number, int set_call_forward);
01281 static int sip_send_mwi_to_peer(struct sip_peer *peer, int cache_only);
01282
01283
01284 static int __sip_autodestruct(const void *data);
01285 static void *registry_unref(struct sip_registry *reg, char *tag);
01286 static int update_call_counter(struct sip_pvt *fup, int event);
01287 static int auto_congest(const void *arg);
01288 static struct sip_pvt *find_call(struct sip_request *req, struct ast_sockaddr *addr, const int intended_method);
01289 static void free_old_route(struct sip_route *route);
01290 static void list_route(struct sip_route *route);
01291 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards, int resp);
01292 static enum check_auth_result register_verify(struct sip_pvt *p, struct ast_sockaddr *addr,
01293 struct sip_request *req, const char *uri);
01294 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
01295 static void check_pendings(struct sip_pvt *p);
01296 static void *sip_park_thread(void *stuff);
01297 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);
01298
01299 static void *sip_pickup_thread(void *stuff);
01300 static int sip_pickup(struct ast_channel *chan);
01301
01302 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
01303 static int is_method_allowed(unsigned int *allowed_methods, enum sipmethod method);
01304
01305
01306 static void try_suggested_sip_codec(struct sip_pvt *p);
01307 static const char *get_sdp_iterate(int* start, struct sip_request *req, const char *name);
01308 static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value);
01309 static int find_sdp(struct sip_request *req);
01310 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action);
01311 static int process_sdp_o(const char *o, struct sip_pvt *p);
01312 static int process_sdp_c(const char *c, struct ast_sockaddr *addr);
01313 static int process_sdp_a_sendonly(const char *a, int *sendonly);
01314 static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newaudiortp, int *last_rtpmap_codec);
01315 static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newvideortp, int *last_rtpmap_codec);
01316 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);
01317 static int process_sdp_a_image(const char *a, struct sip_pvt *p);
01318 static void add_codec_to_sdp(const struct sip_pvt *p, format_t codec,
01319 struct ast_str **m_buf, struct ast_str **a_buf,
01320 int debug, int *min_packet_size);
01321 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
01322 struct ast_str **m_buf, struct ast_str **a_buf,
01323 int debug);
01324 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38);
01325 static void do_setnat(struct sip_pvt *p);
01326 static void stop_media_flows(struct sip_pvt *p);
01327
01328
01329 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
01330 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
01331 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
01332 const char *secret, const char *md5secret, int sipmethod,
01333 const char *uri, enum xmittype reliable, int ignore);
01334 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
01335 int sipmethod, const char *uri, enum xmittype reliable,
01336 struct ast_sockaddr *addr, struct sip_peer **authpeer);
01337 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, const char *uri, enum xmittype reliable, struct ast_sockaddr *addr);
01338
01339
01340 static int check_sip_domain(const char *domain, char *context, size_t len);
01341 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
01342 static void clear_sip_domains(void);
01343
01344
01345 static void add_realm_authentication(struct sip_auth_container **credentials, const char *configuration, int lineno);
01346 static struct sip_auth *find_realm_authentication(struct sip_auth_container *credentials, const char *realm);
01347
01348
01349 static void check_rtp_timeout(struct sip_pvt *dialog, time_t t);
01350 static int reload_config(enum channelreloadreason reason);
01351 static void add_diversion_header(struct sip_request *req, struct sip_pvt *pvt);
01352 static int expire_register(const void *data);
01353 static void *do_monitor(void *data);
01354 static int restart_monitor(void);
01355 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer);
01356 static struct ast_variable *copy_vars(struct ast_variable *src);
01357 static int dialog_find_multiple(void *obj, void *arg, int flags);
01358 static struct ast_channel *sip_pvt_lock_full(struct sip_pvt *pvt);
01359
01360 static int sip_refer_allocate(struct sip_pvt *p);
01361 static int sip_notify_allocate(struct sip_pvt *p);
01362 static void ast_quiet_chan(struct ast_channel *chan);
01363 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
01364 static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context);
01365
01366
01367 static int cb_extensionstate(char *context, char* exten, int state, void *data);
01368 static int sip_devicestate(void *data);
01369 static int sip_poke_noanswer(const void *data);
01370 static int sip_poke_peer(struct sip_peer *peer, int force);
01371 static void sip_poke_all_peers(void);
01372 static void sip_peer_hold(struct sip_pvt *p, int hold);
01373 static void mwi_event_cb(const struct ast_event *, void *);
01374 static void network_change_event_cb(const struct ast_event *, void *);
01375
01376
01377 static const char *sip_nat_mode(const struct sip_pvt *p);
01378 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01379 static char *transfermode2str(enum transfermodes mode) attribute_const;
01380 static int peer_status(struct sip_peer *peer, char *status, int statuslen);
01381 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01382 static char * _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
01383 static struct sip_peer *_sip_show_peers_one(int fd, struct mansession *s, struct show_peers_context *cont, struct sip_peer *peer);
01384 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01385 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01386 static void print_group(int fd, ast_group_t group, int crlf);
01387 static const char *dtmfmode2str(int mode) attribute_const;
01388 static int str2dtmfmode(const char *str) attribute_unused;
01389 static const char *insecure2str(int mode) attribute_const;
01390 static const char *allowoverlap2str(int mode) attribute_const;
01391 static void cleanup_stale_contexts(char *new, char *old);
01392 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
01393 static const char *domain_mode_to_text(const enum domain_mode mode);
01394 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01395 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
01396 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01397 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
01398 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01399 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01400 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01401 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01402 static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01403 static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
01404 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
01405 static char *complete_sip_peer(const char *word, int state, int flags2);
01406 static char *complete_sip_registered_peer(const char *word, int state, int flags2);
01407 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state);
01408 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
01409 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state);
01410 static char *complete_sipnotify(const char *line, const char *word, int pos, int state);
01411 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01412 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01413 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01414 static char *sip_do_debug_ip(int fd, const char *arg);
01415 static char *sip_do_debug_peer(int fd, const char *arg);
01416 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01417 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01418 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01419 static int sip_dtmfmode(struct ast_channel *chan, const char *data);
01420 static int sip_addheader(struct ast_channel *chan, const char *data);
01421 static int sip_do_reload(enum channelreloadreason reason);
01422 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01423 static int ast_sockaddr_resolve_first_af(struct ast_sockaddr *addr,
01424 const char *name, int flag, int family);
01425 static int ast_sockaddr_resolve_first(struct ast_sockaddr *addr,
01426 const char *name, int flag);
01427 static int ast_sockaddr_resolve_first_transport(struct ast_sockaddr *addr,
01428 const char *name, int flag, unsigned int transport);
01429
01430
01431
01432
01433
01434 static void sip_dump_history(struct sip_pvt *dialog);
01435 static inline int sip_debug_test_addr(const struct ast_sockaddr *addr);
01436 static inline int sip_debug_test_pvt(struct sip_pvt *p);
01437 static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
01438 static void sip_dump_history(struct sip_pvt *dialog);
01439
01440
01441 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only);
01442 static int update_call_counter(struct sip_pvt *fup, int event);
01443 static void sip_destroy_peer(struct sip_peer *peer);
01444 static void sip_destroy_peer_fn(void *peer);
01445 static void set_peer_defaults(struct sip_peer *peer);
01446 static struct sip_peer *temp_peer(const char *name);
01447 static void register_peer_exten(struct sip_peer *peer, int onoff);
01448 static struct sip_peer *find_peer(const char *peer, struct ast_sockaddr *addr, int realtime, int forcenamematch, int devstate_only, int transport);
01449 static int sip_poke_peer_s(const void *data);
01450 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
01451 static void reg_source_db(struct sip_peer *peer);
01452 static void destroy_association(struct sip_peer *peer);
01453 static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
01454 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
01455 static void set_socket_transport(struct sip_socket *socket, int transport);
01456
01457
01458 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);
01459 static void update_peer(struct sip_peer *p, int expire);
01460 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config);
01461 static const char *get_name_from_variable(const struct ast_variable *var);
01462 static struct sip_peer *realtime_peer(const char *peername, struct ast_sockaddr *sin, int devstate_only, int which_objects);
01463 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01464
01465
01466 static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p);
01467 static void sip_registry_destroy(struct sip_registry *reg);
01468 static int sip_register(const char *value, int lineno);
01469 static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
01470 static int sip_reregister(const void *data);
01471 static int __sip_do_register(struct sip_registry *r);
01472 static int sip_reg_timeout(const void *data);
01473 static void sip_send_all_registers(void);
01474 static int sip_reinvite_retry(const void *data);
01475
01476
01477 static void append_date(struct sip_request *req);
01478 static int determine_firstline_parts(struct sip_request *req);
01479 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
01480 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
01481 static int find_sip_method(const char *msg);
01482 static unsigned int parse_allowed_methods(struct sip_request *req);
01483 static unsigned int set_pvt_allowed_methods(struct sip_pvt *pvt, struct sip_request *req);
01484 static int parse_request(struct sip_request *req);
01485 static const char *get_header(const struct sip_request *req, const char *name);
01486 static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
01487 static int method_match(enum sipmethod id, const char *name);
01488 static void parse_copy(struct sip_request *dst, const struct sip_request *src);
01489 static const char *find_alias(const char *name, const char *_default);
01490 static const char *__get_header(const struct sip_request *req, const char *name, int *start);
01491 static void lws2sws(struct ast_str *msgbuf);
01492 static void extract_uri(struct sip_pvt *p, struct sip_request *req);
01493 static char *remove_uri_parameters(char *uri);
01494 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
01495 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
01496 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
01497 static int set_address_from_contact(struct sip_pvt *pvt);
01498 static void check_via(struct sip_pvt *p, const struct sip_request *req);
01499 static int get_rpid(struct sip_pvt *p, struct sip_request *oreq);
01500 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq, char **name, char **number, int *reason);
01501 static enum sip_get_dest_result get_destination(struct sip_pvt *p, struct sip_request *oreq, int *cc_recall_core_id);
01502 static int get_msg_text(char *buf, int len, struct sip_request *req);
01503 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout);
01504 static void update_connectedline(struct sip_pvt *p, const void *data, size_t datalen);
01505 static void update_redirecting(struct sip_pvt *p, const void *data, size_t datalen);
01506 static int get_domain(const char *str, char *domain, int len);
01507 static void get_realm(struct sip_pvt *p, const struct sip_request *req);
01508
01509
01510 static void *_sip_tcp_helper_thread(struct ast_tcptls_session_instance *tcptls_session);
01511 static void *sip_tcp_worker_fn(void *);
01512
01513
01514 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
01515 static int init_req(struct sip_request *req, int sipmethod, const char *recip);
01516 static void deinit_req(struct sip_request *req);
01517 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, uint32_t seqno, int newbranch);
01518 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, const char * const explicit_uri);
01519 static int init_resp(struct sip_request *resp, const char *msg);
01520 static inline int resp_needs_contact(const char *msg, enum sipmethod method);
01521 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
01522 static const struct ast_sockaddr *sip_real_dst(const struct sip_pvt *p);
01523 static void build_via(struct sip_pvt *p);
01524 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
01525 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct ast_sockaddr *addr, int newdialog);
01526 static char *generate_random_string(char *buf, size_t size);
01527 static void build_callid_pvt(struct sip_pvt *pvt);
01528 static void change_callid_pvt(struct sip_pvt *pvt, const char *callid);
01529 static void build_callid_registry(struct sip_registry *reg, const struct ast_sockaddr *ourip, const char *fromdomain);
01530 static void build_localtag_registry(struct sip_registry *reg);
01531 static void make_our_tag(struct sip_pvt *pvt);
01532 static int add_header(struct sip_request *req, const char *var, const char *value);
01533 static int add_header_max_forwards(struct sip_pvt *dialog, struct sip_request *req);
01534 static int add_content(struct sip_request *req, const char *line);
01535 static int finalize_content(struct sip_request *req);
01536 static int add_text(struct sip_request *req, const char *text);
01537 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode);
01538 static int add_rpid(struct sip_request *req, struct sip_pvt *p);
01539 static int add_vidupdate(struct sip_request *req);
01540 static void add_route(struct sip_request *req, struct sip_route *route);
01541 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
01542 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
01543 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
01544 static void set_destination(struct sip_pvt *p, char *uri);
01545 static void append_date(struct sip_request *req);
01546 static void build_contact(struct sip_pvt *p);
01547
01548
01549 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int *recount, int *nounlock);
01550 static int handle_request_update(struct sip_pvt *p, struct sip_request *req);
01551 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);
01552 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, uint32_t seqno, int *nounlock);
01553 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
01554 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *sin, const char *e);
01555 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
01556 static int handle_request_message(struct sip_pvt *p, struct sip_request *req);
01557 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e);
01558 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
01559 static int handle_request_options(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
01560 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, uint32_t seqno, struct ast_sockaddr *addr, int *nounlock);
01561 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e);
01562 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, uint32_t seqno, int *nounlock);
01563
01564
01565 static void handle_response_publish(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01566 static void handle_response_invite(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01567 static void handle_response_notify(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01568 static void handle_response_refer(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01569 static void handle_response_subscribe(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01570 static int handle_response_register(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01571 static void handle_response(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01572
01573
01574 static int setup_srtp(struct sip_srtp **srtp);
01575 static int process_crypto(struct sip_pvt *p, struct ast_rtp_instance *rtp, struct sip_srtp **srtp, const char *a);
01576
01577
01578 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
01579 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
01580 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
01581 static void change_t38_state(struct sip_pvt *p, int state);
01582
01583
01584 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp);
01585 static int proc_session_timer(const void *vp);
01586 static void stop_session_timer(struct sip_pvt *p);
01587 static void start_session_timer(struct sip_pvt *p);
01588 static void restart_session_timer(struct sip_pvt *p);
01589 static const char *strefresherparam2str(enum st_refresher r);
01590 static int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher_param *const p_ref);
01591 static int parse_minse(const char *p_hdrval, int *const p_interval);
01592 static int st_get_se(struct sip_pvt *, int max);
01593 static enum st_refresher st_get_refresher(struct sip_pvt *);
01594 static enum st_mode st_get_mode(struct sip_pvt *, int no_cached);
01595 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p);
01596
01597
01598 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);
01599
01600
01601 static int sip_subscribe_mwi(const char *value, int lineno);
01602 static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi);
01603 static void sip_send_all_mwi_subscriptions(void);
01604 static int sip_subscribe_mwi_do(const void *data);
01605 static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi);
01606
01607
01608 const struct ast_channel_tech sip_tech = {
01609 .type = "SIP",
01610 .description = "Session Initiation Protocol (SIP)",
01611 .capabilities = AST_FORMAT_AUDIO_MASK,
01612 .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
01613 .requester = sip_request_call,
01614 .devicestate = sip_devicestate,
01615 .call = sip_call,
01616 .send_html = sip_sendhtml,
01617 .hangup = sip_hangup,
01618 .answer = sip_answer,
01619 .read = sip_read,
01620 .write = sip_write,
01621 .write_video = sip_write,
01622 .write_text = sip_write,
01623 .indicate = sip_indicate,
01624 .transfer = sip_transfer,
01625 .fixup = sip_fixup,
01626 .send_digit_begin = sip_senddigit_begin,
01627 .send_digit_end = sip_senddigit_end,
01628 .bridge = ast_rtp_instance_bridge,
01629 .early_bridge = ast_rtp_instance_early_bridge,
01630 .send_text = sip_sendtext,
01631 .func_channel_read = sip_acf_channel_read,
01632 .setoption = sip_setoption,
01633 .queryoption = sip_queryoption,
01634 .get_pvt_uniqueid = sip_get_callid,
01635 };
01636
01637
01638
01639
01640
01641
01642
01643 struct ast_channel_tech sip_tech_info;
01644
01645 static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan);
01646 static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent);
01647 static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent);
01648 static void sip_cc_agent_respond(struct ast_cc_agent *agent, enum ast_cc_agent_response_reason reason);
01649 static int sip_cc_agent_status_request(struct ast_cc_agent *agent);
01650 static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent);
01651 static int sip_cc_agent_recall(struct ast_cc_agent *agent);
01652 static void sip_cc_agent_destructor(struct ast_cc_agent *agent);
01653
01654 static struct ast_cc_agent_callbacks sip_cc_agent_callbacks = {
01655 .type = "SIP",
01656 .init = sip_cc_agent_init,
01657 .start_offer_timer = sip_cc_agent_start_offer_timer,
01658 .stop_offer_timer = sip_cc_agent_stop_offer_timer,
01659 .respond = sip_cc_agent_respond,
01660 .status_request = sip_cc_agent_status_request,
01661 .start_monitoring = sip_cc_agent_start_monitoring,
01662 .callee_available = sip_cc_agent_recall,
01663 .destructor = sip_cc_agent_destructor,
01664 };
01665
01666 static int find_by_notify_uri_helper(void *obj, void *arg, int flags)
01667 {
01668 struct ast_cc_agent *agent = obj;
01669 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01670 const char *uri = arg;
01671
01672 return !sip_uri_cmp(agent_pvt->notify_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
01673 }
01674
01675 static struct ast_cc_agent *find_sip_cc_agent_by_notify_uri(const char * const uri)
01676 {
01677 struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_notify_uri_helper, (char *)uri, "SIP");
01678 return agent;
01679 }
01680
01681 static int find_by_subscribe_uri_helper(void *obj, void *arg, int flags)
01682 {
01683 struct ast_cc_agent *agent = obj;
01684 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01685 const char *uri = arg;
01686
01687 return !sip_uri_cmp(agent_pvt->subscribe_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
01688 }
01689
01690 static struct ast_cc_agent *find_sip_cc_agent_by_subscribe_uri(const char * const uri)
01691 {
01692 struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_subscribe_uri_helper, (char *)uri, "SIP");
01693 return agent;
01694 }
01695
01696 static int find_by_callid_helper(void *obj, void *arg, int flags)
01697 {
01698 struct ast_cc_agent *agent = obj;
01699 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01700 struct sip_pvt *call_pvt = arg;
01701
01702 return !strcmp(agent_pvt->original_callid, call_pvt->callid) ? CMP_MATCH | CMP_STOP : 0;
01703 }
01704
01705 static struct ast_cc_agent *find_sip_cc_agent_by_original_callid(struct sip_pvt *pvt)
01706 {
01707 struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_callid_helper, pvt, "SIP");
01708 return agent;
01709 }
01710
01711 static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan)
01712 {
01713 struct sip_cc_agent_pvt *agent_pvt = ast_calloc(1, sizeof(*agent_pvt));
01714 struct sip_pvt *call_pvt = chan->tech_pvt;
01715
01716 if (!agent_pvt) {
01717 return -1;
01718 }
01719
01720 ast_assert(!strcmp(chan->tech->type, "SIP"));
01721
01722 ast_copy_string(agent_pvt->original_callid, call_pvt->callid, sizeof(agent_pvt->original_callid));
01723 ast_copy_string(agent_pvt->original_exten, call_pvt->exten, sizeof(agent_pvt->original_exten));
01724 agent_pvt->offer_timer_id = -1;
01725 agent->private_data = agent_pvt;
01726 sip_pvt_lock(call_pvt);
01727 ast_set_flag(&call_pvt->flags[0], SIP_OFFER_CC);
01728 sip_pvt_unlock(call_pvt);
01729 return 0;
01730 }
01731
01732 static int sip_offer_timer_expire(const void *data)
01733 {
01734 struct ast_cc_agent *agent = (struct ast_cc_agent *) data;
01735 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01736
01737 agent_pvt->offer_timer_id = -1;
01738
01739 return ast_cc_failed(agent->core_id, "SIP agent %s's offer timer expired", agent->device_name);
01740 }
01741
01742 static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent)
01743 {
01744 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01745 int when;
01746
01747 when = ast_get_cc_offer_timer(agent->cc_params) * 1000;
01748 agent_pvt->offer_timer_id = ast_sched_add(sched, when, sip_offer_timer_expire, agent);
01749 return 0;
01750 }
01751
01752 static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent)
01753 {
01754 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01755
01756 AST_SCHED_DEL(sched, agent_pvt->offer_timer_id);
01757 return 0;
01758 }
01759
01760 static void sip_cc_agent_respond(struct ast_cc_agent *agent, enum ast_cc_agent_response_reason reason)
01761 {
01762 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01763
01764 sip_pvt_lock(agent_pvt->subscribe_pvt);
01765 ast_set_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
01766 if (reason == AST_CC_AGENT_RESPONSE_SUCCESS || !ast_strlen_zero(agent_pvt->notify_uri)) {
01767
01768
01769
01770
01771
01772
01773
01774
01775
01776
01777
01778
01779 transmit_response(agent_pvt->subscribe_pvt, "200 OK", &agent_pvt->subscribe_pvt->initreq);
01780 transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_QUEUED);
01781 } else {
01782 transmit_response(agent_pvt->subscribe_pvt, "500 Internal Error", &agent_pvt->subscribe_pvt->initreq);
01783 }
01784 sip_pvt_unlock(agent_pvt->subscribe_pvt);
01785 agent_pvt->is_available = TRUE;
01786 }
01787
01788 static int sip_cc_agent_status_request(struct ast_cc_agent *agent)
01789 {
01790 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01791 enum ast_device_state state = agent_pvt->is_available ? AST_DEVICE_NOT_INUSE : AST_DEVICE_INUSE;
01792 return ast_cc_agent_status_response(agent->core_id, state);
01793 }
01794
01795 static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent)
01796 {
01797
01798
01799
01800
01801 return 0;
01802 }
01803
01804 static int sip_cc_agent_recall(struct ast_cc_agent *agent)
01805 {
01806 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01807
01808
01809
01810
01811 if (!agent_pvt->is_available) {
01812 return ast_cc_agent_caller_busy(agent->core_id, "Caller %s is busy, reporting to the core",
01813 agent->device_name);
01814 }
01815
01816
01817
01818 sip_pvt_lock(agent_pvt->subscribe_pvt);
01819 transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_READY);
01820 sip_pvt_unlock(agent_pvt->subscribe_pvt);
01821 return 0;
01822 }
01823
01824 static void sip_cc_agent_destructor(struct ast_cc_agent *agent)
01825 {
01826 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01827
01828 if (!agent_pvt) {
01829
01830 return;
01831 }
01832
01833 sip_cc_agent_stop_offer_timer(agent);
01834 if (agent_pvt->subscribe_pvt) {
01835 sip_pvt_lock(agent_pvt->subscribe_pvt);
01836 if (!ast_test_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
01837
01838
01839
01840 transmit_response(agent_pvt->subscribe_pvt, "500 Internal Server Error", &agent_pvt->subscribe_pvt->initreq);
01841 }
01842 sip_pvt_unlock(agent_pvt->subscribe_pvt);
01843 agent_pvt->subscribe_pvt = dialog_unref(agent_pvt->subscribe_pvt, "SIP CC agent destructor: Remove ref to subscription");
01844 }
01845 ast_free(agent_pvt);
01846 }
01847
01848 struct ao2_container *sip_monitor_instances;
01849
01850 static int sip_monitor_instance_hash_fn(const void *obj, const int flags)
01851 {
01852 const struct sip_monitor_instance *monitor_instance = obj;
01853 return monitor_instance->core_id;
01854 }
01855
01856 static int sip_monitor_instance_cmp_fn(void *obj, void *arg, int flags)
01857 {
01858 struct sip_monitor_instance *monitor_instance1 = obj;
01859 struct sip_monitor_instance *monitor_instance2 = arg;
01860
01861 return monitor_instance1->core_id == monitor_instance2->core_id ? CMP_MATCH | CMP_STOP : 0;
01862 }
01863
01864 static void sip_monitor_instance_destructor(void *data)
01865 {
01866 struct sip_monitor_instance *monitor_instance = data;
01867 if (monitor_instance->subscription_pvt) {
01868 sip_pvt_lock(monitor_instance->subscription_pvt);
01869 monitor_instance->subscription_pvt->expiry = 0;
01870 transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 0, monitor_instance->subscribe_uri);
01871 sip_pvt_unlock(monitor_instance->subscription_pvt);
01872 dialog_unref(monitor_instance->subscription_pvt, "Unref monitor instance ref of subscription pvt");
01873 }
01874 if (monitor_instance->suspension_entry) {
01875 monitor_instance->suspension_entry->body[0] = '\0';
01876 transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_REMOVE ,monitor_instance->notify_uri);
01877 ao2_t_ref(monitor_instance->suspension_entry, -1, "Decrementing suspension entry refcount in sip_monitor_instance_destructor");
01878 }
01879 ast_string_field_free_memory(monitor_instance);
01880 }
01881
01882 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)
01883 {
01884 struct sip_monitor_instance *monitor_instance = ao2_alloc(sizeof(*monitor_instance), sip_monitor_instance_destructor);
01885
01886 if (!monitor_instance) {
01887 return NULL;
01888 }
01889
01890 if (ast_string_field_init(monitor_instance, 256)) {
01891 ao2_ref(monitor_instance, -1);
01892 return NULL;
01893 }
01894
01895 ast_string_field_set(monitor_instance, subscribe_uri, subscribe_uri);
01896 ast_string_field_set(monitor_instance, peername, peername);
01897 ast_string_field_set(monitor_instance, device_name, device_name);
01898 monitor_instance->core_id = core_id;
01899 ao2_link(sip_monitor_instances, monitor_instance);
01900 return monitor_instance;
01901 }
01902
01903 static int find_sip_monitor_instance_by_subscription_pvt(void *obj, void *arg, int flags)
01904 {
01905 struct sip_monitor_instance *monitor_instance = obj;
01906 return monitor_instance->subscription_pvt == arg ? CMP_MATCH | CMP_STOP : 0;
01907 }
01908
01909 static int find_sip_monitor_instance_by_suspension_entry(void *obj, void *arg, int flags)
01910 {
01911 struct sip_monitor_instance *monitor_instance = obj;
01912 return monitor_instance->suspension_entry == arg ? CMP_MATCH | CMP_STOP : 0;
01913 }
01914
01915 static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id);
01916 static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor);
01917 static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor);
01918 static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id);
01919 static void sip_cc_monitor_destructor(void *private_data);
01920
01921 static struct ast_cc_monitor_callbacks sip_cc_monitor_callbacks = {
01922 .type = "SIP",
01923 .request_cc = sip_cc_monitor_request_cc,
01924 .suspend = sip_cc_monitor_suspend,
01925 .unsuspend = sip_cc_monitor_unsuspend,
01926 .cancel_available_timer = sip_cc_monitor_cancel_available_timer,
01927 .destructor = sip_cc_monitor_destructor,
01928 };
01929
01930 static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id)
01931 {
01932 struct sip_monitor_instance *monitor_instance = monitor->private_data;
01933 enum ast_cc_service_type service = monitor->service_offered;
01934 int when;
01935
01936 if (!monitor_instance) {
01937 return -1;
01938 }
01939
01940 if (!(monitor_instance->subscription_pvt = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL))) {
01941 return -1;
01942 }
01943
01944 when = service == AST_CC_CCBS ? ast_get_ccbs_available_timer(monitor->interface->config_params) :
01945 ast_get_ccnr_available_timer(monitor->interface->config_params);
01946
01947 sip_pvt_lock(monitor_instance->subscription_pvt);
01948 ast_set_flag(&monitor_instance->subscription_pvt->flags[0], SIP_OUTGOING);
01949 create_addr(monitor_instance->subscription_pvt, monitor_instance->peername, 0, 1);
01950 ast_sip_ouraddrfor(&monitor_instance->subscription_pvt->sa, &monitor_instance->subscription_pvt->ourip, monitor_instance->subscription_pvt);
01951 monitor_instance->subscription_pvt->subscribed = CALL_COMPLETION;
01952 monitor_instance->subscription_pvt->expiry = when;
01953
01954 transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 2, monitor_instance->subscribe_uri);
01955 sip_pvt_unlock(monitor_instance->subscription_pvt);
01956
01957 ao2_t_ref(monitor, +1, "Adding a ref to the monitor for the scheduler");
01958 *available_timer_id = ast_sched_add(sched, when * 1000, ast_cc_available_timer_expire, monitor);
01959 return 0;
01960 }
01961
01962 static int construct_pidf_body(enum sip_cc_publish_state state, char *pidf_body, size_t size, const char *presentity)
01963 {
01964 struct ast_str *body = ast_str_alloca(size);
01965 char tuple_id[32];
01966
01967 generate_random_string(tuple_id, sizeof(tuple_id));
01968
01969
01970
01971
01972 ast_str_append(&body, 0, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
01973
01974
01975
01976
01977
01978
01979 ast_str_append(&body, 0, "<presence xmlns=\"urn:ietf:params:xml:ns:pidf\" entity=\"%s\">\n", presentity);
01980 ast_str_append(&body, 0, "<tuple id=\"%s\">\n", tuple_id);
01981 ast_str_append(&body, 0, "<status><basic>%s</basic></status>\n", state == CC_OPEN ? "open" : "closed");
01982 ast_str_append(&body, 0, "</tuple>\n");
01983 ast_str_append(&body, 0, "</presence>\n");
01984 ast_copy_string(pidf_body, ast_str_buffer(body), size);
01985 return 0;
01986 }
01987
01988 static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor)
01989 {
01990 struct sip_monitor_instance *monitor_instance = monitor->private_data;
01991 enum sip_publish_type publish_type;
01992 struct cc_epa_entry *cc_entry;
01993
01994 if (!monitor_instance) {
01995 return -1;
01996 }
01997
01998 if (!monitor_instance->suspension_entry) {
01999
02000 if (!(monitor_instance->suspension_entry = create_epa_entry("call-completion", monitor_instance->peername))) {
02001 ast_log(LOG_WARNING, "Unable to allocate sip EPA entry for call-completion\n");
02002 ao2_ref(monitor_instance, -1);
02003 return -1;
02004 }
02005 if (!(cc_entry = ast_calloc(1, sizeof(*cc_entry)))) {
02006 ast_log(LOG_WARNING, "Unable to allocate space for instance data of EPA entry for call-completion\n");
02007 ao2_ref(monitor_instance, -1);
02008 return -1;
02009 }
02010 cc_entry->core_id = monitor->core_id;
02011 monitor_instance->suspension_entry->instance_data = cc_entry;
02012 publish_type = SIP_PUBLISH_INITIAL;
02013 } else {
02014 publish_type = SIP_PUBLISH_MODIFY;
02015 cc_entry = monitor_instance->suspension_entry->instance_data;
02016 }
02017
02018 cc_entry->current_state = CC_CLOSED;
02019
02020 if (ast_strlen_zero(monitor_instance->notify_uri)) {
02021
02022
02023
02024
02025
02026
02027
02028
02029
02030
02031
02032
02033 return 0;
02034 }
02035 construct_pidf_body(CC_CLOSED, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
02036 return transmit_publish(monitor_instance->suspension_entry, publish_type, monitor_instance->notify_uri);
02037 }
02038
02039 static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor)
02040 {
02041 struct sip_monitor_instance *monitor_instance = monitor->private_data;
02042 struct cc_epa_entry *cc_entry;
02043
02044 if (!monitor_instance) {
02045 return -1;
02046 }
02047
02048 ast_assert(monitor_instance->suspension_entry != NULL);
02049
02050 cc_entry = monitor_instance->suspension_entry->instance_data;
02051 cc_entry->current_state = CC_OPEN;
02052 if (ast_strlen_zero(monitor_instance->notify_uri)) {
02053
02054
02055
02056
02057 return 0;
02058 }
02059 construct_pidf_body(CC_OPEN, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
02060 return transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_MODIFY, monitor_instance->notify_uri);
02061 }
02062
02063 static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id)
02064 {
02065 if (*sched_id != -1) {
02066 AST_SCHED_DEL(sched, *sched_id);
02067 ao2_t_ref(monitor, -1, "Removing scheduler's reference to the monitor");
02068 }
02069 return 0;
02070 }
02071
02072 static void sip_cc_monitor_destructor(void *private_data)
02073 {
02074 struct sip_monitor_instance *monitor_instance = private_data;
02075 ao2_unlink(sip_monitor_instances, monitor_instance);
02076 ast_module_unref(ast_module_info->self);
02077 }
02078
02079 static int sip_get_cc_information(struct sip_request *req, char *subscribe_uri, size_t size, enum ast_cc_service_type *service)
02080 {
02081 char *call_info = ast_strdupa(get_header(req, "Call-Info"));
02082 char *uri;
02083 char *purpose;
02084 char *service_str;
02085 static const char cc_purpose[] = "purpose=call-completion";
02086 static const int cc_purpose_len = sizeof(cc_purpose) - 1;
02087
02088 if (ast_strlen_zero(call_info)) {
02089
02090 return -1;
02091 }
02092
02093 uri = strsep(&call_info, ";");
02094
02095 while ((purpose = strsep(&call_info, ";"))) {
02096 if (!strncmp(purpose, cc_purpose, cc_purpose_len)) {
02097 break;
02098 }
02099 }
02100 if (!purpose) {
02101
02102 return -1;
02103 }
02104
02105
02106 while ((service_str = strsep(&call_info, ";"))) {
02107 if (!strncmp(service_str, "m=", 2)) {
02108 break;
02109 }
02110 }
02111 if (!service_str) {
02112
02113
02114
02115 service_str = "BS";
02116 } else {
02117
02118
02119
02120 strsep(&service_str, "=");
02121 }
02122
02123 if ((*service = service_string_to_service_type(service_str)) == AST_CC_NONE) {
02124
02125 return -1;
02126 }
02127
02128 ast_copy_string(subscribe_uri, get_in_brackets(uri), size);
02129
02130 return 0;
02131 }
02132
02133
02134
02135
02136
02137
02138
02139
02140
02141
02142
02143
02144
02145
02146
02147
02148
02149
02150 static void sip_handle_cc(struct sip_pvt *pvt, struct sip_request *req, enum ast_cc_service_type service)
02151 {
02152 enum ast_cc_monitor_policies monitor_policy = ast_get_cc_monitor_policy(pvt->cc_params);
02153 int core_id;
02154 char interface_name[AST_CHANNEL_NAME];
02155
02156 if (monitor_policy == AST_CC_MONITOR_NEVER) {
02157
02158 return;
02159 }
02160
02161 if ((core_id = ast_cc_get_current_core_id(pvt->owner)) == -1) {
02162
02163 return;
02164 }
02165
02166 ast_channel_get_device_name(pvt->owner, interface_name, sizeof(interface_name));
02167
02168 if (monitor_policy == AST_CC_MONITOR_ALWAYS || monitor_policy == AST_CC_MONITOR_NATIVE) {
02169 char subscribe_uri[SIPBUFSIZE];
02170 char device_name[AST_CHANNEL_NAME];
02171 enum ast_cc_service_type offered_service;
02172 struct sip_monitor_instance *monitor_instance;
02173 if (sip_get_cc_information(req, subscribe_uri, sizeof(subscribe_uri), &offered_service)) {
02174
02175
02176
02177
02178 goto generic;
02179 }
02180 ast_channel_get_device_name(pvt->owner, device_name, sizeof(device_name));
02181 if (!(monitor_instance = sip_monitor_instance_init(core_id, subscribe_uri, pvt->peername, device_name))) {
02182
02183 goto generic;
02184 }
02185
02186
02187
02188
02189 ast_module_ref(ast_module_info->self);
02190 ast_queue_cc_frame(pvt->owner, "SIP", pvt->dialstring, offered_service, monitor_instance);
02191 ao2_ref(monitor_instance, -1);
02192 return;
02193 }
02194
02195 generic:
02196 if (monitor_policy == AST_CC_MONITOR_GENERIC || monitor_policy == AST_CC_MONITOR_ALWAYS) {
02197 ast_queue_cc_frame(pvt->owner, AST_CC_GENERIC_MONITOR_TYPE, interface_name, service, NULL);
02198 }
02199 }
02200
02201
02202 static struct ast_tls_config sip_tls_cfg;
02203
02204
02205 static struct ast_tls_config default_tls_cfg;
02206
02207
02208 static struct ast_tcptls_session_args sip_tcp_desc = {
02209 .accept_fd = -1,
02210 .master = AST_PTHREADT_NULL,
02211 .tls_cfg = NULL,
02212 .poll_timeout = -1,
02213 .name = "SIP TCP server",
02214 .accept_fn = ast_tcptls_server_root,
02215 .worker_fn = sip_tcp_worker_fn,
02216 };
02217
02218
02219 static struct ast_tcptls_session_args sip_tls_desc = {
02220 .accept_fd = -1,
02221 .master = AST_PTHREADT_NULL,
02222 .tls_cfg = &sip_tls_cfg,
02223 .poll_timeout = -1,
02224 .name = "SIP TLS server",
02225 .accept_fn = ast_tcptls_server_root,
02226 .worker_fn = sip_tcp_worker_fn,
02227 };
02228
02229
02230
02231 #define append_history(p, event, fmt , args... ) append_history_full(p, "%-15s " fmt, event, ## args)
02232
02233 struct sip_pvt *dialog_ref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
02234 {
02235 if (p)
02236 #ifdef REF_DEBUG
02237 __ao2_ref_debug(p, 1, tag, file, line, func);
02238 #else
02239 ao2_ref(p, 1);
02240 #endif
02241 else
02242 ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
02243 return p;
02244 }
02245
02246 struct sip_pvt *dialog_unref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
02247 {
02248 if (p)
02249 #ifdef REF_DEBUG
02250 __ao2_ref_debug(p, -1, tag, file, line, func);
02251 #else
02252 ao2_ref(p, -1);
02253 #endif
02254 return NULL;
02255 }
02256
02257
02258
02259
02260 static const char *map_x_s(const struct _map_x_s *table, int x, const char *errorstring)
02261 {
02262 const struct _map_x_s *cur;
02263
02264 for (cur = table; cur->s; cur++)
02265 if (cur->x == x)
02266 return cur->s;
02267 return errorstring;
02268 }
02269
02270
02271
02272
02273 static int map_s_x(const struct _map_x_s *table, const char *s, int errorvalue)
02274 {
02275 const struct _map_x_s *cur;
02276
02277 for (cur = table; cur->s; cur++)
02278 if (!strcasecmp(cur->s, s))
02279 return cur->x;
02280 return errorvalue;
02281 }
02282
02283 static enum AST_REDIRECTING_REASON sip_reason_str_to_code(const char *text)
02284 {
02285 enum AST_REDIRECTING_REASON ast = AST_REDIRECTING_REASON_UNKNOWN;
02286 int i;
02287
02288 for (i = 0; i < ARRAY_LEN(sip_reason_table); ++i) {
02289 if (!strcasecmp(text, sip_reason_table[i].text)) {
02290 ast = sip_reason_table[i].code;
02291 break;
02292 }
02293 }
02294
02295 return ast;
02296 }
02297
02298 static const char *sip_reason_code_to_str(enum AST_REDIRECTING_REASON code)
02299 {
02300 if (code >= 0 && code < ARRAY_LEN(sip_reason_table)) {
02301 return sip_reason_table[code].text;
02302 }
02303
02304 return "unknown";
02305 }
02306
02307
02308
02309
02310
02311
02312
02313
02314 #define check_request_transport(peer, tmpl) ({ \
02315 int ret = 0; \
02316 if (peer->socket.type == tmpl->socket.type) \
02317 ; \
02318 else if (!(peer->transports & tmpl->socket.type)) {\
02319 ast_log(LOG_ERROR, \
02320 "'%s' is not a valid transport for '%s'. we only use '%s'! ending call.\n", \
02321 get_transport(tmpl->socket.type), peer->name, get_transport_list(peer->transports) \
02322 ); \
02323 ret = 1; \
02324 } else if (peer->socket.type & SIP_TRANSPORT_TLS) { \
02325 ast_log(LOG_WARNING, \
02326 "peer '%s' HAS NOT USED (OR SWITCHED TO) TLS in favor of '%s' (but this was allowed in sip.conf)!\n", \
02327 peer->name, get_transport(tmpl->socket.type) \
02328 ); \
02329 } else { \
02330 ast_debug(1, \
02331 "peer '%s' has contacted us over %s even though we prefer %s.\n", \
02332 peer->name, get_transport(tmpl->socket.type), get_transport(peer->socket.type) \
02333 ); \
02334 }\
02335 (ret); \
02336 })
02337
02338
02339
02340
02341 static struct ast_variable *copy_vars(struct ast_variable *src)
02342 {
02343 struct ast_variable *res = NULL, *tmp, *v = NULL;
02344
02345 for (v = src ; v ; v = v->next) {
02346 if ((tmp = ast_variable_new(v->name, v->value, v->file))) {
02347 tmp->next = res;
02348 res = tmp;
02349 }
02350 }
02351 return res;
02352 }
02353
02354 static void tcptls_packet_destructor(void *obj)
02355 {
02356 struct tcptls_packet *packet = obj;
02357
02358 ast_free(packet->data);
02359 }
02360
02361 static void sip_tcptls_client_args_destructor(void *obj)
02362 {
02363 struct ast_tcptls_session_args *args = obj;
02364 if (args->tls_cfg) {
02365 ast_free(args->tls_cfg->certfile);
02366 ast_free(args->tls_cfg->pvtfile);
02367 ast_free(args->tls_cfg->cipher);
02368 ast_free(args->tls_cfg->cafile);
02369 ast_free(args->tls_cfg->capath);
02370
02371 ast_ssl_teardown(args->tls_cfg);
02372 }
02373 ast_free(args->tls_cfg);
02374 ast_free((char *) args->name);
02375 }
02376
02377 static void sip_threadinfo_destructor(void *obj)
02378 {
02379 struct sip_threadinfo *th = obj;
02380 struct tcptls_packet *packet;
02381 if (th->alert_pipe[1] > -1) {
02382 close(th->alert_pipe[0]);
02383 }
02384 if (th->alert_pipe[1] > -1) {
02385 close(th->alert_pipe[1]);
02386 }
02387 th->alert_pipe[0] = th->alert_pipe[1] = -1;
02388
02389 while ((packet = AST_LIST_REMOVE_HEAD(&th->packet_q, entry))) {
02390 ao2_t_ref(packet, -1, "thread destruction, removing packet from frame queue");
02391 }
02392
02393 if (th->tcptls_session) {
02394 ao2_t_ref(th->tcptls_session, -1, "remove tcptls_session for sip_threadinfo object");
02395 }
02396 }
02397
02398
02399 static struct sip_threadinfo *sip_threadinfo_create(struct ast_tcptls_session_instance *tcptls_session, int transport)
02400 {
02401 struct sip_threadinfo *th;
02402
02403 if (!tcptls_session || !(th = ao2_alloc(sizeof(*th), sip_threadinfo_destructor))) {
02404 return NULL;
02405 }
02406
02407 th->alert_pipe[0] = th->alert_pipe[1] = -1;
02408
02409 if (pipe(th->alert_pipe) == -1) {
02410 ao2_t_ref(th, -1, "Failed to open alert pipe on sip_threadinfo");
02411 ast_log(LOG_ERROR, "Could not create sip alert pipe in tcptls thread, error %s\n", strerror(errno));
02412 return NULL;
02413 }
02414 ao2_t_ref(tcptls_session, +1, "tcptls_session ref for sip_threadinfo object");
02415 th->tcptls_session = tcptls_session;
02416 th->type = transport ? transport : (tcptls_session->ssl ? SIP_TRANSPORT_TLS: SIP_TRANSPORT_TCP);
02417 ao2_t_link(threadt, th, "Adding new tcptls helper thread");
02418 ao2_t_ref(th, -1, "Decrementing threadinfo ref from alloc, only table ref remains");
02419 return th;
02420 }
02421
02422
02423 static int sip_tcptls_write(struct ast_tcptls_session_instance *tcptls_session, const void *buf, size_t len)
02424 {
02425 int res = len;
02426 struct sip_threadinfo *th = NULL;
02427 struct tcptls_packet *packet = NULL;
02428 struct sip_threadinfo tmp = {
02429 .tcptls_session = tcptls_session,
02430 };
02431 enum sip_tcptls_alert alert = TCPTLS_ALERT_DATA;
02432
02433 if (!tcptls_session) {
02434 return XMIT_ERROR;
02435 }
02436
02437 ast_mutex_lock(&tcptls_session->lock);
02438
02439 if ((tcptls_session->fd == -1) ||
02440 !(th = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread")) ||
02441 !(packet = ao2_alloc(sizeof(*packet), tcptls_packet_destructor)) ||
02442 !(packet->data = ast_str_create(len))) {
02443 goto tcptls_write_setup_error;
02444 }
02445
02446
02447 ast_str_set(&packet->data, 0, "%s", (char *) buf);
02448 packet->len = len;
02449
02450
02451
02452
02453 ao2_lock(th);
02454 if (write(th->alert_pipe[1], &alert, sizeof(alert)) == -1) {
02455 ast_log(LOG_ERROR, "write() to alert pipe failed: %s\n", strerror(errno));
02456 ao2_t_ref(packet, -1, "could not write to alert pipe, remove packet");
02457 packet = NULL;
02458 res = XMIT_ERROR;
02459 } else {
02460 AST_LIST_INSERT_TAIL(&th->packet_q, packet, entry);
02461 }
02462 ao2_unlock(th);
02463
02464 ast_mutex_unlock(&tcptls_session->lock);
02465 ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo object after finding it");
02466 return res;
02467
02468 tcptls_write_setup_error:
02469 if (th) {
02470 ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo obj, could not create packet");
02471 }
02472 if (packet) {
02473 ao2_t_ref(packet, -1, "could not allocate packet's data");
02474 }
02475 ast_mutex_unlock(&tcptls_session->lock);
02476
02477 return XMIT_ERROR;
02478 }
02479
02480
02481 static void *sip_tcp_worker_fn(void *data)
02482 {
02483 struct ast_tcptls_session_instance *tcptls_session = data;
02484
02485 return _sip_tcp_helper_thread(tcptls_session);
02486 }
02487
02488
02489
02490
02491
02492
02493
02494
02495 static int sip_check_authtimeout(time_t start)
02496 {
02497 int timeout;
02498 time_t now;
02499 if(time(&now) == -1) {
02500 ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
02501 return -1;
02502 }
02503
02504 timeout = (authtimeout - (now - start)) * 1000;
02505 if (timeout < 0) {
02506
02507 return 0;
02508 }
02509
02510 return timeout;
02511 }
02512
02513
02514
02515
02516
02517
02518
02519
02520
02521
02522
02523
02524
02525
02526
02527
02528
02529
02530
02531
02532
02533 static int sip_tls_read(struct sip_request *req, struct sip_request *reqcpy, struct ast_tcptls_session_instance *tcptls_session,
02534 int authenticated, time_t start, struct sip_threadinfo *me)
02535 {
02536 int res, content_length, after_poll = 1, need_poll = 1;
02537 size_t datalen = ast_str_strlen(req->data);
02538 char buf[1024] = "";
02539 int timeout = -1;
02540
02541
02542 while (datalen < 4 || strncmp(REQ_OFFSET_TO_STR(req, data->used - 4), "\r\n\r\n", 4)) {
02543 if (!tcptls_session->client && !authenticated) {
02544 if ((timeout = sip_check_authtimeout(start)) < 0) {
02545 ast_debug(2, "SIP TLS server failed to determine authentication timeout\n");
02546 return -1;
02547 }
02548
02549 if (timeout == 0) {
02550 ast_debug(2, "SIP TLS server timed out\n");
02551 return -1;
02552 }
02553 } else {
02554 timeout = -1;
02555 }
02556
02557
02558
02559
02560 if (need_poll) {
02561 need_poll = 0;
02562 after_poll = 1;
02563 res = ast_wait_for_input(tcptls_session->fd, timeout);
02564 if (res < 0) {
02565 ast_debug(2, "SIP TLS server :: ast_wait_for_input returned %d\n", res);
02566 return -1;
02567 } else if (res == 0) {
02568
02569 ast_debug(2, "SIP TLS server timed out\n");
02570 return -1;
02571 }
02572 }
02573
02574 ast_mutex_lock(&tcptls_session->lock);
02575 if (!fgets(buf, sizeof(buf), tcptls_session->f)) {
02576 ast_mutex_unlock(&tcptls_session->lock);
02577 if (after_poll) {
02578 return -1;
02579 } else {
02580 need_poll = 1;
02581 continue;
02582 }
02583 }
02584 ast_mutex_unlock(&tcptls_session->lock);
02585 after_poll = 0;
02586 if (me->stop) {
02587 return -1;
02588 }
02589 ast_str_append(&req->data, 0, "%s", buf);
02590
02591 datalen = ast_str_strlen(req->data);
02592 if (datalen > SIP_MAX_PACKET_SIZE) {
02593 ast_log(LOG_WARNING, "Rejecting TLS packet from '%s' because way too large: %zu\n",
02594 ast_sockaddr_stringify(&tcptls_session->remote_address), datalen);
02595 return -1;
02596 }
02597 }
02598 copy_request(reqcpy, req);
02599 parse_request(reqcpy);
02600
02601 if (sscanf(get_header(reqcpy, "Content-Length"), "%30d", &content_length)) {
02602 while (content_length > 0) {
02603 size_t bytes_read;
02604 if (!tcptls_session->client && !authenticated) {
02605 if ((timeout = sip_check_authtimeout(start)) < 0) {
02606 return -1;
02607 }
02608
02609 if (timeout == 0) {
02610 ast_debug(2, "SIP TLS server timed out\n");
02611 return -1;
02612 }
02613 } else {
02614 timeout = -1;
02615 }
02616
02617 if (need_poll) {
02618 need_poll = 0;
02619 after_poll = 1;
02620 res = ast_wait_for_input(tcptls_session->fd, timeout);
02621 if (res < 0) {
02622 ast_debug(2, "SIP TLS server :: ast_wait_for_input returned %d\n", res);
02623 return -1;
02624 } else if (res == 0) {
02625
02626 ast_debug(2, "SIP TLS server timed out\n");
02627 return -1;
02628 }
02629 }
02630
02631 ast_mutex_lock(&tcptls_session->lock);
02632 if (!(bytes_read = fread(buf, 1, MIN(sizeof(buf) - 1, content_length), tcptls_session->f))) {
02633 ast_mutex_unlock(&tcptls_session->lock);
02634 if (after_poll) {
02635 return -1;
02636 } else {
02637 need_poll = 1;
02638 continue;
02639 }
02640 }
02641 buf[bytes_read] = '\0';
02642 ast_mutex_unlock(&tcptls_session->lock);
02643 after_poll = 0;
02644 if (me->stop) {
02645 return -1;
02646 }
02647 content_length -= strlen(buf);
02648 ast_str_append(&req->data, 0, "%s", buf);
02649
02650 datalen = ast_str_strlen(req->data);
02651 if (datalen > SIP_MAX_PACKET_SIZE) {
02652 ast_log(LOG_WARNING, "Rejecting TLS packet from '%s' because way too large: %zu\n",
02653 ast_sockaddr_stringify(&tcptls_session->remote_address), datalen);
02654 return -1;
02655 }
02656 }
02657 }
02658
02659
02660 return 0;
02661 }
02662
02663
02664
02665
02666 enum message_integrity {
02667
02668
02669
02670
02671 MESSAGE_INVALID,
02672
02673
02674
02675 MESSAGE_FRAGMENT,
02676
02677
02678
02679
02680 MESSAGE_FRAGMENT_COMPLETE,
02681
02682
02683
02684 MESSAGE_COMPLETE,
02685 };
02686
02687
02688
02689
02690
02691
02692
02693
02694 static int read_raw_content_length(const char *message)
02695 {
02696 char *content_length_str;
02697 int content_length = -1;
02698
02699 struct ast_str *msg_copy;
02700 char *msg;
02701
02702
02703 if (!(msg_copy = ast_str_create(strlen(message) + 1))) {
02704 return -1;
02705 }
02706 ast_str_set(&msg_copy, 0, "%s", message);
02707
02708 if (sip_cfg.pedanticsipchecking) {
02709 lws2sws(msg_copy);
02710 }
02711
02712 msg = ast_str_buffer(msg_copy);
02713
02714
02715 if ((content_length_str = strcasestr(msg, "\nContent-Length:"))) {
02716 content_length_str += sizeof("\nContent-Length:") - 1;
02717 } else if ((content_length_str = strcasestr(msg, "\nl:"))) {
02718 content_length_str += sizeof("\nl:") - 1;
02719 } else {
02720
02721
02722
02723
02724
02725 goto done;
02726 }
02727
02728
02729 if (!strchr(content_length_str, '\n')) {
02730 goto done;
02731 }
02732
02733 if (sscanf(content_length_str, "%30d", &content_length) != 1) {
02734 content_length = -1;
02735 }
02736
02737 done:
02738 ast_free(msg_copy);
02739 return content_length;
02740 }
02741
02742
02743
02744
02745
02746
02747
02748
02749
02750
02751
02752
02753
02754 static enum message_integrity check_message_integrity(struct ast_str **request, struct ast_str **overflow)
02755 {
02756 char *message = ast_str_buffer(*request);
02757 char *body;
02758 int content_length;
02759 int message_len = ast_str_strlen(*request);
02760 int body_len;
02761
02762
02763
02764
02765
02766
02767 body = strstr(message, "\r\n\r\n");
02768 if (!body) {
02769
02770
02771
02772 return MESSAGE_FRAGMENT;
02773 }
02774 body += sizeof("\r\n\r\n") - 1;
02775 body_len = message_len - (body - message);
02776
02777 body[-1] = '\0';
02778 content_length = read_raw_content_length(message);
02779 body[-1] = '\n';
02780
02781 if (content_length < 0) {
02782 return MESSAGE_INVALID;
02783 } else if (content_length == 0) {
02784
02785
02786
02787
02788 if (body_len == 0) {
02789 return MESSAGE_COMPLETE;
02790 } else {
02791 ast_str_append(overflow, 0, "%s", body);
02792 ast_str_truncate(*request, message_len - body_len);
02793 return MESSAGE_FRAGMENT_COMPLETE;
02794 }
02795 }
02796
02797
02798
02799 if (body_len < content_length) {
02800
02801 return MESSAGE_FRAGMENT;
02802 } else if (body_len > content_length) {
02803
02804
02805
02806 ast_str_append(overflow, 0, "%s", body + content_length);
02807 ast_str_truncate(*request, message_len - (body_len - content_length));
02808 return MESSAGE_FRAGMENT_COMPLETE;
02809 } else {
02810
02811 return MESSAGE_COMPLETE;
02812 }
02813 }
02814
02815
02816
02817
02818
02819
02820
02821
02822
02823 static int sip_tcp_read(struct sip_request *req, struct ast_tcptls_session_instance *tcptls_session,
02824 int authenticated, time_t start)
02825 {
02826 enum message_integrity message_integrity = MESSAGE_FRAGMENT;
02827
02828 while (message_integrity == MESSAGE_FRAGMENT) {
02829 size_t datalen;
02830
02831 if (ast_str_strlen(tcptls_session->overflow_buf) == 0) {
02832 char readbuf[4097];
02833 int timeout;
02834 int res;
02835 if (!tcptls_session->client && !authenticated) {
02836 if ((timeout = sip_check_authtimeout(start)) < 0) {
02837 return -1;
02838 }
02839
02840 if (timeout == 0) {
02841 ast_debug(2, "SIP TCP server timed out\n");
02842 return -1;
02843 }
02844 } else {
02845 timeout = -1;
02846 }
02847 res = ast_wait_for_input(tcptls_session->fd, timeout);
02848 if (res < 0) {
02849 ast_debug(2, "SIP TCP server :: ast_wait_for_input returned %d\n", res);
02850 return -1;
02851 } else if (res == 0) {
02852 ast_debug(2, "SIP TCP server timed out\n");
02853 return -1;
02854 }
02855
02856 res = recv(tcptls_session->fd, readbuf, sizeof(readbuf) - 1, 0);
02857 if (res < 0) {
02858 ast_debug(2, "SIP TCP server error when receiving data\n");
02859 return -1;
02860 } else if (res == 0) {
02861 ast_debug(2, "SIP TCP server has shut down\n");
02862 return -1;
02863 }
02864 readbuf[res] = '\0';
02865 ast_str_append(&req->data, 0, "%s", readbuf);
02866 } else {
02867 ast_str_append(&req->data, 0, "%s", ast_str_buffer(tcptls_session->overflow_buf));
02868 ast_str_reset(tcptls_session->overflow_buf);
02869 }
02870
02871 datalen = ast_str_strlen(req->data);
02872 if (datalen > SIP_MAX_PACKET_SIZE) {
02873 ast_log(LOG_WARNING, "Rejecting TCP packet from '%s' because way too large: %zu\n",
02874 ast_sockaddr_stringify(&tcptls_session->remote_address), datalen);
02875 return -1;
02876 }
02877
02878 message_integrity = check_message_integrity(&req->data, &tcptls_session->overflow_buf);
02879 }
02880
02881 return 0;
02882 }
02883
02884
02885
02886
02887 static void *_sip_tcp_helper_thread(struct ast_tcptls_session_instance *tcptls_session)
02888 {
02889 int res, timeout = -1, authenticated = 0, flags;
02890 time_t start;
02891 struct sip_request req = { 0, } , reqcpy = { 0, };
02892 struct sip_threadinfo *me = NULL;
02893 char buf[1024] = "";
02894 struct pollfd fds[2] = { { 0 }, { 0 }, };
02895 struct ast_tcptls_session_args *ca = NULL;
02896
02897
02898
02899
02900
02901
02902
02903
02904
02905
02906
02907
02908 if (!tcptls_session->client) {
02909 if (ast_atomic_fetchadd_int(&unauth_sessions, +1) >= authlimit) {
02910
02911 goto cleanup;
02912 }
02913
02914 if ((flags = fcntl(tcptls_session->fd, F_GETFL)) == -1) {
02915 ast_log(LOG_ERROR, "error setting socket to non blocking mode, fcntl() failed: %s\n", strerror(errno));
02916 goto cleanup;
02917 }
02918
02919 flags |= O_NONBLOCK;
02920 if (fcntl(tcptls_session->fd, F_SETFL, flags) == -1) {
02921 ast_log(LOG_ERROR, "error setting socket to non blocking mode, fcntl() failed: %s\n", strerror(errno));
02922 goto cleanup;
02923 }
02924
02925 if (!(me = sip_threadinfo_create(tcptls_session, tcptls_session->ssl ? SIP_TRANSPORT_TLS : SIP_TRANSPORT_TCP))) {
02926 goto cleanup;
02927 }
02928 ao2_t_ref(me, +1, "Adding threadinfo ref for tcp_helper_thread");
02929 } else {
02930 struct sip_threadinfo tmp = {
02931 .tcptls_session = tcptls_session,
02932 };
02933
02934 if ((!(ca = tcptls_session->parent)) ||
02935 (!(me = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread"))) ||
02936 (!(tcptls_session = ast_tcptls_client_start(tcptls_session)))) {
02937 goto cleanup;
02938 }
02939 }
02940
02941 flags = 1;
02942 if (setsockopt(tcptls_session->fd, SOL_SOCKET, SO_KEEPALIVE, &flags, sizeof(flags))) {
02943 ast_log(LOG_ERROR, "error enabling TCP keep-alives on sip socket: %s\n", strerror(errno));
02944 goto cleanup;
02945 }
02946
02947 me->threadid = pthread_self();
02948 ast_debug(2, "Starting thread for %s server\n", tcptls_session->ssl ? "TLS" : "TCP");
02949
02950
02951 fds[0].fd = tcptls_session->fd;
02952 fds[1].fd = me->alert_pipe[0];
02953 fds[0].events = fds[1].events = POLLIN | POLLPRI;
02954
02955 if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
02956 goto cleanup;
02957 }
02958 if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET))) {
02959 goto cleanup;
02960 }
02961
02962 if(time(&start) == -1) {
02963 ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
02964 goto cleanup;
02965 }
02966
02967 for (;;) {
02968 struct ast_str *str_save;
02969
02970 if (!tcptls_session->client && req.authenticated && !authenticated) {
02971 authenticated = 1;
02972 ast_atomic_fetchadd_int(&unauth_sessions, -1);
02973 }
02974
02975
02976 if (!tcptls_session->client && !authenticated ) {
02977 if ((timeout = sip_check_authtimeout(start)) < 0) {
02978 goto cleanup;
02979 }
02980
02981 if (timeout == 0) {
02982 ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "TLS": "TCP");
02983 goto cleanup;
02984 }
02985 } else {
02986 timeout = -1;
02987 }
02988
02989 if (ast_str_strlen(tcptls_session->overflow_buf) == 0) {
02990 res = ast_poll(fds, 2, timeout);
02991 if (res < 0) {
02992 ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", tcptls_session->ssl ? "TLS": "TCP", res);
02993 goto cleanup;
02994 } else if (res == 0) {
02995
02996 ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "TLS": "TCP");
02997 goto cleanup;
02998 }
02999 }
03000
03001
03002
03003
03004
03005 if (fds[0].revents || (ast_str_strlen(tcptls_session->overflow_buf) > 0)) {
03006 fds[0].revents = 0;
03007
03008
03009 str_save = req.data;
03010 memset(&req, 0, sizeof(req));
03011 req.data = str_save;
03012 ast_str_reset(req.data);
03013
03014 str_save = reqcpy.data;
03015 memset(&reqcpy, 0, sizeof(reqcpy));
03016 reqcpy.data = str_save;
03017 ast_str_reset(reqcpy.data);
03018
03019 memset(buf, 0, sizeof(buf));
03020
03021 if (tcptls_session->ssl) {
03022 set_socket_transport(&req.socket, SIP_TRANSPORT_TLS);
03023 req.socket.port = htons(ourport_tls);
03024 } else {
03025 set_socket_transport(&req.socket, SIP_TRANSPORT_TCP);
03026 req.socket.port = htons(ourport_tcp);
03027 }
03028 req.socket.fd = tcptls_session->fd;
03029
03030 if (tcptls_session->ssl) {
03031 res = sip_tls_read(&req, &reqcpy, tcptls_session, authenticated, start, me);
03032 } else {
03033 res = sip_tcp_read(&req, tcptls_session, authenticated, start);
03034 }
03035
03036 if (res < 0) {
03037 goto cleanup;
03038 }
03039
03040 req.socket.tcptls_session = tcptls_session;
03041 handle_request_do(&req, &tcptls_session->remote_address);
03042 }
03043
03044 if (fds[1].revents) {
03045 enum sip_tcptls_alert alert;
03046 struct tcptls_packet *packet;
03047
03048 fds[1].revents = 0;
03049
03050 if (read(me->alert_pipe[0], &alert, sizeof(alert)) == -1) {
03051 ast_log(LOG_ERROR, "read() failed: %s\n", strerror(errno));
03052 continue;
03053 }
03054
03055 switch (alert) {
03056 case TCPTLS_ALERT_STOP:
03057 goto cleanup;
03058 case TCPTLS_ALERT_DATA:
03059 ao2_lock(me);
03060 if (!(packet = AST_LIST_REMOVE_HEAD(&me->packet_q, entry))) {
03061 ast_log(LOG_WARNING, "TCPTLS thread alert_pipe indicated packet should be sent, but frame_q is empty\n");
03062 }
03063 ao2_unlock(me);
03064
03065 if (packet) {
03066 if (ast_tcptls_server_write(tcptls_session, ast_str_buffer(packet->data), packet->len) == -1) {
03067 ast_log(LOG_WARNING, "Failure to write to tcp/tls socket\n");
03068 }
03069 ao2_t_ref(packet, -1, "tcptls packet sent, this is no longer needed");
03070 }
03071 break;
03072 default:
03073 ast_log(LOG_ERROR, "Unknown tcptls thread alert '%d'\n", alert);
03074 }
03075 }
03076 }
03077
03078 ast_debug(2, "Shutting down thread for %s server\n", tcptls_session->ssl ? "TLS" : "TCP");
03079
03080 cleanup:
03081 if (tcptls_session && !tcptls_session->client && !authenticated) {
03082 ast_atomic_fetchadd_int(&unauth_sessions, -1);
03083 }
03084
03085 if (me) {
03086 ao2_t_unlink(threadt, me, "Removing tcptls helper thread, thread is closing");
03087 ao2_t_ref(me, -1, "Removing tcp_helper_threads threadinfo ref");
03088 }
03089 deinit_req(&reqcpy);
03090 deinit_req(&req);
03091
03092
03093 if (ca) {
03094 ao2_t_ref(ca, -1, "closing tcptls thread, getting rid of client tcptls_session arguments");
03095 }
03096
03097 if (tcptls_session) {
03098 ast_mutex_lock(&tcptls_session->lock);
03099 ast_tcptls_close_session_file(tcptls_session);
03100 tcptls_session->parent = NULL;
03101 ast_mutex_unlock(&tcptls_session->lock);
03102
03103 ao2_ref(tcptls_session, -1);
03104 tcptls_session = NULL;
03105 }
03106 return NULL;
03107 }
03108
03109 #ifdef REF_DEBUG
03110 #define ref_peer(arg1,arg2) _ref_peer((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
03111 #define unref_peer(arg1,arg2) _unref_peer((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
03112 static struct sip_peer *_ref_peer(struct sip_peer *peer, char *tag, char *file, int line, const char *func)
03113 {
03114 if (peer)
03115 __ao2_ref_debug(peer, 1, tag, file, line, func);
03116 else
03117 ast_log(LOG_ERROR, "Attempt to Ref a null peer pointer\n");
03118 return peer;
03119 }
03120
03121 static struct sip_peer *_unref_peer(struct sip_peer *peer, char *tag, char *file, int line, const char *func)
03122 {
03123 if (peer)
03124 __ao2_ref_debug(peer, -1, tag, file, line, func);
03125 return NULL;
03126 }
03127 #else
03128
03129
03130
03131
03132
03133 static void *unref_peer(struct sip_peer *peer, char *tag)
03134 {
03135 ao2_t_ref(peer, -1, tag);
03136 return NULL;
03137 }
03138
03139 static struct sip_peer *ref_peer(struct sip_peer *peer, char *tag)
03140 {
03141 ao2_t_ref(peer, 1, tag);
03142 return peer;
03143 }
03144 #endif
03145
03146 static void peer_sched_cleanup(struct sip_peer *peer)
03147 {
03148 if (peer->pokeexpire != -1) {
03149 AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
03150 unref_peer(peer, "removing poke peer ref"));
03151 }
03152 if (peer->expire != -1) {
03153 AST_SCHED_DEL_UNREF(sched, peer->expire,
03154 unref_peer(peer, "remove register expire ref"));
03155 }
03156 }
03157
03158 typedef enum {
03159 SIP_PEERS_MARKED,
03160 SIP_PEERS_ALL,
03161 } peer_unlink_flag_t;
03162
03163
03164
03165 static int match_and_cleanup_peer_sched(void *peerobj, void *arg, int flags)
03166 {
03167 struct sip_peer *peer = peerobj;
03168 peer_unlink_flag_t which = *(peer_unlink_flag_t *)arg;
03169
03170 if (which == SIP_PEERS_ALL || peer->the_mark) {
03171 peer_sched_cleanup(peer);
03172 if (peer->dnsmgr) {
03173 ast_dnsmgr_release(peer->dnsmgr);
03174 peer->dnsmgr = NULL;
03175 unref_peer(peer, "Release peer from dnsmgr");
03176 }
03177 return CMP_MATCH;
03178 }
03179 return 0;
03180 }
03181
03182 static void unlink_peers_from_tables(peer_unlink_flag_t flag)
03183 {
03184 ao2_t_callback(peers, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE,
03185 match_and_cleanup_peer_sched, &flag, "initiating callback to remove marked peers");
03186 ao2_t_callback(peers_by_ip, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE,
03187 match_and_cleanup_peer_sched, &flag, "initiating callback to remove marked peers");
03188 }
03189
03190
03191 static void unlink_marked_peers_from_tables(void)
03192 {
03193 unlink_peers_from_tables(SIP_PEERS_MARKED);
03194 }
03195
03196 static void unlink_all_peers_from_tables(void)
03197 {
03198 unlink_peers_from_tables(SIP_PEERS_ALL);
03199 }
03200
03201
03202 static void unlink_peer_from_tables(struct sip_peer *peer)
03203 {
03204 ao2_t_unlink(peers, peer, "ao2_unlink of peer from peers table");
03205 if (!ast_sockaddr_isnull(&peer->addr)) {
03206 ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
03207 }
03208 }
03209
03210
03211
03212
03213
03214
03215
03216
03217
03218
03219
03220
03221 static void ref_proxy(struct sip_pvt *pvt, struct sip_proxy *proxy)
03222 {
03223 struct sip_proxy *old_obproxy = pvt->outboundproxy;
03224
03225
03226
03227 if (proxy && proxy != &sip_cfg.outboundproxy) {
03228 ao2_ref(proxy, +1);
03229 }
03230 pvt->outboundproxy = proxy;
03231 if (old_obproxy && old_obproxy != &sip_cfg.outboundproxy) {
03232 ao2_ref(old_obproxy, -1);
03233 }
03234 }
03235
03236
03237
03238
03239
03240
03241
03242
03243 void dialog_unlink_all(struct sip_pvt *dialog)
03244 {
03245 struct sip_pkt *cp;
03246 struct ast_channel *owner;
03247
03248 dialog_ref(dialog, "Let's bump the count in the unlink so it doesn't accidentally become dead before we are done");
03249
03250 ao2_t_unlink(dialogs, dialog, "unlinking dialog via ao2_unlink");
03251
03252
03253 owner = sip_pvt_lock_full(dialog);
03254 if (owner) {
03255 ast_debug(1, "Detaching from channel %s\n", owner->name);
03256 owner->tech_pvt = dialog_unref(owner->tech_pvt, "resetting channel dialog ptr in unlink_all");
03257 ast_channel_unlock(owner);
03258 ast_channel_unref(owner);
03259 dialog->owner = NULL;
03260 }
03261 sip_pvt_unlock(dialog);
03262
03263 if (dialog->registry) {
03264 if (dialog->registry->call == dialog) {
03265 dialog->registry->call = dialog_unref(dialog->registry->call, "nulling out the registry's call dialog field in unlink_all");
03266 }
03267 dialog->registry = registry_unref(dialog->registry, "delete dialog->registry");
03268 }
03269 if (dialog->stateid != -1) {
03270 ast_extension_state_del(dialog->stateid, cb_extensionstate);
03271 dialog->stateid = -1;
03272 }
03273
03274 if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog) {
03275 dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
03276 }
03277 if (dialog->relatedpeer && dialog->relatedpeer->call == dialog) {
03278 dialog->relatedpeer->call = dialog_unref(dialog->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
03279 }
03280
03281
03282 while((cp = dialog->packets)) {
03283 dialog->packets = dialog->packets->next;
03284 AST_SCHED_DEL(sched, cp->retransid);
03285 dialog_unref(cp->owner, "remove all current packets in this dialog, and the pointer to the dialog too as part of __sip_destroy");
03286 if (cp->data) {
03287 ast_free(cp->data);
03288 }
03289 ast_free(cp);
03290 }
03291
03292 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"));
03293
03294 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"));
03295
03296 if (dialog->autokillid > -1) {
03297 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"));
03298 }
03299
03300 if (dialog->request_queue_sched_id > -1) {
03301 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"));
03302 }
03303
03304 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"));
03305
03306 if (dialog->t38id > -1) {
03307 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"));
03308 }
03309
03310 if (dialog->stimer) {
03311 stop_session_timer(dialog);
03312 }
03313
03314 dialog_unref(dialog, "Let's unbump the count in the unlink so the poor pvt can disappear if it is time");
03315 }
03316
03317 void *registry_unref(struct sip_registry *reg, char *tag)
03318 {
03319 ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount - 1);
03320 ASTOBJ_UNREF(reg, sip_registry_destroy);
03321 return NULL;
03322 }
03323
03324
03325 static struct sip_registry *registry_addref(struct sip_registry *reg, char *tag)
03326 {
03327 ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount + 1);
03328 return ASTOBJ_REF(reg);
03329 }
03330
03331
03332 static struct ast_udptl_protocol sip_udptl = {
03333 .type = "SIP",
03334 .get_udptl_info = sip_get_udptl_peer,
03335 .set_udptl_peer = sip_set_udptl_peer,
03336 };
03337
03338 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
03339 __attribute__((format(printf, 2, 3)));
03340
03341
03342
03343 static const char *referstatus2str(enum referstatus rstatus)
03344 {
03345 return map_x_s(referstatusstrings, rstatus, "");
03346 }
03347
03348 static inline void pvt_set_needdestroy(struct sip_pvt *pvt, const char *reason)
03349 {
03350 if (pvt->final_destruction_scheduled) {
03351 return;
03352 }
03353 append_history(pvt, "NeedDestroy", "Setting needdestroy because %s", reason);
03354 pvt->needdestroy = 1;
03355 }
03356
03357
03358
03359
03360 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
03361 {
03362 if (p->initreq.headers) {
03363 ast_debug(1, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
03364 } else {
03365 ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
03366 }
03367
03368 copy_request(&p->initreq, req);
03369 parse_request(&p->initreq);
03370 if (req->debug) {
03371 ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
03372 }
03373 }
03374
03375
03376 static void sip_alreadygone(struct sip_pvt *dialog)
03377 {
03378 ast_debug(3, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
03379 dialog->alreadygone = 1;
03380 }
03381
03382
03383 static int proxy_update(struct sip_proxy *proxy)
03384 {
03385
03386
03387 if (!ast_sockaddr_parse(&proxy->ip, proxy->name, 0)) {
03388
03389
03390 proxy->ip.ss.ss_family = get_address_family_filter(SIP_TRANSPORT_UDP);
03391 if (ast_get_ip_or_srv(&proxy->ip, proxy->name, sip_cfg.srvlookup ? "_sip._udp" : NULL) < 0) {
03392 ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
03393 return FALSE;
03394 }
03395
03396 }
03397
03398 ast_sockaddr_set_port(&proxy->ip, proxy->port);
03399
03400 proxy->last_dnsupdate = time(NULL);
03401 return TRUE;
03402 }
03403
03404
03405
03406
03407 static struct sip_proxy *proxy_from_config(const char *proxy, int sipconf_lineno, struct sip_proxy *dest)
03408 {
03409 char *mutable_proxy, *sep, *name;
03410 int allocated = 0;
03411
03412 if (!dest) {
03413 dest = ao2_alloc(sizeof(struct sip_proxy), NULL);
03414 if (!dest) {
03415 ast_log(LOG_WARNING, "Unable to allocate config storage for proxy\n");
03416 return NULL;
03417 }
03418 allocated = 1;
03419 }
03420
03421
03422 mutable_proxy = ast_skip_blanks(ast_strdupa(proxy));
03423 sep = strchr(mutable_proxy, ',');
03424 if (sep) {
03425 *sep++ = '\0';
03426 dest->force = !strncasecmp(ast_skip_blanks(sep), "force", 5);
03427 } else {
03428 dest->force = FALSE;
03429 }
03430
03431 sip_parse_host(mutable_proxy, sipconf_lineno, &name, &dest->port, &dest->transport);
03432
03433
03434 if (ast_strlen_zero(name)) {
03435 if (allocated) {
03436 ao2_ref(dest, -1);
03437 } else {
03438 dest->name[0] = '\0';
03439 }
03440 return NULL;
03441 }
03442 ast_copy_string(dest->name, name, sizeof(dest->name));
03443
03444
03445 proxy_update(dest);
03446
03447 return dest;
03448 }
03449
03450
03451
03452
03453
03454 unsigned int port_str2int(const char *pt, unsigned int standard)
03455 {
03456 int port = standard;
03457 if (ast_strlen_zero(pt) || (sscanf(pt, "%30d", &port) != 1) || (port < 1) || (port > 65535)) {
03458 port = standard;
03459 }
03460
03461 return port;
03462 }
03463
03464
03465 static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
03466 {
03467 if (dialog && dialog->options && dialog->options->outboundproxy) {
03468 if (sipdebug) {
03469 ast_debug(1, "OBPROXY: Applying dialplan set OBproxy to this call\n");
03470 }
03471 append_history(dialog, "OBproxy", "Using dialplan obproxy %s", dialog->options->outboundproxy->name);
03472 return dialog->options->outboundproxy;
03473 }
03474 if (peer && peer->outboundproxy) {
03475 if (sipdebug) {
03476 ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
03477 }
03478 append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
03479 return peer->outboundproxy;
03480 }
03481 if (sip_cfg.outboundproxy.name[0]) {
03482 if (sipdebug) {
03483 ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
03484 }
03485 append_history(dialog, "OBproxy", "Using global obproxy %s", sip_cfg.outboundproxy.name);
03486 return &sip_cfg.outboundproxy;
03487 }
03488 if (sipdebug) {
03489 ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
03490 }
03491 return NULL;
03492 }
03493
03494
03495
03496
03497
03498
03499
03500 static int method_match(enum sipmethod id, const char *name)
03501 {
03502 int len = strlen(sip_methods[id].text);
03503 int l_name = name ? strlen(name) : 0;
03504
03505 return (l_name >= len && name && name[len] < 33 &&
03506 !strncasecmp(sip_methods[id].text, name, len));
03507 }
03508
03509
03510 static int find_sip_method(const char *msg)
03511 {
03512 int i, res = 0;
03513
03514 if (ast_strlen_zero(msg)) {
03515 return 0;
03516 }
03517 for (i = 1; i < ARRAY_LEN(sip_methods) && !res; i++) {
03518 if (method_match(i, msg)) {
03519 res = sip_methods[i].id;
03520 }
03521 }
03522 return res;
03523 }
03524
03525
03526 static inline int sip_debug_test_addr(const struct ast_sockaddr *addr)
03527 {
03528
03529 if (!sipdebug) {
03530 return 0;
03531 }
03532
03533
03534 if (ast_sockaddr_isnull(&debugaddr)) {
03535 return 1;
03536 }
03537
03538
03539
03540
03541 if (ast_sockaddr_port(&debugaddr)) {
03542 return !ast_sockaddr_cmp(&debugaddr, addr);
03543 } else {
03544 return !ast_sockaddr_cmp_addr(&debugaddr, addr);
03545 }
03546 }
03547
03548
03549 static const struct ast_sockaddr *sip_real_dst(const struct sip_pvt *p)
03550 {
03551 if (p->outboundproxy) {
03552 return &p->outboundproxy->ip;
03553 }
03554
03555 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;
03556 }
03557
03558
03559 static const char *sip_nat_mode(const struct sip_pvt *p)
03560 {
03561 return ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) ? "NAT" : "no NAT";
03562 }
03563
03564
03565 static inline int sip_debug_test_pvt(struct sip_pvt *p)
03566 {
03567 if (!sipdebug) {
03568 return 0;
03569 }
03570 return sip_debug_test_addr(sip_real_dst(p));
03571 }
03572
03573
03574 static int get_transport_str2enum(const char *transport)
03575 {
03576 int res = 0;
03577
03578 if (ast_strlen_zero(transport)) {
03579 return res;
03580 }
03581
03582 if (!strcasecmp(transport, "udp")) {
03583 res |= SIP_TRANSPORT_UDP;
03584 }
03585 if (!strcasecmp(transport, "tcp")) {
03586 res |= SIP_TRANSPORT_TCP;
03587 }
03588 if (!strcasecmp(transport, "tls")) {
03589 res |= SIP_TRANSPORT_TLS;
03590 }
03591
03592 return res;
03593 }
03594
03595
03596 static inline const char *get_transport_list(unsigned int transports) {
03597 switch (transports) {
03598 case SIP_TRANSPORT_UDP:
03599 return "UDP";
03600 case SIP_TRANSPORT_TCP:
03601 return "TCP";
03602 case SIP_TRANSPORT_TLS:
03603 return "TLS";
03604 case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TCP:
03605 return "TCP,UDP";
03606 case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TLS:
03607 return "TLS,UDP";
03608 case SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS:
03609 return "TLS,TCP";
03610 default:
03611 return transports ?
03612 "TLS,TCP,UDP" : "UNKNOWN";
03613 }
03614 }
03615
03616
03617 static inline const char *get_transport(enum sip_transport t)
03618 {
03619 switch (t) {
03620 case SIP_TRANSPORT_UDP:
03621 return "UDP";
03622 case SIP_TRANSPORT_TCP:
03623 return "TCP";
03624 case SIP_TRANSPORT_TLS:
03625 return "TLS";
03626 }
03627
03628 return "UNKNOWN";
03629 }
03630
03631
03632 static inline const char *get_srv_protocol(enum sip_transport t)
03633 {
03634 switch (t) {
03635 case SIP_TRANSPORT_UDP:
03636 return "udp";
03637 case SIP_TRANSPORT_TLS:
03638 case SIP_TRANSPORT_TCP:
03639 return "tcp";
03640 }
03641
03642 return "udp";
03643 }
03644
03645
03646 static inline const char *get_srv_service(enum sip_transport t)
03647 {
03648 switch (t) {
03649 case SIP_TRANSPORT_TCP:
03650 case SIP_TRANSPORT_UDP:
03651 return "sip";
03652 case SIP_TRANSPORT_TLS:
03653 return "sips";
03654 }
03655 return "sip";
03656 }
03657
03658
03659
03660
03661
03662
03663
03664 static inline const char *get_transport_pvt(struct sip_pvt *p)
03665 {
03666 if (p->outboundproxy && p->outboundproxy->transport) {
03667 set_socket_transport(&p->socket, p->outboundproxy->transport);
03668 }
03669
03670 return get_transport(p->socket.type);
03671 }
03672
03673
03674
03675
03676
03677
03678
03679
03680
03681
03682
03683
03684 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data)
03685 {
03686 int res = 0;
03687 const struct ast_sockaddr *dst = sip_real_dst(p);
03688
03689 ast_debug(2, "Trying to put '%.11s' onto %s socket destined for %s\n", ast_str_buffer(data), get_transport_pvt(p), ast_sockaddr_stringify(dst));
03690
03691 if (sip_prepare_socket(p) < 0) {
03692 return XMIT_ERROR;
03693 }
03694
03695 if (p->socket.type == SIP_TRANSPORT_UDP) {
03696 res = ast_sendto(p->socket.fd, ast_str_buffer(data), ast_str_strlen(data), 0, dst);
03697 } else if (p->socket.tcptls_session) {
03698 res = sip_tcptls_write(p->socket.tcptls_session, ast_str_buffer(data), ast_str_strlen(data));
03699 } else {
03700 ast_debug(2, "Socket type is TCP but no tcptls_session is present to write to\n");
03701 return XMIT_ERROR;
03702 }
03703
03704 if (res == -1) {
03705 switch (errno) {
03706 case EBADF:
03707 case EHOSTUNREACH:
03708 case ENETDOWN:
03709 case ENETUNREACH:
03710 case ECONNREFUSED:
03711 res = XMIT_ERROR;
03712 }
03713 }
03714 if (res != ast_str_strlen(data)) {
03715 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));
03716 }
03717
03718 return res;
03719 }
03720
03721
03722 static void build_via(struct sip_pvt *p)
03723 {
03724
03725 const char *rport = (ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) || ast_test_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT)) ? ";rport" : "";
03726
03727
03728 snprintf(p->via, sizeof(p->via), "SIP/2.0/%s %s;branch=z9hG4bK%08x%s",
03729 get_transport_pvt(p),
03730 ast_sockaddr_stringify_remote(&p->ourip),
03731 (int) p->branch, rport);
03732 }
03733
03734
03735
03736
03737
03738
03739
03740
03741 static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p)
03742 {
03743 struct ast_sockaddr theirs;
03744
03745
03746
03747
03748
03749
03750
03751
03752
03753
03754
03755
03756
03757 int want_remap = 0;
03758
03759 ast_sockaddr_copy(us, &internip);
03760
03761 ast_ouraddrfor(them, us);
03762 ast_sockaddr_copy(&theirs, them);
03763
03764 if (ast_sockaddr_is_ipv6(&theirs)) {
03765 if (localaddr && !ast_sockaddr_isnull(&externaddr) && !ast_sockaddr_is_any(&bindaddr)) {
03766 ast_log(LOG_WARNING, "Address remapping activated in sip.conf "
03767 "but we're using IPv6, which doesn't need it. Please "
03768 "remove \"localnet\" and/or \"externaddr\" settings.\n");
03769 }
03770 } else {
03771 want_remap = localaddr &&
03772 !ast_sockaddr_isnull(&externaddr) &&
03773 ast_apply_ha(localaddr, &theirs) == AST_SENSE_ALLOW ;
03774 }
03775
03776 if (want_remap &&
03777 (!sip_cfg.matchexternaddrlocally || !ast_apply_ha(localaddr, us)) ) {
03778
03779 if (externexpire && time(NULL) >= externexpire) {
03780 if (ast_sockaddr_resolve_first(&externaddr, externhost, 0)) {
03781 ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
03782 }
03783 externexpire = time(NULL) + externrefresh;
03784 }
03785 if (!ast_sockaddr_isnull(&externaddr)) {
03786 ast_sockaddr_copy(us, &externaddr);
03787 switch (p->socket.type) {
03788 case SIP_TRANSPORT_TCP:
03789 if (!externtcpport && ast_sockaddr_port(&externaddr)) {
03790
03791 externtcpport = ast_sockaddr_port(&externaddr);
03792 }
03793 ast_sockaddr_set_port(us, externtcpport);
03794 break;
03795 case SIP_TRANSPORT_TLS:
03796 ast_sockaddr_set_port(us, externtlsport);
03797 break;
03798 case SIP_TRANSPORT_UDP:
03799 if (!ast_sockaddr_port(&externaddr)) {
03800 ast_sockaddr_set_port(us, ast_sockaddr_port(&bindaddr));
03801 }
03802 break;
03803 default:
03804 break;
03805 }
03806 }
03807 ast_debug(1, "Target address %s is not local, substituting externaddr\n",
03808 ast_sockaddr_stringify(them));
03809 } else {
03810
03811 switch (p->socket.type) {
03812 case SIP_TRANSPORT_TCP:
03813 if (!ast_sockaddr_is_any(&sip_tcp_desc.local_address)) {
03814 ast_sockaddr_copy(us,
03815 &sip_tcp_desc.local_address);
03816 } else {
03817 ast_sockaddr_set_port(us,
03818 ast_sockaddr_port(&sip_tcp_desc.local_address));
03819 }
03820 break;
03821 case SIP_TRANSPORT_TLS:
03822 if (!ast_sockaddr_is_any(&sip_tls_desc.local_address)) {
03823 ast_sockaddr_copy(us,
03824 &sip_tls_desc.local_address);
03825 } else {
03826 ast_sockaddr_set_port(us,
03827 ast_sockaddr_port(&sip_tls_desc.local_address));
03828 }
03829 break;
03830 case SIP_TRANSPORT_UDP:
03831
03832 default:
03833 if (!ast_sockaddr_is_any(&bindaddr)) {
03834 ast_sockaddr_copy(us, &bindaddr);
03835 }
03836 if (!ast_sockaddr_port(us)) {
03837 ast_sockaddr_set_port(us, ast_sockaddr_port(&bindaddr));
03838 }
03839 }
03840 }
03841 ast_debug(3, "Setting SIP_TRANSPORT_%s with address %s\n", get_transport(p->socket.type), ast_sockaddr_stringify(us));
03842 }
03843
03844
03845 static __attribute__((format(printf, 2, 0))) void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
03846 {
03847 char buf[80], *c = buf;
03848 struct sip_history *hist;
03849 int l;
03850
03851 vsnprintf(buf, sizeof(buf), fmt, ap);
03852 strsep(&c, "\r\n");
03853 l = strlen(buf) + 1;
03854 if (!(hist = ast_calloc(1, sizeof(*hist) + l))) {
03855 return;
03856 }
03857 if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
03858 ast_free(hist);
03859 return;
03860 }
03861 memcpy(hist->event, buf, l);
03862 if (p->history_entries == MAX_HISTORY_ENTRIES) {
03863 struct sip_history *oldest;
03864 oldest = AST_LIST_REMOVE_HEAD(p->history, list);
03865 p->history_entries--;
03866 ast_free(oldest);
03867 }
03868 AST_LIST_INSERT_TAIL(p->history, hist, list);
03869 p->history_entries++;
03870 }
03871
03872
03873 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
03874 {
03875 va_list ap;
03876
03877 if (!p) {
03878 return;
03879 }
03880
03881 if (!p->do_history && !recordhistory && !dumphistory) {
03882 return;
03883 }
03884
03885 va_start(ap, fmt);
03886 append_history_va(p, fmt, ap);
03887 va_end(ap);
03888
03889 return;
03890 }
03891
03892
03893 static int retrans_pkt(const void *data)
03894 {
03895 struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
03896 int reschedule = DEFAULT_RETRANS;
03897 int xmitres = 0;
03898
03899 int64_t diff = pkt->retrans_stop_time - ast_tvdiff_ms(ast_tvnow(), pkt->time_sent);
03900
03901
03902
03903
03904 if ((diff <= 0) || (diff > pkt->retrans_stop_time)) {
03905 pkt->retrans_stop = 1;
03906 }
03907
03908
03909 sip_pvt_lock(pkt->owner);
03910
03911 if (!pkt->retrans_stop) {
03912 pkt->retrans++;
03913 if (!pkt->timer_t1) {
03914 if (sipdebug) {
03915 ast_debug(4, "SIP TIMER: Not rescheduling id #%d:%s (Method %d) (No timer T1)\n",
03916 pkt->retransid,
03917 sip_methods[pkt->method].text,
03918 pkt->method);
03919 }
03920 } else {
03921 int siptimer_a;
03922
03923 if (sipdebug) {
03924 ast_debug(4, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n",
03925 pkt->retransid,
03926 pkt->retrans,
03927 sip_methods[pkt->method].text,
03928 pkt->method);
03929 }
03930 if (!pkt->timer_a) {
03931 pkt->timer_a = 2 ;
03932 } else {
03933 pkt->timer_a = 2 * pkt->timer_a;
03934 }
03935
03936
03937 siptimer_a = pkt->timer_t1 * pkt->timer_a;
03938 if (pkt->method != SIP_INVITE && siptimer_a > 4000) {
03939 siptimer_a = 4000;
03940 }
03941
03942
03943 reschedule = siptimer_a;
03944 ast_debug(4, "** SIP timers: Rescheduling retransmission %d to %d ms (t1 %d ms (Retrans id #%d)) \n",
03945 pkt->retrans + 1,
03946 siptimer_a,
03947 pkt->timer_t1,
03948 pkt->retransid);
03949 }
03950
03951 if (sip_debug_test_pvt(pkt->owner)) {
03952 const struct ast_sockaddr *dst = sip_real_dst(pkt->owner);
03953 ast_verbose("Retransmitting #%d (%s) to %s:\n%s\n---\n",
03954 pkt->retrans, sip_nat_mode(pkt->owner),
03955 ast_sockaddr_stringify(dst),
03956 ast_str_buffer(pkt->data));
03957 }
03958
03959 append_history(pkt->owner, "ReTx", "%d %s", reschedule, ast_str_buffer(pkt->data));
03960 xmitres = __sip_xmit(pkt->owner, pkt->data);
03961
03962
03963
03964
03965
03966
03967 if (xmitres != XMIT_ERROR) {
03968 if (reschedule >= diff) {
03969 pkt->retrans_stop = 1;
03970 reschedule = diff;
03971 }
03972 sip_pvt_unlock(pkt->owner);
03973 return reschedule;
03974 }
03975 }
03976
03977
03978
03979
03980 pkt->retransid = -1;
03981
03982 if (pkt->method != SIP_OPTIONS && xmitres == 0) {
03983 if (pkt->is_fatal || sipdebug) {
03984 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"
03985 "Packet timed out after %dms with no response\n",
03986 pkt->owner->callid,
03987 pkt->seqno,
03988 pkt->is_fatal ? "Critical" : "Non-critical",
03989 pkt->is_resp ? "Response" : "Request",
03990 (int) ast_tvdiff_ms(ast_tvnow(), pkt->time_sent));
03991 }
03992 } else if (pkt->method == SIP_OPTIONS && sipdebug) {
03993 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);
03994 }
03995
03996 if (xmitres == XMIT_ERROR) {
03997 ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission on Call ID %s\n", pkt->owner->callid);
03998 append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03999 } else {
04000 append_history(pkt->owner, "MaxRetries", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
04001 }
04002
04003 if (pkt->is_fatal) {
04004 while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
04005 sip_pvt_unlock(pkt->owner);
04006 usleep(1);
04007 sip_pvt_lock(pkt->owner);
04008 }
04009 if (pkt->owner->owner && !pkt->owner->owner->hangupcause) {
04010 pkt->owner->owner->hangupcause = AST_CAUSE_NO_USER_RESPONSE;
04011 }
04012 if (pkt->owner->owner) {
04013 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);
04014
04015 if (pkt->is_resp &&
04016 (pkt->response_code >= 200) &&
04017 (pkt->response_code < 300) &&
04018 pkt->owner->pendinginvite &&
04019 ast_test_flag(&pkt->owner->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
04020
04021
04022
04023
04024
04025
04026
04027 pkt->owner->invitestate = INV_TERMINATED;
04028 pkt->owner->pendinginvite = 0;
04029 } else {
04030
04031 sip_alreadygone(pkt->owner);
04032 }
04033 ast_queue_hangup_with_cause(pkt->owner->owner, AST_CAUSE_NO_USER_RESPONSE);
04034 ast_channel_unlock(pkt->owner->owner);
04035 } else {
04036
04037
04038
04039 if (pkt->method != SIP_OPTIONS && pkt->method != SIP_REGISTER) {
04040 pvt_set_needdestroy(pkt->owner, "no response to critical packet");
04041 sip_alreadygone(pkt->owner);
04042 append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
04043 }
04044 }
04045 }
04046
04047 if (pkt->method == SIP_BYE) {
04048
04049 sip_alreadygone(pkt->owner);
04050 if (pkt->owner->owner) {
04051 ast_channel_unlock(pkt->owner->owner);
04052 }
04053 append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
04054 pvt_set_needdestroy(pkt->owner, "no response to BYE");
04055 }
04056
04057
04058 for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
04059 if (cur == pkt) {
04060 UNLINK(cur, pkt->owner->packets, prev);
04061 sip_pvt_unlock(pkt->owner);
04062 if (pkt->owner) {
04063 pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
04064 }
04065 if (pkt->data) {
04066 ast_free(pkt->data);
04067 }
04068 pkt->data = NULL;
04069 ast_free(pkt);
04070 return 0;
04071 }
04072 }
04073
04074 ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
04075 sip_pvt_unlock(pkt->owner);
04076 return 0;
04077 }
04078
04079
04080
04081
04082
04083
04084 static enum sip_result __sip_reliable_xmit(struct sip_pvt *p, uint32_t seqno, int resp, struct ast_str *data, int fatal, int sipmethod)
04085 {
04086 struct sip_pkt *pkt = NULL;
04087 int siptimer_a = DEFAULT_RETRANS;
04088 int xmitres = 0;
04089 int respid;
04090
04091 if (sipmethod == SIP_INVITE) {
04092
04093 p->pendinginvite = seqno;
04094 }
04095
04096
04097
04098
04099 if (!(p->socket.type & SIP_TRANSPORT_UDP)) {
04100 xmitres = __sip_xmit(p, data);
04101 if (xmitres == XMIT_ERROR) {
04102 append_history(p, "XmitErr", "%s", fatal ? "(Critical)" : "(Non-critical)");
04103 return AST_FAILURE;
04104 } else {
04105 return AST_SUCCESS;
04106 }
04107 }
04108
04109 if (!(pkt = ast_calloc(1, sizeof(*pkt)))) {
04110 return AST_FAILURE;
04111 }
04112
04113 if (!(pkt->data = ast_str_create(ast_str_strlen(data)))) {
04114 ast_free(pkt);
04115 return AST_FAILURE;
04116 }
04117 ast_str_set(&pkt->data, 0, "%s%s", ast_str_buffer(data), "\0");
04118
04119 pkt->method = sipmethod;
04120 pkt->seqno = seqno;
04121 pkt->is_resp = resp;
04122 pkt->is_fatal = fatal;
04123 pkt->owner = dialog_ref(p, "__sip_reliable_xmit: setting pkt->owner");
04124 pkt->next = p->packets;
04125 p->packets = pkt;
04126 if (resp) {
04127
04128 if (sscanf(ast_str_buffer(pkt->data), "SIP/2.0 %30u", &respid) == 1) {
04129 pkt->response_code = respid;
04130 }
04131 }
04132 pkt->timer_t1 = p->timer_t1;
04133 pkt->retransid = -1;
04134 if (pkt->timer_t1) {
04135 siptimer_a = pkt->timer_t1;
04136 }
04137
04138 pkt->time_sent = ast_tvnow();
04139 pkt->retrans_stop_time = 64 * (pkt->timer_t1 ? pkt->timer_t1 : DEFAULT_TIMER_T1);
04140
04141
04142 AST_SCHED_REPLACE_VARIABLE(pkt->retransid, sched, siptimer_a, retrans_pkt, pkt, 1);
04143 if (sipdebug) {
04144 ast_debug(4, "*** SIP TIMER: Initializing retransmit timer on packet: Id #%d\n", pkt->retransid);
04145 }
04146
04147 xmitres = __sip_xmit(pkt->owner, pkt->data);
04148
04149 if (xmitres == XMIT_ERROR) {
04150 append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
04151 ast_log(LOG_ERROR, "Serious Network Trouble; __sip_xmit returns error for pkt data\n");
04152 AST_SCHED_DEL(sched, pkt->retransid);
04153 p->packets = pkt->next;
04154 pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
04155 ast_free(pkt->data);
04156 ast_free(pkt);
04157 return AST_FAILURE;
04158 } else {
04159
04160
04161
04162
04163 if (monitor_thread != AST_PTHREADT_NULL) {
04164 pthread_kill(monitor_thread, SIGURG);
04165 }
04166 return AST_SUCCESS;
04167 }
04168 }
04169
04170
04171
04172
04173
04174
04175 static int __sip_autodestruct(const void *data)
04176 {
04177 struct sip_pvt *p = (struct sip_pvt *)data;
04178 struct ast_channel *owner;
04179
04180
04181 if (p->subscribed && p->subscribed != MWI_NOTIFICATION && p->subscribed != CALL_COMPLETION) {
04182 transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE);
04183 p->subscribed = NONE;
04184 append_history(p, "Subscribestatus", "timeout");
04185 ast_debug(3, "Re-scheduled destruction of SIP subscription %s\n", p->callid ? p->callid : "<unknown>");
04186 return 10000;
04187 }
04188
04189
04190 if (p->packets) {
04191 if (!p->needdestroy) {
04192 char method_str[31];
04193 ast_debug(3, "Re-scheduled destruction of SIP call %s\n", p->callid ? p->callid : "<unknown>");
04194 append_history(p, "ReliableXmit", "timeout");
04195 if (sscanf(p->lastmsg, "Tx: %30s", method_str) == 1 || sscanf(p->lastmsg, "Rx: %30s", method_str) == 1) {
04196 if (p->ongoing_reinvite || method_match(SIP_CANCEL, method_str) || method_match(SIP_BYE, method_str)) {
04197 pvt_set_needdestroy(p, "autodestruct");
04198 }
04199 }
04200 return 10000;
04201 } else {
04202
04203 __sip_pretend_ack(p);
04204 }
04205 }
04206
04207
04208 p->autokillid = -1;
04209
04210
04211
04212
04213 owner = sip_pvt_lock_full(p);
04214 if (owner) {
04215 ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner %s in place (Method: %s). Rescheduling destruction for 10000 ms\n", p->callid, owner->name, sip_methods[p->method].text);
04216 ast_queue_hangup_with_cause(owner, AST_CAUSE_PROTOCOL_ERROR);
04217 ast_channel_unlock(owner);
04218 ast_channel_unref(owner);
04219 sip_pvt_unlock(p);
04220 return 10000;
04221 } else if (p->refer && !p->alreadygone) {
04222 ast_debug(3, "Finally hanging up channel after transfer: %s\n", p->callid);
04223 stop_media_flows(p);
04224 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
04225 append_history(p, "ReferBYE", "Sending BYE on transferer call leg %s", p->callid);
04226 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
04227 } else {
04228 append_history(p, "AutoDestroy", "%s", p->callid);
04229 ast_debug(3, "Auto destroying SIP dialog '%s'\n", p->callid);
04230 sip_pvt_unlock(p);
04231 dialog_unlink_all(p);
04232 sip_pvt_lock(p);
04233
04234
04235
04236 }
04237
04238 sip_pvt_unlock(p);
04239
04240 dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
04241
04242 return 0;
04243 }
04244
04245
04246
04247
04248 void sip_scheddestroy_final(struct sip_pvt *p, int ms)
04249 {
04250 if (p->final_destruction_scheduled) {
04251 return;
04252 }
04253
04254 sip_scheddestroy(p, ms);
04255 if (p->autokillid != -1) {
04256 p->final_destruction_scheduled = 1;
04257 }
04258 }
04259
04260
04261 void sip_scheddestroy(struct sip_pvt *p, int ms)
04262 {
04263 if (p->final_destruction_scheduled) {
04264 return;
04265 }
04266
04267 if (ms < 0) {
04268 if (p->timer_t1 == 0) {
04269 p->timer_t1 = global_t1;
04270 }
04271 if (p->timer_b == 0) {
04272 p->timer_b = global_timer_b;
04273 }
04274 ms = p->timer_t1 * 64;
04275 }
04276 if (sip_debug_test_pvt(p)) {
04277 ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
04278 }
04279 if (sip_cancel_destroy(p)) {
04280 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
04281 }
04282
04283 if (p->do_history) {
04284 append_history(p, "SchedDestroy", "%d ms", ms);
04285 }
04286 p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, dialog_ref(p, "setting ref as passing into ast_sched_add for __sip_autodestruct"));
04287
04288 if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_schedid > 0) {
04289 stop_session_timer(p);
04290 }
04291 }
04292
04293
04294
04295
04296
04297 int sip_cancel_destroy(struct sip_pvt *p)
04298 {
04299 if (p->final_destruction_scheduled) {
04300 return 0;
04301 }
04302
04303 if (p->autokillid > -1) {
04304 append_history(p, "CancelDestroy", "");
04305 AST_SCHED_DEL_UNREF(sched, p->autokillid, dialog_unref(p, "remove ref for autokillid"));
04306 }
04307 return 0;
04308 }
04309
04310
04311
04312 int __sip_ack(struct sip_pvt *p, uint32_t seqno, int resp, int sipmethod)
04313 {
04314 struct sip_pkt *cur, *prev = NULL;
04315 const char *msg = "Not Found";
04316 int res = FALSE;
04317
04318
04319
04320
04321
04322
04323 if (p->outboundproxy && !p->outboundproxy->force){
04324 ref_proxy(p, NULL);
04325 }
04326
04327 for (cur = p->packets; cur; prev = cur, cur = cur->next) {
04328 if (cur->seqno != seqno || cur->is_resp != resp) {
04329 continue;
04330 }
04331 if (cur->is_resp || cur->method == sipmethod) {
04332 res = TRUE;
04333 msg = "Found";
04334 if (!resp && (seqno == p->pendinginvite)) {
04335 ast_debug(1, "Acked pending invite %u\n", p->pendinginvite);
04336 p->pendinginvite = 0;
04337 }
04338 if (cur->retransid > -1) {
04339 if (sipdebug)
04340 ast_debug(4, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
04341 }
04342
04343
04344
04345
04346
04347
04348
04349
04350
04351
04352
04353
04354
04355
04356
04357
04358 while (cur->retransid > -1 && ast_sched_del(sched, cur->retransid)) {
04359 sip_pvt_unlock(p);
04360 usleep(1);
04361 sip_pvt_lock(p);
04362 }
04363 UNLINK(cur, p->packets, prev);
04364 dialog_unref(cur->owner, "unref pkt cur->owner dialog from sip ack before freeing pkt");
04365 if (cur->data) {
04366 ast_free(cur->data);
04367 }
04368 ast_free(cur);
04369 break;
04370 }
04371 }
04372 ast_debug(1, "Stopping retransmission on '%s' of %s %u: Match %s\n",
04373 p->callid, resp ? "Response" : "Request", seqno, msg);
04374 return res;
04375 }
04376
04377
04378
04379 void __sip_pretend_ack(struct sip_pvt *p)
04380 {
04381 struct sip_pkt *cur = NULL;
04382
04383 while (p->packets) {
04384 int method;
04385 if (cur == p->packets) {
04386 ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
04387 return;
04388 }
04389 cur = p->packets;
04390 method = (cur->method) ? cur->method : find_sip_method(ast_str_buffer(cur->data));
04391 __sip_ack(p, cur->seqno, cur->is_resp, method);
04392 }
04393 }
04394
04395
04396 int __sip_semi_ack(struct sip_pvt *p, uint32_t seqno, int resp, int sipmethod)
04397 {
04398 struct sip_pkt *cur;
04399 int res = FALSE;
04400
04401 for (cur = p->packets; cur; cur = cur->next) {
04402 if (cur->seqno == seqno && cur->is_resp == resp &&
04403 (cur->is_resp || method_match(sipmethod, ast_str_buffer(cur->data)))) {
04404
04405 if (cur->retransid > -1) {
04406 if (sipdebug)
04407 ast_debug(4, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
04408 }
04409 AST_SCHED_DEL(sched, cur->retransid);
04410 res = TRUE;
04411 break;
04412 }
04413 }
04414 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");
04415 return res;
04416 }
04417
04418
04419
04420 static void parse_copy(struct sip_request *dst, const struct sip_request *src)
04421 {
04422 copy_request(dst, src);
04423 parse_request(dst);
04424 }
04425
04426
04427 static void add_blank(struct sip_request *req)
04428 {
04429 if (!req->lines) {
04430
04431 ast_str_append(&req->data, 0, "\r\n");
04432 }
04433 }
04434
04435 static int send_provisional_keepalive_full(struct sip_pvt *pvt, int with_sdp)
04436 {
04437 const char *msg = NULL;
04438 struct ast_channel *chan;
04439 int res = 0;
04440 int old_sched_id = pvt->provisional_keepalive_sched_id;
04441
04442 chan = sip_pvt_lock_full(pvt);
04443
04444 if (old_sched_id != pvt->provisional_keepalive_sched_id) {
04445
04446 if (chan) {
04447 ast_channel_unlock(chan);
04448 chan = ast_channel_unref(chan);
04449 }
04450 sip_pvt_unlock(pvt);
04451 dialog_unref(pvt, "dialog ref for provisional keepalive");
04452 return 0;
04453 }
04454
04455 if (!pvt->last_provisional || !strncasecmp(pvt->last_provisional, "100", 3)) {
04456 msg = "183 Session Progress";
04457 }
04458
04459 if (pvt->invitestate < INV_COMPLETED) {
04460 if (with_sdp) {
04461 transmit_response_with_sdp(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq, XMIT_UNRELIABLE, FALSE, FALSE);
04462 } else {
04463 transmit_response(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq);
04464 }
04465 res = PROVIS_KEEPALIVE_TIMEOUT;
04466 }
04467
04468 if (chan) {
04469 ast_channel_unlock(chan);
04470 chan = ast_channel_unref(chan);
04471 }
04472
04473 if (!res) {
04474 pvt->provisional_keepalive_sched_id = -1;
04475 }
04476
04477 sip_pvt_unlock(pvt);
04478
04479 if (!res) {
04480 dialog_unref(pvt, "dialog ref for provisional keepalive");
04481 }
04482 return res;
04483 }
04484
04485 static int send_provisional_keepalive(const void *data) {
04486 struct sip_pvt *pvt = (struct sip_pvt *) data;
04487
04488 return send_provisional_keepalive_full(pvt, 0);
04489 }
04490
04491 static int send_provisional_keepalive_with_sdp(const void *data) {
04492 struct sip_pvt *pvt = (void *)data;
04493
04494 return send_provisional_keepalive_full(pvt, 1);
04495 }
04496
04497 static void update_provisional_keepalive(struct sip_pvt *pvt, int with_sdp)
04498 {
04499 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"));
04500
04501 pvt->provisional_keepalive_sched_id = ast_sched_add(sched, PROVIS_KEEPALIVE_TIMEOUT,
04502 with_sdp ? send_provisional_keepalive_with_sdp : send_provisional_keepalive, dialog_ref(pvt, "Increment refcount to pass dialog pointer to sched callback"));
04503 }
04504
04505 static void add_required_respheader(struct sip_request *req)
04506 {
04507 struct ast_str *str;
04508 int i;
04509
04510 if (!req->reqsipoptions) {
04511 return;
04512 }
04513
04514 str = ast_str_create(32);
04515
04516 for (i = 0; i < ARRAY_LEN(sip_options); ++i) {
04517 if (!(req->reqsipoptions & sip_options[i].id)) {
04518 continue;
04519 }
04520 if (ast_str_strlen(str) > 0) {
04521 ast_str_append(&str, 0, ", ");
04522 }
04523 ast_str_append(&str, 0, "%s", sip_options[i].text);
04524 }
04525
04526 if (ast_str_strlen(str) > 0) {
04527 add_header(req, "Require", ast_str_buffer(str));
04528 }
04529
04530 ast_free(str);
04531 }
04532
04533
04534 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno)
04535 {
04536 int res;
04537
04538 finalize_content(req);
04539 add_blank(req);
04540 if (sip_debug_test_pvt(p)) {
04541 const struct ast_sockaddr *dst = sip_real_dst(p);
04542
04543 ast_verbose("\n<--- %sTransmitting (%s) to %s --->\n%s\n<------------>\n",
04544 reliable ? "Reliably " : "", sip_nat_mode(p),
04545 ast_sockaddr_stringify(dst),
04546 ast_str_buffer(req->data));
04547 }
04548 if (p->do_history) {
04549 struct sip_request tmp = { .rlPart1 = 0, };
04550 parse_copy(&tmp, req);
04551 append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", ast_str_buffer(tmp.data), get_header(&tmp, "CSeq"),
04552 (tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? REQ_OFFSET_TO_STR(&tmp, rlPart2) : sip_methods[tmp.method].text);
04553 deinit_req(&tmp);
04554 }
04555
04556
04557 if (p->initreq.method == SIP_INVITE && reliable == XMIT_CRITICAL) {
04558 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"));
04559 }
04560
04561 res = (reliable) ?
04562 __sip_reliable_xmit(p, seqno, 1, req->data, (reliable == XMIT_CRITICAL), req->method) :
04563 __sip_xmit(p, req->data);
04564 deinit_req(req);
04565 if (res > 0) {
04566 return 0;
04567 }
04568 return res;
04569 }
04570
04571
04572
04573
04574
04575
04576 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno)
04577 {
04578 int res;
04579
04580
04581
04582
04583 if (p->outboundproxy) {
04584 p->sa = p->outboundproxy->ip;
04585 }
04586
04587 finalize_content(req);
04588 add_blank(req);
04589 if (sip_debug_test_pvt(p)) {
04590 if (ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT)) {
04591 ast_verbose("%sTransmitting (NAT) to %s:\n%s\n---\n", reliable ? "Reliably " : "", ast_sockaddr_stringify(&p->recv), ast_str_buffer(req->data));
04592 } else {
04593 ast_verbose("%sTransmitting (no NAT) to %s:\n%s\n---\n", reliable ? "Reliably " : "", ast_sockaddr_stringify(&p->sa), ast_str_buffer(req->data));
04594 }
04595 }
04596 if (p->do_history) {
04597 struct sip_request tmp = { .rlPart1 = 0, };
04598 parse_copy(&tmp, req);
04599 append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", ast_str_buffer(tmp.data), get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
04600 deinit_req(&tmp);
04601 }
04602 res = (reliable) ?
04603 __sip_reliable_xmit(p, seqno, 0, req->data, (reliable == XMIT_CRITICAL), req->method) :
04604 __sip_xmit(p, req->data);
04605 deinit_req(req);
04606 return res;
04607 }
04608
04609 static void enable_dsp_detect(struct sip_pvt *p)
04610 {
04611 int features = 0;
04612
04613 if (p->dsp) {
04614 return;
04615 }
04616
04617 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
04618 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
04619 if (p->rtp) {
04620 ast_rtp_instance_dtmf_mode_set(p->rtp, AST_RTP_DTMF_MODE_INBAND);
04621 }
04622 features |= DSP_FEATURE_DIGIT_DETECT;
04623 }
04624
04625 if (ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_CNG)) {
04626 features |= DSP_FEATURE_FAX_DETECT;
04627 }
04628
04629 if (!features) {
04630 return;
04631 }
04632
04633 if (!(p->dsp = ast_dsp_new())) {
04634 return;
04635 }
04636
04637 ast_dsp_set_features(p->dsp, features);
04638 if (global_relaxdtmf) {
04639 ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
04640 }
04641 }
04642
04643 static void disable_dsp_detect(struct sip_pvt *p)
04644 {
04645 if (p->dsp) {
04646 ast_dsp_free(p->dsp);
04647 p->dsp = NULL;
04648 }
04649 }
04650
04651
04652 static int sip_setoption(struct ast_channel *chan, int option, void *data, int datalen)
04653 {
04654 int res = -1;
04655 struct sip_pvt *p = chan->tech_pvt;
04656
04657 if (!p) {
04658 ast_log(LOG_ERROR, "Attempt to Ref a null pointer. sip private structure is gone!\n");
04659 return -1;
04660 }
04661
04662 sip_pvt_lock(p);
04663
04664 switch (option) {
04665 case AST_OPTION_FORMAT_READ:
04666 if (p->rtp) {
04667 res = ast_rtp_instance_set_read_format(p->rtp, *(int *) data);
04668 }
04669 break;
04670 case AST_OPTION_FORMAT_WRITE:
04671 if (p->rtp) {
04672 res = ast_rtp_instance_set_write_format(p->rtp, *(int *) data);
04673 }
04674 break;
04675 case AST_OPTION_MAKE_COMPATIBLE:
04676 if (p->rtp) {
04677 res = ast_rtp_instance_make_compatible(chan, p->rtp, (struct ast_channel *) data);
04678 }
04679 break;
04680 case AST_OPTION_DIGIT_DETECT:
04681 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
04682 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
04683 char *cp = (char *) data;
04684
04685 ast_debug(1, "%sabling digit detection on %s\n", *cp ? "En" : "Dis", chan->name);
04686 if (*cp) {
04687 enable_dsp_detect(p);
04688 } else {
04689 disable_dsp_detect(p);
04690 }
04691 res = 0;
04692 }
04693 break;
04694 case AST_OPTION_SECURE_SIGNALING:
04695 p->req_secure_signaling = *(unsigned int *) data;
04696 res = 0;
04697 break;
04698 case AST_OPTION_SECURE_MEDIA:
04699 ast_set2_flag(&p->flags[1], *(unsigned int *) data, SIP_PAGE2_USE_SRTP);
04700 res = 0;
04701 break;
04702 default:
04703 break;
04704 }
04705
04706 sip_pvt_unlock(p);
04707
04708 return res;
04709 }
04710
04711
04712 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen)
04713 {
04714 int res = -1;
04715 enum ast_t38_state state = T38_STATE_UNAVAILABLE;
04716 struct sip_pvt *p = (struct sip_pvt *) chan->tech_pvt;
04717 char *cp;
04718
04719 sip_pvt_lock(p);
04720
04721 switch (option) {
04722 case AST_OPTION_T38_STATE:
04723
04724 if (*datalen != sizeof(enum ast_t38_state)) {
04725 ast_log(LOG_ERROR, "Invalid datalen for AST_OPTION_T38_STATE option. Expected %d, got %d\n", (int)sizeof(enum ast_t38_state), *datalen);
04726 break;
04727 }
04728
04729
04730 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
04731 switch (p->t38.state) {
04732 case T38_LOCAL_REINVITE:
04733 case T38_PEER_REINVITE:
04734 state = T38_STATE_NEGOTIATING;
04735 break;
04736 case T38_ENABLED:
04737 state = T38_STATE_NEGOTIATED;
04738 break;
04739 default:
04740 state = T38_STATE_UNKNOWN;
04741 }
04742 }
04743
04744 *((enum ast_t38_state *) data) = state;
04745 res = 0;
04746
04747 break;
04748 case AST_OPTION_DIGIT_DETECT:
04749 cp = (char *) data;
04750 *cp = p->dsp ? 1 : 0;
04751 ast_debug(1, "Reporting digit detection %sabled on %s\n", *cp ? "en" : "dis", chan->name);
04752 break;
04753 case AST_OPTION_SECURE_SIGNALING:
04754 *((unsigned int *) data) = p->req_secure_signaling;
04755 res = 0;
04756 break;
04757 case AST_OPTION_SECURE_MEDIA:
04758 *((unsigned int *) data) = ast_test_flag(&p->flags[1], SIP_PAGE2_USE_SRTP) ? 1 : 0;
04759 res = 0;
04760 break;
04761 case AST_OPTION_DEVICE_NAME:
04762 if (p && p->outgoing_call) {
04763 cp = (char *) data;
04764 ast_copy_string(cp, p->dialstring, *datalen);
04765 res = 0;
04766 }
04767
04768
04769
04770 break;
04771 default:
04772 break;
04773 }
04774
04775 sip_pvt_unlock(p);
04776
04777 return res;
04778 }
04779
04780
04781
04782
04783
04784 const char *find_closing_quote(const char *start, const char *lim)
04785 {
04786 char last_char = '\0';
04787 const char *s;
04788 for (s = start; *s && s != lim; last_char = *s++) {
04789 if (*s == '"' && last_char != '\\')
04790 break;
04791 }
04792 return s;
04793 }
04794
04795
04796 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
04797 {
04798 struct sip_pvt *p = chan->tech_pvt;
04799
04800 if (subclass != AST_HTML_URL)
04801 return -1;
04802
04803 ast_string_field_build(p, url, "<%s>;mode=active", data);
04804
04805 if (sip_debug_test_pvt(p))
04806 ast_debug(1, "Send URL %s, state = %d!\n", data, chan->_state);
04807
04808 switch (chan->_state) {
04809 case AST_STATE_RING:
04810 transmit_response(p, "100 Trying", &p->initreq);
04811 break;
04812 case AST_STATE_RINGING:
04813 transmit_response(p, "180 Ringing", &p->initreq);
04814 break;
04815 case AST_STATE_UP:
04816 if (!p->pendinginvite) {
04817 transmit_reinvite_with_sdp(p, FALSE, FALSE);
04818 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
04819 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
04820 }
04821 break;
04822 default:
04823 ast_log(LOG_WARNING, "Don't know how to send URI when state is %d!\n", chan->_state);
04824 }
04825
04826 return 0;
04827 }
04828
04829
04830 static const char *sip_get_callid(struct ast_channel *chan)
04831 {
04832 return chan->tech_pvt ? ((struct sip_pvt *) chan->tech_pvt)->callid : "";
04833 }
04834
04835
04836
04837
04838
04839
04840 static int sip_sendtext(struct ast_channel *ast, const char *text)
04841 {
04842 struct sip_pvt *dialog = ast->tech_pvt;
04843 int debug;
04844
04845 if (!dialog) {
04846 return -1;
04847 }
04848
04849
04850 if (!text) {
04851 return 0;
04852 }
04853 if(!is_method_allowed(&dialog->allowed_methods, SIP_MESSAGE)) {
04854 ast_debug(2, "Trying to send MESSAGE to device that does not support it.\n");
04855 return(0);
04856 }
04857
04858 debug = sip_debug_test_pvt(dialog);
04859 if (debug) {
04860 ast_verbose("Sending text %s on %s\n", text, ast->name);
04861 }
04862
04863 transmit_message_with_text(dialog, text);
04864 return 0;
04865 }
04866
04867
04868
04869
04870
04871
04872 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)
04873 {
04874 char port[10];
04875 char ipaddr[INET6_ADDRSTRLEN];
04876 char regseconds[20];
04877 char *tablename = NULL;
04878 char str_lastms[20];
04879
04880 const char *sysname = ast_config_AST_SYSTEM_NAME;
04881 char *syslabel = NULL;
04882
04883 time_t nowtime = time(NULL) + expirey;
04884 const char *fc = fullcontact ? "fullcontact" : NULL;
04885
04886 int realtimeregs = ast_check_realtime("sipregs");
04887
04888 tablename = realtimeregs ? "sipregs" : "sippeers";
04889
04890
04891 snprintf(str_lastms, sizeof(str_lastms), "%d", lastms);
04892 snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime);
04893 ast_copy_string(ipaddr, ast_sockaddr_isnull(addr) ? "" : ast_sockaddr_stringify_addr(addr), sizeof(ipaddr));
04894 ast_copy_string(port, ast_sockaddr_port(addr) ? ast_sockaddr_stringify_port(addr) : "", sizeof(port));
04895
04896 if (ast_strlen_zero(sysname))
04897 sysname = NULL;
04898 else if (sip_cfg.rtsave_sysname)
04899 syslabel = "regserver";
04900
04901
04902
04903
04904
04905
04906
04907 if (fc) {
04908 ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
04909 "port", port, "regseconds", regseconds,
04910 deprecated_username ? "username" : "defaultuser", defaultuser,
04911 "useragent", useragent, "lastms", str_lastms,
04912 fc, fullcontact, syslabel, sysname, SENTINEL);
04913 } else {
04914 ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
04915 "port", port, "regseconds", regseconds,
04916 "useragent", useragent, "lastms", str_lastms,
04917 deprecated_username ? "username" : "defaultuser", defaultuser,
04918 syslabel, sysname, SENTINEL);
04919 }
04920 }
04921
04922
04923 static void register_peer_exten(struct sip_peer *peer, int onoff)
04924 {
04925 char multi[256];
04926 char *stringp, *ext, *context;
04927 struct pbx_find_info q = { .stacklen = 0 };
04928
04929
04930
04931
04932
04933 if (ast_strlen_zero(sip_cfg.regcontext))
04934 return;
04935
04936 ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
04937 stringp = multi;
04938 while ((ext = strsep(&stringp, "&"))) {
04939 if ((context = strchr(ext, '@'))) {
04940 *context++ = '\0';
04941 if (!ast_context_find(context)) {
04942 ast_log(LOG_WARNING, "Context %s must exist in regcontext= in sip.conf!\n", context);
04943 continue;
04944 }
04945 } else {
04946 context = sip_cfg.regcontext;
04947 }
04948 if (onoff) {
04949 if (!ast_exists_extension(NULL, context, ext, 1, NULL)) {
04950 ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
04951 ast_strdup(peer->name), ast_free_ptr, "SIP");
04952 }
04953 } else if (pbx_find_extension(NULL, NULL, &q, context, ext, 1, NULL, "", E_MATCH)) {
04954 ast_context_remove_extension(context, ext, 1, NULL);
04955 }
04956 }
04957 }
04958
04959
04960 static void destroy_mailbox(struct sip_mailbox *mailbox)
04961 {
04962 if (mailbox->event_sub)
04963 ast_event_unsubscribe(mailbox->event_sub);
04964 ast_free(mailbox);
04965 }
04966
04967
04968 static void clear_peer_mailboxes(struct sip_peer *peer)
04969 {
04970 struct sip_mailbox *mailbox;
04971
04972 while ((mailbox = AST_LIST_REMOVE_HEAD(&peer->mailboxes, entry)))
04973 destroy_mailbox(mailbox);
04974 }
04975
04976 static void sip_destroy_peer_fn(void *peer)
04977 {
04978 sip_destroy_peer(peer);
04979 }
04980
04981
04982 static void sip_destroy_peer(struct sip_peer *peer)
04983 {
04984 ast_debug(3, "Destroying SIP peer %s\n", peer->name);
04985
04986
04987
04988
04989
04990
04991 clear_peer_mailboxes(peer);
04992
04993 if (peer->outboundproxy) {
04994 ao2_ref(peer->outboundproxy, -1);
04995 peer->outboundproxy = NULL;
04996 }
04997
04998
04999 if (peer->call) {
05000 dialog_unlink_all(peer->call);
05001 peer->call = dialog_unref(peer->call, "peer->call is being unset");
05002 }
05003
05004 if (peer->mwipvt) {
05005 dialog_unlink_all(peer->mwipvt);
05006 peer->mwipvt = dialog_unref(peer->mwipvt, "unreffing peer->mwipvt");
05007 }
05008
05009 if (peer->chanvars) {
05010 ast_variables_destroy(peer->chanvars);
05011 peer->chanvars = NULL;
05012 }
05013
05014 register_peer_exten(peer, FALSE);
05015 ast_free_ha(peer->ha);
05016 ast_free_ha(peer->directmediaha);
05017 if (peer->selfdestruct)
05018 ast_atomic_fetchadd_int(&apeerobjs, -1);
05019 else if (!ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && peer->is_realtime) {
05020 ast_atomic_fetchadd_int(&rpeerobjs, -1);
05021 ast_debug(3, "-REALTIME- peer Destroyed. Name: %s. Realtime Peer objects: %d\n", peer->name, rpeerobjs);
05022 } else
05023 ast_atomic_fetchadd_int(&speerobjs, -1);
05024 if (peer->auth) {
05025 ao2_t_ref(peer->auth, -1, "Removing peer authentication");
05026 peer->auth = NULL;
05027 }
05028
05029 if (peer->socket.tcptls_session) {
05030 ao2_ref(peer->socket.tcptls_session, -1);
05031 peer->socket.tcptls_session = NULL;
05032 }
05033
05034 ast_cc_config_params_destroy(peer->cc_params);
05035
05036 ast_string_field_free_memory(peer);
05037 }
05038
05039
05040 static void update_peer(struct sip_peer *p, int expire)
05041 {
05042 int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
05043 if (sip_cfg.peer_rtupdate &&
05044 (p->is_realtime || rtcachefriends)) {
05045 realtime_update_peer(p->name, &p->addr, p->username, p->fullcontact, p->useragent, expire, p->deprecated_username, p->lastms);
05046 }
05047 }
05048
05049 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *cfg)
05050 {
05051 struct ast_variable *var = NULL;
05052 struct ast_flags flags = {0};
05053 char *cat = NULL;
05054 const char *insecure;
05055 while ((cat = ast_category_browse(cfg, cat))) {
05056 insecure = ast_variable_retrieve(cfg, cat, "insecure");
05057 set_insecure_flags(&flags, insecure, -1);
05058 if (ast_test_flag(&flags, SIP_INSECURE_PORT)) {
05059 var = ast_category_root(cfg, cat);
05060 break;
05061 }
05062 }
05063 return var;
05064 }
05065
05066 static struct ast_variable *get_insecure_variable_from_sippeers(const char *column, const char *value)
05067 {
05068 struct ast_config *peerlist;
05069 struct ast_variable *var = NULL;
05070 if ((peerlist = ast_load_realtime_multientry("sippeers", column, value, "insecure LIKE", "%port%", SENTINEL))) {
05071 if ((var = get_insecure_variable_from_config(peerlist))) {
05072
05073
05074 var = ast_variables_dup(var);
05075 }
05076 ast_config_destroy(peerlist);
05077 }
05078 return var;
05079 }
05080
05081
05082
05083
05084
05085
05086 static struct ast_variable *get_insecure_variable_from_sipregs(const char *column, const char *value, struct ast_variable **var)
05087 {
05088 struct ast_variable *varregs = NULL;
05089 struct ast_config *regs, *peers;
05090 char *regscat;
05091 const char *regname;
05092
05093 if (!(regs = ast_load_realtime_multientry("sipregs", column, value, SENTINEL))) {
05094 return NULL;
05095 }
05096
05097
05098 if (!(peers = ast_load_realtime_multientry("sippeers", "insecure LIKE", "%port%", SENTINEL))) {
05099 ast_config_destroy(regs);
05100 return NULL;
05101 }
05102
05103
05104
05105 regscat = NULL;
05106 while ((regscat = ast_category_browse(regs, regscat)) && (regname = ast_variable_retrieve(regs, regscat, "name"))) {
05107 char *peerscat;
05108 const char *peername;
05109
05110 peerscat = NULL;
05111 while ((peerscat = ast_category_browse(peers, peerscat)) && (peername = ast_variable_retrieve(peers, peerscat, "name"))) {
05112 if (!strcasecmp(regname, peername)) {
05113
05114
05115 const char *insecure = ast_variable_retrieve(peers, peerscat, "insecure");
05116 struct ast_flags flags = {0};
05117 set_insecure_flags(&flags, insecure, -1);
05118 if (ast_test_flag(&flags, SIP_INSECURE_PORT)) {
05119
05120 if ((varregs = ast_variables_dup(ast_category_root(regs, regscat)))) {
05121 if (!(*var = ast_variables_dup(ast_category_root(peers, peerscat)))) {
05122 ast_variables_destroy(varregs);
05123 varregs = NULL;
05124 }
05125 }
05126 goto done;
05127 }
05128 }
05129 }
05130 }
05131
05132 done:
05133 ast_config_destroy(regs);
05134 ast_config_destroy(peers);
05135 return varregs;
05136 }
05137
05138 static const char *get_name_from_variable(const struct ast_variable *var)
05139 {
05140
05141
05142
05143
05144
05145
05146
05147
05148 const struct ast_variable *tmp;
05149 for (tmp = var; tmp; tmp = tmp->next) {
05150 if (!strcasecmp(tmp->name, "name")) {
05151 if (!ast_strlen_zero(tmp->value)) {
05152 return tmp->value;
05153 }
05154 break;
05155 }
05156 }
05157 return NULL;
05158 }
05159
05160
05161
05162 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)
05163 {
05164
05165 if ((*var = ast_load_realtime("sippeers", "name", *name, "host", "dynamic", SENTINEL))) {
05166 ;
05167
05168 } else if (addr && !(*var = ast_load_realtime("sippeers", "name", *name, "host", ipaddr, SENTINEL))) {
05169 ;
05170
05171 } else if ((*var = ast_load_realtime("sippeers", "name", *name, SENTINEL))) {
05172
05173
05174
05175
05176
05177
05178 if (addr) {
05179 struct ast_variable *tmp;
05180 for (tmp = *var; tmp; tmp = tmp->next) {
05181 if (!strcasecmp(tmp->name, "host")) {
05182 struct ast_sockaddr *addrs = NULL;
05183
05184 if (ast_sockaddr_resolve(&addrs,
05185 tmp->value,
05186 PARSE_PORT_FORBID,
05187 get_address_family_filter(SIP_TRANSPORT_UDP)) <= 0 ||
05188 ast_sockaddr_cmp(&addrs[0], addr)) {
05189
05190 ast_variables_destroy(*var);
05191 *var = NULL;
05192 }
05193 ast_free(addrs);
05194 break;
05195 }
05196 }
05197 }
05198 }
05199
05200
05201 if (*var) {
05202 if (varregs) {
05203 *varregs = ast_load_realtime("sipregs", "name", *name, SENTINEL);
05204 }
05205 return 1;
05206 }
05207 return 0;
05208 }
05209
05210
05211
05212
05213
05214
05215
05216 static struct ast_variable *realtime_peer_get_sippeer_helper(const char **name, struct ast_variable **varregs) {
05217 struct ast_variable *var = NULL;
05218 const char *old_name = *name;
05219 *name = get_name_from_variable(*varregs);
05220 if (!*name || !(var = ast_load_realtime("sippeers", "name", *name, SENTINEL))) {
05221 if (!*name) {
05222 ast_log(LOG_WARNING, "Found sipreg but it has no name\n");
05223 }
05224 ast_variables_destroy(*varregs);
05225 *varregs = NULL;
05226 *name = old_name;
05227 }
05228 return var;
05229 }
05230
05231
05232
05233
05234 static int realtime_peer_by_addr(const char **name, struct ast_sockaddr *addr, const char *ipaddr, struct ast_variable **var, struct ast_variable **varregs)
05235 {
05236 char portstring[6];
05237 ast_copy_string(portstring, ast_sockaddr_stringify_port(addr), sizeof(portstring));
05238
05239
05240 *name = NULL;
05241
05242
05243 if ((*var = ast_load_realtime("sippeers", "host", ipaddr, "port", portstring, SENTINEL))) {
05244 ;
05245
05246 } else if (varregs && (*varregs = ast_load_realtime("sipregs", "ipaddr", ipaddr, "port", portstring, SENTINEL)) &&
05247 (*var = realtime_peer_get_sippeer_helper(name, varregs))) {
05248 ;
05249
05250 } else if (!varregs && (*var = ast_load_realtime("sippeers", "ipaddr", ipaddr, "port", portstring, SENTINEL))) {
05251 ;
05252
05253 } else if ((*var = get_insecure_variable_from_sippeers("host", ipaddr))) {
05254 ;
05255
05256
05257
05258
05259 } else if (varregs && (*varregs = get_insecure_variable_from_sipregs("ipaddr", ipaddr, var))) {
05260 ;
05261
05262 } else if (!varregs && (*var = get_insecure_variable_from_sippeers("ipaddr", ipaddr))) {
05263 ;
05264 }
05265
05266
05267 if (!*var) {
05268 return 0;
05269 }
05270
05271
05272
05273
05274 if (!*name && !(*name = get_name_from_variable(*var))) {
05275 ast_log(LOG_WARNING, "Found peer for IP %s but it has no name\n", ipaddr);
05276 ast_variables_destroy(*var);
05277 *var = NULL;
05278 if (varregs && *varregs) {
05279 ast_variables_destroy(*varregs);
05280 *varregs = NULL;
05281 }
05282 return 0;
05283 }
05284
05285
05286
05287
05288 if (varregs && !*varregs) {
05289 *varregs = ast_load_realtime("sipregs", "name", *name, SENTINEL);
05290 }
05291 return 1;
05292 }
05293
05294
05295
05296
05297
05298
05299
05300
05301
05302
05303 static struct sip_peer *realtime_peer(const char *newpeername, struct ast_sockaddr *addr, int devstate_only, int which_objects)
05304 {
05305 struct sip_peer *peer = NULL;
05306 struct ast_variable *var = NULL;
05307 struct ast_variable *varregs = NULL;
05308 char ipaddr[INET6_ADDRSTRLEN];
05309 int realtimeregs = ast_check_realtime("sipregs");
05310
05311 if (addr) {
05312 ast_copy_string(ipaddr, ast_sockaddr_stringify_addr(addr), sizeof(ipaddr));
05313 } else {
05314 ipaddr[0] = '\0';
05315 }
05316
05317 if (newpeername && realtime_peer_by_name(&newpeername, addr, ipaddr, &var, realtimeregs ? &varregs : NULL)) {
05318 ;
05319 } else if (addr && realtime_peer_by_addr(&newpeername, addr, ipaddr, &var, realtimeregs ? &varregs : NULL)) {
05320 ;
05321 } else {
05322 return NULL;
05323 }
05324
05325
05326
05327 if (which_objects == FINDUSERS) {
05328 struct ast_variable *tmp;
05329 for (tmp = var; tmp; tmp = tmp->next) {
05330 if (!strcasecmp(tmp->name, "type") && (!strcasecmp(tmp->value, "peer"))) {
05331 goto cleanup;
05332 }
05333 }
05334 }
05335
05336
05337 peer = build_peer(newpeername, var, varregs, TRUE, devstate_only);
05338 if (!peer) {
05339 goto cleanup;
05340 }
05341
05342
05343
05344 if (peer->type == 0) {
05345 if (which_objects == FINDUSERS) {
05346 peer->type = SIP_TYPE_USER;
05347 } else if (which_objects == FINDPEERS) {
05348 peer->type = SIP_TYPE_PEER;
05349 } else {
05350 peer->type = SIP_TYPE_PEER | SIP_TYPE_USER;
05351 }
05352 }
05353
05354 ast_debug(3, "-REALTIME- loading peer from database to memory. Name: %s. Peer objects: %d\n", peer->name, rpeerobjs);
05355
05356 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && !devstate_only) {
05357
05358 ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
05359 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
05360 AST_SCHED_REPLACE_UNREF(peer->expire, sched, sip_cfg.rtautoclear * 1000, expire_register, peer,
05361 unref_peer(_data, "remove registration ref"),
05362 unref_peer(peer, "remove registration ref"),
05363 ref_peer(peer, "add registration ref"));
05364 }
05365 ao2_t_link(peers, peer, "link peer into peers table");
05366 if (!ast_sockaddr_isnull(&peer->addr)) {
05367 ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
05368 }
05369 }
05370 peer->is_realtime = 1;
05371
05372 cleanup:
05373 ast_variables_destroy(var);
05374 ast_variables_destroy(varregs);
05375 return peer;
05376 }
05377
05378
05379 static int find_by_name(void *obj, void *arg, void *data, int flags)
05380 {
05381 struct sip_peer *search = obj, *match = arg;
05382 int *which_objects = data;
05383
05384
05385 if (strcmp(search->name, match->name)) {
05386 return 0;
05387 }
05388
05389 switch (*which_objects) {
05390 case FINDUSERS:
05391 if (!(search->type & SIP_TYPE_USER)) {
05392 return 0;
05393 }
05394 break;
05395 case FINDPEERS:
05396 if (!(search->type & SIP_TYPE_PEER)) {
05397 return 0;
05398 }
05399 break;
05400 case FINDALLDEVICES:
05401 break;
05402 }
05403
05404 return CMP_MATCH | CMP_STOP;
05405 }
05406
05407
05408
05409
05410
05411
05412
05413
05414
05415
05416
05417
05418
05419
05420 static struct sip_peer *find_peer(const char *peer, struct ast_sockaddr *addr, int realtime, int which_objects, int devstate_only, int transport)
05421 {
05422 struct sip_peer *p = NULL;
05423 struct sip_peer tmp_peer;
05424
05425 if (peer) {
05426 ast_copy_string(tmp_peer.name, peer, sizeof(tmp_peer.name));
05427 p = ao2_t_callback_data(peers, OBJ_POINTER, find_by_name, &tmp_peer, &which_objects, "ao2_find in peers table");
05428 } else if (addr) {
05429 ast_sockaddr_copy(&tmp_peer.addr, addr);
05430 tmp_peer.flags[0].flags = 0;
05431 tmp_peer.transports = transport;
05432 p = ao2_t_find(peers_by_ip, &tmp_peer, OBJ_POINTER, "ao2_find in peers_by_ip table");
05433 if (!p) {
05434 ast_set_flag(&tmp_peer.flags[0], SIP_INSECURE_PORT);
05435 p = ao2_t_find(peers_by_ip, &tmp_peer, OBJ_POINTER, "ao2_find in peers_by_ip table 2");
05436 if (p) {
05437 return p;
05438 }
05439 }
05440 }
05441
05442 if (!p && (realtime || devstate_only)) {
05443 p = realtime_peer(peer, addr, devstate_only, which_objects);
05444 if (p) {
05445 switch (which_objects) {
05446 case FINDUSERS:
05447 if (!(p->type & SIP_TYPE_USER)) {
05448 unref_peer(p, "Wrong type of realtime SIP endpoint");
05449 return NULL;
05450 }
05451 break;
05452 case FINDPEERS:
05453 if (!(p->type & SIP_TYPE_PEER)) {
05454 unref_peer(p, "Wrong type of realtime SIP endpoint");
05455 return NULL;
05456 }
05457 break;
05458 case FINDALLDEVICES:
05459 break;
05460 }
05461 }
05462 }
05463
05464 return p;
05465 }
05466
05467
05468 static void do_setnat(struct sip_pvt *p)
05469 {
05470 const char *mode;
05471 int natflags;
05472
05473 natflags = ast_test_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP);
05474 mode = natflags ? "On" : "Off";
05475
05476 if (p->rtp) {
05477 ast_debug(1, "Setting NAT on RTP to %s\n", mode);
05478 ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_NAT, natflags);
05479 }
05480 if (p->vrtp) {
05481 ast_debug(1, "Setting NAT on VRTP to %s\n", mode);
05482 ast_rtp_instance_set_prop(p->vrtp, AST_RTP_PROPERTY_NAT, natflags);
05483 }
05484 if (p->udptl) {
05485 ast_debug(1, "Setting NAT on UDPTL to %s\n", mode);
05486 ast_udptl_setnat(p->udptl, natflags);
05487 }
05488 if (p->trtp) {
05489 ast_debug(1, "Setting NAT on TRTP to %s\n", mode);
05490 ast_rtp_instance_set_prop(p->trtp, AST_RTP_PROPERTY_NAT, natflags);
05491 }
05492 }
05493
05494
05495 static void change_t38_state(struct sip_pvt *p, int state)
05496 {
05497 int old = p->t38.state;
05498 struct ast_channel *chan = p->owner;
05499 struct ast_control_t38_parameters parameters = { .request_response = 0 };
05500
05501
05502 if (old == state)
05503 return;
05504
05505 p->t38.state = state;
05506 ast_debug(2, "T38 state changed to %d on channel %s\n", p->t38.state, chan ? chan->name : "<none>");
05507
05508
05509 if (!chan)
05510 return;
05511
05512
05513 switch (state) {
05514 case T38_PEER_REINVITE:
05515 parameters = p->t38.their_parms;
05516 parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
05517 parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
05518 ast_udptl_set_tag(p->udptl, "%s", chan->name);
05519 break;
05520 case T38_ENABLED:
05521 parameters = p->t38.their_parms;
05522 parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
05523 parameters.request_response = AST_T38_NEGOTIATED;
05524 ast_udptl_set_tag(p->udptl, "%s", chan->name);
05525 break;
05526 case T38_DISABLED:
05527 if (old == T38_ENABLED) {
05528 parameters.request_response = AST_T38_TERMINATED;
05529 } else if (old == T38_LOCAL_REINVITE) {
05530 parameters.request_response = AST_T38_REFUSED;
05531 }
05532 break;
05533 case T38_LOCAL_REINVITE:
05534
05535 break;
05536 }
05537
05538
05539 if (parameters.request_response)
05540 ast_queue_control_data(chan, AST_CONTROL_T38_PARAMETERS, ¶meters, sizeof(parameters));
05541 }
05542
05543
05544 static void set_t38_capabilities(struct sip_pvt *p)
05545 {
05546 if (p->udptl) {
05547 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY) {
05548 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
05549 } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_FEC) {
05550 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
05551 } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL) {
05552 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
05553 }
05554 }
05555 }
05556
05557 static void copy_socket_data(struct sip_socket *to_sock, const struct sip_socket *from_sock)
05558 {
05559 if (to_sock->tcptls_session) {
05560 ao2_ref(to_sock->tcptls_session, -1);
05561 to_sock->tcptls_session = NULL;
05562 }
05563
05564 if (from_sock->tcptls_session) {
05565 ao2_ref(from_sock->tcptls_session, +1);
05566 }
05567
05568 *to_sock = *from_sock;
05569 }
05570
05571
05572
05573
05574 static int dialog_initialize_rtp(struct sip_pvt *dialog)
05575 {
05576 struct ast_sockaddr bindaddr_tmp;
05577
05578 if (!sip_methods[dialog->method].need_rtp) {
05579 return 0;
05580 }
05581
05582 ast_sockaddr_copy(&bindaddr_tmp, &bindaddr);
05583 if (!(dialog->rtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr_tmp, NULL))) {
05584 return -1;
05585 }
05586
05587 if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS) ||
05588 (ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT) && (dialog->capability & AST_FORMAT_VIDEO_MASK))) {
05589 if (!(dialog->vrtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr_tmp, NULL))) {
05590 return -1;
05591 }
05592 ast_rtp_instance_set_timeout(dialog->vrtp, dialog->rtptimeout);
05593 ast_rtp_instance_set_hold_timeout(dialog->vrtp, dialog->rtpholdtimeout);
05594 ast_rtp_instance_set_keepalive(dialog->vrtp, dialog->rtpkeepalive);
05595
05596 ast_rtp_instance_set_prop(dialog->vrtp, AST_RTP_PROPERTY_RTCP, 1);
05597 ast_rtp_instance_set_qos(dialog->vrtp, global_tos_video, global_cos_video, "SIP VIDEO");
05598 }
05599
05600 if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_TEXTSUPPORT)) {
05601 if (!(dialog->trtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr_tmp, NULL))) {
05602 return -1;
05603 }
05604
05605 ast_rtp_instance_set_keepalive(dialog->trtp, dialog->rtpkeepalive);
05606
05607 ast_rtp_instance_set_prop(dialog->trtp, AST_RTP_PROPERTY_RTCP, 1);
05608 }
05609
05610 ast_rtp_instance_set_timeout(dialog->rtp, dialog->rtptimeout);
05611 ast_rtp_instance_set_hold_timeout(dialog->rtp, dialog->rtpholdtimeout);
05612 ast_rtp_instance_set_keepalive(dialog->rtp, dialog->rtpkeepalive);
05613
05614 ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_RTCP, 1);
05615 ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
05616 ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
05617
05618 ast_rtp_instance_set_qos(dialog->rtp, global_tos_audio, global_cos_audio, "SIP RTP");
05619
05620 do_setnat(dialog);
05621
05622 return 0;
05623 }
05624
05625
05626
05627
05628
05629
05630
05631
05632 static int create_addr_from_peer(struct sip_pvt *dialog, struct sip_peer *peer)
05633 {
05634 struct sip_auth_container *credentials;
05635
05636
05637
05638
05639 if (dialog->socket.type && check_request_transport(peer, dialog))
05640 return -1;
05641 copy_socket_data(&dialog->socket, &peer->socket);
05642
05643 if (!(ast_sockaddr_isnull(&peer->addr) && ast_sockaddr_isnull(&peer->defaddr)) &&
05644 (!peer->maxms || ((peer->lastms >= 0) && (peer->lastms <= peer->maxms)))) {
05645 dialog->sa = ast_sockaddr_isnull(&peer->addr) ? peer->defaddr : peer->addr;
05646 dialog->recv = dialog->sa;
05647 } else
05648 return -1;
05649
05650
05651 ast_copy_flags(&dialog->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
05652 ast_copy_flags(&dialog->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
05653 ast_copy_flags(&dialog->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
05654 dialog->capability = peer->capability;
05655 dialog->prefs = peer->prefs;
05656 dialog->amaflags = peer->amaflags;
05657
05658 ast_string_field_set(dialog, engine, peer->engine);
05659
05660 dialog->rtptimeout = peer->rtptimeout;
05661 dialog->rtpholdtimeout = peer->rtpholdtimeout;
05662 dialog->rtpkeepalive = peer->rtpkeepalive;
05663 if (dialog_initialize_rtp(dialog)) {
05664 return -1;
05665 }
05666
05667 if (dialog->rtp) {
05668 ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
05669 ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
05670
05671 ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(dialog->rtp), dialog->rtp, &dialog->prefs);
05672 dialog->autoframing = peer->autoframing;
05673 }
05674
05675
05676 ast_string_field_set(dialog, peername, peer->name);
05677 ast_string_field_set(dialog, authname, peer->username);
05678 ast_string_field_set(dialog, username, peer->username);
05679 ast_string_field_set(dialog, peersecret, peer->secret);
05680 ast_string_field_set(dialog, peermd5secret, peer->md5secret);
05681 ast_string_field_set(dialog, mohsuggest, peer->mohsuggest);
05682 ast_string_field_set(dialog, mohinterpret, peer->mohinterpret);
05683 ast_string_field_set(dialog, tohost, peer->tohost);
05684 ast_string_field_set(dialog, fullcontact, peer->fullcontact);
05685 ast_string_field_set(dialog, accountcode, peer->accountcode);
05686 ast_string_field_set(dialog, context, peer->context);
05687 ast_string_field_set(dialog, cid_num, peer->cid_num);
05688 ast_string_field_set(dialog, cid_name, peer->cid_name);
05689 ast_string_field_set(dialog, cid_tag, peer->cid_tag);
05690 ast_string_field_set(dialog, mwi_from, peer->mwi_from);
05691 if (!ast_strlen_zero(peer->parkinglot)) {
05692 ast_string_field_set(dialog, parkinglot, peer->parkinglot);
05693 }
05694 ast_string_field_set(dialog, engine, peer->engine);
05695 ref_proxy(dialog, obproxy_get(dialog, peer));
05696 dialog->callgroup = peer->callgroup;
05697 dialog->pickupgroup = peer->pickupgroup;
05698 dialog->allowtransfer = peer->allowtransfer;
05699 dialog->jointnoncodeccapability = dialog->noncodeccapability;
05700
05701
05702 ao2_lock(peer);
05703 credentials = peer->auth;
05704 if (credentials) {
05705 ao2_t_ref(credentials, +1, "Ref peer auth for dialog");
05706 }
05707 ao2_unlock(peer);
05708 ao2_lock(dialog);
05709 if (dialog->peerauth) {
05710 ao2_t_ref(dialog->peerauth, -1, "Unref old dialog peer auth");
05711 }
05712 dialog->peerauth = credentials;
05713 ao2_unlock(dialog);
05714
05715 dialog->maxcallbitrate = peer->maxcallbitrate;
05716 dialog->disallowed_methods = peer->disallowed_methods;
05717 ast_cc_copy_config_params(dialog->cc_params, peer->cc_params);
05718 if (ast_strlen_zero(dialog->tohost))
05719 ast_string_field_set(dialog, tohost, ast_sockaddr_stringify_host_remote(&dialog->sa));
05720 if (!ast_strlen_zero(peer->fromdomain)) {
05721 ast_string_field_set(dialog, fromdomain, peer->fromdomain);
05722 if (!dialog->initreq.headers) {
05723 char *new_callid;
05724 char *tmpcall = ast_strdupa(dialog->callid);
05725
05726 new_callid = strchr(tmpcall, '@');
05727 if (new_callid) {
05728 int callid_size;
05729
05730 *new_callid = '\0';
05731
05732
05733 callid_size = strlen(tmpcall) + strlen(peer->fromdomain) + 2;
05734 new_callid = ast_alloca(callid_size);
05735 snprintf(new_callid, callid_size, "%s@%s", tmpcall, peer->fromdomain);
05736 change_callid_pvt(dialog, new_callid);
05737 }
05738 }
05739 }
05740 if (!ast_strlen_zero(peer->fromuser))
05741 ast_string_field_set(dialog, fromuser, peer->fromuser);
05742 if (!ast_strlen_zero(peer->language))
05743 ast_string_field_set(dialog, language, peer->language);
05744
05745
05746
05747
05748 if (peer->maxms && peer->lastms)
05749 dialog->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
05750 else
05751 dialog->timer_t1 = peer->timer_t1;
05752
05753
05754
05755 if (peer->timer_b)
05756 dialog->timer_b = peer->timer_b;
05757 else
05758 dialog->timer_b = 64 * dialog->timer_t1;
05759
05760 if ((ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
05761 (ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
05762 dialog->noncodeccapability |= AST_RTP_DTMF;
05763 else
05764 dialog->noncodeccapability &= ~AST_RTP_DTMF;
05765 dialog->directmediaha = ast_duplicate_ha_list(peer->directmediaha);
05766 if (peer->call_limit)
05767 ast_set_flag(&dialog->flags[0], SIP_CALL_LIMIT);
05768 if (!dialog->portinuri)
05769 dialog->portinuri = peer->portinuri;
05770 dialog->chanvars = copy_vars(peer->chanvars);
05771 if (peer->fromdomainport)
05772 dialog->fromdomainport = peer->fromdomainport;
05773 dialog->callingpres = peer->callingpres;
05774
05775 return 0;
05776 }
05777
05778
05779 static inline int default_sip_port(enum sip_transport type)
05780 {
05781 return type == SIP_TRANSPORT_TLS ? STANDARD_TLS_PORT : STANDARD_SIP_PORT;
05782 }
05783
05784
05785
05786
05787 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct ast_sockaddr *addr, int newdialog)
05788 {
05789 struct sip_peer *peer;
05790 char *peername, *peername2, *hostn;
05791 char host[MAXHOSTNAMELEN];
05792 char service[MAXHOSTNAMELEN];
05793 int srv_ret = 0;
05794 int tportno;
05795
05796 AST_DECLARE_APP_ARGS(hostport,
05797 AST_APP_ARG(host);
05798 AST_APP_ARG(port);
05799 );
05800
05801 peername = ast_strdupa(opeer);
05802 peername2 = ast_strdupa(opeer);
05803 AST_NONSTANDARD_RAW_ARGS(hostport, peername2, ':');
05804
05805 if (hostport.port)
05806 dialog->portinuri = 1;
05807
05808 dialog->timer_t1 = global_t1;
05809 dialog->timer_b = global_timer_b;
05810 peer = find_peer(peername, NULL, TRUE, FINDPEERS, FALSE, 0);
05811
05812 if (peer) {
05813 int res;
05814 if (newdialog) {
05815 set_socket_transport(&dialog->socket, 0);
05816 }
05817 res = create_addr_from_peer(dialog, peer);
05818 dialog->relatedpeer = ref_peer(peer, "create_addr: setting dialog's relatedpeer pointer");
05819 unref_peer(peer, "create_addr: unref peer from find_peer hashtab lookup");
05820 return res;
05821 } else if (ast_check_digits(peername)) {
05822
05823
05824
05825 ast_log(LOG_WARNING, "Purely numeric hostname (%s), and not a peer--rejecting!\n", peername);
05826 return -1;
05827 } else {
05828 dialog->rtptimeout = global_rtptimeout;
05829 dialog->rtpholdtimeout = global_rtpholdtimeout;
05830 dialog->rtpkeepalive = global_rtpkeepalive;
05831 if (dialog_initialize_rtp(dialog)) {
05832 return -1;
05833 }
05834 }
05835
05836 ast_string_field_set(dialog, tohost, hostport.host);
05837 dialog->allowed_methods &= ~sip_cfg.disallowed_methods;
05838
05839
05840 ref_proxy(dialog, obproxy_get(dialog, NULL));
05841
05842 if (addr) {
05843
05844 ast_sockaddr_copy(&dialog->sa, addr);
05845 } else {
05846
05847
05848
05849
05850
05851
05852 hostn = peername;
05853
05854
05855
05856 if (!hostport.port && sip_cfg.srvlookup) {
05857 snprintf(service, sizeof(service), "_%s._%s.%s",
05858 get_srv_service(dialog->socket.type),
05859 get_srv_protocol(dialog->socket.type), peername);
05860 if ((srv_ret = ast_get_srv(NULL, host, sizeof(host), &tportno,
05861 service)) > 0) {
05862 hostn = host;
05863 }
05864 }
05865
05866 if (ast_sockaddr_resolve_first_transport(&dialog->sa, hostn, 0, dialog->socket.type ? dialog->socket.type : SIP_TRANSPORT_UDP)) {
05867 ast_log(LOG_WARNING, "No such host: %s\n", peername);
05868 return -1;
05869 }
05870
05871 if (srv_ret > 0) {
05872 ast_sockaddr_set_port(&dialog->sa, tportno);
05873 }
05874 }
05875
05876 if (!dialog->socket.type)
05877 set_socket_transport(&dialog->socket, SIP_TRANSPORT_UDP);
05878 if (!dialog->socket.port) {
05879 dialog->socket.port = htons(ast_sockaddr_port(&bindaddr));
05880 }
05881
05882 if (!ast_sockaddr_port(&dialog->sa)) {
05883 ast_sockaddr_set_port(&dialog->sa, default_sip_port(dialog->socket.type));
05884 }
05885 ast_sockaddr_copy(&dialog->recv, &dialog->sa);
05886 return 0;
05887 }
05888
05889
05890
05891
05892 static int auto_congest(const void *arg)
05893 {
05894 struct sip_pvt *p = (struct sip_pvt *)arg;
05895
05896 sip_pvt_lock(p);
05897 p->initid = -1;
05898 if (p->owner) {
05899
05900 if (!ast_channel_trylock(p->owner)) {
05901 append_history(p, "Cong", "Auto-congesting (timer)");
05902 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
05903 ast_channel_unlock(p->owner);
05904 }
05905
05906
05907 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
05908 }
05909 sip_pvt_unlock(p);
05910 dialog_unref(p, "unreffing arg passed into auto_congest callback (p->initid)");
05911 return 0;
05912 }
05913
05914
05915
05916
05917 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
05918 {
05919 int res;
05920 struct sip_pvt *p = ast->tech_pvt;
05921 struct varshead *headp;
05922 struct ast_var_t *current;
05923 const char *referer = NULL;
05924 int cc_core_id;
05925 char uri[SIPBUFSIZE] = "";
05926
05927 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
05928 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
05929 return -1;
05930 }
05931
05932 if (ast_cc_is_recall(ast, &cc_core_id, "SIP")) {
05933 char device_name[AST_CHANNEL_NAME];
05934 struct ast_cc_monitor *recall_monitor;
05935 struct sip_monitor_instance *monitor_instance;
05936 ast_channel_get_device_name(ast, device_name, sizeof(device_name));
05937 if ((recall_monitor = ast_cc_get_monitor_by_recall_core_id(cc_core_id, device_name))) {
05938 monitor_instance = recall_monitor->private_data;
05939 ast_copy_string(uri, monitor_instance->notify_uri, sizeof(uri));
05940 ao2_t_ref(recall_monitor, -1, "Got the URI we need so unreffing monitor");
05941 }
05942 }
05943
05944
05945 headp=&ast->varshead;
05946 AST_LIST_TRAVERSE(headp, current, entries) {
05947
05948 if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
05949 p->options->vxml_url = ast_var_value(current);
05950 } else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
05951 p->options->uri_options = ast_var_value(current);
05952 } else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
05953
05954 p->options->addsipheaders = 1;
05955 } else if (!strcasecmp(ast_var_name(current), "SIPFROMDOMAIN")) {
05956 ast_string_field_set(p, fromdomain, ast_var_value(current));
05957 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER")) {
05958
05959 p->options->transfer = 1;
05960 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REFERER")) {
05961
05962 referer = ast_var_value(current);
05963 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REPLACES")) {
05964
05965 p->options->replaces = ast_var_value(current);
05966 } else if (!strcasecmp(ast_var_name(current), "SIP_MAX_FORWARDS")) {
05967 if (sscanf(ast_var_value(current), "%d", &(p->maxforwards)) != 1) {
05968 ast_log(LOG_WARNING, "The SIP_MAX_FORWARDS channel variable is not a valid integer.\n");
05969 }
05970 }
05971 }
05972
05973
05974 if (p->req_secure_signaling && p->socket.type != SIP_TRANSPORT_TLS) {
05975 ast_log(LOG_WARNING, "Encrypted signaling is required\n");
05976 ast->hangupcause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
05977 return -1;
05978 }
05979
05980 if (ast_test_flag(&p->flags[1], SIP_PAGE2_USE_SRTP)) {
05981 if (ast_test_flag(&p->flags[0], SIP_REINVITE)) {
05982 ast_debug(1, "Direct media not possible when using SRTP, ignoring canreinvite setting\n");
05983 ast_clear_flag(&p->flags[0], SIP_REINVITE);
05984 }
05985
05986 if (p->rtp && !p->srtp && setup_srtp(&p->srtp) < 0) {
05987 ast_log(LOG_WARNING, "SRTP audio setup failed\n");
05988 return -1;
05989 }
05990
05991 if (p->vrtp && !p->vsrtp && setup_srtp(&p->vsrtp) < 0) {
05992 ast_log(LOG_WARNING, "SRTP video setup failed\n");
05993 return -1;
05994 }
05995
05996 if (p->trtp && !p->tsrtp && setup_srtp(&p->tsrtp) < 0) {
05997 ast_log(LOG_WARNING, "SRTP text setup failed\n");
05998 return -1;
05999 }
06000 }
06001
06002 res = 0;
06003 ast_set_flag(&p->flags[0], SIP_OUTGOING);
06004
06005
06006
06007
06008 ast_clear_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_T38);
06009
06010 if (p->options->transfer) {
06011 char buf[SIPBUFSIZE/2];
06012
06013 if (referer) {
06014 if (sipdebug)
06015 ast_debug(3, "Call for %s transferred by %s\n", p->username, referer);
06016 snprintf(buf, sizeof(buf)-1, "-> %s (via %s)", p->cid_name, referer);
06017 } else
06018 snprintf(buf, sizeof(buf)-1, "-> %s", p->cid_name);
06019 ast_string_field_set(p, cid_name, buf);
06020 }
06021 ast_debug(1, "Outgoing Call for %s\n", p->username);
06022
06023 res = update_call_counter(p, INC_CALL_RINGING);
06024
06025 if (res == -1) {
06026 ast->hangupcause = AST_CAUSE_USER_BUSY;
06027 return res;
06028 }
06029 p->callingpres = ast_party_id_presentation(&ast->caller.id);
06030 p->jointcapability = ast_rtp_instance_available_formats(p->rtp, p->capability, p->prefcodec);
06031 p->jointnoncodeccapability = p->noncodeccapability;
06032
06033
06034 if (!(p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
06035 ast_log(LOG_WARNING, "No audio format found to offer. Cancelling call to %s\n", p->username);
06036 res = -1;
06037 } else {
06038 int xmitres;
06039 struct ast_party_connected_line connected;
06040 struct ast_set_party_connected_line update_connected;
06041
06042 sip_pvt_lock(p);
06043
06044
06045 memset(&update_connected, 0, sizeof(update_connected));
06046 ast_party_connected_line_init(&connected);
06047 if (!ast_strlen_zero(p->cid_num)
06048 || (p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
06049 update_connected.id.number = 1;
06050 connected.id.number.valid = 1;
06051 connected.id.number.str = (char *) p->cid_num;
06052 connected.id.number.presentation = p->callingpres;
06053 }
06054 if (!ast_strlen_zero(p->cid_name)
06055 || (p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
06056 update_connected.id.name = 1;
06057 connected.id.name.valid = 1;
06058 connected.id.name.str = (char *) p->cid_name;
06059 connected.id.name.presentation = p->callingpres;
06060 }
06061 if (update_connected.id.number || update_connected.id.name) {
06062 connected.id.tag = (char *) p->cid_tag;
06063 connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
06064 ast_channel_queue_connected_line_update(ast, &connected, &update_connected);
06065 }
06066
06067 xmitres = transmit_invite(p, SIP_INVITE, 1, 2, uri);
06068 if (xmitres == XMIT_ERROR) {
06069 sip_pvt_unlock(p);
06070 return -1;
06071 }
06072 p->invitestate = INV_CALLING;
06073
06074
06075 AST_SCHED_REPLACE_UNREF(p->initid, sched, p->timer_b, auto_congest, p,
06076 dialog_unref(_data, "dialog ptr dec when SCHED_REPLACE del op succeeded"),
06077 dialog_unref(p, "dialog ptr dec when SCHED_REPLACE add failed"),
06078 dialog_ref(p, "dialog ptr inc when SCHED_REPLACE add succeeded") );
06079 sip_pvt_unlock(p);
06080 }
06081 return res;
06082 }
06083
06084
06085
06086 static void sip_registry_destroy(struct sip_registry *reg)
06087 {
06088
06089 ast_debug(3, "Destroying registry entry for %s@%s\n", reg->username, reg->hostname);
06090
06091 if (reg->call) {
06092
06093
06094 reg->call->registry = registry_unref(reg->call->registry, "destroy reg->call->registry");
06095 ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", reg->username, reg->hostname);
06096 dialog_unlink_all(reg->call);
06097 reg->call = dialog_unref(reg->call, "unref reg->call");
06098
06099 }
06100 AST_SCHED_DEL(sched, reg->expire);
06101 AST_SCHED_DEL(sched, reg->timeout);
06102
06103 ast_string_field_free_memory(reg);
06104 ast_atomic_fetchadd_int(®objs, -1);
06105 ast_free(reg);
06106 }
06107
06108
06109 static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi)
06110 {
06111 if (mwi->call) {
06112 mwi->call->mwi = NULL;
06113 sip_destroy(mwi->call);
06114 }
06115
06116 AST_SCHED_DEL(sched, mwi->resub);
06117 ast_string_field_free_memory(mwi);
06118 ast_free(mwi);
06119 }
06120
06121
06122 void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist)
06123 {
06124 struct sip_request *req;
06125
06126
06127 if (p->stimer) {
06128 p->stimer->quit_flag = 1;
06129 stop_session_timer(p);
06130 ast_free(p->stimer);
06131 p->stimer = NULL;
06132 }
06133
06134 if (sip_debug_test_pvt(p))
06135 ast_verbose("Really destroying SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
06136
06137 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
06138 update_call_counter(p, DEC_CALL_LIMIT);
06139 ast_debug(2, "This call did not properly clean up call limits. Call ID %s\n", p->callid);
06140 }
06141
06142
06143 if (p->owner) {
06144 if (lockowner)
06145 ast_channel_lock(p->owner);
06146 ast_debug(1, "Detaching from %s\n", p->owner->name);
06147 p->owner->tech_pvt = NULL;
06148
06149 p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
06150 if (lockowner)
06151 ast_channel_unlock(p->owner);
06152
06153 usleep(1);
06154 }
06155
06156
06157 if (p->relatedpeer && p->relatedpeer->mwipvt == p)
06158 p->relatedpeer->mwipvt = dialog_unref(p->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
06159 if (p->relatedpeer && p->relatedpeer->call == p)
06160 p->relatedpeer->call = dialog_unref(p->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
06161
06162 if (p->relatedpeer)
06163 p->relatedpeer = unref_peer(p->relatedpeer,"unsetting a dialog relatedpeer field in sip_destroy");
06164
06165 if (p->registry) {
06166 if (p->registry->call == p)
06167 p->registry->call = dialog_unref(p->registry->call, "nulling out the registry's call dialog field in unlink_all");
06168 p->registry = registry_unref(p->registry, "delete p->registry");
06169 }
06170
06171 if (p->mwi) {
06172 p->mwi->call = NULL;
06173 p->mwi = NULL;
06174 }
06175
06176 if (dumphistory)
06177 sip_dump_history(p);
06178
06179 if (p->options) {
06180 if (p->options->outboundproxy) {
06181 ao2_ref(p->options->outboundproxy, -1);
06182 }
06183 ast_free(p->options);
06184 p->options = NULL;
06185 }
06186
06187 if (p->notify) {
06188 ast_variables_destroy(p->notify->headers);
06189 ast_free(p->notify->content);
06190 ast_free(p->notify);
06191 p->notify = NULL;
06192 }
06193 if (p->rtp) {
06194 ast_rtp_instance_destroy(p->rtp);
06195 p->rtp = NULL;
06196 }
06197 if (p->vrtp) {
06198 ast_rtp_instance_destroy(p->vrtp);
06199 p->vrtp = NULL;
06200 }
06201 if (p->trtp) {
06202 ast_rtp_instance_destroy(p->trtp);
06203 p->trtp = NULL;
06204 }
06205 if (p->udptl) {
06206 ast_udptl_destroy(p->udptl);
06207 p->udptl = NULL;
06208 }
06209 if (p->refer) {
06210 if (p->refer->refer_call) {
06211 p->refer->refer_call = dialog_unref(p->refer->refer_call, "unref dialog p->refer->refer_call");
06212 }
06213 ast_free(p->refer);
06214 p->refer = NULL;
06215 }
06216 if (p->route) {
06217 free_old_route(p->route);
06218 p->route = NULL;
06219 }
06220 deinit_req(&p->initreq);
06221
06222
06223 if (p->history) {
06224 struct sip_history *hist;
06225 while ( (hist = AST_LIST_REMOVE_HEAD(p->history, list)) ) {
06226 ast_free(hist);
06227 p->history_entries--;
06228 }
06229 ast_free(p->history);
06230 p->history = NULL;
06231 }
06232
06233 while ((req = AST_LIST_REMOVE_HEAD(&p->request_queue, next))) {
06234 ast_free(req);
06235 }
06236
06237 if (p->chanvars) {
06238 ast_variables_destroy(p->chanvars);
06239 p->chanvars = NULL;
06240 }
06241
06242 if (p->srtp) {
06243 sip_srtp_destroy(p->srtp);
06244 p->srtp = NULL;
06245 }
06246
06247 if (p->vsrtp) {
06248 sip_srtp_destroy(p->vsrtp);
06249 p->vsrtp = NULL;
06250 }
06251
06252 if (p->tsrtp) {
06253 sip_srtp_destroy(p->tsrtp);
06254 p->tsrtp = NULL;
06255 }
06256
06257 if (p->directmediaha) {
06258 ast_free_ha(p->directmediaha);
06259 p->directmediaha = NULL;
06260 }
06261
06262 ast_string_field_free_memory(p);
06263
06264 ast_cc_config_params_destroy(p->cc_params);
06265 p->cc_params = NULL;
06266
06267 if (p->epa_entry) {
06268 ao2_ref(p->epa_entry, -1);
06269 p->epa_entry = NULL;
06270 }
06271
06272 if (p->socket.tcptls_session) {
06273 ao2_ref(p->socket.tcptls_session, -1);
06274 p->socket.tcptls_session = NULL;
06275 }
06276
06277 if (p->peerauth) {
06278 ao2_t_ref(p->peerauth, -1, "Removing active peer authentication");
06279 p->peerauth = NULL;
06280 }
06281 }
06282
06283
06284
06285
06286
06287
06288
06289
06290
06291
06292
06293
06294
06295
06296
06297 static int update_call_counter(struct sip_pvt *fup, int event)
06298 {
06299 char name[256];
06300 int *inuse = NULL, *call_limit = NULL, *inringing = NULL;
06301 int outgoing = fup->outgoing_call;
06302 struct sip_peer *p = NULL;
06303
06304 ast_debug(3, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
06305
06306
06307
06308
06309 if (!ast_test_flag(&fup->flags[0], SIP_CALL_LIMIT) && !ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD))
06310 return 0;
06311
06312 ast_copy_string(name, fup->username, sizeof(name));
06313
06314
06315 if (fup->relatedpeer) {
06316 p = ref_peer(fup->relatedpeer, "ref related peer for update_call_counter");
06317 inuse = &p->inUse;
06318 call_limit = &p->call_limit;
06319 inringing = &p->inRinging;
06320 ast_copy_string(name, fup->peername, sizeof(name));
06321 }
06322 if (!p) {
06323 ast_debug(2, "%s is not a local device, no call limit\n", name);
06324 return 0;
06325 }
06326
06327 switch(event) {
06328
06329 case DEC_CALL_LIMIT:
06330
06331 if (inuse) {
06332 sip_pvt_lock(fup);
06333 ao2_lock(p);
06334 if (*inuse > 0) {
06335 if (ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
06336 (*inuse)--;
06337 ast_clear_flag(&fup->flags[0], SIP_INC_COUNT);
06338 }
06339 } else {
06340 *inuse = 0;
06341 }
06342 ao2_unlock(p);
06343 sip_pvt_unlock(fup);
06344 }
06345
06346
06347 if (inringing) {
06348 sip_pvt_lock(fup);
06349 ao2_lock(p);
06350 if (*inringing > 0) {
06351 if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
06352 (*inringing)--;
06353 ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
06354 }
06355 } else {
06356 *inringing = 0;
06357 }
06358 ao2_unlock(p);
06359 sip_pvt_unlock(fup);
06360 }
06361
06362
06363 sip_pvt_lock(fup);
06364 ao2_lock(p);
06365 if (ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD) && sip_cfg.notifyhold) {
06366 ast_clear_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD);
06367 ao2_unlock(p);
06368 sip_pvt_unlock(fup);
06369 sip_peer_hold(fup, FALSE);
06370 } else {
06371 ao2_unlock(p);
06372 sip_pvt_unlock(fup);
06373 }
06374 if (sipdebug)
06375 ast_debug(2, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
06376 break;
06377
06378 case INC_CALL_RINGING:
06379 case INC_CALL_LIMIT:
06380
06381 if (*call_limit > 0 ) {
06382 if (*inuse >= *call_limit) {
06383 ast_log(LOG_NOTICE, "Call %s %s '%s' rejected due to usage limit of %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
06384 unref_peer(p, "update_call_counter: unref peer p, call limit exceeded");
06385 return -1;
06386 }
06387 }
06388 if (inringing && (event == INC_CALL_RINGING)) {
06389 sip_pvt_lock(fup);
06390 ao2_lock(p);
06391 if (!ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
06392 (*inringing)++;
06393 ast_set_flag(&fup->flags[0], SIP_INC_RINGING);
06394 }
06395 ao2_unlock(p);
06396 sip_pvt_unlock(fup);
06397 }
06398 if (inuse) {
06399 sip_pvt_lock(fup);
06400 ao2_lock(p);
06401 if (!ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
06402 (*inuse)++;
06403 ast_set_flag(&fup->flags[0], SIP_INC_COUNT);
06404 }
06405 ao2_unlock(p);
06406 sip_pvt_unlock(fup);
06407 }
06408 if (sipdebug) {
06409 ast_debug(2, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", "peer", name, *inuse, *call_limit);
06410 }
06411 break;
06412
06413 case DEC_CALL_RINGING:
06414 if (inringing) {
06415 sip_pvt_lock(fup);
06416 ao2_lock(p);
06417 if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
06418 if (*inringing > 0) {
06419 (*inringing)--;
06420 }
06421 ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
06422 }
06423 ao2_unlock(p);
06424 sip_pvt_unlock(fup);
06425 }
06426 break;
06427
06428 default:
06429 ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
06430 }
06431
06432 if (p) {
06433 ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "SIP/%s", p->name);
06434 unref_peer(p, "update_call_counter: unref_peer from call counter");
06435 }
06436 return 0;
06437 }
06438
06439
06440 static void sip_destroy_fn(void *p)
06441 {
06442 sip_destroy(p);
06443 }
06444
06445
06446
06447
06448
06449
06450 struct sip_pvt *sip_destroy(struct sip_pvt *p)
06451 {
06452 ast_debug(3, "Destroying SIP dialog %s\n", p->callid);
06453 __sip_destroy(p, TRUE, TRUE);
06454 return NULL;
06455 }
06456
06457
06458 int hangup_sip2cause(int cause)
06459 {
06460
06461
06462 switch(cause) {
06463 case 401:
06464 return AST_CAUSE_CALL_REJECTED;
06465 case 403:
06466 return AST_CAUSE_CALL_REJECTED;
06467 case 404:
06468 return AST_CAUSE_UNALLOCATED;
06469 case 405:
06470 return AST_CAUSE_INTERWORKING;
06471 case 407:
06472 return AST_CAUSE_CALL_REJECTED;
06473 case 408:
06474 return AST_CAUSE_NO_USER_RESPONSE;
06475 case 409:
06476 return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
06477 case 410:
06478 return AST_CAUSE_NUMBER_CHANGED;
06479 case 411:
06480 return AST_CAUSE_INTERWORKING;
06481 case 413:
06482 return AST_CAUSE_INTERWORKING;
06483 case 414:
06484 return AST_CAUSE_INTERWORKING;
06485 case 415:
06486 return AST_CAUSE_INTERWORKING;
06487 case 420:
06488 return AST_CAUSE_NO_ROUTE_DESTINATION;
06489 case 480:
06490 return AST_CAUSE_NO_ANSWER;
06491 case 481:
06492 return AST_CAUSE_INTERWORKING;
06493 case 482:
06494 return AST_CAUSE_INTERWORKING;
06495 case 483:
06496 return AST_CAUSE_NO_ANSWER;
06497 case 484:
06498 return AST_CAUSE_INVALID_NUMBER_FORMAT;
06499 case 485:
06500 return AST_CAUSE_UNALLOCATED;
06501 case 486:
06502 return AST_CAUSE_BUSY;
06503 case 487:
06504 return AST_CAUSE_INTERWORKING;
06505 case 488:
06506 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
06507 case 491:
06508 return AST_CAUSE_INTERWORKING;
06509 case 493:
06510 return AST_CAUSE_INTERWORKING;
06511 case 500:
06512 return AST_CAUSE_FAILURE;
06513 case 501:
06514 return AST_CAUSE_FACILITY_REJECTED;
06515 case 502:
06516 return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
06517 case 503:
06518 return AST_CAUSE_CONGESTION;
06519 case 504:
06520 return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
06521 case 505:
06522 return AST_CAUSE_INTERWORKING;
06523 case 600:
06524 return AST_CAUSE_USER_BUSY;
06525 case 603:
06526 return AST_CAUSE_CALL_REJECTED;
06527 case 604:
06528 return AST_CAUSE_UNALLOCATED;
06529 case 606:
06530 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
06531 default:
06532 if (cause < 500 && cause >= 400) {
06533
06534 return AST_CAUSE_INTERWORKING;
06535 } else if (cause < 600 && cause >= 500) {
06536
06537 return AST_CAUSE_CONGESTION;
06538 } else if (cause < 700 && cause >= 600) {
06539
06540 return AST_CAUSE_INTERWORKING;
06541 }
06542 return AST_CAUSE_NORMAL;
06543 }
06544
06545 return 0;
06546 }
06547
06548
06549
06550
06551
06552
06553
06554
06555
06556
06557
06558
06559
06560
06561
06562
06563
06564
06565
06566
06567
06568
06569
06570
06571
06572
06573
06574
06575
06576
06577
06578
06579
06580 const char *hangup_cause2sip(int cause)
06581 {
06582 switch (cause) {
06583 case AST_CAUSE_UNALLOCATED:
06584 case AST_CAUSE_NO_ROUTE_DESTINATION:
06585 case AST_CAUSE_NO_ROUTE_TRANSIT_NET:
06586 return "404 Not Found";
06587 case AST_CAUSE_CONGESTION:
06588 case AST_CAUSE_SWITCH_CONGESTION:
06589 return "503 Service Unavailable";
06590 case AST_CAUSE_NO_USER_RESPONSE:
06591 return "408 Request Timeout";
06592 case AST_CAUSE_NO_ANSWER:
06593 case AST_CAUSE_UNREGISTERED:
06594 return "480 Temporarily unavailable";
06595 case AST_CAUSE_CALL_REJECTED:
06596 return "403 Forbidden";
06597 case AST_CAUSE_NUMBER_CHANGED:
06598 return "410 Gone";
06599 case AST_CAUSE_NORMAL_UNSPECIFIED:
06600 return "480 Temporarily unavailable";
06601 case AST_CAUSE_INVALID_NUMBER_FORMAT:
06602 return "484 Address incomplete";
06603 case AST_CAUSE_USER_BUSY:
06604 return "486 Busy here";
06605 case AST_CAUSE_FAILURE:
06606 return "500 Server internal failure";
06607 case AST_CAUSE_FACILITY_REJECTED:
06608 return "501 Not Implemented";
06609 case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
06610 return "503 Service Unavailable";
06611
06612 case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
06613 return "502 Bad Gateway";
06614 case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL:
06615 return "488 Not Acceptable Here";
06616
06617 case AST_CAUSE_NOTDEFINED:
06618 default:
06619 ast_debug(1, "AST hangup cause %d (no match found in SIP)\n", cause);
06620 return NULL;
06621 }
06622
06623
06624 return 0;
06625 }
06626
06627 static int reinvite_timeout(const void *data)
06628 {
06629 struct sip_pvt *dialog = (struct sip_pvt *) data;
06630 struct ast_channel *owner = sip_pvt_lock_full(dialog);
06631 dialog->reinviteid = -1;
06632 check_pendings(dialog);
06633 if (owner) {
06634 ast_channel_unlock(owner);
06635 ast_channel_unref(owner);
06636 }
06637 ao2_unlock(dialog);
06638 dialog_unref(dialog, "unref for reinvite timeout");
06639 return 0;
06640 }
06641
06642
06643
06644 static int sip_hangup(struct ast_channel *ast)
06645 {
06646 struct sip_pvt *p = ast->tech_pvt;
06647 int needcancel = FALSE;
06648 int needdestroy = 0;
06649 struct ast_channel *oldowner = ast;
06650
06651 if (!p) {
06652 ast_debug(1, "Asked to hangup channel that was not connected\n");
06653 return 0;
06654 }
06655 if (ast_test_flag(ast, AST_FLAG_ANSWERED_ELSEWHERE) || ast->hangupcause == AST_CAUSE_ANSWERED_ELSEWHERE) {
06656 ast_debug(1, "This call was answered elsewhere\n");
06657 if (ast->hangupcause == AST_CAUSE_ANSWERED_ELSEWHERE) {
06658 ast_debug(1, "####### It's the cause code, buddy. The cause code!!!\n");
06659 }
06660 append_history(p, "Cancel", "Call answered elsewhere");
06661 p->answered_elsewhere = TRUE;
06662 }
06663
06664
06665 if (p->owner)
06666 p->hangupcause = p->owner->hangupcause;
06667
06668 if (ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
06669 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
06670 if (sipdebug)
06671 ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
06672 update_call_counter(p, DEC_CALL_LIMIT);
06673 }
06674 ast_debug(4, "SIP Transfer: Not hanging up right now... Rescheduling hangup for %s.\n", p->callid);
06675 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06676 ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
06677 p->needdestroy = 0;
06678 if (p->owner) {
06679 p->owner->tech_pvt = dialog_unref(p->owner->tech_pvt, "unref p->owner->tech_pvt");
06680 sip_pvt_lock(p);
06681 p->owner = NULL;
06682 sip_pvt_unlock(p);
06683 }
06684 ast_module_unref(ast_module_info->self);
06685 return 0;
06686 }
06687
06688 ast_debug(1, "Hangup call %s, SIP callid %s\n", ast->name, p->callid);
06689
06690 sip_pvt_lock(p);
06691 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
06692 if (sipdebug)
06693 ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
06694 update_call_counter(p, DEC_CALL_LIMIT);
06695 }
06696
06697
06698 if (p->owner != ast) {
06699 ast_log(LOG_WARNING, "Huh? We aren't the owner? Can't hangup call.\n");
06700 sip_pvt_unlock(p);
06701 return 0;
06702 }
06703
06704
06705 if (p->invitestate < INV_COMPLETED && p->owner->_state != AST_STATE_UP) {
06706 needcancel = TRUE;
06707 ast_debug(4, "Hanging up channel in state %s (not UP)\n", ast_state2str(ast->_state));
06708 }
06709
06710 stop_media_flows(p);
06711
06712 append_history(p, needcancel ? "Cancel" : "Hangup", "Cause %s", ast_cause2str(p->hangupcause));
06713
06714
06715 disable_dsp_detect(p);
06716
06717 p->owner = NULL;
06718 ast->tech_pvt = dialog_unref(ast->tech_pvt, "unref ast->tech_pvt");
06719
06720 ast_module_unref(ast_module_info->self);
06721
06722
06723
06724
06725
06726
06727 if (p->alreadygone)
06728 needdestroy = 1;
06729 else if (p->invitestate != INV_CALLING)
06730 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06731
06732
06733 if (!p->alreadygone && p->initreq.data && ast_str_strlen(p->initreq.data)) {
06734 if (needcancel) {
06735 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06736
06737 if (p->invitestate == INV_CALLING) {
06738
06739 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
06740
06741 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06742 append_history(p, "DELAY", "Not sending cancel, waiting for timeout");
06743 } else {
06744 struct sip_pkt *cur;
06745
06746 for (cur = p->packets; cur; cur = cur->next) {
06747 __sip_semi_ack(p, cur->seqno, cur->is_resp, cur->method ? cur->method : find_sip_method(ast_str_buffer(cur->data)));
06748 }
06749 p->invitestate = INV_CANCELLED;
06750
06751 transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
06752
06753
06754 needdestroy = 0;
06755 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06756 }
06757 } else {
06758 const char *res;
06759 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"));
06760 if (p->hangupcause && (res = hangup_cause2sip(p->hangupcause)))
06761 transmit_response_reliable(p, res, &p->initreq);
06762 else
06763 transmit_response_reliable(p, "603 Declined", &p->initreq);
06764 p->invitestate = INV_TERMINATED;
06765 }
06766 } else {
06767 if (p->stimer->st_active == TRUE) {
06768 stop_session_timer(p);
06769 }
06770
06771 if (!p->pendinginvite) {
06772 struct ast_channel *bridge = ast_bridged_channel(oldowner);
06773 char quality_buf[AST_MAX_USER_FIELD], *quality;
06774
06775
06776
06777
06778 while (bridge && ast_channel_trylock(bridge)) {
06779 sip_pvt_unlock(p);
06780 do {
06781 CHANNEL_DEADLOCK_AVOIDANCE(oldowner);
06782 } while (sip_pvt_trylock(p));
06783 bridge = ast_bridged_channel(oldowner);
06784 }
06785
06786 if (p->rtp) {
06787 ast_rtp_instance_set_stats_vars(oldowner, p->rtp);
06788 }
06789
06790 if (bridge) {
06791 struct sip_pvt *q = bridge->tech_pvt;
06792
06793 if (IS_SIP_TECH(bridge->tech) && q && q->rtp) {
06794 ast_rtp_instance_set_stats_vars(bridge, q->rtp);
06795 }
06796 ast_channel_unlock(bridge);
06797 }
06798
06799
06800
06801
06802
06803 if (p->rtp && (quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
06804 if (p->do_history) {
06805 append_history(p, "RTCPaudio", "Quality:%s", quality);
06806 }
06807 pbx_builtin_setvar_helper(oldowner, "RTPAUDIOQOS", quality);
06808 }
06809 if (p->vrtp && (quality = ast_rtp_instance_get_quality(p->vrtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
06810 if (p->do_history) {
06811 append_history(p, "RTCPvideo", "Quality:%s", quality);
06812 }
06813 pbx_builtin_setvar_helper(oldowner, "RTPVIDEOQOS", quality);
06814 }
06815 if (p->trtp && (quality = ast_rtp_instance_get_quality(p->trtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
06816 if (p->do_history) {
06817 append_history(p, "RTCPtext", "Quality:%s", quality);
06818 }
06819 pbx_builtin_setvar_helper(oldowner, "RTPTEXTQOS", quality);
06820 }
06821
06822
06823 if (oldowner->_state == AST_STATE_UP) {
06824 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
06825 }
06826
06827 } else {
06828
06829
06830 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
06831 ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);
06832 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"));
06833 if (sip_cancel_destroy(p)) {
06834 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
06835 }
06836
06837
06838
06839
06840 if (p->ongoing_reinvite && p->reinviteid < 0) {
06841 p->reinviteid = ast_sched_add(sched, 32 * p->timer_t1, reinvite_timeout, dialog_ref(p, "ref for reinvite_timeout"));
06842 }
06843 }
06844 }
06845 }
06846 if (needdestroy) {
06847 pvt_set_needdestroy(p, "hangup");
06848 }
06849 sip_pvt_unlock(p);
06850 return 0;
06851 }
06852
06853
06854 static void try_suggested_sip_codec(struct sip_pvt *p)
06855 {
06856 format_t fmt;
06857 const char *codec;
06858
06859 if (p->outgoing_call) {
06860 codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC_OUTBOUND");
06861 } else if (!(codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC_INBOUND"))) {
06862 codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC");
06863 }
06864
06865 if (!codec)
06866 return;
06867
06868 fmt = ast_getformatbyname(codec);
06869 if (fmt) {
06870 ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC} variable\n", codec);
06871 if (p->jointcapability & fmt) {
06872 p->jointcapability &= fmt;
06873 p->capability &= fmt;
06874 } else
06875 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
06876 } else
06877 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n", codec);
06878 return;
06879 }
06880
06881
06882
06883 static int sip_answer(struct ast_channel *ast)
06884 {
06885 int res = 0;
06886 struct sip_pvt *p = ast->tech_pvt;
06887 int oldsdp = FALSE;
06888
06889 if (!p) {
06890 ast_debug(1, "Asked to answer channel %s without tech pvt; ignoring\n",
06891 ast->name);
06892 return res;
06893 }
06894 sip_pvt_lock(p);
06895 if (ast->_state != AST_STATE_UP) {
06896 try_suggested_sip_codec(p);
06897
06898 if (ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT)) {
06899 oldsdp = TRUE;
06900 }
06901
06902 ast_setstate(ast, AST_STATE_UP);
06903 ast_debug(1, "SIP answering channel: %s\n", ast->name);
06904 ast_rtp_instance_update_source(p->rtp);
06905 res = transmit_response_with_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL, oldsdp, TRUE);
06906 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
06907 }
06908 sip_pvt_unlock(p);
06909 return res;
06910 }
06911
06912
06913 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
06914 {
06915 struct sip_pvt *p = ast->tech_pvt;
06916 int res = 0;
06917
06918 switch (frame->frametype) {
06919 case AST_FRAME_VOICE:
06920 if (!(frame->subclass.codec & ast->nativeformats)) {
06921 char s1[512], s2[512], s3[512];
06922 ast_log(LOG_WARNING, "Asked to transmit frame type %s, while native formats is %s read/write = %s/%s\n",
06923 ast_getformatname(frame->subclass.codec),
06924 ast_getformatname_multiple(s1, sizeof(s1), ast->nativeformats & AST_FORMAT_AUDIO_MASK),
06925 ast_getformatname_multiple(s2, sizeof(s2), ast->readformat),
06926 ast_getformatname_multiple(s3, sizeof(s3), ast->writeformat));
06927 return 0;
06928 }
06929 if (p) {
06930 sip_pvt_lock(p);
06931 if (p->t38.state == T38_ENABLED) {
06932
06933 sip_pvt_unlock(p);
06934 break;
06935 } else if (p->rtp) {
06936
06937 if ((ast->_state != AST_STATE_UP) &&
06938 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06939 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06940 ast_rtp_instance_update_source(p->rtp);
06941 if (!global_prematuremediafilter) {
06942 p->invitestate = INV_EARLY_MEDIA;
06943 transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06944 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06945 }
06946 }
06947 p->lastrtptx = time(NULL);
06948 res = ast_rtp_instance_write(p->rtp, frame);
06949 }
06950 sip_pvt_unlock(p);
06951 }
06952 break;
06953 case AST_FRAME_VIDEO:
06954 if (p) {
06955 sip_pvt_lock(p);
06956 if (p->vrtp) {
06957
06958 if ((ast->_state != AST_STATE_UP) &&
06959 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06960 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06961 p->invitestate = INV_EARLY_MEDIA;
06962 transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06963 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06964 }
06965 p->lastrtptx = time(NULL);
06966 res = ast_rtp_instance_write(p->vrtp, frame);
06967 }
06968 sip_pvt_unlock(p);
06969 }
06970 break;
06971 case AST_FRAME_TEXT:
06972 if (p) {
06973 sip_pvt_lock(p);
06974 if (p->red) {
06975 ast_rtp_red_buffer(p->trtp, frame);
06976 } else {
06977 if (p->trtp) {
06978
06979 if ((ast->_state != AST_STATE_UP) &&
06980 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06981 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06982 p->invitestate = INV_EARLY_MEDIA;
06983 transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06984 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06985 }
06986 p->lastrtptx = time(NULL);
06987 res = ast_rtp_instance_write(p->trtp, frame);
06988 }
06989 }
06990 sip_pvt_unlock(p);
06991 }
06992 break;
06993 case AST_FRAME_IMAGE:
06994 return 0;
06995 break;
06996 case AST_FRAME_MODEM:
06997 if (p) {
06998 sip_pvt_lock(p);
06999
07000
07001
07002
07003 if ((ast->_state == AST_STATE_UP) &&
07004 p->udptl &&
07005 (p->t38.state == T38_ENABLED)) {
07006 res = ast_udptl_write(p->udptl, frame);
07007 }
07008 sip_pvt_unlock(p);
07009 }
07010 break;
07011 default:
07012 ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
07013 return 0;
07014 }
07015
07016 return res;
07017 }
07018
07019
07020
07021 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
07022 {
07023 int ret = -1;
07024 struct sip_pvt *p;
07025
07026 if (newchan && ast_test_flag(newchan, AST_FLAG_ZOMBIE))
07027 ast_debug(1, "New channel is zombie\n");
07028 if (oldchan && ast_test_flag(oldchan, AST_FLAG_ZOMBIE))
07029 ast_debug(1, "Old channel is zombie\n");
07030
07031 if (!newchan || !newchan->tech_pvt) {
07032 if (!newchan)
07033 ast_log(LOG_WARNING, "No new channel! Fixup of %s failed.\n", oldchan->name);
07034 else
07035 ast_log(LOG_WARNING, "No SIP tech_pvt! Fixup of %s failed.\n", oldchan->name);
07036 return -1;
07037 }
07038 p = newchan->tech_pvt;
07039
07040 sip_pvt_lock(p);
07041 append_history(p, "Masq", "Old channel: %s\n", oldchan->name);
07042 append_history(p, "Masq (cont)", "...new owner: %s\n", newchan->name);
07043 if (p->owner != oldchan)
07044 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
07045 else {
07046 p->owner = newchan;
07047
07048
07049
07050
07051
07052
07053 sip_set_rtp_peer(newchan, NULL, NULL, 0, 0, 0);
07054 ret = 0;
07055 }
07056 ast_debug(3, "SIP Fixup: New owner for dialogue %s: %s (Old parent: %s)\n", p->callid, p->owner->name, oldchan->name);
07057
07058 sip_pvt_unlock(p);
07059 return ret;
07060 }
07061
07062 static int sip_senddigit_begin(struct ast_channel *ast, char digit)
07063 {
07064 struct sip_pvt *p = ast->tech_pvt;
07065 int res = 0;
07066
07067 if (!p) {
07068 ast_debug(1, "Asked to begin DTMF digit on channel %s with no pvt; ignoring\n",
07069 ast->name);
07070 return res;
07071 }
07072
07073 sip_pvt_lock(p);
07074 switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
07075 case SIP_DTMF_INBAND:
07076 res = -1;
07077 break;
07078 case SIP_DTMF_RFC2833:
07079 if (p->rtp)
07080 ast_rtp_instance_dtmf_begin(p->rtp, digit);
07081 break;
07082 default:
07083 break;
07084 }
07085 sip_pvt_unlock(p);
07086
07087 return res;
07088 }
07089
07090
07091
07092 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration)
07093 {
07094 struct sip_pvt *p = ast->tech_pvt;
07095 int res = 0;
07096
07097 if (!p) {
07098 ast_debug(1, "Asked to end DTMF digit on channel %s with no pvt; ignoring\n",
07099 ast->name);
07100 return res;
07101 }
07102
07103 sip_pvt_lock(p);
07104 switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
07105 case SIP_DTMF_INFO:
07106 case SIP_DTMF_SHORTINFO:
07107 transmit_info_with_digit(p, digit, duration);
07108 break;
07109 case SIP_DTMF_RFC2833:
07110 if (p->rtp)
07111 ast_rtp_instance_dtmf_end_with_duration(p->rtp, digit, duration);
07112 break;
07113 case SIP_DTMF_INBAND:
07114 res = -1;
07115 break;
07116 }
07117 sip_pvt_unlock(p);
07118
07119 return res;
07120 }
07121
07122
07123 static int sip_transfer(struct ast_channel *ast, const char *dest)
07124 {
07125 struct sip_pvt *p = ast->tech_pvt;
07126 int res;
07127
07128 if (!p) {
07129 ast_debug(1, "Asked to transfer channel %s with no pvt; ignoring\n",
07130 ast->name);
07131 return -1;
07132 }
07133
07134 if (dest == NULL)
07135 dest = "";
07136 sip_pvt_lock(p);
07137 if (ast->_state == AST_STATE_RING)
07138 res = sip_sipredirect(p, dest);
07139 else
07140 res = transmit_refer(p, dest);
07141 sip_pvt_unlock(p);
07142 return res;
07143 }
07144
07145
07146 static int interpret_t38_parameters(struct sip_pvt *p, const struct ast_control_t38_parameters *parameters)
07147 {
07148 int res = 0;
07149
07150 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) || !p->udptl) {
07151 return -1;
07152 }
07153 switch (parameters->request_response) {
07154 case AST_T38_NEGOTIATED:
07155 case AST_T38_REQUEST_NEGOTIATE:
07156
07157 if (!parameters->max_ifp) {
07158 change_t38_state(p, T38_DISABLED);
07159 if (p->t38.state == T38_PEER_REINVITE) {
07160 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"));
07161 transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
07162 }
07163 break;
07164 } else if (p->t38.state == T38_PEER_REINVITE) {
07165 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"));
07166 p->t38.our_parms = *parameters;
07167
07168
07169
07170 if (!p->t38.their_parms.fill_bit_removal) {
07171 p->t38.our_parms.fill_bit_removal = FALSE;
07172 }
07173 if (!p->t38.their_parms.transcoding_mmr) {
07174 p->t38.our_parms.transcoding_mmr = FALSE;
07175 }
07176 if (!p->t38.their_parms.transcoding_jbig) {
07177 p->t38.our_parms.transcoding_jbig = FALSE;
07178 }
07179 p->t38.our_parms.version = MIN(p->t38.our_parms.version, p->t38.their_parms.version);
07180 p->t38.our_parms.rate_management = p->t38.their_parms.rate_management;
07181 ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
07182 change_t38_state(p, T38_ENABLED);
07183 transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
07184 } else if (p->t38.state != T38_ENABLED) {
07185 p->t38.our_parms = *parameters;
07186 ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
07187 change_t38_state(p, T38_LOCAL_REINVITE);
07188 if (!p->pendinginvite) {
07189 transmit_reinvite_with_sdp(p, TRUE, FALSE);
07190 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
07191 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
07192 }
07193 }
07194 break;
07195 case AST_T38_TERMINATED:
07196 case AST_T38_REFUSED:
07197 case AST_T38_REQUEST_TERMINATE:
07198 if (p->t38.state == T38_PEER_REINVITE) {
07199 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"));
07200 change_t38_state(p, T38_DISABLED);
07201 transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
07202 } else if (p->t38.state == T38_ENABLED)
07203 transmit_reinvite_with_sdp(p, FALSE, FALSE);
07204 break;
07205 case AST_T38_REQUEST_PARMS: {
07206 struct ast_control_t38_parameters parameters = p->t38.their_parms;
07207
07208 if (p->t38.state == T38_PEER_REINVITE) {
07209 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"));
07210 parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
07211 parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
07212 if (p->owner) {
07213 ast_queue_control_data(p->owner, AST_CONTROL_T38_PARAMETERS, ¶meters, sizeof(parameters));
07214 }
07215
07216
07217
07218
07219 res = AST_T38_REQUEST_PARMS;
07220 }
07221 break;
07222 }
07223 default:
07224 res = -1;
07225 break;
07226 }
07227
07228 return res;
07229 }
07230
07231
07232
07233
07234
07235
07236
07237
07238
07239
07240 static int initialize_udptl(struct sip_pvt *p)
07241 {
07242 int natflags = ast_test_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP);
07243
07244 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
07245 return 1;
07246 }
07247
07248
07249 if (p->udptl) {
07250 return 0;
07251 }
07252
07253
07254 if ((p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, &bindaddr))) {
07255 if (p->owner) {
07256 ast_channel_set_fd(p->owner, 5, ast_udptl_fd(p->udptl));
07257 }
07258
07259 ast_udptl_setqos(p->udptl, global_tos_audio, global_cos_audio);
07260 p->t38_maxdatagram = p->relatedpeer ? p->relatedpeer->t38_maxdatagram : global_t38_maxdatagram;
07261 set_t38_capabilities(p);
07262
07263 ast_debug(1, "Setting NAT on UDPTL to %s\n", natflags ? "On" : "Off");
07264 ast_udptl_setnat(p->udptl, natflags);
07265 } else {
07266 ast_log(AST_LOG_WARNING, "UDPTL creation failed - disabling T38 for this dialog\n");
07267 ast_clear_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT);
07268 return 1;
07269 }
07270
07271 return 0;
07272 }
07273
07274
07275
07276
07277
07278
07279 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
07280 {
07281 struct sip_pvt *p = ast->tech_pvt;
07282 int res = 0;
07283
07284 if (!p) {
07285 ast_debug(1, "Asked to indicate condition on channel %s with no pvt; ignoring\n",
07286 ast->name);
07287 return res;
07288 }
07289
07290 sip_pvt_lock(p);
07291 switch(condition) {
07292 case AST_CONTROL_RINGING:
07293 if (ast->_state == AST_STATE_RING) {
07294 p->invitestate = INV_EARLY_MEDIA;
07295 if (!ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) ||
07296 (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) {
07297
07298 transmit_provisional_response(p, "180 Ringing", &p->initreq, 0);
07299 ast_set_flag(&p->flags[0], SIP_RINGING);
07300 if (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) != SIP_PROG_INBAND_YES)
07301 break;
07302 } else {
07303
07304 }
07305 }
07306 res = -1;
07307 break;
07308 case AST_CONTROL_BUSY:
07309 if (ast->_state != AST_STATE_UP) {
07310 transmit_response_reliable(p, "486 Busy Here", &p->initreq);
07311 p->invitestate = INV_COMPLETED;
07312 sip_alreadygone(p);
07313 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
07314 break;
07315 }
07316 res = -1;
07317 break;
07318 case AST_CONTROL_CONGESTION:
07319 if (ast->_state != AST_STATE_UP) {
07320 transmit_response_reliable(p, "503 Service Unavailable", &p->initreq);
07321 p->invitestate = INV_COMPLETED;
07322 sip_alreadygone(p);
07323 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
07324 break;
07325 }
07326 res = -1;
07327 break;
07328 case AST_CONTROL_INCOMPLETE:
07329 if (ast->_state != AST_STATE_UP) {
07330 switch (ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP)) {
07331 case SIP_PAGE2_ALLOWOVERLAP_YES:
07332 transmit_response_reliable(p, "484 Address Incomplete", &p->initreq);
07333 p->invitestate = INV_COMPLETED;
07334 sip_alreadygone(p);
07335 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
07336 break;
07337 case SIP_PAGE2_ALLOWOVERLAP_DTMF:
07338
07339 break;
07340 default:
07341
07342 transmit_response_reliable(p, "404 Not Found", &p->initreq);
07343 p->invitestate = INV_COMPLETED;
07344 sip_alreadygone(p);
07345 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
07346 break;
07347 }
07348 }
07349 break;
07350 case AST_CONTROL_PROCEEDING:
07351 if ((ast->_state != AST_STATE_UP) &&
07352 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
07353 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
07354 transmit_response(p, "100 Trying", &p->initreq);
07355 p->invitestate = INV_PROCEEDING;
07356 break;
07357 }
07358 res = -1;
07359 break;
07360 case AST_CONTROL_PROGRESS:
07361 if ((ast->_state != AST_STATE_UP) &&
07362 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
07363 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
07364 p->invitestate = INV_EARLY_MEDIA;
07365 transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
07366 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
07367 break;
07368 }
07369 res = -1;
07370 break;
07371 case AST_CONTROL_HOLD:
07372 ast_rtp_instance_update_source(p->rtp);
07373 ast_moh_start(ast, data, p->mohinterpret);
07374 break;
07375 case AST_CONTROL_UNHOLD:
07376 ast_rtp_instance_update_source(p->rtp);
07377 ast_moh_stop(ast);
07378 break;
07379 case AST_CONTROL_VIDUPDATE:
07380 if (p->vrtp && !p->novideo) {
07381 transmit_info_with_vidupdate(p);
07382
07383 } else
07384 res = -1;
07385 break;
07386 case AST_CONTROL_T38_PARAMETERS:
07387 res = -1;
07388 if (datalen != sizeof(struct ast_control_t38_parameters)) {
07389 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);
07390 } else {
07391 const struct ast_control_t38_parameters *parameters = data;
07392 if (!initialize_udptl(p)) {
07393 res = interpret_t38_parameters(p, parameters);
07394 }
07395 }
07396 break;
07397 case AST_CONTROL_SRCUPDATE:
07398 ast_rtp_instance_update_source(p->rtp);
07399 break;
07400 case AST_CONTROL_SRCCHANGE:
07401 ast_rtp_instance_change_source(p->rtp);
07402 break;
07403 case AST_CONTROL_CONNECTED_LINE:
07404 update_connectedline(p, data, datalen);
07405 break;
07406 case AST_CONTROL_REDIRECTING:
07407 update_redirecting(p, data, datalen);
07408 break;
07409 case AST_CONTROL_AOC:
07410 {
07411 struct ast_aoc_decoded *decoded = ast_aoc_decode((struct ast_aoc_encoded *) data, datalen, ast);
07412 if (!decoded) {
07413 ast_log(LOG_ERROR, "Error decoding indicated AOC data\n");
07414 res = -1;
07415 break;
07416 }
07417 switch (ast_aoc_get_msg_type(decoded)) {
07418 case AST_AOC_REQUEST:
07419 if (ast_aoc_get_termination_request(decoded)) {
07420
07421
07422
07423
07424
07425
07426
07427 ast_debug(1, "AOC-E termination request received on %s. This is not yet supported on sip. Continue with hangup \n", p->owner->name);
07428 ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
07429 }
07430 break;
07431 case AST_AOC_D:
07432 case AST_AOC_E:
07433 if (ast_test_flag(&p->flags[2], SIP_PAGE3_SNOM_AOC)) {
07434 transmit_info_with_aoc(p, decoded);
07435 }
07436 break;
07437 case AST_AOC_S:
07438 default:
07439 break;
07440 }
07441 ast_aoc_destroy_decoded(decoded);
07442 }
07443 break;
07444 case AST_CONTROL_UPDATE_RTP_PEER:
07445 break;
07446 case AST_CONTROL_FLASH:
07447 res = -1;
07448 break;
07449 case -1:
07450 res = -1;
07451 break;
07452 default:
07453 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
07454 res = -1;
07455 break;
07456 }
07457 sip_pvt_unlock(p);
07458 return res;
07459 }
07460
07461
07462
07463
07464
07465
07466
07467
07468
07469
07470
07471
07472 static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title, const char *linkedid)
07473 {
07474 struct ast_channel *tmp;
07475 struct ast_variable *v = NULL;
07476 format_t fmt;
07477 format_t what;
07478 format_t video;
07479 format_t text;
07480 format_t needvideo = 0;
07481 int needtext = 0;
07482 char buf[SIPBUFSIZE];
07483 char *exten;
07484
07485 {
07486 const char *my_name;
07487
07488 if (title) {
07489 my_name = title;
07490 } else {
07491 my_name = ast_strdupa(i->fromdomain);
07492 }
07493
07494 sip_pvt_unlock(i);
07495
07496 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));
07497 }
07498 if (!tmp) {
07499 ast_log(LOG_WARNING, "Unable to allocate AST channel structure for SIP channel\n");
07500 sip_pvt_lock(i);
07501 return NULL;
07502 }
07503 ast_channel_lock(tmp);
07504 sip_pvt_lock(i);
07505 ast_channel_cc_params_init(tmp, i->cc_params);
07506 tmp->caller.id.tag = ast_strdup(i->cid_tag);
07507
07508 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;
07509
07510
07511
07512 if (i->jointcapability) {
07513 what = i->jointcapability;
07514 video = i->jointcapability & AST_FORMAT_VIDEO_MASK;
07515 text = i->jointcapability & AST_FORMAT_TEXT_MASK;
07516 } else if (i->capability) {
07517 what = i->capability;
07518 video = i->capability & AST_FORMAT_VIDEO_MASK;
07519 text = i->capability & AST_FORMAT_TEXT_MASK;
07520 } else {
07521 what = sip_cfg.capability;
07522 video = sip_cfg.capability & AST_FORMAT_VIDEO_MASK;
07523 text = sip_cfg.capability & AST_FORMAT_TEXT_MASK;
07524 }
07525
07526
07527 tmp->nativeformats = ast_codec_choose(&i->prefs, what, 1) | video | text;
07528 ast_debug(3, "*** Our native formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, tmp->nativeformats));
07529 ast_debug(3, "*** Joint capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->jointcapability));
07530 ast_debug(3, "*** Our capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->capability));
07531 ast_debug(3, "*** AST_CODEC_CHOOSE formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, ast_codec_choose(&i->prefs, what, 1)));
07532 if (i->prefcodec)
07533 ast_debug(3, "*** Our preferred formats from the incoming channel are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->prefcodec));
07534
07535
07536 fmt = ast_best_codec(tmp->nativeformats);
07537
07538
07539
07540
07541
07542 if (i->vrtp) {
07543 if (ast_test_flag(&i->flags[1], SIP_PAGE2_VIDEOSUPPORT))
07544 needvideo = AST_FORMAT_VIDEO_MASK;
07545 else if (i->prefcodec)
07546 needvideo = i->prefcodec & AST_FORMAT_VIDEO_MASK;
07547 else
07548 needvideo = i->jointcapability & AST_FORMAT_VIDEO_MASK;
07549 }
07550
07551 if (i->trtp) {
07552 if (i->prefcodec)
07553 needtext = i->prefcodec & AST_FORMAT_TEXT_MASK;
07554 else
07555 needtext = i->jointcapability & AST_FORMAT_TEXT_MASK;
07556 }
07557
07558 if (needvideo)
07559 ast_debug(3, "This channel can handle video! HOLLYWOOD next!\n");
07560 else
07561 ast_debug(3, "This channel will not be able to handle video.\n");
07562
07563 enable_dsp_detect(i);
07564
07565 if ((ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
07566 (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
07567 if (i->rtp) {
07568 ast_rtp_instance_dtmf_mode_set(i->rtp, AST_RTP_DTMF_MODE_INBAND);
07569 }
07570 } else if (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) {
07571 if (i->rtp) {
07572 ast_rtp_instance_dtmf_mode_set(i->rtp, AST_RTP_DTMF_MODE_RFC2833);
07573 }
07574 }
07575
07576
07577
07578
07579 if (i->rtp) {
07580 ast_channel_set_fd(tmp, 0, ast_rtp_instance_fd(i->rtp, 0));
07581 ast_channel_set_fd(tmp, 1, ast_rtp_instance_fd(i->rtp, 1));
07582 ast_rtp_instance_set_write_format(i->rtp, fmt);
07583 ast_rtp_instance_set_read_format(i->rtp, fmt);
07584 }
07585 if (needvideo && i->vrtp) {
07586 ast_channel_set_fd(tmp, 2, ast_rtp_instance_fd(i->vrtp, 0));
07587 ast_channel_set_fd(tmp, 3, ast_rtp_instance_fd(i->vrtp, 1));
07588 }
07589 if (needtext && i->trtp) {
07590 ast_channel_set_fd(tmp, 4, ast_rtp_instance_fd(i->trtp, 0));
07591 }
07592 if (i->udptl) {
07593 ast_channel_set_fd(tmp, 5, ast_udptl_fd(i->udptl));
07594 }
07595
07596 if (state == AST_STATE_RING)
07597 tmp->rings = 1;
07598 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
07599
07600 tmp->writeformat = fmt;
07601 tmp->rawwriteformat = fmt;
07602
07603 tmp->readformat = fmt;
07604 tmp->rawreadformat = fmt;
07605
07606 tmp->tech_pvt = dialog_ref(i, "sip_new: set chan->tech_pvt to i");
07607
07608 tmp->callgroup = i->callgroup;
07609 tmp->pickupgroup = i->pickupgroup;
07610 tmp->caller.id.name.presentation = i->callingpres;
07611 tmp->caller.id.number.presentation = i->callingpres;
07612 if (!ast_strlen_zero(i->parkinglot))
07613 ast_string_field_set(tmp, parkinglot, i->parkinglot);
07614 if (!ast_strlen_zero(i->accountcode))
07615 ast_string_field_set(tmp, accountcode, i->accountcode);
07616 if (i->amaflags)
07617 tmp->amaflags = i->amaflags;
07618 if (!ast_strlen_zero(i->language))
07619 ast_string_field_set(tmp, language, i->language);
07620 i->owner = tmp;
07621 ast_module_ref(ast_module_info->self);
07622 ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
07623
07624
07625
07626
07627 exten = ast_strdupa(i->exten);
07628 sip_pvt_unlock(i);
07629 ast_channel_unlock(tmp);
07630 if (!ast_exists_extension(NULL, i->context, i->exten, 1, i->cid_num)) {
07631 ast_uri_decode(exten);
07632 }
07633 ast_channel_lock(tmp);
07634 sip_pvt_lock(i);
07635 ast_copy_string(tmp->exten, exten, sizeof(tmp->exten));
07636
07637
07638
07639 if (!ast_strlen_zero(i->cid_num)) {
07640 tmp->caller.ani.number.valid = 1;
07641 tmp->caller.ani.number.str = ast_strdup(i->cid_num);
07642 }
07643 if (!ast_strlen_zero(i->rdnis)) {
07644 tmp->redirecting.from.number.valid = 1;
07645 tmp->redirecting.from.number.str = ast_strdup(i->rdnis);
07646 }
07647
07648 if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s")) {
07649 tmp->dialed.number.str = ast_strdup(i->exten);
07650 }
07651
07652 tmp->priority = 1;
07653 if (!ast_strlen_zero(i->uri))
07654 pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
07655 if (!ast_strlen_zero(i->domain))
07656 pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
07657 if (!ast_strlen_zero(i->callid))
07658 pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
07659 if (i->rtp)
07660 ast_jb_configure(tmp, &global_jbconf);
07661
07662 if (!i->relatedpeer) {
07663 tmp->flags |= AST_FLAG_DISABLE_DEVSTATE_CACHE;
07664 }
07665
07666 for (v = i->chanvars ; v ; v = v->next) {
07667 char valuebuf[1024];
07668 pbx_builtin_setvar_helper(tmp, v->name, ast_get_encoded_str(v->value, valuebuf, sizeof(valuebuf)));
07669 }
07670
07671 if (i->do_history)
07672 append_history(i, "NewChan", "Channel %s - from %s", tmp->name, i->callid);
07673
07674
07675 if (sip_cfg.callevents)
07676 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
07677 "Channel: %s\r\nUniqueid: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\n",
07678 tmp->name, tmp->uniqueid, "SIP", i->callid, i->fullcontact);
07679
07680 return tmp;
07681 }
07682
07683
07684 static char *get_body_by_line(const char *line, const char *name, int nameLen, char delimiter)
07685 {
07686 if (!strncasecmp(line, name, nameLen) && line[nameLen] == delimiter)
07687 return ast_skip_blanks(line + nameLen + 1);
07688
07689 return "";
07690 }
07691
07692
07693
07694
07695
07696 static const char *get_sdp_iterate(int *start, struct sip_request *req, const char *name)
07697 {
07698 int len = strlen(name);
07699
07700 while (*start < (req->sdp_start + req->sdp_count)) {
07701 const char *r = get_body_by_line(REQ_OFFSET_TO_STR(req, line[(*start)++]), name, len, '=');
07702 if (r[0] != '\0')
07703 return r;
07704 }
07705
07706
07707 (*start)++;
07708
07709 return "";
07710 }
07711
07712
07713
07714
07715
07716
07717 static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value)
07718 {
07719 char type = '\0';
07720 const char *line = NULL;
07721
07722 if (stop > (req->sdp_start + req->sdp_count)) {
07723 stop = req->sdp_start + req->sdp_count;
07724 }
07725
07726 while (*start < stop) {
07727 line = REQ_OFFSET_TO_STR(req, line[(*start)++]);
07728 if (line[1] == '=') {
07729 type = line[0];
07730 *value = ast_skip_blanks(line + 2);
07731 break;
07732 }
07733 }
07734
07735 return type;
07736 }
07737
07738
07739 static char *get_body(struct sip_request *req, char *name, char delimiter)
07740 {
07741 int x;
07742 int len = strlen(name);
07743 char *r;
07744
07745 for (x = 0; x < req->lines; x++) {
07746 r = get_body_by_line(REQ_OFFSET_TO_STR(req, line[x]), name, len, delimiter);
07747 if (r[0] != '\0')
07748 return r;
07749 }
07750
07751 return "";
07752 }
07753
07754
07755 static const char *find_alias(const char *name, const char *_default)
07756 {
07757
07758 static const struct cfalias {
07759 char * const fullname;
07760 char * const shortname;
07761 } aliases[] = {
07762 { "Content-Type", "c" },
07763 { "Content-Encoding", "e" },
07764 { "From", "f" },
07765 { "Call-ID", "i" },
07766 { "Contact", "m" },
07767 { "Content-Length", "l" },
07768 { "Subject", "s" },
07769 { "To", "t" },
07770 { "Supported", "k" },
07771 { "Refer-To", "r" },
07772 { "Referred-By", "b" },
07773 { "Allow-Events", "u" },
07774 { "Event", "o" },
07775 { "Via", "v" },
07776 { "Accept-Contact", "a" },
07777 { "Reject-Contact", "j" },
07778 { "Request-Disposition", "d" },
07779 { "Session-Expires", "x" },
07780 { "Identity", "y" },
07781 { "Identity-Info", "n" },
07782 };
07783 int x;
07784
07785 for (x = 0; x < ARRAY_LEN(aliases); x++) {
07786 if (!strcasecmp(aliases[x].fullname, name))
07787 return aliases[x].shortname;
07788 }
07789
07790 return _default;
07791 }
07792
07793 static const char *__get_header(const struct sip_request *req, const char *name, int *start)
07794 {
07795
07796
07797
07798
07799
07800
07801
07802
07803
07804 const char *sname = find_alias(name, NULL);
07805 int x, len = strlen(name), slen = (sname ? 1 : 0);
07806 for (x = *start; x < req->headers; x++) {
07807 const char *header = REQ_OFFSET_TO_STR(req, header[x]);
07808 int smatch = 0, match = !strncasecmp(header, name, len);
07809 if (slen) {
07810 smatch = !strncasecmp(header, sname, slen);
07811 }
07812 if (match || smatch) {
07813
07814 const char *r = header + (match ? len : slen );
07815 if (sip_cfg.pedanticsipchecking) {
07816 r = ast_skip_blanks(r);
07817 }
07818
07819 if (*r == ':') {
07820 *start = x+1;
07821 return ast_skip_blanks(r+1);
07822 }
07823 }
07824 }
07825
07826
07827 return "";
07828 }
07829
07830
07831
07832
07833 static const char *get_header(const struct sip_request *req, const char *name)
07834 {
07835 int start = 0;
07836 return __get_header(req, name, &start);
07837 }
07838
07839
07840 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect)
07841 {
07842
07843 struct ast_frame *f;
07844
07845 if (!p->rtp) {
07846
07847 return &ast_null_frame;
07848 }
07849
07850 switch(ast->fdno) {
07851 case 0:
07852 f = ast_rtp_instance_read(p->rtp, 0);
07853 break;
07854 case 1:
07855 f = ast_rtp_instance_read(p->rtp, 1);
07856 break;
07857 case 2:
07858 f = ast_rtp_instance_read(p->vrtp, 0);
07859 break;
07860 case 3:
07861 f = ast_rtp_instance_read(p->vrtp, 1);
07862 break;
07863 case 4:
07864 f = ast_rtp_instance_read(p->trtp, 0);
07865 if (sipdebug_text) {
07866 int i;
07867 unsigned char* arr = f->data.ptr;
07868 for (i=0; i < f->datalen; i++)
07869 ast_verbose("%c", (arr[i] > ' ' && arr[i] < '}') ? arr[i] : '.');
07870 ast_verbose(" -> ");
07871 for (i=0; i < f->datalen; i++)
07872 ast_verbose("%02X ", arr[i]);
07873 ast_verbose("\n");
07874 }
07875 break;
07876 case 5:
07877 f = ast_udptl_read(p->udptl);
07878 break;
07879 default:
07880 f = &ast_null_frame;
07881 }
07882
07883 if (f && (f->frametype == AST_FRAME_DTMF_BEGIN || f->frametype == AST_FRAME_DTMF_END) &&
07884 (ast_test_flag(&p->flags[0], SIP_DTMF) != SIP_DTMF_RFC2833)) {
07885 ast_debug(1, "Ignoring DTMF (%c) RTP frame because dtmfmode is not RFC2833\n", f->subclass.integer);
07886 ast_frfree(f);
07887 return &ast_null_frame;
07888 }
07889
07890
07891 if (!p->owner || (f && f->frametype != AST_FRAME_VOICE))
07892 return f;
07893
07894 if (f && f->subclass.codec != (p->owner->nativeformats & AST_FORMAT_AUDIO_MASK)) {
07895 if (!(f->subclass.codec & p->jointcapability)) {
07896 ast_debug(1, "Bogus frame of format '%s' received from '%s'!\n",
07897 ast_getformatname(f->subclass.codec), p->owner->name);
07898 ast_frfree(f);
07899 return &ast_null_frame;
07900 }
07901 ast_debug(1, "Oooh, format changed to %s\n",
07902 ast_getformatname(f->subclass.codec));
07903 p->owner->nativeformats = (p->owner->nativeformats & (AST_FORMAT_VIDEO_MASK | AST_FORMAT_TEXT_MASK)) | f->subclass.codec;
07904 ast_set_read_format(p->owner, p->owner->readformat);
07905 ast_set_write_format(p->owner, p->owner->writeformat);
07906 }
07907
07908 if (f && p->dsp) {
07909 f = ast_dsp_process(p->owner, p->dsp, f);
07910 if (f && f->frametype == AST_FRAME_DTMF) {
07911 if (f->subclass.integer == 'f') {
07912 ast_debug(1, "Fax CNG detected on %s\n", ast->name);
07913 *faxdetect = 1;
07914
07915 if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
07916 ast_dsp_set_features(p->dsp, DSP_FEATURE_DIGIT_DETECT);
07917 } else {
07918 ast_dsp_free(p->dsp);
07919 p->dsp = NULL;
07920 }
07921 } else {
07922 ast_debug(1, "* Detected inband DTMF '%c'\n", f->subclass.integer);
07923 }
07924 }
07925 }
07926
07927 return f;
07928 }
07929
07930
07931 static struct ast_frame *sip_read(struct ast_channel *ast)
07932 {
07933 struct ast_frame *fr;
07934 struct sip_pvt *p = ast->tech_pvt;
07935 int faxdetected = FALSE;
07936
07937 sip_pvt_lock(p);
07938 fr = sip_rtp_read(ast, p, &faxdetected);
07939 p->lastrtprx = time(NULL);
07940
07941
07942 if (faxdetected && ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_CNG)) {
07943 if (strcmp(ast->exten, "fax")) {
07944 const char *target_context = S_OR(ast->macrocontext, ast->context);
07945
07946
07947
07948
07949
07950 sip_pvt_unlock(p);
07951 ast_channel_unlock(ast);
07952 if (ast_exists_extension(ast, target_context, "fax", 1,
07953 S_COR(ast->caller.id.number.valid, ast->caller.id.number.str, NULL))) {
07954 ast_channel_lock(ast);
07955 sip_pvt_lock(p);
07956 ast_verbose(VERBOSE_PREFIX_2 "Redirecting '%s' to fax extension due to CNG detection\n", ast->name);
07957 pbx_builtin_setvar_helper(ast, "FAXEXTEN", ast->exten);
07958 if (ast_async_goto(ast, target_context, "fax", 1)) {
07959 ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", ast->name, target_context);
07960 }
07961 ast_frfree(fr);
07962 fr = &ast_null_frame;
07963 } else {
07964 ast_channel_lock(ast);
07965 sip_pvt_lock(p);
07966 ast_log(LOG_NOTICE, "FAX CNG detected but no fax extension\n");
07967 }
07968 }
07969 }
07970
07971
07972 if (fr && fr->frametype == AST_FRAME_VOICE && p->invitestate != INV_EARLY_MEDIA && ast->_state != AST_STATE_UP) {
07973 ast_frfree(fr);
07974 fr = &ast_null_frame;
07975 }
07976
07977 sip_pvt_unlock(p);
07978
07979 return fr;
07980 }
07981
07982
07983
07984 static char *generate_random_string(char *buf, size_t size)
07985 {
07986 long val[4];
07987 int x;
07988
07989 for (x=0; x<4; x++)
07990 val[x] = ast_random();
07991 snprintf(buf, size, "%08lx%08lx%08lx%08lx", val[0], val[1], val[2], val[3]);
07992
07993 return buf;
07994 }
07995
07996 static char *generate_uri(struct sip_pvt *pvt, char *buf, size_t size)
07997 {
07998 struct ast_str *uri = ast_str_alloca(size);
07999 ast_str_set(&uri, 0, "%s", pvt->socket.type == SIP_TRANSPORT_TLS ? "sips:" : "sip:");
08000
08001
08002
08003 ast_str_append(&uri, 0, "%s", generate_random_string(buf, size));
08004 ast_str_append(&uri, 0, "@%s", ast_sockaddr_stringify_remote(&pvt->ourip));
08005 ast_copy_string(buf, ast_str_buffer(uri), size);
08006 return buf;
08007 }
08008
08009
08010
08011
08012
08013
08014
08015
08016 static void build_callid_pvt(struct sip_pvt *pvt)
08017 {
08018 char buf[33];
08019 const char *host = S_OR(pvt->fromdomain, ast_sockaddr_stringify_remote(&pvt->ourip));
08020
08021 ast_string_field_build(pvt, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
08022 }
08023
08024
08025 #define CONTAINER_UNLINK(container, obj, tag) \
08026 ({ \
08027 int found = 0; \
08028 typeof((obj)) __removed_obj; \
08029 __removed_obj = ao2_t_callback((container), \
08030 OBJ_UNLINK | OBJ_POINTER, ao2_match_by_addr, (obj), (tag)); \
08031 if (__removed_obj) { \
08032 ao2_ref(__removed_obj, -1); \
08033 found = 1; \
08034 } \
08035 found; \
08036 })
08037
08038
08039
08040
08041
08042
08043
08044
08045
08046
08047 static void change_callid_pvt(struct sip_pvt *pvt, const char *callid)
08048 {
08049 int in_dialog_container;
08050 char *oldid = ast_strdupa(pvt->callid);
08051
08052 ao2_lock(dialogs);
08053 in_dialog_container = CONTAINER_UNLINK(dialogs, pvt,
08054 "About to change the callid -- remove the old name");
08055 if (callid) {
08056 ast_string_field_set(pvt, callid, callid);
08057 } else {
08058 build_callid_pvt(pvt);
08059 }
08060 if (in_dialog_container) {
08061 ao2_t_link(dialogs, pvt, "New dialog callid -- inserted back into table");
08062 }
08063 ao2_unlock(dialogs);
08064
08065 if (strcmp(oldid, pvt->callid)) {
08066 ast_debug(1, "SIP call-id changed from '%s' to '%s'\n", oldid, pvt->callid);
08067 }
08068 }
08069
08070
08071 static void build_callid_registry(struct sip_registry *reg, const struct ast_sockaddr *ourip, const char *fromdomain)
08072 {
08073 char buf[33];
08074
08075 const char *host = S_OR(fromdomain, ast_sockaddr_stringify_host_remote(ourip));
08076
08077 ast_string_field_build(reg, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
08078 }
08079
08080
08081 static void build_localtag_registry(struct sip_registry *reg)
08082 {
08083 ast_string_field_build(reg, localtag, "as%08lx", ast_random());
08084 }
08085
08086
08087 static void make_our_tag(struct sip_pvt *pvt)
08088 {
08089 ast_string_field_build(pvt, tag, "as%08lx", ast_random());
08090 }
08091
08092
08093 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p)
08094 {
08095 struct sip_st_dlg *stp;
08096
08097 if (p->stimer) {
08098 ast_log(LOG_ERROR, "Session-Timer struct already allocated\n");
08099 return p->stimer;
08100 }
08101
08102 if (!(stp = ast_calloc(1, sizeof(struct sip_st_dlg))))
08103 return NULL;
08104
08105 p->stimer = stp;
08106
08107 stp->st_schedid = -1;
08108
08109 return p->stimer;
08110 }
08111
08112
08113
08114
08115
08116 struct sip_pvt *sip_alloc(ast_string_field callid, struct ast_sockaddr *addr,
08117 int useglobal_nat, const int intended_method, struct sip_request *req)
08118 {
08119 struct sip_pvt *p;
08120
08121 if (!(p = ao2_t_alloc(sizeof(*p), sip_destroy_fn, "allocate a dialog(pvt) struct")))
08122 return NULL;
08123
08124 if (ast_string_field_init(p, 512)) {
08125 ao2_t_ref(p, -1, "failed to string_field_init, drop p");
08126 return NULL;
08127 }
08128
08129 if (!(p->cc_params = ast_cc_config_params_init())) {
08130 ao2_t_ref(p, -1, "Yuck, couldn't allocate cc_params struct. Get rid o' p");
08131 return NULL;
08132 }
08133
08134
08135
08136 if (req) {
08137 struct sip_via *via;
08138 const char *cseq = get_header(req, "Cseq");
08139 uint32_t seqno;
08140
08141
08142 via = parse_via(get_header(req, "Via"));
08143 if (via) {
08144
08145
08146 if (!ast_strlen_zero(via->branch) && !strncasecmp(via->branch, "z9hG4bK", 7)) {
08147 ast_string_field_set(p, initviabranch, via->branch);
08148 ast_string_field_set(p, initviasentby, via->sent_by);
08149 }
08150 free_via(via);
08151 }
08152
08153
08154
08155 if (!ast_strlen_zero(cseq) && (sscanf(cseq, "%30u", &seqno) == 1)) {
08156 p->init_icseq = seqno;
08157 }
08158
08159 set_socket_transport(&p->socket, req->socket.type);
08160 } else {
08161 set_socket_transport(&p->socket, SIP_TRANSPORT_UDP);
08162 }
08163
08164 p->socket.fd = -1;
08165 p->method = intended_method;
08166 p->initid = -1;
08167 p->waitid = -1;
08168 p->reinviteid = -1;
08169 p->autokillid = -1;
08170 p->request_queue_sched_id = -1;
08171 p->provisional_keepalive_sched_id = -1;
08172 p->t38id = -1;
08173 p->subscribed = NONE;
08174 p->stateid = -1;
08175 p->sessionversion_remote = -1;
08176 p->session_modify = TRUE;
08177 p->stimer = NULL;
08178 p->prefs = default_prefs;
08179 p->maxforwards = sip_cfg.default_max_forwards;
08180
08181 if (intended_method != SIP_OPTIONS) {
08182 p->timer_t1 = global_t1;
08183 p->timer_b = global_timer_b;
08184 }
08185
08186 if (!addr) {
08187 p->ourip = internip;
08188 } else {
08189 ast_sockaddr_copy(&p->sa, addr);
08190 ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
08191 }
08192
08193
08194 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
08195 ast_copy_flags(&p->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
08196 ast_copy_flags(&p->flags[2], &global_flags[2], SIP_PAGE3_FLAGS_TO_COPY);
08197
08198 p->do_history = recordhistory;
08199
08200 p->branch = ast_random();
08201 make_our_tag(p);
08202 p->ocseq = INITIAL_CSEQ;
08203 p->allowed_methods = UINT_MAX;
08204
08205 if (sip_methods[intended_method].need_rtp) {
08206 p->maxcallbitrate = default_maxcallbitrate;
08207 p->autoframing = global_autoframing;
08208 }
08209
08210 if (useglobal_nat && addr) {
08211
08212 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT_FORCE_RPORT);
08213 ast_sockaddr_copy(&p->recv, addr);
08214
08215 do_setnat(p);
08216 }
08217
08218 if (p->method != SIP_REGISTER) {
08219 ast_string_field_set(p, fromdomain, default_fromdomain);
08220 p->fromdomainport = default_fromdomainport;
08221 }
08222 build_via(p);
08223 if (!callid)
08224 build_callid_pvt(p);
08225 else
08226 ast_string_field_set(p, callid, callid);
08227
08228 ast_string_field_set(p, mohinterpret, default_mohinterpret);
08229 ast_string_field_set(p, mohsuggest, default_mohsuggest);
08230 p->capability = sip_cfg.capability;
08231 p->allowtransfer = sip_cfg.allowtransfer;
08232 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
08233 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
08234 p->noncodeccapability |= AST_RTP_DTMF;
08235 }
08236 ast_string_field_set(p, context, sip_cfg.default_context);
08237 ast_string_field_set(p, parkinglot, default_parkinglot);
08238 ast_string_field_set(p, engine, default_engine);
08239
08240 AST_LIST_HEAD_INIT_NOLOCK(&p->request_queue);
08241
08242
08243
08244 ao2_t_link(dialogs, p, "link pvt into dialogs table");
08245
08246 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");
08247 return p;
08248 }
08249
08250
08251
08252
08253
08254
08255
08256
08257 static int addr_is_multicast(const struct ast_sockaddr *addr)
08258 {
08259 return ((ast_sockaddr_ipv4(addr) & 0xf0000000) == 0xe0000000);
08260 }
08261
08262
08263
08264
08265
08266
08267
08268
08269
08270
08271
08272
08273
08274
08275
08276
08277 static int process_via(struct sip_pvt *p, const struct sip_request *req)
08278 {
08279 struct sip_via *via = parse_via(get_header(req, "Via"));
08280
08281 if (!via) {
08282 ast_log(LOG_ERROR, "error processing via header\n");
08283 return -1;
08284 }
08285
08286 if (via->maddr) {
08287 if (ast_sockaddr_resolve_first_transport(&p->sa, via->maddr, PARSE_PORT_FORBID, p->socket.type)) {
08288 ast_log(LOG_WARNING, "Can't find address for maddr '%s'\n", via->maddr);
08289 ast_log(LOG_ERROR, "error processing via header\n");
08290 free_via(via);
08291 return -1;
08292 }
08293
08294 if (addr_is_multicast(&p->sa)) {
08295 setsockopt(sipsock, IPPROTO_IP, IP_MULTICAST_TTL, &via->ttl, sizeof(via->ttl));
08296 }
08297 }
08298
08299 ast_sockaddr_set_port(&p->sa, via->port ? via->port : STANDARD_SIP_PORT);
08300
08301 free_via(via);
08302 return 0;
08303 }
08304
08305
08306 struct match_req_args {
08307 int method;
08308 const char *callid;
08309 const char *totag;
08310 const char *fromtag;
08311 uint32_t seqno;
08312
08313
08314 const char *ruri;
08315 const char *viabranch;
08316 const char *viasentby;
08317
08318
08319 int authentication_present;
08320 };
08321
08322 enum match_req_res {
08323 SIP_REQ_MATCH,
08324 SIP_REQ_NOT_MATCH,
08325 SIP_REQ_LOOP_DETECTED,
08326 };
08327
08328
08329
08330
08331
08332
08333 static enum match_req_res match_req_to_dialog(struct sip_pvt *sip_pvt_ptr, struct match_req_args *arg)
08334 {
08335 const char *init_ruri = NULL;
08336 if (sip_pvt_ptr->initreq.headers) {
08337 init_ruri = REQ_OFFSET_TO_STR(&sip_pvt_ptr->initreq, rlPart2);
08338 }
08339
08340
08341
08342
08343 if (!ast_strlen_zero(arg->callid) && strcmp(sip_pvt_ptr->callid, arg->callid)) {
08344
08345 return SIP_REQ_NOT_MATCH;
08346 }
08347 if (arg->method == SIP_RESPONSE) {
08348
08349
08350 if (!ast_strlen_zero(sip_pvt_ptr->theirtag) && ast_test_flag(&sip_pvt_ptr->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
08351 if (ast_strlen_zero(arg->totag)) {
08352
08353 return SIP_REQ_NOT_MATCH;
08354 }
08355 if (strcmp(arg->totag, sip_pvt_ptr->theirtag)) {
08356
08357 return SIP_REQ_NOT_MATCH;
08358 }
08359 }
08360
08361 if (strcmp(arg->fromtag, sip_pvt_ptr->tag)) {
08362
08363 return SIP_REQ_NOT_MATCH;
08364 }
08365 } else {
08366
08367
08368
08369 if (!arg->authentication_present && strcmp(arg->fromtag, sip_pvt_ptr->theirtag)) {
08370
08371 return SIP_REQ_NOT_MATCH;
08372 }
08373
08374 if (!ast_strlen_zero(arg->totag) && (strcmp(arg->totag, sip_pvt_ptr->tag))) {
08375
08376 return SIP_REQ_NOT_MATCH;
08377 }
08378 }
08379
08380
08381
08382
08383
08384
08385
08386
08387
08388
08389
08390
08391
08392
08393
08394
08395
08396 if ((arg->method != SIP_RESPONSE) &&
08397 ast_strlen_zero(arg->totag) &&
08398 (sip_pvt_ptr->init_icseq == arg->seqno) &&
08399 !ast_strlen_zero(sip_pvt_ptr->initviabranch) &&
08400 init_ruri) {
08401
08402
08403 if (ast_strlen_zero(arg->viabranch) ||
08404 strcmp(arg->viabranch, sip_pvt_ptr->initviabranch) ||
08405 ast_strlen_zero(arg->viasentby) ||
08406 strcmp(arg->viasentby, sip_pvt_ptr->initviasentby)) {
08407
08408
08409
08410 if ((sip_pvt_ptr->method != arg->method)) {
08411 return SIP_REQ_NOT_MATCH;
08412 }
08413
08414
08415
08416 if (sip_uri_cmp(init_ruri, arg->ruri)) {
08417
08418 return SIP_REQ_NOT_MATCH;
08419 }
08420
08421
08422
08423
08424
08425
08426
08427
08428
08429
08430
08431
08432
08433
08434
08435
08436
08437
08438
08439 return SIP_REQ_LOOP_DETECTED;
08440 }
08441 }
08442
08443
08444
08445
08446
08447
08448 if ((arg->method != SIP_RESPONSE) &&
08449 ast_strlen_zero(arg->totag) &&
08450 arg->authentication_present &&
08451 sip_uri_cmp(init_ruri, arg->ruri)) {
08452
08453
08454 return SIP_REQ_NOT_MATCH;
08455 }
08456
08457 return SIP_REQ_MATCH;
08458 }
08459
08460
08461
08462
08463
08464
08465
08466
08467
08468
08469
08470
08471
08472
08473
08474
08475
08476
08477 static struct ast_channel *sip_pvt_lock_full(struct sip_pvt *pvt)
08478 {
08479 struct ast_channel *chan;
08480
08481
08482
08483
08484 for (;;) {
08485
08486 sip_pvt_lock(pvt);
08487 chan = pvt->owner;
08488 if (chan) {
08489
08490
08491
08492 ast_channel_ref(chan);
08493 } else {
08494
08495 return NULL;
08496 }
08497
08498
08499
08500
08501 sip_pvt_unlock(pvt);
08502
08503
08504 ast_channel_lock(chan);
08505 sip_pvt_lock(pvt);
08506
08507 if (pvt->owner == chan) {
08508
08509 break;
08510 }
08511
08512
08513
08514
08515
08516
08517 ast_channel_unlock(chan);
08518 ast_channel_unref(chan);
08519 sip_pvt_unlock(pvt);
08520 }
08521
08522
08523 return pvt->owner;
08524 }
08525
08526
08527
08528
08529
08530
08531 static struct sip_pvt *find_call(struct sip_request *req, struct ast_sockaddr *addr, const int intended_method)
08532 {
08533 char totag[128];
08534 char fromtag[128];
08535 const char *callid = get_header(req, "Call-ID");
08536 const char *from = get_header(req, "From");
08537 const char *to = get_header(req, "To");
08538 const char *cseq = get_header(req, "Cseq");
08539 struct sip_pvt *sip_pvt_ptr;
08540 uint32_t seqno;
08541
08542
08543 if (ast_strlen_zero(callid) || ast_strlen_zero(to) ||
08544 ast_strlen_zero(from) || ast_strlen_zero(cseq) ||
08545 (sscanf(cseq, "%30u", &seqno) != 1)) {
08546
08547
08548 if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
08549 transmit_response_using_temp(callid, addr, 1, intended_method,
08550 req, "400 Bad Request");
08551 }
08552 return NULL;
08553 }
08554
08555 if (sip_cfg.pedanticsipchecking) {
08556
08557
08558
08559
08560
08561
08562 if (gettag(req, "To", totag, sizeof(totag)))
08563 req->has_to_tag = 1;
08564 gettag(req, "From", fromtag, sizeof(fromtag));
08565
08566 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);
08567
08568
08569 if (ast_strlen_zero(fromtag)) {
08570 ast_debug(5, "%s request has no from tag, dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
08571 return NULL;
08572 }
08573
08574 if (ast_strlen_zero(totag) && (req->method == SIP_ACK || req->method == SIP_BYE || req->method == SIP_INFO )) {
08575 ast_debug(5, "%s must have a to tag. dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
08576 return NULL;
08577 }
08578 }
08579
08580 if (!sip_cfg.pedanticsipchecking) {
08581 struct sip_pvt tmp_dialog = {
08582 .callid = callid,
08583 };
08584 sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find in dialogs");
08585 if (sip_pvt_ptr) {
08586
08587 return sip_pvt_ptr;
08588 }
08589 } else {
08590 struct sip_pvt tmp_dialog = {
08591 .callid = callid,
08592 };
08593 struct match_req_args args = { 0, };
08594 int found;
08595 struct ao2_iterator *iterator = ao2_t_callback(dialogs,
08596 OBJ_POINTER | OBJ_MULTIPLE,
08597 dialog_find_multiple,
08598 &tmp_dialog,
08599 "pedantic ao2_find in dialogs");
08600 struct sip_via *via = NULL;
08601
08602 args.method = req->method;
08603 args.callid = NULL;
08604 args.totag = totag;
08605 args.fromtag = fromtag;
08606 args.seqno = seqno;
08607
08608
08609 if (req->method != SIP_RESPONSE) {
08610 args.ruri = REQ_OFFSET_TO_STR(req, rlPart2);
08611 via = parse_via(get_header(req, "Via"));
08612 if (via) {
08613 args.viasentby = via->sent_by;
08614 args.viabranch = via->branch;
08615 }
08616 if (!ast_strlen_zero(get_header(req, "Authorization")) ||
08617 !ast_strlen_zero(get_header(req, "Proxy-Authorization"))) {
08618 args.authentication_present = 1;
08619 }
08620 }
08621
08622
08623 while (iterator && (sip_pvt_ptr = ao2_iterator_next(iterator))) {
08624 sip_pvt_lock(sip_pvt_ptr);
08625 found = match_req_to_dialog(sip_pvt_ptr, &args);
08626 sip_pvt_unlock(sip_pvt_ptr);
08627
08628 switch (found) {
08629 case SIP_REQ_MATCH:
08630 ao2_iterator_destroy(iterator);
08631 free_via(via);
08632 return sip_pvt_ptr;
08633 case SIP_REQ_LOOP_DETECTED:
08634
08635
08636 transmit_response_using_temp(callid, addr, 1, intended_method, req, "482 (Loop Detected)");
08637 dialog_unref(sip_pvt_ptr, "pvt did not match incoming SIP msg, unref from search.");
08638 ao2_iterator_destroy(iterator);
08639 free_via(via);
08640 return NULL;
08641 case SIP_REQ_NOT_MATCH:
08642 default:
08643 dialog_unref(sip_pvt_ptr, "pvt did not match incoming SIP msg, unref from search");
08644 break;
08645 }
08646 }
08647 if (iterator) {
08648 ao2_iterator_destroy(iterator);
08649 }
08650
08651 free_via(via);
08652 }
08653
08654
08655 if (sip_methods[intended_method].can_create == CAN_CREATE_DIALOG) {
08656 struct sip_pvt *p = NULL;
08657
08658 if (intended_method == SIP_REFER) {
08659
08660 transmit_response_using_temp(callid, addr, 1, intended_method, req, "603 Declined (no dialog)");
08661
08662
08663 } else if (!(p = sip_alloc(callid, addr, 1, intended_method, req))) {
08664
08665
08666
08667
08668
08669
08670
08671
08672 transmit_response_using_temp(callid, addr, 1, intended_method, req, "500 Server internal error");
08673 ast_debug(4, "Failed allocating SIP dialog, sending 500 Server internal error and giving up\n");
08674 }
08675 return p;
08676 } else if( sip_methods[intended_method].can_create == CAN_CREATE_DIALOG_UNSUPPORTED_METHOD) {
08677
08678 transmit_response_using_temp(callid, addr, 1, intended_method, req, "501 Method Not Implemented");
08679 ast_debug(2, "Got a request with unsupported SIP method.\n");
08680 } else if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
08681
08682 transmit_response_using_temp(callid, addr, 1, intended_method, req, "481 Call leg/transaction does not exist");
08683 ast_debug(2, "That's odd... Got a request in unknown dialog. Callid %s\n", callid ? callid : "<unknown>");
08684 }
08685
08686
08687 if (intended_method == SIP_RESPONSE)
08688 ast_debug(2, "That's odd... Got a response on a call we don't know about. Callid %s\n", callid ? callid : "<unknown>");
08689
08690 return NULL;
08691 }
08692
08693
08694 static int sip_register(const char *value, int lineno)
08695 {
08696 struct sip_registry *reg;
08697
08698 if (!(reg = ast_calloc_with_stringfields(1, struct sip_registry, 256))) {
08699 ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry entry\n");
08700 return -1;
08701 }
08702
08703 ast_atomic_fetchadd_int(®objs, 1);
08704 ASTOBJ_INIT(reg);
08705
08706 if (sip_parse_register_line(reg, default_expiry, value, lineno)) {
08707 registry_unref(reg, "failure to parse, unref the reg pointer");
08708 return -1;
08709 }
08710
08711
08712 if (reg->refresh && !reg->expiry && !reg->configured_expiry) {
08713 reg->refresh = reg->expiry = reg->configured_expiry = default_expiry;
08714 }
08715
08716
08717 ASTOBJ_CONTAINER_LINK(®l, reg);
08718
08719
08720 registry_unref(reg, "unref the reg pointer");
08721
08722 return 0;
08723 }
08724
08725
08726 static int sip_subscribe_mwi(const char *value, int lineno)
08727 {
08728 struct sip_subscription_mwi *mwi;
08729 int portnum = 0;
08730 enum sip_transport transport = SIP_TRANSPORT_UDP;
08731 char buf[256] = "";
08732 char *username = NULL, *hostname = NULL, *secret = NULL, *authuser = NULL, *porta = NULL, *mailbox = NULL;
08733
08734 if (!value) {
08735 return -1;
08736 }
08737
08738 ast_copy_string(buf, value, sizeof(buf));
08739
08740 username = buf;
08741
08742 if ((hostname = strrchr(buf, '@'))) {
08743 *hostname++ = '\0';
08744 } else {
08745 return -1;
08746 }
08747
08748 if ((secret = strchr(username, ':'))) {
08749 *secret++ = '\0';
08750 if ((authuser = strchr(secret, ':'))) {
08751 *authuser++ = '\0';
08752 }
08753 }
08754
08755 if ((mailbox = strchr(hostname, '/'))) {
08756 *mailbox++ = '\0';
08757 }
08758
08759 if (ast_strlen_zero(username) || ast_strlen_zero(hostname) || ast_strlen_zero(mailbox)) {
08760 ast_log(LOG_WARNING, "Format for MWI subscription is user[:secret[:authuser]]@host[:port]/mailbox at line %d\n", lineno);
08761 return -1;
08762 }
08763
08764 if ((porta = strchr(hostname, ':'))) {
08765 *porta++ = '\0';
08766 if (!(portnum = atoi(porta))) {
08767 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
08768 return -1;
08769 }
08770 }
08771
08772 if (!(mwi = ast_calloc_with_stringfields(1, struct sip_subscription_mwi, 256))) {
08773 return -1;
08774 }
08775
08776 ASTOBJ_INIT(mwi);
08777 ast_string_field_set(mwi, username, username);
08778 if (secret) {
08779 ast_string_field_set(mwi, secret, secret);
08780 }
08781 if (authuser) {
08782 ast_string_field_set(mwi, authuser, authuser);
08783 }
08784 ast_string_field_set(mwi, hostname, hostname);
08785 ast_string_field_set(mwi, mailbox, mailbox);
08786 mwi->resub = -1;
08787 mwi->portno = portnum;
08788 mwi->transport = transport;
08789
08790 ASTOBJ_CONTAINER_LINK(&submwil, mwi);
08791 ASTOBJ_UNREF(mwi, sip_subscribe_mwi_destroy);
08792
08793 return 0;
08794 }
08795
08796 static void mark_method_allowed(unsigned int *allowed_methods, enum sipmethod method)
08797 {
08798 (*allowed_methods) |= (1 << method);
08799 }
08800
08801 static void mark_method_unallowed(unsigned int *allowed_methods, enum sipmethod method)
08802 {
08803 (*allowed_methods) &= ~(1 << method);
08804 }
08805
08806
08807 static int is_method_allowed(unsigned int *allowed_methods, enum sipmethod method)
08808 {
08809 return ((*allowed_methods) >> method) & 1;
08810 }
08811
08812 static void mark_parsed_methods(unsigned int *methods, char *methods_str)
08813 {
08814 char *method;
08815 for (method = strsep(&methods_str, ","); !ast_strlen_zero(method); method = strsep(&methods_str, ",")) {
08816 int id = find_sip_method(ast_skip_blanks(method));
08817 if (id == SIP_UNKNOWN) {
08818 continue;
08819 }
08820 mark_method_allowed(methods, id);
08821 }
08822 }
08823
08824
08825
08826
08827
08828
08829
08830
08831
08832
08833
08834
08835
08836
08837
08838
08839 static unsigned int parse_allowed_methods(struct sip_request *req)
08840 {
08841 char *allow = ast_strdupa(get_header(req, "Allow"));
08842 unsigned int allowed_methods = SIP_UNKNOWN;
08843
08844 if (ast_strlen_zero(allow)) {
08845
08846
08847
08848
08849 char *contact = ast_strdupa(get_header(req, "Contact"));
08850 char *methods = strstr(contact, ";methods=");
08851
08852 if (ast_strlen_zero(methods)) {
08853
08854
08855
08856
08857
08858
08859
08860
08861
08862
08863
08864 return UINT_MAX;
08865 }
08866 allow = ast_strip_quoted(methods + 9, "\"", "\"");
08867 }
08868 mark_parsed_methods(&allowed_methods, allow);
08869 return allowed_methods;
08870 }
08871
08872
08873
08874
08875
08876
08877
08878
08879
08880
08881 static unsigned int set_pvt_allowed_methods(struct sip_pvt *pvt, struct sip_request *req)
08882 {
08883 pvt->allowed_methods = parse_allowed_methods(req);
08884
08885 if (ast_test_flag(&pvt->flags[1], SIP_PAGE2_RPID_UPDATE)) {
08886 mark_method_allowed(&pvt->allowed_methods, SIP_UPDATE);
08887 }
08888 pvt->allowed_methods &= ~(pvt->disallowed_methods);
08889
08890 return pvt->allowed_methods;
08891 }
08892
08893
08894
08895 static void lws2sws(struct ast_str *data)
08896 {
08897 char *msgbuf = data->str;
08898 int len = ast_str_strlen(data);
08899 int h = 0, t = 0;
08900 int lws = 0;
08901
08902 for (; h < len;) {
08903
08904 if (msgbuf[h] == '\r') {
08905 h++;
08906 continue;
08907 }
08908
08909 if (msgbuf[h] == '\n') {
08910
08911 if (h + 1 == len)
08912 break;
08913
08914 if (msgbuf[h + 1] == ' ' || msgbuf[h + 1] == '\t') {
08915
08916 h++;
08917 continue;
08918 }
08919
08920 msgbuf[t++] = msgbuf[h++];
08921 lws = 0;
08922 continue;
08923 }
08924 if (msgbuf[h] == ' ' || msgbuf[h] == '\t') {
08925 if (lws) {
08926 h++;
08927 continue;
08928 }
08929 msgbuf[t++] = msgbuf[h++];
08930 lws = 1;
08931 continue;
08932 }
08933 msgbuf[t++] = msgbuf[h++];
08934 if (lws)
08935 lws = 0;
08936 }
08937 msgbuf[t] = '\0';
08938 data->used = t;
08939 }
08940
08941
08942
08943
08944 static int parse_request(struct sip_request *req)
08945 {
08946 char *c = req->data->str;
08947 ptrdiff_t *dst = req->header;
08948 int i = 0, lim = SIP_MAX_HEADERS - 1;
08949 unsigned int skipping_headers = 0;
08950 ptrdiff_t current_header_offset = 0;
08951 char *previous_header = "";
08952
08953 req->header[0] = 0;
08954 req->headers = -1;
08955 for (; *c; c++) {
08956 if (*c == '\r') {
08957 *c = '\0';
08958 } else if (*c == '\n') {
08959 *c = '\0';
08960 current_header_offset = (c + 1) - ast_str_buffer(req->data);
08961 previous_header = ast_str_buffer(req->data) + dst[i];
08962 if (skipping_headers) {
08963
08964
08965
08966 if (ast_strlen_zero(previous_header)) {
08967 skipping_headers = 0;
08968 }
08969 dst[i] = current_header_offset;
08970 continue;
08971 }
08972 if (sipdebug) {
08973 ast_debug(4, "%7s %2d [%3d]: %s\n",
08974 req->headers < 0 ? "Header" : "Body",
08975 i, (int) strlen(previous_header), previous_header);
08976 }
08977 if (ast_strlen_zero(previous_header) && req->headers < 0) {
08978 req->headers = i;
08979 dst = req->line;
08980 i = 0;
08981 lim = SIP_MAX_LINES - 1;
08982 } else {
08983 if (i++ == lim) {
08984
08985
08986
08987 if (req->headers != -1) {
08988 break;
08989 } else {
08990 req->headers = i;
08991 dst = req->line;
08992 i = 0;
08993 lim = SIP_MAX_LINES - 1;
08994 skipping_headers = 1;
08995 }
08996 }
08997 }
08998 dst[i] = current_header_offset;
08999 }
09000 }
09001
09002
09003
09004
09005
09006
09007 previous_header = ast_str_buffer(req->data) + dst[i];
09008 if ((i < lim) && !ast_strlen_zero(previous_header)) {
09009 if (sipdebug) {
09010 ast_debug(4, "%7s %2d [%3d]: %s\n",
09011 req->headers < 0 ? "Header" : "Body",
09012 i, (int) strlen(previous_header), previous_header );
09013 }
09014 i++;
09015 }
09016
09017
09018 if (req->headers >= 0) {
09019 req->lines = i;
09020 } else {
09021 req->headers = i;
09022 req->lines = 0;
09023
09024 req->line[0] = ast_str_strlen(req->data);
09025 }
09026
09027 if (*c) {
09028 ast_log(LOG_WARNING, "Too many lines, skipping <%s>\n", c);
09029 }
09030
09031
09032 return determine_firstline_parts(req);
09033 }
09034
09035
09036
09037
09038
09039
09040
09041
09042
09043 static int find_sdp(struct sip_request *req)
09044 {
09045 const char *content_type;
09046 const char *content_length;
09047 const char *search;
09048 char *boundary;
09049 unsigned int x;
09050 int boundaryisquoted = FALSE;
09051 int found_application_sdp = FALSE;
09052 int found_end_of_headers = FALSE;
09053
09054 content_length = get_header(req, "Content-Length");
09055
09056 if (!ast_strlen_zero(content_length)) {
09057 if (sscanf(content_length, "%30u", &x) != 1) {
09058 ast_log(LOG_WARNING, "Invalid Content-Length: %s\n", content_length);
09059 return 0;
09060 }
09061
09062
09063
09064 if (x == 0)
09065 return 0;
09066 }
09067
09068 content_type = get_header(req, "Content-Type");
09069
09070
09071 if (!strncasecmp(content_type, "application/sdp", 15)) {
09072 req->sdp_start = 0;
09073 req->sdp_count = req->lines;
09074 return req->lines ? 1 : 0;
09075 }
09076
09077
09078 if (strncasecmp(content_type, "multipart/mixed", 15))
09079 return 0;
09080
09081
09082 if ((search = strcasestr(content_type, ";boundary=")))
09083 search += 10;
09084 else if ((search = strcasestr(content_type, "; boundary=")))
09085 search += 11;
09086 else
09087 return 0;
09088
09089 if (ast_strlen_zero(search))
09090 return 0;
09091
09092
09093 if (*search == '\"') {
09094 search++;
09095 boundaryisquoted = TRUE;
09096 }
09097
09098
09099
09100 boundary = ast_strdupa(search - 2);
09101 boundary[0] = boundary[1] = '-';
09102
09103 if (boundaryisquoted)
09104 boundary[strlen(boundary) - 1] = '\0';
09105
09106
09107
09108
09109 for (x = 0; x < (req->lines); x++) {
09110 const char *line = REQ_OFFSET_TO_STR(req, line[x]);
09111 if (!strncasecmp(line, boundary, strlen(boundary))){
09112 if (found_application_sdp && found_end_of_headers) {
09113 req->sdp_count = (x - 1) - req->sdp_start;
09114 return 1;
09115 }
09116 found_application_sdp = FALSE;
09117 }
09118 if (!strcasecmp(line, "Content-Type: application/sdp"))
09119 found_application_sdp = TRUE;
09120
09121 if (ast_strlen_zero(line)) {
09122 if (found_application_sdp && !found_end_of_headers){
09123 req->sdp_start = x;
09124 found_end_of_headers = TRUE;
09125 }
09126 }
09127 }
09128 if (found_application_sdp && found_end_of_headers) {
09129 req->sdp_count = x - req->sdp_start;
09130 return TRUE;
09131 }
09132 return FALSE;
09133 }
09134
09135
09136 static void change_hold_state(struct sip_pvt *dialog, struct sip_request *req, int holdstate, int sendonly)
09137 {
09138 if (sip_cfg.notifyhold && (!holdstate || !ast_test_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD)))
09139 sip_peer_hold(dialog, holdstate);
09140 if (sip_cfg.callevents)
09141 manager_event(EVENT_FLAG_CALL, "Hold",
09142 "Status: %s\r\n"
09143 "Channel: %s\r\n"
09144 "Uniqueid: %s\r\n",
09145 holdstate ? "On" : "Off",
09146 dialog->owner->name,
09147 dialog->owner->uniqueid);
09148 append_history(dialog, holdstate ? "Hold" : "Unhold", "%s", ast_str_buffer(req->data));
09149 if (!holdstate) {
09150 ast_clear_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD);
09151 return;
09152 }
09153
09154
09155
09156 ast_clear_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD);
09157
09158 if (sendonly == 1)
09159 ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_ONEDIR);
09160 else if (sendonly == 2)
09161 ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_INACTIVE);
09162 else
09163 ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_ACTIVE);
09164 return;
09165 }
09166
09167
09168 static int get_ip_and_port_from_sdp(struct sip_request *req, const enum media_type media, struct ast_sockaddr *addr)
09169 {
09170 const char *m;
09171 const char *c;
09172 int miterator = req->sdp_start;
09173 int citerator = req->sdp_start;
09174 int x = 0;
09175 int numberofports;
09176 int len;
09177 int af;
09178 char proto[4], host[258] = "";
09179
09180 c = get_sdp_iterate(&citerator, req, "c");
09181 if (sscanf(c, "IN %3s %256s", proto, host) != 2) {
09182 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
09183
09184 }
09185
09186 for (m = get_sdp_iterate(&miterator, req, "m"); !ast_strlen_zero(m); m = get_sdp_iterate(&miterator, req, "m")) {
09187 if ((media == SDP_AUDIO && ((sscanf(m, "audio %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
09188 (sscanf(m, "audio %30u RTP/AVP %n", &x, &len) == 1 && len > 0))) ||
09189 (media == SDP_VIDEO && ((sscanf(m, "video %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
09190 (sscanf(m, "video %30u RTP/AVP %n", &x, &len) == 1 && len > 0)))) {
09191
09192
09193
09194
09195 c = get_sdp_iterate(&citerator, req, "c");
09196 if (!ast_strlen_zero(c)) {
09197 sscanf(c, "IN %3s %256s", proto, host);
09198 }
09199 break;
09200 }
09201 }
09202
09203 if (!strcmp("IP4", proto)) {
09204 af = AF_INET;
09205 } else if (!strcmp("IP6", proto)) {
09206 af = AF_INET6;
09207 } else {
09208 ast_log(LOG_WARNING, "Unknown protocol '%s'.\n", proto);
09209 return -1;
09210 }
09211
09212 if (ast_strlen_zero(host) || x == 0) {
09213 ast_log(LOG_WARNING, "Failed to read an alternate host or port in SDP. Expect %s problems\n", media == SDP_AUDIO ? "audio" : "video");
09214 return -1;
09215 }
09216
09217 if (ast_sockaddr_resolve_first_af(addr, host, 0, af)) {
09218 ast_log(LOG_WARNING, "Could not look up IP address of alternate hostname. Expect %s problems\n", media == SDP_AUDIO? "audio" : "video");
09219 return -1;
09220 }
09221
09222 return 0;
09223 }
09224
09225
09226
09227
09228
09229
09230
09231 static int sockaddr_is_null_or_any(const struct ast_sockaddr *addr)
09232 {
09233 return ast_sockaddr_isnull(addr) || ast_sockaddr_is_any(addr);
09234 }
09235
09236
09237
09238
09239
09240
09241 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action)
09242 {
09243
09244 int start = req->sdp_start;
09245 int next = start;
09246 int iterator = start;
09247
09248
09249 char type = '\0';
09250 const char *value = NULL;
09251 const char *m = NULL;
09252 const char *nextm = NULL;
09253 int len = -1;
09254
09255
09256 struct ast_sockaddr sessionsa;
09257 struct ast_sockaddr audiosa;
09258 struct ast_sockaddr videosa;
09259 struct ast_sockaddr textsa;
09260 struct ast_sockaddr imagesa;
09261 struct ast_sockaddr *sa = NULL;
09262 struct ast_sockaddr *vsa = NULL;
09263 struct ast_sockaddr *tsa = NULL;
09264 struct ast_sockaddr *isa = NULL;
09265 int portno = -1;
09266 int vportno = -1;
09267 int tportno = -1;
09268 int udptlportno = -1;
09269
09270
09271 format_t peercapability = 0, vpeercapability = 0, tpeercapability = 0;
09272 int peernoncodeccapability = 0, vpeernoncodeccapability = 0, tpeernoncodeccapability = 0;
09273
09274 struct ast_rtp_codecs newaudiortp, newvideortp, newtextrtp;
09275 format_t newjointcapability;
09276 format_t newpeercapability;
09277 int newnoncodeccapability;
09278
09279 const char *codecs;
09280 int codec;
09281
09282
09283 int secure_audio = FALSE;
09284 int secure_video = FALSE;
09285
09286
09287 int sendonly = -1;
09288 int numberofports;
09289 int numberofmediastreams = 0;
09290 int last_rtpmap_codec = 0;
09291 int red_data_pt[10];
09292 int red_num_gen = 0;
09293 char red_fmtp[100] = "empty";
09294 int debug = sip_debug_test_pvt(p);
09295
09296
09297 char buf[SIPBUFSIZE];
09298
09299
09300
09301 if (!p->rtp) {
09302 ast_log(LOG_ERROR, "Got SDP but have no RTP session allocated.\n");
09303 return -1;
09304 }
09305
09306
09307 ast_rtp_codecs_payloads_clear(&newaudiortp, NULL);
09308 ast_rtp_codecs_payloads_clear(&newvideortp, NULL);
09309 ast_rtp_codecs_payloads_clear(&newtextrtp, NULL);
09310
09311
09312 p->lastrtprx = p->lastrtptx = time(NULL);
09313
09314 memset(p->offered_media, 0, sizeof(p->offered_media));
09315
09316
09317 p->novideo = TRUE;
09318 p->notext = TRUE;
09319
09320
09321 nextm = get_sdp_iterate(&next, req, "m");
09322 if (ast_strlen_zero(nextm)) {
09323 ast_log(LOG_WARNING, "Insufficient information for SDP (m= not found)\n");
09324 return -1;
09325 }
09326
09327
09328 while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
09329 int processed = FALSE;
09330 switch (type) {
09331 case 'o':
09332
09333
09334
09335 if (!process_sdp_o(value, p)) {
09336 return (p->session_modify == FALSE) ? 0 : -1;
09337 }
09338 processed = TRUE;
09339 break;
09340 case 'c':
09341 if (process_sdp_c(value, &sessionsa)) {
09342 processed = TRUE;
09343 sa = &sessionsa;
09344 vsa = sa;
09345 tsa = sa;
09346 isa = sa;
09347 }
09348 break;
09349 case 'a':
09350 if (process_sdp_a_sendonly(value, &sendonly)) {
09351 processed = TRUE;
09352 }
09353 else if (process_sdp_a_audio(value, p, &newaudiortp, &last_rtpmap_codec))
09354 processed = TRUE;
09355 else if (process_sdp_a_video(value, p, &newvideortp, &last_rtpmap_codec))
09356 processed = TRUE;
09357 else if (process_sdp_a_text(value, p, &newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec))
09358 processed = TRUE;
09359 else if (process_sdp_a_image(value, p))
09360 processed = TRUE;
09361 break;
09362 }
09363
09364 ast_debug(3, "Processing session-level SDP %c=%s... %s\n", type, value, (processed == TRUE)? "OK." : "UNSUPPORTED OR FAILED.");
09365 }
09366
09367
09368 while (!ast_strlen_zero(nextm)) {
09369 int audio = FALSE;
09370 int video = FALSE;
09371 int image = FALSE;
09372 int text = FALSE;
09373 int processed_crypto = FALSE;
09374 char protocol[18] = {0,};
09375 int x;
09376
09377 numberofports = 0;
09378 len = -1;
09379 start = next;
09380 m = nextm;
09381 iterator = next;
09382 nextm = get_sdp_iterate(&next, req, "m");
09383
09384
09385 if (strncmp(m, "audio ", 6) == 0) {
09386 if ((sscanf(m, "audio %30u/%30u RTP/%4s %n", &x, &numberofports, protocol, &len) == 3 && len > 0) ||
09387 (sscanf(m, "audio %30u RTP/%4s %n", &x, protocol, &len) == 2 && len > 0)) {
09388 if (x == 0) {
09389 ast_log(LOG_WARNING, "Ignoring audio media offer because port number is zero\n");
09390 continue;
09391 }
09392
09393
09394 if (numberofports > 1) {
09395 ast_log(LOG_WARNING, "%d ports offered for audio media, not supported by Asterisk. Will try anyway...\n", numberofports);
09396 }
09397
09398 if (!strcmp(protocol, "SAVP")) {
09399 secure_audio = 1;
09400 } else if (strcmp(protocol, "AVP")) {
09401 ast_log(LOG_WARNING, "Unknown RTP profile in audio offer: %s\n", m);
09402 continue;
09403 }
09404
09405 if (p->offered_media[SDP_AUDIO].order_offered) {
09406 ast_log(LOG_WARNING, "Rejecting non-primary audio stream: %s\n", m);
09407 return -1;
09408 }
09409
09410 audio = TRUE;
09411 p->offered_media[SDP_AUDIO].order_offered = ++numberofmediastreams;
09412 portno = x;
09413
09414
09415 codecs = m + len;
09416 ast_copy_string(p->offered_media[SDP_AUDIO].codecs, codecs, sizeof(p->offered_media[SDP_AUDIO].codecs));
09417 for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
09418 if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
09419 ast_log(LOG_WARNING, "Invalid syntax in RTP audio format list: %s\n", codecs);
09420 return -1;
09421 }
09422 if (debug) {
09423 ast_verbose("Found RTP audio format %d\n", codec);
09424 }
09425
09426 ast_rtp_codecs_payloads_set_m_type(&newaudiortp, NULL, codec);
09427 }
09428 } else {
09429 ast_log(LOG_WARNING, "Rejecting audio media offer due to invalid or unsupported syntax: %s\n", m);
09430 return -1;
09431 }
09432 }
09433
09434 else if (strncmp(m, "video ", 6) == 0) {
09435 if ((sscanf(m, "video %30u/%30u RTP/%4s %n", &x, &numberofports, protocol, &len) == 3 && len > 0) ||
09436 (sscanf(m, "video %30u RTP/%4s %n", &x, protocol, &len) == 2 && len > 0)) {
09437 if (x == 0) {
09438 ast_log(LOG_WARNING, "Ignoring video media offer because port number is zero\n");
09439 continue;
09440 }
09441
09442
09443 if (numberofports > 1) {
09444 ast_log(LOG_WARNING, "%d ports offered for video media, not supported by Asterisk. Will try anyway...\n", numberofports);
09445 }
09446
09447 if (!strcmp(protocol, "SAVP")) {
09448 secure_video = 1;
09449 } else if (strcmp(protocol, "AVP")) {
09450 ast_log(LOG_WARNING, "Unknown RTP profile in video offer: %s\n", m);
09451 continue;
09452 }
09453
09454 if (p->offered_media[SDP_VIDEO].order_offered) {
09455 ast_log(LOG_WARNING, "Rejecting non-primary video stream: %s\n", m);
09456 return -1;
09457 }
09458
09459 video = TRUE;
09460 p->novideo = FALSE;
09461 p->offered_media[SDP_VIDEO].order_offered = ++numberofmediastreams;
09462 vportno = x;
09463
09464
09465 codecs = m + len;
09466 ast_copy_string(p->offered_media[SDP_VIDEO].codecs, codecs, sizeof(p->offered_media[SDP_VIDEO].codecs));
09467 for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
09468 if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
09469 ast_log(LOG_WARNING, "Invalid syntax in RTP video format list: %s\n", codecs);
09470 return -1;
09471 }
09472 if (debug) {
09473 ast_verbose("Found RTP video format %d\n", codec);
09474 }
09475 ast_rtp_codecs_payloads_set_m_type(&newvideortp, NULL, codec);
09476 }
09477 } else {
09478 ast_log(LOG_WARNING, "Rejecting video media offer due to invalid or unsupported syntax: %s\n", m);
09479 return -1;
09480 }
09481 }
09482
09483 else if (strncmp(m, "text ", 5) == 0) {
09484 if ((sscanf(m, "text %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
09485 (sscanf(m, "text %30u RTP/AVP %n", &x, &len) == 1 && len > 0)) {
09486 if (x == 0) {
09487 ast_log(LOG_WARNING, "Ignoring text media offer because port number is zero\n");
09488 continue;
09489 }
09490
09491
09492 if (numberofports > 1) {
09493 ast_log(LOG_WARNING, "%d ports offered for text media, not supported by Asterisk. Will try anyway...\n", numberofports);
09494 }
09495
09496 if (p->offered_media[SDP_TEXT].order_offered) {
09497 ast_log(LOG_WARNING, "Rejecting non-primary text stream: %s\n", m);
09498 return -1;
09499 }
09500
09501 text = TRUE;
09502 p->notext = FALSE;
09503 p->offered_media[SDP_TEXT].order_offered = ++numberofmediastreams;
09504 tportno = x;
09505
09506
09507 codecs = m + len;
09508 ast_copy_string(p->offered_media[SDP_TEXT].codecs, codecs, sizeof(p->offered_media[SDP_TEXT].codecs));
09509 for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
09510 if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
09511 ast_log(LOG_WARNING, "Invalid syntax in RTP video format list: %s\n", codecs);
09512 return -1;
09513 }
09514 if (debug) {
09515 ast_verbose("Found RTP text format %d\n", codec);
09516 }
09517 ast_rtp_codecs_payloads_set_m_type(&newtextrtp, NULL, codec);
09518 }
09519 } else {
09520 ast_log(LOG_WARNING, "Rejecting text media offer due to invalid or unsupported syntax: %s\n", m);
09521 return -1;
09522 }
09523 }
09524
09525 else if (strncmp(m, "image ", 6) == 0) {
09526 if (((sscanf(m, "image %30u udptl t38%n", &x, &len) == 1 && len > 0) ||
09527 (sscanf(m, "image %30u UDPTL t38%n", &x, &len) == 1 && len > 0))) {
09528 if (x == 0) {
09529 ast_log(LOG_WARNING, "Ignoring image media offer because port number is zero\n");
09530 continue;
09531 }
09532
09533 if (initialize_udptl(p)) {
09534 ast_log(LOG_WARNING, "Rejecting offer with image stream due to UDPTL initialization failure\n");
09535 return -1;
09536 }
09537
09538 if (p->offered_media[SDP_IMAGE].order_offered) {
09539 ast_log(LOG_WARNING, "Rejecting non-primary image stream: %s\n", m);
09540 return -1;
09541 }
09542
09543 image = TRUE;
09544 if (debug) {
09545 ast_verbose("Got T.38 offer in SDP in dialog %s\n", p->callid);
09546 }
09547
09548 p->offered_media[SDP_IMAGE].order_offered = ++numberofmediastreams;
09549 udptlportno = x;
09550
09551 if (p->t38.state != T38_ENABLED) {
09552 memset(&p->t38.their_parms, 0, sizeof(p->t38.their_parms));
09553
09554
09555
09556 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
09557 }
09558 } else if (sscanf(m, "image %30u %17s t38%n", &x, protocol, &len) == 2 && len > 0) {
09559 ast_log(LOG_WARNING, "Declining image stream due to unsupported transport: %s\n", m);
09560 continue;
09561 } else {
09562 ast_log(LOG_WARNING, "Rejecting image media offer due to invalid or unsupported syntax: %s\n", m);
09563 return -1;
09564 }
09565 } else {
09566 ast_log(LOG_WARNING, "Unsupported top-level media type in offer: %s\n", m);
09567 continue;
09568 }
09569
09570
09571 while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
09572 int processed = FALSE;
09573
09574 switch (type) {
09575 case 'c':
09576 if (audio) {
09577 if (process_sdp_c(value, &audiosa)) {
09578 processed = TRUE;
09579 sa = &audiosa;
09580 }
09581 } else if (video) {
09582 if (process_sdp_c(value, &videosa)) {
09583 processed = TRUE;
09584 vsa = &videosa;
09585 }
09586 } else if (text) {
09587 if (process_sdp_c(value, &textsa)) {
09588 processed = TRUE;
09589 tsa = &textsa;
09590 }
09591 } else if (image) {
09592 if (process_sdp_c(value, &imagesa)) {
09593 processed = TRUE;
09594 isa = &imagesa;
09595 }
09596 }
09597 break;
09598 case 'a':
09599
09600 if (audio) {
09601 if (process_sdp_a_sendonly(value, &sendonly)) {
09602 processed = TRUE;
09603 } else if (!processed_crypto && process_crypto(p, p->rtp, &p->srtp, value)) {
09604 processed_crypto = TRUE;
09605 processed = TRUE;
09606 } else if (process_sdp_a_audio(value, p, &newaudiortp, &last_rtpmap_codec)) {
09607 processed = TRUE;
09608 }
09609 }
09610
09611 else if (video) {
09612 if (!processed_crypto && process_crypto(p, p->vrtp, &p->vsrtp, value)) {
09613 processed_crypto = TRUE;
09614 processed = TRUE;
09615 } else if (process_sdp_a_video(value, p, &newvideortp, &last_rtpmap_codec)) {
09616 processed = TRUE;
09617 }
09618 }
09619
09620 else if (text) {
09621 if (process_sdp_a_text(value, p, &newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec)) {
09622 processed = TRUE;
09623 } else if (!processed_crypto && process_crypto(p, p->trtp, &p->tsrtp, value)) {
09624 processed_crypto = TRUE;
09625 processed = TRUE;
09626 }
09627 }
09628
09629 else if (image) {
09630 if (process_sdp_a_image(value, p))
09631 processed = TRUE;
09632 }
09633 break;
09634 }
09635
09636 ast_debug(3, "Processing media-level (%s) SDP %c=%s... %s\n",
09637 (audio == TRUE)? "audio" : (video == TRUE)? "video" : (text == TRUE)? "text" : "image",
09638 type, value,
09639 (processed == TRUE)? "OK." : "UNSUPPORTED OR FAILED.");
09640 }
09641
09642
09643 if (audio && secure_audio && !processed_crypto) {
09644 ast_log(LOG_WARNING, "Rejecting secure audio stream without encryption details: %s\n", m);
09645 return -1;
09646 } else if (video && secure_video && !processed_crypto) {
09647 ast_log(LOG_WARNING, "Rejecting secure video stream without encryption details: %s\n", m);
09648 return -1;
09649 }
09650 }
09651
09652
09653 if (!sa && !vsa && !tsa && !isa) {
09654 ast_log(LOG_WARNING, "Insufficient information in SDP (c=)...\n");
09655 return -1;
09656 }
09657
09658 if ((portno == -1) &&
09659 (vportno == -1) &&
09660 (tportno == -1) &&
09661 (udptlportno == -1)) {
09662 ast_log(LOG_WARNING, "Failing due to no acceptable offer found\n");
09663 return -1;
09664 }
09665
09666 if (secure_audio && !(p->srtp && (ast_test_flag(p->srtp, SRTP_CRYPTO_OFFER_OK)))) {
09667 ast_log(LOG_WARNING, "Can't provide secure audio requested in SDP offer\n");
09668 return -1;
09669 }
09670
09671 if (!secure_audio && p->srtp) {
09672 ast_log(LOG_WARNING, "We are requesting SRTP for audio, but they responded without it!\n");
09673 return -1;
09674 }
09675
09676 if (secure_video && !(p->vsrtp && (ast_test_flag(p->vsrtp, SRTP_CRYPTO_OFFER_OK)))) {
09677 ast_log(LOG_WARNING, "Can't provide secure video requested in SDP offer\n");
09678 return -1;
09679 }
09680
09681 if (!p->novideo && !secure_video && p->vsrtp) {
09682 ast_log(LOG_WARNING, "We are requesting SRTP for video, but they responded without it!\n");
09683 return -1;
09684 }
09685
09686 if (!(secure_audio || secure_video) && ast_test_flag(&p->flags[1], SIP_PAGE2_USE_SRTP)) {
09687 ast_log(LOG_WARNING, "Matched device setup to use SRTP, but request was not!\n");
09688 return -1;
09689 }
09690
09691 if (udptlportno == -1) {
09692 change_t38_state(p, T38_DISABLED);
09693 }
09694
09695
09696 ast_rtp_codecs_payload_formats(&newaudiortp, &peercapability, &peernoncodeccapability);
09697 ast_rtp_codecs_payload_formats(&newvideortp, &vpeercapability, &vpeernoncodeccapability);
09698 ast_rtp_codecs_payload_formats(&newtextrtp, &tpeercapability, &tpeernoncodeccapability);
09699
09700 newjointcapability = p->capability & (peercapability | vpeercapability | tpeercapability);
09701 newpeercapability = (peercapability | vpeercapability | tpeercapability);
09702 newnoncodeccapability = p->noncodeccapability & peernoncodeccapability;
09703
09704 if (debug) {
09705
09706 char s1[SIPBUFSIZE], s2[SIPBUFSIZE], s3[SIPBUFSIZE], s4[SIPBUFSIZE], s5[SIPBUFSIZE];
09707
09708 ast_verbose("Capabilities: us - %s, peer - audio=%s/video=%s/text=%s, combined - %s\n",
09709 ast_getformatname_multiple(s1, SIPBUFSIZE, p->capability),
09710 ast_getformatname_multiple(s2, SIPBUFSIZE, peercapability),
09711 ast_getformatname_multiple(s3, SIPBUFSIZE, vpeercapability),
09712 ast_getformatname_multiple(s4, SIPBUFSIZE, tpeercapability),
09713 ast_getformatname_multiple(s5, SIPBUFSIZE, newjointcapability));
09714 }
09715 if (debug) {
09716 struct ast_str *s1 = ast_str_alloca(SIPBUFSIZE);
09717 struct ast_str *s2 = ast_str_alloca(SIPBUFSIZE);
09718 struct ast_str *s3 = ast_str_alloca(SIPBUFSIZE);
09719
09720 ast_verbose("Non-codec capabilities (dtmf): us - %s, peer - %s, combined - %s\n",
09721 ast_rtp_lookup_mime_multiple2(s1, p->noncodeccapability, 0, 0),
09722 ast_rtp_lookup_mime_multiple2(s2, peernoncodeccapability, 0, 0),
09723 ast_rtp_lookup_mime_multiple2(s3, newnoncodeccapability, 0, 0));
09724 }
09725 if (!newjointcapability && udptlportno == -1) {
09726 ast_log(LOG_NOTICE, "No compatible codecs, not accepting this offer!\n");
09727
09728 return -1;
09729 }
09730
09731 if (portno != -1 || vportno != -1 || tportno != -1) {
09732
09733
09734 p->jointcapability = newjointcapability;
09735 p->peercapability = newpeercapability;
09736 p->jointnoncodeccapability = newnoncodeccapability;
09737
09738
09739 if (ast_test_flag(&p->flags[1], SIP_PAGE2_PREFERRED_CODEC)) {
09740 p->jointcapability = ast_codec_choose(&p->prefs, p->jointcapability, 1);
09741 }
09742 }
09743
09744
09745 if (p->rtp) {
09746 if (sa && portno > 0) {
09747 ast_sockaddr_set_port(sa, portno);
09748 ast_rtp_instance_set_remote_address(p->rtp, sa);
09749 if (debug) {
09750 ast_verbose("Peer audio RTP is at port %s\n",
09751 ast_sockaddr_stringify(sa));
09752 }
09753
09754 ast_rtp_codecs_payloads_copy(&newaudiortp, ast_rtp_instance_get_codecs(p->rtp), p->rtp);
09755
09756
09757 ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_RTCP, 1);
09758
09759 if (p->owner) {
09760 ast_channel_set_fd(p->owner, 1, ast_rtp_instance_fd(p->rtp, 1));
09761 }
09762
09763 if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) {
09764 ast_clear_flag(&p->flags[0], SIP_DTMF);
09765 if (newnoncodeccapability & AST_RTP_DTMF) {
09766
09767 ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
09768
09769 ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF, 1);
09770 ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
09771 } else {
09772 ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
09773 }
09774 }
09775 } else if (udptlportno > 0) {
09776 if (debug)
09777 ast_verbose("Got T.38 Re-invite without audio. Keeping RTP active during T.38 session.\n");
09778
09779 if (p->owner) {
09780 ast_channel_set_fd(p->owner, 1, -1);
09781 }
09782
09783 ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_RTCP, 0);
09784 } else {
09785 ast_rtp_instance_stop(p->rtp);
09786 if (debug)
09787 ast_verbose("Peer doesn't provide audio\n");
09788 }
09789 }
09790
09791
09792 if (p->vrtp) {
09793 if (vsa && vportno > 0) {
09794 ast_sockaddr_set_port(vsa, vportno);
09795 ast_rtp_instance_set_remote_address(p->vrtp, vsa);
09796 if (debug) {
09797 ast_verbose("Peer video RTP is at port %s\n",
09798 ast_sockaddr_stringify(vsa));
09799 }
09800 ast_rtp_codecs_payloads_copy(&newvideortp, ast_rtp_instance_get_codecs(p->vrtp), p->vrtp);
09801 } else {
09802 ast_rtp_instance_stop(p->vrtp);
09803 if (debug)
09804 ast_verbose("Peer doesn't provide video\n");
09805 }
09806 }
09807
09808
09809 if (p->trtp) {
09810 if (tsa && tportno > 0) {
09811 ast_sockaddr_set_port(tsa, tportno);
09812 ast_rtp_instance_set_remote_address(p->trtp, tsa);
09813 if (debug) {
09814 ast_verbose("Peer T.140 RTP is at port %s\n",
09815 ast_sockaddr_stringify(tsa));
09816 }
09817 if ((p->jointcapability & AST_FORMAT_T140RED)) {
09818 p->red = 1;
09819 ast_rtp_red_init(p->trtp, 300, red_data_pt, 2);
09820 } else {
09821 p->red = 0;
09822 }
09823 ast_rtp_codecs_payloads_copy(&newtextrtp, ast_rtp_instance_get_codecs(p->trtp), p->trtp);
09824 } else {
09825 ast_rtp_instance_stop(p->trtp);
09826 if (debug)
09827 ast_verbose("Peer doesn't provide T.140\n");
09828 }
09829 }
09830
09831
09832 if (p->udptl) {
09833 if (isa && udptlportno > 0) {
09834 if (ast_test_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP) && ast_test_flag(&p->flags[1], SIP_PAGE2_UDPTL_DESTINATION)) {
09835 ast_rtp_instance_get_remote_address(p->rtp, isa);
09836 if (!ast_sockaddr_isnull(isa) && debug) {
09837 ast_debug(1, "Peer T.38 UDPTL is set behind NAT and with destination, destination address now %s\n", ast_sockaddr_stringify(isa));
09838 }
09839 }
09840 ast_sockaddr_set_port(isa, udptlportno);
09841 ast_udptl_set_peer(p->udptl, isa);
09842 if (debug)
09843 ast_debug(1,"Peer T.38 UDPTL is at port %s\n", ast_sockaddr_stringify(isa));
09844
09845
09846 if (!ast_udptl_get_far_max_datagram(p->udptl)) {
09847
09848 ast_udptl_set_far_max_datagram(p->udptl, 0);
09849 }
09850
09851
09852 if ((t38action == SDP_T38_ACCEPT) &&
09853 (p->t38.state == T38_LOCAL_REINVITE)) {
09854 change_t38_state(p, T38_ENABLED);
09855 } else if ((t38action == SDP_T38_INITIATE) &&
09856 p->owner && p->lastinvite) {
09857 change_t38_state(p, T38_PEER_REINVITE);
09858
09859 if (ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_T38)) {
09860 ast_channel_lock(p->owner);
09861 if (strcmp(p->owner->exten, "fax")) {
09862 const char *target_context = S_OR(p->owner->macrocontext, p->owner->context);
09863 ast_channel_unlock(p->owner);
09864 if (ast_exists_extension(p->owner, target_context, "fax", 1,
09865 S_COR(p->owner->caller.id.number.valid, p->owner->caller.id.number.str, NULL))) {
09866 ast_verbose(VERBOSE_PREFIX_2 "Redirecting '%s' to fax extension due to peer T.38 re-INVITE\n", p->owner->name);
09867 pbx_builtin_setvar_helper(p->owner, "FAXEXTEN", p->owner->exten);
09868 if (ast_async_goto(p->owner, target_context, "fax", 1)) {
09869 ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", p->owner->name, target_context);
09870 }
09871 } else {
09872 ast_log(LOG_NOTICE, "T.38 re-INVITE detected but no fax extension\n");
09873 }
09874 } else {
09875 ast_channel_unlock(p->owner);
09876 }
09877 }
09878 }
09879 } else {
09880 change_t38_state(p, T38_DISABLED);
09881 ast_udptl_stop(p->udptl);
09882 if (debug)
09883 ast_debug(1, "Peer doesn't provide T.38 UDPTL\n");
09884 }
09885 }
09886
09887 if ((portno == -1) && (p->t38.state != T38_DISABLED)) {
09888 ast_debug(3, "Have T.38 but no audio, accepting offer anyway\n");
09889 return 0;
09890 }
09891
09892
09893 ast_debug(2, "We're settling with these formats: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, p->jointcapability));
09894
09895 if (!p->owner)
09896 return 0;
09897
09898 ast_debug(4, "We have an owner, now see if we need to change this call\n");
09899
09900 if (!(p->owner->nativeformats & p->jointcapability) && (p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
09901 if (debug) {
09902 char s1[SIPBUFSIZE], s2[SIPBUFSIZE];
09903 ast_debug(1, "Oooh, we need to change our audio formats since our peer supports only %s and not %s\n",
09904 ast_getformatname_multiple(s1, SIPBUFSIZE, p->jointcapability),
09905 ast_getformatname_multiple(s2, SIPBUFSIZE, p->owner->nativeformats));
09906 }
09907 p->owner->nativeformats = ast_codec_choose(&p->prefs, p->jointcapability, 1) | (p->capability & vpeercapability) | (p->capability & tpeercapability);
09908 ast_set_read_format(p->owner, p->owner->readformat);
09909 ast_set_write_format(p->owner, p->owner->writeformat);
09910 }
09911
09912 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)) {
09913 ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
09914
09915 ast_queue_frame(p->owner, &ast_null_frame);
09916 change_hold_state(p, req, FALSE, sendonly);
09917 } 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)) {
09918 ast_queue_control_data(p->owner, AST_CONTROL_HOLD,
09919 S_OR(p->mohsuggest, NULL),
09920 !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
09921 if (sendonly)
09922 ast_rtp_instance_stop(p->rtp);
09923
09924
09925 ast_queue_frame(p->owner, &ast_null_frame);
09926 change_hold_state(p, req, TRUE, sendonly);
09927 }
09928
09929 return 0;
09930 }
09931
09932 static int process_sdp_o(const char *o, struct sip_pvt *p)
09933 {
09934 char *o_copy;
09935 char *token;
09936 int64_t rua_version;
09937
09938
09939
09940
09941
09942
09943
09944
09945
09946
09947 p->session_modify = TRUE;
09948
09949 if (ast_strlen_zero(o)) {
09950 ast_log(LOG_WARNING, "SDP syntax error. SDP without an o= line\n");
09951 return FALSE;
09952 }
09953
09954 o_copy = ast_strdupa(o);
09955 token = strsep(&o_copy, " ");
09956 if (!o_copy) {
09957 ast_log(LOG_WARNING, "SDP syntax error in o= line username\n");
09958 return FALSE;
09959 }
09960 token = strsep(&o_copy, " ");
09961 if (!o_copy) {
09962 ast_log(LOG_WARNING, "SDP syntax error in o= line session-id\n");
09963 return FALSE;
09964 }
09965 token = strsep(&o_copy, " ");
09966 if (!o_copy) {
09967 ast_log(LOG_WARNING, "SDP syntax error in o= line\n");
09968 return FALSE;
09969 }
09970 if (!sscanf(token, "%30" SCNd64, &rua_version)) {
09971 ast_log(LOG_WARNING, "SDP syntax error in o= line version\n");
09972 return FALSE;
09973 }
09974
09975
09976
09977
09978
09979
09980
09981
09982
09983
09984
09985
09986
09987
09988
09989
09990
09991
09992
09993 if (ast_test_flag(&p->flags[1], SIP_PAGE2_IGNORESDPVERSION) ||
09994 (p->sessionversion_remote < 0) ||
09995 (p->sessionversion_remote < rua_version)) {
09996 p->sessionversion_remote = rua_version;
09997 } else {
09998 if (p->t38.state == T38_LOCAL_REINVITE) {
09999 p->sessionversion_remote = rua_version;
10000 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);
10001 } else {
10002 p->session_modify = FALSE;
10003 ast_debug(2, "Call %s responded to our reinvite without changing SDP version; ignoring SDP.\n", p->callid);
10004 return FALSE;
10005 }
10006 }
10007
10008 return TRUE;
10009 }
10010
10011 static int process_sdp_c(const char *c, struct ast_sockaddr *addr)
10012 {
10013 char proto[4], host[258];
10014 int af;
10015
10016
10017 if (sscanf(c, "IN %3s %255s", proto, host) == 2) {
10018 if (!strcmp("IP4", proto)) {
10019 af = AF_INET;
10020 } else if (!strcmp("IP6", proto)) {
10021 af = AF_INET6;
10022 } else {
10023 ast_log(LOG_WARNING, "Unknown protocol '%s'.\n", proto);
10024 return FALSE;
10025 }
10026 if (ast_sockaddr_resolve_first_af(addr, host, 0, af)) {
10027 ast_log(LOG_WARNING, "Unable to lookup RTP Audio host in c= line, '%s'\n", c);
10028 return FALSE;
10029 }
10030 return TRUE;
10031 } else {
10032 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
10033 return FALSE;
10034 }
10035 return FALSE;
10036 }
10037
10038 static int process_sdp_a_sendonly(const char *a, int *sendonly)
10039 {
10040 int found = FALSE;
10041
10042 if (!strcasecmp(a, "sendonly")) {
10043 if (*sendonly == -1)
10044 *sendonly = 1;
10045 found = TRUE;
10046 } else if (!strcasecmp(a, "inactive")) {
10047 if (*sendonly == -1)
10048 *sendonly = 2;
10049 found = TRUE;
10050 } else if (!strcasecmp(a, "sendrecv")) {
10051 if (*sendonly == -1)
10052 *sendonly = 0;
10053 found = TRUE;
10054 }
10055 return found;
10056 }
10057
10058 static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newaudiortp, int *last_rtpmap_codec)
10059 {
10060 int found = FALSE;
10061 int codec;
10062 char mimeSubtype[128];
10063 char fmtp_string[64];
10064 unsigned int sample_rate;
10065 int debug = sip_debug_test_pvt(p);
10066
10067 if (!strncasecmp(a, "ptime", 5)) {
10068 char *tmp = strrchr(a, ':');
10069 long int framing = 0;
10070 if (tmp) {
10071 tmp++;
10072 framing = strtol(tmp, NULL, 10);
10073 if (framing == LONG_MIN || framing == LONG_MAX) {
10074 framing = 0;
10075 ast_debug(1, "Can't read framing from SDP: %s\n", a);
10076 }
10077 }
10078 if (framing && p->autoframing) {
10079 struct ast_codec_pref *pref = &ast_rtp_instance_get_codecs(p->rtp)->pref;
10080 int codec_n;
10081 for (codec_n = 0; codec_n < AST_RTP_MAX_PT; codec_n++) {
10082 struct ast_rtp_payload_type format = ast_rtp_codecs_payload_lookup(ast_rtp_instance_get_codecs(p->rtp), codec_n);
10083 if (!format.asterisk_format || !format.code)
10084 continue;
10085 ast_debug(1, "Setting framing for %s to %ld\n", ast_getformatname(format.code), framing);
10086 ast_codec_pref_setsize(pref, format.code, framing);
10087 }
10088 ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(p->rtp), p->rtp, pref);
10089 }
10090 found = TRUE;
10091 } else if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
10092
10093 if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
10094 if (!(ast_rtp_codecs_payloads_set_rtpmap_type_rate(newaudiortp, NULL, codec, "audio", mimeSubtype,
10095 ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0, sample_rate))) {
10096 if (debug)
10097 ast_verbose("Found audio description format %s for ID %d\n", mimeSubtype, codec);
10098
10099 (*last_rtpmap_codec)++;
10100 found = TRUE;
10101 } else {
10102 ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
10103 if (debug)
10104 ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
10105 }
10106 } else {
10107 if (debug)
10108 ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
10109 }
10110 } else if (sscanf(a, "fmtp: %30u %63s", &codec, fmtp_string) == 2) {
10111 struct ast_rtp_payload_type payload;
10112
10113 payload = ast_rtp_codecs_payload_lookup(newaudiortp, codec);
10114 if (payload.code && payload.asterisk_format) {
10115 unsigned int bit_rate;
10116
10117 switch (payload.code) {
10118 case AST_FORMAT_SIREN7:
10119 if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
10120 if (bit_rate != 32000) {
10121 ast_log(LOG_WARNING, "Got Siren7 offer at %d bps, but only 32000 bps supported; ignoring.\n", bit_rate);
10122 ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
10123 } else {
10124 found = TRUE;
10125 }
10126 }
10127 break;
10128 case AST_FORMAT_SIREN14:
10129 if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
10130 if (bit_rate != 48000) {
10131 ast_log(LOG_WARNING, "Got Siren14 offer at %d bps, but only 48000 bps supported; ignoring.\n", bit_rate);
10132 ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
10133 } else {
10134 found = TRUE;
10135 }
10136 }
10137 break;
10138 case AST_FORMAT_G719:
10139 if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
10140 if (bit_rate != 64000) {
10141 ast_log(LOG_WARNING, "Got G.719 offer at %d bps, but only 64000 bps supported; ignoring.\n", bit_rate);
10142 ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
10143 } else {
10144 found = TRUE;
10145 }
10146 }
10147 }
10148 }
10149 }
10150
10151 return found;
10152 }
10153
10154 static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newvideortp, int *last_rtpmap_codec)
10155 {
10156 int found = FALSE;
10157 int codec;
10158 char mimeSubtype[128];
10159 unsigned int sample_rate;
10160 int debug = sip_debug_test_pvt(p);
10161
10162 if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
10163
10164 if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
10165
10166 if (!strncasecmp(mimeSubtype, "H26", 3) || !strncasecmp(mimeSubtype, "MP4", 3)) {
10167 if (!(ast_rtp_codecs_payloads_set_rtpmap_type_rate(newvideortp, NULL, codec, "video", mimeSubtype, 0, sample_rate))) {
10168 if (debug)
10169 ast_verbose("Found video description format %s for ID %d\n", mimeSubtype, codec);
10170
10171 (*last_rtpmap_codec)++;
10172 found = TRUE;
10173 } else {
10174 ast_rtp_codecs_payloads_unset(newvideortp, NULL, codec);
10175 if (debug)
10176 ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
10177 }
10178 }
10179 } else {
10180 if (debug)
10181 ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
10182 }
10183 }
10184
10185 return found;
10186 }
10187
10188 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)
10189 {
10190 int found = FALSE;
10191 int codec;
10192 char mimeSubtype[128];
10193 unsigned int sample_rate;
10194 char *red_cp;
10195 int debug = sip_debug_test_pvt(p);
10196
10197 if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
10198
10199 if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
10200 if (!strncasecmp(mimeSubtype, "T140", 4)) {
10201 if (p->trtp) {
10202
10203 ast_rtp_codecs_payloads_set_rtpmap_type_rate(newtextrtp, NULL, codec, "text", mimeSubtype, 0, sample_rate);
10204 found = TRUE;
10205 }
10206 } else if (!strncasecmp(mimeSubtype, "RED", 3)) {
10207 if (p->trtp) {
10208 ast_rtp_codecs_payloads_set_rtpmap_type_rate(newtextrtp, NULL, codec, "text", mimeSubtype, 0, sample_rate);
10209 sprintf(red_fmtp, "fmtp:%d ", codec);
10210 if (debug)
10211 ast_verbose("RED submimetype has payload type: %d\n", codec);
10212 found = TRUE;
10213 }
10214 }
10215 } else {
10216 if (debug)
10217 ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
10218 }
10219 } else if (!strncmp(a, red_fmtp, strlen(red_fmtp))) {
10220
10221 red_cp = &red_fmtp[strlen(red_fmtp)];
10222 strncpy(red_fmtp, a, 100);
10223
10224 sscanf(red_cp, "%30u", &red_data_pt[*red_num_gen]);
10225 red_cp = strtok(red_cp, "/");
10226 while (red_cp && (*red_num_gen)++ < AST_RED_MAX_GENERATION) {
10227 sscanf(red_cp, "%30u", &red_data_pt[*red_num_gen]);
10228 red_cp = strtok(NULL, "/");
10229 }
10230 red_cp = red_fmtp;
10231 found = TRUE;
10232 }
10233
10234 return found;
10235 }
10236
10237 static int process_sdp_a_image(const char *a, struct sip_pvt *p)
10238 {
10239 int found = FALSE;
10240 char s[256];
10241 unsigned int x;
10242 char *attrib = ast_strdupa(a);
10243 char *pos;
10244
10245 if (initialize_udptl(p)) {
10246 return found;
10247 }
10248
10249
10250
10251
10252
10253
10254 for (pos = attrib; *pos; ++pos) {
10255 *pos = tolower(*pos);
10256 }
10257
10258 if ((sscanf(attrib, "t38faxmaxbuffer:%30u", &x) == 1)) {
10259 ast_debug(3, "MaxBufferSize:%d\n", x);
10260 found = TRUE;
10261 } else if ((sscanf(attrib, "t38maxbitrate:%30u", &x) == 1) || (sscanf(attrib, "t38faxmaxrate:%30u", &x) == 1)) {
10262 ast_debug(3, "T38MaxBitRate: %d\n", x);
10263 switch (x) {
10264 case 14400:
10265 p->t38.their_parms.rate = AST_T38_RATE_14400;
10266 break;
10267 case 12000:
10268 p->t38.their_parms.rate = AST_T38_RATE_12000;
10269 break;
10270 case 9600:
10271 p->t38.their_parms.rate = AST_T38_RATE_9600;
10272 break;
10273 case 7200:
10274 p->t38.their_parms.rate = AST_T38_RATE_7200;
10275 break;
10276 case 4800:
10277 p->t38.their_parms.rate = AST_T38_RATE_4800;
10278 break;
10279 case 2400:
10280 p->t38.their_parms.rate = AST_T38_RATE_2400;
10281 break;
10282 }
10283 found = TRUE;
10284 } else if ((sscanf(attrib, "t38faxversion:%30u", &x) == 1)) {
10285 ast_debug(3, "FaxVersion: %u\n", x);
10286 p->t38.their_parms.version = x;
10287 found = TRUE;
10288 } else if ((sscanf(attrib, "t38faxmaxdatagram:%30u", &x) == 1) || (sscanf(attrib, "t38maxdatagram:%30u", &x) == 1)) {
10289
10290 if (((signed int) p->t38_maxdatagram >= 0) && ((unsigned int) p->t38_maxdatagram > x)) {
10291 ast_debug(1, "Overriding T38FaxMaxDatagram '%d' with '%d'\n", x, p->t38_maxdatagram);
10292 x = p->t38_maxdatagram;
10293 }
10294 ast_debug(3, "FaxMaxDatagram: %u\n", x);
10295 ast_udptl_set_far_max_datagram(p->udptl, x);
10296 found = TRUE;
10297 } else if ((strncmp(attrib, "t38faxfillbitremoval", 20) == 0)) {
10298 if (sscanf(attrib, "t38faxfillbitremoval:%30u", &x) == 1) {
10299 ast_debug(3, "FillBitRemoval: %d\n", x);
10300 if (x == 1) {
10301 p->t38.their_parms.fill_bit_removal = TRUE;
10302 }
10303 } else {
10304 ast_debug(3, "FillBitRemoval\n");
10305 p->t38.their_parms.fill_bit_removal = TRUE;
10306 }
10307 found = TRUE;
10308 } else if ((strncmp(attrib, "t38faxtranscodingmmr", 20) == 0)) {
10309 if (sscanf(attrib, "t38faxtranscodingmmr:%30u", &x) == 1) {
10310 ast_debug(3, "Transcoding MMR: %d\n", x);
10311 if (x == 1) {
10312 p->t38.their_parms.transcoding_mmr = TRUE;
10313 }
10314 } else {
10315 ast_debug(3, "Transcoding MMR\n");
10316 p->t38.their_parms.transcoding_mmr = TRUE;
10317 }
10318 found = TRUE;
10319 } else if ((strncmp(attrib, "t38faxtranscodingjbig", 21) == 0)) {
10320 if (sscanf(attrib, "t38faxtranscodingjbig:%30u", &x) == 1) {
10321 ast_debug(3, "Transcoding JBIG: %d\n", x);
10322 if (x == 1) {
10323 p->t38.their_parms.transcoding_jbig = TRUE;
10324 }
10325 } else {
10326 ast_debug(3, "Transcoding JBIG\n");
10327 p->t38.their_parms.transcoding_jbig = TRUE;
10328 }
10329 found = TRUE;
10330 } else if ((sscanf(attrib, "t38faxratemanagement:%255s", s) == 1)) {
10331 ast_debug(3, "RateManagement: %s\n", s);
10332 if (!strcasecmp(s, "localTCF"))
10333 p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_LOCAL_TCF;
10334 else if (!strcasecmp(s, "transferredTCF"))
10335 p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF;
10336 found = TRUE;
10337 } else if ((sscanf(attrib, "t38faxudpec:%255s", s) == 1)) {
10338 ast_debug(3, "UDP EC: %s\n", s);
10339 if (!strcasecmp(s, "t38UDPRedundancy")) {
10340 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
10341 } else if (!strcasecmp(s, "t38UDPFEC")) {
10342 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
10343 } else {
10344 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
10345 }
10346 found = TRUE;
10347 }
10348
10349 return found;
10350 }
10351
10352
10353
10354
10355 static int add_supported_header(struct sip_pvt *pvt, struct sip_request *req)
10356 {
10357 int res;
10358 if (st_get_mode(pvt, 0) != SESSION_TIMER_MODE_REFUSE) {
10359 res = add_header(req, "Supported", "replaces, timer");
10360 } else {
10361 res = add_header(req, "Supported", "replaces");
10362 }
10363 return res;
10364 }
10365
10366
10367 static int add_header(struct sip_request *req, const char *var, const char *value)
10368 {
10369 if (req->headers == SIP_MAX_HEADERS) {
10370 ast_log(LOG_WARNING, "Out of SIP header space\n");
10371 return -1;
10372 }
10373
10374 if (req->lines) {
10375 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
10376 return -1;
10377 }
10378
10379 if (sip_cfg.compactheaders) {
10380 var = find_alias(var, var);
10381 }
10382
10383 ast_str_append(&req->data, 0, "%s: %s\r\n", var, value);
10384 req->header[req->headers] = ast_str_strlen(req->data);
10385
10386 req->headers++;
10387
10388 return 0;
10389 }
10390
10391
10392
10393
10394
10395 static int add_header_max_forwards(struct sip_pvt *dialog, struct sip_request *req)
10396 {
10397 char clen[10];
10398
10399 snprintf(clen, sizeof(clen), "%d", dialog->maxforwards);
10400
10401 return add_header(req, "Max-Forwards", clen);
10402 }
10403
10404
10405 static int finalize_content(struct sip_request *req)
10406 {
10407 char clen[10];
10408
10409 if (req->lines) {
10410 ast_log(LOG_WARNING, "finalize_content() called on a message that has already been finalized\n");
10411 return -1;
10412 }
10413
10414 snprintf(clen, sizeof(clen), "%zd", ast_str_strlen(req->content));
10415 add_header(req, "Content-Length", clen);
10416
10417 if (ast_str_strlen(req->content)) {
10418 ast_str_append(&req->data, 0, "\r\n%s", ast_str_buffer(req->content));
10419 }
10420 req->lines = ast_str_strlen(req->content) ? 1 : 0;
10421 return 0;
10422 }
10423
10424
10425 static int add_content(struct sip_request *req, const char *line)
10426 {
10427 if (req->lines) {
10428 ast_log(LOG_WARNING, "Can't add more content when the content has been finalized\n");
10429 return -1;
10430 }
10431
10432 ast_str_append(&req->content, 0, "%s", line);
10433 return 0;
10434 }
10435
10436
10437 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field)
10438 {
10439 const char *tmp = get_header(orig, field);
10440
10441 if (!ast_strlen_zero(tmp))
10442 return add_header(req, field, tmp);
10443 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
10444 return -1;
10445 }
10446
10447
10448 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field)
10449 {
10450 int start = 0;
10451 int copied = 0;
10452 for (;;) {
10453 const char *tmp = __get_header(orig, field, &start);
10454
10455 if (ast_strlen_zero(tmp))
10456 break;
10457
10458 add_header(req, field, tmp);
10459 copied++;
10460 }
10461 return copied ? 0 : -1;
10462 }
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field)
10473 {
10474 int copied = 0;
10475 int start = 0;
10476
10477 for (;;) {
10478 char new[512];
10479 const char *oh = __get_header(orig, field, &start);
10480
10481 if (ast_strlen_zero(oh))
10482 break;
10483
10484 if (!copied) {
10485 char leftmost[512], *others, *rport;
10486
10487
10488 ast_copy_string(leftmost, oh, sizeof(leftmost));
10489 others = strchr(leftmost, ',');
10490 if (others)
10491 *others++ = '\0';
10492
10493
10494 rport = strstr(leftmost, ";rport");
10495 if (rport && *(rport+6) == '=')
10496 rport = NULL;
10497
10498 if (((ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT)) || (rport && ast_test_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT)))) {
10499
10500 char *end;
10501
10502 rport = strstr(leftmost, ";rport");
10503
10504 if (rport) {
10505 end = strchr(rport + 1, ';');
10506 if (end)
10507 memmove(rport, end, strlen(end) + 1);
10508 else
10509 *rport = '\0';
10510 }
10511
10512
10513 snprintf(new, sizeof(new), "%s;received=%s;rport=%d%s%s",
10514 leftmost, ast_sockaddr_stringify_addr_remote(&p->recv),
10515 ast_sockaddr_port(&p->recv),
10516 others ? "," : "", others ? others : "");
10517 } else {
10518
10519 snprintf(new, sizeof(new), "%s;received=%s%s%s",
10520 leftmost, ast_sockaddr_stringify_addr_remote(&p->recv),
10521 others ? "," : "", others ? others : "");
10522 }
10523 oh = new;
10524 }
10525 add_header(req, field, oh);
10526 copied++;
10527 }
10528 if (!copied) {
10529 ast_log(LOG_NOTICE, "No header field '%s' present to copy\n", field);
10530 return -1;
10531 }
10532 return 0;
10533 }
10534
10535
10536 static void add_route(struct sip_request *req, struct sip_route *route)
10537 {
10538 char r[SIPBUFSIZE*2], *p;
10539 int n, rem = sizeof(r);
10540
10541 if (!route)
10542 return;
10543
10544 p = r;
10545 for (;route ; route = route->next) {
10546 n = strlen(route->hop);
10547 if (rem < n+3)
10548 break;
10549 if (p != r) {
10550 *p++ = ',';
10551 --rem;
10552 }
10553 *p++ = '<';
10554 ast_copy_string(p, route->hop, rem);
10555 p += n;
10556 *p++ = '>';
10557 rem -= (n+2);
10558 }
10559 *p = '\0';
10560 add_header(req, "Route", r);
10561 }
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572 static void set_destination(struct sip_pvt *p, char *uri)
10573 {
10574 char *h, *maddr, hostname[256];
10575 int hn;
10576 int debug=sip_debug_test_pvt(p);
10577 int tls_on = FALSE;
10578
10579 if (debug)
10580 ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
10581
10582
10583 h = strchr(uri, '@');
10584 if (h)
10585 ++h;
10586 else {
10587 h = uri;
10588 if (!strncasecmp(h, "sip:", 4)) {
10589 h += 4;
10590 } else if (!strncasecmp(h, "sips:", 5)) {
10591 h += 5;
10592 tls_on = TRUE;
10593 }
10594 }
10595 hn = strcspn(h, ";>") + 1;
10596 if (hn > sizeof(hostname))
10597 hn = sizeof(hostname);
10598 ast_copy_string(hostname, h, hn);
10599
10600 h += hn - 1;
10601
10602
10603
10604 if (ast_sockaddr_resolve_first_transport(&p->sa, hostname, 0, p->socket.type)) {
10605 ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
10606 return;
10607 }
10608
10609
10610 maddr = strstr(h, "maddr=");
10611 if (maddr) {
10612 int port;
10613
10614 maddr += 6;
10615 hn = strspn(maddr, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
10616 "0123456789-.:[]") + 1;
10617 if (hn > sizeof(hostname))
10618 hn = sizeof(hostname);
10619 ast_copy_string(hostname, maddr, hn);
10620
10621 port = ast_sockaddr_port(&p->sa);
10622
10623
10624
10625 if (ast_sockaddr_resolve_first_transport(&p->sa, hostname, PARSE_PORT_FORBID, p->socket.type)) {
10626 ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
10627 return;
10628 }
10629
10630 ast_sockaddr_set_port(&p->sa, port);
10631 }
10632
10633 if (!ast_sockaddr_port(&p->sa)) {
10634 ast_sockaddr_set_port(&p->sa, tls_on ?
10635 STANDARD_TLS_PORT : STANDARD_SIP_PORT);
10636 }
10637
10638 if (debug) {
10639 ast_verbose("set_destination: set destination to %s\n",
10640 ast_sockaddr_stringify(&p->sa));
10641 }
10642 }
10643
10644
10645 static int init_resp(struct sip_request *resp, const char *msg)
10646 {
10647
10648 memset(resp, 0, sizeof(*resp));
10649 resp->method = SIP_RESPONSE;
10650 if (!(resp->data = ast_str_create(SIP_MIN_PACKET)))
10651 goto e_return;
10652 if (!(resp->content = ast_str_create(SIP_MIN_PACKET)))
10653 goto e_free_data;
10654 resp->header[0] = 0;
10655 ast_str_set(&resp->data, 0, "SIP/2.0 %s\r\n", msg);
10656 resp->headers++;
10657 return 0;
10658
10659 e_free_data:
10660 ast_free(resp->data);
10661 resp->data = NULL;
10662 e_return:
10663 return -1;
10664 }
10665
10666
10667 static int init_req(struct sip_request *req, int sipmethod, const char *recip)
10668 {
10669
10670 memset(req, 0, sizeof(*req));
10671 if (!(req->data = ast_str_create(SIP_MIN_PACKET)))
10672 goto e_return;
10673 if (!(req->content = ast_str_create(SIP_MIN_PACKET)))
10674 goto e_free_data;
10675 req->method = sipmethod;
10676 req->header[0] = 0;
10677 ast_str_set(&req->data, 0, "%s %s SIP/2.0\r\n", sip_methods[sipmethod].text, recip);
10678 req->headers++;
10679 return 0;
10680
10681 e_free_data:
10682 ast_free(req->data);
10683 req->data = NULL;
10684 e_return:
10685 return -1;
10686 }
10687
10688
10689 static void deinit_req(struct sip_request *req)
10690 {
10691 if (req->data) {
10692 ast_free(req->data);
10693 req->data = NULL;
10694 }
10695 if (req->content) {
10696 ast_free(req->content);
10697 req->content = NULL;
10698 }
10699 }
10700
10701
10702
10703 static inline int resp_needs_contact(const char *msg, enum sipmethod method) {
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719 switch (method) {
10720
10721 case SIP_INVITE:
10722 case SIP_UPDATE:
10723 case SIP_SUBSCRIBE:
10724 case SIP_NOTIFY:
10725 if ((msg[0] >= '1' && msg[0] <= '3') || !strncmp(msg, "485", 3))
10726 return 1;
10727 break;
10728
10729
10730 case SIP_REGISTER:
10731 case SIP_OPTIONS:
10732 if (msg[0] == '2' || msg[0] == '3' || !strncmp(msg, "485", 3))
10733 return 1;
10734 break;
10735
10736
10737 case SIP_BYE:
10738 case SIP_PRACK:
10739 case SIP_MESSAGE:
10740 case SIP_PUBLISH:
10741 if (msg[0] == '3' || !strncmp(msg, "485", 3))
10742 return 1;
10743 break;
10744
10745
10746 case SIP_REFER:
10747 if (msg[0] >= '2' && msg[0] <= '6')
10748 return 1;
10749 break;
10750
10751
10752 case SIP_ACK:
10753 case SIP_CANCEL:
10754 case SIP_INFO:
10755 case SIP_PING:
10756 default:
10757 return 0;
10758 }
10759 return 0;
10760 }
10761
10762
10763 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req)
10764 {
10765 char newto[256];
10766 const char *ot;
10767
10768 init_resp(resp, msg);
10769 copy_via_headers(p, resp, req, "Via");
10770 if (msg[0] == '1' || msg[0] == '2')
10771 copy_all_header(resp, req, "Record-Route");
10772 copy_header(resp, req, "From");
10773 ot = get_header(req, "To");
10774 if (!strcasestr(ot, "tag=") && strncmp(msg, "100", 3)) {
10775
10776
10777 if (!ast_strlen_zero(p->theirtag) && ast_test_flag(&p->flags[0], SIP_OUTGOING))
10778 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
10779 else if (p->tag && !ast_test_flag(&p->flags[0], SIP_OUTGOING))
10780 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
10781 else
10782 ast_copy_string(newto, ot, sizeof(newto));
10783 ot = newto;
10784 }
10785 add_header(resp, "To", ot);
10786 copy_header(resp, req, "Call-ID");
10787 copy_header(resp, req, "CSeq");
10788 if (!ast_strlen_zero(global_useragent))
10789 add_header(resp, "Server", global_useragent);
10790 add_header(resp, "Allow", ALLOWED_METHODS);
10791 add_supported_header(p, resp);
10792
10793
10794 if (p->method == SIP_INVITE && p->stimer && p->stimer->st_active == TRUE) {
10795 char se_hdr[256];
10796 snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval,
10797 p->stimer->st_ref == SESSION_TIMER_REFRESHER_US ? "uas" : "uac");
10798 add_header(resp, "Session-Expires", se_hdr);
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809 if (p->stimer->st_ref == SESSION_TIMER_REFRESHER_THEM ||
10810 (p->stimer->st_ref == SESSION_TIMER_REFRESHER_US &&
10811 p->stimer->st_active_peer_ua == TRUE)) {
10812 resp->reqsipoptions |= SIP_OPT_TIMER;
10813 }
10814 }
10815
10816 if (msg[0] == '2' && (p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER || p->method == SIP_PUBLISH)) {
10817
10818
10819 char tmp[256];
10820
10821 snprintf(tmp, sizeof(tmp), "%d", p->expiry);
10822 add_header(resp, "Expires", tmp);
10823 if (p->expiry) {
10824 char contact[SIPBUFSIZE];
10825 const char *contact_uri = p->method == SIP_SUBSCRIBE ? p->our_contact : p->fullcontact;
10826 char *brackets = strchr(contact_uri, '<');
10827 snprintf(contact, sizeof(contact), "%s%s%s;expires=%d", brackets ? "" : "<", contact_uri, brackets ? "" : ">", p->expiry);
10828 add_header(resp, "Contact", contact);
10829 }
10830 } else if (!ast_strlen_zero(p->our_contact) && resp_needs_contact(msg, p->method)) {
10831 add_header(resp, "Contact", p->our_contact);
10832 }
10833
10834 if (!ast_strlen_zero(p->url)) {
10835 add_header(resp, "Access-URL", p->url);
10836 ast_string_field_set(p, url, NULL);
10837 }
10838
10839
10840
10841
10842
10843
10844
10845 p->sa = p->recv;
10846
10847 if (process_via(p, req)) {
10848 ast_log(LOG_WARNING, "error processing via header, will send response to originating address\n");
10849 }
10850
10851 return 0;
10852 }
10853
10854
10855 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, uint32_t seqno, int newbranch)
10856 {
10857 struct sip_request *orig = &p->initreq;
10858 char stripped[80];
10859 char tmp[80];
10860 char newto[256];
10861 const char *c;
10862 const char *ot, *of;
10863 int is_strict = FALSE;
10864 int is_outbound = ast_test_flag(&p->flags[0], SIP_OUTGOING);
10865
10866 snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", sip_methods[sipmethod].text);
10867
10868 if (!seqno) {
10869 p->ocseq++;
10870 seqno = p->ocseq;
10871 }
10872
10873
10874 if (sipmethod == SIP_CANCEL) {
10875 p->branch = p->invite_branch;
10876 build_via(p);
10877 } else if (newbranch && (sipmethod == SIP_INVITE)) {
10878 p->branch ^= ast_random();
10879 p->invite_branch = p->branch;
10880 build_via(p);
10881 } else if (newbranch) {
10882 p->branch ^= ast_random();
10883 build_via(p);
10884 }
10885
10886
10887 if (p->route && !ast_strlen_zero(p->route->hop) && strstr(p->route->hop, ";lr") == NULL) {
10888 is_strict = TRUE;
10889 if (sipdebug)
10890 ast_debug(1, "Strict routing enforced for session %s\n", p->callid);
10891 }
10892
10893 if (sipmethod == SIP_CANCEL)
10894 c = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
10895 else if (sipmethod == SIP_ACK) {
10896
10897
10898 if (!ast_strlen_zero(p->okcontacturi))
10899 c = is_strict ? p->route->hop : p->okcontacturi;
10900 else
10901 c = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
10902 } else if (!ast_strlen_zero(p->okcontacturi))
10903 c = is_strict ? p->route->hop : p->okcontacturi;
10904 else if (!ast_strlen_zero(p->uri))
10905 c = p->uri;
10906 else {
10907 char *n;
10908
10909 ast_copy_string(stripped, get_header(orig, is_outbound ? "To" : "From"),
10910 sizeof(stripped));
10911 n = get_in_brackets(stripped);
10912 c = remove_uri_parameters(n);
10913 }
10914 init_req(req, sipmethod, c);
10915
10916 snprintf(tmp, sizeof(tmp), "%u %s", seqno, sip_methods[sipmethod].text);
10917
10918 add_header(req, "Via", p->via);
10919
10920
10921
10922
10923
10924 if (p->route &&
10925 !(sipmethod == SIP_CANCEL ||
10926 (sipmethod == SIP_ACK && (p->invitestate == INV_COMPLETED || p->invitestate == INV_CANCELLED)))) {
10927 set_destination(p, p->route->hop);
10928 add_route(req, is_strict ? p->route->next : p->route);
10929 }
10930 add_header_max_forwards(p, req);
10931
10932 ot = get_header(orig, "To");
10933 of = get_header(orig, "From");
10934
10935
10936
10937 if (!strcasestr(ot, "tag=") && sipmethod != SIP_CANCEL) {
10938
10939
10940 if (is_outbound && !ast_strlen_zero(p->theirtag))
10941 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
10942 else if (!is_outbound)
10943 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
10944 else
10945 snprintf(newto, sizeof(newto), "%s", ot);
10946 ot = newto;
10947 }
10948
10949 if (is_outbound) {
10950 add_header(req, "From", of);
10951 add_header(req, "To", ot);
10952 } else {
10953 add_header(req, "From", ot);
10954 add_header(req, "To", of);
10955 }
10956
10957 if (sipmethod != SIP_BYE && sipmethod != SIP_CANCEL && sipmethod != SIP_MESSAGE)
10958 add_header(req, "Contact", p->our_contact);
10959
10960 copy_header(req, orig, "Call-ID");
10961 add_header(req, "CSeq", tmp);
10962
10963 if (!ast_strlen_zero(global_useragent))
10964 add_header(req, "User-Agent", global_useragent);
10965
10966 if (!ast_strlen_zero(p->url)) {
10967 add_header(req, "Access-URL", p->url);
10968 ast_string_field_set(p, url, NULL);
10969 }
10970
10971
10972
10973
10974
10975
10976
10977
10978 if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE
10979 && sipmethod == SIP_INVITE) {
10980 char se_hdr[256];
10981 snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval,
10982 p->stimer->st_ref == SESSION_TIMER_REFRESHER_US ? "uac" : "uas");
10983 add_header(req, "Session-Expires", se_hdr);
10984 snprintf(se_hdr, sizeof(se_hdr), "%d", st_get_se(p, FALSE));
10985 add_header(req, "Min-SE", se_hdr);
10986 }
10987
10988 return 0;
10989 }
10990
10991
10992 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
10993 {
10994 struct sip_request resp;
10995 uint32_t seqno = 0;
10996
10997 if (reliable && (sscanf(get_header(req, "CSeq"), "%30u ", &seqno) != 1)) {
10998 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
10999 return -1;
11000 }
11001 respprep(&resp, p, msg, req);
11002
11003 if (ast_test_flag(&p->flags[0], SIP_SENDRPID)
11004 && ast_test_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND)
11005 && (!strncmp(msg, "180", 3) || !strncmp(msg, "183", 3))) {
11006 ast_clear_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND);
11007 add_rpid(&resp, p);
11008 }
11009 if (ast_test_flag(&p->flags[0], SIP_OFFER_CC)) {
11010 add_cc_call_info_to_response(p, &resp);
11011 }
11012
11013
11014 if (!strncmp(msg, "302", 3)) {
11015 add_diversion_header(&resp, p);
11016 }
11017
11018
11019
11020 if (p->method == SIP_INVITE && msg[0] != '1') {
11021 char buf[20];
11022
11023 if (ast_test_flag(&p->flags[1], SIP_PAGE2_Q850_REASON)) {
11024 int hangupcause = 0;
11025
11026 if (p->owner && p->owner->hangupcause) {
11027 hangupcause = p->owner->hangupcause;
11028 } else if (p->hangupcause) {
11029 hangupcause = p->hangupcause;
11030 } else {
11031 int respcode;
11032 if (sscanf(msg, "%30d ", &respcode))
11033 hangupcause = hangup_sip2cause(respcode);
11034 }
11035
11036 if (hangupcause) {
11037 sprintf(buf, "Q.850;cause=%i", hangupcause & 0x7f);
11038 add_header(&resp, "Reason", buf);
11039 }
11040 }
11041
11042 if (p->owner && p->owner->hangupcause) {
11043 add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->owner->hangupcause));
11044 snprintf(buf, sizeof(buf), "%d", p->owner->hangupcause);
11045 add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
11046 }
11047 }
11048 return send_response(p, &resp, reliable, seqno);
11049 }
11050
11051 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)
11052 {
11053 struct sip_request resp;
11054
11055 if (need_new_etag) {
11056 create_new_sip_etag(esc_entry, 1);
11057 }
11058 respprep(&resp, p, msg, req);
11059 add_header(&resp, "SIP-ETag", esc_entry->entity_tag);
11060
11061 return send_response(p, &resp, 0, 0);
11062 }
11063
11064 static int temp_pvt_init(void *data)
11065 {
11066 struct sip_pvt *p = data;
11067
11068 p->do_history = 0;
11069 return ast_string_field_init(p, 512);
11070 }
11071
11072 static void temp_pvt_cleanup(void *data)
11073 {
11074 struct sip_pvt *p = data;
11075
11076 ast_string_field_free_memory(p);
11077
11078 ast_free(data);
11079 }
11080
11081
11082 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)
11083 {
11084 struct sip_pvt *p = NULL;
11085
11086 if (!(p = ast_threadstorage_get(&ts_temp_pvt, sizeof(*p)))) {
11087 ast_log(LOG_ERROR, "Failed to get temporary pvt\n");
11088 return -1;
11089 }
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099 p->method = intended_method;
11100
11101 if (!addr) {
11102 ast_sockaddr_copy(&p->ourip, &internip);
11103 } else {
11104 ast_sockaddr_copy(&p->sa, addr);
11105 ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
11106 }
11107
11108 p->branch = ast_random();
11109 make_our_tag(p);
11110 p->ocseq = INITIAL_CSEQ;
11111
11112 if (useglobal_nat && addr) {
11113 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT_FORCE_RPORT);
11114 ast_sockaddr_copy(&p->recv, addr);
11115 do_setnat(p);
11116 }
11117
11118 ast_string_field_set(p, fromdomain, default_fromdomain);
11119 p->fromdomainport = default_fromdomainport;
11120 build_via(p);
11121 ast_string_field_set(p, callid, callid);
11122
11123 copy_socket_data(&p->socket, &req->socket);
11124
11125
11126 __transmit_response(p, msg, req, XMIT_UNRELIABLE);
11127
11128
11129 ast_string_field_init(p, 0);
11130
11131 return 0;
11132 }
11133
11134
11135 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req)
11136 {
11137 return __transmit_response(p, msg, req, XMIT_UNRELIABLE);
11138 }
11139
11140
11141 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported)
11142 {
11143 struct sip_request resp;
11144 respprep(&resp, p, msg, req);
11145 append_date(&resp);
11146 add_header(&resp, "Unsupported", unsupported);
11147 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
11148 }
11149
11150
11151 static int transmit_response_with_minse(struct sip_pvt *p, const char *msg, const struct sip_request *req, int minse_int)
11152 {
11153 struct sip_request resp;
11154 char minse_str[20];
11155
11156 respprep(&resp, p, msg, req);
11157 append_date(&resp);
11158
11159 snprintf(minse_str, sizeof(minse_str), "%d", minse_int);
11160 add_header(&resp, "Min-SE", minse_str);
11161 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
11162 }
11163
11164
11165
11166
11167
11168 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req)
11169 {
11170 return __transmit_response(p, msg, req, req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL);
11171 }
11172
11173
11174 static void append_date(struct sip_request *req)
11175 {
11176 char tmpdat[256];
11177 struct tm tm;
11178 time_t t = time(NULL);
11179
11180 gmtime_r(&t, &tm);
11181 strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
11182 add_header(req, "Date", tmpdat);
11183 }
11184
11185
11186 static int transmit_response_with_retry_after(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *seconds)
11187 {
11188 struct sip_request resp;
11189 respprep(&resp, p, msg, req);
11190 add_header(&resp, "Retry-After", seconds);
11191 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
11192 }
11193
11194
11195 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req)
11196 {
11197 struct sip_request resp;
11198 respprep(&resp, p, msg, req);
11199 append_date(&resp);
11200 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
11201 }
11202
11203
11204 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
11205 {
11206 struct sip_request resp;
11207 respprep(&resp, p, msg, req);
11208 add_header(&resp, "Accept", "application/sdp");
11209 return send_response(p, &resp, reliable, 0);
11210 }
11211
11212
11213 static int transmit_response_with_minexpires(struct sip_pvt *p, const char *msg, const struct sip_request *req)
11214 {
11215 struct sip_request resp;
11216 char tmp[32];
11217
11218 snprintf(tmp, sizeof(tmp), "%d", min_expiry);
11219 respprep(&resp, p, msg, req);
11220 add_header(&resp, "Min-Expires", tmp);
11221 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
11222 }
11223
11224
11225 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)
11226 {
11227 struct sip_request resp;
11228 char tmp[512];
11229 uint32_t seqno = 0;
11230
11231 if (reliable && (sscanf(get_header(req, "CSeq"), "%30u ", &seqno) != 1)) {
11232 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
11233 return -1;
11234 }
11235
11236 get_realm(p, req);
11237
11238
11239
11240 snprintf(tmp, sizeof(tmp), "Digest algorithm=MD5, realm=\"%s\", nonce=\"%s\"%s", p->realm, randdata, stale ? ", stale=true" : "");
11241 respprep(&resp, p, msg, req);
11242 add_header(&resp, header, tmp);
11243 append_history(p, "AuthChal", "Auth challenge sent for %s - nc %d", p->username, p->noncecount);
11244 return send_response(p, &resp, reliable, seqno);
11245 }
11246
11247
11248
11249
11250
11251
11252
11253 static int get_domain(const char *str, char *domain, int len)
11254 {
11255 char tmpf[256];
11256 char *a, *from;
11257
11258 *domain = '\0';
11259 ast_copy_string(tmpf, str, sizeof(tmpf));
11260 from = get_in_brackets(tmpf);
11261 if (!ast_strlen_zero(from)) {
11262 if (strncasecmp(from, "sip:", 4)) {
11263 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", from);
11264 return -1;
11265 }
11266 from += 4;
11267 } else
11268 from = NULL;
11269
11270 if (from) {
11271 int bracket = 0;
11272
11273
11274 if ((a = strchr(from, ';')))
11275 *a = '\0';
11276
11277 for (a = from; *a != '\0'; ++a) {
11278 if (*a == ':' && bracket == 0) {
11279 *a = '\0';
11280 break;
11281 } else if (*a == '[') {
11282 ++bracket;
11283 } else if (*a == ']') {
11284 --bracket;
11285 }
11286 }
11287 if ((a = strchr(from, '@'))) {
11288 *a = '\0';
11289 ast_copy_string(domain, a + 1, len);
11290 } else
11291 ast_copy_string(domain, from, len);
11292 }
11293
11294 return ast_strlen_zero(domain);
11295 }
11296
11297
11298
11299
11300
11301 static void get_realm(struct sip_pvt *p, const struct sip_request *req)
11302 {
11303 char domain[MAXHOSTNAMELEN];
11304
11305 if (!ast_strlen_zero(p->realm))
11306 return;
11307
11308 if (sip_cfg.domainsasrealm &&
11309 !AST_LIST_EMPTY(&domain_list))
11310 {
11311
11312 if (!get_domain(get_header(req, "From"), domain, sizeof(domain))) {
11313 if (check_sip_domain(domain, NULL, 0)) {
11314 ast_string_field_set(p, realm, domain);
11315 return;
11316 }
11317 }
11318
11319 if (!get_domain(get_header(req, "To"), domain, sizeof(domain))) {
11320 if (check_sip_domain(domain, NULL, 0)) {
11321 ast_string_field_set(p, realm, domain);
11322 return;
11323 }
11324 }
11325 }
11326
11327
11328 ast_string_field_set(p, realm, sip_cfg.realm);
11329 }
11330
11331
11332
11333
11334
11335
11336
11337
11338 static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp)
11339 {
11340 int res;
11341
11342 if (!(res = with_sdp ? transmit_response_with_sdp(p, msg, req, XMIT_UNRELIABLE, FALSE, FALSE) : transmit_response(p, msg, req))) {
11343 p->last_provisional = msg;
11344 update_provisional_keepalive(p, with_sdp);
11345 }
11346
11347 return res;
11348 }
11349
11350
11351 static int add_text(struct sip_request *req, const char *text)
11352 {
11353
11354 add_header(req, "Content-Type", "text/plain;charset=UTF-8");
11355 add_content(req, text);
11356 return 0;
11357 }
11358
11359
11360
11361
11362
11363 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode)
11364 {
11365 char tmp[256];
11366 int event;
11367 if (mode) {
11368
11369 if ('0' <= digit && digit <= '9') {
11370 event = digit - '0';
11371 } else if (digit == '*') {
11372 event = 10;
11373 } else if (digit == '#') {
11374 event = 11;
11375 } else if ('A' <= digit && digit <= 'D') {
11376 event = 12 + digit - 'A';
11377 } else if ('a' <= digit && digit <= 'd') {
11378 event = 12 + digit - 'a';
11379 } else {
11380
11381 event = 0;
11382 }
11383 snprintf(tmp, sizeof(tmp), "%d\r\n", event);
11384 add_header(req, "Content-Type", "application/dtmf");
11385 add_content(req, tmp);
11386 } else {
11387
11388 snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=%u\r\n", digit, duration);
11389 add_header(req, "Content-Type", "application/dtmf-relay");
11390 add_content(req, tmp);
11391 }
11392 return 0;
11393 }
11394
11395
11396
11397
11398
11399 static int add_rpid(struct sip_request *req, struct sip_pvt *p)
11400 {
11401 struct ast_str *tmp = ast_str_alloca(256);
11402 char tmp2[256];
11403 char *lid_num;
11404 char *lid_name;
11405 int lid_pres;
11406 const char *fromdomain;
11407 const char *privacy = NULL;
11408 const char *screen = NULL;
11409 const char *anonymous_string = "\"Anonymous\" <sip:anonymous@anonymous.invalid>";
11410
11411 if (!ast_test_flag(&p->flags[0], SIP_SENDRPID)) {
11412 return 0;
11413 }
11414
11415 if (!p->owner) {
11416 return 0;
11417 }
11418 lid_num = S_COR(p->owner->connected.id.number.valid,
11419 p->owner->connected.id.number.str,
11420 NULL);
11421 if (!lid_num) {
11422 return 0;
11423 }
11424 lid_name = S_COR(p->owner->connected.id.name.valid,
11425 p->owner->connected.id.name.str,
11426 NULL);
11427 if (!lid_name) {
11428 lid_name = lid_num;
11429 }
11430 lid_pres = ast_party_id_presentation(&p->owner->connected.id);
11431
11432 if (((lid_pres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) &&
11433 (ast_test_flag(&p->flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND) == SIP_PAGE2_TRUST_ID_OUTBOUND_NO)) {
11434
11435 return 0;
11436 }
11437
11438 fromdomain = p->fromdomain;
11439 if (!fromdomain ||
11440 ((ast_test_flag(&p->flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND) == SIP_PAGE2_TRUST_ID_OUTBOUND_YES) &&
11441 !strcmp("anonymous.invalid", fromdomain))) {
11442
11443
11444 fromdomain = ast_sockaddr_stringify_host_remote(&p->ourip);
11445 }
11446
11447 lid_num = ast_uri_encode(lid_num, tmp2, sizeof(tmp2), 0);
11448
11449 if (ast_test_flag(&p->flags[0], SIP_SENDRPID_PAI)) {
11450 if (ast_test_flag(&p->flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND) != SIP_PAGE2_TRUST_ID_OUTBOUND_LEGACY) {
11451
11452
11453 ast_str_set(&tmp, -1, "\"%s\" <sip:%s@%s>", lid_name, lid_num, fromdomain);
11454 if ((lid_pres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
11455 add_header(req, "Privacy", "id");
11456 }
11457 } else {
11458
11459
11460 if ((lid_pres & AST_PRES_RESTRICTION) == AST_PRES_ALLOWED) {
11461 ast_str_set(&tmp, -1, "\"%s\" <sip:%s@%s>", lid_name, lid_num, fromdomain);
11462 } else {
11463 ast_str_set(&tmp, -1, "%s", anonymous_string);
11464 }
11465 }
11466 add_header(req, "P-Asserted-Identity", ast_str_buffer(tmp));
11467 } else {
11468 ast_str_set(&tmp, -1, "\"%s\" <sip:%s@%s>;party=%s", lid_name, lid_num, fromdomain, p->outgoing_call ? "calling" : "called");
11469
11470 switch (lid_pres) {
11471 case AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED:
11472 case AST_PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN:
11473 privacy = "off";
11474 screen = "no";
11475 break;
11476 case AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN:
11477 case AST_PRES_ALLOWED_NETWORK_NUMBER:
11478 privacy = "off";
11479 screen = "yes";
11480 break;
11481 case AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED:
11482 case AST_PRES_PROHIB_USER_NUMBER_FAILED_SCREEN:
11483 privacy = "full";
11484 screen = "no";
11485 break;
11486 case AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN:
11487 case AST_PRES_PROHIB_NETWORK_NUMBER:
11488 privacy = "full";
11489 screen = "yes";
11490 break;
11491 case AST_PRES_NUMBER_NOT_AVAILABLE:
11492 break;
11493 default:
11494 if ((lid_pres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
11495 privacy = "full";
11496 }
11497 else
11498 privacy = "off";
11499 screen = "no";
11500 break;
11501 }
11502
11503 if (!ast_strlen_zero(privacy) && !ast_strlen_zero(screen)) {
11504 ast_str_append(&tmp, -1, ";privacy=%s;screen=%s", privacy, screen);
11505 }
11506
11507 add_header(req, "Remote-Party-ID", ast_str_buffer(tmp));
11508 }
11509 return 0;
11510 }
11511
11512
11513
11514 static int add_vidupdate(struct sip_request *req)
11515 {
11516 const char *xml_is_a_huge_waste_of_space =
11517 "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
11518 " <media_control>\r\n"
11519 " <vc_primitive>\r\n"
11520 " <to_encoder>\r\n"
11521 " <picture_fast_update>\r\n"
11522 " </picture_fast_update>\r\n"
11523 " </to_encoder>\r\n"
11524 " </vc_primitive>\r\n"
11525 " </media_control>\r\n";
11526 add_header(req, "Content-Type", "application/media_control+xml");
11527 add_content(req, xml_is_a_huge_waste_of_space);
11528 return 0;
11529 }
11530
11531
11532 static void add_codec_to_sdp(const struct sip_pvt *p, format_t codec,
11533 struct ast_str **m_buf, struct ast_str **a_buf,
11534 int debug, int *min_packet_size)
11535 {
11536 int rtp_code;
11537 struct ast_format_list fmt;
11538
11539
11540 if (debug)
11541 ast_verbose("Adding codec 0x%" PRIx64 " (%s) to SDP\n", codec, ast_getformatname(codec));
11542 if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->rtp), 1, codec)) == -1)
11543 return;
11544
11545 if (p->rtp) {
11546 struct ast_codec_pref *pref = &ast_rtp_instance_get_codecs(p->rtp)->pref;
11547 fmt = ast_codec_pref_getsize(pref, codec);
11548 } else
11549 return;
11550 ast_str_append(m_buf, 0, " %d", rtp_code);
11551 ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
11552 ast_rtp_lookup_mime_subtype2(1, codec,
11553 ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0),
11554 ast_rtp_lookup_sample_rate2(1, codec));
11555
11556 switch (codec) {
11557 case AST_FORMAT_G729A:
11558
11559 ast_str_append(a_buf, 0, "a=fmtp:%d annexb=no\r\n", rtp_code);
11560 break;
11561 case AST_FORMAT_G723_1:
11562
11563 ast_str_append(a_buf, 0, "a=fmtp:%d annexa=no\r\n", rtp_code);
11564 break;
11565 case AST_FORMAT_ILBC:
11566
11567 ast_str_append(a_buf, 0, "a=fmtp:%d mode=%d\r\n", rtp_code, fmt.cur_ms);
11568 break;
11569 case AST_FORMAT_SIREN7:
11570
11571 ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=32000\r\n", rtp_code);
11572 break;
11573 case AST_FORMAT_SIREN14:
11574
11575 ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=48000\r\n", rtp_code);
11576 break;
11577 case AST_FORMAT_G719:
11578
11579 ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=64000\r\n", rtp_code);
11580 break;
11581 }
11582
11583 if (fmt.cur_ms && (fmt.cur_ms < *min_packet_size))
11584 *min_packet_size = fmt.cur_ms;
11585
11586
11587 if ((*min_packet_size)==0 && fmt.cur_ms)
11588 *min_packet_size = fmt.cur_ms;
11589 }
11590
11591
11592
11593 static void add_vcodec_to_sdp(const struct sip_pvt *p, format_t codec,
11594 struct ast_str **m_buf, struct ast_str **a_buf,
11595 int debug, int *min_packet_size)
11596 {
11597 int rtp_code;
11598
11599 if (!p->vrtp)
11600 return;
11601
11602 if (debug)
11603 ast_verbose("Adding video codec 0x%" PRIx64 " (%s) to SDP\n", codec, ast_getformatname(codec));
11604
11605 if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->vrtp), 1, codec)) == -1)
11606 return;
11607
11608 ast_str_append(m_buf, 0, " %d", rtp_code);
11609 ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
11610 ast_rtp_lookup_mime_subtype2(1, codec, 0),
11611 ast_rtp_lookup_sample_rate2(1, codec));
11612
11613 }
11614
11615
11616 static void add_tcodec_to_sdp(const struct sip_pvt *p, int codec,
11617 struct ast_str **m_buf, struct ast_str **a_buf,
11618 int debug, int *min_packet_size)
11619 {
11620 int rtp_code;
11621
11622 if (!p->trtp)
11623 return;
11624
11625 if (debug)
11626 ast_verbose("Adding text codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
11627
11628 if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->trtp), 1, codec)) == -1)
11629 return;
11630
11631 ast_str_append(m_buf, 0, " %d", rtp_code);
11632 ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
11633 ast_rtp_lookup_mime_subtype2(1, codec, 0),
11634 ast_rtp_lookup_sample_rate2(1, codec));
11635
11636
11637 if (codec == AST_FORMAT_T140RED) {
11638 int t140code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->trtp), 1, AST_FORMAT_T140);
11639 ast_str_append(a_buf, 0, "a=fmtp:%d %d/%d/%d\r\n", rtp_code,
11640 t140code,
11641 t140code,
11642 t140code);
11643
11644 }
11645 }
11646
11647
11648
11649 static unsigned int t38_get_rate(enum ast_control_t38_rate rate)
11650 {
11651 switch (rate) {
11652 case AST_T38_RATE_2400:
11653 return 2400;
11654 case AST_T38_RATE_4800:
11655 return 4800;
11656 case AST_T38_RATE_7200:
11657 return 7200;
11658 case AST_T38_RATE_9600:
11659 return 9600;
11660 case AST_T38_RATE_12000:
11661 return 12000;
11662 case AST_T38_RATE_14400:
11663 return 14400;
11664 default:
11665 return 0;
11666 }
11667 }
11668
11669
11670 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
11671 struct ast_str **m_buf, struct ast_str **a_buf,
11672 int debug)
11673 {
11674 int rtp_code;
11675
11676 if (debug)
11677 ast_verbose("Adding non-codec 0x%x (%s) to SDP\n", format, ast_rtp_lookup_mime_subtype2(0, format, 0));
11678 if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->rtp), 0, format)) == -1)
11679 return;
11680
11681 ast_str_append(m_buf, 0, " %d", rtp_code);
11682 ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
11683 ast_rtp_lookup_mime_subtype2(0, format, 0),
11684 ast_rtp_lookup_sample_rate2(0, format));
11685 if (format == AST_RTP_DTMF)
11686 ast_str_append(a_buf, 0, "a=fmtp:%d 0-16\r\n", rtp_code);
11687 }
11688
11689
11690
11691
11692 static void get_our_media_address(struct sip_pvt *p, int needvideo, int needtext,
11693 struct ast_sockaddr *addr, struct ast_sockaddr *vaddr,
11694 struct ast_sockaddr *taddr, struct ast_sockaddr *dest,
11695 struct ast_sockaddr *vdest, struct ast_sockaddr *tdest)
11696 {
11697 int use_externip = 0;
11698
11699
11700 ast_rtp_instance_get_local_address(p->rtp, addr);
11701 if (p->vrtp) {
11702 ast_rtp_instance_get_local_address(p->vrtp, vaddr);
11703 }
11704 if (p->trtp) {
11705 ast_rtp_instance_get_local_address(p->trtp, taddr);
11706 }
11707
11708
11709
11710
11711 use_externip = ast_sockaddr_cmp_addr(&p->ourip, addr);
11712
11713
11714
11715 if (!ast_sockaddr_isnull(&p->redirip)) {
11716 ast_sockaddr_copy(dest, &p->redirip);
11717 } else {
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729 ast_sockaddr_copy(dest,
11730 !ast_sockaddr_isnull(&media_address) ? &media_address :
11731 !ast_sockaddr_is_any(addr) && !use_externip ? addr :
11732 &p->ourip);
11733 ast_sockaddr_set_port(dest, ast_sockaddr_port(addr));
11734 }
11735
11736 if (needvideo) {
11737
11738 if (!ast_sockaddr_isnull(&p->vredirip)) {
11739 ast_sockaddr_copy(vdest, &p->vredirip);
11740 } else {
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752 ast_sockaddr_copy(vdest,
11753 !ast_sockaddr_isnull(&media_address) ? &media_address :
11754 !ast_sockaddr_is_any(vaddr) && !use_externip ? vaddr :
11755 &p->ourip);
11756 ast_sockaddr_set_port(vdest, ast_sockaddr_port(vaddr));
11757 }
11758 }
11759
11760 if (needtext) {
11761
11762 if (!ast_sockaddr_isnull(&p->tredirip)) {
11763 ast_sockaddr_copy(tdest, &p->tredirip);
11764 } else {
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776 ast_sockaddr_copy(tdest,
11777 !ast_sockaddr_isnull(&media_address) ? &media_address :
11778 !ast_sockaddr_is_any(taddr) && !use_externip ? taddr :
11779 &p->ourip);
11780 ast_sockaddr_set_port(tdest, ast_sockaddr_port(taddr));
11781 }
11782 }
11783 }
11784
11785 static void get_crypto_attrib(struct sip_srtp *srtp, const char **a_crypto)
11786 {
11787
11788 if (srtp) {
11789 if (!srtp->crypto) {
11790 srtp->crypto = sdp_crypto_setup();
11791 }
11792 if (srtp->crypto && (sdp_crypto_offer(srtp->crypto) >= 0)) {
11793 *a_crypto = sdp_crypto_attrib(srtp->crypto);
11794 }
11795
11796 if (!*a_crypto) {
11797 ast_log(LOG_WARNING, "No SRTP key management enabled\n");
11798 }
11799 }
11800 }
11801
11802
11803
11804
11805
11806
11807
11808 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38)
11809 {
11810 format_t alreadysent = 0;
11811 int doing_directmedia = FALSE;
11812
11813 struct ast_sockaddr addr = { {0,} };
11814 struct ast_sockaddr vaddr = { {0,} };
11815 struct ast_sockaddr taddr = { {0,} };
11816 struct ast_sockaddr udptladdr = { {0,} };
11817 struct ast_sockaddr dest = { {0,} };
11818 struct ast_sockaddr vdest = { {0,} };
11819 struct ast_sockaddr tdest = { {0,} };
11820 struct ast_sockaddr udptldest = { {0,} };
11821
11822
11823 char *version = "v=0\r\n";
11824 char subject[256];
11825 char owner[256];
11826 char connection[256];
11827 char *session_time = "t=0 0\r\n";
11828 char bandwidth[256] = "";
11829 char *hold = "";
11830 struct ast_str *m_audio = ast_str_alloca(256);
11831 struct ast_str *m_video = ast_str_alloca(256);
11832 struct ast_str *m_text = ast_str_alloca(256);
11833 struct ast_str *m_modem = ast_str_alloca(256);
11834 struct ast_str *a_audio = ast_str_alloca(1024);
11835 struct ast_str *a_video = ast_str_alloca(1024);
11836 struct ast_str *a_text = ast_str_alloca(1024);
11837 struct ast_str *a_modem = ast_str_alloca(1024);
11838 const char *a_crypto = NULL;
11839 const char *v_a_crypto = NULL;
11840 const char *t_a_crypto = NULL;
11841
11842 format_t x;
11843 format_t capability = 0;
11844 int needaudio = FALSE;
11845 int needvideo = FALSE;
11846 int needtext = FALSE;
11847 int debug = sip_debug_test_pvt(p);
11848 int min_audio_packet_size = 0;
11849 int min_video_packet_size = 0;
11850 int min_text_packet_size = 0;
11851
11852 char codecbuf[SIPBUFSIZE];
11853 char buf[SIPBUFSIZE];
11854 char dummy_answer[256];
11855
11856
11857 snprintf(subject, sizeof(subject), "s=%s\r\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
11858
11859 if (!p->rtp) {
11860 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
11861 return AST_FAILURE;
11862 }
11863
11864
11865
11866
11867 if (!p->sessionid) {
11868 p->sessionid = (int)ast_random();
11869 p->sessionversion = p->sessionid;
11870 } else {
11871 if (oldsdp == FALSE)
11872 p->sessionversion++;
11873 }
11874
11875 if (add_audio) {
11876 doing_directmedia = (!ast_sockaddr_isnull(&p->redirip) && p->redircodecs) ? TRUE : FALSE;
11877
11878 if ((p->jointcapability & AST_FORMAT_VIDEO_MASK) && !p->novideo) {
11879 if (doing_directmedia && !(p->jointcapability & AST_FORMAT_VIDEO_MASK & p->redircodecs)) {
11880 ast_debug(2, "This call needs video offers, but caller probably did not offer it!\n");
11881 } else if (p->vrtp) {
11882 needvideo = TRUE;
11883 ast_debug(2, "This call needs video offers!\n");
11884 } else {
11885 ast_debug(2, "This call needs video offers, but there's no video support enabled!\n");
11886 }
11887 }
11888
11889 if ((p->jointcapability & AST_FORMAT_TEXT_MASK) && !p->notext) {
11890 if (sipdebug_text)
11891 ast_verbose("We think we can do text\n");
11892 if (p->trtp) {
11893 if (sipdebug_text) {
11894 ast_verbose("And we have a text rtp object\n");
11895 }
11896 needtext = TRUE;
11897 ast_debug(2, "This call needs text offers! \n");
11898 } else {
11899 ast_debug(2, "This call needs text offers, but there's no text support enabled ! \n");
11900 }
11901 }
11902 }
11903
11904 get_our_media_address(p, needvideo, needtext, &addr, &vaddr, &taddr, &dest, &vdest, &tdest);
11905
11906 snprintf(owner, sizeof(owner), "o=%s %d %d IN %s %s\r\n",
11907 ast_strlen_zero(global_sdpowner) ? "-" : global_sdpowner,
11908 p->sessionid, p->sessionversion,
11909 (ast_sockaddr_is_ipv6(&dest) && !ast_sockaddr_is_ipv4_mapped(&dest)) ?
11910 "IP6" : "IP4",
11911 ast_sockaddr_stringify_addr_remote(&dest));
11912
11913 snprintf(connection, sizeof(connection), "c=IN %s %s\r\n",
11914 (ast_sockaddr_is_ipv6(&dest) && !ast_sockaddr_is_ipv4_mapped(&dest)) ?
11915 "IP6" : "IP4",
11916 ast_sockaddr_stringify_addr_remote(&dest));
11917
11918 if (add_audio) {
11919 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_ONEDIR) {
11920 hold = "a=recvonly\r\n";
11921 doing_directmedia = FALSE;
11922 } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_INACTIVE) {
11923 hold = "a=inactive\r\n";
11924 doing_directmedia = FALSE;
11925 } else {
11926 hold = "a=sendrecv\r\n";
11927 }
11928
11929 capability = p->jointcapability;
11930
11931
11932 ast_debug(1, "** Our capability: %s Video flag: %s Text flag: %s\n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), capability),
11933 p->novideo ? "True" : "False", p->notext ? "True" : "False");
11934 ast_debug(1, "** Our prefcodec: %s \n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), p->prefcodec));
11935
11936 if (doing_directmedia) {
11937 capability &= p->redircodecs;
11938 ast_debug(1, "** Our native-bridge filtered capablity: %s\n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), capability));
11939 }
11940
11941
11942 if (capability & AST_FORMAT_AUDIO_MASK)
11943 needaudio = TRUE;
11944
11945 if (debug) {
11946 ast_verbose("Audio is at %s\n", ast_sockaddr_stringify_port(&addr));
11947 }
11948
11949
11950
11951 if (needvideo) {
11952 get_crypto_attrib(p->vsrtp, &v_a_crypto);
11953 ast_str_append(&m_video, 0, "m=video %d RTP/%s", ast_sockaddr_port(&vdest),
11954 v_a_crypto ? "SAVP" : "AVP");
11955
11956
11957 if (p->maxcallbitrate)
11958 snprintf(bandwidth, sizeof(bandwidth), "b=CT:%d\r\n", p->maxcallbitrate);
11959 if (debug) {
11960 ast_verbose("Video is at %s\n", ast_sockaddr_stringify(&vdest));
11961 }
11962 }
11963
11964
11965
11966 if (needtext) {
11967 if (sipdebug_text)
11968 ast_verbose("Lets set up the text sdp\n");
11969 get_crypto_attrib(p->tsrtp, &t_a_crypto);
11970 ast_str_append(&m_text, 0, "m=text %d RTP/%s", ast_sockaddr_port(&tdest),
11971 t_a_crypto ? "SAVP" : "AVP");
11972 if (debug) {
11973 ast_verbose("Text is at %s\n", ast_sockaddr_stringify(&taddr));
11974 }
11975 }
11976
11977
11978
11979
11980
11981
11982 get_crypto_attrib(p->srtp, &a_crypto);
11983 ast_str_append(&m_audio, 0, "m=audio %d RTP/%s", ast_sockaddr_port(&dest),
11984 a_crypto ? "SAVP" : "AVP");
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995 if ((capability & p->prefcodec) & AST_FORMAT_AUDIO_MASK) {
11996 format_t codec = p->prefcodec & AST_FORMAT_AUDIO_MASK;
11997
11998 add_codec_to_sdp(p, codec, &m_audio, &a_audio, debug, &min_audio_packet_size);
11999 alreadysent |= codec;
12000 }
12001
12002
12003 for (x = 0; x < 64; x++) {
12004 format_t codec;
12005
12006 if (!(codec = ast_codec_pref_index(&p->prefs, x)))
12007 break;
12008
12009 if (!(capability & codec))
12010 continue;
12011
12012 if (alreadysent & codec)
12013 continue;
12014
12015 add_codec_to_sdp(p, codec, &m_audio, &a_audio, debug, &min_audio_packet_size);
12016 alreadysent |= codec;
12017 }
12018
12019
12020 for (x = 1ULL; x <= (needtext ? AST_FORMAT_TEXT_MASK : (needvideo ? AST_FORMAT_VIDEO_MASK : AST_FORMAT_AUDIO_MASK)); x <<= 1) {
12021 if (!(capability & x))
12022 continue;
12023
12024 if (alreadysent & x)
12025 continue;
12026
12027 if (x & AST_FORMAT_AUDIO_MASK)
12028 add_codec_to_sdp(p, x, &m_audio, &a_audio, debug, &min_audio_packet_size);
12029 else if (x & AST_FORMAT_VIDEO_MASK)
12030 add_vcodec_to_sdp(p, x, &m_video, &a_video, debug, &min_video_packet_size);
12031 else if (x & AST_FORMAT_TEXT_MASK)
12032 add_tcodec_to_sdp(p, x, &m_text, &a_text, debug, &min_text_packet_size);
12033 }
12034
12035
12036 for (x = 1LL; x <= AST_RTP_MAX; x <<= 1) {
12037 if (!(p->jointnoncodeccapability & x))
12038 continue;
12039
12040 add_noncodec_to_sdp(p, x, &m_audio, &a_audio, debug);
12041 }
12042
12043 ast_debug(3, "-- Done with adding codecs to SDP\n");
12044
12045 if (!p->owner || !ast_internal_timing_enabled(p->owner))
12046 ast_str_append(&a_audio, 0, "a=silenceSupp:off - - - -\r\n");
12047
12048 if (min_audio_packet_size)
12049 ast_str_append(&a_audio, 0, "a=ptime:%d\r\n", min_audio_packet_size);
12050
12051
12052 if (min_video_packet_size)
12053 ast_str_append(&a_video, 0, "a=ptime:%d\r\n", min_video_packet_size);
12054
12055
12056 if (min_text_packet_size)
12057 ast_str_append(&a_text, 0, "a=ptime:%d\r\n", min_text_packet_size);
12058
12059 if (ast_str_size(m_audio) - ast_str_strlen(m_audio) < 2 || ast_str_size(m_video) - ast_str_strlen(m_video) < 2 ||
12060 ast_str_size(m_text) - ast_str_strlen(m_text) < 2 || ast_str_size(a_text) - ast_str_strlen(a_text) < 2 ||
12061 ast_str_size(a_audio) - ast_str_strlen(a_audio) < 2 || ast_str_size(a_video) - ast_str_strlen(a_video) < 2)
12062 ast_log(LOG_WARNING, "SIP SDP may be truncated due to undersized buffer!!\n");
12063 }
12064
12065 if (add_t38) {
12066
12067 ast_udptl_get_us(p->udptl, &udptladdr);
12068
12069
12070 ast_sockaddr_copy(&udptldest, &p->ourip);
12071 ast_sockaddr_set_port(&udptldest, ast_sockaddr_port(&udptladdr));
12072
12073 if (debug) {
12074 ast_debug(1, "T.38 UDPTL is at %s port %d\n", ast_sockaddr_stringify_addr(&p->ourip), ast_sockaddr_port(&udptladdr));
12075 }
12076
12077
12078
12079
12080 ast_str_append(&m_modem, 0, "m=image %d udptl t38\r\n", ast_sockaddr_port(&udptldest));
12081
12082 if (ast_sockaddr_cmp(&udptldest, &dest)) {
12083 ast_str_append(&m_modem, 0, "c=IN %s %s\r\n",
12084 (ast_sockaddr_is_ipv6(&udptldest) && !ast_sockaddr_is_ipv4_mapped(&udptldest)) ?
12085 "IP6" : "IP4", ast_sockaddr_stringify_addr_remote(&udptldest));
12086 }
12087
12088 ast_str_append(&a_modem, 0, "a=T38FaxVersion:%d\r\n", p->t38.our_parms.version);
12089 ast_str_append(&a_modem, 0, "a=T38MaxBitRate:%d\r\n", t38_get_rate(p->t38.our_parms.rate));
12090 if (p->t38.our_parms.fill_bit_removal) {
12091 ast_str_append(&a_modem, 0, "a=T38FaxFillBitRemoval\r\n");
12092 }
12093 if (p->t38.our_parms.transcoding_mmr) {
12094 ast_str_append(&a_modem, 0, "a=T38FaxTranscodingMMR\r\n");
12095 }
12096 if (p->t38.our_parms.transcoding_jbig) {
12097 ast_str_append(&a_modem, 0, "a=T38FaxTranscodingJBIG\r\n");
12098 }
12099 switch (p->t38.our_parms.rate_management) {
12100 case AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF:
12101 ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:transferredTCF\r\n");
12102 break;
12103 case AST_T38_RATE_MANAGEMENT_LOCAL_TCF:
12104 ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:localTCF\r\n");
12105 break;
12106 }
12107 ast_str_append(&a_modem, 0, "a=T38FaxMaxDatagram:%u\r\n", ast_udptl_get_local_max_datagram(p->udptl));
12108 switch (ast_udptl_get_error_correction_scheme(p->udptl)) {
12109 case UDPTL_ERROR_CORRECTION_NONE:
12110 break;
12111 case UDPTL_ERROR_CORRECTION_FEC:
12112 ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPFEC\r\n");
12113 break;
12114 case UDPTL_ERROR_CORRECTION_REDUNDANCY:
12115 ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPRedundancy\r\n");
12116 break;
12117 }
12118 }
12119
12120 if (needaudio)
12121 ast_str_append(&m_audio, 0, "\r\n");
12122 if (needvideo)
12123 ast_str_append(&m_video, 0, "\r\n");
12124 if (needtext)
12125 ast_str_append(&m_text, 0, "\r\n");
12126
12127 add_header(resp, "Content-Type", "application/sdp");
12128 add_content(resp, version);
12129 add_content(resp, owner);
12130 add_content(resp, subject);
12131 add_content(resp, connection);
12132
12133 if (needvideo) {
12134 add_content(resp, bandwidth);
12135 }
12136 add_content(resp, session_time);
12137
12138 if (p->offered_media[SDP_AUDIO].order_offered ||
12139 p->offered_media[SDP_VIDEO].order_offered ||
12140 p->offered_media[SDP_TEXT].order_offered ||
12141 p->offered_media[SDP_IMAGE].order_offered) {
12142 int i;
12143
12144 for (i = 1; i <= 3; i++) {
12145 if (p->offered_media[SDP_AUDIO].order_offered == i) {
12146 if (needaudio) {
12147 add_content(resp, ast_str_buffer(m_audio));
12148 add_content(resp, ast_str_buffer(a_audio));
12149 add_content(resp, hold);
12150 if (a_crypto) {
12151 add_content(resp, a_crypto);
12152 }
12153 } else {
12154 snprintf(dummy_answer, sizeof(dummy_answer), "m=audio 0 RTP/AVP %s\r\n", p->offered_media[SDP_AUDIO].codecs);
12155 add_content(resp, dummy_answer);
12156 }
12157 } else if (p->offered_media[SDP_VIDEO].order_offered == i) {
12158 if (needvideo) {
12159 add_content(resp, ast_str_buffer(m_video));
12160 add_content(resp, ast_str_buffer(a_video));
12161 add_content(resp, hold);
12162 if (v_a_crypto) {
12163 add_content(resp, v_a_crypto);
12164 }
12165 } else {
12166 snprintf(dummy_answer, sizeof(dummy_answer), "m=video 0 RTP/AVP %s\r\n", p->offered_media[SDP_VIDEO].codecs);
12167 add_content(resp, dummy_answer);
12168 }
12169 } else if (p->offered_media[SDP_TEXT].order_offered == i) {
12170 if (needtext) {
12171 add_content(resp, ast_str_buffer(m_text));
12172 add_content(resp, ast_str_buffer(a_text));
12173 add_content(resp, hold);
12174 if (t_a_crypto) {
12175 add_content(resp, t_a_crypto);
12176 }
12177 } else {
12178 snprintf(dummy_answer, sizeof(dummy_answer), "m=text 0 RTP/AVP %s\r\n", p->offered_media[SDP_TEXT].codecs);
12179 add_content(resp, dummy_answer);
12180 }
12181 } else if (p->offered_media[SDP_IMAGE].order_offered == i) {
12182 if (add_t38) {
12183 add_content(resp, ast_str_buffer(m_modem));
12184 add_content(resp, ast_str_buffer(a_modem));
12185 } else {
12186 add_content(resp, "m=image 0 udptl t38\r\n");
12187 }
12188 }
12189 }
12190 } else {
12191
12192 if (needaudio) {
12193 add_content(resp, ast_str_buffer(m_audio));
12194 add_content(resp, ast_str_buffer(a_audio));
12195 add_content(resp, hold);
12196 if (a_crypto) {
12197 add_content(resp, a_crypto);
12198 }
12199 }
12200 if (needvideo) {
12201 add_content(resp, ast_str_buffer(m_video));
12202 add_content(resp, ast_str_buffer(a_video));
12203 add_content(resp, hold);
12204 if (v_a_crypto) {
12205 add_content(resp, v_a_crypto);
12206 }
12207 }
12208 if (needtext) {
12209 add_content(resp, ast_str_buffer(m_text));
12210 add_content(resp, ast_str_buffer(a_text));
12211 add_content(resp, hold);
12212 if (t_a_crypto) {
12213 add_content(resp, t_a_crypto);
12214 }
12215 }
12216 if (add_t38) {
12217 add_content(resp, ast_str_buffer(m_modem));
12218 add_content(resp, ast_str_buffer(a_modem));
12219 }
12220 }
12221
12222
12223 p->lastrtprx = p->lastrtptx = time(NULL);
12224
12225 ast_debug(3, "Done building SDP. Settling with this capability: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, capability));
12226
12227 return AST_SUCCESS;
12228 }
12229
12230
12231 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
12232 {
12233 struct sip_request resp;
12234 uint32_t seqno;
12235
12236 if (sscanf(get_header(req, "CSeq"), "%30u ", &seqno) != 1) {
12237 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
12238 return -1;
12239 }
12240 respprep(&resp, p, msg, req);
12241 if (p->udptl) {
12242 add_sdp(&resp, p, 0, 0, 1);
12243 } else
12244 ast_log(LOG_ERROR, "Can't add SDP to response, since we have no UDPTL session allocated. Call-ID %s\n", p->callid);
12245 if (retrans && !p->pendinginvite)
12246 p->pendinginvite = seqno;
12247 return send_response(p, &resp, retrans, seqno);
12248 }
12249
12250
12251 static void copy_request(struct sip_request *dst, const struct sip_request *src)
12252 {
12253
12254
12255
12256 struct ast_str *duplicate = dst->data;
12257 struct ast_str *duplicate_content = dst->content;
12258
12259
12260
12261 *dst = *src;
12262 dst->data = duplicate;
12263 dst->content = duplicate_content;
12264
12265
12266 if (!dst->data && !(dst->data = ast_str_create(ast_str_strlen(src->data) + 1))) {
12267 return;
12268 }
12269 ast_str_copy_string(&dst->data, src->data);
12270
12271
12272 if (src->content) {
12273 if (!dst->content && !(dst->content = ast_str_create(ast_str_strlen(src->content) + 1))) {
12274 return;
12275 }
12276 ast_str_copy_string(&dst->content, src->content);
12277 }
12278 }
12279
12280 static void add_cc_call_info_to_response(struct sip_pvt *p, struct sip_request *resp)
12281 {
12282 char uri[SIPBUFSIZE];
12283 struct ast_str *header = ast_str_alloca(SIPBUFSIZE);
12284 struct ast_cc_agent *agent = find_sip_cc_agent_by_original_callid(p);
12285 struct sip_cc_agent_pvt *agent_pvt;
12286
12287 if (!agent) {
12288
12289
12290
12291 ast_log(LOG_WARNING, "Can't find SIP CC agent for call '%s' even though OFFER_CC flag was set?\n", p->callid);
12292 return;
12293 }
12294
12295 agent_pvt = agent->private_data;
12296
12297 if (!ast_strlen_zero(agent_pvt->subscribe_uri)) {
12298 ast_copy_string(uri, agent_pvt->subscribe_uri, sizeof(uri));
12299 } else {
12300 generate_uri(p, uri, sizeof(uri));
12301 ast_copy_string(agent_pvt->subscribe_uri, uri, sizeof(agent_pvt->subscribe_uri));
12302 }
12303
12304
12305
12306
12307 ast_str_set(&header, 0, "<%s>;purpose=call-completion;m=%s", uri, "NR");
12308 add_header(resp, "Call-Info", ast_str_buffer(header));
12309 ao2_ref(agent, -1);
12310 }
12311
12312
12313
12314
12315 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)
12316 {
12317 struct sip_request resp;
12318 uint32_t seqno;
12319 if (sscanf(get_header(req, "CSeq"), "%30u ", &seqno) != 1) {
12320 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
12321 return -1;
12322 }
12323 respprep(&resp, p, msg, req);
12324 if (rpid == TRUE) {
12325 add_rpid(&resp, p);
12326 }
12327 if (ast_test_flag(&p->flags[0], SIP_OFFER_CC)) {
12328 add_cc_call_info_to_response(p, &resp);
12329 }
12330 if (p->rtp) {
12331 if (!p->autoframing && !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
12332 ast_debug(1, "Setting framing from config on incoming call\n");
12333 ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(p->rtp), p->rtp, &p->prefs);
12334 }
12335 ast_rtp_instance_activate(p->rtp);
12336 try_suggested_sip_codec(p);
12337 if (p->t38.state == T38_ENABLED) {
12338 add_sdp(&resp, p, oldsdp, TRUE, TRUE);
12339 } else {
12340 add_sdp(&resp, p, oldsdp, TRUE, FALSE);
12341 }
12342 } else
12343 ast_log(LOG_ERROR, "Can't add SDP to response, since we have no RTP session allocated. Call-ID %s\n", p->callid);
12344 if (reliable && !p->pendinginvite)
12345 p->pendinginvite = seqno;
12346 add_required_respheader(&resp);
12347 return send_response(p, &resp, reliable, seqno);
12348 }
12349
12350
12351 static int determine_firstline_parts(struct sip_request *req)
12352 {
12353 char *e = ast_skip_blanks(req->data->str);
12354 char *local_rlPart1;
12355
12356 if (!*e)
12357 return -1;
12358 req->rlPart1 = e - req->data->str;
12359 local_rlPart1 = e;
12360 e = ast_skip_nonblanks(e);
12361 if (*e)
12362 *e++ = '\0';
12363
12364 e = ast_skip_blanks(e);
12365 if ( !*e )
12366 return -1;
12367 ast_trim_blanks(e);
12368
12369 if (!strcasecmp(local_rlPart1, "SIP/2.0") ) {
12370 if (strlen(e) < 3)
12371 return -1;
12372 req->rlPart2 = e - req->data->str;
12373 } else {
12374 if ( *e == '<' ) {
12375 ast_debug(3, "Oops. Bogus uri in <> %s\n", e);
12376 e++;
12377 if (!*e)
12378 return -1;
12379 }
12380 req->rlPart2 = e - req->data->str;
12381 e = ast_skip_nonblanks(e);
12382 if (*e)
12383 *e++ = '\0';
12384 e = ast_skip_blanks(e);
12385 if (strcasecmp(e, "SIP/2.0") ) {
12386 ast_debug(3, "Skipping packet - Bad request protocol %s\n", e);
12387 return -1;
12388 }
12389 }
12390 return 1;
12391 }
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp)
12407 {
12408 struct sip_request req;
12409
12410 reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ? SIP_UPDATE : SIP_INVITE, 0, 1);
12411
12412 add_header(&req, "Allow", ALLOWED_METHODS);
12413 add_supported_header(p, &req);
12414 if (sipdebug) {
12415 if (oldsdp == TRUE)
12416 add_header(&req, "X-asterisk-Info", "SIP re-invite (Session-Timers)");
12417 else
12418 add_header(&req, "X-asterisk-Info", "SIP re-invite (External RTP bridge)");
12419 }
12420
12421 if (ast_test_flag(&p->flags[0], SIP_SENDRPID))
12422 add_rpid(&req, p);
12423
12424 if (p->do_history) {
12425 append_history(p, "ReInv", "Re-invite sent");
12426 }
12427 memset(p->offered_media, 0, sizeof(p->offered_media));
12428
12429 try_suggested_sip_codec(p);
12430 if (t38version) {
12431 add_sdp(&req, p, oldsdp, FALSE, TRUE);
12432 } else {
12433 add_sdp(&req, p, oldsdp, TRUE, FALSE);
12434 }
12435
12436
12437 initialize_initreq(p, &req);
12438 p->lastinvite = p->ocseq;
12439 ast_set_flag(&p->flags[0], SIP_OUTGOING);
12440 p->ongoing_reinvite = 1;
12441 return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
12442 }
12443
12444
12445 static char *remove_uri_parameters(char *uri)
12446 {
12447 char *atsign;
12448 atsign = strchr(uri, '@');
12449 if (!atsign) {
12450 atsign = uri;
12451 }
12452 atsign = strchr(atsign, ';');
12453 if (atsign)
12454 *atsign = '\0';
12455 return uri;
12456 }
12457
12458
12459 static void extract_uri(struct sip_pvt *p, struct sip_request *req)
12460 {
12461 char stripped[SIPBUFSIZE];
12462 char *c;
12463
12464 ast_copy_string(stripped, get_header(req, "Contact"), sizeof(stripped));
12465 c = get_in_brackets(stripped);
12466
12467 c = remove_uri_parameters(c);
12468 if (!ast_strlen_zero(c)) {
12469 ast_string_field_set(p, uri, c);
12470 }
12471
12472 }
12473
12474
12475 static void build_contact(struct sip_pvt *p)
12476 {
12477 char tmp[SIPBUFSIZE];
12478 char *user = ast_uri_encode(p->exten, tmp, sizeof(tmp), 0);
12479
12480 if (p->socket.type == SIP_TRANSPORT_UDP) {
12481 ast_string_field_build(p, our_contact, "<sip:%s%s%s>", user,
12482 ast_strlen_zero(user) ? "" : "@", ast_sockaddr_stringify_remote(&p->ourip));
12483 } else {
12484 ast_string_field_build(p, our_contact, "<sip:%s%s%s;transport=%s>", user,
12485 ast_strlen_zero(user) ? "" : "@", ast_sockaddr_stringify_remote(&p->ourip),
12486 get_transport(p->socket.type));
12487 }
12488 }
12489
12490
12491 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, const char * const explicit_uri)
12492 {
12493 struct ast_str *invite = ast_str_alloca(256);
12494 char from[256];
12495 char to[256];
12496 char tmp_n[SIPBUFSIZE/2];
12497 char tmp_l[SIPBUFSIZE/2];
12498 const char *l = NULL;
12499 const char *n = NULL;
12500 const char *d = NULL;
12501 const char *urioptions = "";
12502 int ourport;
12503
12504 if (ast_test_flag(&p->flags[0], SIP_USEREQPHONE)) {
12505 const char *s = p->username;
12506
12507
12508
12509
12510
12511
12512 if (*s == '+')
12513 s++;
12514 for (; *s; s++) {
12515 if (!strchr(AST_DIGIT_ANYNUM, *s) )
12516 break;
12517 }
12518
12519 if (!*s)
12520 urioptions = ";user=phone";
12521 }
12522
12523
12524 snprintf(p->lastmsg, sizeof(p->lastmsg), "Init: %s", sip_methods[sipmethod].text);
12525
12526 if (ast_strlen_zero(p->fromdomain)) {
12527 d = ast_sockaddr_stringify_host_remote(&p->ourip);
12528 }
12529 if (p->owner) {
12530 if ((ast_party_id_presentation(&p->owner->connected.id) & AST_PRES_RESTRICTION) == AST_PRES_ALLOWED) {
12531 l = p->owner->connected.id.number.valid ? p->owner->connected.id.number.str : NULL;
12532 n = p->owner->connected.id.name.valid ? p->owner->connected.id.name.str : NULL;
12533 } else {
12534
12535
12536 l = "anonymous";
12537 n = CALLERID_UNKNOWN;
12538 d = FROMDOMAIN_INVALID;
12539 }
12540 }
12541
12542
12543
12544
12545
12546
12547
12548 if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->mwi_from)) {
12549 l = p->mwi_from;
12550 }
12551
12552 if (ast_strlen_zero(l))
12553 l = default_callerid;
12554 if (ast_strlen_zero(n))
12555 n = l;
12556
12557 if (!ast_strlen_zero(p->fromuser))
12558 l = p->fromuser;
12559 else
12560 ast_string_field_set(p, fromuser, l);
12561
12562
12563 if (!ast_strlen_zero(p->fromname))
12564 n = p->fromname;
12565 else
12566 ast_string_field_set(p, fromname, n);
12567
12568
12569 if (!ast_strlen_zero(p->fromdomain))
12570 d = p->fromdomain;
12571 else
12572 ast_string_field_set(p, fromdomain, d);
12573
12574 ast_copy_string(tmp_l, l, sizeof(tmp_l));
12575 if (sip_cfg.pedanticsipchecking) {
12576 ast_escape_quoted(n, tmp_n, sizeof(tmp_n));
12577 n = tmp_n;
12578 ast_uri_encode(l, tmp_l, sizeof(tmp_l), 0);
12579 }
12580
12581 ourport = (p->fromdomainport) ? p->fromdomainport : ast_sockaddr_port(&p->ourip);
12582 if (!sip_standard_port(p->socket.type, ourport)) {
12583 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s:%d>;tag=%s", n, tmp_l, d, ourport, p->tag);
12584 } else {
12585 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=%s", n, tmp_l, d, p->tag);
12586 }
12587
12588 if (!ast_strlen_zero(explicit_uri)) {
12589 ast_str_set(&invite, 0, "%s", explicit_uri);
12590 } else {
12591
12592 if (!ast_strlen_zero(p->fullcontact)) {
12593
12594 ast_str_append(&invite, 0, "%s", p->fullcontact);
12595 } else {
12596
12597 ast_str_append(&invite, 0, "sip:");
12598 if (!ast_strlen_zero(p->username)) {
12599 n = p->username;
12600 if (sip_cfg.pedanticsipchecking) {
12601 ast_uri_encode(n, tmp_n, sizeof(tmp_n), 0);
12602 n = tmp_n;
12603 }
12604 ast_str_append(&invite, 0, "%s@", n);
12605 }
12606 ast_str_append(&invite, 0, "%s", p->tohost);
12607 if (p->portinuri) {
12608 ast_str_append(&invite, 0, ":%d", ast_sockaddr_port(&p->sa));
12609 }
12610 ast_str_append(&invite, 0, "%s", urioptions);
12611 }
12612 }
12613
12614
12615 if (p->options && !ast_strlen_zero(p->options->uri_options))
12616 ast_str_append(&invite, 0, ";%s", p->options->uri_options);
12617
12618
12619
12620
12621 ast_string_field_set(p, uri, ast_str_buffer(invite));
12622
12623 if (!ast_strlen_zero(p->todnid)) {
12624
12625 if (!strchr(p->todnid, '@')) {
12626
12627 snprintf(to, sizeof(to), "<sip:%s@%s>%s%s", p->todnid, p->tohost, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
12628 } else {
12629 snprintf(to, sizeof(to), "<sip:%s>%s%s", p->todnid, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
12630 }
12631 } else {
12632 if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->theirtag)) {
12633
12634 snprintf(to, sizeof(to), "<%s%s>;tag=%s", (strncasecmp(p->uri, "sip:", 4) ? "sip:" : ""), p->uri, p->theirtag);
12635 } else if (p->options && p->options->vxml_url) {
12636
12637 snprintf(to, sizeof(to), "<%s>;%s", p->uri, p->options->vxml_url);
12638 } else {
12639 snprintf(to, sizeof(to), "<%s>", p->uri);
12640 }
12641 }
12642
12643 init_req(req, sipmethod, p->uri);
12644
12645 snprintf(tmp_n, sizeof(tmp_n), "%u %s", ++p->ocseq, sip_methods[sipmethod].text);
12646
12647 add_header(req, "Via", p->via);
12648 add_header_max_forwards(p, req);
12649
12650
12651
12652
12653 add_route(req, p->route);
12654
12655 add_header(req, "From", from);
12656 add_header(req, "To", to);
12657 ast_string_field_set(p, exten, l);
12658 build_contact(p);
12659 add_header(req, "Contact", p->our_contact);
12660 add_header(req, "Call-ID", p->callid);
12661 add_header(req, "CSeq", tmp_n);
12662 if (!ast_strlen_zero(global_useragent)) {
12663 add_header(req, "User-Agent", global_useragent);
12664 }
12665 }
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675 static void add_diversion_header(struct sip_request *req, struct sip_pvt *pvt)
12676 {
12677 const char *diverting_number;
12678 const char *diverting_name;
12679 const char *reason;
12680 char header_text[256];
12681
12682 if (!pvt->owner) {
12683 return;
12684 }
12685
12686 diverting_number = pvt->owner->redirecting.from.number.str;
12687 if (!pvt->owner->redirecting.from.number.valid
12688 || ast_strlen_zero(diverting_number)) {
12689 return;
12690 }
12691
12692 reason = sip_reason_code_to_str(pvt->owner->redirecting.reason);
12693
12694
12695 diverting_name = pvt->owner->redirecting.from.name.str;
12696 if (!pvt->owner->redirecting.from.name.valid
12697 || ast_strlen_zero(diverting_name)) {
12698 snprintf(header_text, sizeof(header_text), "<sip:%s@%s>;reason=%s", diverting_number,
12699 ast_sockaddr_stringify_host_remote(&pvt->ourip), reason);
12700 } else {
12701 snprintf(header_text, sizeof(header_text), "\"%s\" <sip:%s@%s>;reason=%s",
12702 diverting_name, diverting_number,
12703 ast_sockaddr_stringify_host_remote(&pvt->ourip), reason);
12704 }
12705
12706 add_header(req, "Diversion", header_text);
12707 }
12708
12709 static int transmit_publish(struct sip_epa_entry *epa_entry, enum sip_publish_type publish_type, const char * const explicit_uri)
12710 {
12711 struct sip_pvt *pvt;
12712 int expires;
12713
12714 epa_entry->publish_type = publish_type;
12715
12716 if (!(pvt = sip_alloc(NULL, NULL, 0, SIP_PUBLISH, NULL))) {
12717 return -1;
12718 }
12719
12720 sip_pvt_lock(pvt);
12721
12722 if (create_addr(pvt, epa_entry->destination, NULL, TRUE)) {
12723 sip_pvt_unlock(pvt);
12724 dialog_unlink_all(pvt);
12725 dialog_unref(pvt, "create_addr failed in transmit_publish. Unref dialog");
12726 return -1;
12727 }
12728 ast_sip_ouraddrfor(&pvt->sa, &pvt->ourip, pvt);
12729 ast_set_flag(&pvt->flags[0], SIP_OUTGOING);
12730 expires = (publish_type == SIP_PUBLISH_REMOVE) ? 0 : DEFAULT_PUBLISH_EXPIRES;
12731 pvt->expiry = expires;
12732
12733
12734 ao2_ref(epa_entry, +1);
12735 pvt->epa_entry = epa_entry;
12736
12737 transmit_invite(pvt, SIP_PUBLISH, FALSE, 2, explicit_uri);
12738 sip_pvt_unlock(pvt);
12739 sip_scheddestroy(pvt, DEFAULT_TRANS_TIMEOUT);
12740 dialog_unref(pvt, "Done with the sip_pvt allocated for transmitting PUBLISH");
12741 return 0;
12742 }
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init, const char * const explicit_uri)
12754 {
12755 struct sip_request req;
12756 struct ast_variable *var;
12757
12758 if (init) {
12759 p->branch ^= ast_random();
12760 p->invite_branch = p->branch;
12761 build_via(p);
12762 }
12763 if (init > 1) {
12764 initreqprep(&req, p, sipmethod, explicit_uri);
12765 } else {
12766
12767 reqprep(&req, p, sipmethod, 0, init ? 0 : 1);
12768 }
12769
12770 if (p->options && p->options->auth) {
12771 add_header(&req, p->options->authheader, p->options->auth);
12772 }
12773 append_date(&req);
12774 if (sipmethod == SIP_REFER) {
12775 if (p->refer) {
12776 char buf[SIPBUFSIZE];
12777 if (!ast_strlen_zero(p->refer->refer_to)) {
12778 add_header(&req, "Refer-To", p->refer->refer_to);
12779 }
12780 if (!ast_strlen_zero(p->refer->referred_by)) {
12781 snprintf(buf, sizeof(buf), "%s <%s>", p->refer->referred_by_name, p->refer->referred_by);
12782 add_header(&req, "Referred-By", buf);
12783 }
12784 }
12785 } else if (sipmethod == SIP_SUBSCRIBE) {
12786 char buf[SIPBUFSIZE];
12787 if (p->subscribed == MWI_NOTIFICATION) {
12788 add_header(&req, "Event", "message-summary");
12789 add_header(&req, "Accept", "application/simple-message-summary");
12790 } else if (p->subscribed == CALL_COMPLETION) {
12791 add_header(&req, "Event", "call-completion");
12792 add_header(&req, "Accept", "application/call-completion");
12793 }
12794 snprintf(buf, sizeof(buf), "%d", p->expiry);
12795 add_header(&req, "Expires", buf);
12796 }
12797
12798
12799
12800 if (p->options && !ast_strlen_zero(p->options->replaces)) {
12801 add_header(&req, "Replaces", p->options->replaces);
12802 add_header(&req, "Require", "replaces");
12803 }
12804
12805
12806 if (st_get_mode(p, 0) == SESSION_TIMER_MODE_ORIGINATE
12807 || (st_get_mode(p, 0) == SESSION_TIMER_MODE_ACCEPT
12808 && st_get_se(p, FALSE) != DEFAULT_MIN_SE)) {
12809 char i2astr[10];
12810
12811 if (!p->stimer->st_interval) {
12812 p->stimer->st_interval = st_get_se(p, TRUE);
12813 }
12814
12815 p->stimer->st_active = TRUE;
12816 if (st_get_mode(p, 0) == SESSION_TIMER_MODE_ORIGINATE) {
12817 snprintf(i2astr, sizeof(i2astr), "%d", p->stimer->st_interval);
12818 add_header(&req, "Session-Expires", i2astr);
12819 }
12820
12821 snprintf(i2astr, sizeof(i2astr), "%d", st_get_se(p, FALSE));
12822 add_header(&req, "Min-SE", i2astr);
12823 }
12824
12825 add_header(&req, "Allow", ALLOWED_METHODS);
12826 add_supported_header(p, &req);
12827
12828 if (p->options && p->options->addsipheaders && p->owner) {
12829 struct ast_channel *chan = p->owner;
12830 struct varshead *headp;
12831
12832 ast_channel_lock(chan);
12833
12834 headp = &chan->varshead;
12835
12836 if (!headp) {
12837 ast_log(LOG_WARNING, "No Headp for the channel...ooops!\n");
12838 } else {
12839 const struct ast_var_t *current;
12840 AST_LIST_TRAVERSE(headp, current, entries) {
12841
12842 if (!strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
12843 char *content, *end;
12844 const char *header = ast_var_value(current);
12845 char *headdup = ast_strdupa(header);
12846
12847
12848 if (*headdup == '"') {
12849 headdup++;
12850 }
12851 if ((content = strchr(headdup, ':'))) {
12852 *content++ = '\0';
12853 content = ast_skip_blanks(content);
12854
12855 end = content + strlen(content) -1;
12856 if (*end == '"') {
12857 *end = '\0';
12858 }
12859
12860 add_header(&req, headdup, content);
12861 if (sipdebug) {
12862 ast_debug(1, "Adding SIP Header \"%s\" with content :%s: \n", headdup, content);
12863 }
12864 }
12865 }
12866 }
12867 }
12868
12869 ast_channel_unlock(chan);
12870 }
12871 if ((sipmethod == SIP_INVITE || sipmethod == SIP_UPDATE) && ast_test_flag(&p->flags[0], SIP_SENDRPID))
12872 add_rpid(&req, p);
12873 if (sipmethod == SIP_INVITE) {
12874 add_diversion_header(&req, p);
12875 }
12876 if (sdp) {
12877 memset(p->offered_media, 0, sizeof(p->offered_media));
12878 if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
12879 ast_debug(1, "T38 is in state %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
12880 add_sdp(&req, p, FALSE, FALSE, TRUE);
12881 } else if (p->rtp) {
12882 try_suggested_sip_codec(p);
12883 add_sdp(&req, p, FALSE, TRUE, FALSE);
12884 }
12885 } else if (p->notify) {
12886 for (var = p->notify->headers; var; var = var->next) {
12887 add_header(&req, var->name, var->value);
12888 }
12889 if (ast_str_strlen(p->notify->content)) {
12890 add_content(&req, ast_str_buffer(p->notify->content));
12891 }
12892 } else if (sipmethod == SIP_PUBLISH) {
12893 char expires[SIPBUFSIZE];
12894
12895 switch (p->epa_entry->static_data->event) {
12896 case CALL_COMPLETION:
12897 snprintf(expires, sizeof(expires), "%d", p->expiry);
12898 add_header(&req, "Event", "call-completion");
12899 add_header(&req, "Expires", expires);
12900 if (p->epa_entry->publish_type != SIP_PUBLISH_INITIAL) {
12901 add_header(&req, "SIP-If-Match", p->epa_entry->entity_tag);
12902 }
12903
12904 if (!ast_strlen_zero(p->epa_entry->body)) {
12905 add_header(&req, "Content-Type", "application/pidf+xml");
12906 add_content(&req, p->epa_entry->body);
12907 }
12908 default:
12909 break;
12910 }
12911 }
12912
12913 if (!p->initreq.headers || init > 2) {
12914 initialize_initreq(p, &req);
12915 }
12916 if (sipmethod == SIP_INVITE || sipmethod == SIP_SUBSCRIBE) {
12917 p->lastinvite = p->ocseq;
12918 }
12919 return send_request(p, &req, init ? XMIT_CRITICAL : XMIT_RELIABLE, p->ocseq);
12920 }
12921
12922
12923 static int sip_subscribe_mwi_do(const void *data)
12924 {
12925 struct sip_subscription_mwi *mwi = (struct sip_subscription_mwi*)data;
12926
12927 if (!mwi) {
12928 return -1;
12929 }
12930
12931 mwi->resub = -1;
12932 __sip_subscribe_mwi_do(mwi);
12933 ASTOBJ_UNREF(mwi, sip_subscribe_mwi_destroy);
12934
12935 return 0;
12936 }
12937
12938 static void on_dns_update_registry(struct ast_sockaddr *old, struct ast_sockaddr *new, void *data)
12939 {
12940 struct sip_registry *reg = data;
12941 const char *old_str;
12942
12943
12944 if (ast_sockaddr_isnull(new)) {
12945 ast_debug(1, "Empty sockaddr change...ignoring!\n");
12946 return;
12947 }
12948
12949 if (!ast_sockaddr_port(new)) {
12950 ast_sockaddr_set_port(new, reg->portno);
12951 }
12952
12953 old_str = ast_strdupa(ast_sockaddr_stringify(old));
12954
12955 ast_debug(1, "Changing registry %s from %s to %s\n", S_OR(reg->peername, reg->hostname), old_str, ast_sockaddr_stringify(new));
12956 ast_sockaddr_copy(®->us, new);
12957 }
12958
12959 static void on_dns_update_peer(struct ast_sockaddr *old, struct ast_sockaddr *new, void *data)
12960 {
12961 struct sip_peer *peer = data;
12962 const char *old_str;
12963
12964
12965 if (ast_sockaddr_isnull(new)) {
12966 ast_debug(1, "Empty sockaddr change...ignoring!\n");
12967 return;
12968 }
12969
12970 if (!ast_sockaddr_isnull(&peer->addr)) {
12971 ao2_unlink(peers_by_ip, peer);
12972 }
12973
12974 if (!ast_sockaddr_port(new)) {
12975 ast_sockaddr_set_port(new, default_sip_port(peer->socket.type));
12976 }
12977
12978 old_str = ast_strdupa(ast_sockaddr_stringify(old));
12979 ast_debug(1, "Changing peer %s address from %s to %s\n", peer->name, old_str, ast_sockaddr_stringify(new));
12980
12981 ao2_lock(peer);
12982 ast_sockaddr_copy(&peer->addr, new);
12983 ao2_unlock(peer);
12984
12985 ao2_link(peers_by_ip, peer);
12986 }
12987
12988 static void on_dns_update_mwi(struct ast_sockaddr *old, struct ast_sockaddr *new, void *data)
12989 {
12990 struct sip_subscription_mwi *mwi = data;
12991 const char *old_str;
12992
12993
12994 if (ast_sockaddr_isnull(new)) {
12995 ast_debug(1, "Empty sockaddr change...ignoring!\n");
12996 return;
12997 }
12998
12999 old_str = ast_strdupa(ast_sockaddr_stringify(old));
13000 ast_debug(1, "Changing mwi %s from %s to %s\n", mwi->hostname, old_str, ast_sockaddr_stringify(new));
13001 ast_sockaddr_copy(&mwi->us, new);
13002 }
13003
13004
13005 static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi)
13006 {
13007
13008 if (!mwi->dnsmgr) {
13009 char transport[MAXHOSTNAMELEN];
13010 struct sip_subscription_mwi *saved;
13011 snprintf(transport, sizeof(transport), "_%s._%s", get_srv_service(mwi->transport), get_srv_protocol(mwi->transport));
13012
13013 mwi->us.ss.ss_family = get_address_family_filter(mwi->transport);
13014 saved = ASTOBJ_REF(mwi);
13015 ast_dnsmgr_lookup_cb(mwi->hostname, &mwi->us, &mwi->dnsmgr, sip_cfg.srvlookup ? transport : NULL, on_dns_update_mwi, saved);
13016 if (!mwi->dnsmgr) {
13017 ASTOBJ_UNREF(saved, sip_subscribe_mwi_destroy);
13018 }
13019 }
13020
13021
13022 if (mwi->call) {
13023 transmit_invite(mwi->call, SIP_SUBSCRIBE, 0, 0, NULL);
13024 return 0;
13025 }
13026
13027
13028 if (!(mwi->call = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL))) {
13029 return -1;
13030 }
13031
13032 ref_proxy(mwi->call, obproxy_get(mwi->call, NULL));
13033
13034 if (!ast_sockaddr_port(&mwi->us) && mwi->portno) {
13035 ast_sockaddr_set_port(&mwi->us, mwi->portno);
13036 }
13037
13038
13039 if (create_addr(mwi->call, mwi->hostname, &mwi->us, 0)) {
13040 dialog_unlink_all(mwi->call);
13041 mwi->call = dialog_unref(mwi->call, "unref dialog after unlink_all");
13042 return 0;
13043 }
13044
13045 mwi->call->expiry = mwi_expiry;
13046
13047 if (!mwi->dnsmgr && mwi->portno) {
13048 ast_sockaddr_set_port(&mwi->call->sa, mwi->portno);
13049 ast_sockaddr_set_port(&mwi->call->recv, mwi->portno);
13050 } else {
13051 mwi->portno = ast_sockaddr_port(&mwi->call->sa);
13052 }
13053
13054
13055 if (!ast_strlen_zero(mwi->authuser)) {
13056 ast_string_field_set(mwi->call, peername, mwi->authuser);
13057 ast_string_field_set(mwi->call, authname, mwi->authuser);
13058 ast_string_field_set(mwi->call, fromuser, mwi->authuser);
13059 } else {
13060 ast_string_field_set(mwi->call, peername, mwi->username);
13061 ast_string_field_set(mwi->call, authname, mwi->username);
13062 ast_string_field_set(mwi->call, fromuser, mwi->username);
13063 }
13064 ast_string_field_set(mwi->call, username, mwi->username);
13065 if (!ast_strlen_zero(mwi->secret)) {
13066 ast_string_field_set(mwi->call, peersecret, mwi->secret);
13067 }
13068 set_socket_transport(&mwi->call->socket, mwi->transport);
13069 mwi->call->socket.port = htons(mwi->portno);
13070 ast_sip_ouraddrfor(&mwi->call->sa, &mwi->call->ourip, mwi->call);
13071 build_contact(mwi->call);
13072 build_via(mwi->call);
13073
13074
13075 change_callid_pvt(mwi->call, NULL);
13076
13077 ast_set_flag(&mwi->call->flags[0], SIP_OUTGOING);
13078
13079
13080 mwi->call->mwi = ASTOBJ_REF(mwi);
13081
13082 mwi->call->subscribed = MWI_NOTIFICATION;
13083
13084
13085 transmit_invite(mwi->call, SIP_SUBSCRIBE, 0, 2, NULL);
13086
13087 return 0;
13088 }
13089
13090
13091 static int find_calling_channel(void *obj, void *arg, void *data, int flags)
13092 {
13093 struct ast_channel *c = obj;
13094 struct sip_pvt *p = data;
13095 int res;
13096
13097 ast_channel_lock(c);
13098
13099 res = (c->pbx &&
13100 (!strcasecmp(c->macroexten, p->exten) || !strcasecmp(c->exten, p->exten)) &&
13101 (sip_cfg.notifycid == IGNORE_CONTEXT || !strcasecmp(c->context, p->context)));
13102
13103 ast_channel_unlock(c);
13104
13105 return res ? CMP_MATCH | CMP_STOP : 0;
13106 }
13107
13108
13109 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)
13110 {
13111 enum state { NOTIFY_OPEN, NOTIFY_INUSE, NOTIFY_CLOSED } local_state = NOTIFY_OPEN;
13112 const char *statestring = "terminated";
13113 const char *pidfstate = "--";
13114 const char *pidfnote= "Ready";
13115 char hint[AST_MAX_EXTENSION];
13116
13117 switch (state) {
13118 case (AST_EXTENSION_RINGING | AST_EXTENSION_INUSE):
13119 statestring = (sip_cfg.notifyringing) ? "early" : "confirmed";
13120 local_state = NOTIFY_INUSE;
13121 pidfstate = "busy";
13122 pidfnote = "Ringing";
13123 break;
13124 case AST_EXTENSION_RINGING:
13125 statestring = "early";
13126 local_state = NOTIFY_INUSE;
13127 pidfstate = "busy";
13128 pidfnote = "Ringing";
13129 break;
13130 case AST_EXTENSION_INUSE:
13131 statestring = "confirmed";
13132 local_state = NOTIFY_INUSE;
13133 pidfstate = "busy";
13134 pidfnote = "On the phone";
13135 break;
13136 case AST_EXTENSION_BUSY:
13137 statestring = "confirmed";
13138 local_state = NOTIFY_CLOSED;
13139 pidfstate = "busy";
13140 pidfnote = "On the phone";
13141 break;
13142 case AST_EXTENSION_UNAVAILABLE:
13143 statestring = "terminated";
13144 local_state = NOTIFY_CLOSED;
13145 pidfstate = "away";
13146 pidfnote = "Unavailable";
13147 break;
13148 case AST_EXTENSION_ONHOLD:
13149 statestring = "confirmed";
13150 local_state = NOTIFY_CLOSED;
13151 pidfstate = "busy";
13152 pidfnote = "On hold";
13153 break;
13154 case AST_EXTENSION_NOT_INUSE:
13155 default:
13156
13157 break;
13158 }
13159
13160
13161 if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, context, exten)) {
13162 char *hint2 = hint, *individual_hint = NULL;
13163 int hint_count = 0, unavailable_count = 0;
13164
13165 while ((individual_hint = strsep(&hint2, "&"))) {
13166 hint_count++;
13167
13168 if (ast_device_state(individual_hint) == AST_DEVICE_UNAVAILABLE)
13169 unavailable_count++;
13170 }
13171
13172
13173
13174
13175 if (hint_count > 0 && hint_count == unavailable_count) {
13176 local_state = NOTIFY_CLOSED;
13177 pidfstate = "away";
13178 pidfnote = "Not online";
13179 }
13180 }
13181
13182 switch (subscribed) {
13183 case XPIDF_XML:
13184 case CPIM_PIDF_XML:
13185 ast_str_append(tmp, 0,
13186 "<?xml version=\"1.0\"?>\n"
13187 "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n"
13188 "<presence>\n");
13189 ast_str_append(tmp, 0, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
13190 ast_str_append(tmp, 0, "<atom id=\"%s\">\n", exten);
13191 ast_str_append(tmp, 0, "<address uri=\"%s;user=ip\" priority=\"0.800000\">\n", mto);
13192 ast_str_append(tmp, 0, "<status status=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "open" : (local_state == NOTIFY_INUSE) ? "inuse" : "closed");
13193 ast_str_append(tmp, 0, "<msnsubstatus substatus=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "online" : (local_state == NOTIFY_INUSE) ? "onthephone" : "offline");
13194 ast_str_append(tmp, 0, "</address>\n</atom>\n</presence>\n");
13195 break;
13196 case PIDF_XML:
13197 ast_str_append(tmp, 0,
13198 "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"
13199 "<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);
13200 ast_str_append(tmp, 0, "<pp:person><status>\n");
13201 if (pidfstate[0] != '-') {
13202 ast_str_append(tmp, 0, "<ep:activities><ep:%s/></ep:activities>\n", pidfstate);
13203 }
13204 ast_str_append(tmp, 0, "</status></pp:person>\n");
13205 ast_str_append(tmp, 0, "<note>%s</note>\n", pidfnote);
13206 ast_str_append(tmp, 0, "<tuple id=\"%s\">\n", exten);
13207 ast_str_append(tmp, 0, "<contact priority=\"1\">%s</contact>\n", mto);
13208 if (pidfstate[0] == 'b')
13209 ast_str_append(tmp, 0, "<status><basic>open</basic></status>\n");
13210 else
13211 ast_str_append(tmp, 0, "<status><basic>%s</basic></status>\n", (local_state != NOTIFY_CLOSED) ? "open" : "closed");
13212 ast_str_append(tmp, 0, "</tuple>\n</presence>\n");
13213 break;
13214 case DIALOG_INFO_XML:
13215 ast_str_append(tmp, 0, "<?xml version=\"1.0\"?>\n");
13216 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);
13217
13218 if ((state & AST_EXTENSION_RINGING) && sip_cfg.notifyringing) {
13219
13220 char local_display[AST_MAX_EXTENSION * 2];
13221 char remote_display[AST_MAX_EXTENSION * 2];
13222 char *local_target = ast_strdupa(mto);
13223
13224
13225
13226
13227
13228
13229
13230
13231 char *remote_target = ast_strdupa(mto);
13232
13233 ast_xml_escape(exten, local_display, sizeof(local_display));
13234 ast_xml_escape(exten, remote_display, sizeof(remote_display));
13235
13236
13237
13238
13239 if (sip_cfg.notifycid) {
13240 struct ast_channel *caller;
13241
13242 if ((caller = ast_channel_callback(find_calling_channel, NULL, p, 0))) {
13243 static char *anonymous = "anonymous";
13244 static char *invalid = "anonymous.invalid";
13245 char *cid_num;
13246 char *connected_num;
13247 int need;
13248 int cid_num_restricted, connected_num_restricted;
13249
13250 ast_channel_lock(caller);
13251
13252 cid_num_restricted = (caller->caller.id.number.presentation &
13253 AST_PRES_RESTRICTION) == AST_PRES_RESTRICTED;
13254 cid_num = S_COR(caller->caller.id.number.valid,
13255 S_COR(cid_num_restricted, anonymous,
13256 caller->caller.id.number.str), "");
13257
13258 need = strlen(cid_num) + (cid_num_restricted ? strlen(invalid) :
13259 strlen(p->fromdomain)) + sizeof("sip:@");
13260
13261 remote_target = ast_alloca(need);
13262 snprintf(remote_target, need, "sip:%s@%s", cid_num,
13263 cid_num_restricted ? invalid : p->fromdomain);
13264
13265 ast_xml_escape(S_COR(caller->caller.id.name.valid,
13266 S_COR((caller->caller.id.name.presentation &
13267 AST_PRES_RESTRICTION) == AST_PRES_RESTRICTED, anonymous,
13268 caller->caller.id.name.str), ""),
13269 remote_display, sizeof(remote_display));
13270
13271 connected_num_restricted = (caller->connected.id.number.presentation &
13272 AST_PRES_RESTRICTION) == AST_PRES_RESTRICTED;
13273 connected_num = S_COR(caller->connected.id.number.valid,
13274 S_COR(connected_num_restricted, anonymous,
13275 caller->connected.id.number.str), "");
13276
13277 need = strlen(connected_num) + (connected_num_restricted ? strlen(invalid) :
13278 strlen(p->fromdomain)) + sizeof("sip:@");
13279 local_target = ast_alloca(need);
13280
13281 snprintf(local_target, need, "sip:%s@%s", connected_num,
13282 connected_num_restricted ? invalid : p->fromdomain);
13283
13284 ast_xml_escape(S_COR(caller->connected.id.name.valid,
13285 S_COR((caller->connected.id.name.presentation &
13286 AST_PRES_RESTRICTION) == AST_PRES_RESTRICTED, anonymous,
13287 caller->connected.id.name.str), ""),
13288 local_display, sizeof(local_display));
13289
13290 ast_channel_unlock(caller);
13291 caller = ast_channel_unref(caller);
13292 }
13293
13294
13295
13296 if (sip_cfg.pedanticsipchecking) {
13297 ast_str_append(tmp, 0, "<dialog id=\"%s\" call-id=\"pickup-%s\" local-tag=\"%s\" remote-tag=\"%s\" direction=\"recipient\">\n",
13298 exten, p->callid, p->theirtag, p->tag);
13299 } else {
13300 ast_str_append(tmp, 0, "<dialog id=\"%s\" call-id=\"pickup-%s\" direction=\"recipient\">\n",
13301 exten, p->callid);
13302 }
13303 ast_str_append(tmp, 0,
13304 "<remote>\n"
13305
13306
13307 "<identity display=\"%s\">%s</identity>\n"
13308 "<target uri=\"%s\"/>\n"
13309 "</remote>\n"
13310 "<local>\n"
13311 "<identity display=\"%s\">%s</identity>\n"
13312 "<target uri=\"%s\"/>\n"
13313 "</local>\n",
13314 remote_display, remote_target, remote_target, local_display, local_target, local_target);
13315 } else {
13316 ast_str_append(tmp, 0, "<dialog id=\"%s\" direction=\"recipient\">\n", exten);
13317 }
13318
13319 } else {
13320 ast_str_append(tmp, 0, "<dialog id=\"%s\">\n", exten);
13321 }
13322 ast_str_append(tmp, 0, "<state>%s</state>\n", statestring);
13323 if (state == AST_EXTENSION_ONHOLD) {
13324 ast_str_append(tmp, 0, "<local>\n<target uri=\"%s\">\n"
13325 "<param pname=\"+sip.rendering\" pvalue=\"no\"/>\n"
13326 "</target>\n</local>\n", mto);
13327 }
13328 ast_str_append(tmp, 0, "</dialog>\n</dialog-info>\n");
13329 break;
13330 case NONE:
13331 default:
13332 break;
13333 }
13334 }
13335
13336 static int transmit_cc_notify(struct ast_cc_agent *agent, struct sip_pvt *subscription, enum sip_cc_notify_state state)
13337 {
13338 struct sip_request req;
13339 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
13340 char uri[SIPBUFSIZE];
13341 char state_str[64];
13342 char subscription_state_hdr[64];
13343
13344 if (state < CC_QUEUED || state > CC_READY) {
13345 ast_log(LOG_WARNING, "Invalid state provided for transmit_cc_notify (%d)\n", state);
13346 return -1;
13347 }
13348
13349 reqprep(&req, subscription, SIP_NOTIFY, 0, TRUE);
13350 snprintf(state_str, sizeof(state_str), "%s\r\n", sip_cc_notify_state_map[state].state_string);
13351 add_header(&req, "Event", "call-completion");
13352 add_header(&req, "Content-Type", "application/call-completion");
13353 snprintf(subscription_state_hdr, sizeof(subscription_state_hdr), "active;expires=%d", subscription->expiry);
13354 add_header(&req, "Subscription-State", subscription_state_hdr);
13355 if (state == CC_READY) {
13356 generate_uri(subscription, agent_pvt->notify_uri, sizeof(agent_pvt->notify_uri));
13357 snprintf(uri, sizeof(uri) - 1, "cc-URI: %s\r\n", agent_pvt->notify_uri);
13358 }
13359 add_content(&req, state_str);
13360 if (state == CC_READY) {
13361 add_content(&req, uri);
13362 }
13363 return send_request(subscription, &req, XMIT_RELIABLE, subscription->ocseq);
13364 }
13365
13366
13367 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout)
13368 {
13369 struct ast_str *tmp = ast_str_alloca(4000);
13370 char from[256], to[256];
13371 char *c, *mfrom, *mto;
13372 struct sip_request req;
13373 const struct cfsubscription_types *subscriptiontype;
13374
13375
13376 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
13377 return 0;
13378 }
13379
13380 memset(from, 0, sizeof(from));
13381 memset(to, 0, sizeof(to));
13382
13383 subscriptiontype = find_subscription_type(p->subscribed);
13384
13385 ast_copy_string(from, get_header(&p->initreq, "From"), sizeof(from));
13386 c = get_in_brackets(from);
13387 if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
13388 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
13389 return -1;
13390 }
13391
13392 mfrom = remove_uri_parameters(c);
13393
13394 ast_copy_string(to, get_header(&p->initreq, "To"), sizeof(to));
13395 c = get_in_brackets(to);
13396 if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
13397 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
13398 return -1;
13399 }
13400 mto = remove_uri_parameters(c);
13401
13402 reqprep(&req, p, SIP_NOTIFY, 0, 1);
13403
13404 switch(state) {
13405 case AST_EXTENSION_DEACTIVATED:
13406 if (timeout)
13407 add_header(&req, "Subscription-State", "terminated;reason=timeout");
13408 else {
13409 add_header(&req, "Subscription-State", "terminated;reason=probation");
13410 add_header(&req, "Retry-After", "60");
13411 }
13412 break;
13413 case AST_EXTENSION_REMOVED:
13414 add_header(&req, "Subscription-State", "terminated;reason=noresource");
13415 break;
13416 default:
13417 if (p->expiry)
13418 add_header(&req, "Subscription-State", "active");
13419 else
13420 add_header(&req, "Subscription-State", "terminated;reason=timeout");
13421 }
13422
13423 switch (p->subscribed) {
13424 case XPIDF_XML:
13425 case CPIM_PIDF_XML:
13426 add_header(&req, "Event", subscriptiontype->event);
13427 state_notify_build_xml(state, full, p->exten, p->context, &tmp, p, p->subscribed, mfrom, mto);
13428 add_header(&req, "Content-Type", subscriptiontype->mediatype);
13429 p->dialogver++;
13430 break;
13431 case PIDF_XML:
13432 add_header(&req, "Event", subscriptiontype->event);
13433 state_notify_build_xml(state, full, p->exten, p->context, &tmp, p, p->subscribed, mfrom, mto);
13434 add_header(&req, "Content-Type", subscriptiontype->mediatype);
13435 p->dialogver++;
13436 break;
13437 case DIALOG_INFO_XML:
13438 add_header(&req, "Event", subscriptiontype->event);
13439 state_notify_build_xml(state, full, p->exten, p->context, &tmp, p, p->subscribed, mfrom, mto);
13440 add_header(&req, "Content-Type", subscriptiontype->mediatype);
13441 p->dialogver++;
13442 break;
13443 case NONE:
13444 default:
13445 break;
13446 }
13447
13448 add_content(&req, ast_str_buffer(tmp));
13449
13450 p->pendinginvite = p->ocseq;
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465 return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
13466 }
13467
13468
13469
13470
13471
13472
13473
13474 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten)
13475 {
13476 struct sip_request req;
13477 struct ast_str *out = ast_str_alloca(500);
13478 int ourport = (p->fromdomainport) ? p->fromdomainport : ast_sockaddr_port(&p->ourip);
13479 const char *domain;
13480 const char *exten = S_OR(vmexten, default_vmexten);
13481
13482 initreqprep(&req, p, SIP_NOTIFY, NULL);
13483 add_header(&req, "Event", "message-summary");
13484 add_header(&req, "Content-Type", default_notifymime);
13485 ast_str_append(&out, 0, "Messages-Waiting: %s\r\n", newmsgs ? "yes" : "no");
13486
13487
13488 domain = S_OR(p->fromdomain, ast_sockaddr_stringify_host_remote(&p->ourip));
13489
13490 if (!sip_standard_port(p->socket.type, ourport)) {
13491 if (p->socket.type == SIP_TRANSPORT_UDP) {
13492 ast_str_append(&out, 0, "Message-Account: sip:%s@%s:%d\r\n", exten, domain, ourport);
13493 } else {
13494 ast_str_append(&out, 0, "Message-Account: sip:%s@%s:%d;transport=%s\r\n", exten, domain, ourport, get_transport(p->socket.type));
13495 }
13496 } else {
13497 if (p->socket.type == SIP_TRANSPORT_UDP) {
13498 ast_str_append(&out, 0, "Message-Account: sip:%s@%s\r\n", exten, domain);
13499 } else {
13500 ast_str_append(&out, 0, "Message-Account: sip:%s@%s;transport=%s\r\n", exten, domain, get_transport(p->socket.type));
13501 }
13502 }
13503
13504
13505
13506 ast_str_append(&out, 0, "Voice-Message: %d/%d%s\r\n",
13507 newmsgs, oldmsgs, (ast_test_flag(&p->flags[1], SIP_PAGE2_BUGGY_MWI) ? "" : " (0/0)"));
13508
13509 if (p->subscribed) {
13510 if (p->expiry) {
13511 add_header(&req, "Subscription-State", "active");
13512 } else {
13513 add_header(&req, "Subscription-State", "terminated;reason=timeout");
13514 }
13515 }
13516
13517 add_content(&req, ast_str_buffer(out));
13518
13519 if (!p->initreq.headers) {
13520 initialize_initreq(p, &req);
13521 }
13522 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
13523 }
13524
13525
13526 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate)
13527 {
13528 struct sip_request req;
13529 char tmp[SIPBUFSIZE/2];
13530
13531 reqprep(&req, p, SIP_NOTIFY, 0, 1);
13532 snprintf(tmp, sizeof(tmp), "refer;id=%d", cseq);
13533 add_header(&req, "Event", tmp);
13534 add_header(&req, "Subscription-state", terminate ? "terminated;reason=noresource" : "active");
13535 add_header(&req, "Content-Type", "message/sipfrag;version=2.0");
13536 add_header(&req, "Allow", ALLOWED_METHODS);
13537 add_supported_header(p, &req);
13538
13539 snprintf(tmp, sizeof(tmp), "SIP/2.0 %s\r\n", message);
13540 add_content(&req, tmp);
13541
13542 if (!p->initreq.headers) {
13543 initialize_initreq(p, &req);
13544 }
13545
13546 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
13547 }
13548
13549 static int manager_sipnotify(struct mansession *s, const struct message *m)
13550 {
13551 const char *channame = astman_get_header(m, "Channel");
13552 struct ast_variable *vars = astman_get_variables(m);
13553 struct sip_pvt *p;
13554 struct ast_variable *header, *var;
13555
13556 if (ast_strlen_zero(channame)) {
13557 astman_send_error(s, m, "SIPNotify requires a channel name");
13558 return 0;
13559 }
13560
13561 if (!strncasecmp(channame, "sip/", 4)) {
13562 channame += 4;
13563 }
13564
13565 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
13566 astman_send_error(s, m, "Unable to build sip pvt data for notify (memory/socket error)");
13567 return 0;
13568 }
13569
13570 if (create_addr(p, channame, NULL, 0)) {
13571
13572 dialog_unlink_all(p);
13573 dialog_unref(p, "unref dialog inside for loop" );
13574
13575 astman_send_error(s, m, "Could not create address");
13576 return 0;
13577 }
13578
13579
13580 ast_set_flag(&p->flags[0], SIP_OUTGOING);
13581 sip_notify_allocate(p);
13582
13583 p->notify->headers = header = ast_variable_new("Subscription-State", "terminated", "");
13584
13585 for (var = vars; var; var = var->next) {
13586 if (!strcasecmp(var->name, "Content")) {
13587 if (ast_str_strlen(p->notify->content))
13588 ast_str_append(&p->notify->content, 0, "\r\n");
13589 ast_str_append(&p->notify->content, 0, "%s", var->value);
13590 } else if (!strcasecmp(var->name, "Content-Length")) {
13591 ast_log(LOG_WARNING, "it is not necessary to specify Content-Length, ignoring\n");
13592 } else {
13593 header->next = ast_variable_new(var->name, var->value, "");
13594 header = header->next;
13595 }
13596 }
13597
13598 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
13599 transmit_invite(p, SIP_NOTIFY, 0, 2, NULL);
13600 dialog_unref(p, "bump down the count of p since we're done with it.");
13601
13602 astman_send_ack(s, m, "Notify Sent");
13603 ast_variables_destroy(vars);
13604 return 0;
13605 }
13606
13607
13608
13609 static void update_redirecting(struct sip_pvt *p, const void *data, size_t datalen)
13610 {
13611 struct sip_request resp;
13612
13613 if (p->owner->_state == AST_STATE_UP || ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
13614 return;
13615 }
13616
13617 respprep(&resp, p, "181 Call is being forwarded", &p->initreq);
13618 add_diversion_header(&resp, p);
13619 send_response(p, &resp, XMIT_UNRELIABLE, 0);
13620 }
13621
13622
13623 static void update_connectedline(struct sip_pvt *p, const void *data, size_t datalen)
13624 {
13625
13626 if (!ast_test_flag(&p->flags[0], SIP_SENDRPID)) {
13627 return;
13628 }
13629 if (!p->owner->connected.id.number.valid
13630 || ast_strlen_zero(p->owner->connected.id.number.str)) {
13631 return;
13632 }
13633
13634 append_history(p, "ConnectedLine", "%s party is now %s <%s>",
13635 ast_test_flag(&p->flags[0], SIP_OUTGOING) ? "Calling" : "Called",
13636 S_COR(p->owner->connected.id.name.valid, p->owner->connected.id.name.str, ""),
13637 S_COR(p->owner->connected.id.number.valid, p->owner->connected.id.number.str, ""));
13638
13639 if (p->owner->_state == AST_STATE_UP || ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
13640 struct sip_request req;
13641
13642 if (!p->pendinginvite && (p->invitestate == INV_CONFIRMED || p->invitestate == INV_TERMINATED)) {
13643 reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ? SIP_UPDATE : SIP_INVITE, 0, 1);
13644
13645 add_header(&req, "Allow", ALLOWED_METHODS);
13646 add_supported_header(p, &req);
13647 add_rpid(&req, p);
13648 add_sdp(&req, p, FALSE, TRUE, FALSE);
13649
13650 initialize_initreq(p, &req);
13651 p->lastinvite = p->ocseq;
13652 ast_set_flag(&p->flags[0], SIP_OUTGOING);
13653 p->invitestate = INV_CALLING;
13654 send_request(p, &req, XMIT_CRITICAL, p->ocseq);
13655 } else if ((is_method_allowed(&p->allowed_methods, SIP_UPDATE)) && (!ast_strlen_zero(p->okcontacturi))) {
13656 reqprep(&req, p, SIP_UPDATE, 0, 1);
13657 add_rpid(&req, p);
13658 add_header(&req, "X-Asterisk-rpid-update", "Yes");
13659 send_request(p, &req, XMIT_CRITICAL, p->ocseq);
13660 } else {
13661
13662 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
13663 }
13664 } else {
13665 ast_set_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND);
13666 if (ast_test_flag(&p->flags[1], SIP_PAGE2_RPID_IMMEDIATE)) {
13667 struct sip_request resp;
13668
13669 if ((p->owner->_state == AST_STATE_RING) && !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT)) {
13670 ast_clear_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND);
13671 respprep(&resp, p, "180 Ringing", &p->initreq);
13672 add_rpid(&resp, p);
13673 send_response(p, &resp, XMIT_UNRELIABLE, 0);
13674 ast_set_flag(&p->flags[0], SIP_RINGING);
13675 } else if (p->owner->_state == AST_STATE_RINGING) {
13676 ast_clear_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND);
13677 respprep(&resp, p, "183 Session Progress", &p->initreq);
13678 add_rpid(&resp, p);
13679 send_response(p, &resp, XMIT_UNRELIABLE, 0);
13680 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
13681 } else {
13682 ast_debug(1, "Unable able to send update to '%s' in state '%s'\n", p->owner->name, ast_state2str(p->owner->_state));
13683 }
13684 }
13685 }
13686 }
13687
13688 static const struct _map_x_s regstatestrings[] = {
13689 { REG_STATE_FAILED, "Failed" },
13690 { REG_STATE_UNREGISTERED, "Unregistered"},
13691 { REG_STATE_REGSENT, "Request Sent"},
13692 { REG_STATE_AUTHSENT, "Auth. Sent"},
13693 { REG_STATE_REGISTERED, "Registered"},
13694 { REG_STATE_REJECTED, "Rejected"},
13695 { REG_STATE_TIMEOUT, "Timeout"},
13696 { REG_STATE_NOAUTH, "No Authentication"},
13697 { -1, NULL }
13698 };
13699
13700
13701 static const char *regstate2str(enum sipregistrystate regstate)
13702 {
13703 return map_x_s(regstatestrings, regstate, "Unknown");
13704 }
13705
13706
13707
13708
13709
13710
13711
13712 static int sip_reregister(const void *data)
13713 {
13714
13715 struct sip_registry *r = (struct sip_registry *) data;
13716
13717
13718 if (!r) {
13719 return 0;
13720 }
13721
13722 if (r->call && r->call->do_history) {
13723 append_history(r->call, "RegistryRenew", "Account: %s@%s", r->username, r->hostname);
13724 }
13725
13726
13727 if (sipdebug) {
13728 ast_log(LOG_NOTICE, " -- Re-registration for %s@%s\n", r->username, r->hostname);
13729 }
13730
13731 r->expire = -1;
13732 r->expiry = r->configured_expiry;
13733 __sip_do_register(r);
13734 registry_unref(r, "unref the re-register scheduled event");
13735 return 0;
13736 }
13737
13738
13739
13740
13741 static int __sip_do_register(struct sip_registry *r)
13742 {
13743 int res;
13744
13745 res = transmit_register(r, SIP_REGISTER, NULL, NULL);
13746 return res;
13747 }
13748
13749
13750
13751
13752
13753
13754
13755 static int sip_reg_timeout(const void *data)
13756 {
13757
13758
13759 struct sip_registry *r = (struct sip_registry *)data;
13760 struct sip_pvt *p;
13761
13762
13763 if (!r) {
13764 return 0;
13765 }
13766
13767 if (r->dnsmgr) {
13768
13769 ast_dnsmgr_refresh(r->dnsmgr);
13770 }
13771
13772
13773
13774
13775
13776 if (r->call) {
13777
13778
13779 p = r->call;
13780 sip_pvt_lock(p);
13781 pvt_set_needdestroy(p, "registration timeout");
13782
13783 __sip_pretend_ack(p);
13784 sip_pvt_unlock(p);
13785
13786
13787
13788 if (p->registry) {
13789 p->registry = registry_unref(p->registry, "p->registry unreffed");
13790 }
13791 r->call = dialog_unref(r->call, "unrefing r->call");
13792 }
13793
13794 r->timeout = -1;
13795 if (global_regattempts_max && r->regattempts >= global_regattempts_max) {
13796
13797
13798
13799 ast_log(LOG_NOTICE, " -- Last Registration Attempt #%d failed, Giving up forever trying to register '%s@%s'\n", r->regattempts, r->username, r->hostname);
13800 r->regstate = REG_STATE_FAILED;
13801 } else {
13802 r->regstate = REG_STATE_UNREGISTERED;
13803 transmit_register(r, SIP_REGISTER, NULL, NULL);
13804 ast_log(LOG_NOTICE, " -- Registration for '%s@%s' timed out, trying again (Attempt #%d)\n", r->username, r->hostname, r->regattempts);
13805 }
13806 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));
13807 registry_unref(r, "unreffing registry_unref r");
13808 return 0;
13809 }
13810
13811 static const char *sip_sanitized_host(const char *host)
13812 {
13813 struct ast_sockaddr addr = { { 0, 0, }, };
13814
13815
13816
13817
13818 if (!ast_sockaddr_parse(&addr, host, PARSE_PORT_FORBID)) {
13819 return host;
13820 }
13821 return ast_sockaddr_stringify_host_remote(&addr);
13822 }
13823
13824
13825
13826
13827 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader)
13828 {
13829 struct sip_request req;
13830 char from[256];
13831 char to[256];
13832 char tmp[80];
13833 char addr[80];
13834 struct sip_pvt *p;
13835 struct sip_peer *peer = NULL;
13836 int res;
13837 int portno = 0;
13838
13839
13840 if (r == NULL || ((auth == NULL) && (r->regstate == REG_STATE_REGSENT || r->regstate == REG_STATE_AUTHSENT))) {
13841 if (r) {
13842 ast_log(LOG_NOTICE, "Strange, trying to register %s@%s when registration already pending\n", r->username, r->hostname);
13843 }
13844 return 0;
13845 }
13846
13847 if (r->dnsmgr == NULL) {
13848 char transport[MAXHOSTNAMELEN];
13849 peer = find_peer(r->hostname, NULL, TRUE, FINDPEERS, FALSE, 0);
13850 snprintf(transport, sizeof(transport), "_%s._%s",get_srv_service(r->transport), get_srv_protocol(r->transport));
13851 r->us.ss.ss_family = get_address_family_filter(r->transport);
13852
13853
13854
13855
13856
13857 if (!obproxy_get(r->call, peer)) {
13858 registry_addref(r, "add reg ref for dnsmgr");
13859 ast_dnsmgr_lookup_cb(peer ? peer->tohost : r->hostname, &r->us, &r->dnsmgr, sip_cfg.srvlookup ? transport : NULL, on_dns_update_registry, r);
13860 if (!r->dnsmgr) {
13861
13862 registry_unref(r, "remove reg ref, dnsmgr disabled");
13863 }
13864 }
13865 if (peer) {
13866 peer = unref_peer(peer, "removing peer ref for dnsmgr_lookup");
13867 }
13868 }
13869
13870 if (r->call) {
13871 if (!auth) {
13872 ast_log(LOG_WARNING, "Already have a REGISTER going on to %s@%s?? \n", r->username, r->hostname);
13873 return 0;
13874 } else {
13875 p = dialog_ref(r->call, "getting a copy of the r->call dialog in transmit_register");
13876 ast_string_field_set(p, theirtag, NULL);
13877 }
13878 } else {
13879
13880 if (!r->callid_valid) {
13881 build_callid_registry(r, &internip, default_fromdomain);
13882 build_localtag_registry(r);
13883 r->callid_valid = TRUE;
13884 }
13885
13886 if (!(p = sip_alloc( r->callid, NULL, 0, SIP_REGISTER, NULL))) {
13887 ast_log(LOG_WARNING, "Unable to allocate registration transaction (memory or socket error)\n");
13888 return 0;
13889 }
13890
13891
13892 ast_string_field_set(p, tag, r->localtag);
13893
13894 if (p->do_history) {
13895 append_history(p, "RegistryInit", "Account: %s@%s", r->username, r->hostname);
13896 }
13897
13898 p->socket.type = r->transport;
13899
13900
13901 if (!ast_sockaddr_isnull(&r->us)) {
13902 if (!ast_sockaddr_port(&r->us) && r->portno) {
13903 ast_sockaddr_set_port(&r->us, r->portno);
13904 }
13905
13906
13907
13908
13909
13910 if ((peer = find_peer(S_OR(r->peername, r->hostname), NULL, TRUE, FINDPEERS, FALSE, 0))) {
13911 if (ast_sockaddr_cmp(&peer->addr, &r->us)) {
13912 on_dns_update_peer(&peer->addr, &r->us, peer);
13913 }
13914 peer = unref_peer(peer, "unref after find_peer");
13915 }
13916 }
13917
13918
13919 if (create_addr(p, S_OR(r->peername, r->hostname), &r->us, 0)) {
13920
13921
13922 dialog_unlink_all(p);
13923 p = dialog_unref(p, "unref dialog after unlink_all");
13924 if (r->timeout > -1) {
13925 AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
13926 registry_unref(_data, "del for REPLACE of registry ptr"),
13927 registry_unref(r, "object ptr dec when SCHED_REPLACE add failed"),
13928 registry_addref(r,"add for REPLACE registry ptr"));
13929 ast_log(LOG_WARNING, "Still have a registration timeout for %s@%s (create_addr() error), %d\n", r->username, r->hostname, r->timeout);
13930 } else {
13931 r->timeout = ast_sched_add(sched, global_reg_timeout * 1000, sip_reg_timeout, registry_addref(r, "add for REPLACE registry ptr"));
13932 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);
13933 }
13934 r->regattempts++;
13935 return 0;
13936 }
13937
13938
13939 ast_string_field_set(r, callid, p->callid);
13940
13941 if (!r->dnsmgr && r->portno) {
13942 ast_sockaddr_set_port(&p->sa, r->portno);
13943 ast_sockaddr_set_port(&p->recv, r->portno);
13944 }
13945 if (!ast_strlen_zero(p->fromdomain)) {
13946 portno = (p->fromdomainport) ? p->fromdomainport : STANDARD_SIP_PORT;
13947 } else if (!ast_strlen_zero(r->regdomain)) {
13948 portno = (r->regdomainport) ? r->regdomainport : STANDARD_SIP_PORT;
13949 } else {
13950 portno = ast_sockaddr_port(&p->sa);
13951 }
13952
13953 ast_set_flag(&p->flags[0], SIP_OUTGOING);
13954 r->call = dialog_ref(p, "copying dialog into registry r->call");
13955 p->registry = registry_addref(r, "transmit_register: addref to p->registry in transmit_register");
13956 if (!ast_strlen_zero(r->secret)) {
13957 ast_string_field_set(p, peersecret, r->secret);
13958 }
13959 if (!ast_strlen_zero(r->md5secret))
13960 ast_string_field_set(p, peermd5secret, r->md5secret);
13961
13962
13963 if (!ast_strlen_zero(r->authuser)) {
13964 ast_string_field_set(p, peername, r->authuser);
13965 ast_string_field_set(p, authname, r->authuser);
13966 } else if (!ast_strlen_zero(r->username)) {
13967 ast_string_field_set(p, peername, r->username);
13968 ast_string_field_set(p, authname, r->username);
13969 ast_string_field_set(p, fromuser, r->username);
13970 }
13971 if (!ast_strlen_zero(r->username)) {
13972 ast_string_field_set(p, username, r->username);
13973 }
13974
13975 if (!ast_strlen_zero(r->callback)) {
13976 ast_string_field_set(p, exten, r->callback);
13977 }
13978
13979
13980 set_socket_transport(&p->socket, r->transport);
13981 if (r->transport == SIP_TRANSPORT_TLS || r->transport == SIP_TRANSPORT_TCP) {
13982 p->socket.port =
13983 htons(ast_sockaddr_port(&sip_tcp_desc.local_address));
13984 }
13985
13986
13987
13988
13989
13990
13991 ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
13992 build_contact(p);
13993 }
13994
13995
13996 if (auth == NULL) {
13997 if (r->timeout > -1) {
13998 ast_log(LOG_WARNING, "Still have a registration timeout, #%d - deleting it\n", r->timeout);
13999 }
14000 AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
14001 registry_unref(_data,"reg ptr unrefed from del in SCHED_REPLACE"),
14002 registry_unref(r,"reg ptr unrefed from add failure in SCHED_REPLACE"),
14003 registry_addref(r,"reg ptr reffed from add in SCHED_REPLACE"));
14004 ast_debug(1, "Scheduled a registration timeout for %s id #%d \n", r->hostname, r->timeout);
14005 }
14006
14007 snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%s", r->username, S_OR(r->regdomain, sip_sanitized_host(p->tohost)), p->tag);
14008 if (!ast_strlen_zero(p->theirtag)) {
14009 snprintf(to, sizeof(to), "<sip:%s@%s>;tag=%s", r->username, S_OR(r->regdomain, sip_sanitized_host(p->tohost)), p->theirtag);
14010 } else {
14011 snprintf(to, sizeof(to), "<sip:%s@%s>", r->username, S_OR(r->regdomain, sip_sanitized_host(p->tohost)));
14012 }
14013
14014
14015
14016 if (portno && portno != STANDARD_SIP_PORT) {
14017 snprintf(addr, sizeof(addr), "sip:%s:%d", S_OR(p->fromdomain,S_OR(r->regdomain, sip_sanitized_host(r->hostname))), portno);
14018 } else {
14019 snprintf(addr, sizeof(addr), "sip:%s", S_OR(p->fromdomain,S_OR(r->regdomain, sip_sanitized_host(r->hostname))));
14020 }
14021
14022 ast_string_field_set(p, uri, addr);
14023
14024 p->branch ^= ast_random();
14025
14026 init_req(&req, sipmethod, addr);
14027
14028
14029 snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, sip_methods[sipmethod].text);
14030 p->ocseq = r->ocseq;
14031
14032 build_via(p);
14033 add_header(&req, "Via", p->via);
14034 add_header_max_forwards(p, &req);
14035 add_header(&req, "From", from);
14036 add_header(&req, "To", to);
14037 add_header(&req, "Call-ID", p->callid);
14038 add_header(&req, "CSeq", tmp);
14039 if (!ast_strlen_zero(global_useragent))
14040 add_header(&req, "User-Agent", global_useragent);
14041
14042 if (auth) {
14043 add_header(&req, authheader, auth);
14044 } else if (!ast_strlen_zero(r->nonce)) {
14045 char digest[1024];
14046
14047
14048
14049
14050
14051
14052 if (sipdebug) {
14053 ast_debug(1, " >>> Re-using Auth data for %s@%s\n", r->username, r->hostname);
14054 }
14055 ast_string_field_set(p, realm, r->realm);
14056 ast_string_field_set(p, nonce, r->nonce);
14057 ast_string_field_set(p, domain, r->authdomain);
14058 ast_string_field_set(p, opaque, r->opaque);
14059 ast_string_field_set(p, qop, r->qop);
14060 p->noncecount = ++r->noncecount;
14061
14062 memset(digest, 0, sizeof(digest));
14063 if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
14064 add_header(&req, "Authorization", digest);
14065 } else {
14066 ast_log(LOG_NOTICE, "No authorization available for authentication of registration to %s@%s\n", r->username, r->hostname);
14067 }
14068 }
14069
14070 snprintf(tmp, sizeof(tmp), "%d", r->expiry);
14071 add_header(&req, "Expires", tmp);
14072 add_header(&req, "Contact", p->our_contact);
14073
14074 initialize_initreq(p, &req);
14075 if (sip_debug_test_pvt(p)) {
14076 ast_verbose("REGISTER %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
14077 }
14078 r->regstate = auth ? REG_STATE_AUTHSENT : REG_STATE_REGSENT;
14079 r->regattempts++;
14080 ast_debug(4, "REGISTER attempt %d to %s@%s\n", r->regattempts, r->username, r->hostname);
14081 res = send_request(p, &req, XMIT_CRITICAL, p->ocseq);
14082 dialog_unref(p, "p is finished here at the end of transmit_register");
14083 return res;
14084 }
14085
14086
14087 static int transmit_message_with_text(struct sip_pvt *p, const char *text)
14088 {
14089 struct sip_request req;
14090
14091 reqprep(&req, p, SIP_MESSAGE, 0, 1);
14092 add_text(&req, text);
14093 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
14094 }
14095
14096
14097 static int sip_refer_allocate(struct sip_pvt *p)
14098 {
14099 p->refer = ast_calloc(1, sizeof(struct sip_refer));
14100 return p->refer ? 1 : 0;
14101 }
14102
14103
14104 static int sip_notify_allocate(struct sip_pvt *p)
14105 {
14106 p->notify = ast_calloc(1, sizeof(struct sip_notify));
14107 if (p->notify) {
14108 p->notify->content = ast_str_create(128);
14109 }
14110 return p->notify ? 1 : 0;
14111 }
14112
14113
14114
14115
14116
14117
14118 static int transmit_refer(struct sip_pvt *p, const char *dest)
14119 {
14120 struct sip_request req = {
14121 .headers = 0,
14122 };
14123 char from[256];
14124 const char *of;
14125 char *c;
14126 char referto[256];
14127 int use_tls=FALSE;
14128
14129 if (sipdebug) {
14130 ast_debug(1, "SIP transfer of %s to %s\n", p->callid, dest);
14131 }
14132
14133
14134 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
14135 of = get_header(&p->initreq, "To");
14136 } else {
14137 of = get_header(&p->initreq, "From");
14138 }
14139
14140 ast_copy_string(from, of, sizeof(from));
14141 of = get_in_brackets(from);
14142 ast_string_field_set(p, from, of);
14143 if (!strncasecmp(of, "sip:", 4)) {
14144 of += 4;
14145 } else if (!strncasecmp(of, "sips:", 5)) {
14146 of += 5;
14147 use_tls = TRUE;
14148 } else {
14149 ast_log(LOG_NOTICE, "From address missing 'sip(s):', assuming sip:\n");
14150 }
14151
14152 if (strchr(dest, '@')) {
14153 c = NULL;
14154 } else if ((c = strchr(of, '@'))) {
14155 *c++ = '\0';
14156 }
14157 if (c) {
14158 snprintf(referto, sizeof(referto), "<sip%s:%s@%s>", use_tls ? "s" : "", dest, c);
14159 } else {
14160 snprintf(referto, sizeof(referto), "<sip%s:%s>", use_tls ? "s" : "", dest);
14161 }
14162
14163
14164 sip_refer_allocate(p);
14165 ast_copy_string(p->refer->refer_to, referto, sizeof(p->refer->refer_to));
14166 ast_copy_string(p->refer->referred_by, p->our_contact, sizeof(p->refer->referred_by));
14167 p->refer->status = REFER_SENT;
14168
14169 reqprep(&req, p, SIP_REFER, 0, 1);
14170
14171 add_header(&req, "Refer-To", referto);
14172 add_header(&req, "Allow", ALLOWED_METHODS);
14173 add_supported_header(p, &req);
14174 if (!ast_strlen_zero(p->our_contact)) {
14175 add_header(&req, "Referred-By", p->our_contact);
14176 }
14177
14178 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188 }
14189
14190
14191 static int transmit_info_with_aoc(struct sip_pvt *p, struct ast_aoc_decoded *decoded)
14192 {
14193 struct sip_request req;
14194 struct ast_str *str = ast_str_alloca(512);
14195 const struct ast_aoc_unit_entry *unit_entry = ast_aoc_get_unit_info(decoded, 0);
14196 enum ast_aoc_charge_type charging = ast_aoc_get_charge_type(decoded);
14197
14198 reqprep(&req, p, SIP_INFO, 0, 1);
14199
14200 if (ast_aoc_get_msg_type(decoded) == AST_AOC_D) {
14201 ast_str_append(&str, 0, "type=active;");
14202 } else if (ast_aoc_get_msg_type(decoded) == AST_AOC_E) {
14203 ast_str_append(&str, 0, "type=terminated;");
14204 } else {
14205
14206 return -1;
14207 }
14208
14209 switch (charging) {
14210 case AST_AOC_CHARGE_FREE:
14211 ast_str_append(&str, 0, "free-of-charge;");
14212 break;
14213 case AST_AOC_CHARGE_CURRENCY:
14214 ast_str_append(&str, 0, "charging;");
14215 ast_str_append(&str, 0, "charging-info=currency;");
14216 ast_str_append(&str, 0, "amount=%u;", ast_aoc_get_currency_amount(decoded));
14217 ast_str_append(&str, 0, "multiplier=%s;", ast_aoc_get_currency_multiplier_decimal(decoded));
14218 if (!ast_strlen_zero(ast_aoc_get_currency_name(decoded))) {
14219 ast_str_append(&str, 0, "currency=%s;", ast_aoc_get_currency_name(decoded));
14220 }
14221 break;
14222 case AST_AOC_CHARGE_UNIT:
14223 ast_str_append(&str, 0, "charging;");
14224 ast_str_append(&str, 0, "charging-info=pulse;");
14225 if (unit_entry) {
14226 ast_str_append(&str, 0, "recorded-units=%u;", unit_entry->amount);
14227 }
14228 break;
14229 default:
14230 ast_str_append(&str, 0, "not-available;");
14231 };
14232
14233 add_header(&req, "AOC", ast_str_buffer(str));
14234
14235 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
14236 }
14237
14238
14239 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration)
14240 {
14241 struct sip_request req;
14242
14243 reqprep(&req, p, SIP_INFO, 0, 1);
14244 add_digit(&req, digit, duration, (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_SHORTINFO));
14245 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
14246 }
14247
14248
14249 static int transmit_info_with_vidupdate(struct sip_pvt *p)
14250 {
14251 struct sip_request req;
14252
14253 reqprep(&req, p, SIP_INFO, 0, 1);
14254 add_vidupdate(&req);
14255 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
14256 }
14257
14258
14259
14260
14261 static int transmit_request(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch)
14262 {
14263 struct sip_request resp;
14264
14265 reqprep(&resp, p, sipmethod, seqno, newbranch);
14266 if (sipmethod == SIP_CANCEL && p->answered_elsewhere) {
14267 add_header(&resp, "Reason", "SIP;cause=200;text=\"Call completed elsewhere\"");
14268 }
14269
14270 if (sipmethod == SIP_ACK) {
14271 p->invitestate = INV_CONFIRMED;
14272 }
14273
14274 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
14275 }
14276
14277
14278 static void auth_headers(enum sip_auth_type code, char **header, char **respheader)
14279 {
14280 if (code == WWW_AUTH) {
14281 *header = "WWW-Authenticate";
14282 *respheader = "Authorization";
14283 } else if (code == PROXY_AUTH) {
14284 *header = "Proxy-Authenticate";
14285 *respheader = "Proxy-Authorization";
14286 } else {
14287 ast_verbose("-- wrong response code %d\n", code);
14288 *header = *respheader = "Invalid";
14289 }
14290 }
14291
14292
14293 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch)
14294 {
14295 struct sip_request resp;
14296
14297 reqprep(&resp, p, sipmethod, seqno, newbranch);
14298 if (!ast_strlen_zero(p->realm)) {
14299 char digest[1024];
14300
14301 memset(digest, 0, sizeof(digest));
14302 if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
14303 char *dummy, *response;
14304 enum sip_auth_type code = p->options ? p->options->auth_type : PROXY_AUTH;
14305 auth_headers(code, &dummy, &response);
14306 add_header(&resp, response, digest);
14307 } else {
14308 ast_log(LOG_WARNING, "No authentication available for call %s\n", p->callid);
14309 }
14310 }
14311
14312
14313 if (sipmethod == SIP_BYE) {
14314 char buf[20];
14315
14316 if (ast_test_flag(&p->flags[1], SIP_PAGE2_Q850_REASON) && p->hangupcause) {
14317 sprintf(buf, "Q.850;cause=%i", p->hangupcause & 0x7f);
14318 add_header(&resp, "Reason", buf);
14319 }
14320
14321 add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->hangupcause));
14322 snprintf(buf, sizeof(buf), "%d", p->hangupcause);
14323 add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
14324 }
14325
14326 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
14327 }
14328
14329
14330 static void destroy_association(struct sip_peer *peer)
14331 {
14332 int realtimeregs = ast_check_realtime("sipregs");
14333 char *tablename = (realtimeregs) ? "sipregs" : "sippeers";
14334
14335 if (!sip_cfg.ignore_regexpire) {
14336 if (peer->rt_fromcontact && sip_cfg.peer_rtupdate) {
14337 ast_update_realtime(tablename, "name", peer->name, "fullcontact", "", "ipaddr", "", "port", "", "regseconds", "0", "regserver", "", "useragent", "", "lastms", "0", SENTINEL);
14338 } else {
14339 ast_db_del("SIP/Registry", peer->name);
14340 ast_db_del("SIP/PeerMethods", peer->name);
14341 }
14342 }
14343 }
14344
14345 static void set_socket_transport(struct sip_socket *socket, int transport)
14346 {
14347
14348 if (socket->type != transport) {
14349 socket->fd = -1;
14350 socket->type = transport;
14351 if (socket->tcptls_session) {
14352 ao2_ref(socket->tcptls_session, -1);
14353 socket->tcptls_session = NULL;
14354 }
14355 }
14356 }
14357
14358
14359 static int expire_register(const void *data)
14360 {
14361 struct sip_peer *peer = (struct sip_peer *)data;
14362
14363 if (!peer) {
14364 return 0;
14365 }
14366
14367 peer->expire = -1;
14368 peer->portinuri = 0;
14369
14370 destroy_association(peer);
14371 set_socket_transport(&peer->socket, peer->default_outbound_transport);
14372
14373 if (peer->socket.tcptls_session) {
14374 ao2_ref(peer->socket.tcptls_session, -1);
14375 peer->socket.tcptls_session = NULL;
14376 }
14377
14378 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
14379 register_peer_exten(peer, FALSE);
14380 ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "SIP/%s", peer->name);
14381
14382
14383
14384
14385 if (peer->is_realtime) {
14386 ast_debug(3, "-REALTIME- peer expired registration. Name: %s. Realtime peer objects now %d\n", peer->name, rpeerobjs);
14387 }
14388
14389 if (peer->selfdestruct ||
14390 ast_test_flag(&peer->flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
14391 unlink_peer_from_tables(peer);
14392 } else if (!ast_sockaddr_isnull(&peer->addr)) {
14393
14394
14395
14396 ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
14397 }
14398
14399
14400
14401 memset(&peer->addr, 0, sizeof(peer->addr));
14402
14403 unref_peer(peer, "removing peer ref for expire_register");
14404
14405 return 0;
14406 }
14407
14408
14409 static int sip_poke_peer_s(const void *data)
14410 {
14411 struct sip_peer *peer = (struct sip_peer *)data;
14412 struct sip_peer *foundpeer;
14413
14414 peer->pokeexpire = -1;
14415
14416 foundpeer = ao2_find(peers, peer, OBJ_POINTER);
14417 if (!foundpeer) {
14418 unref_peer(peer, "removing poke peer ref");
14419 return 0;
14420 } else if (foundpeer->name != peer->name) {
14421 unref_peer(foundpeer, "removing above peer ref");
14422 unref_peer(peer, "removing poke peer ref");
14423 return 0;
14424 }
14425
14426 unref_peer(foundpeer, "removing above peer ref");
14427 sip_poke_peer(peer, 0);
14428 unref_peer(peer, "removing poke peer ref");
14429
14430 return 0;
14431 }
14432
14433
14434 static void reg_source_db(struct sip_peer *peer)
14435 {
14436 char data[256];
14437 struct ast_sockaddr sa;
14438 int expire;
14439 char full_addr[128];
14440 AST_DECLARE_APP_ARGS(args,
14441 AST_APP_ARG(addr);
14442 AST_APP_ARG(port);
14443 AST_APP_ARG(expiry_str);
14444 AST_APP_ARG(username);
14445 AST_APP_ARG(contact);
14446 );
14447
14448
14449 if (peer->rt_fromcontact && sip_cfg.peer_rtupdate) {
14450 return;
14451 }
14452 if (ast_db_get("SIP/Registry", peer->name, data, sizeof(data))) {
14453 return;
14454 }
14455
14456 AST_NONSTANDARD_RAW_ARGS(args, data, ':');
14457
14458 snprintf(full_addr, sizeof(full_addr), "%s:%s", args.addr, args.port);
14459
14460 if (!ast_sockaddr_parse(&sa, full_addr, 0)) {
14461 return;
14462 }
14463
14464 if (args.expiry_str) {
14465 expire = atoi(args.expiry_str);
14466 } else {
14467 return;
14468 }
14469
14470 if (args.username) {
14471 ast_string_field_set(peer, username, args.username);
14472 }
14473 if (args.contact) {
14474 ast_string_field_set(peer, fullcontact, args.contact);
14475 }
14476
14477 ast_debug(2, "SIP Seeding peer from astdb: '%s' at %s@%s for %d\n",
14478 peer->name, peer->username, ast_sockaddr_stringify_host(&sa), expire);
14479
14480 ast_sockaddr_copy(&peer->addr, &sa);
14481 if (peer->maxms) {
14482
14483 AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
14484 ast_random() % ((peer->qualifyfreq) ? peer->qualifyfreq : global_qualifyfreq) + 1,
14485 sip_poke_peer_s, peer,
14486 unref_peer(_data, "removing poke peer ref"),
14487 unref_peer(peer, "removing poke peer ref"),
14488 ref_peer(peer, "adding poke peer ref"));
14489 }
14490 AST_SCHED_REPLACE_UNREF(peer->expire, sched, (expire + 10) * 1000, expire_register, peer,
14491 unref_peer(_data, "remove registration ref"),
14492 unref_peer(peer, "remove registration ref"),
14493 ref_peer(peer, "add registration ref"));
14494 register_peer_exten(peer, TRUE);
14495 }
14496
14497
14498 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req)
14499 {
14500 char contact[SIPBUFSIZE];
14501 char *c;
14502
14503
14504 ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
14505 c = get_in_brackets(contact);
14506
14507
14508 ast_string_field_set(pvt, fullcontact, c);
14509
14510
14511 ast_string_field_set(pvt, okcontacturi, c);
14512
14513
14514
14515 return TRUE;
14516 }
14517
14518
14519
14520
14521
14522
14523
14524 static int parse_uri_legacy_check(char *uri, const char *scheme, char **user, char **pass, char **hostport, char **transport)
14525 {
14526 int ret = parse_uri(uri, scheme, user, pass, hostport, transport);
14527 if (sip_cfg.legacy_useroption_parsing) {
14528 char *p;
14529 if ((p = strchr(uri, (int)';'))) {
14530 *p = '\0';
14531 }
14532 }
14533 return ret;
14534 }
14535
14536 static int __set_address_from_contact(const char *fullcontact, struct ast_sockaddr *addr, int tcp)
14537 {
14538 char *hostport, *transport;
14539 char contact_buf[256];
14540 char *contact;
14541
14542
14543 ast_copy_string(contact_buf, fullcontact, sizeof(contact_buf));
14544 contact = contact_buf;
14545
14546
14547
14548
14549
14550
14551
14552
14553 if (parse_uri_legacy_check(contact, "sip:,sips:", &contact, NULL, &hostport,
14554 &transport)) {
14555 ast_log(LOG_WARNING, "Invalid contact uri %s (missing sip: or sips:), attempting to use anyway\n", fullcontact);
14556 }
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567 if (ast_strlen_zero(hostport)) {
14568 ast_log(LOG_WARNING, "Invalid URI: parse_uri failed to acquire hostport\n");
14569 return -1;
14570 }
14571
14572 if (ast_sockaddr_resolve_first_transport(addr, hostport, 0, get_transport_str2enum(transport))) {
14573 ast_log(LOG_WARNING, "Invalid host name in Contact: (can't "
14574 "resolve in DNS) : '%s'\n", hostport);
14575 return -1;
14576 }
14577
14578
14579 if (!ast_sockaddr_port(addr)) {
14580 ast_sockaddr_set_port(addr,
14581 (get_transport_str2enum(transport) ==
14582 SIP_TRANSPORT_TLS ||
14583 !strncasecmp(fullcontact, "sips", 4)) ?
14584 STANDARD_TLS_PORT : STANDARD_SIP_PORT);
14585 }
14586
14587 return 0;
14588 }
14589
14590
14591 static int set_address_from_contact(struct sip_pvt *pvt)
14592 {
14593 if (ast_test_flag(&pvt->flags[0], SIP_NAT_FORCE_RPORT)) {
14594
14595
14596
14597 pvt->sa = pvt->recv;
14598 return 0;
14599 }
14600
14601 return __set_address_from_contact(pvt->fullcontact, &pvt->sa, pvt->socket.type == SIP_TRANSPORT_TLS ? 1 : 0);
14602 }
14603
14604
14605 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *peer, struct sip_request *req)
14606 {
14607 char contact[SIPBUFSIZE];
14608 char data[SIPBUFSIZE];
14609 const char *expires = get_header(req, "Expires");
14610 int expire = atoi(expires);
14611 char *curi = NULL, *hostport = NULL, *transport = NULL;
14612 int transport_type;
14613 const char *useragent;
14614 struct ast_sockaddr oldsin, testsa;
14615 char *firstcuri = NULL;
14616 int start = 0;
14617 int wildcard_found = 0;
14618 int single_binding_found = 0;
14619
14620 ast_copy_string(contact, __get_header(req, "Contact", &start), sizeof(contact));
14621
14622 if (ast_strlen_zero(expires)) {
14623 char *s = strcasestr(contact, ";expires=");
14624 if (s) {
14625 expires = strsep(&s, ";");
14626 if (sscanf(expires + 9, "%30d", &expire) != 1) {
14627 expire = default_expiry;
14628 }
14629 } else {
14630
14631 expire = default_expiry;
14632 }
14633 }
14634
14635 if (expire > max_expiry) {
14636 expire = max_expiry;
14637 }
14638 if (expire < min_expiry && expire != 0) {
14639 expire = min_expiry;
14640 }
14641 pvt->expiry = expire;
14642
14643 copy_socket_data(&pvt->socket, &req->socket);
14644
14645 do {
14646
14647 curi = contact;
14648 if (strchr(contact, '<') == NULL)
14649 strsep(&curi, ";");
14650 curi = get_in_brackets(contact);
14651 if (!firstcuri) {
14652 firstcuri = ast_strdupa(curi);
14653 }
14654
14655 if (!strcasecmp(curi, "*")) {
14656 wildcard_found = 1;
14657 } else {
14658 single_binding_found = 1;
14659 }
14660
14661 if (wildcard_found && (ast_strlen_zero(expires) || expire != 0 || single_binding_found)) {
14662
14663
14664 return PARSE_REGISTER_FAILED;
14665 }
14666
14667 ast_copy_string(contact, __get_header(req, "Contact", &start), sizeof(contact));
14668 } while (!ast_strlen_zero(contact));
14669 curi = firstcuri;
14670
14671
14672
14673
14674
14675 if (ast_strlen_zero(curi) && ast_strlen_zero(expires)) {
14676
14677 if (peer->expire > -1 && !ast_strlen_zero(peer->fullcontact)) {
14678 pvt->expiry = ast_sched_when(sched, peer->expire);
14679 }
14680 return PARSE_REGISTER_QUERY;
14681 } else if (!strcasecmp(curi, "*") || !expire) {
14682
14683 AST_SCHED_DEL_UNREF(sched, peer->expire,
14684 unref_peer(peer, "remove register expire ref"));
14685 ast_verb(3, "Unregistered SIP '%s'\n", peer->name);
14686 expire_register(ref_peer(peer,"add ref for explicit expire_register"));
14687 return PARSE_REGISTER_UPDATE;
14688 }
14689
14690
14691 ast_string_field_set(peer, fullcontact, curi);
14692
14693
14694 ast_string_field_build(pvt, our_contact, "<%s>", curi);
14695
14696
14697 if (ast_strlen_zero(curi) || parse_uri_legacy_check(curi, "sip:,sips:", &curi, NULL, &hostport, &transport)) {
14698 ast_log(LOG_NOTICE, "Not a valid SIP contact (missing sip:/sips:) trying to use anyway\n");
14699 }
14700
14701
14702 if (!(transport_type = get_transport_str2enum(transport))) {
14703 transport_type = pvt->socket.type;
14704 }
14705
14706
14707
14708
14709 if ((peer->socket.type != transport_type) && (peer->transports & transport_type)) {
14710 set_socket_transport(&peer->socket, transport_type);
14711 }
14712
14713 oldsin = peer->addr;
14714
14715
14716 if (!ast_sockaddr_isnull(&peer->addr) && (!peer->is_realtime || ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS))) {
14717 ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
14718 }
14719
14720 if (!ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) && !ast_test_flag(&peer->flags[0], SIP_NAT_RPORT_PRESENT)) {
14721
14722 ast_debug(1, "Store REGISTER's Contact header for call routing.\n");
14723
14724
14725 if (ast_sockaddr_resolve_first_transport(&testsa, hostport, 0, peer->socket.type)) {
14726 ast_log(LOG_WARNING, "Invalid hostport '%s'\n", hostport);
14727 ast_string_field_set(peer, fullcontact, "");
14728 ast_string_field_set(pvt, our_contact, "");
14729 return PARSE_REGISTER_FAILED;
14730 }
14731
14732
14733
14734 peer->portinuri = ast_sockaddr_port(&testsa) ? TRUE : FALSE;
14735
14736 if (!ast_sockaddr_port(&testsa)) {
14737 ast_sockaddr_set_port(&testsa, default_sip_port(transport_type));
14738 }
14739
14740 ast_sockaddr_copy(&peer->addr, &testsa);
14741 } else {
14742
14743
14744 ast_debug(1, "Store REGISTER's src-IP:port for call routing.\n");
14745 peer->addr = pvt->recv;
14746 }
14747
14748
14749 if (ast_apply_ha(sip_cfg.contact_ha, &peer->addr) != AST_SENSE_ALLOW ||
14750 ast_apply_ha(peer->contactha, &peer->addr) != AST_SENSE_ALLOW) {
14751 ast_log(LOG_WARNING, "Domain '%s' disallowed by contact ACL (violating IP %s)\n", hostport,
14752 ast_sockaddr_stringify_addr(&peer->addr));
14753 ast_string_field_set(peer, fullcontact, "");
14754 ast_string_field_set(pvt, our_contact, "");
14755 return PARSE_REGISTER_DENIED;
14756 }
14757
14758
14759
14760
14761 if ((peer->socket.type == pvt->socket.type) &&
14762 !ast_sockaddr_cmp(&peer->addr, &pvt->recv)) {
14763 copy_socket_data(&peer->socket, &pvt->socket);
14764 }
14765
14766
14767 if (!peer->is_realtime || ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
14768 ao2_t_link(peers_by_ip, peer, "ao2_link into peers_by_ip table");
14769 }
14770
14771
14772 peer->sipoptions = pvt->sipoptions;
14773
14774 if (!ast_strlen_zero(curi) && ast_strlen_zero(peer->username)) {
14775 ast_string_field_set(peer, username, curi);
14776 }
14777
14778 AST_SCHED_DEL_UNREF(sched, peer->expire,
14779 unref_peer(peer, "remove register expire ref"));
14780
14781 if (peer->is_realtime && !ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
14782 peer->expire = -1;
14783 } else {
14784 peer->expire = ast_sched_add(sched, (expire + 10) * 1000, expire_register,
14785 ref_peer(peer, "add registration ref"));
14786 if (peer->expire == -1) {
14787 unref_peer(peer, "remote registration ref");
14788 }
14789 }
14790 snprintf(data, sizeof(data), "%s:%d:%s:%s", ast_sockaddr_stringify(&peer->addr),
14791 expire, peer->username, peer->fullcontact);
14792
14793 if (!peer->rt_fromcontact || !sip_cfg.peer_rtupdate)
14794 ast_db_put("SIP/Registry", peer->name, data);
14795 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));
14796
14797
14798 if (VERBOSITY_ATLEAST(2) && ast_sockaddr_cmp(&peer->addr, &oldsin)) {
14799 ast_verbose(VERBOSE_PREFIX_3 "Registered SIP '%s' at %s\n", peer->name,
14800 ast_sockaddr_stringify(&peer->addr));
14801 }
14802 sip_pvt_unlock(pvt);
14803 sip_poke_peer(peer, 0);
14804 sip_pvt_lock(pvt);
14805 register_peer_exten(peer, 1);
14806
14807
14808 useragent = get_header(req, "User-Agent");
14809 if (strcasecmp(useragent, peer->useragent)) {
14810 ast_string_field_set(peer, useragent, useragent);
14811 ast_verb(4, "Saved useragent \"%s\" for peer %s\n", peer->useragent, peer->name);
14812 }
14813 return PARSE_REGISTER_UPDATE;
14814 }
14815
14816
14817 static void free_old_route(struct sip_route *route)
14818 {
14819 struct sip_route *next;
14820
14821 while (route) {
14822 next = route->next;
14823 ast_free(route);
14824 route = next;
14825 }
14826 }
14827
14828
14829 static void list_route(struct sip_route *route)
14830 {
14831 if (!route) {
14832 ast_verbose("list_route: no route\n");
14833 } else {
14834 for (;route; route = route->next)
14835 ast_verbose("list_route: hop: <%s>\n", route->hop);
14836 }
14837 }
14838
14839
14840
14841 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards, int resp)
14842 {
14843 struct sip_route *thishop, *head, *tail;
14844 int start = 0;
14845 int len;
14846 const char *rr, *c;
14847
14848
14849 if (p->route && p->route_persistent) {
14850 ast_debug(1, "build_route: Retaining previous route: <%s>\n", p->route->hop);
14851 return;
14852 }
14853
14854 if (p->route) {
14855 free_old_route(p->route);
14856 p->route = NULL;
14857 }
14858
14859
14860
14861 if ((resp < 100) || (resp > 199)) {
14862 p->route_persistent = 1;
14863 }
14864
14865
14866
14867
14868
14869
14870 head = NULL;
14871 tail = head;
14872
14873 for (;;) {
14874
14875 int len = 0;
14876 const char *uri;
14877 rr = __get_header(req, "Record-Route", &start);
14878 if (*rr == '\0') {
14879 break;
14880 }
14881 while (!get_in_brackets_const(rr, &uri, &len)) {
14882 len++;
14883 rr = strchr(rr, ',');
14884 if(rr >= uri && rr < (uri + len)) {
14885
14886 const char *next_br = strchr(rr, '<');
14887 if (next_br && next_br < (uri + len)) {
14888 rr++;
14889 continue;
14890 }
14891 continue;
14892 }
14893 if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
14894 ast_copy_string(thishop->hop, uri, len);
14895 ast_debug(2, "build_route: Record-Route hop: <%s>\n", thishop->hop);
14896
14897 if (backwards) {
14898
14899 thishop->next = head;
14900 head = thishop;
14901
14902 if (!tail) {
14903 tail = thishop;
14904 }
14905 } else {
14906 thishop->next = NULL;
14907
14908 if (tail) {
14909 tail->next = thishop;
14910 } else {
14911 head = thishop;
14912 }
14913 tail = thishop;
14914 }
14915 }
14916 rr = strchr(uri + len, ',');
14917 if (rr == NULL) {
14918
14919 break;
14920 }
14921
14922 rr++;
14923 }
14924 }
14925
14926
14927 if (!head || (!ast_strlen_zero(head->hop) && strstr(head->hop, ";lr") == NULL) ) {
14928
14929
14930 char *contact = ast_strdupa(get_header(req, "Contact"));
14931 if (!ast_strlen_zero(contact)) {
14932 ast_debug(2, "build_route: Contact hop: %s\n", contact);
14933
14934 c = get_in_brackets(contact);
14935 len = strlen(c) + 1;
14936 if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
14937
14938 ast_copy_string(thishop->hop, c, len);
14939 thishop->next = NULL;
14940
14941 if (tail) {
14942 tail->next = thishop;
14943 } else {
14944 head = thishop;
14945 }
14946 }
14947 }
14948 }
14949
14950
14951 p->route = head;
14952
14953
14954 if (sip_debug_test_pvt(p)) {
14955 list_route(p->route);
14956 }
14957 }
14958
14959
14960
14961
14962
14963
14964
14965 static void set_nonce_randdata(struct sip_pvt *p, int forceupdate)
14966 {
14967 if (p->stalenonce || forceupdate || ast_strlen_zero(p->randdata)) {
14968 ast_string_field_build(p, randdata, "%08lx", ast_random());
14969 p->stalenonce = 0;
14970 }
14971 }
14972
14973 AST_THREADSTORAGE(check_auth_buf);
14974 #define CHECK_AUTH_BUF_INITLEN 256
14975
14976
14977
14978
14979
14980
14981 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
14982 const char *secret, const char *md5secret, int sipmethod,
14983 const char *uri, enum xmittype reliable, int ignore)
14984 {
14985 const char *response;
14986 char *reqheader, *respheader;
14987 const char *authtoken;
14988 char a1_hash[256];
14989 char resp_hash[256]="";
14990 char *c;
14991 int is_bogus_peer = 0;
14992 int wrongnonce = FALSE;
14993 int good_response;
14994 const char *usednonce = p->randdata;
14995 struct ast_str *buf;
14996 int res;
14997
14998
14999 enum keys { K_RESP, K_URI, K_USER, K_NONCE, K_LAST };
15000 struct x {
15001 const char *key;
15002 const char *s;
15003 } *i, keys[] = {
15004 [K_RESP] = { "response=", "" },
15005 [K_URI] = { "uri=", "" },
15006 [K_USER] = { "username=", "" },
15007 [K_NONCE] = { "nonce=", "" },
15008 [K_LAST] = { NULL, NULL}
15009 };
15010
15011
15012 if (ast_strlen_zero(secret) && ast_strlen_zero(md5secret))
15013 return AUTH_SUCCESSFUL;
15014
15015
15016
15017 response = "401 Unauthorized";
15018
15019
15020
15021
15022
15023 auth_headers(WWW_AUTH, &respheader, &reqheader);
15024
15025 authtoken = get_header(req, reqheader);
15026 if (ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
15027
15028
15029 if (!reliable) {
15030
15031
15032 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
15033
15034 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15035 }
15036 return AUTH_CHALLENGE_SENT;
15037 } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
15038
15039 set_nonce_randdata(p, 1);
15040 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
15041
15042 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15043 return AUTH_CHALLENGE_SENT;
15044 }
15045
15046
15047
15048
15049
15050
15051 if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN))) {
15052 return AUTH_SECRET_FAILED;
15053 }
15054
15055
15056 res = ast_str_set(&buf, 0, "%s", authtoken);
15057
15058 if (res == AST_DYNSTR_BUILD_FAILED) {
15059 return AUTH_SECRET_FAILED;
15060 }
15061
15062 c = buf->str;
15063
15064 while(c && *(c = ast_skip_blanks(c)) ) {
15065 for (i = keys; i->key != NULL; i++) {
15066 const char *separator = ",";
15067
15068 if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
15069 continue;
15070 }
15071
15072 c += strlen(i->key);
15073 if (*c == '"') {
15074 c++;
15075 separator = "\"";
15076 }
15077 i->s = c;
15078 strsep(&c, separator);
15079 break;
15080 }
15081 if (i->key == NULL) {
15082 strsep(&c, " ,");
15083 }
15084 }
15085
15086
15087
15088 if (md5secret && strcmp(md5secret, BOGUS_PEER_MD5SECRET) == 0) {
15089 is_bogus_peer = 1;
15090 }
15091
15092
15093 if (strcmp(username, keys[K_USER].s) && !is_bogus_peer) {
15094 ast_log(LOG_WARNING, "username mismatch, have <%s>, digest has <%s>\n",
15095 username, keys[K_USER].s);
15096
15097 return AUTH_USERNAME_MISMATCH;
15098 }
15099
15100
15101
15102 if (strcasecmp(p->randdata, keys[K_NONCE].s) || p->stalenonce) {
15103 wrongnonce = TRUE;
15104 usednonce = keys[K_NONCE].s;
15105 } else {
15106 p->stalenonce = 1;
15107 }
15108
15109 if (!ast_strlen_zero(md5secret)) {
15110 ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
15111 } else {
15112 char a1[256];
15113
15114 snprintf(a1, sizeof(a1), "%s:%s:%s", username, p->realm, secret);
15115 ast_md5_hash(a1_hash, a1);
15116 }
15117
15118
15119 {
15120 char a2[256];
15121 char a2_hash[256];
15122 char resp[256];
15123
15124 snprintf(a2, sizeof(a2), "%s:%s", sip_methods[sipmethod].text,
15125 S_OR(keys[K_URI].s, uri));
15126 ast_md5_hash(a2_hash, a2);
15127 snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, usednonce, a2_hash);
15128 ast_md5_hash(resp_hash, resp);
15129 }
15130
15131 good_response = keys[K_RESP].s &&
15132 !strncasecmp(keys[K_RESP].s, resp_hash, strlen(resp_hash)) &&
15133 !is_bogus_peer;
15134 if (wrongnonce) {
15135 if (good_response) {
15136 if (sipdebug)
15137 ast_log(LOG_NOTICE, "Correct auth, but based on stale nonce received from '%s'\n", get_header(req, "From"));
15138
15139 set_nonce_randdata(p, 0);
15140 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, TRUE);
15141 } else {
15142
15143 if (!req->ignore) {
15144 if (sipdebug) {
15145 ast_log(LOG_NOTICE, "Bad authentication received from '%s'\n", get_header(req, "To"));
15146 }
15147 set_nonce_randdata(p, 1);
15148 } else {
15149 if (sipdebug) {
15150 ast_log(LOG_NOTICE, "Duplicate authentication received from '%s'\n", get_header(req, "To"));
15151 }
15152 }
15153 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
15154 }
15155
15156
15157 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15158 return AUTH_CHALLENGE_SENT;
15159 }
15160 if (good_response) {
15161 append_history(p, "AuthOK", "Auth challenge successful for %s", username);
15162 return AUTH_SUCCESSFUL;
15163 }
15164
15165
15166
15167
15168
15169
15170 return AUTH_SECRET_FAILED;
15171 }
15172
15173
15174 static void sip_peer_hold(struct sip_pvt *p, int hold)
15175 {
15176 if (!p->relatedpeer) {
15177 return;
15178 }
15179
15180
15181 ast_atomic_fetchadd_int(&p->relatedpeer->onHold, (hold ? +1 : -1));
15182
15183
15184 ast_devstate_changed(AST_DEVICE_UNKNOWN, (p->owner->flags & AST_FLAG_DISABLE_DEVSTATE_CACHE ? AST_DEVSTATE_NOT_CACHABLE : AST_DEVSTATE_CACHABLE),
15185 "SIP/%s", p->relatedpeer->name);
15186
15187 return;
15188 }
15189
15190
15191 static void mwi_event_cb(const struct ast_event *event, void *userdata)
15192 {
15193 struct sip_peer *peer = userdata;
15194
15195 sip_send_mwi_to_peer(peer, 0);
15196 }
15197
15198 static void network_change_event_subscribe(void)
15199 {
15200 if (!network_change_event_subscription) {
15201 network_change_event_subscription = ast_event_subscribe(AST_EVENT_NETWORK_CHANGE,
15202 network_change_event_cb, "SIP Network Change", NULL, AST_EVENT_IE_END);
15203 }
15204 }
15205
15206 static void network_change_event_unsubscribe(void)
15207 {
15208 if (network_change_event_subscription) {
15209 network_change_event_subscription = ast_event_unsubscribe(network_change_event_subscription);
15210 }
15211 }
15212
15213 static int network_change_event_sched_cb(const void *data)
15214 {
15215 network_change_event_sched_id = -1;
15216 sip_send_all_registers();
15217 sip_send_all_mwi_subscriptions();
15218 return 0;
15219 }
15220
15221 static void network_change_event_cb(const struct ast_event *event, void *userdata)
15222 {
15223 ast_debug(1, "SIP, got a network change event, renewing all SIP registrations.\n");
15224 if (network_change_event_sched_id == -1) {
15225 network_change_event_sched_id = ast_sched_add(sched, 1000, network_change_event_sched_cb, NULL);
15226 }
15227 }
15228
15229 static void cb_extensionstate_destroy(int id, void *data)
15230 {
15231 struct sip_pvt *p = data;
15232
15233 dialog_unref(p, "the extensionstate containing this dialog ptr was destroyed");
15234 }
15235
15236
15237
15238
15239 static int cb_extensionstate(char *context, char* exten, int state, void *data)
15240 {
15241 struct sip_pvt *p = data;
15242
15243 sip_pvt_lock(p);
15244
15245 switch(state) {
15246 case AST_EXTENSION_DEACTIVATED:
15247 case AST_EXTENSION_REMOVED:
15248 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15249 ast_verb(2, "Extension state: Watcher for hint %s %s. Notify User %s\n", exten, state == AST_EXTENSION_DEACTIVATED ? "deactivated" : "removed", p->username);
15250 p->subscribed = NONE;
15251 append_history(p, "Subscribestatus", "%s", state == AST_EXTENSION_REMOVED ? "HintRemoved" : "Deactivated");
15252 break;
15253 default:
15254 p->laststate = state;
15255 break;
15256 }
15257 if (p->subscribed != NONE) {
15258 if (!p->pendinginvite) {
15259 transmit_state_notify(p, state, 1, FALSE);
15260 } else {
15261
15262
15263 ast_set_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
15264 }
15265 }
15266 ast_verb(2, "Extension Changed %s[%s] new state %s for Notify User %s %s\n", exten, context, ast_extension_state2str(state), p->username,
15267 ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE) ? "(queued)" : "");
15268
15269 sip_pvt_unlock(p);
15270
15271 return 0;
15272 }
15273
15274
15275
15276
15277 static void transmit_fake_auth_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable)
15278 {
15279
15280
15281 const char *response = "401 Unauthorized";
15282 const char *reqheader = "Authorization";
15283 const char *respheader = "WWW-Authenticate";
15284 const char *authtoken;
15285 struct ast_str *buf;
15286 char *c;
15287
15288
15289 enum keys { K_NONCE, K_LAST };
15290 struct x {
15291 const char *key;
15292 const char *s;
15293 } *i, keys[] = {
15294 [K_NONCE] = { "nonce=", "" },
15295 [K_LAST] = { NULL, NULL}
15296 };
15297
15298 authtoken = get_header(req, reqheader);
15299 if (req->ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
15300
15301
15302 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
15303
15304 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15305 return;
15306 } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
15307
15308 set_nonce_randdata(p, 1);
15309 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
15310
15311 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15312 return;
15313 }
15314
15315 if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN))) {
15316 __transmit_response(p, "403 Forbidden", &p->initreq, reliable);
15317 return;
15318 }
15319
15320
15321 if (ast_str_set(&buf, 0, "%s", authtoken) == AST_DYNSTR_BUILD_FAILED) {
15322 __transmit_response(p, "403 Forbidden", &p->initreq, reliable);
15323 return;
15324 }
15325
15326 c = buf->str;
15327
15328 while (c && *(c = ast_skip_blanks(c))) {
15329 for (i = keys; i->key != NULL; i++) {
15330 const char *separator = ",";
15331
15332 if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
15333 continue;
15334 }
15335
15336 c += strlen(i->key);
15337 if (*c == '"') {
15338 c++;
15339 separator = "\"";
15340 }
15341 i->s = c;
15342 strsep(&c, separator);
15343 break;
15344 }
15345 if (i->key == NULL) {
15346 strsep(&c, " ,");
15347 }
15348 }
15349
15350
15351 if (strcasecmp(p->randdata, keys[K_NONCE].s)) {
15352 if (!req->ignore) {
15353 set_nonce_randdata(p, 1);
15354 }
15355 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
15356
15357
15358 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15359 } else {
15360 __transmit_response(p, "403 Forbidden", &p->initreq, reliable);
15361 }
15362 }
15363
15364
15365
15366
15367
15368
15369
15370
15371
15372
15373
15374
15375
15376
15377
15378 static char *terminate_uri(char *uri)
15379 {
15380 char *t = uri;
15381 while (*t && *t > ' ' && *t != ';') {
15382 t++;
15383 }
15384 *t = '\0';
15385 return uri;
15386 }
15387
15388
15389
15390
15391
15392
15393
15394 static void extract_host_from_hostport(char **hostport)
15395 {
15396 char *dont_care;
15397 ast_sockaddr_split_hostport(*hostport, hostport, &dont_care, PARSE_PORT_IGNORE);
15398 }
15399
15400
15401
15402 static void update_peer_lastmsgssent(struct sip_peer *peer, int value, int locked)
15403 {
15404 if (!locked) {
15405 ao2_lock(peer);
15406 }
15407 peer->lastmsgssent = value;
15408 if (!locked) {
15409 ao2_unlock(peer);
15410 }
15411 }
15412
15413
15414
15415
15416
15417
15418
15419 static enum check_auth_result register_verify(struct sip_pvt *p, struct ast_sockaddr *addr,
15420 struct sip_request *req, const char *uri)
15421 {
15422 enum check_auth_result res = AUTH_NOT_FOUND;
15423 struct sip_peer *peer;
15424 char tmp[256];
15425 char *c, *name, *unused_password, *domain;
15426 char *uri2 = ast_strdupa(uri);
15427 int send_mwi = 0;
15428
15429 terminate_uri(uri2);
15430
15431 ast_copy_string(tmp, get_header(req, "To"), sizeof(tmp));
15432
15433 c = get_in_brackets(tmp);
15434 c = remove_uri_parameters(c);
15435
15436 if (parse_uri_legacy_check(c, "sip:,sips:", &name, &unused_password, &domain, NULL)) {
15437 ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, ast_sockaddr_stringify_addr(addr));
15438 return -1;
15439 }
15440
15441 SIP_PEDANTIC_DECODE(name);
15442 SIP_PEDANTIC_DECODE(domain);
15443
15444 extract_host_from_hostport(&domain);
15445
15446 if (ast_strlen_zero(domain)) {
15447
15448 transmit_response(p, "404 Not found", &p->initreq);
15449 return AUTH_UNKNOWN_DOMAIN;
15450 }
15451
15452 if (ast_strlen_zero(name)) {
15453
15454
15455
15456
15457
15458
15459
15460 name = domain;
15461 }
15462
15463
15464
15465
15466
15467 if (!AST_LIST_EMPTY(&domain_list)) {
15468 if (!check_sip_domain(domain, NULL, 0)) {
15469 if (sip_cfg.alwaysauthreject) {
15470 transmit_fake_auth_response(p, &p->initreq, XMIT_UNRELIABLE);
15471 } else {
15472 transmit_response(p, "404 Not found (unknown domain)", &p->initreq);
15473 }
15474 return AUTH_UNKNOWN_DOMAIN;
15475 }
15476 }
15477
15478 ast_string_field_set(p, exten, name);
15479 build_contact(p);
15480 if (req->ignore) {
15481
15482 const char *expires = get_header(req, "Expires");
15483 int expire = atoi(expires);
15484
15485 if (ast_strlen_zero(expires)) {
15486 if ((expires = strcasestr(get_header(req, "Contact"), ";expires="))) {
15487 expire = atoi(expires + 9);
15488 }
15489 }
15490 if (!ast_strlen_zero(expires) && expire == 0) {
15491 transmit_response_with_date(p, "200 OK", req);
15492 return 0;
15493 }
15494 }
15495 peer = find_peer(name, NULL, TRUE, FINDPEERS, FALSE, 0);
15496
15497
15498
15499 if (!peer && sip_cfg.alwaysauthreject && !sip_cfg.autocreatepeer) {
15500 peer = bogus_peer;
15501 ref_peer(peer, "register_verify: ref the bogus_peer");
15502 }
15503
15504 if (!(peer && ast_apply_ha(peer->ha, addr))) {
15505
15506 if (peer) {
15507 unref_peer(peer, "register_verify: unref_peer: from find_peer operation");
15508 peer = NULL;
15509 res = AUTH_ACL_FAILED;
15510 } else {
15511 res = AUTH_NOT_FOUND;
15512 }
15513 }
15514
15515 if (peer) {
15516 ao2_lock(peer);
15517 if (!peer->host_dynamic) {
15518 ast_log(LOG_ERROR, "Peer '%s' is trying to register, but not configured as host=dynamic\n", peer->name);
15519 res = AUTH_PEER_NOT_DYNAMIC;
15520 } else {
15521 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_NAT_FORCE_RPORT);
15522 if (!(res = check_auth(p, req, peer->name, peer->secret, peer->md5secret, SIP_REGISTER, uri2, XMIT_UNRELIABLE, req->ignore))) {
15523 if (sip_cancel_destroy(p))
15524 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
15525
15526 if (check_request_transport(peer, req)) {
15527 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
15528 transmit_response_with_date(p, "403 Forbidden", req);
15529 res = AUTH_BAD_TRANSPORT;
15530 } else {
15531
15532
15533
15534 switch (parse_register_contact(p, peer, req)) {
15535 case PARSE_REGISTER_DENIED:
15536 ast_log(LOG_WARNING, "Registration denied because of contact ACL\n");
15537 transmit_response_with_date(p, "603 Denied", req);
15538 res = 0;
15539 break;
15540 case PARSE_REGISTER_FAILED:
15541 ast_log(LOG_WARNING, "Failed to parse contact info\n");
15542 transmit_response_with_date(p, "400 Bad Request", req);
15543 res = 0;
15544 break;
15545 case PARSE_REGISTER_QUERY:
15546 ast_string_field_set(p, fullcontact, peer->fullcontact);
15547 transmit_response_with_date(p, "200 OK", req);
15548 res = 0;
15549 break;
15550 case PARSE_REGISTER_UPDATE:
15551 ast_string_field_set(p, fullcontact, peer->fullcontact);
15552
15553 if (p->expiry != 0) {
15554 update_peer(peer, p->expiry);
15555 }
15556
15557 transmit_response_with_date(p, "200 OK", req);
15558 send_mwi = 1;
15559 res = 0;
15560 break;
15561 }
15562 }
15563
15564 }
15565 }
15566 ao2_unlock(peer);
15567 }
15568 if (!peer && sip_cfg.autocreatepeer) {
15569
15570 peer = temp_peer(name);
15571 if (peer) {
15572 ao2_t_link(peers, peer, "link peer into peer table");
15573 if (!ast_sockaddr_isnull(&peer->addr)) {
15574 ao2_t_link(peers_by_ip, peer, "link peer into peers-by-ip table");
15575 }
15576 ao2_lock(peer);
15577 if (sip_cancel_destroy(p))
15578 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
15579 switch (parse_register_contact(p, peer, req)) {
15580 case PARSE_REGISTER_DENIED:
15581 ast_log(LOG_WARNING, "Registration denied because of contact ACL\n");
15582 transmit_response_with_date(p, "403 Forbidden", req);
15583 res = 0;
15584 break;
15585 case PARSE_REGISTER_FAILED:
15586 ast_log(LOG_WARNING, "Failed to parse contact info\n");
15587 transmit_response_with_date(p, "400 Bad Request", req);
15588 res = 0;
15589 break;
15590 case PARSE_REGISTER_QUERY:
15591 ast_string_field_set(p, fullcontact, peer->fullcontact);
15592 transmit_response_with_date(p, "200 OK", req);
15593 send_mwi = 1;
15594 res = 0;
15595 break;
15596 case PARSE_REGISTER_UPDATE:
15597 ast_string_field_set(p, fullcontact, peer->fullcontact);
15598
15599 transmit_response_with_date(p, "200 OK", req);
15600 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));
15601 send_mwi = 1;
15602 res = 0;
15603 break;
15604 }
15605 ao2_unlock(peer);
15606 }
15607 }
15608 if (!res) {
15609 if (send_mwi) {
15610 sip_pvt_unlock(p);
15611 sip_send_mwi_to_peer(peer, 0);
15612 sip_pvt_lock(p);
15613 } else {
15614 update_peer_lastmsgssent(peer, -1, 0);
15615 }
15616 ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "SIP/%s", peer->name);
15617 }
15618 if (res < 0) {
15619 switch (res) {
15620 case AUTH_SECRET_FAILED:
15621
15622 transmit_response(p, "403 Forbidden", &p->initreq);
15623 if (global_authfailureevents) {
15624 const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
15625 const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
15626 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
15627 "ChannelType: SIP\r\n"
15628 "Peer: SIP/%s\r\n"
15629 "PeerStatus: Rejected\r\n"
15630 "Cause: AUTH_SECRET_FAILED\r\n"
15631 "Address: %s\r\n"
15632 "Port: %s\r\n",
15633 name, peer_addr, peer_port);
15634 }
15635 break;
15636 case AUTH_USERNAME_MISMATCH:
15637
15638
15639
15640
15641 case AUTH_NOT_FOUND:
15642 case AUTH_PEER_NOT_DYNAMIC:
15643 case AUTH_ACL_FAILED:
15644 if (sip_cfg.alwaysauthreject) {
15645 transmit_fake_auth_response(p, &p->initreq, XMIT_UNRELIABLE);
15646 if (global_authfailureevents) {
15647 const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
15648 const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
15649 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
15650 "ChannelType: SIP\r\n"
15651 "Peer: SIP/%s\r\n"
15652 "PeerStatus: Rejected\r\n"
15653 "Cause: %s\r\n"
15654 "Address: %s\r\n"
15655 "Port: %s\r\n",
15656 name,
15657 res == AUTH_PEER_NOT_DYNAMIC ? "AUTH_PEER_NOT_DYNAMIC" : "URI_NOT_FOUND",
15658 peer_addr, peer_port);
15659 }
15660 } else {
15661
15662 if (res == AUTH_PEER_NOT_DYNAMIC) {
15663 transmit_response(p, "403 Forbidden", &p->initreq);
15664 if (global_authfailureevents) {
15665 const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
15666 const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
15667 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
15668 "ChannelType: SIP\r\n"
15669 "Peer: SIP/%s\r\n"
15670 "PeerStatus: Rejected\r\n"
15671 "Cause: AUTH_PEER_NOT_DYNAMIC\r\n"
15672 "Address: %s\r\n"
15673 "Port: %s\r\n",
15674 name, peer_addr, peer_port);
15675 }
15676 } else {
15677 transmit_response(p, "404 Not found", &p->initreq);
15678 if (global_authfailureevents) {
15679 const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
15680 const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
15681 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
15682 "ChannelType: SIP\r\n"
15683 "Peer: SIP/%s\r\n"
15684 "PeerStatus: Rejected\r\n"
15685 "Cause: %s\r\n"
15686 "Address: %s\r\n"
15687 "Port: %s\r\n",
15688 name,
15689 (res == AUTH_USERNAME_MISMATCH) ? "AUTH_USERNAME_MISMATCH" : "URI_NOT_FOUND",
15690 peer_addr, peer_port);
15691 }
15692 }
15693 }
15694 break;
15695 case AUTH_BAD_TRANSPORT:
15696 default:
15697 break;
15698 }
15699 }
15700 if (peer) {
15701 unref_peer(peer, "register_verify: unref_peer: tossing stack peer pointer at end of func");
15702 }
15703
15704 return res;
15705 }
15706
15707
15708 static void sip_set_redirstr(struct sip_pvt *p, char *reason) {
15709
15710 if (!strcmp(reason, "unknown")) {
15711 ast_string_field_set(p, redircause, "UNKNOWN");
15712 } else if (!strcmp(reason, "user-busy")) {
15713 ast_string_field_set(p, redircause, "BUSY");
15714 } else if (!strcmp(reason, "no-answer")) {
15715 ast_string_field_set(p, redircause, "NOANSWER");
15716 } else if (!strcmp(reason, "unavailable")) {
15717 ast_string_field_set(p, redircause, "UNREACHABLE");
15718 } else if (!strcmp(reason, "unconditional")) {
15719 ast_string_field_set(p, redircause, "UNCONDITIONAL");
15720 } else if (!strcmp(reason, "time-of-day")) {
15721 ast_string_field_set(p, redircause, "UNKNOWN");
15722 } else if (!strcmp(reason, "do-not-disturb")) {
15723 ast_string_field_set(p, redircause, "UNKNOWN");
15724 } else if (!strcmp(reason, "deflection")) {
15725 ast_string_field_set(p, redircause, "UNKNOWN");
15726 } else if (!strcmp(reason, "follow-me")) {
15727 ast_string_field_set(p, redircause, "UNKNOWN");
15728 } else if (!strcmp(reason, "out-of-service")) {
15729 ast_string_field_set(p, redircause, "UNREACHABLE");
15730 } else if (!strcmp(reason, "away")) {
15731 ast_string_field_set(p, redircause, "UNREACHABLE");
15732 } else {
15733 ast_string_field_set(p, redircause, "UNKNOWN");
15734 }
15735 }
15736
15737
15738
15739
15740
15741 static int get_pai(struct sip_pvt *p, struct sip_request *req)
15742 {
15743 char pai[256];
15744 char privacy[64];
15745 char *cid_num = NULL;
15746 char *cid_name = NULL;
15747 char emptyname[1] = "";
15748 int callingpres = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
15749 char *uri = NULL;
15750 int is_anonymous = 0, do_update = 1, no_name = 0;
15751
15752 ast_copy_string(pai, get_header(req, "P-Asserted-Identity"), sizeof(pai));
15753
15754 if (ast_strlen_zero(pai)) {
15755 return 0;
15756 }
15757
15758
15759 if (get_name_and_number(pai, &cid_name, &cid_num)) {
15760 return 0;
15761 }
15762
15763 if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(cid_num)) {
15764 ast_shrink_phone_number(cid_num);
15765 }
15766
15767 uri = get_in_brackets(pai);
15768 if (!strncasecmp(uri, "sip:anonymous@anonymous.invalid", 31)) {
15769 callingpres = AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
15770
15771
15772
15773 ast_free(cid_num);
15774 is_anonymous = 1;
15775 cid_num = (char *)p->cid_num;
15776 }
15777
15778 ast_copy_string(privacy, get_header(req, "Privacy"), sizeof(privacy));
15779 if (!ast_strlen_zero(privacy) && !strncmp(privacy, "id", 2)) {
15780 callingpres = AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
15781 }
15782 if (!cid_name) {
15783 no_name = 1;
15784 cid_name = (char *)emptyname;
15785 }
15786
15787 if (!strcasecmp(p->cid_num, cid_num) && !strcasecmp(p->cid_name, cid_name) && p->callingpres == callingpres) {
15788 do_update = 0;
15789 } else {
15790
15791 ast_string_field_set(p, cid_num, cid_num);
15792 ast_string_field_set(p, cid_name, cid_name);
15793 p->callingpres = callingpres;
15794
15795 if (p->owner) {
15796 ast_set_callerid(p->owner, cid_num, cid_name, NULL);
15797 p->owner->caller.id.name.presentation = callingpres;
15798 p->owner->caller.id.number.presentation = callingpres;
15799 }
15800 }
15801
15802
15803 if (!is_anonymous) {
15804 ast_free(cid_num);
15805 }
15806 if (!no_name) {
15807 ast_free(cid_name);
15808 }
15809
15810 return do_update;
15811 }
15812
15813
15814
15815
15816
15817 static int get_rpid(struct sip_pvt *p, struct sip_request *oreq)
15818 {
15819 char tmp[256];
15820 struct sip_request *req;
15821 char *cid_num = "";
15822 char *cid_name = "";
15823 int callingpres = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
15824 char *privacy = "";
15825 char *screen = "";
15826 char *start, *end;
15827
15828 if (!ast_test_flag(&p->flags[0], SIP_TRUSTRPID))
15829 return 0;
15830 req = oreq;
15831 if (!req)
15832 req = &p->initreq;
15833 ast_copy_string(tmp, get_header(req, "Remote-Party-ID"), sizeof(tmp));
15834 if (ast_strlen_zero(tmp)) {
15835 return get_pai(p, req);
15836 }
15837
15838
15839
15840
15841
15842
15843
15844
15845
15846 start = tmp;
15847
15848 if (*start == '"') {
15849 *start++ = '\0';
15850 end = strchr(start, '"');
15851 if (!end)
15852 return 0;
15853 *end++ = '\0';
15854 cid_name = start;
15855 start = ast_skip_blanks(end);
15856
15857 } else {
15858 cid_name = start;
15859 start = end = strchr(start, '<');
15860 if (!start) {
15861 return 0;
15862 }
15863
15864 while (--end >= cid_name && *end < 33) {
15865 *end = '\0';
15866 }
15867 }
15868
15869 if (*start != '<')
15870 return 0;
15871 *start++ = '\0';
15872 end = strchr(start, '@');
15873 if (!end)
15874 return 0;
15875 *end++ = '\0';
15876 if (strncasecmp(start, "sip:", 4))
15877 return 0;
15878 cid_num = start + 4;
15879 if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(cid_num))
15880 ast_shrink_phone_number(cid_num);
15881 start = end;
15882
15883 end = strchr(start, '>');
15884 if (!end)
15885 return 0;
15886 *end++ = '\0';
15887 if (*end) {
15888 start = end;
15889 if (*start != ';')
15890 return 0;
15891 *start++ = '\0';
15892 while (!ast_strlen_zero(start)) {
15893 end = strchr(start, ';');
15894 if (end)
15895 *end++ = '\0';
15896 if (!strncasecmp(start, "privacy=", 8))
15897 privacy = start + 8;
15898 else if (!strncasecmp(start, "screen=", 7))
15899 screen = start + 7;
15900 start = end;
15901 }
15902
15903 if (!strcasecmp(privacy, "full")) {
15904 if (!strcasecmp(screen, "yes"))
15905 callingpres = AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN;
15906 else if (!strcasecmp(screen, "no"))
15907 callingpres = AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
15908 } else {
15909 if (!strcasecmp(screen, "yes"))
15910 callingpres = AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN;
15911 else if (!strcasecmp(screen, "no"))
15912 callingpres = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
15913 }
15914 }
15915
15916
15917 if (!strcasecmp(p->cid_num, cid_num) && !strcasecmp(p->cid_name, cid_name) && p->callingpres == callingpres)
15918 return 0;
15919
15920 ast_string_field_set(p, cid_num, cid_num);
15921 ast_string_field_set(p, cid_name, cid_name);
15922 p->callingpres = callingpres;
15923
15924 if (p->owner) {
15925 ast_set_callerid(p->owner, cid_num, cid_name, NULL);
15926 p->owner->caller.id.name.presentation = callingpres;
15927 p->owner->caller.id.number.presentation = callingpres;
15928 }
15929
15930 return 1;
15931 }
15932
15933
15934 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq, char **name, char **number, int *reason)
15935 {
15936 char tmp[256], *exten, *rexten, *rdomain, *rname = NULL;
15937 char *params, *reason_param = NULL;
15938 struct sip_request *req;
15939
15940 req = oreq ? oreq : &p->initreq;
15941
15942 ast_copy_string(tmp, get_header(req, "Diversion"), sizeof(tmp));
15943 if (ast_strlen_zero(tmp))
15944 return -1;
15945
15946 if ((params = strchr(tmp, '>'))) {
15947 params = strchr(params, ';');
15948 }
15949
15950 exten = get_in_brackets(tmp);
15951 if (!strncasecmp(exten, "sip:", 4)) {
15952 exten += 4;
15953 } else if (!strncasecmp(exten, "sips:", 5)) {
15954 exten += 5;
15955 } else {
15956 ast_log(LOG_WARNING, "Huh? Not an RDNIS SIP header (%s)?\n", exten);
15957 return -1;
15958 }
15959
15960
15961 if (params) {
15962 *params = '\0';
15963 params++;
15964 while (*params == ';' || *params == ' ')
15965 params++;
15966
15967 if ((reason_param = strcasestr(params, "reason="))) {
15968 char *end;
15969 reason_param+=7;
15970 if ((end = strchr(reason_param, ';'))) {
15971 *end = '\0';
15972 }
15973
15974 if (*reason_param == '"')
15975 reason_param = ast_strip_quoted(reason_param, "\"", "\"");
15976 if (!ast_strlen_zero(reason_param)) {
15977 sip_set_redirstr(p, reason_param);
15978 if (p->owner) {
15979 pbx_builtin_setvar_helper(p->owner, "__PRIREDIRECTREASON", p->redircause);
15980 pbx_builtin_setvar_helper(p->owner, "__SIPREDIRECTREASON", reason_param);
15981 }
15982 }
15983 }
15984 }
15985
15986 rdomain = exten;
15987 rexten = strsep(&rdomain, "@");
15988 if (p->owner)
15989 pbx_builtin_setvar_helper(p->owner, "__SIPRDNISDOMAIN", rdomain);
15990
15991 if (sip_debug_test_pvt(p))
15992 ast_verbose("RDNIS for this call is %s (reason %s)\n", exten, S_OR(reason_param, ""));
15993
15994
15995
15996 if (*tmp == '\"') {
15997 char *end_quote;
15998 rname = tmp + 1;
15999 end_quote = strchr(rname, '\"');
16000 if (end_quote) {
16001 *end_quote = '\0';
16002 }
16003 }
16004
16005 if (number) {
16006 *number = ast_strdup(rexten);
16007 }
16008
16009 if (name && rname) {
16010 *name = ast_strdup(rname);
16011 }
16012
16013 if (reason && !ast_strlen_zero(reason_param)) {
16014 *reason = sip_reason_str_to_code(reason_param);
16015 }
16016
16017 return 0;
16018 }
16019
16020
16021
16022
16023
16024
16025
16026
16027
16028
16029
16030
16031
16032
16033
16034 static enum sip_get_dest_result get_destination(struct sip_pvt *p, struct sip_request *oreq, int *cc_recall_core_id)
16035 {
16036 char tmp[256] = "", *uri, *unused_password, *domain;
16037 char tmpf[256] = "", *from = NULL;
16038 struct sip_request *req;
16039 char *decoded_uri;
16040
16041 req = oreq;
16042 if (!req) {
16043 req = &p->initreq;
16044 }
16045
16046
16047 if (req->rlPart2)
16048 ast_copy_string(tmp, REQ_OFFSET_TO_STR(req, rlPart2), sizeof(tmp));
16049
16050 uri = ast_strdupa(get_in_brackets(tmp));
16051
16052 if (parse_uri_legacy_check(uri, "sip:,sips:", &uri, &unused_password, &domain, NULL)) {
16053 ast_log(LOG_WARNING, "Not a SIP header (%s)?\n", uri);
16054 return SIP_GET_DEST_INVALID_URI;
16055 }
16056
16057 SIP_PEDANTIC_DECODE(domain);
16058 SIP_PEDANTIC_DECODE(uri);
16059
16060 extract_host_from_hostport(&domain);
16061
16062 if (ast_strlen_zero(uri)) {
16063
16064
16065
16066
16067
16068 uri = "s";
16069 }
16070
16071 ast_string_field_set(p, domain, domain);
16072
16073
16074
16075
16076
16077 ast_copy_string(tmpf, get_header(req, "From"), sizeof(tmpf));
16078 if (!ast_strlen_zero(tmpf)) {
16079 from = get_in_brackets(tmpf);
16080 if (parse_uri_legacy_check(from, "sip:,sips:", &from, NULL, &domain, NULL)) {
16081 ast_log(LOG_WARNING, "Not a SIP header (%s)?\n", from);
16082 return SIP_GET_DEST_INVALID_URI;
16083 }
16084
16085 SIP_PEDANTIC_DECODE(from);
16086 SIP_PEDANTIC_DECODE(domain);
16087
16088 extract_host_from_hostport(&domain);
16089
16090 ast_string_field_set(p, fromdomain, domain);
16091 }
16092
16093 if (!AST_LIST_EMPTY(&domain_list)) {
16094 char domain_context[AST_MAX_EXTENSION];
16095
16096 domain_context[0] = '\0';
16097 if (!check_sip_domain(p->domain, domain_context, sizeof(domain_context))) {
16098 if (!sip_cfg.allow_external_domains && (req->method == SIP_INVITE || req->method == SIP_REFER)) {
16099 ast_debug(1, "Got SIP %s to non-local domain '%s'; refusing request.\n", sip_methods[req->method].text, p->domain);
16100 return SIP_GET_DEST_REFUSED;
16101 }
16102 }
16103
16104
16105 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_HAVEPEERCONTEXT) && !ast_strlen_zero(domain_context)) {
16106 ast_string_field_set(p, context, domain_context);
16107 }
16108 }
16109
16110
16111 if (req->method == SIP_SUBSCRIBE && !ast_strlen_zero(p->subscribecontext)) {
16112 ast_string_field_set(p, context, p->subscribecontext);
16113 }
16114
16115 if (sip_debug_test_pvt(p)) {
16116 ast_verbose("Looking for %s in %s (domain %s)\n", uri, p->context, p->domain);
16117 }
16118
16119
16120
16121 decoded_uri = ast_strdupa(uri);
16122 ast_uri_decode(decoded_uri);
16123
16124
16125 if (req->method == SIP_SUBSCRIBE) {
16126 char hint[AST_MAX_EXTENSION];
16127 int which = 0;
16128 if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, uri) ||
16129 (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, decoded_uri) && (which = 1))) {
16130 if (!oreq) {
16131 ast_string_field_set(p, exten, which ? decoded_uri : uri);
16132 }
16133 return SIP_GET_DEST_EXTEN_FOUND;
16134 } else {
16135 return SIP_GET_DEST_EXTEN_NOT_FOUND;
16136 }
16137 } else {
16138 struct ast_cc_agent *agent;
16139
16140
16141
16142 if (ast_exists_extension(NULL, p->context, uri, 1, S_OR(p->cid_num, from))) {
16143 if (!oreq) {
16144 ast_string_field_set(p, exten, uri);
16145 }
16146 return SIP_GET_DEST_EXTEN_FOUND;
16147 }
16148 if (ast_exists_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from))
16149 || !strcmp(decoded_uri, ast_pickup_ext())) {
16150 if (!oreq) {
16151 ast_string_field_set(p, exten, decoded_uri);
16152 }
16153 return SIP_GET_DEST_EXTEN_FOUND;
16154 }
16155 if ((agent = find_sip_cc_agent_by_notify_uri(tmp))) {
16156 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
16157
16158
16159
16160 ast_string_field_set(p, exten, agent_pvt->original_exten);
16161
16162
16163
16164 ast_cc_agent_recalling(agent->core_id, "SIP caller %s is attempting recall",
16165 agent->device_name);
16166 if (cc_recall_core_id) {
16167 *cc_recall_core_id = agent->core_id;
16168 }
16169 ao2_ref(agent, -1);
16170 return SIP_GET_DEST_EXTEN_FOUND;
16171 }
16172 }
16173
16174 if (ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP)
16175 && (ast_canmatch_extension(NULL, p->context, uri, 1, S_OR(p->cid_num, from))
16176 || ast_canmatch_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from))
16177 || !strncmp(decoded_uri, ast_pickup_ext(), strlen(decoded_uri)))) {
16178
16179 return SIP_GET_DEST_EXTEN_MATCHMORE;
16180 }
16181
16182 return SIP_GET_DEST_EXTEN_NOT_FOUND;
16183 }
16184
16185
16186
16187
16188 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag)
16189 {
16190 struct sip_pvt *sip_pvt_ptr;
16191 struct sip_pvt tmp_dialog = {
16192 .callid = callid,
16193 };
16194
16195 if (totag) {
16196 ast_debug(4, "Looking for callid %s (fromtag %s totag %s)\n", callid, fromtag ? fromtag : "<no fromtag>", totag ? totag : "<no totag>");
16197 }
16198
16199
16200
16201 sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find of dialog in dialogs table");
16202 if (sip_pvt_ptr) {
16203
16204 sip_pvt_lock(sip_pvt_ptr);
16205 if (sip_cfg.pedanticsipchecking) {
16206 unsigned char frommismatch = 0, tomismatch = 0;
16207
16208 if (ast_strlen_zero(fromtag)) {
16209 sip_pvt_unlock(sip_pvt_ptr);
16210 ast_debug(4, "Matched %s call for callid=%s - no from tag specified, pedantic check fails\n",
16211 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
16212 return NULL;
16213 }
16214
16215 if (ast_strlen_zero(totag)) {
16216 sip_pvt_unlock(sip_pvt_ptr);
16217 ast_debug(4, "Matched %s call for callid=%s - no to tag specified, pedantic check fails\n",
16218 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
16219 return NULL;
16220 }
16221
16222
16223
16224
16225
16226
16227
16228
16229
16230
16231
16232
16233
16234
16235 frommismatch = !!strcmp(fromtag, sip_pvt_ptr->theirtag);
16236 tomismatch = !!strcmp(totag, sip_pvt_ptr->tag);
16237
16238
16239
16240
16241 if ((frommismatch && ast_test_flag(&sip_pvt_ptr->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) || tomismatch) {
16242 sip_pvt_unlock(sip_pvt_ptr);
16243 if (frommismatch) {
16244 ast_debug(4, "Matched %s call for callid=%s - pedantic from tag check fails; their tag is %s our tag is %s\n",
16245 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid,
16246 fromtag, sip_pvt_ptr->theirtag);
16247 }
16248 if (tomismatch) {
16249 ast_debug(4, "Matched %s call for callid=%s - pedantic to tag check fails; their tag is %s our tag is %s\n",
16250 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid,
16251 totag, sip_pvt_ptr->tag);
16252 }
16253 return NULL;
16254 }
16255 }
16256
16257 if (totag)
16258 ast_debug(4, "Matched %s call - their tag is %s Our tag is %s\n",
16259 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING",
16260 sip_pvt_ptr->theirtag, sip_pvt_ptr->tag);
16261
16262
16263 while (sip_pvt_ptr->owner && ast_channel_trylock(sip_pvt_ptr->owner)) {
16264 sip_pvt_unlock(sip_pvt_ptr);
16265 usleep(1);
16266 sip_pvt_lock(sip_pvt_ptr);
16267 }
16268 }
16269
16270 return sip_pvt_ptr;
16271 }
16272
16273
16274
16275
16276
16277
16278
16279
16280 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req)
16281 {
16282
16283 const char *p_referred_by = NULL;
16284 char *h_refer_to = NULL;
16285 char *h_referred_by = NULL;
16286 char *refer_to;
16287 const char *p_refer_to;
16288 char *referred_by_uri = NULL;
16289 char *ptr;
16290 struct sip_request *req = NULL;
16291 const char *transfer_context = NULL;
16292 struct sip_refer *referdata;
16293
16294
16295 req = outgoing_req;
16296 referdata = transferer->refer;
16297
16298 if (!req) {
16299 req = &transferer->initreq;
16300 }
16301
16302 p_refer_to = get_header(req, "Refer-To");
16303 if (ast_strlen_zero(p_refer_to)) {
16304 ast_log(LOG_WARNING, "Refer-To Header missing. Skipping transfer.\n");
16305 return -2;
16306 }
16307 h_refer_to = ast_strdupa(p_refer_to);
16308 refer_to = get_in_brackets(h_refer_to);
16309 if (!strncasecmp(refer_to, "sip:", 4)) {
16310 refer_to += 4;
16311 } else if (!strncasecmp(refer_to, "sips:", 5)) {
16312 refer_to += 5;
16313 } else {
16314 ast_log(LOG_WARNING, "Can't transfer to non-sip: URI. (Refer-to: %s)?\n", refer_to);
16315 return -3;
16316 }
16317
16318
16319 p_referred_by = get_header(req, "Referred-By");
16320
16321
16322 if (transferer->owner) {
16323 struct ast_channel *peer = ast_bridged_channel(transferer->owner);
16324 if (peer) {
16325 pbx_builtin_setvar_helper(peer, "SIPREFERRINGCONTEXT", transferer->context);
16326 pbx_builtin_setvar_helper(peer, "SIPREFERREDBYHDR", p_referred_by);
16327 }
16328 }
16329
16330 if (!ast_strlen_zero(p_referred_by)) {
16331 char *lessthan;
16332 h_referred_by = ast_strdupa(p_referred_by);
16333
16334
16335 ast_copy_string(referdata->referred_by_name, h_referred_by, sizeof(referdata->referred_by_name));
16336 if ((lessthan = strchr(referdata->referred_by_name, '<'))) {
16337 *(lessthan - 1) = '\0';
16338 }
16339
16340 referred_by_uri = get_in_brackets(h_referred_by);
16341
16342 if (!strncasecmp(referred_by_uri, "sip:", 4)) {
16343 referred_by_uri += 4;
16344 } else if (!strncasecmp(referred_by_uri, "sips:", 5)) {
16345 referred_by_uri += 5;
16346 } else {
16347 ast_log(LOG_WARNING, "Huh? Not a sip: header (Referred-by: %s). Skipping.\n", referred_by_uri);
16348 referred_by_uri = NULL;
16349 }
16350 }
16351
16352
16353 if ((ptr = strcasestr(refer_to, "replaces="))) {
16354 char *to = NULL, *from = NULL;
16355
16356
16357 referdata->attendedtransfer = 1;
16358 ast_copy_string(referdata->replaces_callid, ptr+9, sizeof(referdata->replaces_callid));
16359 ast_uri_decode(referdata->replaces_callid);
16360 if ((ptr = strchr(referdata->replaces_callid, ';'))) {
16361 *ptr++ = '\0';
16362 }
16363
16364 if (ptr) {
16365
16366 to = strcasestr(ptr, "to-tag=");
16367 from = strcasestr(ptr, "from-tag=");
16368 }
16369
16370
16371 if (to) {
16372 ptr = to + 7;
16373 if ((to = strchr(ptr, '&'))) {
16374 *to = '\0';
16375 }
16376 if ((to = strchr(ptr, ';'))) {
16377 *to = '\0';
16378 }
16379 ast_copy_string(referdata->replaces_callid_totag, ptr, sizeof(referdata->replaces_callid_totag));
16380 }
16381
16382 if (from) {
16383 ptr = from + 9;
16384 if ((to = strchr(ptr, '&'))) {
16385 *to = '\0';
16386 }
16387 if ((to = strchr(ptr, ';'))) {
16388 *to = '\0';
16389 }
16390 ast_copy_string(referdata->replaces_callid_fromtag, ptr, sizeof(referdata->replaces_callid_fromtag));
16391 }
16392
16393 if (!strcmp(referdata->replaces_callid, transferer->callid) &&
16394 (!sip_cfg.pedanticsipchecking ||
16395 (!strcmp(referdata->replaces_callid_fromtag, transferer->theirtag) &&
16396 !strcmp(referdata->replaces_callid_totag, transferer->tag)))) {
16397 ast_log(LOG_WARNING, "Got an attempt to replace own Call-ID on %s\n", transferer->callid);
16398 return -4;
16399 }
16400
16401 if (!sip_cfg.pedanticsipchecking) {
16402 ast_debug(2, "Attended transfer: Will use Replace-Call-ID : %s (No check of from/to tags)\n", referdata->replaces_callid );
16403 } else {
16404 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>" );
16405 }
16406 }
16407
16408 if ((ptr = strchr(refer_to, '@'))) {
16409 char *urioption = NULL, *domain;
16410 int bracket = 0;
16411 *ptr++ = '\0';
16412
16413 if ((urioption = strchr(ptr, ';'))) {
16414 *urioption++ = '\0';
16415 }
16416
16417 domain = ptr;
16418
16419
16420 for (; *ptr != '\0'; ++ptr) {
16421 if (*ptr == ':' && bracket == 0) {
16422 *ptr = '\0';
16423 break;
16424 } else if (*ptr == '[') {
16425 ++bracket;
16426 } else if (*ptr == ']') {
16427 --bracket;
16428 }
16429 }
16430
16431 SIP_PEDANTIC_DECODE(domain);
16432 SIP_PEDANTIC_DECODE(urioption);
16433
16434
16435 ast_copy_string(referdata->refer_to_domain, domain, sizeof(referdata->refer_to_domain));
16436 if (urioption) {
16437 ast_copy_string(referdata->refer_to_urioption, urioption, sizeof(referdata->refer_to_urioption));
16438 }
16439 }
16440
16441 if ((ptr = strchr(refer_to, ';')))
16442 *ptr = '\0';
16443
16444 SIP_PEDANTIC_DECODE(refer_to);
16445 ast_copy_string(referdata->refer_to, refer_to, sizeof(referdata->refer_to));
16446
16447 if (referred_by_uri) {
16448 if ((ptr = strchr(referred_by_uri, ';')))
16449 *ptr = '\0';
16450 SIP_PEDANTIC_DECODE(referred_by_uri);
16451 ast_copy_string(referdata->referred_by, referred_by_uri, sizeof(referdata->referred_by));
16452 } else {
16453 referdata->referred_by[0] = '\0';
16454 }
16455
16456
16457 if (transferer->owner) {
16458
16459 transfer_context = pbx_builtin_getvar_helper(transferer->owner, "TRANSFER_CONTEXT");
16460 if (ast_strlen_zero(transfer_context)) {
16461 transfer_context = transferer->owner->macrocontext;
16462 }
16463 }
16464 if (ast_strlen_zero(transfer_context)) {
16465 transfer_context = S_OR(transferer->context, sip_cfg.default_context);
16466 }
16467
16468 ast_copy_string(referdata->refer_to_context, transfer_context, sizeof(referdata->refer_to_context));
16469
16470
16471 if (referdata->attendedtransfer || ast_exists_extension(NULL, transfer_context, refer_to, 1, NULL) ) {
16472 if (sip_debug_test_pvt(transferer)) {
16473 ast_verbose("SIP transfer to extension %s@%s by %s\n", refer_to, transfer_context, referred_by_uri);
16474 }
16475
16476 return 0;
16477 }
16478 if (sip_debug_test_pvt(transferer))
16479 ast_verbose("Failed SIP Transfer to non-existing extension %s in context %s\n n", refer_to, transfer_context);
16480
16481
16482 return -1;
16483 }
16484
16485
16486
16487
16488
16489 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq)
16490 {
16491 char tmp[256] = "", *c, *a;
16492 struct sip_request *req = oreq ? oreq : &p->initreq;
16493 struct sip_refer *referdata = NULL;
16494 const char *transfer_context = NULL;
16495
16496 if (!p->refer && !sip_refer_allocate(p))
16497 return -1;
16498
16499 referdata = p->refer;
16500
16501 ast_copy_string(tmp, get_header(req, "Also"), sizeof(tmp));
16502 c = get_in_brackets(tmp);
16503
16504 if (parse_uri_legacy_check(c, "sip:,sips:", &c, NULL, &a, NULL)) {
16505 ast_log(LOG_WARNING, "Huh? Not a SIP header in Also: transfer (%s)?\n", c);
16506 return -1;
16507 }
16508
16509 SIP_PEDANTIC_DECODE(c);
16510 SIP_PEDANTIC_DECODE(a);
16511
16512 if (!ast_strlen_zero(a)) {
16513 ast_copy_string(referdata->refer_to_domain, a, sizeof(referdata->refer_to_domain));
16514 }
16515
16516 if (sip_debug_test_pvt(p))
16517 ast_verbose("Looking for %s in %s\n", c, p->context);
16518
16519
16520 if (p->owner) {
16521
16522 transfer_context = pbx_builtin_getvar_helper(p->owner, "TRANSFER_CONTEXT");
16523 if (ast_strlen_zero(transfer_context)) {
16524 transfer_context = p->owner->macrocontext;
16525 }
16526 }
16527 if (ast_strlen_zero(transfer_context)) {
16528 transfer_context = S_OR(p->context, sip_cfg.default_context);
16529 }
16530
16531 if (ast_exists_extension(NULL, transfer_context, c, 1, NULL)) {
16532
16533 ast_debug(1, "SIP Bye-also transfer to Extension %s@%s \n", c, transfer_context);
16534 ast_copy_string(referdata->refer_to, c, sizeof(referdata->refer_to));
16535 ast_copy_string(referdata->referred_by, "", sizeof(referdata->referred_by));
16536 ast_copy_string(referdata->refer_contact, "", sizeof(referdata->refer_contact));
16537
16538 ast_string_field_set(p, context, transfer_context);
16539 return 0;
16540 } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
16541 return 1;
16542 }
16543
16544 return -1;
16545 }
16546
16547
16548
16549
16550
16551
16552
16553
16554
16555
16556
16557 static attribute_unused void check_via_response(struct sip_pvt *p, struct sip_request *req)
16558 {
16559 char via[256];
16560 char *cur, *opts;
16561
16562 ast_copy_string(via, get_header(req, "Via"), sizeof(via));
16563
16564
16565 opts = strchr(via, ',');
16566 if (opts)
16567 *opts = '\0';
16568
16569
16570 opts = strchr(via, ';');
16571 if (!opts)
16572 return;
16573 *opts++ = '\0';
16574 while ( (cur = strsep(&opts, ";")) ) {
16575 if (!strncmp(cur, "rport=", 6)) {
16576 int port = strtol(cur+6, NULL, 10);
16577
16578 ast_sockaddr_set_port(&p->ourip, port);
16579 } else if (!strncmp(cur, "received=", 9)) {
16580 if (ast_parse_arg(cur + 9, PARSE_ADDR, &p->ourip))
16581 ;
16582 }
16583 }
16584 }
16585
16586
16587 static void check_via(struct sip_pvt *p, const struct sip_request *req)
16588 {
16589 char via[512];
16590 char *c, *maddr;
16591 struct ast_sockaddr tmp = { { 0, } };
16592 uint16_t port;
16593
16594 ast_copy_string(via, get_header(req, "Via"), sizeof(via));
16595
16596
16597 c = strchr(via, ',');
16598 if (c)
16599 *c = '\0';
16600
16601
16602 c = strstr(via, ";rport");
16603 if (c && (c[6] != '=')) {
16604 ast_set_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT);
16605 ast_set_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT);
16606 }
16607
16608
16609 maddr = strstr(via, "maddr=");
16610 if (maddr) {
16611 maddr += 6;
16612 c = maddr + strspn(maddr, "abcdefghijklmnopqrstuvwxyz"
16613 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-.:[]");
16614 *c = '\0';
16615 }
16616
16617 c = strchr(via, ';');
16618 if (c)
16619 *c = '\0';
16620
16621 c = strchr(via, ' ');
16622 if (c) {
16623 *c = '\0';
16624 c = ast_skip_blanks(c+1);
16625 if (strcasecmp(via, "SIP/2.0/UDP") && strcasecmp(via, "SIP/2.0/TCP") && strcasecmp(via, "SIP/2.0/TLS")) {
16626 ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
16627 return;
16628 }
16629
16630 if (maddr && ast_sockaddr_resolve_first(&p->sa, maddr, 0)) {
16631 p->sa = p->recv;
16632 }
16633
16634 if (ast_sockaddr_resolve_first(&tmp, c, 0)) {
16635 ast_log(LOG_WARNING, "Could not resolve socket address for '%s'\n", c);
16636 port = STANDARD_SIP_PORT;
16637 } else if (!(port = ast_sockaddr_port(&tmp))) {
16638 port = STANDARD_SIP_PORT;
16639 }
16640
16641 ast_sockaddr_set_port(&p->sa, port);
16642
16643 if (sip_debug_test_pvt(p)) {
16644 ast_verbose("Sending to %s (%s)\n",
16645 ast_sockaddr_stringify(sip_real_dst(p)),
16646 sip_nat_mode(p));
16647 }
16648 }
16649 }
16650
16651
16652 static enum check_auth_result check_peer_ok(struct sip_pvt *p, char *of,
16653 struct sip_request *req, int sipmethod, struct ast_sockaddr *addr,
16654 struct sip_peer **authpeer,
16655 enum xmittype reliable, char *calleridname, char *uri2)
16656 {
16657 enum check_auth_result res;
16658 int debug = sip_debug_test_addr(addr);
16659 struct sip_peer *peer;
16660
16661 if (sipmethod == SIP_SUBSCRIBE) {
16662
16663
16664
16665 peer = find_peer(of, NULL, TRUE, FINDALLDEVICES, FALSE, 0);
16666 } else {
16667
16668 peer = find_peer(of, NULL, TRUE, FINDUSERS, FALSE, 0);
16669
16670
16671 if (!peer) {
16672 peer = find_peer(NULL, &p->recv, TRUE, FINDPEERS, FALSE, p->socket.type);
16673 }
16674 }
16675
16676 if (!peer) {
16677 if (debug) {
16678 ast_verbose("No matching peer for '%s' from '%s'\n",
16679 of, ast_sockaddr_stringify(&p->recv));
16680 }
16681
16682
16683
16684
16685 if (sip_cfg.allowguest || !sip_cfg.alwaysauthreject) {
16686 return AUTH_DONT_KNOW;
16687 }
16688
16689
16690
16691
16692 peer = bogus_peer;
16693 ref_peer(peer, "ref_peer: check_peer_ok: must ref bogus_peer so unreffing it does not fail");
16694 }
16695
16696 if (!ast_apply_ha(peer->ha, addr)) {
16697 ast_debug(2, "Found peer '%s' for '%s', but fails host access\n", peer->name, of);
16698 unref_peer(peer, "unref_peer: check_peer_ok: from find_peer call, early return of AUTH_ACL_FAILED");
16699 return AUTH_ACL_FAILED;
16700 }
16701 if (debug && peer != bogus_peer) {
16702 ast_verbose("Found peer '%s' for '%s' from %s\n",
16703 peer->name, of, ast_sockaddr_stringify(&p->recv));
16704 }
16705
16706
16707
16708 if (p->rtp) {
16709 ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(p->rtp), p->rtp, &peer->prefs);
16710 p->autoframing = peer->autoframing;
16711 }
16712
16713
16714 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
16715 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
16716 ast_copy_flags(&p->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
16717
16718 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) && p->udptl) {
16719 p->t38_maxdatagram = peer->t38_maxdatagram;
16720 set_t38_capabilities(p);
16721 }
16722
16723
16724
16725 if (p->sipoptions)
16726 peer->sipoptions = p->sipoptions;
16727
16728 do_setnat(p);
16729
16730 ast_string_field_set(p, peersecret, peer->secret);
16731 ast_string_field_set(p, peermd5secret, peer->md5secret);
16732 ast_string_field_set(p, subscribecontext, peer->subscribecontext);
16733 ast_string_field_set(p, mohinterpret, peer->mohinterpret);
16734 ast_string_field_set(p, mohsuggest, peer->mohsuggest);
16735 if (!ast_strlen_zero(peer->parkinglot)) {
16736 ast_string_field_set(p, parkinglot, peer->parkinglot);
16737 }
16738 ast_string_field_set(p, engine, peer->engine);
16739 p->disallowed_methods = peer->disallowed_methods;
16740 set_pvt_allowed_methods(p, req);
16741 ast_cc_copy_config_params(p->cc_params, peer->cc_params);
16742 if (peer->callingpres)
16743 p->callingpres = peer->callingpres;
16744 if (peer->maxms && peer->lastms)
16745 p->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
16746 else
16747 p->timer_t1 = peer->timer_t1;
16748
16749
16750 if (peer->timer_b)
16751 p->timer_b = peer->timer_b;
16752 else
16753 p->timer_b = 64 * p->timer_t1;
16754
16755 p->allowtransfer = peer->allowtransfer;
16756
16757 if (ast_test_flag(&peer->flags[0], SIP_INSECURE_INVITE)) {
16758
16759 ast_string_field_set(p, peersecret, NULL);
16760 ast_string_field_set(p, peermd5secret, NULL);
16761 }
16762 if (!(res = check_auth(p, req, peer->name, p->peersecret, p->peermd5secret, sipmethod, uri2, reliable, req->ignore))) {
16763 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
16764 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
16765 ast_copy_flags(&p->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
16766
16767 if (peer->call_limit)
16768 ast_set_flag(&p->flags[0], SIP_CALL_LIMIT);
16769 ast_string_field_set(p, peername, peer->name);
16770 ast_string_field_set(p, authname, peer->name);
16771
16772 if (sipmethod == SIP_INVITE) {
16773
16774 ast_variables_destroy(p->chanvars);
16775 p->chanvars = copy_vars(peer->chanvars);
16776 }
16777
16778 if (authpeer) {
16779 ao2_t_ref(peer, 1, "copy pointer into (*authpeer)");
16780 (*authpeer) = peer;
16781 }
16782
16783 if (!ast_strlen_zero(peer->username)) {
16784 ast_string_field_set(p, username, peer->username);
16785
16786
16787 ast_string_field_set(p, authname, peer->username);
16788 }
16789 if (!get_rpid(p, req)) {
16790 if (!ast_strlen_zero(peer->cid_num)) {
16791 char *tmp = ast_strdupa(peer->cid_num);
16792 if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
16793 ast_shrink_phone_number(tmp);
16794 ast_string_field_set(p, cid_num, tmp);
16795 }
16796 if (!ast_strlen_zero(peer->cid_name))
16797 ast_string_field_set(p, cid_name, peer->cid_name);
16798 if (peer->callingpres)
16799 p->callingpres = peer->callingpres;
16800 }
16801 if (!ast_strlen_zero(peer->cid_tag)) {
16802 ast_string_field_set(p, cid_tag, peer->cid_tag);
16803 }
16804 ast_string_field_set(p, fullcontact, peer->fullcontact);
16805
16806 if (!ast_strlen_zero(peer->context)) {
16807 ast_string_field_set(p, context, peer->context);
16808 }
16809 if (!ast_strlen_zero(peer->mwi_from)) {
16810 ast_string_field_set(p, mwi_from, peer->mwi_from);
16811 }
16812
16813 ast_string_field_set(p, peersecret, peer->secret);
16814 ast_string_field_set(p, peermd5secret, peer->md5secret);
16815 ast_string_field_set(p, language, peer->language);
16816 ast_string_field_set(p, accountcode, peer->accountcode);
16817 p->amaflags = peer->amaflags;
16818 p->callgroup = peer->callgroup;
16819 p->pickupgroup = peer->pickupgroup;
16820 p->capability = peer->capability;
16821 p->prefs = peer->prefs;
16822 p->jointcapability = peer->capability;
16823 if (peer->maxforwards > 0) {
16824 p->maxforwards = peer->maxforwards;
16825 }
16826 if (p->peercapability)
16827 p->jointcapability &= p->peercapability;
16828 p->maxcallbitrate = peer->maxcallbitrate;
16829 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
16830 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
16831 p->noncodeccapability |= AST_RTP_DTMF;
16832 else
16833 p->noncodeccapability &= ~AST_RTP_DTMF;
16834 p->jointnoncodeccapability = p->noncodeccapability;
16835 p->rtptimeout = peer->rtptimeout;
16836 p->rtpholdtimeout = peer->rtpholdtimeout;
16837 p->rtpkeepalive = peer->rtpkeepalive;
16838 if (!dialog_initialize_rtp(p)) {
16839 if (p->rtp) {
16840 ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(p->rtp), p->rtp, &peer->prefs);
16841 p->autoframing = peer->autoframing;
16842 }
16843 } else {
16844 res = AUTH_RTP_FAILED;
16845 }
16846 }
16847 unref_peer(peer, "check_peer_ok: unref_peer: tossing temp ptr to peer from find_peer");
16848 return res;
16849 }
16850
16851
16852
16853
16854
16855
16856
16857 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
16858 int sipmethod, const char *uri, enum xmittype reliable,
16859 struct ast_sockaddr *addr, struct sip_peer **authpeer)
16860 {
16861 char from[256], *of, *name, *unused_password, *domain;
16862 enum check_auth_result res = AUTH_DONT_KNOW;
16863 char calleridname[256];
16864 char *uri2 = ast_strdupa(uri);
16865
16866 terminate_uri(uri2);
16867
16868 ast_copy_string(from, get_header(req, "From"), sizeof(from));
16869
16870
16871
16872 if (!(of = (char *) get_calleridname(from, calleridname, sizeof(calleridname)))) {
16873 ast_log(LOG_ERROR, "FROM header can not be parsed \n");
16874 return res;
16875 }
16876
16877 if (calleridname[0]) {
16878 ast_string_field_set(p, cid_name, calleridname);
16879 }
16880
16881 if (ast_strlen_zero(p->exten)) {
16882 char *t = uri2;
16883 if (!strncasecmp(t, "sip:", 4))
16884 t+= 4;
16885 else if (!strncasecmp(t, "sips:", 5))
16886 t += 5;
16887 ast_string_field_set(p, exten, t);
16888 t = strchr(p->exten, '@');
16889 if (t)
16890 *t = '\0';
16891
16892 if (ast_strlen_zero(p->our_contact))
16893 build_contact(p);
16894 }
16895
16896 of = get_in_brackets(of);
16897
16898
16899 ast_string_field_set(p, from, of);
16900
16901 if (parse_uri_legacy_check(of, "sip:,sips:", &name, &unused_password, &domain, NULL)) {
16902 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
16903 }
16904
16905 SIP_PEDANTIC_DECODE(name);
16906 SIP_PEDANTIC_DECODE(domain);
16907
16908 extract_host_from_hostport(&domain);
16909
16910 if (ast_strlen_zero(domain)) {
16911
16912 ast_log(LOG_ERROR, "Empty domain name in FROM header\n");
16913 return res;
16914 }
16915
16916 if (ast_strlen_zero(name)) {
16917
16918
16919
16920 name = domain;
16921 } else {
16922
16923 char *tmp = ast_strdupa(name);
16924
16925
16926
16927 tmp = strsep(&tmp, ";");
16928 if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp)) {
16929 ast_shrink_phone_number(tmp);
16930 }
16931 ast_string_field_set(p, cid_num, tmp);
16932 }
16933
16934 if (global_match_auth_username) {
16935
16936
16937
16938
16939
16940
16941
16942
16943 const char *hdr = get_header(req, "Authorization");
16944 if (ast_strlen_zero(hdr)) {
16945 hdr = get_header(req, "Proxy-Authorization");
16946 }
16947
16948 if (!ast_strlen_zero(hdr) && (hdr = strstr(hdr, "username=\""))) {
16949 ast_copy_string(from, hdr + strlen("username=\""), sizeof(from));
16950 name = from;
16951 name = strsep(&name, "\"");
16952 }
16953 }
16954
16955 res = check_peer_ok(p, name, req, sipmethod, addr,
16956 authpeer, reliable, calleridname, uri2);
16957 if (res != AUTH_DONT_KNOW) {
16958 return res;
16959 }
16960
16961
16962 if (sip_cfg.allowguest) {
16963
16964 get_rpid(p, req);
16965 p->rtptimeout = global_rtptimeout;
16966 p->rtpholdtimeout = global_rtpholdtimeout;
16967 p->rtpkeepalive = global_rtpkeepalive;
16968 if (!dialog_initialize_rtp(p)) {
16969 res = AUTH_SUCCESSFUL;
16970 } else {
16971 res = AUTH_RTP_FAILED;
16972 }
16973 } else {
16974 res = AUTH_SECRET_FAILED;
16975 }
16976
16977 if (ast_test_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT)) {
16978 ast_set_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT);
16979 }
16980
16981 return res;
16982 }
16983
16984
16985
16986
16987 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, const char *uri, enum xmittype reliable, struct ast_sockaddr *addr)
16988 {
16989 return check_user_full(p, req, sipmethod, uri, reliable, addr, NULL);
16990 }
16991
16992
16993
16994
16995
16996
16997
16998
16999
17000 static int get_msg_text(char *buf, int len, struct sip_request *req)
17001 {
17002 int x;
17003 int linelen;
17004
17005 buf[0] = '\0';
17006 --len;
17007 for (x = 0; len && x < req->lines; ++x) {
17008 const char *line = REQ_OFFSET_TO_STR(req, line[x]);
17009 strncat(buf, line, len);
17010 linelen = strlen(buf);
17011 buf += linelen;
17012 len -= linelen;
17013 if (len) {
17014 strcat(buf, "\n");
17015 ++buf;
17016 --len;
17017 }
17018 }
17019 return 0;
17020 }
17021
17022
17023
17024
17025
17026 static void receive_message(struct sip_pvt *p, struct sip_request *req)
17027 {
17028 char buf[1400];
17029 char *bufp;
17030 struct ast_frame f;
17031 const char *content_type = get_header(req, "Content-Type");
17032
17033 if (strncmp(content_type, "text/plain", strlen("text/plain"))) {
17034 transmit_response(p, "415 Unsupported Media Type", req);
17035 if (!p->owner)
17036 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17037 return;
17038 }
17039
17040 if (get_msg_text(buf, sizeof(buf), req)) {
17041 ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
17042 transmit_response(p, "500 Internal Server Error", req);
17043 if (!p->owner) {
17044 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17045 }
17046 return;
17047 }
17048
17049
17050
17051 bufp = buf + strlen(buf);
17052 while (--bufp >= buf && *bufp == '\n') {
17053 *bufp = '\0';
17054 }
17055
17056 if (p->owner) {
17057 if (sip_debug_test_pvt(p))
17058 ast_verbose("SIP Text message received: '%s'\n", buf);
17059 memset(&f, 0, sizeof(f));
17060 f.frametype = AST_FRAME_TEXT;
17061 f.subclass.integer = 0;
17062 f.offset = 0;
17063 f.data.ptr = buf;
17064 f.datalen = strlen(buf) + 1;
17065 ast_queue_frame(p->owner, &f);
17066 transmit_response(p, "202 Accepted", req);
17067 return;
17068 }
17069
17070
17071 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);
17072 transmit_response(p, "405 Method Not Allowed", req);
17073 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17074 return;
17075 }
17076
17077
17078 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17079 {
17080 #define FORMAT "%-25.25s %-15.15s %-15.15s \n"
17081 #define FORMAT2 "%-25.25s %-15.15s %-15.15s \n"
17082 char ilimits[40];
17083 char iused[40];
17084 int showall = FALSE;
17085 struct ao2_iterator i;
17086 struct sip_peer *peer;
17087
17088 switch (cmd) {
17089 case CLI_INIT:
17090 e->command = "sip show inuse";
17091 e->usage =
17092 "Usage: sip show inuse [all]\n"
17093 " List all SIP devices usage counters and limits.\n"
17094 " Add option \"all\" to show all devices, not only those with a limit.\n";
17095 return NULL;
17096 case CLI_GENERATE:
17097 return NULL;
17098 }
17099
17100 if (a->argc < 3)
17101 return CLI_SHOWUSAGE;
17102
17103 if (a->argc == 4 && !strcmp(a->argv[3], "all"))
17104 showall = TRUE;
17105
17106 ast_cli(a->fd, FORMAT, "* Peer name", "In use", "Limit");
17107
17108 i = ao2_iterator_init(peers, 0);
17109 while ((peer = ao2_t_iterator_next(&i, "iterate thru peer table"))) {
17110 ao2_lock(peer);
17111 if (peer->call_limit)
17112 snprintf(ilimits, sizeof(ilimits), "%d", peer->call_limit);
17113 else
17114 ast_copy_string(ilimits, "N/A", sizeof(ilimits));
17115 snprintf(iused, sizeof(iused), "%d/%d/%d", peer->inUse, peer->inRinging, peer->onHold);
17116 if (showall || peer->call_limit)
17117 ast_cli(a->fd, FORMAT2, peer->name, iused, ilimits);
17118 ao2_unlock(peer);
17119 unref_peer(peer, "toss iterator pointer");
17120 }
17121 ao2_iterator_destroy(&i);
17122
17123 return CLI_SUCCESS;
17124 #undef FORMAT
17125 #undef FORMAT2
17126 }
17127
17128
17129
17130 static char *transfermode2str(enum transfermodes mode)
17131 {
17132 if (mode == TRANSFER_OPENFORALL)
17133 return "open";
17134 else if (mode == TRANSFER_CLOSED)
17135 return "closed";
17136 return "strict";
17137 }
17138
17139
17140
17141
17142
17143
17144
17145 static const struct _map_x_s stmodes[] = {
17146 { SESSION_TIMER_MODE_ACCEPT, "Accept"},
17147 { SESSION_TIMER_MODE_ORIGINATE, "Originate"},
17148 { SESSION_TIMER_MODE_REFUSE, "Refuse"},
17149 { -1, NULL},
17150 };
17151
17152 static const char *stmode2str(enum st_mode m)
17153 {
17154 return map_x_s(stmodes, m, "Unknown");
17155 }
17156
17157 static enum st_mode str2stmode(const char *s)
17158 {
17159 return map_s_x(stmodes, s, -1);
17160 }
17161
17162
17163 static const struct _map_x_s strefresher_params[] = {
17164 { SESSION_TIMER_REFRESHER_PARAM_UNKNOWN, "unknown" },
17165 { SESSION_TIMER_REFRESHER_PARAM_UAC, "uac" },
17166 { SESSION_TIMER_REFRESHER_PARAM_UAS, "uas" },
17167 { -1, NULL },
17168 };
17169
17170 static const struct _map_x_s strefreshers[] = {
17171 { SESSION_TIMER_REFRESHER_AUTO, "auto" },
17172 { SESSION_TIMER_REFRESHER_US, "us" },
17173 { SESSION_TIMER_REFRESHER_THEM, "them" },
17174 { -1, NULL },
17175 };
17176
17177 static const char *strefresherparam2str(enum st_refresher r)
17178 {
17179 return map_x_s(strefresher_params, r, "Unknown");
17180 }
17181
17182 static enum st_refresher str2strefresherparam(const char *s)
17183 {
17184 return map_s_x(strefresher_params, s, -1);
17185 }
17186
17187 static const char *strefresher2str(enum st_refresher r)
17188 {
17189 return map_x_s(strefreshers, r, "Unknown");
17190 }
17191
17192 static int peer_status(struct sip_peer *peer, char *status, int statuslen)
17193 {
17194 int res = 0;
17195 if (peer->maxms) {
17196 if (peer->lastms < 0) {
17197 ast_copy_string(status, "UNREACHABLE", statuslen);
17198 } else if (peer->lastms > peer->maxms) {
17199 snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
17200 res = 1;
17201 } else if (peer->lastms) {
17202 snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
17203 res = 1;
17204 } else {
17205 ast_copy_string(status, "UNKNOWN", statuslen);
17206 }
17207 } else {
17208 ast_copy_string(status, "Unmonitored", statuslen);
17209
17210 res = -1;
17211 }
17212 return res;
17213 }
17214
17215
17216 static char *sip_show_tcp(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17217 {
17218 struct sip_threadinfo *th;
17219 struct ao2_iterator i;
17220
17221 #define FORMAT2 "%-47.47s %9.9s %6.6s\n"
17222 #define FORMAT "%-47.47s %-9.9s %-6.6s\n"
17223
17224 switch (cmd) {
17225 case CLI_INIT:
17226 e->command = "sip show tcp";
17227 e->usage =
17228 "Usage: sip show tcp\n"
17229 " Lists all active TCP/TLS sessions.\n";
17230 return NULL;
17231 case CLI_GENERATE:
17232 return NULL;
17233 }
17234
17235 if (a->argc != 3)
17236 return CLI_SHOWUSAGE;
17237
17238 ast_cli(a->fd, FORMAT2, "Address", "Transport", "Type");
17239
17240 i = ao2_iterator_init(threadt, 0);
17241 while ((th = ao2_t_iterator_next(&i, "iterate through tcp threads for 'sip show tcp'"))) {
17242 ast_cli(a->fd, FORMAT,
17243 ast_sockaddr_stringify(&th->tcptls_session->remote_address),
17244 get_transport(th->type),
17245 (th->tcptls_session->client ? "Client" : "Server"));
17246 ao2_t_ref(th, -1, "decrement ref from iterator");
17247 }
17248 ao2_iterator_destroy(&i);
17249
17250 return CLI_SUCCESS;
17251 #undef FORMAT
17252 #undef FORMAT2
17253 }
17254
17255
17256 static char *sip_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17257 {
17258 regex_t regexbuf;
17259 int havepattern = FALSE;
17260 struct ao2_iterator user_iter;
17261 struct sip_peer *user;
17262
17263 #define FORMAT "%-25.25s %-15.15s %-15.15s %-15.15s %-5.5s%-10.10s\n"
17264
17265 switch (cmd) {
17266 case CLI_INIT:
17267 e->command = "sip show users";
17268 e->usage =
17269 "Usage: sip show users [like <pattern>]\n"
17270 " Lists all known SIP users.\n"
17271 " Optional regular expression pattern is used to filter the user list.\n";
17272 return NULL;
17273 case CLI_GENERATE:
17274 return NULL;
17275 }
17276
17277 switch (a->argc) {
17278 case 5:
17279 if (!strcasecmp(a->argv[3], "like")) {
17280 if (regcomp(®exbuf, a->argv[4], REG_EXTENDED | REG_NOSUB))
17281 return CLI_SHOWUSAGE;
17282 havepattern = TRUE;
17283 } else
17284 return CLI_SHOWUSAGE;
17285 case 3:
17286 break;
17287 default:
17288 return CLI_SHOWUSAGE;
17289 }
17290
17291 ast_cli(a->fd, FORMAT, "Username", "Secret", "Accountcode", "Def.Context", "ACL", "Forcerport");
17292
17293 user_iter = ao2_iterator_init(peers, 0);
17294 while ((user = ao2_t_iterator_next(&user_iter, "iterate thru peers table"))) {
17295 ao2_lock(user);
17296 if (!(user->type & SIP_TYPE_USER)) {
17297 ao2_unlock(user);
17298 unref_peer(user, "sip show users");
17299 continue;
17300 }
17301
17302 if (havepattern && regexec(®exbuf, user->name, 0, NULL, 0)) {
17303 ao2_unlock(user);
17304 unref_peer(user, "sip show users");
17305 continue;
17306 }
17307
17308 ast_cli(a->fd, FORMAT, user->name,
17309 user->secret,
17310 user->accountcode,
17311 user->context,
17312 AST_CLI_YESNO(user->ha != NULL),
17313 AST_CLI_YESNO(ast_test_flag(&user->flags[0], SIP_NAT_FORCE_RPORT)));
17314 ao2_unlock(user);
17315 unref_peer(user, "sip show users");
17316 }
17317 ao2_iterator_destroy(&user_iter);
17318
17319 if (havepattern)
17320 regfree(®exbuf);
17321
17322 return CLI_SUCCESS;
17323 #undef FORMAT
17324 }
17325
17326
17327 static int manager_show_registry(struct mansession *s, const struct message *m)
17328 {
17329 const char *id = astman_get_header(m, "ActionID");
17330 char idtext[256] = "";
17331 int total = 0;
17332
17333 if (!ast_strlen_zero(id))
17334 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
17335
17336 astman_send_listack(s, m, "Registrations will follow", "start");
17337
17338 ASTOBJ_CONTAINER_TRAVERSE(®l, 1, do {
17339 ASTOBJ_RDLOCK(iterator);
17340 astman_append(s,
17341 "Event: RegistryEntry\r\n"
17342 "%s"
17343 "Host: %s\r\n"
17344 "Port: %d\r\n"
17345 "Username: %s\r\n"
17346 "Domain: %s\r\n"
17347 "DomainPort: %d\r\n"
17348 "Refresh: %d\r\n"
17349 "State: %s\r\n"
17350 "RegistrationTime: %ld\r\n"
17351 "\r\n",
17352 idtext,
17353 iterator->hostname,
17354 iterator->portno ? iterator->portno : STANDARD_SIP_PORT,
17355 iterator->username,
17356 S_OR(iterator->regdomain,iterator->hostname),
17357 iterator->regdomainport ? iterator->regdomainport : STANDARD_SIP_PORT,
17358 iterator->refresh,
17359 regstate2str(iterator->regstate),
17360 (long) iterator->regtime.tv_sec);
17361 ASTOBJ_UNLOCK(iterator);
17362 total++;
17363 } while(0));
17364
17365 astman_append(s,
17366 "Event: RegistrationsComplete\r\n"
17367 "EventList: Complete\r\n"
17368 "ListItems: %d\r\n"
17369 "%s"
17370 "\r\n", total, idtext);
17371
17372 return 0;
17373 }
17374
17375
17376
17377 static int manager_sip_show_peers(struct mansession *s, const struct message *m)
17378 {
17379 const char *id = astman_get_header(m, "ActionID");
17380 const char *a[] = {"sip", "show", "peers"};
17381 char idtext[256] = "";
17382 int total = 0;
17383
17384 if (!ast_strlen_zero(id))
17385 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
17386
17387 astman_send_listack(s, m, "Peer status list will follow", "start");
17388
17389 _sip_show_peers(-1, &total, s, m, 3, a);
17390
17391 astman_append(s,
17392 "Event: PeerlistComplete\r\n"
17393 "EventList: Complete\r\n"
17394 "ListItems: %d\r\n"
17395 "%s"
17396 "\r\n", total, idtext);
17397 return 0;
17398 }
17399
17400
17401 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17402 {
17403 switch (cmd) {
17404 case CLI_INIT:
17405 e->command = "sip show peers";
17406 e->usage =
17407 "Usage: sip show peers [like <pattern>]\n"
17408 " Lists all known SIP peers.\n"
17409 " Optional regular expression pattern is used to filter the peer list.\n";
17410 return NULL;
17411 case CLI_GENERATE:
17412 return NULL;
17413 }
17414
17415 return _sip_show_peers(a->fd, NULL, NULL, NULL, a->argc, (const char **) a->argv);
17416 }
17417
17418 int peercomparefunc(const void *a, const void *b);
17419
17420 int peercomparefunc(const void *a, const void *b)
17421 {
17422 struct sip_peer **ap = (struct sip_peer **)a;
17423 struct sip_peer **bp = (struct sip_peer **)b;
17424 return strcmp((*ap)->name, (*bp)->name);
17425 }
17426
17427
17428 #define PEERS_FORMAT2 "%-25.25s %-39.39s %-3.3s %-10.10s %-3.3s %-8s %-10s %s\n"
17429
17430
17431 struct show_peers_context {
17432 regex_t regexbuf;
17433 int havepattern;
17434 char idtext[256];
17435 int realtimepeers;
17436 int peers_mon_online;
17437 int peers_mon_offline;
17438 int peers_unmon_offline;
17439 int peers_unmon_online;
17440 };
17441
17442
17443 static char *_sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[])
17444 {
17445 struct show_peers_context cont = {
17446 .havepattern = FALSE,
17447 .idtext = "",
17448
17449 .peers_mon_online = 0,
17450 .peers_mon_offline = 0,
17451 .peers_unmon_online = 0,
17452 .peers_unmon_offline = 0,
17453 };
17454 struct sip_peer *peer;
17455 struct ao2_iterator* it_peers;
17456
17457 int total_peers = 0;
17458 const char *id;
17459 struct sip_peer **peerarray;
17460 int k;
17461
17462 cont.realtimepeers = ast_check_realtime("sippeers");
17463
17464 if (s) {
17465 id = astman_get_header(m, "ActionID");
17466 if (!ast_strlen_zero(id)) {
17467 snprintf(cont.idtext, sizeof(cont.idtext), "ActionID: %s\r\n", id);
17468 }
17469 }
17470
17471 switch (argc) {
17472 case 5:
17473 if (!strcasecmp(argv[3], "like")) {
17474 if (regcomp(&cont.regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
17475 return CLI_SHOWUSAGE;
17476 cont.havepattern = TRUE;
17477 } else
17478 return CLI_SHOWUSAGE;
17479 case 3:
17480 break;
17481 default:
17482 return CLI_SHOWUSAGE;
17483 }
17484
17485 if (!s) {
17486
17487 ast_cli(fd, PEERS_FORMAT2, "Name/username", "Host", "Dyn", "Forcerport", "ACL", "Port", "Status", (cont.realtimepeers ? "Realtime" : ""));
17488 }
17489
17490 ao2_lock(peers);
17491 if (!(it_peers = ao2_callback(peers, OBJ_MULTIPLE, NULL, NULL))) {
17492 ast_log(AST_LOG_ERROR, "Unable to create iterator for peers container for sip show peers\n");
17493 ao2_unlock(peers);
17494 return CLI_FAILURE;
17495 }
17496 if (!(peerarray = ast_calloc(sizeof(struct sip_peer *), ao2_container_count(peers)))) {
17497 ast_log(AST_LOG_ERROR, "Unable to allocate peer array for sip show peers\n");
17498 ao2_iterator_destroy(it_peers);
17499 ao2_unlock(peers);
17500 return CLI_FAILURE;
17501 }
17502 ao2_unlock(peers);
17503
17504 while ((peer = ao2_t_iterator_next(it_peers, "iterate thru peers table"))) {
17505 ao2_lock(peer);
17506
17507 if (!(peer->type & SIP_TYPE_PEER)) {
17508 ao2_unlock(peer);
17509 unref_peer(peer, "unref peer because it's actually a user");
17510 continue;
17511 }
17512
17513 if (cont.havepattern && regexec(&cont.regexbuf, peer->name, 0, NULL, 0)) {
17514 ao2_unlock(peer);
17515 unref_peer(peer, "toss iterator peer ptr before continue");
17516 continue;
17517 }
17518
17519 peerarray[total_peers++] = peer;
17520 ao2_unlock(peer);
17521 }
17522 ao2_iterator_destroy(it_peers);
17523
17524 qsort(peerarray, total_peers, sizeof(struct sip_peer *), peercomparefunc);
17525
17526 for(k = 0; k < total_peers; k++) {
17527 peerarray[k] = _sip_show_peers_one(fd, s, &cont, peerarray[k]);
17528 }
17529
17530 if (!s) {
17531 ast_cli(fd, "%d sip peers [Monitored: %d online, %d offline Unmonitored: %d online, %d offline]\n",
17532 total_peers, cont.peers_mon_online, cont.peers_mon_offline, cont.peers_unmon_online, cont.peers_unmon_offline);
17533 }
17534
17535 if (cont.havepattern) {
17536 regfree(&cont.regexbuf);
17537 }
17538
17539 if (total) {
17540 *total = total_peers;
17541 }
17542
17543 ast_free(peerarray);
17544
17545 return CLI_SUCCESS;
17546 }
17547
17548
17549 static struct sip_peer *_sip_show_peers_one(int fd, struct mansession *s, struct show_peers_context *cont, struct sip_peer *peer)
17550 {
17551
17552
17553
17554
17555 char name[256];
17556 char status[20] = "";
17557 char pstatus;
17558
17559
17560
17561
17562
17563
17564 char *tmp_port;
17565 char *tmp_host;
17566
17567 tmp_port = ast_sockaddr_isnull(&peer->addr) ?
17568 "0" : ast_strdupa(ast_sockaddr_stringify_port(&peer->addr));
17569
17570 tmp_host = ast_sockaddr_isnull(&peer->addr) ?
17571 "(Unspecified)" : ast_strdupa(ast_sockaddr_stringify_addr(&peer->addr));
17572
17573 ao2_lock(peer);
17574 if (cont->havepattern && regexec(&cont->regexbuf, peer->name, 0, NULL, 0)) {
17575 ao2_unlock(peer);
17576 return unref_peer(peer, "toss iterator peer ptr no match");
17577 }
17578
17579 if (!ast_strlen_zero(peer->username) && !s) {
17580 snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
17581 } else {
17582 ast_copy_string(name, peer->name, sizeof(name));
17583 }
17584
17585 pstatus = peer_status(peer, status, sizeof(status));
17586 if (pstatus == 1) {
17587 cont->peers_mon_online++;
17588 } else if (pstatus == 0) {
17589 cont->peers_mon_offline++;
17590 } else {
17591 if (ast_sockaddr_isnull(&peer->addr) ||
17592 !ast_sockaddr_port(&peer->addr)) {
17593 cont->peers_unmon_offline++;
17594 } else {
17595 cont->peers_unmon_online++;
17596 }
17597 }
17598
17599 if (!s) {
17600 ast_cli(fd, PEERS_FORMAT2, name,
17601 tmp_host,
17602 peer->host_dynamic ? " D " : " ",
17603 ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) ? " N " : " ",
17604 peer->ha ? " A " : " ",
17605 tmp_port, status,
17606 cont->realtimepeers ? (peer->is_realtime ? "Cached RT":"") : "");
17607 } else {
17608
17609 astman_append(s,
17610 "Event: PeerEntry\r\n%s"
17611 "Channeltype: SIP\r\n"
17612 "ObjectName: %s\r\n"
17613 "ChanObjectType: peer\r\n"
17614 "IPaddress: %s\r\n"
17615 "IPport: %s\r\n"
17616 "Dynamic: %s\r\n"
17617 "Forcerport: %s\r\n"
17618 "VideoSupport: %s\r\n"
17619 "TextSupport: %s\r\n"
17620 "ACL: %s\r\n"
17621 "Status: %s\r\n"
17622 "RealtimeDevice: %s\r\n\r\n",
17623 cont->idtext,
17624 peer->name,
17625 ast_sockaddr_isnull(&peer->addr) ? "-none-" : tmp_host,
17626 ast_sockaddr_isnull(&peer->addr) ? "0" : tmp_port,
17627 peer->host_dynamic ? "yes" : "no",
17628 ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) ? "yes" : "no",
17629 ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "yes" : "no",
17630 ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT) ? "yes" : "no",
17631 peer->ha ? "yes" : "no",
17632 status,
17633 cont->realtimepeers ? (peer->is_realtime ? "yes":"no") : "no");
17634 }
17635 ao2_unlock(peer);
17636
17637 return unref_peer(peer, "toss iterator peer ptr");
17638 }
17639 #undef PEERS_FORMAT2
17640
17641 static int peer_dump_func(void *userobj, void *arg, int flags)
17642 {
17643 struct sip_peer *peer = userobj;
17644 int refc = ao2_t_ref(userobj, 0, "");
17645 struct ast_cli_args *a = (struct ast_cli_args *) arg;
17646
17647 ast_cli(a->fd, "name: %s\ntype: peer\nobjflags: %d\nrefcount: %d\n\n",
17648 peer->name, 0, refc);
17649 return 0;
17650 }
17651
17652 static int dialog_dump_func(void *userobj, void *arg, int flags)
17653 {
17654 struct sip_pvt *pvt = userobj;
17655 int refc = ao2_t_ref(userobj, 0, "");
17656 struct ast_cli_args *a = (struct ast_cli_args *) arg;
17657
17658 ast_cli(a->fd, "name: %s\ntype: dialog\nobjflags: %d\nrefcount: %d\n\n",
17659 pvt->callid, 0, refc);
17660 return 0;
17661 }
17662
17663
17664
17665 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17666 {
17667 char tmp[256];
17668
17669 switch (cmd) {
17670 case CLI_INIT:
17671 e->command = "sip show objects";
17672 e->usage =
17673 "Usage: sip show objects\n"
17674 " Lists status of known SIP objects\n";
17675 return NULL;
17676 case CLI_GENERATE:
17677 return NULL;
17678 }
17679
17680 if (a->argc != 3)
17681 return CLI_SHOWUSAGE;
17682 ast_cli(a->fd, "-= Peer objects: %d static, %d realtime, %d autocreate =-\n\n", speerobjs, rpeerobjs, apeerobjs);
17683 ao2_t_callback(peers, OBJ_NODATA, peer_dump_func, a, "initiate ao2_callback to dump peers");
17684 ast_cli(a->fd, "-= Peer objects by IP =-\n\n");
17685 ao2_t_callback(peers_by_ip, OBJ_NODATA, peer_dump_func, a, "initiate ao2_callback to dump peers_by_ip");
17686 ast_cli(a->fd, "-= Registry objects: %d =-\n\n", regobjs);
17687 ASTOBJ_CONTAINER_DUMP(a->fd, tmp, sizeof(tmp), ®l);
17688 ast_cli(a->fd, "-= Dialog objects:\n\n");
17689 ao2_t_callback(dialogs, OBJ_NODATA, dialog_dump_func, a, "initiate ao2_callback to dump dialogs");
17690 return CLI_SUCCESS;
17691 }
17692
17693 static void print_group(int fd, ast_group_t group, int crlf)
17694 {
17695 char buf[256];
17696 ast_cli(fd, crlf ? "%s\r\n" : "%s\n", ast_print_group(buf, sizeof(buf), group) );
17697 }
17698
17699
17700 static const struct _map_x_s dtmfstr[] = {
17701 { SIP_DTMF_RFC2833, "rfc2833" },
17702 { SIP_DTMF_INFO, "info" },
17703 { SIP_DTMF_SHORTINFO, "shortinfo" },
17704 { SIP_DTMF_INBAND, "inband" },
17705 { SIP_DTMF_AUTO, "auto" },
17706 { -1, NULL },
17707 };
17708
17709
17710 static const char *dtmfmode2str(int mode)
17711 {
17712 return map_x_s(dtmfstr, mode, "<error>");
17713 }
17714
17715
17716 static int str2dtmfmode(const char *str)
17717 {
17718 return map_s_x(dtmfstr, str, -1);
17719 }
17720
17721 static const struct _map_x_s insecurestr[] = {
17722 { SIP_INSECURE_PORT, "port" },
17723 { SIP_INSECURE_INVITE, "invite" },
17724 { SIP_INSECURE_PORT | SIP_INSECURE_INVITE, "port,invite" },
17725 { 0, "no" },
17726 { -1, NULL },
17727 };
17728
17729
17730 static const char *insecure2str(int mode)
17731 {
17732 return map_x_s(insecurestr, mode, "<error>");
17733 }
17734
17735 static const struct _map_x_s allowoverlapstr[] = {
17736 { SIP_PAGE2_ALLOWOVERLAP_YES, "Yes" },
17737 { SIP_PAGE2_ALLOWOVERLAP_DTMF, "DTMF" },
17738 { SIP_PAGE2_ALLOWOVERLAP_NO, "No" },
17739 { -1, NULL },
17740 };
17741
17742
17743 static const char *allowoverlap2str(int mode)
17744 {
17745 return map_x_s(allowoverlapstr, mode, "<error>");
17746 }
17747
17748 static const struct _map_x_s trust_id_outboundstr[] = {
17749 { SIP_PAGE2_TRUST_ID_OUTBOUND_LEGACY, "Legacy" },
17750 { SIP_PAGE2_TRUST_ID_OUTBOUND_NO, "No" },
17751 { SIP_PAGE2_TRUST_ID_OUTBOUND_YES, "Yes" },
17752 { -1, NULL },
17753 };
17754
17755 static const char *trust_id_outbound2str(int mode)
17756 {
17757 return map_x_s(trust_id_outboundstr, mode, "<error>");
17758 }
17759
17760
17761
17762
17763 static void cleanup_stale_contexts(char *new, char *old)
17764 {
17765 char *oldcontext, *newcontext, *stalecontext, *stringp, newlist[AST_MAX_CONTEXT];
17766
17767 while ((oldcontext = strsep(&old, "&"))) {
17768 stalecontext = '\0';
17769 ast_copy_string(newlist, new, sizeof(newlist));
17770 stringp = newlist;
17771 while ((newcontext = strsep(&stringp, "&"))) {
17772 if (!strcmp(newcontext, oldcontext)) {
17773
17774 stalecontext = '\0';
17775 break;
17776 } else if (strcmp(newcontext, oldcontext)) {
17777 stalecontext = oldcontext;
17778 }
17779
17780 }
17781 if (stalecontext)
17782 ast_context_destroy(ast_context_find(stalecontext), "SIP");
17783 }
17784 }
17785
17786
17787
17788
17789
17790
17791
17792
17793
17794
17795
17796 static int dialog_needdestroy(void *dialogobj, void *arg, int flags)
17797 {
17798 struct sip_pvt *dialog = dialogobj;
17799 time_t *t = arg;
17800
17801 if (sip_pvt_trylock(dialog)) {
17802
17803
17804 return 0;
17805 }
17806
17807
17808 check_rtp_timeout(dialog, *t);
17809
17810
17811 if (dialog->rtp && ast_rtp_instance_get_bridged(dialog->rtp)) {
17812 ast_debug(2, "Bridge still active. Delaying destroy of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
17813 sip_pvt_unlock(dialog);
17814 return 0;
17815 }
17816
17817 if (dialog->vrtp && ast_rtp_instance_get_bridged(dialog->vrtp)) {
17818 ast_debug(2, "Bridge still active. Delaying destroy of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
17819 sip_pvt_unlock(dialog);
17820 return 0;
17821 }
17822
17823
17824
17825
17826 if (dialog->needdestroy && !dialog->packets && !dialog->owner) {
17827
17828 if (dialog->rtp && ast_rtp_instance_get_bridged(dialog->rtp)) {
17829 ast_debug(2, "Bridge still active. Delaying destruction of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
17830 sip_pvt_unlock(dialog);
17831 return 0;
17832 }
17833
17834 if (dialog->vrtp && ast_rtp_instance_get_bridged(dialog->vrtp)) {
17835 ast_debug(2, "Bridge still active. Delaying destroy of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
17836 sip_pvt_unlock(dialog);
17837 return 0;
17838 }
17839
17840 sip_pvt_unlock(dialog);
17841
17842
17843 ao2_t_link(dialogs_to_destroy, dialog, "Link dialog for destruction");
17844 return 0;
17845 }
17846
17847 sip_pvt_unlock(dialog);
17848
17849 return 0;
17850 }
17851
17852
17853
17854
17855
17856
17857
17858
17859
17860
17861
17862 static int dialog_unlink_callback(void *obj, void *arg, int flags)
17863 {
17864 struct sip_pvt *dialog = obj;
17865
17866 dialog_unlink_all(dialog);
17867
17868 return CMP_MATCH;
17869 }
17870
17871
17872
17873 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17874 {
17875 struct sip_peer *peer, *pi;
17876 int prunepeer = FALSE;
17877 int multi = FALSE;
17878 const char *name = NULL;
17879 regex_t regexbuf;
17880 int havepattern = 0;
17881 struct ao2_iterator i;
17882 static const char * const choices[] = { "all", "like", NULL };
17883 char *cmplt;
17884
17885 if (cmd == CLI_INIT) {
17886 e->command = "sip prune realtime [peer|all]";
17887 e->usage =
17888 "Usage: sip prune realtime [peer [<name>|all|like <pattern>]|all]\n"
17889 " Prunes object(s) from the cache.\n"
17890 " Optional regular expression pattern is used to filter the objects.\n";
17891 return NULL;
17892 } else if (cmd == CLI_GENERATE) {
17893 if (a->pos == 4 && !strcasecmp(a->argv[3], "peer")) {
17894 cmplt = ast_cli_complete(a->word, choices, a->n);
17895 if (!cmplt)
17896 cmplt = complete_sip_peer(a->word, a->n - sizeof(choices), SIP_PAGE2_RTCACHEFRIENDS);
17897 return cmplt;
17898 }
17899 if (a->pos == 5 && !strcasecmp(a->argv[4], "like"))
17900 return complete_sip_peer(a->word, a->n, SIP_PAGE2_RTCACHEFRIENDS);
17901 return NULL;
17902 }
17903 switch (a->argc) {
17904 case 4:
17905 name = a->argv[3];
17906
17907 if (!strcasecmp(name, "peer") || !strcasecmp(name, "like"))
17908 return CLI_SHOWUSAGE;
17909 prunepeer = TRUE;
17910 if (!strcasecmp(name, "all")) {
17911 multi = TRUE;
17912 name = NULL;
17913 }
17914
17915 break;
17916 case 5:
17917
17918 name = a->argv[4];
17919 if (!strcasecmp(a->argv[3], "peer"))
17920 prunepeer = TRUE;
17921 else if (!strcasecmp(a->argv[3], "like")) {
17922 prunepeer = TRUE;
17923 multi = TRUE;
17924 } else
17925 return CLI_SHOWUSAGE;
17926 if (!strcasecmp(name, "like"))
17927 return CLI_SHOWUSAGE;
17928 if (!multi && !strcasecmp(name, "all")) {
17929 multi = TRUE;
17930 name = NULL;
17931 }
17932 break;
17933 case 6:
17934 name = a->argv[5];
17935 multi = TRUE;
17936
17937 if (strcasecmp(a->argv[4], "like"))
17938 return CLI_SHOWUSAGE;
17939 if (!strcasecmp(a->argv[3], "peer")) {
17940 prunepeer = TRUE;
17941 } else
17942 return CLI_SHOWUSAGE;
17943 break;
17944 default:
17945 return CLI_SHOWUSAGE;
17946 }
17947
17948 if (multi && name) {
17949 if (regcomp(®exbuf, name, REG_EXTENDED | REG_NOSUB)) {
17950 return CLI_SHOWUSAGE;
17951 }
17952 havepattern = 1;
17953 }
17954
17955 if (multi) {
17956 if (prunepeer) {
17957 int pruned = 0;
17958
17959 i = ao2_iterator_init(peers, 0);
17960 while ((pi = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
17961 ao2_lock(pi);
17962 if (name && regexec(®exbuf, pi->name, 0, NULL, 0)) {
17963 ao2_unlock(pi);
17964 unref_peer(pi, "toss iterator peer ptr before continue");
17965 continue;
17966 };
17967 if (ast_test_flag(&pi->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
17968 pi->the_mark = 1;
17969 pruned++;
17970 }
17971 ao2_unlock(pi);
17972 unref_peer(pi, "toss iterator peer ptr");
17973 }
17974 ao2_iterator_destroy(&i);
17975 if (pruned) {
17976 unlink_marked_peers_from_tables();
17977 ast_cli(a->fd, "%d peers pruned.\n", pruned);
17978 } else
17979 ast_cli(a->fd, "No peers found to prune.\n");
17980 }
17981 } else {
17982 if (prunepeer) {
17983 struct sip_peer tmp;
17984 ast_copy_string(tmp.name, name, sizeof(tmp.name));
17985 if ((peer = ao2_t_find(peers, &tmp, OBJ_POINTER | OBJ_UNLINK, "finding to unlink from peers"))) {
17986 if (!ast_sockaddr_isnull(&peer->addr)) {
17987 ao2_t_unlink(peers_by_ip, peer, "unlinking peer from peers_by_ip also");
17988 }
17989 if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
17990 ast_cli(a->fd, "Peer '%s' is not a Realtime peer, cannot be pruned.\n", name);
17991
17992 ao2_t_link(peers, peer, "link peer into peer table");
17993 if (!ast_sockaddr_isnull(&peer->addr)) {
17994 ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
17995 }
17996 } else
17997 ast_cli(a->fd, "Peer '%s' pruned.\n", name);
17998 unref_peer(peer, "sip_prune_realtime: unref_peer: tossing temp peer ptr");
17999 } else
18000 ast_cli(a->fd, "Peer '%s' not found.\n", name);
18001 }
18002 }
18003
18004 if (havepattern) {
18005 regfree(®exbuf);
18006 }
18007
18008 return CLI_SUCCESS;
18009 }
18010
18011
18012 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref)
18013 {
18014 int x;
18015 format_t codec;
18016
18017 for(x = 0; x < 64 ; x++) {
18018 codec = ast_codec_pref_index(pref, x);
18019 if (!codec)
18020 break;
18021 ast_cli(fd, "%s", ast_getformatname(codec));
18022 ast_cli(fd, ":%d", pref->framing[x]);
18023 if (x < 31 && ast_codec_pref_index(pref, x + 1))
18024 ast_cli(fd, ",");
18025 }
18026 if (!x)
18027 ast_cli(fd, "none");
18028 }
18029
18030
18031 static const char *domain_mode_to_text(const enum domain_mode mode)
18032 {
18033 switch (mode) {
18034 case SIP_DOMAIN_AUTO:
18035 return "[Automatic]";
18036 case SIP_DOMAIN_CONFIG:
18037 return "[Configured]";
18038 }
18039
18040 return "";
18041 }
18042
18043
18044 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18045 {
18046 struct domain *d;
18047 #define FORMAT "%-40.40s %-20.20s %-16.16s\n"
18048
18049 switch (cmd) {
18050 case CLI_INIT:
18051 e->command = "sip show domains";
18052 e->usage =
18053 "Usage: sip show domains\n"
18054 " Lists all configured SIP local domains.\n"
18055 " Asterisk only responds to SIP messages to local domains.\n";
18056 return NULL;
18057 case CLI_GENERATE:
18058 return NULL;
18059 }
18060
18061 if (AST_LIST_EMPTY(&domain_list)) {
18062 ast_cli(a->fd, "SIP Domain support not enabled.\n\n");
18063 return CLI_SUCCESS;
18064 } else {
18065 ast_cli(a->fd, FORMAT, "Our local SIP domains:", "Context", "Set by");
18066 AST_LIST_LOCK(&domain_list);
18067 AST_LIST_TRAVERSE(&domain_list, d, list)
18068 ast_cli(a->fd, FORMAT, d->domain, S_OR(d->context, "(default)"),
18069 domain_mode_to_text(d->mode));
18070 AST_LIST_UNLOCK(&domain_list);
18071 ast_cli(a->fd, "\n");
18072 return CLI_SUCCESS;
18073 }
18074 }
18075 #undef FORMAT
18076
18077
18078 static int manager_sip_show_peer(struct mansession *s, const struct message *m)
18079 {
18080 const char *a[4];
18081 const char *peer;
18082
18083 peer = astman_get_header(m, "Peer");
18084 if (ast_strlen_zero(peer)) {
18085 astman_send_error(s, m, "Peer: <name> missing.");
18086 return 0;
18087 }
18088 a[0] = "sip";
18089 a[1] = "show";
18090 a[2] = "peer";
18091 a[3] = peer;
18092
18093 _sip_show_peer(1, -1, s, m, 4, a);
18094 astman_append(s, "\r\n" );
18095 return 0;
18096 }
18097
18098
18099 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18100 {
18101 switch (cmd) {
18102 case CLI_INIT:
18103 e->command = "sip show peer";
18104 e->usage =
18105 "Usage: sip show peer <name> [load]\n"
18106 " Shows all details on one SIP peer and the current status.\n"
18107 " Option \"load\" forces lookup of peer in realtime storage.\n";
18108 return NULL;
18109 case CLI_GENERATE:
18110 return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
18111 }
18112 return _sip_show_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
18113 }
18114
18115
18116 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
18117 {
18118 struct sip_peer *peer;
18119 int load_realtime;
18120
18121 if (argc < 4)
18122 return CLI_SHOWUSAGE;
18123
18124 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
18125 if ((peer = find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0))) {
18126 sip_poke_peer(peer, 1);
18127 unref_peer(peer, "qualify: done with peer");
18128 } else if (type == 0) {
18129 ast_cli(fd, "Peer '%s' not found\n", argv[3]);
18130 } else {
18131 astman_send_error(s, m, "Peer not found");
18132 }
18133 return CLI_SUCCESS;
18134 }
18135
18136
18137 static int manager_sip_qualify_peer(struct mansession *s, const struct message *m)
18138 {
18139 const char *a[4];
18140 const char *peer;
18141
18142 peer = astman_get_header(m, "Peer");
18143 if (ast_strlen_zero(peer)) {
18144 astman_send_error(s, m, "Peer: <name> missing.");
18145 return 0;
18146 }
18147 a[0] = "sip";
18148 a[1] = "qualify";
18149 a[2] = "peer";
18150 a[3] = peer;
18151
18152 _sip_qualify_peer(1, -1, s, m, 4, a);
18153 astman_append(s, "\r\n\r\n" );
18154 return 0;
18155 }
18156
18157
18158 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18159 {
18160 switch (cmd) {
18161 case CLI_INIT:
18162 e->command = "sip qualify peer";
18163 e->usage =
18164 "Usage: sip qualify peer <name> [load]\n"
18165 " Requests a response from one SIP peer and the current status.\n"
18166 " Option \"load\" forces lookup of peer in realtime storage.\n";
18167 return NULL;
18168 case CLI_GENERATE:
18169 return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
18170 }
18171 return _sip_qualify_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
18172 }
18173
18174
18175 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer)
18176 {
18177 struct sip_mailbox *mailbox;
18178
18179 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
18180 ast_str_append(mailbox_str, 0, "%s%s%s%s",
18181 mailbox->mailbox,
18182 ast_strlen_zero(mailbox->context) ? "" : "@",
18183 S_OR(mailbox->context, ""),
18184 AST_LIST_NEXT(mailbox, entry) ? "," : "");
18185 }
18186 }
18187
18188 static struct _map_x_s faxecmodes[] = {
18189 { SIP_PAGE2_T38SUPPORT_UDPTL, "None"},
18190 { SIP_PAGE2_T38SUPPORT_UDPTL_FEC, "FEC"},
18191 { SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY, "Redundancy"},
18192 { -1, NULL},
18193 };
18194
18195 static const char *faxec2str(int faxec)
18196 {
18197 return map_x_s(faxecmodes, faxec, "Unknown");
18198 }
18199
18200
18201 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
18202 {
18203 char status[30] = "";
18204 char cbuf[256];
18205 struct sip_peer *peer;
18206 char codec_buf[512];
18207 struct ast_codec_pref *pref;
18208 struct ast_variable *v;
18209 int x = 0, load_realtime;
18210 format_t codec = 0;
18211 int realtimepeers;
18212
18213 realtimepeers = ast_check_realtime("sippeers");
18214
18215 if (argc < 4)
18216 return CLI_SHOWUSAGE;
18217
18218 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
18219 peer = find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0);
18220
18221 if (s) {
18222 if (peer) {
18223 const char *id = astman_get_header(m, "ActionID");
18224
18225 astman_append(s, "Response: Success\r\n");
18226 if (!ast_strlen_zero(id))
18227 astman_append(s, "ActionID: %s\r\n", id);
18228 } else {
18229 snprintf (cbuf, sizeof(cbuf), "Peer %s not found.", argv[3]);
18230 astman_send_error(s, m, cbuf);
18231 return CLI_SUCCESS;
18232 }
18233 }
18234 if (peer && type==0 ) {
18235 struct ast_str *mailbox_str = ast_str_alloca(512);
18236 struct sip_auth_container *credentials;
18237
18238 ao2_lock(peer);
18239 credentials = peer->auth;
18240 if (credentials) {
18241 ao2_t_ref(credentials, +1, "Ref peer auth for show");
18242 }
18243 ao2_unlock(peer);
18244
18245 ast_cli(fd, "\n\n");
18246 ast_cli(fd, " * Name : %s\n", peer->name);
18247 if (realtimepeers) {
18248 ast_cli(fd, " Realtime peer: %s\n", peer->is_realtime ? "Yes, cached" : "No");
18249 }
18250 ast_cli(fd, " Secret : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
18251 ast_cli(fd, " MD5Secret : %s\n", ast_strlen_zero(peer->md5secret)?"<Not set>":"<Set>");
18252 ast_cli(fd, " Remote Secret: %s\n", ast_strlen_zero(peer->remotesecret)?"<Not set>":"<Set>");
18253 if (credentials) {
18254 struct sip_auth *auth;
18255
18256 AST_LIST_TRAVERSE(&credentials->list, auth, node) {
18257 ast_cli(fd, " Realm-auth : Realm %-15.15s User %-10.20s %s\n",
18258 auth->realm,
18259 auth->username,
18260 !ast_strlen_zero(auth->secret)
18261 ? "<Secret set>"
18262 : (!ast_strlen_zero(auth->md5secret)
18263 ? "<MD5secret set>" : "<Not set>"));
18264 }
18265 ao2_t_ref(credentials, -1, "Unref peer auth for show");
18266 }
18267 ast_cli(fd, " Context : %s\n", peer->context);
18268 ast_cli(fd, " Subscr.Cont. : %s\n", S_OR(peer->subscribecontext, "<Not set>") );
18269 ast_cli(fd, " Language : %s\n", peer->language);
18270 if (!ast_strlen_zero(peer->accountcode))
18271 ast_cli(fd, " Accountcode : %s\n", peer->accountcode);
18272 ast_cli(fd, " AMA flags : %s\n", ast_cdr_flags2str(peer->amaflags));
18273 ast_cli(fd, " Transfer mode: %s\n", transfermode2str(peer->allowtransfer));
18274 ast_cli(fd, " CallingPres : %s\n", ast_describe_caller_presentation(peer->callingpres));
18275 if (!ast_strlen_zero(peer->fromuser))
18276 ast_cli(fd, " FromUser : %s\n", peer->fromuser);
18277 if (!ast_strlen_zero(peer->fromdomain))
18278 ast_cli(fd, " FromDomain : %s Port %d\n", peer->fromdomain, (peer->fromdomainport) ? peer->fromdomainport : STANDARD_SIP_PORT);
18279 ast_cli(fd, " Callgroup : ");
18280 print_group(fd, peer->callgroup, 0);
18281 ast_cli(fd, " Pickupgroup : ");
18282 print_group(fd, peer->pickupgroup, 0);
18283 peer_mailboxes_to_str(&mailbox_str, peer);
18284 ast_cli(fd, " MOH Suggest : %s\n", peer->mohsuggest);
18285 ast_cli(fd, " Mailbox : %s\n", ast_str_buffer(mailbox_str));
18286 ast_cli(fd, " VM Extension : %s\n", peer->vmexten);
18287 ast_cli(fd, " LastMsgsSent : %d/%d\n", (peer->lastmsgssent & 0x7fff0000) >> 16, peer->lastmsgssent & 0xffff);
18288 ast_cli(fd, " Call limit : %d\n", peer->call_limit);
18289 ast_cli(fd, " Max forwards : %d\n", peer->maxforwards);
18290 if (peer->busy_level)
18291 ast_cli(fd, " Busy level : %d\n", peer->busy_level);
18292 ast_cli(fd, " Dynamic : %s\n", AST_CLI_YESNO(peer->host_dynamic));
18293 ast_cli(fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
18294 ast_cli(fd, " MaxCallBR : %d kbps\n", peer->maxcallbitrate);
18295 ast_cli(fd, " Expire : %ld\n", ast_sched_when(sched, peer->expire));
18296 ast_cli(fd, " Insecure : %s\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
18297 ast_cli(fd, " Force rport : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT)));
18298 ast_cli(fd, " ACL : %s\n", AST_CLI_YESNO(peer->ha != NULL));
18299 ast_cli(fd, " DirectMedACL : %s\n", AST_CLI_YESNO(peer->directmediaha != NULL));
18300 ast_cli(fd, " T.38 support : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
18301 ast_cli(fd, " T.38 EC mode : %s\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
18302 ast_cli(fd, " T.38 MaxDtgrm: %d\n", peer->t38_maxdatagram);
18303 ast_cli(fd, " DirectMedia : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)));
18304 ast_cli(fd, " PromiscRedir : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)));
18305 ast_cli(fd, " User=Phone : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)));
18306 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)));
18307 ast_cli(fd, " Text Support : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)));
18308 ast_cli(fd, " Ign SDP ver : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_IGNORESDPVERSION)));
18309 ast_cli(fd, " Trust RPID : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_TRUSTRPID)));
18310 ast_cli(fd, " Send RPID : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_SENDRPID)));
18311 ast_cli(fd, " TrustIDOutbnd: %s\n", trust_id_outbound2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND)));
18312 ast_cli(fd, " Subscriptions: %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
18313 ast_cli(fd, " Overlap dial : %s\n", allowoverlap2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWOVERLAP)));
18314 if (peer->outboundproxy)
18315 ast_cli(fd, " Outb. proxy : %s %s\n", ast_strlen_zero(peer->outboundproxy->name) ? "<not set>" : peer->outboundproxy->name,
18316 peer->outboundproxy->force ? "(forced)" : "");
18317
18318
18319 ast_cli(fd, " DTMFmode : %s\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
18320 ast_cli(fd, " Timer T1 : %d\n", peer->timer_t1);
18321 ast_cli(fd, " Timer B : %d\n", peer->timer_b);
18322 ast_cli(fd, " ToHost : %s\n", peer->tohost);
18323 ast_cli(fd, " Addr->IP : %s\n", ast_sockaddr_stringify(&peer->addr));
18324 ast_cli(fd, " Defaddr->IP : %s\n", ast_sockaddr_stringify(&peer->defaddr));
18325 ast_cli(fd, " Prim.Transp. : %s\n", get_transport(peer->socket.type));
18326 ast_cli(fd, " Allowed.Trsp : %s\n", get_transport_list(peer->transports));
18327 if (!ast_strlen_zero(sip_cfg.regcontext))
18328 ast_cli(fd, " Reg. exten : %s\n", peer->regexten);
18329 ast_cli(fd, " Def. Username: %s\n", peer->username);
18330 ast_cli(fd, " SIP Options : ");
18331 if (peer->sipoptions) {
18332 int lastoption = -1;
18333 for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
18334 if (sip_options[x].id != lastoption) {
18335 if (peer->sipoptions & sip_options[x].id)
18336 ast_cli(fd, "%s ", sip_options[x].text);
18337 lastoption = x;
18338 }
18339 }
18340 } else
18341 ast_cli(fd, "(none)");
18342
18343 ast_cli(fd, "\n");
18344 ast_cli(fd, " Codecs : ");
18345 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
18346 ast_cli(fd, "%s\n", codec_buf);
18347 ast_cli(fd, " Codec Order : (");
18348 print_codec_to_cli(fd, &peer->prefs);
18349 ast_cli(fd, ")\n");
18350
18351 ast_cli(fd, " Auto-Framing : %s\n", AST_CLI_YESNO(peer->autoframing));
18352 ast_cli(fd, " Status : ");
18353 peer_status(peer, status, sizeof(status));
18354 ast_cli(fd, "%s\n", status);
18355 ast_cli(fd, " Useragent : %s\n", peer->useragent);
18356 ast_cli(fd, " Reg. Contact : %s\n", peer->fullcontact);
18357 ast_cli(fd, " Qualify Freq : %d ms\n", peer->qualifyfreq);
18358 if (peer->chanvars) {
18359 ast_cli(fd, " Variables :\n");
18360 for (v = peer->chanvars ; v ; v = v->next)
18361 ast_cli(fd, " %s = %s\n", v->name, v->value);
18362 }
18363
18364 ast_cli(fd, " Sess-Timers : %s\n", stmode2str(peer->stimer.st_mode_oper));
18365 ast_cli(fd, " Sess-Refresh : %s\n", strefresherparam2str(peer->stimer.st_ref));
18366 ast_cli(fd, " Sess-Expires : %d secs\n", peer->stimer.st_max_se);
18367 ast_cli(fd, " Min-Sess : %d secs\n", peer->stimer.st_min_se);
18368 ast_cli(fd, " RTP Engine : %s\n", peer->engine);
18369 ast_cli(fd, " Parkinglot : %s\n", peer->parkinglot);
18370 ast_cli(fd, " Use Reason : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_Q850_REASON)));
18371 ast_cli(fd, " Encryption : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_USE_SRTP)));
18372 ast_cli(fd, "\n");
18373 peer = unref_peer(peer, "sip_show_peer: unref_peer: done with peer ptr");
18374 } else if (peer && type == 1) {
18375 char buffer[256];
18376 struct ast_str *mailbox_str = ast_str_alloca(512);
18377 astman_append(s, "Channeltype: SIP\r\n");
18378 astman_append(s, "ObjectName: %s\r\n", peer->name);
18379 astman_append(s, "ChanObjectType: peer\r\n");
18380 astman_append(s, "SecretExist: %s\r\n", ast_strlen_zero(peer->secret)?"N":"Y");
18381 astman_append(s, "RemoteSecretExist: %s\r\n", ast_strlen_zero(peer->remotesecret)?"N":"Y");
18382 astman_append(s, "MD5SecretExist: %s\r\n", ast_strlen_zero(peer->md5secret)?"N":"Y");
18383 astman_append(s, "Context: %s\r\n", peer->context);
18384 astman_append(s, "Language: %s\r\n", peer->language);
18385 if (!ast_strlen_zero(peer->accountcode))
18386 astman_append(s, "Accountcode: %s\r\n", peer->accountcode);
18387 astman_append(s, "AMAflags: %s\r\n", ast_cdr_flags2str(peer->amaflags));
18388 astman_append(s, "CID-CallingPres: %s\r\n", ast_describe_caller_presentation(peer->callingpres));
18389 if (!ast_strlen_zero(peer->fromuser))
18390 astman_append(s, "SIP-FromUser: %s\r\n", peer->fromuser);
18391 if (!ast_strlen_zero(peer->fromdomain))
18392 astman_append(s, "SIP-FromDomain: %s\r\nSip-FromDomain-Port: %d\r\n", peer->fromdomain, (peer->fromdomainport) ? peer->fromdomainport : STANDARD_SIP_PORT);
18393 astman_append(s, "Callgroup: ");
18394 astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->callgroup));
18395 astman_append(s, "Pickupgroup: ");
18396 astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->pickupgroup));
18397 astman_append(s, "MOHSuggest: %s\r\n", peer->mohsuggest);
18398 peer_mailboxes_to_str(&mailbox_str, peer);
18399 astman_append(s, "VoiceMailbox: %s\r\n", ast_str_buffer(mailbox_str));
18400 astman_append(s, "TransferMode: %s\r\n", transfermode2str(peer->allowtransfer));
18401 astman_append(s, "LastMsgsSent: %d\r\n", peer->lastmsgssent);
18402 astman_append(s, "Maxforwards: %d\r\n", peer->maxforwards);
18403 astman_append(s, "Call-limit: %d\r\n", peer->call_limit);
18404 astman_append(s, "Busy-level: %d\r\n", peer->busy_level);
18405 astman_append(s, "MaxCallBR: %d kbps\r\n", peer->maxcallbitrate);
18406 astman_append(s, "Dynamic: %s\r\n", peer->host_dynamic?"Y":"N");
18407 astman_append(s, "Callerid: %s\r\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, ""));
18408 astman_append(s, "RegExpire: %ld seconds\r\n", ast_sched_when(sched, peer->expire));
18409 astman_append(s, "SIP-AuthInsecure: %s\r\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
18410 astman_append(s, "SIP-Forcerport: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT)?"Y":"N"));
18411 astman_append(s, "ACL: %s\r\n", (peer->ha?"Y":"N"));
18412 astman_append(s, "SIP-CanReinvite: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)?"Y":"N"));
18413 astman_append(s, "SIP-DirectMedia: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)?"Y":"N"));
18414 astman_append(s, "SIP-PromiscRedir: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)?"Y":"N"));
18415 astman_append(s, "SIP-UserPhone: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)?"Y":"N"));
18416 astman_append(s, "SIP-VideoSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)?"Y":"N"));
18417 astman_append(s, "SIP-TextSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)?"Y":"N"));
18418 astman_append(s, "SIP-T.38Support: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)?"Y":"N"));
18419 astman_append(s, "SIP-T.38EC: %s\r\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
18420 astman_append(s, "SIP-T.38MaxDtgrm: %d\r\n", peer->t38_maxdatagram);
18421 astman_append(s, "SIP-Sess-Timers: %s\r\n", stmode2str(peer->stimer.st_mode_oper));
18422 astman_append(s, "SIP-Sess-Refresh: %s\r\n", strefresherparam2str(peer->stimer.st_ref));
18423 astman_append(s, "SIP-Sess-Expires: %d\r\n", peer->stimer.st_max_se);
18424 astman_append(s, "SIP-Sess-Min: %d\r\n", peer->stimer.st_min_se);
18425 astman_append(s, "SIP-RTP-Engine: %s\r\n", peer->engine);
18426 astman_append(s, "SIP-Encryption: %s\r\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_USE_SRTP) ? "Y" : "N");
18427
18428
18429 astman_append(s, "SIP-DTMFmode: %s\r\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
18430 astman_append(s, "ToHost: %s\r\n", peer->tohost);
18431 astman_append(s, "Address-IP: %s\r\nAddress-Port: %d\r\n", ast_sockaddr_stringify_addr(&peer->addr), ast_sockaddr_port(&peer->addr));
18432 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));
18433 astman_append(s, "Default-Username: %s\r\n", peer->username);
18434 if (!ast_strlen_zero(sip_cfg.regcontext))
18435 astman_append(s, "RegExtension: %s\r\n", peer->regexten);
18436 astman_append(s, "Codecs: ");
18437 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
18438 astman_append(s, "%s\r\n", codec_buf);
18439 astman_append(s, "CodecOrder: ");
18440 pref = &peer->prefs;
18441 for(x = 0; x < 64 ; x++) {
18442 codec = ast_codec_pref_index(pref, x);
18443 if (!codec)
18444 break;
18445 astman_append(s, "%s", ast_getformatname(codec));
18446 if (x < 63 && ast_codec_pref_index(pref, x+1))
18447 astman_append(s, ",");
18448 }
18449
18450 astman_append(s, "\r\n");
18451 astman_append(s, "Status: ");
18452 peer_status(peer, status, sizeof(status));
18453 astman_append(s, "%s\r\n", status);
18454 astman_append(s, "SIP-Useragent: %s\r\n", peer->useragent);
18455 astman_append(s, "Reg-Contact: %s\r\n", peer->fullcontact);
18456 astman_append(s, "QualifyFreq: %d ms\r\n", peer->qualifyfreq);
18457 astman_append(s, "Parkinglot: %s\r\n", peer->parkinglot);
18458 if (peer->chanvars) {
18459 for (v = peer->chanvars ; v ; v = v->next) {
18460 astman_append(s, "ChanVariable: %s=%s\r\n", v->name, v->value);
18461 }
18462 }
18463 astman_append(s, "SIP-Use-Reason-Header: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_Q850_REASON)) ? "Y" : "N");
18464
18465 peer = unref_peer(peer, "sip_show_peer: unref_peer: done with peer");
18466
18467 } else {
18468 ast_cli(fd, "Peer %s not found.\n", argv[3]);
18469 ast_cli(fd, "\n");
18470 }
18471
18472 return CLI_SUCCESS;
18473 }
18474
18475
18476 static char *complete_sip_user(const char *word, int state)
18477 {
18478 char *result = NULL;
18479 int wordlen = strlen(word);
18480 int which = 0;
18481 struct ao2_iterator user_iter;
18482 struct sip_peer *user;
18483
18484 user_iter = ao2_iterator_init(peers, 0);
18485 while ((user = ao2_t_iterator_next(&user_iter, "iterate thru peers table"))) {
18486 ao2_lock(user);
18487 if (!(user->type & SIP_TYPE_USER)) {
18488 ao2_unlock(user);
18489 unref_peer(user, "complete sip user");
18490 continue;
18491 }
18492
18493 if (!strncasecmp(word, user->name, wordlen) && ++which > state) {
18494 result = ast_strdup(user->name);
18495 }
18496 ao2_unlock(user);
18497 unref_peer(user, "complete sip user");
18498 if (result) {
18499 break;
18500 }
18501 }
18502 ao2_iterator_destroy(&user_iter);
18503 return result;
18504 }
18505
18506 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state)
18507 {
18508 if (pos == 3)
18509 return complete_sip_user(word, state);
18510
18511 return NULL;
18512 }
18513
18514
18515 static char *sip_show_user(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18516 {
18517 char cbuf[256];
18518 struct sip_peer *user;
18519 struct ast_variable *v;
18520 int load_realtime;
18521
18522 switch (cmd) {
18523 case CLI_INIT:
18524 e->command = "sip show user";
18525 e->usage =
18526 "Usage: sip show user <name> [load]\n"
18527 " Shows all details on one SIP user and the current status.\n"
18528 " Option \"load\" forces lookup of peer in realtime storage.\n";
18529 return NULL;
18530 case CLI_GENERATE:
18531 return complete_sip_show_user(a->line, a->word, a->pos, a->n);
18532 }
18533
18534 if (a->argc < 4)
18535 return CLI_SHOWUSAGE;
18536
18537
18538 load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? TRUE : FALSE;
18539
18540 if ((user = find_peer(a->argv[3], NULL, load_realtime, FINDUSERS, FALSE, 0))) {
18541 ao2_lock(user);
18542 ast_cli(a->fd, "\n\n");
18543 ast_cli(a->fd, " * Name : %s\n", user->name);
18544 ast_cli(a->fd, " Secret : %s\n", ast_strlen_zero(user->secret)?"<Not set>":"<Set>");
18545 ast_cli(a->fd, " MD5Secret : %s\n", ast_strlen_zero(user->md5secret)?"<Not set>":"<Set>");
18546 ast_cli(a->fd, " Context : %s\n", user->context);
18547 ast_cli(a->fd, " Language : %s\n", user->language);
18548 if (!ast_strlen_zero(user->accountcode))
18549 ast_cli(a->fd, " Accountcode : %s\n", user->accountcode);
18550 ast_cli(a->fd, " AMA flags : %s\n", ast_cdr_flags2str(user->amaflags));
18551 ast_cli(a->fd, " Transfer mode: %s\n", transfermode2str(user->allowtransfer));
18552 ast_cli(a->fd, " MaxCallBR : %d kbps\n", user->maxcallbitrate);
18553 ast_cli(a->fd, " CallingPres : %s\n", ast_describe_caller_presentation(user->callingpres));
18554 ast_cli(a->fd, " Call limit : %d\n", user->call_limit);
18555 ast_cli(a->fd, " Callgroup : ");
18556 print_group(a->fd, user->callgroup, 0);
18557 ast_cli(a->fd, " Pickupgroup : ");
18558 print_group(a->fd, user->pickupgroup, 0);
18559 ast_cli(a->fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), user->cid_name, user->cid_num, "<unspecified>"));
18560 ast_cli(a->fd, " ACL : %s\n", AST_CLI_YESNO(user->ha != NULL));
18561 ast_cli(a->fd, " Sess-Timers : %s\n", stmode2str(user->stimer.st_mode_oper));
18562 ast_cli(a->fd, " Sess-Refresh : %s\n", strefresherparam2str(user->stimer.st_ref));
18563 ast_cli(a->fd, " Sess-Expires : %d secs\n", user->stimer.st_max_se);
18564 ast_cli(a->fd, " Sess-Min-SE : %d secs\n", user->stimer.st_min_se);
18565 ast_cli(a->fd, " RTP Engine : %s\n", user->engine);
18566
18567 ast_cli(a->fd, " Codec Order : (");
18568 print_codec_to_cli(a->fd, &user->prefs);
18569 ast_cli(a->fd, ")\n");
18570
18571 ast_cli(a->fd, " Auto-Framing: %s \n", AST_CLI_YESNO(user->autoframing));
18572 if (user->chanvars) {
18573 ast_cli(a->fd, " Variables :\n");
18574 for (v = user->chanvars ; v ; v = v->next)
18575 ast_cli(a->fd, " %s = %s\n", v->name, v->value);
18576 }
18577
18578 ast_cli(a->fd, "\n");
18579
18580 ao2_unlock(user);
18581 unref_peer(user, "sip show user");
18582 } else {
18583 ast_cli(a->fd, "User %s not found.\n", a->argv[3]);
18584 ast_cli(a->fd, "\n");
18585 }
18586
18587 return CLI_SUCCESS;
18588 }
18589
18590
18591 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18592 {
18593 struct ast_str *cbuf;
18594 struct ast_cb_names cbnames = {9, { "retrans_pkt",
18595 "__sip_autodestruct",
18596 "expire_register",
18597 "auto_congest",
18598 "sip_reg_timeout",
18599 "sip_poke_peer_s",
18600 "sip_poke_noanswer",
18601 "sip_reregister",
18602 "sip_reinvite_retry"},
18603 { retrans_pkt,
18604 __sip_autodestruct,
18605 expire_register,
18606 auto_congest,
18607 sip_reg_timeout,
18608 sip_poke_peer_s,
18609 sip_poke_noanswer,
18610 sip_reregister,
18611 sip_reinvite_retry}};
18612
18613 switch (cmd) {
18614 case CLI_INIT:
18615 e->command = "sip show sched";
18616 e->usage =
18617 "Usage: sip show sched\n"
18618 " Shows stats on what's in the sched queue at the moment\n";
18619 return NULL;
18620 case CLI_GENERATE:
18621 return NULL;
18622 }
18623
18624 cbuf = ast_str_alloca(2048);
18625
18626 ast_cli(a->fd, "\n");
18627 ast_sched_report(sched, &cbuf, &cbnames);
18628 ast_cli(a->fd, "%s", ast_str_buffer(cbuf));
18629
18630 return CLI_SUCCESS;
18631 }
18632
18633
18634 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18635 {
18636 #define FORMAT2 "%-39.39s %-6.6s %-12.12s %8.8s %-20.20s %-25.25s\n"
18637 #define FORMAT "%-39.39s %-6.6s %-12.12s %8d %-20.20s %-25.25s\n"
18638 char host[80];
18639 char user[80];
18640 char tmpdat[256];
18641 struct ast_tm tm;
18642 int counter = 0;
18643
18644 switch (cmd) {
18645 case CLI_INIT:
18646 e->command = "sip show registry";
18647 e->usage =
18648 "Usage: sip show registry\n"
18649 " Lists all registration requests and status.\n";
18650 return NULL;
18651 case CLI_GENERATE:
18652 return NULL;
18653 }
18654
18655 if (a->argc != 3)
18656 return CLI_SHOWUSAGE;
18657 ast_cli(a->fd, FORMAT2, "Host", "dnsmgr", "Username", "Refresh", "State", "Reg.Time");
18658
18659 ASTOBJ_CONTAINER_TRAVERSE(®l, 1, do {
18660 ASTOBJ_RDLOCK(iterator);
18661 snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
18662 snprintf(user, sizeof(user), "%s", iterator->username);
18663 if (!ast_strlen_zero(iterator->regdomain)) {
18664 snprintf(tmpdat, sizeof(tmpdat), "%s", user);
18665 snprintf(user, sizeof(user), "%s@%s", tmpdat, iterator->regdomain);}
18666 if (iterator->regdomainport) {
18667 snprintf(tmpdat, sizeof(tmpdat), "%s", user);
18668 snprintf(user, sizeof(user), "%s:%d", tmpdat, iterator->regdomainport);}
18669 if (iterator->regtime.tv_sec) {
18670 ast_localtime(&iterator->regtime, &tm, NULL);
18671 ast_strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T", &tm);
18672 } else
18673 tmpdat[0] = '\0';
18674 ast_cli(a->fd, FORMAT, host, (iterator->dnsmgr) ? "Y" : "N", user, iterator->refresh, regstate2str(iterator->regstate), tmpdat);
18675 ASTOBJ_UNLOCK(iterator);
18676 counter++;
18677 } while(0));
18678 ast_cli(a->fd, "%d SIP registrations.\n", counter);
18679 return CLI_SUCCESS;
18680 #undef FORMAT
18681 #undef FORMAT2
18682 }
18683
18684
18685
18686
18687
18688 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18689 {
18690 struct sip_peer *peer;
18691 int load_realtime = 0;
18692
18693 switch (cmd) {
18694 case CLI_INIT:
18695 e->command = "sip unregister";
18696 e->usage =
18697 "Usage: sip unregister <peer>\n"
18698 " Unregister (force expiration) a SIP peer from the registry\n";
18699 return NULL;
18700 case CLI_GENERATE:
18701 return complete_sip_unregister(a->line, a->word, a->pos, a->n);
18702 }
18703
18704 if (a->argc != 3)
18705 return CLI_SHOWUSAGE;
18706
18707 if ((peer = find_peer(a->argv[2], NULL, load_realtime, FINDPEERS, TRUE, 0))) {
18708 if (peer->expire > 0) {
18709 AST_SCHED_DEL_UNREF(sched, peer->expire,
18710 unref_peer(peer, "remove register expire ref"));
18711 expire_register(ref_peer(peer, "ref for expire_register"));
18712 ast_cli(a->fd, "Unregistered peer \'%s\'\n\n", a->argv[2]);
18713 } else {
18714 ast_cli(a->fd, "Peer %s not registered\n", a->argv[2]);
18715 }
18716 unref_peer(peer, "sip_unregister: unref_peer via sip_unregister: done with peer from find_peer call");
18717 } else {
18718 ast_cli(a->fd, "Peer unknown: \'%s\'. Not unregistered.\n", a->argv[2]);
18719 }
18720
18721 return CLI_SUCCESS;
18722 }
18723
18724
18725 static int show_chanstats_cb(void *__cur, void *__arg, int flags)
18726 {
18727 #define FORMAT2 "%-15.15s %-11.11s %-8.8s %-10.10s %-10.10s ( %%) %-6.6s %-10.10s %-10.10s ( %%) %-6.6s\n"
18728 #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"
18729 struct sip_pvt *cur = __cur;
18730 struct ast_rtp_instance_stats stats;
18731 char durbuf[10];
18732 int duration;
18733 int durh, durm, durs;
18734 struct ast_channel *c;
18735 struct __show_chan_arg *arg = __arg;
18736 int fd = arg->fd;
18737
18738 sip_pvt_lock(cur);
18739 c = cur->owner;
18740
18741 if (cur->subscribed != NONE) {
18742
18743 sip_pvt_unlock(cur);
18744 return 0;
18745 }
18746
18747 if (!cur->rtp) {
18748 if (sipdebug) {
18749 ast_cli(fd, "%-15.15s %-11.11s (inv state: %s) -- %s\n",
18750 ast_sockaddr_stringify_addr(&cur->sa), cur->callid,
18751 invitestate2string[cur->invitestate].desc,
18752 "-- No RTP active");
18753 }
18754 sip_pvt_unlock(cur);
18755 return 0;
18756 }
18757
18758 if (ast_rtp_instance_get_stats(cur->rtp, &stats, AST_RTP_INSTANCE_STAT_ALL)) {
18759 sip_pvt_unlock(cur);
18760 ast_log(LOG_WARNING, "Could not get RTP stats.\n");
18761 return 0;
18762 }
18763
18764 if (c && c->cdr && !ast_tvzero(c->cdr->start)) {
18765 duration = (int)(ast_tvdiff_ms(ast_tvnow(), c->cdr->start) / 1000);
18766 durh = duration / 3600;
18767 durm = (duration % 3600) / 60;
18768 durs = duration % 60;
18769 snprintf(durbuf, sizeof(durbuf), "%02d:%02d:%02d", durh, durm, durs);
18770 } else {
18771 durbuf[0] = '\0';
18772 }
18773
18774 ast_cli(fd, FORMAT,
18775 ast_sockaddr_stringify_addr(&cur->sa),
18776 cur->callid,
18777 durbuf,
18778 stats.rxcount > (unsigned int) 100000 ? (unsigned int) (stats.rxcount)/(unsigned int) 1000 : stats.rxcount,
18779 stats.rxcount > (unsigned int) 100000 ? "K":" ",
18780 stats.rxploss,
18781 (stats.rxcount + stats.rxploss) > 0 ? (double) stats.rxploss / (stats.rxcount + stats.rxploss) * 100 : 0,
18782 stats.rxjitter,
18783 stats.txcount > (unsigned int) 100000 ? (unsigned int) (stats.txcount)/(unsigned int) 1000 : stats.txcount,
18784 stats.txcount > (unsigned int) 100000 ? "K":" ",
18785 stats.txploss,
18786 stats.txcount > 0 ? (double) stats.txploss / stats.txcount * 100 : 0,
18787 stats.txjitter
18788 );
18789 arg->numchans++;
18790 sip_pvt_unlock(cur);
18791
18792 return 0;
18793 }
18794
18795
18796 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18797 {
18798 struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
18799
18800 switch (cmd) {
18801 case CLI_INIT:
18802 e->command = "sip show channelstats";
18803 e->usage =
18804 "Usage: sip show channelstats\n"
18805 " Lists all currently active SIP channel's RTCP statistics.\n"
18806 " Note that calls in the much optimized RTP P2P bridge mode will not show any packets here.";
18807 return NULL;
18808 case CLI_GENERATE:
18809 return NULL;
18810 }
18811
18812 if (a->argc != 3)
18813 return CLI_SHOWUSAGE;
18814
18815 ast_cli(a->fd, FORMAT2, "Peer", "Call ID", "Duration", "Recv: Pack", "Lost", "Jitter", "Send: Pack", "Lost", "Jitter");
18816
18817 ao2_t_callback(dialogs, OBJ_NODATA, show_chanstats_cb, &arg, "callback to sip show chanstats");
18818 ast_cli(a->fd, "%d active SIP channel%s\n", arg.numchans, (arg.numchans != 1) ? "s" : "");
18819 return CLI_SUCCESS;
18820 }
18821 #undef FORMAT
18822 #undef FORMAT2
18823
18824
18825 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18826 {
18827 int realtimepeers;
18828 int realtimeregs;
18829 char codec_buf[SIPBUFSIZE];
18830 const char *msg;
18831 struct sip_auth_container *credentials;
18832
18833 switch (cmd) {
18834 case CLI_INIT:
18835 e->command = "sip show settings";
18836 e->usage =
18837 "Usage: sip show settings\n"
18838 " Provides detailed list of the configuration of the SIP channel.\n";
18839 return NULL;
18840 case CLI_GENERATE:
18841 return NULL;
18842 }
18843
18844 if (a->argc != 3)
18845 return CLI_SHOWUSAGE;
18846
18847 realtimepeers = ast_check_realtime("sippeers");
18848 realtimeregs = ast_check_realtime("sipregs");
18849
18850 ast_mutex_lock(&authl_lock);
18851 credentials = authl;
18852 if (credentials) {
18853 ao2_t_ref(credentials, +1, "Ref global auth for show");
18854 }
18855 ast_mutex_unlock(&authl_lock);
18856
18857 ast_cli(a->fd, "\n\nGlobal Settings:\n");
18858 ast_cli(a->fd, "----------------\n");
18859 ast_cli(a->fd, " UDP Bindaddress: %s\n", ast_sockaddr_stringify(&bindaddr));
18860 if (ast_sockaddr_is_ipv6(&bindaddr) && ast_sockaddr_is_any(&bindaddr)) {
18861 ast_cli(a->fd, " ** Additional Info:\n");
18862 ast_cli(a->fd, " [::] may include IPv4 in addition to IPv6, if such a feature is enabled in the OS.\n");
18863 }
18864 ast_cli(a->fd, " TCP SIP Bindaddress: %s\n",
18865 sip_cfg.tcp_enabled != FALSE ?
18866 ast_sockaddr_stringify(&sip_tcp_desc.local_address) :
18867 "Disabled");
18868 ast_cli(a->fd, " TLS SIP Bindaddress: %s\n",
18869 default_tls_cfg.enabled != FALSE ?
18870 ast_sockaddr_stringify(&sip_tls_desc.local_address) :
18871 "Disabled");
18872 ast_cli(a->fd, " Videosupport: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT)));
18873 ast_cli(a->fd, " Textsupport: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT)));
18874 ast_cli(a->fd, " Ignore SDP sess. ver.: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION)));
18875 ast_cli(a->fd, " AutoCreate Peer: %s\n", AST_CLI_YESNO(sip_cfg.autocreatepeer));
18876 ast_cli(a->fd, " Match Auth Username: %s\n", AST_CLI_YESNO(global_match_auth_username));
18877 ast_cli(a->fd, " Allow unknown access: %s\n", AST_CLI_YESNO(sip_cfg.allowguest));
18878 ast_cli(a->fd, " Allow subscriptions: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
18879 ast_cli(a->fd, " Allow overlap dialing: %s\n", allowoverlap2str(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP)));
18880 ast_cli(a->fd, " Allow promisc. redir: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_PROMISCREDIR)));
18881 ast_cli(a->fd, " Enable call counters: %s\n", AST_CLI_YESNO(global_callcounter));
18882 ast_cli(a->fd, " SIP domain support: %s\n", AST_CLI_YESNO(!AST_LIST_EMPTY(&domain_list)));
18883 ast_cli(a->fd, " Realm. auth: %s\n", AST_CLI_YESNO(credentials != NULL));
18884 if (credentials) {
18885 struct sip_auth *auth;
18886
18887 AST_LIST_TRAVERSE(&credentials->list, auth, node) {
18888 ast_cli(a->fd, " Realm. auth entry: Realm %-15.15s User %-10.20s %s\n",
18889 auth->realm,
18890 auth->username,
18891 !ast_strlen_zero(auth->secret)
18892 ? "<Secret set>"
18893 : (!ast_strlen_zero(auth->md5secret)
18894 ? "<MD5secret set>" : "<Not set>"));
18895 }
18896 ao2_t_ref(credentials, -1, "Unref global auth for show");
18897 }
18898 ast_cli(a->fd, " Our auth realm %s\n", sip_cfg.realm);
18899 ast_cli(a->fd, " Use domains as realms: %s\n", AST_CLI_YESNO(sip_cfg.domainsasrealm));
18900 ast_cli(a->fd, " Call to non-local dom.: %s\n", AST_CLI_YESNO(sip_cfg.allow_external_domains));
18901 ast_cli(a->fd, " URI user is phone no: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_USEREQPHONE)));
18902 ast_cli(a->fd, " Always auth rejects: %s\n", AST_CLI_YESNO(sip_cfg.alwaysauthreject));
18903 ast_cli(a->fd, " Direct RTP setup: %s\n", AST_CLI_YESNO(sip_cfg.directrtpsetup));
18904 ast_cli(a->fd, " User Agent: %s\n", global_useragent);
18905 ast_cli(a->fd, " SDP Session Name: %s\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
18906 ast_cli(a->fd, " SDP Owner Name: %s\n", ast_strlen_zero(global_sdpowner) ? "-" : global_sdpowner);
18907 ast_cli(a->fd, " Reg. context: %s\n", S_OR(sip_cfg.regcontext, "(not set)"));
18908 ast_cli(a->fd, " Regexten on Qualify: %s\n", AST_CLI_YESNO(sip_cfg.regextenonqualify));
18909 ast_cli(a->fd, " Legacy userfield parse: %s\n", AST_CLI_YESNO(sip_cfg.legacy_useroption_parsing));
18910 ast_cli(a->fd, " Caller ID: %s\n", default_callerid);
18911 if ((default_fromdomainport) && (default_fromdomainport != STANDARD_SIP_PORT)) {
18912 ast_cli(a->fd, " From: Domain: %s:%d\n", default_fromdomain, default_fromdomainport);
18913 } else {
18914 ast_cli(a->fd, " From: Domain: %s\n", default_fromdomain);
18915 }
18916 ast_cli(a->fd, " Record SIP history: %s\n", AST_CLI_ONOFF(recordhistory));
18917 ast_cli(a->fd, " Call Events: %s\n", AST_CLI_ONOFF(sip_cfg.callevents));
18918 ast_cli(a->fd, " Auth. Failure Events: %s\n", AST_CLI_ONOFF(global_authfailureevents));
18919
18920 ast_cli(a->fd, " T.38 support: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
18921 ast_cli(a->fd, " T.38 EC mode: %s\n", faxec2str(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
18922 ast_cli(a->fd, " T.38 MaxDtgrm: %d\n", global_t38_maxdatagram);
18923 if (!realtimepeers && !realtimeregs)
18924 ast_cli(a->fd, " SIP realtime: Disabled\n" );
18925 else
18926 ast_cli(a->fd, " SIP realtime: Enabled\n" );
18927 ast_cli(a->fd, " Qualify Freq : %d ms\n", global_qualifyfreq);
18928 ast_cli(a->fd, " Q.850 Reason header: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_Q850_REASON)));
18929 ast_cli(a->fd, " Store SIP_CAUSE: %s\n", AST_CLI_YESNO(global_store_sip_cause));
18930 ast_cli(a->fd, "\nNetwork QoS Settings:\n");
18931 ast_cli(a->fd, "---------------------------\n");
18932 ast_cli(a->fd, " IP ToS SIP: %s\n", ast_tos2str(global_tos_sip));
18933 ast_cli(a->fd, " IP ToS RTP audio: %s\n", ast_tos2str(global_tos_audio));
18934 ast_cli(a->fd, " IP ToS RTP video: %s\n", ast_tos2str(global_tos_video));
18935 ast_cli(a->fd, " IP ToS RTP text: %s\n", ast_tos2str(global_tos_text));
18936 ast_cli(a->fd, " 802.1p CoS SIP: %d\n", global_cos_sip);
18937 ast_cli(a->fd, " 802.1p CoS RTP audio: %d\n", global_cos_audio);
18938 ast_cli(a->fd, " 802.1p CoS RTP video: %d\n", global_cos_video);
18939 ast_cli(a->fd, " 802.1p CoS RTP text: %d\n", global_cos_text);
18940 ast_cli(a->fd, " Jitterbuffer enabled: %s\n", AST_CLI_YESNO(ast_test_flag(&global_jbconf, AST_JB_ENABLED)));
18941 if (ast_test_flag(&global_jbconf, AST_JB_ENABLED)) {
18942 ast_cli(a->fd, " Jitterbuffer forced: %s\n", AST_CLI_YESNO(ast_test_flag(&global_jbconf, AST_JB_FORCED)));
18943 ast_cli(a->fd, " Jitterbuffer max size: %ld\n", global_jbconf.max_size);
18944 ast_cli(a->fd, " Jitterbuffer resync: %ld\n", global_jbconf.resync_threshold);
18945 ast_cli(a->fd, " Jitterbuffer impl: %s\n", global_jbconf.impl);
18946 if (!strcasecmp(global_jbconf.impl, "adaptive")) {
18947 ast_cli(a->fd, " Jitterbuffer tgt extra: %ld\n", global_jbconf.target_extra);
18948 }
18949 ast_cli(a->fd, " Jitterbuffer log: %s\n", AST_CLI_YESNO(ast_test_flag(&global_jbconf, AST_JB_LOG)));
18950 }
18951
18952 ast_cli(a->fd, "\nNetwork Settings:\n");
18953 ast_cli(a->fd, "---------------------------\n");
18954
18955 if (localaddr == NULL)
18956 msg = "Disabled, no localnet list";
18957 else if (ast_sockaddr_isnull(&externaddr))
18958 msg = "Disabled";
18959 else if (!ast_strlen_zero(externhost))
18960 msg = "Enabled using externhost";
18961 else
18962 msg = "Enabled using externaddr";
18963 ast_cli(a->fd, " SIP address remapping: %s\n", msg);
18964 ast_cli(a->fd, " Externhost: %s\n", S_OR(externhost, "<none>"));
18965 ast_cli(a->fd, " Externaddr: %s\n", ast_sockaddr_stringify(&externaddr));
18966 ast_cli(a->fd, " Externrefresh: %d\n", externrefresh);
18967 {
18968 struct ast_ha *d;
18969 const char *prefix = "Localnet:";
18970
18971 for (d = localaddr; d ; prefix = "", d = d->next) {
18972 const char *addr = ast_strdupa(ast_sockaddr_stringify_addr(&d->addr));
18973 const char *mask = ast_strdupa(ast_sockaddr_stringify_addr(&d->netmask));
18974 ast_cli(a->fd, " %-24s%s/%s\n", prefix, addr, mask);
18975 }
18976 }
18977 ast_cli(a->fd, "\nGlobal Signalling Settings:\n");
18978 ast_cli(a->fd, "---------------------------\n");
18979 ast_cli(a->fd, " Codecs: ");
18980 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, sip_cfg.capability);
18981 ast_cli(a->fd, "%s\n", codec_buf);
18982 ast_cli(a->fd, " Codec Order: ");
18983 print_codec_to_cli(a->fd, &default_prefs);
18984 ast_cli(a->fd, "\n");
18985 ast_cli(a->fd, " Relax DTMF: %s\n", AST_CLI_YESNO(global_relaxdtmf));
18986 ast_cli(a->fd, " RFC2833 Compensation: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_RFC2833_COMPENSATE)));
18987 ast_cli(a->fd, " Symmetric RTP: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_SYMMETRICRTP)));
18988 ast_cli(a->fd, " Compact SIP headers: %s\n", AST_CLI_YESNO(sip_cfg.compactheaders));
18989 ast_cli(a->fd, " RTP Keepalive: %d %s\n", global_rtpkeepalive, global_rtpkeepalive ? "" : "(Disabled)" );
18990 ast_cli(a->fd, " RTP Timeout: %d %s\n", global_rtptimeout, global_rtptimeout ? "" : "(Disabled)" );
18991 ast_cli(a->fd, " RTP Hold Timeout: %d %s\n", global_rtpholdtimeout, global_rtpholdtimeout ? "" : "(Disabled)");
18992 ast_cli(a->fd, " MWI NOTIFY mime type: %s\n", default_notifymime);
18993 ast_cli(a->fd, " DNS SRV lookup: %s\n", AST_CLI_YESNO(sip_cfg.srvlookup));
18994 ast_cli(a->fd, " Pedantic SIP support: %s\n", AST_CLI_YESNO(sip_cfg.pedanticsipchecking));
18995 ast_cli(a->fd, " Reg. min duration %d secs\n", min_expiry);
18996 ast_cli(a->fd, " Reg. max duration: %d secs\n", max_expiry);
18997 ast_cli(a->fd, " Reg. default duration: %d secs\n", default_expiry);
18998 ast_cli(a->fd, " Outbound reg. timeout: %d secs\n", global_reg_timeout);
18999 ast_cli(a->fd, " Outbound reg. attempts: %d\n", global_regattempts_max);
19000 ast_cli(a->fd, " Outbound reg. retry 403:%d\n", global_reg_retry_403);
19001 ast_cli(a->fd, " Notify ringing state: %s\n", AST_CLI_YESNO(sip_cfg.notifyringing));
19002 if (sip_cfg.notifyringing) {
19003 ast_cli(a->fd, " Include CID: %s%s\n",
19004 AST_CLI_YESNO(sip_cfg.notifycid),
19005 sip_cfg.notifycid == IGNORE_CONTEXT ? " (Ignoring context)" : "");
19006 }
19007 ast_cli(a->fd, " Notify hold state: %s\n", AST_CLI_YESNO(sip_cfg.notifyhold));
19008 ast_cli(a->fd, " SIP Transfer mode: %s\n", transfermode2str(sip_cfg.allowtransfer));
19009 ast_cli(a->fd, " Max Call Bitrate: %d kbps\n", default_maxcallbitrate);
19010 ast_cli(a->fd, " Auto-Framing: %s\n", AST_CLI_YESNO(global_autoframing));
19011 ast_cli(a->fd, " Outb. proxy: %s %s\n", ast_strlen_zero(sip_cfg.outboundproxy.name) ? "<not set>" : sip_cfg.outboundproxy.name,
19012 sip_cfg.outboundproxy.force ? "(forced)" : "");
19013 ast_cli(a->fd, " Session Timers: %s\n", stmode2str(global_st_mode));
19014 ast_cli(a->fd, " Session Refresher: %s\n", strefresherparam2str(global_st_refresher));
19015 ast_cli(a->fd, " Session Expires: %d secs\n", global_max_se);
19016 ast_cli(a->fd, " Session Min-SE: %d secs\n", global_min_se);
19017 ast_cli(a->fd, " Timer T1: %d\n", global_t1);
19018 ast_cli(a->fd, " Timer T1 minimum: %d\n", global_t1min);
19019 ast_cli(a->fd, " Timer B: %d\n", global_timer_b);
19020 ast_cli(a->fd, " No premature media: %s\n", AST_CLI_YESNO(global_prematuremediafilter));
19021 ast_cli(a->fd, " Max forwards: %d\n", sip_cfg.default_max_forwards);
19022
19023 ast_cli(a->fd, "\nDefault Settings:\n");
19024 ast_cli(a->fd, "-----------------\n");
19025 ast_cli(a->fd, " Allowed transports: %s\n", get_transport_list(default_transports));
19026 ast_cli(a->fd, " Outbound transport: %s\n", get_transport(default_primary_transport));
19027 ast_cli(a->fd, " Context: %s\n", sip_cfg.default_context);
19028 ast_cli(a->fd, " Force rport: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_NAT_FORCE_RPORT)));
19029 ast_cli(a->fd, " DTMF: %s\n", dtmfmode2str(ast_test_flag(&global_flags[0], SIP_DTMF)));
19030 ast_cli(a->fd, " Qualify: %d\n", default_qualify);
19031 ast_cli(a->fd, " Use ClientCode: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_USECLIENTCODE)));
19032 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)));
19033 ast_cli(a->fd, " Language: %s\n", default_language);
19034 ast_cli(a->fd, " MOH Interpret: %s\n", default_mohinterpret);
19035 ast_cli(a->fd, " MOH Suggest: %s\n", default_mohsuggest);
19036 ast_cli(a->fd, " Voice Mail Extension: %s\n", default_vmexten);
19037
19038
19039 if (realtimepeers || realtimeregs) {
19040 ast_cli(a->fd, "\nRealtime SIP Settings:\n");
19041 ast_cli(a->fd, "----------------------\n");
19042 ast_cli(a->fd, " Realtime Peers: %s\n", AST_CLI_YESNO(realtimepeers));
19043 ast_cli(a->fd, " Realtime Regs: %s\n", AST_CLI_YESNO(realtimeregs));
19044 ast_cli(a->fd, " Cache Friends: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)));
19045 ast_cli(a->fd, " Update: %s\n", AST_CLI_YESNO(sip_cfg.peer_rtupdate));
19046 ast_cli(a->fd, " Ignore Reg. Expire: %s\n", AST_CLI_YESNO(sip_cfg.ignore_regexpire));
19047 ast_cli(a->fd, " Save sys. name: %s\n", AST_CLI_YESNO(sip_cfg.rtsave_sysname));
19048 ast_cli(a->fd, " Auto Clear: %d (%s)\n", sip_cfg.rtautoclear, ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR) ? "Enabled" : "Disabled");
19049 }
19050 ast_cli(a->fd, "\n----\n");
19051 return CLI_SUCCESS;
19052 }
19053
19054 static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
19055 {
19056 #define FORMAT "%-30.30s %-12.12s %-10.10s %-10.10s\n"
19057 char host[80];
19058
19059 switch (cmd) {
19060 case CLI_INIT:
19061 e->command = "sip show mwi";
19062 e->usage =
19063 "Usage: sip show mwi\n"
19064 " Provides a list of MWI subscriptions and status.\n";
19065 return NULL;
19066 case CLI_GENERATE:
19067 return NULL;
19068 }
19069
19070 ast_cli(a->fd, FORMAT, "Host", "Username", "Mailbox", "Subscribed");
19071
19072 ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
19073 ASTOBJ_RDLOCK(iterator);
19074 snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
19075 ast_cli(a->fd, FORMAT, host, iterator->username, iterator->mailbox, AST_CLI_YESNO(iterator->subscribed));
19076 ASTOBJ_UNLOCK(iterator);
19077 } while(0));
19078
19079 return CLI_SUCCESS;
19080 #undef FORMAT
19081 }
19082
19083
19084
19085 static const char *subscription_type2str(enum subscriptiontype subtype)
19086 {
19087 int i;
19088
19089 for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
19090 if (subscription_types[i].type == subtype) {
19091 return subscription_types[i].text;
19092 }
19093 }
19094 return subscription_types[0].text;
19095 }
19096
19097
19098 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype)
19099 {
19100 int i;
19101
19102 for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
19103 if (subscription_types[i].type == subtype) {
19104 return &subscription_types[i];
19105 }
19106 }
19107 return &subscription_types[0];
19108 }
19109
19110
19111
19112
19113
19114
19115
19116
19117 #define FORMAT4 "%-15.15s %-15.15s %-15.15s %-15.15s %-13.13s %-15.15s %-10.10s %-6.6d\n"
19118 #define FORMAT3 "%-15.15s %-15.15s %-15.15s %-15.15s %-13.13s %-15.15s %-10.10s %-6.6s\n"
19119 #define FORMAT2 "%-15.15s %-15.15s %-15.15s %-15.15s %-7.7s %-15.15s %-10.10s %-10.10s\n"
19120 #define FORMAT "%-15.15s %-15.15s %-15.15s %-15.15s %-3.3s %-3.3s %-15.15s %-10.10s %-10.10s\n"
19121
19122
19123 static int show_channels_cb(void *__cur, void *__arg, int flags)
19124 {
19125 struct sip_pvt *cur = __cur;
19126 struct __show_chan_arg *arg = __arg;
19127 const struct ast_sockaddr *dst;
19128
19129 sip_pvt_lock(cur);
19130 dst = sip_real_dst(cur);
19131
19132
19133 if (cur->subscribed == NONE && !arg->subscriptions) {
19134
19135 const char *referstatus = cur->refer ? referstatus2str(cur->refer->status) : "";
19136 char formatbuf[SIPBUFSIZE/2];
19137
19138 ast_cli(arg->fd, FORMAT, ast_sockaddr_stringify_addr(dst),
19139 S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
19140 cur->callid,
19141 ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0),
19142 AST_CLI_YESNO(ast_test_flag(&cur->flags[1], SIP_PAGE2_CALL_ONHOLD)),
19143 cur->needdestroy ? "(d)" : "",
19144 cur->lastmsg ,
19145 referstatus,
19146 cur->relatedpeer ? cur->relatedpeer->name : "<guest>"
19147 );
19148 arg->numchans++;
19149 }
19150 if (cur->subscribed != NONE && arg->subscriptions) {
19151 struct ast_str *mailbox_str = ast_str_alloca(512);
19152 if (cur->subscribed == MWI_NOTIFICATION && cur->relatedpeer)
19153 peer_mailboxes_to_str(&mailbox_str, cur->relatedpeer);
19154 ast_cli(arg->fd, FORMAT4, ast_sockaddr_stringify_addr(dst),
19155 S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
19156 cur->callid,
19157
19158 cur->subscribed == MWI_NOTIFICATION ? "--" : cur->subscribeuri,
19159 cur->subscribed == MWI_NOTIFICATION ? "<none>" : ast_extension_state2str(cur->laststate),
19160 subscription_type2str(cur->subscribed),
19161 cur->subscribed == MWI_NOTIFICATION ? S_OR(ast_str_buffer(mailbox_str), "<none>") : "<none>",
19162 cur->expiry
19163 );
19164 arg->numchans++;
19165 }
19166 sip_pvt_unlock(cur);
19167 return 0;
19168 }
19169
19170
19171
19172
19173
19174
19175 static char *sip_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
19176 {
19177 struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
19178
19179
19180 if (cmd == CLI_INIT) {
19181 e->command = "sip show {channels|subscriptions}";
19182 e->usage =
19183 "Usage: sip show channels\n"
19184 " Lists all currently active SIP calls (dialogs).\n"
19185 "Usage: sip show subscriptions\n"
19186 " Lists active SIP subscriptions.\n";
19187 return NULL;
19188 } else if (cmd == CLI_GENERATE)
19189 return NULL;
19190
19191 if (a->argc != e->args)
19192 return CLI_SHOWUSAGE;
19193 arg.subscriptions = !strcasecmp(a->argv[e->args - 1], "subscriptions");
19194 if (!arg.subscriptions)
19195 ast_cli(arg.fd, FORMAT2, "Peer", "User/ANR", "Call ID", "Format", "Hold", "Last Message", "Expiry", "Peer");
19196 else
19197 ast_cli(arg.fd, FORMAT3, "Peer", "User", "Call ID", "Extension", "Last state", "Type", "Mailbox", "Expiry");
19198
19199
19200 ao2_t_callback(dialogs, OBJ_NODATA, show_channels_cb, &arg, "callback to show channels");
19201
19202
19203 ast_cli(arg.fd, "%d active SIP %s%s\n", arg.numchans,
19204 (arg.subscriptions ? "subscription" : "dialog"),
19205 ESS(arg.numchans));
19206 return CLI_SUCCESS;
19207 #undef FORMAT
19208 #undef FORMAT2
19209 #undef FORMAT3
19210 }
19211
19212
19213
19214
19215
19216
19217 static char *complete_sipch(const char *line, const char *word, int pos, int state)
19218 {
19219 int which=0;
19220 struct sip_pvt *cur;
19221 char *c = NULL;
19222 int wordlen = strlen(word);
19223 struct ao2_iterator i;
19224
19225 if (pos != 3) {
19226 return NULL;
19227 }
19228
19229 i = ao2_iterator_init(dialogs, 0);
19230 while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
19231 sip_pvt_lock(cur);
19232 if (!strncasecmp(word, cur->callid, wordlen) && ++which > state) {
19233 c = ast_strdup(cur->callid);
19234 sip_pvt_unlock(cur);
19235 dialog_unref(cur, "drop ref in iterator loop break");
19236 break;
19237 }
19238 sip_pvt_unlock(cur);
19239 dialog_unref(cur, "drop ref in iterator loop");
19240 }
19241 ao2_iterator_destroy(&i);
19242 return c;
19243 }
19244
19245
19246
19247 static char *complete_sip_peer(const char *word, int state, int flags2)
19248 {
19249 char *result = NULL;
19250 int wordlen = strlen(word);
19251 int which = 0;
19252 struct ao2_iterator i = ao2_iterator_init(peers, 0);
19253 struct sip_peer *peer;
19254
19255 while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
19256
19257 if (!strncasecmp(word, peer->name, wordlen) &&
19258 (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
19259 ++which > state)
19260 result = ast_strdup(peer->name);
19261 unref_peer(peer, "toss iterator peer ptr before break");
19262 if (result) {
19263 break;
19264 }
19265 }
19266 ao2_iterator_destroy(&i);
19267 return result;
19268 }
19269
19270
19271 static char *complete_sip_registered_peer(const char *word, int state, int flags2)
19272 {
19273 char *result = NULL;
19274 int wordlen = strlen(word);
19275 int which = 0;
19276 struct ao2_iterator i;
19277 struct sip_peer *peer;
19278
19279 i = ao2_iterator_init(peers, 0);
19280 while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
19281 if (!strncasecmp(word, peer->name, wordlen) &&
19282 (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
19283 ++which > state && peer->expire > 0)
19284 result = ast_strdup(peer->name);
19285 if (result) {
19286 unref_peer(peer, "toss iterator peer ptr before break");
19287 break;
19288 }
19289 unref_peer(peer, "toss iterator peer ptr");
19290 }
19291 ao2_iterator_destroy(&i);
19292 return result;
19293 }
19294
19295
19296 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state)
19297 {
19298 if (pos == 3)
19299 return complete_sipch(line, word, pos, state);
19300
19301 return NULL;
19302 }
19303
19304
19305 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state)
19306 {
19307 if (pos == 3) {
19308 return complete_sip_peer(word, state, 0);
19309 }
19310
19311 return NULL;
19312 }
19313
19314
19315 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state)
19316 {
19317 if (pos == 2)
19318 return complete_sip_registered_peer(word, state, 0);
19319
19320 return NULL;
19321 }
19322
19323
19324 static char *complete_sipnotify(const char *line, const char *word, int pos, int state)
19325 {
19326 char *c = NULL;
19327
19328 if (pos == 2) {
19329 int which = 0;
19330 char *cat = NULL;
19331 int wordlen = strlen(word);
19332
19333
19334
19335 if (!notify_types)
19336 return NULL;
19337
19338 while ( (cat = ast_category_browse(notify_types, cat)) ) {
19339 if (!strncasecmp(word, cat, wordlen) && ++which > state) {
19340 c = ast_strdup(cat);
19341 break;
19342 }
19343 }
19344 return c;
19345 }
19346
19347 if (pos > 2)
19348 return complete_sip_peer(word, state, 0);
19349
19350 return NULL;
19351 }
19352
19353
19354 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
19355 {
19356 struct sip_pvt *cur;
19357 size_t len;
19358 int found = 0;
19359 struct ao2_iterator i;
19360
19361 switch (cmd) {
19362 case CLI_INIT:
19363 e->command = "sip show channel";
19364 e->usage =
19365 "Usage: sip show channel <call-id>\n"
19366 " Provides detailed status on a given SIP dialog (identified by SIP call-id).\n";
19367 return NULL;
19368 case CLI_GENERATE:
19369 return complete_sipch(a->line, a->word, a->pos, a->n);
19370 }
19371
19372 if (a->argc != 4)
19373 return CLI_SHOWUSAGE;
19374 len = strlen(a->argv[3]);
19375
19376 i = ao2_iterator_init(dialogs, 0);
19377 while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
19378 sip_pvt_lock(cur);
19379
19380 if (!strncasecmp(cur->callid, a->argv[3], len)) {
19381 char formatbuf[SIPBUFSIZE/2];
19382 ast_cli(a->fd, "\n");
19383 if (cur->subscribed != NONE)
19384 ast_cli(a->fd, " * Subscription (type: %s)\n", subscription_type2str(cur->subscribed));
19385 else
19386 ast_cli(a->fd, " * SIP Call\n");
19387 ast_cli(a->fd, " Curr. trans. direction: %s\n", ast_test_flag(&cur->flags[0], SIP_OUTGOING) ? "Outgoing" : "Incoming");
19388 ast_cli(a->fd, " Call-ID: %s\n", cur->callid);
19389 ast_cli(a->fd, " Owner channel ID: %s\n", cur->owner ? cur->owner->name : "<none>");
19390 ast_cli(a->fd, " Our Codec Capability: %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->capability));
19391 ast_cli(a->fd, " Non-Codec Capability (DTMF): %d\n", cur->noncodeccapability);
19392 ast_cli(a->fd, " Their Codec Capability: %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->peercapability));
19393 ast_cli(a->fd, " Joint Codec Capability: %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->jointcapability));
19394 ast_cli(a->fd, " Format: %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0) );
19395 ast_cli(a->fd, " T.38 support %s\n", AST_CLI_YESNO(cur->udptl != NULL));
19396 ast_cli(a->fd, " Video support %s\n", AST_CLI_YESNO(cur->vrtp != NULL));
19397 ast_cli(a->fd, " MaxCallBR: %d kbps\n", cur->maxcallbitrate);
19398 ast_cli(a->fd, " Theoretical Address: %s\n", ast_sockaddr_stringify(&cur->sa));
19399 ast_cli(a->fd, " Received Address: %s\n", ast_sockaddr_stringify(&cur->recv));
19400 ast_cli(a->fd, " SIP Transfer mode: %s\n", transfermode2str(cur->allowtransfer));
19401 ast_cli(a->fd, " Force rport: %s\n", AST_CLI_YESNO(ast_test_flag(&cur->flags[0], SIP_NAT_FORCE_RPORT)));
19402 if (ast_sockaddr_isnull(&cur->redirip)) {
19403 ast_cli(a->fd,
19404 " Audio IP: %s (local)\n",
19405 ast_sockaddr_stringify_addr(&cur->ourip));
19406 } else {
19407 ast_cli(a->fd,
19408 " Audio IP: %s (Outside bridge)\n",
19409 ast_sockaddr_stringify_addr(&cur->redirip));
19410 }
19411 ast_cli(a->fd, " Our Tag: %s\n", cur->tag);
19412 ast_cli(a->fd, " Their Tag: %s\n", cur->theirtag);
19413 ast_cli(a->fd, " SIP User agent: %s\n", cur->useragent);
19414 if (!ast_strlen_zero(cur->username))
19415 ast_cli(a->fd, " Username: %s\n", cur->username);
19416 if (!ast_strlen_zero(cur->peername))
19417 ast_cli(a->fd, " Peername: %s\n", cur->peername);
19418 if (!ast_strlen_zero(cur->uri))
19419 ast_cli(a->fd, " Original uri: %s\n", cur->uri);
19420 if (!ast_strlen_zero(cur->cid_num))
19421 ast_cli(a->fd, " Caller-ID: %s\n", cur->cid_num);
19422 ast_cli(a->fd, " Need Destroy: %s\n", AST_CLI_YESNO(cur->needdestroy));
19423 ast_cli(a->fd, " Last Message: %s\n", cur->lastmsg);
19424 ast_cli(a->fd, " Promiscuous Redir: %s\n", AST_CLI_YESNO(ast_test_flag(&cur->flags[0], SIP_PROMISCREDIR)));
19425 ast_cli(a->fd, " Route: %s\n", cur->route ? cur->route->hop : "N/A");
19426 ast_cli(a->fd, " DTMF Mode: %s\n", dtmfmode2str(ast_test_flag(&cur->flags[0], SIP_DTMF)));
19427 ast_cli(a->fd, " SIP Options: ");
19428 if (cur->sipoptions) {
19429 int x;
19430 for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
19431 if (cur->sipoptions & sip_options[x].id)
19432 ast_cli(a->fd, "%s ", sip_options[x].text);
19433 }
19434 ast_cli(a->fd, "\n");
19435 } else
19436 ast_cli(a->fd, "(none)\n");
19437
19438 if (!cur->stimer)
19439 ast_cli(a->fd, " Session-Timer: Uninitiallized\n");
19440 else {
19441 ast_cli(a->fd, " Session-Timer: %s\n", cur->stimer->st_active ? "Active" : "Inactive");
19442 if (cur->stimer->st_active == TRUE) {
19443 ast_cli(a->fd, " S-Timer Interval: %d\n", cur->stimer->st_interval);
19444 ast_cli(a->fd, " S-Timer Refresher: %s\n", strefresher2str(cur->stimer->st_ref));
19445 ast_cli(a->fd, " S-Timer Sched Id: %d\n", cur->stimer->st_schedid);
19446 ast_cli(a->fd, " S-Timer Peer Sts: %s\n", cur->stimer->st_active_peer_ua ? "Active" : "Inactive");
19447 ast_cli(a->fd, " S-Timer Cached Min-SE: %d\n", cur->stimer->st_cached_min_se);
19448 ast_cli(a->fd, " S-Timer Cached SE: %d\n", cur->stimer->st_cached_max_se);
19449 ast_cli(a->fd, " S-Timer Cached Ref: %s\n", strefresherparam2str(cur->stimer->st_cached_ref));
19450 ast_cli(a->fd, " S-Timer Cached Mode: %s\n", stmode2str(cur->stimer->st_cached_mode));
19451 }
19452 }
19453
19454 ast_cli(a->fd, "\n\n");
19455
19456 found++;
19457 }
19458
19459 sip_pvt_unlock(cur);
19460
19461 ao2_t_ref(cur, -1, "toss dialog ptr set by iterator_next");
19462 }
19463 ao2_iterator_destroy(&i);
19464
19465 if (!found)
19466 ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
19467
19468 return CLI_SUCCESS;
19469 }
19470
19471
19472 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
19473 {
19474 struct sip_pvt *cur;
19475 size_t len;
19476 int found = 0;
19477 struct ao2_iterator i;
19478
19479 switch (cmd) {
19480 case CLI_INIT:
19481 e->command = "sip show history";
19482 e->usage =
19483 "Usage: sip show history <call-id>\n"
19484 " Provides detailed dialog history on a given SIP call (specified by call-id).\n";
19485 return NULL;
19486 case CLI_GENERATE:
19487 return complete_sip_show_history(a->line, a->word, a->pos, a->n);
19488 }
19489
19490 if (a->argc != 4)
19491 return CLI_SHOWUSAGE;
19492
19493 if (!recordhistory)
19494 ast_cli(a->fd, "\n***Note: History recording is currently DISABLED. Use 'sip set history on' to ENABLE.\n");
19495
19496 len = strlen(a->argv[3]);
19497
19498 i = ao2_iterator_init(dialogs, 0);
19499 while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
19500 sip_pvt_lock(cur);
19501 if (!strncasecmp(cur->callid, a->argv[3], len)) {
19502 struct sip_history *hist;
19503 int x = 0;
19504
19505 ast_cli(a->fd, "\n");
19506 if (cur->subscribed != NONE)
19507 ast_cli(a->fd, " * Subscription\n");
19508 else
19509 ast_cli(a->fd, " * SIP Call\n");
19510 if (cur->history)
19511 AST_LIST_TRAVERSE(cur->history, hist, list)
19512 ast_cli(a->fd, "%d. %s\n", ++x, hist->event);
19513 if (x == 0)
19514 ast_cli(a->fd, "Call '%s' has no history\n", cur->callid);
19515 found++;
19516 }
19517 sip_pvt_unlock(cur);
19518 ao2_t_ref(cur, -1, "toss dialog ptr from iterator_next");
19519 }
19520 ao2_iterator_destroy(&i);
19521
19522 if (!found)
19523 ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
19524
19525 return CLI_SUCCESS;
19526 }
19527
19528
19529 static void sip_dump_history(struct sip_pvt *dialog)
19530 {
19531 int x = 0;
19532 struct sip_history *hist;
19533 static int errmsg = 0;
19534
19535 if (!dialog)
19536 return;
19537
19538 if (!option_debug && !sipdebug) {
19539 if (!errmsg) {
19540 ast_log(LOG_NOTICE, "You must have debugging enabled (SIP or Asterisk) in order to dump SIP history.\n");
19541 errmsg = 1;
19542 }
19543 return;
19544 }
19545
19546 ast_debug(1, "\n---------- SIP HISTORY for '%s' \n", dialog->callid);
19547 if (dialog->subscribed)
19548 ast_debug(1, " * Subscription\n");
19549 else
19550 ast_debug(1, " * SIP Call\n");
19551 if (dialog->history)
19552 AST_LIST_TRAVERSE(dialog->history, hist, list)
19553 ast_debug(1, " %-3.3d. %s\n", ++x, hist->event);
19554 if (!x)
19555 ast_debug(1, "Call '%s' has no history\n", dialog->callid);
19556 ast_debug(1, "\n---------- END SIP HISTORY for '%s' \n", dialog->callid);
19557 }
19558
19559
19560
19561 static void handle_request_info(struct sip_pvt *p, struct sip_request *req)
19562 {
19563 char buf[1024] = "";
19564 unsigned int event;
19565 const char *c = get_header(req, "Content-Type");
19566
19567
19568 if (!strcasecmp(c, "application/dtmf-relay") ||
19569 !strcasecmp(c, "application/vnd.nortelnetworks.digits") ||
19570 !strcasecmp(c, "application/dtmf")) {
19571 unsigned int duration = 0;
19572
19573 if (!p->owner) {
19574 transmit_response(p, "481 Call leg/transaction does not exist", req);
19575 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19576 return;
19577 }
19578
19579
19580
19581 if (strcasecmp(c, "application/dtmf")) {
19582 const char *msg_body;
19583
19584 if ( ast_strlen_zero(msg_body = get_body(req, "Signal", '='))
19585 && ast_strlen_zero(msg_body = get_body(req, "d", '='))) {
19586 ast_log(LOG_WARNING, "Unable to retrieve DTMF signal for INFO message on "
19587 "call %s\n", p->callid);
19588 transmit_response(p, "200 OK", req);
19589 return;
19590 }
19591 ast_copy_string(buf, msg_body, sizeof(buf));
19592
19593 if (!ast_strlen_zero((msg_body = get_body(req, "Duration", '=')))) {
19594 sscanf(msg_body, "%30u", &duration);
19595 }
19596 } else {
19597
19598 get_msg_text(buf, sizeof(buf), req);
19599 }
19600
19601
19602 if (ast_strlen_zero(buf)) {
19603 transmit_response(p, "200 OK", req);
19604 return;
19605 }
19606
19607 if (!duration) {
19608 duration = 100;
19609 }
19610
19611 if (buf[0] == '*') {
19612 event = 10;
19613 } else if (buf[0] == '#') {
19614 event = 11;
19615 } else if (buf[0] == '!') {
19616 event = 16;
19617 } else if ('A' <= buf[0] && buf[0] <= 'D') {
19618 event = 12 + buf[0] - 'A';
19619 } else if ('a' <= buf[0] && buf[0] <= 'd') {
19620 event = 12 + buf[0] - 'a';
19621 } else if ((sscanf(buf, "%30u", &event) != 1) || event > 16) {
19622 ast_log(AST_LOG_WARNING, "Unable to convert DTMF event signal code to a valid "
19623 "value for INFO message on call %s\n", p->callid);
19624 transmit_response(p, "200 OK", req);
19625 return;
19626 }
19627
19628 if (event == 16) {
19629
19630 struct ast_frame f = { AST_FRAME_CONTROL, { AST_CONTROL_FLASH, } };
19631 ast_queue_frame(p->owner, &f);
19632 if (sipdebug) {
19633 ast_verbose("* DTMF-relay event received: FLASH\n");
19634 }
19635 } else {
19636
19637 struct ast_frame f = { AST_FRAME_DTMF, };
19638 if (event < 10) {
19639 f.subclass.integer = '0' + event;
19640 } else if (event == 10) {
19641 f.subclass.integer = '*';
19642 } else if (event == 11) {
19643 f.subclass.integer = '#';
19644 } else {
19645 f.subclass.integer = 'A' + (event - 12);
19646 }
19647 f.len = duration;
19648 ast_queue_frame(p->owner, &f);
19649 if (sipdebug) {
19650 ast_verbose("* DTMF-relay event received: %c\n", (int) f.subclass.integer);
19651 }
19652 }
19653 transmit_response(p, "200 OK", req);
19654 return;
19655 } else if (!strcasecmp(c, "application/media_control+xml")) {
19656
19657 if (p->owner)
19658 ast_queue_control(p->owner, AST_CONTROL_VIDUPDATE);
19659 transmit_response(p, "200 OK", req);
19660 return;
19661 } else if (!ast_strlen_zero(c = get_header(req, "X-ClientCode"))) {
19662
19663 if (ast_test_flag(&p->flags[0], SIP_USECLIENTCODE)) {
19664 if (p->owner && p->owner->cdr)
19665 ast_cdr_setuserfield(p->owner, c);
19666 if (p->owner && ast_bridged_channel(p->owner) && ast_bridged_channel(p->owner)->cdr)
19667 ast_cdr_setuserfield(ast_bridged_channel(p->owner), c);
19668 transmit_response(p, "200 OK", req);
19669 } else {
19670 transmit_response(p, "403 Forbidden", req);
19671 }
19672 return;
19673 } else if (!ast_strlen_zero(c = get_header(req, "Record"))) {
19674
19675
19676
19677
19678
19679
19680
19681 struct ast_call_feature *feat;
19682 int j;
19683 struct ast_frame f = { AST_FRAME_DTMF, };
19684
19685 if (!p->owner) {
19686 transmit_response(p, "481 Call leg/transaction does not exist", req);
19687 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19688 return;
19689 }
19690
19691
19692 ast_rdlock_call_features();
19693 feat = ast_find_call_feature("automon");
19694 if (!feat || ast_strlen_zero(feat->exten)) {
19695 ast_log(LOG_WARNING, "Recording requested, but no One Touch Monitor registered. (See features.conf)\n");
19696
19697 transmit_response(p, "403 Forbidden", req);
19698 ast_unlock_call_features();
19699 return;
19700 }
19701
19702 f.len = 100;
19703 for (j=0; j < strlen(feat->exten); j++) {
19704 f.subclass.integer = feat->exten[j];
19705 ast_queue_frame(p->owner, &f);
19706 if (sipdebug)
19707 ast_verbose("* DTMF-relay event faked: %c\n", f.subclass.integer);
19708 }
19709 ast_unlock_call_features();
19710
19711 ast_debug(1, "Got a Request to Record the channel, state %s\n", c);
19712 transmit_response(p, "200 OK", req);
19713 return;
19714 } else if (ast_strlen_zero(c = get_header(req, "Content-Length")) || !strcasecmp(c, "0")) {
19715
19716 transmit_response(p, "200 OK", req);
19717 return;
19718 }
19719
19720
19721
19722
19723 ast_log(LOG_WARNING, "Unable to parse INFO message from %s. Content %s\n", p->callid, buf);
19724 transmit_response(p, "415 Unsupported media type", req);
19725 return;
19726 }
19727
19728
19729 static char *sip_do_debug_ip(int fd, const char *arg)
19730 {
19731 if (ast_sockaddr_resolve_first_af(&debugaddr, arg, 0, 0)) {
19732 return CLI_SHOWUSAGE;
19733 }
19734
19735 ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_sockaddr_stringify_addr(&debugaddr));
19736 sipdebug |= sip_debug_console;
19737
19738 return CLI_SUCCESS;
19739 }
19740
19741
19742 static char *sip_do_debug_peer(int fd, const char *arg)
19743 {
19744 struct sip_peer *peer = find_peer(arg, NULL, TRUE, FINDPEERS, FALSE, 0);
19745 if (!peer)
19746 ast_cli(fd, "No such peer '%s'\n", arg);
19747 else if (ast_sockaddr_isnull(&peer->addr))
19748 ast_cli(fd, "Unable to get IP address of peer '%s'\n", arg);
19749 else {
19750 ast_sockaddr_copy(&debugaddr, &peer->addr);
19751 ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_sockaddr_stringify_addr(&debugaddr));
19752 sipdebug |= sip_debug_console;
19753 }
19754 if (peer)
19755 unref_peer(peer, "sip_do_debug_peer: unref_peer, from find_peer call");
19756 return CLI_SUCCESS;
19757 }
19758
19759
19760 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
19761 {
19762 int oldsipdebug = sipdebug & sip_debug_console;
19763 const char *what;
19764
19765 if (cmd == CLI_INIT) {
19766 e->command = "sip set debug {on|off|ip|peer}";
19767 e->usage =
19768 "Usage: sip set debug {off|on|ip addr[:port]|peer peername}\n"
19769 " Globally disables dumping of SIP packets,\n"
19770 " or enables it either globally or for a (single)\n"
19771 " IP address or registered peer.\n";
19772 return NULL;
19773 } else if (cmd == CLI_GENERATE) {
19774 if (a->pos == 4 && !strcasecmp(a->argv[3], "peer"))
19775 return complete_sip_peer(a->word, a->n, 0);
19776 return NULL;
19777 }
19778
19779 what = a->argv[e->args-1];
19780 if (a->argc == e->args) {
19781 if (!strcasecmp(what, "on")) {
19782 sipdebug |= sip_debug_console;
19783 sipdebug_text = 1;
19784 memset(&debugaddr, 0, sizeof(debugaddr));
19785 ast_cli(a->fd, "SIP Debugging %senabled\n", oldsipdebug ? "re-" : "");
19786 return CLI_SUCCESS;
19787 } else if (!strcasecmp(what, "off")) {
19788 sipdebug &= ~sip_debug_console;
19789 sipdebug_text = 0;
19790 ast_cli(a->fd, "SIP Debugging Disabled\n");
19791 return CLI_SUCCESS;
19792 }
19793 } else if (a->argc == e->args +1) {
19794 if (!strcasecmp(what, "ip"))
19795 return sip_do_debug_ip(a->fd, a->argv[e->args]);
19796 else if (!strcasecmp(what, "peer"))
19797 return sip_do_debug_peer(a->fd, a->argv[e->args]);
19798 }
19799 return CLI_SHOWUSAGE;
19800 }
19801
19802
19803 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
19804 {
19805 struct ast_variable *varlist;
19806 int i;
19807
19808 switch (cmd) {
19809 case CLI_INIT:
19810 e->command = "sip notify";
19811 e->usage =
19812 "Usage: sip notify <type> <peer> [<peer>...]\n"
19813 " Send a NOTIFY message to a SIP peer or peers\n"
19814 " Message types are defined in sip_notify.conf\n";
19815 return NULL;
19816 case CLI_GENERATE:
19817 return complete_sipnotify(a->line, a->word, a->pos, a->n);
19818 }
19819
19820 if (a->argc < 4)
19821 return CLI_SHOWUSAGE;
19822
19823 if (!notify_types) {
19824 ast_cli(a->fd, "No %s file found, or no types listed there\n", notify_config);
19825 return CLI_FAILURE;
19826 }
19827
19828 varlist = ast_variable_browse(notify_types, a->argv[2]);
19829
19830 if (!varlist) {
19831 ast_cli(a->fd, "Unable to find notify type '%s'\n", a->argv[2]);
19832 return CLI_FAILURE;
19833 }
19834
19835 for (i = 3; i < a->argc; i++) {
19836 struct sip_pvt *p;
19837 char buf[512];
19838 struct ast_variable *header, *var;
19839
19840 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
19841 ast_log(LOG_WARNING, "Unable to build sip pvt data for notify (memory/socket error)\n");
19842 return CLI_FAILURE;
19843 }
19844
19845 if (create_addr(p, a->argv[i], NULL, 1)) {
19846
19847 dialog_unlink_all(p);
19848 dialog_unref(p, "unref dialog inside for loop" );
19849
19850 ast_cli(a->fd, "Could not create address for '%s'\n", a->argv[i]);
19851 continue;
19852 }
19853
19854
19855 ast_set_flag(&p->flags[0], SIP_OUTGOING);
19856 sip_notify_allocate(p);
19857 p->notify->headers = header = ast_variable_new("Subscription-State", "terminated", "");
19858
19859 for (var = varlist; var; var = var->next) {
19860 ast_copy_string(buf, var->value, sizeof(buf));
19861 ast_unescape_semicolon(buf);
19862
19863 if (!strcasecmp(var->name, "Content")) {
19864 if (ast_str_strlen(p->notify->content))
19865 ast_str_append(&p->notify->content, 0, "\r\n");
19866 ast_str_append(&p->notify->content, 0, "%s", buf);
19867 } else if (!strcasecmp(var->name, "Content-Length")) {
19868 ast_log(LOG_WARNING, "it is not necessary to specify Content-Length in sip_notify.conf, ignoring\n");
19869 } else {
19870 header->next = ast_variable_new(var->name, buf, "");
19871 header = header->next;
19872 }
19873 }
19874
19875
19876 ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
19877 build_via(p);
19878
19879 change_callid_pvt(p, NULL);
19880
19881 ast_cli(a->fd, "Sending NOTIFY of type '%s' to '%s'\n", a->argv[2], a->argv[i]);
19882 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
19883 transmit_invite(p, SIP_NOTIFY, 0, 2, NULL);
19884 dialog_unref(p, "bump down the count of p since we're done with it.");
19885 }
19886
19887 return CLI_SUCCESS;
19888 }
19889
19890
19891 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
19892 {
19893 switch (cmd) {
19894 case CLI_INIT:
19895 e->command = "sip set history {on|off}";
19896 e->usage =
19897 "Usage: sip set history {on|off}\n"
19898 " Enables/Disables recording of SIP dialog history for debugging purposes.\n"
19899 " Use 'sip show history' to view the history of a call number.\n";
19900 return NULL;
19901 case CLI_GENERATE:
19902 return NULL;
19903 }
19904
19905 if (a->argc != e->args)
19906 return CLI_SHOWUSAGE;
19907
19908 if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
19909 recordhistory = TRUE;
19910 ast_cli(a->fd, "SIP History Recording Enabled (use 'sip show history')\n");
19911 } else if (!strncasecmp(a->argv[e->args - 1], "off", 3)) {
19912 recordhistory = FALSE;
19913 ast_cli(a->fd, "SIP History Recording Disabled\n");
19914 } else {
19915 return CLI_SHOWUSAGE;
19916 }
19917 return CLI_SUCCESS;
19918 }
19919
19920
19921 static int do_register_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code)
19922 {
19923 char *header, *respheader;
19924 char digest[1024];
19925
19926 p->authtries++;
19927 auth_headers(code, &header, &respheader);
19928 memset(digest, 0, sizeof(digest));
19929 if (reply_digest(p, req, header, SIP_REGISTER, digest, sizeof(digest))) {
19930
19931
19932 if (sip_debug_test_pvt(p) && p->registry)
19933 ast_verbose("No authentication challenge, sending blank registration to domain/host name %s\n", p->registry->hostname);
19934
19935 return -1;
19936 }
19937 if (p->do_history)
19938 append_history(p, "RegistryAuth", "Try: %d", p->authtries);
19939 if (sip_debug_test_pvt(p) && p->registry)
19940 ast_verbose("Responding to challenge, registration to domain/host name %s\n", p->registry->hostname);
19941 return transmit_register(p->registry, SIP_REGISTER, digest, respheader);
19942 }
19943
19944
19945 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code, int sipmethod, int init)
19946 {
19947 char *header, *respheader;
19948 char digest[1024];
19949
19950 if (!p->options && !(p->options = ast_calloc(1, sizeof(*p->options))))
19951 return -2;
19952
19953 p->authtries++;
19954 auth_headers(code, &header, &respheader);
19955 ast_debug(2, "Auth attempt %d on %s\n", p->authtries, sip_methods[sipmethod].text);
19956 memset(digest, 0, sizeof(digest));
19957 if (reply_digest(p, req, header, sipmethod, digest, sizeof(digest) )) {
19958
19959 return -1;
19960 }
19961
19962 p->options->auth = digest;
19963 p->options->authheader = respheader;
19964 return transmit_invite(p, sipmethod, sipmethod == SIP_INVITE, init, NULL);
19965 }
19966
19967
19968
19969
19970
19971 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len)
19972 {
19973 char tmp[512];
19974 char *c;
19975 char oldnonce[256];
19976
19977
19978 const struct x {
19979 const char *key;
19980 const ast_string_field *field;
19981 } *i, keys[] = {
19982 { "realm=", &p->realm },
19983 { "nonce=", &p->nonce },
19984 { "opaque=", &p->opaque },
19985 { "qop=", &p->qop },
19986 { "domain=", &p->domain },
19987 { NULL, 0 },
19988 };
19989
19990 ast_copy_string(tmp, get_header(req, header), sizeof(tmp));
19991 if (ast_strlen_zero(tmp))
19992 return -1;
19993 if (strncasecmp(tmp, "Digest ", strlen("Digest "))) {
19994 ast_log(LOG_WARNING, "missing Digest.\n");
19995 return -1;
19996 }
19997 c = tmp + strlen("Digest ");
19998 ast_copy_string(oldnonce, p->nonce, sizeof(oldnonce));
19999 while (c && *(c = ast_skip_blanks(c))) {
20000 for (i = keys; i->key != NULL; i++) {
20001 char *src, *separator;
20002 if (strncasecmp(c, i->key, strlen(i->key)) != 0)
20003 continue;
20004
20005 c += strlen(i->key);
20006 if (*c == '"') {
20007 src = ++c;
20008 separator = "\"";
20009 } else {
20010 src = c;
20011 separator = ",";
20012 }
20013 strsep(&c, separator);
20014 ast_string_field_ptr_set(p, i->field, src);
20015 break;
20016 }
20017 if (i->key == NULL)
20018 strsep(&c, ",");
20019 }
20020
20021 if (strcmp(p->nonce, oldnonce))
20022 p->noncecount = 0;
20023
20024
20025 if (p->registry) {
20026 struct sip_registry *r = p->registry;
20027
20028 if (strcmp(r->nonce, p->nonce)) {
20029 ast_string_field_set(r, realm, p->realm);
20030 ast_string_field_set(r, nonce, p->nonce);
20031 ast_string_field_set(r, authdomain, p->domain);
20032 ast_string_field_set(r, opaque, p->opaque);
20033 ast_string_field_set(r, qop, p->qop);
20034 r->noncecount = 0;
20035 }
20036 }
20037 return build_reply_digest(p, sipmethod, digest, digest_len);
20038 }
20039
20040
20041
20042
20043
20044
20045 static int build_reply_digest(struct sip_pvt *p, int method, char* digest, int digest_len)
20046 {
20047 char a1[256];
20048 char a2[256];
20049 char a1_hash[256];
20050 char a2_hash[256];
20051 char resp[256];
20052 char resp_hash[256];
20053 char uri[256];
20054 char opaque[256] = "";
20055 char cnonce[80];
20056 const char *username;
20057 const char *secret;
20058 const char *md5secret;
20059 struct sip_auth *auth;
20060 struct sip_auth_container *credentials;
20061
20062 if (!ast_strlen_zero(p->domain))
20063 snprintf(uri, sizeof(uri), "%s:%s", p->socket.type == SIP_TRANSPORT_TLS ? "sips" : "sip", p->domain);
20064 else if (!ast_strlen_zero(p->uri))
20065 ast_copy_string(uri, p->uri, sizeof(uri));
20066 else
20067 snprintf(uri, sizeof(uri), "%s:%s@%s", p->socket.type == SIP_TRANSPORT_TLS ? "sips" : "sip", p->username, ast_sockaddr_stringify_host_remote(&p->sa));
20068
20069 snprintf(cnonce, sizeof(cnonce), "%08lx", ast_random());
20070
20071
20072 ao2_lock(p);
20073 credentials = p->peerauth;
20074 if (credentials) {
20075 ao2_t_ref(credentials, +1, "Ref peer auth for digest");
20076 }
20077 ao2_unlock(p);
20078 auth = find_realm_authentication(credentials, p->realm);
20079 if (!auth) {
20080
20081 if (credentials) {
20082 ao2_t_ref(credentials, -1, "Unref peer auth for digest");
20083 }
20084 ast_mutex_lock(&authl_lock);
20085 credentials = authl;
20086 if (credentials) {
20087 ao2_t_ref(credentials, +1, "Ref global auth for digest");
20088 }
20089 ast_mutex_unlock(&authl_lock);
20090 auth = find_realm_authentication(credentials, p->realm);
20091 }
20092
20093 if (auth) {
20094 ast_debug(3, "use realm [%s] from peer [%s][%s]\n", auth->username, p->peername, p->username);
20095 username = auth->username;
20096 secret = auth->secret;
20097 md5secret = auth->md5secret;
20098 if (sipdebug)
20099 ast_debug(1, "Using realm %s authentication for call %s\n", p->realm, p->callid);
20100 } else {
20101
20102 username = p->authname;
20103 secret = p->relatedpeer
20104 && !ast_strlen_zero(p->relatedpeer->remotesecret)
20105 ? p->relatedpeer->remotesecret : p->peersecret;
20106 md5secret = p->peermd5secret;
20107 }
20108 if (ast_strlen_zero(username)) {
20109
20110 if (credentials) {
20111 ao2_t_ref(credentials, -1, "Unref auth for digest");
20112 }
20113 return -1;
20114 }
20115
20116
20117 snprintf(a1, sizeof(a1), "%s:%s:%s", username, p->realm, secret);
20118 snprintf(a2, sizeof(a2), "%s:%s", sip_methods[method].text, uri);
20119 if (!ast_strlen_zero(md5secret))
20120 ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
20121 else
20122 ast_md5_hash(a1_hash, a1);
20123 ast_md5_hash(a2_hash, a2);
20124
20125 p->noncecount++;
20126 if (!ast_strlen_zero(p->qop))
20127 snprintf(resp, sizeof(resp), "%s:%s:%08x:%s:%s:%s", a1_hash, p->nonce, p->noncecount, cnonce, "auth", a2_hash);
20128 else
20129 snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, p->nonce, a2_hash);
20130 ast_md5_hash(resp_hash, resp);
20131
20132
20133 if (!ast_strlen_zero(p->opaque)) {
20134 snprintf(opaque, sizeof(opaque), ", opaque=\"%s\"", p->opaque);
20135 }
20136
20137
20138 if (!ast_strlen_zero(p->qop))
20139 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);
20140 else
20141 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);
20142
20143 append_history(p, "AuthResp", "Auth response sent for %s in realm %s - nc %d", username, p->realm, p->noncecount);
20144
20145 if (credentials) {
20146 ao2_t_ref(credentials, -1, "Unref auth for digest");
20147 }
20148 return 0;
20149 }
20150
20151
20152 static int func_header_read(struct ast_channel *chan, const char *function, char *data, char *buf, size_t len)
20153 {
20154 struct sip_pvt *p;
20155 const char *content = NULL;
20156 AST_DECLARE_APP_ARGS(args,
20157 AST_APP_ARG(header);
20158 AST_APP_ARG(number);
20159 );
20160 int i, number, start = 0;
20161
20162 if (!chan) {
20163 ast_log(LOG_WARNING, "No channel was provided to %s function.\n", function);
20164 return -1;
20165 }
20166
20167 if (ast_strlen_zero(data)) {
20168 ast_log(LOG_WARNING, "This function requires a header name.\n");
20169 return -1;
20170 }
20171
20172 ast_channel_lock(chan);
20173 if (!IS_SIP_TECH(chan->tech)) {
20174 ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
20175 ast_channel_unlock(chan);
20176 return -1;
20177 }
20178
20179 AST_STANDARD_APP_ARGS(args, data);
20180 if (!args.number) {
20181 number = 1;
20182 } else {
20183 sscanf(args.number, "%30d", &number);
20184 if (number < 1)
20185 number = 1;
20186 }
20187
20188 p = chan->tech_pvt;
20189
20190
20191 if (!p) {
20192 ast_channel_unlock(chan);
20193 return -1;
20194 }
20195
20196 for (i = 0; i < number; i++)
20197 content = __get_header(&p->initreq, args.header, &start);
20198
20199 if (ast_strlen_zero(content)) {
20200 ast_channel_unlock(chan);
20201 return -1;
20202 }
20203
20204 ast_copy_string(buf, content, len);
20205 ast_channel_unlock(chan);
20206
20207 return 0;
20208 }
20209
20210 static struct ast_custom_function sip_header_function = {
20211 .name = "SIP_HEADER",
20212 .read = func_header_read,
20213 };
20214
20215
20216 static int func_check_sipdomain(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
20217 {
20218 if (ast_strlen_zero(data)) {
20219 ast_log(LOG_WARNING, "CHECKSIPDOMAIN requires an argument - A domain name\n");
20220 return -1;
20221 }
20222 if (check_sip_domain(data, NULL, 0))
20223 ast_copy_string(buf, data, len);
20224 else
20225 buf[0] = '\0';
20226 return 0;
20227 }
20228
20229 static struct ast_custom_function checksipdomain_function = {
20230 .name = "CHECKSIPDOMAIN",
20231 .read = func_check_sipdomain,
20232 };
20233
20234
20235 static int function_sippeer(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
20236 {
20237 struct sip_peer *peer;
20238 char *colname;
20239
20240 if ((colname = strchr(data, ':'))) {
20241 static int deprecation_warning = 0;
20242 *colname++ = '\0';
20243 if (deprecation_warning++ % 10 == 0)
20244 ast_log(LOG_WARNING, "SIPPEER(): usage of ':' to separate arguments is deprecated. Please use ',' instead.\n");
20245 } else if ((colname = strchr(data, ',')))
20246 *colname++ = '\0';
20247 else
20248 colname = "ip";
20249
20250 if (!(peer = find_peer(data, NULL, TRUE, FINDPEERS, FALSE, 0)))
20251 return -1;
20252
20253 if (!strcasecmp(colname, "ip")) {
20254 ast_copy_string(buf, ast_sockaddr_stringify_addr(&peer->addr), len);
20255 } else if (!strcasecmp(colname, "port")) {
20256 snprintf(buf, len, "%d", ast_sockaddr_port(&peer->addr));
20257 } else if (!strcasecmp(colname, "status")) {
20258 peer_status(peer, buf, len);
20259 } else if (!strcasecmp(colname, "language")) {
20260 ast_copy_string(buf, peer->language, len);
20261 } else if (!strcasecmp(colname, "regexten")) {
20262 ast_copy_string(buf, peer->regexten, len);
20263 } else if (!strcasecmp(colname, "limit")) {
20264 snprintf(buf, len, "%d", peer->call_limit);
20265 } else if (!strcasecmp(colname, "busylevel")) {
20266 snprintf(buf, len, "%d", peer->busy_level);
20267 } else if (!strcasecmp(colname, "curcalls")) {
20268 snprintf(buf, len, "%d", peer->inUse);
20269 } else if (!strcasecmp(colname, "maxforwards")) {
20270 snprintf(buf, len, "%d", peer->maxforwards);
20271 } else if (!strcasecmp(colname, "accountcode")) {
20272 ast_copy_string(buf, peer->accountcode, len);
20273 } else if (!strcasecmp(colname, "callgroup")) {
20274 ast_print_group(buf, len, peer->callgroup);
20275 } else if (!strcasecmp(colname, "pickupgroup")) {
20276 ast_print_group(buf, len, peer->pickupgroup);
20277 } else if (!strcasecmp(colname, "useragent")) {
20278 ast_copy_string(buf, peer->useragent, len);
20279 } else if (!strcasecmp(colname, "mailbox")) {
20280 struct ast_str *mailbox_str = ast_str_alloca(512);
20281 peer_mailboxes_to_str(&mailbox_str, peer);
20282 ast_copy_string(buf, ast_str_buffer(mailbox_str), len);
20283 } else if (!strcasecmp(colname, "context")) {
20284 ast_copy_string(buf, peer->context, len);
20285 } else if (!strcasecmp(colname, "expire")) {
20286 snprintf(buf, len, "%d", peer->expire);
20287 } else if (!strcasecmp(colname, "dynamic")) {
20288 ast_copy_string(buf, peer->host_dynamic ? "yes" : "no", len);
20289 } else if (!strcasecmp(colname, "callerid_name")) {
20290 ast_copy_string(buf, peer->cid_name, len);
20291 } else if (!strcasecmp(colname, "callerid_num")) {
20292 ast_copy_string(buf, peer->cid_num, len);
20293 } else if (!strcasecmp(colname, "codecs")) {
20294 ast_getformatname_multiple(buf, len -1, peer->capability);
20295 } else if (!strcasecmp(colname, "encryption")) {
20296 snprintf(buf, len, "%d", ast_test_flag(&peer->flags[1], SIP_PAGE2_USE_SRTP));
20297 } else if (!strncasecmp(colname, "chanvar[", 8)) {
20298 char *chanvar=colname + 8;
20299 struct ast_variable *v;
20300
20301 chanvar = strsep(&chanvar, "]");
20302 for (v = peer->chanvars ; v ; v = v->next) {
20303 if (!strcasecmp(v->name, chanvar)) {
20304 ast_copy_string(buf, v->value, len);
20305 }
20306 }
20307 } else if (!strncasecmp(colname, "codec[", 6)) {
20308 char *codecnum;
20309 format_t codec = 0;
20310
20311 codecnum = colname + 6;
20312 codecnum = strsep(&codecnum, "]");
20313 if((codec = ast_codec_pref_index(&peer->prefs, atoi(codecnum)))) {
20314 ast_copy_string(buf, ast_getformatname(codec), len);
20315 } else {
20316 buf[0] = '\0';
20317 }
20318 } else {
20319 buf[0] = '\0';
20320 }
20321
20322 unref_peer(peer, "unref_peer from function_sippeer, just before return");
20323
20324 return 0;
20325 }
20326
20327
20328 static struct ast_custom_function sippeer_function = {
20329 .name = "SIPPEER",
20330 .read = function_sippeer,
20331 };
20332
20333
20334 static int function_sipchaninfo_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
20335 {
20336 struct sip_pvt *p;
20337 static int deprecated = 0;
20338
20339 *buf = 0;
20340
20341 if (!chan) {
20342 ast_log(LOG_WARNING, "No channel was provided to %s function.\n", cmd);
20343 return -1;
20344 }
20345
20346 if (!data) {
20347 ast_log(LOG_WARNING, "This function requires a parameter name.\n");
20348 return -1;
20349 }
20350
20351 ast_channel_lock(chan);
20352 if (!IS_SIP_TECH(chan->tech)) {
20353 ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
20354 ast_channel_unlock(chan);
20355 return -1;
20356 }
20357
20358 if (deprecated++ % 20 == 0) {
20359
20360 ast_log(LOG_WARNING, "SIPCHANINFO() is deprecated. Please transition to using CHANNEL().\n");
20361 }
20362
20363 p = chan->tech_pvt;
20364
20365
20366 if (!p) {
20367 ast_channel_unlock(chan);
20368 return -1;
20369 }
20370
20371 if (!strcasecmp(data, "peerip")) {
20372 ast_copy_string(buf, ast_sockaddr_stringify_addr(&p->sa), len);
20373 } else if (!strcasecmp(data, "recvip")) {
20374 ast_copy_string(buf, ast_sockaddr_stringify_addr(&p->recv), len);
20375 } else if (!strcasecmp(data, "from")) {
20376 ast_copy_string(buf, p->from, len);
20377 } else if (!strcasecmp(data, "uri")) {
20378 ast_copy_string(buf, p->uri, len);
20379 } else if (!strcasecmp(data, "useragent")) {
20380 ast_copy_string(buf, p->useragent, len);
20381 } else if (!strcasecmp(data, "peername")) {
20382 ast_copy_string(buf, p->peername, len);
20383 } else if (!strcasecmp(data, "t38passthrough")) {
20384 if (p->t38.state == T38_DISABLED) {
20385 ast_copy_string(buf, "0", len);
20386 } else {
20387 ast_copy_string(buf, "1", len);
20388 }
20389 } else {
20390 ast_channel_unlock(chan);
20391 return -1;
20392 }
20393 ast_channel_unlock(chan);
20394
20395 return 0;
20396 }
20397
20398
20399 static struct ast_custom_function sipchaninfo_function = {
20400 .name = "SIPCHANINFO",
20401 .read = function_sipchaninfo_read,
20402 };
20403
20404
20405
20406
20407 static void change_redirecting_information(struct sip_pvt *p, struct sip_request *req,
20408 struct ast_party_redirecting *redirecting,
20409 struct ast_set_party_redirecting *update_redirecting, int set_call_forward)
20410 {
20411 char *redirecting_from_name = NULL;
20412 char *redirecting_from_number = NULL;
20413 char *redirecting_to_name = NULL;
20414 char *redirecting_to_number = NULL;
20415 int reason = AST_REDIRECTING_REASON_UNCONDITIONAL;
20416 int is_response = req->method == SIP_RESPONSE;
20417 int res = 0;
20418
20419 res = get_rdnis(p, req, &redirecting_from_name, &redirecting_from_number, &reason);
20420 if (res == -1) {
20421 if (is_response) {
20422 get_name_and_number(get_header(req, "TO"), &redirecting_from_name, &redirecting_from_number);
20423 } else {
20424 return;
20425 }
20426 }
20427
20428
20429
20430
20431
20432 if (is_response) {
20433 parse_moved_contact(p, req, &redirecting_to_name, &redirecting_to_number, set_call_forward);
20434 } else {
20435 get_name_and_number(get_header(req, "TO"), &redirecting_to_name, &redirecting_to_number);
20436 }
20437
20438 if (!ast_strlen_zero(redirecting_from_number)) {
20439 ast_debug(3, "Got redirecting from number %s\n", redirecting_from_number);
20440 update_redirecting->from.number = 1;
20441 redirecting->from.number.valid = 1;
20442 ast_free(redirecting->from.number.str);
20443 redirecting->from.number.str = redirecting_from_number;
20444 }
20445 if (!ast_strlen_zero(redirecting_from_name)) {
20446 ast_debug(3, "Got redirecting from name %s\n", redirecting_from_name);
20447 update_redirecting->from.name = 1;
20448 redirecting->from.name.valid = 1;
20449 ast_free(redirecting->from.name.str);
20450 redirecting->from.name.str = redirecting_from_name;
20451 }
20452 if (!ast_strlen_zero(p->cid_tag)) {
20453 ast_free(redirecting->from.tag);
20454 redirecting->from.tag = ast_strdup(p->cid_tag);
20455 ast_free(redirecting->to.tag);
20456 redirecting->to.tag = ast_strdup(p->cid_tag);
20457 }
20458 if (!ast_strlen_zero(redirecting_to_number)) {
20459 ast_debug(3, "Got redirecting to number %s\n", redirecting_to_number);
20460 update_redirecting->to.number = 1;
20461 redirecting->to.number.valid = 1;
20462 ast_free(redirecting->to.number.str);
20463 redirecting->to.number.str = redirecting_to_number;
20464 }
20465 if (!ast_strlen_zero(redirecting_to_name)) {
20466 ast_debug(3, "Got redirecting to name %s\n", redirecting_from_number);
20467 update_redirecting->to.name = 1;
20468 redirecting->to.name.valid = 1;
20469 ast_free(redirecting->to.name.str);
20470 redirecting->to.name.str = redirecting_to_name;
20471 }
20472 redirecting->reason = reason;
20473 }
20474
20475
20476
20477
20478
20479
20480
20481 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req, char **name, char **number, int set_call_forward)
20482 {
20483 char contact[SIPBUFSIZE];
20484 char *contact_name = NULL;
20485 char *contact_number = NULL;
20486 char *separator, *trans;
20487 char *domain;
20488 enum sip_transport transport = SIP_TRANSPORT_UDP;
20489
20490 ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
20491 if ((separator = strchr(contact, ',')))
20492 *separator = '\0';
20493
20494 contact_number = get_in_brackets(contact);
20495 if ((trans = strcasestr(contact_number, ";transport="))) {
20496 trans += 11;
20497
20498 if ((separator = strchr(trans, ';')))
20499 *separator = '\0';
20500
20501 if (!strncasecmp(trans, "tcp", 3))
20502 transport = SIP_TRANSPORT_TCP;
20503 else if (!strncasecmp(trans, "tls", 3))
20504 transport = SIP_TRANSPORT_TLS;
20505 else {
20506 if (strncasecmp(trans, "udp", 3))
20507 ast_debug(1, "received contact with an invalid transport, '%s'\n", contact_number);
20508
20509 transport = SIP_TRANSPORT_UDP;
20510 }
20511 }
20512 contact_number = remove_uri_parameters(contact_number);
20513
20514 if (p->socket.tcptls_session) {
20515 ao2_ref(p->socket.tcptls_session, -1);
20516 p->socket.tcptls_session = NULL;
20517 }
20518
20519 set_socket_transport(&p->socket, transport);
20520
20521 if (set_call_forward && ast_test_flag(&p->flags[0], SIP_PROMISCREDIR)) {
20522 char *host = NULL;
20523 if (!strncasecmp(contact_number, "sip:", 4))
20524 contact_number += 4;
20525 else if (!strncasecmp(contact_number, "sips:", 5))
20526 contact_number += 5;
20527 separator = strchr(contact_number, '/');
20528 if (separator)
20529 *separator = '\0';
20530 if ((host = strchr(contact_number, '@'))) {
20531 *host++ = '\0';
20532 ast_debug(2, "Found promiscuous redirection to 'SIP/%s::::%s@%s'\n", contact_number, get_transport(transport), host);
20533 if (p->owner)
20534 ast_string_field_build(p->owner, call_forward, "SIP/%s::::%s@%s", contact_number, get_transport(transport), host);
20535 } else {
20536 ast_debug(2, "Found promiscuous redirection to 'SIP/::::%s@%s'\n", get_transport(transport), contact_number);
20537 if (p->owner)
20538 ast_string_field_build(p->owner, call_forward, "SIP/::::%s@%s", get_transport(transport), contact_number);
20539 }
20540 } else {
20541 separator = strchr(contact, '@');
20542 if (separator) {
20543 *separator++ = '\0';
20544 domain = separator;
20545 } else {
20546
20547 domain = contact;
20548 }
20549 separator = strchr(contact, '/');
20550 if (separator)
20551 *separator = '\0';
20552
20553 if (!strncasecmp(contact_number, "sip:", 4))
20554 contact_number += 4;
20555 else if (!strncasecmp(contact_number, "sips:", 5))
20556 contact_number += 5;
20557 separator = strchr(contact_number, ';');
20558 if (separator)
20559 *separator = '\0';
20560 ast_uri_decode(contact_number);
20561 if (set_call_forward) {
20562 ast_debug(2, "Received 302 Redirect to extension '%s' (domain %s)\n", contact_number, domain);
20563 if (p->owner) {
20564 pbx_builtin_setvar_helper(p->owner, "SIPDOMAIN", domain);
20565 ast_string_field_set(p->owner, call_forward, contact_number);
20566 }
20567 }
20568 }
20569
20570
20571
20572 if (*contact == '\"') {
20573 contact_name = contact + 1;
20574 if (!(separator = (char *)find_closing_quote(contact_name, NULL))) {
20575 ast_log(LOG_NOTICE, "No closing quote on name in Contact header? %s\n", contact);
20576 }
20577 *separator = '\0';
20578 }
20579
20580 if (name && !ast_strlen_zero(contact_name)) {
20581 *name = ast_strdup(contact_name);
20582 }
20583 if (number) {
20584 *number = ast_strdup(contact_number);
20585 }
20586 }
20587
20588
20589
20590
20591
20592
20593 static void check_pendings(struct sip_pvt *p)
20594 {
20595 if (ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
20596 if (p->reinviteid > -1) {
20597
20598 return;
20599 } else if (p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA) {
20600
20601 p->invitestate = INV_CANCELLED;
20602 transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
20603
20604 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
20605 ast_clear_flag(&p->flags[0], SIP_PENDINGBYE);
20606 }
20607
20608
20609 } else {
20610
20611
20612
20613 if (p->pendinginvite && !p->ongoing_reinvite)
20614 return;
20615
20616 if (p->owner) {
20617 ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
20618 }
20619
20620 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, TRUE);
20621 ast_clear_flag(&p->flags[0], SIP_PENDINGBYE);
20622 }
20623 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20624 } else if (ast_test_flag(&p->flags[0], SIP_NEEDREINVITE)) {
20625
20626 if (p->pendinginvite || p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA || p->waitid > 0) {
20627 ast_debug(2, "NOT Sending pending reinvite (yet) on '%s'\n", p->callid);
20628 } else {
20629 ast_debug(2, "Sending pending reinvite on '%s'\n", p->callid);
20630
20631 transmit_reinvite_with_sdp(p, (p->t38.state == T38_LOCAL_REINVITE ? TRUE : FALSE), FALSE);
20632 ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);
20633 }
20634 }
20635 }
20636
20637
20638
20639
20640
20641 static int sip_reinvite_retry(const void *data)
20642 {
20643 struct sip_pvt *p = (struct sip_pvt *) data;
20644 struct ast_channel *owner;
20645
20646 sip_pvt_lock(p);
20647 while ((owner = p->owner) && ast_channel_trylock(owner)) {
20648 sip_pvt_unlock(p);
20649 usleep(1);
20650 sip_pvt_lock(p);
20651 }
20652 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
20653 p->waitid = -1;
20654 check_pendings(p);
20655 sip_pvt_unlock(p);
20656 if (owner) {
20657 ast_channel_unlock(owner);
20658 }
20659 dialog_unref(p, "unref the dialog ptr from sip_reinvite_retry, because it held a dialog ptr");
20660 return 0;
20661 }
20662
20663
20664
20665
20666
20667
20668 static void handle_response_update(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
20669 {
20670 if (p->options) {
20671 p->options->auth_type = (resp == 401 ? WWW_AUTH : PROXY_AUTH);
20672 }
20673 if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp, SIP_UPDATE, 1)) {
20674 ast_log(LOG_NOTICE, "Failed to authenticate on UPDATE to '%s'\n", get_header(&p->initreq, "From"));
20675 }
20676 }
20677
20678 static void cc_handle_publish_error(struct sip_pvt *pvt, const int resp, struct sip_request *req, struct sip_epa_entry *epa_entry)
20679 {
20680 struct cc_epa_entry *cc_entry = epa_entry->instance_data;
20681 struct sip_monitor_instance *monitor_instance = ao2_callback(sip_monitor_instances, 0,
20682 find_sip_monitor_instance_by_suspension_entry, epa_entry);
20683 const char *min_expires;
20684
20685 if (!monitor_instance) {
20686 ast_log(LOG_WARNING, "Can't find monitor_instance corresponding to epa_entry %p.\n", epa_entry);
20687 return;
20688 }
20689
20690 if (resp != 423) {
20691 ast_cc_monitor_failed(cc_entry->core_id, monitor_instance->device_name,
20692 "Received error response to our PUBLISH");
20693 ao2_ref(monitor_instance, -1);
20694 return;
20695 }
20696
20697
20698
20699
20700
20701
20702
20703
20704
20705 min_expires = get_header(req, "Min-Expires");
20706 if (ast_strlen_zero(min_expires)) {
20707 pvt->expiry *= 2;
20708 if (pvt->expiry < 0) {
20709
20710 ast_cc_monitor_failed(cc_entry->core_id, monitor_instance->device_name,
20711 "PUBLISH expiry overflowed");
20712 ao2_ref(monitor_instance, -1);
20713 return;
20714 }
20715 } else if (sscanf(min_expires, "%d", &pvt->expiry) != 1) {
20716 ast_cc_monitor_failed(cc_entry->core_id, monitor_instance->device_name,
20717 "Min-Expires has non-numeric value");
20718 ao2_ref(monitor_instance, -1);
20719 return;
20720 }
20721
20722
20723
20724 transmit_invite(pvt, SIP_PUBLISH, FALSE, 0, NULL);
20725 ao2_ref(monitor_instance, -1);
20726 }
20727
20728 static void handle_response_publish(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
20729 {
20730 struct sip_epa_entry *epa_entry = p->epa_entry;
20731 const char *etag = get_header(req, "Sip-ETag");
20732
20733 ast_assert(epa_entry != NULL);
20734
20735 if (resp == 401 || resp == 407) {
20736 ast_string_field_set(p, theirtag, NULL);
20737 if (p->options) {
20738 p->options->auth_type = (resp == 401 ? WWW_AUTH : PROXY_AUTH);
20739 }
20740 if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp, SIP_PUBLISH, 0)) {
20741 ast_log(LOG_NOTICE, "Failed to authenticate on PUBLISH to '%s'\n", get_header(&p->initreq, "From"));
20742 pvt_set_needdestroy(p, "Failed to authenticate on PUBLISH");
20743 sip_alreadygone(p);
20744 }
20745 return;
20746 }
20747
20748 if (resp == 501 || resp == 405) {
20749 mark_method_unallowed(&p->allowed_methods, SIP_PUBLISH);
20750 }
20751
20752 if (resp == 200) {
20753 p->authtries = 0;
20754
20755
20756
20757 if (!ast_strlen_zero(etag)) {
20758 ast_copy_string(epa_entry->entity_tag, etag, sizeof(epa_entry->entity_tag));
20759 }
20760
20761
20762
20763
20764 if (epa_entry->static_data->handle_ok) {
20765 epa_entry->static_data->handle_ok(p, req, epa_entry);
20766 }
20767 } else {
20768
20769
20770
20771
20772 if (epa_entry->static_data->handle_error) {
20773 epa_entry->static_data->handle_error(p, resp, req, epa_entry);
20774 }
20775 }
20776 }
20777
20778
20779
20780
20781
20782
20783
20784
20785
20786
20787
20788
20789 static void sip_queue_hangup_cause(struct sip_pvt *p, int cause)
20790 {
20791 struct ast_channel *owner = p->owner;
20792 const char *name = ast_strdupa(owner->name);
20793
20794
20795 ast_channel_ref(owner);
20796 ast_channel_unlock(owner);
20797 sip_pvt_unlock(p);
20798 ast_set_hangupsource(owner, name, 0);
20799 if (cause) {
20800 ast_queue_hangup_with_cause(owner, cause);
20801 } else {
20802 ast_queue_hangup(owner);
20803 }
20804 ast_channel_unref(owner);
20805
20806
20807 owner = sip_pvt_lock_full(p);
20808 if (owner) {
20809 ast_channel_unref(owner);
20810 }
20811 }
20812
20813
20814 static void handle_response_invite(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
20815 {
20816 int outgoing = ast_test_flag(&p->flags[0], SIP_OUTGOING);
20817 int res = 0;
20818 int xmitres = 0;
20819 int reinvite = ast_test_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
20820 char *p_hdrval;
20821 int rtn;
20822 struct ast_party_connected_line connected;
20823 struct ast_set_party_connected_line update_connected;
20824
20825 if (reinvite)
20826 ast_debug(4, "SIP response %d to RE-invite on %s call %s\n", resp, outgoing ? "outgoing" : "incoming", p->callid);
20827 else
20828 ast_debug(4, "SIP response %d to standard invite\n", resp);
20829
20830 if (p->alreadygone) {
20831 ast_debug(1, "Got response on call that is already terminated: %s (ignoring)\n", p->callid);
20832 return;
20833 }
20834
20835
20836
20837 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"));
20838
20839
20840
20841
20842 if (resp > 100 && resp < 200 && resp!=101 && resp != 180 && resp != 181 && resp != 182 && resp != 183)
20843 resp = 183;
20844
20845
20846 if (resp >= 100 && resp < 200 && p->invitestate == INV_CALLING)
20847 p->invitestate = INV_PROCEEDING;
20848
20849
20850 if (resp >= 300 && (p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA ))
20851 p->invitestate = INV_COMPLETED;
20852
20853 if ((resp >= 200 && reinvite)) {
20854 p->ongoing_reinvite = 0;
20855 if (p->reinviteid > -1) {
20856 AST_SCHED_DEL_UNREF(sched, p->reinviteid, dialog_unref(p, "unref dialog for reinvite timeout because of a final response"));
20857 }
20858 }
20859
20860
20861 if ((resp == 200 || resp >= 300) && p->pendinginvite && seqno == p->pendinginvite) {
20862 p->pendinginvite = 0;
20863 }
20864
20865
20866
20867
20868 if (!reinvite) {
20869 set_pvt_allowed_methods(p, req);
20870 }
20871
20872 switch (resp) {
20873 case 100:
20874 case 101:
20875 if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p))
20876 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
20877 check_pendings(p);
20878 break;
20879
20880 case 180:
20881 case 182:
20882 if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p))
20883 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
20884
20885
20886
20887 parse_ok_contact(p, req);
20888 if (!reinvite) {
20889 build_route(p, req, 1, resp);
20890 }
20891 if (!req->ignore && p->owner) {
20892 if (get_rpid(p, req)) {
20893
20894 ast_party_connected_line_init(&connected);
20895 memset(&update_connected, 0, sizeof(update_connected));
20896
20897 update_connected.id.number = 1;
20898 connected.id.number.valid = 1;
20899 connected.id.number.str = (char *) p->cid_num;
20900 connected.id.number.presentation = p->callingpres;
20901
20902 update_connected.id.name = 1;
20903 connected.id.name.valid = 1;
20904 connected.id.name.str = (char *) p->cid_name;
20905 connected.id.name.presentation = p->callingpres;
20906
20907 connected.id.tag = (char *) p->cid_tag;
20908 connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
20909 ast_channel_queue_connected_line_update(p->owner, &connected,
20910 &update_connected);
20911 }
20912 sip_handle_cc(p, req, AST_CC_CCNR);
20913 ast_queue_control(p->owner, AST_CONTROL_RINGING);
20914 if (p->owner->_state != AST_STATE_UP) {
20915 ast_setstate(p->owner, AST_STATE_RINGING);
20916 }
20917 }
20918 if (find_sdp(req)) {
20919 if (p->invitestate != INV_CANCELLED)
20920 p->invitestate = INV_EARLY_MEDIA;
20921 res = process_sdp(p, req, SDP_T38_NONE);
20922 if (!req->ignore && p->owner) {
20923
20924 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
20925 }
20926 ast_rtp_instance_activate(p->rtp);
20927 }
20928 check_pendings(p);
20929 break;
20930
20931 case 181:
20932 if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
20933 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
20934
20935
20936
20937 parse_ok_contact(p, req);
20938 if (!reinvite) {
20939 build_route(p, req, 1, resp);
20940 }
20941 if (!req->ignore && p->owner) {
20942 struct ast_party_redirecting redirecting;
20943 struct ast_set_party_redirecting update_redirecting;
20944
20945 ast_party_redirecting_init(&redirecting);
20946 memset(&update_redirecting, 0, sizeof(update_redirecting));
20947 change_redirecting_information(p, req, &redirecting, &update_redirecting,
20948 FALSE);
20949 ast_channel_queue_redirecting_update(p->owner, &redirecting,
20950 &update_redirecting);
20951 ast_party_redirecting_free(&redirecting);
20952 sip_handle_cc(p, req, AST_CC_CCNR);
20953 }
20954 check_pendings(p);
20955 break;
20956
20957 case 183:
20958 if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
20959 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
20960
20961
20962
20963 parse_ok_contact(p, req);
20964 if (!reinvite) {
20965 build_route(p, req, 1, resp);
20966 }
20967 if (!req->ignore && p->owner) {
20968 if (get_rpid(p, req)) {
20969
20970 ast_party_connected_line_init(&connected);
20971 memset(&update_connected, 0, sizeof(update_connected));
20972
20973 update_connected.id.number = 1;
20974 connected.id.number.valid = 1;
20975 connected.id.number.str = (char *) p->cid_num;
20976 connected.id.number.presentation = p->callingpres;
20977
20978 update_connected.id.name = 1;
20979 connected.id.name.valid = 1;
20980 connected.id.name.str = (char *) p->cid_name;
20981 connected.id.name.presentation = p->callingpres;
20982
20983 connected.id.tag = (char *) p->cid_tag;
20984 connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
20985 ast_channel_queue_connected_line_update(p->owner, &connected,
20986 &update_connected);
20987 }
20988 sip_handle_cc(p, req, AST_CC_CCNR);
20989 }
20990 if (find_sdp(req)) {
20991 if (p->invitestate != INV_CANCELLED)
20992 p->invitestate = INV_EARLY_MEDIA;
20993 res = process_sdp(p, req, SDP_T38_NONE);
20994 if (!req->ignore && p->owner) {
20995
20996 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
20997 }
20998 ast_rtp_instance_activate(p->rtp);
20999 } else {
21000
21001
21002
21003
21004 if (!req->ignore && p->owner) {
21005 ast_queue_control(p->owner, AST_CONTROL_RINGING);
21006 }
21007 }
21008 check_pendings(p);
21009 break;
21010
21011 case 200:
21012 if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
21013 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
21014 p->authtries = 0;
21015 if (find_sdp(req)) {
21016 if ((res = process_sdp(p, req, SDP_T38_ACCEPT)) && !req->ignore) {
21017 if (!reinvite) {
21018
21019
21020 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
21021 p->hangupcause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
21022 if (p->owner) {
21023 p->owner->hangupcause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
21024 sip_queue_hangup_cause(p, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
21025 }
21026 }
21027 }
21028 ast_rtp_instance_activate(p->rtp);
21029 } else if (!reinvite) {
21030 struct ast_sockaddr remote_address = {{0,}};
21031
21032 ast_rtp_instance_get_remote_address(p->rtp, &remote_address);
21033 if (ast_sockaddr_isnull(&remote_address) || (!ast_strlen_zero(p->theirprovtag) && strcmp(p->theirtag, p->theirprovtag))) {
21034 ast_log(LOG_WARNING, "Received response: \"200 OK\" from '%s' without SDP\n", p->relatedpeer->name);
21035 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
21036 ast_rtp_instance_activate(p->rtp);
21037 }
21038 }
21039
21040 if (!req->ignore && p->owner) {
21041 int rpid_changed;
21042
21043 rpid_changed = get_rpid(p, req);
21044 if (rpid_changed || !reinvite) {
21045
21046 ast_party_connected_line_init(&connected);
21047 memset(&update_connected, 0, sizeof(update_connected));
21048 if (rpid_changed
21049 || !ast_strlen_zero(p->cid_num)
21050 || (p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
21051 update_connected.id.number = 1;
21052 connected.id.number.valid = 1;
21053 connected.id.number.str = (char *) p->cid_num;
21054 connected.id.number.presentation = p->callingpres;
21055 }
21056 if (rpid_changed
21057 || !ast_strlen_zero(p->cid_name)
21058 || (p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
21059 update_connected.id.name = 1;
21060 connected.id.name.valid = 1;
21061 connected.id.name.str = (char *) p->cid_name;
21062 connected.id.name.presentation = p->callingpres;
21063 }
21064 if (update_connected.id.number || update_connected.id.name) {
21065 connected.id.tag = (char *) p->cid_tag;
21066 connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
21067 ast_channel_queue_connected_line_update(p->owner, &connected,
21068 &update_connected);
21069 }
21070 }
21071 }
21072
21073
21074
21075
21076 if (outgoing) {
21077 update_call_counter(p, DEC_CALL_RINGING);
21078 parse_ok_contact(p, req);
21079
21080 if (!reinvite) {
21081 build_route(p, req, 1, resp);
21082 }
21083 if(set_address_from_contact(p)) {
21084
21085
21086 if (!p->route && !req->ignore)
21087 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
21088 }
21089
21090 }
21091
21092 if (!req->ignore && p->owner) {
21093 if (!reinvite && !res) {
21094 ast_queue_control(p->owner, AST_CONTROL_ANSWER);
21095 if (sip_cfg.callevents)
21096 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
21097 "Channel: %s\r\nChanneltype: %s\r\nUniqueid: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
21098 p->owner->name, "SIP", p->owner->uniqueid, p->callid, p->fullcontact, p->peername);
21099 } else {
21100 if (p->t38.state == T38_DISABLED) {
21101 ast_queue_control(p->owner, AST_CONTROL_UPDATE_RTP_PEER);
21102 } else {
21103 ast_queue_frame(p->owner, &ast_null_frame);
21104 }
21105 }
21106 } else {
21107
21108
21109
21110 if (!req->ignore)
21111 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
21112 }
21113
21114
21115 if (st_get_mode(p, 0) != SESSION_TIMER_MODE_REFUSE) {
21116 p_hdrval = (char*)get_header(req, "Session-Expires");
21117 if (!ast_strlen_zero(p_hdrval)) {
21118
21119 enum st_refresher_param st_ref_param;
21120 int tmp_st_interval = 0;
21121 rtn = parse_session_expires(p_hdrval, &tmp_st_interval, &st_ref_param);
21122 if (rtn != 0) {
21123 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
21124 } else if (tmp_st_interval < st_get_se(p, FALSE)) {
21125 ast_log(LOG_WARNING, "Got Session-Expires less than local Min-SE in 200 OK, tearing down call\n");
21126 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
21127 }
21128 if (st_ref_param == SESSION_TIMER_REFRESHER_PARAM_UAC) {
21129 p->stimer->st_ref = SESSION_TIMER_REFRESHER_US;
21130 } else if (st_ref_param == SESSION_TIMER_REFRESHER_PARAM_UAS) {
21131 p->stimer->st_ref = SESSION_TIMER_REFRESHER_THEM;
21132 } else {
21133 ast_log(LOG_WARNING, "Unknown refresher on %s\n", p->callid);
21134 }
21135 if (tmp_st_interval) {
21136 p->stimer->st_interval = tmp_st_interval;
21137 }
21138 p->stimer->st_active = TRUE;
21139 p->stimer->st_active_peer_ua = TRUE;
21140 start_session_timer(p);
21141 } else {
21142
21143 if (st_get_mode(p, 0) == SESSION_TIMER_MODE_ORIGINATE) {
21144 p->stimer->st_ref = SESSION_TIMER_REFRESHER_US;
21145 p->stimer->st_active_peer_ua = FALSE;
21146 start_session_timer(p);
21147 }
21148 }
21149 }
21150
21151
21152
21153 p->invitestate = INV_TERMINATED;
21154 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
21155 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, TRUE);
21156 check_pendings(p);
21157 break;
21158
21159 case 407:
21160 case 401:
21161
21162 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
21163 if (p->options)
21164 p->options->auth_type = resp;
21165
21166
21167 ast_string_field_set(p, theirtag, NULL);
21168 if (!req->ignore) {
21169 if (p->authtries < MAX_AUTHTRIES)
21170 p->invitestate = INV_CALLING;
21171 if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, SIP_INVITE, 1)) {
21172 ast_log(LOG_NOTICE, "Failed to authenticate on INVITE to '%s'\n", get_header(&p->initreq, "From"));
21173 pvt_set_needdestroy(p, "failed to authenticate on INVITE");
21174 sip_alreadygone(p);
21175 if (p->owner)
21176 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
21177 }
21178 }
21179 break;
21180
21181 case 403:
21182
21183 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
21184 ast_log(LOG_WARNING, "Received response: \"Forbidden\" from '%s'\n", get_header(&p->initreq, "From"));
21185 if (!req->ignore && p->owner) {
21186 sip_queue_hangup_cause(p, hangup_sip2cause(resp));
21187 }
21188 break;
21189
21190 case 404:
21191 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
21192 if (p->owner && !req->ignore) {
21193 sip_queue_hangup_cause(p, hangup_sip2cause(resp));
21194 }
21195 break;
21196
21197 case 481:
21198
21199 ast_log(LOG_WARNING, "Re-invite to non-existing call leg on other UA. SIP dialog '%s'. Giving up.\n", p->callid);
21200 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
21201 if (p->owner) {
21202 ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
21203 }
21204 break;
21205
21206 case 422:
21207 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
21208 ast_string_field_set(p, theirtag, NULL);
21209 proc_422_rsp(p, req);
21210 break;
21211
21212 case 428:
21213 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
21214 append_history(p, "Identity", "SIP identity is required. Not supported by Asterisk.");
21215 ast_log(LOG_WARNING, "SIP identity required by proxy. SIP dialog '%s'. Giving up.\n", p->callid);
21216 if (p->owner && !req->ignore) {
21217 ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
21218 }
21219 break;
21220
21221 case 487:
21222
21223
21224
21225 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
21226 if (p->owner && !req->ignore) {
21227 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_NORMAL_CLEARING);
21228 append_history(p, "Hangup", "Got 487 on CANCEL request from us. Queued AST hangup request");
21229 } else if (!req->ignore) {
21230 update_call_counter(p, DEC_CALL_LIMIT);
21231 append_history(p, "Hangup", "Got 487 on CANCEL request from us on call without owner. Killing this dialog.");
21232 }
21233 check_pendings(p);
21234 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21235 break;
21236 case 415:
21237 case 488:
21238 case 606:
21239 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
21240 if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
21241 change_t38_state(p, T38_DISABLED);
21242
21243
21244
21245
21246 transmit_reinvite_with_sdp(p, FALSE, FALSE);
21247 } else {
21248
21249 if (p->owner && !req->ignore) {
21250 ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
21251 }
21252 }
21253 break;
21254 case 491:
21255 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
21256 if (p->owner && !req->ignore) {
21257 if (p->owner->_state != AST_STATE_UP) {
21258 ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
21259 } else {
21260
21261
21262
21263 int wait;
21264
21265
21266 if (p->outgoing_call) {
21267 wait = 2100 + ast_random() % 2000;
21268 } else {
21269 wait = ast_random() % 2000;
21270 }
21271 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."));
21272 ast_debug(2, "Reinvite race. Scheduled sip_reinvite_retry in %d secs in handle_response_invite (waitid %d, dialog '%s')\n",
21273 wait, p->waitid, p->callid);
21274 }
21275 }
21276 break;
21277
21278 case 408:
21279 case 405:
21280 case 501:
21281 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
21282 if (p->owner) {
21283 ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
21284 }
21285 break;
21286 }
21287 if (xmitres == XMIT_ERROR)
21288 ast_log(LOG_WARNING, "Could not transmit message in dialog %s\n", p->callid);
21289 }
21290
21291
21292
21293
21294 static void handle_response_notify(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
21295 {
21296 switch (resp) {
21297 case 200:
21298
21299 if (p->owner) {
21300 if (p->refer) {
21301 ast_log(LOG_NOTICE, "Got OK on REFER Notify message\n");
21302 } else {
21303 ast_log(LOG_WARNING, "Notify answer on an owned channel? - %s\n", p->owner->name);
21304 }
21305 } else {
21306 if (p->subscribed == NONE && !p->refer) {
21307 ast_debug(4, "Got 200 accepted on NOTIFY %s\n", p->callid);
21308 pvt_set_needdestroy(p, "received 200 response");
21309 }
21310 if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
21311
21312 ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
21313 cb_extensionstate((char *)p->context, (char *)p->exten, p->laststate, (void *) p);
21314 }
21315 }
21316 break;
21317 case 401:
21318 case 407:
21319 if (!p->notify) {
21320 break;
21321 }
21322 ast_string_field_set(p, theirtag, NULL);
21323 if (ast_strlen_zero(p->authname)) {
21324 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));
21325 pvt_set_needdestroy(p, "unable to authenticate NOTIFY");
21326 }
21327 if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_NOTIFY, 0)) {
21328 ast_log(LOG_NOTICE, "Failed to authenticate on NOTIFY to '%s'\n", get_header(&p->initreq, "From"));
21329 pvt_set_needdestroy(p, "failed to authenticate NOTIFY");
21330 }
21331 break;
21332 case 481:
21333 pvt_set_needdestroy(p, "Received 481 response for NOTIFY");
21334 break;
21335 }
21336 }
21337
21338
21339 static void handle_response_subscribe(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
21340 {
21341 if (p->subscribed == CALL_COMPLETION) {
21342 struct sip_monitor_instance *monitor_instance;
21343
21344 if (resp < 300) {
21345 return;
21346 }
21347
21348
21349 monitor_instance = ao2_callback(sip_monitor_instances, 0,
21350 find_sip_monitor_instance_by_subscription_pvt, p);
21351 if (monitor_instance) {
21352 ast_cc_monitor_failed(monitor_instance->core_id,
21353 monitor_instance->device_name,
21354 "Received error response to our SUBSCRIBE");
21355 }
21356 return;
21357 }
21358
21359 if (p->subscribed != MWI_NOTIFICATION) {
21360 return;
21361 }
21362 if (!p->mwi) {
21363 return;
21364 }
21365
21366 switch (resp) {
21367 case 200:
21368 ast_debug(3, "Got 200 OK on subscription for MWI\n");
21369 set_pvt_allowed_methods(p, req);
21370 if (p->options) {
21371 if (p->options->outboundproxy) {
21372 ao2_ref(p->options->outboundproxy, -1);
21373 }
21374 ast_free(p->options);
21375 p->options = NULL;
21376 }
21377 p->mwi->subscribed = 1;
21378 if ((p->mwi->resub = ast_sched_add(sched, mwi_expiry * 1000, sip_subscribe_mwi_do, ASTOBJ_REF(p->mwi))) < 0) {
21379 ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
21380 }
21381 break;
21382 case 401:
21383 case 407:
21384 ast_string_field_set(p, theirtag, NULL);
21385 if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_SUBSCRIBE, 0)) {
21386 ast_log(LOG_NOTICE, "Failed to authenticate on SUBSCRIBE to '%s'\n", get_header(&p->initreq, "From"));
21387 p->mwi->call = NULL;
21388 ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
21389 pvt_set_needdestroy(p, "failed to authenticate SUBSCRIBE");
21390 }
21391 break;
21392 case 403:
21393 transmit_response_with_date(p, "200 OK", req);
21394 ast_log(LOG_WARNING, "Authentication failed while trying to subscribe for MWI.\n");
21395 p->mwi->call = NULL;
21396 ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
21397 pvt_set_needdestroy(p, "received 403 response");
21398 sip_alreadygone(p);
21399 break;
21400 case 404:
21401 ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side said that a mailbox may not have been configured.\n");
21402 p->mwi->call = NULL;
21403 ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
21404 pvt_set_needdestroy(p, "received 404 response");
21405 break;
21406 case 481:
21407 ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side said that our dialog did not exist.\n");
21408 p->mwi->call = NULL;
21409 ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
21410 pvt_set_needdestroy(p, "received 481 response");
21411 break;
21412 case 500:
21413 case 501:
21414 ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side may have suffered a heart attack.\n");
21415 p->mwi->call = NULL;
21416 ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
21417 pvt_set_needdestroy(p, "received 500/501 response");
21418 break;
21419 }
21420 }
21421
21422
21423
21424
21425 static void handle_response_refer(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
21426 {
21427 enum ast_control_transfer message = AST_TRANSFER_FAILED;
21428
21429
21430 if (!p->refer)
21431 return;
21432
21433 switch (resp) {
21434 case 202:
21435
21436
21437 p->refer->status = REFER_ACCEPTED;
21438
21439 ast_debug(3, "Got 202 accepted on transfer\n");
21440
21441 break;
21442
21443 case 401:
21444 case 407:
21445 if (ast_strlen_zero(p->authname)) {
21446 ast_log(LOG_WARNING, "Asked to authenticate REFER to %s but we have no matching peer or realm auth!\n",
21447 ast_sockaddr_stringify(&p->recv));
21448 if (p->owner) {
21449 ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
21450 }
21451 pvt_set_needdestroy(p, "unable to authenticate REFER");
21452 }
21453 if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_REFER, 0)) {
21454 ast_log(LOG_NOTICE, "Failed to authenticate on REFER to '%s'\n", get_header(&p->initreq, "From"));
21455 p->refer->status = REFER_NOAUTH;
21456 if (p->owner) {
21457 ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
21458 }
21459 pvt_set_needdestroy(p, "failed to authenticate REFER");
21460 }
21461 break;
21462
21463 case 405:
21464
21465
21466 ast_log(LOG_NOTICE, "SIP transfer to %s failed, REFER not allowed. \n", p->refer->refer_to);
21467 pvt_set_needdestroy(p, "received 405 response");
21468 p->refer->status = REFER_FAILED;
21469 if (p->owner) {
21470 ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
21471 }
21472 break;
21473
21474 case 481:
21475
21476
21477
21478
21479 ast_log(LOG_WARNING, "Remote host can't match REFER request to call '%s'. Giving up.\n", p->callid);
21480 if (p->owner)
21481 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
21482 pvt_set_needdestroy(p, "received 481 response");
21483 break;
21484
21485 case 500:
21486 case 501:
21487
21488
21489 ast_log(LOG_NOTICE, "SIP transfer to %s failed, call miserably fails. \n", p->refer->refer_to);
21490 pvt_set_needdestroy(p, "received 500/501 response");
21491 p->refer->status = REFER_FAILED;
21492 if (p->owner) {
21493 ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
21494 }
21495 break;
21496 case 603:
21497 ast_log(LOG_NOTICE, "SIP transfer to %s declined, call miserably fails. \n", p->refer->refer_to);
21498 p->refer->status = REFER_FAILED;
21499 pvt_set_needdestroy(p, "received 603 response");
21500 if (p->owner) {
21501 ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
21502 }
21503 break;
21504 default:
21505
21506
21507
21508
21509 if (resp < 299) {
21510 ast_log(LOG_WARNING, "SIP transfer to %s had unxpected 2xx response (%d), confusion is possible. \n", p->refer->refer_to, resp);
21511 } else {
21512 ast_log(LOG_WARNING, "SIP transfer to %s with response (%d). \n", p->refer->refer_to, resp);
21513 }
21514
21515 p->refer->status = REFER_FAILED;
21516 pvt_set_needdestroy(p, "received failure response");
21517 if (p->owner) {
21518 ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
21519 }
21520 break;
21521 }
21522 }
21523
21524
21525 static int handle_response_register(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
21526 {
21527 int expires, expires_ms;
21528 struct sip_registry *r;
21529 r=p->registry;
21530
21531 switch (resp) {
21532 case 401:
21533 if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
21534 ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s@%s' (Tries %d)\n", p->registry->username, p->registry->hostname, p->authtries);
21535 pvt_set_needdestroy(p, "failed to authenticate REGISTER");
21536 }
21537 break;
21538 case 403:
21539 if (global_reg_retry_403) {
21540 ast_log(LOG_NOTICE, "Treating 403 response to REGISTER as non-fatal for %s@%s\n",
21541 p->registry->username, p->registry->hostname);
21542 ast_string_field_set(r, nonce, "");
21543 ast_string_field_set(p, nonce, "");
21544 break;
21545 }
21546 ast_log(LOG_WARNING, "Forbidden - wrong password on authentication for REGISTER for '%s' to '%s'\n", p->registry->username, p->registry->hostname);
21547 AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 403"));
21548 r->regstate = REG_STATE_NOAUTH;
21549 pvt_set_needdestroy(p, "received 403 response");
21550 break;
21551 case 404:
21552 ast_log(LOG_WARNING, "Got 404 Not found on SIP register to service %s@%s, giving up\n", p->registry->username, p->registry->hostname);
21553 pvt_set_needdestroy(p, "received 404 response");
21554 if (r->call)
21555 r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 404");
21556 r->regstate = REG_STATE_REJECTED;
21557 AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 404"));
21558 break;
21559 case 407:
21560 if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
21561 ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s' (tries '%d')\n", get_header(&p->initreq, "From"), p->authtries);
21562 pvt_set_needdestroy(p, "failed to authenticate REGISTER");
21563 }
21564 break;
21565 case 408:
21566
21567 if (r) {
21568 r->regattempts = 0;
21569 } else {
21570 ast_log(LOG_WARNING, "Got a 408 response to our REGISTER on call %s after we had destroyed the registry object\n", p->callid);
21571 }
21572 break;
21573 case 423:
21574 r->expiry = atoi(get_header(req, "Min-Expires"));
21575 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);
21576 AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 423"));
21577 if (r->call) {
21578 r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 423");
21579 pvt_set_needdestroy(p, "received 423 response");
21580 }
21581 if (r->expiry > max_expiry) {
21582 ast_log(LOG_WARNING, "Required expiration time from %s@%s is too high, giving up\n", p->registry->username, p->registry->hostname);
21583 r->expiry = r->configured_expiry;
21584 r->regstate = REG_STATE_REJECTED;
21585 } else {
21586 r->regstate = REG_STATE_UNREGISTERED;
21587 transmit_register(r, SIP_REGISTER, NULL, NULL);
21588 }
21589 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));
21590 break;
21591 case 479:
21592 ast_log(LOG_WARNING, "Got error 479 on register to %s@%s, giving up (check config)\n", p->registry->username, p->registry->hostname);
21593 pvt_set_needdestroy(p, "received 479 response");
21594 if (r->call)
21595 r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 479");
21596 r->regstate = REG_STATE_REJECTED;
21597 AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 479"));
21598 break;
21599 case 200:
21600 if (!r) {
21601 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));
21602 pvt_set_needdestroy(p, "received erroneous 200 response");
21603 return 0;
21604 }
21605
21606 r->regstate = REG_STATE_REGISTERED;
21607 r->regtime = ast_tvnow();
21608 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));
21609 r->regattempts = 0;
21610 ast_debug(1, "Registration successful\n");
21611 if (r->timeout > -1) {
21612 ast_debug(1, "Cancelling timeout %d\n", r->timeout);
21613 }
21614 AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 200"));
21615 if (r->call)
21616 r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 200");
21617 p->registry = registry_unref(p->registry, "unref registry entry p->registry");
21618
21619
21620 pvt_set_needdestroy(p, "Registration successfull");
21621
21622
21623
21624
21625
21626 expires = 0;
21627
21628
21629 if (!ast_strlen_zero(get_header(req, "Contact"))) {
21630 const char *contact = NULL;
21631 const char *tmptmp = NULL;
21632 int start = 0;
21633 for(;;) {
21634 contact = __get_header(req, "Contact", &start);
21635
21636 if(!ast_strlen_zero(contact)) {
21637 if( (tmptmp=strstr(contact, p->our_contact))) {
21638 contact=tmptmp;
21639 break;
21640 }
21641 } else
21642 break;
21643 }
21644 tmptmp = strcasestr(contact, "expires=");
21645 if (tmptmp) {
21646 if (sscanf(tmptmp + 8, "%30d", &expires) != 1) {
21647 expires = 0;
21648 }
21649 }
21650
21651 }
21652 if (!expires)
21653 expires=atoi(get_header(req, "expires"));
21654 if (!expires)
21655 expires=default_expiry;
21656
21657 expires_ms = expires * 1000;
21658 if (expires <= EXPIRY_GUARD_LIMIT)
21659 expires_ms -= MAX((expires_ms * EXPIRY_GUARD_PCT), EXPIRY_GUARD_MIN);
21660 else
21661 expires_ms -= EXPIRY_GUARD_SECS * 1000;
21662 if (sipdebug)
21663 ast_log(LOG_NOTICE, "Outbound Registration: Expiry for %s is %d sec (Scheduling reregistration in %d s)\n", r->hostname, expires, expires_ms/1000);
21664
21665 r->refresh= (int) expires_ms / 1000;
21666
21667
21668 AST_SCHED_REPLACE_UNREF(r->expire, sched, expires_ms, sip_reregister, r,
21669 registry_unref(_data,"unref in REPLACE del fail"),
21670 registry_unref(r,"unref in REPLACE add fail"),
21671 registry_addref(r,"The Addition side of REPLACE"));
21672 }
21673 return 1;
21674 }
21675
21676
21677 static void handle_response_peerpoke(struct sip_pvt *p, int resp, struct sip_request *req)
21678 {
21679 struct sip_peer *peer = p->relatedpeer ;
21680 int statechanged, is_reachable, was_reachable;
21681 int pingtime = ast_tvdiff_ms(ast_tvnow(), peer->ps);
21682
21683
21684
21685
21686
21687
21688 if (pingtime < 1) {
21689 pingtime = 1;
21690 }
21691
21692 if (!peer->maxms) {
21693 pvt_set_needdestroy(p, "got OPTIONS response but qualify is not enabled");
21694 return;
21695 }
21696
21697
21698
21699
21700
21701 was_reachable = peer->lastms > 0 && peer->lastms <= peer->maxms;
21702 is_reachable = pingtime <= peer->maxms;
21703 statechanged = peer->lastms == 0
21704 || was_reachable != is_reachable;
21705
21706 peer->lastms = pingtime;
21707 peer->call = dialog_unref(peer->call, "unref dialog peer->call");
21708 if (statechanged) {
21709 const char *s = is_reachable ? "Reachable" : "Lagged";
21710 char str_lastms[20];
21711 snprintf(str_lastms, sizeof(str_lastms), "%d", pingtime);
21712
21713 ast_log(LOG_NOTICE, "Peer '%s' is now %s. (%dms / %dms)\n",
21714 peer->name, s, pingtime, peer->maxms);
21715 ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "SIP/%s", peer->name);
21716 if (sip_cfg.peer_rtupdate) {
21717 ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", str_lastms, SENTINEL);
21718 }
21719 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
21720 "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: %s\r\nTime: %d\r\n",
21721 peer->name, s, pingtime);
21722 if (is_reachable && sip_cfg.regextenonqualify)
21723 register_peer_exten(peer, TRUE);
21724 }
21725
21726 pvt_set_needdestroy(p, "got OPTIONS response");
21727
21728
21729 AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
21730 is_reachable ? peer->qualifyfreq : DEFAULT_FREQ_NOTOK,
21731 sip_poke_peer_s, peer,
21732 unref_peer(_data, "removing poke peer ref"),
21733 unref_peer(peer, "removing poke peer ref"),
21734 ref_peer(peer, "adding poke peer ref"));
21735 }
21736
21737
21738
21739
21740
21741
21742
21743
21744 static void handle_response_info(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
21745 {
21746 int sipmethod = SIP_INFO;
21747
21748 switch (resp) {
21749 case 401:
21750 case 407:
21751 ast_log(LOG_WARNING, "Host '%s' requests authentication (%d) for '%s'\n",
21752 ast_sockaddr_stringify(&p->sa), resp, sip_methods[sipmethod].text);
21753 break;
21754 case 405:
21755 case 501:
21756 mark_method_unallowed(&p->allowed_methods, sipmethod);
21757 if (p->relatedpeer) {
21758 mark_method_allowed(&p->relatedpeer->disallowed_methods, sipmethod);
21759 }
21760 ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n",
21761 ast_sockaddr_stringify(&p->sa), sip_methods[sipmethod].text);
21762 break;
21763 default:
21764 if (300 <= resp && resp < 700) {
21765 ast_verb(3, "Got SIP %s response %d \"%s\" back from host '%s'\n",
21766 sip_methods[sipmethod].text, resp, rest, ast_sockaddr_stringify(&p->sa));
21767 }
21768 break;
21769 }
21770 }
21771
21772
21773
21774
21775
21776
21777
21778
21779
21780 static void handle_response_message(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
21781 {
21782 int sipmethod = SIP_MESSAGE;
21783
21784
21785
21786 switch (resp) {
21787 case 401:
21788 case 407:
21789 ast_log(LOG_WARNING, "Host '%s' requests authentication (%d) for '%s'\n",
21790 ast_sockaddr_stringify(&p->sa), resp, sip_methods[sipmethod].text);
21791 break;
21792 case 405:
21793 case 501:
21794 mark_method_unallowed(&p->allowed_methods, sipmethod);
21795 if (p->relatedpeer) {
21796 mark_method_allowed(&p->relatedpeer->disallowed_methods, sipmethod);
21797 }
21798 ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n",
21799 ast_sockaddr_stringify(&p->sa), sip_methods[sipmethod].text);
21800 break;
21801 default:
21802 if (100 <= resp && resp < 200) {
21803
21804 } else if (200 <= resp && resp < 300) {
21805 p->authtries = 0;
21806 } else if (300 <= resp && resp < 700) {
21807 ast_verb(3, "Got SIP %s response %d \"%s\" back from host '%s'\n",
21808 sip_methods[sipmethod].text, resp, rest, ast_sockaddr_stringify(&p->sa));
21809 }
21810 break;
21811 }
21812 }
21813
21814
21815 static void stop_media_flows(struct sip_pvt *p)
21816 {
21817
21818 if (p->rtp)
21819 ast_rtp_instance_stop(p->rtp);
21820 if (p->vrtp)
21821 ast_rtp_instance_stop(p->vrtp);
21822 if (p->trtp)
21823 ast_rtp_instance_stop(p->trtp);
21824 if (p->udptl)
21825 ast_udptl_stop(p->udptl);
21826 }
21827
21828
21829
21830 static void handle_response(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
21831 {
21832 struct ast_channel *owner;
21833 int sipmethod;
21834 const char *c = get_header(req, "Cseq");
21835
21836 char *c_copy = ast_strdupa(c);
21837
21838 const char *msg = ast_skip_blanks(ast_skip_nonblanks(c_copy));
21839
21840 if (!msg)
21841 msg = "";
21842
21843 sipmethod = find_sip_method(msg);
21844
21845 owner = p->owner;
21846 if (owner) {
21847 const char *rp = NULL, *rh = NULL;
21848
21849 owner->hangupcause = 0;
21850 if (ast_test_flag(&p->flags[1], SIP_PAGE2_Q850_REASON) && (rh = get_header(req, "Reason"))) {
21851 rh = ast_skip_blanks(rh);
21852 if (!strncasecmp(rh, "Q.850", 5)) {
21853 rp = strstr(rh, "cause=");
21854 if (rp && sscanf(rp + 6, "%30d", &owner->hangupcause) == 1) {
21855 owner->hangupcause &= 0x7f;
21856 if (req->debug)
21857 ast_verbose("Using Reason header for cause code: %d\n", owner->hangupcause);
21858 }
21859 }
21860 }
21861
21862 if (!owner->hangupcause)
21863 owner->hangupcause = hangup_sip2cause(resp);
21864 }
21865
21866 if (p->socket.type == SIP_TRANSPORT_UDP) {
21867 int ack_res = FALSE;
21868
21869
21870 if ((resp >= 100) && (resp <= 199)) {
21871
21872 if (sipmethod == SIP_INVITE) {
21873 ack_res = __sip_semi_ack(p, seqno, 0, sipmethod);
21874 }
21875 } else {
21876 ack_res = __sip_ack(p, seqno, 0, sipmethod);
21877 }
21878
21879 if (ack_res == FALSE) {
21880
21881 if (sipmethod == SIP_INVITE && resp >= 200) {
21882 transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, resp < 300 ? TRUE: FALSE);
21883 }
21884
21885 append_history(p, "Ignore", "Ignoring this retransmit\n");
21886 return;
21887 }
21888 }
21889
21890
21891 if (!p->owner && sipmethod == SIP_NOTIFY && p->pendinginvite) {
21892 p->pendinginvite = 0;
21893 }
21894
21895
21896 if (ast_strlen_zero(p->theirtag) || (resp >= 200)) {
21897 char tag[128];
21898
21899 gettag(req, "To", tag, sizeof(tag));
21900 ast_string_field_set(p, theirtag, tag);
21901 } else {
21902
21903 ast_string_field_set(p, theirprovtag, p->theirtag);
21904 }
21905
21906
21907
21908
21909
21910
21911
21912
21913
21914
21915
21916
21917
21918
21919
21920
21921 if ((resp == 404 || resp == 408 || resp == 481) && sipmethod == SIP_BYE) {
21922 pvt_set_needdestroy(p, "received 4XX response to a BYE");
21923 return;
21924 }
21925
21926 if (p->relatedpeer && sipmethod == SIP_OPTIONS) {
21927
21928
21929
21930 if (resp != 100)
21931 handle_response_peerpoke(p, resp, req);
21932 } else if (sipmethod == SIP_REFER && resp >= 200) {
21933 handle_response_refer(p, resp, rest, req, seqno);
21934 } else if (sipmethod == SIP_PUBLISH) {
21935
21936
21937
21938 handle_response_publish(p, resp, rest, req, seqno);
21939 } else if (sipmethod == SIP_INFO) {
21940
21941 handle_response_info(p, resp, rest, req, seqno);
21942 } else if (sipmethod == SIP_MESSAGE) {
21943
21944 handle_response_message(p, resp, rest, req, seqno);
21945 } else if (sipmethod == SIP_NOTIFY) {
21946
21947 handle_response_notify(p, resp, rest, req, seqno);
21948 } else if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
21949 switch(resp) {
21950 case 100:
21951 case 101:
21952 case 183:
21953 case 180:
21954 case 182:
21955 case 181:
21956 if (sipmethod == SIP_INVITE)
21957 handle_response_invite(p, resp, rest, req, seqno);
21958 break;
21959 case 200:
21960 p->authtries = 0;
21961 if (sipmethod == SIP_INVITE) {
21962 handle_response_invite(p, resp, rest, req, seqno);
21963 } else if (sipmethod == SIP_REGISTER) {
21964 handle_response_register(p, resp, rest, req, seqno);
21965 } else if (sipmethod == SIP_SUBSCRIBE) {
21966 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
21967 handle_response_subscribe(p, resp, rest, req, seqno);
21968 } else if (sipmethod == SIP_BYE) {
21969 pvt_set_needdestroy(p, "received 200 response");
21970 ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
21971 }
21972 break;
21973 case 401:
21974 case 407:
21975 if (sipmethod == SIP_INVITE)
21976 handle_response_invite(p, resp, rest, req, seqno);
21977 else if (sipmethod == SIP_SUBSCRIBE)
21978 handle_response_subscribe(p, resp, rest, req, seqno);
21979 else if (p->registry && sipmethod == SIP_REGISTER)
21980 handle_response_register(p, resp, rest, req, seqno);
21981 else if (sipmethod == SIP_UPDATE) {
21982 handle_response_update(p, resp, rest, req, seqno);
21983 } else if (sipmethod == SIP_BYE) {
21984 if (p->options)
21985 p->options->auth_type = resp;
21986 if (ast_strlen_zero(p->authname)) {
21987 ast_log(LOG_WARNING, "Asked to authenticate %s, to %s but we have no matching peer!\n",
21988 msg, ast_sockaddr_stringify(&p->recv));
21989 pvt_set_needdestroy(p, "unable to authenticate BYE");
21990 } else if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp, sipmethod, 0)) {
21991 ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
21992 pvt_set_needdestroy(p, "failed to authenticate BYE");
21993 }
21994 } else {
21995 ast_log(LOG_WARNING, "Got authentication request (%d) on %s to '%s'\n", resp, sip_methods[sipmethod].text, get_header(req, "To"));
21996 pvt_set_needdestroy(p, "received 407 response");
21997 }
21998 break;
21999 case 403:
22000 if (sipmethod == SIP_INVITE)
22001 handle_response_invite(p, resp, rest, req, seqno);
22002 else if (sipmethod == SIP_SUBSCRIBE)
22003 handle_response_subscribe(p, resp, rest, req, seqno);
22004 else if (p->registry && sipmethod == SIP_REGISTER)
22005 handle_response_register(p, resp, rest, req, seqno);
22006 else {
22007 ast_log(LOG_WARNING, "Forbidden - maybe wrong password on authentication for %s\n", msg);
22008 pvt_set_needdestroy(p, "received 403 response");
22009 }
22010 break;
22011 case 404:
22012 if (p->registry && sipmethod == SIP_REGISTER)
22013 handle_response_register(p, resp, rest, req, seqno);
22014 else if (sipmethod == SIP_INVITE)
22015 handle_response_invite(p, resp, rest, req, seqno);
22016 else if (sipmethod == SIP_SUBSCRIBE)
22017 handle_response_subscribe(p, resp, rest, req, seqno);
22018 else if (owner)
22019 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
22020 break;
22021 case 423:
22022 if (sipmethod == SIP_REGISTER)
22023 handle_response_register(p, resp, rest, req, seqno);
22024 break;
22025 case 408:
22026 if (sipmethod == SIP_INVITE)
22027 handle_response_invite(p, resp, rest, req, seqno);
22028 else if (sipmethod == SIP_REGISTER)
22029 handle_response_register(p, resp, rest, req, seqno);
22030 else if (sipmethod == SIP_BYE) {
22031 pvt_set_needdestroy(p, "received 408 response");
22032 ast_debug(4, "Got timeout on bye. Thanks for the answer. Now, kill this call\n");
22033 } else {
22034 if (owner)
22035 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
22036 pvt_set_needdestroy(p, "received 408 response");
22037 }
22038 break;
22039
22040 case 428:
22041 case 422:
22042 if (sipmethod == SIP_INVITE) {
22043 handle_response_invite(p, resp, rest, req, seqno);
22044 }
22045 break;
22046
22047 case 481:
22048 if (sipmethod == SIP_INVITE) {
22049 handle_response_invite(p, resp, rest, req, seqno);
22050 } else if (sipmethod == SIP_SUBSCRIBE) {
22051 handle_response_subscribe(p, resp, rest, req, seqno);
22052 } else if (sipmethod == SIP_BYE) {
22053
22054
22055 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
22056 } else if (sipmethod == SIP_CANCEL) {
22057
22058
22059 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
22060 } else {
22061 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
22062
22063 }
22064 break;
22065 case 487:
22066 if (sipmethod == SIP_INVITE)
22067 handle_response_invite(p, resp, rest, req, seqno);
22068 break;
22069 case 415:
22070 case 488:
22071 case 606:
22072 if (sipmethod == SIP_INVITE)
22073 handle_response_invite(p, resp, rest, req, seqno);
22074 break;
22075 case 491:
22076 if (sipmethod == SIP_INVITE)
22077 handle_response_invite(p, resp, rest, req, seqno);
22078 else {
22079 ast_debug(1, "Got 491 on %s, unsupported. Call ID %s\n", sip_methods[sipmethod].text, p->callid);
22080 pvt_set_needdestroy(p, "received 491 response");
22081 }
22082 break;
22083 case 405:
22084 case 501:
22085 mark_method_unallowed(&p->allowed_methods, sipmethod);
22086 if (p->relatedpeer) {
22087 mark_method_allowed(&p->relatedpeer->disallowed_methods, sipmethod);
22088 }
22089 if (sipmethod == SIP_INVITE)
22090 handle_response_invite(p, resp, rest, req, seqno);
22091 else
22092 ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n", ast_sockaddr_stringify(&p->sa), msg);
22093 break;
22094 default:
22095 if ((resp >= 300) && (resp < 700)) {
22096
22097 if ((resp != 487))
22098 ast_verb(3, "Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_sockaddr_stringify(&p->sa));
22099
22100 if (sipmethod == SIP_INVITE)
22101 stop_media_flows(p);
22102
22103
22104 switch(resp) {
22105 case 300:
22106 case 301:
22107 case 302:
22108 case 305:
22109 if (p->owner) {
22110 struct ast_party_redirecting redirecting;
22111 struct ast_set_party_redirecting update_redirecting;
22112
22113 ast_party_redirecting_init(&redirecting);
22114 memset(&update_redirecting, 0, sizeof(update_redirecting));
22115 change_redirecting_information(p, req, &redirecting,
22116 &update_redirecting, TRUE);
22117 ast_channel_set_redirecting(p->owner, &redirecting,
22118 &update_redirecting);
22119 ast_party_redirecting_free(&redirecting);
22120 }
22121
22122 case 486:
22123 case 600:
22124 case 603:
22125 if (p->owner) {
22126 sip_handle_cc(p, req, AST_CC_CCBS);
22127 ast_queue_control(p->owner, AST_CONTROL_BUSY);
22128 }
22129 break;
22130 case 482:
22131 case 480:
22132 case 404:
22133 case 410:
22134 case 400:
22135 case 500:
22136 if (sipmethod == SIP_SUBSCRIBE) {
22137 handle_response_subscribe(p, resp, rest, req, seqno);
22138 break;
22139 }
22140
22141 case 502:
22142 case 503:
22143 case 504:
22144 if (owner)
22145 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
22146 break;
22147 case 484:
22148 if (owner && sipmethod != SIP_BYE) {
22149 switch (ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP)) {
22150 case SIP_PAGE2_ALLOWOVERLAP_YES:
22151 ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
22152 break;
22153 default:
22154 ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(404));
22155 break;
22156 }
22157 }
22158 break;
22159 default:
22160
22161 if (owner && sipmethod != SIP_BYE)
22162 ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
22163 break;
22164 }
22165
22166 if (sipmethod == SIP_INVITE)
22167 transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
22168 sip_alreadygone(p);
22169 if (!p->owner) {
22170 pvt_set_needdestroy(p, "transaction completed");
22171 }
22172 } else if ((resp >= 100) && (resp < 200)) {
22173 if (sipmethod == SIP_INVITE) {
22174 if (!req->ignore && sip_cancel_destroy(p))
22175 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
22176 if (find_sdp(req))
22177 process_sdp(p, req, SDP_T38_NONE);
22178 if (p->owner) {
22179
22180 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
22181 }
22182 }
22183 } else
22184 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));
22185 }
22186 } else {
22187
22188
22189 if (req->debug)
22190 ast_verbose("SIP Response message for INCOMING dialog %s arrived\n", msg);
22191
22192 if (sipmethod == SIP_INVITE && resp == 200) {
22193
22194
22195 char tag[128];
22196
22197 gettag(req, "To", tag, sizeof(tag));
22198 ast_string_field_set(p, theirtag, tag);
22199 }
22200
22201 switch(resp) {
22202 case 200:
22203 if (sipmethod == SIP_INVITE) {
22204 handle_response_invite(p, resp, rest, req, seqno);
22205 } else if (sipmethod == SIP_CANCEL) {
22206 ast_debug(1, "Got 200 OK on CANCEL\n");
22207
22208
22209 } else if (sipmethod == SIP_BYE) {
22210 pvt_set_needdestroy(p, "transaction completed");
22211 }
22212 break;
22213 case 401:
22214 case 407:
22215 if (sipmethod == SIP_INVITE)
22216 handle_response_invite(p, resp, rest, req, seqno);
22217 else if (sipmethod == SIP_BYE) {
22218 if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, sipmethod, 0)) {
22219 ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
22220 pvt_set_needdestroy(p, "failed to authenticate BYE");
22221 }
22222 }
22223 break;
22224 case 481:
22225 if (sipmethod == SIP_INVITE) {
22226
22227 handle_response_invite(p, resp, rest, req, seqno);
22228 } else if (sipmethod == SIP_BYE) {
22229 pvt_set_needdestroy(p, "received 481 response");
22230 } else if (sipdebug) {
22231 ast_debug(1, "Remote host can't match request %s to call '%s'. Giving up\n", sip_methods[sipmethod].text, p->callid);
22232 }
22233 break;
22234 case 501:
22235 if (sipmethod == SIP_INVITE)
22236 handle_response_invite(p, resp, rest, req, seqno);
22237 break;
22238 default:
22239 if ((resp >= 100) && (resp < 200)) {
22240 if (sipmethod == SIP_INVITE) {
22241 if (!req->ignore && sip_cancel_destroy(p))
22242 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
22243 }
22244 }
22245 if ((resp >= 300) && (resp < 700)) {
22246 if ((resp != 487))
22247 ast_verb(3, "Incoming call: Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_sockaddr_stringify(&p->sa));
22248 switch(resp) {
22249 case 415:
22250 case 488:
22251 case 603:
22252 case 500:
22253 case 502:
22254 case 503:
22255 case 504:
22256
22257
22258 if (sipmethod == SIP_INVITE && sip_cancel_destroy(p))
22259 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
22260 break;
22261 }
22262 }
22263 break;
22264 }
22265 }
22266 }
22267
22268
22269
22270
22271
22272
22273
22274 static void *sip_park_thread(void *stuff)
22275 {
22276 struct ast_channel *transferee, *transferer;
22277 struct sip_pvt *transferer_pvt;
22278 struct sip_dual *d;
22279 int ext;
22280 int res;
22281
22282 d = stuff;
22283 transferee = d->chan1;
22284 transferer = d->chan2;
22285 transferer_pvt = transferer->tech_pvt;
22286
22287 ast_debug(4, "SIP Park: Transferer channel %s, Transferee %s\n", transferer->name, transferee->name);
22288
22289 res = ast_park_call_exten(transferee, transferer, d->park_exten, d->park_context, 0, &ext);
22290
22291 #ifdef WHEN_WE_KNOW_THAT_THE_CLIENT_SUPPORTS_MESSAGE
22292 if (res) {
22293 transmit_message_with_text(transferer_pvt, "Unable to park call.\n");
22294 } else {
22295
22296 sprintf(buf, "Call parked on extension '%d'", ext);
22297 transmit_message_with_text(transferer_pvt, buf);
22298 }
22299 #endif
22300
22301
22302
22303 ast_set_flag(&transferer_pvt->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
22304 if (!res) {
22305
22306 append_history(transferer_pvt, "SIPpark", "Parked call on %d", ext);
22307 transmit_notify_with_sipfrag(transferer_pvt, d->seqno, "200 OK", TRUE);
22308 transferer->hangupcause = AST_CAUSE_NORMAL_CLEARING;
22309 ast_debug(1, "SIP Call parked on extension '%d'\n", ext);
22310 } else {
22311 transmit_notify_with_sipfrag(transferer_pvt, d->seqno, "503 Service Unavailable", TRUE);
22312 append_history(transferer_pvt, "SIPpark", "Parking failed\n");
22313 ast_log(AST_LOG_NOTICE, "SIP Call parked failed for %s\n", transferee->name);
22314 ast_hangup(transferee);
22315 }
22316 ast_hangup(transferer);
22317 deinit_req(&d->req);
22318 ast_free(d->park_exten);
22319 ast_free(d->park_context);
22320 ast_free(d);
22321 return NULL;
22322 }
22323
22324
22325 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)
22326 {
22327 struct sip_dual *d;
22328 struct ast_channel *transferee, *transferer;
22329 pthread_t th;
22330
22331 transferee = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan1->accountcode, chan1->exten, chan1->context, chan1->linkedid, chan1->amaflags, "Parking/%s", chan1->name);
22332 transferer = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan2->accountcode, chan2->exten, chan2->context, chan2->linkedid, chan2->amaflags, "SIPPeer/%s", chan2->name);
22333 d = ast_calloc(1, sizeof(*d));
22334 if (!transferee || !transferer || !d) {
22335 if (transferee) {
22336 ast_hangup(transferee);
22337 }
22338 if (transferer) {
22339 ast_hangup(transferer);
22340 }
22341 ast_free(d);
22342 return -1;
22343 }
22344 d->park_exten = ast_strdup(park_exten);
22345 d->park_context = ast_strdup(park_context);
22346 if (!d->park_exten || !d->park_context) {
22347 ast_hangup(transferee);
22348 ast_hangup(transferer);
22349 ast_free(d->park_exten);
22350 ast_free(d->park_context);
22351 ast_free(d);
22352 return -1;
22353 }
22354
22355
22356 transferee->readformat = chan1->readformat;
22357 transferee->writeformat = chan1->writeformat;
22358
22359
22360 if (ast_channel_masquerade(transferee, chan1)) {
22361 ast_hangup(transferee);
22362 ast_hangup(transferer);
22363 ast_free(d->park_exten);
22364 ast_free(d->park_context);
22365 ast_free(d);
22366 return -1;
22367 }
22368
22369
22370 ast_copy_string(transferee->context, chan1->context, sizeof(transferee->context));
22371 ast_copy_string(transferee->exten, chan1->exten, sizeof(transferee->exten));
22372 transferee->priority = chan1->priority;
22373
22374 ast_do_masquerade(transferee);
22375
22376
22377
22378
22379
22380 transferer->readformat = chan2->readformat;
22381 transferer->writeformat = chan2->writeformat;
22382 ast_string_field_set(transferer, parkinglot, chan2->parkinglot);
22383
22384
22385 if (ast_channel_masquerade(transferer, chan2)) {
22386 ast_hangup(transferee);
22387 ast_hangup(transferer);
22388 ast_free(d->park_exten);
22389 ast_free(d->park_context);
22390 ast_free(d);
22391 return -1;
22392 }
22393
22394
22395 ast_copy_string(transferer->context, chan2->context, sizeof(transferer->context));
22396 ast_copy_string(transferer->exten, chan2->exten, sizeof(transferer->exten));
22397 transferer->priority = chan2->priority;
22398
22399 ast_do_masquerade(transferer);
22400
22401
22402 copy_request(&d->req, req);
22403 d->chan1 = transferee;
22404 d->chan2 = transferer;
22405 d->seqno = seqno;
22406 if (ast_pthread_create_detached_background(&th, NULL, sip_park_thread, d) < 0) {
22407
22408 ast_hangup(transferer);
22409 ast_hangup(transferee);
22410 deinit_req(&d->req);
22411 ast_free(d->park_exten);
22412 ast_free(d->park_context);
22413 ast_free(d);
22414
22415 return -1;
22416 }
22417 return 0;
22418 }
22419
22420
22421
22422
22423
22424 static void *sip_pickup_thread(void *stuff)
22425 {
22426 struct ast_channel *chan;
22427 chan = stuff;
22428
22429 if (ast_pickup_call(chan)) {
22430 chan->hangupcause = AST_CAUSE_CALL_REJECTED;
22431 } else {
22432 chan->hangupcause = AST_CAUSE_NORMAL_CLEARING;
22433 }
22434 ast_hangup(chan);
22435 ast_channel_unref(chan);
22436 chan = NULL;
22437 return NULL;
22438 }
22439
22440
22441
22442
22443 static int sip_pickup(struct ast_channel *chan)
22444 {
22445 pthread_t threadid;
22446
22447 ast_channel_ref(chan);
22448
22449 if (ast_pthread_create_detached_background(&threadid, NULL, sip_pickup_thread, chan)) {
22450 ast_debug(1, "Unable to start Group pickup thread on channel %s\n", chan->name);
22451 ast_channel_unref(chan);
22452 return -1;
22453 }
22454 ast_debug(1, "Started Group pickup thread on channel %s\n", chan->name);
22455 return 0;
22456 }
22457
22458
22459
22460
22461
22462 static void ast_quiet_chan(struct ast_channel *chan)
22463 {
22464 if (chan && chan->_state == AST_STATE_UP) {
22465 if (ast_test_flag(chan, AST_FLAG_MOH))
22466 ast_moh_stop(chan);
22467 else if (chan->generatordata)
22468 ast_deactivate_generator(chan);
22469 }
22470 }
22471
22472
22473
22474 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target)
22475 {
22476 int res = 0;
22477 struct ast_channel *peera = NULL,
22478 *peerb = NULL,
22479 *peerc = NULL,
22480 *peerd = NULL;
22481
22482
22483
22484
22485 ast_debug(4, "Sip transfer:--------------------\n");
22486 if (transferer->chan1)
22487 ast_debug(4, "-- Transferer to PBX channel: %s State %s\n", transferer->chan1->name, ast_state2str(transferer->chan1->_state));
22488 else
22489 ast_debug(4, "-- No transferer first channel - odd??? \n");
22490 if (target->chan1)
22491 ast_debug(4, "-- Transferer to PBX second channel (target): %s State %s\n", target->chan1->name, ast_state2str(target->chan1->_state));
22492 else
22493 ast_debug(4, "-- No target first channel ---\n");
22494 if (transferer->chan2)
22495 ast_debug(4, "-- Bridged call to transferee: %s State %s\n", transferer->chan2->name, ast_state2str(transferer->chan2->_state));
22496 else
22497 ast_debug(4, "-- No bridged call to transferee\n");
22498 if (target->chan2)
22499 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)");
22500 else
22501 ast_debug(4, "-- No target second channel ---\n");
22502 ast_debug(4, "-- END Sip transfer:--------------------\n");
22503 if (transferer->chan2) {
22504 peera = transferer->chan1;
22505 peerb = target->chan1;
22506 peerc = transferer->chan2;
22507 peerd = target->chan2;
22508 ast_debug(3, "SIP transfer: Four channels to handle\n");
22509 } else if (target->chan2) {
22510 peera = target->chan1;
22511 peerb = transferer->chan1;
22512 peerc = target->chan2;
22513 peerd = transferer->chan2;
22514 ast_debug(3, "SIP transfer: Three channels to handle\n");
22515 }
22516
22517 if (peera && peerb && peerc && (peerb != peerc)) {
22518 ast_quiet_chan(peera);
22519
22520
22521
22522 ast_quiet_chan(peerc);
22523 if (peerd)
22524 ast_quiet_chan(peerd);
22525
22526 ast_debug(4, "SIP transfer: trying to masquerade %s into %s\n", peerc->name, peerb->name);
22527 if (ast_channel_masquerade(peerb, peerc)) {
22528 ast_log(LOG_WARNING, "Failed to masquerade %s into %s\n", peerb->name, peerc->name);
22529 res = -1;
22530 } else
22531 ast_debug(4, "SIP transfer: Succeeded to masquerade channels.\n");
22532 return res;
22533 } else {
22534 ast_log(LOG_NOTICE, "SIP Transfer attempted with no appropriate bridged calls to transfer\n");
22535 if (transferer->chan1)
22536 ast_softhangup_nolock(transferer->chan1, AST_SOFTHANGUP_DEV);
22537 if (target->chan1)
22538 ast_softhangup_nolock(target->chan1, AST_SOFTHANGUP_DEV);
22539 return -1;
22540 }
22541 return 0;
22542 }
22543
22544
22545
22546
22547
22548
22549 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize)
22550 {
22551 const char *thetag;
22552
22553 if (!tagbuf)
22554 return NULL;
22555 tagbuf[0] = '\0';
22556 thetag = get_header(req, header);
22557 thetag = strcasestr(thetag, ";tag=");
22558 if (thetag) {
22559 thetag += 5;
22560 ast_copy_string(tagbuf, thetag, tagbufsize);
22561 return strsep(&tagbuf, ";");
22562 }
22563 return NULL;
22564 }
22565
22566 static int handle_cc_notify(struct sip_pvt *pvt, struct sip_request *req)
22567 {
22568 struct sip_monitor_instance *monitor_instance = ao2_callback(sip_monitor_instances, 0,
22569 find_sip_monitor_instance_by_subscription_pvt, pvt);
22570 const char *status = get_body(req, "cc-state", ':');
22571 struct cc_epa_entry *cc_entry;
22572 char *uri;
22573
22574 if (!monitor_instance) {
22575 transmit_response(pvt, "400 Bad Request", req);
22576 return -1;
22577 }
22578
22579 if (ast_strlen_zero(status)) {
22580 ao2_ref(monitor_instance, -1);
22581 transmit_response(pvt, "400 Bad Request", req);
22582 return -1;
22583 }
22584
22585 if (!strcmp(status, "queued")) {
22586
22587
22588
22589
22590 ast_cc_monitor_request_acked(monitor_instance->core_id, "SIP endpoint %s accepted request", monitor_instance->device_name);
22591 transmit_response(pvt, "200 OK", req);
22592 ao2_ref(monitor_instance, -1);
22593 return 0;
22594 }
22595
22596
22597 uri = get_body(req, "cc-URI", ':');
22598 if (ast_strlen_zero(uri)) {
22599 uri = get_in_brackets((char *)get_header(req, "From"));
22600 }
22601
22602 ast_string_field_set(monitor_instance, notify_uri, uri);
22603 if (monitor_instance->suspension_entry) {
22604 cc_entry = monitor_instance->suspension_entry->instance_data;
22605 if (cc_entry->current_state == CC_CLOSED) {
22606
22607
22608
22609
22610
22611 construct_pidf_body(CC_CLOSED, monitor_instance->suspension_entry->body,
22612 sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
22613 transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_INITIAL, monitor_instance->notify_uri);
22614 } else {
22615 ast_cc_monitor_callee_available(monitor_instance->core_id, "SIP monitored callee has become available");
22616 }
22617 } else {
22618 ast_cc_monitor_callee_available(monitor_instance->core_id, "SIP monitored callee has become available");
22619 }
22620 ao2_ref(monitor_instance, -1);
22621 transmit_response(pvt, "200 OK", req);
22622
22623 return 0;
22624 }
22625
22626
22627 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e)
22628 {
22629
22630
22631 int res = 0;
22632 const char *event = get_header(req, "Event");
22633 char *sep;
22634
22635 if( (sep = strchr(event, ';')) ) {
22636 *sep++ = '\0';
22637 }
22638
22639 if (sipdebug)
22640 ast_debug(2, "Got NOTIFY Event: %s\n", event);
22641
22642 if (!strcmp(event, "refer")) {
22643
22644
22645
22646
22647
22648 char buf[1024];
22649 char *cmd, *code;
22650 int respcode;
22651 int success = TRUE;
22652
22653
22654
22655
22656
22657
22658
22659
22660 if (strncasecmp(get_header(req, "Content-Type"), "message/sipfrag", strlen("message/sipfrag"))) {
22661
22662 transmit_response(p, "400 Bad request", req);
22663 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22664 return -1;
22665 }
22666
22667
22668 if (get_msg_text(buf, sizeof(buf), req)) {
22669 ast_log(LOG_WARNING, "Unable to retrieve attachment from NOTIFY %s\n", p->callid);
22670 transmit_response(p, "400 Bad request", req);
22671 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22672 return -1;
22673 }
22674
22675
22676
22677
22678
22679
22680
22681
22682
22683
22684
22685
22686
22687
22688
22689
22690
22691
22692
22693
22694
22695 ast_debug(3, "* SIP Transfer NOTIFY Attachment: \n---%s\n---\n", buf);
22696 cmd = ast_skip_blanks(buf);
22697 code = cmd;
22698
22699 while(*code && (*code > 32)) {
22700 code++;
22701 }
22702 *code++ = '\0';
22703 code = ast_skip_blanks(code);
22704 sep = code;
22705 sep++;
22706 while(*sep && (*sep > 32)) {
22707 sep++;
22708 }
22709 *sep++ = '\0';
22710 respcode = atoi(code);
22711 switch (respcode) {
22712 case 200:
22713
22714 break;
22715 case 301:
22716 case 302:
22717
22718 success = FALSE;
22719 break;
22720 case 503:
22721 case 603:
22722
22723 success = FALSE;
22724 break;
22725 case 0:
22726
22727 ast_log(LOG_NOTICE, "Error parsing sipfrag in NOTIFY in response to REFER.\n");
22728 success = FALSE;
22729 break;
22730 default:
22731 if (respcode < 200) {
22732
22733 success = -1;
22734 } else {
22735 ast_log(LOG_NOTICE, "Got unknown code '%d' in NOTIFY in response to REFER.\n", respcode);
22736 success = FALSE;
22737 }
22738 break;
22739 }
22740 if (success == FALSE) {
22741 ast_log(LOG_NOTICE, "Transfer failed. Sorry. Nothing further to do with this call\n");
22742 }
22743
22744 if (p->owner && success != -1) {
22745 enum ast_control_transfer message = success ? AST_TRANSFER_SUCCESS : AST_TRANSFER_FAILED;
22746 ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
22747 }
22748
22749 transmit_response(p, "200 OK", req);
22750 } else if (!strcmp(event, "message-summary")) {
22751 const char *mailbox = NULL;
22752 char *c = ast_strdupa(get_body(req, "Voice-Message", ':'));
22753
22754 if (!p->mwi) {
22755 struct sip_peer *peer = find_peer(NULL, &p->recv, TRUE, FINDPEERS, FALSE, p->socket.type);
22756
22757 if (peer) {
22758 mailbox = ast_strdupa(peer->unsolicited_mailbox);
22759 unref_peer(peer, "removing unsolicited mwi ref");
22760 }
22761 } else {
22762 mailbox = p->mwi->mailbox;
22763 }
22764
22765 if (!ast_strlen_zero(mailbox) && !ast_strlen_zero(c)) {
22766 char *old = strsep(&c, " ");
22767 char *new = strsep(&old, "/");
22768 struct ast_event *event;
22769
22770 if ((event = ast_event_new(AST_EVENT_MWI,
22771 AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox,
22772 AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, "SIP_Remote",
22773 AST_EVENT_IE_NEWMSGS, AST_EVENT_IE_PLTYPE_UINT, atoi(new),
22774 AST_EVENT_IE_OLDMSGS, AST_EVENT_IE_PLTYPE_UINT, atoi(old),
22775 AST_EVENT_IE_END))) {
22776 ast_event_queue_and_cache(event);
22777 }
22778 transmit_response(p, "200 OK", req);
22779 } else {
22780 transmit_response(p, "489 Bad event", req);
22781 res = -1;
22782 }
22783 } else if (!strcmp(event, "keep-alive")) {
22784
22785
22786 transmit_response(p, "200 OK", req);
22787 } else if (!strcmp(event, "call-completion")) {
22788 res = handle_cc_notify(p, req);
22789 } else {
22790
22791 transmit_response(p, "489 Bad event", req);
22792 res = -1;
22793 }
22794
22795 if (!p->lastinvite)
22796 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22797
22798 return res;
22799 }
22800
22801
22802
22803
22804 static int handle_request_options(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e)
22805 {
22806 const char *msg;
22807 enum sip_get_dest_result gotdest;
22808 int res;
22809
22810 if (p->lastinvite) {
22811
22812 transmit_response_with_allow(p, "200 OK", req, 0);
22813 return 0;
22814 }
22815
22816 if (sip_cfg.auth_options_requests) {
22817
22818 copy_request(&p->initreq, req);
22819 set_pvt_allowed_methods(p, req);
22820 res = check_user(p, req, SIP_OPTIONS, e, XMIT_UNRELIABLE, addr);
22821 if (res == AUTH_CHALLENGE_SENT) {
22822 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22823 return 0;
22824 }
22825 if (res < 0) {
22826 ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", get_header(req, "From"));
22827 transmit_response(p, "403 Forbidden", req);
22828 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22829 return 0;
22830 }
22831 }
22832
22833
22834 gotdest = get_destination(p, req, NULL);
22835 build_contact(p);
22836
22837 if (ast_strlen_zero(p->context))
22838 ast_string_field_set(p, context, sip_cfg.default_context);
22839
22840 if (ast_shutting_down()) {
22841 msg = "503 Unavailable";
22842 } else {
22843 msg = "404 Not Found";
22844 switch (gotdest) {
22845 case SIP_GET_DEST_INVALID_URI:
22846 msg = "416 Unsupported URI scheme";
22847 break;
22848 case SIP_GET_DEST_EXTEN_MATCHMORE:
22849 case SIP_GET_DEST_REFUSED:
22850 case SIP_GET_DEST_EXTEN_NOT_FOUND:
22851
22852 break;
22853 case SIP_GET_DEST_EXTEN_FOUND:
22854 msg = "200 OK";
22855 break;
22856 }
22857 }
22858 transmit_response_with_allow(p, msg, req, 0);
22859
22860
22861
22862 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22863
22864 return 0;
22865 }
22866
22867
22868
22869
22870
22871
22872
22873
22874
22875
22876
22877
22878
22879 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, uint32_t seqno, struct ast_sockaddr *addr, int *nounlock)
22880 {
22881 int earlyreplace = 0;
22882 int oneleggedreplace = 0;
22883 struct ast_channel *c = p->owner;
22884 struct ast_channel *replacecall = p->refer->refer_call->owner;
22885 struct ast_channel *targetcall;
22886
22887
22888 if (replacecall->_state == AST_STATE_RING)
22889 earlyreplace = 1;
22890
22891
22892 if (!(targetcall = ast_bridged_channel(replacecall))) {
22893
22894 if (!earlyreplace) {
22895 ast_debug(2, " Attended transfer attempted to replace call with no bridge (maybe ringing). Channel %s!\n", replacecall->name);
22896 oneleggedreplace = 1;
22897 }
22898 }
22899 if (targetcall && targetcall->_state == AST_STATE_RINGING)
22900 ast_debug(4, "SIP transfer: Target channel is in ringing state\n");
22901
22902 if (targetcall)
22903 ast_debug(4, "SIP transfer: Invite Replace incoming channel should bridge to channel %s while hanging up channel %s\n", targetcall->name, replacecall->name);
22904 else
22905 ast_debug(4, "SIP transfer: Invite Replace incoming channel should replace and hang up channel %s (one call leg)\n", replacecall->name);
22906
22907 if (req->ignore) {
22908 ast_log(LOG_NOTICE, "Ignoring this INVITE with replaces in a stupid way.\n");
22909
22910
22911
22912 transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE, FALSE);
22913
22914 if (c) {
22915 *nounlock = 1;
22916 ast_channel_unlock(c);
22917 }
22918 ast_channel_unlock(replacecall);
22919 sip_pvt_unlock(p->refer->refer_call);
22920 return 1;
22921 }
22922 if (!c) {
22923
22924 ast_log(LOG_ERROR, "Unable to create new channel. Invite/replace failed.\n");
22925 transmit_response_reliable(p, "503 Service Unavailable", req);
22926 append_history(p, "Xfer", "INVITE/Replace Failed. No new channel.");
22927 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22928 ast_channel_unlock(replacecall);
22929 sip_pvt_unlock(p->refer->refer_call);
22930 return 1;
22931 }
22932 append_history(p, "Xfer", "INVITE/Replace received");
22933
22934
22935
22936
22937
22938
22939
22940
22941
22942
22943
22944 transmit_response(p, "100 Trying", req);
22945 ast_setstate(c, AST_STATE_RING);
22946
22947
22948
22949
22950
22951 transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE, FALSE);
22952
22953 ast_setstate(c, AST_STATE_UP);
22954
22955
22956 ast_quiet_chan(replacecall);
22957 ast_quiet_chan(targetcall);
22958 ast_debug(4, "Invite/Replaces: preparing to masquerade %s into %s\n", c->name, replacecall->name);
22959
22960
22961 if (! earlyreplace && ! oneleggedreplace )
22962 ast_set_flag(&p->refer->refer_call->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
22963
22964
22965 if(ast_channel_masquerade(replacecall, c))
22966 ast_log(LOG_ERROR, "Failed to masquerade C into Replacecall\n");
22967 else
22968 ast_debug(4, "Invite/Replaces: Going to masquerade %s into %s\n", c->name, replacecall->name);
22969
22970
22971
22972
22973
22974 ast_channel_ref(c);
22975 ast_channel_unlock(replacecall);
22976 ast_channel_unlock(c);
22977 sip_pvt_unlock(p->refer->refer_call);
22978 sip_pvt_unlock(p);
22979 if (ast_do_masquerade(replacecall)) {
22980 ast_log(LOG_WARNING, "Failed to perform masquerade with INVITE replaces\n");
22981 }
22982 if (earlyreplace || oneleggedreplace ) {
22983 ast_channel_lock(c);
22984 c->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
22985 ast_channel_unlock(c);
22986 }
22987
22988
22989 c->tech_pvt = dialog_unref(c->tech_pvt, "unref dialog c->tech_pvt");
22990
22991
22992 ast_hangup(c);
22993
22994 *nounlock = 1;
22995
22996 sip_pvt_lock(p);
22997 ast_channel_unref(c);
22998 return 0;
22999 }
23000
23001
23002 static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context)
23003 {
23004 struct ast_str *str = ast_str_alloca(AST_MAX_EXTENSION + AST_MAX_CONTEXT + 2);
23005 struct ast_app *pickup = pbx_findapp("Pickup");
23006
23007 if (!pickup) {
23008 ast_log(LOG_ERROR, "Unable to perform pickup: Application 'Pickup' not loaded (app_directed_pickup.so).\n");
23009 return -1;
23010 }
23011
23012 ast_str_set(&str, 0, "%s@%s", extension, sip_cfg.notifycid == IGNORE_CONTEXT ? "PICKUPMARK" : context);
23013
23014 ast_debug(2, "About to call Pickup(%s)\n", ast_str_buffer(str));
23015
23016
23017
23018
23019 pbx_exec(channel, pickup, ast_str_buffer(str));
23020
23021 return 0;
23022 }
23023
23024
23025 static int sip_t38_abort(const void *data)
23026 {
23027 struct sip_pvt *p = (struct sip_pvt *) data;
23028
23029 sip_pvt_lock(p);
23030
23031
23032
23033
23034
23035 if (p->t38id != -1) {
23036 change_t38_state(p, T38_DISABLED);
23037 transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
23038 p->t38id = -1;
23039 dialog_unref(p, "unref the dialog ptr from sip_t38_abort, because it held a dialog ptr");
23040 }
23041 sip_pvt_unlock(p);
23042 return 0;
23043 }
23044
23045
23046
23047
23048
23049
23050
23051
23052
23053
23054
23055
23056 static int handle_request_update(struct sip_pvt *p, struct sip_request *req)
23057 {
23058 if (ast_strlen_zero(get_header(req, "X-Asterisk-rpid-update"))) {
23059 transmit_response(p, "501 Method Not Implemented", req);
23060 return 0;
23061 }
23062 if (!p->owner) {
23063 transmit_response(p, "481 Call/Transaction Does Not Exist", req);
23064 return 0;
23065 }
23066 if (get_rpid(p, req)) {
23067 struct ast_party_connected_line connected;
23068 struct ast_set_party_connected_line update_connected;
23069
23070 ast_party_connected_line_init(&connected);
23071 memset(&update_connected, 0, sizeof(update_connected));
23072
23073 update_connected.id.number = 1;
23074 connected.id.number.valid = 1;
23075 connected.id.number.str = (char *) p->cid_num;
23076 connected.id.number.presentation = p->callingpres;
23077
23078 update_connected.id.name = 1;
23079 connected.id.name.valid = 1;
23080 connected.id.name.str = (char *) p->cid_name;
23081 connected.id.name.presentation = p->callingpres;
23082
23083 connected.id.tag = (char *) p->cid_tag;
23084 connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
23085 ast_channel_queue_connected_line_update(p->owner, &connected, &update_connected);
23086 }
23087 transmit_response(p, "200 OK", req);
23088 return 0;
23089 }
23090
23091
23092
23093
23094
23095
23096
23097 static int handle_request_invite_st(struct sip_pvt *p, struct sip_request *req,
23098 const char *required, int reinvite)
23099 {
23100 const char *p_uac_se_hdr;
23101 const char *p_uac_min_se;
23102 int uac_max_se = -1;
23103 int uac_min_se = -1;
23104 int st_active = FALSE;
23105 int st_interval = 0;
23106 enum st_refresher tmp_st_ref = SESSION_TIMER_REFRESHER_AUTO;
23107 int dlg_min_se = -1;
23108 int dlg_max_se = global_max_se;
23109 int rtn;
23110
23111
23112 if ((p->sipoptions & SIP_OPT_TIMER)) {
23113 enum st_refresher_param st_ref_param = SESSION_TIMER_REFRESHER_PARAM_UNKNOWN;
23114
23115
23116
23117 ast_debug(2, "Incoming INVITE with 'timer' option supported\n");
23118
23119
23120 if (!p->stimer) {
23121 sip_st_alloc(p);
23122 }
23123
23124
23125 p_uac_se_hdr = get_header(req, "Session-Expires");
23126 if (!ast_strlen_zero(p_uac_se_hdr)) {
23127 ast_debug(2, "INVITE also has \"Session-Expires\" header.\n");
23128 rtn = parse_session_expires(p_uac_se_hdr, &uac_max_se, &st_ref_param);
23129 tmp_st_ref = (st_ref_param == SESSION_TIMER_REFRESHER_PARAM_UAC) ? SESSION_TIMER_REFRESHER_THEM : SESSION_TIMER_REFRESHER_US;
23130 if (rtn != 0) {
23131 transmit_response_reliable(p, "400 Session-Expires Invalid Syntax", req);
23132 return -1;
23133 }
23134 }
23135
23136
23137 p_uac_min_se = get_header(req, "Min-SE");
23138 if (!ast_strlen_zero(p_uac_min_se)) {
23139 ast_debug(2, "INVITE also has \"Min-SE\" header.\n");
23140 rtn = parse_minse(p_uac_min_se, &uac_min_se);
23141 if (rtn != 0) {
23142 transmit_response_reliable(p, "400 Min-SE Invalid Syntax", req);
23143 return -1;
23144 }
23145 }
23146
23147 dlg_min_se = st_get_se(p, FALSE);
23148 switch (st_get_mode(p, 1)) {
23149 case SESSION_TIMER_MODE_ACCEPT:
23150 case SESSION_TIMER_MODE_ORIGINATE:
23151 if (uac_max_se > 0 && uac_max_se < dlg_min_se) {
23152 transmit_response_with_minse(p, "422 Session Interval Too Small", req, dlg_min_se);
23153 return -1;
23154 }
23155
23156 p->stimer->st_active_peer_ua = TRUE;
23157 st_active = TRUE;
23158 if (st_ref_param == SESSION_TIMER_REFRESHER_PARAM_UNKNOWN) {
23159 tmp_st_ref = st_get_refresher(p);
23160 }
23161
23162 dlg_max_se = st_get_se(p, TRUE);
23163 if (uac_max_se > 0) {
23164 if (dlg_max_se >= uac_min_se) {
23165 st_interval = (uac_max_se < dlg_max_se) ? uac_max_se : dlg_max_se;
23166 } else {
23167 st_interval = uac_max_se;
23168 }
23169 } else if (uac_min_se > 0) {
23170 st_interval = MAX(dlg_max_se, uac_min_se);
23171 } else {
23172 st_interval = dlg_max_se;
23173 }
23174 break;
23175
23176 case SESSION_TIMER_MODE_REFUSE:
23177 if (p->reqsipoptions & SIP_OPT_TIMER) {
23178 transmit_response_with_unsupported(p, "420 Option Disabled", req, required);
23179 ast_log(LOG_WARNING, "Received SIP INVITE with supported but disabled option: %s\n", required);
23180 return -1;
23181 }
23182 break;
23183
23184 default:
23185 ast_log(LOG_ERROR, "Internal Error %d at %s:%d\n", st_get_mode(p, 1), __FILE__, __LINE__);
23186 break;
23187 }
23188 } else {
23189
23190
23191
23192 switch (st_get_mode(p, 1)) {
23193 case SESSION_TIMER_MODE_ORIGINATE:
23194 st_active = TRUE;
23195 st_interval = st_get_se(p, TRUE);
23196 tmp_st_ref = SESSION_TIMER_REFRESHER_US;
23197 p->stimer->st_active_peer_ua = (p->sipoptions & SIP_OPT_TIMER) ? TRUE : FALSE;
23198 break;
23199
23200 default:
23201 break;
23202 }
23203 }
23204
23205 if (reinvite == 0) {
23206
23207 if (st_active == TRUE) {
23208 p->stimer->st_active = TRUE;
23209 p->stimer->st_interval = st_interval;
23210 p->stimer->st_ref = tmp_st_ref;
23211 }
23212 } else {
23213 if (p->stimer->st_active == TRUE) {
23214
23215
23216
23217 ast_debug (2, "Restarting session-timers on a refresh - %s\n", p->callid);
23218
23219
23220 if (st_interval > 0) {
23221 p->stimer->st_interval = st_interval;
23222 p->stimer->st_ref = tmp_st_ref;
23223 }
23224 }
23225 }
23226
23227 return 0;
23228 }
23229
23230
23231
23232
23233
23234
23235
23236
23237 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)
23238 {
23239 int res = 1;
23240 int gotdest;
23241 const char *p_replaces;
23242 char *replace_id = NULL;
23243 int refer_locked = 0;
23244 const char *required;
23245 unsigned int required_profile = 0;
23246 struct ast_channel *c = NULL;
23247 struct sip_peer *authpeer = NULL;
23248 int reinvite = 0;
23249 struct ast_party_redirecting redirecting;
23250 struct ast_set_party_redirecting update_redirecting;
23251
23252 struct {
23253 char exten[AST_MAX_EXTENSION];
23254 char context[AST_MAX_CONTEXT];
23255 } pickup = {
23256 .exten = "",
23257 };
23258
23259
23260 if (!p->sipoptions) {
23261 const char *supported = get_header(req, "Supported");
23262 if (!ast_strlen_zero(supported)) {
23263 p->sipoptions = parse_sip_options(supported, NULL, 0);
23264 }
23265 }
23266
23267
23268 required = get_header(req, "Require");
23269 if (!ast_strlen_zero(required)) {
23270 char unsupported[256] = { 0, };
23271 required_profile = parse_sip_options(required, unsupported, ARRAY_LEN(unsupported));
23272
23273
23274
23275 if (!ast_strlen_zero(unsupported)) {
23276 transmit_response_with_unsupported(p, "420 Bad extension (unsupported)", req, unsupported);
23277 ast_log(LOG_WARNING, "Received SIP INVITE with unsupported required extension: required:%s unsupported:%s\n", required, unsupported);
23278 p->invitestate = INV_COMPLETED;
23279 if (!p->lastinvite)
23280 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
23281 res = -1;
23282 goto request_invite_cleanup;
23283 }
23284 }
23285
23286
23287
23288 p->sipoptions |= required_profile;
23289 p->reqsipoptions = required_profile;
23290
23291
23292 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) {
23293
23294
23295
23296
23297
23298 int different;
23299 const char *initial_rlPart2 = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
23300 const char *this_rlPart2 = REQ_OFFSET_TO_STR(req, rlPart2);
23301 if (sip_cfg.pedanticsipchecking)
23302 different = sip_uri_cmp(initial_rlPart2, this_rlPart2);
23303 else
23304 different = strcmp(initial_rlPart2, this_rlPart2);
23305 if (!different) {
23306 transmit_response(p, "482 Loop Detected", req);
23307 p->invitestate = INV_COMPLETED;
23308 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
23309 res = 0;
23310 goto request_invite_cleanup;
23311 } else {
23312
23313
23314
23315
23316
23317
23318
23319 char *uri = ast_strdupa(this_rlPart2);
23320 char *at = strchr(uri, '@');
23321 char *peerorhost;
23322 ast_debug(2, "Potential spiral detected. Original RURI was %s, new RURI is %s\n", initial_rlPart2, this_rlPart2);
23323 transmit_response(p, "100 Trying", req);
23324 if (at) {
23325 *at = '\0';
23326 }
23327
23328 if ((peerorhost = strchr(uri, ':'))) {
23329 *peerorhost++ = '\0';
23330 }
23331 ast_string_field_set(p, theirtag, NULL);
23332
23333
23334 ast_string_field_set(p->owner, call_forward, peerorhost);
23335 ast_queue_control(p->owner, AST_CONTROL_BUSY);
23336 res = 0;
23337 goto request_invite_cleanup;
23338 }
23339 }
23340
23341 if (!req->ignore && p->pendinginvite) {
23342 if (!ast_test_flag(&p->flags[0], SIP_OUTGOING) && (p->invitestate == INV_COMPLETED || p->invitestate == INV_TERMINATED)) {
23343
23344
23345
23346
23347
23348
23349
23350
23351
23352
23353 __sip_ack(p, p->pendinginvite, 1, 0);
23354 } else {
23355
23356 p->glareinvite = seqno;
23357 if (p->rtp && find_sdp(req)) {
23358 struct ast_sockaddr addr;
23359 if (get_ip_and_port_from_sdp(req, SDP_AUDIO, &addr)) {
23360 ast_log(LOG_WARNING, "Failed to set an alternate media source on glared reinvite. Audio may not work properly on this call.\n");
23361 } else {
23362 ast_rtp_instance_set_alt_remote_address(p->rtp, &addr);
23363 }
23364 if (p->vrtp) {
23365 if (get_ip_and_port_from_sdp(req, SDP_VIDEO, &addr)) {
23366 ast_log(LOG_WARNING, "Failed to set an alternate media source on glared reinvite. Video may not work properly on this call.\n");
23367 } else {
23368 ast_rtp_instance_set_alt_remote_address(p->vrtp, &addr);
23369 }
23370 }
23371 }
23372 transmit_response_reliable(p, "491 Request Pending", req);
23373 check_via(p, req);
23374 ast_debug(1, "Got INVITE on call where we already have pending INVITE, deferring that - %s\n", p->callid);
23375
23376 res = 0;
23377 goto request_invite_cleanup;
23378 }
23379 }
23380
23381 p_replaces = get_header(req, "Replaces");
23382 if (!ast_strlen_zero(p_replaces)) {
23383
23384 char *ptr;
23385 char *fromtag = NULL;
23386 char *totag = NULL;
23387 char *start, *to;
23388 int error = 0;
23389
23390 if (p->owner) {
23391 ast_debug(3, "INVITE w Replaces on existing call? Refusing action. [%s]\n", p->callid);
23392 transmit_response_reliable(p, "400 Bad request", req);
23393 check_via(p, req);
23394 copy_request(&p->initreq, req);
23395
23396 res = -1;
23397 goto request_invite_cleanup;
23398 }
23399
23400 if (sipdebug)
23401 ast_debug(3, "INVITE part of call transfer. Replaces [%s]\n", p_replaces);
23402
23403 replace_id = ast_strdupa(p_replaces);
23404 ast_uri_decode(replace_id);
23405
23406 if (!p->refer && !sip_refer_allocate(p)) {
23407 transmit_response_reliable(p, "500 Server Internal Error", req);
23408 append_history(p, "Xfer", "INVITE/Replace Failed. Out of memory.");
23409 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
23410 p->invitestate = INV_COMPLETED;
23411 check_via(p, req);
23412 copy_request(&p->initreq, req);
23413 res = -1;
23414 goto request_invite_cleanup;
23415 }
23416
23417
23418
23419
23420
23421
23422
23423
23424
23425
23426 replace_id = ast_skip_blanks(replace_id);
23427
23428 start = replace_id;
23429 while ( (ptr = strsep(&start, ";")) ) {
23430 ptr = ast_skip_blanks(ptr);
23431 if ( (to = strcasestr(ptr, "to-tag=") ) )
23432 totag = to + 7;
23433 else if ( (to = strcasestr(ptr, "from-tag=") ) ) {
23434 fromtag = to + 9;
23435 fromtag = strsep(&fromtag, "&");
23436 }
23437 }
23438
23439 if (sipdebug)
23440 ast_debug(4, "Invite/replaces: Will use Replace-Call-ID : %s Fromtag: %s Totag: %s\n",
23441 replace_id,
23442 fromtag ? fromtag : "<no from tag>",
23443 totag ? totag : "<no to tag>");
23444
23445
23446
23447
23448
23449 if (strncmp(replace_id, "pickup-", 7) == 0) {
23450 struct sip_pvt *subscription = NULL;
23451 replace_id += 7;
23452
23453 if ((subscription = get_sip_pvt_byid_locked(replace_id, totag, fromtag)) == NULL) {
23454 ast_log(LOG_NOTICE, "Unable to find subscription with call-id: %s\n", replace_id);
23455 transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
23456 error = 1;
23457 } else {
23458 ast_log(LOG_NOTICE, "Trying to pick up %s@%s\n", subscription->exten, subscription->context);
23459 ast_copy_string(pickup.exten, subscription->exten, sizeof(pickup.exten));
23460 ast_copy_string(pickup.context, subscription->context, sizeof(pickup.context));
23461 sip_pvt_unlock(subscription);
23462 if (subscription->owner) {
23463 ast_channel_unlock(subscription->owner);
23464 }
23465 subscription = dialog_unref(subscription, "unref dialog subscription");
23466 }
23467 }
23468
23469
23470 if (!error && ast_strlen_zero(pickup.exten) && (p->refer->refer_call = get_sip_pvt_byid_locked(replace_id, totag, fromtag)) == NULL) {
23471 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existent call id (%s)!\n", replace_id);
23472 transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
23473 error = 1;
23474 } else {
23475 refer_locked = 1;
23476 }
23477
23478
23479
23480
23481
23482 if (p->refer->refer_call == p) {
23483 ast_log(LOG_NOTICE, "INVITE with replaces into it's own call id (%s == %s)!\n", replace_id, p->callid);
23484 transmit_response_reliable(p, "400 Bad request", req);
23485 error = 1;
23486 }
23487
23488 if (!error && ast_strlen_zero(pickup.exten) && !p->refer->refer_call->owner) {
23489
23490 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existing call id (%s)!\n", replace_id);
23491
23492 transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replace)", req);
23493 error = 1;
23494 }
23495
23496 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) {
23497 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-ringing or active call id (%s)!\n", replace_id);
23498 transmit_response_reliable(p, "603 Declined (Replaces)", req);
23499 error = 1;
23500 }
23501
23502 if (error) {
23503 append_history(p, "Xfer", "INVITE/Replace Failed.");
23504 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
23505 sip_pvt_unlock(p);
23506 if (p->refer->refer_call) {
23507 sip_pvt_unlock(p->refer->refer_call);
23508 if (p->refer->refer_call->owner) {
23509 ast_channel_unlock(p->refer->refer_call->owner);
23510 }
23511 p->refer->refer_call = dialog_unref(p->refer->refer_call, "unref dialog p->refer->refer_call");
23512 }
23513 refer_locked = 0;
23514 p->invitestate = INV_COMPLETED;
23515 check_via(p, req);
23516 copy_request(&p->initreq, req);
23517 res = -1;
23518 goto request_invite_cleanup;
23519 }
23520 }
23521
23522
23523
23524
23525 if (!req->ignore) {
23526 int newcall = (p->initreq.headers ? TRUE : FALSE);
23527
23528 if (sip_cancel_destroy(p))
23529 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
23530
23531 p->pendinginvite = seqno;
23532 check_via(p, req);
23533
23534 copy_request(&p->initreq, req);
23535 if (sipdebug)
23536 ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
23537 if (!p->owner) {
23538 if (debug)
23539 ast_verbose("Using INVITE request as basis request - %s\n", p->callid);
23540 if (newcall)
23541 append_history(p, "Invite", "New call: %s", p->callid);
23542 parse_ok_contact(p, req);
23543 } else {
23544 ast_clear_flag(&p->flags[0], SIP_OUTGOING);
23545 if (get_rpid(p, req)) {
23546 struct ast_party_connected_line connected;
23547 struct ast_set_party_connected_line update_connected;
23548
23549 ast_party_connected_line_init(&connected);
23550 memset(&update_connected, 0, sizeof(update_connected));
23551
23552 update_connected.id.number = 1;
23553 connected.id.number.valid = 1;
23554 connected.id.number.str = (char *) p->cid_num;
23555 connected.id.number.presentation = p->callingpres;
23556
23557 update_connected.id.name = 1;
23558 connected.id.name.valid = 1;
23559 connected.id.name.str = (char *) p->cid_name;
23560 connected.id.name.presentation = p->callingpres;
23561
23562 connected.id.tag = (char *) p->cid_tag;
23563 connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
23564 ast_channel_queue_connected_line_update(p->owner, &connected,
23565 &update_connected);
23566 }
23567
23568 if (find_sdp(req)) {
23569 if (process_sdp(p, req, SDP_T38_INITIATE)) {
23570 if (!ast_strlen_zero(get_header(req, "Content-Encoding"))) {
23571
23572
23573
23574 transmit_response_reliable(p, "415 Unsupported Media type", req);
23575 } else {
23576 transmit_response_reliable(p, "488 Not acceptable here", req);
23577 }
23578 if (!p->lastinvite)
23579 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
23580 res = -1;
23581 goto request_invite_cleanup;
23582 }
23583 ast_queue_control(p->owner, AST_CONTROL_SRCUPDATE);
23584 } else {
23585 p->jointcapability = p->capability;
23586 ast_debug(1, "Hm.... No sdp for the moment\n");
23587
23588
23589
23590 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
23591 ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
23592
23593 ast_queue_frame(p->owner, &ast_null_frame);
23594 change_hold_state(p, req, FALSE, 0);
23595 }
23596 }
23597 if (p->do_history)
23598 append_history(p, "ReInv", "Re-invite received");
23599 }
23600 } else if (debug)
23601 ast_verbose("Ignoring this INVITE request\n");
23602
23603 if (!p->lastinvite && !req->ignore && !p->owner) {
23604
23605
23606 int cc_recall_core_id = -1;
23607 set_pvt_allowed_methods(p, req);
23608 res = check_user_full(p, req, SIP_INVITE, e, XMIT_RELIABLE, addr, &authpeer);
23609 if (res == AUTH_CHALLENGE_SENT) {
23610 p->invitestate = INV_COMPLETED;
23611 res = 0;
23612 goto request_invite_cleanup;
23613 }
23614 if (res < 0) {
23615 ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", get_header(req, "From"));
23616 transmit_response_reliable(p, "403 Forbidden", req);
23617 p->invitestate = INV_COMPLETED;
23618 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
23619 res = 0;
23620 goto request_invite_cleanup;
23621 }
23622
23623
23624 if (p->relatedpeer) {
23625 p->relatedpeer = unref_peer(p->relatedpeer,"unsetting the relatedpeer field in the dialog, before it is set to something else.");
23626 }
23627 if (authpeer) {
23628 p->relatedpeer = ref_peer(authpeer, "setting dialog's relatedpeer pointer");
23629 }
23630
23631 req->authenticated = 1;
23632
23633
23634 if (find_sdp(req)) {
23635 if (process_sdp(p, req, SDP_T38_INITIATE)) {
23636
23637
23638
23639 if (!ast_strlen_zero(get_header(req, "Content-Encoding"))) {
23640 transmit_response_reliable(p, "415 Unsupported Media type", req);
23641 } else {
23642
23643 transmit_response_reliable(p, "488 Not acceptable here", req);
23644 }
23645 p->invitestate = INV_COMPLETED;
23646 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
23647 ast_debug(1, "No compatible codecs for this SIP call.\n");
23648 res = -1;
23649 goto request_invite_cleanup;
23650 }
23651 } else {
23652 p->jointcapability = p->capability;
23653 ast_debug(2, "No SDP in Invite, third party call control\n");
23654 }
23655
23656
23657 if (ast_strlen_zero(p->context))
23658 ast_string_field_set(p, context, sip_cfg.default_context);
23659
23660
23661
23662 ast_debug(1, "Checking SIP call limits for device %s\n", p->username);
23663 if ((res = update_call_counter(p, INC_CALL_LIMIT))) {
23664 if (res < 0) {
23665 ast_log(LOG_NOTICE, "Failed to place call for device %s, too many calls\n", p->username);
23666 transmit_response_reliable(p, "480 Temporarily Unavailable (Call limit) ", req);
23667 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
23668 p->invitestate = INV_COMPLETED;
23669 }
23670 res = 0;
23671 goto request_invite_cleanup;
23672 }
23673 gotdest = get_destination(p, NULL, &cc_recall_core_id);
23674 extract_uri(p, req);
23675 build_contact(p);
23676
23677 if (p->rtp) {
23678 ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
23679 ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
23680 }
23681
23682 if (!replace_id && (gotdest != SIP_GET_DEST_EXTEN_FOUND)) {
23683 switch(gotdest) {
23684 case SIP_GET_DEST_INVALID_URI:
23685 transmit_response_reliable(p, "416 Unsupported URI scheme", req);
23686 break;
23687 case SIP_GET_DEST_EXTEN_MATCHMORE:
23688 if (ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP)
23689 == SIP_PAGE2_ALLOWOVERLAP_YES) {
23690 transmit_response_reliable(p, "484 Address Incomplete", req);
23691 break;
23692 }
23693
23694
23695
23696
23697
23698
23699
23700
23701
23702 case SIP_GET_DEST_EXTEN_NOT_FOUND:
23703 {
23704 char *decoded_exten = ast_strdupa(p->exten);
23705 transmit_response_reliable(p, "404 Not Found", req);
23706 ast_uri_decode(decoded_exten);
23707 ast_log(LOG_NOTICE, "Call from '%s' (%s) to extension"
23708 " '%s' rejected because extension not found in context '%s'.\n",
23709 S_OR(p->username, p->peername), ast_sockaddr_stringify(&p->recv), decoded_exten, p->context);
23710 }
23711 break;
23712 case SIP_GET_DEST_REFUSED:
23713 default:
23714 transmit_response_reliable(p, "403 Forbidden", req);
23715 }
23716
23717 p->invitestate = INV_COMPLETED;
23718 update_call_counter(p, DEC_CALL_LIMIT);
23719 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
23720 res = 0;
23721 goto request_invite_cleanup;
23722 } else {
23723
23724
23725
23726 if (ast_strlen_zero(p->exten))
23727 ast_string_field_set(p, exten, "s");
23728
23729
23730 make_our_tag(p);
23731
23732 if (handle_request_invite_st(p, req, required, reinvite)) {
23733 p->invitestate = INV_COMPLETED;
23734 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
23735 res = -1;
23736 goto request_invite_cleanup;
23737 }
23738
23739
23740
23741 c = sip_new(p, AST_STATE_DOWN, S_OR(p->peername, NULL), NULL);
23742 if (cc_recall_core_id != -1) {
23743 ast_setup_cc_recall_datastore(c, cc_recall_core_id);
23744 ast_cc_agent_set_interfaces_chanvar(c);
23745 }
23746 *recount = 1;
23747
23748
23749 build_route(p, req, 0, 0);
23750
23751 if (c) {
23752 ast_party_redirecting_init(&redirecting);
23753 memset(&update_redirecting, 0, sizeof(update_redirecting));
23754 change_redirecting_information(p, req, &redirecting, &update_redirecting,
23755 FALSE);
23756 ast_channel_set_redirecting(c, &redirecting, &update_redirecting);
23757 ast_party_redirecting_free(&redirecting);
23758 }
23759 }
23760 } else {
23761 ast_party_redirecting_init(&redirecting);
23762 memset(&update_redirecting, 0, sizeof(update_redirecting));
23763 if (sipdebug) {
23764 if (!req->ignore)
23765 ast_debug(2, "Got a SIP re-invite for call %s\n", p->callid);
23766 else
23767 ast_debug(2, "Got a SIP re-transmit of INVITE for call %s\n", p->callid);
23768 }
23769 if (!req->ignore)
23770 reinvite = 1;
23771
23772 if (handle_request_invite_st(p, req, required, reinvite)) {
23773 p->invitestate = INV_COMPLETED;
23774 if (!p->lastinvite) {
23775 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
23776 }
23777 res = -1;
23778 goto request_invite_cleanup;
23779 }
23780
23781 c = p->owner;
23782 change_redirecting_information(p, req, &redirecting, &update_redirecting, FALSE);
23783 if (c) {
23784 ast_channel_set_redirecting(c, &redirecting, &update_redirecting);
23785 }
23786 ast_party_redirecting_free(&redirecting);
23787 }
23788
23789 if (p->stimer->st_active == TRUE) {
23790 if (reinvite == 0) {
23791 start_session_timer(p);
23792 } else {
23793 restart_session_timer(p);
23794 }
23795 }
23796
23797 if (!req->ignore && p)
23798 p->lastinvite = seqno;
23799
23800 if (c && replace_id) {
23801 if (!ast_strlen_zero(pickup.exten)) {
23802 append_history(p, "Xfer", "INVITE/Replace received");
23803
23804
23805 transmit_response(p, "100 Trying", req);
23806 p->invitestate = INV_PROCEEDING;
23807 ast_setstate(c, AST_STATE_RING);
23808
23809
23810 ast_channel_unlock(c);
23811 *nounlock = 1;
23812
23813
23814
23815
23816
23817
23818 sip_pvt_unlock(p);
23819 do_magic_pickup(c, pickup.exten, pickup.context);
23820
23821 ast_hangup(c);
23822 sip_pvt_lock(p);
23823
23824 res = 0;
23825 goto request_invite_cleanup;
23826 } else {
23827
23828 if (sipdebug)
23829 ast_debug(4, "Sending this call to the invite/replcaes handler %s\n", p->callid);
23830 res = handle_invite_replaces(p, req, debug, seqno, addr, nounlock);
23831 refer_locked = 0;
23832 goto request_invite_cleanup;
23833 }
23834 }
23835
23836
23837 if (c) {
23838 enum ast_channel_state c_state = c->_state;
23839
23840 if (c_state != AST_STATE_UP && reinvite &&
23841 (p->invitestate == INV_TERMINATED || p->invitestate == INV_CONFIRMED)) {
23842
23843
23844
23845
23846
23847
23848
23849
23850
23851 c_state = AST_STATE_UP;
23852 }
23853
23854 switch(c_state) {
23855 case AST_STATE_DOWN:
23856 ast_debug(2, "%s: New call is still down.... Trying... \n", c->name);
23857 transmit_provisional_response(p, "100 Trying", req, 0);
23858 p->invitestate = INV_PROCEEDING;
23859 ast_setstate(c, AST_STATE_RING);
23860 if (strcmp(p->exten, ast_pickup_ext())) {
23861 enum ast_pbx_result result;
23862
23863 result = ast_pbx_start(c);
23864
23865 switch(result) {
23866 case AST_PBX_FAILED:
23867 ast_log(LOG_WARNING, "Failed to start PBX :(\n");
23868 p->invitestate = INV_COMPLETED;
23869 transmit_response_reliable(p, "503 Unavailable", req);
23870 break;
23871 case AST_PBX_CALL_LIMIT:
23872 ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
23873 p->invitestate = INV_COMPLETED;
23874 transmit_response_reliable(p, "480 Temporarily Unavailable", req);
23875 break;
23876 case AST_PBX_SUCCESS:
23877
23878 break;
23879 }
23880
23881 if (result) {
23882
23883
23884 ast_channel_unlock(c);
23885 *nounlock = 1;
23886 sip_pvt_unlock(p);
23887 ast_hangup(c);
23888 sip_pvt_lock(p);
23889 c = NULL;
23890 }
23891 } else {
23892 if (sip_pickup(c)) {
23893 ast_log(LOG_WARNING, "Failed to start Group pickup by %s\n", c->name);
23894 transmit_response_reliable(p, "480 Temporarily Unavailable", req);
23895 sip_alreadygone(p);
23896 c->hangupcause = AST_CAUSE_FAILURE;
23897
23898
23899 ast_channel_unlock(c);
23900 *nounlock = 1;
23901
23902 p->invitestate = INV_COMPLETED;
23903 sip_pvt_unlock(p);
23904 ast_hangup(c);
23905 sip_pvt_lock(p);
23906 c = NULL;
23907 }
23908 }
23909 break;
23910 case AST_STATE_RING:
23911 transmit_provisional_response(p, "100 Trying", req, 0);
23912 p->invitestate = INV_PROCEEDING;
23913 break;
23914 case AST_STATE_RINGING:
23915 transmit_provisional_response(p, "180 Ringing", req, 0);
23916 p->invitestate = INV_PROCEEDING;
23917 break;
23918 case AST_STATE_UP:
23919 ast_debug(2, "%s: This call is UP.... \n", c->name);
23920
23921 transmit_response(p, "100 Trying", req);
23922
23923 if (p->t38.state == T38_PEER_REINVITE) {
23924 if (p->t38id > -1) {
23925
23926 AST_SCHED_DEL_UNREF(sched, p->t38id, dialog_unref(p, "remove ref for t38id"));
23927 }
23928 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."));
23929 } else if (p->t38.state == T38_ENABLED) {
23930 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
23931 transmit_response_with_t38_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL)));
23932 } else if (p->t38.state == T38_DISABLED) {
23933
23934 if (p->srtp && !ast_test_flag(p->srtp, SRTP_CRYPTO_OFFER_OK)) {
23935 ast_log(LOG_WARNING, "Target does not support required crypto\n");
23936 transmit_response_reliable(p, "488 Not Acceptable Here (crypto)", req);
23937 } else {
23938 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
23939 transmit_response_with_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL)), p->session_modify == TRUE ? FALSE : TRUE, FALSE);
23940 ast_queue_control(p->owner, AST_CONTROL_UPDATE_RTP_PEER);
23941 }
23942 }
23943
23944 p->invitestate = INV_TERMINATED;
23945 break;
23946 default:
23947 ast_log(LOG_WARNING, "Don't know how to handle INVITE in state %d\n", c->_state);
23948 transmit_response(p, "100 Trying", req);
23949 break;
23950 }
23951 } else {
23952 if (p && (p->autokillid == -1)) {
23953 const char *msg;
23954
23955 if (!p->jointcapability)
23956 msg = "488 Not Acceptable Here (codec error)";
23957 else {
23958 ast_log(LOG_NOTICE, "Unable to create/find SIP channel for this INVITE\n");
23959 msg = "503 Unavailable";
23960 }
23961 transmit_response_reliable(p, msg, req);
23962 p->invitestate = INV_COMPLETED;
23963 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
23964 }
23965 }
23966
23967 request_invite_cleanup:
23968
23969 if (refer_locked && p->refer && p->refer->refer_call) {
23970 sip_pvt_unlock(p->refer->refer_call);
23971 if (p->refer->refer_call->owner) {
23972 ast_channel_unlock(p->refer->refer_call->owner);
23973 }
23974 p->refer->refer_call = dialog_unref(p->refer->refer_call, "unref dialog p->refer->refer_call");
23975 }
23976 if (authpeer) {
23977 authpeer = unref_peer(authpeer, "unref_peer, from handle_request_invite authpeer");
23978 }
23979
23980 return res;
23981 }
23982
23983
23984
23985
23986
23987
23988
23989
23990
23991
23992
23993
23994
23995
23996 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, uint32_t seqno, int *nounlock)
23997 {
23998 struct sip_dual target;
23999
24000 int res = 0;
24001 struct sip_pvt *targetcall_pvt;
24002 struct ast_party_connected_line connected_to_transferee;
24003 struct ast_party_connected_line connected_to_target;
24004 char transferer_linkedid[32];
24005 struct ast_channel *chans[2];
24006
24007
24008 if (!(targetcall_pvt = get_sip_pvt_byid_locked(transferer->refer->replaces_callid, transferer->refer->replaces_callid_totag,
24009 transferer->refer->replaces_callid_fromtag))) {
24010 if (transferer->refer->localtransfer) {
24011
24012
24013
24014 transmit_notify_with_sipfrag(transferer, seqno, "481 Call leg/transaction does not exist", TRUE);
24015 append_history(transferer, "Xfer", "Refer failed");
24016 ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
24017 transferer->refer->status = REFER_FAILED;
24018 return -1;
24019 }
24020
24021 ast_debug(3, "SIP attended transfer: Not our call - generating INVITE with replaces\n");
24022 return 0;
24023 }
24024
24025
24026 append_history(transferer, "Xfer", "Refer accepted");
24027 if (!targetcall_pvt->owner) {
24028 ast_debug(4, "SIP attended transfer: Error: No owner of target call\n");
24029
24030 transmit_notify_with_sipfrag(transferer, seqno, "503 Service Unavailable", TRUE);
24031 append_history(transferer, "Xfer", "Refer failed");
24032 ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
24033 transferer->refer->status = REFER_FAILED;
24034 sip_pvt_unlock(targetcall_pvt);
24035 if (targetcall_pvt)
24036 ao2_t_ref(targetcall_pvt, -1, "Drop targetcall_pvt pointer");
24037 return -1;
24038 }
24039
24040
24041 target.chan1 = ast_channel_ref(targetcall_pvt->owner);
24042 target.chan2 = ast_bridged_channel(targetcall_pvt->owner);
24043 if (target.chan2) {
24044 ast_channel_ref(target.chan2);
24045 }
24046
24047 if (!target.chan2 || !(target.chan2->_state == AST_STATE_UP || target.chan2->_state == AST_STATE_RINGING) ) {
24048
24049 if (target.chan2)
24050 ast_debug(4, "SIP attended transfer: Error: Wrong state of target call: %s\n", ast_state2str(target.chan2->_state));
24051 else if (target.chan1->_state != AST_STATE_RING)
24052 ast_debug(4, "SIP attended transfer: Error: No target channel\n");
24053 else
24054 ast_debug(4, "SIP attended transfer: Attempting transfer in ringing state\n");
24055 }
24056
24057
24058 if (sipdebug) {
24059 if (current->chan2)
24060 ast_debug(4, "SIP attended transfer: trying to bridge %s and %s\n", target.chan1->name, current->chan2->name);
24061 else
24062 ast_debug(4, "SIP attended transfer: trying to make %s take over (masq) %s\n", target.chan1->name, current->chan1->name);
24063 }
24064
24065 ast_set_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
24066
24067 ast_copy_string(transferer_linkedid, transferer->owner->linkedid, sizeof(transferer_linkedid));
24068
24069
24070 chans[0] = transferer->owner;
24071 chans[1] = target.chan1;
24072 ast_manager_event_multichan(EVENT_FLAG_CALL, "Transfer", 2, chans,
24073 "TransferMethod: SIP\r\n"
24074 "TransferType: Attended\r\n"
24075 "Channel: %s\r\n"
24076 "Uniqueid: %s\r\n"
24077 "SIP-Callid: %s\r\n"
24078 "TargetChannel: %s\r\n"
24079 "TargetUniqueid: %s\r\n",
24080 transferer->owner->name,
24081 transferer->owner->uniqueid,
24082 transferer->callid,
24083 target.chan1->name,
24084 target.chan1->uniqueid);
24085 ast_party_connected_line_init(&connected_to_transferee);
24086 ast_party_connected_line_init(&connected_to_target);
24087
24088 ast_party_connected_line_copy(&connected_to_transferee, ¤t->chan1->connected);
24089
24090 ast_party_connected_line_copy(&connected_to_target, &target.chan1->connected);
24091 connected_to_target.source = connected_to_transferee.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
24092 res = attempt_transfer(current, &target);
24093 if (res) {
24094
24095 transmit_notify_with_sipfrag(transferer, seqno, "486 Busy Here", TRUE);
24096 append_history(transferer, "Xfer", "Refer failed");
24097 ast_clear_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
24098
24099 sip_pvt_unlock(targetcall_pvt);
24100 ast_channel_unlock(target.chan1);
24101 } else {
24102
24103 const char *xfersound = pbx_builtin_getvar_helper(target.chan1, "ATTENDED_TRANSFER_COMPLETE_SOUND");
24104
24105
24106 ast_cel_report_event(target.chan1, AST_CEL_ATTENDEDTRANSFER, NULL, transferer_linkedid, target.chan2);
24107
24108
24109 transmit_notify_with_sipfrag(transferer, seqno, "200 OK", TRUE);
24110 append_history(transferer, "Xfer", "Refer succeeded");
24111 transferer->refer->status = REFER_200OK;
24112 if (target.chan2 && !ast_strlen_zero(xfersound) && ast_streamfile(target.chan2, xfersound, target.chan2->language) >= 0) {
24113 ast_waitstream(target.chan2, "");
24114 }
24115
24116
24117
24118
24119
24120
24121
24122
24123
24124
24125
24126 ast_channel_ref(current->chan1);
24127 ast_channel_unlock(current->chan1);
24128 ast_channel_unlock(target.chan1);
24129 *nounlock = 1;
24130 sip_pvt_unlock(targetcall_pvt);
24131 sip_pvt_unlock(transferer);
24132
24133 ast_do_masquerade(target.chan1);
24134
24135 if (target.chan2) {
24136 ast_indicate(target.chan2, AST_CONTROL_UNHOLD);
24137 }
24138
24139 if (current->chan2 && current->chan2->_state == AST_STATE_RING) {
24140 ast_indicate(target.chan1, AST_CONTROL_RINGING);
24141 }
24142
24143 if (target.chan2) {
24144 ast_channel_queue_connected_line_update(target.chan1, &connected_to_transferee, NULL);
24145 ast_channel_queue_connected_line_update(target.chan2, &connected_to_target, NULL);
24146 } else {
24147
24148
24149
24150
24151
24152
24153
24154 struct ast_control_read_action_payload *frame_payload;
24155 int payload_size;
24156 int frame_size;
24157 unsigned char connected_line_data[1024];
24158 payload_size = ast_connected_line_build_data(connected_line_data,
24159 sizeof(connected_line_data), &connected_to_target, NULL);
24160 frame_size = payload_size + sizeof(*frame_payload);
24161 if (payload_size != -1) {
24162 frame_payload = ast_alloca(frame_size);
24163 frame_payload->payload_size = payload_size;
24164 memcpy(frame_payload->payload, connected_line_data, payload_size);
24165 frame_payload->action = AST_FRAME_READ_ACTION_CONNECTED_LINE_MACRO;
24166 ast_queue_control_data(target.chan1, AST_CONTROL_READ_ACTION, frame_payload, frame_size);
24167 }
24168
24169
24170
24171
24172 ast_channel_queue_connected_line_update(target.chan1, &connected_to_transferee, NULL);
24173
24174 }
24175 sip_pvt_lock(transferer);
24176
24177 ast_channel_unref(current->chan1);
24178 }
24179
24180
24181 ast_party_connected_line_free(&connected_to_target);
24182 ast_party_connected_line_free(&connected_to_transferee);
24183 ast_channel_unref(target.chan1);
24184 if (target.chan2) {
24185 ast_channel_unref(target.chan2);
24186 }
24187 if (targetcall_pvt)
24188 ao2_t_ref(targetcall_pvt, -1, "drop targetcall_pvt");
24189 return 1;
24190 }
24191
24192
24193
24194
24195
24196
24197
24198
24199
24200
24201
24202
24203
24204
24205
24206
24207
24208
24209
24210
24211
24212
24213
24214
24215
24216
24217
24218
24219
24220
24221
24222
24223
24224
24225
24226
24227
24228
24229
24230
24231
24232
24233
24234
24235
24236
24237
24238
24239
24240
24241
24242
24243
24244
24245
24246
24247
24248
24249
24250
24251
24252
24253
24254
24255
24256 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, uint32_t seqno, int *nounlock)
24257 {
24258
24259
24260
24261
24262 struct sip_dual current = { 0, };
24263 struct ast_channel *chans[2] = { 0, };
24264 char *refer_to = NULL;
24265 char *refer_to_domain = NULL;
24266 char *refer_to_context = NULL;
24267 char *referred_by = NULL;
24268 char *callid = NULL;
24269 int localtransfer = 0;
24270 int attendedtransfer = 0;
24271 int res = 0;
24272
24273 if (req->debug) {
24274 ast_verbose("Call %s got a SIP call transfer from %s: (REFER)!\n",
24275 p->callid,
24276 ast_test_flag(&p->flags[0], SIP_OUTGOING) ? "callee" : "caller");
24277 }
24278
24279 if (!p->owner) {
24280
24281
24282 ast_debug(3, "Call %s: Declined REFER, outside of dialog...\n", p->callid);
24283 transmit_response(p, "603 Declined (No dialog)", req);
24284 if (!req->ignore) {
24285 append_history(p, "Xfer", "Refer failed. Outside of dialog.");
24286 sip_alreadygone(p);
24287 pvt_set_needdestroy(p, "outside of dialog");
24288 }
24289 res = 0;
24290 goto handle_refer_cleanup;
24291 }
24292
24293
24294 if (p->allowtransfer == TRANSFER_CLOSED ) {
24295
24296 transmit_response(p, "603 Declined (policy)", req);
24297 append_history(p, "Xfer", "Refer failed. Allowtransfer == closed.");
24298
24299 res = 0;
24300 goto handle_refer_cleanup;
24301 }
24302
24303 if (!req->ignore && ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
24304
24305 transmit_response(p, "491 Request pending", req);
24306 append_history(p, "Xfer", "Refer failed. Request pending.");
24307 res = 0;
24308 goto handle_refer_cleanup;
24309 }
24310
24311
24312 if (!p->refer && !sip_refer_allocate(p)) {
24313 transmit_response(p, "500 Internal Server Error", req);
24314 append_history(p, "Xfer", "Refer failed. Memory allocation error.");
24315 res = -3;
24316 goto handle_refer_cleanup;
24317 }
24318
24319 res = get_refer_info(p, req);
24320
24321 p->refer->status = REFER_SENT;
24322
24323 if (res != 0) {
24324 switch (res) {
24325 case -2:
24326 transmit_response(p, "400 Bad Request (Refer-to missing)", req);
24327 append_history(p, "Xfer", "Refer failed. Refer-to missing.");
24328 if (req->debug) {
24329 ast_debug(1, "SIP transfer to black hole can't be handled (no refer-to: )\n");
24330 }
24331 break;
24332 case -3:
24333 transmit_response(p, "603 Declined (Non sip: uri)", req);
24334 append_history(p, "Xfer", "Refer failed. Non SIP uri");
24335 if (req->debug) {
24336 ast_debug(1, "SIP transfer to non-SIP uri denied\n");
24337 }
24338 break;
24339 default:
24340
24341 transmit_response(p, "202 Accepted", req);
24342 append_history(p, "Xfer", "Refer failed. Bad extension.");
24343 transmit_notify_with_sipfrag(p, seqno, "404 Not found", TRUE);
24344 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
24345 if (req->debug) {
24346 ast_debug(1, "SIP transfer to bad extension: %s\n", p->refer->refer_to);
24347 }
24348 break;
24349 }
24350 res = 0;
24351 goto handle_refer_cleanup;
24352 }
24353 if (ast_strlen_zero(p->context)) {
24354 ast_string_field_set(p, context, sip_cfg.default_context);
24355 }
24356
24357
24358 if (sip_cfg.allow_external_domains && check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
24359 p->refer->localtransfer = 1;
24360 if (sipdebug) {
24361 ast_debug(3, "This SIP transfer is local : %s\n", p->refer->refer_to_domain);
24362 }
24363 } else if (AST_LIST_EMPTY(&domain_list) || check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
24364
24365 p->refer->localtransfer = 1;
24366 } else if (sipdebug) {
24367 ast_debug(3, "This SIP transfer is to a remote SIP extension (remote domain %s)\n", p->refer->refer_to_domain);
24368 }
24369
24370
24371
24372 if (req->ignore) {
24373 goto handle_refer_cleanup;
24374 }
24375
24376
24377
24378
24379
24380
24381
24382
24383
24384
24385
24386
24387
24388
24389
24390
24391
24392
24393
24394
24395
24396
24397
24398
24399
24400
24401 chans[0] = current.chan1 = p->owner;
24402
24403
24404 chans[1] = current.chan2 = ast_bridged_channel(current.chan1);
24405
24406 ast_channel_ref(current.chan1);
24407 if (current.chan2) {
24408 ast_channel_ref(current.chan2);
24409 }
24410
24411 if (sipdebug) {
24412 ast_debug(3, "SIP %s transfer: Transferer channel %s, transferee channel %s\n",
24413 p->refer->attendedtransfer ? "attended" : "blind",
24414 current.chan1->name,
24415 current.chan2 ? current.chan2->name : "<none>");
24416 }
24417
24418 if (!current.chan2 && !p->refer->attendedtransfer) {
24419
24420
24421
24422 if (sipdebug) {
24423 ast_debug(3, "Refused SIP transfer on non-bridged channel.\n");
24424 }
24425 p->refer->status = REFER_FAILED;
24426 append_history(p, "Xfer", "Refer failed. Non-bridged channel.");
24427 transmit_response(p, "603 Declined", req);
24428 res = -1;
24429 goto handle_refer_cleanup;
24430 }
24431
24432 if (current.chan2) {
24433 if (sipdebug) {
24434 ast_debug(4, "Got SIP transfer, applying to bridged peer '%s'\n", current.chan2->name);
24435 }
24436 ast_queue_control(current.chan1, AST_CONTROL_UNHOLD);
24437 }
24438
24439 ast_set_flag(&p->flags[0], SIP_GOTREFER);
24440
24441
24442 transmit_response(p, "202 Accepted", req);
24443
24444
24445 if (p->refer->attendedtransfer) {
24446
24447 if ((res = local_attended_transfer(p, ¤t, req, seqno, nounlock))) {
24448 goto handle_refer_cleanup;
24449 }
24450
24451 if (sipdebug) {
24452 ast_debug(4, "SIP attended transfer: Still not our call - generating INVITE with replaces\n");
24453 }
24454
24455 }
24456
24457
24458 refer_to = ast_strdupa(p->refer->refer_to);
24459 refer_to_domain = ast_strdupa(p->refer->refer_to_domain);
24460 refer_to_context = ast_strdupa(p->refer->refer_to_context);
24461 referred_by = ast_strdupa(p->refer->referred_by);
24462 callid = ast_strdupa(p->callid);
24463 localtransfer = p->refer->localtransfer;
24464 attendedtransfer = p->refer->attendedtransfer;
24465
24466 if (!*nounlock) {
24467 ast_channel_unlock(p->owner);
24468 *nounlock = 1;
24469 }
24470 sip_pvt_unlock(p);
24471
24472
24473 if (localtransfer && ast_parking_ext_valid(refer_to, current.chan1, refer_to_context)) {
24474 sip_pvt_lock(p);
24475 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
24476 p->refer->status = REFER_200OK;
24477 append_history(p, "Xfer", "REFER to call parking.");
24478 sip_pvt_unlock(p);
24479
24480 ast_manager_event_multichan(EVENT_FLAG_CALL, "Transfer", 2, chans,
24481 "TransferMethod: SIP\r\n"
24482 "TransferType: Blind\r\n"
24483 "Channel: %s\r\n"
24484 "Uniqueid: %s\r\n"
24485 "SIP-Callid: %s\r\n"
24486 "TargetChannel: %s\r\n"
24487 "TargetUniqueid: %s\r\n"
24488 "TransferExten: %s\r\n"
24489 "Transfer2Parking: Yes\r\n",
24490 current.chan1->name,
24491 current.chan1->uniqueid,
24492 callid,
24493 current.chan2->name,
24494 current.chan2->uniqueid,
24495 refer_to);
24496
24497 if (sipdebug) {
24498 ast_debug(4, "SIP transfer to parking: trying to park %s. Parked by %s\n", current.chan2->name, current.chan1->name);
24499 }
24500
24501
24502 if (sip_park(current.chan2, current.chan1, req, seqno, refer_to, refer_to_context)) {
24503 sip_pvt_lock(p);
24504 transmit_notify_with_sipfrag(p, seqno, "500 Internal Server Error", TRUE);
24505 } else {
24506 sip_pvt_lock(p);
24507 }
24508 goto handle_refer_cleanup;
24509 }
24510
24511
24512
24513
24514 if (current.chan1 && current.chan2) {
24515 ast_debug(3, "chan1->name: %s\n", current.chan1->name);
24516 pbx_builtin_setvar_helper(current.chan1, "BLINDTRANSFER", current.chan2->name);
24517 }
24518
24519 if (current.chan2) {
24520 pbx_builtin_setvar_helper(current.chan2, "BLINDTRANSFER", current.chan1->name);
24521 pbx_builtin_setvar_helper(current.chan2, "SIPDOMAIN", refer_to_domain);
24522 pbx_builtin_setvar_helper(current.chan2, "SIPTRANSFER", "yes");
24523
24524 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER", "yes");
24525
24526 if (!ast_strlen_zero(referred_by)) {
24527 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REFERER", referred_by);
24528 }
24529 }
24530
24531 sip_pvt_lock(p);
24532
24533 if (!ast_strlen_zero(p->refer->replaces_callid)) {
24534 char tempheader[SIPBUFSIZE];
24535 snprintf(tempheader, sizeof(tempheader), "%s%s%s%s%s", p->refer->replaces_callid,
24536 p->refer->replaces_callid_totag ? ";to-tag=" : "",
24537 p->refer->replaces_callid_totag,
24538 p->refer->replaces_callid_fromtag ? ";from-tag=" : "",
24539 p->refer->replaces_callid_fromtag);
24540
24541 if (current.chan2) {
24542 sip_pvt_unlock(p);
24543 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REPLACES", tempheader);
24544 sip_pvt_lock(p);
24545 }
24546 }
24547
24548
24549
24550
24551 if (!p->refer->attendedtransfer) {
24552 transmit_notify_with_sipfrag(p, seqno, "180 Ringing", FALSE);
24553 }
24554
24555
24556
24557
24558
24559 if (!current.chan2) {
24560
24561
24562
24563
24564
24565
24566
24567 p->refer->status = REFER_FAILED;
24568 transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable (can't handle one-legged xfers)", TRUE);
24569 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
24570 append_history(p, "Xfer", "Refer failed (only bridged calls).");
24571 res = -1;
24572 goto handle_refer_cleanup;
24573 }
24574 ast_set_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
24575
24576
24577
24578
24579
24580
24581
24582 sip_pvt_unlock(p);
24583 ast_indicate(current.chan2, AST_CONTROL_UNHOLD);
24584 res = ast_async_goto(current.chan2, refer_to_context, refer_to, 1);
24585
24586 if (!res) {
24587 ast_manager_event_multichan(EVENT_FLAG_CALL, "Transfer", 2, chans,
24588 "TransferMethod: SIP\r\n"
24589 "TransferType: Blind\r\n"
24590 "Channel: %s\r\n"
24591 "Uniqueid: %s\r\n"
24592 "SIP-Callid: %s\r\n"
24593 "TargetChannel: %s\r\n"
24594 "TargetUniqueid: %s\r\n"
24595 "TransferExten: %s\r\n"
24596 "TransferContext: %s\r\n",
24597 current.chan1->name,
24598 current.chan1->uniqueid,
24599 callid,
24600 current.chan2->name,
24601 current.chan2->uniqueid,
24602 refer_to,
24603 refer_to_context);
24604
24605 ast_debug(3, "%s transfer succeeded. Telling transferer.\n", attendedtransfer? "Attended" : "Blind");
24606
24607
24608 ast_channel_lock(current.chan1);
24609 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);
24610 ast_channel_unlock(current.chan1);
24611
24612 sip_pvt_lock(p);
24613 transmit_notify_with_sipfrag(p, seqno, "200 Ok", TRUE);
24614 if (p->refer->localtransfer) {
24615 p->refer->status = REFER_200OK;
24616 }
24617 if (p->owner) {
24618 p->owner->hangupcause = AST_CAUSE_NORMAL_CLEARING;
24619 }
24620 append_history(p, "Xfer", "Refer succeeded.");
24621 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
24622
24623
24624 res = 0;
24625 } else {
24626 sip_pvt_lock(p);
24627 ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
24628 ast_debug(3, "%s transfer failed. Resuming original call.\n", p->refer->attendedtransfer? "Attended" : "Blind");
24629 append_history(p, "Xfer", "Refer failed.");
24630
24631 p->refer->status = REFER_FAILED;
24632 transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable", TRUE);
24633 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
24634 res = -1;
24635 }
24636
24637 handle_refer_cleanup:
24638 if (current.chan1) {
24639 ast_channel_unref(current.chan1);
24640 }
24641 if (current.chan2) {
24642 ast_channel_unref(current.chan2);
24643 }
24644
24645
24646 return res;
24647 }
24648
24649
24650 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req)
24651 {
24652
24653 check_via(p, req);
24654 sip_alreadygone(p);
24655
24656 if (p->owner && p->owner->_state == AST_STATE_UP) {
24657
24658 transmit_response(p, "200 OK", req);
24659 ast_debug(1, "Got CANCEL on an answered call. Ignoring... \n");
24660 return 0;
24661 }
24662
24663
24664
24665
24666
24667
24668 if (p->invitestate == INV_TERMINATED || p->invitestate == INV_COMPLETED) {
24669 __sip_pretend_ack(p);
24670 }
24671 if (p->invitestate != INV_TERMINATED)
24672 p->invitestate = INV_CANCELLED;
24673
24674 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD))
24675 update_call_counter(p, DEC_CALL_LIMIT);
24676
24677 stop_media_flows(p);
24678 if (p->owner) {
24679 sip_queue_hangup_cause(p, 0);
24680 } else {
24681 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
24682 }
24683 if (ast_str_strlen(p->initreq.data) > 0) {
24684 struct sip_pkt *pkt, *prev_pkt;
24685
24686
24687
24688
24689
24690
24691
24692
24693
24694
24695
24696 for (pkt = p->packets, prev_pkt = NULL; pkt; prev_pkt = pkt, pkt = pkt->next) {
24697 if (pkt->seqno == p->lastinvite && pkt->response_code == 487) {
24698 AST_SCHED_DEL(sched, pkt->retransid);
24699 UNLINK(pkt, p->packets, prev_pkt);
24700 dialog_unref(pkt->owner, "unref packet->owner from dialog");
24701 if (pkt->data) {
24702 ast_free(pkt->data);
24703 }
24704 ast_free(pkt);
24705 break;
24706 }
24707 }
24708 transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
24709 transmit_response(p, "200 OK", req);
24710 return 1;
24711 } else {
24712 transmit_response(p, "481 Call Leg Does Not Exist", req);
24713 return 0;
24714 }
24715 }
24716
24717
24718 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req)
24719 {
24720 struct ast_channel *c=NULL;
24721 int res;
24722 struct ast_channel *bridged_to;
24723 const char *required;
24724
24725
24726 if (p->pendinginvite && !ast_test_flag(&p->flags[0], SIP_OUTGOING) && !req->ignore) {
24727 transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
24728 }
24729
24730 __sip_pretend_ack(p);
24731
24732 p->invitestate = INV_TERMINATED;
24733
24734 copy_request(&p->initreq, req);
24735 if (sipdebug)
24736 ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
24737 check_via(p, req);
24738 sip_alreadygone(p);
24739
24740
24741 if (p->do_history || p->owner) {
24742 char quality_buf[AST_MAX_USER_FIELD], *quality;
24743 struct ast_channel *bridge = p->owner ? ast_bridged_channel(p->owner) : NULL;
24744
24745
24746
24747
24748 while (bridge && ast_channel_trylock(bridge)) {
24749 ast_channel_unlock(p->owner);
24750 do {
24751
24752 sip_pvt_unlock(p);
24753 usleep(1);
24754 sip_pvt_lock(p);
24755 } while (p->owner && ast_channel_trylock(p->owner));
24756 bridge = p->owner ? ast_bridged_channel(p->owner) : NULL;
24757 }
24758
24759
24760 if (p->rtp && (quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
24761 if (p->do_history) {
24762 append_history(p, "RTCPaudio", "Quality:%s", quality);
24763
24764 if ((quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY_JITTER, quality_buf, sizeof(quality_buf)))) {
24765 append_history(p, "RTCPaudioJitter", "Quality:%s", quality);
24766 }
24767 if ((quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY_LOSS, quality_buf, sizeof(quality_buf)))) {
24768 append_history(p, "RTCPaudioLoss", "Quality:%s", quality);
24769 }
24770 if ((quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY_RTT, quality_buf, sizeof(quality_buf)))) {
24771 append_history(p, "RTCPaudioRTT", "Quality:%s", quality);
24772 }
24773 }
24774
24775 if (p->owner) {
24776 ast_rtp_instance_set_stats_vars(p->owner, p->rtp);
24777 }
24778
24779 }
24780
24781 if (bridge) {
24782 struct sip_pvt *q = bridge->tech_pvt;
24783
24784 if (IS_SIP_TECH(bridge->tech) && q && q->rtp) {
24785 ast_rtp_instance_set_stats_vars(bridge, q->rtp);
24786 }
24787 ast_channel_unlock(bridge);
24788 }
24789
24790 if (p->vrtp && (quality = ast_rtp_instance_get_quality(p->vrtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
24791 if (p->do_history) {
24792 append_history(p, "RTCPvideo", "Quality:%s", quality);
24793 }
24794 if (p->owner) {
24795 pbx_builtin_setvar_helper(p->owner, "RTPVIDEOQOS", quality);
24796 }
24797 }
24798 if (p->trtp && (quality = ast_rtp_instance_get_quality(p->trtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
24799 if (p->do_history) {
24800 append_history(p, "RTCPtext", "Quality:%s", quality);
24801 }
24802 if (p->owner) {
24803 pbx_builtin_setvar_helper(p->owner, "RTPTEXTQOS", quality);
24804 }
24805 }
24806 }
24807
24808 stop_media_flows(p);
24809 stop_session_timer(p);
24810
24811 if (!ast_strlen_zero(get_header(req, "Also"))) {
24812 ast_log(LOG_NOTICE, "Client '%s' using deprecated BYE/Also transfer method. Ask vendor to support REFER instead\n",
24813 ast_sockaddr_stringify(&p->recv));
24814 if (ast_strlen_zero(p->context))
24815 ast_string_field_set(p, context, sip_cfg.default_context);
24816 res = get_also_info(p, req);
24817 if (!res) {
24818 c = p->owner;
24819 if (c) {
24820 bridged_to = ast_bridged_channel(c);
24821 if (bridged_to) {
24822
24823 ast_queue_control(c, AST_CONTROL_UNHOLD);
24824 ast_channel_unlock(c);
24825 ast_async_goto(bridged_to, p->context, p->refer->refer_to, 1);
24826 ast_channel_lock(c);
24827 } else
24828 ast_queue_hangup(p->owner);
24829 }
24830 } else {
24831 ast_log(LOG_WARNING, "Invalid transfer information from '%s'\n", ast_sockaddr_stringify(&p->recv));
24832 if (p->owner)
24833 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
24834 }
24835 } else if (p->owner) {
24836 sip_queue_hangup_cause(p, 0);
24837 sip_scheddestroy_final(p, DEFAULT_TRANS_TIMEOUT);
24838 ast_debug(3, "Received bye, issuing owner hangup\n");
24839 } else {
24840 sip_scheddestroy_final(p, DEFAULT_TRANS_TIMEOUT);
24841 ast_debug(3, "Received bye, no owner, selfdestruct soon.\n");
24842 }
24843 ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
24844
24845
24846 required = get_header(req, "Require");
24847 if (!ast_strlen_zero(required)) {
24848 char unsupported[256] = { 0, };
24849 parse_sip_options(required, unsupported, ARRAY_LEN(unsupported));
24850
24851
24852 if (!ast_strlen_zero(unsupported)) {
24853 transmit_response_with_unsupported(p, "420 Bad extension (unsupported)", req, unsupported);
24854 ast_log(LOG_WARNING, "Received SIP BYE with unsupported required extension: required:%s unsupported:%s\n", required, unsupported);
24855 } else {
24856 transmit_response(p, "200 OK", req);
24857 }
24858 } else {
24859 transmit_response(p, "200 OK", req);
24860 }
24861
24862 return 1;
24863 }
24864
24865
24866 static int handle_request_message(struct sip_pvt *p, struct sip_request *req)
24867 {
24868 if (!req->ignore) {
24869 if (req->debug)
24870 ast_verbose("Receiving message!\n");
24871 receive_message(p, req);
24872 } else
24873 transmit_response(p, "202 Accepted", req);
24874 return 1;
24875 }
24876
24877 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)
24878 {
24879 int etag_present = !ast_strlen_zero(etag);
24880 int body_present = req->lines > 0;
24881
24882 ast_assert(expires_int != NULL);
24883
24884 if (ast_strlen_zero(expires)) {
24885
24886
24887
24888
24889 *expires_int = DEFAULT_PUBLISH_EXPIRES;
24890 } else if (sscanf(expires, "%30d", expires_int) != 1) {
24891 return SIP_PUBLISH_UNKNOWN;
24892 }
24893
24894 if (*expires_int == 0) {
24895 return SIP_PUBLISH_REMOVE;
24896 } else if (!etag_present && body_present) {
24897 return SIP_PUBLISH_INITIAL;
24898 } else if (etag_present && !body_present) {
24899 return SIP_PUBLISH_REFRESH;
24900 } else if (etag_present && body_present) {
24901 return SIP_PUBLISH_MODIFY;
24902 }
24903
24904 return SIP_PUBLISH_UNKNOWN;
24905 }
24906
24907 #ifdef HAVE_LIBXML2
24908 static void get_pidf_body(struct sip_request *req, char *pidf_body, size_t size)
24909 {
24910 int i;
24911 struct ast_str *str = ast_str_alloca(size);
24912 for (i = 0; i < req->lines; ++i) {
24913 ast_str_append(&str, 0, "%s", REQ_OFFSET_TO_STR(req, line[i]));
24914 }
24915 ast_copy_string(pidf_body, ast_str_buffer(str), size);
24916 }
24917
24918 static int pidf_validate_tuple(struct ast_xml_node *tuple_node)
24919 {
24920 const char *id;
24921 int status_found = FALSE;
24922 struct ast_xml_node *tuple_children;
24923 struct ast_xml_node *tuple_children_iterator;
24924
24925 if (!(id = ast_xml_get_attribute(tuple_node, "id"))) {
24926 ast_log(LOG_WARNING, "Tuple XML element has no attribute 'id'\n");
24927 return FALSE;
24928 }
24929
24930 ast_xml_free_attr(id);
24931
24932 if (!(tuple_children = ast_xml_node_get_children(tuple_node))) {
24933
24934 ast_log(LOG_WARNING, "Tuple XML element has no child elements\n");
24935 return FALSE;
24936 }
24937 for (tuple_children_iterator = tuple_children; tuple_children_iterator;
24938 tuple_children_iterator = ast_xml_node_get_next(tuple_children_iterator)) {
24939
24940
24941
24942
24943 if (strcmp(ast_xml_node_get_name(tuple_children_iterator), "status")) {
24944
24945 continue;
24946 }
24947 if (status_found == TRUE) {
24948
24949 ast_log(LOG_WARNING, "Multiple status elements found in tuple. Only one allowed\n");
24950 return FALSE;
24951 }
24952 status_found = TRUE;
24953 }
24954 return status_found;
24955 }
24956
24957
24958 static int pidf_validate_presence(struct ast_xml_doc *doc)
24959 {
24960 struct ast_xml_node *presence_node = ast_xml_get_root(doc);
24961 struct ast_xml_node *child_nodes;
24962 struct ast_xml_node *node_iterator;
24963 struct ast_xml_ns *ns;
24964 const char *entity;
24965 const char *namespace;
24966 const char presence_namespace[] = "urn:ietf:params:xml:ns:pidf";
24967
24968 if (!presence_node) {
24969 ast_log(LOG_WARNING, "Unable to retrieve root node of the XML document\n");
24970 return FALSE;
24971 }
24972
24973
24974
24975 if (strcmp(ast_xml_node_get_name(presence_node), "presence")) {
24976 ast_log(LOG_WARNING, "Root node of PIDF document is not 'presence'. Invalid\n");
24977 return FALSE;
24978 }
24979
24980
24981
24982
24983 if (!(entity = ast_xml_get_attribute(presence_node, "entity"))) {
24984 ast_log(LOG_WARNING, "Presence element of PIDF document has no 'entity' attribute\n");
24985 return FALSE;
24986 }
24987
24988 ast_xml_free_attr(entity);
24989
24990 if (!(ns = ast_xml_find_namespace(doc, presence_node, NULL))) {
24991 ast_log(LOG_WARNING, "Couldn't find default namespace...\n");
24992 return FALSE;
24993 }
24994
24995 namespace = ast_xml_get_ns_href(ns);
24996 if (ast_strlen_zero(namespace) || strcmp(namespace, presence_namespace)) {
24997 ast_log(LOG_WARNING, "PIDF document has invalid namespace value %s\n", namespace);
24998 return FALSE;
24999 }
25000
25001 if (!(child_nodes = ast_xml_node_get_children(presence_node))) {
25002 ast_log(LOG_WARNING, "PIDF document has no elements as children of 'presence'. Invalid\n");
25003 return FALSE;
25004 }
25005
25006
25007
25008
25009
25010
25011
25012
25013
25014 for (node_iterator = child_nodes; node_iterator;
25015 node_iterator = ast_xml_node_get_next(node_iterator)) {
25016 if (strcmp(ast_xml_node_get_name(node_iterator), "tuple")) {
25017
25018 continue;
25019 }
25020 if (pidf_validate_tuple(node_iterator) == FALSE) {
25021 ast_log(LOG_WARNING, "Unable to validate tuple\n");
25022 return FALSE;
25023 }
25024 }
25025
25026 return TRUE;
25027 }
25028
25029
25030
25031
25032
25033
25034
25035
25036
25037
25038
25039
25040
25041
25042
25043
25044 static int sip_pidf_validate(struct sip_request *req, struct ast_xml_doc **pidf_doc)
25045 {
25046 struct ast_xml_doc *doc;
25047 int content_length;
25048 const char *content_length_str = get_header(req, "Content-Length");
25049 const char *content_type = get_header(req, "Content-Type");
25050 char pidf_body[SIPBUFSIZE];
25051 int res;
25052
25053 if (ast_strlen_zero(content_type) || strcmp(content_type, "application/pidf+xml")) {
25054 ast_log(LOG_WARNING, "Content type is not PIDF\n");
25055 return FALSE;
25056 }
25057
25058 if (ast_strlen_zero(content_length_str)) {
25059 ast_log(LOG_WARNING, "No content length. Can't determine bounds of PIDF document\n");
25060 return FALSE;
25061 }
25062
25063 if (sscanf(content_length_str, "%30d", &content_length) != 1) {
25064 ast_log(LOG_WARNING, "Invalid content length provided\n");
25065 return FALSE;
25066 }
25067
25068 if (content_length > sizeof(pidf_body)) {
25069 ast_log(LOG_WARNING, "Content length of PIDF document truncated to %d bytes\n", (int) sizeof(pidf_body));
25070 content_length = sizeof(pidf_body);
25071 }
25072
25073 get_pidf_body(req, pidf_body, content_length);
25074
25075 if (!(doc = ast_xml_read_memory(pidf_body, content_length))) {
25076 ast_log(LOG_WARNING, "Unable to open XML PIDF document. Is it malformed?\n");
25077 return FALSE;
25078 }
25079
25080 res = pidf_validate_presence(doc);
25081 if (res == TRUE) {
25082 *pidf_doc = doc;
25083 } else {
25084 ast_xml_close(doc);
25085 }
25086 return res;
25087 }
25088
25089 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)
25090 {
25091 const char *uri = REQ_OFFSET_TO_STR(req, rlPart2);
25092 struct ast_cc_agent *agent;
25093 struct sip_cc_agent_pvt *agent_pvt;
25094 struct ast_xml_doc *pidf_doc = NULL;
25095 const char *basic_status = NULL;
25096 struct ast_xml_node *presence_node;
25097 struct ast_xml_node *presence_children;
25098 struct ast_xml_node *tuple_node;
25099 struct ast_xml_node *tuple_children;
25100 struct ast_xml_node *status_node;
25101 struct ast_xml_node *status_children;
25102 struct ast_xml_node *basic_node;
25103 int res = 0;
25104
25105 if (!((agent = find_sip_cc_agent_by_notify_uri(uri)) || (agent = find_sip_cc_agent_by_subscribe_uri(uri)))) {
25106 ast_log(LOG_WARNING, "Could not find agent using uri '%s'\n", uri);
25107 transmit_response(pvt, "412 Conditional Request Failed", req);
25108 return -1;
25109 }
25110
25111 agent_pvt = agent->private_data;
25112
25113 if (sip_pidf_validate(req, &pidf_doc) == FALSE) {
25114 res = -1;
25115 goto cc_publish_cleanup;
25116 }
25117
25118
25119
25120
25121
25122
25123
25124 presence_node = ast_xml_get_root(pidf_doc);
25125 if (!(presence_children = ast_xml_node_get_children(presence_node))) {
25126 ast_log(LOG_WARNING, "No tuples within presence element.\n");
25127 res = -1;
25128 goto cc_publish_cleanup;
25129 }
25130
25131 if (!(tuple_node = ast_xml_find_element(presence_children, "tuple", NULL, NULL))) {
25132 ast_log(LOG_NOTICE, "Couldn't find tuple node?\n");
25133 res = -1;
25134 goto cc_publish_cleanup;
25135 }
25136
25137
25138
25139
25140 tuple_children = ast_xml_node_get_children(tuple_node);
25141
25142 status_node = ast_xml_find_element(tuple_children, "status", NULL, NULL);
25143
25144 if (!(status_children = ast_xml_node_get_children(status_node))) {
25145 ast_log(LOG_WARNING, "No basic elements within status element.\n");
25146 res = -1;
25147 goto cc_publish_cleanup;
25148 }
25149
25150 if (!(basic_node = ast_xml_find_element(status_children, "basic", NULL, NULL))) {
25151 ast_log(LOG_WARNING, "Couldn't find basic node?\n");
25152 res = -1;
25153 goto cc_publish_cleanup;
25154 }
25155
25156 basic_status = ast_xml_get_text(basic_node);
25157
25158 if (ast_strlen_zero(basic_status)) {
25159 ast_log(LOG_NOTICE, "NOthing in basic node?\n");
25160 res = -1;
25161 goto cc_publish_cleanup;
25162 }
25163
25164 if (!strcmp(basic_status, "open")) {
25165 agent_pvt->is_available = TRUE;
25166 ast_cc_agent_caller_available(agent->core_id, "Received PUBLISH stating SIP caller %s is available",
25167 agent->device_name);
25168 } else if (!strcmp(basic_status, "closed")) {
25169 agent_pvt->is_available = FALSE;
25170 ast_cc_agent_caller_busy(agent->core_id, "Received PUBLISH stating SIP caller %s is busy",
25171 agent->device_name);
25172 } else {
25173 ast_log(LOG_NOTICE, "Invalid content in basic element: %s\n", basic_status);
25174 }
25175
25176 cc_publish_cleanup:
25177 if (basic_status) {
25178 ast_xml_free_text(basic_status);
25179 }
25180 if (pidf_doc) {
25181 ast_xml_close(pidf_doc);
25182 }
25183 ao2_ref(agent, -1);
25184 if (res) {
25185 transmit_response(pvt, "400 Bad Request", req);
25186 }
25187 return res;
25188 }
25189
25190 #endif
25191
25192 static int handle_sip_publish_initial(struct sip_pvt *p, struct sip_request *req, struct event_state_compositor *esc, const int expires)
25193 {
25194 struct sip_esc_entry *esc_entry = create_esc_entry(esc, req, expires);
25195 int res = 0;
25196
25197 if (!esc_entry) {
25198 transmit_response(p, "503 Internal Server Failure", req);
25199 return -1;
25200 }
25201
25202 if (esc->callbacks->initial_handler) {
25203 res = esc->callbacks->initial_handler(p, req, esc, esc_entry);
25204 }
25205
25206 if (!res) {
25207 transmit_response_with_sip_etag(p, "200 OK", req, esc_entry, 0);
25208 }
25209
25210 ao2_ref(esc_entry, -1);
25211 return res;
25212 }
25213
25214 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)
25215 {
25216 struct sip_esc_entry *esc_entry = get_esc_entry(etag, esc);
25217 int expires_ms = expires * 1000;
25218 int res = 0;
25219
25220 if (!esc_entry) {
25221 transmit_response(p, "412 Conditional Request Failed", req);
25222 return -1;
25223 }
25224
25225 AST_SCHED_REPLACE_UNREF(esc_entry->sched_id, sched, expires_ms, publish_expire, esc_entry,
25226 ao2_ref(_data, -1),
25227 ao2_ref(esc_entry, -1),
25228 ao2_ref(esc_entry, +1));
25229
25230 if (esc->callbacks->refresh_handler) {
25231 res = esc->callbacks->refresh_handler(p, req, esc, esc_entry);
25232 }
25233
25234 if (!res) {
25235 transmit_response_with_sip_etag(p, "200 OK", req, esc_entry, 1);
25236 }
25237
25238 ao2_ref(esc_entry, -1);
25239 return res;
25240 }
25241
25242 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)
25243 {
25244 struct sip_esc_entry *esc_entry = get_esc_entry(etag, esc);
25245 int expires_ms = expires * 1000;
25246 int res = 0;
25247
25248 if (!esc_entry) {
25249 transmit_response(p, "412 Conditional Request Failed", req);
25250 return -1;
25251 }
25252
25253 AST_SCHED_REPLACE_UNREF(esc_entry->sched_id, sched, expires_ms, publish_expire, esc_entry,
25254 ao2_ref(_data, -1),
25255 ao2_ref(esc_entry, -1),
25256 ao2_ref(esc_entry, +1));
25257
25258 if (esc->callbacks->modify_handler) {
25259 res = esc->callbacks->modify_handler(p, req, esc, esc_entry);
25260 }
25261
25262 if (!res) {
25263 transmit_response_with_sip_etag(p, "200 OK", req, esc_entry, 1);
25264 }
25265
25266 ao2_ref(esc_entry, -1);
25267 return res;
25268 }
25269
25270 static int handle_sip_publish_remove(struct sip_pvt *p, struct sip_request *req, struct event_state_compositor *esc, const char * const etag)
25271 {
25272 struct sip_esc_entry *esc_entry = get_esc_entry(etag, esc);
25273 int res = 0;
25274
25275 if (!esc_entry) {
25276 transmit_response(p, "412 Conditional Request Failed", req);
25277 return -1;
25278 }
25279
25280 AST_SCHED_DEL(sched, esc_entry->sched_id);
25281
25282 ao2_ref(esc_entry, -1);
25283
25284 if (esc->callbacks->remove_handler) {
25285 res = esc->callbacks->remove_handler(p, req, esc, esc_entry);
25286 }
25287
25288 if (!res) {
25289 transmit_response_with_sip_etag(p, "200 OK", req, esc_entry, 1);
25290 }
25291
25292
25293 ao2_unlink(esc->compositor, esc_entry);
25294 ao2_ref(esc_entry, -1);
25295 return res;
25296 }
25297
25298 static int handle_request_publish(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const uint32_t seqno, const char *uri)
25299 {
25300 const char *etag = get_header(req, "SIP-If-Match");
25301 const char *event = get_header(req, "Event");
25302 struct event_state_compositor *esc;
25303 enum sip_publish_type publish_type;
25304 const char *expires_str = get_header(req, "Expires");
25305 int expires_int;
25306 int auth_result;
25307 int handler_result = -1;
25308
25309 if (ast_strlen_zero(event)) {
25310 transmit_response(p, "489 Bad Event", req);
25311 pvt_set_needdestroy(p, "missing Event: header");
25312 return -1;
25313 }
25314
25315 if (!(esc = get_esc(event))) {
25316 transmit_response(p, "489 Bad Event", req);
25317 pvt_set_needdestroy(p, "unknown event package in publish");
25318 return -1;
25319 }
25320
25321 auth_result = check_user(p, req, SIP_PUBLISH, uri, XMIT_UNRELIABLE, addr);
25322 if (auth_result == AUTH_CHALLENGE_SENT) {
25323 p->lastinvite = seqno;
25324 return 0;
25325 } else if (auth_result < 0) {
25326 ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", get_header(req, "From"));
25327 transmit_response(p, "403 Forbidden", req);
25328 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
25329 ast_string_field_set(p, theirtag, NULL);
25330 return 0;
25331 } else if (auth_result == AUTH_SUCCESSFUL && p->lastinvite) {
25332
25333 __sip_ack(p, p->lastinvite, 1, 0);
25334 }
25335
25336 publish_type = determine_sip_publish_type(req, event, etag, expires_str, &expires_int);
25337
25338 if (expires_int > max_expiry) {
25339 expires_int = max_expiry;
25340 } else if (expires_int < min_expiry && expires_int > 0) {
25341 transmit_response_with_minexpires(p, "423 Interval too small", req);
25342 pvt_set_needdestroy(p, "Expires is less that the min expires allowed.");
25343 return 0;
25344 }
25345 p->expiry = expires_int;
25346
25347
25348
25349
25350 switch (publish_type) {
25351 case SIP_PUBLISH_UNKNOWN:
25352 transmit_response(p, "400 Bad Request", req);
25353 break;
25354 case SIP_PUBLISH_INITIAL:
25355 handler_result = handle_sip_publish_initial(p, req, esc, expires_int);
25356 break;
25357 case SIP_PUBLISH_REFRESH:
25358 handler_result = handle_sip_publish_refresh(p, req, esc, etag, expires_int);
25359 break;
25360 case SIP_PUBLISH_MODIFY:
25361 handler_result = handle_sip_publish_modify(p, req, esc, etag, expires_int);
25362 break;
25363 case SIP_PUBLISH_REMOVE:
25364 handler_result = handle_sip_publish_remove(p, req, esc, etag);
25365 break;
25366 default:
25367 transmit_response(p, "400 Impossible Condition", req);
25368 break;
25369 }
25370 if (!handler_result && p->expiry > 0) {
25371 sip_scheddestroy(p, (p->expiry + 10) * 1000);
25372 } else {
25373 pvt_set_needdestroy(p, "forcing expiration");
25374 }
25375
25376 return handler_result;
25377 }
25378
25379
25380
25381
25382
25383
25384
25385 static void add_peer_mwi_subs(struct sip_peer *peer)
25386 {
25387 struct sip_mailbox *mailbox;
25388
25389 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
25390 if (mailbox->event_sub) {
25391 ast_event_unsubscribe(mailbox->event_sub);
25392 }
25393
25394 mailbox->event_sub = ast_event_subscribe(AST_EVENT_MWI, mwi_event_cb, "SIP mbox event", peer,
25395 AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox->mailbox,
25396 AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, S_OR(mailbox->context, "default"),
25397 AST_EVENT_IE_END);
25398 }
25399 }
25400
25401 static int handle_cc_subscribe(struct sip_pvt *p, struct sip_request *req)
25402 {
25403 const char *uri = REQ_OFFSET_TO_STR(req, rlPart2);
25404 char *param_separator;
25405 struct ast_cc_agent *agent;
25406 struct sip_cc_agent_pvt *agent_pvt;
25407 const char *expires_str = get_header(req, "Expires");
25408 int expires = -1;
25409
25410 if (!ast_strlen_zero(expires_str)) {
25411 sscanf(expires_str, "%d", &expires);
25412 }
25413
25414 if ((param_separator = strchr(uri, ';'))) {
25415 *param_separator = '\0';
25416 }
25417
25418 p->subscribed = CALL_COMPLETION;
25419
25420 if (!(agent = find_sip_cc_agent_by_subscribe_uri(uri))) {
25421 if (!expires) {
25422
25423
25424
25425
25426
25427
25428 transmit_response(p, "200 OK", req);
25429 return 0;
25430 }
25431 ast_log(LOG_WARNING, "Invalid URI '%s' in CC subscribe\n", uri);
25432 transmit_response(p, "404 Not Found", req);
25433 return -1;
25434 }
25435
25436 agent_pvt = agent->private_data;
25437
25438 if (!expires) {
25439
25440
25441
25442 ast_cc_failed(agent->core_id, "CC is being canceled by %s", agent->device_name);
25443 transmit_response(p, "200 OK", req);
25444 ao2_ref(agent, -1);
25445 return 0;
25446 }
25447
25448 agent_pvt->subscribe_pvt = dialog_ref(p, "SIP CC agent gains reference to subscription dialog");
25449 ast_cc_agent_accept_request(agent->core_id, "SIP caller %s has requested CC via SUBSCRIBE",
25450 agent->device_name);
25451
25452
25453
25454
25455 ao2_ref(agent, -1);
25456 return 0;
25457 }
25458
25459
25460 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e)
25461 {
25462 int gotdest = 0;
25463 int res = 0;
25464 int firststate;
25465 struct sip_peer *authpeer = NULL;
25466 const char *eventheader = get_header(req, "Event");
25467 int resubscribe = (p->subscribed != NONE) && !req->ignore;
25468 char *event_end;
25469 ptrdiff_t event_len = 0;
25470
25471 if (p->initreq.headers) {
25472
25473 if (p->initreq.method != SIP_SUBSCRIBE) {
25474
25475
25476 transmit_response(p, "403 Forbidden (within dialog)", req);
25477
25478 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);
25479 return 0;
25480 } else if (req->debug) {
25481 if (resubscribe)
25482 ast_debug(1, "Got a re-subscribe on existing subscription %s\n", p->callid);
25483 else
25484 ast_debug(1, "Got a new subscription %s (possibly with auth) or retransmission\n", p->callid);
25485 }
25486 }
25487
25488
25489
25490
25491 if (!sip_cfg.allowsubscribe) {
25492 transmit_response(p, "403 Forbidden (policy)", req);
25493 pvt_set_needdestroy(p, "forbidden");
25494 return 0;
25495 }
25496
25497 if (!req->ignore && !resubscribe) {
25498 const char *to = get_header(req, "To");
25499 char totag[128];
25500 set_pvt_allowed_methods(p, req);
25501
25502
25503 if (!ast_strlen_zero(to) && gettag(req, "To", totag, sizeof(totag))) {
25504 if (req->debug)
25505 ast_verbose("Received resubscription for a dialog we no longer know about. Telling remote side to subscribe again.\n");
25506 transmit_response(p, "481 Subscription does not exist", req);
25507 pvt_set_needdestroy(p, "subscription does not exist");
25508 return 0;
25509 }
25510
25511
25512 if (req->debug)
25513 ast_verbose("Creating new subscription\n");
25514
25515 copy_request(&p->initreq, req);
25516 if (sipdebug)
25517 ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
25518 check_via(p, req);
25519 build_route(p, req, 0, 0);
25520 } else if (req->debug && req->ignore)
25521 ast_verbose("Ignoring this SUBSCRIBE request\n");
25522
25523
25524 if (ast_strlen_zero(eventheader)) {
25525 transmit_response(p, "489 Bad Event", req);
25526 ast_debug(2, "Received SIP subscribe for unknown event package: <none>\n");
25527 pvt_set_needdestroy(p, "unknown event package in subscribe");
25528 return 0;
25529 }
25530
25531 event_end = strchr(eventheader, ';');
25532 if (event_end) {
25533 event_len = event_end - eventheader;
25534 }
25535
25536
25537
25538
25539 if (p->subscribed == NONE || resubscribe) {
25540 res = check_user_full(p, req, SIP_SUBSCRIBE, e, XMIT_UNRELIABLE, addr, &authpeer);
25541
25542
25543 if (res == AUTH_CHALLENGE_SENT)
25544 return 0;
25545 if (res != AUTH_SUCCESSFUL) {
25546 ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", get_header(req, "From"));
25547 transmit_response(p, "403 Forbidden", req);
25548
25549 pvt_set_needdestroy(p, "authentication failed");
25550 return 0;
25551 }
25552 }
25553
25554
25555
25556
25557
25558
25559 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
25560 transmit_response(p, "403 Forbidden (policy)", req);
25561 pvt_set_needdestroy(p, "subscription not allowed");
25562 if (authpeer) {
25563 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 1)");
25564 }
25565 return 0;
25566 }
25567
25568 if (strncmp(eventheader, "message-summary", MAX(event_len, 15)) && strncmp(eventheader, "call-completion", MAX(event_len, 15))) {
25569
25570 gotdest = get_destination(p, NULL, NULL);
25571 }
25572
25573
25574 parse_ok_contact(p, req);
25575
25576 build_contact(p);
25577 if (gotdest != SIP_GET_DEST_EXTEN_FOUND) {
25578 if (gotdest == SIP_GET_DEST_INVALID_URI) {
25579 transmit_response(p, "416 Unsupported URI scheme", req);
25580 } else {
25581 transmit_response(p, "404 Not Found", req);
25582 }
25583 pvt_set_needdestroy(p, "subscription target not found");
25584 if (authpeer) {
25585 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
25586 }
25587 return 0;
25588 }
25589
25590
25591 if (ast_strlen_zero(p->tag))
25592 make_our_tag(p);
25593
25594 if (!strncmp(eventheader, "presence", MAX(event_len, 8)) || !strncmp(eventheader, "dialog", MAX(event_len, 6))) {
25595 unsigned int pidf_xml;
25596 const char *accept;
25597 int start = 0;
25598 enum subscriptiontype subscribed = NONE;
25599 const char *unknown_acceptheader = NULL;
25600
25601
25602 accept = __get_header(req, "Accept", &start);
25603 while ((subscribed == NONE) && !ast_strlen_zero(accept)) {
25604 pidf_xml = strstr(accept, "application/pidf+xml") ? 1 : 0;
25605
25606
25607
25608 if (pidf_xml && strstr(p->useragent, "Polycom")) {
25609 subscribed = XPIDF_XML;
25610 } else if (pidf_xml) {
25611 subscribed = PIDF_XML;
25612 } else if (strstr(accept, "application/dialog-info+xml")) {
25613 subscribed = DIALOG_INFO_XML;
25614
25615 } else if (strstr(accept, "application/cpim-pidf+xml")) {
25616 subscribed = CPIM_PIDF_XML;
25617 } else if (strstr(accept, "application/xpidf+xml")) {
25618 subscribed = XPIDF_XML;
25619 } else {
25620 unknown_acceptheader = accept;
25621 }
25622
25623 accept = __get_header(req, "Accept", &start);
25624 }
25625
25626 if (!start) {
25627 if (p->subscribed == NONE) {
25628 transmit_response(p, "489 Bad Event", req);
25629 ast_log(LOG_WARNING,"SUBSCRIBE failure: no Accept header: pvt: "
25630 "stateid: %d, laststate: %d, dialogver: %u, subscribecont: "
25631 "'%s', subscribeuri: '%s'\n",
25632 p->stateid,
25633 p->laststate,
25634 p->dialogver,
25635 p->subscribecontext,
25636 p->subscribeuri);
25637 pvt_set_needdestroy(p, "no Accept header");
25638 if (authpeer) {
25639 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
25640 }
25641 return 0;
25642 }
25643
25644
25645 } else if (subscribed == NONE) {
25646
25647 char mybuf[200];
25648 if (!ast_strlen_zero(unknown_acceptheader)) {
25649 snprintf(mybuf, sizeof(mybuf), "489 Bad Event (format %s)", unknown_acceptheader);
25650 } else {
25651 snprintf(mybuf, sizeof(mybuf), "489 Bad Event");
25652 }
25653 transmit_response(p, mybuf, req);
25654 ast_log(LOG_WARNING,"SUBSCRIBE failure: unrecognized format:"
25655 "'%s' pvt: subscribed: %d, stateid: %d, laststate: %d,"
25656 "dialogver: %u, subscribecont: '%s', subscribeuri: '%s'\n",
25657 unknown_acceptheader,
25658 (int)p->subscribed,
25659 p->stateid,
25660 p->laststate,
25661 p->dialogver,
25662 p->subscribecontext,
25663 p->subscribeuri);
25664 pvt_set_needdestroy(p, "unrecognized format");
25665 if (authpeer) {
25666 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
25667 }
25668 return 0;
25669 } else {
25670 p->subscribed = subscribed;
25671 }
25672 } else if (!strncmp(eventheader, "message-summary", MAX(event_len, 15))) {
25673 int start = 0;
25674 int found_supported = 0;
25675 const char *acceptheader;
25676
25677 acceptheader = __get_header(req, "Accept", &start);
25678 while (!found_supported && !ast_strlen_zero(acceptheader)) {
25679 found_supported = strcmp(acceptheader, "application/simple-message-summary") ? 0 : 1;
25680 if (!found_supported && (option_debug > 2)) {
25681 ast_log(LOG_DEBUG, "Received SIP mailbox subscription for unknown format: %s\n", acceptheader);
25682 }
25683 acceptheader = __get_header(req, "Accept", &start);
25684 }
25685 if (start && !found_supported) {
25686
25687 transmit_response(p, "406 Not Acceptable", req);
25688 ast_debug(2, "Received SIP mailbox subscription for unknown format: %s\n", acceptheader);
25689 pvt_set_needdestroy(p, "unknown format");
25690 if (authpeer) {
25691 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 3)");
25692 }
25693 return 0;
25694 }
25695
25696
25697
25698
25699
25700 if (!authpeer || AST_LIST_EMPTY(&authpeer->mailboxes)) {
25701 if (!authpeer) {
25702 transmit_response(p, "404 Not found", req);
25703 } else {
25704 transmit_response(p, "404 Not found (no mailbox)", req);
25705 ast_log(LOG_NOTICE, "Received SIP subscribe for peer without mailbox: %s\n", S_OR(authpeer->name, ""));
25706 }
25707 pvt_set_needdestroy(p, "received 404 response");
25708 if (authpeer) {
25709 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 3)");
25710 }
25711 return 0;
25712 }
25713
25714 p->subscribed = MWI_NOTIFICATION;
25715 if (ast_test_flag(&authpeer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY)) {
25716 ao2_unlock(p);
25717 add_peer_mwi_subs(authpeer);
25718 ao2_lock(p);
25719 }
25720 if (authpeer->mwipvt != p) {
25721
25722 if (authpeer->mwipvt) {
25723 dialog_unlink_all(authpeer->mwipvt);
25724 authpeer->mwipvt = dialog_unref(authpeer->mwipvt, "unref dialog authpeer->mwipvt");
25725 }
25726 authpeer->mwipvt = dialog_ref(p, "setting peers' mwipvt to p");
25727 }
25728 if (p->relatedpeer != authpeer) {
25729 if (p->relatedpeer) {
25730 unref_peer(p->relatedpeer, "Unref previously stored relatedpeer ptr");
25731 }
25732 p->relatedpeer = ref_peer(authpeer, "setting dialog's relatedpeer pointer");
25733 }
25734
25735 } else if (!strncmp(eventheader, "call-completion", MAX(event_len, 15))) {
25736 handle_cc_subscribe(p, req);
25737 } else {
25738 transmit_response(p, "489 Bad Event", req);
25739 ast_debug(2, "Received SIP subscribe for unknown event package: %s\n", eventheader);
25740 pvt_set_needdestroy(p, "unknown event package");
25741 if (authpeer) {
25742 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 5)");
25743 }
25744 return 0;
25745 }
25746
25747
25748 if (p->subscribed != MWI_NOTIFICATION && p->subscribed != CALL_COMPLETION && !resubscribe) {
25749 if (p->stateid != -1) {
25750 ast_extension_state_del(p->stateid, cb_extensionstate);
25751 }
25752 dialog_ref(p, "copying dialog ptr into extension state struct");
25753 p->stateid = ast_extension_state_add_destroy(p->context, p->exten,
25754 cb_extensionstate, cb_extensionstate_destroy, p);
25755 if (p->stateid == -1) {
25756 dialog_unref(p, "copying dialog ptr into extension state struct failed");
25757 }
25758 }
25759
25760 if (!req->ignore) {
25761 p->lastinvite = seqno;
25762 }
25763 if (!p->needdestroy) {
25764 p->expiry = atoi(get_header(req, "Expires"));
25765
25766
25767 if (p->expiry > max_expiry) {
25768 p->expiry = max_expiry;
25769 } else if (p->expiry < min_expiry && p->expiry > 0) {
25770 transmit_response_with_minexpires(p, "423 Interval too small", req);
25771 ast_log(LOG_WARNING, "Received subscription for extension \"%s\" context \"%s\" "
25772 "with Expire header less that 'minexpire' limit. Received \"Expire: %d\" min is %d\n",
25773 p->exten, p->context, p->expiry, min_expiry);
25774 pvt_set_needdestroy(p, "Expires is less that the min expires allowed.");
25775 if (authpeer) {
25776 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 6)");
25777 }
25778 return 0;
25779 }
25780
25781 if (sipdebug) {
25782 const char *action = p->expiry > 0 ? "Adding" : "Removing";
25783 if (p->subscribed == MWI_NOTIFICATION && p->relatedpeer) {
25784 ast_debug(2, "%s subscription for mailbox notification - peer %s\n",
25785 action, p->relatedpeer->name);
25786 } else if (p->subscribed == CALL_COMPLETION) {
25787 ast_debug(2, "%s CC subscription for peer %s\n", action, p->username);
25788 } else {
25789 ast_debug(2, "%s subscription for extension %s context %s for peer %s\n",
25790 action, p->exten, p->context, p->username);
25791 }
25792 }
25793 if (p->autokillid > -1 && sip_cancel_destroy(p))
25794 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
25795 if (p->expiry > 0)
25796 sip_scheddestroy(p, (p->expiry + 10) * 1000);
25797
25798 if (p->subscribed == MWI_NOTIFICATION) {
25799 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
25800 transmit_response(p, "200 OK", req);
25801 if (p->relatedpeer) {
25802 struct sip_peer *peer = p->relatedpeer;
25803 ref_peer(peer, "ensure a peer ref is held during MWI sending");
25804 ao2_unlock(p);
25805 sip_send_mwi_to_peer(peer, 0);
25806 ao2_lock(p);
25807 unref_peer(peer, "release a peer ref now that MWI is sent");
25808 }
25809 } else if (p->subscribed != CALL_COMPLETION) {
25810 sip_pvt_unlock(p);
25811 firststate = ast_extension_state(NULL, p->context, p->exten);
25812 sip_pvt_lock(p);
25813
25814 if (firststate < 0) {
25815 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));
25816 transmit_response(p, "404 Not found", req);
25817 pvt_set_needdestroy(p, "no extension for SUBSCRIBE");
25818 if (authpeer) {
25819 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 6)");
25820 }
25821 return 0;
25822 }
25823 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
25824 transmit_response(p, "200 OK", req);
25825 transmit_state_notify(p, firststate, 1, FALSE);
25826 append_history(p, "Subscribestatus", "%s", ast_extension_state2str(firststate));
25827
25828 ast_string_field_build(p, subscribeuri, "%s@%s", p->exten, p->context);
25829
25830
25831 }
25832 if (!p->expiry) {
25833 pvt_set_needdestroy(p, "forcing expiration");
25834 }
25835 }
25836
25837 if (authpeer) {
25838 unref_peer(authpeer, "unref pointer into (*authpeer)");
25839 }
25840 return 1;
25841 }
25842
25843
25844 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e)
25845 {
25846 enum check_auth_result res;
25847
25848
25849
25850 if (p->initreq.headers && p->initreq.method != SIP_REGISTER) {
25851 ast_log(LOG_WARNING, "Ignoring spurious REGISTER with Call-ID: %s\n", p->callid);
25852 return -1;
25853 }
25854
25855
25856 copy_request(&p->initreq, req);
25857 if (sipdebug)
25858 ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
25859 check_via(p, req);
25860 if ((res = register_verify(p, addr, req, e)) < 0) {
25861 const char *reason;
25862
25863 switch (res) {
25864 case AUTH_SECRET_FAILED:
25865 reason = "Wrong password";
25866 break;
25867 case AUTH_USERNAME_MISMATCH:
25868 reason = "Username/auth name mismatch";
25869 break;
25870 case AUTH_NOT_FOUND:
25871 reason = "No matching peer found";
25872 break;
25873 case AUTH_UNKNOWN_DOMAIN:
25874 reason = "Not a local domain";
25875 break;
25876 case AUTH_PEER_NOT_DYNAMIC:
25877 reason = "Peer is not supposed to register";
25878 break;
25879 case AUTH_ACL_FAILED:
25880 reason = "Device does not match ACL";
25881 break;
25882 case AUTH_BAD_TRANSPORT:
25883 reason = "Device not configured to use this transport type";
25884 break;
25885 default:
25886 reason = "Unknown failure";
25887 break;
25888 }
25889 ast_log(LOG_NOTICE, "Registration from '%s' failed for '%s' - %s\n",
25890 get_header(req, "To"), ast_sockaddr_stringify(addr),
25891 reason);
25892 append_history(p, "RegRequest", "Failed : Account %s : %s", get_header(req, "To"), reason);
25893 } else {
25894 req->authenticated = 1;
25895 append_history(p, "RegRequest", "Succeeded : Account %s", get_header(req, "To"));
25896 }
25897
25898 if (res < 1) {
25899
25900
25901 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
25902 }
25903 return res;
25904 }
25905
25906
25907
25908
25909
25910
25911
25912
25913 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int *recount, int *nounlock)
25914 {
25915
25916
25917 const char *cmd;
25918 const char *cseq;
25919 const char *useragent;
25920 const char *via;
25921 const char *callid;
25922 int via_pos = 0;
25923 uint32_t seqno;
25924 int len;
25925 int respid;
25926 int res = 0;
25927 int debug = sip_debug_test_pvt(p);
25928 const char *e;
25929 int error = 0;
25930 int oldmethod = p->method;
25931 int acked = 0;
25932
25933
25934
25935
25936 cseq = get_header(req, "Cseq");
25937 cmd = REQ_OFFSET_TO_STR(req, header[0]);
25938
25939 via = __get_header(req, "Via", &via_pos);
25940
25941 callid = get_header(req, "Call-ID");
25942
25943
25944 if (ast_strlen_zero(cmd) || ast_strlen_zero(cseq) || ast_strlen_zero(via)) {
25945 ast_log(LOG_ERROR, "Dropping this SIP message with Call-ID '%s', it's incomplete.\n", callid);
25946 error = 1;
25947 }
25948 if (!error && sscanf(cseq, "%30u%n", &seqno, &len) != 1) {
25949 ast_log(LOG_ERROR, "No seqno in '%s'. Dropping incomplete message.\n", cmd);
25950 error = 1;
25951 }
25952 if (error) {
25953 if (!p->initreq.headers) {
25954 pvt_set_needdestroy(p, "no headers");
25955 }
25956 return -1;
25957 }
25958
25959
25960 cmd = REQ_OFFSET_TO_STR(req, rlPart1);
25961 e = ast_skip_blanks(REQ_OFFSET_TO_STR(req, rlPart2));
25962
25963
25964 useragent = get_header(req, "User-Agent");
25965 if (!ast_strlen_zero(useragent))
25966 ast_string_field_set(p, useragent, useragent);
25967
25968
25969 if (req->method == SIP_RESPONSE) {
25970
25971
25972
25973
25974
25975
25976 if (ast_strlen_zero(e)) {
25977 return 0;
25978 }
25979 if (sscanf(e, "%30d %n", &respid, &len) != 1) {
25980 ast_log(LOG_WARNING, "Invalid response: '%s'\n", e);
25981 return 0;
25982 }
25983 if (respid <= 0) {
25984 ast_log(LOG_WARNING, "Invalid SIP response code: '%d'\n", respid);
25985 return 0;
25986 }
25987
25988
25989
25990 if (!ast_strlen_zero(__get_header(req, "via", &via_pos))) {
25991 ast_log(LOG_WARNING, "Misrouted SIP response '%s' with Call-ID '%s', too many vias\n", e, callid);
25992 return 0;
25993 }
25994 if (p->ocseq && (p->ocseq < seqno)) {
25995 ast_debug(1, "Ignoring out of order response %u (expecting %u)\n", seqno, p->ocseq);
25996 return -1;
25997 } else {
25998 char causevar[256], causeval[256];
25999
26000 if ((respid == 200) || ((respid >= 300) && (respid <= 399))) {
26001 extract_uri(p, req);
26002 }
26003
26004 handle_response(p, respid, e + len, req, seqno);
26005
26006 if (global_store_sip_cause && p->owner) {
26007 struct ast_channel *owner = p->owner;
26008
26009 snprintf(causevar, sizeof(causevar), "MASTER_CHANNEL(HASH(SIP_CAUSE,%s))", owner->name);
26010 snprintf(causeval, sizeof(causeval), "SIP %s", REQ_OFFSET_TO_STR(req, rlPart2));
26011
26012 ast_channel_ref(owner);
26013 sip_pvt_unlock(p);
26014 ast_channel_unlock(owner);
26015 *nounlock = 1;
26016 pbx_builtin_setvar_helper(owner, causevar, causeval);
26017 ast_channel_unref(owner);
26018 sip_pvt_lock(p);
26019 }
26020 }
26021 return 0;
26022 }
26023
26024
26025
26026
26027
26028 p->method = req->method;
26029 ast_debug(4, "**** Received %s (%d) - Command in SIP %s\n", sip_methods[p->method].text, sip_methods[p->method].id, cmd);
26030
26031 if (p->icseq && (p->icseq > seqno) ) {
26032 if (p->pendinginvite && seqno == p->pendinginvite && (req->method == SIP_ACK || req->method == SIP_CANCEL)) {
26033 ast_debug(2, "Got CANCEL or ACK on INVITE with transactions in between.\n");
26034 } else {
26035 ast_debug(1, "Ignoring too old SIP packet packet %u (expecting >= %u)\n", seqno, p->icseq);
26036 if (req->method == SIP_INVITE) {
26037 unsigned int ran = (ast_random() % 10) + 1;
26038 char seconds[4];
26039 snprintf(seconds, sizeof(seconds), "%u", ran);
26040 transmit_response_with_retry_after(p, "500 Server error", req, seconds);
26041 } else if (req->method != SIP_ACK) {
26042 transmit_response(p, "500 Server error", req);
26043 }
26044 return -1;
26045 }
26046 } else if (p->icseq &&
26047 p->icseq == seqno &&
26048 req->method != SIP_ACK &&
26049 (p->method != SIP_CANCEL || p->alreadygone)) {
26050
26051
26052
26053 req->ignore = 1;
26054 ast_debug(3, "Ignoring SIP message because of retransmit (%s Seqno %u, ours %u)\n", sip_methods[p->method].text, p->icseq, seqno);
26055 }
26056
26057
26058
26059 if (!p->pendinginvite && (req->method == SIP_CANCEL)) {
26060 transmit_response(p, "481 Call/Transaction Does Not Exist", req);
26061 return res;
26062 }
26063
26064 if (seqno >= p->icseq)
26065
26066
26067
26068 p->icseq = seqno;
26069
26070
26071 if (ast_strlen_zero(p->theirtag)) {
26072 char tag[128];
26073
26074 gettag(req, "From", tag, sizeof(tag));
26075 ast_string_field_set(p, theirtag, tag);
26076 }
26077 snprintf(p->lastmsg, sizeof(p->lastmsg), "Rx: %s", cmd);
26078
26079 if (sip_cfg.pedanticsipchecking) {
26080
26081
26082
26083
26084 if (!p->initreq.headers && req->has_to_tag) {
26085
26086 if (!req->ignore && req->method == SIP_INVITE) {
26087
26088
26089
26090
26091
26092
26093 char totag[128];
26094 gettag(req, "To", totag, sizeof(totag));
26095 ast_string_field_set(p, tag, totag);
26096 p->pendinginvite = p->icseq;
26097 transmit_response_reliable(p, "481 Call/Transaction Does Not Exist", req);
26098
26099 return res;
26100 } else if (req->method != SIP_ACK) {
26101 transmit_response(p, "481 Call/Transaction Does Not Exist", req);
26102 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
26103 return res;
26104 }
26105
26106 }
26107 }
26108
26109 if (!e && (p->method == SIP_INVITE || p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER || p->method == SIP_NOTIFY || p->method == SIP_PUBLISH)) {
26110 transmit_response(p, "400 Bad request", req);
26111 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
26112 return -1;
26113 }
26114
26115
26116 switch (p->method) {
26117 case SIP_OPTIONS:
26118 res = handle_request_options(p, req, addr, e);
26119 break;
26120 case SIP_INVITE:
26121 res = handle_request_invite(p, req, debug, seqno, addr, recount, e, nounlock);
26122 break;
26123 case SIP_REFER:
26124 res = handle_request_refer(p, req, debug, seqno, nounlock);
26125 break;
26126 case SIP_CANCEL:
26127 res = handle_request_cancel(p, req);
26128 break;
26129 case SIP_BYE:
26130 res = handle_request_bye(p, req);
26131 break;
26132 case SIP_MESSAGE:
26133 res = handle_request_message(p, req);
26134 break;
26135 case SIP_PUBLISH:
26136 res = handle_request_publish(p, req, addr, seqno, e);
26137 break;
26138 case SIP_SUBSCRIBE:
26139 res = handle_request_subscribe(p, req, addr, seqno, e);
26140 break;
26141 case SIP_REGISTER:
26142 res = handle_request_register(p, req, addr, e);
26143 break;
26144 case SIP_INFO:
26145 if (req->debug)
26146 ast_verbose("Receiving INFO!\n");
26147 if (!req->ignore)
26148 handle_request_info(p, req);
26149 else
26150 transmit_response(p, "200 OK", req);
26151 break;
26152 case SIP_NOTIFY:
26153 res = handle_request_notify(p, req, addr, seqno, e);
26154 break;
26155 case SIP_UPDATE:
26156 res = handle_request_update(p, req);
26157 break;
26158 case SIP_ACK:
26159
26160 if (seqno == p->pendinginvite) {
26161 p->invitestate = INV_TERMINATED;
26162 p->pendinginvite = 0;
26163 acked = __sip_ack(p, seqno, 1 , 0);
26164 if (p->owner && find_sdp(req)) {
26165 if (process_sdp(p, req, SDP_T38_NONE)) {
26166 return -1;
26167 }
26168 if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
26169 ast_queue_control(p->owner, AST_CONTROL_SRCCHANGE);
26170 }
26171 }
26172 check_pendings(p);
26173 } else if (p->glareinvite == seqno) {
26174
26175 p->glareinvite = 0;
26176 acked = __sip_ack(p, seqno, 1, 0);
26177 }
26178 if (!acked) {
26179
26180
26181 p->method = oldmethod;
26182 }
26183 if (!p->lastinvite && ast_strlen_zero(p->randdata)) {
26184 pvt_set_needdestroy(p, "unmatched ACK");
26185 }
26186 break;
26187 default:
26188 transmit_response_with_allow(p, "501 Method Not Implemented", req, 0);
26189 ast_log(LOG_NOTICE, "Unknown SIP command '%s' from '%s'\n",
26190 cmd, ast_sockaddr_stringify(&p->sa));
26191
26192 if (!p->initreq.headers) {
26193 pvt_set_needdestroy(p, "unimplemented method");
26194 }
26195 break;
26196 }
26197 return res;
26198 }
26199
26200
26201
26202
26203
26204
26205 static int sipsock_read(int *id, int fd, short events, void *ignore)
26206 {
26207 struct sip_request req;
26208 struct ast_sockaddr addr;
26209 int res;
26210 static char readbuf[65535];
26211
26212 memset(&req, 0, sizeof(req));
26213 res = ast_recvfrom(fd, readbuf, sizeof(readbuf) - 1, 0, &addr);
26214 if (res < 0) {
26215 #if !defined(__FreeBSD__)
26216 if (errno == EAGAIN)
26217 ast_log(LOG_NOTICE, "SIP: Received packet with bad UDP checksum\n");
26218 else
26219 #endif
26220 if (errno != ECONNREFUSED)
26221 ast_log(LOG_WARNING, "Recv error: %s\n", strerror(errno));
26222 return 1;
26223 }
26224
26225 readbuf[res] = '\0';
26226
26227 if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
26228 return 1;
26229 }
26230
26231 if (ast_str_set(&req.data, 0, "%s", readbuf) == AST_DYNSTR_BUILD_FAILED) {
26232 return -1;
26233 }
26234
26235 req.socket.fd = sipsock;
26236 set_socket_transport(&req.socket, SIP_TRANSPORT_UDP);
26237 req.socket.tcptls_session = NULL;
26238 req.socket.port = htons(ast_sockaddr_port(&bindaddr));
26239
26240 handle_request_do(&req, &addr);
26241 deinit_req(&req);
26242
26243 return 1;
26244 }
26245
26246
26247
26248
26249
26250 static int handle_request_do(struct sip_request *req, struct ast_sockaddr *addr)
26251 {
26252 struct sip_pvt *p;
26253 struct ast_channel *owner_chan_ref = NULL;
26254 int recount = 0;
26255 int nounlock = 0;
26256
26257 if (sip_debug_test_addr(addr))
26258 req->debug = 1;
26259 if (sip_cfg.pedanticsipchecking)
26260 lws2sws(req->data);
26261 if (req->debug) {
26262 ast_verbose("\n<--- SIP read from %s:%s --->\n%s\n<------------->\n",
26263 get_transport(req->socket.type), ast_sockaddr_stringify(addr), ast_str_buffer(req->data));
26264 }
26265
26266 if (parse_request(req) == -1) {
26267 ast_str_reset(req->data);
26268 return 1;
26269 }
26270 req->method = find_sip_method(REQ_OFFSET_TO_STR(req, rlPart1));
26271
26272 if (req->debug)
26273 ast_verbose("--- (%d headers %d lines)%s ---\n", req->headers, req->lines, (req->headers + req->lines == 0) ? " Nat keepalive" : "");
26274
26275 if (req->headers < 2) {
26276 ast_str_reset(req->data);
26277 return 1;
26278 }
26279
26280
26281 ast_mutex_lock(&netlock);
26282
26283
26284 p = find_call(req, addr, req->method);
26285 if (p == NULL) {
26286 ast_debug(1, "Invalid SIP message - rejected , no callid, len %zu\n", ast_str_strlen(req->data));
26287 ast_mutex_unlock(&netlock);
26288 return 1;
26289 }
26290
26291
26292
26293 owner_chan_ref = sip_pvt_lock_full(p);
26294
26295 copy_socket_data(&p->socket, &req->socket);
26296
26297 ast_sockaddr_copy(&p->recv, addr);
26298
26299
26300 if (p->owner) {
26301 req->authenticated = 1;
26302 }
26303
26304 if (p->do_history)
26305 append_history(p, "Rx", "%s / %s / %s", ast_str_buffer(req->data), get_header(req, "CSeq"), REQ_OFFSET_TO_STR(req, rlPart2));
26306
26307 if (handle_incoming(p, req, addr, &recount, &nounlock) == -1) {
26308
26309 ast_debug(1, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
26310 }
26311
26312 if (recount) {
26313 ast_update_use_count();
26314 }
26315
26316 if (p->owner && !nounlock) {
26317 ast_channel_unlock(p->owner);
26318 }
26319 if (owner_chan_ref) {
26320 ast_channel_unref(owner_chan_ref);
26321 }
26322 sip_pvt_unlock(p);
26323 ao2_t_ref(p, -1, "throw away dialog ptr from find_call at end of routine");
26324 ast_mutex_unlock(&netlock);
26325
26326 return 1;
26327 }
26328
26329
26330
26331
26332
26333
26334
26335 static int sip_standard_port(enum sip_transport type, int port)
26336 {
26337 if (type & SIP_TRANSPORT_TLS)
26338 return port == STANDARD_TLS_PORT;
26339 else
26340 return port == STANDARD_SIP_PORT;
26341 }
26342
26343 static int threadinfo_locate_cb(void *obj, void *arg, int flags)
26344 {
26345 struct sip_threadinfo *th = obj;
26346 struct ast_sockaddr *s = arg;
26347
26348 if (!ast_sockaddr_cmp(s, &th->tcptls_session->remote_address)) {
26349 return CMP_MATCH | CMP_STOP;
26350 }
26351
26352 return 0;
26353 }
26354
26355
26356
26357
26358
26359
26360 static struct ast_tcptls_session_instance *sip_tcp_locate(struct ast_sockaddr *s)
26361 {
26362 struct sip_threadinfo *th;
26363 struct ast_tcptls_session_instance *tcptls_instance = NULL;
26364
26365 if ((th = ao2_callback(threadt, 0, threadinfo_locate_cb, s))) {
26366 tcptls_instance = (ao2_ref(th->tcptls_session, +1), th->tcptls_session);
26367 ao2_t_ref(th, -1, "decrement ref from callback");
26368 }
26369
26370 return tcptls_instance;
26371 }
26372
26373
26374
26375
26376
26377
26378 int get_address_family_filter(unsigned int transport)
26379 {
26380 const struct ast_sockaddr *addr = NULL;
26381
26382 if ((transport == SIP_TRANSPORT_UDP) || !transport) {
26383 addr = &bindaddr;
26384 }
26385 else if (transport == SIP_TRANSPORT_TCP) {
26386 addr = &sip_tcp_desc.local_address;
26387 }
26388 else if (transport == SIP_TRANSPORT_TLS) {
26389 addr = &sip_tls_desc.local_address;
26390 }
26391
26392 if (ast_sockaddr_is_ipv6(addr) && ast_sockaddr_is_any(addr)) {
26393 return 0;
26394 }
26395
26396 return addr->ss.ss_family;
26397 }
26398
26399
26400 static int sip_prepare_socket(struct sip_pvt *p)
26401 {
26402 struct sip_socket *s = &p->socket;
26403 static const char name[] = "SIP socket";
26404 struct sip_threadinfo *th = NULL;
26405 struct ast_tcptls_session_instance *tcptls_session;
26406 struct ast_tcptls_session_args *ca;
26407 struct ast_sockaddr sa_tmp;
26408 pthread_t launched;
26409
26410
26411 if ((s->fd != -1) && (s->type == SIP_TRANSPORT_UDP)) {
26412 return s->fd;
26413 }
26414 if ((s->type & (SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS)) &&
26415 (s->tcptls_session) &&
26416 (s->tcptls_session->fd != -1)) {
26417 return s->tcptls_session->fd;
26418 }
26419
26420
26421
26422
26423 if (p->outboundproxy && p->outboundproxy->transport) {
26424 s->type = p->outboundproxy->transport;
26425 }
26426
26427 if (s->type == SIP_TRANSPORT_UDP) {
26428 s->fd = sipsock;
26429 return s->fd;
26430 }
26431
26432
26433
26434
26435
26436
26437
26438
26439
26440
26441
26442 ast_sockaddr_copy(&sa_tmp, sip_real_dst(p));
26443 if ((tcptls_session = sip_tcp_locate(&sa_tmp))) {
26444 s->fd = tcptls_session->fd;
26445 if (s->tcptls_session) {
26446 ao2_ref(s->tcptls_session, -1);
26447 s->tcptls_session = NULL;
26448 }
26449 s->tcptls_session = tcptls_session;
26450 return s->fd;
26451
26452 } else if (s->tcptls_session) {
26453 return s->fd;
26454 }
26455
26456
26457
26458 if (!(ca = ao2_alloc(sizeof(*ca), sip_tcptls_client_args_destructor)) ||
26459 !(ca->name = ast_strdup(name))) {
26460 goto create_tcptls_session_fail;
26461 }
26462 ca->accept_fd = -1;
26463 ast_sockaddr_copy(&ca->remote_address,sip_real_dst(p));
26464
26465 if (s->type == SIP_TRANSPORT_TLS) {
26466 if (!(ca->tls_cfg = ast_calloc(1, sizeof(*ca->tls_cfg)))) {
26467 goto create_tcptls_session_fail;
26468 }
26469 memcpy(ca->tls_cfg, &default_tls_cfg, sizeof(*ca->tls_cfg));
26470
26471 if (!(ca->tls_cfg->certfile = ast_strdup(default_tls_cfg.certfile)) ||
26472 !(ca->tls_cfg->pvtfile = ast_strdup(default_tls_cfg.pvtfile)) ||
26473 !(ca->tls_cfg->cipher = ast_strdup(default_tls_cfg.cipher)) ||
26474 !(ca->tls_cfg->cafile = ast_strdup(default_tls_cfg.cafile)) ||
26475 !(ca->tls_cfg->capath = ast_strdup(default_tls_cfg.capath))) {
26476
26477 goto create_tcptls_session_fail;
26478 }
26479
26480
26481 if (!ast_strlen_zero(p->tohost)) {
26482 ast_copy_string(ca->hostname, p->tohost, sizeof(ca->hostname));
26483 }
26484 }
26485
26486
26487 if (!(s->tcptls_session = ast_tcptls_client_create(ca))) {
26488 goto create_tcptls_session_fail;
26489 }
26490
26491 s->fd = s->tcptls_session->fd;
26492
26493
26494
26495
26496
26497 if (!(th = sip_threadinfo_create(s->tcptls_session, s->type))) {
26498 goto create_tcptls_session_fail;
26499 }
26500
26501
26502 ao2_ref(s->tcptls_session, +1);
26503
26504 if (ast_pthread_create_detached_background(&launched, NULL, sip_tcp_worker_fn, s->tcptls_session)) {
26505 ast_debug(1, "Unable to launch '%s'.", ca->name);
26506 ao2_ref(s->tcptls_session, -1);
26507 goto create_tcptls_session_fail;
26508 }
26509
26510 return s->fd;
26511
26512 create_tcptls_session_fail:
26513 if (ca) {
26514 ao2_t_ref(ca, -1, "failed to create client, getting rid of client tcptls_session arguments");
26515 }
26516 if (s->tcptls_session) {
26517 ast_tcptls_close_session_file(s->tcptls_session);
26518 s->fd = -1;
26519 ao2_ref(s->tcptls_session, -1);
26520 s->tcptls_session = NULL;
26521 }
26522 if (th) {
26523 ao2_t_unlink(threadt, th, "Removing tcptls thread info object, thread failed to open");
26524 }
26525
26526 return -1;
26527 }
26528
26529
26530
26531
26532
26533 static int get_cached_mwi(struct sip_peer *peer, int *new, int *old)
26534 {
26535 struct sip_mailbox *mailbox;
26536 int in_cache;
26537
26538 in_cache = 0;
26539 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
26540 struct ast_event *event;
26541 event = ast_event_get_cached(AST_EVENT_MWI,
26542 AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox->mailbox,
26543 AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, S_OR(mailbox->context, "default"),
26544 AST_EVENT_IE_END);
26545 if (!event)
26546 continue;
26547 *new += ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
26548 *old += ast_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS);
26549 ast_event_destroy(event);
26550 in_cache = 1;
26551 }
26552
26553 return in_cache;
26554 }
26555
26556
26557
26558
26559 static int sip_send_mwi_to_peer(struct sip_peer *peer, int cache_only)
26560 {
26561
26562 struct sip_pvt *p;
26563 int newmsgs = 0, oldmsgs = 0;
26564 const char *vmexten = NULL;
26565
26566 ao2_lock(peer);
26567
26568 if (peer->vmexten) {
26569 vmexten = ast_strdupa(peer->vmexten);
26570 }
26571
26572 if (ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY) && !peer->mwipvt) {
26573 update_peer_lastmsgssent(peer, -1, 1);
26574 ao2_unlock(peer);
26575 return 0;
26576 }
26577
26578
26579 if (ast_sockaddr_isnull(&peer->addr) && ast_sockaddr_isnull(&peer->defaddr)) {
26580 update_peer_lastmsgssent(peer, -1, 1);
26581 ao2_unlock(peer);
26582 return 0;
26583 }
26584
26585
26586 if (!get_cached_mwi(peer, &newmsgs, &oldmsgs) && !cache_only) {
26587
26588 struct ast_str *mailbox_str = ast_str_alloca(512);
26589 peer_mailboxes_to_str(&mailbox_str, peer);
26590 ao2_unlock(peer);
26591
26592 if (!ast_str_strlen(mailbox_str)) {
26593 update_peer_lastmsgssent(peer, -1, 0);
26594 return 0;
26595 }
26596 ast_app_inboxcount(ast_str_buffer(mailbox_str), &newmsgs, &oldmsgs);
26597 ao2_lock(peer);
26598 }
26599
26600 if (peer->mwipvt) {
26601
26602 p = dialog_ref(peer->mwipvt, "sip_send_mwi_to_peer: Setting dialog ptr p from peer->mwipvt");
26603 ao2_unlock(peer);
26604 } else {
26605 ao2_unlock(peer);
26606
26607 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
26608 update_peer_lastmsgssent(peer, -1, 0);
26609 return -1;
26610 }
26611
26612
26613
26614
26615
26616 set_socket_transport(&p->socket, 0);
26617 if (create_addr_from_peer(p, peer)) {
26618
26619 dialog_unlink_all(p);
26620 dialog_unref(p, "unref dialog p just created via sip_alloc");
26621 update_peer_lastmsgssent(peer, -1, 0);
26622 return 0;
26623 }
26624
26625 ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
26626 build_via(p);
26627
26628 ao2_lock(peer);
26629 if (!ast_strlen_zero(peer->mwi_from)) {
26630 ast_string_field_set(p, mwi_from, peer->mwi_from);
26631 } else if (!ast_strlen_zero(default_mwi_from)) {
26632 ast_string_field_set(p, mwi_from, default_mwi_from);
26633 }
26634 ao2_unlock(peer);
26635
26636
26637 change_callid_pvt(p, NULL);
26638
26639
26640 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
26641 }
26642
26643
26644
26645 sip_pvt_lock(p);
26646
26647
26648 ast_set_flag(&p->flags[0], SIP_OUTGOING);
26649
26650 transmit_notify_with_mwi(p, newmsgs, oldmsgs, vmexten);
26651 sip_pvt_unlock(p);
26652 dialog_unref(p, "unref dialog ptr p just before it goes out of scope at the end of sip_send_mwi_to_peer.");
26653
26654 update_peer_lastmsgssent(peer, ((newmsgs > 0x7fff ? 0x7fff0000 : (newmsgs << 16)) | (oldmsgs > 0xffff ? 0xffff : oldmsgs)), 0);
26655
26656 return 0;
26657 }
26658
26659
26660 static void check_rtp_timeout(struct sip_pvt *dialog, time_t t)
26661 {
26662
26663 if (!dialog->rtp || !dialog->owner)
26664 return;
26665
26666
26667 if (dialog->owner->_state != AST_STATE_UP || !ast_sockaddr_isnull(&dialog->redirip))
26668 return;
26669
26670
26671 if (dialog->t38.state == T38_ENABLED)
26672 return;
26673
26674
26675 if (!ast_rtp_instance_get_keepalive(dialog->rtp) && !ast_rtp_instance_get_timeout(dialog->rtp) && !ast_rtp_instance_get_hold_timeout(dialog->rtp)) {
26676 return;
26677 }
26678
26679
26680 if (dialog->lastrtptx && ast_rtp_instance_get_keepalive(dialog->rtp) &&
26681 (t > dialog->lastrtptx + ast_rtp_instance_get_keepalive(dialog->rtp))) {
26682
26683 dialog->lastrtptx = time(NULL);
26684 ast_rtp_instance_sendcng(dialog->rtp, 0);
26685 }
26686
26687
26688
26689
26690
26691
26692
26693
26694 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))) {
26695 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)))) {
26696
26697 if (ast_rtp_instance_get_timeout(dialog->rtp)) {
26698 if (!dialog->owner || ast_channel_trylock(dialog->owner)) {
26699
26700
26701
26702
26703 return;
26704 }
26705 ast_log(LOG_NOTICE, "Disconnecting call '%s' for lack of RTP activity in %ld seconds\n",
26706 dialog->owner->name, (long) (t - dialog->lastrtprx));
26707
26708 ast_softhangup_nolock(dialog->owner, AST_SOFTHANGUP_DEV);
26709 ast_channel_unlock(dialog->owner);
26710
26711
26712
26713
26714 ast_rtp_instance_set_timeout(dialog->rtp, 0);
26715 ast_rtp_instance_set_hold_timeout(dialog->rtp, 0);
26716 if (dialog->vrtp) {
26717 ast_rtp_instance_set_timeout(dialog->vrtp, 0);
26718 ast_rtp_instance_set_hold_timeout(dialog->vrtp, 0);
26719 }
26720 }
26721 }
26722 }
26723 }
26724
26725
26726
26727
26728
26729 static void *do_monitor(void *data)
26730 {
26731 int res;
26732 time_t t;
26733 int reloading;
26734
26735
26736 if (sipsock > -1)
26737 sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
26738
26739
26740 for(;;) {
26741
26742 ast_mutex_lock(&sip_reload_lock);
26743 reloading = sip_reloading;
26744 sip_reloading = FALSE;
26745 ast_mutex_unlock(&sip_reload_lock);
26746 if (reloading) {
26747 ast_verb(1, "Reloading SIP\n");
26748 sip_do_reload(sip_reloadreason);
26749
26750
26751 if (sipsock > -1) {
26752 if (sipsock_read_id)
26753 sipsock_read_id = ast_io_change(io, sipsock_read_id, sipsock, NULL, 0, NULL);
26754 else
26755 sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
26756 } else if (sipsock_read_id) {
26757 ast_io_remove(io, sipsock_read_id);
26758 sipsock_read_id = NULL;
26759 }
26760 }
26761
26762
26763 t = time(NULL);
26764
26765
26766
26767
26768
26769
26770
26771
26772
26773
26774 ao2_t_callback(dialogs, OBJ_NODATA | OBJ_MULTIPLE, dialog_needdestroy, &t,
26775 "callback to monitor dialog status");
26776 if (ao2_container_count(dialogs_to_destroy)) {
26777
26778 ao2_t_callback(dialogs_to_destroy, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE,
26779 dialog_unlink_callback, NULL, "callback to dialog_unlink_all");
26780 }
26781
26782
26783
26784
26785
26786
26787
26788 pthread_testcancel();
26789
26790 res = ast_sched_wait(sched);
26791 if ((res < 0) || (res > 1000))
26792 res = 1000;
26793 res = ast_io_wait(io, res);
26794 if (res > 20)
26795 ast_debug(1, "chan_sip: ast_io_wait ran %d all at once\n", res);
26796 ast_mutex_lock(&monlock);
26797 res = ast_sched_runq(sched);
26798 if (res >= 20)
26799 ast_debug(1, "chan_sip: ast_sched_runq ran %d all at once\n", res);
26800 if (global_store_sip_cause && res >= 100)
26801 ast_log(LOG_WARNING, "scheduler delays detected, setting 'storesipcause' to 'no' in %s will improve performance\n", config);
26802 ast_mutex_unlock(&monlock);
26803 }
26804
26805
26806 return NULL;
26807 }
26808
26809
26810 static int restart_monitor(void)
26811 {
26812
26813 if (monitor_thread == AST_PTHREADT_STOP)
26814 return 0;
26815 ast_mutex_lock(&monlock);
26816 if (monitor_thread == pthread_self()) {
26817 ast_mutex_unlock(&monlock);
26818 ast_log(LOG_WARNING, "Cannot kill myself\n");
26819 return -1;
26820 }
26821 if (monitor_thread != AST_PTHREADT_NULL) {
26822
26823 pthread_kill(monitor_thread, SIGURG);
26824 } else {
26825
26826 if (ast_pthread_create_background(&monitor_thread, NULL, do_monitor, NULL) < 0) {
26827 ast_mutex_unlock(&monlock);
26828 ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
26829 return -1;
26830 }
26831 }
26832 ast_mutex_unlock(&monlock);
26833 return 0;
26834 }
26835
26836
26837
26838 static void restart_session_timer(struct sip_pvt *p)
26839 {
26840 if (!p->stimer) {
26841 ast_log(LOG_WARNING, "Null stimer in restart_session_timer - %s\n", p->callid);
26842 return;
26843 }
26844
26845 if (p->stimer->st_active == TRUE) {
26846 ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
26847 AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
26848 dialog_unref(p, "Removing session timer ref"));
26849 start_session_timer(p);
26850 }
26851 }
26852
26853
26854
26855 static void stop_session_timer(struct sip_pvt *p)
26856 {
26857 if (!p->stimer) {
26858 ast_log(LOG_WARNING, "Null stimer in stop_session_timer - %s\n", p->callid);
26859 return;
26860 }
26861
26862 if (p->stimer->st_active == TRUE) {
26863 p->stimer->st_active = FALSE;
26864 ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
26865 AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
26866 dialog_unref(p, "removing session timer ref"));
26867 }
26868 }
26869
26870
26871
26872 static void start_session_timer(struct sip_pvt *p)
26873 {
26874 unsigned int timeout_ms;
26875
26876 if (!p->stimer) {
26877 ast_log(LOG_WARNING, "Null stimer in start_session_timer - %s\n", p->callid);
26878 return;
26879 }
26880
26881 if (p->stimer->st_schedid > -1) {
26882
26883 ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
26884 AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
26885 dialog_unref(p, "unref stimer->st_schedid from dialog"));
26886 }
26887
26888
26889
26890
26891
26892
26893
26894
26895
26896
26897 timeout_ms = (1000 * p->stimer->st_interval);
26898 if (p->stimer->st_ref == SESSION_TIMER_REFRESHER_US) {
26899 timeout_ms /= 2;
26900 } else {
26901 timeout_ms -= MIN(timeout_ms / 3, 32000);
26902 }
26903
26904 p->stimer->st_schedid = ast_sched_add(sched, timeout_ms, proc_session_timer,
26905 dialog_ref(p, "adding session timer ref"));
26906
26907 if (p->stimer->st_schedid < 0) {
26908 dialog_unref(p, "removing session timer ref");
26909 ast_log(LOG_ERROR, "ast_sched_add failed - %s\n", p->callid);
26910 } else {
26911 p->stimer->st_active = TRUE;
26912 ast_debug(2, "Session timer started: %d - %s %ums\n", p->stimer->st_schedid, p->callid, timeout_ms);
26913 }
26914 }
26915
26916
26917
26918 static int proc_session_timer(const void *vp)
26919 {
26920 struct sip_pvt *p = (struct sip_pvt *) vp;
26921 int res = 0;
26922
26923 if (!p->stimer) {
26924 ast_log(LOG_WARNING, "Null stimer in proc_session_timer - %s\n", p->callid);
26925 goto return_unref;
26926 }
26927
26928 ast_debug(2, "Session timer expired: %d - %s\n", p->stimer->st_schedid, p->callid);
26929
26930 if (!p->owner) {
26931 goto return_unref;
26932 }
26933
26934 if ((p->stimer->st_active != TRUE) || (p->owner->_state != AST_STATE_UP)) {
26935 goto return_unref;
26936 }
26937
26938 if (p->stimer->st_ref == SESSION_TIMER_REFRESHER_US) {
26939 res = 1;
26940 if (T38_ENABLED == p->t38.state) {
26941 transmit_reinvite_with_sdp(p, TRUE, TRUE);
26942 } else {
26943 transmit_reinvite_with_sdp(p, FALSE, TRUE);
26944 }
26945 } else {
26946 if (p->stimer->quit_flag) {
26947 goto return_unref;
26948 }
26949 ast_log(LOG_WARNING, "Session-Timer expired - %s\n", p->callid);
26950 sip_pvt_lock(p);
26951 while (p->owner && ast_channel_trylock(p->owner)) {
26952 sip_pvt_unlock(p);
26953 usleep(1);
26954 if (p->stimer && p->stimer->quit_flag) {
26955 goto return_unref;
26956 }
26957 sip_pvt_lock(p);
26958 }
26959
26960 ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
26961 ast_channel_unlock(p->owner);
26962 sip_pvt_unlock(p);
26963 }
26964
26965 return_unref:
26966 if (!res) {
26967
26968 if (p->stimer) {
26969 ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
26970 p->stimer->st_schedid = -1;
26971 stop_session_timer(p);
26972 }
26973
26974
26975
26976 dialog_unref(p, "removing session timer ref");
26977 }
26978
26979 return res;
26980 }
26981
26982
26983
26984 int parse_minse (const char *p_hdrval, int *const p_interval)
26985 {
26986 if (ast_strlen_zero(p_hdrval)) {
26987 ast_log(LOG_WARNING, "Null Min-SE header\n");
26988 return -1;
26989 }
26990
26991 *p_interval = 0;
26992 p_hdrval = ast_skip_blanks(p_hdrval);
26993 if (!sscanf(p_hdrval, "%30d", p_interval)) {
26994 ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
26995 return -1;
26996 }
26997
26998 ast_debug(2, "Received Min-SE: %d\n", *p_interval);
26999 return 0;
27000 }
27001
27002
27003
27004 int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher_param *const p_ref)
27005 {
27006 char *p_token;
27007 int ref_idx;
27008 char *p_se_hdr;
27009
27010 if (ast_strlen_zero(p_hdrval)) {
27011 ast_log(LOG_WARNING, "Null Session-Expires header\n");
27012 return -1;
27013 }
27014
27015 *p_ref = SESSION_TIMER_REFRESHER_PARAM_UNKNOWN;
27016 *p_interval = 0;
27017
27018 p_se_hdr = ast_strdupa(p_hdrval);
27019 p_se_hdr = ast_skip_blanks(p_se_hdr);
27020
27021 while ((p_token = strsep(&p_se_hdr, ";"))) {
27022 p_token = ast_skip_blanks(p_token);
27023 if (!sscanf(p_token, "%30d", p_interval)) {
27024 ast_log(LOG_WARNING, "Parsing of Session-Expires failed\n");
27025 return -1;
27026 }
27027
27028 ast_debug(2, "Session-Expires: %d\n", *p_interval);
27029
27030 if (!p_se_hdr)
27031 continue;
27032
27033 p_se_hdr = ast_skip_blanks(p_se_hdr);
27034 ref_idx = strlen("refresher=");
27035 if (!strncasecmp(p_se_hdr, "refresher=", ref_idx)) {
27036 p_se_hdr += ref_idx;
27037 p_se_hdr = ast_skip_blanks(p_se_hdr);
27038
27039 if (!strncasecmp(p_se_hdr, "uac", strlen("uac"))) {
27040 *p_ref = SESSION_TIMER_REFRESHER_PARAM_UAC;
27041 ast_debug(2, "Refresher: UAC\n");
27042 } else if (!strncasecmp(p_se_hdr, "uas", strlen("uas"))) {
27043 *p_ref = SESSION_TIMER_REFRESHER_PARAM_UAS;
27044 ast_debug(2, "Refresher: UAS\n");
27045 } else {
27046 ast_log(LOG_WARNING, "Invalid refresher value %s\n", p_se_hdr);
27047 return -1;
27048 }
27049 break;
27050 }
27051 }
27052 return 0;
27053 }
27054
27055
27056
27057
27058
27059
27060
27061
27062
27063 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp)
27064 {
27065 int rtn;
27066 const char *p_hdrval;
27067 int minse;
27068
27069 p_hdrval = get_header(rsp, "Min-SE");
27070 if (ast_strlen_zero(p_hdrval)) {
27071 ast_log(LOG_WARNING, "422 response without a Min-SE header %s\n", p_hdrval);
27072 return;
27073 }
27074 rtn = parse_minse(p_hdrval, &minse);
27075 if (rtn != 0) {
27076 ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
27077 return;
27078 }
27079 p->stimer->st_cached_min_se = minse;
27080 if (p->stimer->st_interval < minse) {
27081 p->stimer->st_interval = minse;
27082 }
27083 transmit_invite(p, SIP_INVITE, 1, 2, NULL);
27084 }
27085
27086
27087
27088
27089
27090
27091 int st_get_se(struct sip_pvt *p, int max)
27092 {
27093 if (max == TRUE) {
27094 if (p->stimer->st_cached_max_se) {
27095 return p->stimer->st_cached_max_se;
27096 }
27097 if (p->relatedpeer) {
27098 p->stimer->st_cached_max_se = p->relatedpeer->stimer.st_max_se;
27099 return (p->stimer->st_cached_max_se);
27100 }
27101 p->stimer->st_cached_max_se = global_max_se;
27102 return (p->stimer->st_cached_max_se);
27103 }
27104
27105 if (p->stimer->st_cached_min_se) {
27106 return p->stimer->st_cached_min_se;
27107 }
27108 if (p->relatedpeer) {
27109 p->stimer->st_cached_min_se = p->relatedpeer->stimer.st_min_se;
27110 return (p->stimer->st_cached_min_se);
27111 }
27112 p->stimer->st_cached_min_se = global_min_se;
27113 return (p->stimer->st_cached_min_se);
27114 }
27115
27116
27117
27118
27119
27120
27121
27122
27123 enum st_refresher st_get_refresher(struct sip_pvt *p)
27124 {
27125 if (p->stimer->st_cached_ref != SESSION_TIMER_REFRESHER_AUTO) {
27126 return p->stimer->st_cached_ref;
27127 }
27128
27129 if (p->relatedpeer) {
27130 p->stimer->st_cached_ref = (p->relatedpeer->stimer.st_ref == SESSION_TIMER_REFRESHER_PARAM_UAC) ? SESSION_TIMER_REFRESHER_THEM : SESSION_TIMER_REFRESHER_US;
27131 return p->stimer->st_cached_ref;
27132 }
27133
27134 p->stimer->st_cached_ref = (global_st_refresher == SESSION_TIMER_REFRESHER_PARAM_UAC) ? SESSION_TIMER_REFRESHER_THEM : SESSION_TIMER_REFRESHER_US;
27135 return p->stimer->st_cached_ref;
27136 }
27137
27138
27139
27140
27141
27142
27143
27144
27145 enum st_mode st_get_mode(struct sip_pvt *p, int no_cached)
27146 {
27147 if (!p->stimer) {
27148 sip_st_alloc(p);
27149 if (!p->stimer) {
27150 return SESSION_TIMER_MODE_INVALID;
27151 }
27152 }
27153
27154 if (!no_cached && p->stimer->st_cached_mode != SESSION_TIMER_MODE_INVALID)
27155 return p->stimer->st_cached_mode;
27156
27157 if (p->relatedpeer) {
27158 p->stimer->st_cached_mode = p->relatedpeer->stimer.st_mode_oper;
27159 return p->stimer->st_cached_mode;
27160 }
27161
27162 p->stimer->st_cached_mode = global_st_mode;
27163 return global_st_mode;
27164 }
27165
27166
27167
27168 static int sip_poke_noanswer(const void *data)
27169 {
27170 struct sip_peer *peer = (struct sip_peer *)data;
27171
27172 peer->pokeexpire = -1;
27173
27174 if (peer->lastms > -1) {
27175 ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE! Last qualify: %d\n", peer->name, peer->lastms);
27176 if (sip_cfg.peer_rtupdate) {
27177 ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", "-1", SENTINEL);
27178 }
27179 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer->name, -1);
27180 if (sip_cfg.regextenonqualify) {
27181 register_peer_exten(peer, FALSE);
27182 }
27183 }
27184
27185 if (peer->call) {
27186 dialog_unlink_all(peer->call);
27187 peer->call = dialog_unref(peer->call, "unref dialog peer->call");
27188
27189 }
27190
27191
27192 if (peer->lastms > -1) {
27193 peer->lastms = -1;
27194 ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "SIP/%s", peer->name);
27195 }
27196
27197
27198 AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
27199 DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer,
27200 unref_peer(_data, "removing poke peer ref"),
27201 unref_peer(peer, "removing poke peer ref"),
27202 ref_peer(peer, "adding poke peer ref"));
27203
27204
27205 unref_peer(peer, "release peer poke noanswer ref");
27206
27207 return 0;
27208 }
27209
27210
27211
27212
27213
27214
27215
27216
27217
27218 static int sip_poke_peer(struct sip_peer *peer, int force)
27219 {
27220 struct sip_pvt *p;
27221 int xmitres = 0;
27222
27223 if ((!peer->maxms && !force) || ast_sockaddr_isnull(&peer->addr)) {
27224
27225
27226 AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
27227 unref_peer(peer, "removing poke peer ref"));
27228
27229 peer->lastms = 0;
27230 if (peer->call) {
27231 peer->call = dialog_unref(peer->call, "unref dialog peer->call");
27232 }
27233 return 0;
27234 }
27235 if (peer->call) {
27236 if (sipdebug) {
27237 ast_log(LOG_NOTICE, "Still have a QUALIFY dialog active, deleting\n");
27238 }
27239 dialog_unlink_all(peer->call);
27240 peer->call = dialog_unref(peer->call, "unref dialog peer->call");
27241
27242 }
27243 if (!(p = sip_alloc(NULL, NULL, 0, SIP_OPTIONS, NULL))) {
27244 return -1;
27245 }
27246 peer->call = dialog_ref(p, "copy sip alloc from p to peer->call");
27247
27248 p->sa = peer->addr;
27249 p->recv = peer->addr;
27250 copy_socket_data(&p->socket, &peer->socket);
27251 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
27252 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
27253 ast_copy_flags(&p->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
27254
27255
27256 if (!ast_strlen_zero(peer->fullcontact)) {
27257 ast_string_field_set(p, fullcontact, peer->fullcontact);
27258 }
27259
27260 if (!ast_strlen_zero(peer->fromuser)) {
27261 ast_string_field_set(p, fromuser, peer->fromuser);
27262 }
27263
27264 if (!ast_strlen_zero(peer->tohost)) {
27265 ast_string_field_set(p, tohost, peer->tohost);
27266 } else {
27267 ast_string_field_set(p, tohost, ast_sockaddr_stringify_host_remote(&peer->addr));
27268 }
27269
27270
27271 ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
27272 build_via(p);
27273
27274
27275 change_callid_pvt(p, NULL);
27276
27277 AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
27278 unref_peer(peer, "removing poke peer ref"));
27279
27280 if (p->relatedpeer)
27281 p->relatedpeer = unref_peer(p->relatedpeer,"unsetting the relatedpeer field in the dialog, before it is set to something else.");
27282 p->relatedpeer = ref_peer(peer, "setting the relatedpeer field in the dialog");
27283 ast_set_flag(&p->flags[0], SIP_OUTGOING);
27284 #ifdef VOCAL_DATA_HACK
27285 ast_copy_string(p->username, "__VOCAL_DATA_SHOULD_READ_THE_SIP_SPEC__", sizeof(p->username));
27286 xmitres = transmit_invite(p, SIP_INVITE, 0, 2, NULL);
27287 #else
27288 xmitres = transmit_invite(p, SIP_OPTIONS, 0, 2, NULL);
27289 #endif
27290 peer->ps = ast_tvnow();
27291 if (xmitres == XMIT_ERROR) {
27292
27293 sip_poke_noanswer(ref_peer(peer, "add ref for peerexpire (fake, for sip_poke_noanswer to remove)"));
27294 } else if (!force) {
27295 AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, peer->maxms * 2, sip_poke_noanswer, peer,
27296 unref_peer(_data, "removing poke peer ref"),
27297 unref_peer(peer, "removing poke peer ref"),
27298 ref_peer(peer, "adding poke peer ref"));
27299 }
27300 dialog_unref(p, "unref dialog at end of sip_poke_peer, obtained from sip_alloc, just before it goes out of scope");
27301 return 0;
27302 }
27303
27304
27305
27306
27307
27308
27309
27310
27311
27312
27313
27314
27315
27316
27317
27318
27319
27320
27321
27322
27323
27324
27325
27326
27327
27328
27329
27330
27331
27332
27333
27334
27335
27336
27337 static int sip_devicestate(void *data)
27338 {
27339 char *host;
27340 char *tmp;
27341 struct sip_peer *p;
27342
27343 int res = AST_DEVICE_INVALID;
27344
27345
27346 host = ast_strdupa(data ? data : "");
27347 if ((tmp = strchr(host, '@')))
27348 host = tmp + 1;
27349
27350 ast_debug(3, "Checking device state for peer %s\n", host);
27351
27352
27353
27354
27355
27356
27357
27358
27359 if ((p = find_peer(host, NULL, FALSE, FINDALLDEVICES, TRUE, 0))) {
27360 if (!(ast_sockaddr_isnull(&p->addr) && ast_sockaddr_isnull(&p->defaddr))) {
27361
27362
27363
27364
27365
27366
27367
27368
27369
27370
27371
27372 if (p->onHold)
27373
27374 res = AST_DEVICE_ONHOLD;
27375 else if (p->inRinging) {
27376 if (p->inRinging == p->inUse)
27377 res = AST_DEVICE_RINGING;
27378 else
27379 res = AST_DEVICE_RINGINUSE;
27380 } else if (p->call_limit && (p->inUse == p->call_limit))
27381
27382 res = AST_DEVICE_BUSY;
27383 else if (p->call_limit && p->busy_level && p->inUse >= p->busy_level)
27384
27385 res = AST_DEVICE_BUSY;
27386 else if (p->call_limit && p->inUse)
27387
27388 res = AST_DEVICE_INUSE;
27389 else if (p->maxms && ((p->lastms > p->maxms) || (p->lastms < 0)))
27390
27391 res = AST_DEVICE_UNAVAILABLE;
27392 else
27393 res = AST_DEVICE_NOT_INUSE;
27394 } else {
27395
27396 res = AST_DEVICE_UNAVAILABLE;
27397 }
27398 unref_peer(p, "unref_peer, from sip_devicestate, release ref from find_peer");
27399 }
27400
27401 return res;
27402 }
27403
27404
27405
27406
27407
27408
27409
27410
27411
27412
27413
27414
27415
27416
27417
27418
27419 static struct ast_channel *sip_request_call(const char *type, format_t format, const struct ast_channel *requestor, void *data, int *cause)
27420 {
27421 struct sip_pvt *p;
27422 struct ast_channel *tmpc = NULL;
27423 char *ext = NULL, *host;
27424 char tmp[256];
27425 char *dest = data;
27426 char *dnid;
27427 char *secret = NULL;
27428 char *md5secret = NULL;
27429 char *authname = NULL;
27430 char *trans = NULL;
27431 char dialstring[256];
27432 char *remote_address;
27433 enum sip_transport transport = 0;
27434 format_t oldformat = format;
27435 AST_DECLARE_APP_ARGS(args,
27436 AST_APP_ARG(peerorhost);
27437 AST_APP_ARG(exten);
27438 AST_APP_ARG(remote_address);
27439 );
27440
27441
27442
27443
27444
27445
27446
27447
27448 format &= AST_FORMAT_AUDIO_MASK;
27449 if (!format) {
27450 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));
27451 *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
27452 return NULL;
27453 }
27454 ast_debug(1, "Asked to create a SIP channel with formats: %s\n", ast_getformatname_multiple(tmp, sizeof(tmp), oldformat));
27455
27456 if (ast_strlen_zero(dest)) {
27457 ast_log(LOG_ERROR, "Unable to create channel with empty destination.\n");
27458 *cause = AST_CAUSE_CHANNEL_UNACCEPTABLE;
27459 return NULL;
27460 }
27461
27462 if (!(p = sip_alloc(NULL, NULL, 0, SIP_INVITE, NULL))) {
27463 ast_log(LOG_ERROR, "Unable to build sip pvt data for '%s' (Out of memory or socket error)\n", dest);
27464 *cause = AST_CAUSE_SWITCH_CONGESTION;
27465 return NULL;
27466 }
27467
27468 p->outgoing_call = TRUE;
27469
27470 snprintf(dialstring, sizeof(dialstring), "%s/%s", type, dest);
27471 ast_string_field_set(p, dialstring, dialstring);
27472
27473 if (!(p->options = ast_calloc(1, sizeof(*p->options)))) {
27474 dialog_unlink_all(p);
27475 dialog_unref(p, "unref dialog p from mem fail");
27476
27477 ast_log(LOG_ERROR, "Unable to build option SIP data structure - Out of memory\n");
27478 *cause = AST_CAUSE_SWITCH_CONGESTION;
27479 return NULL;
27480 }
27481
27482
27483 ast_copy_string(tmp, dest, sizeof(tmp));
27484
27485
27486 dnid = strchr(tmp, '!');
27487 if (dnid != NULL) {
27488 *dnid++ = '\0';
27489 ast_string_field_set(p, todnid, dnid);
27490 }
27491
27492
27493 AST_NONSTANDARD_APP_ARGS(args, tmp, '/');
27494
27495
27496 host = strchr(args.peerorhost, '@');
27497 if (host) {
27498 *host++ = '\0';
27499 ext = args.peerorhost;
27500 secret = strchr(ext, ':');
27501 }
27502 if (secret) {
27503 *secret++ = '\0';
27504 md5secret = strchr(secret, ':');
27505 }
27506 if (md5secret) {
27507 *md5secret++ = '\0';
27508 authname = strchr(md5secret, ':');
27509 }
27510 if (authname) {
27511 *authname++ = '\0';
27512 trans = strchr(authname, ':');
27513 }
27514 if (trans) {
27515 *trans++ = '\0';
27516 if (!strcasecmp(trans, "tcp"))
27517 transport = SIP_TRANSPORT_TCP;
27518 else if (!strcasecmp(trans, "tls"))
27519 transport = SIP_TRANSPORT_TLS;
27520 else {
27521 if (strcasecmp(trans, "udp"))
27522 ast_log(LOG_WARNING, "'%s' is not a valid transport option to Dial() for SIP calls, using udp by default.\n", trans);
27523 transport = SIP_TRANSPORT_UDP;
27524 }
27525 } else {
27526 transport = SIP_TRANSPORT_UDP;
27527 }
27528
27529 if (!host) {
27530 ext = args.exten;
27531 host = args.peerorhost;
27532 remote_address = args.remote_address;
27533 } else {
27534 remote_address = args.remote_address;
27535 if (!ast_strlen_zero(args.exten)) {
27536 ast_log(LOG_NOTICE, "Conflicting extension values given. Using '%s' and not '%s'\n", ext, args.exten);
27537 }
27538 }
27539
27540 if (!ast_strlen_zero(remote_address)) {
27541 p->options->outboundproxy = proxy_from_config(remote_address, 0, NULL);
27542 if (!p->options->outboundproxy) {
27543 ast_log(LOG_WARNING, "Unable to parse outboundproxy %s. We will not use this remote IP address\n", remote_address);
27544 }
27545 }
27546
27547 set_socket_transport(&p->socket, transport);
27548
27549
27550
27551
27552
27553
27554 if (create_addr(p, host, NULL, 1)) {
27555 *cause = AST_CAUSE_UNREGISTERED;
27556 ast_debug(3, "Cant create SIP call - target device not registered\n");
27557 dialog_unlink_all(p);
27558 dialog_unref(p, "unref dialog p UNREGISTERED");
27559
27560 return NULL;
27561 }
27562 if (ast_strlen_zero(p->peername) && ext)
27563 ast_string_field_set(p, peername, ext);
27564
27565 ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
27566 build_via(p);
27567
27568
27569 change_callid_pvt(p, NULL);
27570
27571
27572
27573
27574
27575
27576 if (ext) {
27577 ast_string_field_set(p, username, ext);
27578 ast_string_field_set(p, fullcontact, NULL);
27579 }
27580 if (secret && !ast_strlen_zero(secret))
27581 ast_string_field_set(p, peersecret, secret);
27582
27583 if (md5secret && !ast_strlen_zero(md5secret))
27584 ast_string_field_set(p, peermd5secret, md5secret);
27585
27586 if (authname && !ast_strlen_zero(authname))
27587 ast_string_field_set(p, authname, authname);
27588 #if 0
27589 printf("Setting up to call extension '%s' at '%s'\n", ext ? ext : "<none>", host);
27590 #endif
27591 p->prefcodec = oldformat;
27592 p->jointcapability = oldformat & p->capability;
27593 sip_pvt_lock(p);
27594 tmpc = sip_new(p, AST_STATE_DOWN, host, requestor ? requestor->linkedid : NULL);
27595 if (sip_cfg.callevents)
27596 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
27597 "Channel: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
27598 p->owner ? p->owner->name : "", "SIP", p->callid, p->fullcontact, p->peername);
27599 sip_pvt_unlock(p);
27600 if (!tmpc) {
27601 dialog_unlink_all(p);
27602
27603 } else {
27604 ast_channel_unlock(tmpc);
27605 }
27606 dialog_unref(p, "toss pvt ptr at end of sip_request_call");
27607 ast_update_use_count();
27608 restart_monitor();
27609 return tmpc;
27610 }
27611
27612
27613 static void set_insecure_flags (struct ast_flags *flags, const char *value, int lineno)
27614 {
27615 if (ast_strlen_zero(value))
27616 return;
27617
27618 if (!ast_false(value)) {
27619 char buf[64];
27620 char *word, *next;
27621
27622 ast_copy_string(buf, value, sizeof(buf));
27623 next = buf;
27624 while ((word = strsep(&next, ","))) {
27625 if (!strcasecmp(word, "port"))
27626 ast_set_flag(&flags[0], SIP_INSECURE_PORT);
27627 else if (!strcasecmp(word, "invite"))
27628 ast_set_flag(&flags[0], SIP_INSECURE_INVITE);
27629 else
27630 ast_log(LOG_WARNING, "Unknown insecure mode '%s' on line %d\n", value, lineno);
27631 }
27632 }
27633 }
27634
27635
27636
27637
27638
27639 static int handle_t38_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v,
27640 int *maxdatagram)
27641 {
27642 int res = 1;
27643
27644 if (!strcasecmp(v->name, "t38pt_udptl")) {
27645 char *buf = ast_strdupa(v->value);
27646 char *word, *next = buf;
27647
27648 ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT);
27649
27650 while ((word = strsep(&next, ","))) {
27651 if (ast_true(word) || !strcasecmp(word, "fec")) {
27652 ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
27653 ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_FEC);
27654 } else if (!strcasecmp(word, "redundancy")) {
27655 ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
27656 ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY);
27657 } else if (!strcasecmp(word, "none")) {
27658 ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
27659 ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL);
27660 } else if (!strncasecmp(word, "maxdatagram=", 12)) {
27661 if (sscanf(&word[12], "%30u", maxdatagram) != 1) {
27662 ast_log(LOG_WARNING, "Invalid maxdatagram '%s' at line %d of %s\n", v->value, v->lineno, config);
27663 *maxdatagram = global_t38_maxdatagram;
27664 }
27665 }
27666 }
27667 } else if (!strcasecmp(v->name, "t38pt_usertpsource")) {
27668 ast_set_flag(&mask[1], SIP_PAGE2_UDPTL_DESTINATION);
27669 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_UDPTL_DESTINATION);
27670 } else {
27671 res = 0;
27672 }
27673
27674 return res;
27675 }
27676
27677
27678
27679
27680
27681
27682
27683
27684 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v)
27685 {
27686 int res = 1;
27687
27688 if (!strcasecmp(v->name, "trustrpid")) {
27689 ast_set_flag(&mask[0], SIP_TRUSTRPID);
27690 ast_set2_flag(&flags[0], ast_true(v->value), SIP_TRUSTRPID);
27691 } else if (!strcasecmp(v->name, "sendrpid")) {
27692 ast_set_flag(&mask[0], SIP_SENDRPID);
27693 if (!strcasecmp(v->value, "pai")) {
27694 ast_set_flag(&flags[0], SIP_SENDRPID_PAI);
27695 } else if (!strcasecmp(v->value, "rpid")) {
27696 ast_set_flag(&flags[0], SIP_SENDRPID_RPID);
27697 } else if (ast_true(v->value)) {
27698 ast_set_flag(&flags[0], SIP_SENDRPID_RPID);
27699 }
27700 } else if (!strcasecmp(v->name, "rpid_update")) {
27701 ast_set_flag(&mask[1], SIP_PAGE2_RPID_UPDATE);
27702 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RPID_UPDATE);
27703 } else if (!strcasecmp(v->name, "rpid_immediate")) {
27704 ast_set_flag(&mask[1], SIP_PAGE2_RPID_IMMEDIATE);
27705 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RPID_IMMEDIATE);
27706 } else if (!strcasecmp(v->name, "trust_id_outbound")) {
27707 ast_set_flag(&mask[1], SIP_PAGE2_TRUST_ID_OUTBOUND);
27708 ast_clear_flag(&flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND);
27709 if (!strcasecmp(v->value, "legacy")) {
27710 ast_set_flag(&flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND_LEGACY);
27711 } else if (ast_true(v->value)) {
27712 ast_set_flag(&flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND_YES);
27713 } else if (ast_false(v->value)) {
27714 ast_set_flag(&flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND_NO);
27715 } else {
27716 ast_log(LOG_WARNING, "Unknown trust_id_outbound mode '%s' on line %d, using legacy\n", v->value, v->lineno);
27717 ast_set_flag(&flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND_LEGACY);
27718 }
27719 } else if (!strcasecmp(v->name, "g726nonstandard")) {
27720 ast_set_flag(&mask[0], SIP_G726_NONSTANDARD);
27721 ast_set2_flag(&flags[0], ast_true(v->value), SIP_G726_NONSTANDARD);
27722 } else if (!strcasecmp(v->name, "useclientcode")) {
27723 ast_set_flag(&mask[0], SIP_USECLIENTCODE);
27724 ast_set2_flag(&flags[0], ast_true(v->value), SIP_USECLIENTCODE);
27725 } else if (!strcasecmp(v->name, "dtmfmode")) {
27726 ast_set_flag(&mask[0], SIP_DTMF);
27727 ast_clear_flag(&flags[0], SIP_DTMF);
27728 if (!strcasecmp(v->value, "inband"))
27729 ast_set_flag(&flags[0], SIP_DTMF_INBAND);
27730 else if (!strcasecmp(v->value, "rfc2833"))
27731 ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
27732 else if (!strcasecmp(v->value, "info"))
27733 ast_set_flag(&flags[0], SIP_DTMF_INFO);
27734 else if (!strcasecmp(v->value, "shortinfo"))
27735 ast_set_flag(&flags[0], SIP_DTMF_SHORTINFO);
27736 else if (!strcasecmp(v->value, "auto"))
27737 ast_set_flag(&flags[0], SIP_DTMF_AUTO);
27738 else {
27739 ast_log(LOG_WARNING, "Unknown dtmf mode '%s' on line %d, using rfc2833\n", v->value, v->lineno);
27740 ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
27741 }
27742 } else if (!strcasecmp(v->name, "nat")) {
27743 ast_set_flag(&mask[0], SIP_NAT_FORCE_RPORT);
27744 ast_set_flag(&mask[1], SIP_PAGE2_SYMMETRICRTP);
27745 if (!strcasecmp(v->value, "yes")) {
27746 ast_set_flag(&flags[0], SIP_NAT_FORCE_RPORT);
27747 ast_set_flag(&flags[1], SIP_PAGE2_SYMMETRICRTP);
27748 } else if (!strcasecmp(v->value, "force_rport")) {
27749 ast_set_flag(&flags[0], SIP_NAT_FORCE_RPORT);
27750 } else if (!strcasecmp(v->value, "comedia")) {
27751 ast_set_flag(&flags[1], SIP_PAGE2_SYMMETRICRTP);
27752 }
27753 } else if (!strcasecmp(v->name, "directmedia") || !strcasecmp(v->name, "canreinvite")) {
27754 ast_set_flag(&mask[0], SIP_REINVITE);
27755 ast_clear_flag(&flags[0], SIP_REINVITE);
27756 if (ast_true(v->value)) {
27757 ast_set_flag(&flags[0], SIP_DIRECT_MEDIA | SIP_DIRECT_MEDIA_NAT);
27758 } else if (!ast_false(v->value)) {
27759 char buf[64];
27760 char *word, *next = buf;
27761
27762 ast_copy_string(buf, v->value, sizeof(buf));
27763 while ((word = strsep(&next, ","))) {
27764 if (!strcasecmp(word, "update")) {
27765 ast_set_flag(&flags[0], SIP_REINVITE_UPDATE | SIP_DIRECT_MEDIA);
27766 } else if (!strcasecmp(word, "nonat")) {
27767 ast_set_flag(&flags[0], SIP_DIRECT_MEDIA);
27768 ast_clear_flag(&flags[0], SIP_DIRECT_MEDIA_NAT);
27769 } else if (!strcasecmp(word, "outgoing")) {
27770 ast_set_flag(&flags[0], SIP_DIRECT_MEDIA);
27771 ast_set_flag(&mask[2], SIP_PAGE3_DIRECT_MEDIA_OUTGOING);
27772 ast_set_flag(&flags[2], SIP_PAGE3_DIRECT_MEDIA_OUTGOING);
27773 } else {
27774 ast_log(LOG_WARNING, "Unknown directmedia mode '%s' on line %d\n", v->value, v->lineno);
27775 }
27776 }
27777 }
27778 } else if (!strcasecmp(v->name, "insecure")) {
27779 ast_set_flag(&mask[0], SIP_INSECURE);
27780 ast_clear_flag(&flags[0], SIP_INSECURE);
27781 set_insecure_flags(&flags[0], v->value, v->lineno);
27782 } else if (!strcasecmp(v->name, "progressinband")) {
27783 ast_set_flag(&mask[0], SIP_PROG_INBAND);
27784 ast_clear_flag(&flags[0], SIP_PROG_INBAND);
27785 if (ast_true(v->value))
27786 ast_set_flag(&flags[0], SIP_PROG_INBAND_YES);
27787 else if (strcasecmp(v->value, "never"))
27788 ast_set_flag(&flags[0], SIP_PROG_INBAND_NO);
27789 } else if (!strcasecmp(v->name, "promiscredir")) {
27790 ast_set_flag(&mask[0], SIP_PROMISCREDIR);
27791 ast_set2_flag(&flags[0], ast_true(v->value), SIP_PROMISCREDIR);
27792 } else if (!strcasecmp(v->name, "videosupport")) {
27793 if (!strcasecmp(v->value, "always")) {
27794 ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
27795 ast_set_flag(&flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
27796 } else {
27797 ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT);
27798 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_VIDEOSUPPORT);
27799 }
27800 } else if (!strcasecmp(v->name, "textsupport")) {
27801 ast_set_flag(&mask[1], SIP_PAGE2_TEXTSUPPORT);
27802 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_TEXTSUPPORT);
27803 res = 1;
27804 } else if (!strcasecmp(v->name, "allowoverlap")) {
27805 ast_set_flag(&mask[1], SIP_PAGE2_ALLOWOVERLAP);
27806 ast_clear_flag(&flags[1], SIP_PAGE2_ALLOWOVERLAP);
27807 if (ast_true(v->value)) {
27808 ast_set_flag(&flags[1], SIP_PAGE2_ALLOWOVERLAP_YES);
27809 } else if (!strcasecmp(v->value, "dtmf")){
27810 ast_set_flag(&flags[1], SIP_PAGE2_ALLOWOVERLAP_DTMF);
27811 }
27812 } else if (!strcasecmp(v->name, "allowsubscribe")) {
27813 ast_set_flag(&mask[1], SIP_PAGE2_ALLOWSUBSCRIBE);
27814 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWSUBSCRIBE);
27815 } else if (!strcasecmp(v->name, "ignoresdpversion")) {
27816 ast_set_flag(&mask[1], SIP_PAGE2_IGNORESDPVERSION);
27817 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_IGNORESDPVERSION);
27818 } else if (!strcasecmp(v->name, "faxdetect")) {
27819 ast_set_flag(&mask[1], SIP_PAGE2_FAX_DETECT);
27820 if (ast_true(v->value)) {
27821 ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_BOTH);
27822 } else if (ast_false(v->value)) {
27823 ast_clear_flag(&flags[1], SIP_PAGE2_FAX_DETECT_BOTH);
27824 } else {
27825 char *buf = ast_strdupa(v->value);
27826 char *word, *next = buf;
27827
27828 while ((word = strsep(&next, ","))) {
27829 if (!strcasecmp(word, "cng")) {
27830 ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_CNG);
27831 } else if (!strcasecmp(word, "t38")) {
27832 ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_T38);
27833 } else {
27834 ast_log(LOG_WARNING, "Unknown faxdetect mode '%s' on line %d.\n", word, v->lineno);
27835 }
27836 }
27837 }
27838 } else if (!strcasecmp(v->name, "rfc2833compensate")) {
27839 ast_set_flag(&mask[1], SIP_PAGE2_RFC2833_COMPENSATE);
27840 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RFC2833_COMPENSATE);
27841 } else if (!strcasecmp(v->name, "buggymwi")) {
27842 ast_set_flag(&mask[1], SIP_PAGE2_BUGGY_MWI);
27843 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_BUGGY_MWI);
27844 } else
27845 res = 0;
27846
27847 return res;
27848 }
27849
27850
27851 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context)
27852 {
27853 struct domain *d;
27854
27855 if (ast_strlen_zero(domain)) {
27856 ast_log(LOG_WARNING, "Zero length domain.\n");
27857 return 1;
27858 }
27859
27860 if (!(d = ast_calloc(1, sizeof(*d))))
27861 return 0;
27862
27863 ast_copy_string(d->domain, domain, sizeof(d->domain));
27864
27865 if (!ast_strlen_zero(context))
27866 ast_copy_string(d->context, context, sizeof(d->context));
27867
27868 d->mode = mode;
27869
27870 AST_LIST_LOCK(&domain_list);
27871 AST_LIST_INSERT_TAIL(&domain_list, d, list);
27872 AST_LIST_UNLOCK(&domain_list);
27873
27874 if (sipdebug)
27875 ast_debug(1, "Added local SIP domain '%s'\n", domain);
27876
27877 return 1;
27878 }
27879
27880
27881 static int check_sip_domain(const char *domain, char *context, size_t len)
27882 {
27883 struct domain *d;
27884 int result = 0;
27885
27886 AST_LIST_LOCK(&domain_list);
27887 AST_LIST_TRAVERSE(&domain_list, d, list) {
27888 if (strcasecmp(d->domain, domain)) {
27889 continue;
27890 }
27891
27892 if (len && !ast_strlen_zero(d->context))
27893 ast_copy_string(context, d->context, len);
27894
27895 result = 1;
27896 break;
27897 }
27898 AST_LIST_UNLOCK(&domain_list);
27899
27900 return result;
27901 }
27902
27903
27904 static void clear_sip_domains(void)
27905 {
27906 struct domain *d;
27907
27908 AST_LIST_LOCK(&domain_list);
27909 while ((d = AST_LIST_REMOVE_HEAD(&domain_list, list)))
27910 ast_free(d);
27911 AST_LIST_UNLOCK(&domain_list);
27912 }
27913
27914
27915
27916
27917
27918
27919
27920
27921
27922 static void destroy_realm_authentication(void *obj)
27923 {
27924 struct sip_auth_container *credentials = obj;
27925 struct sip_auth *auth;
27926
27927 while ((auth = AST_LIST_REMOVE_HEAD(&credentials->list, node))) {
27928 ast_free(auth);
27929 }
27930 }
27931
27932
27933
27934
27935
27936
27937
27938
27939
27940
27941
27942 static void add_realm_authentication(struct sip_auth_container **credentials, const char *configuration, int lineno)
27943 {
27944 char *authcopy;
27945 char *username=NULL, *realm=NULL, *secret=NULL, *md5secret=NULL;
27946 struct sip_auth *auth;
27947
27948 if (ast_strlen_zero(configuration)) {
27949
27950 return;
27951 }
27952
27953 ast_debug(1, "Auth config :: %s\n", configuration);
27954
27955 authcopy = ast_strdupa(configuration);
27956 username = authcopy;
27957
27958
27959 realm = strrchr(username, '@');
27960 if (realm)
27961 *realm++ = '\0';
27962 if (ast_strlen_zero(username) || ast_strlen_zero(realm)) {
27963 ast_log(LOG_WARNING, "Format for authentication entry is user[:secret]@realm at line %d\n", lineno);
27964 return;
27965 }
27966
27967
27968 if ((secret = strchr(username, ':'))) {
27969 *secret++ = '\0';
27970 } else if ((md5secret = strchr(username, '#'))) {
27971 *md5secret++ = '\0';
27972 }
27973
27974
27975 if (!*credentials) {
27976 *credentials = ao2_t_alloc(sizeof(**credentials), destroy_realm_authentication,
27977 "Create realm auth container.");
27978 if (!*credentials) {
27979
27980 return;
27981 }
27982 }
27983
27984
27985 auth = ast_calloc(1, sizeof(*auth));
27986 if (!auth) {
27987 return;
27988 }
27989 ast_copy_string(auth->realm, realm, sizeof(auth->realm));
27990 ast_copy_string(auth->username, username, sizeof(auth->username));
27991 if (secret)
27992 ast_copy_string(auth->secret, secret, sizeof(auth->secret));
27993 if (md5secret)
27994 ast_copy_string(auth->md5secret, md5secret, sizeof(auth->md5secret));
27995
27996
27997 AST_LIST_INSERT_TAIL(&(*credentials)->list, auth, node);
27998
27999 ast_verb(3, "Added authentication for realm %s\n", realm);
28000 }
28001
28002
28003
28004
28005
28006
28007
28008
28009
28010
28011 static struct sip_auth *find_realm_authentication(struct sip_auth_container *credentials, const char *realm)
28012 {
28013 struct sip_auth *auth;
28014
28015 if (credentials) {
28016 AST_LIST_TRAVERSE(&credentials->list, auth, node) {
28017 if (!strcasecmp(auth->realm, realm)) {
28018 break;
28019 }
28020 }
28021 } else {
28022 auth = NULL;
28023 }
28024
28025 return auth;
28026 }
28027
28028
28029
28030
28031 static struct ast_variable *add_var(const char *buf, struct ast_variable *list)
28032 {
28033 struct ast_variable *tmpvar = NULL;
28034 char *varname = ast_strdupa(buf), *varval = NULL;
28035
28036 if ((varval = strchr(varname, '='))) {
28037 *varval++ = '\0';
28038 if ((tmpvar = ast_variable_new(varname, varval, ""))) {
28039 tmpvar->next = list;
28040 list = tmpvar;
28041 }
28042 }
28043 return list;
28044 }
28045
28046
28047 static void set_peer_defaults(struct sip_peer *peer)
28048 {
28049 if (peer->expire == 0) {
28050
28051
28052
28053 peer->expire = -1;
28054 peer->pokeexpire = -1;
28055 set_socket_transport(&peer->socket, SIP_TRANSPORT_UDP);
28056 }
28057 peer->type = SIP_TYPE_PEER;
28058 ast_copy_flags(&peer->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
28059 ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
28060 ast_copy_flags(&peer->flags[2], &global_flags[2], SIP_PAGE3_FLAGS_TO_COPY);
28061 ast_string_field_set(peer, context, sip_cfg.default_context);
28062 ast_string_field_set(peer, subscribecontext, sip_cfg.default_subscribecontext);
28063 ast_string_field_set(peer, language, default_language);
28064 ast_string_field_set(peer, mohinterpret, default_mohinterpret);
28065 ast_string_field_set(peer, mohsuggest, default_mohsuggest);
28066 ast_string_field_set(peer, engine, default_engine);
28067 ast_sockaddr_setnull(&peer->addr);
28068 ast_sockaddr_setnull(&peer->defaddr);
28069 peer->capability = sip_cfg.capability;
28070 peer->maxcallbitrate = default_maxcallbitrate;
28071 peer->rtptimeout = global_rtptimeout;
28072 peer->rtpholdtimeout = global_rtpholdtimeout;
28073 peer->rtpkeepalive = global_rtpkeepalive;
28074 peer->allowtransfer = sip_cfg.allowtransfer;
28075 peer->autoframing = global_autoframing;
28076 peer->t38_maxdatagram = global_t38_maxdatagram;
28077 peer->qualifyfreq = global_qualifyfreq;
28078 if (global_callcounter)
28079 peer->call_limit=INT_MAX;
28080 ast_string_field_set(peer, vmexten, default_vmexten);
28081 ast_string_field_set(peer, secret, "");
28082 ast_string_field_set(peer, remotesecret, "");
28083 ast_string_field_set(peer, md5secret, "");
28084 ast_string_field_set(peer, cid_num, "");
28085 ast_string_field_set(peer, cid_name, "");
28086 ast_string_field_set(peer, cid_tag, "");
28087 ast_string_field_set(peer, fromdomain, "");
28088 ast_string_field_set(peer, fromuser, "");
28089 ast_string_field_set(peer, regexten, "");
28090 peer->callgroup = 0;
28091 peer->pickupgroup = 0;
28092 peer->maxms = default_qualify;
28093 peer->prefs = default_prefs;
28094 peer->stimer.st_mode_oper = global_st_mode;
28095 peer->stimer.st_ref = global_st_refresher;
28096 peer->stimer.st_min_se = global_min_se;
28097 peer->stimer.st_max_se = global_max_se;
28098 peer->timer_t1 = global_t1;
28099 peer->timer_b = global_timer_b;
28100 clear_peer_mailboxes(peer);
28101 peer->disallowed_methods = sip_cfg.disallowed_methods;
28102 peer->transports = default_transports;
28103 peer->default_outbound_transport = default_primary_transport;
28104 if (peer->outboundproxy) {
28105 ao2_ref(peer->outboundproxy, -1);
28106 peer->outboundproxy = NULL;
28107 }
28108 }
28109
28110
28111 static struct sip_peer *temp_peer(const char *name)
28112 {
28113 struct sip_peer *peer;
28114
28115 if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct")))
28116 return NULL;
28117
28118 if (ast_string_field_init(peer, 512)) {
28119 ao2_t_ref(peer, -1, "failed to string_field_init, drop peer");
28120 return NULL;
28121 }
28122
28123 if (!(peer->cc_params = ast_cc_config_params_init())) {
28124 ao2_t_ref(peer, -1, "failed to allocate cc_params for peer");
28125 return NULL;
28126 }
28127
28128 ast_atomic_fetchadd_int(&apeerobjs, 1);
28129 set_peer_defaults(peer);
28130
28131 ast_copy_string(peer->name, name, sizeof(peer->name));
28132
28133 peer->selfdestruct = TRUE;
28134 peer->host_dynamic = TRUE;
28135 peer->prefs = default_prefs;
28136 reg_source_db(peer);
28137
28138 return peer;
28139 }
28140
28141
28142 static void add_peer_mailboxes(struct sip_peer *peer, const char *value)
28143 {
28144 char *next, *mbox, *context;
28145
28146 next = ast_strdupa(value);
28147
28148 while ((mbox = context = strsep(&next, ","))) {
28149 struct sip_mailbox *mailbox;
28150 int duplicate = 0;
28151
28152 mbox = ast_strip(mbox);
28153 strsep(&context, "@");
28154
28155 if (ast_strlen_zero(mbox)) {
28156 continue;
28157 }
28158
28159
28160 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
28161 if (!strcmp(mailbox->mailbox, mbox) && !strcmp(S_OR(mailbox->context, ""), S_OR(context, ""))) {
28162 duplicate = 1;
28163 break;
28164 }
28165 }
28166 if (duplicate) {
28167 continue;
28168 }
28169
28170 if (!(mailbox = ast_calloc(1, sizeof(*mailbox) + strlen(mbox) + strlen(S_OR(context, ""))))) {
28171 continue;
28172 }
28173
28174 if (!ast_strlen_zero(context)) {
28175 mailbox->context = mailbox->mailbox + strlen(mbox) + 1;
28176 strcpy(mailbox->context, context);
28177 }
28178 strcpy(mailbox->mailbox, mbox);
28179
28180 AST_LIST_INSERT_TAIL(&peer->mailboxes, mailbox, entry);
28181 }
28182 }
28183
28184
28185 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only)
28186 {
28187 struct sip_peer *peer = NULL;
28188 struct ast_ha *oldha = NULL;
28189 struct ast_ha *olddirectmediaha = NULL;
28190 int found = 0;
28191 int firstpass = 1;
28192 uint16_t port = 0;
28193 int format = 0;
28194 int timerb_set = 0, timert1_set = 0;
28195 time_t regseconds = 0;
28196 struct ast_flags peerflags[3] = {{(0)}};
28197 struct ast_flags mask[3] = {{(0)}};
28198 char callback[256] = "";
28199 struct sip_peer tmp_peer;
28200 const char *srvlookup = NULL;
28201 static int deprecation_warning = 1;
28202 int alt_fullcontact = alt ? 1 : 0, headercount = 0;
28203 struct ast_str *fullcontact = ast_str_alloca(512);
28204
28205 if (!realtime || ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
28206
28207
28208
28209
28210
28211 ast_copy_string(tmp_peer.name, name, sizeof(tmp_peer.name));
28212 peer = ao2_t_find(peers, &tmp_peer, OBJ_POINTER | OBJ_UNLINK, "find and unlink peer from peers table");
28213 }
28214
28215 if (peer) {
28216
28217 found++;
28218
28219
28220 if (!ast_sockaddr_isnull(&peer->addr)) {
28221 ao2_t_unlink(peers_by_ip, peer, "ao2_unlink peer from peers_by_ip table");
28222 }
28223 if (!(peer->the_mark))
28224 firstpass = 0;
28225 } else {
28226 if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct")))
28227 return NULL;
28228
28229 if (ast_string_field_init(peer, 512)) {
28230 ao2_t_ref(peer, -1, "failed to string_field_init, drop peer");
28231 return NULL;
28232 }
28233
28234 if (!(peer->cc_params = ast_cc_config_params_init())) {
28235 ao2_t_ref(peer, -1, "failed to allocate cc_params for peer");
28236 return NULL;
28237 }
28238
28239 if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
28240 ast_atomic_fetchadd_int(&rpeerobjs, 1);
28241 ast_debug(3, "-REALTIME- peer built. Name: %s. Peer objects: %d\n", name, rpeerobjs);
28242 } else
28243 ast_atomic_fetchadd_int(&speerobjs, 1);
28244 }
28245
28246
28247 if (firstpass) {
28248 peer->lastmsgssent = -1;
28249 oldha = peer->ha;
28250 peer->ha = NULL;
28251 olddirectmediaha = peer->directmediaha;
28252 peer->directmediaha = NULL;
28253 set_peer_defaults(peer);
28254 peer->type = 0;
28255 }
28256
28257
28258 ast_copy_string(peer->name, name, sizeof(peer->name));
28259
28260
28261 if (peer->chanvars) {
28262 ast_variables_destroy(peer->chanvars);
28263 peer->chanvars = NULL;
28264
28265 }
28266
28267 if (found)
28268 peer->portinuri = 0;
28269
28270
28271 ao2_lock(peer);
28272 if (peer->auth) {
28273 ao2_t_ref(peer->auth, -1, "Removing old peer authentication");
28274 peer->auth = NULL;
28275 }
28276 ao2_unlock(peer);
28277
28278
28279 peer->default_outbound_transport = 0;
28280 peer->transports = 0;
28281
28282 if (!devstate_only) {
28283 struct sip_mailbox *mailbox;
28284 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
28285 mailbox->delme = 1;
28286 }
28287 }
28288
28289 for (; v || ((v = alt) && !(alt=NULL)); v = v->next) {
28290 if (!devstate_only) {
28291 if (handle_common_options(&peerflags[0], &mask[0], v)) {
28292 continue;
28293 }
28294 if (handle_t38_options(&peerflags[0], &mask[0], v, &peer->t38_maxdatagram)) {
28295 continue;
28296 }
28297 if (!strcasecmp(v->name, "transport")) {
28298 char *val = ast_strdupa(v->value);
28299 char *trans;
28300
28301 peer->transports = peer->default_outbound_transport = 0;
28302 while ((trans = strsep(&val, ","))) {
28303 trans = ast_skip_blanks(trans);
28304
28305 if (!strncasecmp(trans, "udp", 3)) {
28306 peer->transports |= SIP_TRANSPORT_UDP;
28307 } else if (sip_cfg.tcp_enabled && !strncasecmp(trans, "tcp", 3)) {
28308 peer->transports |= SIP_TRANSPORT_TCP;
28309 } else if (default_tls_cfg.enabled && !strncasecmp(trans, "tls", 3)) {
28310 peer->transports |= SIP_TRANSPORT_TLS;
28311 } else if (!strncasecmp(trans, "tcp", 3) || !strncasecmp(trans, "tls", 3)) {
28312 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);
28313 } else {
28314 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);
28315 }
28316
28317 if (!peer->default_outbound_transport) {
28318 peer->default_outbound_transport = peer->transports;
28319 }
28320 }
28321 } else if (realtime && !strcasecmp(v->name, "regseconds")) {
28322 ast_get_time_t(v->value, ®seconds, 0, NULL);
28323 } else if (realtime && !strcasecmp(v->name, "name")) {
28324 ast_copy_string(peer->name, v->value, sizeof(peer->name));
28325 } else if (realtime && !strcasecmp(v->name, "useragent")) {
28326 ast_string_field_set(peer, useragent, v->value);
28327 } else if (!strcasecmp(v->name, "type")) {
28328 if (!strcasecmp(v->value, "peer")) {
28329 peer->type |= SIP_TYPE_PEER;
28330 } else if (!strcasecmp(v->value, "user")) {
28331 peer->type |= SIP_TYPE_USER;
28332 } else if (!strcasecmp(v->value, "friend")) {
28333 peer->type = SIP_TYPE_USER | SIP_TYPE_PEER;
28334 }
28335 } else if (!strcasecmp(v->name, "remotesecret")) {
28336 ast_string_field_set(peer, remotesecret, v->value);
28337 } else if (!strcasecmp(v->name, "secret")) {
28338 ast_string_field_set(peer, secret, v->value);
28339 } else if (!strcasecmp(v->name, "md5secret")) {
28340 ast_string_field_set(peer, md5secret, v->value);
28341 } else if (!strcasecmp(v->name, "auth")) {
28342 add_realm_authentication(&peer->auth, v->value, v->lineno);
28343 } else if (!strcasecmp(v->name, "callerid")) {
28344 char cid_name[80] = { '\0' }, cid_num[80] = { '\0' };
28345
28346 ast_callerid_split(v->value, cid_name, sizeof(cid_name), cid_num, sizeof(cid_num));
28347 ast_string_field_set(peer, cid_name, cid_name);
28348 ast_string_field_set(peer, cid_num, cid_num);
28349 } else if (!strcasecmp(v->name, "mwi_from")) {
28350 ast_string_field_set(peer, mwi_from, v->value);
28351 } else if (!strcasecmp(v->name, "fullname")) {
28352 ast_string_field_set(peer, cid_name, v->value);
28353 } else if (!strcasecmp(v->name, "trunkname")) {
28354
28355 ast_string_field_set(peer, cid_name, "");
28356 } else if (!strcasecmp(v->name, "cid_number")) {
28357 ast_string_field_set(peer, cid_num, v->value);
28358 } else if (!strcasecmp(v->name, "cid_tag")) {
28359 ast_string_field_set(peer, cid_tag, v->value);
28360 } else if (!strcasecmp(v->name, "context")) {
28361 ast_string_field_set(peer, context, v->value);
28362 ast_set_flag(&peer->flags[1], SIP_PAGE2_HAVEPEERCONTEXT);
28363 } else if (!strcasecmp(v->name, "subscribecontext")) {
28364 ast_string_field_set(peer, subscribecontext, v->value);
28365 } else if (!strcasecmp(v->name, "fromdomain")) {
28366 char *fromdomainport;
28367 ast_string_field_set(peer, fromdomain, v->value);
28368 if ((fromdomainport = strchr(peer->fromdomain, ':'))) {
28369 *fromdomainport++ = '\0';
28370 if (!(peer->fromdomainport = port_str2int(fromdomainport, 0))) {
28371 ast_log(LOG_NOTICE, "'%s' is not a valid port number for fromdomain.\n",fromdomainport);
28372 }
28373 } else {
28374 peer->fromdomainport = STANDARD_SIP_PORT;
28375 }
28376 } else if (!strcasecmp(v->name, "usereqphone")) {
28377 ast_set2_flag(&peer->flags[0], ast_true(v->value), SIP_USEREQPHONE);
28378 } else if (!strcasecmp(v->name, "fromuser")) {
28379 ast_string_field_set(peer, fromuser, v->value);
28380 } else if (!strcasecmp(v->name, "outboundproxy")) {
28381 struct sip_proxy *proxy;
28382 if (ast_strlen_zero(v->value)) {
28383 ast_log(LOG_WARNING, "no value given for outbound proxy on line %d of sip.conf\n", v->lineno);
28384 continue;
28385 }
28386 proxy = proxy_from_config(v->value, v->lineno, peer->outboundproxy);
28387 if (!proxy) {
28388 ast_log(LOG_WARNING, "failure parsing the outbound proxy on line %d of sip.conf.\n", v->lineno);
28389 continue;
28390 }
28391 peer->outboundproxy = proxy;
28392 } else if (!strcasecmp(v->name, "host")) {
28393 if (!strcasecmp(v->value, "dynamic")) {
28394
28395 if ((!found && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) || !peer->host_dynamic) {
28396
28397
28398 ast_sockaddr_setnull(&peer->addr);
28399 }
28400 peer->host_dynamic = TRUE;
28401 } else {
28402
28403 AST_SCHED_DEL_UNREF(sched, peer->expire,
28404 unref_peer(peer, "removing register expire ref"));
28405 peer->host_dynamic = FALSE;
28406 srvlookup = v->value;
28407 }
28408 } else if (!strcasecmp(v->name, "defaultip")) {
28409 if (!ast_strlen_zero(v->value) && ast_get_ip(&peer->defaddr, v->value)) {
28410 unref_peer(peer, "unref_peer: from build_peer defaultip");
28411 return NULL;
28412 }
28413 } else if (!strcasecmp(v->name, "permit") || !strcasecmp(v->name, "deny")) {
28414 int ha_error = 0;
28415 if (!ast_strlen_zero(v->value)) {
28416 peer->ha = ast_append_ha(v->name, v->value, peer->ha, &ha_error);
28417 }
28418 if (ha_error) {
28419 ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
28420 }
28421 } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny")) {
28422 int ha_error = 0;
28423 if (!ast_strlen_zero(v->value)) {
28424 peer->contactha = ast_append_ha(v->name + 7, v->value, peer->contactha, &ha_error);
28425 }
28426 if (ha_error) {
28427 ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
28428 }
28429 } else if (!strcasecmp(v->name, "directmediapermit") || !strcasecmp(v->name, "directmediadeny")) {
28430 int ha_error = 0;
28431 peer->directmediaha = ast_append_ha(v->name + 11, v->value, peer->directmediaha, &ha_error);
28432 if (ha_error) {
28433 ast_log(LOG_ERROR, "Bad directmedia ACL entry in configuration line %d : %s\n", v->lineno, v->value);
28434 }
28435 } else if (!strcasecmp(v->name, "port")) {
28436 peer->portinuri = 1;
28437 if (!(port = port_str2int(v->value, 0))) {
28438 if (realtime) {
28439
28440 peer->portinuri = 0;
28441 } else {
28442 ast_log(LOG_WARNING, "Invalid peer port configuration at line %d : %s\n", v->lineno, v->value);
28443 }
28444 }
28445 } else if (!strcasecmp(v->name, "callingpres")) {
28446 peer->callingpres = ast_parse_caller_presentation(v->value);
28447 if (peer->callingpres == -1) {
28448 peer->callingpres = atoi(v->value);
28449 }
28450 } else if (!strcasecmp(v->name, "username") || !strcmp(v->name, "defaultuser")) {
28451 ast_string_field_set(peer, username, v->value);
28452 if (!strcasecmp(v->name, "username")) {
28453 if (deprecation_warning) {
28454 ast_log(LOG_NOTICE, "The 'username' field for sip peers has been deprecated in favor of the term 'defaultuser'\n");
28455 deprecation_warning = 0;
28456 }
28457 peer->deprecated_username = 1;
28458 }
28459 } else if (!strcasecmp(v->name, "language")) {
28460 ast_string_field_set(peer, language, v->value);
28461 } else if (!strcasecmp(v->name, "regexten")) {
28462 ast_string_field_set(peer, regexten, v->value);
28463 } else if (!strcasecmp(v->name, "callbackextension")) {
28464 ast_copy_string(callback, v->value, sizeof(callback));
28465 } else if (!strcasecmp(v->name, "amaflags")) {
28466 format = ast_cdr_amaflags2int(v->value);
28467 if (format < 0) {
28468 ast_log(LOG_WARNING, "Invalid AMA Flags for peer: %s at line %d\n", v->value, v->lineno);
28469 } else {
28470 peer->amaflags = format;
28471 }
28472 } else if (!strcasecmp(v->name, "maxforwards")) {
28473 if (sscanf(v->value, "%30d", &peer->maxforwards) != 1
28474 || peer->maxforwards < 1 || 255 < peer->maxforwards) {
28475 ast_log(LOG_WARNING, "'%s' is not a valid maxforwards value at line %d. Using default.\n", v->value, v->lineno);
28476 peer->maxforwards = sip_cfg.default_max_forwards;
28477 }
28478 } else if (!strcasecmp(v->name, "accountcode")) {
28479 ast_string_field_set(peer, accountcode, v->value);
28480 } else if (!strcasecmp(v->name, "mohinterpret")) {
28481 ast_string_field_set(peer, mohinterpret, v->value);
28482 } else if (!strcasecmp(v->name, "mohsuggest")) {
28483 ast_string_field_set(peer, mohsuggest, v->value);
28484 } else if (!strcasecmp(v->name, "parkinglot")) {
28485 ast_string_field_set(peer, parkinglot, v->value);
28486 } else if (!strcasecmp(v->name, "rtp_engine")) {
28487 ast_string_field_set(peer, engine, v->value);
28488 } else if (!strcasecmp(v->name, "mailbox")) {
28489 add_peer_mailboxes(peer, v->value);
28490 } else if (!strcasecmp(v->name, "hasvoicemail")) {
28491
28492
28493 if (ast_true(v->value) && AST_LIST_EMPTY(&peer->mailboxes)) {
28494 add_peer_mailboxes(peer, name);
28495 }
28496 } else if (!strcasecmp(v->name, "subscribemwi")) {
28497 ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_SUBSCRIBEMWIONLY);
28498 } else if (!strcasecmp(v->name, "vmexten")) {
28499 ast_string_field_set(peer, vmexten, v->value);
28500 } else if (!strcasecmp(v->name, "callgroup")) {
28501 peer->callgroup = ast_get_group(v->value);
28502 } else if (!strcasecmp(v->name, "allowtransfer")) {
28503 peer->allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
28504 } else if (!strcasecmp(v->name, "pickupgroup")) {
28505 peer->pickupgroup = ast_get_group(v->value);
28506 } else if (!strcasecmp(v->name, "allow")) {
28507 int error = ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, TRUE);
28508 if (error) {
28509 ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
28510 }
28511 } else if (!strcasecmp(v->name, "disallow")) {
28512 int error = ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, FALSE);
28513 if (error) {
28514 ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
28515 }
28516 } else if (!strcasecmp(v->name, "preferred_codec_only")) {
28517 ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_PREFERRED_CODEC);
28518 } else if (!strcasecmp(v->name, "autoframing")) {
28519 peer->autoframing = ast_true(v->value);
28520 } else if (!strcasecmp(v->name, "rtptimeout")) {
28521 if ((sscanf(v->value, "%30d", &peer->rtptimeout) != 1) || (peer->rtptimeout < 0)) {
28522 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
28523 peer->rtptimeout = global_rtptimeout;
28524 }
28525 } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
28526 if ((sscanf(v->value, "%30d", &peer->rtpholdtimeout) != 1) || (peer->rtpholdtimeout < 0)) {
28527 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
28528 peer->rtpholdtimeout = global_rtpholdtimeout;
28529 }
28530 } else if (!strcasecmp(v->name, "rtpkeepalive")) {
28531 if ((sscanf(v->value, "%30d", &peer->rtpkeepalive) != 1) || (peer->rtpkeepalive < 0)) {
28532 ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d. Using default.\n", v->value, v->lineno);
28533 peer->rtpkeepalive = global_rtpkeepalive;
28534 }
28535 } else if (!strcasecmp(v->name, "timert1")) {
28536 if ((sscanf(v->value, "%30d", &peer->timer_t1) != 1) || (peer->timer_t1 < 200) || (peer->timer_t1 < global_t1min)) {
28537 ast_log(LOG_WARNING, "'%s' is not a valid T1 time at line %d. Using default.\n", v->value, v->lineno);
28538 peer->timer_t1 = global_t1min;
28539 }
28540 timert1_set = 1;
28541 } else if (!strcasecmp(v->name, "timerb")) {
28542 if ((sscanf(v->value, "%30d", &peer->timer_b) != 1) || (peer->timer_b < 200)) {
28543 ast_log(LOG_WARNING, "'%s' is not a valid Timer B time at line %d. Using default.\n", v->value, v->lineno);
28544 peer->timer_b = global_timer_b;
28545 }
28546 timerb_set = 1;
28547 } else if (!strcasecmp(v->name, "setvar")) {
28548 peer->chanvars = add_var(v->value, peer->chanvars);
28549 } else if (!strcasecmp(v->name, "header")) {
28550 char tmp[4096];
28551 snprintf(tmp, sizeof(tmp), "__SIPADDHEADERpre%2d=%s", ++headercount, v->value);
28552 peer->chanvars = add_var(tmp, peer->chanvars);
28553 } else if (!strcasecmp(v->name, "qualifyfreq")) {
28554 int i;
28555 if (sscanf(v->value, "%30d", &i) == 1) {
28556 peer->qualifyfreq = i * 1000;
28557 } else {
28558 ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
28559 peer->qualifyfreq = global_qualifyfreq;
28560 }
28561 } else if (!strcasecmp(v->name, "maxcallbitrate")) {
28562 peer->maxcallbitrate = atoi(v->value);
28563 if (peer->maxcallbitrate < 0) {
28564 peer->maxcallbitrate = default_maxcallbitrate;
28565 }
28566 } else if (!strcasecmp(v->name, "session-timers")) {
28567 int i = (int) str2stmode(v->value);
28568 if (i < 0) {
28569 ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
28570 peer->stimer.st_mode_oper = global_st_mode;
28571 } else {
28572 peer->stimer.st_mode_oper = i;
28573 }
28574 } else if (!strcasecmp(v->name, "session-expires")) {
28575 if (sscanf(v->value, "%30d", &peer->stimer.st_max_se) != 1) {
28576 ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
28577 peer->stimer.st_max_se = global_max_se;
28578 }
28579 } else if (!strcasecmp(v->name, "session-minse")) {
28580 if (sscanf(v->value, "%30d", &peer->stimer.st_min_se) != 1) {
28581 ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
28582 peer->stimer.st_min_se = global_min_se;
28583 }
28584 if (peer->stimer.st_min_se < DEFAULT_MIN_SE) {
28585 ast_log(LOG_WARNING, "session-minse '%s' at line %d of %s is not allowed to be < %d secs\n", v->value, v->lineno, config, DEFAULT_MIN_SE);
28586 peer->stimer.st_min_se = global_min_se;
28587 }
28588 } else if (!strcasecmp(v->name, "session-refresher")) {
28589 int i = (int) str2strefresherparam(v->value);
28590 if (i < 0) {
28591 ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
28592 peer->stimer.st_ref = global_st_refresher;
28593 } else {
28594 peer->stimer.st_ref = i;
28595 }
28596 } else if (!strcasecmp(v->name, "disallowed_methods")) {
28597 char *disallow = ast_strdupa(v->value);
28598 mark_parsed_methods(&peer->disallowed_methods, disallow);
28599 } else if (!strcasecmp(v->name, "unsolicited_mailbox")) {
28600 ast_string_field_set(peer, unsolicited_mailbox, v->value);
28601 } else if (!strcasecmp(v->name, "use_q850_reason")) {
28602 ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_Q850_REASON);
28603 } else if (!strcasecmp(v->name, "encryption")) {
28604 ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_USE_SRTP);
28605 } else if (!strcasecmp(v->name, "snom_aoc_enabled")) {
28606 ast_set2_flag(&peer->flags[2], ast_true(v->value), SIP_PAGE3_SNOM_AOC);
28607 }
28608 }
28609
28610
28611 if (realtime && !strcasecmp(v->name, "lastms")) {
28612 sscanf(v->value, "%30d", &peer->lastms);
28613 } else if (realtime && !strcasecmp(v->name, "ipaddr") && !ast_strlen_zero(v->value) ) {
28614 ast_sockaddr_parse(&peer->addr, v->value, PARSE_PORT_FORBID);
28615 } else if (realtime && !strcasecmp(v->name, "fullcontact")) {
28616 if (alt_fullcontact && !alt) {
28617
28618
28619
28620
28621
28622 alt_fullcontact = 0;
28623 ast_str_reset(fullcontact);
28624 }
28625
28626 if (ast_str_strlen(fullcontact) > 0) {
28627 ast_str_append(&fullcontact, 0, ";%s", v->value);
28628 } else {
28629 ast_str_set(&fullcontact, 0, "%s", v->value);
28630 }
28631 } else if (!strcasecmp(v->name, "qualify")) {
28632 if (!strcasecmp(v->value, "no")) {
28633 peer->maxms = 0;
28634 } else if (!strcasecmp(v->value, "yes")) {
28635 peer->maxms = default_qualify ? default_qualify : DEFAULT_MAXMS;
28636 } else if (sscanf(v->value, "%30d", &peer->maxms) != 1) {
28637 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);
28638 peer->maxms = 0;
28639 }
28640 if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && peer->maxms > 0) {
28641
28642
28643
28644
28645 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);
28646 peer->maxms = 0;
28647 }
28648 } else if (!strcasecmp(v->name, "callcounter")) {
28649 peer->call_limit = ast_true(v->value) ? INT_MAX : 0;
28650 } else if (!strcasecmp(v->name, "call-limit")) {
28651 peer->call_limit = atoi(v->value);
28652 if (peer->call_limit < 0) {
28653 peer->call_limit = 0;
28654 }
28655 } else if (!strcasecmp(v->name, "busylevel")) {
28656 peer->busy_level = atoi(v->value);
28657 if (peer->busy_level < 0) {
28658 peer->busy_level = 0;
28659 }
28660 } else if (ast_cc_is_config_param(v->name)) {
28661 ast_cc_set_param(peer->cc_params, v->name, v->value);
28662 }
28663 }
28664
28665 if (!devstate_only) {
28666 struct sip_mailbox *mailbox;
28667 AST_LIST_TRAVERSE_SAFE_BEGIN(&peer->mailboxes, mailbox, entry) {
28668 if (mailbox->delme) {
28669 AST_LIST_REMOVE_CURRENT(entry);
28670 destroy_mailbox(mailbox);
28671 }
28672 }
28673 AST_LIST_TRAVERSE_SAFE_END;
28674 }
28675
28676 if (!can_parse_xml && (ast_get_cc_agent_policy(peer->cc_params) == AST_CC_AGENT_NATIVE)) {
28677 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);
28678 ast_set_cc_agent_policy(peer->cc_params, AST_CC_AGENT_NEVER);
28679 }
28680
28681
28682
28683 if (peer->timer_b < peer->timer_t1 * 64) {
28684 if (timerb_set && timert1_set) {
28685 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);
28686 } else if (timerb_set) {
28687 if ((peer->timer_t1 = peer->timer_b / 64) < global_t1min) {
28688 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);
28689 peer->timer_t1 = global_t1min;
28690 peer->timer_b = peer->timer_t1 * 64;
28691 }
28692 peer->timer_t1 = peer->timer_b / 64;
28693 } else {
28694 peer->timer_b = peer->timer_t1 * 64;
28695 }
28696 }
28697
28698 if (!peer->default_outbound_transport) {
28699
28700 peer->transports = default_transports;
28701
28702 peer->default_outbound_transport = default_primary_transport;
28703 }
28704
28705
28706
28707
28708
28709 if (((peer->socket.type != peer->default_outbound_transport) && (peer->expire == -1)) ||
28710 !(peer->socket.type & peer->transports) || !(peer->socket.type)) {
28711
28712 set_socket_transport(&peer->socket, peer->default_outbound_transport);
28713 }
28714
28715 ast_copy_flags(&peer->flags[0], &peerflags[0], mask[0].flags);
28716 ast_copy_flags(&peer->flags[1], &peerflags[1], mask[1].flags);
28717 ast_copy_flags(&peer->flags[2], &peerflags[2], mask[2].flags);
28718
28719 if (ast_str_strlen(fullcontact)) {
28720 ast_string_field_set(peer, fullcontact, ast_str_buffer(fullcontact));
28721 peer->rt_fromcontact = TRUE;
28722
28723
28724
28725
28726
28727
28728
28729
28730 if (!ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) || ast_sockaddr_isnull(&peer->addr)) {
28731 __set_address_from_contact(ast_str_buffer(fullcontact), &peer->addr, 0);
28732 }
28733 }
28734
28735 if (srvlookup && peer->dnsmgr == NULL) {
28736 char transport[MAXHOSTNAMELEN];
28737 char _srvlookup[MAXHOSTNAMELEN];
28738 char *params;
28739
28740 ast_copy_string(_srvlookup, srvlookup, sizeof(_srvlookup));
28741 if ((params = strchr(_srvlookup, ';'))) {
28742 *params++ = '\0';
28743 }
28744
28745 snprintf(transport, sizeof(transport), "_%s._%s", get_srv_service(peer->socket.type), get_srv_protocol(peer->socket.type));
28746
28747 peer->addr.ss.ss_family = get_address_family_filter(peer->socket.type);
28748 if (ast_dnsmgr_lookup_cb(_srvlookup, &peer->addr, &peer->dnsmgr, sip_cfg.srvlookup && !peer->portinuri ? transport : NULL,
28749 on_dns_update_peer, ref_peer(peer, "Store peer on dnsmgr"))) {
28750 ast_log(LOG_ERROR, "srvlookup failed for host: %s, on peer %s, removing peer\n", _srvlookup, peer->name);
28751 unref_peer(peer, "dnsmgr lookup failed, getting rid of peer dnsmgr ref");
28752 unref_peer(peer, "getting rid of a peer pointer");
28753 return NULL;
28754 }
28755 if (!peer->dnsmgr) {
28756
28757 unref_peer(peer, "dnsmgr disabled, unref peer");
28758 }
28759
28760 ast_string_field_set(peer, tohost, srvlookup);
28761
28762 if (global_dynamic_exclude_static && !ast_sockaddr_isnull(&peer->addr)) {
28763 int ha_error = 0;
28764 sip_cfg.contact_ha = ast_append_ha("deny", ast_sockaddr_stringify_addr(&peer->addr),
28765 sip_cfg.contact_ha, &ha_error);
28766 if (ha_error) {
28767 ast_log(LOG_ERROR, "Bad or unresolved host/IP entry in configuration for peer %s, cannot add to contact ACL\n", peer->name);
28768 }
28769 }
28770 } else if (peer->dnsmgr && !peer->host_dynamic) {
28771
28772 ast_dnsmgr_refresh(peer->dnsmgr);
28773 }
28774
28775 if (port && !realtime && peer->host_dynamic) {
28776 ast_sockaddr_set_port(&peer->defaddr, port);
28777 } else if (port) {
28778 ast_sockaddr_set_port(&peer->addr, port);
28779 }
28780
28781 if (ast_sockaddr_port(&peer->addr) == 0) {
28782 ast_sockaddr_set_port(&peer->addr,
28783 (peer->socket.type & SIP_TRANSPORT_TLS) ?
28784 STANDARD_TLS_PORT : STANDARD_SIP_PORT);
28785 }
28786 if (ast_sockaddr_port(&peer->defaddr) == 0) {
28787 ast_sockaddr_set_port(&peer->defaddr,
28788 (peer->socket.type & SIP_TRANSPORT_TLS) ?
28789 STANDARD_TLS_PORT : STANDARD_SIP_PORT);
28790 }
28791 if (!peer->socket.port) {
28792 peer->socket.port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
28793 }
28794
28795 if (realtime) {
28796 int enablepoke = 1;
28797
28798 if (!sip_cfg.ignore_regexpire && peer->host_dynamic) {
28799 time_t nowtime = time(NULL);
28800
28801 if ((nowtime - regseconds) > 0) {
28802 destroy_association(peer);
28803 memset(&peer->addr, 0, sizeof(peer->addr));
28804 peer->lastms = -1;
28805 enablepoke = 0;
28806 ast_debug(1, "Bah, we're expired (%d/%d/%d)!\n", (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
28807 }
28808 }
28809
28810
28811 if (!devstate_only && enablepoke) {
28812 ref_peer(peer, "schedule qualify");
28813 sip_poke_peer(peer, 0);
28814 }
28815 }
28816
28817 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
28818 sip_cfg.allowsubscribe = TRUE;
28819 }
28820
28821 if (peer->host_dynamic && (!peer->is_realtime || !sip_cfg.peer_rtupdate)) {
28822 reg_source_db(peer);
28823 }
28824
28825
28826
28827 if (!devstate_only && !ast_test_flag(&peer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY) &&
28828 !AST_LIST_EMPTY(&peer->mailboxes)) {
28829 add_peer_mwi_subs(peer);
28830
28831
28832
28833 sip_send_mwi_to_peer(peer, 1);
28834 }
28835
28836 peer->the_mark = 0;
28837
28838 ast_free_ha(oldha);
28839 ast_free_ha(olddirectmediaha);
28840 if (!ast_strlen_zero(callback)) {
28841 char *reg_string;
28842 if (ast_asprintf(®_string, "%s?%s:%s@%s/%s", peer->name, peer->username, !ast_strlen_zero(peer->remotesecret) ? peer->remotesecret : peer->secret, peer->tohost, callback) >= 0) {
28843 sip_register(reg_string, 0);
28844 ast_free(reg_string);
28845 }
28846 }
28847 return peer;
28848 }
28849
28850 static int peer_markall_func(void *device, void *arg, int flags)
28851 {
28852 struct sip_peer *peer = device;
28853 peer->the_mark = 1;
28854 return 0;
28855 }
28856
28857 static void display_nat_warning(const char *cat, int reason, struct ast_flags *flags) {
28858 int global_nat, specific_nat;
28859
28860 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))) {
28861 ast_log(LOG_WARNING, "!!! PLEASE NOTE: Setting 'nat' for a peer/user that differs from the global setting can make\n");
28862 ast_log(LOG_WARNING, "!!! the name of that peer/user discoverable by an attacker. Replies for non-existent peers/users\n");
28863 ast_log(LOG_WARNING, "!!! will be sent to a different port than replies for an existing peer/user. If at all possible,\n");
28864 ast_log(LOG_WARNING, "!!! use the global 'nat' setting and do not set 'nat' per peer/user.\n");
28865 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));
28866 }
28867 }
28868
28869 static void cleanup_all_regs(void)
28870 {
28871
28872
28873 ASTOBJ_CONTAINER_TRAVERSE(®l, 1, do {
28874 ASTOBJ_WRLOCK(iterator);
28875 if (iterator->call) {
28876 ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", iterator->username, iterator->hostname);
28877
28878 dialog_unlink_all(iterator->call);
28879 iterator->call = dialog_unref(iterator->call, "remove iterator->call from registry traversal");
28880 }
28881 if (iterator->expire > -1) {
28882 AST_SCHED_DEL_UNREF(sched, iterator->expire, registry_unref(iterator, "reg ptr unref from reload config"));
28883 }
28884 if (iterator->timeout > -1) {
28885 AST_SCHED_DEL_UNREF(sched, iterator->timeout, registry_unref(iterator, "reg ptr unref from reload config"));
28886 }
28887 if (iterator->dnsmgr) {
28888 ast_dnsmgr_release(iterator->dnsmgr);
28889 iterator->dnsmgr = NULL;
28890 registry_unref(iterator, "reg ptr unref from dnsmgr");
28891 }
28892 ASTOBJ_UNLOCK(iterator);
28893 } while(0));
28894 }
28895
28896
28897
28898
28899
28900
28901
28902 static int reload_config(enum channelreloadreason reason)
28903 {
28904 struct ast_config *cfg, *ucfg;
28905 struct ast_variable *v;
28906 struct sip_peer *peer;
28907 char *cat, *stringp, *context, *oldregcontext;
28908 char newcontexts[AST_MAX_CONTEXT], oldcontexts[AST_MAX_CONTEXT];
28909 struct ast_flags mask[3] = {{0}};
28910 struct ast_flags setflags[3] = {{0}};
28911 struct ast_flags config_flags = { reason == CHANNEL_MODULE_LOAD ? 0 : ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) ? 0 : CONFIG_FLAG_FILEUNCHANGED };
28912 int auto_sip_domains = FALSE;
28913 struct ast_sockaddr old_bindaddr = bindaddr;
28914 int registry_count = 0, peer_count = 0, timerb_set = 0, timert1_set = 0;
28915 int subscribe_network_change = 1;
28916 time_t run_start, run_end;
28917 int bindport = 0;
28918
28919 run_start = time(0);
28920 ast_unload_realtime("sipregs");
28921 ast_unload_realtime("sippeers");
28922 cfg = ast_config_load(config, config_flags);
28923
28924
28925 if (!cfg) {
28926 ast_log(LOG_NOTICE, "Unable to load config %s\n", config);
28927 return -1;
28928 } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
28929 ucfg = ast_config_load("users.conf", config_flags);
28930 if (ucfg == CONFIG_STATUS_FILEUNCHANGED) {
28931 return 1;
28932 } else if (ucfg == CONFIG_STATUS_FILEINVALID) {
28933 ast_log(LOG_ERROR, "Contents of users.conf are invalid and cannot be parsed\n");
28934 return 1;
28935 }
28936
28937 ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
28938 if ((cfg = ast_config_load(config, config_flags)) == CONFIG_STATUS_FILEINVALID) {
28939 ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed\n", config);
28940 ast_config_destroy(ucfg);
28941 return 1;
28942 }
28943 if (!cfg) {
28944
28945 ast_log(LOG_NOTICE, "Unable to load config %s\n", config);
28946 return -1;
28947 }
28948 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
28949 ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed\n", config);
28950 return 1;
28951 } else {
28952 ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
28953 if ((ucfg = ast_config_load("users.conf", config_flags)) == CONFIG_STATUS_FILEINVALID) {
28954 ast_log(LOG_ERROR, "Contents of users.conf are invalid and cannot be parsed\n");
28955 ast_config_destroy(cfg);
28956 return 1;
28957 }
28958 }
28959
28960 ast_free_ha(sip_cfg.contact_ha);
28961 sip_cfg.contact_ha = NULL;
28962
28963 default_tls_cfg.enabled = FALSE;
28964
28965 if (reason != CHANNEL_MODULE_LOAD) {
28966 ast_debug(4, "--------------- SIP reload started\n");
28967
28968 clear_sip_domains();
28969 ast_mutex_lock(&authl_lock);
28970 if (authl) {
28971 ao2_t_ref(authl, -1, "Removing old global authentication");
28972 authl = NULL;
28973 }
28974 ast_mutex_unlock(&authl_lock);
28975
28976
28977 cleanup_all_regs();
28978
28979 ASTOBJ_CONTAINER_DESTROYALL(®l, sip_registry_destroy);
28980 ast_debug(4, "--------------- Done destroying registry list\n");
28981 ao2_t_callback(peers, OBJ_NODATA, peer_markall_func, NULL, "callback to mark all peers");
28982 }
28983
28984
28985 if (reason != CHANNEL_MODULE_LOAD) {
28986 ast_free(default_tls_cfg.certfile);
28987 ast_free(default_tls_cfg.pvtfile);
28988 ast_free(default_tls_cfg.cipher);
28989 ast_free(default_tls_cfg.cafile);
28990 ast_free(default_tls_cfg.capath);
28991 }
28992 default_tls_cfg.certfile = ast_strdup(AST_CERTFILE);
28993 default_tls_cfg.pvtfile = ast_strdup("");
28994 default_tls_cfg.cipher = ast_strdup("");
28995 default_tls_cfg.cafile = ast_strdup("");
28996 default_tls_cfg.capath = ast_strdup("");
28997
28998
28999 ast_copy_string(oldcontexts, sip_cfg.regcontext, sizeof(oldcontexts));
29000 oldregcontext = oldcontexts;
29001
29002
29003
29004 sipdebug &= sip_debug_console;
29005 ast_clear_flag(&global_flags[0], AST_FLAGS_ALL);
29006 ast_clear_flag(&global_flags[1], AST_FLAGS_ALL);
29007 ast_clear_flag(&global_flags[2], AST_FLAGS_ALL);
29008
29009
29010 ast_sockaddr_parse(&bindaddr, "0.0.0.0:0", 0);
29011 memset(&internip, 0, sizeof(internip));
29012
29013
29014 ast_free_ha(localaddr);
29015 memset(&localaddr, 0, sizeof(localaddr));
29016 memset(&externaddr, 0, sizeof(externaddr));
29017 memset(&media_address, 0, sizeof(media_address));
29018 memset(&default_prefs, 0 , sizeof(default_prefs));
29019 memset(&sip_cfg.outboundproxy, 0, sizeof(struct sip_proxy));
29020 sip_cfg.outboundproxy.force = FALSE;
29021 default_transports = SIP_TRANSPORT_UDP;
29022 default_primary_transport = SIP_TRANSPORT_UDP;
29023 ourport_tcp = STANDARD_SIP_PORT;
29024 ourport_tls = STANDARD_TLS_PORT;
29025 externtcpport = STANDARD_SIP_PORT;
29026 externtlsport = STANDARD_TLS_PORT;
29027 sip_cfg.srvlookup = DEFAULT_SRVLOOKUP;
29028 global_tos_sip = DEFAULT_TOS_SIP;
29029 global_tos_audio = DEFAULT_TOS_AUDIO;
29030 global_tos_video = DEFAULT_TOS_VIDEO;
29031 global_tos_text = DEFAULT_TOS_TEXT;
29032 global_cos_sip = DEFAULT_COS_SIP;
29033 global_cos_audio = DEFAULT_COS_AUDIO;
29034 global_cos_video = DEFAULT_COS_VIDEO;
29035 global_cos_text = DEFAULT_COS_TEXT;
29036
29037 externhost[0] = '\0';
29038 externexpire = 0;
29039 externrefresh = 10;
29040
29041
29042 sip_cfg.allow_external_domains = DEFAULT_ALLOW_EXT_DOM;
29043 sip_cfg.regcontext[0] = '\0';
29044 sip_cfg.capability = DEFAULT_CAPABILITY;
29045 sip_cfg.regextenonqualify = DEFAULT_REGEXTENONQUALIFY;
29046 sip_cfg.legacy_useroption_parsing = DEFAULT_LEGACY_USEROPTION_PARSING;
29047 sip_cfg.notifyringing = DEFAULT_NOTIFYRINGING;
29048 sip_cfg.notifycid = DEFAULT_NOTIFYCID;
29049 sip_cfg.notifyhold = FALSE;
29050 sip_cfg.directrtpsetup = FALSE;
29051 sip_cfg.alwaysauthreject = DEFAULT_ALWAYSAUTHREJECT;
29052 sip_cfg.auth_options_requests = DEFAULT_AUTH_OPTIONS;
29053 sip_cfg.allowsubscribe = FALSE;
29054 sip_cfg.disallowed_methods = SIP_UNKNOWN;
29055 sip_cfg.contact_ha = NULL;
29056 snprintf(global_useragent, sizeof(global_useragent), "%s %s", DEFAULT_USERAGENT, ast_get_version());
29057 snprintf(global_sdpsession, sizeof(global_sdpsession), "%s %s", DEFAULT_SDPSESSION, ast_get_version());
29058 snprintf(global_sdpowner, sizeof(global_sdpowner), "%s", DEFAULT_SDPOWNER);
29059 global_prematuremediafilter = TRUE;
29060 ast_copy_string(default_notifymime, DEFAULT_NOTIFYMIME, sizeof(default_notifymime));
29061 ast_copy_string(sip_cfg.realm, S_OR(ast_config_AST_SYSTEM_NAME, DEFAULT_REALM), sizeof(sip_cfg.realm));
29062 sip_cfg.domainsasrealm = DEFAULT_DOMAINSASREALM;
29063 ast_copy_string(default_callerid, DEFAULT_CALLERID, sizeof(default_callerid));
29064 ast_copy_string(default_mwi_from, DEFAULT_MWI_FROM, sizeof(default_mwi_from));
29065 sip_cfg.compactheaders = DEFAULT_COMPACTHEADERS;
29066 global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
29067 global_regattempts_max = 0;
29068 global_reg_retry_403 = 0;
29069 sip_cfg.pedanticsipchecking = DEFAULT_PEDANTIC;
29070 sip_cfg.autocreatepeer = DEFAULT_AUTOCREATEPEER;
29071 global_autoframing = 0;
29072 sip_cfg.allowguest = DEFAULT_ALLOWGUEST;
29073 global_callcounter = DEFAULT_CALLCOUNTER;
29074 global_match_auth_username = FALSE;
29075 global_rtptimeout = 0;
29076 global_rtpholdtimeout = 0;
29077 global_rtpkeepalive = DEFAULT_RTPKEEPALIVE;
29078 sip_cfg.allowtransfer = TRANSFER_OPENFORALL;
29079 sip_cfg.rtautoclear = 120;
29080 ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE);
29081 ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP_YES);
29082 sip_cfg.peer_rtupdate = TRUE;
29083 global_dynamic_exclude_static = 0;
29084 sip_cfg.tcp_enabled = FALSE;
29085
29086
29087 global_st_mode = SESSION_TIMER_MODE_ACCEPT;
29088 global_st_refresher = SESSION_TIMER_REFRESHER_PARAM_UAS;
29089 global_min_se = DEFAULT_MIN_SE;
29090 global_max_se = DEFAULT_MAX_SE;
29091
29092
29093 global_qualify_gap = DEFAULT_QUALIFY_GAP;
29094 global_qualify_peers = DEFAULT_QUALIFY_PEERS;
29095
29096
29097 ast_copy_string(sip_cfg.default_context, DEFAULT_CONTEXT, sizeof(sip_cfg.default_context));
29098 sip_cfg.default_subscribecontext[0] = '\0';
29099 sip_cfg.default_max_forwards = DEFAULT_MAX_FORWARDS;
29100 default_language[0] = '\0';
29101 default_fromdomain[0] = '\0';
29102 default_fromdomainport = 0;
29103 default_qualify = DEFAULT_QUALIFY;
29104 default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
29105 ast_copy_string(default_mohinterpret, DEFAULT_MOHINTERPRET, sizeof(default_mohinterpret));
29106 ast_copy_string(default_mohsuggest, DEFAULT_MOHSUGGEST, sizeof(default_mohsuggest));
29107 ast_copy_string(default_vmexten, DEFAULT_VMEXTEN, sizeof(default_vmexten));
29108 ast_set_flag(&global_flags[0], SIP_DTMF_RFC2833);
29109 ast_set_flag(&global_flags[0], SIP_DIRECT_MEDIA);
29110 ast_set_flag(&global_flags[0], SIP_NAT_FORCE_RPORT);
29111 ast_copy_string(default_engine, DEFAULT_ENGINE, sizeof(default_engine));
29112 ast_copy_string(default_parkinglot, DEFAULT_PARKINGLOT, sizeof(default_parkinglot));
29113
29114
29115 dumphistory = FALSE;
29116 recordhistory = FALSE;
29117 sipdebug &= ~sip_debug_config;
29118
29119
29120 global_relaxdtmf = FALSE;
29121 sip_cfg.callevents = DEFAULT_CALLEVENTS;
29122 global_authfailureevents = FALSE;
29123 global_t1 = DEFAULT_TIMER_T1;
29124 global_timer_b = 64 * DEFAULT_TIMER_T1;
29125 global_t1min = DEFAULT_T1MIN;
29126 global_qualifyfreq = DEFAULT_QUALIFYFREQ;
29127 global_t38_maxdatagram = -1;
29128 global_shrinkcallerid = 1;
29129 authlimit = DEFAULT_AUTHLIMIT;
29130 authtimeout = DEFAULT_AUTHTIMEOUT;
29131 global_store_sip_cause = DEFAULT_STORE_SIP_CAUSE;
29132
29133 sip_cfg.matchexternaddrlocally = DEFAULT_MATCHEXTERNADDRLOCALLY;
29134
29135
29136 memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
29137
29138 ast_clear_flag(&global_flags[1], SIP_PAGE2_FAX_DETECT);
29139 ast_clear_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT | SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
29140 ast_clear_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT);
29141 ast_clear_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION);
29142
29143
29144
29145 for (v = ast_variable_browse(cfg, "general"); v; v = v->next) {
29146 if (handle_common_options(&setflags[0], &mask[0], v)) {
29147 continue;
29148 }
29149 if (handle_t38_options(&setflags[0], &mask[0], v, &global_t38_maxdatagram)) {
29150 continue;
29151 }
29152
29153 if (!ast_jb_read_conf(&global_jbconf, v->name, v->value))
29154 continue;
29155
29156
29157 if (!strcasecmp(v->name, "tlsverifyclient")) {
29158 ast_log(LOG_WARNING, "Ignoring unsupported option 'tlsverifyclient'\n");
29159 continue;
29160 } else if (!ast_tls_read_conf(&default_tls_cfg, &sip_tls_desc, v->name, v->value)) {
29161 continue;
29162 }
29163
29164 if (!strcasecmp(v->name, "context")) {
29165 ast_copy_string(sip_cfg.default_context, v->value, sizeof(sip_cfg.default_context));
29166 } else if (!strcasecmp(v->name, "subscribecontext")) {
29167 ast_copy_string(sip_cfg.default_subscribecontext, v->value, sizeof(sip_cfg.default_subscribecontext));
29168 } else if (!strcasecmp(v->name, "callcounter")) {
29169 global_callcounter = ast_true(v->value) ? 1 : 0;
29170 } else if (!strcasecmp(v->name, "allowguest")) {
29171 sip_cfg.allowguest = ast_true(v->value) ? 1 : 0;
29172 } else if (!strcasecmp(v->name, "realm")) {
29173 ast_copy_string(sip_cfg.realm, v->value, sizeof(sip_cfg.realm));
29174 } else if (!strcasecmp(v->name, "domainsasrealm")) {
29175 sip_cfg.domainsasrealm = ast_true(v->value);
29176 } else if (!strcasecmp(v->name, "useragent")) {
29177 ast_copy_string(global_useragent, v->value, sizeof(global_useragent));
29178 ast_debug(1, "Setting SIP channel User-Agent Name to %s\n", global_useragent);
29179 } else if (!strcasecmp(v->name, "sdpsession")) {
29180 ast_copy_string(global_sdpsession, v->value, sizeof(global_sdpsession));
29181 } else if (!strcasecmp(v->name, "sdpowner")) {
29182
29183 if (!strstr(v->value, " ")) {
29184 ast_copy_string(global_sdpowner, v->value, sizeof(global_sdpowner));
29185 } else {
29186 ast_log(LOG_WARNING, "'%s' must not contain spaces at line %d. Using default.\n", v->value, v->lineno);
29187 }
29188 } else if (!strcasecmp(v->name, "allowtransfer")) {
29189 sip_cfg.allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
29190 } else if (!strcasecmp(v->name, "rtcachefriends")) {
29191 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTCACHEFRIENDS);
29192 } else if (!strcasecmp(v->name, "rtsavesysname")) {
29193 sip_cfg.rtsave_sysname = ast_true(v->value);
29194 } else if (!strcasecmp(v->name, "rtupdate")) {
29195 sip_cfg.peer_rtupdate = ast_true(v->value);
29196 } else if (!strcasecmp(v->name, "ignoreregexpire")) {
29197 sip_cfg.ignore_regexpire = ast_true(v->value);
29198 } else if (!strcasecmp(v->name, "timert1")) {
29199
29200
29201
29202 global_t1 = atoi(v->value);
29203 } else if (!strcasecmp(v->name, "timerb")) {
29204 int tmp = atoi(v->value);
29205 if (tmp < 500) {
29206 global_timer_b = global_t1 * 64;
29207 ast_log(LOG_WARNING, "Invalid value for timerb ('%s'). Setting to default ('%d').\n", v->value, global_timer_b);
29208 }
29209 timerb_set = 1;
29210 } else if (!strcasecmp(v->name, "t1min")) {
29211 global_t1min = atoi(v->value);
29212 } else if (!strcasecmp(v->name, "transport")) {
29213 char *val = ast_strdupa(v->value);
29214 char *trans;
29215
29216 default_transports = default_primary_transport = 0;
29217 while ((trans = strsep(&val, ","))) {
29218 trans = ast_skip_blanks(trans);
29219
29220 if (!strncasecmp(trans, "udp", 3)) {
29221 default_transports |= SIP_TRANSPORT_UDP;
29222 } else if (!strncasecmp(trans, "tcp", 3)) {
29223 default_transports |= SIP_TRANSPORT_TCP;
29224 } else if (!strncasecmp(trans, "tls", 3)) {
29225 default_transports |= SIP_TRANSPORT_TLS;
29226 } else {
29227 ast_log(LOG_NOTICE, "'%s' is not a valid transport type. if no other is specified, udp will be used.\n", trans);
29228 }
29229 if (default_primary_transport == 0) {
29230 default_primary_transport = default_transports;
29231 }
29232 }
29233 } else if (!strcasecmp(v->name, "tcpenable")) {
29234 if (!ast_false(v->value)) {
29235 ast_debug(2, "Enabling TCP socket for listening\n");
29236 sip_cfg.tcp_enabled = TRUE;
29237 }
29238 } else if (!strcasecmp(v->name, "tcpbindaddr")) {
29239 if (ast_parse_arg(v->value, PARSE_ADDR,
29240 &sip_tcp_desc.local_address)) {
29241 ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n",
29242 v->name, v->value, v->lineno, config);
29243 }
29244 ast_debug(2, "Setting TCP socket address to %s\n",
29245 ast_sockaddr_stringify(&sip_tcp_desc.local_address));
29246 } else if (!strcasecmp(v->name, "dynamic_exclude_static") || !strcasecmp(v->name, "dynamic_excludes_static")) {
29247 global_dynamic_exclude_static = ast_true(v->value);
29248 } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny")) {
29249 int ha_error = 0;
29250 sip_cfg.contact_ha = ast_append_ha(v->name + 7, v->value, sip_cfg.contact_ha, &ha_error);
29251 if (ha_error) {
29252 ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
29253 }
29254 } else if (!strcasecmp(v->name, "rtautoclear")) {
29255 int i = atoi(v->value);
29256 if (i > 0) {
29257 sip_cfg.rtautoclear = i;
29258 } else {
29259 i = 0;
29260 }
29261 ast_set2_flag(&global_flags[1], i || ast_true(v->value), SIP_PAGE2_RTAUTOCLEAR);
29262 } else if (!strcasecmp(v->name, "usereqphone")) {
29263 ast_set2_flag(&global_flags[0], ast_true(v->value), SIP_USEREQPHONE);
29264 } else if (!strcasecmp(v->name, "prematuremedia")) {
29265 global_prematuremediafilter = ast_true(v->value);
29266 } else if (!strcasecmp(v->name, "relaxdtmf")) {
29267 global_relaxdtmf = ast_true(v->value);
29268 } else if (!strcasecmp(v->name, "vmexten")) {
29269 ast_copy_string(default_vmexten, v->value, sizeof(default_vmexten));
29270 } else if (!strcasecmp(v->name, "rtptimeout")) {
29271 if ((sscanf(v->value, "%30d", &global_rtptimeout) != 1) || (global_rtptimeout < 0)) {
29272 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
29273 global_rtptimeout = 0;
29274 }
29275 } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
29276 if ((sscanf(v->value, "%30d", &global_rtpholdtimeout) != 1) || (global_rtpholdtimeout < 0)) {
29277 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
29278 global_rtpholdtimeout = 0;
29279 }
29280 } else if (!strcasecmp(v->name, "rtpkeepalive")) {
29281 if ((sscanf(v->value, "%30d", &global_rtpkeepalive) != 1) || (global_rtpkeepalive < 0)) {
29282 ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d. Using default.\n", v->value, v->lineno);
29283 global_rtpkeepalive = DEFAULT_RTPKEEPALIVE;
29284 }
29285 } else if (!strcasecmp(v->name, "compactheaders")) {
29286 sip_cfg.compactheaders = ast_true(v->value);
29287 } else if (!strcasecmp(v->name, "notifymimetype")) {
29288 ast_copy_string(default_notifymime, v->value, sizeof(default_notifymime));
29289 } else if (!strcasecmp(v->name, "directrtpsetup")) {
29290 sip_cfg.directrtpsetup = ast_true(v->value);
29291 } else if (!strcasecmp(v->name, "notifyringing")) {
29292 sip_cfg.notifyringing = ast_true(v->value);
29293 } else if (!strcasecmp(v->name, "notifyhold")) {
29294 sip_cfg.notifyhold = ast_true(v->value);
29295 } else if (!strcasecmp(v->name, "notifycid")) {
29296 if (!strcasecmp(v->value, "ignore-context")) {
29297 sip_cfg.notifycid = IGNORE_CONTEXT;
29298 } else {
29299 sip_cfg.notifycid = ast_true(v->value) ? ENABLED : DISABLED;
29300 }
29301 } else if (!strcasecmp(v->name, "alwaysauthreject")) {
29302 sip_cfg.alwaysauthreject = ast_true(v->value);
29303 } else if (!strcasecmp(v->name, "auth_options_requests")) {
29304 if (ast_true(v->value)) {
29305 sip_cfg.auth_options_requests = 1;
29306 }
29307 } else if (!strcasecmp(v->name, "mohinterpret")) {
29308 ast_copy_string(default_mohinterpret, v->value, sizeof(default_mohinterpret));
29309 } else if (!strcasecmp(v->name, "mohsuggest")) {
29310 ast_copy_string(default_mohsuggest, v->value, sizeof(default_mohsuggest));
29311 } else if (!strcasecmp(v->name, "language")) {
29312 ast_copy_string(default_language, v->value, sizeof(default_language));
29313 } else if (!strcasecmp(v->name, "regcontext")) {
29314 ast_copy_string(newcontexts, v->value, sizeof(newcontexts));
29315 stringp = newcontexts;
29316
29317 cleanup_stale_contexts(stringp, oldregcontext);
29318
29319 while ((context = strsep(&stringp, "&"))) {
29320 ast_copy_string(used_context, context, sizeof(used_context));
29321 ast_context_find_or_create(NULL, NULL, context, "SIP");
29322 }
29323 ast_copy_string(sip_cfg.regcontext, v->value, sizeof(sip_cfg.regcontext));
29324 } else if (!strcasecmp(v->name, "regextenonqualify")) {
29325 sip_cfg.regextenonqualify = ast_true(v->value);
29326 } else if (!strcasecmp(v->name, "legacy_useroption_parsing")) {
29327 sip_cfg.legacy_useroption_parsing = ast_true(v->value);
29328 } else if (!strcasecmp(v->name, "callerid")) {
29329 ast_copy_string(default_callerid, v->value, sizeof(default_callerid));
29330 } else if (!strcasecmp(v->name, "mwi_from")) {
29331 ast_copy_string(default_mwi_from, v->value, sizeof(default_mwi_from));
29332 } else if (!strcasecmp(v->name, "fromdomain")) {
29333 char *fromdomainport;
29334 ast_copy_string(default_fromdomain, v->value, sizeof(default_fromdomain));
29335 if ((fromdomainport = strchr(default_fromdomain, ':'))) {
29336 *fromdomainport++ = '\0';
29337 if (!(default_fromdomainport = port_str2int(fromdomainport, 0))) {
29338 ast_log(LOG_NOTICE, "'%s' is not a valid port number for fromdomain.\n",fromdomainport);
29339 }
29340 } else {
29341 default_fromdomainport = STANDARD_SIP_PORT;
29342 }
29343 } else if (!strcasecmp(v->name, "outboundproxy")) {
29344 struct sip_proxy *proxy;
29345 if (ast_strlen_zero(v->value)) {
29346 ast_log(LOG_WARNING, "no value given for outbound proxy on line %d of sip.conf\n", v->lineno);
29347 continue;
29348 }
29349 proxy = proxy_from_config(v->value, v->lineno, &sip_cfg.outboundproxy);
29350 if (!proxy) {
29351 ast_log(LOG_WARNING, "failure parsing the outbound proxy on line %d of sip.conf.\n", v->lineno);
29352 continue;
29353 }
29354 } else if (!strcasecmp(v->name, "autocreatepeer")) {
29355 sip_cfg.autocreatepeer = ast_true(v->value);
29356 } else if (!strcasecmp(v->name, "match_auth_username")) {
29357 global_match_auth_username = ast_true(v->value);
29358 } else if (!strcasecmp(v->name, "srvlookup")) {
29359 sip_cfg.srvlookup = ast_true(v->value);
29360 } else if (!strcasecmp(v->name, "pedantic")) {
29361 sip_cfg.pedanticsipchecking = ast_true(v->value);
29362 } else if (!strcasecmp(v->name, "maxexpirey") || !strcasecmp(v->name, "maxexpiry")) {
29363 max_expiry = atoi(v->value);
29364 if (max_expiry < 1) {
29365 max_expiry = DEFAULT_MAX_EXPIRY;
29366 }
29367 } else if (!strcasecmp(v->name, "minexpirey") || !strcasecmp(v->name, "minexpiry")) {
29368 min_expiry = atoi(v->value);
29369 if (min_expiry < 1) {
29370 min_expiry = DEFAULT_MIN_EXPIRY;
29371 }
29372 } else if (!strcasecmp(v->name, "defaultexpiry") || !strcasecmp(v->name, "defaultexpirey")) {
29373 default_expiry = atoi(v->value);
29374 if (default_expiry < 1) {
29375 default_expiry = DEFAULT_DEFAULT_EXPIRY;
29376 }
29377 } else if (!strcasecmp(v->name, "mwiexpiry") || !strcasecmp(v->name, "mwiexpirey")) {
29378 mwi_expiry = atoi(v->value);
29379 if (mwi_expiry < 1) {
29380 mwi_expiry = DEFAULT_MWI_EXPIRY;
29381 }
29382 } else if (!strcasecmp(v->name, "tcpauthtimeout")) {
29383 if (ast_parse_arg(v->value, PARSE_INT32|PARSE_DEFAULT|PARSE_IN_RANGE,
29384 &authtimeout, DEFAULT_AUTHTIMEOUT, 1, INT_MAX)) {
29385 ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n",
29386 v->name, v->value, v->lineno, config);
29387 }
29388 } else if (!strcasecmp(v->name, "tcpauthlimit")) {
29389 if (ast_parse_arg(v->value, PARSE_INT32|PARSE_DEFAULT|PARSE_IN_RANGE,
29390 &authlimit, DEFAULT_AUTHLIMIT, 1, INT_MAX)) {
29391 ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n",
29392 v->name, v->value, v->lineno, config);
29393 }
29394 } else if (!strcasecmp(v->name, "sipdebug")) {
29395 if (ast_true(v->value))
29396 sipdebug |= sip_debug_config;
29397 } else if (!strcasecmp(v->name, "dumphistory")) {
29398 dumphistory = ast_true(v->value);
29399 } else if (!strcasecmp(v->name, "recordhistory")) {
29400 recordhistory = ast_true(v->value);
29401 } else if (!strcasecmp(v->name, "registertimeout")) {
29402 global_reg_timeout = atoi(v->value);
29403 if (global_reg_timeout < 1) {
29404 global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
29405 }
29406 } else if (!strcasecmp(v->name, "registerattempts")) {
29407 global_regattempts_max = atoi(v->value);
29408 } else if (!strcasecmp(v->name, "register_retry_403")) {
29409 global_reg_retry_403 = ast_true(v->value);
29410 } else if (!strcasecmp(v->name, "bindaddr") || !strcasecmp(v->name, "udpbindaddr")) {
29411 if (ast_parse_arg(v->value, PARSE_ADDR, &bindaddr)) {
29412 ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
29413 }
29414 } else if (!strcasecmp(v->name, "localnet")) {
29415 struct ast_ha *na;
29416 int ha_error = 0;
29417
29418 if (!(na = ast_append_ha("d", v->value, localaddr, &ha_error))) {
29419 ast_log(LOG_WARNING, "Invalid localnet value: %s\n", v->value);
29420 } else {
29421 localaddr = na;
29422 }
29423 if (ha_error) {
29424 ast_log(LOG_ERROR, "Bad localnet configuration value line %d : %s\n", v->lineno, v->value);
29425 }
29426 } else if (!strcasecmp(v->name, "media_address")) {
29427 if (ast_parse_arg(v->value, PARSE_ADDR, &media_address))
29428 ast_log(LOG_WARNING, "Invalid address for media_address keyword: %s\n", v->value);
29429 } else if (!strcasecmp(v->name, "externaddr") || !strcasecmp(v->name, "externip")) {
29430 if (ast_parse_arg(v->value, PARSE_ADDR, &externaddr)) {
29431 ast_log(LOG_WARNING,
29432 "Invalid address for externaddr keyword: %s\n",
29433 v->value);
29434 }
29435 externexpire = 0;
29436 } else if (!strcasecmp(v->name, "externhost")) {
29437 ast_copy_string(externhost, v->value, sizeof(externhost));
29438 if (ast_sockaddr_resolve_first(&externaddr, externhost, 0)) {
29439 ast_log(LOG_WARNING, "Invalid address for externhost keyword: %s\n", externhost);
29440 }
29441 externexpire = time(NULL);
29442 } else if (!strcasecmp(v->name, "externrefresh")) {
29443 if (sscanf(v->value, "%30d", &externrefresh) != 1) {
29444 ast_log(LOG_WARNING, "Invalid externrefresh value '%s', must be an integer >0 at line %d\n", v->value, v->lineno);
29445 externrefresh = 10;
29446 }
29447 } else if (!strcasecmp(v->name, "externtcpport")) {
29448 if (!(externtcpport = port_str2int(v->value, 0))) {
29449 ast_log(LOG_WARNING, "Invalid externtcpport value, must be a positive integer between 1 and 65535 at line %d\n", v->lineno);
29450 externtcpport = 0;
29451 }
29452 } else if (!strcasecmp(v->name, "externtlsport")) {
29453 if (!(externtlsport = port_str2int(v->value, STANDARD_TLS_PORT))) {
29454 ast_log(LOG_WARNING, "Invalid externtlsport value, must be a positive integer between 1 and 65535 at line %d\n", v->lineno);
29455 }
29456 } else if (!strcasecmp(v->name, "allow")) {
29457 int error = ast_parse_allow_disallow(&default_prefs, &sip_cfg.capability, v->value, TRUE);
29458 if (error) {
29459 ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
29460 }
29461 } else if (!strcasecmp(v->name, "disallow")) {
29462 int error = ast_parse_allow_disallow(&default_prefs, &sip_cfg.capability, v->value, FALSE);
29463 if (error) {
29464 ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
29465 }
29466 } else if (!strcasecmp(v->name, "preferred_codec_only")) {
29467 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_PREFERRED_CODEC);
29468 } else if (!strcasecmp(v->name, "autoframing")) {
29469 global_autoframing = ast_true(v->value);
29470 } else if (!strcasecmp(v->name, "allowexternaldomains")) {
29471 sip_cfg.allow_external_domains = ast_true(v->value);
29472 } else if (!strcasecmp(v->name, "autodomain")) {
29473 auto_sip_domains = ast_true(v->value);
29474 } else if (!strcasecmp(v->name, "domain")) {
29475 char *domain = ast_strdupa(v->value);
29476 char *cntx = strchr(domain, ',');
29477
29478 if (cntx) {
29479 *cntx++ = '\0';
29480 }
29481
29482 if (ast_strlen_zero(cntx)) {
29483 ast_debug(1, "No context specified at line %d for domain '%s'\n", v->lineno, domain);
29484 }
29485 if (ast_strlen_zero(domain)) {
29486 ast_log(LOG_WARNING, "Empty domain specified at line %d\n", v->lineno);
29487 } else {
29488 add_sip_domain(ast_strip(domain), SIP_DOMAIN_CONFIG, cntx ? ast_strip(cntx) : "");
29489 }
29490 } else if (!strcasecmp(v->name, "register")) {
29491 if (sip_register(v->value, v->lineno) == 0) {
29492 registry_count++;
29493 }
29494 } else if (!strcasecmp(v->name, "mwi")) {
29495 sip_subscribe_mwi(v->value, v->lineno);
29496 } else if (!strcasecmp(v->name, "tos_sip")) {
29497 if (ast_str2tos(v->value, &global_tos_sip)) {
29498 ast_log(LOG_WARNING, "Invalid tos_sip value at line %d, refer to QoS documentation\n", v->lineno);
29499 }
29500 } else if (!strcasecmp(v->name, "tos_audio")) {
29501 if (ast_str2tos(v->value, &global_tos_audio)) {
29502 ast_log(LOG_WARNING, "Invalid tos_audio value at line %d, refer to QoS documentation\n", v->lineno);
29503 }
29504 } else if (!strcasecmp(v->name, "tos_video")) {
29505 if (ast_str2tos(v->value, &global_tos_video)) {
29506 ast_log(LOG_WARNING, "Invalid tos_video value at line %d, refer to QoS documentation\n", v->lineno);
29507 }
29508 } else if (!strcasecmp(v->name, "tos_text")) {
29509 if (ast_str2tos(v->value, &global_tos_text)) {
29510 ast_log(LOG_WARNING, "Invalid tos_text value at line %d, refer to QoS documentation\n", v->lineno);
29511 }
29512 } else if (!strcasecmp(v->name, "cos_sip")) {
29513 if (ast_str2cos(v->value, &global_cos_sip)) {
29514 ast_log(LOG_WARNING, "Invalid cos_sip value at line %d, refer to QoS documentation\n", v->lineno);
29515 }
29516 } else if (!strcasecmp(v->name, "cos_audio")) {
29517 if (ast_str2cos(v->value, &global_cos_audio)) {
29518 ast_log(LOG_WARNING, "Invalid cos_audio value at line %d, refer to QoS documentation\n", v->lineno);
29519 }
29520 } else if (!strcasecmp(v->name, "cos_video")) {
29521 if (ast_str2cos(v->value, &global_cos_video)) {
29522 ast_log(LOG_WARNING, "Invalid cos_video value at line %d, refer to QoS documentation\n", v->lineno);
29523 }
29524 } else if (!strcasecmp(v->name, "cos_text")) {
29525 if (ast_str2cos(v->value, &global_cos_text)) {
29526 ast_log(LOG_WARNING, "Invalid cos_text value at line %d, refer to QoS documentation\n", v->lineno);
29527 }
29528 } else if (!strcasecmp(v->name, "bindport")) {
29529 if (sscanf(v->value, "%5d", &bindport) != 1) {
29530 ast_log(LOG_WARNING, "Invalid port number '%s' at line %d of %s\n", v->value, v->lineno, config);
29531 }
29532 } else if (!strcasecmp(v->name, "qualify")) {
29533 if (!strcasecmp(v->value, "no")) {
29534 default_qualify = 0;
29535 } else if (!strcasecmp(v->value, "yes")) {
29536 default_qualify = DEFAULT_MAXMS;
29537 } else if (sscanf(v->value, "%30d", &default_qualify) != 1) {
29538 ast_log(LOG_WARNING, "Qualification default should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", v->lineno);
29539 default_qualify = 0;
29540 }
29541 } else if (!strcasecmp(v->name, "qualifyfreq")) {
29542 int i;
29543 if (sscanf(v->value, "%30d", &i) == 1) {
29544 global_qualifyfreq = i * 1000;
29545 } else {
29546 ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
29547 global_qualifyfreq = DEFAULT_QUALIFYFREQ;
29548 }
29549 } else if (!strcasecmp(v->name, "callevents")) {
29550 sip_cfg.callevents = ast_true(v->value);
29551 } else if (!strcasecmp(v->name, "authfailureevents")) {
29552 global_authfailureevents = ast_true(v->value);
29553 } else if (!strcasecmp(v->name, "maxcallbitrate")) {
29554 default_maxcallbitrate = atoi(v->value);
29555 if (default_maxcallbitrate < 0)
29556 default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
29557 } else if (!strcasecmp(v->name, "matchexternaddrlocally") || !strcasecmp(v->name, "matchexterniplocally")) {
29558 sip_cfg.matchexternaddrlocally = ast_true(v->value);
29559 } else if (!strcasecmp(v->name, "session-timers")) {
29560 int i = (int) str2stmode(v->value);
29561 if (i < 0) {
29562 ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
29563 global_st_mode = SESSION_TIMER_MODE_ACCEPT;
29564 } else {
29565 global_st_mode = i;
29566 }
29567 } else if (!strcasecmp(v->name, "session-expires")) {
29568 if (sscanf(v->value, "%30d", &global_max_se) != 1) {
29569 ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
29570 global_max_se = DEFAULT_MAX_SE;
29571 }
29572 } else if (!strcasecmp(v->name, "session-minse")) {
29573 if (sscanf(v->value, "%30d", &global_min_se) != 1) {
29574 ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
29575 global_min_se = DEFAULT_MIN_SE;
29576 }
29577 if (global_min_se < DEFAULT_MIN_SE) {
29578 ast_log(LOG_WARNING, "session-minse '%s' at line %d of %s is not allowed to be < %d secs\n", v->value, v->lineno, config, DEFAULT_MIN_SE);
29579 global_min_se = DEFAULT_MIN_SE;
29580 }
29581 } else if (!strcasecmp(v->name, "session-refresher")) {
29582 int i = (int) str2strefresherparam(v->value);
29583 if (i < 0) {
29584 ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
29585 global_st_refresher = SESSION_TIMER_REFRESHER_PARAM_UAS;
29586 } else {
29587 global_st_refresher = i;
29588 }
29589 } else if (!strcasecmp(v->name, "storesipcause")) {
29590 global_store_sip_cause = ast_true(v->value);
29591 } else if (!strcasecmp(v->name, "qualifygap")) {
29592 if (sscanf(v->value, "%30d", &global_qualify_gap) != 1) {
29593 ast_log(LOG_WARNING, "Invalid qualifygap '%s' at line %d of %s\n", v->value, v->lineno, config);
29594 global_qualify_gap = DEFAULT_QUALIFY_GAP;
29595 }
29596 } else if (!strcasecmp(v->name, "qualifypeers")) {
29597 if (sscanf(v->value, "%30d", &global_qualify_peers) != 1) {
29598 ast_log(LOG_WARNING, "Invalid pokepeers '%s' at line %d of %s\n", v->value, v->lineno, config);
29599 global_qualify_peers = DEFAULT_QUALIFY_PEERS;
29600 }
29601 } else if (!strcasecmp(v->name, "disallowed_methods")) {
29602 char *disallow = ast_strdupa(v->value);
29603 mark_parsed_methods(&sip_cfg.disallowed_methods, disallow);
29604 } else if (!strcasecmp(v->name, "shrinkcallerid")) {
29605 if (ast_true(v->value)) {
29606 global_shrinkcallerid = 1;
29607 } else if (ast_false(v->value)) {
29608 global_shrinkcallerid = 0;
29609 } else {
29610 ast_log(LOG_WARNING, "shrinkcallerid value %s is not valid at line %d.\n", v->value, v->lineno);
29611 }
29612 } else if (!strcasecmp(v->name, "use_q850_reason")) {
29613 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_Q850_REASON);
29614 } else if (!strcasecmp(v->name, "maxforwards")) {
29615 if (sscanf(v->value, "%30d", &sip_cfg.default_max_forwards) != 1
29616 || sip_cfg.default_max_forwards < 1 || 255 < sip_cfg.default_max_forwards) {
29617 ast_log(LOG_WARNING, "'%s' is not a valid maxforwards value at line %d. Using default.\n", v->value, v->lineno);
29618 sip_cfg.default_max_forwards = DEFAULT_MAX_FORWARDS;
29619 }
29620 } else if (!strcasecmp(v->name, "subscribe_network_change_event")) {
29621 if (ast_true(v->value)) {
29622 subscribe_network_change = 1;
29623 } else if (ast_false(v->value)) {
29624 subscribe_network_change = 0;
29625 } else {
29626 ast_log(LOG_WARNING, "subscribe_network_change_event value %s is not valid at line %d.\n", v->value, v->lineno);
29627 }
29628 } else if (!strcasecmp(v->name, "snom_aoc_enabled")) {
29629 ast_set2_flag(&global_flags[2], ast_true(v->value), SIP_PAGE3_SNOM_AOC);
29630 } else if (!strcasecmp(v->name, "parkinglot")) {
29631 ast_copy_string(default_parkinglot, v->value, sizeof(default_parkinglot));
29632 }
29633 }
29634
29635
29636 ast_copy_flags(&global_flags[0], &setflags[0], mask[0].flags);
29637 ast_copy_flags(&global_flags[1], &setflags[1], mask[1].flags);
29638 ast_copy_flags(&global_flags[2], &setflags[2], mask[2].flags);
29639
29640 if (subscribe_network_change) {
29641 network_change_event_subscribe();
29642 } else {
29643 network_change_event_unsubscribe();
29644 }
29645
29646 if (global_t1 < global_t1min) {
29647 ast_log(LOG_WARNING, "'t1min' (%d) cannot be greater than 't1timer' (%d). Resetting 't1timer' to the value of 't1min'\n", global_t1min, global_t1);
29648 global_t1 = global_t1min;
29649 }
29650
29651 if (global_timer_b < global_t1 * 64) {
29652 if (timerb_set && timert1_set) {
29653 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);
29654 } else if (timerb_set) {
29655 if ((global_t1 = global_timer_b / 64) < global_t1min) {
29656 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);
29657 global_t1 = global_t1min;
29658 global_timer_b = global_t1 * 64;
29659 }
29660 } else {
29661 global_timer_b = global_t1 * 64;
29662 }
29663 }
29664 if (!sip_cfg.allow_external_domains && AST_LIST_EMPTY(&domain_list)) {
29665 ast_log(LOG_WARNING, "To disallow external domains, you need to configure local SIP domains.\n");
29666 sip_cfg.allow_external_domains = 1;
29667 }
29668
29669 if (!sip_cfg.tcp_enabled && (default_transports & SIP_TRANSPORT_TCP)) {
29670 ast_log(LOG_WARNING, "Cannot use 'tcp' transport with tcpenable=no. Removing from available transports.\n");
29671 default_primary_transport &= ~SIP_TRANSPORT_TCP;
29672 default_transports &= ~SIP_TRANSPORT_TCP;
29673 }
29674 if (!default_tls_cfg.enabled && (default_transports & SIP_TRANSPORT_TLS)) {
29675 ast_log(LOG_WARNING, "Cannot use 'tls' transport with tlsenable=no. Removing from available transports.\n");
29676 default_primary_transport &= ~SIP_TRANSPORT_TLS;
29677 default_transports &= ~SIP_TRANSPORT_TLS;
29678 }
29679 if (!default_transports) {
29680 ast_log(LOG_WARNING, "No valid transports available, falling back to 'udp'.\n");
29681 default_transports = default_primary_transport = SIP_TRANSPORT_UDP;
29682 } else if (!default_primary_transport) {
29683 ast_log(LOG_WARNING, "No valid default transport. Selecting 'udp' as default.\n");
29684 default_primary_transport = SIP_TRANSPORT_UDP;
29685 }
29686
29687
29688 for (v = ast_variable_browse(cfg, "authentication"); v ; v = v->next) {
29689
29690 if (!strcasecmp(v->name, "auth")) {
29691 add_realm_authentication(&authl, v->value, v->lineno);
29692 }
29693 }
29694
29695 if (bindport) {
29696 if (ast_sockaddr_port(&bindaddr)) {
29697 ast_log(LOG_WARNING, "bindport is also specified in bindaddr. "
29698 "Using %d.\n", bindport);
29699 }
29700 ast_sockaddr_set_port(&bindaddr, bindport);
29701 }
29702
29703 if (!ast_sockaddr_port(&bindaddr)) {
29704 ast_sockaddr_set_port(&bindaddr, STANDARD_SIP_PORT);
29705 }
29706
29707
29708 ast_sockaddr_copy(&internip, &bindaddr);
29709 if (ast_find_ourip(&internip, &bindaddr, 0)) {
29710 ast_log(LOG_WARNING, "Unable to get own IP address, SIP disabled\n");
29711 ast_config_destroy(cfg);
29712 return 0;
29713 }
29714
29715 ast_mutex_lock(&netlock);
29716 if ((sipsock > -1) && (ast_sockaddr_cmp(&old_bindaddr, &bindaddr))) {
29717 close(sipsock);
29718 sipsock = -1;
29719 }
29720 if (sipsock < 0) {
29721 sipsock = socket(ast_sockaddr_is_ipv6(&bindaddr) ?
29722 AF_INET6 : AF_INET, SOCK_DGRAM, 0);
29723 if (sipsock < 0) {
29724 ast_log(LOG_WARNING, "Unable to create SIP socket: %s\n", strerror(errno));
29725 ast_config_destroy(cfg);
29726 ast_mutex_unlock(&netlock);
29727 return -1;
29728 } else {
29729
29730 const int reuseFlag = 1;
29731
29732 setsockopt(sipsock, SOL_SOCKET, SO_REUSEADDR,
29733 (const char*)&reuseFlag,
29734 sizeof reuseFlag);
29735
29736 ast_enable_packet_fragmentation(sipsock);
29737
29738 if (ast_bind(sipsock, &bindaddr) < 0) {
29739 ast_log(LOG_WARNING, "Failed to bind to %s: %s\n",
29740 ast_sockaddr_stringify(&bindaddr), strerror(errno));
29741 close(sipsock);
29742 sipsock = -1;
29743 } else {
29744 ast_verb(2, "SIP Listening on %s\n", ast_sockaddr_stringify(&bindaddr));
29745 ast_set_qos(sipsock, global_tos_sip, global_cos_sip, "SIP");
29746 }
29747 }
29748 } else {
29749 ast_set_qos(sipsock, global_tos_sip, global_cos_sip, "SIP");
29750 }
29751 ast_mutex_unlock(&netlock);
29752
29753
29754 if (sip_cfg.tcp_enabled) {
29755 if (ast_sockaddr_isnull(&sip_tcp_desc.local_address)) {
29756 ast_sockaddr_copy(&sip_tcp_desc.local_address, &bindaddr);
29757 }
29758 if (!ast_sockaddr_port(&sip_tcp_desc.local_address)) {
29759 ast_sockaddr_set_port(&sip_tcp_desc.local_address, STANDARD_SIP_PORT);
29760 }
29761 } else {
29762 ast_sockaddr_setnull(&sip_tcp_desc.local_address);
29763 }
29764 ast_tcptls_server_start(&sip_tcp_desc);
29765 if (sip_cfg.tcp_enabled && sip_tcp_desc.accept_fd == -1) {
29766
29767 ast_log(LOG_ERROR, "SIP TCP Server start failed. Not listening on TCP socket.\n");
29768 } else {
29769 ast_debug(2, "SIP TCP server started\n");
29770 }
29771
29772
29773 memcpy(sip_tls_desc.tls_cfg, &default_tls_cfg, sizeof(default_tls_cfg));
29774
29775 if (ast_ssl_setup(sip_tls_desc.tls_cfg)) {
29776 if (ast_sockaddr_isnull(&sip_tls_desc.local_address)) {
29777 ast_sockaddr_copy(&sip_tls_desc.local_address, &bindaddr);
29778 ast_sockaddr_set_port(&sip_tls_desc.local_address,
29779 STANDARD_TLS_PORT);
29780 }
29781 if (!ast_sockaddr_port(&sip_tls_desc.local_address)) {
29782 ast_sockaddr_set_port(&sip_tls_desc.local_address,
29783 STANDARD_TLS_PORT);
29784 }
29785 ast_tcptls_server_start(&sip_tls_desc);
29786 if (default_tls_cfg.enabled && sip_tls_desc.accept_fd == -1) {
29787 ast_log(LOG_ERROR, "TLS Server start failed. Not listening on TLS socket.\n");
29788 sip_tls_desc.tls_cfg = NULL;
29789 }
29790 } else if (sip_tls_desc.tls_cfg->enabled) {
29791 sip_tls_desc.tls_cfg = NULL;
29792 ast_log(LOG_WARNING, "SIP TLS server did not load because of errors.\n");
29793 }
29794
29795 if (ucfg) {
29796 struct ast_variable *gen;
29797 int genhassip, genregistersip;
29798 const char *hassip, *registersip;
29799
29800 genhassip = ast_true(ast_variable_retrieve(ucfg, "general", "hassip"));
29801 genregistersip = ast_true(ast_variable_retrieve(ucfg, "general", "registersip"));
29802 gen = ast_variable_browse(ucfg, "general");
29803 cat = ast_category_browse(ucfg, NULL);
29804 while (cat) {
29805 if (strcasecmp(cat, "general")) {
29806 hassip = ast_variable_retrieve(ucfg, cat, "hassip");
29807 registersip = ast_variable_retrieve(ucfg, cat, "registersip");
29808 if (ast_true(hassip) || (!hassip && genhassip)) {
29809 peer = build_peer(cat, gen, ast_variable_browse(ucfg, cat), 0, 0);
29810 if (peer) {
29811
29812 peer->type = SIP_TYPE_USER | SIP_TYPE_PEER;
29813 ao2_t_link(peers, peer, "link peer into peer table");
29814 if ((peer->type & SIP_TYPE_PEER) && !ast_sockaddr_isnull(&peer->addr)) {
29815 ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
29816 }
29817
29818 unref_peer(peer, "unref_peer: from reload_config");
29819 peer_count++;
29820 }
29821 }
29822 if (ast_true(registersip) || (!registersip && genregistersip)) {
29823 char tmp[256];
29824 const char *host = ast_variable_retrieve(ucfg, cat, "host");
29825 const char *username = ast_variable_retrieve(ucfg, cat, "username");
29826 const char *secret = ast_variable_retrieve(ucfg, cat, "secret");
29827 const char *contact = ast_variable_retrieve(ucfg, cat, "contact");
29828 const char *authuser = ast_variable_retrieve(ucfg, cat, "authuser");
29829 if (!host) {
29830 host = ast_variable_retrieve(ucfg, "general", "host");
29831 }
29832 if (!username) {
29833 username = ast_variable_retrieve(ucfg, "general", "username");
29834 }
29835 if (!secret) {
29836 secret = ast_variable_retrieve(ucfg, "general", "secret");
29837 }
29838 if (!contact) {
29839 contact = "s";
29840 }
29841 if (!ast_strlen_zero(username) && !ast_strlen_zero(host)) {
29842 if (!ast_strlen_zero(secret)) {
29843 if (!ast_strlen_zero(authuser)) {
29844 snprintf(tmp, sizeof(tmp), "%s?%s:%s:%s@%s/%s", cat, username, secret, authuser, host, contact);
29845 } else {
29846 snprintf(tmp, sizeof(tmp), "%s?%s:%s@%s/%s", cat, username, secret, host, contact);
29847 }
29848 } else if (!ast_strlen_zero(authuser)) {
29849 snprintf(tmp, sizeof(tmp), "%s?%s::%s@%s/%s", cat, username, authuser, host, contact);
29850 } else {
29851 snprintf(tmp, sizeof(tmp), "%s?%s@%s/%s", cat, username, host, contact);
29852 }
29853 if (sip_register(tmp, 0) == 0) {
29854 registry_count++;
29855 }
29856 }
29857 }
29858 }
29859 cat = ast_category_browse(ucfg, cat);
29860 }
29861 ast_config_destroy(ucfg);
29862 }
29863
29864
29865 cat = NULL;
29866 while ( (cat = ast_category_browse(cfg, cat)) ) {
29867 const char *utype;
29868 if (!strcasecmp(cat, "general") || !strcasecmp(cat, "authentication"))
29869 continue;
29870 utype = ast_variable_retrieve(cfg, cat, "type");
29871 if (!utype) {
29872 ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
29873 continue;
29874 } else {
29875 if (!strcasecmp(utype, "user")) {
29876 ;
29877 } else if (!strcasecmp(utype, "friend")) {
29878 ;
29879 } else if (!strcasecmp(utype, "peer")) {
29880 ;
29881 } else {
29882 ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, "sip.conf");
29883 continue;
29884 }
29885 peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0, 0);
29886 if (peer) {
29887 display_nat_warning(cat, reason, &peer->flags[0]);
29888 ao2_t_link(peers, peer, "link peer into peers table");
29889 if ((peer->type & SIP_TYPE_PEER) && !ast_sockaddr_isnull(&peer->addr)) {
29890 ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
29891 }
29892 unref_peer(peer, "unref the result of the build_peer call. Now, the links from the tables are the only ones left.");
29893 peer_count++;
29894 }
29895 }
29896 }
29897
29898
29899
29900
29901
29902
29903 if (auto_sip_domains) {
29904 char temp[MAXHOSTNAMELEN];
29905
29906
29907 if (!ast_sockaddr_isnull(&bindaddr) && !ast_sockaddr_is_any(&bindaddr)) {
29908 add_sip_domain(ast_sockaddr_stringify_addr(&bindaddr),
29909 SIP_DOMAIN_AUTO, NULL);
29910 } else if (!ast_sockaddr_isnull(&internip) && !ast_sockaddr_is_any(&internip)) {
29911
29912 add_sip_domain(ast_sockaddr_stringify_addr(&internip),
29913 SIP_DOMAIN_AUTO, NULL);
29914 } else {
29915 ast_log(LOG_NOTICE, "Can't add wildcard IP address to domain list, please add IP address to domain manually.\n");
29916 }
29917
29918
29919 if (!ast_sockaddr_isnull(&sip_tcp_desc.local_address) &&
29920 !ast_sockaddr_cmp(&bindaddr, &sip_tcp_desc.local_address)) {
29921 add_sip_domain(ast_sockaddr_stringify_addr(&sip_tcp_desc.local_address),
29922 SIP_DOMAIN_AUTO, NULL);
29923 }
29924
29925
29926 if (!ast_sockaddr_isnull(&sip_tls_desc.local_address) &&
29927 !ast_sockaddr_cmp(&bindaddr, &sip_tls_desc.local_address) &&
29928 !ast_sockaddr_cmp(&sip_tcp_desc.local_address,
29929 &sip_tls_desc.local_address)) {
29930 add_sip_domain(ast_sockaddr_stringify_addr(&sip_tcp_desc.local_address),
29931 SIP_DOMAIN_AUTO, NULL);
29932 }
29933
29934
29935 if (!ast_sockaddr_isnull(&externaddr)) {
29936 add_sip_domain(ast_sockaddr_stringify_addr(&externaddr),
29937 SIP_DOMAIN_AUTO, NULL);
29938 }
29939
29940
29941 if (!ast_strlen_zero(externhost)) {
29942 add_sip_domain(externhost, SIP_DOMAIN_AUTO, NULL);
29943 }
29944
29945
29946 if (!gethostname(temp, sizeof(temp))) {
29947 add_sip_domain(temp, SIP_DOMAIN_AUTO, NULL);
29948 }
29949 }
29950
29951
29952 ast_config_destroy(cfg);
29953
29954
29955 if (notify_types)
29956 ast_config_destroy(notify_types);
29957 if ((notify_types = ast_config_load(notify_config, config_flags)) == CONFIG_STATUS_FILEINVALID) {
29958 ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed.\n", notify_config);
29959 notify_types = NULL;
29960 }
29961
29962
29963 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);
29964 run_end = time(0);
29965 ast_debug(4, "SIP reload_config done...Runtime= %d sec\n", (int)(run_end-run_start));
29966
29967 return 0;
29968 }
29969
29970 static int apply_directmedia_ha(struct sip_pvt *p1, struct sip_pvt *p2, const char *op)
29971 {
29972 struct ast_sockaddr us = { { 0, }, }, them = { { 0, }, };
29973 int res = AST_SENSE_ALLOW;
29974
29975 ast_rtp_instance_get_remote_address(p1->rtp, &them);
29976 ast_rtp_instance_get_local_address(p1->rtp, &us);
29977
29978
29979
29980 if (!p2->relatedpeer) {
29981 return res;
29982 }
29983
29984 if ((res = ast_apply_ha(p2->relatedpeer->directmediaha, &them)) == AST_SENSE_DENY) {
29985 const char *us_addr = ast_strdupa(ast_sockaddr_stringify(&us));
29986 const char *them_addr = ast_strdupa(ast_sockaddr_stringify(&them));
29987
29988 ast_debug(3, "Reinvite %s to %s denied by directmedia ACL on %s\n",
29989 op, them_addr, us_addr);
29990 }
29991
29992 return res;
29993 }
29994
29995 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan)
29996 {
29997 struct sip_pvt *p;
29998 struct ast_channel *opp_chan;
29999 struct sip_pvt *opp;
30000 struct ast_udptl *udptl = NULL;
30001
30002 p = chan->tech_pvt;
30003 if (!p) {
30004 return NULL;
30005 }
30006
30007 if (!(opp_chan = ast_bridged_channel(chan))) {
30008 return NULL;
30009 } else if (((opp_chan->tech != &sip_tech) && (opp_chan->tech != &sip_tech_info)) ||
30010 (!(opp = opp_chan->tech_pvt))) {
30011 return NULL;
30012 }
30013
30014 sip_pvt_lock(p);
30015 while (sip_pvt_trylock(opp)) {
30016 sip_pvt_unlock(p);
30017 usleep(1);
30018 sip_pvt_lock(p);
30019 }
30020
30021 if (p->udptl && ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
30022 if (apply_directmedia_ha(p, opp, "UDPTL T.38 data")) {
30023 udptl = p->udptl;
30024 }
30025 }
30026
30027 sip_pvt_unlock(opp);
30028 sip_pvt_unlock(p);
30029 return udptl;
30030 }
30031
30032 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl)
30033 {
30034 struct sip_pvt *p;
30035
30036
30037 ast_channel_lock(chan);
30038 p = chan->tech_pvt;
30039 if (!p) {
30040 ast_channel_unlock(chan);
30041 return -1;
30042 }
30043 sip_pvt_lock(p);
30044 if (p->owner != chan) {
30045
30046 ast_debug(1, "The private is not owned by channel %s anymore.\n", chan->name);
30047 sip_pvt_unlock(p);
30048 ast_channel_unlock(chan);
30049 return 0;
30050 }
30051
30052 if (udptl) {
30053 ast_udptl_get_peer(udptl, &p->udptlredirip);
30054 } else {
30055 memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
30056 }
30057 if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
30058 if (!p->pendinginvite) {
30059 ast_debug(3, "Sending reinvite on SIP '%s' - It's UDPTL soon redirected to IP %s\n",
30060 p->callid, ast_sockaddr_stringify(udptl ? &p->udptlredirip : &p->ourip));
30061 transmit_reinvite_with_sdp(p, TRUE, FALSE);
30062 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
30063 ast_debug(3, "Deferring reinvite on SIP '%s' - It's UDPTL will be redirected to IP %s\n",
30064 p->callid, ast_sockaddr_stringify(udptl ? &p->udptlredirip : &p->ourip));
30065 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
30066 }
30067 }
30068
30069 p->lastrtprx = p->lastrtptx = time(NULL);
30070 sip_pvt_unlock(p);
30071 ast_channel_unlock(chan);
30072 return 0;
30073 }
30074
30075 static enum ast_rtp_glue_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
30076 {
30077 struct sip_pvt *p = NULL;
30078 struct ast_channel *opp_chan;
30079 struct sip_pvt *opp = NULL;
30080 enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_LOCAL;
30081
30082 if (!(p = chan->tech_pvt)) {
30083 return AST_RTP_GLUE_RESULT_FORBID;
30084 }
30085
30086 if ((opp_chan = ast_bridged_channel(chan)) && (((opp_chan->tech != &sip_tech) && (opp_chan->tech != &sip_tech_info)) ||
30087 (!(opp = opp_chan->tech_pvt)))) {
30088 return AST_RTP_GLUE_RESULT_FORBID;
30089 }
30090
30091 sip_pvt_lock(p);
30092 while (opp && sip_pvt_trylock(opp)) {
30093 sip_pvt_unlock(p);
30094 usleep(1);
30095 sip_pvt_lock(p);
30096 }
30097
30098 if (!(p->rtp)) {
30099 if (opp) {
30100 sip_pvt_unlock(opp);
30101 }
30102 sip_pvt_unlock(p);
30103 return AST_RTP_GLUE_RESULT_FORBID;
30104 }
30105
30106 ao2_ref(p->rtp, +1);
30107 *instance = p->rtp;
30108
30109 if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
30110 res = AST_RTP_GLUE_RESULT_REMOTE;
30111 if (opp && !apply_directmedia_ha(p, opp, "audio")) {
30112 res = AST_RTP_GLUE_RESULT_FORBID;
30113 }
30114 } else if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA_NAT)) {
30115 res = AST_RTP_GLUE_RESULT_REMOTE;
30116 } else if (ast_test_flag(&global_jbconf, AST_JB_FORCED)) {
30117 res = AST_RTP_GLUE_RESULT_FORBID;
30118 }
30119
30120 if (opp) {
30121 sip_pvt_unlock(opp);
30122 }
30123
30124 if (p->srtp) {
30125 res = AST_RTP_GLUE_RESULT_FORBID;
30126 }
30127
30128 sip_pvt_unlock(p);
30129
30130 return res;
30131 }
30132
30133 static enum ast_rtp_glue_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
30134 {
30135 struct sip_pvt *p = NULL;
30136 struct ast_channel *opp_chan;
30137 struct sip_pvt *opp = NULL;
30138 enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_FORBID;
30139
30140 if (!(p = chan->tech_pvt)) {
30141 return AST_RTP_GLUE_RESULT_FORBID;
30142 }
30143
30144 if ((opp_chan = ast_bridged_channel(chan)) && (((opp_chan->tech != &sip_tech) && (opp_chan->tech != &sip_tech_info)) ||
30145 (!(opp = opp_chan->tech_pvt)))) {
30146 return AST_RTP_GLUE_RESULT_FORBID;
30147 }
30148
30149 sip_pvt_lock(p);
30150 while (opp && sip_pvt_trylock(opp)) {
30151 sip_pvt_unlock(p);
30152 usleep(1);
30153 sip_pvt_lock(p);
30154 }
30155
30156 if (!(p->vrtp)) {
30157 if (opp) {
30158 sip_pvt_unlock(opp);
30159 }
30160 sip_pvt_unlock(p);
30161 return AST_RTP_GLUE_RESULT_FORBID;
30162 }
30163
30164 ao2_ref(p->vrtp, +1);
30165 *instance = p->vrtp;
30166
30167 if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
30168 res = AST_RTP_GLUE_RESULT_REMOTE;
30169 if (opp && !apply_directmedia_ha(p, opp, "video")) {
30170 res = AST_RTP_GLUE_RESULT_FORBID;
30171 }
30172 }
30173
30174 if (opp) {
30175 sip_pvt_unlock(opp);
30176 }
30177 sip_pvt_unlock(p);
30178
30179 return res;
30180 }
30181
30182 static enum ast_rtp_glue_result sip_get_trtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
30183 {
30184 struct sip_pvt *p = NULL;
30185 struct ast_channel *opp_chan;
30186 struct sip_pvt *opp = NULL;
30187 enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_FORBID;
30188
30189 if (!(p = chan->tech_pvt)) {
30190 return AST_RTP_GLUE_RESULT_FORBID;
30191 }
30192
30193 if ((opp_chan = ast_bridged_channel(chan)) && (((opp_chan->tech != &sip_tech) && (opp_chan->tech != &sip_tech_info)) ||
30194 (!(opp = opp_chan->tech_pvt)))) {
30195 return AST_RTP_GLUE_RESULT_FORBID;
30196 }
30197
30198 sip_pvt_lock(p);
30199 while (opp && sip_pvt_trylock(opp)) {
30200 sip_pvt_unlock(p);
30201 usleep(1);
30202 sip_pvt_lock(p);
30203 }
30204
30205 if (!(p->trtp)) {
30206 if (opp) {
30207 sip_pvt_unlock(opp);
30208 }
30209 sip_pvt_unlock(p);
30210 return AST_RTP_GLUE_RESULT_FORBID;
30211 }
30212
30213 ao2_ref(p->trtp, +1);
30214 *instance = p->trtp;
30215
30216 if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
30217 res = AST_RTP_GLUE_RESULT_REMOTE;
30218 if (opp && !apply_directmedia_ha(p, opp, "text")) {
30219 res = AST_RTP_GLUE_RESULT_FORBID;
30220 }
30221 }
30222
30223 if (opp) {
30224 sip_pvt_unlock(opp);
30225 }
30226 sip_pvt_unlock(p);
30227
30228 return res;
30229 }
30230
30231 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)
30232 {
30233 struct sip_pvt *p;
30234 int changed = 0;
30235
30236
30237 ast_channel_lock(chan);
30238 p = chan->tech_pvt;
30239 if (!p) {
30240 ast_channel_unlock(chan);
30241 return -1;
30242 }
30243 sip_pvt_lock(p);
30244 if (p->owner != chan) {
30245
30246 ast_debug(1, "The private is not owned by channel %s anymore.\n", chan->name);
30247 sip_pvt_unlock(p);
30248 ast_channel_unlock(chan);
30249 return 0;
30250 }
30251
30252
30253 if ((instance || vinstance || tinstance) &&
30254 !ast_bridged_channel(chan) &&
30255 !sip_cfg.directrtpsetup) {
30256 sip_pvt_unlock(p);
30257 ast_channel_unlock(chan);
30258 return 0;
30259 }
30260
30261 if (p->alreadygone) {
30262
30263 sip_pvt_unlock(p);
30264 ast_channel_unlock(chan);
30265 return 0;
30266 }
30267
30268
30269
30270
30271 if (nat_active && !ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA_NAT)) {
30272 sip_pvt_unlock(p);
30273 ast_channel_unlock(chan);
30274 return 0;
30275 }
30276
30277 if (instance) {
30278 changed |= ast_rtp_instance_get_and_cmp_remote_address(instance, &p->redirip);
30279
30280 if (p->rtp) {
30281
30282 ast_channel_set_fd(chan, 1, -1);
30283
30284 ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_RTCP, 0);
30285 }
30286 } else if (!ast_sockaddr_isnull(&p->redirip)) {
30287 memset(&p->redirip, 0, sizeof(p->redirip));
30288 changed = 1;
30289
30290 if (p->rtp) {
30291
30292
30293 ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_RTCP, 1);
30294
30295 ast_channel_set_fd(chan, 1, ast_rtp_instance_fd(p->rtp, 1));
30296 }
30297 }
30298
30299 if (vinstance) {
30300 changed |= ast_rtp_instance_get_and_cmp_remote_address(vinstance, &p->vredirip);
30301
30302 if (p->vrtp) {
30303
30304 ast_channel_set_fd(chan, 3, -1);
30305
30306 ast_rtp_instance_set_prop(p->vrtp, AST_RTP_PROPERTY_RTCP, 0);
30307 }
30308 } else if (!ast_sockaddr_isnull(&p->vredirip)) {
30309 memset(&p->vredirip, 0, sizeof(p->vredirip));
30310 changed = 1;
30311
30312 if (p->vrtp) {
30313
30314
30315 ast_rtp_instance_set_prop(p->vrtp, AST_RTP_PROPERTY_RTCP, 1);
30316
30317 ast_channel_set_fd(chan, 3, ast_rtp_instance_fd(p->vrtp, 1));
30318 }
30319 }
30320
30321 if (tinstance) {
30322 changed |= ast_rtp_instance_get_and_cmp_remote_address(tinstance, &p->tredirip);
30323 } else if (!ast_sockaddr_isnull(&p->tredirip)) {
30324 memset(&p->tredirip, 0, sizeof(p->tredirip));
30325 changed = 1;
30326 }
30327 if (codecs && (p->redircodecs != codecs)) {
30328 p->redircodecs = codecs;
30329 changed = 1;
30330 }
30331
30332 if (ast_test_flag(&p->flags[2], SIP_PAGE3_DIRECT_MEDIA_OUTGOING) && !p->outgoing_call) {
30333
30334
30335
30336
30337 ast_clear_flag(&p->flags[2], SIP_PAGE3_DIRECT_MEDIA_OUTGOING);
30338 sip_pvt_unlock(p);
30339 ast_channel_unlock(chan);
30340 return 0;
30341 }
30342
30343 if (changed && !ast_test_flag(&p->flags[0], SIP_GOTREFER) && !ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
30344 if (chan->_state != AST_STATE_UP) {
30345 if (p->do_history)
30346 append_history(p, "ExtInv", "Initial invite sent with remote bridge proposal.");
30347 ast_debug(1, "Early remote bridge setting SIP '%s' - Sending media to %s\n", p->callid, ast_sockaddr_stringify(instance ? &p->redirip : &p->ourip));
30348 } else if (!p->pendinginvite) {
30349 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));
30350 transmit_reinvite_with_sdp(p, FALSE, FALSE);
30351 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
30352 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));
30353
30354 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
30355 }
30356 }
30357
30358 p->lastrtprx = p->lastrtptx = time(NULL);
30359 sip_pvt_unlock(p);
30360 ast_channel_unlock(chan);
30361 return 0;
30362 }
30363
30364 static format_t sip_get_codec(struct ast_channel *chan)
30365 {
30366 struct sip_pvt *p = chan->tech_pvt;
30367 return p->peercapability ? p->peercapability : p->capability;
30368 }
30369
30370 static struct ast_rtp_glue sip_rtp_glue = {
30371 .type = "SIP",
30372 .get_rtp_info = sip_get_rtp_peer,
30373 .get_vrtp_info = sip_get_vrtp_peer,
30374 .get_trtp_info = sip_get_trtp_peer,
30375 .update_peer = sip_set_rtp_peer,
30376 .get_codec = sip_get_codec,
30377 };
30378
30379 static char *app_dtmfmode = "SIPDtmfMode";
30380 static char *app_sipaddheader = "SIPAddHeader";
30381 static char *app_sipremoveheader = "SIPRemoveHeader";
30382
30383
30384 static int sip_dtmfmode(struct ast_channel *chan, const char *data)
30385 {
30386 struct sip_pvt *p;
30387 const char *mode = data;
30388
30389 if (!data) {
30390 ast_log(LOG_WARNING, "This application requires the argument: info, inband, rfc2833\n");
30391 return 0;
30392 }
30393 ast_channel_lock(chan);
30394 if (!IS_SIP_TECH(chan->tech)) {
30395 ast_log(LOG_WARNING, "Call this application only on SIP incoming calls\n");
30396 ast_channel_unlock(chan);
30397 return 0;
30398 }
30399 p = chan->tech_pvt;
30400 if (!p) {
30401 ast_channel_unlock(chan);
30402 return 0;
30403 }
30404 sip_pvt_lock(p);
30405 if (!strcasecmp(mode, "info")) {
30406 ast_clear_flag(&p->flags[0], SIP_DTMF);
30407 ast_set_flag(&p->flags[0], SIP_DTMF_INFO);
30408 p->jointnoncodeccapability &= ~AST_RTP_DTMF;
30409 } else if (!strcasecmp(mode, "shortinfo")) {
30410 ast_clear_flag(&p->flags[0], SIP_DTMF);
30411 ast_set_flag(&p->flags[0], SIP_DTMF_SHORTINFO);
30412 p->jointnoncodeccapability &= ~AST_RTP_DTMF;
30413 } else if (!strcasecmp(mode, "rfc2833")) {
30414 ast_clear_flag(&p->flags[0], SIP_DTMF);
30415 ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
30416 p->jointnoncodeccapability |= AST_RTP_DTMF;
30417 } else if (!strcasecmp(mode, "inband")) {
30418 ast_clear_flag(&p->flags[0], SIP_DTMF);
30419 ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
30420 p->jointnoncodeccapability &= ~AST_RTP_DTMF;
30421 } else {
30422 ast_log(LOG_WARNING, "I don't know about this dtmf mode: %s\n", mode);
30423 }
30424 if (p->rtp)
30425 ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
30426 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
30427 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
30428 enable_dsp_detect(p);
30429 } else {
30430 disable_dsp_detect(p);
30431 }
30432 sip_pvt_unlock(p);
30433 ast_channel_unlock(chan);
30434 return 0;
30435 }
30436
30437
30438 static int sip_addheader(struct ast_channel *chan, const char *data)
30439 {
30440 int no = 0;
30441 int ok = FALSE;
30442 char varbuf[30];
30443 const char *inbuf = data;
30444 char *subbuf;
30445
30446 if (ast_strlen_zero(inbuf)) {
30447 ast_log(LOG_WARNING, "This application requires the argument: Header\n");
30448 return 0;
30449 }
30450 ast_channel_lock(chan);
30451
30452
30453 while (!ok && no <= 50) {
30454 no++;
30455 snprintf(varbuf, sizeof(varbuf), "__SIPADDHEADER%.2d", no);
30456
30457
30458 if ((pbx_builtin_getvar_helper(chan, (const char *) varbuf + 2) == (const char *) NULL)) {
30459 ok = TRUE;
30460 }
30461 }
30462 if (ok) {
30463 size_t len = strlen(inbuf);
30464 subbuf = ast_alloca(len + 1);
30465 ast_get_encoded_str(inbuf, subbuf, len + 1);
30466 pbx_builtin_setvar_helper(chan, varbuf, subbuf);
30467 if (sipdebug) {
30468 ast_debug(1, "SIP Header added \"%s\" as %s\n", inbuf, varbuf);
30469 }
30470 } else {
30471 ast_log(LOG_WARNING, "Too many SIP headers added, max 50\n");
30472 }
30473 ast_channel_unlock(chan);
30474 return 0;
30475 }
30476
30477
30478 static int sip_removeheader(struct ast_channel *chan, const char *data)
30479 {
30480 struct ast_var_t *newvariable;
30481 struct varshead *headp;
30482 int removeall = 0;
30483 char *inbuf = (char *) data;
30484
30485 if (ast_strlen_zero(inbuf)) {
30486 removeall = 1;
30487 }
30488 ast_channel_lock(chan);
30489
30490 headp=&chan->varshead;
30491 AST_LIST_TRAVERSE_SAFE_BEGIN (headp, newvariable, entries) {
30492 if (strncasecmp(ast_var_name(newvariable), "SIPADDHEADER", strlen("SIPADDHEADER")) == 0) {
30493 if (removeall || (!strncasecmp(ast_var_value(newvariable),inbuf,strlen(inbuf)))) {
30494 if (sipdebug)
30495 ast_debug(1,"removing SIP Header \"%s\" as %s\n",
30496 ast_var_value(newvariable),
30497 ast_var_name(newvariable));
30498 AST_LIST_REMOVE_CURRENT(entries);
30499 ast_var_delete(newvariable);
30500 }
30501 }
30502 }
30503 AST_LIST_TRAVERSE_SAFE_END;
30504
30505 ast_channel_unlock(chan);
30506 return 0;
30507 }
30508
30509
30510
30511
30512
30513
30514
30515 static int sip_sipredirect(struct sip_pvt *p, const char *dest)
30516 {
30517 char *cdest;
30518 char *extension, *domain;
30519
30520 cdest = ast_strdupa(dest);
30521
30522 extension = strsep(&cdest, "@");
30523 domain = cdest;
30524 if (ast_strlen_zero(extension)) {
30525 ast_log(LOG_ERROR, "Missing mandatory argument: extension\n");
30526 return 0;
30527 }
30528
30529
30530 if (!domain) {
30531 char *local_to_header;
30532 char to_header[256];
30533
30534 ast_copy_string(to_header, get_header(&p->initreq, "To"), sizeof(to_header));
30535 if (ast_strlen_zero(to_header)) {
30536 ast_log(LOG_ERROR, "Cannot retrieve the 'To' header from the original SIP request!\n");
30537 return 0;
30538 }
30539 if (((local_to_header = strcasestr(to_header, "sip:")) || (local_to_header = strcasestr(to_header, "sips:")))
30540 && (local_to_header = strchr(local_to_header, '@'))) {
30541 char ldomain[256];
30542
30543 memset(ldomain, 0, sizeof(ldomain));
30544 local_to_header++;
30545
30546 sscanf(local_to_header, "%256[^<>; ]", ldomain);
30547 if (ast_strlen_zero(ldomain)) {
30548 ast_log(LOG_ERROR, "Can't find the host address\n");
30549 return 0;
30550 }
30551 domain = ast_strdupa(ldomain);
30552 }
30553 }
30554
30555 ast_string_field_build(p, our_contact, "Transfer <sip:%s@%s>", extension, domain);
30556 transmit_response_reliable(p, "302 Moved Temporarily", &p->initreq);
30557
30558 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
30559 sip_alreadygone(p);
30560
30561 if (p->owner) {
30562 enum ast_control_transfer message = AST_TRANSFER_SUCCESS;
30563 ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
30564 }
30565
30566 return 0;
30567 }
30568
30569 static int sip_is_xml_parsable(void)
30570 {
30571 #ifdef HAVE_LIBXML2
30572 return TRUE;
30573 #else
30574 return FALSE;
30575 #endif
30576 }
30577
30578
30579 static void sip_poke_all_peers(void)
30580 {
30581 int ms = 0, num = 0;
30582 struct ao2_iterator i;
30583 struct sip_peer *peer;
30584
30585 if (!speerobjs) {
30586 return;
30587 }
30588
30589 i = ao2_iterator_init(peers, 0);
30590 while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
30591 ao2_lock(peer);
30592
30593 if (peer->maxms) {
30594 if (num == global_qualify_peers) {
30595 ms += global_qualify_gap;
30596 num = 0;
30597 } else {
30598 num++;
30599 }
30600 AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, ms, sip_poke_peer_s, peer,
30601 unref_peer(_data, "removing poke peer ref"),
30602 unref_peer(peer, "removing poke peer ref"),
30603 ref_peer(peer, "adding poke peer ref"));
30604 }
30605 ao2_unlock(peer);
30606 unref_peer(peer, "toss iterator peer ptr");
30607 }
30608 ao2_iterator_destroy(&i);
30609 }
30610
30611
30612 static void sip_send_all_registers(void)
30613 {
30614 int ms;
30615 int regspacing;
30616 if (!regobjs)
30617 return;
30618 regspacing = default_expiry * 1000/regobjs;
30619 if (regspacing > 100) {
30620 regspacing = 100;
30621 }
30622 ms = regspacing;
30623 ASTOBJ_CONTAINER_TRAVERSE(®l, 1, do {
30624 ASTOBJ_WRLOCK(iterator);
30625 ms += regspacing;
30626 AST_SCHED_REPLACE_UNREF(iterator->expire, sched, ms, sip_reregister, iterator,
30627 registry_unref(_data, "REPLACE sched del decs the refcount"),
30628 registry_unref(iterator, "REPLACE sched add failure decs the refcount"),
30629 registry_addref(iterator, "REPLACE sched add incs the refcount"));
30630 ASTOBJ_UNLOCK(iterator);
30631 } while (0)
30632 );
30633 }
30634
30635
30636 static void sip_send_all_mwi_subscriptions(void)
30637 {
30638 ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
30639 struct sip_subscription_mwi *saved;
30640 ASTOBJ_WRLOCK(iterator);
30641 AST_SCHED_DEL(sched, iterator->resub);
30642 saved = ASTOBJ_REF(iterator);
30643 if ((iterator->resub = ast_sched_add(sched, 1, sip_subscribe_mwi_do, saved)) < 0) {
30644 ASTOBJ_UNREF(saved, sip_subscribe_mwi_destroy);
30645 }
30646 ASTOBJ_UNLOCK(iterator);
30647 } while (0));
30648 }
30649
30650
30651 static int setup_srtp(struct sip_srtp **srtp)
30652 {
30653 if (!ast_rtp_engine_srtp_is_registered()) {
30654 ast_log(LOG_ERROR, "No SRTP module loaded, can't setup SRTP session.\n");
30655 return -1;
30656 }
30657
30658 if (!(*srtp = sip_srtp_alloc())) {
30659 return -1;
30660 }
30661
30662 return 0;
30663 }
30664
30665 static int process_crypto(struct sip_pvt *p, struct ast_rtp_instance *rtp, struct sip_srtp **srtp, const char *a)
30666 {
30667
30668 if (!rtp) {
30669 ast_debug(3, "Received offer with crypto line for media stream that is not enabled\n");
30670 return FALSE;
30671 }
30672
30673 if (strncasecmp(a, "crypto:", 7)) {
30674 return FALSE;
30675 }
30676 if (!*srtp) {
30677 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
30678 ast_log(LOG_WARNING, "Ignoring unexpected crypto attribute in SDP answer\n");
30679 return FALSE;
30680 }
30681
30682 if (setup_srtp(srtp) < 0) {
30683 return FALSE;
30684 }
30685 }
30686
30687 if (!(*srtp)->crypto && !((*srtp)->crypto = sdp_crypto_setup())) {
30688 return FALSE;
30689 }
30690
30691 if (sdp_crypto_process((*srtp)->crypto, a, rtp) < 0) {
30692 return FALSE;
30693 }
30694
30695 ast_set_flag(*srtp, SRTP_CRYPTO_OFFER_OK);
30696
30697 return TRUE;
30698 }
30699
30700
30701 static int sip_do_reload(enum channelreloadreason reason)
30702 {
30703 time_t start_poke, end_poke;
30704
30705 reload_config(reason);
30706 ast_sched_dump(sched);
30707
30708 start_poke = time(0);
30709
30710 unlink_marked_peers_from_tables();
30711
30712 ast_debug(4, "--------------- Done destroying pruned peers\n");
30713
30714
30715 sip_poke_all_peers();
30716
30717
30718 sip_send_all_registers();
30719
30720 sip_send_all_mwi_subscriptions();
30721
30722 end_poke = time(0);
30723
30724 ast_debug(4, "do_reload finished. peer poke/prune reg contact time = %d sec.\n", (int)(end_poke-start_poke));
30725
30726 ast_debug(4, "--------------- SIP reload done\n");
30727
30728 return 0;
30729 }
30730
30731
30732 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
30733 {
30734 static struct sip_peer *tmp_peer, *new_peer;
30735
30736 switch (cmd) {
30737 case CLI_INIT:
30738 e->command = "sip reload";
30739 e->usage =
30740 "Usage: sip reload\n"
30741 " Reloads SIP configuration from sip.conf\n";
30742 return NULL;
30743 case CLI_GENERATE:
30744 return NULL;
30745 }
30746
30747 ast_mutex_lock(&sip_reload_lock);
30748 if (sip_reloading) {
30749 ast_verbose("Previous SIP reload not yet done\n");
30750 } else {
30751 sip_reloading = TRUE;
30752 sip_reloadreason = (a && a->fd) ? CHANNEL_CLI_RELOAD : CHANNEL_MODULE_RELOAD;
30753 }
30754 ast_mutex_unlock(&sip_reload_lock);
30755 restart_monitor();
30756
30757 tmp_peer = bogus_peer;
30758
30759 if ((new_peer = temp_peer("(bogus_peer)"))) {
30760 ast_string_field_set(new_peer, md5secret, BOGUS_PEER_MD5SECRET);
30761 ast_clear_flag(&new_peer->flags[0], SIP_INSECURE);
30762 bogus_peer = new_peer;
30763 ao2_t_ref(tmp_peer, -1, "unref the old bogus_peer during reload");
30764 } else {
30765 ast_log(LOG_ERROR, "Could not update the fake authentication peer.\n");
30766
30767 }
30768
30769 return CLI_SUCCESS;
30770 }
30771
30772
30773 static int reload(void)
30774 {
30775 if (sip_reload(0, 0, NULL))
30776 return 0;
30777 return 1;
30778 }
30779
30780
30781
30782
30783
30784 static int ast_sockaddr_resolve_first_af(struct ast_sockaddr *addr,
30785 const char* name, int flag, int family)
30786 {
30787 struct ast_sockaddr *addrs;
30788 int addrs_cnt;
30789
30790 addrs_cnt = ast_sockaddr_resolve(&addrs, name, flag, family);
30791 if (addrs_cnt <= 0) {
30792 return 1;
30793 }
30794 if (addrs_cnt > 1) {
30795 ast_debug(1, "Multiple addresses, using the first one only\n");
30796 }
30797
30798 ast_sockaddr_copy(addr, &addrs[0]);
30799
30800 ast_free(addrs);
30801 return 0;
30802 }
30803
30804
30805
30806
30807
30808 static int ast_sockaddr_resolve_first(struct ast_sockaddr *addr,
30809 const char* name, int flag)
30810 {
30811 return ast_sockaddr_resolve_first_af(addr, name, flag, get_address_family_filter(SIP_TRANSPORT_UDP));
30812 }
30813
30814
30815
30816
30817
30818 static int ast_sockaddr_resolve_first_transport(struct ast_sockaddr *addr,
30819 const char* name, int flag, unsigned int transport)
30820 {
30821 return ast_sockaddr_resolve_first_af(addr, name, flag, get_address_family_filter(transport));
30822 }
30823
30824
30825
30826
30827 static int peer_hash_cb(const void *obj, const int flags)
30828 {
30829 const struct sip_peer *peer = obj;
30830
30831 return ast_str_case_hash(peer->name);
30832 }
30833
30834
30835
30836
30837 static int peer_cmp_cb(void *obj, void *arg, int flags)
30838 {
30839 struct sip_peer *peer = obj, *peer2 = arg;
30840
30841 return !strcasecmp(peer->name, peer2->name) ? CMP_MATCH | CMP_STOP : 0;
30842 }
30843
30844
30845
30846
30847
30848
30849 static int peer_iphash_cb(const void *obj, const int flags)
30850 {
30851 const struct sip_peer *peer = obj;
30852 int ret = 0;
30853
30854 if (ast_sockaddr_isnull(&peer->addr)) {
30855 ast_log(LOG_ERROR, "Empty address\n");
30856 }
30857
30858 ret = ast_sockaddr_hash(&peer->addr);
30859
30860 if (ret < 0) {
30861 ret = -ret;
30862 }
30863
30864 return ret;
30865 }
30866
30867
30868
30869
30870
30871
30872
30873
30874
30875
30876
30877
30878
30879
30880
30881
30882
30883
30884
30885 static int peer_ipcmp_cb(void *obj, void *arg, int flags)
30886 {
30887 struct sip_peer *peer = obj, *peer2 = arg;
30888
30889 if (ast_sockaddr_cmp_addr(&peer->addr, &peer2->addr)) {
30890
30891 return 0;
30892 }
30893
30894
30895 if ((peer->transports & peer2->transports) & (SIP_TRANSPORT_TLS | SIP_TRANSPORT_TCP)) {
30896
30897 return CMP_MATCH | CMP_STOP;
30898 } else if (ast_test_flag(&peer2->flags[0], SIP_INSECURE_PORT)) {
30899
30900
30901 return ast_test_flag(&peer->flags[0], SIP_INSECURE_PORT) ?
30902 (CMP_MATCH | CMP_STOP) : 0;
30903 }
30904
30905
30906 return ast_sockaddr_port(&peer->addr) == ast_sockaddr_port(&peer2->addr) ?
30907 (CMP_MATCH | CMP_STOP) : 0;
30908 }
30909
30910
30911 static int threadt_hash_cb(const void *obj, const int flags)
30912 {
30913 const struct sip_threadinfo *th = obj;
30914
30915 return ast_sockaddr_hash(&th->tcptls_session->remote_address);
30916 }
30917
30918 static int threadt_cmp_cb(void *obj, void *arg, int flags)
30919 {
30920 struct sip_threadinfo *th = obj, *th2 = arg;
30921
30922 return (th->tcptls_session == th2->tcptls_session) ? CMP_MATCH | CMP_STOP : 0;
30923 }
30924
30925
30926
30927
30928 static int dialog_hash_cb(const void *obj, const int flags)
30929 {
30930 const struct sip_pvt *pvt = obj;
30931
30932 return ast_str_case_hash(pvt->callid);
30933 }
30934
30935
30936
30937
30938 static int dialog_find_multiple(void *obj, void *arg, int flags)
30939 {
30940 struct sip_pvt *pvt = obj, *pvt2 = arg;
30941
30942 return !strcasecmp(pvt->callid, pvt2->callid) ? CMP_MATCH : 0;
30943 }
30944
30945
30946
30947
30948 static int dialog_cmp_cb(void *obj, void *arg, int flags)
30949 {
30950 struct sip_pvt *pvt = obj, *pvt2 = arg;
30951
30952 return !strcasecmp(pvt->callid, pvt2->callid) ? CMP_MATCH | CMP_STOP : 0;
30953 }
30954
30955
30956 static struct ast_cli_entry cli_sip[] = {
30957 AST_CLI_DEFINE(sip_show_channels, "List active SIP channels or subscriptions"),
30958 AST_CLI_DEFINE(sip_show_channelstats, "List statistics for active SIP channels"),
30959 AST_CLI_DEFINE(sip_show_domains, "List our local SIP domains"),
30960 AST_CLI_DEFINE(sip_show_inuse, "List all inuse/limits"),
30961 AST_CLI_DEFINE(sip_show_objects, "List all SIP object allocations"),
30962 AST_CLI_DEFINE(sip_show_peers, "List defined SIP peers"),
30963 AST_CLI_DEFINE(sip_show_registry, "List SIP registration status"),
30964 AST_CLI_DEFINE(sip_unregister, "Unregister (force expiration) a SIP peer from the registry"),
30965 AST_CLI_DEFINE(sip_show_settings, "Show SIP global settings"),
30966 AST_CLI_DEFINE(sip_show_mwi, "Show MWI subscriptions"),
30967 AST_CLI_DEFINE(sip_cli_notify, "Send a notify packet to a SIP peer"),
30968 AST_CLI_DEFINE(sip_show_channel, "Show detailed SIP channel info"),
30969 AST_CLI_DEFINE(sip_show_history, "Show SIP dialog history"),
30970 AST_CLI_DEFINE(sip_show_peer, "Show details on specific SIP peer"),
30971 AST_CLI_DEFINE(sip_show_users, "List defined SIP users"),
30972 AST_CLI_DEFINE(sip_show_user, "Show details on specific SIP user"),
30973 AST_CLI_DEFINE(sip_qualify_peer, "Send an OPTIONS packet to a peer"),
30974 AST_CLI_DEFINE(sip_show_sched, "Present a report on the status of the scheduler queue"),
30975 AST_CLI_DEFINE(sip_prune_realtime, "Prune cached Realtime users/peers"),
30976 AST_CLI_DEFINE(sip_do_debug, "Enable/Disable SIP debugging"),
30977 AST_CLI_DEFINE(sip_set_history, "Enable/Disable SIP history"),
30978 AST_CLI_DEFINE(sip_reload, "Reload SIP configuration"),
30979 AST_CLI_DEFINE(sip_show_tcp, "List TCP Connections")
30980 };
30981
30982
30983 static void sip_register_tests(void)
30984 {
30985 sip_config_parser_register_tests();
30986 sip_request_parser_register_tests();
30987 sip_dialplan_function_register_tests();
30988 }
30989
30990
30991 static void sip_unregister_tests(void)
30992 {
30993 sip_config_parser_unregister_tests();
30994 sip_request_parser_unregister_tests();
30995 sip_dialplan_function_unregister_tests();
30996 }
30997
30998 #ifdef TEST_FRAMEWORK
30999 AST_TEST_DEFINE(test_sip_mwi_subscribe_parse)
31000 {
31001 int found = 0;
31002 enum ast_test_result_state res = AST_TEST_PASS;
31003 const char *mwi1 = "1234@mysipprovider.com/1234";
31004 const char *mwi2 = "1234:password@mysipprovider.com/1234";
31005 const char *mwi3 = "1234:password@mysipprovider.com:5061/1234";
31006 const char *mwi4 = "1234:password:authuser@mysipprovider.com/1234";
31007 const char *mwi5 = "1234:password:authuser@mysipprovider.com:5061/1234";
31008 const char *mwi6 = "1234:password";
31009
31010 switch (cmd) {
31011 case TEST_INIT:
31012 info->name = "sip_mwi_subscribe_parse_test";
31013 info->category = "/channels/chan_sip/";
31014 info->summary = "SIP MWI subscribe line parse unit test";
31015 info->description =
31016 "Tests the parsing of mwi subscription lines (e.g., mwi => from sip.conf)";
31017 return AST_TEST_NOT_RUN;
31018 case TEST_EXECUTE:
31019 break;
31020 }
31021
31022 if (sip_subscribe_mwi(mwi1, 1)) {
31023 res = AST_TEST_FAIL;
31024 } else {
31025 found = 0;
31026 res = AST_TEST_FAIL;
31027 ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
31028 ASTOBJ_WRLOCK(iterator);
31029 if (
31030 !strcmp(iterator->hostname, "mysipprovider.com") &&
31031 !strcmp(iterator->username, "1234") &&
31032 !strcmp(iterator->secret, "") &&
31033 !strcmp(iterator->authuser, "") &&
31034 !strcmp(iterator->mailbox, "1234") &&
31035 iterator->portno == 0) {
31036 found = 1;
31037 res = AST_TEST_PASS;
31038 }
31039 ASTOBJ_UNLOCK(iterator);
31040 } while(0));
31041 if (!found) {
31042 ast_test_status_update(test, "sip_subscribe_mwi test 1 failed\n");
31043 }
31044 }
31045
31046 if (sip_subscribe_mwi(mwi2, 1)) {
31047 res = AST_TEST_FAIL;
31048 } else {
31049 found = 0;
31050 res = AST_TEST_FAIL;
31051 ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
31052 ASTOBJ_WRLOCK(iterator);
31053 if (
31054 !strcmp(iterator->hostname, "mysipprovider.com") &&
31055 !strcmp(iterator->username, "1234") &&
31056 !strcmp(iterator->secret, "password") &&
31057 !strcmp(iterator->authuser, "") &&
31058 !strcmp(iterator->mailbox, "1234") &&
31059 iterator->portno == 0) {
31060 found = 1;
31061 res = AST_TEST_PASS;
31062 }
31063 ASTOBJ_UNLOCK(iterator);
31064 } while(0));
31065 if (!found) {
31066 ast_test_status_update(test, "sip_subscribe_mwi test 2 failed\n");
31067 }
31068 }
31069
31070 if (sip_subscribe_mwi(mwi3, 1)) {
31071 res = AST_TEST_FAIL;
31072 } else {
31073 found = 0;
31074 res = AST_TEST_FAIL;
31075 ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
31076 ASTOBJ_WRLOCK(iterator);
31077 if (
31078 !strcmp(iterator->hostname, "mysipprovider.com") &&
31079 !strcmp(iterator->username, "1234") &&
31080 !strcmp(iterator->secret, "password") &&
31081 !strcmp(iterator->authuser, "") &&
31082 !strcmp(iterator->mailbox, "1234") &&
31083 iterator->portno == 5061) {
31084 found = 1;
31085 res = AST_TEST_PASS;
31086 }
31087 ASTOBJ_UNLOCK(iterator);
31088 } while(0));
31089 if (!found) {
31090 ast_test_status_update(test, "sip_subscribe_mwi test 3 failed\n");
31091 }
31092 }
31093
31094 if (sip_subscribe_mwi(mwi4, 1)) {
31095 res = AST_TEST_FAIL;
31096 } else {
31097 found = 0;
31098 res = AST_TEST_FAIL;
31099 ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
31100 ASTOBJ_WRLOCK(iterator);
31101 if (
31102 !strcmp(iterator->hostname, "mysipprovider.com") &&
31103 !strcmp(iterator->username, "1234") &&
31104 !strcmp(iterator->secret, "password") &&
31105 !strcmp(iterator->authuser, "authuser") &&
31106 !strcmp(iterator->mailbox, "1234") &&
31107 iterator->portno == 0) {
31108 found = 1;
31109 res = AST_TEST_PASS;
31110 }
31111 ASTOBJ_UNLOCK(iterator);
31112 } while(0));
31113 if (!found) {
31114 ast_test_status_update(test, "sip_subscribe_mwi test 4 failed\n");
31115 }
31116 }
31117
31118 if (sip_subscribe_mwi(mwi5, 1)) {
31119 res = AST_TEST_FAIL;
31120 } else {
31121 found = 0;
31122 res = AST_TEST_FAIL;
31123 ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
31124 ASTOBJ_WRLOCK(iterator);
31125 if (
31126 !strcmp(iterator->hostname, "mysipprovider.com") &&
31127 !strcmp(iterator->username, "1234") &&
31128 !strcmp(iterator->secret, "password") &&
31129 !strcmp(iterator->authuser, "authuser") &&
31130 !strcmp(iterator->mailbox, "1234") &&
31131 iterator->portno == 5061) {
31132 found = 1;
31133 res = AST_TEST_PASS;
31134 }
31135 ASTOBJ_UNLOCK(iterator);
31136 } while(0));
31137 if (!found) {
31138 ast_test_status_update(test, "sip_subscribe_mwi test 5 failed\n");
31139 }
31140 }
31141
31142 if (sip_subscribe_mwi(mwi6, 1)) {
31143 res = AST_TEST_PASS;
31144 } else {
31145 res = AST_TEST_FAIL;
31146 }
31147 return res;
31148 }
31149
31150 AST_TEST_DEFINE(test_sip_peers_get)
31151 {
31152 struct sip_peer *peer;
31153 struct ast_data *node;
31154 struct ast_data_query query = {
31155 .path = "/asterisk/channel/sip/peers",
31156 .search = "peers/peer/name=test_peer_data_provider"
31157 };
31158
31159 switch (cmd) {
31160 case TEST_INIT:
31161 info->name = "sip_peers_get_data_test";
31162 info->category = "/main/data/sip/peers/";
31163 info->summary = "SIP peers data providers unit test";
31164 info->description =
31165 "Tests whether the SIP peers data provider implementation works as expected.";
31166 return AST_TEST_NOT_RUN;
31167 case TEST_EXECUTE:
31168 break;
31169 }
31170
31171
31172 peer = build_peer("test_peer_data_provider", NULL, NULL, 0, 0);
31173 if (!peer) {
31174 return AST_TEST_FAIL;
31175 }
31176 peer->type = SIP_TYPE_USER;
31177 peer->call_limit = 10;
31178 ao2_link(peers, peer);
31179
31180
31181 node = ast_data_get(&query);
31182 if (!node) {
31183 ao2_unlink(peers, peer);
31184 ao2_ref(peer, -1);
31185 return AST_TEST_FAIL;
31186 }
31187
31188
31189 if (strcmp(ast_data_retrieve_string(node, "peer/name"), "test_peer_data_provider")) {
31190 ao2_unlink(peers, peer);
31191 ao2_ref(peer, -1);
31192 ast_data_free(node);
31193 return AST_TEST_FAIL;
31194 }
31195
31196 if (strcmp(ast_data_retrieve_string(node, "peer/type"), "user")) {
31197 ao2_unlink(peers, peer);
31198 ao2_ref(peer, -1);
31199 ast_data_free(node);
31200 return AST_TEST_FAIL;
31201 }
31202
31203 if (ast_data_retrieve_int(node, "peer/call_limit") != 10) {
31204 ao2_unlink(peers, peer);
31205 ao2_ref(peer, -1);
31206 ast_data_free(node);
31207 return AST_TEST_FAIL;
31208 }
31209
31210
31211 ast_data_free(node);
31212
31213 ao2_unlink(peers, peer);
31214 ao2_ref(peer, -1);
31215
31216 return AST_TEST_PASS;
31217 }
31218
31219
31220
31221
31222
31223
31224
31225
31226
31227
31228
31229
31230
31231
31232
31233
31234
31235
31236
31237 static int mock_tcp_loop(char *fragments[], size_t num_fragments,
31238 struct ast_str **overflow, char **messages, int *num_messages, struct ast_test* test)
31239 {
31240 struct ast_str *req_data;
31241 int i = 0;
31242 int res = 0;
31243
31244 req_data = ast_str_create(128);
31245 ast_str_reset(*overflow);
31246
31247 while (i < num_fragments || ast_str_strlen(*overflow) > 0) {
31248 enum message_integrity message_integrity = MESSAGE_FRAGMENT;
31249 ast_str_reset(req_data);
31250 while (message_integrity == MESSAGE_FRAGMENT) {
31251 if (ast_str_strlen(*overflow) > 0) {
31252 ast_str_append(&req_data, 0, "%s", ast_str_buffer(*overflow));
31253 ast_str_reset(*overflow);
31254 } else {
31255 ast_str_append(&req_data, 0, "%s", fragments[i++]);
31256 }
31257 message_integrity = check_message_integrity(&req_data, overflow);
31258 }
31259 if (strcmp(ast_str_buffer(req_data), messages[*num_messages])) {
31260 ast_test_status_update(test, "Mismatch in SIP messages.\n");
31261 ast_test_status_update(test, "Expected message:\n%s", messages[*num_messages]);
31262 ast_test_status_update(test, "Parsed message:\n%s", ast_str_buffer(req_data));
31263 res = -1;
31264 goto end;
31265 } else {
31266 ast_test_status_update(test, "Successfully read message:\n%s", ast_str_buffer(req_data));
31267 }
31268 (*num_messages)++;
31269 }
31270
31271 end:
31272 ast_free(req_data);
31273 return res;
31274 };
31275
31276 AST_TEST_DEFINE(test_tcp_message_fragmentation)
31277 {
31278
31279 char *normal[] = {
31280 "INVITE sip:bob@example.org SIP/2.0\r\n"
31281 "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
31282 "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
31283 "To: <sip:bob@example.org:5060>\r\n"
31284 "Call-ID: 12345\r\n"
31285 "CSeq: 1 INVITE\r\n"
31286 "Contact: sip:127.0.0.1:5061\r\n"
31287 "Max-Forwards: 70\r\n"
31288 "Content-Type: application/sdp\r\n"
31289 "Content-Length: 130\r\n"
31290 "\r\n"
31291 "v=0\r\n"
31292 "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
31293 "s=-\r\n"
31294 "c=IN IP4 127.0.0.1\r\n"
31295 "t=0 0\r\n"
31296 "m=audio 10000 RTP/AVP 0\r\n"
31297 "a=rtpmap:0 PCMU/8000\r\n"
31298 };
31299
31300
31301
31302
31303 char *fragmented[] = {
31304 "INVITE sip:bob@example.org SIP/2.0\r\n"
31305 "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
31306 "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
31307 "To: <sip:bob@example.org:5060>\r\n"
31308 "Call-ID: 12345\r\n"
31309 "CSeq: 1 INVITE\r\n"
31310 "Contact: sip:127.0.0.1:5061\r\n"
31311 "Max-Forwards: ",
31312
31313 "70\r\n"
31314 "Content-Type: application/sdp\r\n"
31315 "Content-Length: 130\r\n"
31316 "\r\n"
31317 "v=0\r\n"
31318 "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
31319 "s=-\r\n"
31320 "c=IN IP4 127.0.0.1\r\n"
31321 "t=0 0\r\n"
31322 "m=audio 10000 RTP/AVP 0\r\n"
31323 "a=rtpmap:0 PCMU/8000\r\n"
31324 };
31325
31326
31327
31328 char *fragmented_body[] = {
31329 "INVITE sip:bob@example.org SIP/2.0\r\n"
31330 "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
31331 "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
31332 "To: <sip:bob@example.org:5060>\r\n"
31333 "Call-ID: 12345\r\n"
31334 "CSeq: 1 INVITE\r\n"
31335 "Contact: sip:127.0.0.1:5061\r\n"
31336 "Max-Forwards: 70\r\n"
31337 "Content-Type: application/sdp\r\n"
31338 "Content-Length: 130\r\n"
31339 "\r\n",
31340
31341 "v=0\r\n"
31342 "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
31343 "s=-\r\n"
31344 "c=IN IP4 127.0.0.1\r\n"
31345 "t=0 0\r\n"
31346 "m=audio 10000 RTP/AVP 0\r\n"
31347 "a=rtpmap:0 PCMU/8000\r\n"
31348 };
31349
31350
31351
31352
31353 char *multi_fragment[] = {
31354 "INVITE sip:bob@example.org SIP/2.0\r\n"
31355 "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
31356 "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
31357 "To: <sip:bob@example.org:5060>\r\n"
31358 "Call-ID: 12345\r\n"
31359 "CSeq: 1 INVITE\r\n",
31360
31361 "Contact: sip:127.0.0.1:5061\r\n"
31362 "Max-Forwards: 70\r\n"
31363 "Content-Type: application/sdp\r\n"
31364 "Content-Length: 130\r\n"
31365 "\r\n"
31366 "v=0\r\n"
31367 "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
31368 "s=-\r\n"
31369 "c=IN IP4",
31370
31371 " 127.0.0.1\r\n"
31372 "t=0 0\r\n"
31373 "m=audio 10000 RTP/AVP 0\r\n"
31374 "a=rtpmap:0 PCMU/8000\r\n"
31375 };
31376
31377
31378
31379
31380 char *multi_message[] = {
31381 "SIP/2.0 100 Trying\r\n"
31382 "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
31383 "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
31384 "To: <sip:bob@example.org:5060>\r\n"
31385 "Call-ID: 12345\r\n"
31386 "CSeq: 1 INVITE\r\n"
31387 "Contact: <sip:bob@example.org:5060>\r\n"
31388 "Content-Length: 0\r\n"
31389 "\r\n"
31390 "SIP/2.0 180 Ringing\r\n"
31391 "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
31392 "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
31393 "To: <sip:bob@example.org:5060>\r\n"
31394 "Call-ID: 12345\r\n"
31395 "CSeq: 1 INVITE\r\n"
31396 "Contact: <sip:bob@example.org:5060>\r\n"
31397 "Content-Length: 0\r\n"
31398 "\r\n"
31399 };
31400 char *multi_message_divided[] = {
31401 "SIP/2.0 100 Trying\r\n"
31402 "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
31403 "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
31404 "To: <sip:bob@example.org:5060>\r\n"
31405 "Call-ID: 12345\r\n"
31406 "CSeq: 1 INVITE\r\n"
31407 "Contact: <sip:bob@example.org:5060>\r\n"
31408 "Content-Length: 0\r\n"
31409 "\r\n",
31410
31411 "SIP/2.0 180 Ringing\r\n"
31412 "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
31413 "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
31414 "To: <sip:bob@example.org:5060>\r\n"
31415 "Call-ID: 12345\r\n"
31416 "CSeq: 1 INVITE\r\n"
31417 "Contact: <sip:bob@example.org:5060>\r\n"
31418 "Content-Length: 0\r\n"
31419 "\r\n"
31420 };
31421
31422
31423
31424 char *multi_message_body[] = {
31425 "INVITE sip:bob@example.org SIP/2.0\r\n"
31426 "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
31427 "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
31428 "To: <sip:bob@example.org:5060>\r\n"
31429 "Call-ID: 12345\r\n"
31430 "CSeq: 1 INVITE\r\n"
31431 "Contact: sip:127.0.0.1:5061\r\n"
31432 "Max-Forwards: 70\r\n"
31433 "Content-Type: application/sdp\r\n"
31434 "Content-Length: 130\r\n"
31435 "\r\n"
31436 "v=0\r\n"
31437 "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
31438 "s=-\r\n"
31439 "c=IN IP4 127.0.0.1\r\n"
31440 "t=0 0\r\n"
31441 "m=audio 10000 RTP/AVP 0\r\n"
31442 "a=rtpmap:0 PCMU/8000\r\n"
31443 "INVITE sip:bob@example.org SIP/2.0\r\n"
31444 "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
31445 "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
31446 "To: <sip:bob@example.org:5060>\r\n"
31447 "Call-ID: 12345\r\n"
31448 "CSeq: 2 INVITE\r\n"
31449 "Contact: sip:127.0.0.1:5061\r\n"
31450 "Max-Forwards: 70\r\n"
31451 "Content-Type: application/sdp\r\n"
31452 "Content-Length: 130\r\n"
31453 "\r\n"
31454 "v=0\r\n"
31455 "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
31456 "s=-\r\n"
31457 "c=IN IP4 127.0.0.1\r\n"
31458 "t=0 0\r\n"
31459 "m=audio 10000 RTP/AVP 0\r\n"
31460 "a=rtpmap:0 PCMU/8000\r\n"
31461 };
31462 char *multi_message_body_divided[] = {
31463 "INVITE sip:bob@example.org SIP/2.0\r\n"
31464 "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
31465 "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
31466 "To: <sip:bob@example.org:5060>\r\n"
31467 "Call-ID: 12345\r\n"
31468 "CSeq: 1 INVITE\r\n"
31469 "Contact: sip:127.0.0.1:5061\r\n"
31470 "Max-Forwards: 70\r\n"
31471 "Content-Type: application/sdp\r\n"
31472 "Content-Length: 130\r\n"
31473 "\r\n"
31474 "v=0\r\n"
31475 "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
31476 "s=-\r\n"
31477 "c=IN IP4 127.0.0.1\r\n"
31478 "t=0 0\r\n"
31479 "m=audio 10000 RTP/AVP 0\r\n"
31480 "a=rtpmap:0 PCMU/8000\r\n",
31481
31482 "INVITE sip:bob@example.org SIP/2.0\r\n"
31483 "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
31484 "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
31485 "To: <sip:bob@example.org:5060>\r\n"
31486 "Call-ID: 12345\r\n"
31487 "CSeq: 2 INVITE\r\n"
31488 "Contact: sip:127.0.0.1:5061\r\n"
31489 "Max-Forwards: 70\r\n"
31490 "Content-Type: application/sdp\r\n"
31491 "Content-Length: 130\r\n"
31492 "\r\n"
31493 "v=0\r\n"
31494 "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
31495 "s=-\r\n"
31496 "c=IN IP4 127.0.0.1\r\n"
31497 "t=0 0\r\n"
31498 "m=audio 10000 RTP/AVP 0\r\n"
31499 "a=rtpmap:0 PCMU/8000\r\n"
31500 };
31501
31502
31503
31504
31505
31506 char *multi_message_in_fragments[] = {
31507 "SIP/2.0 100 Trying\r\n"
31508 "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
31509 "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
31510 "To: <sip:bob@example.org:5060>\r\n"
31511 "Call-ID: 12345\r\n"
31512 "CSeq: 1 INVI",
31513
31514 "TE\r\n"
31515 "Contact: <sip:bob@example.org:5060>\r\n"
31516 "Content-Length: 0\r\n"
31517 "\r\n"
31518 "SIP/2.0 180 Ringing\r\n"
31519 "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
31520 "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
31521 "To: <sip:bob@example.org:5060>\r\n"
31522 "Call-ID: 12345\r\n"
31523 "CSeq: 1 INVITE\r\n"
31524 "Contact: <sip:bob@example.org:5060>\r\n"
31525 "Content-Length: 0\r\n"
31526 "\r\n"
31527 };
31528
31529
31530
31531
31532 char *compact[] = {
31533 "INVITE sip:bob@example.org SIP/2.0\r\n"
31534 "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
31535 "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
31536 "To: <sip:bob@example.org:5060>\r\n"
31537 "Call-ID: 12345\r\n"
31538 "CSeq: 1 INVITE\r\n"
31539 "Contact: sip:127.0.0.1:5061\r\n"
31540 "Max-Forwards: 70\r\n"
31541 "Content-Type: application/sdp\r\n"
31542 "l:130\r\n"
31543 "\r\n"
31544 "v=0\r\n"
31545 "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
31546 "s=-\r\n"
31547 "c=IN IP4 127.0.0.1\r\n"
31548 "t=0 0\r\n"
31549 "m=audio 10000 RTP/AVP 0\r\n"
31550 "a=rtpmap:0 PCMU/8000\r\n"
31551 };
31552
31553
31554
31555
31556 char *faux[] = {
31557 "INVITE sip:bob@example.org SIP/2.0\r\n"
31558 "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
31559 "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
31560 "To: <sip:bob@example.org:5060>\r\n"
31561 "Call-ID: 12345\r\n"
31562 "CSeq: 1 INVITE\r\n"
31563 "Contact: sip:127.0.0.1:5061\r\n"
31564 "Max-Forwards: 70\r\n"
31565 "Content-Type: application/sdp\r\n"
31566 "DisContent-Length: 0\r\n"
31567 "MalContent-Length: 60\r\n"
31568 "Content-Length:130\r\n"
31569 "\r\n"
31570 "v=0\r\n"
31571 "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
31572 "s=-\r\n"
31573 "c=IN IP4 127.0.0.1\r\n"
31574 "t=0 0\r\n"
31575 "m=audio 10000 RTP/AVP 0\r\n"
31576 "a=rtpmap:0 PCMU/8000\r\n"
31577 };
31578
31579
31580
31581
31582
31583
31584 char *folded[] = {
31585 "INVITE sip:bob@example.org SIP/2.0\r\n"
31586 "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
31587 "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
31588 "To: <sip:bob@example.org:5060>\r\n"
31589 "Call-ID: 12345\r\n"
31590 "CSeq: 1 INVITE\r\n"
31591 "Contact: sip:127.0.0.1:5061\r\n"
31592 "Max-Forwards: 70\r\n"
31593 "Content-Type: application/sdp\r\n"
31594 "Content-Length: \t\r\n"
31595 "\t \r\n"
31596 " 130\t \r\n"
31597 "\r\n"
31598 "v=0\r\n"
31599 "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
31600 "s=-\r\n"
31601 "c=IN IP4 127.0.0.1\r\n"
31602 "t=0 0\r\n"
31603 "m=audio 10000 RTP/AVP 0\r\n"
31604 "a=rtpmap:0 PCMU/8000\r\n"
31605 };
31606
31607
31608
31609
31610
31611 char *cl_in_body[] = {
31612 "INVITE sip:bob@example.org SIP/2.0\r\n"
31613 "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
31614 "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
31615 "To: <sip:bob@example.org:5060>\r\n"
31616 "Call-ID: 12345\r\n"
31617 "CSeq: 1 INVITE\r\n"
31618 "Contact: sip:127.0.0.1:5061\r\n"
31619 "Max-Forwards: 70\r\n"
31620 "Content-Type: application/sdp\r\n"
31621 "l: 149\r\n"
31622 "\r\n"
31623 "v=0\r\n"
31624 "Content-Length: 0\r\n"
31625 "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
31626 "s=-\r\n"
31627 "c=IN IP4 127.0.0.1\r\n"
31628 "t=0 0\r\n"
31629 "m=audio 10000 RTP/AVP 0\r\n"
31630 "a=rtpmap:0 PCMU/8000\r\n"
31631 };
31632
31633 struct ast_str *overflow;
31634 struct {
31635 char **fragments;
31636 char **expected;
31637 int num_expected;
31638 const char *description;
31639 } tests[] = {
31640 { normal, normal, 1, "normal" },
31641 { fragmented, normal, 1, "fragmented" },
31642 { fragmented_body, normal, 1, "fragmented_body" },
31643 { multi_fragment, normal, 1, "multi_fragment" },
31644 { multi_message, multi_message_divided, 2, "multi_message" },
31645 { multi_message_body, multi_message_body_divided, 2, "multi_message_body" },
31646 { multi_message_in_fragments, multi_message_divided, 2, "multi_message_in_fragments" },
31647 { compact, compact, 1, "compact" },
31648 { faux, faux, 1, "faux" },
31649 { folded, folded, 1, "folded" },
31650 { cl_in_body, cl_in_body, 1, "cl_in_body" },
31651 };
31652 int i;
31653 enum ast_test_result_state res = AST_TEST_PASS;
31654
31655 switch (cmd) {
31656 case TEST_INIT:
31657 info->name = "sip_tcp_message_fragmentation";
31658 info->category = "/main/sip/transport/";
31659 info->summary = "SIP TCP message fragmentation test";
31660 info->description =
31661 "Tests reception of different TCP messages that have been fragmented or"
31662 "run together. This test mimicks the code that TCP reception uses.";
31663 return AST_TEST_NOT_RUN;
31664 case TEST_EXECUTE:
31665 break;
31666 }
31667 if (!sip_cfg.pedanticsipchecking) {
31668 ast_log(LOG_WARNING, "Not running test. Pedantic SIP checking is not enabled, so it is guaranteed to fail\n");
31669 return AST_TEST_NOT_RUN;
31670 }
31671
31672 overflow = ast_str_create(128);
31673 if (!overflow) {
31674 return AST_TEST_FAIL;
31675 }
31676 for (i = 0; i < ARRAY_LEN(tests); ++i) {
31677 int num_messages = 0;
31678 if (mock_tcp_loop(tests[i].fragments, ARRAY_LEN(tests[i].fragments),
31679 &overflow, tests[i].expected, &num_messages, test)) {
31680 ast_test_status_update(test, "Failed to parse message '%s'\n", tests[i].description);
31681 res = AST_TEST_FAIL;
31682 break;
31683 }
31684 if (num_messages != tests[i].num_expected) {
31685 ast_test_status_update(test, "Did not receive the expected number of messages. "
31686 "Expected %d but received %d\n", tests[i].num_expected, num_messages);
31687 res = AST_TEST_FAIL;
31688 break;
31689 }
31690 }
31691 ast_free(overflow);
31692 return res;
31693 }
31694
31695 AST_TEST_DEFINE(get_in_brackets_const_test)
31696 {
31697 const char *input;
31698 const char *start = NULL;
31699 int len = 0;
31700 int res;
31701
31702 #define CHECK_RESULTS(in, expected_res, expected_start, expected_len) do { \
31703 input = (in); \
31704 res = get_in_brackets_const(input, &start, &len); \
31705 if ((expected_res) != res) { \
31706 ast_test_status_update(test, "Unexpected result: %d != %d\n", expected_res, res); \
31707 return AST_TEST_FAIL; \
31708 } \
31709 if ((expected_start) != start) { \
31710 const char *e = expected_start ? expected_start : "(null)"; \
31711 const char *a = start ? start : "(null)"; \
31712 ast_test_status_update(test, "Unexpected start: %s != %s\n", e, a); \
31713 return AST_TEST_FAIL; \
31714 } \
31715 if ((expected_len) != len) { \
31716 ast_test_status_update(test, "Unexpected len: %d != %d\n", expected_len, len); \
31717 return AST_TEST_FAIL; \
31718 } \
31719 } while(0)
31720
31721 switch (cmd) {
31722 case TEST_INIT:
31723 info->name = __func__;
31724 info->category = "/channels/chan_sip/";
31725 info->summary = "get_in_brackets_const test";
31726 info->description =
31727 "Tests the get_in_brackets_const function";
31728 return AST_TEST_NOT_RUN;
31729 case TEST_EXECUTE:
31730 break;
31731 }
31732
31733 CHECK_RESULTS("", 1, NULL, -1);
31734 CHECK_RESULTS("normal <test>", 0, input + 8, 4);
31735 CHECK_RESULTS("\"normal\" <test>", 0, input + 10, 4);
31736 CHECK_RESULTS("not normal <test", -1, NULL, -1);
31737 CHECK_RESULTS("\"yes < really\" <test>", 0, input + 16, 4);
31738 CHECK_RESULTS("\"even > this\" <test>", 0, input + 15, 4);
31739 CHECK_RESULTS("<sip:id1@10.10.10.10;lr>", 0, input + 1, 22);
31740 CHECK_RESULTS("<sip:id1@10.10.10.10;lr>, <sip:id1@10.10.10.20;lr>", 0, input + 1, 22);
31741 CHECK_RESULTS("<sip:id1,id2@10.10.10.10;lr>", 0, input + 1, 26);
31742 CHECK_RESULTS("<sip:id1@10., <sip:id2@10.10.10.10;lr>", 0, input + 1, 36);
31743 CHECK_RESULTS("\"quoted text\" <sip:dlg1@10.10.10.10;lr>", 0, input + 15, 23);
31744
31745 return AST_TEST_PASS;
31746 }
31747
31748 #endif
31749
31750 #define DATA_EXPORT_SIP_PEER(MEMBER) \
31751 MEMBER(sip_peer, name, AST_DATA_STRING) \
31752 MEMBER(sip_peer, secret, AST_DATA_PASSWORD) \
31753 MEMBER(sip_peer, md5secret, AST_DATA_PASSWORD) \
31754 MEMBER(sip_peer, remotesecret, AST_DATA_PASSWORD) \
31755 MEMBER(sip_peer, context, AST_DATA_STRING) \
31756 MEMBER(sip_peer, subscribecontext, AST_DATA_STRING) \
31757 MEMBER(sip_peer, username, AST_DATA_STRING) \
31758 MEMBER(sip_peer, accountcode, AST_DATA_STRING) \
31759 MEMBER(sip_peer, tohost, AST_DATA_STRING) \
31760 MEMBER(sip_peer, regexten, AST_DATA_STRING) \
31761 MEMBER(sip_peer, fromuser, AST_DATA_STRING) \
31762 MEMBER(sip_peer, fromdomain, AST_DATA_STRING) \
31763 MEMBER(sip_peer, fullcontact, AST_DATA_STRING) \
31764 MEMBER(sip_peer, cid_num, AST_DATA_STRING) \
31765 MEMBER(sip_peer, cid_name, AST_DATA_STRING) \
31766 MEMBER(sip_peer, vmexten, AST_DATA_STRING) \
31767 MEMBER(sip_peer, language, AST_DATA_STRING) \
31768 MEMBER(sip_peer, mohinterpret, AST_DATA_STRING) \
31769 MEMBER(sip_peer, mohsuggest, AST_DATA_STRING) \
31770 MEMBER(sip_peer, parkinglot, AST_DATA_STRING) \
31771 MEMBER(sip_peer, useragent, AST_DATA_STRING) \
31772 MEMBER(sip_peer, mwi_from, AST_DATA_STRING) \
31773 MEMBER(sip_peer, engine, AST_DATA_STRING) \
31774 MEMBER(sip_peer, unsolicited_mailbox, AST_DATA_STRING) \
31775 MEMBER(sip_peer, is_realtime, AST_DATA_BOOLEAN) \
31776 MEMBER(sip_peer, host_dynamic, AST_DATA_BOOLEAN) \
31777 MEMBER(sip_peer, autoframing, AST_DATA_BOOLEAN) \
31778 MEMBER(sip_peer, inUse, AST_DATA_INTEGER) \
31779 MEMBER(sip_peer, inRinging, AST_DATA_INTEGER) \
31780 MEMBER(sip_peer, onHold, AST_DATA_INTEGER) \
31781 MEMBER(sip_peer, call_limit, AST_DATA_INTEGER) \
31782 MEMBER(sip_peer, t38_maxdatagram, AST_DATA_INTEGER) \
31783 MEMBER(sip_peer, maxcallbitrate, AST_DATA_INTEGER) \
31784 MEMBER(sip_peer, rtptimeout, AST_DATA_SECONDS) \
31785 MEMBER(sip_peer, rtpholdtimeout, AST_DATA_SECONDS) \
31786 MEMBER(sip_peer, rtpkeepalive, AST_DATA_SECONDS) \
31787 MEMBER(sip_peer, lastms, AST_DATA_MILLISECONDS) \
31788 MEMBER(sip_peer, maxms, AST_DATA_MILLISECONDS) \
31789 MEMBER(sip_peer, qualifyfreq, AST_DATA_MILLISECONDS) \
31790 MEMBER(sip_peer, timer_t1, AST_DATA_MILLISECONDS) \
31791 MEMBER(sip_peer, timer_b, AST_DATA_MILLISECONDS)
31792
31793 AST_DATA_STRUCTURE(sip_peer, DATA_EXPORT_SIP_PEER);
31794
31795 static int peers_data_provider_get(const struct ast_data_search *search,
31796 struct ast_data *data_root)
31797 {
31798 struct sip_peer *peer;
31799 struct ao2_iterator i;
31800 struct ast_data *data_peer, *data_peer_mailboxes = NULL, *data_peer_mailbox, *enum_node;
31801 struct ast_data *data_sip_options;
31802 int total_mailboxes, x;
31803 struct sip_mailbox *mailbox;
31804
31805 i = ao2_iterator_init(peers, 0);
31806 while ((peer = ao2_iterator_next(&i))) {
31807 ao2_lock(peer);
31808
31809 data_peer = ast_data_add_node(data_root, "peer");
31810 if (!data_peer) {
31811 ao2_unlock(peer);
31812 ao2_ref(peer, -1);
31813 continue;
31814 }
31815
31816 ast_data_add_structure(sip_peer, data_peer, peer);
31817
31818
31819 enum_node = ast_data_add_node(data_peer, "allowtransfer");
31820 if (!enum_node) {
31821 ao2_unlock(peer);
31822 ao2_ref(peer, -1);
31823 continue;
31824 }
31825 ast_data_add_str(enum_node, "text", transfermode2str(peer->allowtransfer));
31826 ast_data_add_int(enum_node, "value", peer->allowtransfer);
31827
31828
31829 ast_data_add_str(data_peer, "transports", get_transport_list(peer->transports));
31830
31831
31832 if ((peer->type & SIP_TYPE_USER) && (peer->type & SIP_TYPE_PEER)) {
31833 ast_data_add_str(data_peer, "type", "friend");
31834 } else if (peer->type & SIP_TYPE_PEER) {
31835 ast_data_add_str(data_peer, "type", "peer");
31836 } else if (peer->type & SIP_TYPE_USER) {
31837 ast_data_add_str(data_peer, "type", "user");
31838 }
31839
31840
31841 total_mailboxes = 0;
31842 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
31843 if (!total_mailboxes) {
31844 data_peer_mailboxes = ast_data_add_node(data_peer, "mailboxes");
31845 if (!data_peer_mailboxes) {
31846 break;
31847 }
31848 total_mailboxes++;
31849 }
31850
31851 data_peer_mailbox = ast_data_add_node(data_peer_mailboxes, "mailbox");
31852 if (!data_peer_mailbox) {
31853 continue;
31854 }
31855 ast_data_add_str(data_peer_mailbox, "mailbox", mailbox->mailbox);
31856 ast_data_add_str(data_peer_mailbox, "context", mailbox->context);
31857 }
31858
31859
31860 enum_node = ast_data_add_node(data_peer, "amaflags");
31861 if (!enum_node) {
31862 ao2_unlock(peer);
31863 ao2_ref(peer, -1);
31864 continue;
31865 }
31866 ast_data_add_int(enum_node, "value", peer->amaflags);
31867 ast_data_add_str(enum_node, "text", ast_cdr_flags2str(peer->amaflags));
31868
31869
31870 data_sip_options = ast_data_add_node(data_peer, "sipoptions");
31871 if (!data_sip_options) {
31872 ao2_unlock(peer);
31873 ao2_ref(peer, -1);
31874 continue;
31875 }
31876 for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
31877 ast_data_add_bool(data_sip_options, sip_options[x].text, peer->sipoptions & sip_options[x].id);
31878 }
31879
31880
31881 enum_node = ast_data_add_node(data_peer, "callingpres");
31882 if (!enum_node) {
31883 ao2_unlock(peer);
31884 ao2_ref(peer, -1);
31885 continue;
31886 }
31887 ast_data_add_int(enum_node, "value", peer->callingpres);
31888 ast_data_add_str(enum_node, "text", ast_describe_caller_presentation(peer->callingpres));
31889
31890
31891 ast_data_add_codecs(data_peer, "codecs", peer->capability);
31892
31893 if (!ast_data_search_match(search, data_peer)) {
31894 ast_data_remove_node(data_root, data_peer);
31895 }
31896
31897 ao2_unlock(peer);
31898 ao2_ref(peer, -1);
31899 }
31900 ao2_iterator_destroy(&i);
31901
31902 return 0;
31903 }
31904
31905 static const struct ast_data_handler peers_data_provider = {
31906 .version = AST_DATA_HANDLER_VERSION,
31907 .get = peers_data_provider_get
31908 };
31909
31910 static const struct ast_data_entry sip_data_providers[] = {
31911 AST_DATA_ENTRY("asterisk/channel/sip/peers", &peers_data_provider),
31912 };
31913
31914
31915 static int load_module(void)
31916 {
31917 ast_verbose("SIP channel loading...\n");
31918
31919
31920
31921 peers = ao2_t_container_alloc(HASH_PEER_SIZE, peer_hash_cb, peer_cmp_cb, "allocate peers");
31922 peers_by_ip = ao2_t_container_alloc(HASH_PEER_SIZE, peer_iphash_cb, peer_ipcmp_cb, "allocate peers_by_ip");
31923 dialogs = ao2_t_container_alloc(HASH_DIALOG_SIZE, dialog_hash_cb, dialog_cmp_cb, "allocate dialogs");
31924 dialogs_to_destroy = ao2_t_container_alloc(1, NULL, NULL, "allocate dialogs_to_destroy");
31925 threadt = ao2_t_container_alloc(HASH_DIALOG_SIZE, threadt_hash_cb, threadt_cmp_cb, "allocate threadt table");
31926 if (!peers || !peers_by_ip || !dialogs || !dialogs_to_destroy || !threadt) {
31927 ast_log(LOG_ERROR, "Unable to create primary SIP container(s)\n");
31928 return AST_MODULE_LOAD_FAILURE;
31929 }
31930
31931 ASTOBJ_CONTAINER_INIT(®l);
31932 ASTOBJ_CONTAINER_INIT(&submwil);
31933
31934 if (!(sched = sched_context_create())) {
31935 ast_log(LOG_ERROR, "Unable to create scheduler context\n");
31936 return AST_MODULE_LOAD_FAILURE;
31937 }
31938
31939 if (!(io = io_context_create())) {
31940 ast_log(LOG_ERROR, "Unable to create I/O context\n");
31941 sched_context_destroy(sched);
31942 return AST_MODULE_LOAD_FAILURE;
31943 }
31944
31945 sip_reloadreason = CHANNEL_MODULE_LOAD;
31946
31947 can_parse_xml = sip_is_xml_parsable();
31948 if (reload_config(sip_reloadreason)) {
31949 return AST_MODULE_LOAD_DECLINE;
31950 }
31951
31952
31953 if (!(bogus_peer = temp_peer("(bogus_peer)"))) {
31954 ast_log(LOG_ERROR, "Unable to create bogus_peer for authentication\n");
31955 io_context_destroy(io);
31956 sched_context_destroy(sched);
31957 return AST_MODULE_LOAD_FAILURE;
31958 }
31959
31960 ast_string_field_set(bogus_peer, md5secret, BOGUS_PEER_MD5SECRET);
31961 ast_clear_flag(&bogus_peer->flags[0], SIP_INSECURE);
31962
31963
31964
31965
31966
31967 memcpy(&sip_tech_info, &sip_tech, sizeof(sip_tech));
31968 memset((void *) &sip_tech_info.send_digit_begin, 0, sizeof(sip_tech_info.send_digit_begin));
31969
31970
31971 if (ast_channel_register(&sip_tech)) {
31972 ast_log(LOG_ERROR, "Unable to register channel type 'SIP'\n");
31973 ao2_t_ref(bogus_peer, -1, "unref the bogus_peer");
31974 io_context_destroy(io);
31975 sched_context_destroy(sched);
31976 return AST_MODULE_LOAD_FAILURE;
31977 }
31978
31979 #ifdef TEST_FRAMEWORK
31980 AST_TEST_REGISTER(test_sip_peers_get);
31981 AST_TEST_REGISTER(test_sip_mwi_subscribe_parse);
31982 AST_TEST_REGISTER(test_tcp_message_fragmentation);
31983 AST_TEST_REGISTER(get_in_brackets_const_test);
31984 #endif
31985
31986
31987 ast_data_register_multiple(sip_data_providers, ARRAY_LEN(sip_data_providers));
31988
31989
31990 ast_cli_register_multiple(cli_sip, ARRAY_LEN(cli_sip));
31991
31992
31993 ast_udptl_proto_register(&sip_udptl);
31994
31995
31996 ast_rtp_glue_register(&sip_rtp_glue);
31997
31998
31999 ast_register_application_xml(app_dtmfmode, sip_dtmfmode);
32000 ast_register_application_xml(app_sipaddheader, sip_addheader);
32001 ast_register_application_xml(app_sipremoveheader, sip_removeheader);
32002
32003
32004 ast_custom_function_register(&sip_header_function);
32005 ast_custom_function_register(&sippeer_function);
32006 ast_custom_function_register(&sipchaninfo_function);
32007 ast_custom_function_register(&checksipdomain_function);
32008
32009
32010 ast_manager_register_xml("SIPpeers", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peers);
32011 ast_manager_register_xml("SIPshowpeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peer);
32012 ast_manager_register_xml("SIPqualifypeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_qualify_peer);
32013 ast_manager_register_xml("SIPshowregistry", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_show_registry);
32014 ast_manager_register_xml("SIPnotify", EVENT_FLAG_SYSTEM, manager_sipnotify);
32015 sip_poke_all_peers();
32016 sip_send_all_registers();
32017 sip_send_all_mwi_subscriptions();
32018 initialize_escs();
32019
32020 if (sip_epa_register(&cc_epa_static_data)) {
32021 return AST_MODULE_LOAD_DECLINE;
32022 }
32023
32024 if (sip_reqresp_parser_init() == -1) {
32025 ast_log(LOG_ERROR, "Unable to initialize the SIP request and response parser\n");
32026 return AST_MODULE_LOAD_DECLINE;
32027 }
32028
32029 if (can_parse_xml) {
32030
32031
32032
32033 if (ast_cc_agent_register(&sip_cc_agent_callbacks)) {
32034 return AST_MODULE_LOAD_DECLINE;
32035 }
32036 }
32037 if (ast_cc_monitor_register(&sip_cc_monitor_callbacks)) {
32038 return AST_MODULE_LOAD_DECLINE;
32039 }
32040 if (!(sip_monitor_instances = ao2_container_alloc(37, sip_monitor_instance_hash_fn, sip_monitor_instance_cmp_fn))) {
32041 return AST_MODULE_LOAD_DECLINE;
32042 }
32043
32044
32045 restart_monitor();
32046
32047 ast_realtime_require_field(ast_check_realtime("sipregs") ? "sipregs" : "sippeers",
32048 "name", RQ_CHAR, 10,
32049 "ipaddr", RQ_CHAR, INET6_ADDRSTRLEN - 1,
32050 "port", RQ_UINTEGER2, 5,
32051 "regseconds", RQ_INTEGER4, 11,
32052 "defaultuser", RQ_CHAR, 10,
32053 "fullcontact", RQ_CHAR, 35,
32054 "regserver", RQ_CHAR, 20,
32055 "useragent", RQ_CHAR, 20,
32056 "lastms", RQ_INTEGER4, 11,
32057 SENTINEL);
32058
32059
32060 sip_register_tests();
32061 network_change_event_subscribe();
32062
32063 return AST_MODULE_LOAD_SUCCESS;
32064 }
32065
32066
32067 static int unload_module(void)
32068 {
32069 struct sip_pvt *p;
32070 struct sip_threadinfo *th;
32071 struct ast_context *con;
32072 struct ao2_iterator i;
32073 int wait_count;
32074
32075 network_change_event_unsubscribe();
32076
32077 ast_sched_dump(sched);
32078
32079
32080 ast_channel_unregister(&sip_tech);
32081
32082
32083 ast_custom_function_unregister(&sipchaninfo_function);
32084 ast_custom_function_unregister(&sippeer_function);
32085 ast_custom_function_unregister(&sip_header_function);
32086 ast_custom_function_unregister(&checksipdomain_function);
32087
32088
32089 ast_unregister_application(app_dtmfmode);
32090 ast_unregister_application(app_sipaddheader);
32091 ast_unregister_application(app_sipremoveheader);
32092
32093 #ifdef TEST_FRAMEWORK
32094 AST_TEST_UNREGISTER(test_sip_peers_get);
32095 AST_TEST_UNREGISTER(test_sip_mwi_subscribe_parse);
32096 AST_TEST_UNREGISTER(test_tcp_message_fragmentation);
32097 AST_TEST_UNREGISTER(get_in_brackets_const_test);
32098 #endif
32099
32100 ast_data_unregister(NULL);
32101
32102
32103 ast_cli_unregister_multiple(cli_sip, ARRAY_LEN(cli_sip));
32104
32105
32106 ast_udptl_proto_unregister(&sip_udptl);
32107
32108
32109 ast_rtp_glue_unregister(&sip_rtp_glue);
32110
32111
32112 ast_manager_unregister("SIPpeers");
32113 ast_manager_unregister("SIPshowpeer");
32114 ast_manager_unregister("SIPqualifypeer");
32115 ast_manager_unregister("SIPshowregistry");
32116 ast_manager_unregister("SIPnotify");
32117
32118
32119 if (sip_tcp_desc.master) {
32120 ast_tcptls_server_stop(&sip_tcp_desc);
32121 }
32122 if (sip_tls_desc.master) {
32123 ast_tcptls_server_stop(&sip_tls_desc);
32124 }
32125 ast_ssl_teardown(sip_tls_desc.tls_cfg);
32126
32127
32128 i = ao2_iterator_init(threadt, 0);
32129 while ((th = ao2_t_iterator_next(&i, "iterate through tcp threads for 'sip show tcp'"))) {
32130 pthread_t thread = th->threadid;
32131 th->stop = 1;
32132 pthread_kill(thread, SIGURG);
32133 ao2_t_ref(th, -1, "decrement ref from iterator");
32134 }
32135 ao2_iterator_destroy(&i);
32136
32137
32138 i = ao2_iterator_init(dialogs, 0);
32139 while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
32140 if (p->owner)
32141 ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
32142 ao2_t_ref(p, -1, "toss dialog ptr from iterator_next");
32143 }
32144 ao2_iterator_destroy(&i);
32145
32146 unlink_all_peers_from_tables();
32147
32148 ast_mutex_lock(&monlock);
32149 if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP) && (monitor_thread != AST_PTHREADT_NULL)) {
32150 pthread_t th = monitor_thread;
32151 monitor_thread = AST_PTHREADT_STOP;
32152 pthread_cancel(th);
32153 pthread_kill(th, SIGURG);
32154 ast_mutex_unlock(&monlock);
32155 pthread_join(th, NULL);
32156 } else {
32157 monitor_thread = AST_PTHREADT_STOP;
32158 ast_mutex_unlock(&monlock);
32159 }
32160
32161
32162 i = ao2_iterator_init(dialogs, 0);
32163 while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
32164 dialog_unlink_all(p);
32165 ao2_t_ref(p, -1, "throw away iterator result");
32166 }
32167 ao2_iterator_destroy(&i);
32168
32169
32170 ast_free_ha(localaddr);
32171
32172 ast_mutex_lock(&authl_lock);
32173 if (authl) {
32174 ao2_t_ref(authl, -1, "Removing global authentication");
32175 authl = NULL;
32176 }
32177 ast_mutex_unlock(&authl_lock);
32178
32179 sip_epa_unregister_all();
32180 destroy_escs();
32181
32182 ast_free(default_tls_cfg.certfile);
32183 ast_free(default_tls_cfg.pvtfile);
32184 ast_free(default_tls_cfg.cipher);
32185 ast_free(default_tls_cfg.cafile);
32186 ast_free(default_tls_cfg.capath);
32187
32188 cleanup_all_regs();
32189 ASTOBJ_CONTAINER_DESTROYALL(®l, sip_registry_destroy);
32190 ASTOBJ_CONTAINER_DESTROY(®l);
32191
32192 ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
32193 ASTOBJ_WRLOCK(iterator);
32194 if (iterator->dnsmgr) {
32195 ast_dnsmgr_release(iterator->dnsmgr);
32196 iterator->dnsmgr = NULL;
32197 ASTOBJ_UNREF(iterator, sip_subscribe_mwi_destroy);
32198 }
32199 ASTOBJ_UNLOCK(iterator);
32200 } while(0));
32201 ASTOBJ_CONTAINER_DESTROYALL(&submwil, sip_subscribe_mwi_destroy);
32202 ASTOBJ_CONTAINER_DESTROY(&submwil);
32203
32204
32205
32206
32207
32208
32209
32210
32211 wait_count = 1000;
32212 while (ao2_container_count(threadt) && --wait_count) {
32213 sched_yield();
32214 }
32215 if (!wait_count) {
32216 ast_debug(2, "TCP/TLS thread container did not become empty :(\n");
32217 }
32218
32219 ao2_t_ref(bogus_peer, -1, "unref the bogus_peer");
32220
32221 ao2_t_ref(peers, -1, "unref the peers table");
32222 ao2_t_ref(peers_by_ip, -1, "unref the peers_by_ip table");
32223 ao2_t_ref(dialogs, -1, "unref the dialogs table");
32224 ao2_t_ref(dialogs_to_destroy, -1, "unref dialogs_to_destroy");
32225 ao2_t_ref(threadt, -1, "unref the thread table");
32226 ao2_t_ref(sip_monitor_instances, -1, "unref the sip_monitor_instances table");
32227
32228 clear_sip_domains();
32229 ast_free_ha(sip_cfg.contact_ha);
32230 if (sipsock_read_id) {
32231 ast_io_remove(io, sipsock_read_id);
32232 sipsock_read_id = NULL;
32233 }
32234 close(sipsock);
32235 io_context_destroy(io);
32236 sched_context_destroy(sched);
32237 con = ast_context_find(used_context);
32238 if (con) {
32239 ast_context_destroy(con, "SIP");
32240 }
32241 ast_unload_realtime("sipregs");
32242 ast_unload_realtime("sippeers");
32243 ast_cc_monitor_unregister(&sip_cc_monitor_callbacks);
32244 ast_cc_agent_unregister(&sip_cc_agent_callbacks);
32245
32246 sip_reqresp_parser_exit();
32247 sip_unregister_tests();
32248
32249 if (notify_types) {
32250 ast_config_destroy(notify_types);
32251 notify_types = NULL;
32252 }
32253
32254 return 0;
32255 }
32256
32257 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Session Initiation Protocol (SIP)",
32258 .load = load_module,
32259 .unload = unload_module,
32260 .reload = reload,
32261 .load_pri = AST_MODPRI_CHANNEL_DRIVER,
32262 .nonoptreq = "res_crypto,chan_local",
32263 );